diff --git "a/5209.jsonl" "b/5209.jsonl" new file mode 100644--- /dev/null +++ "b/5209.jsonl" @@ -0,0 +1,736 @@ +{"seq_id":"144468930","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 03 11:29:28 2016\n\n@author: Chaggai\n\"\"\"\nimport numpy as np\n \n#def math_ballooncalc_wrong(mpayload, hbal, molarmgas, buoyancyperc,accuracy=10):\n# \"\"\" first order estimation of the balloon \"\"\" \n# import VenusAtmosphere as atm\n# R = 8.314459848\n# Tatm, Patm, rhoatm, GravAcc=atm.VenusAtmosphere30latitude(hbal)\n# #calculate density volume and total mass of balloon \n# rhogas = Patm/((R/(molarmgas/1000.))*Tatm)\n# mtot=sum([ mpayload*(1/0.2)**(i+1)*(buoyancyperc/100.)**(i)*(rhogas/(rhoatm-rhogas))**i for i in range(0,accuracy)]) \n# # iteration to determine fianl mass\n# Vbal=mtot/(rhoatm-rhogas)*(buoyancyperc/100.) \n# mgas=rhogas*Vbal \n# Presgas = rhogas*R/(molarmgas/1000.)*Tatm\n# return mtot,Vbal,mgas, Presgas\n \ndef balloonInital(mpayload=90, Hbouyancy=50000, molarmgas=2.016,accuracy=10):\n \"\"\" first order estimation of the balloon given bouyance altitude\"\"\" \n import VenusAtmosphere as atm\n R = 8.314459848\n Tatm, Patm, rhoatm, GravAcc=atm.VenusAtmosphere30latitude(Hbouyancy)\n #calculate density volume and total mass of balloon \n rhogas = Patm/((R/(molarmgas/1000.))*Tatm)\n mtot=sum([ mpayload*(1/0.2)**(i+1)*(rhogas/(rhoatm-rhogas))**i for i in range(0,accuracy)]) \n # iteration to determine fianl mass\n Vbal=mtot/(rhoatm-rhogas)\n mgas=rhogas*Vbal \n Presgas = rhogas*R/(molarmgas/1000.)*Tatm\n return mtot,molarmgas,Vbal,mgas,Presgas,Tatm\n\ndef balloonCruise(mtot,molarmgas,Vbal,mgas,Pgas,Tgas,expanFactor,contracFactor,cruiseBuoyancy,accuracy=0.00001):\n import VenusAtmosphere as atm\n R = 8.314459848\n Rsp = R/(molarmgas/1000.)\n mcruise=cruiseBuoyancy*mtot\n #rhocruise = P / (Rsp*T)\n altitude0=0\n step0=200000\n def findAlt(altitude,step):\n #assert altitude>0\n Tatm, Patm, rhoatm, GravAcc = atm.VenusAtmosphere30latitude(altitude)\n rhooutside = rhoatm\n\n factor = sorted([1-contracFactor, Pgas/Patm * Tatm/Tgas, 1+expanFactor])[1]\n\n Vcruise=factor*Vbal\n rhoinside=mgas/Vcruise\n \n deltaRho=mcruise/Vcruise\n currentDeltaRho=rhooutside-rhoinside\n #print(altitude,step,factor,deltaRho,currentDeltaRho)\n if abs(deltaRho-currentDeltaRho)currentDeltaRho:\n return findAlt(altitude-step/2.,step/2.)\n else:\n return findAlt(altitude+step/2.,step/2.)\n \n Hcruise,rhogas = findAlt(altitude0,step0)\n Tatm, Patm, rhoatm, GravAcc = atm.VenusAtmosphere30latitude(Hcruise)\n Pgas = rhogas*Rsp*Tatm\n return Hcruise,rhogas,Pgas,Patm\n \n \ndef fullbuoyancy(mgas, mtot, Vbal, expancruise,accuracy=0.0001): \n import VenusAtmosphere as atm\n #assume balloon goes down and balloon was slightly expanded at higher alt. Adjust Volume for return to normal shape\n Vbalnew=Vbal*(100.-expancruise)/100.\n rhogasnew=mgas/Vbalnew\n rhoatm=mtot/Vbalnew+rhogasnew \n #find what alt buoyancy is 100%\n altitude0 = 0\n step0=200000 \n def findAlt(altitude,step):\n #print(altitude,step)\n rhocurrent = atm.VenusAtmosphere30latitude(altitude)[2]\n if abs(rhocurrent-rhoatm) image.size[0]):\n image = image.rotate(90, expand=1)\n\nimage = image.resize((4096, int(image.size[1] * (4096.0 / image.size[0]))), Image.ANTIALIAS)\n\nprint(\"Resized image to \" + str(image.size))\n\nxy2rgb = numpy.empty([4096, 4096], dtype=tuple)\n\nprint(\"Putting data in bitmap array (xy2rgb)...\") # Top spacer\nfor y in range(0, int((4096-image.size[1])/2)):\n for x in range(0, 4096):\n xy2rgb[x][y] = (0xff, 0xff, 0xff)\nfor y in range(int((4096-image.size[1])/2), 4096): # Bottom spacer\n for x in range(0, 4096):\n xy2rgb[x][y] = (0xff, 0xff, 0xff)\n\nc = 4096 - image.size[1]\nc = int(c / 2)\nc = c * 4096\n\nfor p in image.getdata():\n xy2rgb[c % 4096][int(c / 4096)] = p\n c = c + 1\n\nprint(\"Generating color dictionary (rgb2xy)...\")\nrgb2xy = numpy.zeros([256, 256, 256], dtype=set)\n\nfor y in range(0, 4096):\n for x in range(0, 4096):\n p = xy2rgb[(x, y)]\n if(rgb2xy[p[0]][p[1]][p[2]] == 0):\n rgb2xy[p[0]][p[1]][p[2]] = set({(x, y)})\n else:\n rgb2xy[p[0]][p[1]][p[2]].update({(x, y)})\n\nprint(\"Generating set of complete RGB color space (unusedcolors)...\")\n\nunusedcolors = numpy.array([[[True] * 256] * 256] * 256)\n\nprint(\"Iterating through set of all RGB colors, and finding closest match on image...\")\n\ndef getxyfromrgb(rgb):\n S = rgb2xy[rgb[0]][rgb[1]][rgb[2]]\n if(S != 0):\n p = rgb2xy[rgb[0]][rgb[1]][rgb[2]].pop()\n if(len(rgb2xy[rgb[0]][rgb[1]][rgb[2]]) == 0):\n rgb2xy[rgb[0]][rgb[1]][rgb[2]] = 0\n return p\n else:\n return None\n\n#print(\"Creating GUI...\")\n\n#app = lib.App()\n#time.sleep(1)\n\ncomplete_image = numpy.empty([4096, 4096], dtype=tuple)\n\nfor n in range(1, 256):\n delta_set = {x for x in itertools.product(range(0, n), range(0, n), range(0, n))} - {x for x in itertools.product(range(0, n-1), range(0, n-1), range(0, n-1))}\n print(\"Searching delta \" + str(n-1) + \" set (\" + str(len(delta_set)) + \" items)...\")\n for v in delta_set:\n for r in range(0, 255):\n for g in range(0, 255):\n for b in range(0, 255):\n if(unusedcolors[r][g][b] == True):\n p = (r, g, b)\n pv = (r + v[0], g + v[1], b + v[2])\n xy = getxyfromrgb(pv)\n if (xy != None):\n complete_image[xy[0]][xy[1]] = p\n unusedcolors[r][g][b] = False\n continue\n #if (xy[1] % 2 == 0):\n #app.img.put(\"#%02x%02x%02x\" % pv, (xy[0], int(xy[1] / 2)))\n pv = (r - v[0], g - v[1], b - v[2])\n xy = getxyfromrgb(pv)\n if (xy != None):\n complete_image[xy[0]][xy[1]] = p\n unusedcolors[r][g][b] = False\n #if (xy[1] % 2 == 0):\n #app.img.put(\"#%02x%02x%02x\" % pv, (xy[0], int(xy[1] / 2)))\n print(str(r) + \"/255\")","sub_path":"everycolor.py","file_name":"everycolor.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"531468224","text":"from machine import Pin, UART\r\n#import uos\r\n#uos.dupterm(None,1)\r\nuart=UART(0,115200)\r\nuart.init(115200,bits=8,parity=None,stop=1)\r\nled=Pin(5,Pin.OUT)\r\nch=b''\r\ni=0\r\ni=str(i)\r\nwhile True:\r\n if uart.any()>0:\r\n ch= uart.readline()\r\n if ch==b'on':\r\n uart.write('led on')\r\n led.on()\r\n #temp=type(i)\r\n uart.write(bytearray(i))\r\n i=int(i)\r\n i=i+1\r\n i=str(i)\r\n elif ch==b'off':\r\n uart.write('led off')\r\n led.off()\r\n else:\r\n uart.write('recibi: ')\r\n uart.write(ch)\r\n","sub_path":"micropy/workSpace/test_uart.py","file_name":"test_uart.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"211570061","text":"import argparse\nimport time\nfrom src.dependencies.injector import Injector\nfrom src.shared.utils import get_project_root\nfrom src.shared.logger_factory import LoggerFactory\n\nlog = LoggerFactory.logger(__name__)\n\nDEFAULT_PATH = str(get_project_root()) + \"/src/scripts/config/detect_core_config.yaml\"\n\n\ndef detect_core(name: int, path=DEFAULT_PATH):\n try:\n injector = Injector.get_injector_from_file(path)\n process_module = injector.get_process_module()\n\n core_detector = process_module.get_core_detector()\n core_detector.detect_core_by_screen_name(name)\n except Exception as e:\n log.exception(e)\n exit()\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Short script to download tweets\n \"\"\"\n parser = argparse.ArgumentParser(description='Downloads the given number of tweets')\n parser.add_argument('-n', '--name', dest='name', required=True,\n help='The name of the user to start on', type=str)\n parser.add_argument('-p', '--path', dest='path', required=False,\n default=DEFAULT_PATH, help='The path of the config file', type=str)\n\n args = parser.parse_args()\n\n detect_core(args.name, args.path)\n","sub_path":"src/scripts/detect_core.py","file_name":"detect_core.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"249251458","text":"import ROOT as R \nR.gStyle.SetPalette(R.kLightTemperature)\nimport sys\nfrom math import sqrt\nimport pandas as pd \n\ndf = pd.read_csv(sys.argv[1], sep=\";\")\nprint(df)\n\nWjets_bins = {\"res\": [ \"Wjets_deta1_jpt1\",\"Wjets_deta1_jpt2\",\"Wjets_deta2_jpt1\",\"Wjets_deta2_jpt2\",\"Wjets_jpt3\"],\n \"boost\": [\"Wjets_boost1\", \"Wjets_boost2\"]\n}\n\nc = R.TCanvas()\nmg = R.TMultiGraph()\nleg = R.TLegend(0.7,0.6,0.9,0.9)\n\noffset = 0\n\nfor iy, year in enumerate((2016,2017,2018)):\n for lepfl in (\"ele\",\"mu\"):\n i = 0\n g = R.TGraphErrors()\n leg.AddEntry(g, \"{}_{}\".format(lepfl,year), \"p\")\n for cat in (\"res\", \"boost\"):\n \n channel = \"wjetcr_{}_dnnhigh_{}_{}\".format(cat, lepfl, year)\n if lepfl==\"ele\": offset = (iy+1)*0.1 - 0.3\n else: offset = (iy+1)*0.1\n \n for wjetbin in Wjets_bins[cat]:\n data = df[(df.channel==channel) & (df.bin==wjetbin)]\n g.SetPoint(i, i+1+offset,data.norm/data.prefitnorm )\n g.SetPointError(i, 0., data.err/data.prefitnorm )\n i+=1\n mg.Add(g)\n if lepfl ==\"ele\": g.SetMarkerStyle(21)\n else: g.SetMarkerStyle(22)\n g.SetMarkerSize(1.5)\n\n\nmg.Draw(\"AP PMC PFC PLC\")\nmg.SetTitle(\"Wjets deta_jetpt prefit/postfit norms;bin;post/prefit norm\")\n\ni = 0\ntt = []\nfor cat in (\"res\", \"boost\"):\n for wjetbin in Wjets_bins[cat]:\n t = R.TText(i+1-0.3, 0.4, wjetbin)\n t.SetTextFont(18)\n t.SetTextSize(15)\n t.SetTextAngle(45)\n i+=1\n t.Draw(\"same\")\n tt.append(t)\n\nmg.GetYaxis().SetRangeUser(0.4, 2)\n\nls = []\nfor i in range(7):\n line = R.TLine(i+1.5, 0.5, i+1.5,2)\n line.Draw(\"same\")\n ls.append(line)\nleg.Draw(\"same\")\nc.Draw()\n","sub_path":"Configurations/VBSjjlnu/scripts/plot_postfit_norms.py","file_name":"plot_postfit_norms.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"574998559","text":"# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Stochastic Adversarial Video Prediction model.\n\nReference: https://arxiv.org/abs/1804.01523\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensor2tensor.layers import common_layers\nfrom tensor2tensor.layers import common_video\nfrom tensor2tensor.models.research import next_frame_params # pylint: disable=unused-import\nfrom tensor2tensor.models.research import next_frame_sv2p\nfrom tensor2tensor.utils import registry\nimport tensorflow as tf\n\n\n@registry.register_model\nclass NextFrameSAVP(next_frame_sv2p.NextFrameStochastic):\n \"\"\"Stochastic Adversarial Video Prediction.\"\"\"\n\n def encoder(self, inputs, n_layers=3):\n \"\"\"COnvnet that encodes inputs into mean and std of a gaussian.\n\n Args:\n inputs: 5-D Tensor, shape (batch_size, num_frames, width, height, channels)\n n_layers: Number of layers.\n\n Returns:\n z_mu: Mean of the latent gaussians.\n z_log_var: log(var) of the latent gaussians.\n\n Raises:\n ValueError: If inputs is not a 5-D tensor or not float32.\n \"\"\"\n latent_dims = self.hparams.z_dim\n\n shape_as_list = inputs.shape.as_list()\n if len(shape_as_list) != 5:\n raise ValueError(\"Expected inputs to be a 5-D, got %d\" %\n len(shape_as_list))\n if inputs.dtype != tf.float32:\n raise ValueError(\"Expected dtype tf.float32, got %s\" % inputs.dtype)\n\n # Flatten (N,T,W,H,C) into (NT,W,H,C)\n batch_size, _ = shape_as_list[:2]\n inputs = tf.reshape(inputs, [-1] + list(inputs.shape)[2:])\n n_filters = 64\n rectified = None\n\n # Applies 3 layer conv-net with padding, instance normalization\n # and leaky relu as per the encoder in\n # https://github.com/alexlee-gk/video_prediction\n padding = [[0, 0], [1, 1], [1, 1], [0, 0]]\n for i in range(n_layers):\n with tf.variable_scope(\"layer_%d\" % (i + 1)):\n n_filters *= 2**i\n if i:\n padded = tf.pad(rectified, padding)\n else:\n padded = tf.pad(inputs, padding)\n convolved = tf.layers.conv2d(padded, filters=n_filters, kernel_size=4,\n strides=2, padding=\"VALID\")\n normalized = tf.contrib.layers.instance_norm(convolved)\n rectified = tf.nn.leaky_relu(normalized, alpha=0.2)\n\n # Mean pooling across all spatial dimensions.\n pooled = tf.nn.avg_pool(\n rectified, [1] + rectified.shape[1:3].as_list() + [1],\n strides=[1, 1, 1, 1], padding=\"VALID\")\n squeezed = tf.squeeze(pooled, [1, 2])\n\n # Down-project and output the mean and log of the standard deviation of\n # the latents.\n with tf.variable_scope(\"z_mu\"):\n z_mu = tf.layers.dense(squeezed, latent_dims)\n with tf.variable_scope(\"z_log_sigma_sq\"):\n z_log_var = tf.layers.dense(squeezed, latent_dims)\n z_log_var = tf.clip_by_value(z_log_var, -10, 10)\n\n # Reshape to (batch_size X num_frames X latent_dims)\n z_mu = tf.reshape(z_mu, (batch_size, -1, latent_dims))\n z_log_var = tf.reshape(\n z_log_var, (batch_size, -1, latent_dims))\n return z_mu, z_log_var\n\n def construct_model(self, images, actions, rewards):\n \"\"\"Model that takes in images and returns predictions.\n\n Args:\n images: list of 4-D Tensors indexed by time.\n (batch_size, width, height, channels)\n actions: list of action tensors\n each action should be in the shape ?x1xZ\n rewards: list of reward tensors\n each reward should be in the shape ?x1xZ\n\n Returns:\n video: list of 4-D predicted frames.\n all_rewards: predicted rewards.\n latent_means: list of gaussian means conditioned on the input at\n every frame.\n latent_stds: list of gaussian stds conditioned on the input at\n every frame.\n \"\"\"\n images = tf.unstack(images, axis=0)\n actions = tf.unstack(actions, axis=0)\n rewards = tf.unstack(rewards, axis=0)\n\n latent_dims = self.hparams.z_dim\n context_frames = self.hparams.video_num_input_frames\n seq_len = len(images)\n input_shape = common_layers.shape_list(images[0])\n batch_size = input_shape[0]\n\n # Model does not support reward-conditioned frame generation.\n fake_rewards = rewards[:-1]\n\n # Concatenate x_{t-1} and x_{t} along depth and encode it to\n # produce the mean and standard deviation of z_{t-1}\n image_pairs = tf.concat([images[:seq_len - 1],\n images[1:seq_len]], axis=-1)\n\n z_mu, z_log_sigma_sq = self.encoder(image_pairs)\n # Unstack z_mu and z_log_sigma_sq along the time dimension.\n z_mu = tf.unstack(z_mu, axis=0)\n z_log_sigma_sq = tf.unstack(z_log_sigma_sq, axis=0)\n iterable = zip(images[:-1], actions[:-1], fake_rewards,\n z_mu, z_log_sigma_sq)\n\n # Initialize LSTM State\n lstm_state = [None] * 7\n gen_cond_video, gen_prior_video, all_rewards, latent_means, latent_stds = \\\n [], [], [], [], []\n pred_image = tf.zeros_like(images[0])\n prior_latent_state, cond_latent_state = None, None\n train_mode = self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n\n # Create scheduled sampling function\n ss_func = self.get_scheduled_sample_func(batch_size)\n\n with tf.variable_scope(\"prediction\", reuse=tf.AUTO_REUSE):\n\n for step, (image, action, reward, mu, log_sigma_sq) in enumerate(iterable): # pylint:disable=line-too-long\n # Sample latents using a gaussian centered at conditional mu and std.\n latent = self.get_gaussian_latent(mu, log_sigma_sq)\n\n # Sample prior latents from isotropic normal distribution.\n prior_latent = tf.random_normal(tf.shape(latent), dtype=tf.float32)\n\n # LSTM that encodes correlations between conditional latents.\n # Pg 22 in https://arxiv.org/pdf/1804.01523.pdf\n enc_cond_latent, cond_latent_state = common_video.basic_lstm(\n latent, cond_latent_state, latent_dims, name=\"cond_latent\")\n\n # LSTM that encodes correlations between prior latents.\n enc_prior_latent, prior_latent_state = common_video.basic_lstm(\n prior_latent, prior_latent_state, latent_dims, name=\"prior_latent\")\n\n # Scheduled Sampling\n done_warm_start = step > context_frames - 1\n groundtruth_items = [image]\n generated_items = [pred_image]\n input_image, = self.get_scheduled_sample_inputs(\n done_warm_start, groundtruth_items, generated_items, ss_func)\n\n all_latents = tf.concat([enc_cond_latent, enc_prior_latent], axis=0)\n all_image = tf.concat([input_image, input_image], axis=0)\n all_action = tf.concat([action, action], axis=0)\n all_rewards = tf.concat([reward, reward], axis=0)\n\n all_pred_images, lstm_state = self.construct_predictive_tower(\n all_image, all_rewards, all_action, lstm_state, all_latents,\n concat_latent=True)\n\n cond_pred_images, prior_pred_images = \\\n all_pred_images[:batch_size], all_pred_images[batch_size:]\n\n if train_mode:\n pred_image = cond_pred_images\n else:\n pred_image = prior_pred_images\n\n gen_cond_video.append(cond_pred_images)\n gen_prior_video.append(prior_pred_images)\n latent_means.append(mu)\n latent_stds.append(log_sigma_sq)\n\n gen_cond_video = tf.stack(gen_cond_video, axis=0)\n gen_prior_video = tf.stack(gen_prior_video, axis=0)\n fake_rewards = tf.stack(fake_rewards, axis=0)\n\n if train_mode:\n return gen_cond_video, fake_rewards, latent_means, latent_stds\n else:\n return gen_prior_video, fake_rewards, latent_means, latent_stds\n","sub_path":"tensor2tensor/models/research/next_frame_savp.py","file_name":"next_frame_savp.py","file_ext":"py","file_size_in_byte":8229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"613726300","text":"operation = input ('Enter operation 1,2,3 or 4 \\nWhere 1 is Addition \\n2 is multblication \\n3 is divison \\nAnd 4 is factorial: ')\nnumber_one = input ('Enter first number : ') \nif operation != 4 : \n number_two = input ('Enter second number : ') \n \n \ndef factorial(n):\n num = 1\n while n >= 1:\n num = num * n\n n = n - 1\n return num\n \n \n \nif operation ==1: \n print (\"A + B = \" + str (number_one + number_two) ) \nelif operation ==2: \t\n\t print (\"A x B = \" + str (number_one * number_two) ) \nelif operation == 3 : \n\t if number_two != 0: \n\t print (\"A / B = \" + str (number_one / number_two)) \n\t else:\n\t print (\"cannot devide by 0 \") \nelif operation ==4:\n print(\"factorial is \" +str(factorial(number_one)))\n \n \n","sub_path":"New Project/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"96306506","text":"def solution(answers):\n answer = []\n first = [1,2,3,4,5]\n lf = len(first)\n sec = [2,1,2,3,2,4,2,5]\n ls = len(sec)\n third = [3,3,1,1,2,2,4,4,5,5]\n lt = len(third)\n score1 = 0\n score2 = 0\n score3 = 0\n for i,x in enumerate(answers):\n fIdx = i % lf\n sIdx = i % ls\n tIdx = i % lt\n if x==first[fIdx]:\n score1 += 1\n if x==sec[sIdx]:\n score2 += 1\n if x==third[tIdx]:\n score3 += 1\n \n maxVal = max(score1, score2, score3)\n if maxVal == score1:\n answer.append(1)\n if maxVal == score2:\n answer.append(2)\n if maxVal == score3:\n answer.append(3)\n return answer\n","sub_path":"programmers/완전탐색/모의고사.py","file_name":"모의고사.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"413265753","text":"import pandas\nimport pymysql\nimport matplotlib.pylab\nimport numpy\n\n# 读取数据\nconn = pymysql.connect(\"127.0.0.1\",\"root\",\"root\",\"pythontestdb\")\nsql = \"select * from taob\"\ndbData = pandas.read_sql(sql,conn)\nprint(dbData.describe())\ndbData[\"price\"][(dbData[\"price\"]==0)]=None\nx = 0\nfor i in dbData.columns:\n for j in range(len(dbData)):\n if(dbData[i].isnull())[j]:\n dbData[i][j] = 36\n x+=1\nprint(x)\nsData = dbData.T\n# 获取价格数据\npriceList = sData.values[2]\ncommentList = sData.values[3]\n# matplotlib.pylab.plot(priceList,commentList,\"mo\")\n# matplotlib.pylab.show()\nda=dbData.values\nline = len(da)\nclo = len(da[0])\nfor i in range(0,line):\n for j in range(0,clo):\n if (da[i][2] > 130):\n print(da[i])\n da[i][j] = 36\n if (da[i][3] > 300):\n print(da[i])\n da[i][j] = 58\nafterData = da.T\nprice = afterData[2]\ncomment = afterData[3]\nmatplotlib.pylab.plot(price,comment,\"ro\")\nmatplotlib.pylab.show()\n\n# 分布分析\npriceMax = afterData[2].max()\npriceMin = afterData[2].min()\ncommentMax = afterData[3].max()\ncommentMin = afterData[3].min()\n\n#极差\npricejc = priceMax - priceMin\ncommentjc = commentMax-commentMin\n\n#组距\npricezj = pricejc/12\ncommentzj = commentjc/12\n\n# 价格直方图\npricesty = numpy.arange(priceMin,priceMax,pricezj)\nmatplotlib.pylab.hist(afterData[2],pricesty)\nmatplotlib.pylab.show()\n# 评论直方图\ncommentsty = numpy.arange(commentMin,commentMax,commentzj)\nmatplotlib.pylab.hist(afterData[3],commentsty)\nmatplotlib.pylab.show()\n\n","sub_path":"天善数据分析与挖掘demo/day03数据清洗、集成和变换/淘宝商品数据清洗.py","file_name":"淘宝商品数据清洗.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"187028924","text":"#This program was created by Vishwa Nathan (vnathan@umich.edu) on June 28, 2019\n\n\n#THIS FILE CONTAINS THE HELPER FUNCTIONS WHICH ARE USED TO CONTROL THE VELOCITY OF THE LINEAR STAGE\n\n\nfrom time import sleep #imports sleep function used by the run_motor command\nimport RPi.GPIO as GPIO #allows for use of GPIO pins\nGPIO.setwarnings(False) #Turns off unnecessary warnings provided by Raspberry Pi\n\nGPIO.setmode(GPIO.BCM) #uses BCM mode for pin layout (Don't change)\n\n\n#STEPPER MOTOR CLASS\n\n#Creates a stepper motor class. This class takes in the step_angle, leadscrew pitch, pulse pin, direction pin and the number of microsteps in one full step. \n\nclass stepper:\n def __init__(self, step_angle, screw_pitch, pulse_pin, dir_pin, msteps):\n self.screw_pitch = float(screw_pitch)\n self.pulse_pin = int(pulse_pin)\n self.dir_pin = int(dir_pin)\n self.steps_per_rev = int((360/step_angle)*msteps)\n GPIO.setup(int(pulse_pin), GPIO.OUT) #initializes the pulse pin as an output\n GPIO.setup(int(dir_pin), GPIO.OUT) #initializes the direction pin as an output\n\n\n\n#Helper function to calculate overall change in position from the start point to the final point\ndef delta_position(final_position, initial_position):\n return (abs(final_position-initial_position)) #As a result, only the change in position matters, not its initial and final position.\n\n#Returns the number of motor rotations required to move the stage a specified distance\ndef calculate_rotations(mystepper, initial_position, final_position):\n delta_pos = delta_position(final_position,initial_position) #calculates the distance the stage moves\n num_rotations = delta_pos/(mystepper.screw_pitch) #divides the ttravel distance by the screw pitch to calculate the number of rotations\n return num_rotations\n\n\n#Creates a list of the linear stage's position at each step. This function calculates the number of steps required to travel a specified distance \n#and stores each step in a list. Each step is then converted to mm. The values stored in the list are its position at each step, not how far it moves with one step.\n#Example: The linear stage is set to move 10 mm and it moves at 2mm/step. The values in the position list will be [0,2,4,6,8,10] not [2,2,2,2,2]\ndef create_Yc_vector(initial_position, final_position, mystepper):\n total_rotations = calculate_rotations(mystepper, initial_position, final_position) #calculates rotations\n num_steps = int(total_rotations * mystepper.steps_per_rev) #calculates number of total steps by multiplying the number of rotations by steps per rotation\n position_list = [] #creates a list variable to store every position for every step\n mm_per_step = float(mystepper.screw_pitch)/mystepper.steps_per_rev #calculates the distance the stage moves for each step\n for i in range (1, num_steps):\n position_list.append(i*mm_per_step)#converts steps to mm and appends it to the list.\n return position_list\n\n#Creates a list which holds the stage's velocity at each step. This function is used regardless of the velocity profile\ndef create_velocity_vector(const_a, const_b , const_c , position_list):\n velocity_list = [] \n for i in range (len(position_list)):\n v = float(const_c)*(position_list[i]**2)+ float(const_b)*position_list[i]+float(const_a) #calculates velocity based on the equation ct^2+bt+a\n velocity_list.append(v) #appends the velocity to the list.\n return velocity_list\n\n#Calculates the delay which in turn controls the speed of the motor.\n#Based on this equation\n #Linear velocity = (screw pitch * pulse_frequency)/ (steps per revolution of stepper motor)\n#Rearranged to solve for pulse_frequency\n#delay = 1/pulse frequency (From the equation (seconds = 1/frequency))\ndef calculate_delay(linear_velocity, mystepper):\n numerator = linear_velocity * mystepper.steps_per_rev \n denominator = mystepper.screw_pitch\n pulse_freq = numerator/denominator\n delay = 1.0/pulse_freq\n return delay\n\n#Creates a list that holds all the delay values for the stepper motor speed. Delay is the inverse of pulse frequency\ndef create_delay_vector(velocity_vector,mystepper):\n delay_vector = []\n for i in range (len(velocity_vector)):\n delay_vector.append(calculate_delay(velocity_vector[i], mystepper)) #calculates the delay necessary for the motor to travel at a specified velocity\n return delay_vector\n\n#Moves the motor one step\ndef runmotor(mystepper, delay, direction):\n GPIO.output(mystepper.dir_pin, direction) #sets direction of motor\n GPIO.output(mystepper.pulse_pin,1) #sends a pulse to the motor to move one step\n sleep(delay) \n GPIO.output(mystepper.pulse_pin,0) #turns off the motor\n sleep(delay)\n\n#This function utilizes the previous functions to move the stage\ndef move_linear_stage(initial_position, final_position, mystepper, const_a, const_b, const_c, direction):\n position_vector = create_Yc_vector(float(initial_position), float(final_position), mystepper) #creates a list of the stage's position for each step\n vel_vector = create_velocity_vector(float(const_a), float(const_b), float(const_c), position_vector) #calculates the stage's velocity at each step\n del_vector = create_delay_vector(vel_vector,mystepper) #converts the velocity list into delays\n for i in range(len(del_vector)): \n runmotor(mystepper, del_vector[i], direction) \n\n\n#Alternate move function which is used in the home function. It does not calculate velocity at each step since the home function moves at a constant velocity.\ndef movedistance(mystepper, delay, direction, distance):\n for x in range (0, distance):\n runmotor(mystepper, delay, direction)\n\n\n# Homes the linear stage towards the endstop and then moves it four full revolutions away from the endstop to prevent retriggering. \n# Only used if the stage has an endstop\ndef home(mystepper, limitswitch_pin, home_speed, direction):\n while(GPIO.input(limitswitch_pin)==True): #run the motor while the endstop is not pressed\n runmotor(mystepper, home_speed, direction)\n GPIO.output(mystepper.pulse_pin, 0) \n if (direction ==1): #Changes the direction\n direction =0\n else:\n direction =1\n \n movedistance(mystepper, home_speed*2, direction, 4*mystepper.steps_per_rev) #to move away from the endstoop\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":"linear_stage_functions.py","file_name":"linear_stage_functions.py","file_ext":"py","file_size_in_byte":6542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"404287966","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django.core.urlresolvers import reverse\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom horizon import exceptions\nfrom horizon import forms\nfrom horizon import tables\nfrom horizon import tabs\nfrom horizon.utils import memoized\n\nfrom openstack_dashboard import api\nfrom openstack_dashboard.api import cinder\nfrom openstack_dashboard.usage import quotas\n\nfrom openstack_dashboard.dashboards.project.cg_snapshots \\\n import forms as cg_snapshot_forms\nfrom openstack_dashboard.dashboards.project.cg_snapshots \\\n import tables as cg_snapshot_tables\nfrom openstack_dashboard.dashboards.project.cg_snapshots \\\n import tabs as cg_snapshot_tabs\n\nCGROUP_INFO_FIELDS = (\"name\",\n \"description\")\n\nINDEX_URL = \"horizon:project:cg_snapshots:index\"\n\n\nclass CGSnapshotsView(tables.DataTableView):\n table_class = cg_snapshot_tables.CGSnapshotsTable\n page_title = _(\"Consistency Group Snapshots\")\n\n def get_data(self):\n try:\n cg_snapshots = api.cinder.volume_cg_snapshot_list(self.request)\n except Exception:\n cg_snapshots = []\n exceptions.handle(self.request, _(\"Unable to retrieve \"\n \"volume consistency group \"\n \"snapshots.\"))\n return cg_snapshots\n\n\nclass DetailView(tabs.TabView):\n tab_group_class = cg_snapshot_tabs.CGSnapshotsDetailTabs\n template_name = 'horizon/common/_detail.html'\n page_title = \"{{ cg_snapshot.name|default:cg_snapshot.id }}\"\n\n def get_context_data(self, **kwargs):\n context = super(DetailView, self).get_context_data(**kwargs)\n cg_snapshot = self.get_data()\n table = cg_snapshot_tables.CGSnapshotsTable(self.request)\n context[\"cg_snapshot\"] = cg_snapshot\n context[\"url\"] = self.get_redirect_url()\n context[\"actions\"] = table.render_row_actions(cg_snapshot)\n return context\n\n @memoized.memoized_method\n def get_data(self):\n try:\n cg_snapshot_id = self.kwargs['cg_snapshot_id']\n cg_snapshot = api.cinder.volume_cg_snapshot_get(self.request,\n cg_snapshot_id)\n\n cgroup_id = cg_snapshot.consistencygroup_id\n cgroup = api.cinder.volume_cgroup_get(self.request,\n cgroup_id)\n cg_snapshot.cg_name = cgroup.name\n cg_snapshot.volume_type_names = []\n for vol_type_id in cgroup.volume_types:\n vol_type = api.cinder.volume_type_get(self.request,\n vol_type_id)\n cg_snapshot.volume_type_names.append(vol_type.name)\n\n cg_snapshot.volume_names = []\n search_opts = {'consistencygroup_id': cgroup_id}\n volumes = api.cinder.volume_list(self.request,\n search_opts=search_opts)\n for volume in volumes:\n cg_snapshot.volume_names.append(volume.name)\n\n except Exception:\n redirect = self.get_redirect_url()\n exceptions.handle(self.request,\n _('Unable to retrieve consistency group '\n 'snapshot details.'),\n redirect=redirect)\n return cg_snapshot\n\n @staticmethod\n def get_redirect_url():\n return reverse(INDEX_URL)\n\n def get_tabs(self, request, *args, **kwargs):\n cg_snapshot = self.get_data()\n return self.tab_group_class(request, cg_snapshot=cg_snapshot, **kwargs)\n\n\nclass CreateCGroupView(forms.ModalFormView):\n form_class = cg_snapshot_forms.CreateCGroupForm\n template_name = 'project/cg_snapshots/create.html'\n submit_url = \"horizon:project:cg_snapshots:create_cgroup\"\n success_url = reverse_lazy('horizon:project:cgroups:index')\n page_title = _(\"Create Volume Consistency Group\")\n\n def get_context_data(self, **kwargs):\n context = super(CreateCGroupView, self).get_context_data(**kwargs)\n context['cg_snapshot_id'] = self.kwargs['cg_snapshot_id']\n args = (self.kwargs['cg_snapshot_id'],)\n context['submit_url'] = reverse(self.submit_url, args=args)\n try:\n # get number of volumes we will be creating\n cg_snapshot = cinder.volume_cg_snapshot_get(\n self.request, context['cg_snapshot_id'])\n\n cgroup_id = cg_snapshot.consistencygroup_id\n\n search_opts = {'consistencygroup_id': cgroup_id}\n volumes = api.cinder.volume_list(self.request,\n search_opts=search_opts)\n num_volumes = len(volumes)\n usages = quotas.tenant_limit_usages(self.request)\n\n if usages['totalVolumesUsed'] + num_volumes > \\\n usages['maxTotalVolumes']:\n raise ValueError(_('Unable to create consistency group due to '\n 'exceeding volume quota limit.'))\n else:\n usages['numRequestedItems'] = num_volumes\n context['usages'] = usages\n\n except ValueError as e:\n exceptions.handle(self.request, e.message)\n return None\n except Exception:\n exceptions.handle(self.request,\n _('Unable to retrieve consistency '\n 'group information.'))\n return context\n\n def get_initial(self):\n return {'cg_snapshot_id': self.kwargs[\"cg_snapshot_id\"]}\n","sub_path":"app/portal/horizon/openstack_dashboard/dashboards/project/cg_snapshots/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"210528470","text":"from settings import db_name, db_host, db_password, db_port, db_user, db_driver, api_key, api_token\nimport pyodbc\nimport requests\nimport time\nimport json\nfrom datetime import date\n\n\ndef validate_status(status_list, status):\n for status_iter in status_list:\n stat = status_iter.strip()\n if stat == status.strip():\n return True\n\n return False\n\n\nprint('(+) Database connection started')\n\n# api headers\nheaders = {\n 'content-type': \"application/json\",\n 'accept': \"application/vnd.vtex.ds.v10+json\",\n 'x-vtex-api-appkey': api_key,\n 'x-vtex-api-apptoken': api_token\n}\n\n# database connection\nconnection = pyodbc.connect(\n \"Driver={\"+db_driver+\"};\"\n \"Database=\"+db_name + \";\"\n \"Server= \"+db_host+\",\"+db_port+\";\"\n \"UID=\"+db_user+\";\"\n \"PWD=\"+db_password+\";\"\n)\nconnection.setencoding('utf-16-le')\n\ncursor = connection.cursor()\n# SQL PART FROM NEXUS\n\n# getting all new vtex- order from nexuss\nquery_vtex_nexus = \"select id_importex,stare_comanda, id_document from accesex_comenzi_clienti where id_importex like 'vtex-%' and data_document='{}' \".format(\n str(date.today()))\n\n\n# query to get series and number\nquery_invoice_nexus = \"\"\"\nSELECT acc.id_importex, acc.stare_comanda, accl.id_produs, afc.numar_document, afc.serie_document , afc.data_document, afc.numar_awb, afc.id_arhiva_factura\nFROM accesex_comenzi_clienti acc\nINNER JOIN accesex_comenzi_clienti_lin accl ON accl.id_document = acc.id_document\nLEFT JOIN accesex_facturi_clienti_lin afcl ON afcl.id_comanda = CONCAT(acc.id,'(',acc.pct_lcr,')') AND afcl.id_produs = accl.id_produs\nLEFT JOIN accesex_facturi_clienti afc ON afc.id_document = afcl.id_document\n\nWHERE acc.id_document = '{}'\n\n\"\"\"\n\n# retriving order\nurl_get_order = 'https://vetro.vtexcommercestable.com.br/api/oms/pvt/orders/{}'\n# post notification\nurl_post_invoice_notification = 'https://vetro.vtexcommercestable.com.br/api/oms/pvt/orders/{}/invoice'\n# cancel order\nurl_post_cancel_order = \"https://vetro.vtexcommercestable.com.br/api/oms/pvt/orders/{}/cancel\"\n# ready for handling order\n\nurl_post_ready = \"https://vetro.vtexcommercestable.com.br/api/oms/pvt/orders/{}/start-handling\"\n\ncursor.execute(query_vtex_nexus)\norders_status = cursor.fetchall()\n\nstatus_invoice = ['Onorata, Incasata, Inchisa',\n 'Onorata partial, Inchisa',\n 'Onorata partial, Incasata, Inchisa',\n 'Onorata, Inchisa',\n 'Onorata partial',\n 'Onorata']\n\nstatus_ready_for_handling = ['Neprocesata', 'Ferma']\n\nstatus_cancelled_order = [\n 'Ferma, Incasata, Inchisa', 'Anulata', 'Ferma, Inchisa']\n\n\nfor order in orders_status:\n vtex_id = order[0].split('vtex-')[1]\n status = order[1]\n number_order = order[2]\n\n print(\"(+) Requesting order {}\".format(vtex_id))\n\n response = requests.request(\n \"GET\", url_get_order.format(vtex_id), headers=headers)\n order_details = response.json()\n\n vtex_status = order_details['status']\n vtex_date_invoice = order_details['invoicedDate']\n\n if validate_status(status_invoice, status) and not vtex_status == 'invoiced' and not vtex_date_invoice:\n print(\"(+) Updating state on vtex order {} [invoice]\".format(vtex_id))\n\n value = order_details['value']\n\n print(' - executing query this takes along time')\n cursor.execute(query_invoice_nexus.format(number_order))\n invoice = cursor.fetchone()\n date_invoice = invoice[5]\n serie = invoice[4]\n number = invoice[3]\n\n if number and serie:\n # building payload\n payload = {}\n payload['invoiceNumber'] = serie+'-'+str(number)\n payload['invoiceValue'] = value\n payload['issuanceDate'] = str(date_invoice)\n payload['invoiceUrl'] = \"https://dev.vetro.vet/externe/json_api/read_factura.php?serie_factura={}&numar_document={}\".format(\n serie, str(number_order))\n payload = json.dumps(payload)\n print(' - sending invoice notification')\n response = requests.request('POST', url_post_invoice_notification.format(\n vtex_id), data=payload, headers=headers)\n response = requests.request('POST', url_post_ready.format(\n vtex_id), data=payload, headers=headers)\n\n if validate_status(status_cancelled_order, status) and not vtex_status == 'cancelled':\n print(\n \"(+) Updating state on vtex order {} [cancelled]\".format(vtex_id))\n response = requests.request(\n 'POST', url_post_cancel_order.format(vtex_id), headers=headers)\n\n if validate_status(status_ready_for_handling, status) and not vtex_status == 'ready-for-handling':\n print(\n \"(+) Updating state on vtex order {} [ready-for-handling]\".format(vtex_id))\n response = requests.request(\n 'POST', url_post_ready.format(vtex_id), headers=headers)\n","sub_path":"vetro-b2c/update_status/update_status.py","file_name":"update_status.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"187099598","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('component', '0012_auto_20160928_1838'),\n ('partners', '0003_partner_compose_arches'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='partner',\n name='errata_packages',\n field=models.ManyToManyField(default=[], to='component.GlobalComponent', blank=True),\n ),\n ]\n","sub_path":"product-definition-center/rhpdc/apps/partners/migrations/0004_partner_errata_packages.py","file_name":"0004_partner_errata_packages.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"641255007","text":"import typing\n\nfrom pytometa import tools, loader\nfrom pytometa.descriptors import TypeDescriptor, ListDescriptor, DictDescriptor\n\nclass _A(object):\n a = TypeDescriptor(int)\n b = TypeDescriptor(str)\n\nclass _C(object):\n inner = DictDescriptor(TypeDescriptor(_A)) # type: typing.Dict[str, int]\n\nclass _D(object):\n inner = DictDescriptor(_A) # type: typing.Dict\n\n\ndef test_load_dict_object():\n\n res = loader.load_from_dict({\n \"inner\":{\n \"zz\":{\n \"a\": 1,\n \"b\": 2,\n },\n \"xx\": {\n \"a\": 3,\n \"b\": 4,\n }\n }\n }, _C())\n assert type(res.inner) is dict\n assert len(res.inner) == 2\n assert res.inner[\"zz\"].a == 1\n assert res.inner[\"zz\"].b == \"2\"\n assert res.inner[\"xx\"].a == 3\n assert res.inner[\"xx\"].b == '4'\n\n\n","sub_path":"src/test/tools_test/test_load_dict.py","file_name":"test_load_dict.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"38662003","text":"#!/usr/bin/env python\n# -- coding: utf-8 --\nfrom IPython import embed\n\nfrom keras.models import load_model\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport itertools\nfrom keras.utils import np_utils\n\ndef load_data():\n\tdata = pd.read_csv('train.csv')\n\ty_train = np_utils.to_categorical(np.array(data['label']), 7)\n\n\tx_train = data['feature']\n\tx_train = np.array(map(lambda x: map(float, x.split()), x_train))\n\tx_train = np.reshape(x_train, (x_train.shape[0], 48, 48, 1))/255\n\tx_train = x_train\n\n\treturn x_train, y_train\n\n\ndef plot_confusion_matrix(cm, classes, title='Confusion matrix', cmap=plt.cm.jet):\n\t\"\"\"\n\tThis function prints and plots the confusion matrix.\n\t\"\"\"\n\tcm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\tplt.imshow(cm, interpolation='nearest', cmap=cmap)\n\tplt.title(title)\n\tplt.colorbar()\n\ttick_marks = np.arange(len(classes))\n\tplt.xticks(tick_marks, classes, rotation=45)\n\tplt.yticks(tick_marks, classes)\n\n\tthresh = cm.max() / 2.\n\tfor i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n\t\tplt.text(j, i, '{:.2f}'.format(cm[i, j]), horizontalalignment=\"center\",\n\t\t\t\t color=\"white\" if cm[i, j] > thresh else \"black\")\n\tplt.tight_layout()\n\tplt.ylabel('True label')\n\tplt.xlabel('Predicted label')\n\ndef main():\n\temotion_classifier = load_model('model100.h5')\n\tnp.set_printoptions(precision=2)\n\tx_train, y_train = load_data()\n\tsz = x_train.shape[0]/10\n\tpredictions = emotion_classifier.predict(x_train[4*sz:5*sz], 128)\n\tpre = np.array(map(lambda x: np.where(x == x.max())[0][0], predictions))\n\tans = np.array(map(lambda x: np.where(x == x.max())[0][0], y_train[4*sz:5*sz]))\n\tpre2 = [x for i, x in enumerate(pre) if x != ans[i]]\n\tans2 = [x for i, x in enumerate(ans) if x != pre[i]]\n\t#embed()\n\tconf_mat = confusion_matrix(ans2, pre2)\n\n\tplt.figure()\n\tplot_confusion_matrix(conf_mat, classes=[\"Angry\",\"Disgust\",\"Fear\",\"Happy\",\"Sad\",\"Surprise\",\"Neutral\"])\n\t#plt.show()\n\tplt.savefig('confusion_matrix2.png')\n\nmain()\n","sub_path":"hw3/confusion_matrix.py","file_name":"confusion_matrix.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"345332571","text":"# -*- coding: utf-8 -*-\n\"\"\"Implementation of `aiida_common_workflows.common.relax.generator.CommonRelaxInputGenerator` for Quantum ESPRESSO.\"\"\"\nfrom typing import Any, Dict, List, Tuple, Union\n\nfrom aiida import engine\nfrom aiida import orm\nfrom aiida import plugins\n\nfrom aiida_common_workflows.common import ElectronicType, RelaxType, SpinType\nfrom ..generator import CommonRelaxInputGenerator\n\n__all__ = ('QuantumEspressoCommonRelaxInputGenerator',)\n\nStructureData = plugins.DataFactory('structure')\n\n\ndef create_magnetic_allotrope(structure, magnetization_per_site):\n \"\"\"Create new structure with the correct magnetic kinds based on the magnetization per site\n\n :param structure: StructureData for which to create the new kinds.\n :param magnetization_per_site: List of magnetizations (defined as magnetic moments) for each site in the provided\n `structure`.\n \"\"\"\n # pylint: disable=too-many-locals,too-many-branches,too-many-statements\n import string\n if structure.is_alloy:\n raise ValueError('Alloys are currently not supported.')\n\n allotrope = StructureData(cell=structure.cell, pbc=structure.pbc)\n allotrope_magnetic_moments = {}\n\n for element in structure.get_symbols_set():\n\n # Filter the sites and magnetic moments on the site element\n element_sites, element_magnetic_moments = zip(\n *[(site, magnetic_moment)\n for site, magnetic_moment in zip(structure.sites, magnetization_per_site)\n if site.kind_name.rstrip(string.digits) == element]\n )\n magnetic_moment_set = set(element_magnetic_moments)\n if len(magnetic_moment_set) > 10:\n raise ValueError(\n 'The requested magnetic configuration would require more than 10 different kind names for element '\n f'{element}. This is currently not supported to due the character limit for kind names in Quantum '\n 'ESPRESSO.'\n )\n if len(magnetic_moment_set) == 1:\n magnetic_moment_kinds = {element_magnetic_moments[0]: element}\n else:\n magnetic_moment_kinds = {\n magmom: f'{element}{index}' for magmom, index in zip(magnetic_moment_set, string.digits)\n }\n for site, magnetic_moment in zip(element_sites, element_magnetic_moments):\n allotrope.append_atom(\n name=magnetic_moment_kinds[magnetic_moment],\n symbols=(element,),\n weights=(1.0,),\n position=site.position,\n )\n allotrope_magnetic_moments.update({kind_name: magmom for magmom, kind_name in magnetic_moment_kinds.items()})\n\n return (allotrope, allotrope_magnetic_moments)\n\n\nclass QuantumEspressoCommonRelaxInputGenerator(CommonRelaxInputGenerator):\n \"\"\"Input generator for the `QuantumEspressoCommonRelaxWorkChain`.\"\"\"\n\n _engine_types = {\n 'relax': {\n 'code_plugin': 'quantumespresso.pw',\n 'description': 'The code to perform the relaxation.'\n }\n }\n _relax_types = {\n relax_type: '...'\n for relax_type in RelaxType\n if relax_type not in (RelaxType.VOLUME, RelaxType.POSITIONS_VOLUME)\n }\n _spin_types = {\n SpinType.NONE: 'Treat the system without spin polarization.',\n SpinType.COLLINEAR: 'Treat the system with spin polarization.'\n }\n _electronic_types = {\n ElectronicType.METAL: 'Treat the system as a metal with smeared occupations.',\n ElectronicType.INSULATOR: 'Treat the system as an insulator with fixed occupations.'\n }\n\n def __init__(self, *args, **kwargs):\n \"\"\"Construct an instance of the input generator, validating the class attributes.\"\"\"\n process_class = kwargs.get('process_class', None)\n\n if process_class is not None:\n self._default_protocol = process_class._process_class.get_default_protocol()\n self._protocols = process_class._process_class.get_available_protocols()\n\n super().__init__(*args, **kwargs)\n\n def _initialize_protocols(self):\n \"\"\"Initialize the protocols class attribute by parsing them from the configuration file.\"\"\"\n self._default_protocol = self.process_class.get_default_protocol()\n self._protocols = self.process_class.get_available_protocols()\n\n def get_builder(\n self,\n structure: StructureData,\n engines: Dict[str, Any],\n *,\n protocol: str = None,\n relax_type: Union[RelaxType, str] = RelaxType.POSITIONS,\n electronic_type: Union[ElectronicType, str] = ElectronicType.METAL,\n spin_type: Union[SpinType, str] = SpinType.NONE,\n magnetization_per_site: Union[List[float], Tuple[float]] = None,\n threshold_forces: float = None,\n threshold_stress: float = None,\n reference_workchain=None,\n **kwargs\n ) -> engine.ProcessBuilder:\n \"\"\"Return a process builder for the corresponding workchain class with inputs set according to the protocol.\n\n :param structure: the structure to be relaxed.\n :param engines: a dictionary containing the computational resources for the relaxation.\n :param protocol: the protocol to use when determining the workchain inputs.\n :param relax_type: the type of relaxation to perform.\n :param electronic_type: the electronic character that is to be used for the structure.\n :param spin_type: the spin polarization type to use for the calculation.\n :param magnetization_per_site: a list with the initial spin polarization for each site. Float or integer in\n units of electrons. If not defined, the builder will automatically define the initial magnetization if and\n only if `spin_type != SpinType.NONE`.\n :param threshold_forces: target threshold for the forces in eV/Å.\n :param threshold_stress: target threshold for the stress in eV/Å^3.\n :param reference_workchain: a RelaxWorkChain node.\n :param kwargs: any inputs that are specific to the plugin.\n :return: a `aiida.engine.processes.ProcessBuilder` instance ready to be submitted.\n \"\"\"\n # pylint: disable=too-many-locals,too-many-branches\n from aiida_quantumespresso.common import types\n from qe_tools import CONSTANTS\n\n protocol = protocol or self.get_default_protocol_name()\n\n super().get_builder(\n structure,\n engines,\n protocol=protocol,\n relax_type=relax_type,\n electronic_type=electronic_type,\n spin_type=spin_type,\n magnetization_per_site=magnetization_per_site,\n threshold_forces=threshold_forces,\n threshold_stress=threshold_stress,\n reference_workchain=reference_workchain,\n **kwargs\n )\n\n if isinstance(electronic_type, str):\n electronic_type = types.ElectronicType(electronic_type)\n else:\n electronic_type = types.ElectronicType(electronic_type.value)\n\n if isinstance(relax_type, str):\n relax_type = types.RelaxType(relax_type)\n else:\n relax_type = types.RelaxType(relax_type.value)\n\n if isinstance(spin_type, str):\n spin_type = types.SpinType(spin_type)\n else:\n spin_type = types.SpinType(spin_type.value)\n\n if magnetization_per_site:\n kind_to_magnetization = set(zip([site.kind_name for site in structure.sites], magnetization_per_site))\n\n if len(structure.kinds) != len(kind_to_magnetization):\n structure, initial_magnetic_moments = create_magnetic_allotrope(structure, magnetization_per_site)\n else:\n initial_magnetic_moments = dict(kind_to_magnetization)\n else:\n initial_magnetic_moments = None\n\n builder = self.process_class._process_class.get_builder_from_protocol( # pylint: disable=protected-access\n engines['relax']['code'],\n structure,\n protocol=protocol,\n overrides={\n 'base': {\n 'pw': {\n 'metadata': {\n 'options': engines['relax']['options']\n }\n }\n },\n },\n relax_type=relax_type,\n electronic_type=electronic_type,\n spin_type=spin_type,\n initial_magnetic_moments=initial_magnetic_moments,\n )\n\n if threshold_forces is not None:\n threshold = threshold_forces * CONSTANTS.bohr_to_ang / CONSTANTS.ry_to_ev\n parameters = builder.base['pw']['parameters'].get_dict()\n parameters.setdefault('CONTROL', {})['forc_conv_thr'] = threshold\n builder.base['pw']['parameters'] = orm.Dict(dict=parameters)\n\n if threshold_stress is not None:\n threshold = threshold_stress * CONSTANTS.bohr_to_ang**3 / CONSTANTS.ry_to_ev\n parameters = builder.base['pw']['parameters'].get_dict()\n parameters.setdefault('CELL', {})['press_conv_thr'] = threshold\n builder.base['pw']['parameters'] = orm.Dict(dict=parameters)\n\n if reference_workchain:\n relax = reference_workchain.get_outgoing(node_class=orm.WorkChainNode).one().node\n base = sorted(relax.called, key=lambda x: x.ctime)[-1]\n calc = sorted(base.called, key=lambda x: x.ctime)[-1]\n kpoints = calc.inputs.kpoints\n\n builder.base.pop('kpoints_distance', None)\n builder.base.pop('kpoints_force_parity', None)\n builder.base_final_scf.pop('kpoints_distance', None)\n builder.base_final_scf.pop('kpoints_force_parity', None)\n\n builder.base['kpoints'] = kpoints\n builder.base_final_scf['kpoints'] = kpoints\n\n # Currently the builder is set for the `PwRelaxWorkChain`, but we should return one for the wrapper workchain\n # `QuantumEspressoCommonRelaxWorkChain` for which this input generator is built\n builder._process_class = self.process_class # pylint: disable=protected-access\n\n return builder\n","sub_path":"aiida_common_workflows/workflows/relax/quantum_espresso/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":10173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"284296944","text":"import requests, os\nfrom qiniu import Auth, put_file\nfrom PIL import Image\nfrom requests_html import HTMLSession\nfrom app.extensions import db\n\n\ndef down_file(resource, file_name, save_path):\n \"\"\"\n 下载文件 到本地\n :param resource: 目标文件地址\n :param file_name: 文件名\n :param save_path: 保存路径,没有的话就自动创建\n :return:\n \"\"\"\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n path = os.path.join(save_path, file_name)\n with open(path, 'wb') as file:\n file.write(requests.get(resource).content)\n return path\n\n\ndef update_to_qiniu(file, file_name=None):\n \"\"\"\n 上传文件到七牛\n :param file: 文件路径\n :param file_name: 自定义文件名\n :return:\n \"\"\"\n access_key = os.getenv('QINIU_ACCESS_KEY')\n secret_key = os.getenv(\"QINIU_SECRET_KEY\")\n bucket = os.getenv(\"QINIU_BUCKET\")\n\n try:\n qiniu = Auth(access_key, secret_key)\n token = qiniu.upload_token(bucket)\n ret, detail_info = put_file(token, file_name, file)\n return ret.get('key')\n\n except:\n update_to_qiniu(file, file_name)\n\n\ndef thumbnail(file_path, multiple, save_dir, save_name, save_ext=None):\n \"\"\"\n 生成缩略图\n :param file_path: 源文件\n :param multiple: 缩放倍速\n :param save_dir: 保存路径\n :param save_name: 保存的文件名\n :param save_ext: 文件类型\n :return: 文件路径\n \"\"\"\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n path = os.path.join(save_dir, save_name)\n img = Image.open(file_path)\n w, h = img.size\n img.thumbnail((w // multiple, h // multiple))\n img.save(path, save_ext)\n return path\n\n\ndef spider_image():\n \"\"\"\n 爬取网页内容\n :return:\n \"\"\"\n from app.servives import image_srv\n\n session = HTMLSession()\n page = 1\n while True:\n url = 'https://www.apptu.cn/wp-admin/admin-ajax.php?action=getpost&paged=' + str(page)\n response = session.get(url)\n datas = response.json()\n\n if not datas:\n return True\n for data in datas:\n image_srv.save(url=data.get('message'), img_id=data.get('id'), bookmarked=data.get('bookmarked'))\n db.session.commit()\n\n page = page + 1\n print(url)\n","sub_path":"app/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"514774618","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 30 13:01:35 2021\r\n\r\n@author: Selim Arslan\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport sympy as sp\r\nsp.init_printing()\r\n\r\n\r\n#%% SEP Aufgabe 6\r\n#Daten\r\nt_i = np.array([0., 14., 28., 42., 56.])\r\nN_i = np.array([29., 2072., 15798., 25854., 28997.])\r\n\r\n# Aufgabe a)\r\n# ----------\r\n# N(0) = N_0\r\n# N(inf) = G\r\n\r\n#%% \r\n# Aufgabe b\r\nplt.plot(t_i, N_i, 'o')\r\nplt.grid()\r\n# Aus dem plot ist ersichtlich, dass man nach 56 Tagen schon nahe am\r\n# stationären Zustand N(inf) ist. Daher Also:\r\n\r\n# Schätzung G=30000 (mit grosser Toleranz) \r\n# Schätzung N_0=29\r\n#%%\r\n# Aufgabe c\r\n\"\"\"\r\nN(t) = N_0 * np.exp(c*t)\r\numwandeln\r\nln(N(t)) = ln(N_0 * np.exp(c*t))\r\nln(N(t)) = c*t * ln(N_0 * np.exp())\r\nln(N(t)) = c*t * ln(N_0) + ln(np.exp())\r\nln(N(t)) = c*t * ln(N_0) + 1\r\nc = ln(N(t)) / ln()\r\nUmwandeln zu c = ln(N(t)) / ln(N0)\r\n\"\"\"\r\n\r\nc = (np.log(N_i[1]) - np.log(N_i[0]))/(t_i[1] - t_i[0])\r\nprint(c)\r\n\r\n\r\n\r\n#%% Aufgabed\r\n\r\np = sp.symbols('G N0 c')\r\n\r\ndef N(t,p):\r\n return p[0]/((p[0]-p[1])/p[1]*sp.exp(-p[2]*t)+1)\r\n\r\ng = sg = sp.Matrix([N_i[k]-N(t_i[k],p) for k in range(len(t_i))])\r\nprint(g)\r\nDg = g.jacobian(p)\r\nprint(Dg)\r\n\r\n#Umwandlung der Symbolischen Grössen g und Dg in numerische Funktion.\r\n#Damit kann als Input ein Array akzeptiert werden\r\ng = sp.lambdify([p], g, 'numpy')\r\nDg = sp.lambdify([p], Dg, 'numpy')\r\n\r\ndef gedämpftes_Gauss_Newton(g, DG, lam0, tol, nMax, pMax, damping):\r\n n = 0\r\n lam = np.copy(lam0)\r\n inkrement = tol + 1\r\n err_func = np.linalg.norm(g(lam))**2\r\n \r\n while inkrement > tol and n < nMax:\r\n #QR-Zerlegung\r\n [Q,R] = np.linalg.qr(DG(lam))\r\n delta = np.linalg.solve(R, -Q.T @ g(lam)).flatten()\r\n \r\n #dämpfung\r\n p = 0\r\n while damping and np.linalg.norm(g(lam+delta/(2.**p)))**2 >= err_func and p<=pMax:\r\n p = p + 1\r\n if p == pMax + 1:\r\n p = 0\r\n \r\n lam = lam + delta * (0.5**p)\r\n err_func = np.linalg.norm(g(lam))**2\r\n inkrement = np.linalg.norm(delta/(2.**p))\r\n n += 1\r\n print('Iteration: ', n)\r\n print('Lambda = ', lam)\r\n print('Inkrement ', inkrement)\r\n print('Fehlerfunktion = ', err_func)\r\n \r\n return (lam, n)\r\n\r\nprint('\\nGauss-Newton-Verfahren:\\n')\r\ntol = 1e-5\r\nnMax = 30\r\nlam0 = np.array([30000., 29., 0.305],dtype=np.float64)\r\npMax = 10\r\ndamping = 1\r\n[lam1, n] = gedämpftes_Gauss_Newton(g, Dg, lam0, tol, nMax, pMax, damping)\r\nprint(lam1, n)\r\n\r\n#Plot\r\nt = sp.symbols('t')\r\nF = N(t,lam1)\r\nF = sp.lambdify([t], F, 'numpy')\r\n\r\nt = np.arange(0.,56.,1)\r\n\r\nplt.plot(t_i, N_i,'o', t, F(t))\r\nplt.grid()\r\n\r\n \r\n\r\n","sub_path":"GedämpftesNewtonVerfahren_Entwicklung.py","file_name":"GedämpftesNewtonVerfahren_Entwicklung.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"476585862","text":"import pathlib\nfrom setuptools import setup\n\n# The directory containing this file\nHERE = pathlib.Path(__file__).parent\n\n# The text of the README file\nREADME = (HERE / \"README.md\").read_text()\n\n# This call to setup() does all the work\nsetup(\n name=\"rm-options\",\n version=\"2.0.1\",\n description=\"python package for easy cli options handling\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/MartinR2295/rm-options\",\n author=\"Martin Rader\",\n author_email=\"m1rader@edu.aau.at\",\n license=\"MIT\",\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n ],\n packages=[\"rmoptions\", \"rmoptions.mapper\"],\n include_package_data=True,\n install_requires=[],\n entry_points={\n \"console_scripts\": []\n },\n)\n","sub_path":"src/rm_options/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"101883264","text":"#A tuple is a collection which is ordered and unchangeable.In Python tuples are written with round brackets.\n#You can convert the tuple into a list, change the list, and convert the list back into a tuple.\n#To create a tuple with only one item, you have to add a comma after the item\n#the things that you can do with tuple: del ,join tuples,looping,checking items\nTuples=(\n ('sazid',17),\n \"It is a kind of list\",\n 'tuples is unchangeable'\n)\n#p=[1, 2, 3 ,4 ,5 ,6]\nprint(Tuples[0])","sub_path":"Python1/Collections/Tuple.py","file_name":"Tuple.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"497536268","text":"print(__doc__)\n\n\nimport matplotlib.pyplot as plt \nimport numpy as np \nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n#load the diabetes datasets\n\ndiabetes = datasets.load_diabetes()\n\n#Use only one feature \ndiabetes_X = diabetes.data[:, np.newaxis, 2]\n\n#splite the data into training/testing sets\ndiabetes_X_train = diabetes_X[:-20]\ndiabetes_X_test = diabetes_X[-20:]\n\n#splite the data into training/testing stes\ndiabetes_y_train = diabetes.target[:-20]\ndiabetes_y_test = diabetes.target[-20:]\n\n\nregr = linear_model.LinearRegression()\nregr.fit(diabetes_X_train,diabetes_y_train)\n\n\ndiabetes_y_pred = regr.predict(diabetes_X_test)\n\nprint(\"Mean squared error: %.2f\" % mean_squared_error(diabetes_y_test,diabetes_y_pred))\n\n\nplt.scatter(diabetes_X_test, diabetes_y_test, color='black')\nplt.plot(diabetes_X_test,diabetes_y_pred, color='blue', linewidth=4)\nplt.xticks(())\nplt.yticks(())\nplt.show()","sub_path":"2.3_homework/2.3_practise/0_linearRegression.py","file_name":"0_linearRegression.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"337117668","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom ray.tune.visual_utils import load_results_to_df\npd.options.display.max_rows = 999\ntypes = ['gainA', 'gainB', 'gainC', 'gainD', 'gainE', 'gainF', 'gainAB',\n 'gainBC', 'gainCD', 'gainDE', 'gainAC', 'gainBD', 'gainCE']\ncifar100_files = [\"/home/fbc23/mario/scratch/ray_results/gainlayer_cifar_lp1x1/\",\n \"/home/fbc23/mario/scratch/ray_results/gainlayer_cifar_dwt3x3/\"]\n\nif __name__ == '__main__':\n mpl.rcParams['font.size'] = 16\n mpl.rcParams['text.usetex'] = True\n mpl.rcParams['font.family'] = 'serif'\n mpl.rcParams['font.serif'] = 'Computer Modern Roman'\n\n assert os.path.exists(cifar100_files[0])\n assert os.path.exists(cifar100_files[1])\n df1 = load_results_to_df(cifar100_files[0])\n df2 = load_results_to_df(cifar100_files[1])\n GOOD_FIELDS = ['type', 'mean_accuracy']\n df1 = df1[GOOD_FIELDS]\n df1 = df1.dropna()\n df2 = df2[GOOD_FIELDS]\n df2 = df2.dropna()\n group1 = df1.groupby(['type'])\n group2 = df2.groupby(['type'])\n vals1 = group1['mean_accuracy'].agg(['mean', 'std'])\n vals2 = group2['mean_accuracy'].agg(['mean', 'std'])\n ref = pd.concat([df1[df1.type == 'ref'], df2[df2.type=='ref']])\n\n plt.figure(figsize=(7,8))\n w = 0.2\n space = 0.1\n lw = 1\n plt.barh(-1, ref.mean_accuracy.mean(), xerr=ref.mean_accuracy.std(),\n edgecolor='k', color='k', alpha=0.2, align='center', height=2*w,\n error_kw={'ecolor': 'k', 'capsize': 0, 'elinewidth': lw})\n plt.barh(np.arange(len(types))-w/2-space/2, vals2.loc[types,'mean'],\n xerr=vals2.loc[types,'std'], edgecolor='r',\n color='r', alpha=0.2, align='center', height=w,\n error_kw={'ecolor': 'r', 'capsize': 0, 'elinewidth': lw})\n plt.barh(np.arange(len(types))+w/2+space/2, vals1.loc[types,'mean'],\n xerr=vals1.loc[types,'std'], edgecolor='b',\n color='b', alpha=0.2, align='center', height=w,\n error_kw={'ecolor': 'b', 'capsize': 0, 'elinewidth': lw})\n\n plt.xlim(70, 75)\n plt.yticks(range(-1, vals1.shape[0]), labels=['ref'] + types)\n #plt.plot(range(5))\n plt.gca().invert_yaxis()\n plt.axvline(ref.mean_accuracy.mean(), color='k', ls='--', lw=1)\n plt.xlabel('Accuracy (\\%)')\n plt.show()\n","sub_path":"freqlearn/images/cifar100_bars.py","file_name":"cifar100_bars.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"470445135","text":"# coding: utf-8\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport subprocess\nimport uuid\nimport shutil\nimport json\n\nfrom blueboss import common as bc\n\n\ndef print_help():\n print(\"USAGE : [command] [opts]\")\n\n\ndef main(args):\n if len(args) == 0 or args[0] == help:\n print_help()\n\n if args[0] == 'json':\n try:\n output = subprocess.check_output(\n ['clang', '-Xclang', '-load',\n '-Xclang', '/usr/local/lib/CXXDeclsExtractor.so',\n '-Xclang', '-plugin', '-Xclang', 'print-decls'] + args[1:]\n )\n\n js = bc.loadJson(bc.mergeJson(json.loads(output)))\n messages = []\n for i in js.diagnostics:\n if (i.level == 'fatal' or i.level == 'error'):\n print(\"-\" * 30)\n i.show(sys.stderr)\n messages.append(i)\n print(output)\n if messages:\n sys.exit(1)\n except subprocess.CalledProcessError as exc:\n print(\"Status : FAIL\", exc.returncode, exc.output, file=sys.stderr)\n elif args[0] == 'java':\n tmp_dir = '/tmp/{}'.format(uuid.uuid4().hex)\n try:\n output = subprocess.check_output(\n ['python', '-m', 'blueboss.conv_java',\n '--dst-dir', tmp_dir,\n '--default-package', args[1],\n '--libname', args[2],\n '--jni-filename', os.path.join(tmp_dir, 'jniex.cpp')] + args[3:],\n stderr=subprocess.STDOUT,\n )\n output = output.strip()\n if output:\n sys.stderr.write(output)\n sys.stderr.write('\\n')\n sys.stderr.flush()\n # with open(os.path.join(tmp_dir, 'log'), 'w') as fp:\n # fp.write(output)\n\n subprocess.check_call(\n ['tar', '-C', tmp_dir,\n '--create', '-f', '-', '.'])\n except subprocess.CalledProcessError as exc:\n print(\"Status : FAIL\", exc.returncode, exc.output, file=sys.stderr)\n finally:\n if os.path.exists(tmp_dir):\n shutil.rmtree(tmp_dir)\n\n elif args[0] == 'objc':\n tmp_dir = '/'\n while os.path.exists(tmp_dir):\n tmp_dir = '/tmp/{}'.format(uuid.uuid4().hex)\n\n try:\n os.mkdir(tmp_dir)\n\n output = subprocess.check_output(\n ['python', '-m', 'blueboss.conv_objc',\n '--dst-header', os.path.join(tmp_dir, '{}.h'.format(args[1])),\n '--dst-source', os.path.join(tmp_dir, '{}.mm'.format(args[1]))] + args[2:],\n stderr=subprocess.STDOUT,\n )\n output = output.strip()\n if output:\n sys.stderr.write(output)\n sys.stderr.write('\\n')\n sys.stderr.flush()\n # with open(os.path.join(tmp_dir, 'log'), 'w') as fp:\n # fp.write(output)\n subprocess.check_call(\n ['tar', '-C', tmp_dir,\n '--create', '-f', '-', '.'])\n except subprocess.CalledProcessError as exc:\n print(\"Status : FAIL\", exc.returncode, exc.output, file=sys.stderr)\n finally:\n if os.path.exists(tmp_dir):\n shutil.rmtree(tmp_dir)\n else:\n print_help()\n\n\ndef __entry_point():\n main(sys.argv[1:])\n\n\nif __name__ == '__main__':\n __entry_point()\n","sub_path":"docker/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"217843320","text":"# -*- coding: utf-8 -*-\ndef bot_join(messages):\n\tfor message in messages:\n\t\tmsg = message\n\t\tis_bot = bot.get_me().id\n\t\tget_admin = bot.get_chat_administrators(msg.chat.id)\n\t\tadmin = [x.user.id for x in get_admin]\n\t\tif msg.content_type == \"new_chat_members\" and msg.new_chat_member.id == is_bot:\n\t\t\tif str(msg.chat.id) not in DATA[\"data_group\"]:\n\t\t\t\tret = {\n\t\t\t\t\t\t\tstr(msg.chat.id):{\n\t\t\t\t\t\t\t\t\t\"user_ban\":{},\n\t\t\t\t\t\t\t\t\t\"white_list\":{},\n\t\t\t\t\t\t\t\t\t\"options\":{\"restricted\":False,\"anti_link\":False},\n\t\t\t\t\t\t\t\t\t\"admin\":admin\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\tDATA[\"data_group\"].update(ret)\n\t\t\t\tbackupjson()\n\t\t\t\t\ndef update_config(messages):\n\tfor message in messages:\n\t\tmsg = message\n\t\tadmin = bot.get_chat_administrators(msg.chat.id)\n\t\tis_admin = [x.user.id for x in admin]\n\t\tif msg.content_type == \"text\" and msg.chat.type in [\"group\",\"supergroup\"] and msg.from_user.id in is_admin:\n\t\t\ttext = msg.text.lower()\n\t\t\tif text.startswith(\"default\") or text.startswith(\"/default\"):\n\t\t\t\tmrk = InlineKeyboardMarkup()\n\t\t\t\tmrk.add(InlineKeyboardButton(\"Yes\",callback_data=\"default_yes\"),\n\t\t\t\t\t\t\t InlineKeyboardButton(\"Hell no!\",callback_data=\"default_no\"))\n\t\t\t\tbot.send_message(msg.chat.id,RESET_STATUS,reply_markup=mrk,parse_mode=\"Markdown\")\n\t\t\tif text.startswith(\"status\") or text.startswith(\"/status\"):\n\t\t\t\tif str(msg.chat.id) not in DATA[\"data_group\"]:\n\t\t\t\t\tmrk = InlineKeyboardMarkup()\n\t\t\t\t\tmrk.add(InlineKeyboardButton(\"Update!\",callback_data=\"update_status_yes\"),\n\t\t\t\t\t\t\t\t InlineKeyboardButton(\"Not now\",callback_data=\"update_status_no\"))\n\t\t\t\t\tbot.reply_to(msg,\"Sorry no have current data from this group,please update status of this group!\",reply_markup=mrk)\n\t\t\t\telse:\n\t\t\t\t\tbot.reply_to(msg,json.dumps(DATA[\"data_group\"][str(msg.chat.id)], indent=4))\n\ndef update_status(msg):\n\tif msg.content_type == \"text\" and msg.chat.type in [\"group\",\"supergroup\"]:\n\t\tget_admin = bot.get_chat_administrators(msg.chat.id)\n\t\tadmin = [x.user.id for x in get_admin]\n\t\tret = {\n\t\t\t\t\tstr(msg.chat.id):{\n\t\t\t\t\t\t\t\"user_ban\":{},\n\t\t\t\t\t\t\t\"white_list\":{},\n\t\t\t\t\t\t\t\"options\":{\"restricted\":False,\"anti_link\":False},\n\t\t\t\t\t\t\t\"admin\":admin\n\t\t\t\t\t}\n\t\t\t\t}\n\t\tDATA[\"data_group\"].update(ret)\n\t\tbackupjson()\n\t\ttext = f\"Status update!\\n{json.dumps(ret,indent=4)}\"\n\t\tbot.reply_to(msg,text)\n\t\nbot.set_update_listener(update_config)\nbot.set_update_listener(bot_join)","sub_path":"teleBotx/command/joiningbot.py","file_name":"joiningbot.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"251049602","text":"#!/usr/bin/env python\n\n'''\nCreated by Samvel Khalatyan, Feb 23, 2012\nCopyright 2011, All rights reserved\n'''\n\nimport ROOT\n\ndef compare(function):\n '''\n function decorator: it will call custom ratio calculation function and\n adjust styles for ratio plot to look nice\n '''\n\n def compare_decorator(*parg, **karg):\n '''\n wrapper around custom ratio calculator: adjust ratio plot style\n '''\n\n # let custom function calcaule ratio and set all titles\n ratio = function(*parg, **karg)\n\n # adjust style of ratio plot\n axis = ratio.GetXaxis()\n axis.SetTitleSize(0.1)\n axis.SetTitleOffset(1.2)\n\n axis = ratio.GetYaxis()\n axis.SetTitleSize(0.1)\n axis.SetTitleOffset(0.7)\n axis.SetNdivisions(4)\n axis.SetRangeUser(-1, 1)\n\n for axis in ratio.GetYaxis(), ratio.GetXaxis():\n axis.SetLabelSize(0.09)\n\n ratio.SetMarkerSize(1)\n ratio.SetMarkerStyle(20)\n ratio.SetLineWidth(2)\n ratio.SetLineColor(ROOT.kGray + 2)\n ratio.SetLineStyle(1)\n ratio.SetMarkerColor(ROOT.kBlack)\n\n return ratio\n\n return compare_decorator\n\n@compare\ndef ratio(data, background, title = None):\n h = data.Clone()\n h.SetDirectory(0)\n h.Reset()\n\n h.Divide(data, background)\n\n h.GetYaxis().SetTitle(title if title else \"#frac{Data}{BKGD}\")\n\n return h\n\n@compare\ndef data_mins_bg_over_bg(data, background, title = None):\n h = data.Clone()\n h.SetDirectory(0)\n\n h.Add(background, -1)\n h.Divide(background)\n\n h.GetYaxis().SetTitle(title if title else \"#frac{Data - BKGD}{BKGD}\")\n\n return h\n\nclass ComparisonCanvas(object):\n '''\n Canvas with two pads:\n\n 1 (top) original plots should be drawn here\n 2 (bottom) comparison of the plots should be drawn in this pad\n\n It is recommended to use ComparisonCanvas class in conjuction with compare\n decorator, e.g.:\n\n class DataMcComparisonCanvas(ComparisonCanvas):\n ...\n\n @compare\n def ratio(self, data, mc):\n ratio = data.Clone()\n ratio.SetDirectory(0)\n\n ratio.Add(mc, -1)\n ratio.Divide(mc)\n ratio.GetYaxis().SetTitle(\"#frac{Data - MC}{MC}\")\n\n return ratio\n\n def draw(self, data, mc):\n canvas = self.canvas\n canvas.cd(1)\n\n stack = ROOT.THStack()\n stack.Add(data)\n stack.Add(mc)\n stack.Draw(\"nostack hist 9\")\n\n canvas.cd(2)\n self.ratio(data, mc).Draw(\"e 9\")\n \n ...\n\n in the above example ratio method will be wrapped into compare decorator\n and comparison plot (ratio) style will be automatically adjusted\n\n Canvas is automatically created on acesss\n '''\n\n def __init__(self, pads=2, lazy_init=False):\n '''\n Initialize with empty canvas\n '''\n\n self.__canvas = None\n self.__pads = pads\n\n if not lazy_init:\n self.canvas\n\n @property\n def canvas(self):\n '''\n Create canvas if one does not exist and split into 70% and 30%\n vertical Pads for comparison plot\n '''\n\n if not self.__canvas:\n # create canvas\n canvas = ROOT.TCanvas()\n canvas.SetWindowSize(640, 560 if 1 == self.__pads else 800)\n\n if 1 != self.__pads:\n canvas.Divide(1, self.__pads)\n\n # prepare top pad for original plots to be drawn overlayed\n pad = canvas.cd(1)\n pad.SetPad(0, 0.3, 1, 1)\n pad.SetRightMargin(5)\n\n # prepare bottom pad for comparison/ratio draw\n pad_height = 0.3 / (self.__pads - 1) if 1 != self.__pads else 0.3\n for pad_number in range(1, self.__pads):\n pad = canvas.cd(pad_number + 1)\n pad.SetPad(0, 0.3 - pad_number * pad_height, 1, 0.3 - (pad_number - 1) * pad_height)\n pad.SetBottomMargin(0.2)\n pad.SetRightMargin(5)\n pad.SetGrid()\n\n canvas.cd(1)\n\n self.__canvas = canvas\n\n return self.__canvas\n\n\n\nif \"__main__\" == __name__:\n import root.style\n\n style = root.style.tdr()\n style.cd()\n\n # Prepare function for later random fill\n my_gaus1 = ROOT.TF1(\"my_gaus1\", \"gaus(0)\", 0, 100)\n my_gaus1.SetParameters(1, 50, 10)\n\n my_gaus2 = ROOT.TF1(\"my_gaus2\", \"gaus(0)\", 0, 100)\n my_gaus2.SetParameters(1, 40, 10)\n\n # Create plot and randomly fill with above function\n plot1 = ROOT.TH1F(\"plot1\", \"plot1\", 50, 0, 100);\n plot1.FillRandom(\"my_gaus1\", 10000)\n plot1.SetLineColor(ROOT.kRed + 1)\n\n plot2 = ROOT.TH1F(\"plot2\", \"plot2\", 50, 0, 100);\n plot2.FillRandom(\"my_gaus2\", 10000)\n\n class ComparePlots(ComparisonCanvas):\n @compare\n def ratio(self, first, second):\n ratio = first.Clone()\n ratio.SetDirectory(0)\n ratio.Reset()\n\n ratio.Divide(first, second)\n ratio.GetYaxis().SetTitle(\"{0}/{1}\".format(first.GetName(), second.GetName()))\n\n return ratio\n\n def __call__(self, first, second):\n canvas = self.canvas\n canvas.cd(1)\n\n stack = ROOT.THStack()\n stack.Add(first)\n stack.Add(second)\n stack.Draw(\"nostack hist 9\")\n\n canvas.cd(2)\n ratio = self.ratio(first, second)\n ratio.Draw(\"e 9\")\n\n canvas.Update()\n \n raw_input(\"enter\")\n\n compare = ComparePlots()\n compare(plot1, plot2)\n","sub_path":"python/root/comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":5732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"480989485","text":"# -*- coding: utf-8 -*-\n__author__ = 'yusongmin'\n\nimport csv\n\n\ndef write(file_name, column_name, matrix):\n csvfile = file(file_name + \".csv\", 'ab')\n writer = csv.writer(csvfile)\n writer.writerow(column_name)\n data = matrix\n writer.writerows(data)\n csvfile.close()","sub_path":"ThirdPaper/Scripts/CSV_IO.py","file_name":"CSV_IO.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"102432530","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(name='igv-jupyter',\n packages=['igv'],\n version='0.9.8',\n description='Jupyter extension for embedding the igv.js genome visualization in a notebook',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n license='MIT',\n author='Jim Robinson',\n url='https://github.com/igvteam/igv.js-jupyter',\n # download_url='https://github.com/igvteam/igv.js-jupyter/archive/0.2.1.tar.gz',\n keywords=['igv', 'bioinformatics', 'genomics', 'visualization', 'ipython', 'jupyter'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Framework :: IPython',\n ],\n install_requires=[\n 'jupyter',\n 'notebook>=4.2.0',\n ],\n package_data={'igv': ['static/extension.js', 'static/igvjs/*']},\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"568159788","text":"from app.models.rental import Rental\nfrom app import db\nfrom app.models.video import Video\nfrom flask import request, Blueprint, make_response,jsonify\nfrom datetime import datetime \n\n\n# Video route for all inquiry GET & POST\nvideo_bp = Blueprint(\"videos\", __name__, url_prefix=\"/videos\")\n\n@video_bp.route(\"\", methods=[\"GET\", \"POST\"], strict_slashes=False)\ndef handle_video_get_post_all():\n\n if request.method == \"GET\":\n\n video_list = Video.query.all()\n video_response = []\n \n if video_list is None:\n return make_response(\"\", 404)\n \n \n\n for video in video_list:\n\n video_response.append(video.json_object())\n return jsonify(video_response)\n \n elif request.method == \"POST\":\n\n request_body = request.get_json()\n \n if \"title\" not in request_body or \"release_date\" not in request_body or \"total_inventory\" not in request_body:\n return make_response({\n \"details\": \"Invaild data\"\n }), 400\n \n new_video = Video(title=request_body[\"title\"],\n release_date=request_body[\"release_date\"],\n total_inventory=request_body[\"total_inventory\"])\n db.session.add(new_video)\n db.session.commit()\n \n return (\n {\n \"id\": new_video.video_id\n\n }, 201)\n\n\n# /videos/\n@video_bp.route(\"/\", methods=[\"GET\", \"PUT\", \"DELETE\"], strict_slashes=False)\ndef get_single_video(video_id):\n video = Video.query.get(video_id)\n #when I request in the url and have no details return None and a 404 message\n \n if video is None: #If customer \n return jsonify(None), 404\n\n if request.method == \"GET\":\n\n return make_response(video.json_object(), 200)\n\n elif request.method == \"PUT\":\n request_body = request.get_json()\n\n if \"title\" not in request_body or \"release_date\" not in request_body or \"total_inventory\" not in request_body:\n return make_response({\n \"details\": \"Invaild data\"\n }), 400\n\n form_data = request.get_json()\n \n video.title = form_data[\"title\"]\n video.release_date = form_data[\"release_date\"]\n video.total_inventory = form_data[\"total_inventory\"] \n\n db.session.commit()\n\n return make_response(video.json_object())\n\n elif request.method == \"DELETE\":\n\n db.session.delete(video)\n db.session.commit()\n return make_response({\n \"id\": video.video_id\n\n }, 200)\n \n@video_bp.route(\"//rentals\", methods=[\"GET\"], strict_slashes=False)\ndef video_id_rentals(id):\n rentals = Rental.query.filter_by(video_id = id)\n results = []\n for rental in rentals:\n results.append({\n \"due_date\": rental.due_date,\n \"name\": rental.customer.name,\n \"phone\": rental.customer.phone,\n \"postal_code\": rental.customer.postal_code\n })\n\n return make_response(jsonify(results), 200)","sub_path":"app/video_route.py","file_name":"video_route.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"209500078","text":"#!/usr/bin/env python\n\nimport hashlib\nimport json\nimport multiprocessing\nimport os\nimport sys\nfrom collections import OrderedDict\nfrom unittest.mock import call, mock_open, patch\n\nimport pytest\nimport requests\n\nimport wasapi_client as wc\n\n\nWASAPI_URL = 'http://example.com/webdata'\n\nWASAPI_TEXT = \"\".join(\"\"\"{\n \"count\": 2,\n \"files\": [\n {\n \"account\": 1,\n \"checksums\": {\n \"md5\": \"61f818912d1f39bc9dd15d4b87461110\",\n \"sha1\": \"edef6bca652d75d0587ef411d5f028335341b074\"\n },\n \"collection\": 7967,\n \"crawl\": 256123,\n \"crawl-start\": \"2016-12-22T14:07:24Z\",\n \"crawl-time\": \"2016-12-22T18:55:12Z\",\n \"filename\": \"AIT-JOB256123-00000.warc.gz\",\n \"filetype\": \"warc\",\n \"locations\": [\n \"https://warcs.example.com/webdatafile/AIT-JOB256123-00000.warc.gz\",\n \"https://example.com/download/AIT-JOB256123-00000.warc.gz\"\n ],\n \"size\": 943100093\n },\n {\n \"account\": 1,\n \"checksums\": {\n \"md5\": \"748120fd9672b22df5942bb44e9cde81\",\n \"sha1\": \"54a466421471ef7d8cb4d6bbfb85afd76022a378\"\n },\n \"collection\": 7967,\n \"crawl\": 256118,\n \"crawl-start\": \"2016-12-22T14:01:53Z\",\n \"crawl-time\": \"2016-12-22T14:01:58Z\",\n \"filename\": \"ARCHIVEIT-JOB256118-00000.warc.gz\",\n \"filetype\": \"warc\",\n \"locations\": [\n \"https://warcs.example.com/webdatafile/AIT-JOB256118-00000.warc.gz\",\n \"https://example.com/download/AIT-JOB256118-00000.warc.gz\"\n ],\n \"size\": 6265488\n }\n ],\n \"includes-extra\": false,\n \"next\": null,\n \"previous\": null,\n \"request-url\": \"https://example.com/wasapi/v1/webdata\"\n}\"\"\".split())\n\n\nNO_FILES = \"\"\"{\n \"count\": 0,\n \"files\": [],\n \"request-url\": \"https://example.com/wasapi/v1/webdata\",\n \"includes-extra\": false,\n \"next\": null,\n \"previous\": null\n}\"\"\"\n\n\nclass MockResponse200:\n \"\"\"A mocked successful requests GET response from WASAPI.\"\"\"\n\n def __init__(self, text=WASAPI_TEXT):\n self.status_code = 200\n self.text = text\n self.reason = 'OK'\n\n def json(self):\n return json.loads(self.text)\n\n\nclass MockResponse403:\n \"\"\"A mocked unsuccessful requests GET response from WASAPI.\"\"\"\n\n def __init__(self):\n self.status_code = 403\n self.reason = 'Forbidden'\n\n\nclass Test_make_session:\n def test_make_session_auth(self):\n auth = ('user', 'pass')\n session = wc.make_session(auth)\n assert session.auth == auth\n\n def test_make_session_no_auth(self):\n session = wc.make_session(None)\n assert session.auth is None\n\n\nclass Test_get_webdata:\n def test_get_webdata(self):\n \"\"\"Test a successful response.\"\"\"\n session = requests.Session()\n with patch.object(session, 'get', return_value=MockResponse200()):\n response = wc.get_webdata(WASAPI_URL, session)\n # Compare with whitespace stripped.\n response_text = \"\".join(json.dumps(response, sort_keys=True).split())\n assert response_text == WASAPI_TEXT\n\n def test_get_webdata_403_forbidden(self):\n \"\"\"Test bad authentication handling.\"\"\"\n session = requests.Session()\n with patch.object(session, 'get', return_value=MockResponse403()):\n with pytest.raises(SystemExit):\n wc.get_webdata(WASAPI_URL, session)\n\n def test_get_webdata_ConnectionError(self):\n \"\"\"Test host connection isn't made.\"\"\"\n session = requests.Session()\n error = requests.exceptions.ConnectionError\n with patch.object(session, 'get', side_effect=error):\n with pytest.raises(SystemExit):\n wc.get_webdata(WASAPI_URL, session)\n\n def test_get_webdata_json_error(self):\n \"\"\"Test 200 non-JSON repsonse exits.\"\"\"\n session = requests.Session()\n text = 'response text is not json'\n with patch.object(session, 'get', return_value=MockResponse200(text)):\n with pytest.raises(SystemExit):\n wc.get_webdata(WASAPI_URL, session)\n\n\n@patch('requests.Session')\nclass Test_Downloads:\n def test_populate_downloads(self, mock_session):\n \"\"\"Test a queue is returned with expected data.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n downloads = wc.Downloads(WASAPI_URL, download=True)\n j_queue = downloads.get_q\n assert j_queue.qsize() == 2\n # Drain the JoinableQueue to avoid BrokenPipeError.\n # There could be a better way to handle this...\n while j_queue.qsize():\n q_item = j_queue.get()\n j_queue.task_done()\n for field in ['locations', 'filename', 'checksums']:\n assert field in q_item\n\n def test_populate_downloads_multi_page(self, mock_session):\n \"\"\"Test the queue returned for multiple results pages.\"\"\"\n # Give the first of our two page responses a next page URL.\n p1 = WASAPI_TEXT.replace('\"next\":null', '\"next\":\"http://test?page=2\"')\n responses = [MockResponse200(p1), MockResponse200()]\n mock_session.return_value.get.side_effect = responses\n downloads = wc.Downloads(WASAPI_URL, download=True)\n j_queue = downloads.get_q\n assert j_queue.qsize() == 4\n # Drain the JoinableQueue to avoid BrokenPipeError.\n while j_queue.qsize():\n q_item = j_queue.get()\n j_queue.task_done()\n for field in ('locations', 'filename', 'checksums'):\n assert field in q_item\n\n def test_populate_downloads_no_get_q(self, mock_session):\n \"\"\"Test download=False prevents get_q attribute existing.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n downloads = wc.Downloads(WASAPI_URL, download=False)\n with pytest.raises(AttributeError):\n getattr(downloads, 'get_q')\n\n def test_populate_downloads_urls(self, mock_session):\n \"\"\"Test urls is populated with first location per file.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n downloads = wc.Downloads(WASAPI_URL, download=False)\n assert len(downloads.urls) == 2\n for url in ['https://warcs.example.com/webdatafile/AIT-JOB256123-00000.warc.gz',\n 'https://warcs.example.com/webdatafile/AIT-JOB256118-00000.warc.gz']:\n assert url in downloads.urls\n\n def test_populate_downloads_manifest(self, mock_session):\n \"\"\"Test the checksums dict is populated.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n downloads = wc.Downloads(WASAPI_URL, download=False)\n assert len(downloads.checksums)\n assert downloads.checksums['md5'] == [('61f818912d1f39bc9dd15d4b87461110',\n 'AIT-JOB256123-00000.warc.gz'),\n ('748120fd9672b22df5942bb44e9cde81',\n 'ARCHIVEIT-JOB256118-00000.warc.gz')]\n assert downloads.checksums['sha1'] == [('edef6bca652d75d0587ef411d5f028335341b074',\n 'AIT-JOB256123-00000.warc.gz'),\n ('54a466421471ef7d8cb4d6bbfb85afd76022a378',\n 'ARCHIVEIT-JOB256118-00000.warc.gz')]\n\n def test_populate_downloads_manifest_destination(self, mock_session):\n \"\"\"Test the checksums dict is populated with destination included.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n downloads = wc.Downloads(WASAPI_URL, download=False, destination='{}tmp'.format(os.sep))\n assert len(downloads.checksums)\n assert downloads.checksums['md5'] == [\n ('61f818912d1f39bc9dd15d4b87461110',\n os.path.normpath('/tmp/AIT-JOB256123-00000.warc.gz')),\n ('748120fd9672b22df5942bb44e9cde81',\n os.path.normpath('/tmp/ARCHIVEIT-JOB256118-00000.warc.gz'))\n ]\n assert downloads.checksums['sha1'] == [\n ('edef6bca652d75d0587ef411d5f028335341b074',\n os.path.normpath('/tmp/AIT-JOB256123-00000.warc.gz')),\n ('54a466421471ef7d8cb4d6bbfb85afd76022a378',\n os.path.normpath('/tmp/ARCHIVEIT-JOB256118-00000.warc.gz'))\n ]\n\n def test_populate_downloads_generate_manifest(self, mock_session, tmpdir):\n \"\"\"Test checksum files are created for all algorithms.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n sub_dir = 'downloads'\n dest = tmpdir.mkdir(sub_dir)\n downloads = wc.Downloads(WASAPI_URL, download=False, destination=str(dest))\n downloads.generate_manifests()\n sub_dir_contents = dest.listdir()\n assert len(sub_dir_contents) == 2\n for name in ['manifest-md5.txt', 'manifest-sha1.txt']:\n assert dest.join(name) in sub_dir_contents\n\n def test_write_manifest_file(self, mock_session, tmpdir):\n \"\"\"Test a manifest file is written for the given algorithm.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n sub_dir = 'downloads'\n dest = tmpdir.mkdir(sub_dir)\n downloads = wc.Downloads(WASAPI_URL, download=False, destination=str(dest))\n downloads.write_manifest_file('sha1')\n assert len(dest.listdir()) == 1\n txt = (\n 'edef6bca652d75d0587ef411d5f028335341b074\\t{p}{s}AIT-JOB256123-00000.warc.gz\\n'\n '54a466421471ef7d8cb4d6bbfb85afd76022a378\\t{p}{s}ARCHIVEIT-JOB256118-00000.warc.gz\\n'\n )\n assert dest.join('manifest-sha1.txt').read() == txt.format(p=dest, s=os.sep)\n\n def test_write_manifest_file_wrong_algorithm(self, mock_session, tmpdir):\n \"\"\"Test writing a manifest file for an algorithm we don't have.\"\"\"\n mock_session.return_value.get.return_value = MockResponse200()\n sub_dir = 'downloads'\n dest = tmpdir.mkdir(sub_dir)\n downloads = wc.Downloads(WASAPI_URL, download=False, destination=str(dest))\n with pytest.raises(wc.WASAPIManifestError):\n downloads.write_manifest_file('sha2')\n\n\n@patch('requests.Session')\nclass Test_get_files_count:\n def test_get_files_count(self, mock_session):\n mock_session.return_value.get.return_value = MockResponse200()\n count = wc.get_files_count(WASAPI_URL)\n assert count == 2\n\n\n@patch('requests.Session')\nclass Test_get_files_size:\n def test_get_files_size(self, mock_session):\n mock_session.return_value.get.return_value = MockResponse200()\n count, total = wc.get_files_size(WASAPI_URL)\n assert count == 2\n assert total == 949365581\n\n def test_get_files_size_multi_page(self, mock_session):\n # Give the first of our two page responses a next page URL.\n p1 = WASAPI_TEXT.replace('\"next\":null',\n '\"next\":\"{}?page=2\"'.format(WASAPI_URL))\n # The value for `count` is pulled from the last page. Though,\n # in actuality, `count` should be same on all pages.\n p2 = WASAPI_TEXT.replace('\"count\":2', '\"count\":4')\n responses = [MockResponse200(p1), MockResponse200(p2)]\n mock_session.return_value.get.side_effect = responses\n count, total = wc.get_files_size(WASAPI_URL)\n assert count == 4\n assert total == 949365581 * 2\n\n def test_get_files_size_no_files(self, mock_session):\n mock_session.return_value.get.return_value = MockResponse200(NO_FILES)\n count, total = wc.get_files_size(WASAPI_URL)\n assert count == 0\n assert total == 0\n\n\nclass Test_convert_bytes:\n @pytest.mark.parametrize('size, expected', [\n (0, '0.0B'),\n (1023, '1023.0B'),\n (1024, '1.0KB'),\n (1024000, '1000.0KB'),\n (1048576, '1.0MB'),\n (1073741824, '1.0GB'),\n (1099511628000, '1.0TB')\n ])\n def test_convert_bytes(self, size, expected):\n assert wc.convert_bytes(size) == expected\n\n\nclass Test_download_file:\n FILE_DATA = {\n 'locations': ['http://loc1/blah.warc.gz',\n 'http://loc2/blah.warc.gz'],\n 'filename': 'blah.warc.gz',\n 'checksums': {'sha1': '33304d104f95d826da40079bad2400dc4d005403',\n 'md5': '62f87a969af0dd857ecd6c3e7fde6aed'}\n }\n\n def test_download_file_200(self):\n session = requests.Session()\n mock_200 = MockResponse200('')\n loc = self.FILE_DATA['locations'][0]\n filename = self.FILE_DATA['filename']\n\n with patch.object(session, 'get', return_value=mock_200) as mock_get, \\\n patch('wasapi_client.write_file') as mock_write_file:\n wc.download_file(self.FILE_DATA, session, filename)\n\n # Check we only tried downloading files until successful download.\n mock_get.assert_called_once_with(loc, stream=True)\n mock_write_file.assert_called_once_with(mock_200, filename)\n\n def test_download_file_not_200(self):\n session = requests.Session()\n mock_403 = MockResponse403()\n locations = self.FILE_DATA['locations']\n filename = self.FILE_DATA['filename']\n\n with patch.object(session, 'get', return_value=mock_403) as mock_get, \\\n pytest.raises(wc.WASAPIDownloadError) as err:\n wc.download_file(self.FILE_DATA, session, filename)\n\n for item in (str(locations), filename):\n assert item in str(err)\n # Check all locations were tried.\n calls = [call(locations[0], stream=True),\n call(locations[1], stream=True)]\n mock_get.assert_has_calls(calls)\n\n def test_download_file_OSError(self):\n session = requests.Session()\n mock_200 = MockResponse200('')\n locations = self.FILE_DATA['locations']\n filename = self.FILE_DATA['filename']\n\n with patch.object(session, 'get', return_value=mock_200) as mock_get, \\\n patch('wasapi_client.write_file') as mock_write_file:\n mock_write_file.side_effect = OSError\n with pytest.raises(wc.WASAPIDownloadError) as err:\n wc.download_file(self.FILE_DATA, session, filename)\n\n for item in (str(locations), filename):\n assert item in str(err)\n # Check we only tried downloading files until successful download.\n mock_get.assert_called_once_with(locations[0], stream=True)\n mock_write_file.assert_called_once_with(mock_200, filename)\n\n\nclass Test_verify_file:\n @patch('wasapi_client.calculate_sum')\n def test_verify_file(self, mock_calc_sum):\n \"\"\"Test a matching checksum returns True.\"\"\"\n checksum = '33304d104f95d826da40079bad2400dc4d005403'\n checksums = {'sha1': checksum}\n mock_calc_sum.return_value = checksum\n assert wc.verify_file(checksums, 'dummy/path')\n\n def test_verify_file_unsupported_algorithm(self):\n \"\"\"Test all algorithms being unsupported returns False.\"\"\"\n checksums = {'shaq1': 'shaq1algorithmdoesnotexist'}\n assert not wc.verify_file(checksums, 'dummy/path')\n\n @patch('wasapi_client.calculate_sum')\n def test_verify_file_checksum_mismatch(self, mock_calc_sum):\n \"\"\"Test calculated checksum does not match the expected.\"\"\"\n checksum = '33304d104f95d826da40079bad2400dc4d005403'\n checksums = {'sha1': checksum}\n mock_calc_sum.return_value = checksum + 'notmatching'\n with patch('wasapi_client.logging', autospec=True) as mock_logging:\n assert not wc.verify_file(checksums, 'dummy/path')\n msg = 'Checksum mismatch for dummy/path: expected {}, got {}notmatching'.format(checksum,\n checksum)\n mock_logging.error.assert_called_once_with(msg)\n\n @patch('wasapi_client.calculate_sum')\n def test_verify_file_one_supported_algorithm(self, mock_calc_sum):\n \"\"\"Test one unsupported/one supported algorithm returns True.\"\"\"\n checksum = '33304d104f95d826da40079bad2400dc4d005403'\n checksums = OrderedDict([('abc', 'algorithm_unsupported'),\n ('sha1', checksum)])\n mock_calc_sum.return_value = checksum\n with patch('wasapi_client.logging', autospec=True) as mock_logging:\n assert wc.verify_file(checksums, 'dummy/path')\n # Check that unsupported algorithm was tried.\n mock_logging.debug.assert_called_once_with('abc is unsupported')\n mock_logging.info.assert_called_once_with('Checksum success at: dummy/path')\n\n\nclass Test_calculate_sum:\n @pytest.mark.skipif(sys.version_info < (3, 4, 4), reason=('bug via mock_open '\n 'https://github.com/python/cpython/commit/86b34d'))\n def test_calculate_sum(self):\n data = 'data from file'.encode('utf-8')\n with patch('builtins.open', mock_open(read_data=data)):\n checksum = wc.calculate_sum(hashlib.sha1, 'dummy/path')\n assert checksum == hashlib.sha1(data).hexdigest()\n\n\nclass Test_convert_queue:\n def test_convert_queue(self):\n q = multiprocessing.Manager().Queue()\n q.put(('success', 'name1'))\n q.put(('failure', 'name2'))\n dict_from_q = wc.convert_queue(q)\n assert dict_from_q['success'] == ['name1']\n assert dict_from_q['failure'] == ['name2']\n\n\nclass Test_generate_report:\n def test_generate_report_all_success(self):\n q = multiprocessing.Manager().Queue()\n q.put(('success', 'name1'))\n q.put(('success', 'name2'))\n report = wc.generate_report(q)\n assert report == ('Total downloads attempted: 2\\n'\n 'Successful downloads: 2\\n'\n 'Failed downloads: 0\\n')\n\n def test_generate_report_one_failure(self):\n q = multiprocessing.Manager().Queue()\n q.put(('success', 'name1'))\n q.put(('failure', 'name2'))\n report = wc.generate_report(q)\n assert report == ('Total downloads attempted: 2\\n'\n 'Successful downloads: 1\\n'\n 'Failed downloads: 1\\n'\n 'Failed files (see log for details):\\n'\n ' name2\\n')\n\n def test_generate_report_all_failure(self):\n q = multiprocessing.Manager().Queue()\n q.put(('failure', 'name1'))\n q.put(('failure', 'name2'))\n report = wc.generate_report(q)\n assert report == ('Total downloads attempted: 2\\n'\n 'Successful downloads: 0\\n'\n 'Failed downloads: 2\\n')\n\n\n@patch('wasapi_client.download_file')\nclass TestDownloader:\n FILE_DATA = {\n 'locations': ['http://loc1/blah.warc.gz',\n 'http://loc2/blah.warc.gz'],\n 'filename': 'blah.warc.gz',\n 'checksums': {'sha1': '33304d104f95d826da40079bad2400dc4d005403',\n 'md5': '62f87a969af0dd857ecd6c3e7fde6aed'}\n }\n\n def test_run(self, mock_download):\n \"\"\"Test downloader when downloads are successful.\"\"\"\n # Create a queue holding two sets of file data.\n get_q = multiprocessing.JoinableQueue()\n for _ in (1, 2):\n get_q.put(self.FILE_DATA)\n result_q = multiprocessing.Queue()\n log_q = multiprocessing.Queue()\n with patch('wasapi_client.verify_file', return_value=True):\n p = wc.Downloader(get_q, result_q, log_q)\n p.start()\n p.run()\n # If the join doesn't block, the queue is fully processed.\n get_q.join()\n assert result_q.qsize() == 2\n assert log_q.qsize() == 0\n for _ in (1, 2):\n assert result_q.get() == ('success', self.FILE_DATA['filename'])\n\n def test_run_WASAPIDownloadError(self, mock_download):\n \"\"\"Test downloader when downloads fail.\"\"\"\n mock_download.side_effect = wc.WASAPIDownloadError()\n # Create a queue holding two sets of file data.\n get_q = multiprocessing.JoinableQueue()\n for _ in (1, 2):\n get_q.put(self.FILE_DATA)\n result_q = multiprocessing.Queue()\n log_q = multiprocessing.Queue()\n p = wc.Downloader(get_q, result_q, log_q)\n p.start()\n p.run()\n # If the join doesn't block, the queue is fully processed.\n get_q.join()\n assert result_q.qsize() == 2\n assert log_q.qsize() == 2\n for _ in (1, 2):\n assert result_q.get() == ('failure', self.FILE_DATA['filename'])\n\n\nclass Test_parse_args:\n def test_SetQueryParametersAction(self):\n \"\"\"Test that arguments passed with this action are in query_params.\"\"\"\n args = wc._parse_args(['--crawl-start-after',\n '2016-12-22T13:01:00',\n '--crawl-start-before',\n '2016-12-22T15:11:00',\n '-c'])\n assert len(args.query_params) == 2\n assert args.query_params['crawl-start-after'] == '2016-12-22T13:01:00'\n assert args.query_params['crawl-start-before'] == '2016-12-22T15:11:00'\n\n def test_SetQueryParametersAction_multiple_collections(self):\n \"\"\"Test multiple collections end up in query_params.\n\n A query can have multiple collections, so test that the\n user can supply multiple values.\n \"\"\"\n args = wc._parse_args(['--collection', '12345', '98', '--crawl', '12'])\n assert len(args.query_params) == 2\n assert args.query_params['collection'] == ['12345', '98']\n","sub_path":"tests/test_wasapi_client.py","file_name":"test_wasapi_client.py","file_ext":"py","file_size_in_byte":21491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"553522819","text":"from __future__ import print_function\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom scipy import stats\n\nfrom sklearn import metrics\nfrom sklearn.metrics import classification_report\nfrom sklearn import preprocessing\n\nimport keras\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Flatten, Reshape, GlobalAveragePooling1D\nfrom keras.layers import Conv2D, MaxPooling2D, Conv1D, MaxPooling1D\nfrom keras.utils import np_utils\n\ndef feature_normalize(dataset):\n\n mu = np.mean(dataset, axis=0)\n sigma = np.std(dataset, axis=0)\n for i in range(0, dataset.shape[1]):\n if sigma[i] == 0:\n sigma[i] = 1\n return (dataset - mu)/sigma\n\ndef read_data(file_path):\n df = pd.read_csv(file_path)\n return df\n\nLABELS = [\"line\",\"shake\",\"square\",\"circle\",\"still\"]\nresult = [0, 0, 0, 0, 0]\n\nmodel = load_model('./bestmodel/C5_25rssi_1.h5')\n\nfor k in range(0,5):\n result = [0, 0, 0, 0, 0]\n for j in range(1 ,21):\n\n #phase = read_data('../reader_data/ML_realdata/phase_still_0_50_' + str(j) + '.csv')\n rssi = read_data('../reader_data/ML_realdata/rssi_' + LABELS[k] + '_0_50_' + str(j) + '.csv')\n #rssi = read_data('../reader_data/ML_realdata/rssi_' + 'still' + '_0_50_' + str(j) + '.csv')\n\n\n #X_phase = np.asarray(phase, dtype= np.float32)\n X_rssi = np.asarray(rssi, dtype= np.float32)\n\n\n #X_phase = feature_normalize(X_phase)\n X_rssi = feature_normalize(X_rssi)\n\n size = X_rssi.shape[1]\n\n X_test_A = []\n for i in range(0, size):\n A = X_rssi[:,i][:,np.newaxis]\n if i == 0:\n X_test_A = A\n else:\n X_test_A = np.concatenate((X_test_A, A))\n X_test = np.asarray(np.vsplit(X_test_A, size))\n\n # Set input & output dimensions\n num_time_periods, num_sensors = X_test.shape[1], X_test.shape[2]\n num_classes = 5\n\n # Set input_shape / reshape for Keras\n # Remark: acceleration data is concatenated in one array in order to feed\n # it properly into coreml later, the preferred matrix of shape [40,3]\n # cannot be read in with the current version of coreml (see also reshape\n # layer as the first layer in the keras model)\n input_shape = (num_time_periods*num_sensors)\n\n # print('input_shape:', input_shape)\n\n x_test = X_test\n\n x_test = x_test.reshape(x_test.shape[0], input_shape)\n\n x_test = x_test.astype(\"float32\")\n # print('test after load: ', model.predict(x_test))\n y_pred_test = model.predict(x_test)\n # Take the class with the highest probability from the test predictions\n max_y_pred_test = np.argmax(y_pred_test, axis=1)\n for i in range(0, size):\n print(j,LABELS[max_y_pred_test[i]], y_pred_test)\n result[max_y_pred_test[i]] = result[max_y_pred_test[i]] + 1\n \n #print(k+1)\n print(result)\n","sub_path":"ML/test_readerdata_rssi.py","file_name":"test_readerdata_rssi.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"50250742","text":"import math\nimport random\n\nclass Berserker(object):\n MAX_hp = 250\n base_hp = 250\n base_speed = 75\n priority = 'Normal'\n mindset_multiplier = 1.00\n move = ''\n\n def Jab(self,opponent):\n \"\"\" Jab - A fast, light attack. Does 30 Basic Damage to Opponent\"\"\"\n self.priority = 'Fast'\n opponent.base_hp -= math.floor( 30*self.mindset_multiplier )\n\n def Haymaker(self,opponent):\n \"\"\" Haymaker - A Slow, strong attack. Does 65 Base to Opponent and 30 Base Damage to User\"\"\"\n self.priority = 'Slow'\n opponent.base_hp -= math.floor (65*self.mindset_multiplier)\n self.base_hp -= math.floor(30*self.mindset_multiplier)\n\n def PumpUp(self,opponent):\n \"\"\" PumpUp - Normal speed. Improves the Mindset of the User ( x 1.25 )\"\"\"\n self.priority = 'Normal'\n self.mindset_multiplier *= 1.25\n\n move_pool = {'1':Jab,'2':Haymaker,'3':PumpUp}\n\nclass Yogi(object):\n MAX_hp = 220\n base_hp = 220\n base_speed = 80\n priority = 'Normal'\n mindset_multiplier = 1.00\n move = ''\n\n def Sukha(self,opponent):\n \"\"\" Sukha - A Normal speed move. Restores up to a Base of 30 HP to User\"\"\"\n self.priority = 'Normal'\n\n if self.base_hp<=self.MAX_hp:\n self.base_hp += math.floor(30*self.mindset_multiplier)\n else:\n self.base_hp = self.MAX_hp\n\n def Dukha(self,opponent):\n \"\"\" Dukha - A Normal-speed attack. Does 40 Base Damage to the Opponent\"\"\"\n self.priority = 'Normal'\n opponent.base_hp -= math.floor(40*self.mindset_multiplier)\n\n def Meditate(self,opponent):\n \"\"\" Meditate - A Normal-speed move. Improves the Mindset of the User (x 1.35)\"\"\"\n self.priority = 'Normal'\n self.mindset_multiplier *= 1.35\n\n move_pool = {'1':Sukha,'2':Dukha,'3':Meditate}\n\nclass Trickster(object):\n MAX_hp = 175\n base_hp = 175\n base_speed = 100\n priority = 'Normal'\n mindset_multiplier = 1.00\n move = ''\n\n def Bag_o_tricks(self,opponent):\n \"\"\" Bag-O-Tricks - A Normal-speed move. Increases or Decreases Opponent HP anywhere from 0 to 100 and User HP from 0 to 50\"\"\"\n self.priority = 'Normal'\n opponent.base_hp -= math.floor ( random.uniform(-1,1)*100*self.mindset_multiplier )\n if opponent.base_hp > opponent.MAX_hp:\n opponent.base_hp = opponent.MAX_hp\n\n if self.base_hp <= self.MAX_hp:\n self.base_hp += math.floor ( random.uniform(-1,1)*50*self.mindset_multiplier )\n else:\n pass\n\n if self.base_hp > self.MAX_hp:\n self.base_hp = self.MAX_hp\n\n def Tease(self,opponent):\n \"\"\" Tease - A Normal-speed move. Reduces the Mindset of the Opponent (x 0.8)\"\"\"\n self.priority = 'Normal'\n opponent.mindset_multiplier *= 0.9\n self.mindset_multiplier *= 1.05\n\n def Swapper(self,opponent):\n \"\"\" Swapper - A Normal-speed move. Swaps the User HP with the Opponent HP\"\"\"\n self.priority = 'Normal'\n self.base_hp, opponent.base_hp = opponent.base_hp, self.base_hp\n self.MAX_hp, opponent.MAX_hp = opponent.MAX_hp, self.MAX_hp\n\n move_pool = {'1':Bag_o_tricks,'2':Tease,'3':Swapper}\n","sub_path":"pyfight_characters.py","file_name":"pyfight_characters.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"525636739","text":"import sys\nsys.stdin = open('cargo.txt', 'r')\n\n\ndef pathfinder(idx, end):\n global num, aa\n num += 1\n # print('gogo', num)\n global cnt, maxx\n if idx >= len(base)-1:\n if maxx < cnt:\n maxx = cnt\n return\n # if maxx != 0:\n # if abs(base[idx][0] - base[idx][1]) > aa//maxx:\n # return\n if end == 0:\n ended.append(base[idx][1])\n end = ended[-1]\n if end <= base[idx+1][0]:\n ended.append(base[idx+1][1])\n end = ended[-1]\n cnt += 1\n pathfinder(idx + 1, end)\n cnt -= 1\n ended.pop(-1)\n end = ended[-1]\n else:\n pathfinder(idx+1, end)\n pathfinder(idx + 1, end)\n\n\ndef func():\n global se\n if len(se) == 0:\n return\n else:\n s = se.pop(0)\n if res[-1][1] <= s[0] and s not in res:\n res.append(s)\n func()\n\n\n# T = int(input())\n# for tc in range(1, T+1):\n# N = int(input())\n# se = [list(map(int, input().split())) for _ in range(N)]\n# for i in range(N-1):\n# mi = i\n# for j in range(i+1, N):\n# if se[mi][1] > se[j][1]:\n# mi = j\n# se[i], se[mi] = se[mi], se[i]\n# res = [se[0]]\n# func()\n# print('#%d %d' % (tc, len(res)))\n#\nimport copy\n\n\ntestcase = int(input())\nfor test_num in range(1, testcase+1):\n N = int(input())\n cnt = 0\n num =0\n result = 0\n base = [0]*N\n maxx = 0\n ended = []\n for i in range(N):\n base[i] = list(map(int, input().split()))\n base = sorted(base)\n # print(base)\n a = copy.deepcopy(base)\n for i in range(len(base)):\n for j in range(i+1, len(base)):\n if base[i][0] == base[j][0]:\n a[j] = 0\n new = []\n for i in range(len(a)):\n if a[i] != 0:\n new.append(a[i])\n base = new\n aa = abs(base[0][0] - base[0][1])\n pathfinder(0, 0)\n\n print('#%d %d'%(test_num, maxx+1))\n","sub_path":"algorithm_practice/algo_19_sep_3rd/5202_cargo_dock.py","file_name":"5202_cargo_dock.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"42950532","text":"N = int(input())\nA = list(map(int, input().split()))\n\n# tmp = 0\n# S = [0] +[(tmp := (tmp + i)) for i in A] # python3.8以降であれば省略可能\nS = [0]\nfor i in A:\n S.append(S[-1] + i)\n\nfor i in range(1, N + 1):\n print(max(iter(S[j] - S[j - i] for j in range(i, N + 1))))\n","sub_path":"累積和/全国統一プログラミング王決定戦本戦A/ruisekiwa.py","file_name":"ruisekiwa.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"303657614","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport image_cropping.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('website', '0011_news_featured_small'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='event',\n name='subtitle',\n ),\n migrations.AddField(\n model_name='event',\n name='local',\n field=models.CharField(default=None, max_length=150, verbose_name=b'Local'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='news',\n name=b'featured_small',\n field=image_cropping.fields.ImageRatioField(b'featured_image', '170x170', hide_image_field=False, size_warning=False, allow_fullsize=False, free_crop=False, adapt_rotation=False, help_text=b'Imagem para mais destaques na central de not\\xc3\\xadcias.', verbose_name=b'Destaque Pequeno'),\n preserve_default=True,\n ),\n ]\n","sub_path":"apps/website/migrations/0012_auto_20150924_1602.py","file_name":"0012_auto_20150924_1602.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"204140125","text":"#!/usr/bin/env python3\nimport matplotlib.pyplot as plt\nimport math\n\n\nHERTZ = range(5, 21)\nSIDES = range(3, 10)\nCANVAS_SIZE = [-10, 10]\nWAVES = 350\nCOLORS = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow',]\nALPHA = 0.75\n\n\nclass Colors(object):\n\t\"\"\" Iterates over matplotlib colors \"\"\"\n\tdef __init__(self):\n\t\tself.i = 0\n\tdef __iter__(self):\n\t\treturn self\n\tdef __next__(self):\n\t\tself.i += 1\n\t\tif self.i >= len(COLORS):\n\t\t\tself.i = 0\n\t\treturn COLORS[self.i]\n\n\ndef get_vertices(sides):\n\tvertices = []\n\tfor degrees in range(0, 360, int(360/sides)):\n\t\tradians = math.radians(degrees)\n\t\tx = math.cos(radians)\n\t\ty = math.sin(radians)\n\t\tvertices.append((x, y))\n\t\tprint(f'({x}, {y}) for degrees: {degrees}, radians: {radians}')\n\treturn vertices\n\n\ndef get_waves(vertex, hertz, color):\n\tcircles = []\n\tdelta = 1/hertz\n\tcircles.append(plt.Circle(vertex, 0.075, color='black', fill=True))\n\tfor i in range(WAVES):\n\t\tcircles.append(\n\t\t\tplt.Circle(\n\t\t\t\tvertex,\n\t\t\t\tdelta * i,\n\t\t\t\tcolor=color,\n\t\t\t\tfill=False,\n\t\t\t\talpha=ALPHA,\n\t\t\t)\n\t\t)\n\treturn circles\n\n\ndef create_plot(sides, hertz):\n\tfig, ax = plt.subplots()\n\tax.add_artist(plt.Circle((0,0), 0.05, color='black', fill=True))\n\tvertices = get_vertices(sides)\n\tcolors = Colors()\n\tfor vertex in vertices:\n\t\tcolor = colors.__next__()\n\t\twaves = get_waves(vertex, hertz, color)\n\t\tfor wave in waves:\n\t\t\tax.add_artist(wave)\n\n\tfig.canvas.draw()\n\tplt.ylim(CANVAS_SIZE)\n\tplt.xlim(CANVAS_SIZE)\n\tplt.title(f'{sides} Equidistant Waves at {hertz}Hz')\n\tfig.savefig(f'waves-{WAVES}_sides-{sides}_hertz-{hertz}.png')\n\tplt.show()\n\n\nfor sides in SIDES:\n\tfor hertz in HERTZ:\n\t\tcreate_plot(sides, hertz)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"597077873","text":"import os\nimport json\nfrom qcloud_cos import CosConfig, CosS3Client\n\nwith open('package.json') as f:\n package = json.loads(f.read())\n\nProject = package['name']\nDeploy = package['deploy']['prod']\n\nconfig = CosConfig(\n Region=Deploy['region'],\n SecretId=Deploy['secretId'],\n SecretKey=Deploy['secretKey']\n)\nclient = CosS3Client(config)\n\nmarker = \"\"\nwhile True:\n response = client.list_objects(\n Bucket=Deploy['bucket'],\n Marker=marker\n )\n\n if 'Contents' in response.keys():\n objects = map(lambda v: {'Key': v['Key']}, response['Contents'])\n client.delete_objects(\n Bucket=Deploy['bucket'],\n Delete={\n 'Object': list(objects),\n 'Quiet': 'true'\n }\n )\n\n if response['IsTruncated'] == 'false':\n break\n\n marker = response['NextMarker']\n\nprint('Clear COS OK!')\n\nfor root, dir, files in os.walk('dist/' + Project):\n for file in files:\n local = os.path.join(root, file).replace('\\\\', '/')\n key = local.replace('dist/' + Project + '/', '')\n client.upload_file(\n Bucket=Deploy['bucket'],\n LocalFilePath=local,\n Key=key\n )\n print('Send <' + key + '> Success')\n\nprint('Sync COS OK!')\n","sub_path":"ngx_deploy_for_cos/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"642801270","text":"# -*- coding: utf-8 -*-\nfrom odoo import fields, models, api, _\nimport logging\nfrom datetime import datetime, timedelta, date\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass LoanAccountPaymentWizard(models.TransientModel):\n _name = 'loan.account.payment.wizard'\n\n payment_journal_id = fields.Many2one(comodel_name='account.journal', string='Payment Journal',\n domain='[(\"type\",\"in\",[\"bank\",\"cash\"])]')\n\n def generate_payment(self):\n loan_id = self.env.context.get('active_id')\n loan = self.env['loan.payment'].browse(loan_id)\n acc_payment_date = 'Loan/' + datetime.now().strftime(\"%Y\") + '/' + loan.name\n vals = {\n 'payment_type': 'outbound',\n 'partner_type': 'customer',\n 'partner_id': loan.partner_id.id,\n 'amount': loan.req_amount,\n 'journal_id': self.payment_journal_id.id,\n 'communication': loan.desc,\n 'payment_method_id': self.env.ref('account.account_payment_method_manual_out').id,\n 'source_doc': acc_payment_date\n }\n loan.state = 'closed'\n self.env['account.payment'].create(vals)\n self.env['account.payment']._onchange_journal()\n","sub_path":"centione_hr_loan/wizard/loan_account_payment_wizard.py","file_name":"loan_account_payment_wizard.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"480290056","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom bson.objectid import ObjectId\nfrom bson.errors import InvalidId\nfrom datetime import datetime\nfrom flask import Flask\nfrom flask.ext.babel import Babel, format_date, format_time, format_timedelta\nfrom flask.ext.mongoengine import MongoEngine\nfrom flask.ext.login import LoginManager\nfrom itsdangerous import base64_encode, base64_decode\nfrom jinja2 import Undefined\nfrom urlparse import urlparse\nfrom werkzeug.datastructures import ImmutableDict\nfrom werkzeug.routing import BaseConverter, ValidationError\n\nfrom mis import settings\n\n# make custom undefined class\n\nclass MalleableUndefined(Undefined):\n def __getitem__(self, key):\n return self\n\n def __getattr__(self, key):\n return self\n\n# make custom flask with our undefined class\n\nclass MisFlask(Flask):\n def create_jinja_environment(self):\n self.jinja_options = ImmutableDict(undefined=MalleableUndefined, **self.jinja_options)\n return super(MisFlask, self).create_jinja_environment()\n\n# init application\napp = MisFlask(\"mis\", instance_relative_config=True)\napp.config.from_object(settings)\napp.config.from_pyfile(\"mis.conf\", silent=True)\n\n# init db\ndb = MongoEngine(app)\n\n# init login manager\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"auth.login\"\n\n# init localization\nbabel = Babel(app)\n\n# declare custom url ObjectId converter\nclass ObjectIDConverter(BaseConverter):\n def to_python(self, value):\n try:\n return ObjectId(base64_decode(value))\n except (InvalidId, ValueError, TypeError):\n raise ValidationError()\n\n def to_url(self, value):\n return base64_encode(value.binary)\n\napp.url_map.converters['objectid'] = ObjectIDConverter\n\n# now we can import blueprints\nfrom mis.auth import auth\nfrom mis.core import core\n\n# register blueprints\napp.register_blueprint(auth)\napp.register_blueprint(core)\n\n@app.context_processor\ndef inject_current_datetime():\n return dict(datetime=datetime.now())\n\n@app.template_filter(\"defaults\")\ndef defaults(value, name):\n if type(value) == list:\n for item in value:\n try:\n if item[name]: return item[name]\n except TypeError:\n if item: return item\n except KeyError:\n return \"\"\n\n elif value:\n return value\n\n return \"\"\n\n@app.template_filter(\"date\")\ndef date_filter(value, format=\"short\"):\n if type(value) == datetime: return format_date(value, format=format)\n else: return value\n\n@app.template_filter(\"time\")\ndef time_filter(value, format=\"HH:mm\"):\n if type(value) == datetime: return format_time(value, format=format)\n else: return value\n\n@app.template_filter(\"timedelta\")\ndef timedelta_filter(value):\n if type(value) == datetime: return format_timedelta(value)\n else: return value\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"mis/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"112091221","text":"from django.urls import path\nfrom . import views\n\n\napp_name = 'users'\nurlpatterns = [\n\tpath('registration/', views.userRegistration, name='user_registration_url'),\n\tpath('authorization/', views.userAuthorization, name='user_authorization_url'),\n\tpath('logout/', views.userLogout, name='user_logout_url'),\n\tpath('admin/', views.userAdmin, name='user_admin_url'),\n\tpath('edit/', views.userEdit, name='user_edit_url'),\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"488463636","text":"# -*- coding: UTF-8 -*-\n\nimport glob\nimport csv\nimport os.path\n\nimport arcpy\n\naprx_folder = r\"G:\\Mon Drive\\dev\\scan_projets_ESRI\\aprx_sample\" # indiquer entre les guillemets le chemin absolu du dossier contenant les fichiers .aprx à \"scanner\"\n# csv_folder = r\"C:\\Users\\Administrateur\\Desktop\\test_workbenchs\"\ncsv_folder = r\"G:\\Mon Drive\\dev\\scan_projets_ESRI\"\n\nli_aprx_path = glob.glob(aprx_folder + \"\\*.aprx\")\n\ncsv_content = []\nfor aprx_path in li_aprx_path:\n service_name = os.path.basename(r\"{}\".format(aprx_path))[:-5]\n\n aprx = arcpy.mp.ArcGISProject(aprx_path)\n li_maps = aprx.listMaps()\n\n for map in li_maps:\n li_layers = [lyr for lyr in map.listLayers() if lyr.name != \"World Topographic Map\"]\n\n for lyr in li_layers:\n\n layer_title = lyr.name\n data_path = lyr.dataSource\n data_name = os.path.basename(r\"{}\".format(data_path))\n\n if \",Dataset=\" not in data_path and data_name.endswith(\".shp\"):\n data_name = data_name[:-4]\n elif \",Dataset=\" in data_path:\n data_name = data_name[data_name.index(\",Dataset=\") + len(\",Dataset=\"):]\n else:\n pass\n\n csv_line = [\n aprx_path,\n service_name,\n layer_title,\n data_path,\n data_name\n ]\n\n csv_content.append(csv_line)\n\ncsv_file_path = csv_folder + \"\\mapping_aprx.csv\"\ncsv_file_path = csv_file_path.replace(\"\\\\\", \"\\\\\\\\\")\n\nwith open(csv_file_path, 'w', newline=\"\") as csvfile:\n csv_writer = csv.writer(csvfile, delimiter='|')\n csv_writer.writerow([\"service_path\", \"service_name\", \"layer_title\", \"data_path\", \"data_name\"])\n \n for line in csv_content:\n csv_writer.writerow(line) \n\n\n# https://pro.arcgis.com/fr/pro-app/latest/arcpy/mapping/migratingfrom10xarcpymapping.htm\n\n# C:\\Program Files\\ArcGIS\\Pro\\bin\\Python\\envs\\arcgispro-py3","sub_path":"scripts/scan_projets_ESRI/mapping_aprx_layers.py","file_name":"mapping_aprx_layers.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"101903602","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nCopyright: Deutsches Zentrum fuer Luft- und Raumfahrt e.V., 2015 (c)\nContact: daniel.boehnke@dlr.de and jonas.jepsen@dlr.de\n'''\n\nfrom VAMPzero.Lib.CPACS.Export.Wing.Structure.functions import createWingWingAttachment\n\nfrom VAMPzero.Lib.CPACS.Export.export import getObjfromXpath, createTransformation, createHeader\nfrom VAMPzero.Lib.CPACS.Export.Wing.Shape.trapezoid import createTrapezoidWing\nfrom VAMPzero.Lib.CPACS.Export.enums import WING_LOD\nfrom VAMPzero.Lib.CPACS.cpacs import stringBaseType, stringUIDBaseType\n\ndef createHTP(CPACSObj, id, xRoot, zRoot, tcRoot, tcTip, cRoot, cTip, span, phiLE, dihedral, LoD=0, location=True):\n if LoD == WING_LOD.NONE:\n return \n # just for now\n cpacsPath = '/cpacs/vehicles/aircraft/model/wings/wing[' + id + ']'\n # the next line is the one to use later on\n # cpacsPath = '/cpacs/vehicles/aircraft/model[model]/wings/wing[' + self.id + ']'\n # get the wing object from given cpacs path\n myWing = getObjfromXpath(CPACSObj, cpacsPath)\n myWing.set_name(stringBaseType(valueOf_='htp'))\n strUID = createHeader(myWing, id)\n myWing.set_symmetry('x-z-plane')\n\n\n if location:\n myWing.set_parentUID(stringUIDBaseType(isLink=True, valueOf_='fuselage'))\n createTransformation(myWing, 'absGlobal', xRoot, 0., zRoot)\n else:\n myWing.set_parentUID(stringUIDBaseType(isLink=True, valueOf_='vtp'))\n createTransformation(myWing, 'absGlobal', xRoot, 0., zRoot)\n\n # call corresponding wing creation method\n if LoD == WING_LOD.SINGLE:\n createTrapezoidWing(myWing, id, tcTip, tcRoot, cTip, cRoot, span, phiLE, dihedral, 0., strUID)\n\n if not location:\n createWingWingAttachment(myWing.get_componentSegments().get_componentSegment()[0], strUID, targetUID='vtp_Cseg', typeOfSeg='ttail')\n","sub_path":"src/VAMPzero/Lib/CPACS/Export/HTP/htp.py","file_name":"htp.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"41633247","text":"import pytest\nimport requests\n\nfrom core.recipe import KwestiaSmaku, RecipeSite, recipe_sites\n\n\nclass TestRecipe:\n def test_base_class(self):\n with pytest.raises(NotImplementedError):\n r = RecipeSite(requests.Request())\n\n def test_is_recipes_sites_a_dict(self):\n assert isinstance(recipe_sites, dict)\n\n def test_inherited_class(self):\n class Inherited(RecipeSite):\n pass\n\n request = requests.Request()\n request.text = r\"\"\"\"\"\"\n\n parser = Inherited(request)\n with pytest.raises(NotImplementedError):\n assert parser.get_recipe_title()\n with pytest.raises(NotImplementedError):\n assert parser.get_list_of_ingredients()\n with pytest.raises(NotImplementedError):\n assert parser.get_count_of_servings()\n with pytest.raises(NotImplementedError):\n assert parser.is_valid()\n\n def test_all_parsers_override_methods(self):\n\n request = requests.Request()\n request.text = r\"\"\n\n for parser in recipe_sites.values():\n try:\n p = parser(request)\n p.get_count_of_servings()\n p.get_data()\n p.get_list_of_ingredients()\n p.get_recipe_title()\n except NotImplementedError:\n pytest.fail(f\"Not all parsers override needed methods. ({parser.__name__})\")\n except:\n continue\n \n def test_kwestia_smaku(self):\n request = requests.Request()\n request.text = r\"\"\"\n

TITLE

\n
2
\n
\n
    \n
  • 150 g chicken breast
  • \n
  • 1 red pepper
\n
\n \"\"\"\n \n parser = KwestiaSmaku(request)\n\n assert parser.get_recipe_title() == \"TITLE\"\n assert parser.get_count_of_servings() == 2\n assert parser.get_list_of_ingredients() == [\n \"150 g chicken breast\",\n \"1 red pepper\"\n ]\n assert parser.is_valid()\n","sub_path":"core/tests/test_recipe.py","file_name":"test_recipe.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"570397625","text":"# -*-coding:utf-8 -*-\nfrom django.shortcuts import render\n\nfrom django.http import HttpResponse, JsonResponse\nfrom django.db import transaction\nfrom django.db.models import Q\n\nimport uuid,json\nimport datetime\n\n\ndef getdeptName(request):\n # print(request.POST)\n from ManagementSystem import models\n all_dept = models.DeptInf.objects.all()\n depts_names = []\n for dept in all_dept:\n # id = dept.id\n deptn = dept.deptname\n # deptmark = dept.remark\n single_name = {'deptname':deptn}\n depts_names.append(single_name)\n resData = {'code':200,'msg':\"ok\",'data':depts_names}\n\n return HttpResponse(json.dumps(resData))\n\n\ndef getDeptInf(request):\n pagenum = request.GET.get('page')\n pagelimit = request.GET.get('limit')\n web_deptname = request.GET.get('deptname')\n web_deptremark = request.GET.get('remark')\n\n kwargs = {}\n if web_deptname!= None and web_deptname!=\"\":\n kwargs['deptname'] = web_deptname\n\n fuzzy_remark = \"\"\n if web_deptremark!= None and web_deptremark!=\"\":\n fuzzy_remark = web_deptremark\n\n\n # print(request.POST)\n from ManagementSystem import models\n all_dept = models.DeptInf.objects.filter(**kwargs,remark__contains=fuzzy_remark)\n ing_dept = all_dept[(\n int(pagenum) - 1) * int(pagelimit):int(pagelimit) * int(pagenum)]\n count = all_dept.count()\n\n depts_list = []\n\n for dept in ing_dept:\n id = dept.id\n deptn = dept.deptname\n deptmark = dept.remark\n\n single_dept = {'id':id,'deptname':deptn,'remark':deptmark}\n depts_list.append(single_dept)\n resData = {'code':200,'count':count,'msg':\"ok\",'data':depts_list}\n return HttpResponse(json.dumps(resData))\n\n\ndef editDeptInf(request):\n print(request.POST)\n return HttpResponse(json.dumps('{\"count\":0}'))","sub_path":"MYMS/ManagementSystem/deptviews.py","file_name":"deptviews.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"204651971","text":"import tensorflow as tf\nimport numpy\nfrom network.vgg_adverserial import VGG16Adverserial\nfrom network.vgg_adverserial_100 import VGG16Adverserial100\nfrom network.mnist_adverserial import MNISTAdverserial\n\nclass AdverserialTrainer(object):\n \"\"\"\n Train a network using robust objective\n \"\"\"\n def __init__(self, learning_rate_net, learning_rate_adv, device_name,class_size):\n \"\"\"\n :return:\n \"\"\"\n self.batch_size = 128\n real_weight_decay = 0.002\n if not class_size==9:\n self.ph_images = tf.placeholder(tf.float32, [None, 32, 32, 3])\n self.ph_labels = tf.placeholder(tf.float32, [None, class_size])\n else:\n self.ph_images = tf.placeholder(tf.float32, [None, 28*28]) \n self.ph_labels = tf.placeholder(tf.float32, [None, 10])\n\n self.ph_domains = tf.placeholder(tf.float32, [None, 2])\n self.keep_prob = tf.placeholder(tf.float32)\n self.phase = tf.placeholder(tf.bool, name='phase') # train or test for batch norm\n self.lr_adv = learning_rate_adv\n self.flip_factor = tf.placeholder(tf.float32)\n self.learning_rate = tf.placeholder(tf.float32)\n\n with tf.device(device_name):\n if class_size ==100:\n real_net = VGG16Adverserial100({'data': self.ph_images}, phase=self.phase, keep_prob=self.flip_factor)\n elif class_size==9:\n real_net = MNISTAdverserial({'data': self.ph_images}, phase=self.phase, keep_prob=self.flip_factor)\n else:\n real_net = VGG16Adverserial({'data': self.ph_images}, phase=self.phase, keep_prob=self.flip_factor)\n \n class_pred = real_net.layers['fc7']\n domain_pred = real_net.layers['adv_fc3']\n real_pred_sm = tf.nn.softmax(class_pred)\n self.pred_l = real_pred_sm\n\n self.features = tf.reshape(real_net.layers['feat'],[-1,512])\n\n real_net_vars = tf.trainable_variables()\n real_l2_loss = tf.add_n([tf.nn.l2_loss(v)\n for v in real_net_vars\n if 'bias' not in v.name and 'adv' not in v.name]) * real_weight_decay\n\n per_image_loss = tf.nn.softmax_cross_entropy_with_logits(class_pred, self.ph_labels)\n self.real_loss = tf.reduce_mean(per_image_loss, 0) + real_l2_loss\n\n # this is simply adding batch norm moving average to train operations\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.real_train_op = tf.train.MomentumOptimizer(self.learning_rate,0.9).minimize(self.real_loss)\n\n correct_prediction = tf.equal(tf.argmax(real_pred_sm, 1), tf.argmax(self.ph_labels, 1))\n self.accuracy_per_im = tf.cast(correct_prediction, \"float\")\n self.real_accuracy = tf.reduce_mean(self.accuracy_per_im)\n\n net_vars = tf.trainable_variables()\n # this is a regularizer, a small weight decay\n adv_l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in net_vars\n if 'bias' not in v.name and 'adv' in v.name])\n\n self.adv_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(domain_pred, self.ph_domains), 0)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.adv_train_op = tf.train.MomentumOptimizer(self.learning_rate,0.9).minimize(self.adv_loss)\n\n tf.summary.scalar(\"summary_real_training_accuracy\", self.real_accuracy)\n tf.summary.scalar(\"summary_real_loss\", self.real_loss)\n self.summaries = tf.summary.merge_all()\n self.test_summary = tf.summary.scalar(\"summary_real_test_accuracy\", self.real_accuracy)\n\n self.adv_summ = tf.summary.merge([tf.summary.scalar(\"adverserial loss\", self.adv_loss)])\n \n def assign_batch(self, real_batch, adv_batch):\n self.real_batch = real_batch\n self.adv_batch = adv_batch\n\n @staticmethod\n def sample_with_replacement(large_batch, loss_estimates, batch_size, gamma=0.5):\n assert gamma <= 1.0\n # bimodal probabilities\n num_examples = large_batch['images'].shape[0]\n uniform_prob = 1.0 / num_examples\n uniform_prob_list = numpy.ones((num_examples,1)) * uniform_prob\n bimodal_dist = (1-gamma) * loss_estimates.reshape((num_examples,1)) + gamma * uniform_prob_list\n bimodal_dist_flat = bimodal_dist[:, 0]\n # this distribution might be distorted because of numerical error\n bimodal_dist_flat = bimodal_dist_flat / bimodal_dist_flat.sum()\n choices = numpy.random.choice(num_examples, batch_size, replace=True, p=bimodal_dist_flat)\n small_batch = {'images': large_batch['images'][choices], 'labels': large_batch['labels'][choices]}\n return small_batch\n\n def learning_step(self, session, batch_percent, final_m):\n fact = 2. / (1. + numpy.exp(-10. * batch_percent)) - 1\n lr = 0.0005 / (1. + 10 * batch_percent)**0.75 # 0.01 was the frst\n _ = session.run([self.real_train_op], feed_dict={self.ph_images: self.real_batch['images'],\n self.ph_labels: self.real_batch['labels'],\n self.phase: 1, self.learning_rate: lr})\n\n im = numpy.concatenate((self.real_batch['images'], self.adv_batch['images']), axis=0)\n l = numpy.concatenate(\n (numpy.ones((self.real_batch['images'].shape[0], 1)), numpy.zeros((self.adv_batch['images'].shape[0], 1))),\n axis=0)\n ll = numpy.concatenate((l, 1-l), axis=1)\n\n _ = session.run([self.adv_train_op], feed_dict={self.ph_images: im, self.ph_domains: ll, self.phase: 1, self.flip_factor:(fact*final_m), self.learning_rate:lr})\n #print 'LS', self.real_batch['images'].shape, self.adv_batch['images'].shape\n\n def summary_step(self, session):\n summ, loss = session.run([self.summaries, self.real_loss],\n feed_dict={self.ph_images: self.real_batch['images'],\n self.ph_labels: self.real_batch['labels'], self.phase: 0})\n\n im = numpy.concatenate((self.real_batch['images'], self.adv_batch['images']), axis=0)\n l = numpy.concatenate(\n (numpy.ones((self.real_batch['images'].shape[0],1)),numpy.zeros((self.adv_batch['images'].shape[0],1))),\n axis=0)\n ll = numpy.concatenate((l,1-l), axis=1)\n\n adv_summ, adv_loss = session.run([self.adv_summ, self.adv_loss],\n feed_dict={self.ph_images: im,\n self.ph_domains: ll, self.phase: 0})\n\n return loss, summ, adv_loss, adv_summ\n\n def test_step(self, images, labels, session):\n acc, summ = session.run([self.real_accuracy, self.test_summary],\n feed_dict={self.ph_images: images,\n self.ph_labels: labels, self.phase: 0})\n return acc, summ\n\n def active_sample(self, session, data, how_many,cl):\n num_images = data['images'].shape[0]\n num_batch = int(numpy.ceil(num_images*1.0/self.batch_size))\n all_feat = numpy.zeros((num_images,512))\n all_l = numpy.zeros((num_images,cl))\n gt_l = numpy.zeros((num_images,cl))\n for b in range(num_batch):\n set_min = b*self.batch_size\n set_max = min((b+1)*self.batch_size, num_images)\n if set_max > set_min:\n im = data['images'][set_min:set_max]\n l = data['labels'][set_min:set_max]\n feat_values, lb = session.run([self.features,self.pred_l],\n feed_dict={self.ph_images: im,\n self.ph_labels: l,\n self.phase: 0})\n\n all_feat[set_min:set_max] = feat_values\n all_l[set_min:set_max] = lb\n gt_l[set_min:set_max] = l\n return all_feat, all_l, gt_l\n","sub_path":"tf_base/src/adverserial_trainer.py","file_name":"adverserial_trainer.py","file_ext":"py","file_size_in_byte":8275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"247117664","text":"from django import forms\nfrom django.forms import ModelForm\n\nfrom .models import *\n\n\nclass FeedbackSubmissionForm(ModelForm):\n class Meta:\n model = FeedbackSubmission\n fields = '__all__'\n widgets = {\n 'email': forms.TextInput(attrs={'class': 'form-control', 'id': 'email', 'placeholder': 'Email Address'}),\n 'text': forms.Textarea(\n attrs={'class': 'form-control', 'id': 'text_input', 'placeholder': 'Enter Feedback Here'})\n }\n","sub_path":"feedbacksubmissions/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"598339097","text":"class fSelectProduct :\r\n def __init__(self, formObj, parentForm) :\r\n self.app = formObj.ClientApplication\r\n self.ProductId = None\r\n self.ProductName = None\r\n self.FundCategory = None\r\n self.PercentageOfAmilFunds = 0.0\r\n self.IsFirstShow = 1\r\n self.BranchCode = None\r\n\r\n def OnDoubleClick(self,sender):\r\n self.FormObject.Close(1)\r\n \r\n def bApplyFilterClick(self,sender):\r\n self.DisplayData()\r\n \r\n def DisplayData(self):\r\n AddParam = \"\"\r\n uipFilter = self.uipFilter\r\n\r\n FilterText = (uipFilter.FilterText or '').strip().upper()\r\n \r\n if FilterText != '' :\r\n if uipFilter.FilterCategory == 'N' :\r\n AddParam += \" and ProductNameUpCase like '%s' \" % FilterText\r\n else:\r\n AddParam += \" and AccountNameUpCase like '%s' \" % FilterText\r\n # end if else\r\n #-- end if\r\n \r\n self.qProduct.OQLText = \"\"\"\r\n select from VProduct\r\n [ status = 'A' and\r\n BranchCode = :BranchCode and\r\n ( (currencycode ='000' and producttype <> 'J' )\r\n or (producttype='J')\r\n )\r\n %s\r\n ]\r\n ( ProductId, AccountName,\r\n ProductName as ProductName,\r\n FundCategory $ as FundType,\r\n FundCategory as FundCategory,\r\n PercentageOfAmilFunds, ProductCode,\r\n Idx,\r\n AccountNo, self) then order by ProductName;\"\"\" % AddParam\r\n\r\n self.qProduct.SetParameter('BranchCode', self.BranchCode)\r\n self.qProduct.DisplayData()\r\n \r\n def GetProduct(self, branchCode):\r\n self.uipFilter.Edit()\r\n self.BranchCode = branchCode\r\n\r\n if self.IsFirstShow :\r\n self.uipFilter.FilterText = \"\"\r\n self.uipFilter.FilterCategory = \"N\"\r\n self.DisplayData()\r\n self.IsFirstShow = 0\r\n \r\n st = self.FormContainer.Show()\r\n if st == 1:\r\n self.ProductId = self.qProduct.GetFieldValue('VProduct.ProductId')\r\n self.ProductName = self.qProduct.GetFieldValue('VProduct.AccountName')\r\n self.FundCategory = self.qProduct.GetFieldValue('VProduct.FundCategory')\r\n self.PercentageOfAmilFunds = self.qProduct.GetFieldValue('VProduct.PercentageOfAmilFunds')\r\n self.AccountNo = self.qProduct.GetFieldValue('VProduct.AccountNo')\r\n\r\n return st\r\n\r\n","sub_path":"dialogs/Transaksi/fSelectProduct_intr.py","file_name":"fSelectProduct_intr.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"537106566","text":"import requests\nimport os\nimport json\n\nclass NoticeSlackLine():\n default_api_url = {\n \"slack\": \"https://hooks.slack.com/services/\",\n \"line\": 'https://notify-api.line.me/api/notify'\n }\n \n def __init__(self, app=\"slack\", token=None):\n \"\"\"\n Notice to Slack or LINE.\n\n Parameters:\n app : string (Default:\"slack\")\n \"line\" or \"slack\"\n token : string (Default:None)\n String of API Token \n or\n The path where the token is located.\n\n Returns:\n None \n \"\"\"\n self.app = app\n \n if token is None:\n raise ValueError(\"token is not passed as an argument\")\n elif os.path.isfile(token): # tokenがファイル形式のとき\n with open(token) as token_file: # JSON形式だと対応していないかも\n self.token = token_file.read()\n else:\n self.token = token\n \n def _send_line(self, message):\n \"\"\" \n Notice to LINE.\n\n Parameters:\n message : string\n Notice message.\n\n Returns:\n None\n \"\"\"\n payload = {\"message\": message}\n headers = {\"Authorization\": 'Bearer ' + self.token}\n requests.post(self.default_api_url[\"line\"], data=payload, headers=headers)\n \n def _send_slack(self, message):\n \"\"\" \n Notice to Slack.\n\n Parameters:\n message : string\n Notice message.\n\n Returns:\n None\n \"\"\"\n if self.token.startswith(self.default_api_url[\"slack\"]):\n URL = self.token\n else:\n URL = self.default_api_url[\"slack\"] + self.token\n print(URL)\n payload = {\n \"text\": message,\n# \"icon_emoji\": \":heart\" # アイコンを変更したいときに設定\n }\n \n data = json.dumps(payload)\n requests.post(URL, data)\n \n def notice(self, message=\"Processes completed.\"):\n \"\"\"\n Notice to Slack or LINE.\n\n Parameters:\n message : string\n Notice message\n Returns:\n None\n \"\"\"\n if self.app == \"slack\":\n self._send_slack(message)\n elif self.app == \"line\":\n self._send_line(message)","sub_path":"noticesl/noticeapp.py","file_name":"noticeapp.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"19016422","text":"\"\"\"\nDefines an implementation of Lapig's drivers\n\"\"\"\n\nfrom bdc_sample.core.driver import CSV\n\n\nclass Lapig(CSV):\n \"\"\"\n Driver for Lapig Sample for data loading to `sampledb`\n \"\"\"\n def __init__(self, entries, mappings=None, **kwargs):\n \"\"\"Builds a Fototeca driver\"\"\"\n\n if not mappings:\n mappings = dict(class_name='label')\n\n super(Lapig, self).__init__(entries, mappings, **kwargs)\n","sub_path":"examples/lapig.py","file_name":"lapig.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"555903197","text":"#!/usr/bin/python\n\nimport os\nimport datetime\n\n#use path.join to accommodate different base paths\nbase_path = '/home/cvkluka/Documents/site_akc/shc'\nbase_web = 'http://localhost'\n\n#base_path = '/home/cvkluka/public_html/akcatholics.org/chs'\n#base_web = 'http://www.akcatholics.org'\n\n############################# Reformatted ###############################################\n\nlit_rel_base = '/calendar/liturgy'\nlit_rel_home = '/calendar/liturgy/calendar.html'\nlit_abs_home = os.path.join(base_path, 'calendar/liturgy/calendar.html')\nlit_web_base = os.path.join(base_web, 'calendar/liturgy')\nlit_month = os.path.join(base_path, 'calendar/liturgy/month_head.html')\nlit_cal = os.path.join(base_path, 'calendar/liturgy')\nlit_rel_2014 = '/calendar/liturgy/2014'\nlit_rel_2015 = '/calendar/liturgy/2015'\nlit_header = os.path.join(base_path, 'calendar/liturgy/lit_header.html')\ncal_header = os.path.join(base_path, 'calendar/www/cal_header.html')\n\ndb_path = os.path.join(base_path, 'bce/sign_up.db')\npkl_calendar = os.path.join(base_path, 'bce/calendar.pk')\n#pickled dicts of month paths, edit has control in path\npkl_2014 = os.path.join(base_path, 'bce/pkl_2014.pk')\npkl_2015 = os.path.join(base_path, 'bce/pkl_2015.pk') \nlit_2014 = os.path.join(base_path, 'bce/lit_2014.pk')\nlit_2015 = os.path.join(base_path, 'bce/lit_2015.pk')\npkl_edit_2014 = os.path.join(base_path, 'bce/pkl_edit_2014.pk')\npkl_edit_2015 = os.path.join(base_path, 'bce/pkl_edit_2015.pk')\n\nsign_ed = os.path.join(base_path, 'calendar/forms/sign_ed.html')\ned_header = os.path.join(base_path, 'calendar/forms/ed_header.html')\ned_form = os.path.join(base_path, 'calendar/forms/ed_form.html')\nconfirm_ed = os.path.join(base_path, 'calendar/forms/confirm_ed.html')\ncomment_form = os.path.join(base_path, 'calendar/forms/comment_form.html')\ndb_comments = os.path.join(base_path, 'bce/comments.db')\ntemplate_lem = os.path.join(base_path, 'calendar/www/position.html') \n\n# email stuff \nemail_to = ['cvkluka@gmail.com'] #disable once operational\neducation_mail = ['cvkluka@gmail.com']\nemail_from = 'webmaster@akcatholics.org'\n#mail path is an apache-writable file\nmail_path = os.path.join(base_path, 'sac/email_out.txt')\ncontact_address = 'webmaster@akcatholics.org'\n \n#working paths\nact_rel_home = '/calendar/control/activity/calendar.html'\nact_rel_view = '/calendar/activity/calendar.html'\nlay_rel_home = '/calendar/www/calendar.html'\nlay_abs_home = os.path.join(base_path, 'calendar/www/calendar.html')\nact_rel = '/calendar/control/activity'\nact_abs = os.path.join(base_path, 'calendar/control/activity')\nlit_abs = os.path.join(base_path, 'calendar/liturgy')\nact_base = os.path.join(base_path, 'calendar/control/activity/calendar.html')\n#act web used only in edit_act.cgi\nact_web = os.path.join(base_web, 'calendar/control/activity/act_edit.html')\nact_header = os.path.join(base_path, 'calendar/control/activity/act_hhead.html')\nact_head = os.path.join(base_path, 'calendar/control/activity/act_head.html')\nmonth_head = os.path.join(base_path, 'calendar/liturgy/month_head.html')\nlit_head = os.path.join(base_path, 'calendar/liturgy/lit_head.html')\nact_add = os.path.join(base_path, 'calendar/control/activity/act_add.html')\nadd_edit = os.path.join(base_path, 'calendar/control/activity/add_edit.html')\nact_error = os.path.join(base_path, 'calendar/control/activity/act_error.html')\nact_confirm = os.path.join(base_path, 'calendar/control/activity/act_confirm.html')\nact_edit = os.path.join(base_path, 'calendar/control/activity/act_edit.html')\nedit_confirm = os.path.join(base_path, 'calendar/control/activity/edit_confirm.html')\n#no control in path\nact_db = os.path.join(base_path, 'bce/activities.db')\nact_openhome = os.path.join(base_path, 'calendar/activity/calendar.html') \nact_openbase = os.path.join(base_path, 'calendar/activity') \nact_openheader = os.path.join(base_path, 'calendar/activity/act_hhead.html')\nact_openhead = os.path.join(base_path, 'calendar/activity/act_head.html')\n\n#this replaces month integers with month names\nmonths_num = { 1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', \\\n7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December' }\n\n#this reads values from the form, matches all_fields database but now defined in each script, check this\nform_list = ['User', 'Date', 'Holy_Day', 'Mass', 'EM1', 'EM2', 'EM3', 'Lector1', \\\n 'Lector2', 'Altar1', 'Altar2', 'Altar3', 'Altar4', 'Sacristan', 'First_Name', \\\n 'Last_Name', 'Notify']\n\n#one-level dict used in template substitution (lem.cgi)\nsub_fields = { 'User':'',\\\n 'Date':'',\\\n 'Holy_Day':'',\\\n 'Mass':'',\\\n 'EM1':'',\\\n 'EM2':'',\\\n 'EM3':'',\\\n 'Lector1':'',\\\n 'Lector2':'',\\\n 'Altar1':'',\\\n 'Altar2':'',\\\n 'Altar3':'',\\\n 'Altar4':'',\\\n 'Sacristan':'',\\\n 'month_name':'',\\\n 'month_path':'',\\\n 'First_Name':'',\\\n 'Last_Name':'' }\n\n#find the python module that does this translation...\ntime_dict = {'00:00':'Select', \n '06:00':'6:00AM', \\\n '06:30':'6:30AM',\\\n '07:00':'7:00AM',\\\n '07:30':'7:30AM', \\\n '08:00':'8:00AM',\\\n '08:30':'8:30AM',\\\n '09:00':'9:00AM',\\\n '09:30':'9:30AM',\\\n '10:00':'10:00AM',\\\n '10:30':'10:30AM',\\\n '11:00':'11:00AM',\\\n '11:30':'11:30AM',\\\n '12:00':'12:00PM',\\\n '12:30':'12:30PM',\\\n '13:00':'1:00PM',\\\n '13:30':'1:30PM',\\\n '14:00':'2:00PM',\\\n '14:30':'2:30PM',\\\n '15:00':'3:00PM',\\\n '15:30':'3:30PM',\\\n '16:00':'4:00PM',\\\n '16:30':'4:30PM',\\\n '17:00':'5:00PM',\\\n '17:30':'5:30PM',\\\n '18:00':'6:00PM',\\\n '18:30':'6:30PM',\\\n '19:00':'7:00PM',\\\n '19:30':'7:30PM',\\\n '20:00':'8:00PM',\\\n '20:30':'8:30PM',\\\n '21:00':'9:00PM',\\\n '21:30':'9:30PM',\\\n '22:00':'10:00PM',\\\n '22:30':'10:30PM',\\\n '23:00':'11:00PM',\\\n '23:30':'11:30PM',\\\n '00:00':'12:00AM'}\n\n#this prints the full string to the table cell for the calendar day \nmass_args = { '09:00':'9:00 AM Mass', \\\n '10:00':'10:00 AM Mass', \\\n '10:30':'10:30 AM Mass', \\\n '11:00':'11:00 AM Mass',\\\n '11:30':'11:30 AM Mass', \\\n '12:10':'12:10 PM Mass',\\\n '13:00':'1:00 PM Mass', \\\n '15:00':'3:00 PM Mass', \\\n '17:00':'5:00 PM Mass', \\\n '17:30':'5:30 PM Mass', \\\n 'Filipino Simbang Gabi Mass 5:30 PM': 'Filipino Simbang Gabi Mass 5:30 PM',\\\n '18:00':'6:00 PM Solemn Vespers',\\\n '18:30':'6:30 PM Mass', \\\n 'Advent Reconciliation Service 7:00 PM':'Advent Reconciliation Service 7:00 PM',\\\n '19:00':'7:00 PM Mass',\\\n '19:30':'7:30 PM Mass',\\\n '22:00':'10:00 PM Holy Hour',\\\n '23:00':'11:00 PM Vigil Mass',\\\n '23:30':'11:30 PM Vigil Mass'} \n\n#this replaces time args with user-friendly strings in the html page (full_list) loaded by lem.cgi (CLEAN up later)\nmass_times = { '09:00':'09:00 AM', '10:00':'10:00 AM', '10:30':'10:30 AM', '11:00':'11:00 AM', '11:30':'11:30 AM', \\\n '12:10':'12:10 PM', '13:00':'1:00 PM', '15:00':'3:00 PM', '17:00':'5:00 PM', '17:30':'5:30 PM', \\\n '18:00':'6:00 PM', '18:30':'6:30 PM', '19:00':'7:00 PM', '19:30':'7:30 PM', '22:00':'10:00 PM',\\\n '23:00':'11:00 PM', '23:30':'11:30 PM' } \n \n#this format matches calendar days to date strings in template substitution \nHoly_Days = { '2014-01-01':'Mary_Mother_of_God', \\\n '2014-03-05':'Ash_Wednesday', \\\n '2014-04-13':'Palm_Sunday', \\\n '2014-04-17':'Holy_Thursday',\n '2014-04-18':'Good_Friday',\\\n '2014-04-19':'Holy_Saturday', \\\n '2014-04-20':'Easter_Sunday', \\\n '2014-04-27':'Divine_Mercy_Sunday',\\\n '2014-05-29':'Ascension', \\\n '2014-06-08':'Pentecost', \\\n '2014-06-15':'Holy_Trinity',\\\n '2014-06-19':'Corpus_Christi', \\\n '2014-06-27':'Sacred_Heart_of_Jesus', \\\n '2014-08-15':'Assumption_of_Mary', \\\n '2014-11-01':'All_Saints_Day', \\\n '2014-11-27':'Thanksgiving',\\\n '2014-11-30':'First_Advent', \\\n '2014-12-07':'Second_Advent, Our_Lady_of_Guadalupe', \\\n '2014-12-08':'Immaculate_Conception', \\\n '2014-12-14':'Third_Advent', \\\n '2014-12-15':'Episcopal_Ordination',\\\n '2014-12-21':'Fourth_Advent',\\\n '2014-12-24':'Christmas_Eve',\\\n '2014-12-25':'Christmas_Day',\\\n '2014-12-28':'Feast_of_the_Holy_Family',\\\n '2014-12-31':'New_Year_Eve',\\\n '2015-01-01':'Mary_Mother_of_God', \\\n '2015-01-04':'Epiphany', \\\n '2015-01-11':'Baptism_of_the_Lord',\\\n '2015-03-18':'Ash_Wednesday', \\\n '2015-03-29':'Palm_Sunday', \\\n '2015-04-02':'Holy_Thursday',\\\n '2015-04-03':'Good_Friday',\\\n '2015-04-04':'Holy_Saturday', \\\n '2015-04-05':'Easter_Sunday', \\\n '2015-04-12':'Divine_Mercy_Sunday',\\\n '2015-05-14':'Ascension', \\\n '2015-05-24':'Pentecost', \\\n '2015-05-31':'Holy_Trinity',\\\n '2015-06-04':'Corpus_Christi', \\\n '2015-06-12':'Sacred_Heart_of_Jesus', \\\n '2015-08-15':'Assumption_of_Mary', \\\n '2015-11-01':'All_Saints_Day', \\\n '2015-11-30':'First_Advent', \\\n '2015-12-08':'Immaculate_Conception', \\\n '2015-12-25':'Christmas_Day'}\n\nfext = '.html'\n\ntable_header = '''\n \n \n \n \n \n '''\n\ned_footer = '''
\n
SundayMondayTuesdayWednesdayThursdayFridaySaturday
\n \n
\n '''\n\n\n\n\n\n\n\n\n","sub_path":"akc/config_cal.py","file_name":"config_cal.py","file_ext":"py","file_size_in_byte":10892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"205542231","text":"#! /usr/bin/env python3\nimport numpy as np\n\nimport events\nimport network\nimport simulation\nimport toolkit\n\nsQuo_world = network.World.load('config files/sQuo.yml')\nsQuo_sim = simulation.Simulation.load('config files/sQuo-config.yml')\n\nseeds = [sQuo_sim.seed+i*sQuo_sim.increment for i in range(sQuo_sim.rep)]\nsQuo_minTTCs = {1: [], 2: []}\nsQuo_minDistances = {1: {}, 2: {}}\nfor categoryNum in sQuo_minDistances:\n for seed in seeds:\n sQuo_minDistances[categoryNum][seed] = []#\n\nsQuo_PETs = []\nsQuo_interactions = []\n\nsQuo_rearEndnInter10 = []\nsQuo_rearEndnInter20 = []\nsQuo_rearEndnInter50 = []\n\nsQuo_sidenInter10 = []\nsQuo_sidenInter20 = []\nsQuo_sidenInter50 = []\n\n\nfor seed in seeds:\n print(str(seeds.index(seed)+1) + 'out of {}'.format(len(seeds)))\n sQuo_world = network.World.load('config files/sQuo.yml')\n sQuo_sim.seed = seed\n sQuo_sim.run(sQuo_world)\n for inter in sQuo_world.completedInteractions:\n if inter.categoryNum is not None:\n sQuo_distance = inter.getIndicator(events.Interaction.indicatorNames[2])\n if sQuo_distance is not None:\n sQuo_minDistances[inter.categoryNum][seed].append(sQuo_distance.getMostSevereValue(1))\n sQuo_ttc = inter.getIndicator(events.Interaction.indicatorNames[7])\n if sQuo_ttc is not None:\n sQuo_minTTC = sQuo_ttc.getMostSevereValue(1)*sQuo_sim.timeStep # seconds\n if sQuo_minTTC < 0:\n print(inter.num, inter.categoryNum, sQuo_ttc.values)\n if sQuo_minTTC < 20:\n sQuo_minTTCs[inter.categoryNum].append(sQuo_minTTC)\n values = sQuo_ttc.getValues(False)\n if len(values) > 5:\n sQuo_interactions.append(inter)\n if inter.getIndicator(events.Interaction.indicatorNames[10]) is not None:\n sQuo_PETs.append(inter.getIndicator(events.Interaction.indicatorNames[10]).getMostSevereValue(1))\n\n sQuo_rearEndnInter10.append((np.array(sQuo_minDistances[1][seed]) <= 10).sum())\n sQuo_rearEndnInter20.append((np.array(sQuo_minDistances[1][seed]) <= 20).sum())\n sQuo_rearEndnInter50.append((np.array(sQuo_minDistances[1][seed]) <= 50).sum())\n\n sQuo_sidenInter10.append((np.array(sQuo_minDistances[2][seed]) <= 10).sum())\n sQuo_sidenInter20.append((np.array(sQuo_minDistances[2][seed]) <= 20).sum())\n sQuo_sidenInter50.append((np.array(sQuo_minDistances[2][seed]) <= 50).sum())\n\nsQuo_nInter10 = {1: np.mean(sQuo_rearEndnInter10), 2: np.mean(sQuo_sidenInter10)}\nsQuo_nInter20 = {1: np.mean(sQuo_rearEndnInter20), 2: np.mean(sQuo_sidenInter20)}\nsQuo_nInter50 = {1: np.mean(sQuo_rearEndnInter50), 2: np.mean(sQuo_sidenInter50)}\n\ntoolkit.callWhenDone()\n\nsQuo_results = {'PETS': sQuo_PETs,\n 'TTCs': sQuo_minTTCs,\n 'side-nInter10': sQuo_sidenInter10,\n 'side-nInter20': sQuo_sidenInter20,\n 'side-nInter50': sQuo_sidenInter50,\n 'rear-nInter10': sQuo_rearEndnInter10,\n 'rear-nInter20': sQuo_rearEndnInter20,\n 'rear-nInter50': sQuo_rearEndnInter50,\n 'nInter10' : sQuo_nInter10,\n 'nInter20': sQuo_nInter20,\n 'nInter50': sQuo_nInter50,\n 'minDistances': sQuo_minDistances,\n }\ntoolkit.saveYaml('sQuo_results.yml', sQuo_results)","sub_path":"experiments/squo.py","file_name":"squo.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"96082091","text":"from db import TABLE_NAME ,insert,get_row ,update ,delete\nimport logging\n\nlog_d = logging.info\n\nclass BaseSteta:\n list_state = []\n model = TABLE_NAME\n state_zero = ''\n session = None\n state = state_zero\n\n def _create_session(self,user_id:str):\n insert(self.model, {\n \"user_id\": user_id,\n \"state\": self.state_zero\n })\n self._is_session(user_id)\n log_d(f\"Create sessions {user_id}\")\n\n def _is_session(self,user_id:int)->bool:\n\n user_id = int(user_id)\n session = get_row(self.model,['user_id','body_text','photo','locate','state'],['user_id', user_id])\n log_d(f\"Get session {self.__class__} {user_id} \\n {session}\")\n if len(session) == 0 :\n return False\n else:\n self.session = session[0]\n return True\n\n def __init__(self,user_id:int)->None:\n if self._is_session(user_id) == False:\n self._create_session(user_id)\n\n def check_state(self,state)->bool:\n log_d(f\"Class state: {self.state}\\n User state {self.session['state']}\")\n if state == self.state:\n return True\n else:\n return False\n\n def _change_data(self,change_data:dict):\n change_data['state'] = self.state\n log_d(f\"Session date {self.session}\\nChange data {change_data}\")\n update(TABLE_NAME, column_and_data=change_data, conditional=['user_id', self.session['user_id']])\n\nclass StateText(BaseSteta):\n state = 'text'\n def get_text(self)->str:\n return self.session['text']\n\n def set_text(self,text):\n self._change_data({\n 'body_text':text\n })\n\n @property\n def is_text(self,):\n return True\n\nclass StatePhoto(BaseSteta):\n state = 'photo'\n\n def get_photo(self)->list[str]:\n photo = self.session['photo']\n photo_split = photo.split(';')\n log_d(f\"Photo date {self.session['photo']}\\n Split {photo_split}\")\n return photo_split\n\n def set_photo(self,id_photo:str):\n photo = self.session['photo']\n log_d(f\"Set photo {photo} :{photo.__class__} --{id_photo}\")\n if photo == None:\n photo = id_photo\n else:\n photo = photo + \";\" + id_photo\n self._change_data({\n 'photo': photo\n })\n\n @property\n def is_photo(self,):\n return True\n\n\nclass StateGeo(BaseSteta):\n state = 'geo'\n def get_geo_link(self):\n return self.session['locate']\n\n def set_geo_link(self,geo:str,type:str):\n log_d(\"Set locate \")\n\n self._change_data({\n 'locate': \"{}:{}\".format(type, geo)\n })\n\n @property\n def is_geo(self):\n if self.session['locate'].split(\":\")[0] == \"cord\":\n return True\n else:\n return False\n\n @property\n def is_geo_text(self):\n\n if self.session['locate'].split(\":\")[0] == \"text\":\n return True\n else:\n return False\n\ndef get_state(user_id:str)->BaseSteta:\n state = BaseSteta(user_id).session['state']\n if BaseSteta.state == state:\n return StateText(user_id)\n elif StateText.state == state:\n return StateGeo(user_id)\n elif StateGeo.state == state:\n return StatePhoto(user_id)\n elif StatePhoto.state ==state:\n return StatePhoto(user_id)\n\ndef drop_task_state(user_id):\n delete(TABLE_NAME,user_id)\n BaseSteta(user_id)","sub_path":"bot/free_bot_telegramm/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"372401135","text":"# ordered arguments\n# Keyword arguments - Parameter order does not matter. \n# Optional parameters assigned '' and put to right\ndef fn(a, b = 'B', c = '', d = ''):\n print(a + b + c + d)\n\n# Positional arguments\nfn('b', 'z')\n\nfn(b='b', a='z') \n\nfn('b', 'c', d='D')\n\n# Send copy to list fn(list[:])\n\n# Create empty tuple for the function\n#fn(*topping)\n\n# Create variable args\n#fn(**args)\n\n\"\"\"\nimport lib\n\nlib.fn()\n\nCan also import a single function\nfrom module_name import fn(), fn1()\n\nAlias module name due to conflict\nimport module_name as m_name\n\nimport all functions to avoid module.fn convention\nimport module_name *\n\n\"\"\"\n","sub_path":"Python/Crash Course/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"212454601","text":"print(\"Monthly Bills with Remaining Balance\")\nprint(\"If no payment for the month is required, enter a value of 0\")\nprint()\npay = float(input(\"Monthly Income:$\"))\nrent = float(input(\"Rent:$\"))\ncpayment = float(input(\"Car Payment:$\"))\ncarinsurance = float(input(\"Car Insurance:$\"))\ninternet = float(input(\"Internet:$\"))\nphone = float(input(\"Phone:$\"))\nfood = float(input(\"Food allowance:$\"))\nccards = float(input(\"Credit Card Payments:$\"))\nsloans = float(input(\"Student Loans:$\"))\nmisc = float(input(\"Misc Items:$\"))\n\n\ndifference = float(pay) - (float(cpayment) + float(carinsurance) + float(internet) + float(phone)\n + float(food) + float(rent) + float(ccards) + float(sloans) + float(misc))\n\nprint()\nprint(\"The remaining balance is ${:.2f} \"\"this month.\".format(difference))\n","sub_path":"portfolio projects/finances.py","file_name":"finances.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"59576343","text":"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mp\n\ndata_dir = '/mnt/data_local/WORKING/paper/'\ndata_ext = '.xlsx'\ndata_fn = 'Book1'\n\nheader = ['treatment', 'replicate', 'ice thickness (cm)', 'oil thickness (mm)', 'elapsed time D (d)', 'migration rate (cm d^(-1))', 'T2', 'V2', 'T3', 'V3']\nxl_file = pd.read_excel(os.path.join(data_dir, data_fn+data_ext), sheetname=0, names=header, skiprows=2)\n\n# reshape columns\nxl_file1 = xl_file.drop(['T2', 'V2', 'T3', 'V3'], axis=1)\nxl_file1['time'] = '1'\nxl_file2 = xl_file.drop(['elapsed time D (d)', 'migration rate (cm d^(-1))', 'T3', 'V3'], axis=1)\nxl_file2['time'] = '2'\nxl_file2.rename(columns={'T2': 'elapsed time D (d)', 'V2': 'migration rate (cm d^(-1))'}, inplace=True)\nxl_fileS = xl_file.drop(['elapsed time D (d)', 'migration rate (cm d^(-1))', 'T2', 'V2'], axis=1)\nxl_fileS['time'] = 'S'\nxl_fileS.rename(columns={'T3': 'elapsed time D (d)', 'V3': 'migration rate (cm d^(-1))'}, inplace=True)\n\nxl = xl_file1.append(xl_file2)\nxl = xl.append(xl_fileS).reset_index()\nxl['oil/ice thickness'] = xl['oil thickness (mm)']/10/xl['ice thickness (cm)']\n\nxl.treatment.unique().__len__()\nxl.time.unique().__len__()\n\ncolor = ['r', 'g', 'b']\nmarkers = ('o', 's', 'D', '^', 'v', 'x', '+')\n\nh = []\nl = ['1st surfacing', '2nd surfacing', 'steady state'] + list(xl.treatment.unique())\nii = 0\ncolor_dict = {}\nfor time in xl.time.unique():\n color_dict[time] = color[ii]\n h.append(mp.patches.Rectangle((0, 0), 1, 1, edgecolor=color[ii], facecolor='None'))\n ii+=1\nii = 0\nmarkers_dict = {}\nfor treatment in xl.treatment.unique():\n markers_dict[treatment] = markers[ii]\n h.append(plt.Line2D((0, 1),(0, 0), markerfacecolor='k', markeredgecolor='k', marker=markers[ii], linestyle=''))\n ii+=1\n\n\nfig = plt.figure(figsize=(7, 3.5))\nmp.rcParams.update({'font.size': 10})\nax1 = fig.add_subplot(1, 2, 1)\nx_label = 'oil/ice thickness'\nx_label = 'ice thickness (cm)'\n\ny_label = 'elapsed time D (d)'\nfor treatment in xl.treatment.unique():\n for time in xl.loc[xl.treatment == treatment, 'time'].unique():\n ax1.plot(xl.loc[(xl.treatment == treatment) & (xl.time == time), x_label], xl.loc[(xl.treatment == treatment) & (xl.time == time), y_label], marker=markers_dict[treatment], markeredgecolor=color_dict[time], markerfacecolor='None', linestyle='')\nax1.axes.set_xlabel(x_label)\nax1.axes.set_ylabel(y_label)\nax1.set_yscale('log')\nfig.text(0.025, 0.95, '(a)')\n\nax2 = fig.add_subplot(1, 2, 2, sharex=ax1)\ny_label = 'migration rate (cm d^(-1))'\nfor treatment in xl.treatment.unique():\n for time in xl.loc[xl.treatment == treatment, 'time'].unique():\n ax2.plot(xl.loc[(xl.treatment == treatment) & (xl.time == time), x_label], xl.loc[(xl.treatment == treatment) & (xl.time == time), y_label], marker=markers_dict[treatment], markeredgecolor=color_dict[time], markerfacecolor='None', linestyle='')\nax2.axes.set_xlabel(x_label)\nax2.axes.set_ylabel(y_label)\nax2.set_yscale('log')\nfig.text(0.55, 0.95, '(b)')\n\nbox1 = ax1.get_position()\nax1.set_position([0.1, 0.25, 0.38, 0.7])\nbox2 = ax2.get_position()\nax2.set_position([0.6, 0.25, 0.38, 0.7])\nplt.legend(h, l, loc='upper center', bbox_to_anchor=(-0.2, -0.15), fancybox=False, shadow=False, ncol=5, frameon=False)\n\nax1.spines['top'].set_visible(False)\nax2.spines['top'].set_visible(False)\nax1.spines['right'].set_visible(False)\nax2.spines['right'].set_visible(False)\n\nplt.savefig(os.path.join(data_dir, x_label+'-'+y_label + '.png'), dpi=int(300))\n","sub_path":"percolation_rate.py","file_name":"percolation_rate.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"384768642","text":"\n\nfrom __future__ import print_function\nfrom pylab import *\n\nfrom simple_kalman import *\n\n\n\n\ndef cal_acc_control_rocket(x, c, aa):\n ## In this case we have a spaceship that is guided by three\n ## thrusters. We can control the roll and the pitch, not yaw, and\n ## we can also accelerate forward or backwards.\n \n ## The target is to \"park\" the ship at the origin\n ## The goal state is all zeros.\n desired = zeros(13)\n desired[6] = 1.0\n \n ## Simply return the error. Suppose we can accelerate to any direction.\n accel = zeros(6)\n\n ## Calculate the \"forward\" direction of the ship.\n R = matrix_from_quaternion(x[6:10])[2]\n\n k1 = aa[c,0]*10.0\n k2 = aa[c,1]*10.0\n\n accel[:3] = k1*R\n accel[4] = k2\n\n return accel\n\n\n\ndef quantize(x, lowlim, parmrg):\n xx = x[[0,2,3,5,6,8,11]]\n xr = 1.0\n vr = 1.0\n ar = 3.0 * sign(xx[6])\n wr = 1.0\n Q = array([ xr, xr,\n vr, vr,\n ar, ar,\n wr,])\n\n qq = np.array(np.round(xx*Q), dtype=int16)\n\n out = 0\n for k in range(lowlim.shape[0]):\n vv = qq[k] - lowlim[k]\n if vv < 0 or vv > parmrg[k]:\n raise ValueError\n out *= parmrg[k]\n out += vv\n return out\n\n\nif __name__ == '__main__':\n set_printoptions(precision=3)\n\n kk = Kalman6DOF()\n\n dt = 0.1\n\n\n\n lowlim = array([-1,-1,-5,-5,-4,-4,-5], dtype=int16)\n higlim = array([10, 5, 5, 5, 4, 4, 5], dtype=int16)\n parmrg = higlim - lowlim + 1\n\n\n actions = array([[-1, 0],\n [ 0,-1],\n [ 0, 0],\n [ 0, 1],\n [ 1, 0],\n ])\n\n initial_state = zeros(13)\n initial_state[6] = 1.0\n\n\n policy = { quantize(initial_state, lowlim, parmrg): [0,0] }\n\n states = [(0,initial_state)]\n\n next_states = []\n\n while states != []:\n k,ss = states.pop(0) ## pick next state in the queue\n if k > 200:\n print(\"too many iters\")\n continue\n for aa in range(5):\n \n kk.state = ss\n kk.predict_state_simulation(-dt, cal_acc_control_rocket, aa, actions)\n \n sd = kk.state\n\n print(quantize(ss, lowlim, parmrg), aa, end=' ')\n\n try:\n sdq = quantize(sd, lowlim, parmrg)\n except ValueError:\n print(' - out')\n continue\n\n print(sdq, end='')\n if sdq in policy.keys():\n print(' - exists')\n continue\n else:\n print(' - record')\n policy[sdq] = aa\n states.append((k+1,sd))\n\n\n import pickle\n pickle.dump(policy, open('policy.p', 'wb'))\n\n\n\n","sub_path":"rocket_opt.py","file_name":"rocket_opt.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"413246527","text":"import datetime\nimport io\n\nimport pandas as pd\nfrom lxml import etree\n\nfrom Utilities.Debugging.Logger import Logger\nfrom Utilities.Downloaders import WebHandler as web\n\nlog = Logger(__name__)\n\n\ndef extract_row_for_onepage(url):\n # The Header for the table consists of the 2 rows -> the first row has the following structure\n #\n # Date, Open, High, Low, Close, Volume, --- Spread (2 col wide) --\n # ------------------------------------- (high - low) , (open-close)\n #\n # To parse the HTML table into a pandas dataframe -\n # 1. the xpath for the column is 'td'\n # 2. there will be 8 columns\n # - The first 6 are relevant [Date, Open, High, Low, Close, Volume]\n # - The last 2 columns are irrelevant\n # 3. For each row element, extracted above\n # - run a xpath query on the row element\n # - extract the text of the first six column\n # - zip the headers and values into a ictionary {Headers: Values}\n # - add this dictionary to a list\n\n # Fetch the page and parse it into a tree\n html_page = web.FetchURL(url)\n parser = etree.HTMLParser()\n tree = etree.parse(io.StringIO(html_page.text), parser)\n\n # xpath for extracting the table of prices\n # datatable_xpath = '/html/body/center[2]/div/div/div[5]/div[3]/div[4]/table/tr'\n datatable_xpath = '//*[@id=\"mc_mainWrapper\"]/div[3]/div/div[3]/div[4]/table/tr'\n table_tree = tree.xpath(datatable_xpath)\n\n # Table Headers - the first 2 rows\n column_xpath = 'th'\n columns = table_tree[0].xpath(column_xpath)\n table_headers = [columns[i].text for i in range(6)]\n\n # Table data - row 2 and beyond\n table_tree.pop(0)\n table_tree.pop(0)\n log.record(etree.tostring(table_tree[0]), \"debug\")\n\n def extract_columns(single_row_element): # has dependency on global variable table_headers\n\n # Parsing the data columns\n col_xpath = 'td'\n col_elements = single_row_element.xpath(col_xpath)\n col_vals = [col_elements[i].text for i in range(6)]\n\n # Zip into a dictionary\n dictionary = dict(zip(table_headers, col_vals))\n return dictionary\n\n return [extract_columns(el) for el in table_tree]\n\n\ndef parse_history(sc_id, from_dt, to_dt):\n base_url = 'http://www.moneycontrol.com/stocks/hist_stock_result.php%s'\n # CONVERT THE DATES TO THE STRING FORM e.g, 2004-12-01\n from_dt_str = from_dt.strftime(\"%Y-%m-%d\")\n to_dt_str = to_dt.strftime(\"%Y-%m-%d\")\n # CREATE THE QUERY PART OF THE SKELETON\n query_skeleton = '?sc_id=%s&pno=1&hdn=daily&fdt=%s&todt=%s'\n query_string = query_skeleton % (sc_id, from_dt_str, to_dt_str)\n #\n page_url = base_url % query_string\n log.record(\"1st page of the table %s\" % page_url, 'info')\n\n html_page = web.FetchURL(page_url)\n parser = etree.HTMLParser()\n tree = etree.parse(io.StringIO(html_page.text), parser)\n\n # List of all buttons in the table scroller come in the format ---- << Previous 1 2 3 4 5 ... Next >>\\\n # the length of the returned list - 2 gives the number of pages to scroll\n # remove 1st link ----- 1 \n # remove the last link --- Next\n\n xpath = '//*[@id=\"mc_mainWrapper\"]/div[3]/div/div[3]/div[4]/div/div/div[1]/div/a'\n filtered_html = tree.xpath(xpath) # this will be an array [elements]\n # num_pages = len(filtered_html)-2\n filtered_html.pop(0) # remove the 1st link\n filtered_html.pop() # remove the last link\n\n # From the remaining link extract the GET strings\n get_extracts = [el.get(\"href\") for el in filtered_html]\n\n # Construct the url from the extracts\n to_parse_links = [base_url % x for x in get_extracts]\n to_parse_links = [page_url] + to_parse_links\n log.record(to_parse_links, 'debug')\n\n # Extract rows from the each page\n list_of_row_list = [extract_row_for_onepage(url) for url in to_parse_links]\n # the format of list_of_row_list = [ [rows from one page], [rows from another page], ... ]\n log.record(list_of_row_list, \"debug\")\n flattened_list = [item for sublist in list_of_row_list for item in sublist]\n df = pd.DataFrame(flattened_list)\n df.Date = df.Date.map(lambda x: datetime.datetime.strptime(x, \"%d-%m-%Y\"))\n # To return data structure\n to_return = {'ListofDict': flattened_list, 'dataframe': df}\n\n return to_return\n\n\nif __name__ == '__main__':\n from datetime import date\n\n data1 = parse_history('TCS', date(2000, 1, 1), date.today())\n # There are two main parts\n print(data1[\"dataframe\"])\n","sub_path":"IndiaSingleStocks/MoneyControl_History.py","file_name":"MoneyControl_History.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"23531779","text":"\"\"\"\nThis problem was asked by Google.\n\nThe edit distance between two strings refers to the minimum number of character insertions, deletions, and\nsubstitutions required to change one string to the other.\n\nFor example, the edit distance between “kitten” and “sitting” is three:\nsubstitute the “k” for “s”, substitute the “e” for “i”, and append a “g”.\n\nGiven two strings, compute the edit distance between them.\n\"\"\"\n\n# O(NM) time, O(NM) space\ndef min_distance(word1, word2):\n n, m = len(word1) + 1, len(word2) + 1\n dp = [[0 for _ in range(m)] for _ in range(n)]\n for i in range(n):\n dp[i][0] = i\n for j in range(m):\n dp[0][j] = j\n for i in range(1, n):\n for j in range(1, m):\n dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (word1[i - 1] != word2[j - 1]))\n\n return dp[-1][-1]\n\n\n# O(NM) time, O(N) space\ndef min_distance2(word1, word2):\n n, m = len(word1) + 1, len(word2) + 1\n pre = [j for j in range(m)]\n for i in range(n):\n cur = [i] * m\n for j in range(1, m):\n cur[j] = min(cur[j - 1] + 1, pre[j] + 1, pre[j - 1] + (word1[i - 1] != word2[j - 1]))\n pre = cur[:]\n\n return pre[-1]\n\n\nif __name__ == '__main__':\n word1 = 'kitten'\n word2 = 'sitting'\n\n print(min_distance2(word1, word2))\n","sub_path":"Problems/daily-coding-problem/Problem_31.py","file_name":"Problem_31.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"362100129","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpg\n\n# On crée une matrice à la taille finale, de 50 par 100 avec toutes ses valeurs fixées à 255.\nM = 255 * np.ones((50, 100), dtype = np.uint8)\n\n# Maintenant, nous avons besoin d'une matrice en une colonne\n# 5 vrai puis 5 faux et ainsi de suite sur toute la hauteur d'une colonne obtenu par reshape\nA = np.array(([True]*5+[False]*5)*5).reshape(50,1)\n\n# La multiplication de l'un par l'autre va donner une matrice donc les valeurs vont alterner de 255 puis 0 tous les 5 lignes\nM = M*A\n\n# Il ne reste plus qu'à empiler 3 fois la même matrice comme nous travaillons en noir et blanc\nH = np.stack((M, M, M), axis = 2)\n\n# affiche et sauvegarde en png de la matrice.\nplt.imshow(H)\nplt.show()\nmpg.imsave('Horizontale.png', H)","sub_path":"Sprint1/Horizontale 4.py","file_name":"Horizontale 4.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"632286398","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 15 11:40:21 2015\n\n@author: abhishekthab\n\"\"\"\n#import necessary modules\nimport vtk\nfrom vtk.util import numpy_support\nimport os\nimport numpy\nimport matplotlib.pyplot as plt\n\n#function to convert the vtk image into a numpy array, useful for showing images\ndef vtkImageToNumPy(image, pixelDims):\n pointData = image.GetPointData()\n arrayData = pointData.GetArray(0)\n ArrayDicom = numpy_support.vtk_to_numpy(arrayData)\n ArrayDicom = ArrayDicom.reshape(pixelDims, order = 'F') #reshape the array into Fourier space\n \n return ArrayDicom\n\n#---code start--- \npath = os.getcwd() #define path from current working directory\nreader = vtk.vtkDICOMImageReader() #load DICOM reader\nreader.SetDirectoryName(path)\nreader.Update() #read in DICOM files\n\ndims = reader.GetDataExtent() #extract pixel dimensions\nConstPixelDims = [dims[1]-dims[0]+1, dims[3]-dims[2]+1, dims[5]-dims[4]+1] #calculate true pixel dimensions\nConstPixelSpacing = reader.GetPixelSpacing() #extract pixel spacing information\n\n\n\n#ArrayDicom = vtkImageToNumPy(reader.GetOutput(), ConstPixelDims)\nimg = reader.GetOutputPort()\n\nthreshold = vtk.vtkImageThreshold () #load threshold function\nthreshold.SetInputConnection(img) #load image from reader\nthreshold.ThresholdByUpper(400) # set the upper Threshold Value, using Hounsfield Values\nthreshold.ReplaceInOn() # tell VTK to replace all values above set value\nthreshold.SetInValue(1) # set all values below 400 to 0\nthreshold.ReplaceOutOn() #tell VTK to replace all values below set value\nthreshold.SetOutValue(0) # set all values above 400 to 1\nthreshold.Update() #update the image\n\nimgThreshold = threshold.GetOutputPort() \n\n\n\"\"\"\n#uncomment if you want to view the thresholded image\nArrayDicom2 = vtkImageToNumPy(threshold.GetOutput(), ConstPixelDims)\n\nplt.imshow(numpy.rot90(ArrayDicom2[:, :, 17]), cmap=plt.cm.gray)\nplt.show()\n\"\"\"\n\n\"\"\"\n#only uncomment which algorithm you want to use \n\n\"\"\"\n\"\"\"\n#DISCRETE MARCHING CUBES ALGORITHM\ndmc = vtk.vtkDiscreteMarchingCubes()#load Discrete Marching Cubes Algorithm\ndmc.SetInputConnection(imgThreshold) #import the thresholded image\ndmc.GenerateValues(1, 1, 1) #aspect ratio stays at 1:1:1\ndmc.Update() #perform the algorithm\npolydata = dmc.GetOutput() #export the 3D image as a polygon data file\nalgordata = dmc.GetOutputPort() #export the 3D image as an algorithm file\n\n\"\"\"\n\n\n#MARCHING CUBES ALGORITHM\nmc = vtk.vtkMarchingCubes()#load Marching Cubes Algorithm\nmc.SetInputConnection(imgThreshold) #import the thresholded image\nmc.GenerateValues(1, 1, 1) #aspect ratio stays at 1:1:1\nmc.Update() #perform the algorithm\npolydata = mc.GetOutput() #export the 3D image as a polygon data file\nalgordata = mc.GetOutputPort() #export the 3D image as an algorithm file\n\n\n\n\"\"\"\n#CONTOURING ALGORITHM\ncontour = vtk.vtkContourFilter()#load Discrete Marching Cubes Algorithm\ncontour.SetInputConnection(imgThreshold) #import the thresholded image\ncontour.GenerateValues(1, 1, 1) #aspect ratio stays at 1:1:1\ncontour.Update() #perform the algorithm\npolydata = contour.GetOutput() #export the 3D image as a polygon data file\nalgordata = contour.GetOutputPort() #export the 3D image as an algorithm file\n\"\"\"\n\"\"\"\n#VOXEL CONTOURING ALGORITHM (doesnt work yet)\nvcsf = vtk.vtkVoxelContoursToSurfaceFilter()\nvcsf.SetInputConnection(imgThreshold)\nvcsf.Update()\npolydata = vcsf.GetOutput() #export the 3D image as a polygon data file\nalgordata = vcsf.GetOutputPort() #export the 3D image as an algorithm file\n\"\"\"\n#############################\n\n\n#Reduce Number of Triangles\ndecimator = vtk.vtkDecimatePro()\ndecimator.SetInputConnection(algordata)\ndecimator.SetTargetReduction(0.5)\ndecimator.SetPreserveTopology(1)\ndecimator.Update()\nreducetri = decimator.GetOutputPort()\n#\n\n\n#Smooth\nsmooth = vtk.vtkSmoothPolyDataFilter()\nsmooth.SetInputConnection(filhol)\nsmooth.SetNumberOfIterations(15)\nsmooth.SetFeatureAngle(10)\nsmooth.SetRelaxationFactor(0.05)\nsmooth.FeatureEdgeSmoothingOn()\nfinaldata = smooth.GetOutputPort()\n\n\n##################################\n\n\n#####################\n\nwriter = vtk.vtkSTLWriter()\nwriter.SetFileName(\"VTK_HoleFill_PHENIX.stl\")\nwriter.SetInputConnection(finaldata())\nwriter.Write()\n\n","sub_path":"VTK/VTK.py","file_name":"VTK.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"321659768","text":"import sys\nimport random\nimport math\n\ndef loadData(datafile):\n f = open(datafile, 'r')\n data = []\n i = 0;\n l = f.readline()\n while l != '':\n a = l.split()\n l2 = []\n for j in range(0, len(a), 1):\n l2.append(float(a[j]))\n data.append(l2)\n l = f.readline()\n return data\n\n\ndef v_plus(a, b):\n cols = len(a)\n c = [0] * cols\n for i in range(0, cols):\n c[i] = a[i] + b[i]\n return c\n\ndef v_divide(a,n):\n cols=len(a)\n for i in range(0,cols):\n a[i]=a[i]/n\n return a\ndef cal_means(data, c):\n n0 = 0\n n1 = 0\n rows = len(data)\n cols = len(data[0])\n m0 = [0] * cols\n m1 = [0] * cols\n for i in range(0, rows):\n if c[i] == 0:\n m0 = v_plus(m0, data[i])\n n0 += 1\n else:\n m1 = v_plus(m1, data[i])\n n1 += 1\n\n m0 = [0]*cols if n0 == 0 else v_divide(m0, n0)\n m1 = [0]*cols if n1 == 0 else v_divide(m1, n1)\n return m0, m1\ndef dist(a, b):\n cols = len(a)\n d = 0\n for i in range(0, cols):\n d += (a[i] - b[i]) ** 2\n return math.sqrt(d)\n\ndatafile = sys.argv[1]\ndata = loadData(datafile)\nrows = len(data)\ncols = len(data[0])\nprint(data)\n# initialize\nc = [0] * rows\nfor i in range(0, rows):\n c[i] = random.randint(0, 1)\nm0, m1 = cal_means(data, c)\n\nconvergence=.0001\ndifference=1\nerror=0\n#update\nwhile difference>convergence:\n for i in range(0,rows):\n if dist(data[i],m0)= ((1 + e) * x):\n\t\t\tLB = n * _F_R / (1 + e)\n\t\t\tbreak\n\n\ta = (l * math.log(n) + math.log(2)) ** 0.5\n\tb = ((1 - math.exp(-1)) * (math.log(comb(n, k)) + l * math.log(n) + math.log(2))) ** 0.5\n\tlmd2 = 200 * n * np.square((1 - math.exp(-1)) * a + b)\n\tsita = lmd2 / LB\n\n\twhile (len(R) <= sita):\n\t\tv = random.randint(1, n)\n\t\tif model_type == 'IC':\n\t\t\tRR = generateRR_IC(v)\n\t\telif model_type == 'LT':\n\t\t\tRR = generateRR_LT(v)\n\t\tif len(RR) != 0:\n\t\t\tR.append(RR)\n\n\treturn R\n\n\ndef F_R(S_i, R):\n\tcount = 0.0\n\n\tif S_i is None:\n\t\treturn count\n\tfor i in range(len(R)):\n\t\t### condider R[i]\n\n\t\tfor seed in S_i:\n\n\t\t\tif seed in R[i]:\n\t\t\t\tcount += 1\n\t\t\t\tbreak\n\t# return a fraction number: |RR| / |R|\n\n\treturn (count / len(R))\n\n\ndef NodeSelection(R, k):\n\tfreq_list = np.zeros(n + 1, dtype=np.int)\n\tfor _RR in R:\n\t\tfor i in _RR:\n\t\t\tfreq_list[i] += 1\n\n\tV_set = set()\n\tfor idx in range(1, n + 1):\n\t\tif freq_list[idx] != 0:\n\t\t\tV_set.add(idx)\n\n\tS_k = []\n\n\tq = queue.PriorityQueue()\n\n\tfor v in V_set:\n\t\tq.put((-freq_list[v], 0, v))\n\n\tv0 = q.get()\n\tS_k.append(v0[2])\n\n\t# delete get()'s RR\n\tfor _RR in R:\n\t\tif v0[2] in _RR:\n\t\t\tfor r in _RR:\n\t\t\t\tfreq_list[r] -= 1\n\t\t\t\tif freq_list[r] == 0:\n\t\t\t\t\tV_set.remove(r)\n\n\titer = 1\n\n\twhile (len(S_k) != k):\n\n\t\tif len(V_set) == 0:\n\t\t\tbreak\n\n\t\t# for v in V_set:\n\t\t# marginal_gain = freq_list[v]\n\t\t#\n\t\t# if marginal_gain > max:\n\t\t# max = marginal_gain\n\t\t# max_v = v\n\t\t#\n\n\t\twhile (q.queue[0][1] != -iter):\n\t\t\tV = q.get()\n\t\t\tif V[2] not in V_set:\n\t\t\t\tcontinue\n\n\t\t\tmarginal_gain = freq_list[V[2]]\n\t\t\tq.put((-marginal_gain, -iter, V[2]))\n\n\t\tmax_V = q.get()\n\t\titer += 1\n\t\tS_k.append(max_V[2])\n\n\t\tfor _RR in R:\n\t\t\tif max_V[2] in _RR:\n\t\t\t\tfor r in _RR:\n\t\t\t\t\tfreq_list[r] -= 1\n\t\t\t\t\tif freq_list[r] == 0:\n\t\t\t\t\t\tV_set.remove(r)\n\n\twhile (len(S_k) != k):\n\t\tnode = random.randint(1, n)\n\t\tif node not in S_k:\n\t\t\tS_k.append(node)\n\n\treturn S_k\n\n\ndef main():\n\ttime1 = time.time()\n\tinit()\n\ttime2 = time.time()\n\t# print(\"ReadingTime\",time2-time1)\n\tl = 1 + math.log(2) / math.log(n) #### l = 1\n\n\tR = Sampling(0.2, l) #### ipsilon = 0.1\n\tS_k = NodeSelection(R, k)\n\n\tprint(S_k)\n\t# print(time.time()-time1)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"lab3-IMPs/IMP2.py","file_name":"IMP2.py","file_ext":"py","file_size_in_byte":5854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"533131979","text":"\"\"\"This module contains various utility functions.\"\"\"\n\nfrom cheryl.checkers import is_correct_isbn, is_correct_pages\nfrom cheryl.config import (\n GAP, ARROW, ISBN_PATTERN, MAX_PAGES,\n ISBN_LENGTH, PAGES_LENGTH, SPACE_AROUND,\n FORMAT_STRING,\n)\n\n\ndef quote(item: str, *, quote_type: str = \"'\") -> str:\n \"\"\"Quote item with quote_type of quotes.\"\"\"\n return f\"{quote_type}{item}{quote_type}\"\n\n\ndef unquote(item: str, *, quote_type: str = \"'\") -> str:\n \"\"\"Unquote item from quote_type of quotes.\"\"\"\n return item.strip(quote_type)\n\n\ndef get_sorted_by() -> dict:\n \"\"\"Get sorted_by Engine attribute.\"\"\"\n sorted_by = {\n \"isbn\": False,\n \"title\": False,\n \"author\": False,\n \"publisher\": False,\n \"pages\": False,\n }\n return sorted_by\n\n\ndef get_longest() -> dict:\n \"\"\"Get longest Engine attribute.\"\"\"\n longest = {\n \"title\": 0,\n \"author\": 0,\n \"publisher\": 0,\n }\n return longest\n\n\ndef get_prompt(*, message: str, gaps=0) -> str:\n \"\"\"Get a new prompt string using given message.\"\"\"\n return f\"{gaps*GAP}{message}{ARROW}\"\n\n\ndef get_from_user(*, message: str, gaps=0, lower=True) -> str:\n \"\"\"Get value from user.\n\n Set lower to False if needed.\n \"\"\"\n prompt = get_prompt(message=message, gaps=gaps)\n value = input(prompt)\n value = value.strip()\n if lower:\n return value.lower()\n else:\n return value\n\n\ndef is_correct(value, *, checker=None) -> bool:\n \"\"\"Check if value is correct using checker function.\"\"\"\n if checker:\n return checker(value)\n else:\n return bool(value)\n\n\ndef get_book_attr(*, attr: str, error: str, checker=None) -> str:\n \"\"\"Get book attribute from user.\n\n checker function is used to check attribute for correctness.\n \"\"\"\n message = attr\n while True:\n attr = get_from_user(message=message, gaps=1, lower=False)\n if is_correct(attr, checker=checker):\n break\n else:\n print(error)\n return attr\n\n\ndef there_is_nothing_to(do):\n \"\"\"Inform user that there are no books.\"\"\"\n print(f\"There is nothing to {do} yet\")\n\n\ndef key_must_be_in(keys):\n \"\"\"Inform user that key must be in keys.\"\"\"\n print(f\"Key must be in {keys}\")\n\n\ndef cannot_perform_action(action, key, target):\n \"\"\"Inform user that the program cannot perform action.\"\"\"\n print(f\"Cannot {action} a book with {key} '{target}'\")\n\n\ndef get_empty_attr_error(attr, *, gaps=0) -> str:\n \"\"\"Return empty attribute error.\"\"\"\n return f\"{gaps*GAP}{attr} cannot be empty\"\n\n\ndef get_isbn_error(*, gaps=0) -> str:\n \"\"\"Return isbn error.\"\"\"\n return f\"{gaps*GAP}isbn must be like '{ISBN_PATTERN}' where 'd' is digit\"\n\n\ndef get_pages_error(*, gaps=0) -> str:\n \"\"\"Return pages error.\"\"\"\n return f\"{gaps*GAP}pages must be positive integer less than {MAX_PAGES+1}\"\n\n\ndef create_book():\n \"\"\"Create a new book.\"\"\"\n book = {}\n book[\"isbn\"] = get_book_attr(attr=\"isbn\", error=get_isbn_error(gaps=2),\n checker=is_correct_isbn)\n book[\"title\"] = get_book_attr(attr=\"title\",\n error=get_empty_attr_error(\"title\", gaps=2))\n book[\"author\"] = get_book_attr(\n attr=\"author\",\n error=get_empty_attr_error(\"author\", gaps=2))\n book[\"publisher\"] = get_book_attr(\n attr=\"publisher\",\n error=get_empty_attr_error(\"publisher\", gaps=2))\n book[\"pages\"] = int(get_book_attr(attr=\"pages\",\n error=get_pages_error(gaps=2),\n checker=is_correct_pages))\n return book\n\n\ndef print_book(engine, book):\n \"\"\"Print book using FORMAT_STRING.\"\"\"\n print(FORMAT_STRING.format(\n book[\"isbn\"], ISBN_LENGTH + SPACE_AROUND,\n book[\"title\"], engine.longest[\"title\"] + SPACE_AROUND,\n book[\"author\"], engine.longest[\"author\"] + SPACE_AROUND,\n book[\"publisher\"], engine.longest[\"publisher\"] + SPACE_AROUND,\n book[\"pages\"], PAGES_LENGTH + SPACE_AROUND,\n ))\n\n\ndef print_books(engine):\n \"\"\"Print all books.\"\"\"\n for book in engine.books:\n print_book(engine, book)\n","sub_path":"cheryl/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"178877753","text":"# -*- coding:utf-8 -*-\nimport pymysql\nimport sys\nimport traceback\nimport ConfigParser\n\n\n\ndef user_monitor(username):\n try:\n class myconf(ConfigParser.ConfigParser):\n def __init__(self, defaults=None):\n ConfigParser.ConfigParser.__init__(self, defaults=None)\n\n def optionxform(self, optionstr):\n return optionstr\n\n conf = myconf()\n conf.read(\"/etc/zabbix/scripts/config/db.conf\")\n option = conf.sections()\n index = option[1]\n host = conf.get(index, 'host')\n port = int(conf.get(index, 'port'))\n user = conf.get(index, 'user')\n db = conf.get(index, 'db')\n passwd = conf.get(index, 'passwd')\n charset = conf.get(index, 'charset')\n # host = '192.168.1.136'\n # port = 3306\n # user = 'root'\n # db = 'dg_dqc'\n # passwd = 'root'\n # charset = 'utf8'\n conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset)\n cursor = conn.cursor()\n #返回结果为字典类型\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n except Exception:\n print(\"\")\n print('traceback.format_exc():\\n%s' % traceback.format_exc())\n cursor.close()\n conn.close()\n else:\n if username == '正常':\n username = 0\n elif username == '警告':\n username = 1\n elif username == '错误':\n username = 2\n elif username == '严重错误':\n username = 3\n elif username == '异常':\n username = 9\n else:\n print(0)\n return\n\n #sql = \"SELECT A2.Task_Name,A1.Error_Level_Cd,A1.Tx_Date,A1.TaskRunTime,A2.DQID FROM M07_CHECKRESULT A1 INNER JOIN M07_CHECKLIST A2 ON A1.DQID = A2.DQID WHERE A1.Error_Level_Cd in (1,2,3,9) AND A2.Start_Dt <= A1.TaskRunTime AND A2.End_Dt > A1.TaskRunTime \"\n sql = \"select a1.error_level_cd ,count(*) from m07_checkresult a1 inner join m07_checklist a2 on a1.dqid = a2.dqid where a1.error_level_cd in (1,2,3,9) and a2.start_dt <= a1.taskruntime and a2.end_dt > a1.taskruntime\"\n #系统前一天的时间\n #sql+=\" and a1.tx_date = (select date_sub(curdate(),interval 1 day))\"\n #要查询的异常级别\n sql +=\" and a1.error_level_cd = '{0}'\".format(username)\n sql +=\" group by a1.error_level_cd\"\n row_count = cursor.execute(sql)\n row_3 = cursor.fetchall()\n\n# print(row_3)\n if row_count==0:\n print(0)\n else:\n for i in row_3:\n print (i['error_level_cd'])\n\n\n conn.commit()\n cursor.close()\n conn.close()\n\n\nif __name__ == \"__main__\":\n user_monitor(sys.argv[1])\n #user_monitor('错误')","sub_path":"interface/tellhow/scrpit/scripts/UserParameter/ErrNumMonitor.py","file_name":"ErrNumMonitor.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"315620983","text":"import pandas as pd\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import PCA, TruncatedSVD\n\nfrom base.feature_computer import FeatureComputer\nfrom base.training.base_trainer import BaseTrainer\nfrom dataset import Dataset\n\nclass Clustering(BaseTrainer):\n def __init__(self,\n data_path='data/Calofir A. Petrișor-Ionuț.csv',\n tf_idf=None,\n count_vectorizer=None,\n dim_reduction=None,\n clf=None):\n self._tf_idf = tf_idf\n self._count_vectorizer = count_vectorizer\n self._dim_reduction = dim_reduction\n self._clf = clf\n super().__init__(data_path)\n\n def _build_train(self, data_path):\n self._data = Dataset(data_path)\n self._X_train, self._y_train = \\\n self._data.get_data_clustering()\n\n self._model = FeatureComputer(\n tf_idf=TfidfVectorizer() if self._tf_idf else None,\n count_vectorizer=CountVectorizer() if self._count_vectorizer else None,\n dim_reduction=self._dim_reduction,\n clf=self._clf\n )\n\n def save_model(self, name='default'):\n joblib.dump(self, 'models/' + name + '.joblib')\n","sub_path":"An I Sem I/ml/Homework2/src/training/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"399104956","text":"# -*-coding:utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\n\ndef add_link(link):\n new_link = \"https://ratings.fide.com/\" + link\n return new_link\n#把获取的子link变成完整link\n\ndef request_raw(link):\n raw = requests.get(link)\n return raw.text\n\n#获取网页源码\n\ndef add_main_link_list(link):\n names = []\n for x in link:\n url = x[\"href\"]\n names.append(add_link(url))\n return names\n#将所有子网页转换成list\n\ndef make_soup(xml):\n name = BeautifulSoup(xml, \"lxml\")\n return name\n#生成beautifulSoup对象\n\ndef president_info(soup):\n list1 = []\n for x in soup.find(\"span\", text=re.compile(\"Presi.*|Dele.*\"),class_=\"dir_title\").next_siblings:\n if x.string != None:\n list1.append(x.string)\n return list1\n\ndef getting(url_list, rules):\n for link in url_list:\n a = request_raw(link)\n b = make_soup(a)\n c = rules(b)\n print(c)\n#get获取\n\ndef posting(url_list, rules, data):\n videos = {}\n for link in url_list:\n a = post_raw(link,data)\n b = make_soup(a)\n c = rules(b)\n videos.update(c)\n return videos\n\ndef post_raw(link,data):\n raw = requests.post(link,data=data)\n return raw.text\n\n\ndef save_data(data):\n with open(\"/Users/Evisolpxe/PycharmProjects/request/data.txt\", 'w+') as f:\n json.dump(data,f)\n#保存数据\n","sub_path":"request/Requests.py","file_name":"Requests.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"150656893","text":"#!/usr/bin/env python\nfrom os import environ, path\n\nfrom pocketsphinx.pocketsphinx import *\nfrom sphinxbase.sphinxbase import *\nimport speech_recognition as sr\n\nprint(\"setting model directories\")\nMODELDIR = \"../cmusphinx-nl-5.2/\"\n\n# Create a decoder with certain model\nprint(\"creating decoder.\")\nconfig = Decoder.default_config()\nconfig.set_string('-hmm', path.join(MODELDIR, 'model_parameters/voxforge_nl_sphinx.cd_cont_2000'))\nconfig.set_string('-lm', path.join(MODELDIR, 'etc/voxforge_nl_sphinx.lm.bin'))\nconfig.set_string('-dict', path.join(MODELDIR, 'etc/voxforge_nl_sphinx.dic'))\ndecoder = Decoder(config)\n\ndecoder = Decoder(config)\n\nwith sr.Microphone() as source:\n print(\"Say something!\")\n decoder.listen(source)\n\n# recognize speech using Sphinx\ntry:\n print(\"Sphinx thinks you said \" + recognizer.recognize_sphinx(audio))\nexcept sr.UnknownValueError:\n print(\"Sphinx could not understand audio\")\nexcept sr.RequestError as e:\n print(\"Sphinx error; {0}\".format(e))","sub_path":"sphinxtest.py","file_name":"sphinxtest.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"553681338","text":"import numpy as np\nimport dill\nfrom polharmonic import util, multi, dist, sft\nimport os; import time; start = time.time(); print('Running...')\nnp.set_printoptions(precision=3, suppress=True)\n\n# Specify saving path\nfolder = 'ortho'\nif not os.path.exists(folder):\n os.makedirs(folder)\ndata_file = folder+'/'+folder+'.dat'\n\n# Build microscope\nexp = multi.MultiMicroscope(ill_thetas=[90], det_nas=[1.1], max_l=4, n_pts=250)\n\n# Calculate and save (comment this on repeat runs)\nexp.calc_sys_matrix()\ndill.dump(exp.psi, open(data_file,'wb'))\n\nimport pdb; pdb.set_trace() \n# Load \nf = open(data_file, 'rb')\nexp.psi = dill.load(f)\n\n# Calculate B\nexp.calc_B_matrix()\n\n# Generate phantom of true orientations\nnx, ny = 10, 10\nt = np.linspace(0, np.pi/2, nx)\np = np.linspace(0, np.pi, ny)\ntv, pv = np.meshgrid(t, p)\ntvv = np.expand_dims(tv, 2)\npvv = np.expand_dims(pv, 2)\ntp_field = np.concatenate([tvv, pvv], 2)\n\n# Expand onto spherical harmonics\nsh_field = sft.field_tp_sft(tp_field, max_l=4)\ndf = dist.DistributionField(sh_arr=sh_field)\ndf.make_positive(exp.B)\ndf.sh_arr[:,:,6:] = 0 # Low pass to simplify phantom\ndf.plot_dist_field(exp.B, exp.xyz, exp.triangles, filename=folder+'/phantom.png',\n mag=5, show=True)\n\n# Reconstruct phantom\ng = exp.calc_intensity_field(df)\ndf2 = exp.recon_dist_field(g)\ndf2.plot_dist_field(exp.B, exp.xyz, exp.triangles, filename=folder+'/phantom_recon.png',\n mag=5, show=True)\n\nprint('Total time: '+str(np.round(time.time() - start, 2)))\nos.system('say \"done\"')\n","sub_path":"notes/2018-01-18-osa-abstract/figs/analyze_ortho.py","file_name":"analyze_ortho.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"472132181","text":"import numpy as np\nimport pandas as pd\nimport re\nimport io\n\nfrom os.path import *\n# from S2.utils.tools import *\nfrom utils._tools import *\n\nread_prefix = \"/data/MIMIC3/\"\ndis_sum_prefix = \"/data/liu/mimic3/NOTESEVENT_EXTRACTION/ALL\"\nwrite_prefix=\"/data/liu/mimic3/CLAMP_NER/input\"\nrule_dissum_file = \"ReRule%d_Discharge summary\"\n\ndef clean_string(string):\n if(string):\n return string.strip('\\n').lower()\n else: \n return None\n\n## Revised Section Extraction Script\ndef re_split(text, regex = r\"\\n\\n[A-Z][A-Za-z/ ]+:\"):\n \"\"\"Split Discharge Summary to mulitple sections according to respective titles using regex rules\n\n Return:\n ------\n {titles:sections}: dict\n titiles : list. \n 1) Remove enter character\n 2) Transfer all titles to lower case, making it easier to check and match\n line_number : int.\n line number of each title\n sections: list. \n len(sections)=len(titles)+1. The first section doesn't have title as it is not beginning \n with \"\\n\" \n \"\"\"\n titles = re.findall(regex, text)\n sections = re.split(regex, text)[1:]\n sections_lines = [len(section.splitlines()) for section in sections]\n # split_lines=text.splitlines()\n # TODO:\n ## BUG: some line number mismatch to title\n title_search_index=0\n title_length=len(titles)\n title_linenums=[None]*title_length\n\n if(titles):\n with io.StringIO(text) as f:\n for num, line in enumerate(f, start=1):\n # print('{} : {}'.format(i, line.strip()))\n # print(\"line_num: %d\"%num)\n if(titles[title_search_index].strip('\\n') in line):\n # print(\"find line number %d for title %s\"%(num,titles[title_search_index].strip('\\n')))\n title_linenums[title_search_index]=num\n title_search_index = title_search_index+1 \n if(title_search_index==title_length): break;\n else: continue; \n\n # # Prvious version\n # title_linenums = [num+1 for num, line in zip(range(len(split_lines)),split_lines) \n # if any(title.strip('\\n') in line for title in titles)]\n\n next_titleline = title_linenums[1:]+[None]\n next_title = titles[1:]+[None]\n section_endline = [x+y for x, y in zip (title_linenums, sections_lines)]\n\n ## 1) transform extracted titles to lower case 2)zip line numbers and sections\n # if len(titles):\n # return dict(zip(map(clean_string,titles), zip(title_linenums, sections)))\n # else:\n # return None\n \n\n return dict(zip(map(clean_string,titles), zip(\n title_linenums, \n sections, \n section_endline,\n next_titleline,\n map(clean_string,next_title))))\n\n \n \ndef extract_sections(text,rule_index = 0, rerules = [\n r\"\\n\\n[A-Z][A-Z/ ]+:\",\n r\"\\n[A-Z][A-Z/ ]+:\",\n r\"\\n\\n[A-Z][A-Za-z/ ]+:\",\n r\"\\n[A-Z][A-Za-z/ ]+:\"\n], selected_titles = [[\"hospital course\"],[\"medical history\"],[\"medication\",\"admission\"]]):\n \"\"\"\n\n Arguments:\n ---------\n selected_titles: list\n 1)hospital course: brief hc\n 2)medical history:\n 3)medications on admission: admission medications\n \n Step:\n -----\n 1) split original text to multiple sections with titles: dict{title -> section}\n 2) select key sections by matching their titles to selected titles\n \"\"\"\n section_dict = re_split(text, rerules[rule_index]) \n # return section_dict\n\n # if(section_dict):\n # ## selected title -> matched title\n # titles_dict =dict([(selected_title, title) for title in section_dict.keys() for selected_title in selected_titles if selected_title in title])\n # ## get actually extracted titles that are matched to selected titles\n # section_titles = [titles_dict.get(title, None) for title in selected_titles]\n # ## unzip line numbers and sections \n # line_numbers, sections = list(zip(*[section_dict.get(title, (None,None)) for title in section_titles]))\n # # return section_titles\n # return tuple([(',').join(filter(None, section_titles)),\n # (',').join(filter(None, map(str,line_numbers)))]+list(sections))\n\n # else:\n # return tuple([None]*5)\n\n ## selected title -> matched title\n # BUG: medication -> [medication, admission]\n ## get actually extracted titles that are matched to selected titles\n len_selected_titles = len(selected_titles)\n section_titles=[None]*len_selected_titles\n # dict(zip(map((\";\").join,test),zip(range(3),test)))\n search_selected_titles = dict(\n zip(map((\" \").join, selected_titles), zip(\n range(len_selected_titles), selected_titles)))\n\n for extract_title in section_dict.keys():\n for key in list(search_selected_titles):\n value = search_selected_titles[key]\n if all(word in extract_title for word in value[1]):\n # print(\"find extracted title %s for %d selected title\"%(\n # extract_title,value[0]))\n section_titles[value[0]] = extract_title\n search_selected_titles.pop(key)\n # section_titles=dict(zip(map((\";\").join, selected_titles),extract_selected_titles))\n # # HACK: previous version\n # titles_dict =dict([\n # (selected_title, title) \n # for title in section_dict.keys() \n # for selected_title in selected_titles \n # if selected_title in title])\n\n # # HACK: previous version\n # section_titles = [titles_dict.get(title, None) for title in selected_titles]\n ## unzip line numbers and sections \n title_line, sections, section_endline, next_titleline, next_title= list(\n zip(*[section_dict.get(title, (None,None,None,None,None)) for title in section_titles]))\n # return section_titles\n return tuple([(',').join(filter(None, section_titles)),\n (',').join(filter(None, map(str,title_line))),\n (',').join(filter(None, map(str,section_endline))),\n (',').join(filter(None, map(str,next_titleline))),\n (',').join(filter(None, next_title))]+list(sections))\n\n\ndef save_keysessions_byfile(\n notes_discharge_df,\n rule_index,\n file=\"%s_%s_%d\",\n folder_titles = ['HOSPITAL COURSE', 'MEDICAL HISTORY', 'MEDICATIONS ON ADMISSION']):\n \n write_rule_prefix = join(write_prefix, \"Rule%d\"%rule_index)\n create_folder_overwrite(write_rule_prefix)\n tilfolder_path = [join(write_rule_prefix, title.replace(\" \",\"_\")) for title in folder_titles]\n [create_folder_overwrite(path) for path in tilfolder_path]\n title_path_dict = dict(zip(folder_titles, tilfolder_path))\n \n for subject_id, group in notes_discharge_df.groupby(['SUBJECT_ID']):\n hadm_ids = group['HADM_ID'].unique()\n ## create folder ~/subject_id/hadm_id\n cols = ['GROUP_RANK','HOSPITAL COURSE', 'MEDICAL HISTORY', 'MEDICATIONS ON ADMISSION']\n \n for hadm_id, subgroup in group.groupby(['HADM_ID']): \n \n for _, row in subgroup[cols].iterrows():\n file_name = file%(str(subject_id), hadm_id, row['GROUP_RANK'])\n [write2txt(row[title], join(\n title_path_dict[title],file_name.replace(\" \",\"_\"))) for title in folder_titles if row[title]]\n # write2txt(row[\"HOSPITAL COURSE\"],join(course_pre,file_name))\n # write2txt(row[\"MEDICAL HISTORY\"],join(pastdrug_pre,file_name))\n # write2txt(row[\"MEDICATIONS ON ADMISSION\"],join(admi_medi_pre,file_name)) \n\ndef run_rule(notes_discharge_df, rule_index):\n # notes_discharge_df=read_data(join(dis_sum_prefix,\"Discharge summary_All\"),dtype={\"HADM_ID\":str})\n add_cols = [\"TITLE\", \"TTITLE_LINE\", \"SECTION_END_LINE\",\"NEXT_TITLE_LINE\",\"NEXT_TITLE\",\"HOSPITAL COURSE\", \"MEDICAL HISTORY\", \"MEDICATIONS ON ADMISSION\"]\n notes_discharge_df[add_cols] = pd.DataFrame(notes_discharge_df['TEXT'].apply(lambda x: \n extract_sections(x,rule_index)).tolist())\n # print(notes_discharge_df)\n if(notes_discharge_df['TITLE'].isnull().values.all()):\n print(\"Rule %d is useless\"%rule_index)\n\n #TODO: uncomment \n write2file(notes_discharge_df,join(write_prefix,(\"%s_All\"%rule_dissum_file)%rule_index))\n save_keysessions_byfile(notes_discharge_df,rule_index)\n # return notes_discharge_df\n\ndef get_rule_result(rule_index):\n ## check whetehr the input file (output by last rule) exists\n # if isfile(join(write_prefix, (\"%s_All.csv\"%rule_dissum_file)%(rule_index))):\n # notes_discharge_df=read_data(join(write_prefix,(\"%s_All\"%rule_dissum_file)%(rule_index)),dtype={\"HADM_ID\":str})\n\n if(rule_index==0):\n run_rule(read_data(join(dis_sum_prefix,\"Discharge summary_All\"),dtype={\"HADM_ID\":str}),rule_index)\n \n else:\n run_rule(read_data(join(write_prefix,(\"%s_Remain\"%rule_dissum_file)%(rule_index-1)),dtype={\"HADM_ID\":str}),rule_index)\n \n notes_discharge_df = read_data(join(write_prefix,(\"%s_All\"%rule_dissum_file)%rule_index),dtype={\"HADM_ID\":str})\n rule_only_df, remain_df= [x for _, x in notes_discharge_df.groupby(notes_discharge_df['TITLE'].isna())]\n print(\"Rule %d :\\nrule only df row num %d \\n episode num %d \\n\\nremain df row num %d \\n episode num %d \\n\\n\"%(\n rule_index,len(rule_only_df),len(rule_only_df['HADM_ID'].unique()),len(remain_df),len(remain_df['HADM_ID'].unique())))\n \n write2file(rule_only_df,join(write_prefix,(\"%s_Only\"%rule_dissum_file)%(rule_index)))\n write2file(remain_df,join(write_prefix,(\"%s_Remain\"%rule_dissum_file)%(rule_index)))\n\n\n\"\"\"\n test code: remain, 4 rules\n\"\"\"\ndef main():\n for rule_index in range(0,4):\n # notes_discharge_df=read_data(join(write_prefix,(\"%s_Remain\"%rule_dissum_file)%(rule_index-1)),dtype={\"HADM_ID\":str})\n # notes_discharge_df_rule1 = run_rule(notes_discharge_df, rule_index=1)\n get_rule_result(rule_index)\n\n# main()\n\n\n\"\"\"\n test added columns\n\"\"\"\n# notes_discharge_df=read_data(join(dis_sum_prefix,\"Discharge summary_All\"),dtype={\"HADM_ID\":str})\n# # print(len(notes_discharge_df))\n# notes_discharge_df.head()\n# notes_df=notes_discharge_df\n# # test_df = notes_df[notes_df['HADM_ID']==\"196600\"]\n# test_df = notes_df.head()\n\n# # test_df_text = test_df.loc[36180,\"TEXT\"]\n# # print(len(test_df))\n# # print(extract_sections(test_df.loc[36180,\"TEXT\"],rule_index=2))\n# run_rule(test_df,rule_index=2)\n\n\n\n\"\"\"\ntt\n\"\"\"\n# notes_discharge_df.head()\n# notes_df=notes_discharge_df\n# test_df = notes_df[notes_df['HADM_ID']==\"137810\"]\n# test_df_text = test_df.loc[36180,\"TEXT\"]\n# titles = extract_sections(test_df_text,3)\n# print(len(titles))\n\n\n\"\"\"\n test code: one text, rule 0\n\"\"\"\n# notes_discharge_df=read_data(join(dis_sum_prefix,\"Discharge summary_All\"),dtype={\"HADM_ID\":str})\n# print(len(notes_discharge_df))\n# notes_discharge_df.head()\n# notes_df=notes_discharge_df\n# test_df = notes_df[notes_df['HADM_ID']==\"196600\"]\n# test_df_text = test_df.loc[36180,\"TEXT\"]\n# titles = extract_sections(test_df_text,3)\n# print(len(titles))\n","sub_path":"Scripts/Data_Process_Server/S2/dis_sum_extraction.py","file_name":"dis_sum_extraction.py","file_ext":"py","file_size_in_byte":11088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"601400143","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport cStringIO\nimport sys\nimport xml\nimport base64\nimport urllib2\nimport xml.dom.minidom\nimport pyfits\nimport numpy as np\nimport aplpy\nimport time\n\n\n# grab MOS xml definition from WM given account and barcode\ndef get_slitmask_xml(username, password, barcode):\n \"\"\"\n Return the slit mask XML as a DOM document.\n \"\"\"\n encoded_username = base64.encodestring(username).strip()\n encoded_password = base64.encodestring(password).strip()\n\n mask_url = 'https://www.salt.ac.za/wm/downloads/SlitmaskXml.php'\n\n # We pass the parameters in a GET request.\n url = mask_url + '?username=%s&password=%s&Barcode=%s' % (encoded_username,\n encoded_password,\n barcode)\n response = urllib2.urlopen(url)\n dom = xml.dom.minidom.parse(response)\n\n # Handle the case that the request wasn't successful.\n if dom.documentElement.tagName == 'Invalid':\n raise Exception('You are not allowed to view the slit mask XML.')\n\n return dom\n\n\n# grab 10' x 10' image from STScI server and pull it into pyfits\ndef get_dss(imserver, ra, dec):\n url = \"http://archive.stsci.edu/cgi-bin/dss_search?v=%s&r=%f&d=%f&e=J2000&h=10.0&w=10.0&f=fits&c=none\" % (imserver, ra, dec)\n fitsData = cStringIO.StringIO()\n data = urllib2.urlopen(url).read()\n fitsData.write(data)\n fitsData.seek(0)\n return pyfits.open(fitsData)\n\n\n# grab uploaded base64-encoded FITS\ndef get_fits(b64str):\n fitsData = cStringIO.StringIO()\n fitsData.write(base64.b64decode(b64str))\n fitsData.seek(0)\n return pyfits.open(fitsData)\n\n\n# draw a line centered at ra,dec of a given length at a given angle\n# theta,ra,dec => deg; length => arcmin\ndef draw_line(plot, theta, length, ra, dec, color='b', linewidth=1, alpha=0.7):\n theta = theta * np.pi / 180.0\n length = length / 2.0\n dx = np.sin(theta) * length / (np.cos(dec * np.pi / 180.0) * 60.0)\n dy = np.cos(theta) * length / 60.0\n coords = np.array([[ra + dx, ra - dx], [dec + dy, dec - dy]])\n plot.show_lines([coords], color=color, linewidth=linewidth, alpha=alpha)\n return plot\n\n\n# draw a box centered at ra,dec of a given length and width at a given angle\n# theta,ra,dec => deg; width, height => arcmin\ndef draw_box(plot, theta, width, length, ra, dec,\n color='b', linewidth=1, alpha=0.7):\n theta = theta * np.pi / 180.0\n length = length / 2.0\n width = width / 2.0\n # position of line centers\n ra_l = ra + np.cos(theta) * width / (np.cos(dec * np.pi / 180.0) * 60.0)\n ra_r = ra - np.cos(theta) * width / (np.cos(dec * np.pi / 180.0) * 60.0)\n dec_l = dec - np.sin(theta) * width / 60.0\n dec_r = dec + np.sin(theta) * width / 60.0\n\n dx = np.sin(theta) * length / (np.cos(dec * np.pi / 180.0) * 60.0)\n dy = np.cos(theta) * length / 60.0\n coords = np.array([[ra_l, ra_l + dx, ra_r + dx,\n ra_r - dx, ra_l - dx, ra_l],\n [dec_l, dec_l + dy, dec_r + dy,\n dec_r - dy, dec_l - dy, dec_l]])\n plot.show_lines([coords], color=color, linewidth=linewidth, alpha=alpha)\n return plot\n\n\n# draw slits and reference boxes for MOS\ndef mos_plot(plot, slits, refs, pa):\n # draw the slits\n for slit in slits:\n tilt = 0.0\n if 'tilt' in slit.attributes:\n tilt = float(slit.attributes['tilt'].value)\n draw_box(plot,\n pa + tilt,\n float(slit.attributes['width'].value) / 60.0,\n float(slit.attributes['length'].value) / 60.0,\n float(slit.attributes['xce'].value),\n float(slit.attributes['yce'].value),\n color='r')\n # make bigger boxes around the reference objects\n for ref in refs:\n draw_box(plot,\n pa,\n 5.0 / 60.0,\n 5.0 / 60.0,\n float(ref.attributes['xce'].value),\n float(ref.attributes['yce'].value),\n color=(1, 1, 0),\n linewidth=2)\n return plot\n\n\n# read in an ephem file for non-siderial targets\n# the start and end times to be plotted are required\ndef read_ephem(ephemfilename, startTime, endTime):\n ephData = np.loadtxt(ephemfilename,\n dtype=({'names': ('times',\n 'RAhr',\n 'RAmin',\n 'RAsec',\n 'Decdeg',\n 'Decmin',\n 'Decsec',\n 'RaRate',\n 'DecRate'),\n 'formats': ('S100',\n np.float,\n np.float,\n np.float,\n np.float,\n np.float,\n np.float,\n np.float,\n np.float)}),\n delimiter=' ',\n skiprows=2)\n\n times = []\n for i in ephData:\n times.append(time.mktime(time.strptime(i['times'],\n '%Y-%m-%dT%H:%M:%S')))\n\n times = np.array(times)\n\n req_startTime = time.mktime(time.strptime(startTime,\n '%Y-%m-%dT%H:%M:%S'))\n req_endTime = time.mktime(time.strptime(endTime,\n '%Y-%m-%dT%H:%M:%S'))\n # get back the indeces where the time conditions are met\n req_i = np.where((times >= req_startTime) & (times <= req_endTime))\n\n # create array with the RA and DEC in degrees from the time restriction\n RA = ephData[req_i]['RAhr'] * 15.0 +\\\n ephData[req_i]['RAmin'] / 60.0 +\\\n ephData[req_i]['RAsec'] / 3600.0\n DEC = ephData[req_i]['Decdeg'] +\\\n ephData[req_i]['Decmin'] / 60.0 +\\\n ephData[req_i]['Decsec'] / 3600.0\n\n # calculate the mean RA/DEC, this will be the centre of the finder chart\n mean_RA = np.mean(RA)\n mean_DEC = np.mean(DEC)\n\n return mean_RA, mean_DEC, RA, DEC\n\n\n# plot the object positions as a function of time from the ephem file\ndef plot_ephem(plot, RA_pos, DEC_pos, startTime, endTime):\n # plot the object positions\n plot.show_markers(RA_pos,\n DEC_pos,\n layer='object_path_markers',\n edgecolor='red',\n facecolor='none',\n marker='o',\n s=12,\n linestyle='solid')\n\n # plot the lines that connect the markers\n lv = np.vstack([RA_pos, DEC_pos])\n plot.show_lines([lv],\n layer='object_path_lines',\n edgecolor='red',\n linestyle='solid')\n\n dra = RA_pos[-1] - RA_pos[-2]\n ddec = DEC_pos[-1] - DEC_pos[-2]\n\n # plot the arrow at the start time to show direction\n plot.show_arrows(RA_pos[0] - 1.5 * dra,\n DEC_pos[0] - 1.5 * ddec,\n dra,\n ddec,\n layer='direction_begin',\n edgecolor='r',\n facecolor='None',\n width=3,\n head_width=8,\n head_length=6)\n\n # plot the arrow at the end time to show the direction\n plot.show_arrows(RA_pos[-1] + dra / 2.0,\n DEC_pos[-1] + ddec / 2.0,\n dra,\n ddec,\n layer='direction_end',\n edgecolor='r',\n facecolor='None',\n width=3,\n head_width=8,\n head_length=6)\n\n # add the start time label\n plot.add_label(RA_pos[0] - 0.002,\n DEC_pos[0],\n startTime.replace('T', ' '),\n relative=False,\n size='8',\n horizontalalignment='left',\n color=(0, 0, 1))\n\n # add the end time label\n plot.add_label(RA_pos[-1] - 0.002,\n DEC_pos[-1],\n endTime.replace('T', ' '),\n relative=False,\n size='8',\n horizontalalignment='left',\n color=(0, 0, 1))\n\n return plot\n\n\n# set up basic plot\ndef init_plot(hdu, imserver, title, ra, dec, pa):\n servname = {}\n servname['poss2ukstu_red'] = \"POSS2/UKSTU Red\"\n servname['poss2ukstu_blue'] = \"POSS2/UKSTU Blue\"\n servname['poss2ukstu_ir'] = \"POSS2/UKSTU IR\"\n servname['poss1_blue'] = \"POSS1 Blue\"\n servname['poss1_red'] = \"POSS1 Red\"\n\n out = sys.stdout\n sys.stdout = open(\"/dev/null\", 'w')\n plot = aplpy.FITSFigure(hdu)\n plot.show_grayscale()\n plot.set_theme('publication')\n sys.stdout = out\n\n plot.add_label(0.95,\n -0.05,\n \"PA = %.1f\" % pa,\n relative=True,\n style='italic',\n weight='bold')\n\n plot.add_label(0.5,\n 1.03,\n title,\n relative=True,\n style='italic',\n weight='bold',\n size='large')\n plot.add_label(-0.05,\n -0.05,\n \"%s\" % servname[imserver],\n relative=True,\n style='italic',\n weight='bold')\n\n plot.add_grid()\n plot.grid.set_alpha(0.2)\n plot.grid.set_color('b')\n\n plot.show_circles([ra, ra],\n [dec, dec],\n [4.0 / 60.0, 5.0 / 60.0],\n edgecolor='g')\n plot.add_label(0.79,\n 0.79,\n \"RSS\",\n relative=True,\n style='italic',\n weight='bold',\n size='large',\n horizontalalignment='left',\n color=(0, 0, 1))\n plot.add_label(0.86,\n 0.86,\n \"SCAM\",\n relative=True,\n style='italic',\n weight='bold',\n size='large',\n horizontalalignment='left',\n color=(0, 0, 1))\n plot.add_label(ra,\n dec + 4.8 / 60.0,\n \"N\",\n style='italic',\n weight='bold',\n size='large',\n color=(0, 0.5, 1))\n plot.add_label(ra + 4.8 / (np.abs(np.cos(dec * np.pi / 180.0)) * 60),\n dec,\n \"E\",\n style='italic',\n weight='bold',\n size='large',\n horizontalalignment='right',\n color=(0, 0.5, 1))\n plot = draw_line(plot, 0, 8, ra, dec, color='g', linewidth=0.5, alpha=1.0)\n plot = draw_line(plot, 90, 8, ra, dec, color='g', linewidth=0.5, alpha=1.0)\n return plot\n","sub_path":"finder_chart.py","file_name":"finder_chart.py","file_ext":"py","file_size_in_byte":11312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"136790599","text":"\"\"\"\npython3 ~/PycharmProjects/Rekkari/video2images.py \"Rekisteri_4_short.mp4\" 0 2700 25\n\nFunctions related to read and write videos and images in opencv\nfilename firstFrame lastFrame stride\n\"\"\"\n\n\nimport cv2\nimport numpy as np\nimport sys\nimport time\n\n\nclass VideoIO():\n def __init__(self, videoFileName=None, fps=24, first_frame=0, last_frame=None, stride=1, colorChange=cv2.COLOR_RGB2GRAY):\n\n self.fps = fps\n self.videoFileName = videoFileName\n #self.cap = cv2.VideoCapture(*args)\n self.first_frame = first_frame\n self.last_frame = last_frame\n self.stride = stride\n self.colorChange=colorChange\n self.n_frames=None\n self.frames=None\n print (\"INIT OK\")\n\n def changeColor(self, imageIn):\n if self.colorChange=='mok.COLOR_YUV2GRAY_420':\n N=imageIn[0]*imageIn[1]\n print(\"N\",N, N.shape)\n sys.exit()\n else:\n return cv2.cvtColor(imageIn, self.colorChange)\n\n def readVideoFrames(self, videoFileName=None):\n \"\"\" read in frames and convert to desired format\"\"\"\n if videoFileName is None:\n videoFileName = self.videoFileName\n if self.first_frame is None:\n first_frame = 0\n else:\n first_frame = self.first_frame\n last_frame = self.last_frame\n\n print (\"starting reading: filename\", videoFileName)\n cap = cv2.VideoCapture(videoFileName)\n while not cap.isOpened():\n cap = cv2.VideoCapture(videoFileName)\n cv2.waitKey(1000)\n print(\"Wait for the header\")\n\n print(\"self:\", last_frame)\n if last_frame is None:\n last_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n print(\"LAST NR\", )\n self.frames = []\n\n cap.set(cv2.CAP_PROP_POS_FRAMES, first_frame)\n count = self.first_frame\n while True:\n flag, frame = cap.read()\n print(\"FRAME:\", frame.shape)\n pos_frame = cap.get(cv2.CAP_PROP_POS_FRAMES)\n if flag:\n gray = self.changeColor(imageIn=frame)\n #gray = cv2.cvtColor(frame, self.colorChange)\n if count >= self.first_frame + stride:\n self.frames.append(gray)\n count=self.first_frame\n print (str(pos_frame)+\" frames\")\n else:\n # The next frame is not ready, so we try to read it again\n cap.set(cv2.CAP_PROP_POS_FRAMES, pos_frame-1)\n print(\"frame is not ready\")\n # It is better to wait for a while for next frame to be ready\n cv2.waitKey(1000)\n\n count = count + 1\n if cap.get(cv2.CAP_PROP_POS_FRAMES) == last_frame+1:\n # If the number of captured frames is equal to the total number of frames,\n # we stop\n break\n\n\n\n self.n_frames=last_frame-first_frame+1\n cap.release()\n print(\"finished reading\")\n\n def setColorChange(self, colorChange):\n self.colorChange = colorChange\n\n\n def writeAllImages(self, format='jpg', prefix=''):\n \"\"\"Write given frames to disk as images one-by-one\"\"\"\n\n for i, frame in enumerate(self.frames):\n cv2.imwrite(prefix+'.'+str(i+self.first_frame)+'.'+format, frame)\n\n\n\n def backgroundSubtractorMOG2(self):\n \"\"\"\n http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/ \\\n py_video/py_bg_subtraction/py_bg_subtraction.html#background-subtraction\n \"\"\"\n\n fgbg = cv2.createBackgroundSubtractorMOG2()\n\n for frame in self.frames:\n fgmask = fgbg.apply(frame)\n #self.toContours(fgmask, frame)\n cv2.imshow('frame',fgmask)\n while True:\n k = cv2.waitKey(30) & 0xff\n if k == 27:\n break\n\n cv2.destroyAllWindows()\n\n\n def toContours(self, mask, frame):\n \"\"\"\n after background subtarctorm blur edges and get contours\n \"\"\"\n sys.path.append('/home/mka/PycharmProjects/')\n from Image2Letters.initialCharacterRegions import InitialCharacterRegions\n kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))\n kernel2=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10))\n mask = cv2.morphologyEx(mask,cv2.MORPH_ERODE, kernel)\n mask = cv2.morphologyEx(mask,cv2.MORPH_DILATE,kernel2)\n contours = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]\n regions=[]\n for contour in contours:\n regions.append(cv2.boundingRect(contour))\n dummy = InitialCharacterRegions()\n dummy.showAllRectangles(clone=frame.copy(), regions=regions)\n\n\n def backgroundSubtractorKNN(self):\n \"\"\"\n http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/ \\\n py_video/py_bg_subtraction/py_bg_subtraction.html#background-subtraction\n \"\"\"\n\n fgbg = cv2.createBackgroundSubtractorKNN(detectShadows=False)\n\n for frame in self.frames:\n #fgmask = cv2.bitwise_not(fgbg.apply(frame))\n fgmask = fgbg.apply(frame)\n self.getContourRectangles(fgmask, frame)\n cv2.imshow('frame',frame)\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n cv2.destroyAllWindows()\n\n\n def camShift(self, initFrame, initRectangle):\n\n # setup initial location of window\n # x,y,width,height\n (r,h,c,w) = initRectangle\n track_window = initRectangle\n\n # set up the ROI for tracking\n roi = self.frames[initFrame][r:r+h, c:c+w]\n #hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\n #mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))\n #roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])\n roi_hist = cv2.calcHist(roi,[0], mask=None, histSize=[255],ranges=[0,255])\n #cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)\n\n # Setup the termination criteria, either 10 iteration or move by atleast 1 pt\n term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )\n\n for frame in self.frames[initFrame:]:\n\n #hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n #dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)\n dst = cv2.calcBackProject(roi,[0],roi_hist,[0,255],1)\n\n # apply camshift to get the new location\n ret, track_window = cv2.CamShift(dst, track_window, term_crit)\n\n # Draw it on image\n pts = cv2.boxPoints(ret)\n pts = np.int0(pts)\n img2 = cv2.polylines(frame,[pts],True, 255,5)\n cv2.imshow('img2',img2)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n time.sleep(0.1)\n\n\n\n def backgroundSubtractorSimple(self, minArea = None):\n \"\"\"assume constant background\"\"\"\n\n\n background = self.frames[0]\n\n for frame in self.frames:\n frameDelta = cv2.absdiff(background, frame)\n #thresh = cv2.adaptiveThreshold(frameDelta, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \\\n # cv2.THRESH_BINARY, 11, 2)\n thresh = cv2.threshold(frameDelta, 30, 255, cv2.THRESH_BINARY)[1]\n # fill holes in thresholded image\n thresh = cv2.dilate(thresh, None, iterations=2)\n self.getContourRectangles(thresh, frame)\n\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n time.sleep(0.1)\n #while True:\n # k = cv2.waitKey(30) & 0xff\n # if k == 27:\n # break\n\n cv2.destroyAllWindows()\n\n def getContourRectangles(self, thresh, frame, minArea=None):\n\n # assume a car is at least 1% of the image area\n if minArea is None:\n minArea = self.frames[0].shape[0] * self.frames[0].shape[1] * 0.01\n\n contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]\n\n for contour in contours:\n if cv2.contourArea(contour) < minArea:\n continue\n (x, y, w, h) = cv2.boundingRect(contour)\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n\n\n\n\n\nif __name__ == '__main__':\n import sys\n videoFileName=sys.argv[1]\n first_frame=int(sys.argv[2])\n last_frame=int(sys.argv[3])\n stride=int(sys.argv[4])\n \n video2images = VideoIO(videoFileName=videoFileName,\n first_frame=first_frame,\n last_frame=last_frame,\n stride=stride,\n colorChange=cv2.COLOR_RGB2GRAY)\n video2images.readVideoFrames(videoFileName=videoFileName)\n video2images.camShift(0, (1000,650,50,20))\n #video2images.backgroundSubtractorSimple()\n #video2images.backgroundSubtractorKNN()\n #video2images.backgroundSubtractorMOG2()\n #video2images.writeAllImages(prefix=videoFileName)\n\n\n\n\n","sub_path":"video2images.py","file_name":"video2images.py","file_ext":"py","file_size_in_byte":9126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"603624554","text":"import numpy as np\nimport pandas as pd\nfrom time import time\nfrom HybridCRO import *\nfrom utilities import *\n\nt1 = time()\nsum_scores = [0, 0, 0]\nruns = 30\n\nfor seed in range(runs):\n data = pd.read_csv('breastcancer.txt', sep=',', header=None)\n data = data.sample(frac=1, random_state=seed).reset_index(drop=True)\n\n y_data = data[0]\n y_data = y_data.values\n\n x_data = data.drop([0], axis=1)\n x_data = x_data.values\n x_data = normalize(x_data)\n\n clusters = 2\n\n kbox = KMeans(n_clusters=clusters, max_iter=60, random_state=seed)\n kbox.fit(x_data)\n centroids = np.array(kbox.cluster_centers_).copy()\n\n labels = []\n for y in y_data:\n if y == 'M':\n labels.append(0)\n elif y == 'B':\n labels.append(1)\n\n labels = np.array(labels)\n\n scores = metrics(x_data, centroids, labels)\n\n sum_scores[0] += scores[0]\n sum_scores[1] += scores[1]\n sum_scores[2] += scores[2]\n\nprint(f'Accuracy =\\t {sum_scores[0] / runs}')\nprint(f'F-measure =\\t {sum_scores[1] / runs}')\nprint(f'SSE =\\t {sum_scores[2] / runs}')\n\nt2 = time()\nprint(t2 - t1)\n","sub_path":"Main Tests/Wisconsin breastcancer/mycode_cancer_KMeans.py","file_name":"mycode_cancer_KMeans.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"363420456","text":"import os\nimport bpy\nimport json\nfrom morse.builder.data import MORSE_COMPONENTS\n\n\"\"\"\ncomponents-dictionary-convention:\n{\n 'component-directory': {\n '.blend-file': ['main-object-name', 'child1-name', ...]\n }\n}\n\"\"\"\nclass ComponentsData(object):\n \"\"\" Build the components-dictionary (*/*.blend/Object/*)\n http://www.blender.org/documentation/blender_python_api_2_57_release/bpy.types.BlendDataLibraries.html#bpy.types.BlendDataLibraries.load\n \"\"\"\n def __init__(self, path):\n self.path = path\n self._data = {}\n self._update()\n def _update(self):\n for category in os.listdir(self.path):\n pathc = os.path.join(self.path, category)\n if os.path.isdir(pathc):\n self._data[category] = {}\n for blend in os.listdir(pathc):\n pathb = os.path.join(pathc, blend)\n if os.path.isfile(pathb) & blend.endswith('.blend'):\n self._data[category][blend[:-6]] = self.objects(pathb)\n def objects(self, blend):\n \"\"\" bpy.data.libraries.load(path) is 2.57 OK (but 2.56 NOK!)\n \"\"\"\n objects = []\n with bpy.data.libraries.load(blend) as (src, _):\n objects = src.objects\n return objects\n def dump(self, dest):\n with open(dest, 'w') as f:\n f.write(\"# generated by morse.builder.generator\\n\")\n f.write(\"MORSE_MIDDLEWARE_DICT = \")\n f.write( json.dumps(self.data, indent=1) )\n @property\n def data(self):\n return self._data\n\ndef generate():\n import tempfile\n import morse.builder.data\n components = ComponentsData(morse.builder.data.MORSE_COMPONENTS)\n fd, path = tempfile.mkstemp(prefix=\"components-\", suffix=\".py\")\n try:\n components.dump(path)\n finally:\n os.close(fd)\n print(\"path: %s\"%path)\n\n\"\"\"\n# write the data in a temp file\nimport sys\nsys.path.append(\"/usr/local/lib/python3.1/dist-packages\")\nimport morse.builder.generator\nmorse.builder.generator.generate()\n\"\"\"\n\n","sub_path":"src/morse/builder/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"645463798","text":"\n# можно использовать любые разделители (,;/) впермежку\nstr_out = ''\nlist1 = input('Введите элементы списка через запятую (или ;, или /):').replace('/',',').replace(';',',').split(',')\nset1 = set(list1)\nfor element in set1:\n if list1.count(element) == 1:\n str_out += element+','\nprint(str_out[:-1])\n\n\n","sub_path":"2seq.py","file_name":"2seq.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"55893755","text":"from present import * #ここで使用する暗号器を指定する\nfrom Crypto.Random import get_random_bytes#ランダム変数\n\nclass Analysis_model():\n def __init__(self,gpu_num,TRAIN_NUM,TEST_NUM,ROUND):\n #変数などの定義\n print(\"Let's do a Learning----------------!\")#Greeting\n self.gpu_num=gpu_num#使用するGPUナンバー\n self.x_train=0#入力トレーニングデータの初期化\n self.x_test=0#入力テストデータの初期化\n self.y_train=0#教師トレーニングデータの初期化\n self.y_test=0#教師テストデータの初期化\n \n self.TRAIN_NUM=TRAIN_NUM#トレーニングデータ数\n self.TEST_NUM=TEST_NUM#テストデータ数\n self.ROUND=ROUND#ラウンド数\n \n #self.x_length=len(self.x_train[0])#トレーニングデータのブロック長\n #self.y_length=len(self.y_train[0])#テストデータのブロック長\n\n self.learning_rate=0.001#学習率\n self.loss_func='mse'#損失関数\n\n self.batch_size=200#バッチサイズ\n self.epochsize=300#エポック数\n self.valisplit=0.2#トレーニング・検証データの分割(テストデータの分割ではない)\n \n #アーリーストッピング手法におけるパラメータ\n self.es_monitor='val_loss'#監視するパラメータ\n self.es_patience=10#es_monitorがこの回数以上改善がなかったら,学習を打ち切る\n \n #-----------------------暗号器オブジェクトの作成-------------\n self.cp=CiphMachine(self.ROUND)#暗号器インスタンス\n self.cp.test()#テストを行う\n\n def data_gen_roundkey(self):\n #-----------------鍵スケジュール解析 入力データ:最終段段鍵--------\n #-----------------データ生成---------------------------------------\n #------------------データをテキストファイルに書き出す---------------\n import os\n path = \"./Datas\"\n os.makedirs(\"./Datas\", exist_ok=True)#-------結果保存用--------\n\n file_x_train=open(\"./Datas/x_train.txt\",\"w\")\n file_y_train=open(\"./Datas/y_train.txt\",\"w\")\n file_x_test=open(\"./Datas/x_test.txt\",\"w\")\n file_y_test=open(\"./Datas/y_test.txt\",\"w\")\n\n SUM=self.TRAIN_NUM+self.TEST_NUM\n for i in range(SUM): \n cp=CiphMachine(self.ROUND)\n round_key=cp.last_round_key#段鍵\n mas_key=cp.mas_key#秘密鍵\n\n if(i>j)&1))\n file_y_train.write(\" \") \n file_y_train.write(\"\\n\")\n for j in range(cp.block_len):\n file_x_train.write(str((round_key>>j)&1))\n file_x_train.write(\" \") \n file_x_train.write(\"\\n\")\n else:\n for j in range(cp.key_len):\n file_y_test.write(str((mas_key>>j)&1))\n file_y_test.write(\" \") \n file_y_test.write(\"\\n\")\n for j in range(cp.block_len):\n file_x_test.write(str((round_key>>j)&1))\n file_x_test.write(\" \") \n file_x_test.write(\"\\n\")\n\n file_x_train.close()\n file_y_train.close()\n file_x_test.close()\n file_y_test.close()\n print(\"Completed Data_Generating\")#データの生成完了メッセージ\n \n #---------------------データの配列への変換------------------------\n import numpy as np\n self.x_train=np.loadtxt(\"./Datas/x_train.txt\")\n self.y_train=np.loadtxt(\"./Datas/y_train.txt\")\n self.x_test=np.loadtxt(\"./Datas/x_test.txt\")\n self.y_test=np.loadtxt(\"./Datas/y_test.txt\")\n print(\"Completed Data_Trainslation\")#リストへの変換の完了メッセージ\n\n def data_gen_keyreg(self):\n #-----------------鍵スケジュール解析 入力データ:最終段鍵スケジュール内部状態 --------\n #-----------------データ生成---------------------------------------\n #------------------データをテキストファイルに書き出す---------------\n import os\n path = \"./Datas\"\n os.makedirs(\"./Datas\", exist_ok=True)#-------結果保存用--------\n\n file_x_train=open(\"./Datas/x_train.txt\",\"w\")\n file_y_train=open(\"./Datas/y_train.txt\",\"w\")\n file_x_test=open(\"./Datas/x_test.txt\",\"w\")\n file_y_test=open(\"./Datas/y_test.txt\",\"w\")\n\n SUM=self.TRAIN_NUM+self.TEST_NUM\n for i in range(SUM): \n cp=CiphMachine(self.ROUND)\n key_reg=cp.last_round_key_reg#キーレジスタ\n mas_key=cp.mas_key#秘密鍵\n\n if(i>j)&1))\n file_y_train.write(\" \") \n file_y_train.write(\"\\n\")\n for j in range(cp.key_len):\n file_x_train.write(str((key_reg>>j)&1))\n file_x_train.write(\" \") \n file_x_train.write(\"\\n\")\n else:\n for j in range(cp.key_len):\n file_y_test.write(str((mas_key>>j)&1))\n file_y_test.write(\" \") \n file_y_test.write(\"\\n\")\n for j in range(cp.key_len):\n file_x_test.write(str((key_reg>>j)&1))\n file_x_test.write(\" \") \n file_x_test.write(\"\\n\")\n\n file_x_train.close()\n file_y_train.close()\n file_x_test.close()\n file_y_test.close()\n print(\"Completed Data_Generating\")#データの生成完了メッセージ\n \n #---------------------データの配列への変換------------------------\n import numpy as np\n self.x_train=np.loadtxt(\"./Datas/x_train.txt\")\n self.y_train=np.loadtxt(\"./Datas/y_train.txt\")\n self.x_test=np.loadtxt(\"./Datas/x_test.txt\")\n self.y_test=np.loadtxt(\"./Datas/y_test.txt\")\n print(\"Completed Data_Trainslation\")#リストへの変換の完了メッセージ\n \n def learning(self):\n #鍵スケジュール解析の学習モデル&実行\n import numpy as np\n x_train=self.x_train\n y_train=self.y_train\n x_test=self.x_test\n y_test=self.y_test\n \n acc_list=[]#正答率を格納するリスト\n \n print(\"Model for predicting Plain text.\")#Greeting\n \n #-----------------------使用するGPU指定------------------------\n import os\n import tensorflow as tf\n # Specify which GPU(s) to use\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = self.gpu_num # Or 2, 3, etc. other than 0\n\n # On CPU/GPU placement\n config = tf.compat.v1.ConfigProto(allow_soft_placement=True, log_device_placement=True)\n config.gpu_options.allow_growth = True\n tf.compat.v1.Session(config=config)\n # Note that ConfigProto disappeared in TF-2.0\n \n for bit_posi in range(len(y_train[0])):\n #各ビットごとに正答率を求める\n #y_trainのbit_posi列だけを抜き出す\n y_train_column=y_train.T[bit_posi]\n y_test_column=y_test.T[bit_posi]\n \n for trial in range(10):\n #学習が成功するまで学習を繰り返す ただし上限あり (失敗は val_acc ≒ 0.5 とする)\n #----------------------モデル作成-----------------------\n from tensorflow import keras\n model = keras.Sequential()\n\n #中間層の追加\n from tensorflow.python.keras.layers import Dense\n\n model.add(\n Dense(\n units=32,#パーセプトロン数\n input_shape=(len(x_train[0]) ,),#入力層だけ入力のパーセプトロン数を指定\n activation=\"relu\",#活性化関数\n kernel_initializer=keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)#パラメータ初期化\n )\n )\n model.add(\n Dense(\n units=16,#パーセプトロン数\n activation=\"relu\",#活性化関数\n kernel_initializer=keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)#パラメータ初期化\n )\n )\n model.add(\n Dense(\n units=8,#パーセプトロン数\n activation=\"relu\",#活性化関数\n kernel_initializer=keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)#パラメータ初期化\n )\n )\n #出力層の追加\n model.add(\n Dense(\n units=1,#パーセプトロン数\n #活性化関数なし\n kernel_initializer=keras.initializers.RandomNormal(mean=0.0, stddev=0.05, seed=None)#パラメータ初期化\n )\n )\n\n #---------------------------------学習-------------------------------\n # Early-stopping \n early_stopping = keras.callbacks.EarlyStopping(monitor=self.es_monitor, min_delta=0, patience=self.es_patience, verbose=0, mode='auto')#この形式で書かないと怒られる\n\n #オプティマイザー(最適化関数)の指定\n opt = keras.optimizers.Adam(\n learning_rate=self.learning_rate#学習率の指定\n )\n\n #モデルのコンパイル\n model.compile(\n optimizer=opt,#上記の最適化関数\n loss=self.loss_func,#損失関数\n metrics=['accuracy']\n )\n\n #計算開始\n history_adam=model.fit(\n x_train,\n y_train_column,\n batch_size=self.batch_size,\n epochs=self.epochsize,\n validation_split=self.valisplit,\n callbacks=[early_stopping]#アーリーストッピング\n )\n\n\n #---------------------------------------テストフェーズ---------------------\n #テストフェーズ時の予測値\n predict=model.predict(x_test)#予測値は0~1の実数で表現される\n predict=(predict>0.5)*1#それを0or1で表現する\n answer=(predict.T==y_test_column)*1#教師データy_testと答え合わせ 正解なら1 不正解なら0\n #正答率 \n acc=np.sum(answer)/(self.TEST_NUM)\n\n loss_value = history_adam.history[\"val_loss\"][len(history_adam.history[\"val_loss\"]) -1]#val_lossの最終値\n if(loss_value<0.45):#学習が成功したならば \n print(\"end of %dth bit learning\" % bit_posi)\n print(\"Accuracy is below\")\n #print(acc)#リストで表示\n print(acc)\n print(\"\")#ただの改行\n acc_list.append(acc)\n break\n else:\n if(trial<9):\n print(\"Failure of Learning, Start of Re_Learning\")\n \n #各ビットの正答率の平均\n print(\"Accuracy is below\")\n #print(acc_list)#リストで表示\n for acc_i in acc_list:\n print(str(acc_i)+\",\",end=\"\")#リストaccの要素をカンマを付けながら表示\n print(\"\\n\")\n \n #正答率の平均\n print(\"Average Accuracy is below\")\n print(sum(acc_list)/len(acc_list))\n print(\"\")","sub_path":"analysis_model_keysche.py","file_name":"analysis_model_keysche.py","file_ext":"py","file_size_in_byte":12156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"482386525","text":"from typing import Optional\n\nimport databases\nimport pytest\nimport sqlalchemy\n\nimport ormar\nfrom tests.settings import DATABASE_URL\n\ndatabase = databases.Database(DATABASE_URL)\nmetadata = sqlalchemy.MetaData()\n\n\nclass BaseMeta(ormar.ModelMeta):\n metadata = metadata\n database = database\n\n\nclass Author(ormar.Model):\n class Meta(BaseMeta):\n tablename = \"authors\"\n\n id: int = ormar.Integer(primary_key=True)\n name: str = ormar.String(max_length=100)\n\n\nclass Book(ormar.Model):\n class Meta(BaseMeta):\n tablename = \"books\"\n\n id: int = ormar.Integer(primary_key=True)\n author: Optional[Author] = ormar.ForeignKey(Author)\n title: str = ormar.String(max_length=100)\n year: int = ormar.Integer(nullable=True)\n\n\n@pytest.fixture(autouse=True, scope=\"module\")\ndef create_test_database():\n engine = sqlalchemy.create_engine(DATABASE_URL)\n metadata.drop_all(engine)\n metadata.create_all(engine)\n yield\n metadata.drop_all(engine)\n\n\n@pytest.mark.asyncio\nasync def test_is_null():\n async with database:\n tolkien = await Author.objects.create(name=\"J.R.R. Tolkien\")\n await Book.objects.create(author=tolkien, title=\"The Hobbit\")\n await Book.objects.create(\n author=tolkien, title=\"The Lord of the Rings\", year=1955\n )\n await Book.objects.create(author=tolkien, title=\"The Silmarillion\", year=1977)\n\n books = await Book.objects.all(year__isnull=True)\n assert len(books) == 1\n assert books[0].year is None\n assert books[0].title == \"The Hobbit\"\n\n books = await Book.objects.all(year__isnull=False)\n assert len(books) == 2\n\n tolkien = await Author.objects.select_related(\"books\").get(\n books__year__isnull=True\n )\n assert len(tolkien.books) == 1\n assert tolkien.books[0].year is None\n assert tolkien.books[0].title == \"The Hobbit\"\n\n tolkien = (\n await Author.objects.select_related(\"books\")\n .paginate(1, 10)\n .get(books__year__isnull=True)\n )\n assert len(tolkien.books) == 1\n assert tolkien.books[0].year is None\n assert tolkien.books[0].title == \"The Hobbit\"\n\n tolkien = await Author.objects.select_related(\"books\").get(\n books__year__isnull=False\n )\n assert len(tolkien.books) == 2\n assert tolkien.books[0].year == 1955\n assert tolkien.books[0].title == \"The Lord of the Rings\"\n","sub_path":"tests/test_queries/test_isnull_filter.py","file_name":"test_isnull_filter.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"233110561","text":"###########\n# IMPORTS #\n###########\n\nfrom heapq import heappop as heap_pop\nfrom heapq import nsmallest as heap_read\nfrom heapq import nlargest\n\nfrom terminaltables import AsciiTable\n\nimport settings\nfrom settings import NODES\nimport log\n\n#########\n# CLASS #\n#########\n\nclass Scheduler:\n time = 0\n time_previous = 0\n events = []\n\n def __str__(self):\n lines = [\"\",\n Scheduler._get_heap_table(),\n \"\",\n Scheduler._get_status_table()]\n return \"\\n\".join(lines)\n\n def step():\n # logging\n log.plain(\"\\n\")\n log.success(\"stepping\")\n # logging\n\n packet = heap_pop(Scheduler.events)\n\n Scheduler.time_previous = Scheduler.time\n Scheduler.time = packet.time\n\n # this works because the way the list is built introduces a 1:1 relation between the id and the index\n # if the packet was lost (i.e. the queue was full), take no action\n current_node = NODES[packet.sender]\n if not packet.is_queued:\n current_node.generate_next_packet()\n if not packet.is_lost:\n current_node.handle_packet(packet)\n\n # logging\n log.plain(Scheduler())\n # logging\n\n def handle_results():\n if settings.FOLDER:\n file_total = open(settings.FOLDER+\"/total.csv\", \"a\")\n file_nodes = open(settings.FOLDER+\"/nodes.csv\", \"a\")\n\n results_title = log.format_color(\"results\", \"green\")\n results_data = [[\"NODE\", \"THROUGHPUT (kB/s)\", \"COLLISION RATE (%)\", \"LOSS RATE (%)\", \"generated\"]]\n\n loss_rate_total = 0\n collision_rate_total = 0\n throughput_total = 0\n # exponential scale is the mean of an exponential distribution https://www.johndcook.com/blog/2010/02/03/statistical-distributions-in-scipy/\n # mean of the size of each single packet divided by the mean of the inter arrival time\n average_load = ((settings.UNIFORM_MAX-settings.UNIFORM_MIN)/2) / (settings.GAMMA_SHAPE*settings.GAMMA_SCALE) # mean of the size of each single packet divided by the mean of the inter arrival time\n for node in NODES:\n throughput = node.data_sent/nlargest(1, Scheduler.events)[0].time # data_sent/last absolute time # mean of data sent per second\n throughput_total += throughput\n loss_rate = node.packets_lost/node.packets_generated\n loss_rate_total += loss_rate\n try:\n collision_rate = node.packets_collided/(node.packets_received+node.packets_collided)\n except ZeroDivisionError:\n collision_rate = 0\n collision_rate_total += collision_rate\n\n line = [str(node.id), settings.PRECISION.format(throughput/1000), settings.PRECISION.format(collision_rate*100), settings.PRECISION.format(loss_rate*100), settings.PRECISION.format(node.packets_generated)]\n results_data.append(line)\n if settings.FOLDER:\n file_nodes.write(\",\".join([str(node.id), settings.PRECISION.format(settings.GAMMA_SCALE), settings.PRECISION.format(throughput), settings.PRECISION.format(average_load), settings.PRECISION.format(collision_rate*100), settings.PRECISION.format(loss_rate*100)]))\n file_nodes.write(\"\\n\")\n\n line = [\"MEAN\", settings.PRECISION.format(throughput_total/1000/len(NODES)), settings.PRECISION.format(collision_rate_total/len(NODES)*100), settings.PRECISION.format(loss_rate_total/len(NODES)*100)]\n results_data.append(line)\n if settings.FOLDER:\n file_total.write(\",\".join([settings.PRECISION.format(settings.GAMMA_SCALE), settings.PRECISION.format(throughput_total/len(NODES)), settings.PRECISION.format(average_load), settings.PRECISION.format(collision_rate_total/len(NODES)*100), settings.PRECISION.format(loss_rate_total/len(NODES)*100)]))\n file_total.write(\"\\n\")\n\n if not settings.QUIET:\n print(\"\\n\")\n print(AsciiTable(results_data, results_title).table)\n print(\"\\n\")\n print(\" \".join([\"SYSTEM THROUGHPUT (kB/s) =\", settings.PRECISION.format(throughput_total/1000)]))\n\n if settings.FOLDER:\n file_nodes.close()\n file_total.close()\n\n def _get_heap_table():\n heap_title = log.format_color(\"events\", \"green\")\n heap_data = [[\"TIME\", \"NODE\", \"PACKET\"]]\n\n ordered_events = heap_read(len(Scheduler.events), Scheduler.events)\n for packet in ordered_events:\n if packet.time == Scheduler.time:\n time = log.format_evidence(settings.PRECISION.format(packet.time), \"yellow\")\n else:\n time = settings.PRECISION.format(packet.time)\n\n heap_data.append([time, str(packet.sender), str(packet.id)])\n\n return AsciiTable(heap_data, heap_title).table\n\n def _get_status_table():\n status_title = log.format_color(\" \".join([\"time =\", settings.PRECISION, \"s(abs)\"]).format(Scheduler.time), \"green\")\n status_data = [[\"NODE\", \"STATUS\", \"QUEUE\", \"TO\", \"FOR s(rel)\", \"UNTIL s(abs)\", \"LOST\", \"SENT\", \"RECEIVED\", \"COLLIDED\"]]\n\n for node in NODES:\n if node.is_idle():\n status = log.format_evidence(\"IDLE\", \"green\")\n time_relative = \"-\"\n time_absolute = \"-\"\n elif node.is_sending():\n status = log.format_evidence(\"SENDING\", \"cyan\")\n time_relative = settings.PRECISION.format(node.sending_until-Scheduler.time)\n time_absolute = settings.PRECISION.format(node.sending_until)\n elif node.is_receiving():\n status = log.format_evidence(\"RECEIVING\", \"magenta\")\n time_relative = settings.PRECISION.format(node.receiving_until-Scheduler.time)\n time_absolute = settings.PRECISION.format(node.receiving_until)\n\n destinations = []\n for neighbour in node.neighbours:\n destinations.append(neighbour.id)\n\n queued = []\n for packet in node.queue:\n queued.append(packet.id)\n\n status_data.append([str(node.id), status, str(queued), str(destinations), time_relative, time_absolute, str(node.packets_lost), str(node.packets_sent), str(node.packets_received), str(node.packets_collided)])\n\n return AsciiTable(status_data, status_title).table\n","sub_path":"iris/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":6385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"71177541","text":"#!/usr/bin/python\n# coding:utf-8\n\n\nimport math\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom modules.embedding import Embedding\nfrom modules.encoder_blocks import EncoderBlock\nfrom modules.intraction import CQAttention\nfrom modules.layers import Initialized_Conv1d\nfrom modules.pointer import Pointer\n\nclass QANet(nn.Module):\n def __init__(self, word_mat, char_mat,\n c_max_len, q_max_len, d_model, train_cemb=False, pad=0,\n dropout=0.1, num_head=1): # !!! notice: set it to be a config parameter later.\n super().__init__()\n if train_cemb:\n self.char_emb = nn.Embedding.from_pretrained(char_mat, freeze=False)\n else:\n self.char_emb = nn.Embedding.from_pretrained(char_mat)\n self.word_emb = nn.Embedding.from_pretrained(word_mat)\n wemb_dim = word_mat.shape[1]\n cemb_dim = char_mat.shape[1]\n self.emb = Embedding(wemb_dim, cemb_dim, d_model)\n self.num_head = num_head\n self.emb_enc = EncoderBlock(conv_num=4, d_model=d_model, num_head=num_head, k=7, dropout=0.1)\n self.cq_att = CQAttention(d_model=d_model)\n self.cq_resizer = Initialized_Conv1d(d_model * 4, d_model)\n self.model_enc_blks = nn.ModuleList(\n [EncoderBlock(conv_num=2, d_model=d_model, num_head=num_head, k=5, dropout=0.1)\n for _ in range(7)])\n self.out = Pointer(d_model)\n self.PAD = pad\n self.Lc = c_max_len\n self.Lq = q_max_len\n self.dropout = dropout\n\n def forward(self, Cwid, Ccid, Qwid, Qcid):\n maskC = (torch.ones_like(Cwid) *\n self.PAD != Cwid).float()\n maskQ = (torch.ones_like(Qwid) *\n self.PAD != Qwid).float()\n Cw, Cc = self.word_emb(Cwid), self.char_emb(Ccid)\n Qw, Qc = self.word_emb(Qwid), self.char_emb(Qcid)\n C, Q = self.emb(Cc, Cw, self.Lc), self.emb(Qc, Qw, self.Lq)\n Ce = self.emb_enc(C, maskC, 1, 1)\n Qe = self.emb_enc(Q, maskQ, 1, 1)\n X = self.cq_att(Ce, Qe, maskC, maskQ)\n M0 = self.cq_resizer(X)\n M0 = F.dropout(M0, p=self.dropout, training=self.training)\n for i, blk in enumerate(self.model_enc_blks):\n M0 = blk(M0, maskC, i*(2+2)+1, 7)\n M1 = M0\n for i, blk in enumerate(self.model_enc_blks):\n M0 = blk(M0, maskC, i*(2+2)+1, 7)\n M2 = M0\n M0 = F.dropout(M0, p=self.dropout, training=self.training)\n for i, blk in enumerate(self.model_enc_blks):\n M0 = blk(M0, maskC, i*(2+2)+1, 7)\n M3 = M0\n p1, p2 = self.out(M1, M2, M3, maskC)\n return p1, p2\n\n def summary(self):\n model_parameters = filter(lambda p: p.requires_grad, self.parameters())\n params = sum([np.prod(p.size()) for p in model_parameters])\n print('Trainable parameters:', params)\n","sub_path":"QANet.py","file_name":"QANet.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"629616396","text":"\"\"\"\r\nBLOCK.py\r\nContains definitions for block element classes.\r\n\"\"\"\r\nfrom util import *\r\nimport StringIO\r\nfrom dom import NODE_MAP, DOMElement\r\n\r\nclass BlockElement(DOMElement):\r\n def codegen(self, out, indent=0):\r\n s = FileStream(StringIO.StringIO())\r\n self.blockcodegen(s)\r\n out.writeblock(indent,s._file.getvalue())\r\n s.close()\r\n\r\n \"\"\" \r\n blockcodegen defines the output of the block element if the indentation was 0. \r\n Indentation is handled by codegen.\r\n \"\"\"\r\n def blockcodegen(self, out):\r\n pass\r\n\r\n def isInline():\r\n return false\r\n\r\n#### HEADERS ####\r\nclass H1Element(BlockElement):\r\n def blockcodegen(self, out, indent=0):\r\n start = out.numchars()\r\n out.writet(self.text)\r\n for child in self:\r\n child.codegen(out, indent)\r\n out.write(ENDL, \"=\"*(out.numchars() - start), ENDL)\r\n out.writet(strip(self.tail))\r\nNODE_MAP(\"h1\", H1Element)\r\n\r\nclass H2Element(BlockElement):\r\n def blockcodegen(self, out, indent=0):\r\n out.write(ENDL)\r\n start = out.numchars()\r\n out.writet(self.text)\r\n for child in self:\r\n child.codegen(out, indent)\r\n out.write(ENDL, \"-\"*(out.numchars() - start), ENDL)\r\n out.writet(strip(self.tail))\r\nNODE_MAP(\"h2\", H2Element)\r\nNODE_MAP(\"h3\", H2Element)\r\nNODE_MAP(\"h4\", H2Element)\r\nNODE_MAP(\"h5\", H2Element)\r\nNODE_MAP(\"h6\", H2Element)\r\nNODE_MAP(\"h7\", H2Element)\r\n\r\nclass ParagraphElement(BlockElement):\r\n def codegen(self, out, indent=0):\r\n out.write(ENDL)\r\n out.writet(strip(self.text))\r\n for child in self:\r\n child.codegen(out, indent)\r\n out.writet(strip(self.tail))\r\n out.write(ENDL)\r\n\r\nNODE_MAP(\"p\", ParagraphElement)","sub_path":"block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"152087011","text":"from django.urls import path\n\nfrom ..views import analytics\n\nANALYTICS_URL = [\n path(\n \"create_analytics_product//\",\n analytics.create_product_analytics,\n name=\"create_product_analytics\",\n ),\n path(\n \"create_shop_analytics//\",\n analytics.create_shop_analytics,\n name=\"create_shop_analytics\",\n ),\n path(\n \"create_tags_analytics/\",\n analytics.create_tags_analytics,\n name=\"create_tags_analytics\",\n ),\n path(\"get_data//\", analytics.get_product_clicks, name=\"get_data\"),\n path(\"get_shop_view/\", analytics.get_shop_views, name=\"get_shop_view\"),\n path(\"get_products_clicked/\", analytics.get_product_clicked, name=\"get_products\"),\n]\n","sub_path":"api/urls_route/analytics.py","file_name":"analytics.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"360614494","text":"import dbdetails as dbd\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Category, Item, User\n\nengine = create_engine('postgres+psycopg2://{}:{}@{}:{}/{}'.format(dbd.name,\n dbd.password,\n dbd.host,\n dbd.port,\n dbd.dbname))\n\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n# Add the moderator user details\nmoderator = User(name='CarlosEAM', email='carlos.alford@gmail.com')\nsession.add(moderator)\nsession.commit()\n\n# Airplanes category\ncategory1 = Category(name='Airplanes', user=moderator)\nsession.add(category1)\nsession.commit()\n\nitem1 = Item(name='Early powered flights', description='An airplane or \\\n aeroplane (informally plane) is a powered, fixed-wing aircraft that \\\n is propelled forward by thrust from a jet engine, propeller or rocket \\\n engine. Airplanes come in a variety of sizes, shapes, and wing \\\n configurations. The broad spectrum of uses for airplanes includes \\\n recreation, transportation of goods and people, military, and research. \\\n Worldwide, commercial aviation transports more than four billion \\\n passengers annually on airliners[1] and transports more than 200 billion \\\n tonne-kilometres[2] of cargo annually, which is less than 1 percent of \\\n the world\\'s cargo movement.[3] Most airplanes are flown by a pilot on \\\n board the aircraft, but some are designed to be remotely or \\\n computer-controlled.', category=category1, user=moderator)\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name='Wright brothers', description='The Wright brothers flights \\\n in 1903 are recognized by the Fédération Aéronautique Internationale \\\n (FAI), the standard setting and record-keeping body for aeronautics, as \\\n \"the first sustained and controlled heavier-than-air powered flight\".[4] \\\n By 1905, the Wright Flyer III was capable of fully controllable, stable \\\n flight for substantial periods. The Wright brothers credited Otto \\\n Lilienthal as a major inspiration for their decision to pursue manned \\\n flight.', category=category1, user=moderator)\nsession.add(item2)\nsession.commit()\n\nitem3 = Item(name='Gas turbine', description='A turboprop gas turbine engine \\\n consists of an intake, compressor, combustor, turbine, and a propelling \\\n nozzle, which provide power from a shaft through a reduction gearing to \\\n the propeller. The propelling nozzle provides a relatively small \\\n proportion of the thrust generated by a turboprop.',\n category=category1, user=moderator)\nsession.add(item3)\nsession.commit()\n\nitem4 = Item(name='Jet', description='Jet aircraft are propelled by jet \\\n engines, which are used because the aerodynamic limitations of propellers \\\n do not apply to jet propulsion. These engines are much more powerful \\\n than a reciprocating engine for a given size or weight and are \\\n comparatively quiet and work well at higher altitude. Variants of the jet \\\n engine include the ramjet and the scramjet, which rely on high airspeed \\\n and intake geometry to compress the combustion air, prior to the \\\n introduction and ignition of fuel. Rocket motors provide thrust by \\\n burning a fuel with an oxidizer and expelling gas through a \\\n nozzle.', category=category1, user=moderator)\nsession.add(item4)\nsession.commit()\n\n# Skateboarding category\ncategory2 = Category(name='Skateboarding', user=moderator)\nsession.add(category2)\nsession.commit()\n\nitem1 = Item(name='1940s–1960s', description='The first skateboards started \\\n with wooden boxes, or boards, with roller skate wheels attached to the \\\n bottom. Crate scooters preceded skateboards, having a wooden crate \\\n attached to the nose (front of the board), which formed rudimentary \\\n handlebars. The boxes turned into planks, similar to the skateboard \\\n decks of today.[9]', category=category2, user=moderator)\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name='Dogtown and Z-Boys', description='Is an award winning \\\n 2001 documentary film directed by Stacy Peralta. The documentary explores \\\n the pioneering of the Zephyr skateboard team in the 1970s (of which \\\n Peralta was a member) and the evolving sport of skateboarding. Using \\\n a mix of film of the Zephyr skateboard team (Z-Boys) shot in the 1970s \\\n by Craig Stecyk, along with contemporary interviews, the documentary \\\n tells the story of a group of teenage surfer/skateboarders and their \\\n influence on the history of skateboarding (and to a lesser extent \\\n surfing) culture.', category=category2, user=moderator)\nsession.add(item2)\nsession.commit()\n\nitem3 = Item(name='Trick skating', description='With the evolution of \\\n skateparks and ramp skating, the skateboard began to change. Early skate \\\n tricks had consisted mainly of two-dimensional freestyle manoeuvres like \\\n riding on only two wheels (\"wheelie\" or \"manual\"), spinning only on the \\\n back wheels (a \"pivot\"), high jumping over a bar and landing on the board \\\n again, also known as a \"hippie jump\", long jumping from one board to \\\n another, (often over small barrels or fearless teenagers), or slalom. \\\n Another popular trick was the Bertlemann slide, named after Larry \\\n Bertelemann\\'s surfing manoeuvres.', category=category2, user=moderator)\nsession.add(item3)\nsession.commit()\n\nitem4 = Item(name='Skate shoe', description='Whilst early skateboarders \\\n generally rode barefoot, preferring direct foot-to-board contact, and \\\n some skaters continue to do so, one of the early leading trends associated\\\n with the sub-culture of skateboarding itself, was the sticky-soled slip-on\\\n skate shoe, most popularized by Sean Penn\\'s skateboarding character \\\n from the film Fast Times at Ridgemont High.[8] Because early skateboarders\\\n were actually surfers trying to emulate the sport of surfing, at the time \\\n when skateboards first came out on the market, many skateboarded barefoot.\\\n But skaters often lacked traction, which led to foot injuries.[25] This \\\n necessitated the need for a shoe that was specifically designed and \\\n marketed for skateboarding, such as the Randy \"720\", manufactured by the \\\n Randolph Rubber Company, and Vans sneakers, which eventually became \\\n cultural iconic signifiers for skateboarders during the 1970s and \\'80s \\\n as skateboarding became more widespread',\n category=category2, user=moderator)\nsession.add(item4)\nsession.commit()\n\n# NASA category\ncategory3 = Category(name='NASA', user=moderator)\nsession.add(category3)\nsession.commit()\n\nitem1 = Item(name='Project Mercury (1958–1963)', description='Shortly after \\\n the Space Race began, an early objective was to get a person into Earth \\\n orbit as soon as possible, therefore the simplest spacecraft that could \\\n be launched by existing rockets was favored. The US Air Force\\'s Man in \\\n Space Soonest program considered many manned spacecraft designs, ranging \\\n from rocket planes like the X-15, to small ballistic space capsules.[32] \\\n By 1958, the space plane concepts were eliminated in favor of the \\\n ballistic capsule', category=category3, user=moderator)\nsession.add(item1)\nsession.commit()\n\nitem2 = Item(name='Skylab (1965–1979)', description='Skylab was the United \\\n States first and only independently built space station.[57] Conceived \\\n in 1965 as a workshop to be constructed in space from a spent Saturn IB \\\n upper stage, the 169,950 lb (77,088 kg) station was constructed on Earth \\\n and launched on May 14, 1973, atop the first two \\\n stages of a Saturn V, into a 235-nautical-mile (435 km) orbit inclined \\\n at 50° to the equator.', category=category3, user=moderator)\nsession.add(item2)\nsession.commit()\n\nitem3 = Item(name='Space Shuttle program (1972–2011)', description='The Space \\\n Shuttle became the major focus of NASA in the late 1970s and the 1980s. \\\n Planned as a frequently launchable and mostly reusable vehicle, four \\\n Space Shuttle orbiters were built by 1985. The first to launch, Columbia, \\\n did so on April 12, 1981,[62] the 20th anniversary of the first known \\\n human space flight', category=category3, user=moderator)\nsession.add(item3)\nsession.commit()\n\nprint(\"Categories, Items and Users added\")\n","sub_path":"testdatabase.py","file_name":"testdatabase.py","file_ext":"py","file_size_in_byte":8457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"247947945","text":"from argparse import ArgumentParser\nimport logging\nimport os\nimport sys\n\nfrom symbol_table_generator import SymbolTableGenerator\n\n\ndef get_args():\n arg_parser = ArgumentParser()\n arg_parser.add_argument(\n \"--elf\",\n required=True,\n )\n arg_parser.add_argument(\n \"-o\", \"--output\",\n required=True,\n )\n arg_parser.add_argument(\n \"-l\", \"--log-output\",\n default=None,\n dest=\"log_output\",\n )\n return arg_parser.parse_args()\n\ndef main():\n args = get_args()\n elf_filepath = args.elf\n output = args.output\n log_output = args.log_output\n\n elf_filename = os.path.basename(elf_filepath)\n basename, ext = os.path.splitext(os.path.basename(elf_filepath))\n output_filename = \"{}.json\".format(basename)\n\n if os.path.isdir(output) or \".\" not in os.path.basename(output):\n output_filepath = os.path.join(output, output_filename)\n else:\n output_filepath = output\n\n if not os.path.isdir(os.path.dirname(output_filepath)):\n os.makedirs(os.path.dirname(output_filepath))\n\n if log_output is not None:\n log_filename = \"{}.log\".format(basename)\n\n if os.path.isdir(log_output) or \".\" not in os.path.basename(log_output):\n log_filepath = os.path.join(log_output, log_filename)\n else:\n log_filepath = output\n\n logging.basicConfig(filename=log_filepath, level=logging.DEBUG)\n\n if not os.path.isfile(elf_filepath):\n print(\"Unable to find ELF file: [{}]\".format(elf_filepath))\n return 1 # Return early\n\n with open(elf_filepath,\"rb\") as file:\n symbol_table_generator = SymbolTableGenerator(file)\n\n message = \"Generating Symbol Table [{}] -> [{}]\".format(elf_filename, output_filename)\n print(message)\n\n symbol_table = symbol_table_generator.generate_symbol_table()\n symbol_table.to_json(output_filepath)\n\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"site_scons/site_tools/symbol_table/generate_symbol_table.py","file_name":"generate_symbol_table.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"550619109","text":"from django.shortcuts import render\r\n\r\n\r\ndef CV(request):\r\n import datetime\r\n birth_date = datetime.datetime(year=1992, month=3, day=1)\r\n developer_from_date = datetime.datetime(year=2016, month=12, day=1)\r\n date_now = datetime.date.today()\r\n\r\n age = date_now.year - birth_date.year - ((date_now.month, date_now.day) < (birth_date.month, birth_date.day))\r\n experience_years = date_now.year - developer_from_date.year - ((date_now.month, date_now.day) < (developer_from_date.month, developer_from_date.day))\r\n\r\n\r\n context = {\r\n\r\n 'age': age,\r\n 'experience': experience_years,\r\n 'skills': {\r\n 'Backend': [\r\n ('Python', 4),\r\n ('Django', 3),\r\n ('Django REST', 1),\r\n ('Nginx', 4),\r\n ],\r\n\r\n 'Frontend': [\r\n ('JS', 2),\r\n ('jQuery', 3),\r\n ('VueJS', 3),\r\n ('HTML', 4),\r\n ('CSS', 3),\r\n ('Bootstrap', 3)\r\n ],\r\n\r\n 'Template engine': [\r\n ('Jinja2', 3)\r\n ],\r\n\r\n 'Tools': [\r\n ('Git', 3),\r\n ('Docker', 3),\r\n ('Supervisor', 4),\r\n ],\r\n\r\n 'Testing': [\r\n ('Selenium', 4),\r\n ('Unit testing', 1)\r\n ],\r\n\r\n 'Databases(SQL / noSQL)': [\r\n ('PostgreSQL', 4),\r\n ('Django ORM', 3),\r\n ('Redis', 4)\r\n ],\r\n\r\n 'VoIP': [\r\n ('Asterisk', 3)\r\n ],\r\n\r\n 'Python libs': [\r\n ('Pandas', 2),\r\n ('Numpy', 3),\r\n ('Pydub', 3)\r\n ]\r\n\r\n\r\n }\r\n }\r\n\r\n return render(request, 'cv.html', context)","sub_path":"conf/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"604612828","text":"import argparse\nfrom attrdict import AttrDict\nfrom deriva.core import ErmrestCatalog, get_credential, DerivaPathError\nfrom deriva.utils.catalog.components.deriva_model import DerivaCatalog\nimport deriva.core.ermrest_model as em\nfrom deriva.core.ermrest_config import tag as chaise_tags\nfrom deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args\n\ngroups = {\n 'pdb-admin': 'https://auth.globus.org/0b98092c-3c41-11e9-a8c8-0ee7d80087ee',\n 'pdb-reader': 'https://auth.globus.org/8875a770-3c40-11e9-a8c8-0ee7d80087ee',\n 'pdb-writer': 'https://auth.globus.org/c94a1e5c-3c40-11e9-a5d1-0aacc65bfe9a',\n 'pdb-curator': 'https://auth.globus.org/eef3e02a-3c40-11e9-9276-0edc9bdd56a6',\n 'isrd-staff': 'https://auth.globus.org/176baec4-ed26-11e5-8e88-22000ab4b42b'\n}\n\ntable_name = 'pdbx_unobs_or_zero_occ_atoms'\n\nschema_name = 'PDB'\n\ncolumn_annotations = {\n 'RCT': {\n chaise_tags.display: {\n 'name': 'Creation Time'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'RMT': {\n chaise_tags.display: {\n 'name': 'Last Modified Time'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'RCB': {\n chaise_tags.display: {\n 'name': 'Created By'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'RMB': {\n chaise_tags.display: {\n 'name': 'Modified By'\n },\n chaise_tags.generated: None,\n chaise_tags.immutable: None\n },\n 'structure_id': {},\n 'PDB_model_num': {},\n 'auth_asym_id': {},\n 'auth_atom_id': {},\n 'auth_comp_id': {},\n 'auth_seq_id': {},\n 'id': {},\n 'label_asym_id': {},\n 'label_atom_id': {},\n 'label_comp_id': {},\n 'label_seq_id': {},\n 'occupancy_flag': {},\n 'polymer_flag': {},\n 'Owner': {}\n}\n\ncolumn_comment = {\n 'structure_id': 'type:text\\nThe value of _entry.id identifies the data block.\\n\\n Note that this item need not be a number; it can be any unique\\n identifier.',\n 'PDB_model_num': 'type:int4\\nA unique identifier for the structural model being deposited.',\n 'auth_asym_id': 'type:text\\nPart of the identifier for the unobserved or zero occupancy atom.\\n\\n This data item is a pointer to _atom_site.auth_asym_id in the\\n ATOM_SITE category.',\n 'auth_atom_id': 'type:text\\nPart of the identifier for the unobserved or zero occupancy atom.\\n\\n This data item is a pointer to _atom_site.auth_atom_id in the\\n ATOM_SITE category.',\n 'auth_comp_id': 'type:text\\nThe value of _chem_comp.id must uniquely identify each item in\\n the CHEM_COMP list.\\n\\n For protein polymer entities, this is the three-letter code for\\n the amino acid.\\n\\n For nucleic acid polymer entities, this is the one-letter code\\n for the base.',\n 'auth_seq_id': 'type:text\\nPart of the identifier for the unobserved or zero occupancy atom.\\n\\n This data item is a pointer to _atom_site.auth_seq_id in the\\n ATOM_SITE category.',\n 'id': 'type:int4\\nThe value of _pdbx_unobs_or_zero_occ_atoms.id must uniquely identify\\n each item in the PDBX_UNOBS_OR_ZERO_OCC_ATOMS list.\\n\\n This is an integer serial number.',\n 'label_asym_id': 'type:text\\nThe value of _struct_asym.id must uniquely identify a record in\\n the STRUCT_ASYM list.\\n\\n Note that this item need not be a number; it can be any unique\\n identifier.',\n 'label_atom_id': 'type:text\\nPart of the identifier for the unobserved or zero occupancy atom.\\n\\n This data item is a pointer to _atom_site.label_atom_id in the\\n ATOM_SITE category.',\n 'label_comp_id': 'type:text\\nThe value of _chem_comp.id must uniquely identify each item in\\n the CHEM_COMP list.\\n\\n For protein polymer entities, this is the three-letter code for\\n the amino acid.\\n\\n For nucleic acid polymer entities, this is the one-letter code\\n for the base.',\n 'label_seq_id': 'type:int4\\nPart of the identifier for the unobserved or zero occupancy atom.\\n\\n This data item is a pointer to _atom_site.label_seq_id in the\\n ATOM_SITE category.',\n 'occupancy_flag': 'type:int4\\nThe value of occupancy flag indicates whether the atom is\\n either unobserved (=1) or has zero occupancy (=0)',\n 'polymer_flag': 'type:text\\nThe value of polymer flag indicates whether the unobserved or zero\\n occupancy atom is part of a polymer chain',\n 'Owner': 'Group that can update the record.'\n}\n\ncolumn_acls = {}\n\ncolumn_acl_bindings = {}\n\ncolumn_defs = [\n em.Column.define(\n 'structure_id',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['structure_id'],\n ),\n em.Column.define(\n 'PDB_model_num',\n em.builtin_types['int4'],\n nullok=False,\n comment=column_comment['PDB_model_num'],\n ),\n em.Column.define(\n 'auth_asym_id',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['auth_asym_id'],\n ),\n em.Column.define(\n 'auth_atom_id',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['auth_atom_id'],\n ),\n em.Column.define(\n 'auth_comp_id',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['auth_comp_id'],\n ),\n em.Column.define(\n 'auth_seq_id',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['auth_seq_id'],\n ),\n em.Column.define('id', em.builtin_types['int4'], nullok=False, comment=column_comment['id'],\n ),\n em.Column.define(\n 'label_asym_id', em.builtin_types['text'], comment=column_comment['label_asym_id'],\n ),\n em.Column.define(\n 'label_atom_id', em.builtin_types['text'], comment=column_comment['label_atom_id'],\n ),\n em.Column.define(\n 'label_comp_id', em.builtin_types['text'], comment=column_comment['label_comp_id'],\n ),\n em.Column.define(\n 'label_seq_id', em.builtin_types['int4'], comment=column_comment['label_seq_id'],\n ),\n em.Column.define(\n 'occupancy_flag',\n em.builtin_types['int4'],\n nullok=False,\n comment=column_comment['occupancy_flag'],\n ),\n em.Column.define(\n 'polymer_flag',\n em.builtin_types['text'],\n nullok=False,\n comment=column_comment['polymer_flag'],\n ),\n em.Column.define('Owner', em.builtin_types['text'], comment=column_comment['Owner'],\n ),\n]\n\ntable_annotations = {}\n\ntable_comment = None\n\ntable_acls = {}\n\ntable_acl_bindings = {\n 'self_service_group': {\n 'types': ['update', 'delete'],\n 'projection': ['Owner'],\n 'projection_type': 'acl',\n 'scope_acl': ['*']\n },\n 'self_service_creator': {\n 'types': ['update', 'delete'],\n 'projection': ['RCB'],\n 'projection_type': 'acl',\n 'scope_acl': ['*']\n }\n}\n\nkey_defs = [\n em.Key.define(['RID'], constraint_names=[('PDB', 'pdbx_unobs_or_zero_occ_atoms_RIDkey1')],\n ),\n em.Key.define(\n ['structure_id', 'id'],\n constraint_names=[('PDB', 'pdbx_unobs_or_zero_occ_atoms_primary_key')],\n ),\n]\n\nfkey_defs = [\n em.ForeignKey.define(\n ['polymer_flag'],\n 'Vocab',\n 'pdbx_unobs_or_zero_occ_atoms_polymer_flag_term', ['ID'],\n constraint_names=[('PDB', 'pdbx_unobs_or_zero_occ_atoms_polymer_flag_term_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n on_update='CASCADE',\n on_delete='SET NULL',\n ),\n em.ForeignKey.define(\n ['Owner'],\n 'public',\n 'Catalog_Group', ['ID'],\n constraint_names=[('PDB', 'pdbx_unobs_or_zero_occ_atoms_Owner_fkey')],\n acls={\n 'insert': [groups['pdb-curator']],\n 'update': [groups['pdb-curator']]\n },\n acl_bindings={\n 'set_owner': {\n 'types': ['update', 'insert'],\n 'projection': ['ID'],\n 'projection_type': 'acl',\n 'scope_acl': ['*']\n }\n },\n ),\n em.ForeignKey.define(\n ['RCB'],\n 'public',\n 'ERMrest_Client', ['ID'],\n constraint_names=[('PDB', 'pdbx_unobs_or_zero_occ_atoms_RCB_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n ),\n em.ForeignKey.define(\n ['RMB'],\n 'public',\n 'ERMrest_Client', ['ID'],\n constraint_names=[('PDB', 'pdbx_unobs_or_zero_occ_atoms_RMB_fkey')],\n acls={\n 'insert': ['*'],\n 'update': ['*']\n },\n ),\n]\n\ntable_def = em.Table.define(\n table_name,\n column_defs=column_defs,\n key_defs=key_defs,\n fkey_defs=fkey_defs,\n annotations=table_annotations,\n acls=table_acls,\n acl_bindings=table_acl_bindings,\n comment=table_comment,\n provide_system=True\n)\n\n\ndef main(catalog, mode, replace=False, really=False):\n updater = CatalogUpdater(catalog)\n updater.update_table(mode, schema_name, table_def, replace=replace, really=really)\n\n\nif __name__ == \"__main__\":\n host = 'pdb.isrd.isi.edu'\n catalog_id = 5\n mode, replace, host, catalog_id = parse_args(host, catalog_id, is_table=True)\n catalog = DerivaCatalog(host, catalog_id=catalog_id, validate=False)\n main(catalog, mode, replace)\n\n","sub_path":"catalog-configs/PDB/pdbx_unobs_or_zero_occ_atoms.py","file_name":"pdbx_unobs_or_zero_occ_atoms.py","file_ext":"py","file_size_in_byte":9324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"647192626","text":"# 소수일 경우 False\n# 소수가 아닐 경우 True\n\ns = 123456 * 2 + 1\nl = [False] * s\nl[0] = l[1] = True\n\nfor i in range(2, int(s ** (1 / 2)) + 1):\n if l[i] == True:\n continue\n for j in range(i * i, len(l), i):\n if j % i == 0:\n l[j] = True\n\nwhile True:\n n = int(input())\n if n == 0:\n break\n\n cnt = 0\n for i in range(n + 1, (n * 2) + 1):\n if l[i] == False:\n cnt += 1\n\n print(cnt)\n","sub_path":"BOJ/4948_2.py","file_name":"4948_2.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"639704633","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport json\nimport redis\nfrom urllib.parse import quote_plus,unquote\nfrom scrapy.utils.project import get_project_settings\nfrom proweb.items import ProwebLicensingXyzgItem\nsettings = get_project_settings()\n\nclass TycLicensingxyzgSpider(scrapy.Spider):\n '''\n 行政许可(信用中国)\n '''\n name = 'tyc_licensingXyzg'\n allowed_domains = ['tianyancha.com']\n # start_urls = ['http://tianyancha.com/']\n\n def start_requests(self):\n redis_pool = redis.StrictRedis(host=settings['REDIS_HOST'], port=settings['REDIS_PORT'], password=settings['REDIS_PASSWORD'],db=settings['REDIS_DB'], decode_responses=True)\n while True:\n allkeys = redis_pool.hscan_iter(settings['NAME'],settings['PATTERN'],settings['COUNT'])\n for item in allkeys:\n key = item[0]\n val = json.loads(item[1].replace(\"'\",'\"'))\n if not redis_pool.sismember(\"hasLicensingChinaSign\",\"haslicensingChina:\"+key):\n url = \"https://www.tianyancha.com/pagination/licensingXyzg.xhtml?ps=30&pn=1&id=%s&name=%s\"%(key,quote_plus(val['name']))\n yield scrapy.Request(url,callback=self.parse,meta={'id':key,'name':quote_plus(val['name'])})\n else:\n print(\"数据已存在\")\n break\n else:\n print(\"没有数据\")\n\n\n def parse(self, response):\n item = ProwebLicensingXyzgItem()\n info_list = []\n sign = None\n meta = response.meta\n table_trs = response.css(\"table.table>tbody>tr\")\n if table_trs:\n for tr in table_trs:\n table_dict = {}\n #行政许可(信用中国)详情\n table_dict[\"licence_content\"] = tr.xpath(\"./td[last()]/script/text()\").extract_first() if tr.xpath(\"./td[last()]/script/text()\") else \"-\"\n info_list.append(table_dict)\n item[\"info\"] = info_list\n\n next_ul = response.css(\"ul.pagination\")\n next_num = \"\"\n if next_ul:\n if next_ul.css(\"li a.-next\"):\n next_num = next_ul.css(\"li a.-next::attr(onclick)\").extract_first().split(\"(\")[1].split(\",\")[0]\n sign = False\n elif next_ul.css(\"li a.-current\"):\n next_num = next_ul.css(\"li a.-current::text\").extract_first()\n sign = True\n url = \"https://www.tianyancha.com/pagination/licensingXyzg.xhtml?ps=30&pn=%s&id=%s&name=%s\"%(next_num,meta['id'],meta['name'])\n yield scrapy.Request(url,callback=self.parse,meta=meta)\n else:\n sign = True\n else:\n item[\"info\"] = \"-\"\n sign = True\n item[\"id\"] = meta['id']\n item[\"name\"] = meta['name']\n item[\"sign\"] = sign\n # print(item)\n yield item\n\n","sub_path":"proweb/proweb/spiders/tyc_licensingXyzg.py","file_name":"tyc_licensingXyzg.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"183747177","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nimport sys\n\n\ndirectory_fix = \"\"\"#!/bin/sh\n\nfunction log {\n\tloglevel=$1\n\tmessage=$2\n\n\techo $loglevel $(date +\"%F %T\") $message\n}\n\nlog \"INFO\" \"RUN (patched csrctl.sh script)\"\n\nif [ \"$BASEDIR\" = \"\" ] ; then\n\tlog \"INFO\" \"no base directory given\"\n\tSCRIPT=$(readlink -f \"$0\")\n\tBASEDIR=$(dirname \"$SCRIPT\")\n\tlog \"INFO\" \"new base directory is $BASEDIR\"\n\n\tcd $BASEDIR\n\tlog \"INFO\" \"pwd is now `pwd`\"\n\n\tlog \"INFO\" \"current config dir: $CONFIGDIR\"\n\tCONFIGDIR=$BASEDIR/etc\n\tlog \"INFO\" \"new config dir: $CONFIGDIR\"\nfi\n\n\n# -- end of fix directories patch\n\n\"\"\"\n\ncsrctl_filename = sys.argv[1]\ncsrctl_patched_filename = sys.argv[2]\n\npatched_file = open(csrctl_patched_filename, 'w')\n\nwith open(csrctl_filename) as f:\n\tfor line in f:\n\t\tif '#!/bin/sh' in line:\n\t\t\tline = directory_fix\n\t\tif '\"$EXECUTABLE\" $JVMPARAM' in line:\n\t\t\tline = line.lstrip(\"\\t\")\n\t\t\tpos = line.find(\"<\")\n\t\t\tlinenew = line[0:0+pos]\n\t\t\tline = \"\\n\\n\\n\\t# old command line:\\n\\t#\" + line + \"\\techo INFO running application with params:\\n\\techo \\\"\" + linenew.rstrip(\"\\n\") + \"\\\"\\n\\texec \" + linenew + \"\\n\\n\\n\"\n\t\tpatched_file.write(line)\n\nf.close()\npatched_file.close()\n","sub_path":".s2i/bin/patch_csrctl.py","file_name":"patch_csrctl.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"306133457","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# wrapping_paper01a.py\n\n\"\"\"\nPrint a \"slanted\" msg on wrapping paper.\nEach line begins with the next character in the msg.\nThis version outputs in this format:\nHappy Birthday! Happy Birthday! Happy Birthday! ...\nappy Birthday! Happy Birthday! Happy Birthday! ...\nppy Birthday! Happy Birthday! Happy Birthday! ...\n\"\"\"\n\nmsg = \"Happy New Year!\"\ncolumns = 100 # Number of columns on output paper. (For DEV, use 80.)\ntotal_lines = 100 # Number of lines to print. (For DEV, use 50.)\n\n# Build output string\n# Create the substring that begins each line.\nline_cnt = 1 # Current output line counter.\n\nwhile line_cnt <= total_lines:\n output_str = \"\" # Container for this line of output.\n # Use MOD to create a string index never > msg length.\n str_index = (line_cnt-1) % len(msg)\n\n # Start the line with the indexed string.\n output_str = msg[str_index:] + \" \"\n\n # Build a string that's at least as long as number of columns.\n while len(output_str) < (columns + 1):\n output_str += (msg + \" \")\n\n # Output string is now >= columns. Truncate as necessary.\n output_str = output_str[0:columns]\n print(output_str)\n\n line_cnt += 1\n","sub_path":"rbv_python3_experiments/wrapping_paper/wrapping_paper01a.py","file_name":"wrapping_paper01a.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"201721987","text":"import discord\nfrom discord.ext import commands,tasks\nimport time\nimport json\n\nwith open('setting.json', mode='r',encoding='utf8') as jfile:\n jdata = json.load(jfile)\n\nintents = discord.Intents.all()\nbot=commands.Bot(command_prefix=\".\",intents=intents)\n\n@bot.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(bot))\n game = discord.Game(\"testing\")\n await bot.change_presence(status=discord.Status.idle, activity=game)\n#####################################################################################\n\n@bot.command()\nasync def sayd(ctx, *, msg):\n await ctx.message.delete()\n userid = discord.ClientUser.id(ctx.author)\n if userid == (int(jfile['Young_ID']) or int(jfile['Rou_ID'])):\n await ctx.send(msg)\n else:\n await ctx.send(\"Authority Error\")\n\n#####################################################################################\nbot.run(jdata['TestBotTOKEN'])\n\n","sub_path":"undone/bottest.py","file_name":"bottest.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"123715393","text":"import math\n\nimport pygame\nfrom pygame.locals import *\n\nimport engine.config\nfrom engine.hud import Hud\nfrom engine.block import *\nfrom engine.items import *\nfrom engine.areas import *\n\n\nclass Viewport():\n\n def __init__(self, virtual_width, virtual_height, map_height, map_width):\n\n\n self.v_rect = pygame.Rect(0, 0, virtual_width, virtual_height-config.hud_size)\n self.map_rect = pygame.Rect(0, 0, map_width, map_height)\n\n self.hud_rect = pygame.Rect(0, 0, virtual_width, virtual_height-config.hud_size)\n self.hud_height = virtual_height - config.hud_size\n\n self.map_layer = []\n self.map_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h))\n\n self.area_layer = [\n MeetingArea([ (x, y) for x in range(10) for y in range(10) ])\n ]\n self.area_layer_surf = pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA)\n\n self.item_layer = []\n self.item_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA)\n\n self.unit_layer = []\n self.unit_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA)\n\n self.unit_action_surf = pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA)\n\n self.hud = Hud(0, 0, virtual_width, config.hud_size, self)\n self.hud_surf = pygame.Surface((virtual_width, config.hud_size))\n self.hud_surf.fill(pygame.Color(\"#737373\"))\n self.hud_font = pygame.font.Font(\"assets/bitwise/bitwise.ttf\", 25)\n\n self.dirty = 1\n\n self.font = pygame.font.Font(None, 20)\n\n self.mouse_events = []\n\n def south(self):\n if abs(self.v_rect.y) + 5 < self.map_rect.h - config.window_size[1] + config.hud_size:\n self.v_rect.y += 5\n elif abs(self.v_rect.y) + 1 < self.map_rect.h - config.window_size[1]:\n self.v_rect.y += 1\n\n def north(self):\n if abs(self.v_rect.y) - 5 >= 0:\n self.v_rect.y -= 5\n elif abs(self.v_rect.y) - 1 >= 0:\n self.v_rect.y -= 1\n\n\n def east(self):\n if abs(self.v_rect.x) + 5 < self.map_rect.w - config.window_size[0]:\n self.v_rect.x += 5\n elif abs(self.v_rect.x) + 1 < self.map_rect.w - config.window_size[0]:\n self.v_rect.x += 1\n\n\n def west(self):\n if abs(self.v_rect.x) - 5 >= 0:\n self.v_rect.x -= 5\n elif abs(self.v_rect.x) - 1 >= 0:\n self.v_rect.x -= 1\n\n\n def handle_keyboard_events(self):\n keys = pygame.key.get_pressed()\n if keys[K_UP]:\n self.north()\n\n if keys[K_DOWN]:\n self.south()\n\n if keys[K_LEFT]:\n self.west()\n\n if keys[K_RIGHT]:\n self.east()\n\n def handle_mouse_events(self):\n mouse_pos = pygame.mouse.get_pos()\n for y in self.item_layer:\n for x in y:\n if x is not None:\n if isinstance(x, list):\n for item in x:\n if item.mouse_collide(mouse_pos):\n for event in self.mouse_events:\n if item.mouse_collide(event.pos, side_effect=False):\n item.toggle_selected()\n else:\n if x.mouse_collide(mouse_pos):\n for event in self.mouse_events:\n if x.mouse_collide(event.pos, side_effect=False):\n x.toggle_selected()\n\n hovering_unit = False\n for unit in self.unit_layer:\n if unit.mouse_collide():\n self.hud.set_state(\"hovered_unit\", unit)\n self.dirty = 1\n hovering_unit = True\n break\n\n if not hovering_unit and self.hud.state(\"hovered_unit\") != None:\n self.hud.set_state(\"hovered_unit\", None)\n self.dirty = 1\n\n hovering_stock_pile = False\n hovering_building_placeholder = False\n for y in self.item_layer:\n for x in y:\n if isinstance(x, Stockpile):\n if x.mouse_collide(mouse_pos, side_effect=False) or x.mouse_collide(side_effect=False):\n self.hud.set_state(\"hovered_stock_pile\", x)\n self.dirty = 1\n hovering_stock_pile= True\n break\n if isinstance(x, BuildingPlaceholder):\n if x.mouse_collide(mouse_pos, side_effect=False) or x.mouse_collide(side_effect=False):\n self.hud.set_state(\"hovered_building_placeholder\", x)\n self.dirty = 1\n hovering_building_placeholder = True\n break\n\n if not hovering_stock_pile and self.hud.state(\"hovered_stock_pile\") != None:\n self.hud.set_state(\"hovered_stock_pile\", None)\n self.dirty = 1\n\n if not hovering_building_placeholder and self.hud.state(\"hovered_building_placeholder\") != None:\n self.hud.set_state(\"hovered_building_placeholder\", None)\n self.dirty = 1\n\n self.mouse_events = []\n\n\n def render(self):\n self.hud.render()\n\n def update(self):\n for area in self.area_layer:\n area.update()\n\n self.hud.update()\n\n def draw(self, surf, forced=False):\n if self.dirty == 1 or self.dirty == 2:\n if self.dirty == 1:\n self.dirty = 0\n\n diff_rects = []\n for y in range(0, config.world_size[0]):\n for x in range(0, config.world_size[1]):\n map_diff = self.map_layer[y][x].draw(self.map_layer_surf)\n\n item_diff = None\n if self.item_layer[y][x] != None:\n if isinstance(self.item_layer[y][x], list):\n for item in self.item_layer[y][x]:\n item_diff = item.draw(self.item_layer_surf)\n diff_rects.append(item_diff)\n else: # not a list\n item_diff = self.item_layer[y][x].draw(self.item_layer_surf)\n diff_rects.append(item_diff)\n\n diff_rects.append(map_diff)\n\n for area in self.area_layer:\n diff = area.draw(self.area_layer_surf)\n diff_rects.append(diff)\n\n for unit in self.unit_layer:\n unit.draw(self.unit_layer_surf)\n\n self.unit_action_surf.fill(pygame.Color(0, 0, 0, 1))\n for unit in self.unit_layer:\n unit.draw_action(self.unit_action_surf)\n\n self.hud.draw(self.hud_surf)\n\n\n rects = [ ]\n\n # draw map layer\n rects.append( surf.blit(self.map_layer_surf, (0, 0), area=self.v_rect) )\n\n # draw area layer\n rects.append( surf.blit(self.area_layer_surf, (0, 0), area=self.v_rect) )\n\n # item layer\n rects.append( surf.blit(self.item_layer_surf, (0, 0), area=self.v_rect) )\n\n # unit layer\n rects.append( surf.blit(self.unit_layer_surf, (0, 0), area=self.v_rect) )\n\n # unit action layer\n rects.append( surf.blit(self.unit_action_surf, (0, 0), area=self.v_rect) )\n\n # draw hud layer\n rects.append( surf.blit(self.hud_surf, (0, self.hud_height), area=self.hud_rect) )\n\n\n return rects\n\n\n\n","sub_path":"engine/viewport.py","file_name":"viewport.py","file_ext":"py","file_size_in_byte":7511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"106038169","text":"\n# -*- coding: utf-8 -*-\n\n# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# All Rights Reserved.\n# Copyright 2012 Red Hat, Inc.\n# Copyright 2014 Alvaro Lopez Garcia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os\n\nfrom oslo_config import cfg\n\nopts = [\n cfg.StrOpt('basedir',\n default=os.path.abspath(os.path.join(os.path.dirname(__file__),\n '../')),\n help='Directory where the atrope python module is installed'),\n cfg.StrOpt('state_path',\n default='$basedir',\n help=\"Top-level directory for maintaining atrope's state\"),\n]\n\nCONF = cfg.CONF\nCONF.register_opts(opts)\n\n\ndef state_path_def(*args):\n \"\"\"Return an uninterpolated path relative to $state_path.\"\"\"\n return os.path.join('$state_path', *args)\n","sub_path":"atrope/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"316079846","text":"import logging\nimport os\nimport time\nfrom tqdm import tqdm\nimport torch\nimport numpy as np\nimport math\nfrom SoccerNet.Downloader import getListGames\nfrom visualization import visualize\nfrom SoccerNet.Evaluation.ReplayGrounding import evaluate, average_mAP, game_results_to_json\n\ndef trainer(train_loader,\n val_loader,\n val_metric_loader,\n test_loader,\n model,\n optimizer,\n scheduler,\n criterion,\n weights,\n model_name,\n max_epochs=1000,\n evaluation_frequency=20,\n annotation_path='',\n detection_path='',\n save_results=False\n ):\n\n logging.info(\"start training\")\n\n best_loss = 9e99\n best_metric = -1\n\n for epoch in range(max_epochs):\n best_model_path = os.path.join(\"models\", model_name, \"model.pth.tar\")\n\n\n # train for one epoch\n loss_training = train(\n train_loader,\n model,\n criterion_conf,\n criterion_loc,\n weights,\n optimizer,\n epoch + 1,\n train = True)\n\n # evaluate on validation set\n loss_validation = train(\n val_loader,\n model,\n criterion_conf,\n criterion_loc,\n weights,\n optimizer,\n epoch + 1,\n train = False)\n\n \n\n state = {\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'best_loss': best_loss,\n 'optimizer': optimizer.state_dict(),\n }\n os.makedirs(os.path.join(\"models\", model_name), exist_ok=True)\n # torch.save(\n # state,\n # os.path.join(\"models\", model_name,\n # \"model_epoch\" + str(epoch + 1) + \".pth.tar\"))\n\n # remember best prec@1 and save checkpoint\n is_better = loss_validation < best_loss\n best_loss = min(loss_validation, best_loss)\n\n\n\n # Save the best model based on loss only if the evaluation frequency too long\n if is_better and evaluation_frequency > 50:\n torch.save(state, best_model_path)\n\n # Test the model on the validation set\n if epoch % evaluation_frequency == 0 and epoch != 0:\n performance_validation = test(\n val_metric_loader,\n model, \n model_name,\n \"valid\",\n annotation_path,\n detection_path, \n save_results)\n\n logging.info(\"Validation performance at epoch \" + str(epoch+1) + \" -> \" + str(performance_validation))\n\n is_better_metric = performance_validation > best_metric\n best_metric = max(performance_validation,best_metric)\n\n\n # Save the best model based on metric only if the evaluation frequency is short enough\n if is_better_metric and evaluation_frequency <= 50:\n torch.save(state, best_model_path)\n performance_test = test(\n\t\ttest_loader,\n\t\tmodel, \n\t\tmodel_name,\n\t\t\"test\",\n annotation_path,\n detection_path, \n save_results)\n\n\n logging.info(\"Test performance at epoch \" + str(epoch+1) + \" -> \" + str(performance_test))\n\n if scheduler is not None:\n prevLR = optimizer.param_groups[0]['lr']\n scheduler.step(loss_validation)\n currLR = optimizer.param_groups[0]['lr']\n if (currLR is not prevLR and scheduler.num_bad_epochs == 0):\n logging.info(\"Plateau Reached!\")\n\n if (prevLR < 2 * scheduler.eps and\n scheduler.num_bad_epochs >= scheduler.patience):\n logging.info(\n \"Plateau Reached and no more reduction -> Exiting Loop\")\n break\n else:\n current_learning_rate = optimizer.param_groups[0]['lr']\n new_learning_rate = current_learning_rate * 0.993116#- (scheduler[0]-scheduler[1])/max_epochs# * 0.993116\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_learning_rate\n\n print(new_learning_rate)\n\n \"\"\"\n\n \"\"\"\n return\n\ndef train(dataloader,\n model,\n criterion_conf,\n criterion_loc, \n weights,\n optimizer,\n epoch,\n train=False):\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n losses_segmentation = AverageMeter()\n losses_spotting = AverageMeter()\n\n # switch to train mode\n if train:\n model.train()\n else:\n model.eval()\n \n end = time.time()\n with tqdm(enumerate(dataloader), total=len(dataloader), ncols=160) as t:\n for i, (feats, labels, targets) in t: \n # measure data loading time\n data_time.update(time.time() - end)\n\n feats = feats.cuda()\n labels = labels.cuda().float()\n targets = targets.cuda().float()\n\n # compute output\n output_segmentation, output_spotting = model(feats)\n\n loss_segmentation = criterion[0](labels, output_segmentation) \n loss_spotting = criterion[1](targets, output_spotting)\n\n loss = weights[0]*loss_segmentation + weights[1]*loss_spotting\n\n # measure accuracy and record loss\n losses.update(loss.item(), feats.size(0))\n losses_segmentation.update(loss_segmentation.item(), feats.size(0))\n losses_spotting.update(loss_spotting.item(), feats.size(0))\n\n if train:\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if train:\n desc = f'Train {epoch}: '\n else:\n desc = f'Evaluate {epoch}: '\n desc += f'Time {batch_time.avg:.3f}s '\n desc += f'(it:{batch_time.val:.3f}s) '\n desc += f'Data:{data_time.avg:.3f}s '\n desc += f'(it:{data_time.val:.3f}s) '\n desc += f'Loss {losses.avg:.4e} '\n desc += f'Loss Seg {losses_segmentation.avg:.4e} '\n desc += f'Loss Spot {losses_spotting.avg:.4e} '\n t.set_description(desc)\n\n return losses.avg\n\n\ndef test(dataloader,model, model_name,split,annotation_path,detection_path,save_results):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n\n spotting_grountruth = list()\n spotting_predictions = list()\n segmentation_predictions = list()\n replay_grountruth = list()\n\n chunk_size = model.chunk_size\n receptive_field = model.receptive_field\n\n model.eval()\n\n def timestamps2long(output_spotting, video_size, chunk_size, receptive_field):\n\n start = 0\n last = False\n receptive_field = receptive_field//2\n\n timestamps_long = torch.zeros([video_size,1], dtype = torch.float, device=output_spotting.device)-1\n\n\n for batch in np.arange(output_spotting.size()[0]):\n\n tmp_timestamps = torch.zeros([chunk_size,1], dtype = torch.float, device=output_spotting.device)-1\n \n tmp_timestamps[torch.floor(output_spotting[batch,0,1]*(chunk_size-1)).type(torch.int) , 0 ] = output_spotting[batch,0,0]\n\n # ------------------------------------------\n # Store the result of the chunk in the video\n # ------------------------------------------\n if video_size <= chunk_size:\n timestamps_long = tmp_timestamps[0:video_size]\n break\n\n # For the first chunk\n if start == 0:\n timestamps_long[0:chunk_size-receptive_field] = tmp_timestamps[0:chunk_size-receptive_field]\n\n # For the last chunk\n elif last:\n timestamps_long[start+receptive_field:start+chunk_size] = tmp_timestamps[receptive_field:]\n break\n\n # For every other chunk\n else:\n timestamps_long[start+receptive_field:start+chunk_size-receptive_field] = tmp_timestamps[receptive_field:chunk_size-receptive_field]\n \n # ---------------\n # Loop Management\n # ---------------\n\n # Update the index\n start += chunk_size - 2 * receptive_field\n # Check if we are at the last index of the game\n if start + chunk_size >= video_size:\n start = video_size - chunk_size \n last = True\n return timestamps_long\n\n def batch2long(output_segmentation, video_size, chunk_size, receptive_field):\n\n start = 0\n last = False\n receptive_field = receptive_field//2\n\n segmentation_long = torch.zeros([video_size,1], dtype = torch.float, device=output_segmentation.device)\n\n\n for batch in np.arange(output_segmentation.size()[0]):\n\n tmp_segmentation = 1-output_segmentation[batch]\n\n\n # ------------------------------------------\n # Store the result of the chunk in the video\n # ------------------------------------------\n\n # For the first chunk\n if start == 0:\n segmentation_long[0:chunk_size-receptive_field] = tmp_segmentation[0:chunk_size-receptive_field]\n\n # For the last chunk\n elif last:\n segmentation_long[start+receptive_field:start+chunk_size] = tmp_segmentation[receptive_field:]\n break\n\n # For every other chunk\n else:\n segmentation_long[start+receptive_field:start+chunk_size-receptive_field] = tmp_segmentation[receptive_field:chunk_size-receptive_field]\n \n # ---------------\n # Loop Management\n # ---------------\n\n # Update the index\n start += chunk_size - 2 * receptive_field\n # Check if we are at the last index of the game\n if start + chunk_size >= video_size:\n start = video_size - chunk_size \n last = True\n return segmentation_long\n\n end = time.time()\n game_list=getListGames(split)\n with tqdm(enumerate(dataloader), total=len(dataloader), ncols=120) as t:\n for i, (feat_half1, feat_half2, replay_half1, replay_half2, label_half1, label_half2, label_replay_half1, label_replay_half2,replay_name_half1,replay_name_half2) in t:\n\n data_time.update(time.time() - end)\n\n replay_half1 = replay_half1.cuda().squeeze(0)\n replay_half2 = replay_half2.cuda().squeeze(0)\n\n feat_half1 = feat_half1.cuda().squeeze(0)\n feat_half2 = feat_half2.cuda().squeeze(0)\n feat_half1=feat_half1.unsqueeze(1)\n feat_half2=feat_half2.unsqueeze(1)\n detection_half1 = list()\n replay_names_half1 = list()\n for replay, label, label_replay, replay_name in zip(replay_half1, label_half1, label_replay_half1,replay_name_half1):\n label = label.float().squeeze(0)\n label_replay = label_replay.float().squeeze(0)\n replay = replay.unsqueeze(0).repeat(feat_half1.shape[0],1,1).unsqueeze(1)\n feat = torch.cat((feat_half1,replay),1)\n output_segmentation_half_1, output_spotting_half_1 = model(feat)\n timestamp_long_half_1 = timestamps2long(output_spotting_half_1.cpu().detach(), label.size()[0], chunk_size, receptive_field)\n segmentation_long_half_1 = batch2long(output_segmentation_half_1.cpu().detach(), label.size()[0], chunk_size, receptive_field)\n detection_half1.append(timestamp_long_half_1)\n \n replay_names_half1.append(replay_name)\n spotting_grountruth.append(label)\n spotting_predictions.append(timestamp_long_half_1)\n segmentation_predictions.append(segmentation_long_half_1)\n replay_grountruth.append(label_replay)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n detection_half2 = list()\n replay_names_half2 = list()\n for replay, label, label_replay, replay_name in zip(replay_half2, label_half2, label_replay_half2, replay_name_half2):\n label = label.float().squeeze(0)\n label_replay = label_replay.float().squeeze(0)\n replay = replay.unsqueeze(0).repeat(feat_half2.shape[0],1,1).unsqueeze(1)\n feat = torch.cat((feat_half2,replay),1)\n output_segmentation_half_2, output_spotting_half_2 = model(feat)\n timestamp_long_half_2 = timestamps2long(output_spotting_half_2.cpu().detach(), label.size()[0], chunk_size, receptive_field)\n segmentation_long_half_2 = batch2long(output_segmentation_half_2.cpu().detach(), label.size()[0], chunk_size, receptive_field)\n detection_half2.append(timestamp_long_half_2)\n \n replay_names_half2.append(replay_name)\n spotting_grountruth.append(label)\n spotting_predictions.append(timestamp_long_half_2)\n segmentation_predictions.append(segmentation_long_half_2)\n replay_grountruth.append(label_replay)\n if save_results:\n game_results_to_json(detection_path,split,detection_half1,detection_half2,replay_names_half1,replay_names_half2,model.framerate,timestamp_long_half_1.shape[0],timestamp_long_half_2.shape[0])\n\n #visualize(spotting_grountruth ,spotting_predictions,segmentation_predictions, replay_grountruth)\n \n if not save_results:\n a_AP = average_mAP(spotting_grountruth, spotting_predictions, model.framerate)\n print(\"a-AP: \", a_AP)\n if save_results:\n results=evaluate(annotation_path,detection_path,\"Detection-replays.json\",split)\n print(\"a_AP: \",results[\"a_AP\"])\n return results[\"a_AP\"]\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count","sub_path":"Task3-ReplayGrounding/SoccerNetv2-ReplayGrounding-CALF/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":14451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"503560117","text":"import os\nimport sys\nfrom PIL import Image, ImageDraw\n\nclass Area:\n def __init__(self,box):\n self.position = (box[0], box[1])\n self.size = (box[2], box[3])\n self.area = box\n\nclass SkinMeta:\n elements =[\n \"head\",\n \"body\",\n \"rightArm\",\n \"leftArm\",\n \"rightLeg\",\n \"leftLeg\",\n \"head2\",\n \"body2\",\n \"rightArm2\",\n \"leftArm2\",\n \"rightLeg2\",\n \"leftLeg2\"\n ]\n degradedElements =[\n \"head\",\n \"body\",\n \"rightArm\",\n \"rightLeg\",\n \"head2\"\n ]\n \n head = Area((0,0,32,16))\n body = Area((16,16,24,16))\n rightArm = Area((40,16,16,16))\n leftArm = Area((32,48,16,16))\n rightLeg = Area((0,16,16,16))\n leftLeg = Area((16,48,16,16))\n \n head2 = Area((32,0,32,16))\n body2 = Area((16,32,24,16))\n rightArm2 = Area((40,32,16,16))\n leftArm2 = Area((48,48,16,16))\n rightLeg2 = Area((0,32,16,16))\n leftLeg2 = Area((0,48,16,16))\n\nclass Skin:\n def __init__(self, image):\n self.loadSkin(image)\n\n \"\"\"\n Merge overlay down.\n \"\"\"\n def mergeDown(self):\n self.body.paste(self.body2, (0,0), self.body2)\n self.rightArm.paste(self.rightArm2, (0,0), self.rightArm2)\n self.leftArm.paste(self.leftArm2, (0,0), self.leftArm2)\n self.rightLeg.paste(self.rightLeg2, (0,0), self.rightLeg2)\n self.leftLeg.paste(self.leftLeg2, (0,0), self.leftLeg2)\n\n \"\"\"\n Check isn't female skin?\n \n :return: boolean\n \"\"\"\n def isFemale(self):\n rightArmImage = self.rightArm\n #x0, y0, x1, y1\n areas=[\n (10,0,11,3),\n (14,4,15,5)\n ]\n for area in areas:\n if(checkTransparentInArea(rightArmImage, area)):\n return True\n return False\n\n \"\"\"\n Get entire image\n \n :return: Pillow.Image\n \"\"\"\n def getOutput(self):\n image = Image.new(\"RGBA\", (64, 64))\n for element in SkinMeta.elements:\n subImage = getattr(self, element)\n position = getattr(SkinMeta, element).position\n image.paste(subImage, position)\n return image\n\n \"\"\"\n Get degraded image, which is v1.7(64*32).\n \n :return: Pillow.Image\n \"\"\"\n def getDegradedOutput(self):\n image = Image.new(\"RGBA\", (64, 32))\n for element in SkinMeta.degradedElements:\n subImage = getattr(self, element)\n position = getattr(SkinMeta, element).position\n image.paste(subImage, position)\n return image\n \n def fixArms(self):\n self.fixRightArm(self.rightArm)\n self.fixRightArm(self.rightArm2)\n self.fixLeftArm(self.leftArm)\n self.fixLeftArm(self.leftArm2)\n\n \"\"\"\n Use skin of left arm to replaced right arm.\n \"\"\"\n def useLeftArm(self):\n missions ={\n 'top': [(4,0), (4,4)], #position, size\n 'bottom': [(8,0), (4,4)],\n 'front':[(4,4), (4,12)], \n 'back': [(12,4), (4,12)],\n 'right':[(0,4), (4,12)], \n 'left': [(8,4), (4,12)]\n }\n\n for mission in missions.values():\n self.copyReserveAndPaste(self.leftArm, self.rightArm, mission[0], mission[1])\n \n self.copyPasteSwitch(self.rightArm, [(0,4), (8,4)], (4,12))\n\n \"\"\"\n Use skin of left leg to replaced left leg.\n \"\"\"\n def useLeftLeg(self):\n missions ={\n 'top': [(4,0), (4,4)], #position, size\n 'bottom': [(8,0), (4,4)],\n 'right':[(0,4), (4,12)], \n 'front':[(4,4), (4,12)], \n 'left': [(8,4), (4,12)],\n 'back': [(12,4), (4,12)]\n }\n for mission in missions.values():\n self.copyReserveAndPaste(self.leftLeg, self.rightLeg, mission[0], mission[1])\n \n self.copyPasteSwitch(self.rightLeg, [(0,4), (8,4)], (4,12))\n\n \"\"\"\n ========Private stuff========\n \"\"\"\n\n \"\"\"\n \n \"\"\"\n def copyReserveAndPaste(self, sourceImage, targetImage, position, size):\n image = self.cropImage(sourceImage, position, size).transpose(Image.FLIP_LEFT_RIGHT)\n targetImage.paste(image, position)\n \n def copyPaste(self, sourceImage, targetImage, position, size):\n image = self.cropImage(sourceImage, position, size)\n targetImage.paste(image, position)\n \n def copyPasteSwitch(self, image, positions, size):\n image1 = self.cropImage(image, positions[0], size)\n image2 = self.cropImage(image, positions[1], size)\n image.paste(image2, positions[0])\n image.paste(image1, positions[1])\n\n\n \"\"\"\n The female skin has lost 1 pixel of arm,\n and older skin do not support it.\n \n :param rightArmImage: Pillow.Image\n \"\"\"\n def fixRightArm(self, rightArmImage):\n imageDraw = ImageDraw.Draw(rightArmImage)\n #fix yaw\n handImage = self.cropImage(rightArmImage, (7,0),(3,4))\n sideArmImage = self.cropImage(rightArmImage, (7,4),(7,12))\n imageDraw.rectangle((7,0,15,15),(0,0,0,0))#clean right side\n rightArmImage.paste(handImage,(8,0))\n rightArmImage.paste(sideArmImage,(9,4))\n #fill blank\n missions = [\n [(6,0),(1,16),(7,0)],#position, size, target position\n [(10,0),(1,4),(11,0)],\n [(9,4),(1,12),(8,4)]\n ]\n for mission in missions:\n fill = self.cropImage(rightArmImage, mission[0],mission[1])\n rightArmImage.paste(fill,mission[2])\n \n \"\"\"\n The female skin has lost 1 pixel of arm,\n and older skin do not support it.\n \n :param leftArmImage: Pillow.Image\n \"\"\"\n def fixLeftArm(self, leftArmImage):\n #move hand\n self.cutAndMoveImage(leftArmImage, (7,0), (3,4), (9,0))\n #move side arm1\n self.cutAndMoveImage(leftArmImage, (7,4), (7,12), (8,4))\n #move shoulder and side arm\n self.cutAndMoveImage(leftArmImage, (4,0), (3,16), (5,0))\n \n #fill blank\n missions = [\n [(5,0),(1,16),(4,0)],#position, size, target position\n [(9,0),(1,4),(8,0)],\n [(14,4),(1,12),(15,4)]\n ]\n for mission in missions:\n fill = self.cropImage(leftArmImage, mission[0], mission[1])\n leftArmImage.paste(fill,mission[2])\n\n \"\"\"\n Cut image down and move it to another position\n \n :param image: Pillow.Image\n :param position: tuple which has two element.\n :param size: tuple which has two element.\n :param target: tuple which has two element.\n \"\"\"\n def cutAndMoveImage(self, image, position, size, target):\n imageDraw = ImageDraw.Draw(image)\n cropImage = self.cropImage(image, position, size)\n position2 = (position[0]+size[0]-1,position[1]+size[1]-1)\n imageDraw.rectangle(position + position2,(0,0,0,0)) #clean\n image.paste(cropImage, target)\n \n \"\"\"\n Split an image as different part of skin.\n \n :param image: Pillow.Image\n \"\"\"\n def loadSkin(self, image):\n for element in SkinMeta.elements:\n position = getattr(SkinMeta, element).position\n size = getattr(SkinMeta, element).size\n subImage = self.cropImage(image, position, size)\n setattr(self, element, subImage)\n \n \"\"\"\n Crop image by location and size.\n \n :param image: Pillow.Image\n :param location: tuple which has two element.\n :param size: tuple which has two element.\n \"\"\"\n def cropImage(self, image, location, size):\n area = [\n location[0],\n location[1],\n location[0]+size[0],\n location[1]+size[1],\n ]\n return image.crop(area)\n\n \"\"\"\n Checking all pixel are transparent in area.\n \n :param image: Pillow.Image\n :param box: tuple describe rectangular region.\n \"\"\"\n def checkTransparentInArea(self, image, box):\n for x in range(box[0],box[2]):\n for y in range(box[1],box[3]):\n r,g,b,a = image.getpixel((x,y));\n if(a==0):\n return True\n return False\n","sub_path":"Skin.py","file_name":"Skin.py","file_ext":"py","file_size_in_byte":8099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"328083677","text":"from django.db import models\n\n# Create your models here.\nclass Status(models.Model):\n month_choices = [\n ('Jan', 'Jan'),\n ('Feb', 'Feb'),\n ('Mar', 'Mar'),\n ('Apr', 'Apr'),\n ('May', 'May'),\n ('Jun', 'Jun'),\n ('July', 'July'),\n ('Aug', 'Aug'),\n ('Sep', 'Sep'),\n ('Oct', 'Oct'),\n ('Nov', 'Nov'),\n ('Dec', 'Dec')\n ]\n\n lead_type_choices = [\n ('New Lead', 'New Lead'),\n ('Existing Lead', 'Existing Lead')\n ]\n\n lead_priority_choices = [\n ('High', 'High'),\n ('Medium', 'Medium'),\n ('Low', 'Low')\n ]\n\n lead_source_choices = [\n ('MARKET PLACE', 'MARKET PLACE'),\n ('SEO', 'SEO'),\n ('INSIDE SALES', 'INSIDE SALES'),\n ('DIRECT', 'DIRECT'),\n ('SMO', 'SMO')\n ]\n\n marketplace_subsource_choices = [\n ('UPWORK', 'UPWORK'),\n ('FREELANCER', 'FREELANCER'),\n ('PPH', 'PPH'),\n ('GURU', 'GURU'),\n ('OTHERS', 'OTHERS')\n ]\n\n country_choices = [\n ('Afghanistan', 'Afghanistan'),\n ('Albania', 'Albania'),\n ('Algeria', 'Algeria'),\n ('American Samoa', 'American Samoa'),\n ('Andorra', 'Andorra'),\n ('Angola', 'Angola'),\n ('Anguilla', 'Anguilla'),\n ('Antarctica', 'Antarctica'),\n ('Antigua And Barbuda', 'Antigua And Barbuda'),\n ('Argentina', 'Argentina'),\n ('Armenia', 'Armenia'),\n ('Aruba', 'Aruba'),\n ('Australia', 'Australia'),\n ('Austria', 'Austria'),\n ('Azerbaijan', 'Azerbaijan'),\n ('Bahrain', 'Bahrain'),\n ('Bangkok', 'Bangkok'),\n ('Bangladesh', 'Bangladesh'),\n ('Barbados', 'Barbados'),\n ('Belarus', 'Belarus'),\n ('Belgium', 'Belgium'),\n ('Belize', 'Benin'),\n ('Botswana', 'Botswana'),\n ('Bouvet Island', 'Bouvet Island'),\n ('Brazil', 'Brazil'),\n ('British Indian Ocean Territory', 'British Indian Ocean Territory'),\n ('Bulgaria', 'Bulgaria'),\n ('Burkina Faso', 'Burkina Faso'),\n ('Burundi', 'Burundi'),\n ('Cambodia', 'Cambodia'),\n ('Cameroon', 'Cameroon'),\n ('Canada', 'Canada'),\n ('Cape Verde', 'Cape Verde'),\n ('Cayman Islands', 'Cayman Islands'),\n ('Chile', 'Chile'),\n ('China', 'China'),\n ('Colombia', 'Colombia'),\n ('Costa Rica', 'Costa Rica'),\n ('Cote DIvoire (Ivory Coast)', \"Cote D'Ivoire (Ivory Coast)\"),\n ('Croatia (Hrvatska)', 'Croatia (Hrvatska)'),\n ('Cyprus', 'Cyprus'),\n ('Czech Republic', 'Czech Republic'),\n ('Democratic Republic Of The Congo', 'Democratic Republic Of The Congo'),\n ('Denmark', 'Denmark'),\n ('Ecuador', 'Ecuador'),\n ('Egypt', 'Egypt'),\n ('Fiji Islands', 'Fiji Islands'),\n ('Finland', 'Finland'),\n ('France', 'France'),\n ('French Guiana', 'French Guiana'),\n ('Gabon', 'Gabon'),\n ('Georgia', 'Georgia'),\n ('Germany', 'Germany'),\n ('Ghana', 'Ghana'),\n ('Gibraltar', 'Gibraltar'),\n ('Greece', 'Greece'),\n ('Greenland', 'Greenland'),\n ('Grenada', 'Grenada'),\n ('Guernsey & Alderney', 'Guernsey and Alderney'),\n ('Guinea-Bissau', 'Guinea-Bissau'),\n ('Haiti', 'Haiti'),\n ('Hong Kong', 'Hong Kong'),\n ('Hungary', 'Hungary'),\n ('Iceland', 'Iceland'),\n ('India', 'India'),\n ('Indonesia', 'Indonesia'),\n ('Iran', 'Iran'),\n ('Iraq', 'Iraq'),\n ('Ireland', 'Ireland'),\n ('Isle of Man', 'Isle of Man'),\n ('Israel', 'Israel'),\n ('Italy', 'Italy'),\n ('Jamaica', 'Jamaica'),\n ('Japan', 'Japan'),\n ('Jordan', 'Jordan'),\n ('Kazakhstan', 'Kazakhstan'),\n ('Kenya', 'Kenya'),\n ('Kiribati', 'Kiribati'),\n ('Kuwait', 'Kuwait'),\n ('Kyrgyzstan', 'Kyrgyzstan'),\n ('Laos', 'Laos'),\n ('Latvia', 'Latvia'),\n ('Lebanon', 'Lebanon'),\n ('Lesotho', 'Lesotho'),\n ('Liberia', 'Liberia'),\n ('Liechtenstein', 'Liechtenstein'),\n ('Lithuania', 'Lithuania'),\n ('Luxembourg', 'Luxembourg'),\n ('Macau S.A.R.', 'Macau S.A.R.'),\n ('Macedonia', 'Macedonia'),\n ('Madagascar', 'Madagascar'),\n ('Malawi', 'Malawi'),\n ('Malaysia', 'Malaysia'),\n ('Mali', 'Mali'),\n ('Malta', 'Malta'),\n ('Mauritania', 'Mauritania'),\n ('Mayotte', 'Mayotte'),\n ('Mexico', 'Mexico'),\n ('Moldova', 'Moldova'),\n ('Mongolia', 'Mongolia'), \n ('Morocco', 'Morocco'),\n ('Myanmar', 'Myanmar'),\n ('Namibia', 'Namibia'),\n ('Nauru', 'Nauru'),\n ('Nepal', 'Nepal'),\n ('Netherlands', 'Netherlands'),\n ('Netherlands Antilles', 'Netherlands Antilles'),\n ('New Zealand', 'New Zealand'),\n ('Niger', 'Niger'),\n ('Nigeria', 'Nigeria'),\n ('Niue', 'Niue'), \n ('Norfolk Island', 'Norfolk Island'),\n ('North Korea', 'North Korea'),\n ('Norway', 'Norway'),\n ('Oman', 'Oman'),\n ('Others', 'Others'),\n ('Pakistan', 'Pakistan'),\n ('Palau', 'Palau'),\n ('Palestinian Territory Occupied', 'Palestinian Territory Occupied'),\n ('Panama', 'Panama'),\n ('Peru', 'Peru'),\n ('Philippines', 'Philippines'), \n ('Pitcairn Island', 'Pitcairn Island'),\n ('Poland', 'Poland'),\n ('Portugal', 'Portugal'),\n ('Qatar', 'Qatar'),\n ('Republic Of The Congo', 'Republic Of The Congo'),\n ('Romania', 'Romania'),\n ('Russia', 'Russia'),\n ('Rwanda', 'Rwanda'),\n ('Saint Helena', 'Saint Helena'),\n ('Saint Lucia', 'Saint Lucia'),\n ('Saint Vincent And The Grenadines', 'Saint Vincent And The Grenadines'), \n ('Samoa', 'Samoa'),\n ('Saudi Arabia', 'Saudi Arabia'),\n ('Serbia', 'Serbia'),\n ('Seychelles', 'Seychelles'),\n ('Singapore', 'Singapore'),\n ('Slovakia', 'Slovakia'),\n ('South Africa', 'South Africa'),\n ('South Korea', 'South Korea'),\n ('Spain', 'Spain'),\n ('Sri Lanka', 'Sri Lanka'),\n ('Swaziland', 'Swaziland'), \n ('Sweden', 'Sweden'),\n ('Switzerland', 'Switzerland'),\n ('Taiwan', 'Taiwan'),\n ('Tanzania', 'Tanzania'),\n ('Thailand', 'Thailand'),\n ('The Bahamas', 'The Bahamas'),\n ('Trinidad And Tobago', 'Trinidad And Tobago'),\n ('Tunisia', 'Tunisia'),\n ('Turkey', 'Turkey'),\n ('Turkmenistan', 'Turkmenistan'),\n ('Turks And Caicos Islands', 'Turks And Caicos Islands'), \n ('Uganda', 'Uganda'),\n ('Ukraine', 'Ukraine'),\n ('United Arab Emirates', 'United Arab Emirates'),\n ('United Kingdom', 'United Kingdom'),\n ('United States', 'United States'),\n ('Uruguay', 'Uruguay'),\n ('Venezuela', 'Venezuela'),\n ('Vietnam', 'Vietnam'),\n ('Zambia', 'Zambia'),\n ('Zimbabwe', 'Zimbabwe')\n ]\n\n company_size_choices = [\n ('Small company', 'Small company'),\n ('Midsize company', 'Midsize company'),\n ('Large company', 'Large company'),\n ('Multinational company', 'Multinational company')\n ]\n\n\n platform_choices = [\n ('MOBILE APP + BACKEND', 'MOBILE APP + BACKEND'),\n ('IOT', 'IOT'),\n ('GAME', 'GAME'),\n ('MOBILE APP', 'MOBILE APP'),\n ('Open Backend', 'Open Backend'),\n ('Blockchain- ICO Launch', 'Blockchain- ICO Launch'),\n ('Blockchain- Crypto Exchange', 'Blockchain- Crypto Exchange'),\n ('WEB', 'WEB'),\n ('BOTS', 'BOTS'),\n ('Blockchain- ICO Marketing', 'Blockchain- ICO Marketing'),\n ('Native Mobile', 'Native Mobile'),\n ('Blockchain- Crypto Wallet', 'Blockchain- Crypto Wallet'),\n ('Blockchain- DApp', 'Blockchain- DApp'),\n ('Blockchain- Smart Contract Development & Audit', 'Blockchain- Smart Contract Development and Audit'),\n ('DIGITAL MARKETING', 'DIGITAL MARKETING'),\n ('Others', 'Others')\n ]\n\n\n\n Month = models.CharField(max_length=100, choices=month_choices)\n Lead_Type = models.CharField(max_length=100, choices=lead_type_choices)\n Leads_Priority = models.CharField(max_length=100, choices=lead_priority_choices)\n Lead_Source = models.CharField(max_length=100, choices=lead_source_choices)\n Market_Place_Subsource = models.CharField(max_length=100, choices=marketplace_subsource_choices)\n Country = models.CharField(max_length=100, choices=country_choices)\n Business_Potential = models.IntegerField()\n Company_Size = models.CharField(max_length=100, choices=company_size_choices)\n Platform = models.CharField(max_length=100, choices=platform_choices)\n\n\n def __str__(self):\n return self.platform","sub_path":"Machine_Learning_Deployment/sales_classifier/model_api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"425605613","text":"import numpy as np\nimport pandas as pd\n\n\ndef largest_species(fname: str) -> pd.Series:\n \"\"\" Return largest column by year from the text file \"\"\"\n\n data = pd.read_csv(fname, index_col=0, sep='\\t', dtype=np.int64)\n return data.idxmax(axis=1)\n\n\ndef lynxes_when_hares(fname: str) -> pd.Series:\n \"\"\" Returns the number of lynxes when hares > fox \"\"\"\n\n data = pd.read_csv(fname, index_col=0, sep='\\t', dtype=np.int64)\n return data.loc[data['hare'] > data['fox'], 'lynx']\n\n\ndef mean_animals(fname: str) -> pd.DataFrame:\n \"\"\" Add a fourth column with the normalized mean number of animals in each year \"\"\"\n data = pd.read_csv(fname, index_col=0, sep='\\t', dtype=np.int64)\n # Could use the .assign() method as well\n data['mean_animals'] = data.sum(axis=1)\n data['mean_animals'] /= data['mean_animals'].max()\n return data\n\n\nif __name__ == '__main__':\n fname = 'populations.txt'\n a = largest_species(fname)\n b = lynxes_when_hares(fname)\n d = mean_animals(fname)\n","sub_path":"solutions_grades/assignment4/hw4_q2.py","file_name":"hw4_q2.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"410256939","text":"from django.db import models\n\n\nclass Receita(models.Model):\n id = models.IntegerField(primary_key=True, null=False, unique=True)\n nome = models.CharField(max_length=100)\n valores = models.DecimalField(max_digits=10, decimal_places=2)\n\n @staticmethod\n def calcular(valor):\n result = valor * 0.2\n\n return result\n","sub_path":"Python/3°_Semestre_de_ADS 2021.1/revisao/PAO_DURO/polls/models/Receita.py","file_name":"Receita.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"276657218","text":"import bpy, bmesh, math, mathutils\n\ndef line(p1, p2):\n A = (p1[1] - p2[1])\n B = (p2[0] - p1[0])\n C = (p1[0]*p2[1] - p2[0]*p1[1])\n return A, B, -C\n\ndef intersection(L1, L2):\n D = L1[0] * L2[1] - L1[1] * L2[0]\n Dx = L1[2] * L2[1] - L1[1] * L2[2]\n Dy = L1[0] * L2[2] - L1[2] * L2[0]\n if D != 0:\n x = Dx / D\n y = Dy / D\n return x,y\n else:\n print(\"false\" * 8)\n return False\n\ndef intersection3(L1, L2):\n D = L1[0] * L2[1] - L1[1] * L2[0]\n Dx = L1[2] * L2[1] - L1[1] * L2[2]\n Dy = L1[0] * L2[2] - L1[2] * L2[0]\n if D != 0:\n x = Dx / D\n y = Dy / D\n return x,y,0\n else:\n print(\"false\" * 8)\n return False\n\ndef dis_v2(x, y):\n pass\n return math.sqrt(x*x + y*y)\n\ndef dis_v3(a,b):\n x = (mathutils.Vector(a) - mathutils.Vector(b)).x\n y = (mathutils.Vector(a) - mathutils.Vector(b)).y\n z = (mathutils.Vector(a) - mathutils.Vector(b)).z\n return math.sqrt(x*x + y*y + z*z)\n\nhos_radius = 8\nhos_radius = 2\n\nhos_windows = 3\nhos_min_height = 3\nhos_max_height = 4\n\n\nprint(\"\\n\" * 12)\nprint(\"Started...\")\n\n\nobj = bpy.context.active_object\n\nnew_me = bpy.data.meshes.new(\"mesh_houses\")\nnew_ob = bpy.data.objects.new(\"houses\", new_me)\nscene = bpy.context.scene\n\nscene.objects.link(new_ob)\nscene.objects.active = new_ob\nnew_ob.select = True\n\nnew_me = bpy.context.object.data\nnew_bm = bmesh.new()\n\n\nif obj.mode == 'EDIT':\n # modo edit y tal\n bm = bmesh.from_edit_mesh(obj.data)\n verts = [vert.co for vert in bm.verts]\n\nelse:\n # pa'l modo orbjetoh\n co_verts = [vert.co for vert in obj.data.vertices]\n verts = [vert for vert in obj.data.vertices]\n edges = [vert for vert in obj.data.edges]\n faces = [vert for vert in obj.data.polygons]\n\nindex_vertex = [vert.index for vert in verts]\nplain_edges = [edge for edge in edges]\n\ndicti = {}\nfor i in zip(index_vertex, co_verts):\n dicti[i[0]] = i[1]\n\n# paso 1, encontrar los puntos medios de las aristas.\nprint(u\"creando puntos medios de las aristas...\")\nlista_edges_ari = []\nfor i in plain_edges:\n #print (i.index, i.vertices, i.vertices[0], i.vertices[1])\n #print (dicti[i.vertices[0]], dicti[i.vertices[1]])\n #print ((dicti[i.vertices[1]] - dicti[i.vertices[0]]) / 2.0 + dicti[i.vertices[0]])\n\n\n x0 = -(dicti[i.vertices[1]] - dicti[i.vertices[0]]).x\n y0 = -(dicti[i.vertices[1]] - dicti[i.vertices[0]]).y\n z0 = -(dicti[i.vertices[1]] - dicti[i.vertices[0]]).z\n\n #print (dicti[i.vertices[0]], dicti[i.vertices[1]], x0, y0)\n\n # ax = 0.0\n # ay = 0.0\n # az = math.atan2(math.sqrt(x0**2+y0**2),z0);\n\n r = math.sqrt(x0*x0 + y0*y0 + z0*z0)\n #t = math.atan(y0/x0) * 57.2958\n t = math.atan2(y0,x0) # * 57.2958 + 90\n\n #if (t<0): t = - t\n\n p = math.acos(z0/r) # * 57.2958\n\n #print(t)\n\n lista_edges_ari.append([i, ((dicti[i.vertices[1]] - dicti[i.vertices[0]]) / 2.0 + dicti[i.vertices[0]]), t])\n\n\n#print(\"...\\n\", lista_edges_ari)\n\n\nlist_of_sepparated_vertex = []\nprint(\"creando vértices laterales\")\nfor n, j in enumerate(lista_edges_ari):\n #print(\"Adding walls from...\")\n #print(j)\n\n #x = r * sin(p) * cos(t)\n #y = r * sin(p) * sin(t)\n #z = r * cos(p)\n\n x = hos_radius * math.cos(j[2] + 3.1415926535 * 0.5)\n y = hos_radius * math.sin(j[2] + 3.1415926535 * 0.5)\n\n tmp_vec = mathutils.Vector((x, y, 0))\n\n #new_bm.verts.new((j[1]) + tmp_vec)\n #j.append((j[1]) + tmp_vec)\n #new_bm.verts.new((j[1]) - tmp_vec)\n #j.append((j[1]) - tmp_vec)\n\n tmp_a = new_bm.verts.new((j[1]) + tmp_vec)\n tmp_b = new_bm.verts.new((j[1]) - tmp_vec)\n\n j.append(tmp_a)\n j.append(tmp_b)\n\n\n\n#print(\"...\\n\")\n#for k in lista_edges_ari: print(k)\n\n# \n# lista_edges_ari\n# [edge_reference, punto_medio, ángulo, punto_0, punto1]\n#\n\n\nprint(u\"uniendo vértices para crear grupos de edges\")\nlista_esquinas = []\nfor n, grupo_datos in enumerate(lista_edges_ari):\n\n #porque los grupos de edges van por parejas...\n if n < len(lista_edges_ari) - 1:\n print(\"ronda...\", n)\n\n angle = grupo_datos[2]\n gx = grupo_datos[3].co.x\n gy = grupo_datos[3].co.y\n ñx = grupo_datos[4].co.x\n ñy = grupo_datos[4].co.y\n\n bangle = lista_edges_ari[n+1][2]\n bgx = lista_edges_ari[n+1][3].co.x\n bgy = lista_edges_ari[n+1][3].co.y\n bñx = lista_edges_ari[n+1][4].co.x\n bñy = lista_edges_ari[n+1][4].co.y\n\n linea_0 = line([gx+99*math.cos(angle), gy+99*math.sin(angle)],[gx-99*math.cos(angle), gy-99*math.sin(angle)])\n linea_1 = line([ñx+99*math.cos(angle), ñy+99*math.sin(angle)],[ñx-99*math.cos(angle), ñy-99*math.sin(angle)])\n\n blinea_0 = line([bgx+99*math.cos(bangle), bgy+99*math.sin(bangle)],[bgx-99*math.cos(bangle), bgy-99*math.sin(bangle)])\n blinea_1 = line([bñx+99*math.cos(bangle), bñy+99*math.sin(bangle)],[bñx-99*math.cos(bangle), bñy-99*math.sin(bangle)])\n\n R1 = intersection3(linea_0, blinea_0)\n R2 = intersection3(linea_0, blinea_1)\n R1b = intersection3(linea_1, blinea_0)\n R2b = intersection3(linea_1, blinea_1)\n\n tmp_list = []\n\n tmp_list.append([dis_v3(linea_0, R1) + dis_v3(blinea_0, R1),R1] )\n tmp_list.append([dis_v3(linea_0, R2) + dis_v3(blinea_1, R2),R2] )\n tmp_list.append([dis_v3(linea_1, R1b) + dis_v3(blinea_0, R1b),R1b])\n tmp_list.append([dis_v3(linea_1, R2b) + dis_v3(blinea_1, R2b),R2b])\n\n angulo_medio = angle / 2.0 + bangle / 2.0 + 3.1415926535 / 2.0\n v_medio = grupo_datos[0].vertices[0]\n\n #print(grupo_datos[0])\n #print(dicti[grupo_datos[0].vertices[0]])\n #print(dicti[grupo_datos[0].vertices[1]])\n\n #print(\"\\n\")\n #for ih in tmp_list:\n # print(ih)\n\n if (dis_v3(linea_0, R1) + dis_v3(blinea_0, R1) < dis_v3(linea_0, R2) + dis_v3(blinea_1, R2)):\n v_min = R2\n v_max = R1\n else:\n v_min = R2\n v_max = R1\n\n if (dis_v3(linea_1, R1b) + dis_v3(blinea_0, R1b) < dis_v3(linea_1, R2b) + dis_v3(blinea_1, R2b)):\n vb_min = R2b\n vb_max = R1b\n else:\n vb_min = R2b\n vb_max = R1b\n\n if (v_min < vb_min):\n final_min = v_min\n final_max = vb_max\n\n else:\n final_min = vb_min\n final_max = v_max\n\n tmp_a = new_bm.verts.new((final_min[0], final_min[1], 0))\n tmp_b = new_bm.verts.new((final_max[0], final_max[1], 0))\n\n lista_esquinas.append([tmp_a, tmp_b])\n\n\n\n#unimos todos los vértices y ese tipo de cosas.\nprint(u\"uniendo vértices para crear grupos de edges\")\nlista_edges_creada = []\nfor n, i in enumerate(lista_edges_ari):\n\n lista_edges_creada_buffer = []\n\n if n < len(lista_edges_ari) - 1:\n\n vertex_a_0 = lista_edges_ari[n][3]\n vertex_a_1 = lista_edges_ari[n][4]\n\n vertex_w_0 = lista_esquinas[n][0]\n vertex_w_1 = lista_esquinas[n][1]\n\n vertex_b_0 = lista_edges_ari[n+1][3]\n vertex_b_1 = lista_edges_ari[n+1][4]\n\n #new_bm.edges.new((vertex_a_0, vertex_a_1))\n\n\n tmp_list = []\n\n #print(\"\\n\" * 2)\n #print(dis_v3(vertex_a_0.co, vertex_w_0.co) + dis_v3(vertex_w_0.co, vertex_b_0.co))\n #print(dis_v3(vertex_a_0.co, vertex_w_0.co) + dis_v3(vertex_w_0.co, vertex_b_1.co))\n\n tmp_list.append( [dis_v3(vertex_a_0.co, vertex_w_0.co) + dis_v3(vertex_w_0.co, vertex_b_0.co), vertex_a_0, vertex_w_0, vertex_b_0] )\n tmp_list.append( [dis_v3(vertex_a_0.co, vertex_w_0.co) + dis_v3(vertex_w_0.co, vertex_b_1.co), vertex_a_0, vertex_w_0, vertex_b_1] )\n tmp_list.append( [dis_v3(vertex_a_0.co, vertex_w_1.co) + dis_v3(vertex_w_1.co, vertex_b_0.co), vertex_a_0, vertex_w_1, vertex_b_0] )\n tmp_list.append( [dis_v3(vertex_a_0.co, vertex_w_1.co) + dis_v3(vertex_w_1.co, vertex_b_1.co), vertex_a_0, vertex_w_1, vertex_b_1] )\n tmp_list.append( [dis_v3(vertex_a_1.co, vertex_w_0.co) + dis_v3(vertex_w_0.co, vertex_b_0.co), vertex_a_1, vertex_w_0, vertex_b_0] )\n tmp_list.append( [dis_v3(vertex_a_1.co, vertex_w_0.co) + dis_v3(vertex_w_0.co, vertex_b_1.co), vertex_a_1, vertex_w_0, vertex_b_1] )\n tmp_list.append( [dis_v3(vertex_a_1.co, vertex_w_1.co) + dis_v3(vertex_w_1.co, vertex_b_0.co), vertex_a_1, vertex_w_1, vertex_b_0] )\n tmp_list.append( [dis_v3(vertex_a_1.co, vertex_w_1.co) + dis_v3(vertex_w_1.co, vertex_b_1.co), vertex_a_1, vertex_w_1, vertex_b_1] )\n\n #for iusd in tmp_list:print(iusd)\n\n #print(\"---> \",dis_v3((2.0,-3.0, 0), (2.0,-5.17157, 0)) + dis_v3((2.0,-5.17157, 0), (1.08579,-9.91421, 0))) \n #print(\"---> \",dis_v3((2.0,-3.0, 0), (2.0,-5.17157, 0)) + dis_v3((2.0,-5.17157, 0), (3.91421,-7.08579, 0))) \n\n tmp_list.sort(key = lambda x: x[0])\n\n #print(\"\\n\")\n #for iusd in tmp_list:print(iusd[0], iusd[1].co, iusd[2].co, iusd[3].co)\n\n #print(tmp_list[0])\n #print(tmp_list[-1])\n #new_bm.update()\n\n #print(tmp_list[0])\n #print(tmp_list[-1])\n\n to_add_0 = new_bm.edges.new((tmp_list[0][1], tmp_list[0][2]))\n to_add_1 = new_bm.edges.new((tmp_list[0][2], tmp_list[0][3]))\n\n if (tmp_list[0][1] == vertex_a_0):\n a = vertex_a_1\n else:\n a = vertex_a_0\n\n if (tmp_list[0][2] != vertex_b_0):\n b = vertex_b_1\n else:\n b = vertex_b_0\n\n if (tmp_list[0][3] == vertex_w_0):\n w = vertex_w_1\n else:\n w = vertex_w_0\n\n to_add_2 = new_bm.edges.new((a, w))\n to_add_3 = new_bm.edges.new((w, b))\n\n lista_edges_creada_buffer.append(to_add_0)\n lista_edges_creada_buffer.append(to_add_1)\n lista_edges_creada_buffer.append(to_add_2)\n lista_edges_creada_buffer.append(to_add_3)\n\n lista_edges_creada.append(lista_edges_creada_buffer)\n\n\n #new_bm.edges.new((tmp_list[-1][1], tmp_list[-1][2]))\n #new_bm.edges.new((tmp_list[-1][2], tmp_list[-1][3]))\n\n #new_bm.edges.new((vertex_a_0, vertex_a_1))\n #new_bm.edges.new((vertex_b_0, vertex_b_1))\n\n #if (dis_v3(vertex_a_0, vertex_w_0) + dis_v3(vertex_w_0, vertex_b_0) < dis_v3(linea_0, R2) + dis_v3(blinea_1, R2)):\n # new_bm.edges.new((vertex_a_0, vertex_w_0))\n # new_bm.edges.new((vertex_w_0, vertex_b_0))\n #else:\n # new_bm.edges.new((vertex_a_0, vertex_w_0))\n # new_bm.edges.new((vertex_w_0, vertex_b_0))\n\n\n\n #new_bm.edges.new((vertex_a_1, vertex_w_1))\n #new_bm.edges.new((vertex_w_1, vertex_b_1)) \n\n #new_bm.update()\n\n #else:\n #\n # vertex_a_0 = lista_edges_ari[n][3]\n # vertex_a_1 = lista_edges_ari[n][4]\n #\n # new_bm.edges.new((vertex_a_0, vertex_a_1))\n\n #esto\n\n\nfor iuha in lista_edges_creada:\n print(iuha)\n\nprint(u\"we add the connecting edges...\")\ntmp_list = []\nfor n, i in enumerate(lista_edges_ari):\n vertex_a_0 = lista_edges_ari[n][3]\n vertex_a_1 = lista_edges_ari[n][4]\n edge_sel = new_bm.edges.new((vertex_a_0, vertex_a_1))\n tmp_list.append(edge_sel)\n\n\nprint(len(lista_edges_ari))\nprint(len(lista_edges_creada))\n\nfor n, iuy in enumerate(lista_edges_creada):\n iuy.append(tmp_list[n+0])\n iuy.append(tmp_list[n+1])\n\nfor iuha in lista_edges_creada:\n print(iuha)\n\n\nlista_vertices_casa = []\nprint(u\"Creando listas de vértices...\")\nfor sub_lista_segmento in lista_edges_creada:\n tmp_list = []\n for segmento in sub_lista_segmento:\n\n if not segmento.verts[0] in tmp_list:\n tmp_list.append(segmento.verts[0])\n\n if not segmento.verts[1] in tmp_list:\n tmp_list.append(segmento.verts[1])\n\n lista_vertices_casa.append(tmp_list)\n\n#for n, sub_lista_segmento in enumerate(lista_edges_creada):\n# for segmento in sub_lista_segmento:\n# sub_lista_segmento.append(segmento.verts[1])\n# #lista_vertices_casa.append(tmp_list)\n\nprint(\"lista vertices...\")\nfor iuhb in lista_vertices_casa:\n for v in iuhb:\n print(type(v), v.index, v.co)\n print(\" >\")\n\n\nprint(\"Creando caras...\")\nlista_caras_casa = []\nfor grupo_vertices in lista_vertices_casa:\n\n buffer_caras_casa = []\n\n # lista_caras_casa.append(new_bm.faces.new(tuple(grupo_vertices[0:3])) )\n # lista_caras_casa.append(new_bm.faces.new(tuple(grupo_vertices[3:])) )\n\n #lista_caras_casa.append(new_bm.faces.new( (grupo_vertices[0], grupo_vertices[1], grupo_vertices[2]) ) )\n #lista_caras_casa.append(new_bm.faces.new( (grupo_vertices[2], grupo_vertices[5], grupo_vertices[0]) ) )\n #lista_caras_casa.append(new_bm.faces.new( (grupo_vertices[2], grupo_vertices[3], grupo_vertices[4]) ) )\n buffer_caras_casa.append(new_bm.faces.new( (grupo_vertices[2], grupo_vertices[4], grupo_vertices[5]) ) )\n buffer_caras_casa.append(new_bm.faces.new( (grupo_vertices[2], grupo_vertices[4], grupo_vertices[1]) ) )\n buffer_caras_casa.append(new_bm.faces.new( (grupo_vertices[4], grupo_vertices[3], grupo_vertices[1]) ) )\n buffer_caras_casa.append(new_bm.faces.new( (grupo_vertices[0], grupo_vertices[3], grupo_vertices[1]) ) )\n\n lista_caras_casa.append(buffer_caras_casa)\n#new_me.normals_make_consistent()\n\nnew_bm.to_mesh(new_me)\n\nbpy.ops.object.mode_set(mode='EDIT')\nbpy.ops.mesh.select_all(action='SELECT')\n\nbpy.ops.mesh.normals_make_consistent(inside=False)\n\nbpy.ops.object.editmode_toggle()\n#new_me.normals_make_consistent()\n\nnew_bm.free()\n","sub_path":"versalles_paris_generator.py","file_name":"versalles_paris_generator.py","file_ext":"py","file_size_in_byte":13443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"349073701","text":"# Copyright © 2014-2015 ISIS Rutherford Appleton Laboratory, NScD\n# Oak Ridge National Laboratory & European Spallation Source\n#\n# This file is part of Mantid.\n# Mantid 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# Mantid is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# File change history is stored at: .\n# Code Documentation is available at: \n\nimport numpy as np\n\n# The code of the 'Wavelet-Fourier' stripe removal method is heavily based on\n# the implementation of this method in tomopy\n# The original code from Tomopy is:\n# #########################################################################\n# Copyright (c) 2015, UChicago Argonne, LLC. All rights reserved. #\n# #\n# Copyright 2015. UChicago Argonne, LLC. This software was produced #\n# under U.S. Government contract DE-AC02-06CH11357 for Argonne National #\n# Laboratory (ANL), which is operated by UChicago Argonne, LLC for the #\n# U.S. Department of Energy. The U.S. Government has rights to use, #\n# reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR #\n# UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR #\n# ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is #\n# modified to produce derivative works, such modified software should #\n# be clearly marked, so as not to confuse it with the version available #\n# from ANL. #\n# #\n# Additionally, redistribution and use in source and binary forms, with #\n# or without modification, are permitted provided that the following #\n# conditions are met: #\n# #\n# * Redistributions of source code must retain the above copyright #\n# notice, this list of conditions and the following disclaimer. #\n# #\n# * Redistributions in binary form must reproduce the above copyright #\n# notice, this list of conditions and the following disclaimer in #\n# the documentation and/or other materials provided with the #\n# distribution. #\n# #\n# * Neither the name of UChicago Argonne, LLC, Argonne National #\n# Laboratory, ANL, the U.S. Government, nor the names of its #\n# contributors may be used to endorse or promote products derived #\n# from this software without specific prior written permission. #\n# #\n# THIS SOFTWARE IS PROVIDED BY UChicago Argonne, LLC AND CONTRIBUTORS #\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS #\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UChicago #\n# Argonne, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, #\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, #\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER #\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT #\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN #\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #\n# POSSIBILITY OF SUCH DAMAGE. #\n# #########################################################################\n\ndef remove_sino_stripes_rings_wf(data_vol, wv_levels, wavelet_name='db5', sigma=2, pad=True):\n \"\"\"\n Removes horizontal stripes in sinograms (reducing ring artifacts in the reconstructed volume).\n Implements a combined Wavelet-Fourier filter (wf) as described in:\n\n Muench B, Trtrik P, Marone F, and Stampanoni M. 2009. Optics Express, 17(10):8567-8591.\n Stripe and ring artifact removal with combined wavelet-fourier filtering. 2009.\n\n This implementation is heavily based on the implementation from tomopy. This is not parallel\n at the moment.\n \"\"\"\n try:\n import pywt\n except ImportError as exc:\n raise ImportError(\"Could not import the package pywt. Details: {0}\".format(exc))\n\n dimx = data_vol.shape[0]\n n_x = dimx\n if pad:\n n_x = dimx + dimx / 8\n xshift = int((n_x - dimx) / 2.)\n\n for sino_idx in range(0, data_vol.shape[1]):\n sli = np.zeros((n_x, data_vol.shape[2]), dtype='float32')\n sli[xshift:dimx + xshift] = data_vol[:, sino_idx, :]\n\n # Wavelet decomposition\n c_H, c_V, c_D = [], [], []\n for _ in range(wv_levels):\n sli, (cHt, cVt, cDt) = pywt.dwt2(sli, wavelet_name)\n c_H.append(cHt)\n c_V.append(cVt)\n c_D.append(cDt)\n\n c_V = ft_horizontal_bands(c_V, wv_levels, sigma)\n\n # Wavelet reconstruction\n for nlvl in range(wv_levels)[::-1]:\n sli = sli[0:c_H[nlvl].shape[0], 0:c_H[nlvl].shape[1]]\n sli = pywt.idwt2((sli, (c_H[nlvl], c_V[nlvl], c_D[nlvl])),\n wavelet_name)\n data_vol[:, sino_idx, :] = sli[xshift:dimx + xshift, 0:data_vol.shape[2]]\n\n return data_vol\n\ndef ft_horizontal_bands(c_V, wv_levels, sigma):\n \"\"\"\n Fourier transform of horizontal frequency bands\n \"\"\"\n for nlvl in range(wv_levels):\n # FT\n fcV = np.fft.fftshift(np.fft.fft(c_V[nlvl], axis=0))\n m_y, m_x = fcV.shape\n\n # Damping of ring artifact information\n y_hat = (np.arange(-m_y, m_y, 2, dtype='float32') + 1) / 2\n damp = 1 - np.exp(-np.power(y_hat, 2) / (2 * np.power(sigma, 2)))\n fcV = np.multiply(fcV, np.transpose(np.tile(damp, (m_x, 1))))\n\n # Inverse FT\n c_V[nlvl] = np.real(np.fft.ifft(np.fft.ifftshift(fcV), axis=0))\n\n return c_V\n\n","sub_path":"scripts/Imaging/IMAT/prep/filters_adv.py","file_name":"filters_adv.py","file_ext":"py","file_size_in_byte":6784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"463940279","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^register$', views.register),\n url(r'^login$', views.login),\n url(r'^level1$', views.level1),\n url(r'^firstFlag$', views.firstFlag),\n url(r'^level2$', views.level2),\n url(r'^Hell$', views.Hell),\n url(r'^HellLogic$', views.HellLogic),\n url(r'^level3$', views.level3),\n url(r'^level3Logic$', views.level3Logic),\n url(r'^level4$', views.level4),\n url(r'^level4Logic$', views.level4Logic),\n url(r'^level5$', views.level5),\n url(r'^level5Logic$', views.level5Logic),\n url(r'^youWin$', views.youWin)\n]\n","sub_path":"apps/ctf_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"80315882","text":"\n#!/bin/python3\n\nimport sys\n\n\nn,m = input().strip().split(' ')\nn,m = [int(n),int(m)]\ntopic = []\ntopic_i = 0\nmaxcount = 0\ntally = 0\ncountlist = []\n\nfor topic_i in range(n):\n topic_t = str(input().strip())\n topic.append(topic_t)\n\nfor i in range(n):\n temp1 = topic[i]\n for j in range(i + 1, n):\n count = m\n temp2 = topic[j]\n for k in range(m):\n if (temp1[k] != \"1\") and (temp2[k]) != \"1\":\n count -= 1\n countlist.append(count)\n if maxcount < count:\n maxcount = count\n \nfor i in countlist:\n if i == maxcount:\n tally += 1\n \nprint(maxcount)\nprint(tally)\n","sub_path":"Python_3.4_Hackerrank_Algorithms/Implementation/ACM_ICPC_Team.py","file_name":"ACM_ICPC_Team.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"323929220","text":"\"\"\"\nOptuna example that optimizes multi-layer perceptrons using PyTorch.\n\nIn this example, we optimize the validation accuracy of hand-written digit recognition using\nPyTorch and MNIST. We optimize the neural network architecture as well as the optimizer\nconfiguration. As it is too time consuming to use the whole MNIST dataset, we here use a small\nsubset of it.\n\n\"\"\"\n\nimport os\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\nfrom torchvision import datasets\nfrom torchvision import transforms\nimport argparse\nfrom functools import partial\nfrom main import *\n\nimport optuna\n\n\nparser = argparse.ArgumentParser() \n\n# parser.add_argument(\"-embed\", \"--embedding_size\", default=100, type=int, help = \"Give embedding size\") #\n# parser.add_argument(\"-heads\", \"--nhead\", default=4, type=int, help = \"Give number of heads\") #\n# parser.add_argument(\"-hid\", \"--nhid\", default=100, type=int, help = \"Give hidden size\") #\n\n# parser.add_argument(\"-l_e1\", \"--nlayers_e1\", default=3, type=int, help = \"Give number of layers for Encoder 1\") #\n# parser.add_argument(\"-l_e2\", \"--nlayers_e2\", default=3, type=int, help = \"Give number of layers for Encoder 2\") #\n# parser.add_argument(\"-l_d\", \"--nlayers_d\", default=3, type=int, help = \"Give number of layers for Decoder\")\n\n# parser.add_argument(\"-d\", \"--dropout\",default=0.2, type=float, help = \"Give dropout\") # \nparser.add_argument(\"-bs\", \"--batch_size\", default=8, type=int, help = \"Give batch size\") #\nparser.add_argument(\"-e\", \"--epochs\", default=3, type=int, help = \"Give number of epochs\") #\nparser.add_argument(\"-model\", \"--model_type\", default=\"SET\", help=\"Give model name one of [SET, HIER, MAT]\")\n\nargs = parser.parse_args()\n\nclass ARGS:\n def __init__(self, **entries):\n self.__dict__.update(entries)\n def __str__(self):\n return str(self.__dict__)\n \ndef define_args(main_args, trial):\n # We optimize the number of layers, hidden untis and dropout ratio in each layer.\n args2 = {\n# 'embedding_size': trial.suggest_int(\"embedding_size\", 50, 400), \n 'nhead': trial.suggest_int(\"nhead\", 2, 8),\n 'embedding_perhead': trial.suggest_int(\"embedding_perhead\", 25, 40),\n 'nhid_perhead': trial.suggest_int(\"nhid_perhead\", 10, 40),\n# 'nhid': trial.suggest_int(\"nhid\", 50, 400),\n 'nlayers_e1': trial.suggest_int(\"nlayers_e1\", 2, 6),\n 'nlayers_e2': trial.suggest_int(\"nlayers_e2\", 2, 6),\n 'nlayers_d': trial.suggest_int(\"nlayers_d\", 2, 6),\n 'dropout': trial.suggest_float(\"dropout\", 0.1, 0.8),\n 'batch_size': main_args.batch_size,\n 'epochs': main_args.epochs,\n 'model_type': main_args.model_type\n }\n \n # following need to be divisible by nhead\n args2['embedding_size'] = args2['embedding_perhead']*args2['nhead']\n args2['nhid'] = args2['nhid_perhead']*args2['nhead'] \n \n args = ARGS(**args2)\n print(args)\n return args\n\n\n\ndef objective(main_args, trial):\n print(\"\\n\\n===>\", trial)\n # Generate the model.\n args = define_args(main_args, trial)\n\n # Generate the optimizers.\n #optimizer_name = trial.suggest_categorical(\"optimizer\", [\"Adam\", \"RMSprop\", \"SGD\"])\n #lr = trial.suggest_float(\"lr\", 1e-5, 1e-1, log=True)\n #optimizer = getattr(optim, optimizer_name)(model.parameters(), lr=lr)\n\n # Get the dataset.\n #train_loader, valid_loader = get_mnist()\n\n # Training of the model\n \n def callback(epoch, val_accuracy): # NewMethod\n trial.report(val_accuracy, epoch)\n\n # Handle pruning based on the intermediate value.\n if trial.should_prune():\n raise optuna.exceptions.TrialPruned()\n \n # NewMethod\n val_criteria = run(args, optuna_callback=callback) # callback should be called internally after each epoch.\n \n return val_criteria\n\n\nif __name__ == \"__main__\":\n \"\"\"GLOBALS\n \"\"\" \n study = optuna.create_study(study_name='hier-study', direction=\"maximize\", storage=f'sqlite:///{args.model_type.lower()}.db', load_if_exists=True)\n study.optimize(partial(objective, args), n_trials=15)\n\n pruned_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.PRUNED]\n complete_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]\n\n print(\"Study statistics: \")\n print(\" Number of finished trials: \", len(study.trials))\n print(\" Number of pruned trials: \", len(pruned_trials))\n print(\" Number of complete trials: \", len(complete_trials))\n\n print(\"Best trial:\")\n trial = study.best_trial\n\n print(\" Value: \", trial.value)\n\n print(\" Params: \")\n for key, value in trial.params.items():\n print(\" {}: {}\".format(key, value))\n \n fig = optuna.visualization.plot_optimization_history(study)\n fig.write_html('search_history.html')\n fig = optuna.visualization.plot_parallel_coordinate(study)\n fig.write_html('search_parallel.html')\n","sub_path":"search_params.py","file_name":"search_params.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"100658954","text":"\"\"\"\nWsgi Server\n\"\"\"\n\n__author__ = 'VMware, Inc.'\n__copyright__ = 'Copyright 2015-2017, 2019 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long\n\nimport logging\nimport six\nimport ssl\nimport werkzeug\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.routing import (Rule, Map)\nfrom werkzeug.wrappers import Request, Response\nfrom wsgiref.simple_server import make_server\n\nfrom vmware.vapi.data.serializers.cleanjson import DataValueConverter\nfrom vmware.vapi.lib.addr_url_parser import parse_addr_url\nfrom vmware.vapi.lib.constants import (\n JSON_CONTENT_TYPE, JSONRPC)\nfrom vmware.vapi.lib.log import get_vapi_logger, get_provider_wire_logger\nfrom vmware.vapi.lib.std import make_error_value_from_msgs, make_std_error_def\nfrom vmware.vapi.l10n.runtime import message_factory\nfrom vmware.vapi.rest.handler import RESTHandler\nfrom vmware.vapi.server.server_interface import ServerInterface\n\nlogger = get_vapi_logger(__name__)\nprovider_wire_logger = get_provider_wire_logger()\n\n\nclass WsgiApplication(object):\n \"\"\"\n Python WSGI application. For more details about WSGI\n specification, see PEP 333.\n \"\"\"\n def __init__(self, msg_handler_map, provider_config):\n \"\"\"\n Initialize WsgiApplication\n\n :type msg_handler_map: :class:`dict` of :class:`str` and\n :class:`vmware.vapi.protocol.server.api_handler.ApiHandler`\n :param msg_handler_map: Map of content type to the message\n handler for that content type\n \"\"\"\n self._msg_handler_map = msg_handler_map\n\n jsonrpc_prefix = provider_config.get_jsonrpc_prefix()\n if jsonrpc_prefix:\n routing_rules = [Rule(jsonrpc_prefix, endpoint=JSONRPC)]\n else:\n # No prefix specified, use path converter rule, that matches\n # any prefix.\n # This is used for backcompat as previously, specifying\n # jsonrpc prefix was not required for wsgi applications.\n routing_rules = [Rule('/', endpoint=JSONRPC)]\n\n if provider_config.enable_rest():\n json_msg_handler = self._msg_handler_map.get(JSON_CONTENT_TYPE)\n allow_cookies = provider_config.are_cookies_supported()\n self._rest_handler = RESTHandler(\n json_msg_handler.provider, allow_cookies, provider_config)\n self._rest_prefix = provider_config.get_rest_prefix()\n routing_rules += self._rest_handler.rest_rules\n\n self.rule_map = Map(routing_rules)\n logger.info(self.rule_map)\n\n def _handle_jsonrpc_call(self, request):\n \"\"\"\n Handle a JSONRPC protocol request\n\n :type request: :class:`werkzeug.wrappers.Request`\n :param request: Request object\n :rtype: :class:`str`\n :return: output string\n \"\"\"\n content_type, _ = werkzeug.http.parse_options_header(\n request.content_type)\n handler = self._msg_handler_map.get(content_type)\n if handler is None:\n raise werkzeug.exceptions.BadRequest(\n 'Content-Type %s is not supported' % (content_type))\n try:\n result, headers = handler.handle_request(request.get_data(),\n request.headers)\n except Exception as e:\n logger.exception(e)\n raise werkzeug.exceptions.InternalServerError(\n 'Unexpected error. See server logs for more details.')\n return result, headers\n\n def _handle_rest_call(self, request, endpoint, args):\n \"\"\"\n Handle HTTP REST call\n\n :type request: :class:`werkzeug.wrappers.Request`\n :param request: Request object\n :type endpoint: :class:`str`\n :param endpoint: Tuple of service ID and operation ID\n :type args: :class:`dict` of :class:`str` and :class:`object`\n :param args: Arguments parsed from the HTTP URL\n :rtype: :class:`tuple` of :class:`str` and :class:`str`\n :return: HTTP status string and output\n \"\"\"\n # Accept only json content type\n if request.content_length:\n content_type, _ = werkzeug.http.parse_options_header(\n request.content_type)\n if content_type != JSON_CONTENT_TYPE and request.method in [\n 'POST', 'PATCH', 'PUT']:\n raise werkzeug.exceptions.UnsupportedMediaType(\n '%s content type is not supported' % content_type)\n try:\n output = self._rest_handler.invoke(request, endpoint, args)\n except werkzeug.exceptions.BadRequest as e:\n raise e\n except werkzeug.exceptions.NotFound as e:\n raise e\n except Exception as e:\n logger.exception(e)\n raise werkzeug.exceptions.InternalServerError(\n 'Unexpected error. See server logs for more details.')\n return output\n\n @Request.application\n def __call__(self, request):\n \"\"\"\n The implementation of WsgiApplication\n\n :type request: :class:`werkzeug.wrappers.Request`\n :param request: Request object\n :rtype: :class:`werkzeug.wrappers.Response`\n :return: Response object\n \"\"\"\n try:\n urls = self.rule_map.bind_to_environ(request.environ)\n endpoint, args = urls.match()\n if provider_wire_logger.isEnabledFor(logging.DEBUG):\n provider_wire_logger.debug(\n 'HTTP %s %s ', request.method, request.url)\n provider_wire_logger.debug(\n 'REQUEST HEADERS: %s', request.headers)\n provider_wire_logger.debug(\n 'REQUEST BODY: %s', request.get_data())\n if endpoint == JSONRPC:\n result, headers = self._handle_jsonrpc_call(request)\n response = Response(result)\n if headers:\n response.headers = headers\n else:\n status, result, cookies, headers = self._handle_rest_call(\n request, endpoint, args)\n response = Response(result)\n response.status_code = status\n if headers:\n response.headers = headers\n if cookies:\n path = self._rest_prefix\n for k, v in six.iteritems(cookies):\n response.set_cookie(k, v, path=path)\n response.content_type = JSON_CONTENT_TYPE\n if provider_wire_logger.isEnabledFor(logging.DEBUG):\n provider_wire_logger.debug(\n 'RESPONSE STATUS: %s', response.status_code)\n provider_wire_logger.debug(\n 'RESPONSE HEADERS: %s', response.headers)\n provider_wire_logger.debug(\n 'RESPONSE BODY: %s', response.response)\n return response\n except HTTPException as e:\n try:\n internal_server_error_def = make_std_error_def(\n 'com.vmware.vapi.std.errors.invalid_request')\n msg = message_factory.get_message('vapi.method.invoke.exception', # pylint: disable=line-too-long\n e.description)\n error_value = make_error_value_from_msgs(\n internal_server_error_def, msg)\n json_output = DataValueConverter.convert_to_json(error_value)\n response = e.get_response()\n response.set_data(json_output)\n response.headers['Content-Type'] = 'application/json'\n return response\n except Exception:\n # if there is error in serialize the error,\n # just return the original raw exception\n return e\n\n\nclass WsgiServer(ServerInterface):\n \"\"\"\n Server wrapper class for Wsgi application.\n \"\"\"\n\n SUPPORTED_SCHEMES = ('http', 'https')\n HTTP_CONTENT_MAPPING = {'json': 'application/json',\n 'xml': 'text/xml',\n '': ''}\n\n def __init__(self):\n \"\"\"\n Initialize WsgiServer\n \"\"\"\n self._protocol_handler_map = {}\n self._url = None\n self._wsgi_application = None\n self._http_server = None\n self.provider_config = None\n ServerInterface.__init__(self)\n\n def register_handler(self, addr, msg_type, protocol_handler, ssl_args=None):\n \"\"\"\n Register protocol handler\n\n :type addr: :class:`str`\n :param addr: addr url\n :type msg_type: :class:`str`\n :param msg_type: protocol message type\n :type protocol_handler: :class:`vmware.vapi.protocol.server.transport.\\\n async_protocol_handler.AsyncProtocolHandler`\n :param protocol_handler: protocol handler for this addr\n :type ssl_args: :class:`dict`\n :param ssl_args: ssl arguments\n \"\"\"\n assert(protocol_handler)\n content_type = self.HTTP_CONTENT_MAPPING.get(msg_type)\n if content_type is None:\n logger.error('Unsupported msg type: %s', msg_type)\n return\n self._protocol_handler_map[content_type] = protocol_handler\n self._url = addr\n self._ssl_args = ssl_args\n\n def get_wsgi_application(self):\n \"\"\"\n Returns the WSGI application.\n\n :rtype: :class:`vmware.vapi.server.wsgi_server.WsgiApplication`\n :return: WSGI application.\n \"\"\"\n if self._wsgi_application is None:\n assert(self.provider_config)\n self._wsgi_application = WsgiApplication(\n self._protocol_handler_map, self.provider_config)\n return self._wsgi_application\n\n def serve_forever(self):\n _, host, port, _, _, _, _ = parse_addr_url(self._url)\n self._http_server = make_server(host, port, self.get_wsgi_application())\n if self._ssl_args:\n self._http_server.socket = ssl.wrap_socket(\n self._http_server.socket, keyfile=self._ssl_args['keyfile'],\n certfile=self._ssl_args['certfile'], server_side=True)\n logger.info('Listening on: %s', self._url)\n self._http_server.serve_forever()\n\n def shutdown(self):\n self._http_server.shutdown()\n\n\ndef get_server():\n \"\"\"\n Get wsgi server\n\n :rtype: :class:`vmware.vapi.server.server_interface.ServerInterface`\n :return: subclass of ServerInterface\n \"\"\"\n return WsgiServer()\n","sub_path":"vmware/vapi/server/wsgi_server.py","file_name":"wsgi_server.py","file_ext":"py","file_size_in_byte":10551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"385772907","text":"import re\n\n\nclass Preprocessor():\n def __init__(self, variables=None):\n if variables is None:\n variables = []\n parsed_variables = []\n for variable in variables:\n parts = variable.split(':')\n if len(parts) <= 1:\n raise Exception('Invalid variable fortmat')\n name = parts[0]\n wrapped_regex = ':'.join(parts[1:])\n regex = wrapped_regex[1:-1]\n parsed_variables.append((name, regex))\n self.variables = [\n (tuple[0], re.compile(tuple[1])) for tuple in parsed_variables\n ]\n\n def process(self, line):\n for (name, regex) in self.variables:\n line = re.sub(regex, name, line)\n return line\n","sub_path":"log_mine/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"618304361","text":"from __future__ import print_function\nimport boto3\nimport os\nimport sys\nimport uuid\nfrom PIL import Image\n\ns3_client = boto3.client('s3')\nRESIZED_BUCKET_NAME = 'takesone-image-resized'\nRESIZED_IMAGE_SIZE = (200, 100)\n\ndef resize_image(image_path, resized_path):\n with Image.open(image_path) as image:\n image.thumbnail(RESIZED_IMAGE_SIZE)\n image.save(resized_path)\n\ndef lambda_handler(event, context):\n for record in event['Records']:\n bucket = record['s3']['bucket']['name']\n key = record['s3']['object']['key'] \n download_path = '/tmp/{}{}'.format(uuid.uuid4(), key)\n upload_path = '/tmp/resized-{}'.format(key)\n\n s3_client.download_file(bucket, key, download_path)\n resize_image(download_path, upload_path)\n s3_client.upload_file(upload_path, RESIZED_BUCKET_NAME, key)\n\n","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"502754763","text":"# JSON 格式的响应是常见的,用 Flask 写这样的 API 是很容易上手的。\n# 如果从视图 返回一个 dict ,那么它会被转换为一个 JSON 响应。\n@app.route(\"/me\")\ndef me_api():\n user = get_current_user()\n return {\n \"username\": user.username,\n \"theme\": user.theme,\n \"image\": url_for(\"user_image\", filename=user.image),\n }\n\n# 如果 dict 还不能满足需求,还需要创建其他类型的 JSON 格式响应,可以使用 jsonify() 函数。\n# 该函数会序列化任何支持的 JSON 数据类型。\n# 也可以��究研究 Flask 社区扩展,以支持更复杂的应用。\n@app.route(\"/users\")\ndef users_api():\n users = get_all_users()\n return jsonify([user.to_json() for user in users])\n\n","sub_path":"Python/Python-Flask/Flask/013.JSON格式的API.py","file_name":"013.JSON格式的API.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"262513062","text":"from sqlalchemy import Column, Integer, String, Float, Boolean, TIMESTAMP, create_engine, UniqueConstraint\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.exc import IntegrityError\nimport requests\nimport time\nimport datetime\n#This code here is used because, apparently, Python3 doesnt' have native MySQLdb?\n#Should check if this really is the case. In the meantime, you will have to import\n#the module pymysql.\ntry:\n import pymysql\n pymysql.install_as_MySQLdb()\nexcept ImportError:\n pass\ndef base(engine):\n #This code is used to set up a database. Careful: __tablename__ is not a variable name, so\n #do not change it.\n Base = declarative_base()\n class User(Base):\n __tablename__ = 'station_info'\n\n update_id = Column(Integer, primary_key=True)\n name = Column(String(255))\n status = Column(String(255))\n available_bike_stands = Column(Integer)\n available_bikes = Column(Integer)\n last_update = Column(TIMESTAMP)\n UniqueConstraint('name', 'status', 'available_bike_stands', 'available_bikes', 'last_update', name='uix_1')\n\n #This code sends the command to create the table. I left it commented because the table is already created.\n #But guess you can drop the table in the database and try to create again, to make sure it really works.\n Base.metadata.create_all(engine)\n return User\n\ndef connectAPI():\n #This code open the connection to the Dublin Bikes API.\n base_url = 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=8a48bea4967f8f374d1b211fc80da143d607e28a'\n\n #This code sets up our static data table for all the stations.\n #This code gets the data from Dublin Bikes.\n response = requests.get(base_url)\n #print(response) #This is just to show that the response connected without error (should show 2:\n raise ValueError(\"Found an ROIAnnotation within another ROIAnnotation, did not expect this\")\n #don't use RectangleAnnotations if there are also ROIAnnotations\n #(inherited from matlab code, not sure where this logic comes in)\n if field.nestdepth < maxdepth: continue\n if field.nestdepth > maxdepth:\n del rectangles[:]\n maxdepth = field.nestdepth\n\n if not field.isacquired: continue\n rectangles.append(\n Rectangle(\n n=len(rectangles)+1,\n x=field.x,\n y=field.y,\n cx=field.cx,\n cy=field.cy,\n w=field.w,\n h=field.h,\n t=field.time,\n file=field.im3path.name,\n pscale=self.pscale,\n readingfromfile=False,\n xmlfolder=self.__xmlfolder,\n )\n )\n if microscopename is None:\n microscopename = str(annotation.microscopename)\n elif microscopename != annotation.microscopename:\n raise ValueError(\"Found multiple different microscope names '{microscopename}' '{annotation.microscopename}'\")\n\n return rectangles, globals, perimeters, microscopename\n\n @property\n def rectangles(self): return self.getdata()[0]\n @property\n def globals(self): return self.getdata()[1]\n @property\n def perimeters(self): return self.getdata()[2]\n @property\n def microscopename(self): return self.getdata()[3]\n\nclass AnnotationBase(units.ThingWithPscale):\n \"\"\"\n There are two kinds of annotations in the xml files,\n depending on the microscope model and software version.\n This is the base class for both of them. \n \"\"\"\n def __init__(self, xmlnode, *, pscale, nestdepth=1):\n self.__xmlnode = xmlnode\n self.__nestdepth = nestdepth\n self.__pscale = pscale\n @property\n def pscale(self): return self.__pscale\n @property\n def xmlnode(self): return self.__xmlnode\n @property\n def nestdepth(self): return self.__nestdepth\n def __str__(self): return str(self.xmlnode)\n @property\n @abc.abstractmethod\n def fields(self):\n \"\"\"\n RectangleAnnotations for all HPFs within this annotation\n \"\"\"\n @property\n @abc.abstractmethod\n def globals(self):\n \"\"\"\n Global variables from the annotation\n \"\"\"\n @property\n @abc.abstractmethod\n def perimeters(self):\n \"\"\"\n ROI perimeters from the annotation\n \"\"\"\n @property\n @abc.abstractmethod\n def microscopename(self):\n \"\"\"\n The microscope name from the annotation\n (really the name of the computer connected to the microscope)\n \"\"\"\n\n @property\n def subtype(self):\n \"\"\"\n The annotation subtype - RectangleAnnotation or ROIAnnotation\n \"\"\"\n return self.__xmlnode.get_xml_attr(\"subtype\")\n\nclass RectangleAnnotation(AnnotationBase):\n \"\"\"\n A rectangle annotation is for a single HPF.\n \"\"\"\n @property\n def fields(self):\n \"\"\"\n A rectangle annotation is for a single HPF\n \"\"\"\n return self,\n @property\n def history(self):\n \"\"\"\n The history of the HPF scanning\n \"\"\"\n history = self.xmlnode[\"History\"][\"History-i\"]\n if isinstance(history, jxmlease.XMLDictNode): history = history,\n return history\n @property\n def isacquired(self):\n \"\"\"\n Was this HPF acquired? (i.e. did it finish successfully?)\n \"\"\"\n return self.history[-1][\"Type\"] == \"Acquired\"\n @property\n def im3path(self):\n \"\"\"\n Path to the im3 file\n \"\"\"\n return pathlib.PureWindowsPath(self.history[-1][\"Im3Path\"])\n @property\n def microscopename(self):\n \"\"\"\n Name of the computer operating the microscope\n \"\"\"\n if not self.isacquired: return None\n return self.history[-1][\"UserName\"]\n @property\n def x(self):\n \"\"\"\n x position of the HPF\n \"\"\"\n return float(self.xmlnode[\"Bounds\"][\"Origin\"][\"X\"]) * self.onemicron\n @property\n def y(self):\n \"\"\"\n y position of the HPF\n \"\"\"\n return float(self.xmlnode[\"Bounds\"][\"Origin\"][\"Y\"]) * self.onemicron\n @property\n def w(self):\n \"\"\"\n width of the HPF\n \"\"\"\n return float(self.xmlnode[\"Bounds\"][\"Size\"][\"Width\"]) * self.onemicron\n @property\n def h(self):\n \"\"\"\n height of the HPF\n \"\"\"\n return float(self.xmlnode[\"Bounds\"][\"Size\"][\"Height\"]) * self.onemicron\n @property\n def cx(self):\n \"\"\"\n x of the HPF's center in integer pixels\n \"\"\"\n return floattoint(np.round(float((self.x+0.5*self.w) / self.onemicron))) * self.onemicron\n @property\n def cy(self):\n \"\"\"\n y of the HPF's center in integer pixels\n \"\"\"\n return floattoint(np.round(float((self.y+0.5*self.h) / self.onemicron))) * self.onemicron\n @property\n def time(self):\n \"\"\"\n time stamp when the HPF was acquired\n \"\"\"\n return dateutil.parser.parse(self.history[-1][\"TimeStamp\"])\n\n @property\n def globals(self): \"RectangleAnnotations don't have global variables\"\n @property\n def perimeters(self): \"RectangleAnnotations don't have perimeters\"\n\nclass ROIAnnotation(AnnotationBase):\n \"\"\"\n An ROIAnnotation includes multiple HPFs within the region of interest\n \"\"\"\n @property\n def fields(self):\n \"\"\"\n The HPFs in this ROI\n \"\"\"\n fields = self.xmlnode[\"Fields\"][\"Fields-i\"]\n if isinstance(fields, jxmlease.XMLDictNode): fields = fields,\n for field in fields:\n yield from AnnotationFactory(field, nestdepth=self.nestdepth+1, pscale=self.pscale).fields\n @property\n def globals(self):\n \"\"\"\n Global variables for the ROI\n \"\"\"\n return {\n \"x\": float(self.xmlnode[\"Bounds\"][\"Origin\"][\"X\"]) * self.onemicron,\n \"y\": float(self.xmlnode[\"Bounds\"][\"Origin\"][\"Y\"]) * self.onemicron,\n \"Width\": float(self.xmlnode[\"Bounds\"][\"Size\"][\"Width\"]) * self.onemicron,\n \"Height\": float(self.xmlnode[\"Bounds\"][\"Size\"][\"Height\"]) * self.onemicron,\n \"Unit\": \"microns\",\n \"Tc\": dateutil.parser.parse(self.xmlnode[\"History\"][\"History-i\"][\"TimeStamp\"]),\n }\n @property\n def perimeters(self):\n \"\"\"\n Describes the perimeter of the ROI\n \"\"\"\n result = []\n perimeters = self.xmlnode[\"Perimeter\"][\"Perimeter-i\"]\n if isinstance(perimeters, jxmlease.XMLDictNode): perimeters = perimeters,\n for i, perimeter in enumerate(perimeters, start=1):\n result.append({\n \"n\": i,\n \"x\": float(perimeter[\"X\"]) * self.onemicron,\n \"y\": float(perimeter[\"Y\"]) * self.onemicron,\n })\n return result\n\n @property\n def microscopename(self):\n \"\"\"\n Name of the computer operating the microscope\n \"\"\"\n names = {field.microscopename for field in self.fields if field.microscopename is not None}\n if not names:\n return None\n if len(names) > 1:\n raise ValueError(\"Multiple microscope names: \"+\", \".join(names))\n return names.pop()\n\ndef AnnotationFactory(xmlnode, **kwargs):\n \"\"\"\n Returns the right kind of annotation, either Rectangle or ROI\n \"\"\"\n return {\n \"RectangleAnnotation\": RectangleAnnotation,\n \"ROIAnnotation\": ROIAnnotation,\n }[xmlnode.get_xml_attr(\"subtype\")](xmlnode, **kwargs)\n","sub_path":"astropath/baseclasses/annotationxmlreader.py","file_name":"annotationxmlreader.py","file_ext":"py","file_size_in_byte":8460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"458303165","text":"import sys\nimport numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import TruncatedSVD\nfrom scipy.stats import ttest_ind\nfrom numpy.linalg import svd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom qvalues import qvalues\nfrom multiprocessing import Pool\nsns.set(color_codes=True)\n\nMETHYLATION_FILE = 'data/GSE76399_data_with_probe_ann.txt'\nPATIENT_FILE = 'data/samples_clinical_data.txt'\n\n\ndef csvToDataFrame(filename):\n '''Reads tab-separated data from filename and returns a dataframe'''\n with open(filename,'r') as f:\n data = pd.read_csv(f,sep='\\t')\n return data\n\n\ndef cleanData(methylation_data,patient_data):\n '''Takes raw methylation and patient data. Removes non-SAT data, removes probes without genes,\n and converts gene information from csv to sets.\n Returns cleaned methylation and patient data.'''\n SAT_patient_data = patient_data[patient_data['Tissue_type']=='subcutaneous adipose tissue']\n\n # Removing non-SAT data\n no_SAT_patient_data = patient_data[patient_data['Tissue_type']!='subcutaneous adipose tissue']\n SAT_methylation_data = methylation_data.drop(no_SAT_patient_data['GEO_accession'],axis=1)\n\n # Removing probes without genes\n gene_SAT_methylation_data = SAT_methylation_data.drop(SAT_methylation_data[SAT_methylation_data['UCSC_RefGene_Accession'].isnull()].index)\n # Converting genes to a set instead of semi-colon separated strings\n gene_SAT_methylation_data.loc[:,'UCSC_RefGene_Accession'] = gene_SAT_methylation_data['UCSC_RefGene_Accession'].str.split(';').apply(set)\n return gene_SAT_methylation_data, SAT_patient_data\n\n\ndef betaToM(beta):\n '''Converts a beta-value to a M-value.'''\n return np.log2(beta/(1-beta))\n\n\ndef columnsFromBetaToM(df, SAT_geo_accession):\n '''Turns the columns containing beta values into columns containing M-values.'''\n df.loc[:,SAT_geo_accession] = df.loc[:,SAT_geo_accession].applymap(betaToM)\n return df\n\n\ndef dropBadRows(df,SAT_geo_accession,eps=0.1):\n '''Drop all rows that contain values outside of (eps,1-eps) range.'''\n idxs = df[((df.loc[:,SAT_geo_accession] < eps) | (df.loc[:,SAT_geo_accession] >(1- eps))).any(1)].index\n df = df.drop(idxs)\n return df\n\n\ndef HistPlot(df,SAT_geo_accession,insulin_geo_dict):\n data = df[insulin_geo_dict['resistant'].append(insulin_geo_dict['sensitive'])].values.flatten() \n\n g = sns.distplot(data, kde=False, bins = 150)\n plt.show()\n\n\ndef HistPlotM(df,SAT_geo_accession,insulin_geo_dict):\n data = df[insulin_geo_dict['resistant'].append(insulin_geo_dict['sensitive'])].values.flatten() \n\n sns.distplot(data, kde=False, bins = 150)\n plt.show()\n \n\ndef main():\n # Reading data from file\n methylation_data = csvToDataFrame(METHYLATION_FILE)\n patient_data = csvToDataFrame(PATIENT_FILE)\n\n SAT_methylation_data, SAT_patient_data = cleanData(methylation_data, patient_data)\n\n # Picks out SAT samples (columns)\n SAT_geo_accession = SAT_patient_data['GEO_accession']\n insulin_geo_dict = {x:SAT_patient_data[SAT_patient_data['Insulin_state']==x]['GEO_accession'] for x in ['resistant','sensitive']}\n\n\t\n\t#Drop bad rows\n #SAT_methylation_data = dropBadRows(SAT_methylation_data,SAT_geo_accession)\n \n ## Plot input data from beta-values\n HistPlot(SAT_methylation_data,SAT_geo_accession,insulin_geo_dict)\n\n\t## Converts beta to m-values\n #SAT_methylation_data = columnsFromBetaToM(SAT_methylation_data,SAT_geo_accession)\n\n ## Plot input data from M values\n #HistPlotM(SAT_methylation_data,SAT_geo_accession,insulin_geo_dict)\n\n \nif __name__=='__main__':\n main()\n\n\n\n\n","sub_path":"experiments/20171128/results/20171220/plot-main.py","file_name":"plot-main.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"117931365","text":"from dexy.constants import Constants\nfrom ordereddict import OrderedDict\nimport sqlite3\nimport dexy.database\nimport json\nimport os\n\nclass SqliteDatabase(dexy.database.Database):\n \"\"\"\n The Database class stores metadata around dexy batches/runs. This metadata\n is used for reporting and can be used as a version history of the documents\n you process with dexy.\n The database can also be used to parallelize/distribute the processing of\n dexy runs and to store ctime/mtime/inode data to speed up cache detection.\n \"\"\"\n\n FIELDS = [\n (\"batch_id\" , \"int\"),\n (\"batch_order\" , \"int\"),\n (\"elapsed\" , \"int\"),\n (\"hashstring\" , \"text\"),\n (\"source\" , \"text\")\n ]\n\n def create_table_sql(self):\n sql = \"create table artifacts (id text primary key, %s)\"\n fields = [\"%s %s\" % k for k in self.FIELDS]\n fields.extend(\"%s text\" % k for k in self.whitelist_keys)\n return sql % (\", \".join(fields))\n\n def create_table(self):\n try:\n self.conn.execute(self.create_table_sql())\n except sqlite3.OperationalError:\n pass\n\n def __init__(self, logsdir=Constants.DEFAULT_LDIR, dbfile=Constants.DEFAULT_DBFILE):\n self.logsdir = logsdir or \"\"\n if dbfile:\n filename = os.path.join(self.logsdir, dbfile)\n self.filename = filename\n # TODO test that schema hasn't changed\n else:\n # use in-memory db\n self.filename = \":memory:\"\n\n self.conn = sqlite3.connect(self.filename)\n self.conn.row_factory = sqlite3.Row\n\n self.field_keys = [k[0] for k in self.FIELDS]\n self.whitelist_keys = sorted(Constants.ARTIFACT_HASH_WHITELIST)\n self.field_names = ['id'] + self.field_keys + self.whitelist_keys\n self.create_table()\n self.batch_orders = {}\n self.extra_keys = []\n\n def persist(self):\n self.conn.commit()\n\n def max_batch_id(self):\n return self.conn.execute(\"select max(batch_id) from artifacts\").fetchone()[0] or 0\n\n def next_batch_id(self):\n return self.max_batch_id() + 1\n\n def max_batch_order(self, batch_id, incr=False):\n # using a hash for calculating batch order since hitting the DB each\n # time is too slow. should be getting this from topo sort? should be\n # per-artifact rather than per-document? This isn't used for anything\n # currently, so not a big deal.\n if not self.batch_orders.has_key(batch_id):\n self.batch_orders[batch_id] = 0\n elif incr:\n self.batch_orders[batch_id] += 1\n return self.batch_orders[batch_id]\n\n def next_batch_order(self, batch_id):\n return self.max_batch_order(batch_id, True)\n\n def get_attributes_for_artifact(self, artifact):\n hd = artifact.hash_dict()\n values = [artifact.unique_key()]\n\n # add attrs not in hash whitelist\n values.extend(getattr(artifact, k) for k in self.field_keys)\n\n # get attrs from the hash whitelist, converting any OrderedDicts into JSON\n artifact_values = (hd.get(k, None) for k in self.whitelist_keys)\n convert_to_json = lambda v: isinstance(v, OrderedDict) and json.dumps(v) or v\n values.extend(convert_to_json(v) for v in artifact_values)\n\n return values\n\n def append_artifacts(self, artifacts):\n qs = (\"?,\" * len(self.field_names))[:-1]\n sql = \"INSERT INTO artifacts VALUES (%s)\" % qs\n for a in artifacts:\n self.conn.execute(sql, self.get_attributes_for_artifact(a))\n\n def update_artifact(self, artifact):\n values = self.get_attributes_for_artifact(artifact)[1:]\n values.append(artifact.unique_key())\n sql = \"UPDATE artifacts SET %s where id = ?\" % (\", \".join(\"%s = ? \" % k for k in self.field_names[1:]))\n self.conn.execute(sql, values)\n\n def artifact_row(self, artifact):\n \"\"\"Returns the db row corresponding to an artifact.\"\"\"\n sql = \"SELECT * from artifacts where id = ?\"\n return self.conn.execute(sql, (artifact.unique_key(),)).fetchone()\n\n def references_for_batch_id(self, batch_id=None):\n \"\"\"\n Return information for a given batch.\n \"\"\"\n if not batch_id:\n # use most recent batch\n batch_id = self.max_batch_id()\n sql = \"SELECT * from artifacts where batch_id = ?\"\n return self.conn.execute(sql, (batch_id,)).fetchall()\n\n def all(self, limit=None):\n if limit:\n return self.conn.execute(\"SELECT * from artifacts LIMIT ?\", (limit,)).fetchall()\n else:\n return self.conn.execute(\"SELECT * from artifacts\").fetchall()\n\n def query_unique_key(self, unique_key):\n return self.conn.execute(\"SELECT * from artifacts where id = ?\", (unique_key,)).fetchall()\n\n def query_like(self, query):\n return self.conn.execute(\"SELECT * from artifacts where (is_last = 'True' or additional='True') and batch_id = ? and key like ?\", (self.max_batch_id(), query,)).fetchall()\n","sub_path":"dexy/databases/sqlite_database.py","file_name":"sqlite_database.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"286655039","text":"from types import FrameType\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef make_coordinates(image, line_parameters):\n slope, intercept = line_parameters\n y1 = image.shape[0] # Bottom of the image\n y2 = int(y1 * (3 / 5)) # Slightly lower than the middle\n x1 = int((y1 - intercept) / slope)\n x2 = int((y2 - intercept) / slope)\n return [[x1, y1, x2, y2]]\n\ndef average_slope_intercept(image, lines):\n left_fit = []\n right_fit = []\n if lines is None:\n return None\n for line in lines:\n for x1, y1, x2, y2 in line:\n fit = np.polyfit((x1, x2), (y1, y2), 1)\n slope = fit[0]\n intercept = fit[1]\n if slope < 0: # y is reversed in image\n left_fit.append((slope, intercept))\n else:\n right_fit.append((slope, intercept))\n left_fit_average = np.average(left_fit, axis=0)\n right_fit_average = np.average(right_fit, axis=0)\n left_line = make_coordinates(image, left_fit_average)\n right_line = make_coordinates(image, right_fit_average)\n return [left_line, right_line]\n\ndef canny(image):\n grayscale_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n kernel = 5\n blurred_image = cv2.GaussianBlur(grayscale_image, (kernel, kernel), 0)\n canny_image = cv2.Canny(blurred_image, 50, 150)\n return canny_image\n\ndef region_of_interest(image):\n height = image.shape[0]\n mask = np.zeros_like(image)\n polygons = np.array([[(200, height), (1100, height), (550, 250)]], np.int32) \n cv2.fillPoly(mask, polygons, 255)\n masked_image = cv2.bitwise_and(image, mask)\n return masked_image\n\ndef display_lines(image, lines):\n line_image = np.zeros_like(image)\n if lines is not None:\n for line in lines:\n for x1, y1, x2, y2 in line:\n cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 10)\n return line_image\n\n\n# test_image = cv2.imread('../image/test_image.jpg')\n\n# # Copy our image array into a new variable. Thus, the changes we make will not affect the actual image.\n# image = np.copy(test_image)\n\n# canny_image = canny(image)\n# cropped_image = region_of_interest(canny_image)\n# lines = cv2.HoughLinesP(cropped_image, 2, np.pi / 180, 100, np.array([]), minLineLength=40, maxLineGap=5)\n# averaged_lines = average_slope_intercept(image, lines)\n# line_image = display_lines(image, averaged_lines)\n# image_with_lines = cv2.addWeighted(image, 0.8, line_image, 1, 1)\n\n# cv2.imshow('Result', image_with_lines)\n# cv2.waitKey(0)\n\n\ncap = cv2.VideoCapture('../video/test_video.mp4')\nwhile (cap.isOpened()):\n # Returns two values which we can unpack. First value is a boolean and second is current frame of the video.\n _, frame = cap.read()\n canny_image = canny(frame)\n cropped_image = region_of_interest(canny_image)\n lines = cv2.HoughLinesP(cropped_image, 2, np.pi / 180, 100, np.array([]), minLineLength=40, maxLineGap=5)\n averaged_lines = average_slope_intercept(frame, lines)\n line_image = display_lines(frame, averaged_lines)\n image_with_lines = cv2.addWeighted(frame, 0.8, line_image, 1, 1)\n cv2.imshow('Video', image_with_lines)\n # waitKey returns a 32bit integer value.\n # Common trick is to apply bitwise AND operation with the hexadecimal constant to mask our integer to eight bits\n # We are comparing this to the numeric encoding of the 'q' character to break the loop:\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"source/lanes.py","file_name":"lanes.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"365275671","text":"import numpy as np\ntry:\n import gridpp\nexcept ImportError:\n gridpp = None\n\n\ndef horizontal_oi(geo, background, observations, gelevs, glafs, hlength=10000.,\n vlength=10000., wlength=0.5, elev_gradient=0, structure_function=\"Barnes\",\n max_locations=50, epsilon=0.5, minvalue=None, maxvalue=None,\n interpol=\"bilinear\", debug=False):\n\n if gridpp is None:\n raise Exception(\"You need gridpp to perform OI\")\n\n if debug:\n print(gridpp.__file__)\n print(gridpp.__version__)\n glats = geo.lats\n glons = geo.lons\n\n def obs2vectors(my_obs):\n return my_obs.lons, my_obs.lats, my_obs.stids, my_obs.elevs, \\\n my_obs.values, my_obs.cis, my_obs.lafs\n\n vectors = np.vectorize(obs2vectors)\n lons, lats, stids, elevs, values, pci, lafs = vectors(observations)\n\n glats = np.transpose(glats)\n glons = np.transpose(glons)\n background = np.transpose(background)\n gelevs = np.transpose(gelevs)\n\n bgrid = gridpp.Grid(glats, glons, gelevs)\n points = gridpp.Points(lats, lons, elevs)\n if interpol == \"bilinear\":\n pbackground = gridpp.bilinear(bgrid, points, background)\n elif interpol == \"nearest\":\n pbackground = gridpp.nearest(bgrid, points, background, elev_gradient)\n else:\n raise NotImplementedError\n variance_ratios = np.full(points.size(), epsilon)\n\n if structure_function == \"Barnes\":\n structure = gridpp.BarnesStructure(hlength, vlength, wlength)\n else:\n raise NotImplementedError\n\n field = gridpp.optimal_interpolation(bgrid, background, points, values, variance_ratios, pbackground, structure,\n max_locations)\n field = np.asarray(field)\n if minvalue is not None:\n field[field < minvalue] = minvalue\n if maxvalue is not None:\n field[field > maxvalue] = maxvalue\n return np.transpose(field)\n","sub_path":"surfex/assim.py","file_name":"assim.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"442725576","text":"import os\n\npath=os.path.join(os.path.dirname(os.path.abspath(__file__)),'11\\\\')\nprint(path)\n\nfile_version_map ={}\n\nfor onefile in os.listdir(path):\n if os.path.isfile(os.path.join(path,onefile)):\n version = onefile.split('_')[1:6]\n aa = []\n for i in version:\n aa.append(int(i))\n\n file_version_map[tuple(aa)] = onefile\n\ndata =sorted(file_version_map.items(),key=lambda x:x[0])\n#print(data)\n\nwith open('Plugin-Filter.txt','w') as f:\n for version,name in data:\n print(name,type(name))\n if name.startswith('Plugin-Filter'):\n f.write(name + '\\n')\n\n\n\n\n\n","sub_path":"filenamesort.py","file_name":"filenamesort.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"67254861","text":"import pygame\nfrom pygame.locals import *\nimport os\nimport sys\nfrom random import uniform\nfrom random import randint\nimport time\nfrom math import floor\n\ndef load_image(nombre, dir_imagen, alpha=False):\n \"\"\"Funcion que retorna una imagen\"\"\"\n # Encontramos la ruta completa de la imagen\n ruta = os.path.join(dir_imagen, nombre)\n try:\n image = pygame.image.load(ruta)\n except:\n print (\"Error, no se puede cargar la imagen: \", ruta)\n sys.exit(1)\n # Comprobar si la imagen tiene \"canal alpha\" (como los png)\n if alpha == True:\n image = image.convert_alpha()\n else:\n image = image.convert()\n return image\n\nclass Corazon(pygame.sprite.Sprite):\n def __init__(self,posx,posy,_cargaImagen):\n pygame.sprite.Sprite.__init__(self)\n self.distancia = 0\n self.frameActual=1\n self.image = load_image(\"Corazon/c1.gif\", \"imagenes\", alpha=True)\n self.rect = Rect(0,0,10,20)\n self.rect.centerx = posx\n self.rect.centery = posy\n self.mov = True\n\n def flechazo(self, baleado):\n if self.rect.colliderect(baleado.rect) and not(baleado.invencible):\n self.kill()\n self.mov = False\n baleado.invencible = True\n return True\n\n def cambiarFrame(self):\n if self.mov == True:\n self.frameActual += 1 \n if self.frameActual>5:\n self.frameActual = 1\n a = self.frameActual//3 + 1\n self.image = load_image(\"Corazon/c\"+str(a)+\".gif\", \"imagenes\", alpha=True)\n\n def mover(self,tiempo,objetivo):\n if objetivo.rect.centerx > self.rect.centerx:\n self.rect.centerx = self.rect.centerx + 3.6*(tiempo/30) \n elif objetivo.rect.centerx < self.rect.centerx:\n self.rect.centerx = self.rect.centerx - 3.6*(tiempo/30)\n if objetivo.rect.centery > self.rect.centery:\n self.rect.centery = self.rect.centery + 3.6*(tiempo/30)\n elif objetivo.rect.centery < self.rect.centery:\n self.rect.centery = self.rect.centery - 3.6*(tiempo/30)\n \n self.distancia+=3.4*(tiempo/30)\n\n if self.distancia>190:\n self.kill()\n self.mov = False","sub_path":"IWBTE/Proyecto 1.1/Corazon.py","file_name":"Corazon.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"176817980","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom layers import *\nfrom data import VOC_300, MOT_300, VOC_512\nimport os\nfrom .networks import vgg, vgg_base, add_extras,extras, mbox, ConvAttention, ConvLSTMCell, ConvGRUCell\n\nclass SSD(nn.Module):\n \"\"\"Single Shot Multibox Architecture\n The network is composed of a base VGG network followed by the\n added multibox conv layers. Each multibox layer branches into\n 1) conv2d for class conf scores\n 2) conv2d for localization predictions\n 3) associated priorbox layer to produce default bounding\n boxes specific to the layer's feature map size.\n See: https://arxiv.org/pdf/1512.02325.pdf for more details.\n\n Args:\n phase: (string) Can be \"test\" or \"train\"\n base: VGG16 layers for input, size of either 300 or 500\n extras: extra layers that feed to multibox loc and conf layers\n head: \"multibox head\" consists of loc and conf conv layers\n \"\"\"\n\n def __init__(self, phase, base, extras, head, num_classes, size=300, top_k=200, thresh=0.01, nms_thresh=0.45, attention=False):\n super(SSD, self).__init__()\n self.phase = phase\n self.num_classes = num_classes\n self.attention_flag = attention\n # if prior=='VOC_300':\n # self.priorbox = PriorBox(VOC_300)\n # elif prior=='MOT_300':\n # self.priorbox = PriorBox(MOT_300)\n # elif prior=='VOC_512':\n # self.priorbox = PriorBox(VOC_512)\n\n # with torch.no_grad():\n # self.priors = self.priorbox.forward().to(self.device)\n self.size = size\n\n # SSD network\n self.backbone = nn.ModuleList(base)\n self.conv4_3_layer = (23, 33)[len(self.backbone)>40]\n # Layer learns to scale the l2 normalized features from conv4_3\n self.L2Norm = L2Norm(512, 20)\n self.extras = nn.ModuleList(extras)\n self.extras_skip = (2, 3)[len(self.backbone)>40]\n self.loc = nn.ModuleList(head[0])\n self.conf = nn.ModuleList(head[1])\n if self.attention_flag:\n self.attention = nn.ModuleList([ConvAttention(512),ConvAttention(256)])\n # ConvAttention(512),ConvAttention(256),\n # ConvAttention(256),ConvAttention(256)])\n print(self.attention)\n if phase == 'test':\n self.softmax = nn.Softmax(dim=1)\n self.detect = Detect(num_classes, 0, top_k=top_k, conf_thresh=thresh, nms_thresh=nms_thresh)\n # num_classes, bkg_label, top_k, conf_thresh, nms_thresh\n\n def forward(self, x):\n \"\"\"Applies network layers and ops on input image(s) x.\n\n Args:\n x: input image or batch of images. Shape: [batch,3*batch,300,300].\n\n Return:\n Depending on phase:\n test:\n Variable(tensor) of output class label predictions,\n confidence score, and corresponding location predictions for\n each object detected. Shape: [batch,topk,7]\n\n train:\n list of concat outputs from:\n 1: confidence layers, Shape: [batch*num_priors,num_classes]\n 2: localization layers, Shape: [batch,num_priors*4]\n 3: priorbox layers, Shape: [2,num_priors*4]\n \"\"\"\n sources = list()\n loc = list()\n conf = list()\n a_map = list()\n # apply vgg up to conv4_3 relu\n for k in range(self.conv4_3_layer):\n x = self.backbone[k](x)\n s = self.L2Norm(x)\n sources.append(s)\n\n # apply vgg up to fc7\n for k in range(self.conv4_3_layer, len(self.backbone)):\n x = self.backbone[k](x)\n sources.append(x)\n\n # apply extra layers and cache source layer outputs\n for k, v in enumerate(self.extras):\n x = F.relu(v(x), inplace=True)\n if k % self.extras_skip == 1:\n sources.append(x)\n\n # apply multibox head to source layers\n if self.attention_flag:\n for i, (f, l, c) in enumerate(zip(sources, self.loc, self.conf)):\n a_map.append(self.attention[i//3](f))\n a_feat = f*a_map[-1]\n loc.append(l(a_feat).permute(0, 2, 3, 1).contiguous()) # [ith_multi_layer, batch, height, width, out_channel]\n conf.append(c(a_feat).permute(0, 2, 3, 1).contiguous())\n else:\n for (f, l, c) in zip(sources, self.loc, self.conf):\n loc.append(l(f).permute(0, 2, 3, 1).contiguous()) # [ith_multi_layer, batch, height, width, out_channel]\n conf.append(c(f).permute(0, 2, 3, 1).contiguous())\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n if self.phase == \"test\":\n output = self.detect(\n loc.view(loc.size(0), -1, 4), # loc preds\n self.softmax(conf.view(-1, self.num_classes)), # conf preds\n self.priors, # default boxes\n )\n else:\n output = (\n loc.view(loc.size(0), -1, 4),\n conf.view(conf.size(0), -1, self.num_classes),\n self.priors,\n )\n return output, tuple(a_map)\n\n def load_weights(self, base_file):\n other, ext = os.path.splitext(base_file)\n if ext == '.pkl' or '.pth':\n print('Loading weights into state dict...')\n self.load_state_dict(torch.load(base_file, map_location=lambda storage, loc: storage))\n print('Finished!')\n else:\n print('Sorry only .pth and .pkl files supported.')\n\nclass TSSD(nn.Module):\n\n def __init__(self, phase, base, extras, head, num_classes, lstm='lstm', size=300,\n top_k=200,thresh= 0.01,nms_thresh=0.45, attention=False,\n tub=0, tub_thresh=1.0, tub_generate_score=0.7):\n super(TSSD, self).__init__()\n self.phase = phase\n self.num_classes = num_classes\n\n # if prior=='VOC_300':\n # self.priorbox = PriorBox(VOC_300)\n # elif prior=='MOT_300':\n # self.priorbox = PriorBox(MOT_300)\n # elif prior=='VOC_512':\n # self.priorbox = PriorBox(VOC_512)\n #\n # with torch.no_grad():\n # self.priors = self.priorbox.forward().to(self.device)\n self.size = size\n self.attention_flag = attention\n # SSD network\n self.backbone = nn.ModuleList(base)\n self.conv4_3_layer = (23, 33)[len(self.backbone)>40]\n # Layer learns to scale the l2 normalized features from conv4_3\n self.L2Norm = L2Norm(512, 20)\n self.extras = nn.ModuleList(extras)\n self.extras_skip = (2, 3)[len(self.backbone)>40]\n self.lstm_mode = lstm\n\n self.rnn = nn.ModuleList(head[2])\n self.loc = nn.ModuleList(head[0])\n self.conf = nn.ModuleList(head[1])\n print(self.rnn)\n if self.attention_flag:\n in_channel = 512\n self.attention = nn.ModuleList([ConvAttention(in_channel*2), ConvAttention(in_channel)])\n print(self.attention)\n if phase == 'test':\n self.tub = tub\n self.softmax = nn.Softmax(dim=1)\n self.detect = Detect(num_classes, 0, top_k=top_k, conf_thresh=thresh, nms_thresh=nms_thresh,\n tub=tub, tub_thresh=tub_thresh, tub_generate_score=tub_generate_score)\n\n def forward(self, tx, state=None, init_tub=False):\n if self.phase == \"train\":\n rnn_state = [None] * 6\n seq_output = list()\n seq_sources = list()\n seq_a_map = []\n for time_step in range(tx.size(1)):\n x = tx[:,time_step]\n sources = list()\n loc = list()\n conf = list()\n a_map = list()\n\n # apply vgg up to conv4_3 relu\n for k in range(self.conv4_3_layer):\n x = self.backbone[k](x)\n\n s = self.L2Norm(x)\n sources.append(s)\n\n # apply vgg up to fc7\n for k in range(23, len(self.backbone)):\n x = self.backbone[k](x)\n sources.append(x)\n\n # apply extra layers and cache source layer outputs\n for k, v in enumerate(self.extras):\n x = F.relu(v(x), inplace=True)\n if k % self.extras_skip == 1:\n sources.append(x)\n seq_sources.append(sources)\n # apply multibox head to source layers\n if self.attention_flag:\n for i, (x, l, c) in enumerate(zip(sources, self.loc, self.conf)):\n if time_step == 0:\n rnn_state[i] = self.rnn[i // 3].init_state(x)\n a_map.append(self.attention[i//3](torch.cat((x, rnn_state[i][-1]),1)))\n # a_map.append(a(x))\n a_feat = x *a_map[-1]\n # a_feat = self.o_ratio*x + self.a_ratio*x*(a_map[-1])\n rnn_state[i] = self.rnn[i//3](a_feat, rnn_state[i])\n c_current = c(rnn_state[i][-1])\n conf.append(c(rnn_state[i][-1]).permute(0, 2, 3, 1).contiguous())\n loc.append(l(rnn_state[i][-1]).permute(0, 2, 3, 1).contiguous())\n c_previous = c_current\n else:\n for i, (x, l, c) in enumerate(zip(sources, self.loc, self.conf)):\n rnn_state[i] = self.rnn[i//3](x, rnn_state[i])\n conf.append(c(rnn_state[i][-1]).permute(0, 2, 3, 1).contiguous())\n loc.append(l(rnn_state[i][-1]).permute(0, 2, 3, 1).contiguous())\n\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n\n output = (\n loc.view(loc.size(0), -1, 4),\n conf.view(conf.size(0), -1, self.num_classes),\n # self.priors,\n )\n seq_output.append(output)\n seq_a_map.append(tuple(a_map))\n\n return tuple(seq_output), tuple(seq_a_map)\n elif self.phase == 'test':\n\n sources = list()\n loc = list()\n conf = list()\n a_map = list()\n\n # apply vgg up to conv4_3 relu\n for k in range(self.conv4_3_layer):\n tx = self.backbone[k](tx)\n\n s = self.L2Norm(tx)\n sources.append(s)\n\n # apply vgg up to fc7\n for k in range(23, len(self.backbone)):\n tx = self.backbone[k](tx)\n sources.append(tx)\n\n # apply extra layers and cache source layer outputs\n for k, v in enumerate(self.extras):\n tx = F.relu(v(tx), inplace=True)\n if k % self.extras_skip == 1:\n sources.append(tx)\n\n # apply multibox head to source layers\n if self.attention_flag:\n for i, (x, l, c) in enumerate(zip(sources, self.loc, self.conf)):\n if state[i] is None:\n state[i] = self.rnn[i // 3].init_state(x)\n a_map.append(self.attention[i // 3](torch.cat((x, state[i][-1]), 1)))\n # a_map.append(a(x))\n # a_feat = self.o_ratio * x + self.a_ratio * x * (a_map[-1])\n a_feat = x * a_map[-1]\n state[i] = self.rnn[i // 3](a_feat, state[i])\n # conf.append(c(a_feat).permute(0, 2, 3, 1).contiguous())\n # loc.append(l(a_feat).permute(0, 2, 3, 1).contiguous())\n conf.append(c(state[i][-1]).permute(0, 2, 3, 1).contiguous())\n loc.append(l(state[i][-1]).permute(0, 2, 3, 1).contiguous())\n else:\n for i, (x, l, c) in enumerate(zip(sources, self.loc, self.conf)):\n state[i] = self.rnn[i//3](x, state[i])\n conf.append(c(state[i][-1]).permute(0, 2, 3, 1).contiguous())\n loc.append(l(state[i][-1]).permute(0, 2, 3, 1).contiguous())\n\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n if self.tub:\n with torch.no_grad():\n for a_idx, a in enumerate(a_map[:3]):\n if not a_idx:\n tub_tensor = a\n tub_tensor_size = a.size()[2:]\n else:\n tub_tensor = torch.cat((tub_tensor, F.upsample(a, tub_tensor_size, mode='bilinear', align_corners=True)), dim=1)\n if init_tub:\n self.detect.init_tubelets()\n output = self.detect(\n loc.view(loc.size(0), -1, 4), # loc preds\n self.softmax(conf.view(-1, self.num_classes)), # conf preds\n # self.priors, # default boxes\n tub_tensor\n )\n else:\n output = self.detect(\n loc.view(loc.size(0), -1, 4), # loc preds\n self.softmax(conf.view(-1, self.num_classes)), # conf preds\n # self.priors, # default boxes\n )\n\n return output, state, tuple(a_map)\n\n\n def load_weights(self, base_file):\n other, ext = os.path.splitext(base_file)\n if ext == '.pkl' or '.pth':\n print('Loading weights into state dict...')\n self.load_state_dict(torch.load(base_file, map_location=lambda storage, loc: storage))\n print('Finished!')\n else:\n print('Sorry only .pth and .pkl files supported.')\n\ndef multibox(vgg, extra_layers, cfg, num_classes, lstm=None, phase='train', batch_norm=False):\n loc_layers = []\n conf_layers = []\n rnn_layer = []\n vgg_source = ([24, -2], [34, -3])[batch_norm==True]\n for k, v in enumerate(vgg_source):\n\n loc_layers += [nn.Conv2d(vgg[v].out_channels,\n cfg[k] * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(vgg[v].out_channels,\n cfg[k] * num_classes, kernel_size=3, padding=1)]\n key_extra_layers = (extra_layers[1::2], extra_layers[1::3])[batch_norm==True]\n for k, v in enumerate(key_extra_layers, 2):\n\n loc_layers += [nn.Conv2d(v.out_channels, cfg[k]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(v.out_channels, cfg[k]\n * num_classes, kernel_size=3, padding=1)]\n if lstm in ['tblstm']:\n rnn_layer = [ConvLSTMCell(512,512,phase=phase), ConvLSTMCell(256,256,phase=phase)]\n elif lstm in ['gru']:\n rnn_layer = [ConvGRUCell(512,512,phase=phase), ConvGRUCell(256,256,phase=phase)]\n return vgg, extra_layers, (loc_layers, conf_layers, rnn_layer)\n\n\ndef build_net(phase, size=300, num_classes=21, tssd='ssd', top_k=200, thresh=0.01, prior='VOC_300', bn=False,\n nms_thresh=0.45, attention=False, tub=0, tub_thresh=1.0, tub_generate_score=0.7):\n if phase != \"test\" and phase != \"train\":\n print(\"Error: Phase not recognized\")\n return\n if size not in [300, 512]:\n print(\"Error: Sorry only SSD300 is supported currently!\")\n return\n if tssd == 'ssd':\n return SSD(phase, *multibox(vgg(vgg_base[str(size)], 3, batch_norm=bn),\n add_extras(extras[str(size)], 512, batch_norm=bn, size=size),\n mbox[prior], num_classes, phase=phase, batch_norm=bn), num_classes,size=size,\n top_k=top_k,thresh= thresh,nms_thresh=nms_thresh, attention=attention, prior=prior)\n else:\n return TSSD(phase, *multibox(vgg(vgg_base[str(size)], 3, batch_norm=bn),\n add_extras(extras[str(size)], 512, size=size),\n mbox[prior], num_classes, lstm=tssd, phase=phase,batch_norm=bn),\n num_classes, lstm=tssd, size=size, top_k=top_k, thresh=thresh, prior=prior,\n nms_thresh=nms_thresh, attention=attention,\n tub=tub, tub_thresh=tub_thresh, tub_generate_score=tub_generate_score\n )\n","sub_path":"model/ssd.py","file_name":"ssd.py","file_ext":"py","file_size_in_byte":16669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"8485603","text":"\nimport random\n\ndef guess(x):\n low = 1\n high = x #1+x\n feedback = ''\n while feedback !='c':\n if low != high:\n guess = random.randint(low, high)\n else:\n guess = low #could also be high\n\n feedback = input(f\"Is {guess} the correct number(c) or too high(h) or too low(l)??\").lower()\n \n if feedback =='h':\n high = guess - 1\n elif feedback =='l':\n low = guess + 1\n \n print(f\"Yay! I guessed the number {guess} correctly!\")\n\nguess(100)\n","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"450646537","text":"\"\"\"\n\n Strings\n\n\"\"\"\n\ndef camel_case(string):\n string = ''.join(c for c in string.title() if c.isalnum())\n return string[0].lower() + string[1:]\n\ndef capitalize(string):\n return ''.join(c for c in string.upper() if c.isalnum() or c.isspace())\n\ndef ends_with(string, char, index=None):\n if not index:\n index = len(string)\n\n return string[index - 1] == char\n\ndef escape(string):\n return (string.replace('&', '&')\n .replace('>', '>')\n .replace('<', '<')\n .encode('ascii', 'xmlcharrefreplace'))\n\ndef kebab_case(string):\n for i, c in enumerate(string):\n if c.isupper() and i:\n string = string[:i] + '-' + c.lower() + string[i + 1:]\n\n if c.isspace() and i:\n string = string[:i + 1] + '-' + string[i + 2:]\n elif not c.isalnum() and i:\n string = string[:i + 1] + '-' + string[i + 2:]\n\n if not string[len(string)-1].isalnum():\n string = string[:len(string)-1]\n\n return ''.join(\n c for c in string.lower() if c.isalnum() or c == '-'\n )\n\ndef lower_case(string):\n for i, c in enumerate(string):\n if c.isupper() and i:\n string = string[:i] + ' ' + c + string[i + 1:]\n\n if not c.isalnum() and not c.isspace():\n string = string.replace(string[i + 1], ' ')\n\n return string.lower()\n\ndef lower_first(string):\n return string[0].lower() + string[1:]\n\ndef pad(string, length, chars):\n computed_length = length - len(string)\n\n if computed_length <= 0:\n return string\n\n left_length, right_length = computed_length // 2, -(-computed_length // 2)\n\n before, after = '', ''\n\n i = 0\n while i < left_length:\n try:\n before += chars[i]\n i += 1\n except IndexError:\n left_length = left_length - len(chars)\n i = 0\n\n i = 0\n while i < right_length:\n try:\n after += chars[i]\n i += 1\n except IndexError:\n right_length = right_length - len(chars)\n i = 0\n\n return before + string + after\n\ndef repeat(string, n=1):\n return string * n\n\ndef replace(string, pattern, replacement):\n return string.replace(pattern, replacement)\n\ndef snake_case(string):\n for i, c in enumerate(string):\n if c.isupper() and i:\n string = string[:i] + '_' + c.lower() + string[i + 1:]\n\n if c.isspace() and i:\n string = string[:i + 1] + '_' + string[i + 2:]\n elif not c.isalnum() and i:\n string = string[:i + 1] + '_' + string[i + 2:]\n\n if not string[len(string)-1].isalnum():\n string = string[:len(string)-1]\n\n return ''.join(c for c in string.lower() if c.isalnum() or c == '_')\n","sub_path":"src/strings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"286556158","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 7 17:00:31 2019\n\n@author: illenium\n\"\"\"\nraio = float(input())\n\npi = 3.14159\n\narea = pi * raio**2\n\nprint(\"A={0:.4f}\".format(area))\n","sub_path":"python/1002.py","file_name":"1002.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"414147777","text":"# -*- coding: utf-8 -*-\n\n\"\"\"PyOBO's Resolution Service.\n\nRun with ``python -m pyobo.apps.resolver``\n\"\"\"\n\nimport gzip\nimport logging\nimport os\nfrom collections import Counter, defaultdict\nfrom pathlib import Path\nfrom typing import Mapping, Optional, Union\n\nimport pandas as pd\nfrom flasgger import Swagger\nfrom flask import Blueprint, Flask, current_app, jsonify, render_template\nfrom flask_bootstrap import Bootstrap\nfrom humanize import intcomma\nfrom humanize.filesize import naturalsize\nfrom tqdm import tqdm\nfrom werkzeug.local import LocalProxy\n\nimport pyobo\nfrom pyobo.apps.resolver.backends import Backend, MemoryBackend, RawSQLBackend\nfrom pyobo.resource_utils import ensure_alts, ensure_definitions, ensure_ooh_na_na\n\nlogger = logging.getLogger(__name__)\n\nresolve_blueprint = Blueprint(\"resolver\", __name__)\n\nbackend: Backend = LocalProxy(lambda: current_app.config[\"resolver_backend\"])\n\n\n@resolve_blueprint.route(\"/\")\ndef home():\n \"\"\"Serve the home page.\"\"\"\n return render_template(\n \"home.html\",\n name_count=intcomma(backend.count_names()),\n alts_count=intcomma(backend.count_alts()),\n prefix_count=intcomma(backend.count_prefixes()),\n definition_count=intcomma(backend.count_definitions()),\n )\n\n\n@resolve_blueprint.route(\"/resolve/\")\ndef resolve(curie: str):\n \"\"\"Resolve a CURIE.\n\n The goal of this endpoint is to resolve a CURIE.\n\n - ``doid:14330``, an exact match to the CURIE for Parkinson's disease in the Disease Ontology\n - ``DOID:14330``, a close match to the CURIE for Parkinson's disease in the Disease Ontology, only differing\n by capitalization\n - ``do:14330``, a match to doid via synonyms in the metaregistry. Still resolves to Parkinson's disease\n in the Disease Ontology.\n ---\n parameters:\n - name: curie\n in: path\n description: compact uniform resource identifier (CURIE) of the entity\n required: true\n type: string\n example: doid:14330\n \"\"\"\n return jsonify(backend.resolve(curie))\n\n\n@resolve_blueprint.route(\"/summary\")\ndef summary():\n \"\"\"Serve the summary page.\"\"\"\n return render_template(\n \"summary.html\",\n summary_df=backend.summary_df(),\n )\n\n\n@resolve_blueprint.route(\"/summary.json\")\ndef summary_json():\n \"\"\"Summary of the content in the service.\"\"\"\n return jsonify(backend.summarize_names())\n\n\n@resolve_blueprint.route(\"/size\")\ndef size():\n \"\"\"Return how much memory we're taking.\n\n Doesn't work if you're running with Gunicorn because it makes child processes.\n \"\"\"\n try:\n import psutil\n except ImportError:\n return jsonify({})\n process = psutil.Process(os.getpid())\n n_bytes = process.memory_info().rss # in bytes\n return jsonify(\n n_bytes=n_bytes,\n n_bytes_human=naturalsize(n_bytes),\n )\n\n\ndef get_app(\n name_data: Union[None, str, pd.DataFrame] = None,\n alts_data: Union[None, str, pd.DataFrame] = None,\n defs_data: Union[None, str, pd.DataFrame] = None,\n lazy: bool = False,\n sql: bool = False,\n uri: Optional[str] = None,\n refs_table: Optional[str] = None,\n alts_table: Optional[str] = None,\n defs_table: Optional[str] = None,\n) -> Flask:\n \"\"\"Build a flask app.\n\n :param name_data: If none, uses the internal PyOBO loader. If a string, assumes is a gzip and reads a\n dataframe from there. If a dataframe, uses it directly. Assumes data frame has 3 columns - prefix,\n identifier, and name and is a TSV.\n :param alts_data: If none, uses the internal PyOBO loader. If a string, assumes is a gzip and reads a\n dataframe from there. If a dataframe, uses it directly. Assumes data frame has 3 columns - prefix,\n alt identifier, and identifier and is a TSV.\n :param lazy: don't load the full cache into memory to run\n :param sql_table: Use SQL-based backend\n \"\"\"\n app = Flask(__name__)\n Swagger(\n app,\n merge=True,\n config={\n \"title\": \"Bioresolver API\",\n \"description\": \"Resolves CURIEs to their names, definitions, and other attributes.\",\n \"contact\": {\n \"responsibleDeveloper\": \"Charles Tapley Hoyt\",\n \"email\": \"cthoyt@gmail.com\",\n },\n },\n )\n Bootstrap(app)\n\n app.config[\"resolver_backend\"] = _get_resolver(\n name_data=name_data,\n alts_data=alts_data,\n defs_data=defs_data,\n lazy=lazy,\n sql=sql,\n uri=uri,\n refs_table=refs_table,\n alts_table=alts_table,\n defs_table=defs_table,\n )\n app.register_blueprint(resolve_blueprint)\n\n @app.before_first_request\n def before_first_request():\n logger.info(\"before_first_request\")\n backend.count_prefixes()\n backend.count_alts()\n backend.count_names()\n\n return app\n\n\ndef _get_resolver(\n name_data: Union[None, str, pd.DataFrame] = None,\n alts_data: Union[None, str, pd.DataFrame] = None,\n defs_data: Union[None, str, pd.DataFrame] = None,\n lazy: bool = False,\n sql: bool = False,\n uri: Optional[str] = None,\n refs_table: Optional[str] = None,\n alts_table: Optional[str] = None,\n defs_table: Optional[str] = None,\n) -> Backend:\n if sql:\n logger.info(\"using raw SQL backend\")\n return RawSQLBackend(\n engine=uri,\n refs_table=refs_table,\n alts_table=alts_table,\n defs_table=defs_table,\n )\n\n if lazy:\n name_lookup = None\n elif name_data is None:\n name_lookup = _get_lookup_from_path(ensure_ooh_na_na())\n elif isinstance(name_data, str):\n name_lookup = _get_lookup_from_path(name_data)\n elif isinstance(name_data, pd.DataFrame):\n name_lookup = _get_lookup_from_df(name_data)\n else:\n raise TypeError(f\"invalid type for `name_data`: {name_data}\")\n\n if lazy:\n alts_lookup = None\n elif alts_data is None and not lazy:\n alts_lookup = _get_lookup_from_path(ensure_alts())\n elif isinstance(alts_data, str):\n alts_lookup = _get_lookup_from_path(alts_data)\n elif isinstance(alts_data, pd.DataFrame):\n alts_lookup = _get_lookup_from_df(alts_data)\n else:\n raise TypeError(f\"invalid type for `alt_data`: {alts_data}\")\n\n if lazy:\n defs_lookup = None\n elif defs_data is None and not lazy:\n defs_lookup = _get_lookup_from_path(ensure_definitions())\n elif isinstance(defs_data, str):\n defs_lookup = _get_lookup_from_path(defs_data)\n elif isinstance(defs_data, pd.DataFrame):\n defs_lookup = _get_lookup_from_df(defs_data)\n else:\n raise TypeError(f\"invalid type for `defs_data`: {defs_data}\")\n\n return _prepare_backend_with_lookup(\n name_lookup=name_lookup,\n alts_lookup=alts_lookup,\n defs_lookup=defs_lookup,\n )\n\n\ndef _prepare_backend_with_lookup(\n name_lookup: Optional[Mapping[str, Mapping[str, str]]] = None,\n alts_lookup: Optional[Mapping[str, Mapping[str, str]]] = None,\n defs_lookup: Optional[Mapping[str, Mapping[str, str]]] = None,\n) -> Backend:\n get_id_name_mapping, summarize_names = _h(name_lookup, pyobo.get_id_name_mapping)\n get_alts_to_id, summarize_alts = _h(alts_lookup, pyobo.get_alts_to_id)\n get_id_definition_mapping, summarize_definitions = _h(\n defs_lookup, pyobo.get_id_definition_mapping\n )\n\n return MemoryBackend(\n get_id_name_mapping=get_id_name_mapping,\n get_alts_to_id=get_alts_to_id,\n get_id_definition_mapping=get_id_definition_mapping,\n summarize_names=summarize_names,\n summarize_alts=summarize_alts,\n summarize_definitions=summarize_definitions,\n )\n\n\ndef _h(lookup, alt_lookup):\n if lookup is None: # lazy mode, will download/cache data as needed\n return alt_lookup, Counter\n\n def _summarize():\n return Counter({k: len(v) for k, v in lookup.items()})\n\n return lookup.get, _summarize\n\n\ndef _get_lookup_from_df(df: pd.DataFrame) -> Mapping[str, Mapping[str, str]]:\n lookup = defaultdict(dict)\n it = tqdm(df.values, total=len(df.index), desc=\"loading mappings\", unit_scale=True)\n for prefix, identifier, name in it:\n lookup[prefix][identifier] = name\n return dict(lookup)\n\n\ndef _get_lookup_from_path(path: Union[str, Path]) -> Mapping[str, Mapping[str, str]]:\n lookup = defaultdict(dict)\n with gzip.open(path, \"rt\") as file:\n _ = next(file)\n for line in tqdm(file, desc=\"loading mappings\", unit_scale=True):\n prefix, identifier, name = line.strip().split(\"\\t\")\n lookup[prefix][identifier] = name\n return dict(lookup)\n","sub_path":"src/pyobo/apps/resolver/resolver.py","file_name":"resolver.py","file_ext":"py","file_size_in_byte":8628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"594383625","text":"import json\nimport pathlib\nfrom contextlib import ExitStack\nfrom glob import glob\nfrom typing import Optional, Tuple\n\nimport click\nimport confluent_kafka\nimport pendulum\nfrom confluent_kafka import Message\nfrom confluent_kafka.avro import AvroProducer\n\nfrom esque.avromessage import AvroFileReader, AvroFileWriter\nfrom esque.config import Config\nfrom esque.errors import raise_for_kafka_error, raise_for_message, MessageEmptyException\nfrom esque.helpers import delivery_callback, delta_t\nfrom esque.message import KafkaMessage, PlainTextFileReader, PlainTextFileWriter, FileReader, FileWriter\nfrom esque.schemaregistry import SchemaRegistryClient\nfrom abc import ABC, abstractmethod\n\n\nclass AbstractConsumer(ABC):\n def __init__(self, group_id: str, topic_name: str, last: bool):\n offset_reset = \"earliest\"\n if last:\n offset_reset = \"latest\"\n\n self._config = Config().create_confluent_config()\n self._config.update(\n {\n \"group.id\": group_id,\n \"error_cb\": raise_for_kafka_error,\n # We need to commit offsets manually once we\"re sure it got saved\n # to the sink\n \"enable.auto.commit\": True,\n \"enable.partition.eof\": False,\n # We need this to start at the last committed offset instead of the\n # latest when subscribing for the first time\n \"default.topic.config\": {\"auto.offset.reset\": offset_reset},\n }\n )\n self._consumer = confluent_kafka.Consumer(self._config)\n self._subscribe(topic_name)\n\n def _subscribe(self, topic: str) -> None:\n self._consumer.subscribe([topic])\n\n @abstractmethod\n def consume(self, amount: int) -> int:\n pass\n\n def _consume_single_message(self, timeout=30) -> Optional[Message]:\n message = self._consumer.poll(timeout=timeout)\n raise_for_message(message)\n return message\n\n\nclass PingConsumer(AbstractConsumer):\n def consume(self, amount: int) -> Optional[Tuple[str, int]]:\n message = self._consume_single_message()\n\n msg_sent_at = pendulum.from_timestamp(float(message.value()))\n delta_sent = pendulum.now() - msg_sent_at\n return message.key(), delta_sent.microseconds / 1000\n\n\nclass FileConsumer(AbstractConsumer):\n def __init__(self, group_id: str, topic_name: str, working_dir: pathlib.Path, last: bool):\n super().__init__(group_id, topic_name, last)\n self.working_dir = working_dir\n offset_reset = \"earliest\"\n if last:\n offset_reset = \"latest\"\n\n self._config.update({\"default.topic.config\": {\"auto.offset.reset\": offset_reset}})\n self._consumer = confluent_kafka.Consumer(self._config)\n self._subscribe(topic_name)\n\n def consume(self, amount: int) -> int:\n counter = 0\n file_writers = {}\n with ExitStack() as stack:\n while counter < amount:\n try:\n message = self._consume_single_message()\n except MessageEmptyException:\n return counter\n\n if message.partition() not in file_writers:\n partition = message.partition()\n file_writer = self.get_file_writer(partition)\n stack.enter_context(file_writer)\n file_writers[partition] = file_writer\n\n file_writer = file_writers[partition]\n file_writer.write_message_to_file(message)\n counter += 1\n\n return counter\n\n def get_file_writer(self, partition: int) -> FileWriter:\n return PlainTextFileWriter((self.working_dir / f\"partition_{partition}\"))\n\n\nclass AvroFileConsumer(FileConsumer):\n def __init__(self, group_id: str, topic_name: str, working_dir: pathlib.Path, last: bool):\n super().__init__(group_id, topic_name, working_dir, last)\n self.schema_registry_client = SchemaRegistryClient(Config().schema_registry)\n\n def get_file_writer(self, partition: int) -> FileWriter:\n return AvroFileWriter((self.working_dir / f\"partition_{partition}\"), self.schema_registry_client)\n\n\nclass Producer(ABC):\n def __init__(self):\n self.queue_length = 100000\n self.internal_queue_length_limit = self.queue_length / 0.5\n self._config = Config().create_confluent_config()\n self._config.update(\n {\n \"on_delivery\": delivery_callback,\n \"error_cb\": raise_for_kafka_error,\n \"queue.buffering.max.messages\": self.queue_length,\n }\n )\n\n @abstractmethod\n def produce(self, topic_name: str) -> int:\n pass\n\n\nclass PingProducer(Producer):\n def __init__(self):\n super().__init__()\n self._producer = confluent_kafka.Producer(self._config)\n\n def produce(self, topic_name: str) -> int:\n start = pendulum.now()\n self._producer.produce(topic=topic_name, key=str(0), value=str(pendulum.now().timestamp()))\n while True:\n left_messages = self._producer.flush(1)\n if left_messages == 0:\n break\n click.echo(f\"{delta_t(start)} | Still {left_messages} messages left, flushing...\")\n return 1\n\n\nclass FileProducer(Producer):\n def __init__(self, working_dir: pathlib.Path):\n super().__init__()\n self._producer = confluent_kafka.Producer(self._config)\n self.working_dir = working_dir\n\n def produce(self, topic_name: str) -> int:\n path_list = glob(str(self.working_dir / \"partition_*\"))\n counter = 0\n for partition_path in path_list:\n with self.get_file_reader(pathlib.Path(partition_path)) as file_reader:\n for message in file_reader.read_from_file():\n self.produce_message(topic_name, message)\n left_messages = self._producer.flush(0)\n if left_messages > self.internal_queue_length_limit:\n self.flush_all()\n counter += 1\n self.flush_all()\n\n return counter\n\n def flush_all(self):\n while True:\n left_messages = self._producer.flush(1)\n if left_messages == 0:\n break\n click.echo(f\"Still {left_messages} messages left, flushing...\")\n\n def get_file_reader(self, directory: pathlib.Path) -> FileReader:\n return PlainTextFileReader(directory)\n\n def produce_message(self, topic_name: str, message: KafkaMessage):\n self._producer.produce(topic=topic_name, key=message.key, value=message.value, partition=message.partition)\n\n\nclass AvroFileProducer(FileProducer):\n def __init__(self, working_dir: pathlib.Path):\n super().__init__(working_dir)\n self._config.update({\"schema.registry.url\": Config().schema_registry})\n self._producer = AvroProducer(self._config)\n\n def get_file_reader(self, directory: pathlib.Path) -> FileReader:\n return AvroFileReader(directory)\n\n def produce_message(self, topic_name: str, message: KafkaMessage):\n self._producer.produce(\n topic=topic_name,\n key=json.loads(message.key),\n value=json.loads(message.value),\n key_schema=message.key_schema,\n value_schema=message.value_schema,\n partition=message.partition,\n )\n","sub_path":"esque/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":7398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"50602602","text":"# ===============================================================================\n#\n# Copyright (C) 2003 Martin Furter \n# Copyright (C) 2013 Tom Taxon \n#\n# This file is part of SvnDumpTool\n#\n# SvnDumpTool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2, or (at your option)\n# any later version.\n#\n# SvnDumpTool is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with SvnDumpTool; see the file COPYING. If not, write to\n# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.\n#\n# ===============================================================================\n\nfrom __future__ import print_function\n\nfrom optparse import OptionParser\nimport os\nimport re\nimport sys\n\nfrom svndump import __version, SvnDumpFile\n\n\nclass LargeFileLister:\n \"\"\"\n A class for listing the n largest files in a repository\n \"\"\"\n\n def __init__(self, max_files=20):\n \"\"\"\n Creates a LargeFileLister class.\n\n @type max_files: int\n @param max_files: The number of largest files to print\n \"\"\"\n self.__max_files = max_files\n self.__large_files = []\n self.__smallest_file = 0\n\n def process_node(self, dump, node):\n if node.get_kind() == \"file\":\n size = node.get_text_length()\n if size > self.__smallest_file:\n self.__large_files.append((size, dump.get_rev_nr(), node))\n self.__large_files.sort(key=lambda tup: tup[0])\n if len(self.__large_files) > self.__max_files:\n self.__large_files.pop(0)\n if len(self.__large_files) == self.__max_files:\n self.__smallest_file = self.__large_files[0][0]\n\n def done(self, dump):\n self.__large_files.reverse()\n max_size = self.__large_files[0][0]\n max_rev = 0\n for tup in self.__large_files:\n max_rev = max(max_rev, tup[1])\n size_len = max(4, len(str(max_size)))\n rev_len = max(8, len(str(max_rev)))\n print(\" %-*s %-*s Path\" % (size_len, \"Size\", rev_len, \"Revision\"))\n for tup in self.__large_files:\n print(\" %*d %*d %s\" % (size_len, tup[0], rev_len, tup[1], tup[2].get_path()))\n\n\ndef list_files(srcfile, lister):\n \"\"\"\n List the largest files from the dump file.\n\n @type srcfile: string\n @param srcfile: Source filename.\n @type dstfile: string\n @param dstfile: Destination filename.\n \"\"\"\n\n # SvnDumpFile classes for reading/writing dumps\n srcdmp = SvnDumpFile()\n # open source file\n srcdmp.open(srcfile)\n hasrev = srcdmp.read_next_rev()\n if hasrev:\n while hasrev:\n if srcdmp.get_node_count() > 0:\n for node in srcdmp.get_nodes_iter():\n lister.process_node(srcdmp, node)\n hasrev = srcdmp.read_next_rev()\n else:\n print(\"no revisions in the source dump '%s' ???\" % srcfile)\n lister.done(srcdmp)\n\n # cleanup\n srcdmp.close()\n\n\ndef svndump_list_large_files(appname, args):\n \"\"\"\n Parses the commandline and lists the large files based on the options.\n\n Usage:\n\n >>> svndump_list_arge_files( sys.argv[0], sys.argv[1:] )\n\n @type appname: string\n @param appname: Name of the application (used in help text).\n @type args: list( string )\n @param args: Commandline arguments.\n @rtype: integer\n @return: Return code (0 = OK).\n \"\"\"\n\n usage = \"usage: %s source\" % appname\n usage += \"\\n\\nThis command lists the largest files in the dump file\"\n parser = OptionParser(usage=usage, version=\"%prog \" + __version)\n\n parser.add_option(\"-n\", \"--num\", action=\"store\", type=\"int\", dest=\"max_files\", default=20,\n help=\"the maximum number of files to show (default=20).\")\n\n (options, args) = parser.parse_args(args)\n\n if len(args) != 1:\n print(\"Specify a dump file from which to list the large files\")\n return 1\n\n list_files(args[0], LargeFileLister(options.max_files))\n return 0\n","sub_path":"svndump/listfiles.py","file_name":"listfiles.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"626437152","text":"# video writer\n# * writes frames at a fixed rate even if camera's rate varies or is imprecise,\n# possibly dropping or repeating frames in the process\n# (note: for LifeCam, the frame rate depends on the exposure)\n# * also writes trajectories (which need to be in sync with frames written)\n# * stop() needs to be called at the end of video, unless VideoWriter is\n# instantiated with \"with\"\n# code comes from\n# Ulrich Stern\n# https://github.com/ulrichstern/SkinnerTrax/blob/master/rt-trx/rt-trx.py\n# modified by Matias Andina 2020-02-01\n\nimport queue\nimport threading\nimport cv2\nimport time\nimport numpy as np\n\nclass VideoWriter:\n\n _EXT = \".avi\"\n\n # note: extension \".avi\" will be added to given video filename\n def __init__(self, filename=None, fps=20.0, resolution = (640,480)):\n self.filename = filename \n self.empty_filename = filename is None\n if self.empty_filename:\n return\n print (\"\\nwriting video to %s\" %filename)\n if resolution is None:\n resolution = (320, 240)\n\n self.fourcc = cv2.VideoWriter_fourcc(*'XVID')\n self.fps = fps\n self.dt = 1.0/fps\n self.resolution = resolution\n # We will put frames on a queue and get them from there\n self.q = queue.Queue()\n self._stop = False\n # n is the frame number\n self.n = 0 \n self.wrtr = threading.Thread(target=self.recorder)\n self.wrtr.start()\n\n # writer thread\n def recorder(self):\n # initialize things to None\n # we will receive tuples, lastframe_ts has the frame and timestamp\n lastframe_ts = t0 = video_writer = None\n while True:\n if self._stop:\n break\n frame_ts = lastframe_ts\n # while we have frames in queue get most recent frame\n while not self.q.empty():\n # get queue as tupple\n frame_ts = self.q.get_nowait()\n # only do things with frames that are not None\n if frame_ts is not None:\n lastframe_ts = frame_ts\n # unpack\n frame, ts = frame_ts\n if video_writer is None:\n # initialize cv2 video_writer\n video_writer = cv2.VideoWriter(self.filename + self._EXT,\n self.fourcc,\n self.fps,\n self.resolution,\n isColor= self.is_color(frame))\n t0 = time.time()\n # write frame\n video_writer.write(frame)\n # write timestamp\n self.write_timestamp(timestamp=ts)\n self.n += 1\n if t0 is None:\n dt = self.dt\n else:\n dt = max(0, t0 + self.n * self.dt - time.time())\n # this will put the thread to sleep to satisfy frame rate\n time.sleep(dt)\n\n # for \"with\"\n def __enter__(self): return self\n def __exit__(self, exc_type, exc_value, traceback):\n if not self.empty_filename and not self._stop:\n self.stop()\n\n # write frame; can be called at rate different from fps\n def put_to_q(self, frame, timestamp):\n if not self.empty_filename:\n # put frame and timestamp as tupple into queue\n self.q.put((frame, timestamp))\n\n\n # returns number (0,1,...) of next frame written to video; None if no video\n # written\n def frameNum(self): return None if self.empty_filename else self.n\n\n # returns the video filename (without extension), None if no video written\n def filename(self): return self.filename\n\n # stop video writer\n def stop(self):\n if not self.empty_filename:\n self._stop = True\n self.wrtr.join()\n\n def is_color(self, frame):\n if (len(frame.shape) == 3):\n return True\n else:\n return False\n\n def write_timestamp(self, timestamp):\n # '%Y-%m-%dT%H:%M:%S.%f' is better than '%Y-%m-%dT%H:%M:%S:%f'\n timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f')\n # this will write timestamps to file\n # mind that timestamp must be in a [] for numpy to like it\n with open(self.filename + \"_timestamp.csv\",'a') as outfile:\n np.savetxt(outfile, [timestamp],\n delimiter=',', fmt='%s')\n","sub_path":"camera/videowriter.py","file_name":"videowriter.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"446175703","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 26 21:08:39 2018\n\n@author: yuta\n\"\"\"\nimport time\nfrom Q_H01 import*\nimport itertools\nfrom scipy.stats import binom\nfrom numpy.random import*\nimport matplotlib.pyplot as plt\n\"\"\"\nこのクラスはベイズ推定のためのクラスです.\n効用はベイズリスク、エントロピーが選べます。\n確率のルックアップテーブルは十字に計算するか、全て計算するか選ぶことが出来ます。\n\"\"\"\nclass Bayes_Function(Q_H):\n \"\"\"\n ベイズ推定のメソッドをまとめたクラス\n \"\"\"\n def __init__(self):\n \"\"\"\n 変数にデフォルト値を代入\n \"\"\"\n Q_H.__init__(self)\n self.ex=100 #試行回数\n self.i=0 #現在の試行回数\n self.n=100 #推定��底毎のパーティクルの数\n self.g=100 #量子操作において変更するパラメータの分割数\n self.d=1000 #一度の推定に使用する実験データの数\n self.a=0.75 #パーティクルの再配分における移動強度\n self.resample_threshold=0.5 #パーティクルの再配分を行う判断をする閾値\n self.approx_ratio=0.98 #不要なパーティクルを削除する際の残す割合\n self.bayes_threshold=1 #推定を終えるベイズリスクの閾値\n self.mode=1 #Expsimの測定モード(1:確率,0:射影測定)\n self.state=0 #0:ms=0で射影測定,1:ms=±1で射影測定\n self.flag1=False #パーティクルの数が変化したらTrue\n self.flag2=False #実験設計の数が変化したらTrue\n self.Q=0\n self.U=0\n self.B_R=0 #ベイズリスク\n self.Utility=\"binomial\"\n self.ptable_mode=\"all\" #all or cross\n #結果格納配列\n self.i_list=[]\n self.ptable_C=[]\n self.ptable_x=[]\n self.ptable=[]\n self.risk=[]\n #パーティクル\n self.w=0 #現在のパーティクルの重みs\n self.ParamH=[1,0,0,0,0] #変更するパーティクルのパラメータ\n self.RangeH=[10] #変更する範囲\n #実験設計\n self.OMEGA=10 #Rabi周波数の中心[MHz]\n self.t=0.05 #MWパルス長[us]\n self.MWf=2870 #MW周波数の中心[MHz]\n self.ParamC=[1,0,0] #変更する量子操作のパラメータ\n self.RangeC=[5,0,0] #変更する範囲\n self.C_best=0\n self.C_best_i=0\n #GRAPE\n self.omega_j=[]\n self.U_grape=[]\n \n def params(self):\n self.x0=[self.D0, self.AN, self.QN, self.Be+self.Bo] #真のハミルトニアン\n self.D=np.empty([self.d,1])\n self.x=[self.D0-3, self.AN-0.05, self.QN, self.Be+self.Bo] #現在のパーティクル\n self.x_first=self.x\n \n \n def n_particles(self):\n \"\"\"\n パーティクルの数を返す\n \"\"\"\n if self.i==0:\n n_p=self.n ** sum(self.ParamH)\n else:\n n_p=len(self.w)\n return n_p\n \n def n_exp(self):\n \"\"\"\n 実験設計の数を返す\n \"\"\"\n if self.i==0:\n n_C=self.g ** sum(self.ParamC)\n else:\n n_C=len(self.U)\n return n_C\n \n def Mean(self,w,x): #重み付き平均を計算する関数\n \"\"\"\n w:重み\n x:パラメータ\n wで重みづけされたxの平均を返す\n \"\"\"\n i=0\n n=len(w)\n m=len(x[0])\n mu=np.zeros([1,m])\n for i in range(n):\n mu=mu+w[i][0]*x[i]\n return mu\n \n def init_C(self):\n \"\"\"\n 実験設計の初期値代入\n \"\"\"\n self.C=[self.OMEGA, self.t, self.MWf]\n \n def init_w(self):\n \"\"\"\n 重みを一様分布に初期化\n \"\"\"\n n_p=self.n_particles()\n self.w=np.ones([n_p,1])\n \n def init_U(self):\n \"\"\"\n 効用を一様分布に初期化\n \"\"\"\n n_C=self.n_exp()\n self.U=np.ones([n_C,1])\n \n def init_R(self):\n \"\"\"\n ベイズリスクを一様分布に初期化\n \"\"\"\n n_C=self.n_exp()\n self.B_R=np.ones([n_C,1])\n \n def init_x(self):\n \"\"\"\n パーティクルの中心を生成\n ここでは炭素の超微細相互作用を追加\n \"\"\"\n for Ac in self.Ac_list:\n self.x.append(Ac)\n \n def init_x0(self):\n \"\"\"\n パーティクルの真値を生成\n ここでは炭素の超微細相互作用を追加\n \"\"\"\n for Ac in self.Ac_list:\n self.x0.append(Ac)\n \n def weighting_matrix(self):\n \"\"\"\n ベイズリスクの重み行列を作成\n ParamHの要素が1ならば対応する重み行列の要素も1\n つまり、ベイズリスクを考慮する\n \"\"\"\n self.Q=np.zeros([len(self.x0), len(self.x0)])\n for i in range(len(self.ParamH)):\n p=self.ParamH[i]\n self.Q[i][i]=p\n \n def resample(self,w,x): #パーティクルの移動と重みの再配分を行う関数\n \"\"\"\n a:resample強度\n 各パーティクルをx=a*x+(1-a)*x_averageに移動させる\n つまり、各パーティクルを分布の中心に寄せる\n \"\"\"\n i=0\n n=len(w)\n m=len(x[0])\n mu=self.Mean(w,x)\n mui=np.zeros([1,m])\n for i in range(n):\n if w[i]<1.0/n*self.a:\n mui=self.a*x[i]+(1-self.a)*mu\n x[i]=mui\n w[i][0]=1.0/n\n print (\"resample\")\n return w,x\n \n def reapprox_par(self): #不要となったパーティ���ルを削除する関数\n \"\"\"\n m:残すパーティクルの数\n ws:昇順に並び替えた重み\n wsの(m+1)番目の要素よりも大きい重みのパーティクルは残す\n \"\"\"\n n=len(self.w)\n ws=sorted(self.w)\n m=floor(n*(1.0-self.approx_ratio))\n if m<1:\n m=0\n j=0\n delist=[]\n while j!=m:\n i=0\n for i in range(n):\n if self.w[i]==ws[j] and n!=0:\n delist.append(i)\n j=j+1\n if j==m:\n break\n self.w=np.delete(self.w,delist,0)\n self.w=self.w/sum(self.w)\n self.x=np.delete(self.x,delist,0)\n if n != len(self.w):\n self.flag1=True\n print(\"reapprox_exp\")\n else:\n self.flag1=False\n \n def reapprox_exp(self): #不要となったパーティクルを削除する関数\n \"\"\"\n m:残すパーティクルの数\n ws:昇順に並び替えた重み\n wsの(m+1)番目の要素よりも大きい重みのパーティクルは残す\n \"\"\"\n n=len(self.U)\n Us=sorted(self.U)\n m=floor(n*(1.0-self.approx_ratio))\n if m<1:\n m=0\n j=0\n delist=[]\n while j!=m:\n i=0\n for i in range(n):\n if self.U[i]==Us[j] and n!=0:\n delist.append(i)\n j=j+1\n if j==m:\n break\n self.U=np.delete(self.U,delist,0)\n self.U=self.U/sum(self.U)\n self.U=np.delete(self.U,delist,0)\n if n != len(self.U):\n self.flag2=True\n print(\"reapprox_exp\")\n else:\n self.flag2=False\n \n def Particlemaker(self,x,n,Param,Range): #パーティクルを生成する関数\n #itertools.product与えられた変数軍([x1,x2,x3],[y1,y2])の総重複なし組み合わせを配列として出力\n \"\"\"\n パーティクルを生成する関数\n 最小値:x-Range/2\n 最大値:x+Range/2\n \"\"\"\n N=len(x)\n temp=[]\n for i in range(N):\n if(Param[i]==1):\n temp.append(np.linspace(x[i]-Range[i]/2,x[i]+Range[i]/2,n))\n else:\n temp.append([x[i]])\n return(np.array(list(itertools.product(*temp))))\n \n def Expsim(self,x,C): #実験と同様のシーケンスを行いデータの生成を行う関数\n \"\"\"\n パーティクルxに実験Cで実験シミュレーションを行う関数\n \"\"\"\n H0=self.H(x)\n HfMW=self.H_rot(C[2]) #C[2]:MW周波数\n VdMW=self.Vdrive(C[0]) #C[0]:ラビ周波数\n rhof=self.Tevo(C[1]) #MWwidth\n expect0=self.exp(rhof) #ms=0で測定\n if self.mode==0:\n if rand()>=expect0:\n mes=1 #ms=+1,-1\n else:\n mes=0 #ms=0\n else:\n if self.state==0:\n mes=expect0\n else:\n mes=1.0-expect0\n if mes<0:\n mes=0\n return mes\n \n def Prob_Lookup(self,x,C): #確率のルックアップテーブルを作る。もっと軽量化したい\n \"\"\"\n 確率のルックアップテーブルを作成する\n allの場合,ルックアップテーブルの形は(パーティクル数 * 実験設計数)\n \"\"\"\n self.mode=1 #Expsimでms=0の確率を算出\n if self.ptable_mode==\"cross\":\n if len(x) == self.n_particles():#各パーティクルについてある実験Cで実験を行う\n self.ptable_x=np.zeros([self.n_particles(),1])\n for i in range(self.n_particles()):\n self.ptable_x[i]=self.Expsim(self.x[i],C) \n else: #あるパーティクルについて全実験設計で実験を行う\n self.ptable_C=np.zeros([self.n_exp(),1])\n for i in range(self.n_exp()):\n self.ptable_C[i]=self.Expsim(x,self.C[i])\n \n elif (self.ptable_mode==\"all\"):\n self.ptable=np.zeros([self.n_particles(),self.n_exp()])\n for i in range(self.n_exp()):\n for j in range(self.n_particles()):\n self.ptable[j,i]=self.Expsim(self.x[j],self.C[i])\n \n\n def UtilIG(self): #量子操作の効用を計算する関数\n \"\"\"\n 各パーティクルについてエントロピーを計算する。\n エントロピーをかけて効用の分布を更新する\n \"\"\"\n if self.ptable_mode==\"cross\":\n ent_table = -self.ptable_C*np.log2(self.ptable_C) #エントロピーテーブル(各要素は各々の実験でのエントロピー)\n ent_array = (np.reshape(ent_table,[len(ent_table),1])) #2D配列に変換\n elif self.ptable_mode==\"all\":\n w_ptable = self.ptable*self.w #重み付き確率テーブル\n ent_table = -w_ptable*np.log2(w_ptable) #エントロピーテーブル\n ent_array = np.sum(ent_table,axis=0) #各C行使時における情報量(各パーティクルについてエントロピーの和を取る)\n ent_array = (np.reshape(ent_array,[len(ent_array),1])) #2D配列に変換\n self.U=ent_array*self.U\n self.U=self.U/np.sum(self.U)\n self.C_best_i=np.argmax(self.U)\n self.C_best=self.C[self.C_best_i]\n\n def Update(self): #ベイズ推定を行う関数 引数(self,Ci)\n \"\"\"\n パーティクルの重みを更新する関数\n \"\"\"\n self.mode=1\n p_exp=self.Expsim(self.x0,self.C_best)#真値におけるms0の確立\n num=binomial(self.d, p_exp)#実験をd回行いms=0であった回数\n if self.ptable_mode==\"cross\":\n temp=binom.pmf(num,n=self.d,p=self.ptable_x)#各パーティクルでの実験でms=0にいた確率\n self.w=self.w*temp.reshape([len(temp),1]) #重みの更新\n elif self.ptable_mode==\"all\":\n temp=binom.pmf(num,n=self.d,p=self.ptable)[:,self.C_best_i]#各パーティクルでの実験でms=0にいた確率\n self.w=self.w*temp #重みの更新\n self.w=self.w/np.sum(self.w) #重みの規格化\n \n def UtilIG_bayes_risk(self): #ベイズリスクを計算する関数\n \"\"\"\n ベイズリスクを計算する関数\n \"\"\"\n x_infer=self.Mean(self.w,self.x) \n self.risk.append(np.trace(self.Q*np.dot((self.x - x_infer[0]).T,(self.x - x_infer[0]))))\n \n #=============================結果を描画する関数=============================\n def show_w(self):\n wi=np.linspace(1,self.n_particles(),self.n_particles())\n plt.plot(wi,self.w)\n plt.xlabel(\"particle\")\n plt.ylabel(\"weight (a.u.)\")\n plt.title(\"weight\", fontsize=24)\n plt.show()\n \n def show_U(self):\n Ui=np.linspace(1,self.n_exp(),self.n_exp())\n plt.plot(Ui,self.U)\n plt.xlabel(\"experiment\")\n plt.ylabel(\"Utility (a.u.)\")\n plt.title(\"Utility\", fontsize=24)\n plt.show()\n \n def show_r(self):\n plt.plot(self.i_list,self.risk)\n plt.xlabel(\"experiment\")\n plt.ylabel(\"Bayes_risk \")\n plt.yscale(\"log\")\n plt.title(\"Bayes_risk\", fontsize=24)\n plt.show()\n \n def show_hyper_parameter(self):\n print(\"============================ハイパーパラメータの表示======================\\n\")\n print(\"実験回数:%d\" %(self.i))\n print(\"リサンプリング強度 %f\" %(self.a))\n print(\"リサンプリング閾値 %f\" %(self.resample_threshold))\n print(\"ベイズリスクの閾値 %f\" %(self.bayes_threshold))\n print(\"パーティクルの真の値\")\n print(self.x0)\n print(\"始めのパーティクルの中心\")\n print(self.x_first)\n print(\"推定したパラメータD0, AN, QN, Bz, Ac_list\")\n print(self.ParamH)\n print(self.RangeH)\n print(\"変化させた実験設計とその範囲\")\n print(self.ParamC)\n print(self.RangeC)\n print(\"現在のパーティクルの数:%d\" %(self.n_particles()))\n print(\"ルックアップテーブルの表式 %s\" %(self.ptable_mode))\n \n \n #=================================GRAPE====================================\n def Tevo_operator(self,U_init,width):\n HI=Vd+H0-HfMW\n U=(-2*pi*1j*HI*width).expm()\n Ud=U*U_init\n return Ud\n \n def GRAPEpulse(self):\n m=np.argmax(self.w)\n C_known=[]\n for i in range(len(self.Ac_list)):\n if self.Ac_list[i] != 0:\n C_known.append(self.Ac_list[i])\n grape=GRAPE(self.x[m][0],self.x[m][1],0,C_known,C_inhomo,Be,theta,phi1,phi2,state_init,\n state_goal,weighting_value,permax,pulse_time,t_div,target_list)\n \n phi_array, self.omega_array=grape.optimize()\n return self.omega_array\n \n def GRAPE_operator(self,x,omega_j):\n H0=self.H(x)\n HfMW=self.H_rot(C[2])\n C_list=[]\n for i in range(len(self.Ac_list)):\n C_list.append(2)\n U0=tensor(III,III,self.C_mat)\n U=U0\n for i in range(len(omega_j)):\n VdMW=self.Vdrive(omega_j[i])\n U=self.Tevo_operator(H0,VdMW,HfMW,U,t_div)\n return U","sub_path":"機械学習/サブpy/Bayes_function05.py","file_name":"Bayes_function05.py","file_ext":"py","file_size_in_byte":15135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"312523733","text":"from django.conf import settings\n\ndef get_all_pages_struct():\n\t\"\"\"\n\tReturn an iterator over all distinct pages on the site.\n\tEach page is returned as a tuple consisting of:\n\t(url, search weight, last_modified)\n\n\tIt will do so by looking for the module \"struct\" in all\n\tinstalled applications, and calling the get_struct() function\n\tin all such modules.\n\t\"\"\"\n\tfor app in settings.INSTALLED_APPS:\n\t\tif app.startswith('pgweb.'):\n\t\t\ttry:\n\t\t\t\tm = __import__(app+\".struct\", {}, {}, 'get_struct')\n\t\t\texcept:\n\t\t\t\t# Failed to import - probably module didnd't exist\n\t\t\t\tcontinue\n\n\t\t\tfor x in m.get_struct(): yield x\n","sub_path":"pgweb/util/sitestruct.py","file_name":"sitestruct.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"662808","text":"import os\nimport sys\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nSECRET_KEY = '6f(d+b8s6s@!ko&z110%fur4%vud_9&%3-ve51m-t8gf1g@f)y'\n\nDEBUG = True #SECURITY WARNING: don't run with debug turned on in production!\n\nALLOWED_HOSTS = []\n\nROOT_URLCONF = 'conf.urls'\nWSGI_APPLICATION = 'conf.wsgi.application'\n\nDJANGO_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n]\n\nTHIRDPARTY_APPS = [\n 'whitenoise.runserver_nostatic',\n]\n\n# e.g.: 'apps.appname',\nPROJECT_APPS = [\n]\n\nINSTALLED_APPS = DJANGO_APPS + THIRDPARTY_APPS + PROJECT_APPS\n\nMIDDLEWARE_CLASSES = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n]\n\n\nTEMPLATE_ROOT = os.path.join(BASE_DIR, \"templates/\")\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [TEMPLATE_ROOT],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\n#DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.sqlite3',\n# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n# }\n#}\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Europe/Budapest'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, \"staticfiles/\")\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, \"media/\")\n\nSTATICFILES_DIRS = (\n os.path.join(os.path.join(BASE_DIR, \"static\")),\n)\n\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder'\n)\n\nLOG_ROOT = os.path.join(BASE_DIR, \"logs/\")\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'standard': {\n 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt' : \"%Y/%b/%d %H:%M:%S\"\n },\n },\n 'handlers': {\n 'file': {\n 'level':'DEBUG',\n 'class':'logging.handlers.RotatingFileHandler',\n 'filename': LOG_ROOT + \"/debug.log\",\n 'maxBytes': 50000,\n 'backupCount': 2,\n 'formatter': 'standard',\n },\n 'console':{\n 'level':'INFO',\n 'class':'logging.StreamHandler',\n 'formatter': 'standard'\n },\n },\n 'loggers': {\n 'django': {\n 'handlers':['console'],\n 'propagate': True,\n 'level':'WARNING',\n },\n 'django.db.backends': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n 'MYPROJECT': {\n 'handlers': ['console', 'file'],\n 'level': 'DEBUG',\n },\n }\n}\n","sub_path":"project/conf/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"360474243","text":"class Solution:\n \"\"\"\n @param pattern: a string, denote pattern string\n @param str: a string, denote matching string\n @return: an boolean, denote whether the pattern string and the matching string match or not\n \"\"\"\n\n def wordPattern(self, pattern, str):\n # write your code here\n words, dic, showed = str.split(' '), {}, set()\n if len(words) != len(pattern): return False\n\n for i in range(len(pattern)):\n p, w = pattern[i], words[i]\n if p in dic:\n if w != dic[p]: return False\n else:\n if w in showed: return False\n dic[p] = w\n showed.add(w)\n return True\n","sub_path":"lintcode/828-word-pattern.py","file_name":"828-word-pattern.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"27273438","text":"\n# coding=utf-8\nfrom __future__ import absolute_import\nfrom octoprint.server import user_permission\n\nimport octoprint.plugin\nimport os\nimport flask\nimport sys\nimport shutil\nimport requests\n\nfrom flask import send_file\n\nclass UICustomizerPlugin(octoprint.plugin.StartupPlugin,\n octoprint.plugin.SettingsPlugin,\n octoprint.plugin.AssetPlugin,\n octoprint.plugin.TemplatePlugin,\n octoprint.plugin.EventHandlerPlugin):\n\n def __init__(self):\n self.themeURL = 'https://lazemss.github.io/OctoPrint-UICustomizerThemes/css/'\n self.themeVersion = 'https://api.github.com/repos/LazeMSS/OctoPrint-UICustomizerThemes/releases/latest'\n\n def on_after_startup(self):\n self._logger.info(\"UI Customizer is initialized.\")\n\n def get_assets(self):\n return dict(\n js=[\"js/uicustomizer.js\",\"js/Sortable.min.js\"],\n css=[\"css/uicustomizer.css\"]\n )\n\n def on_settings_initialized(self):\n curTheme = self._settings.get([\"theme\"],merged=True,asdict=True)\n themeLocal = self._settings.get([\"themeLocal\"],merged=True,asdict=True)\n if curTheme:\n self.setThemeFile(curTheme,themeLocal)\n\n def setThemeFile(self,source,localTheme = True,themeVersion = False):\n baseFolder = os.path.join(os.path.dirname(os.path.realpath(__file__)),'static','themes','css')\n targetTheme = os.path.join(baseFolder,'active.css')\n srcTheme = os.path.join(baseFolder,source+'.css')\n\n # Download the file or not\n if localTheme == False and source != \"default\":\n dlURL = self.themeURL+source+\".css\"\n try:\n r = requests.get(dlURL, allow_redirects=True)\n except Exception as e:\n self._logger.error(\"Failed to download theme: %s (%s)\",dlURL,e);\n return\n\n if r.status_code == 200:\n with open(srcTheme, 'wb') as f:\n f.write(r.content)\n self._logger.info(\"Downloaded theme: \"+dlURL)\n else:\n self._logger.warning(\"Unable to download theme: \"+dlURL);\n\n if os.path.exists(baseFolder) and os.path.isfile(srcTheme):\n # remove old\n try:\n os.remove(targetTheme)\n except OSError:\n pass\n\n # symlink on linux else we copy\n if sys.platform.startswith(\"linux\"):\n os.symlink(srcTheme, targetTheme)\n else:\n shutil.copy2(srcTheme, targetTheme)\n\n # Set the theme version\n if themeVersion == False:\n themeVersion = self.getRemoteThemeVersion()\n if themeVersion != False:\n self._settings.set([\"themeVersion\"],str(themeVersion))\n\n else:\n self._logger.warning(\"Unable to set the theme: %s\",srcTheme)\n\n def getRemoteThemeVersion(self):\n try:\n r = requests.get(self.themeVersion, allow_redirects=True)\n except Exception as e:\n self._logger.error(\"Failed to get theme version: %s (%s)\",self.themeVersion,e);\n return False\n if r.status_code == 200:\n jsonVersion = r.json()\n if \"tag_name\" in jsonVersion:\n return jsonVersion['tag_name']\n return False\n\n # Check for new versions on login\n def on_event(self,event,payload):\n if event == \"UserLoggedIn\":\n themeLocal = self._settings.get([\"themeLocal\"],merged=True,asdict=True)\n # Using remote themes?\n if themeLocal == False:\n # Get the remote theme version\n themeVersionRemote = self.getRemoteThemeVersion()\n # Did we get the version no\n if themeVersionRemote != False:\n # Get local versio no\n themeVersionLocal = str(self._settings.get([\"themeVersion\"],merged=True,asdict=True))\n # Different versions?\n if themeVersionLocal != themeVersionRemote:\n themeName = self._settings.get([\"theme\"],merged=True,asdict=True)\n self._logger.info(\"Newer themes found - starting update. %s < %s : %s\", themeVersionLocal, themeVersionRemote,themeName)\n self.setThemeFile(str(themeName),False,themeVersionRemote)\n\n\n def on_settings_save(self,data):\n # save\n octoprint.plugin.SettingsPlugin.on_settings_save(self, data)\n\n # Theme selected - lets fix it\n if 'theme' in data and data['theme']:\n # Local or not\n themeLocal = self._settings.get([\"themeLocal\"],merged=True,asdict=True)\n self._logger.info(\"Setting theme \\\"%s\\\"\",str(data['theme']))\n self.setThemeFile(str(data['theme']),themeLocal)\n\n # default settings\n def get_settings_defaults(self):\n return {\n \"rows\" : [\n {\n \"#sidebar_plugin_firmware_check_wrapper\": True,\n \"#files_wrapper\": True,\n \"#connection_wrapper\": True\n },\n {\n \"div.UICmainTabs\": True\n },\n {\n \"#UICWebCamWidget\": True,\n \"#UICGcodeVWidget\": True,\n \"#state_wrapper\": True,\n \"#sidebar_plugin_action_command_notification_wrapper\": True\n }\n ],\n \"widths\" : [3,6,3],\n \"fluidLayout\" : True,\n \"fixedHeader\" : True,\n \"fixedFooter\" : True,\n \"hideGraphBackground\" : True,\n \"responsiveMode\": True,\n \"navbarplugintempfix\": True,\n \"addWebCamZoom\" : True,\n \"centerTopIcons\": True,\n \"compactMenu\": True,\n \"hideMainCam\": False,\n \"gcodeFullWidth\": False,\n \"filesFullHeight\": True,\n \"compressTempControls\" : True,\n \"disableTermInactive\": False,\n \"mainTabsCustomize\" : True,\n \"mainTabs\": [\n ['control_link',True,False,'fas fa-expand-arrows-alt',True,False],\n ['temp_link',True,False,'fas fa-thermometer-half',True,False],\n ['timelapse_link',True,False,'fas fa-film',True,False],\n ['term_link',True,False,'fas fa-terminal',True,False],\n ['gcode_link',True,False,'fab fa-codepen',True,False],\n ],\n 'mainTabsIconSize': '',\n \"topIconSort\" : [],\n \"gcodeZoom\": 3,\n \"theme\" : \"default\",\n \"themeLocal\" : True,\n \"customCSS\" : \"\",\n \"themeVersion\": \"0\"\n }\n\n def get_template_configs(self):\n return [\n dict(type=\"settings\", custom_bindings=False)\n ]\n\n def get_update_information(self):\n # Define the configuration for your plugin to use with the Software Update\n # Plugin here. See https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html\n # for details.\n return dict(\n uicustomizer=dict(\n displayName=self._plugin_name,\n displayVersion=self._plugin_version,\n\n # version check: github repository\n type=\"github_release\",\n user=\"LazeMSS\",\n repo=\"OctoPrint-UICustomizer\",\n current=self._plugin_version,\n\n # update method: pip\n pip=\"https://github.com/LazeMSS/OctoPrint-UICustomizer/archive/{target_version}.zip\"\n )\n )\n\n\n__plugin_name__ = \"UI Customizer\"\n__plugin_pythoncompat__ = \">=2.7,<4\"\n\ndef __plugin_load__():\n global __plugin_implementation__\n __plugin_implementation__ = UICustomizerPlugin()\n\n global __plugin_hooks__\n __plugin_hooks__ = {\n \"octoprint.plugin.softwareupdate.check_config\": __plugin_implementation__.get_update_information\n }\n","sub_path":"octoprint_uicustomizer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"482794956","text":"import socketserver\nimport logs\nimport controlador_servidor\nimport peticion\nimport respuesta\n\n\nTAMANO_BUFFER = 10240\nHOST = '127.0.0.1'\nPUERTO = 8888\n\nlog = logs.get_logger('Servidor')\n\ncontrolador = controlador_servidor.ControladorServidor()\n\nclass ServidorHandler(socketserver.BaseRequestHandler):\n def handle(self):\n try:\n data = str(self.request.recv(TAMANO_BUFFER),'utf-8').strip()\n log.info('%s envio: %s'%(self.client_address,data))\n pet = peticion.Peticion()\n resp = respuesta.Respuesta()\n try:\n pet.desde_json(data)\n except:\n error = 'Los datos suministrados no tienen formato JSON: %s'%data\n resp.set_error(error)\n log.error(error)\n if not resp.en_error():\n try:\n controlador.procesar_peticion(pet,resp)\n except Exception as e:\n error = str(e)\n resp.set_error(error)\n log.error(error)\n self.request.sendall(bytes(resp.a_json(),'utf-8'))\n except Exception as e:\n log.error(str(e))\n\n\nclass Servidor:\n def iniciar(self):\n socksrv = socketserver.TCPServer((HOST,PUERTO),ServidorHandler)\n log.info('Servidor inicia ejecucion')\n socksrv.serve_forever()\n\nif __name__=='__main__':\n srv = Servidor()\n srv.iniciar()","sub_path":"servidor_socket.py","file_name":"servidor_socket.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"625617457","text":"#print('Hello world')\n#print('hello again')\nimport random,os,sys\nnum = random.randint(0,9)\nclear = lambda: os.system('cls')\nx = int(input('enter any number from 0 to 9'))\nclear()\nif x == num:\n print('you guessed the correct number',x)\nelse :\n print('better luck next time')\n\ns = input('do you want to play again \\ntype yes or no')\nclear()\nif s == 'yes' :\n os.system('practise1.py')\nelif s == 'no' :\n exit()\n\n","sub_path":"practise 1.py","file_name":"practise 1.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"476331645","text":"def main():\r\n #Create list of string\r\n cities = ['New York', 'Boston', 'Atlanta', 'Dallas']\r\n\r\n #Open file for write\r\n outfile = open('cities.txt', 'w')\r\n\r\n #Write lsit to file\r\n for item in cities:\r\n outfile.write(item + '\\n')\r\n\r\n #Close file\r\n outfile.close()\r\n\r\nmain() \r\n","sub_path":"Chap 7/write_list.py","file_name":"write_list.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"514462303","text":"import agentsim\nfrom person import Person\nimport random\nimport callername\n\n# we need to hook in the predicate that tests is one class is permitted\n# to teleport another. You can do importing here because the classes you\n# want to mention are derived from MoveEnhanced.\n\nglobal can_teleport\n\n# need to have the properties of how close is close, and when zombies are\n# close enough to turn a normal into a zombie.\n\nclass MoveEnhanced(Person):\n\n def __init__(self, move_limit = None, **keywords):\n\n \"\"\"\n # fetch and remove the move_limit keyword so that we don't confuse\n # the explicit keywords in the Person constructor\n if \"move_limit\" in keywords:\n move_limit = abs(keywords[\"move_limit\"])\n del(keywords[\"move_limit\"])\n else:\n move_limit = None\n \"\"\"\n\n # now ok to initialize parent\n Person.__init__(self, **keywords)\n\n # initialize the move limit\n self._move_limit = move_limit\n\n if agentsim.debug.get(2):\n print(\"MoveEnhanced\", self._name)\n\n # returns True if self is exactly this class, not a subclass\n def is_exactly_MoveEnhanced(self):\n return repr(MoveEnhanced) == repr(type(self))\n\n def get_move_limit(self):\n return self._move_limit\n\n def get_max_size(self):\n return 60\n\n # overload set_size to prevent setting of size once created for any\n # derived class\n def set_size(self, size):\n # only let callers of the same type as me set my size\n my_name = callername.caller_name(level = 0)\n # get back module.class.method, match just the invoking class\n my_name_parts = my_name.split(\".\")\n my_class = my_name_parts[1]\n pattern = r\"\\.\" + my_class + r\"\\.\"\n callername.caller_name_match(pattern, \n abort = True, debug = agentsim.debug.get(256))\n\n # ok, we can our size, but not too big\n super(MoveEnhanced, self).set_size(min(size, self.get_max_size()))\n\n # when you set your size, also change the move limit\n # nominal move limit is 10, range it from 5 to 15\n\n min_size = self.get_min_size()\n adjust = 10 * (\n (self.get_size() - min_size) / (self.get_max_size() - min_size) )\n\n if my_class == \"Normal\":\n # normals are slow when small, fast when big\n self._move_limit = 5 + adjust\n elif my_class == \"Zombie\":\n # normals are fast when small, slow when big\n self._move_limit = 15 - adjust\n\n # PRIVATE - no derived class is every supposed to call this.\n # it is just to support the simulation.\n\n def _move_to(self, x, y):\n # guard against anyone but the main program or teleport calling me\n callername.caller_name_match(\n \"__main__|^moveenhanced.Defender.teleport$\",\n abort = True,\n debug = agentsim.debug.get(256))\n \n old_move_limit = self._move_limit\n self._move_limit = None\n self.move_by(x - self.get_xpos(), y - self.get_ypos())\n self._move_limit = old_move_limit\n\n # overload move_by to make sure move is limited\n def move_by(self, delta_x, delta_y):\n # guard against anyone but the main program or _move_to calling me\n callername.caller_name_match(r\"__main__|\\._move_to$\",\n abort = True,\n debug = agentsim.debug.get(256))\n\n if self._move_limit is not None:\n delta_d = (delta_x * delta_x + delta_y * delta_y) ** 0.5\n\n if delta_d > self._move_limit:\n delta_x = delta_x * self._move_limit / delta_d\n delta_y = delta_y * self._move_limit / delta_d\n\n # Don't allow you to move onto another person. This means that if \n # you are already on a person, you have to jump off by making a big\n # move.\n\n no_collision = True;\n # only collide with someone present\n for p in Person.get_all_present_instances():\n\n # would we collide with p?\n if self.is_near_after_move(p, delta_x, delta_y):\n if agentsim.debug.get(16):\n print(\"MoveEnhanced.move_by\", self.get_name(), \"would collide with\", p.get_name(), delta_x, delta_y)\n\n no_collision = False\n break\n\n # make the move if no collision\n if no_collision:\n if agentsim.debug.get(16):\n print(\"MoveEnhanced.move_by\", self.get_name(), \"moving by\", delta_x, delta_y)\n super(MoveEnhanced, self).move_by(delta_x, delta_y)\n\n def is_near_after_move(self, target, delta_x, delta_y, epsilon = 0):\n # you are not near yourself\n if self is target: return False\n\n # distances before move\n (d, dx, dy, d_e_e) = self.distances_to(target)\n\n # after move\n dx = dx - delta_x\n dy = dy - delta_y\n d = (dx*dx + dy*dy) ** 0.5 - (self.get_size() + target.get_size()) / 2\n\n r = d <= epsilon \n\n return r\n\n def is_near(self, target, epsilon = 0):\n # you are not near yourself\n if self is target: return False\n\n # near means within epsilon units or overlapping the other\n d_e_e = self.distances_to(target)[3]\n return d_e_e <= epsilon\n\n # if the e_to_e distance is <= this value, two persons are near to \n # touch each other\n def get_touching_threshold(self):\n return 3;\n\n # if the e_to_e distance is <= this, a defender can teleport a zombie\n def get_teleport_threshold(self):\n return 3;\n\n # teleport person target to x_dest, y_dest if allowed.\n def teleport(self, target, x_dest, y_dest):\n if can_teleport is not None and can_teleport(self, target) and self.is_near(target, self.get_teleport_threshold()):\n if agentsim.debug.get(16):\n print(\"{} is teleporting {} to ({}, {})\".format(\n self.get_name(), target.get_name(), x_dest, y_dest))\n\n # the teleport occurs immediately, not bufferred like a move_by.\n # this means you can cheat by repeatedly calling teleport inside\n # the compute_next_move function. \n target._move_to(x_dest, y_dest)\n\n","sub_path":"zombie/moveenhanced.py","file_name":"moveenhanced.py","file_ext":"py","file_size_in_byte":6207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"143762835","text":"from selenium import webdriver\nfrom lxml import etree\nimport requests\nimport time\n\ndriver = webdriver.Chrome()\nurl = \"https://10fastfingers.com/typing-test/simplified-chinese\"\nword_url = \"https://10fastfingers.com/speedtests/get_words\"\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36\"}\n# 1.获取页面数据\ndriver.get(url)\nhtml_str = driver.page_source\nhtml = etree.HTML(html_str)\n# 2.提取单词内容\nwords = html.xpath(\"//div[@id='row1']/span\")\nword_list = []\nfor word in words:\n word_list.append(word.xpath(\"./text()\")[0] if len(word.xpath(\"./text()\"))>0 else None)\nprint(word_list)\n# 3.选中文本框\n# 点击输入文本框\ninput_field = driver.find_element_by_xpath(\".//input[@id='inputfield']\")\n# 4.遍历列表,输入信息\nfor word in word_list:\n # 输入内容\n input_field.send_keys(word)\n # 输入空格\n time.sleep(0.2)\n input_field.send_keys(\" \")\n","sub_path":"004-Scrapy框架/002-careers/tencent/spiders/006-typing_test.py","file_name":"006-typing_test.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"284351281","text":"food = ['panner', 'curd', 'chole', 'rajma']\n\nfor foods in food[1:]:\n print(foods[:])\n print(len(foods))\n'''\nrange example\n\nfor x in range(10):\n print(x+1)\n\nprint(food[0])\n'''\nvar = 12\n","sub_path":"code/forloop.py","file_name":"forloop.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"43729211","text":"import numpy as np\nfrom utils import classifyLDA\n\nclass LDA:\n \"\"\"Implementing an LDA (Linear Discriminant Analysis) model from scratch\"\"\"\n\n def __init__(self, data):\n \"\"\"\n Constructor to create a new LDA instance\n\n data = matrix (numpy ndarray) of dataset with labels as the last column\n X = matrix (numpy ndarray) of dataset with labels (last column) removed\n X1 = (numpy ndarray) rows of X that belong to class 1\n X0 = (numpy ndarray) rows of X that belong to class 0\n\n \"\"\"\n self.X = data[:,:-1]\n self.X1 = self.X[data[:,-1]==1]\n self.X0 = self.X[data[:,-1]==0]\n\n # Model implementation begins below: \n def fit(self):\n \"\"\"\n Fit training data\n Calculates mu1 and mu0 (mean vectors) and sigma (shared covariance matrix) using training data.\n\n num0 = number of training examples in class 0 (number of rows of X0)\n num1 = number of training examples in class 1 (number of rows of X1)\n mu1 = array of mean of columns in X1\n mu0 = array of mean of columns in X0\n m = total number of training examples (= number of rows of X)\n sigma = shared covariance matrix for the dataset\n\n \"\"\"\n\n self.num1 = self.X1.shape[0] \n self.num0 = self.X0.shape[0]\n self.mu1 = np.mean(self.X1, axis=0)[:,np.newaxis]\n self.mu0 = np.mean(self.X0, axis=0)[:,np.newaxis]\n m = self.X.shape[0]\n self.sigma = (np.cov(self.X1.T) + np.cov(self.X0.T)) / (m - 2)\n\n\n def predict(self, X_test):\n \"\"\"\n Given a trained model, predict labels for new data X_test (which is a mxn matrix),\n predict returns a m-dimensional vector of 0/1 predicted labels\n\n calculated using the formula on lecture 5, slide 26, comp 551 fall 2019\n from https://cs.mcgill.ca/~wlh/comp551/slides/05-linear_classification_cont.pdf\n\n\n logodds_vector = vector of predicted log odds for every row in X_test\n \"\"\"\n sigma_inv = np.linalg.inv(self.sigma)\n term1 = np.log(self.num1/self.num0) #no need to include the denominators as they cancel out\n term2 = 0.5*(self.mu1.T @ sigma_inv @ self.mu1)\n term3 = 0.5*(self.mu0.T @ sigma_inv @ self.mu0)\n term4 = X_test @ sigma_inv @ (self.mu1-self.mu0)\n\n logodds_vector = term1 - term2 + term3 + term4\n predicted_labels = classifyLDA(logodds_vector)\n return predicted_labels","sub_path":"LDA.py","file_name":"LDA.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"404012717","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, date\nfrom django.test import TestCase, client as test_client\nfrom django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse\nfrom django.core import mail\nfrom profile.exceptions import IncorrectClaimStateException\nfrom profile.tests import get_full_valid_data\nfrom profile.forms import ClaimForm\nfrom profile import CLAIM_WAITING_PAYMENT, CLAIM_ACCEPTED, CLAIM_CANCELLED, \\\n CLAIM_REJECTED, CLAIM_SENT, CLAIM_WAITING_APPROVEMENT\nfrom profile.models import Claim\n\nclass PaymentTest(TestCase):\n def setUp(self):\n self.claim = ClaimForm(get_full_valid_data()).save()\n self.claim.claim_state = CLAIM_WAITING_PAYMENT\n self.money = 10000\n self.date = date.today()\n\n def get_claim(self):\n return Claim.objects.get(pk=1)\n\n def test_payment_success(self):\n self.claim.payment(self.money, self.date)\n self.assertEquals(CLAIM_ACCEPTED, self.get_claim().claim_state)\n self.assertAlmostEquals(self.money, self.get_claim().payment_sum)\n\n def test_is_waiting_payment_after(self):\n self.claim.payment(self.money, self.date)\n self.assertFalse(self.get_claim().is_waiting_payment())\n\n def test_is_waiting_payment(self):\n self.claim.claim_state = CLAIM_WAITING_PAYMENT\n self.claim.save()\n self.assertTrue(self.get_claim().is_waiting_payment())\n\n def test_payment_fail_if_initial_status_is_not_waiting_payment(self):\n wrong_states = [\n CLAIM_ACCEPTED, CLAIM_CANCELLED, CLAIM_REJECTED,\n CLAIM_SENT, CLAIM_WAITING_APPROVEMENT\n ]\n\n for state in wrong_states:\n def catch_exception():\n self.claim.claim_state = state\n self.claim.save()\n self.claim.payment(self.money, self.date )\n\n self.assertRaises(IncorrectClaimStateException, catch_exception)\n\n def test_payment_success_if_not_waiting_payment_and_paid(self):\n wrong_states = [\n CLAIM_ACCEPTED, CLAIM_CANCELLED, CLAIM_REJECTED,\n CLAIM_SENT, CLAIM_WAITING_APPROVEMENT\n ]\n\n for state in wrong_states:\n self.claim.claim_state = state\n self.claim.payment_date = datetime.now()\n self.claim.save()\n self.claim.payment(self.money, self.date )\n\n def test_payment_view_redirect_to_login_if_not_admin(self):\n User.objects.create_user('demo', 'demo@demo.de', 'demo')\n\n client = test_client.Client()\n client.login(username='demo', password='demo')\n\n # Построить подопытный URL\n url = reverse('manage_claim_payment', kwargs=dict(id = self.claim.id))\n\n # Перейти на страницу оплаты. убедиться. что она есть\n resp = client.get(url)\n self.assertEqual(302, resp.status_code)\n\n def test_payment_view_redirect_to_login_if_unauth(self):\n url = reverse('manage_claim_payment', kwargs=dict(id = self.claim.id))\n client = test_client.Client()\n resp = client.get(url)\n self.assertEqual(302, resp.status_code)\n\n def test_payment_view_404_if_not_waiting(self):\n User.objects.create_superuser('demo', 'demo@demo.de', 'demo')\n client = test_client.Client()\n client.login(username='demo', password='demo')\n url = reverse('manage_claim_payment', kwargs=dict(id=self.claim.id))\n resp = client.get(url)\n self.assertEqual(404, resp.status_code)\n\n def test_payment_view_404_if_paid(self):\n User.objects.create_superuser('demo', 'demo@demo.de', 'demo')\n client = test_client.Client()\n client.login(username='demo', password='demo')\n url = reverse('manage_claim_payment', kwargs=dict(id=self.claim.id))\n\n self.claim.claim_state = CLAIM_SENT\n self.claim.bill_date = None\n self.claim.save()\n\n resp = client.get(url)\n self.assertEqual(404, resp.status_code)\n\n\n def test_payment_view_200_if_paid_or_waiting(self):\n User.objects.create_superuser('demo', 'demo@demo.de', 'demo')\n client = test_client.Client()\n client.login(username='demo', password='demo')\n url = reverse('manage_claim_payment', kwargs=dict(id=self.claim.id))\n\n self.claim.claim_state = CLAIM_WAITING_PAYMENT\n self.claim.bill_date = datetime.now()\n self.claim.save()\n\n resp = client.get(url)\n self.assertEqual(200, resp.status_code)\n\n\n def test_payment_view_integro(self):\n # Создать суперпользователя\n User.objects.create_superuser('demo', 'demo@demo.de', 'demo')\n\n client = test_client.Client()\n client.login(username='demo', password='demo')\n\n\n # Пометить заявку как ожидающую оплаты\n self.claim.claim_state = CLAIM_WAITING_PAYMENT\n self.claim.save()\n\n # Построить подопытный URL\n url = reverse('manage_claim_payment', kwargs=dict(id = self.claim.id))\n\n # Перейти на страницу оплаты. убедиться. что она есть\n resp = client.get(url)\n self.assertEqual(200, resp.status_code)\n\n # Заполнить форму оплаты\n resp = client.post(url, dict(sum=10000, date='07.05.2010'))\n\n # Проверить, что произошёл редирект (форма правильно заполнена)\n self.assertEquals(302, resp.status_code)\n\n # Проверить, что письмо c подстрокой 'claim successfully paid' в очереди\n from django.template.loader import render_to_string\n subject = render_to_string('profile/email/payment.subj.html')\n self.assertTrue(subject == mail.outbox[-1].subject)\n\n ## Проверить, что теперь страницы не существует\n resp = client.get(url)\n self.assertEquals(200, resp.status_code)\n\n #def test_payment_view_integro(self):\n\n","sub_path":"profile/tests/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"385885741","text":"from django.urls import path\nfrom .views import CountryView, RegionView, ContinentView, SubRegionView, CityView, DistrictView, ContinentDetailView, \\\n CountryDetailView, RegionDetailView, SubRegionDetailView, CityDetailView, DistrictDetailView\n\n\nurlpatterns = [\n path('continent/', ContinentView.as_view()),\n path('continent//', ContinentDetailView.as_view()),\n path('country/', CountryView.as_view()),\n path('country//', CountryDetailView.as_view()),\n path('region/', RegionView.as_view()),\n path('region//', RegionDetailView.as_view()),\n path('subregion/', SubRegionView.as_view()),\n path('subregion//', SubRegionDetailView.as_view()),\n path('city/', CityView.as_view()),\n path('city//', CityDetailView.as_view()),\n path('district/', DistrictView.as_view()),\n path('district//', DistrictDetailView.as_view()),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"290510934","text":"import socket, sys, json, datetime, threading, time\n\nHOST = ''\nPORT = 29428\n\ndef log(info, prefix=\"\",p=True): # '*' = Serverlog; '<>'/'' = GameServerlog\n lenght = 30; current_time = prefix + str(datetime.datetime.now())\n with open(\"serverlog.txt\",\"a\") as f:\n text = f'{current_time:<{lenght}}' + \" - \" + info + \"\\n\"\n f.write(text) #how isn't this causing race conditions? xD -> the file is most certainly accessed by multiple threads at the same time.. somehow it works.. nice :D I think ist because CPythons threading isnt \"reaL\" threading... xD (someone on stackoverflow said so, didnt dig deeper, I wont complain if it works)\n if p: print(text[:-1])\n\nclass Server():\n def __init__(self):\n self.init_socket()\n self.bind()\n self.loop = True\n self._lock = threading.Lock() \n\n def init_socket(self):\n try:\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #self.socket.setblocking(0)\n log(\"Socket successfully created!\", \"*\")\n except socket.error as err:\n log(\"socket creation failed with error %s\" %(err), \"*\")\n self.close()\n \n def close(self):\n try:\n self.socket.close()\n self.loop = False\n log(\"Socket successfully closed!\\n--------\\n\",\"*\")\n except socket.error as e:\n log(str(e),\"*\")\n log(\"trying to exit...\",\"*\")\n quit()\n \n def bind(self,host=HOST,port=PORT):\n try:\n self.socket.bind((host, port))\n log(\"Socket successfully bound to address: %s:%s\" %(HOST,PORT),\"*\")\n except socket.error as e:\n log(str(e),\"*\")\n self.close()\n return\n self.socket.listen()\n log(\"Socket is listening...\",\"*\")\n\nclass GameServer(Server):\n def __init__(self):\n super().__init__()\n self.connections = []\n self.lobbys = {} # {lobby_nr : [0,1]}\n self.waiting_for_lobby = None\n self.lobby_counter = 0\n\n self.shutting_off = False\n self.shut_down_time = 30\n\n def shut_off_timer(self):\n while self.shutting_off:\n time.sleep(1)\n self.shut_down_time -= 1\n if self.shut_down_time <= 0:\n self.shutting_off = False\n self.close()\n\n \"\"\"def close(self):\n try:\n self.loop = False\n for conn in self.connections:\n conn[\"conn\"].close()\n #while threading.active_count() > 3: #2 -> 2 if no inp thread (/loop) (main programm/ programm with out extra active threads consists of two it seems ^^) - shut down threads also counts as one extra!..\n # pass\n self.socket.close()\n log(\"Socket successfully closed!\\n--------\\n\",\"*\")\n except socket.error as e:\n log(str(e),\"*\")\n log(\"trying to exit...\",\"*\")\n exit()\"\"\"\n\n def register(self,conn):\n if self.shutting_off: self.shutting_off = False\n self.connections.append(conn)\n log(f'New connection from addr: {conn[\"addr\"]} num_conns: {len(self.connections)}',\">>>\")\n with self._lock:\n self.assign_lobby(conn)\n\n def unregister(self,conn):\n with self._lock:\n self.connections.remove(conn)\n log(f'Lost connection: {conn[\"addr\"]}, lobby: {conn[\"lobby\"]}, num_conns: {len(self.connections)}',\"<<<\")\n if conn[\"lobby\"] != None:\n if conn[\"lobby\"] in self.lobbys.keys(): #probably unnecessary.. lobby_mate[\"lobby\"] = None fixed this occuring.. pretty sure.. :)\n info = {'type': 'abort'}\n self.notify_lobby(info,conn) \n self.lobbys[conn[\"lobby\"]].remove(conn)\n lobby_mate = self.lobbys.pop(conn[\"lobby\"])[0]\n lobby_mate[\"lobby\"] = None\n \n log(f'updated and notified affected lobby (lobby nr. {conn[\"lobby\"]})',\"\")\n\n self.assign_lobby(lobby_mate)\n else:\n log(f'this shouldn\\'t (can\\'t) happen! lobby nr. {conn[\"lobby\"]} of conn {conn[\"conn\"]} isn\\'t in self.lobbys',\"\")\n else:\n if self.waiting_for_lobby == conn:\n self.waiting_for_lobby = None\n \n if len(self.connections) == 0:\n self.shutting_off = True\n self.shut_down_time = 30\n threading.Thread(target=self.shut_off_timer).start()\n log(f\"!! Starting shutt off timer !! t: -{self.shut_down_time}s\",\"*\")\n \n def assign_lobby(self,conn):\n if self.waiting_for_lobby != None:\n lobby_nr = self.lobby_counter\n self.waiting_for_lobby[\"lobby\"] = lobby_nr\n conn[\"lobby\"] = lobby_nr\n self.lobbys[lobby_nr] = [self.waiting_for_lobby, conn]\n log(f\"waiting conn ('{self.waiting_for_lobby['addr']}') & new conn ('{conn['addr']}') now in lobby nr. {lobby_nr} | lobby count: {len(self.lobbys)}\",\"\")\n self.waiting_for_lobby = None\n info = {'type': 'join'}\n self.notify_lobby(info,conn,True)\n self.lobby_counter += 1\n else:\n self.waiting_for_lobby = conn\n log(f\"new conn ('{conn['addr']}') waiting for lobby (2. conn required for creation) | lobby count: {len(self.lobbys)}\",\"\")\n\n def notify_lobby(self,data,conn,send_sender=False):\n if conn[\"lobby\"] != None:\n log(f\"trying to send {data} to lobby nr.: {conn['lobby']}\",\"\")\n for c in self.lobbys[conn[\"lobby\"]]:\n if send_sender or c != conn:\n try:\n c[\"conn\"].sendall((json.dumps(data) + \"\\n\").encode())\n except:\n log(f\"failed to send data: {data} to {c['addr']} | lobby {c['lobby']}\",\"\")\n \n def receiver(self,conn,bits=1096):\n buffer = \"\"\n while self.loop:\n try:\n data = conn[\"conn\"].recv(bits).decode()\n if not data: break #reading a zero length string (?) after connection is dropped ^^\n buffer += data\n except Exception as err:\n log(f\"\\n{err}\\n\")\n break\n if \"\\n\" in buffer:\n (message, buffer) = buffer.split(\"\\n\", 1)\n yield message\n self.unregister(conn)\n\n def connection_loop(self,conn):\n recv = self.receiver(conn)\n for message in recv:\n data = json.loads(message) #if data isn't json formatted, server will get an error\n log(f\"received {data} from {conn['addr']}\",\"\")\n self.notify_lobby(data,conn)\n\n def main_loop(self):\n log(\"main loop active.\", \"\")\n while self.loop:\n try:\n conn, addr = self.socket.accept()\n new_conn = {\"conn\" : conn, \"addr\" : addr, \"lobby\" : None}\n self.register(new_conn) \n threading.Thread(target=self.connection_loop,args=([new_conn])).start() \n except Exception as err:\n pass\n #log(f\"\\n{err}\\n\")\n #log(f\"!! error whilst establishing a connection !! num_conns: {len(self.connections)} (open threads: {threading.active_count()})\",\"\")\n log(\"main loop terminated.\", \"\")\n\n def input_loop(self):\n while self.loop:\n inp = input(\"inp: \")\n if inp == \"/c\":\n self.close()\n\nif __name__ == \"__main__\":\n server = GameServer()\n #threading.Thread(target=server.input_loop).start()\n server.main_loop()\n","sub_path":"server_framework/testing and old/new_server_dev_version.py","file_name":"new_server_dev_version.py","file_ext":"py","file_size_in_byte":7783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"205261640","text":"from django.db import models\n\n\n# Communication type model\nclass CommunicationType(models.Model):\n extid = models.CharField(max_length=36, db_index=True, blank=True)\n name = models.CharField(max_length=250, verbose_name=\"Наименование\")\n code = models.CharField(max_length=6, verbose_name=\"Код\")\n is_phone = models.BooleanField(default=False, verbose_name=\"Для звонков\")\n\n @classmethod\n def from_tuple(cls, row):\n communication_type, created = CommunicationType.objects.get_or_create(\n extid=row[1]\n )\n if created:\n res = \"Создан новый Тип Контрагента\"\n else:\n res = \"Обновлен тип контрагента\"\n\n communication_type.extid = row[1]\n communication_type.name = row[2]\n communication_type.code = row[3]\n communication_type.is_phone = row[4] == \"1\"\n communication_type.save()\n\n return res\n\n class Meta:\n ordering = [\"name\"]\n verbose_name = \"Тип средства связи\"\n verbose_name_plural = \"Типы средств связи\"\n\n def __str__(self):\n return self.name\n\n\n# Country model\nclass Country(models.Model):\n extid = models.CharField(max_length=36, db_index=True, blank=True)\n name = models.CharField(max_length=250, verbose_name=\"Наименование\")\n\n @classmethod\n def from_tuple(cls, row):\n country, created = Country.objects.get_or_create(extid=row[1])\n if created:\n res = \"Создана новая страна\"\n else:\n res = \"Обновлена страна\"\n\n country.extid = row[1]\n country.name = row[2]\n country.save()\n\n return res\n\n class Meta:\n ordering = [\"name\"]\n verbose_name = \"Страна\"\n verbose_name_plural = \"Страны\"\n\n def __str__(self):\n return self.name\n\n\n# State model\nclass State(models.Model):\n extid = models.CharField(max_length=36, db_index=True, blank=True)\n name = models.CharField(max_length=250, verbose_name=\"Наименование\")\n country = models.ForeignKey(\n Country,\n related_name=\"states\",\n verbose_name=\"Страна\",\n on_delete=models.PROTECT,\n null=True,\n )\n\n @classmethod\n def from_tuple(cls, row):\n state, created = State.objects.get_or_create(extid=row[1])\n if created:\n res = \"Created a new state\"\n else:\n res = \"Updated an existed state\"\n\n state.extid = row[1]\n state.name = row[2]\n\n countries = Country.objects.filter(extid=row[3])\n if countries.exists():\n state.country = countries[0]\n else:\n raise ValueError(\"Unknown country ID in the state data.\")\n\n state.save()\n\n return res\n\n class Meta(object):\n ordering = [\"name\"]\n verbose_name = \"Регион\"\n verbose_name_plural = \"Регионы\"\n\n def __str__(self):\n return self.name\n\n\n# City model\nclass City(models.Model):\n extid = models.CharField(max_length=36, db_index=True, blank=True)\n name = models.CharField(max_length=250, verbose_name=\"Наименование\")\n country = models.ForeignKey(\n Country,\n related_name=\"cities\",\n verbose_name=\"Страна\",\n on_delete=models.PROTECT,\n null=True,\n )\n state = models.ForeignKey(\n State,\n related_name=\"subjects\",\n verbose_name=\"Регион\",\n on_delete=models.PROTECT,\n null=True,\n )\n phone_code = models.CharField(max_length=5, null=True, verbose_name=\"Тел. код\")\n kladr_code = models.CharField(max_length=13, null=True, verbose_name=\"КЛАДР\")\n\n class Meta:\n ordering = [\"name\"]\n verbose_name = \"Город\"\n verbose_name_plural = \"Города\"\n\n def __str__(self):\n return self.name\n\n @classmethod\n def from_tuple(cls, row):\n city, created = City.objects.get_or_create(extid=row[1])\n if created:\n res = \"Created a new city\"\n else:\n res = \"Updated an existed city\"\n\n city.extid = row[1]\n city.name = row[2]\n\n countries = Country.objects.filter(extid=row[3])\n if countries.exists():\n city.country = countries[0]\n else:\n raise ValueError(\"Unknown country ID in the city data.\")\n\n states = State.objects.filter(extid=row[4])\n if states.exists():\n city.state = states[0]\n else:\n raise ValueError(\"Unknown state ID in the city data.\")\n\n if row[5]:\n phone_code = row[5] if len(row[5]) <= 5 else row[5][:5]\n city.phone_code = phone_code\n\n if row[6]:\n city.kladr_code = row[6]\n\n city.save()\n\n return res\n","sub_path":"crm/common/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"61260050","text":"import argparse\nimport socket\n\ndef parse_command_line():\n parser = argparse.ArgumentParser(description=\"Receiver parameters\")\n parser.add_argument(\"--port\", help=\"The port to send on\", type=int,required=True)\n parser.add_argument(\"--receiver\", help=\"The computer to sent to\", type=str,required=True)\n\n args = parser.parse_args()\n\n return args\n\nargs = parse_command_line()\n\n# UDP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ndest = (args.receiver, args.port)\n\n# Have the socket recv return periodically\n# so the program can terminate\nsock.settimeout(0.1)\nwhile True:\n msg = raw_input('>> ')\n sock.sendto(msg, dest)","sub_path":"samples/SimpleChat/Sender.py","file_name":"Sender.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"579191404","text":"class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n res = []\n\n def helper(path, ind):\n if path not in res:\n res.append(path[:])\n if len(path) > len(nums):\n return\n for i in range(ind, len(nums)):\n path.append(nums[i])\n helper(path, i + 1)\n path.pop()\n\n helper([], 0)\n return res\n","sub_path":"78_Subsets.py","file_name":"78_Subsets.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"519466588","text":"\"\"\"Designed to process public data files, that have been processed to be '|' pipe delimited, and examine particular fields\nfor the presence of '-' in the data. Used successfully on 20180315 CJS\"\"\"\n\nindex_list = [89, 91, 95, 109, 111, 115, 129, 131, 139, 142, 145, 147, 149, 153, 154, 155, 156, 160, 162, 163, 164, 165, 166, 170, 171, 174, 175]\n# Example: E:\\DoIT_SDATRealProperty_Project\\_PublicData_02.txt\npublic_text_file = input(\"Paste the file path for previously split Anne Arundel public data file\\n>\")\ncounter = 0\nwith open(public_text_file,'r') as fhand_publictextfile:\n for line in fhand_publictextfile:\n newlist = line.split(\"|\")\n for index in index_list:\n if \"-\" in newlist[index]:\n counter+=1\n\nprint(counter)\n\n","sub_path":"TestForDashInSpecificIndexPositionsInData.py","file_name":"TestForDashInSpecificIndexPositionsInData.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"548496274","text":"from bs4 import BeautifulSoup\nimport requests\n\n\nhtml = requests.get('http://www.python.org')\n#print(html.text)\n\nsoup = BeautifulSoup(html.text, \"html.parser\")\n\ntitles = soup.find_all('title')\nprint(titles[0].text)\n\nintro = soup.find_all('div', {'class': 'introduction'})\nprint(intro)\nprint(intro[0].text)","sub_path":"old/language/python/udemy/ds/158/158.py","file_name":"158.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"3561497","text":"# -*- coding: utf-8 -*-\n# Author : Jin Kim\n# e-mail : jinkim@seculayer.co.kr\n# Powered by Seculayer © 2021 Service Model Team, Intelligence R&D Center.\n\nfrom mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract\n\n\nclass OneHotEncode(ConvertAbstract):\n def __init__(self, arg_list: list, stat_dict: dict):\n super().__init__(arg_list=arg_list, stat_dict=stat_dict)\n self.unique_dict: dict = dict()\n self.unique_count = 0\n\n for idx, key in enumerate(sorted(self.stat_dict.get(\"unique\").keys())):\n self.unique_dict[key] = idx\n self.unique_count += 1\n\n def apply(self, data):\n # ZERO\n result = [0 for i in range(self.unique_count)]\n try:\n # GET INDEX\n index = self.unique_dict.get(data)\n result[index] = 1\n except Exception as e:\n # self.LOGGER.getLogger().warn(e)\n result[0] = 1\n\n # List return\n return result\n\n def get_num_feat(self):\n return self.unique_count\n\n\nif __name__ == \"__main__\":\n one_hot_encode = OneHotEncode(\n stat_dict={\"unique\": \"0@COMMA@1\", \"uniqueCount\": 2}, arg_list=list()\n )\n\n print(one_hot_encode.apply(\"0\"))\n print(one_hot_encode.apply(\"1\"))\n print(one_hot_encode.apply(\"1\"))\n","sub_path":"mlps/core/data/cnvrtr/functions/OneHotEncode.py","file_name":"OneHotEncode.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"648318842","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\"\"\"\n 第二代防火墙 --> 自定义对象--> url类型组\n\n modify log\n 2016-4-6:\n 1、增加恢复系统默认设置选项\n 2016-5-24::\n 1、重构代码(pylint 2.64/befor 9.52/after)\n 2、修复编码问题\n 2016-7-11:\n 1、系统命令路径统一从 core.setting 中导入\n 2、过滤空url列表项,不写入配置文件\n\"\"\"\n\nimport os\nimport sys\nimport codecs\nfrom logging import getLogger\n\nfrom db.config import search_data, execute_sql, mkdir_file\nfrom utils.logger_init import logger_init\nfrom core.setting import LOG_BASE_PATH\n\n\nFILE_PATH = '/usr/local/bdwaf/conf/url_filter_category.conf'\nURL_PATH = '/usr/local/bdwaf/conf/URLs'\nLOG_NAME = 'URL_GROUP'\nLOG_PATH = os.path.join(LOG_BASE_PATH, 'url_group.log')\n\nlogger_init(LOG_NAME, LOG_PATH, 'DEBUG')\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass UrlGroupConfigFile(object):\n \"\"\"\n 把url类型组写入到配置文件中\n \"\"\"\n\n def __init__(self, data):\n \"\"\"\n 初始化\n \"\"\"\n\n self.data = data\n mkdir_file(FILE_PATH, 'file')\n\n def add(self):\n \"\"\"\n 把url类型组写到配置文件\n args:\n None\n return:\n True: 增加成功\n False: 增加失败\n \"\"\"\n\n config_list = []\n # id\n id_str = 'ID:%d' %(int(self.data['id']))\n config_list.append(id_str)\n\n # URL组名称\n urlg_name_str = 'URLG Name:%s' %(self.data['sURLGroupName'])\n config_list.append(urlg_name_str)\n\n # URL组描述\n urlg_desc_str = 'URLG Description:%s' %(self.data['sGroupDesc'])\n config_list.append(urlg_desc_str)\n\n # url(多个用分号分隔)\n url_num = 0\n urls = []\n if self.data['sURL']:\n if self.data['sURL'].endswith('.txt'):\n filepath = codecs.open(self.data['sURL'], 'r', 'utf-8')\n lines = filepath.readlines()\n filepath.close()\n if lines:\n urls = [x.replace('\\n', '').replace('\\r', '').strip() for x in lines]\n else:\n urls = self.data['sURL'].split(',')\n urls = [item.strip() for item in urls]\n if urls:\n urls = [item for item in urls if item] # 去除空项\n url_num = len(urls)\n for i in xrange(0, url_num, 30):\n url_list = urls[i:i+30]\n url_str = ';'.join(url_list)\n url_str = 'URL:%s' %(url_str)\n config_list.append(url_str)\n else:\n config_list.append('URL:')\n\n # 关键字\n #keyword_str = 'Keyword:%s' %(self.data['sDomainKey'])\n #config_list.append(keyword_str)\n config_list.append('\\n')\n\n try:\n config_str = '\\n'.join(config_list)\n except Exception as err:\n getLogger(LOG_NAME).debug(err)\n\n # 把规则写入配置文件\n try:\n filepath = codecs.open(FILE_PATH, 'a', 'utf-8')\n filepath.write(config_str)\n return True\n except IOError as err:\n getLogger(LOG_NAME).debug(err)\n return False\n finally:\n filepath.close()\n\n def delete(self):\n \"\"\"\n 删除url类型组\n args:\n None\n return:\n True: 删除成功\n False: 删除失败\n \"\"\"\n\n try:\n filepath = codecs.open(FILE_PATH, 'r', 'utf-8')\n lines_list = filepath.readlines()\n except IOError as err:\n getLogger(LOG_NAME).debug(err)\n finally:\n filepath.close()\n\n # 求匹配的开始和结束索引号\n re_str = 'ID:%d\\n' %(int(self.data['id']))\n\n if not re_str in lines_list:\n return\n\n snum = lines_list.index(re_str)\n\n count = snum + 1\n len_lines = len(lines_list) -1\n while count <= len_lines:\n if lines_list[count] == '\\n':\n enum = count\n break\n count += 1\n\n # 删除匹配的规则并从新写入配置文件\n for i in xrange(enum, snum-1, -1):\n lines_list.pop(i)\n lines_str = ''.join(lines_list)\n try:\n filepath = codecs.open(FILE_PATH, 'w', 'utf-8')\n filepath.write(lines_str)\n return True\n except IOError as err:\n getLogger(LOG_NAME).debug(err)\n finally:\n filepath.close()\n return False\n\ndef set_urls():\n \"\"\" 将内置的url过滤规则入库 \"\"\"\n files = os.listdir(URL_PATH)\n files = [x for x in files if x.endswith('.txt')]\n\n # 先删除库中内置类型数据\n filenames = [x.split('.')[0].decode('utf-8') for x in files]\n for filename in filenames:\n sql = 'DELETE from m_tburlgroup where sURLGroupName=\"%s\" and iType=1;' \\\n %(filename)\n execute_sql(sql)\n\n contents = [[x.split('.')[0].decode('utf-8'), URL_PATH+'/'+x.decode('utf-8'), 1] for x in files]\n urlg = codecs.open('/usr/local/bdwaf/conf/URLs/m_tburlgroup.csv', 'r', 'utf-8')\n lines = urlg.readlines()\n urlg.close()\n\n num = len(contents)\n for line in lines:\n line = line.split(',')\n for i in range(num):\n if line[1] == contents[i][0]:\n contents[i].insert(1, line[2])\n break\n\n for content in contents:\n try:\n sql = 'INSERT INTO m_tburlgroup (sURLGroupName, sGroupDesc, sURL, \\\n iType) VALUES(\"%s\", \"%s\", \"%s\", %d)' \\\n %(content[0], content[1], content[2], content[3])\n except Exception as err:\n getLogger(LOG_NAME).debug(err)\n execute_sql(sql)\n\ndef main(args):\n \"\"\" 主函数 \"\"\"\n\n os.system('/usr/bin/cat /dev/null > %s' % (FILE_PATH))\n\n if args == 'init':\n pass\n elif args == 'reboot':\n #set_urls()\n\n g_sql = 'select * from m_tburlgroup;'\n datas = search_data(g_sql)\n for data in datas:\n conf = UrlGroupConfigFile(data)\n conf.add()\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n getLogger(LOG_NAME).debug('more args (eg: python url_filter init/reboot)')\n else:\n main(sys.argv[1])\n #print \"url group well done\"\n","sub_path":"chuhuo_2.71/bluedon/objectdefine/url_group.py","file_name":"url_group.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"352821555","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport requests\nfrom mysetting import *\nimport json\nimport os\nfrom bs4 import BeautifulSoup\nimport time\nimport sqlite3\nimport win32crypt\n\n\ndef get_headers(headers):\n username = os.environ.get('USERNAME')[:5]\n cookie_file = f'C:/Users/{username}/AppData/Local/Google/Chrome/User Data/Default/Cookies'\n conn = sqlite3.connect(cookie_file)\n cursor = conn.cursor()\n sql = \"SELECT encrypted_value FROM cookies where host_key = 'ai.deepshare.net' and name = 'pc_user_key';\"\n cursor.execute(sql)\n results = cursor.fetchone()\n conn.close()\n if not results:\n raise ValueError(f'no cookie!{results}')\n pc_user_key = win32crypt.CryptUnprotectData(results[0], None, None, None, 0)[1].decode('utf-8')#解密\n\n headers['Cookie'] = headers['Cookie'].replace('$pc_user_key', pc_user_key)\n return headers\n\ndef get_goods_id(goods_url):\n goods_id_all = {}\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',\n }\n\n req = requests.get(goods_url, headers=headers)\n soup = BeautifulSoup(req.text)\n results = soup.find_all(class_=\"hot-item\")\n for result in results:\n try:\n goods_data = {\"page_size\":20,\"last_id\":\"\",\"resource_type\":[1,2,3,4]}\n title = result.div.div.string.strip()\n goods_id, goods_type = result['href'].split('/')[2], result['href'].split('/')[3]\n goods_data['goods_id'] = goods_id\n goods_data['goods_type'] = int(goods_type) if goods_type else 6\n goods_data = json.dumps(goods_data)\n goods_id_all[title] = goods_data\n except:\n print(result)\n return goods_id_all\n\ndef get_videoslist_from_local(dirpath):\n return os.listdir(dirpath)\n\ndef get_info_from_api(api, headers, params, data):\n req = None\n try:\n req = requests.post(api, headers=headers, params=params, data=data)\n req = json.loads(req.text)\n except Exception as e:\n print(f'【9】{e}\\n{req}')\n while not req:\n req = get_info_from_api(api, headers, params, data)\n\n return req\n\ndef parse_goodslist(req):\n goods_list = []\n last_id = None\n id = 1\n try:\n goodslist = req.get('data').get('goods_list')\n# print(goodslist)\n last_id = req.get('data').get('last_id')\n except Exception as e:\n print(f'【24】{e}\\n{req}')\n\n if goodslist:\n selection = ['resource_id', 'resource_type', 'title', 'redirect_url']\n for good in goodslist:\n id += 1\n selection_info = [good.get(key) for key in selection]\n# selection_info = [good.get(key) for key in selection if good.get('video_length', 0) > 0]\n if selection_info:\n good = dict(zip(selection, selection_info))\n goods_list.append(good)\n\n return goods_list, last_id\n\n\ndef get_goodslist(url, headers, app_id, data):\n params = {'app_id': f'{app_id}'}\n goods_list_all = []\n req = get_info_from_api(url, headers, params, data)\n# print(req)\n goods_list, last_id = parse_goodslist(req)\n goods_list_all.extend(goods_list)\n\n while goods_list:\n data = json.loads(data)\n data['last_id'] = last_id\n data['order_type'] = 0\n data = json.dumps(data)\n req = get_info_from_api(url, headers, params, data)\n goods_list, last_id = parse_goodslist(req)\n goods_list_all.extend(goods_list)\n\n# if not goods_list_all: print(req)\n\n return goods_list_all\n\ndef get_video(url, headers, good, app_id):\n# print(url)\n params = {'app_id': f'{app_id}'}\n data = {}\n data['goods_id'] = good.get('resource_id')\n data['goods_type'] = good.get('resource_type')\n data = json.dumps(data)\n req_info = get_info_from_api(url, headers, params, data)\n# print(req_info)\n video_info = req_info.get('data')\n return video_info\n\ndef download_video(video_info, dirpath, title):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',\n }\n m3u8_url = video_info.get('video_m3u8')\n if m3u8_url:\n name = f\"{dirpath}/{title}.mp4\"\n try:\n shell_command = f\"ffmpeg -i {m3u8_url} -c copy {name}\"\n os.system(shell_command)\n except Exception as e:\n print(e)\n print(shell_command)\n\ndef save_description(video_info, dirpath, title):\n content = video_info.get('content')\n with open(f'{dirpath}/{title}.html', 'w', encoding='utf-8') as f:\n f.write(content)\n\n\n\nif __name__ == '__main__':\n headers = get_headers(headers)\n goods_id_all = get_goods_id(goods_url)\n for title, data in goods_id_all.items():\n print(f\"开始下载【{title}】\".center(50,'='))\n dirpath = 'f:/深度之眼/' + title\n try:\n os.mkdir(dirpath)\n print(f'{dirpath}已经创建!')\n except Exception as e:\n if '当文件已存在时' not in str(e):\n print(f'【{dirpath}】{e}!')\n goods_list = get_goodslist(main_api, headers, app_id, data)\n for good in goods_list:\n # print(good)\n video = get_video(page_api, headers, good, app_id)\n if video:\n # print(video)\n if 'title' in video:\n title = video.get('title').replace('|', ',').replace(' ','')\n if f'{title}.html' not in get_videoslist_from_local(dirpath):\n print(f'【下载】{title}')\n download_video(video, dirpath, title)\n time.sleep(1)\n save_description(video, dirpath, title)\n else:\n # print(f'【已存在】{title}')\n pass\n else:\n print(video)\n\n # os.system('shutdown -s -t 60')\n\n\n\n\n\n","sub_path":"download_video_from_aideepshare.py","file_name":"download_video_from_aideepshare.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"295790279","text":"from django.conf.urls import url\nfrom . import views\nfrom django.urls import path\n\nurlpatterns = [\n url(r'daily/schedules/', views.get_daily_commutes_for_user),\n url(r'daily/details/', views.get_journey_details),\n url(r'daily/notification/', views.daily_commuter_notification),\n url(r'daily/', views.create_daily_commute),\n url(r'daily/', views.delete_daily_commute),\n url(r'daily/', views.update_daily_commute),\n ]","sub_path":"daily_commute/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"318703733","text":"import random\r\nimport pysnooper\r\nimport time\r\n# @pysnooper.snoop()\r\ndef vcode(chart_len = 4):\r\n global v_code\r\n v_chart = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'\r\n # print v_chart\r\n v_chart_list = list(v_chart)\r\n v_len = len(v_chart)\r\n v_code_list = []\r\n # print(v_chart_list)\r\n for i in range(chart_len):\r\n index = random.randint(0,v_len - 1)\r\n print(index)\r\n v_code_list.append(v_chart_list[index])\r\n v_code = ''.join(v_code_list)\r\n print(v_code)\r\n\r\n\r\ndef trigger():\r\n zhongjianghaoma = 'aJ3f'\r\n count = 0\r\n while True:\r\n time.sleep(0.5)\r\n count += 1\r\n print ('%s times'%count)\r\n vcode()\r\n zhongjianghaoma = 'aJ3f'\r\n if zhongjianghaoma == v_code:\r\n print('zhongjiangle')\r\n break\r\n else:\r\n continue\r\nif __name__ == '__main__':\r\n trigger()\r\n vcode()","sub_path":"v_code.py","file_name":"v_code.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"181573157","text":"from pydogpack.utils import xt_functions\nfrom pydogpack.utils import flux_functions\nfrom pydogpack.basis import basis\nfrom pydogpack.mesh import mesh\nfrom pydogpack.mesh import boundary\nfrom apps.onedimensional.convectiondiffusion import convection_diffusion\n\nimport numpy as np\nimport yaml\n\nif __name__ == \"__main__\":\n exact_solution = xt_functions.AdvectingSine(amplitude=0.1, offset=0.15)\n diffusion_function = flux_functions.Polynomial(degree=3)\n problem = convection_diffusion.NonlinearDiffusion.manufactured_solution(\n exact_solution, diffusion_function\n )\n t = 0.0\n bc = boundary.Periodic()\n n = 10\n dict_ = dict()\n for bc in [boundary.Periodic(), boundary.Extrapolation()]:\n dict_[str(bc)] = dict()\n dict_bc = dict_[str(bc)]\n for basis_class in basis.BASIS_LIST:\n dict_bc[basis_class.string] = dict()\n dict_basis = dict_bc[basis_class.string]\n for num_basis_cpts in range(1, 4):\n dict_basis[num_basis_cpts] = dict()\n dict_cpt = dict_basis[num_basis_cpts]\n basis_ = basis_class(num_basis_cpts)\n for num_elems in range(10, 90, 10):\n mesh_ = mesh.Mesh1DUniform(0.0, 1.0, num_elems)\n dg_solution = basis_.project(problem.initial_condition, mesh_)\n (matrix, vector) = problem.ldg_matrix(\n dg_solution, t, bc, bc\n )\n eigvals = np.linalg.eigvals(matrix)\n # change into real and complex values\n eigvals_real = [float(np.real(e)) for e in eigvals]\n eigvals_imag = [float(np.imag(e)) for e in eigvals]\n dict_cpt[num_elems] = dict()\n dict_cpt[num_elems][\"real\"] = eigvals_real\n dict_cpt[num_elems][\"imag\"] = eigvals_imag\n\n with open(\"spectra.yml\", \"w\") as file:\n yaml.dump(dict_, file, default_flow_style=False)\n","sub_path":"apps/onedimensional/convectiondiffusion/compute_spectra.py","file_name":"compute_spectra.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"409020427","text":"import property_resolver\nimport re\n\ndef load(filepath, prefix = ''):\n \"\"\"Loads properties from file with optional prefix without resolving references\"\"\"\n with open(filepath) as f:\n properties = {}\n for line in f.readlines():\n line = line.strip()\n if not line or line[0] in ';#':\n continue\n result = re.search('\\s*([^=]+)\\s*=\\s*(.*)', line)\n if len(result.groups()) == 2:\n properties[prefix + result.group(1).strip()] = result.group(2).strip()\n\n return properties\n","sub_path":"revolver/property_file_loader.py","file_name":"property_file_loader.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"611664445","text":"import csv\nimport datetime\nimport os\n\nimport pytz\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db.models import Q\nfrom django.utils import timezone\n\nfrom clubs.models import Badge, Club, Event\n\n\nclass Command(BaseCommand):\n help = \"Import information from the SAC fair spreadsheet to create events for the SAC fair.\"\n\n def add_arguments(\n self, parser,\n ):\n parser.add_argument(\n \"file\",\n type=str,\n help=\"The name of the CSV file to import. \"\n \"Assumes that there is a column title row and skips the first row.\",\n )\n parser.add_argument(\n \"--dry-run\",\n dest=\"dry_run\",\n action=\"store_true\",\n help=\"If set to true, don't actually makes changes to the database.\",\n )\n\n def handle(\n self, *args, **kwargs,\n ):\n file = kwargs[\"file\"]\n dry_run = kwargs[\"dry_run\"]\n\n if not os.path.isfile(file):\n raise CommandError(f\"The file '{file}' does not exist.\")\n\n club_codes = set()\n events = []\n\n with open(file, \"r\",) as f:\n reader = csv.reader(f)\n next(reader)\n for line in reader:\n if len(line) < 3:\n continue\n (code, tag, day,) = line\n if code in club_codes:\n continue\n club_codes.add(code)\n events.append((code, tag, day,))\n self.stdout.write(f\"Loaded {len(events)} clubs from spreadsheet.\")\n\n if not events:\n raise CommandError(\"There are no clubs in the spreadsheet.\")\n\n # remove invalid clubs from fair\n invalid_clubs = Club.objects.filter(Q(fair=True) & ~Q(code__in=club_codes))\n invalid_club_codes = \", \".join(invalid_clubs.values_list(\"code\", flat=True,))\n self.stdout.write(\n f\"The following {invalid_clubs.count()} clubs have fair marked as true, \"\n f\"but not in the sheet: {invalid_club_codes}\"\n )\n if not dry_run:\n invalid_clubs.update(fair=False)\n else:\n return\n\n # add event badges to system\n self.stdout.write(\"Adding event badges to system...\")\n event_badges = set([e[1] for e in events])\n badge_map = {}\n for badge in event_badges:\n (badge_obj, stat,) = Badge.objects.get_or_create(\n label=badge,\n defaults={\n \"description\": f\"This is a badge for the {badge} category for the SAC Fair.\",\n \"color\": \"0099FF\",\n \"org\": None,\n \"purpose\": \"fair\",\n },\n )\n badge_map[badge] = badge_obj\n self.stdout.write(f\"{'Created' if stat else 'Retrieved'} {badge} badge.\")\n\n eastern_tz = pytz.timezone(\"America/New_York\")\n year = timezone.now().year\n\n # add event badges and events to clubs\n self.stdout.write(\"Adding events to system...\")\n for (code, tag, day,) in events:\n club = Club.objects.get(code=code)\n club.badges.add(badge_map[tag])\n\n start_time = eastern_tz.localize(datetime.datetime(year, 9, int(day), 17, 0, 0))\n duration = datetime.timedelta(hours=3)\n\n (_, created) = Event.objects.get_or_create(\n code=f\"sac-fair-{year}-{code}\",\n club=club,\n defaults={\n \"creator\": None,\n \"name\": \"SAC Fair Info Session\",\n \"start_time\": start_time,\n \"type\": Event.FAIR,\n \"end_time\": start_time + duration,\n \"description\": \"Replace this description!\",\n },\n )\n\n self.stdout.write(f\"{'Created' if created else 'Retrieved'} event for {club.code}.\")\n","sub_path":"backend/clubs/management/commands/import_sac.py","file_name":"import_sac.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"329948172","text":"from random import randint\n\ndef lancerUnDe(n):\n d = randint(1,n)\n return d\n\ndef lancerDeDes(nbDes,nbFaces):\n listeDesDes = []\n for i in range(nbDes):\n d = lancerUnDe(nbFaces)\n listeDesDes.append(d)\n return listeDesDes\n \ndef resultat(lancer):\n s = 0\n reu = 0\n for i in lancer:\n if i >= SR:\n s=s+1\n if i > 1 and i < SR:\n s=s\n if i == 1:\n s=s-1\n if s < 0:\n r=\"Echec critique\"\n if s == 0:\n r=\"Echec\"\n if s > 0:\n r=\"Valeur de la réussite\", s\n print(r)\n \nnbDes = int(input(\"Saisissez le nombre de dés : \"))\nnbFaces = int(input(\"Saisissez le nombre de faces pour chaque dé : \"))\nSR = int(input(\"Définissez la difficulté de votre lancer : \"))\nl=lancerDeDes(nbDes,nbFaces)\n\nprint(\"Le résultat du lancer donne : \", l)\n\nprint(resultat(l))\n","sub_path":"V3.py","file_name":"V3.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"53773074","text":"import numpy as np\nfrom itertools import permutations\nfrom sklearn import datasets\nfrom matplotlib import pyplot\nfrom my_kmeans import my_kmeans\n\n\ndef score(y_true, y_pred):\n n_clusters = int(np.max(y_true)) + 1\n max_score = 0\n for perm in permutations(list(range(n_clusters))):\n perm_score = sum(\n np.sum(np.logical_and(y_pred == perm[i], y_true == i))\n for i in range(n_clusters)\n )\n if perm_score > max_score:\n max_score = perm_score\n # return maximum score among all possible permutations of labels\n return max_score\n\n\ndef kmeans_test(dataname, smart=False):\n data = np.genfromtxt('data/{}.csv'.format(dataname), delimiter=',')\n X, y_true = data[:, :2], data[:, 2]\n n_clusters = int(np.max(y_true)) + 1\n\n centroids_mykm, y_pred_mykm = my_kmeans(X, n_clusters=n_clusters, smart=smart)\n score_mykm = score(y_true, y_pred_mykm)\n print('Score: {}/{}. Accuracy: {}'.format(\n score_mykm, y_true.shape[0], score_mykm / y_true.shape[0]\n ))\n\n pyplot.rcParams['figure.figsize'] = (10, 5)\n pyplot.subplot(1, 2, 1).set_title('My K-means labels')\n pyplot.scatter(X[:, 0], X[:, 1], c=y_pred_mykm, s=2)\n pyplot.scatter(\n centroids_mykm[:, 0], centroids_mykm[:, 1],\n marker=(5, 1), c=np.arange(n_clusters), s=100)\n\n pyplot.subplot(1, 2, 2).set_title('Correct labels')\n pyplot.scatter(X[:, 0], X[:, 1], c=y_true, s=2)\n pyplot.show()\n\n\ndef kmeans_testblobs(n_trials=10, smart=False):\n data = np.genfromtxt('{}.csv'.format('blobs'), delimiter=',')\n X, y_true = data[:, :2], data[:, 2]\n n_clusters = int(np.max(y_true)) + 1\n scores = np.zeros(n_trials)\n\n for t in range(n_trials):\n centroids_mykm, y_pred_mykm = my_kmeans(X, n_clusters=n_clusters, smart=smart)\n score_mykm = score(y_true, y_pred_mykm)\n print('Trial t = {}. Score: {}/{}. Accuracy: {}'.format(\n t+1, score_mykm, y_true.shape[0], score_mykm / y_true.shape[0]\n ))\n scores[t] = score_mykm\n\n print('---------------------------------------------------')\n print('Completed {} trials.'.format(n_trials))\n average_score = np.mean(scores)\n n_samples = y_true.shape[0]\n print('Average score: {}/{} ({}%%)'.format(\n average_score, n_samples, round(100 * average_score / n_samples, 2)\n ))\n n_perfect_trials = int(np.sum(scores == y_true.shape[0]))\n print('Perfect score achieved: {}/{} trials ({}%%)'.format(\n n_perfect_trials, n_trials, round(100 * n_perfect_trials / n_trials, 2)\n ))\n\n\n# kmeans_test('blobs', smart=False) # Uncomment de test cau hoi TH1\n# kmeans_testblobs(100, smart=True) # Uncomment de test cau hoi TH2. Doi smart=False thanh smart=True de test centroi_smart_select cura ban\n# kmeans_test('mouse', smart=True) # Uncomment de test cau hoi TH3A. Doi smart=False thanh smart=True de so sanh output\n# kmeans_test('circles', smart=True) # Uncomment de test cau hoi TH3B. Doi smart=False thanh smart=True de so sanh output\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"254733435","text":"\"\"\"\nClasse no\nRepresenta os nós da árvore do PPM. Contém um conteúdo que representa o caractere que ocorreu, um contador que indica a quantidade de vezes que\nesse caractere ocorreu e uma lista com os nós que ele aponta\n\"\"\"\n\nclass No:\n\n\tdef __init__(self, conteudo, contador, dictNos, listaConteudo):\n\t\tself.conteudo = conteudo\n\t\tself.contador = contador\n\t\tself.dictNos = dictNos\n\t\tself.listaConteudo = listaConteudo","sub_path":"PPM-C/No.py","file_name":"No.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"122219568","text":"\"\"\"\n Interface to communicate with Facebook Messenger\n https://developers.facebook.com/docs/messenger-platform/send-api-reference\n\"\"\"\n\nimport json\nimport requests\nimport warnings\n\nfrom enum import Enum\n\n\nclass NotificationType(Enum):\n REGULAR = \"REGULAR\"\n SILENT_PUSH = \"SILENT_PUSH\"\n NO_PUSH = \"NO_PUSH\"\n\n\nclass RecipientMethod(Enum):\n ID = \"id\"\n PHONE_NUMBER = \"phone_number\"\n\n\nclass AttachmentType(Enum):\n IMAGE = \"image\"\n TEMPLATE = \"template\"\n BUTTON = \"button\"\n\n\nclass ButtonType(Enum):\n WEBURL = \"web_url\"\n POSTBACK = \"postback\"\n SHARE = \"element_share\"\n\n\nclass SenderActions(Enum):\n SEEN = \"mark_seen\"\n TYPING_ON = \"typing_on\"\n TYPING_OFF = \"typing_off\"\n\n\nclass BotInterface(object):\n def __init__(self, fb_api_version, fb_access_token):\n self.FB_API_VERSION = fb_api_version\n self.FB_ACCESS_TOKEN = fb_access_token\n\n self.URL = (\n \"https://graph.facebook.com\"\n \"/v{0}/me/messages?access_token={1}\"\n ).format(self.FB_API_VERSION, self.FB_ACCESS_TOKEN)\n\n def create_text_message(self, recipient_info, message,\n recipient_method, notification_type):\n\n recipient_json = {recipient_method: recipient_info}\n\n message = {\n \"recipient\": recipient_json,\n \"message\": {\n \"text\": message\n },\n \"notification_type\": notification_type\n }\n\n return message\n\n def create_generic_payload_message(self, recipient_info,\n recipient_method=RecipientMethod.ID.value,\n notification_type=NotificationType.REGULAR.value,\n attachment={}):\n message = self.create_text_message(recipient_info, None,\n recipient_method, notification_type)\n\n message[\"message\"] = {\"attachment\": attachment}\n\n return message\n\n #################### CREATE TEMPLATES ####################\n\n def create_generic_template(self, template_elements=[]):\n \"\"\"\n template_elements: Array of generic_template_elements\n \"\"\"\n assert type(template_elements) == list\n\n attachment = {\n \"type\": AttachmentType.TEMPLATE.value,\n \"payload\": {\n \"template_type\": \"generic\",\n \"elements\": template_elements\n }\n }\n return attachment\n\n def create_image_template(self, image_url=\"\"):\n \"\"\"\n image_url: this should be the image URL\n \"\"\"\n assert type(image_url) == str\n\n attachment = {\n \"type\": AttachmentType.IMAGE.value,\n \"payload\": {\n \"url\": image_url,\n }\n }\n return attachment\n\n def create_button_template(self, button_title=\"\", buttons=[]):\n assert type(button_title) in [str, unicode]\n assert type(buttons) == list\n assert len(buttons) > 0\n\n attachment = {\n \"type\": AttachmentType.TEMPLATE.value,\n \"payload\": {\n \"template_type\": \"button\",\n \"text\": button_title,\n \"buttons\": buttons\n }\n }\n\n return attachment\n\n #################### CREATE ELEMENTS/BUTTONS ####################\n\n def create_generic_template_element(self, element_title=\"\", element_item_url=\"\",\n element_image_url=\"\", element_subtitle=\"\",\n element_buttons=None):\n \"\"\"\n element_title: Some title\n element_item_url: URL opened when button is tapped\n element_image_url: Bubble Image\n element_subtitle: Bubble subtitle\n element_buttons: Array of buttons\n \"\"\"\n element = {\n \"title\": element_title,\n \"item_url\": element_item_url,\n \"image_url\": element_image_url,\n \"subtitle\": element_subtitle\n }\n\n if element_buttons:\n assert type(element_buttons) == list\n element['buttons'] = element_buttons\n\n return element\n\n def create_button(self, button_type=ButtonType.WEBURL.value,\n title=\"\", url=\"\", payload=\"\"):\n assert type(title) in [str, unicode]\n assert type(url) == str\n assert type(payload) == str\n\n button_dict = {}\n if button_type == ButtonType.WEBURL.value:\n assert len(url) > 0\n button_dict = {\n \"type\": ButtonType.WEBURL.value,\n \"title\": title,\n \"url\": url\n }\n return button_dict\n elif button_type == ButtonType.POSTBACK.value:\n assert len(payload) > 0\n button_dict = {\n \"type\": ButtonType.POSTBACK.value,\n \"title\": title,\n \"payload\": payload\n }\n return button_dict\n elif button_type == ButtonType.SHARE.value:\n button_dict = {\n \"type\": ButtonType.SHARE.value\n }\n\n warnings.warn(\"button_type of %s does not exist\" % button_type, UserWarning)\n return button_dict\n\n #################### SEND MESSAGE FUNCTIONS ####################\n\n def send_text_message(self, recipient_info, message,\n recipient_method=RecipientMethod.ID.value,\n notification_type=NotificationType.REGULAR.value):\n\n message = self.create_text_message(recipient_info, message,\n recipient_method, notification_type)\n\n return self._send(message)\n\n def send_sender_action(self, recipient_info, sender_action=SenderActions.SEEN.value):\n message = {\"recipient\": {\"id\": recipient_info}, \"sender_action\": sender_action}\n return self._send(message)\n\n def send_generic_payload_message(self, recipient_info,\n recipient_method=RecipientMethod.ID.value,\n notification_type=NotificationType.REGULAR.value,\n elements=[]):\n\n attachment = self.create_generic_template(elements)\n\n message = self.create_generic_payload_message(recipient_info,\n recipient_method, notification_type,\n attachment=attachment)\n\n return self._send(message)\n\n def send_image_payload_message(self, recipient_info,\n recipient_method=RecipientMethod.ID.value,\n notification_type=NotificationType.REGULAR.value,\n image_url=\"\"):\n\n attachment = self.create_image_template(image_url)\n\n message = self.create_generic_payload_message(recipient_info,\n recipient_method, notification_type,\n attachment=attachment)\n\n return self._send(message)\n\n def send_button_payload_message(self, recipient_info,\n recipient_method=RecipientMethod.ID.value,\n notification_type=NotificationType.REGULAR.value,\n button_title=\"\", buttons=[]):\n\n attachment = self.create_button_template(button_title, buttons)\n\n message = self.create_generic_payload_message(recipient_info,\n recipient_method, notification_type,\n attachment=attachment)\n\n return self._send(message)\n\n def _send(self, message_json):\n response = requests.post(self.URL, json=message_json,\n headers={\"Content-Type\": \"application/json\"})\n\n if response.status_code != 200:\n raise Exception(\"The Facebook API did not like the message we tried to send them\",\n response.content)\n\n return response\n\n def get_user_profile_info(self, user_id):\n url = (\n \"https://graph.facebook.com\"\n \"/v{0}/{1}?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token={2}\"\n ).format(self.FB_API_VERSION, user_id, self.FB_ACCESS_TOKEN)\n\n response = requests.get(url, headers={\"Content-Type\": \"application/json\"})\n\n return json.loads(response.content)\n","sub_path":"climatechangebot/bot_interface/bot_interface.py","file_name":"bot_interface.py","file_ext":"py","file_size_in_byte":8587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"398822140","text":"import collections\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom domainbed.lib.fast_data_loader import FastDataLoader\n\nif torch.cuda.is_available():\n device = \"cuda\"\nelse:\n device = \"cpu\"\n\n\ndef accuracy_from_loader(algorithm, loader, weights, debug=False, open_set=False, known_classes=None):\n correct = 0\n total = 0\n losssum = 0.0\n weights_offset = 0\n\n algorithm.eval()\n\n predictions = {}\n\n for i, batch in enumerate(loader):\n x = batch[\"x\"].to(device)\n y = batch[\"y\"].to(device)\n \n if 'idx' in batch:\n ids = batch['idx']\n\n with torch.no_grad():\n logits = algorithm.predict(x)\n if open_set:\n logits=logits[:,:-1] # esclude last class (unknown)\n preds=nn.Softmax(dim=1)(logits)\n for i, img_index in enumerate(ids): \n predictions[img_index.item()]={'cls': preds[i].argmax().cpu().item(), 'conf': preds[i].max().cpu().item()}\n mask = y < known_classes\n x = x[mask]\n y = y[mask]\n logits = logits[mask]\n\n loss = F.cross_entropy(logits, y).item()\n\n\n B = len(x)\n losssum += loss * B\n\n if weights is None:\n batch_weights = torch.ones(len(x))\n else:\n batch_weights = weights[weights_offset : weights_offset + len(x)]\n weights_offset += len(x)\n batch_weights = batch_weights.to(device)\n if logits.size(1) == 1:\n correct += (logits.gt(0).eq(y).float() * batch_weights).sum().item()\n else:\n correct += (logits.argmax(1).eq(y).float() * batch_weights).sum().item()\n total += batch_weights.sum().item()\n\n if debug:\n break\n\n algorithm.train()\n\n acc = correct / total\n loss = losssum / total\n return acc, loss, correct, total, predictions\n\n\ndef accuracy(algorithm, loader_kwargs, weights, **kwargs):\n if isinstance(loader_kwargs, dict):\n loader = FastDataLoader(**loader_kwargs)\n elif isinstance(loader_kwargs, FastDataLoader):\n loader = loader_kwargs\n else:\n raise ValueError(loader_kwargs)\n return accuracy_from_loader(algorithm, loader, weights, **kwargs)\n\n\nclass Evaluator:\n def __init__(\n self, test_envs, eval_meta, n_envs, logger, evalmode=\"fast\", debug=False, target_env=None, open_set=False, known_classes=None,\n ):\n all_envs = list(range(n_envs))\n train_envs = sorted(set(all_envs) - set(test_envs))\n self.test_envs = test_envs\n self.train_envs = train_envs\n self.eval_meta = eval_meta\n self.n_envs = n_envs\n self.logger = logger\n self.evalmode = evalmode\n self.debug = debug\n self.open_set = open_set\n self.known_classes = known_classes\n\n if target_env is not None:\n self.set_target_env(target_env)\n\n def set_target_env(self, target_env):\n \"\"\"When len(test_envs) == 2, you can specify target env for computing exact test acc.\"\"\"\n self.test_envs = [target_env]\n\n def evaluate(self, algorithm, ret_losses=False, ret_predictions=False):\n n_train_envs = len(self.train_envs)\n n_test_envs = len(self.test_envs)\n assert n_test_envs == 1\n summaries = collections.defaultdict(float)\n # for key order\n summaries[\"test_in\"] = 0.0\n summaries[\"test_out\"] = 0.0\n summaries[\"test_all\"] = 0.0\n summaries[\"train_in\"] = 0.0\n summaries[\"train_out\"] = 0.0\n accuracies = {}\n losses = {}\n test_correct_all = 0\n test_count_all = 0\n test_predictions = {}\n\n # order: in_splits + out_splits.\n for name, loader_kwargs, weights in self.eval_meta:\n # env\\d_[in|out]\n env_name, inout = name.split(\"_\")\n env_num = int(env_name[3:])\n\n skip_eval = self.evalmode == \"fast\" and inout == \"in\" and env_num not in self.test_envs\n if skip_eval:\n continue\n\n is_test = env_num in self.test_envs\n acc, loss, correct, total, predictions = accuracy(algorithm, loader_kwargs, weights, debug=self.debug,open_set=self.open_set,known_classes=self.known_classes)\n accuracies[name] = acc\n losses[name] = loss\n\n if env_num in self.train_envs:\n summaries[\"train_\" + inout] += acc / n_train_envs\n if inout == \"out\":\n summaries[\"tr_\" + inout + \"loss\"] += loss / n_train_envs\n elif is_test:\n summaries[\"test_\" + inout] += acc / n_test_envs\n test_correct_all += correct\n test_count_all += total\n test_predictions.update(predictions)\n\n summaries[\"test_all\"] = test_correct_all/ test_count_all\n if ret_losses:\n return accuracies, summaries, losses\n else:\n if ret_predictions:\n return accuracies, summaries, test_predictions\n return accuracies, summaries\n","sub_path":"domainbed/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":5084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"514590987","text":"from __future__ import absolute_import, print_function\n\nimport argparse\n\nfrom .install_command import InstallCommand\nfrom .list_command import ListCommand\n\n\nclass Arguments(object):\n \"\"\"\n Class responsible to parse all command line arguments.\n \"\"\"\n\n def __init__(self, version):\n self.__version = version\n self.__parser = argparse.ArgumentParser(description=\"Lazy Package Manager\")\n self.__command_subparser = self.__parser.add_subparsers(help=\"sub commands\", dest=\"command\")\n self.__init_version_arg__()\n\n self.install_command = InstallCommand(self.__parser, self.__command_subparser)\n self.list_command = ListCommand(self.__parser, self.__command_subparser)\n\n def parse_args(self, args):\n \"\"\"\n Parse command line parameters\n\n :param args: command line parameters as list of strings\n :return: command line parameters as :obj:`airgparse.Namespace`\n \"\"\"\n return self.__parser.parse_args(args)\n\n def __init_version_arg__(self):\n \"\"\"\n Initializing version\n \"\"\"\n self.__parser.add_argument(\n '-v',\n '--version',\n action='version',\n version='lazy {ver}'.format(ver=self.__version))\n","sub_path":"lazy/arguments/arguments.py","file_name":"arguments.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"536938856","text":"'''\nCreated on 18 janv. 2017\n\n@author: havarjos\n'''\n\nimport PIL.Image as Image\nfrom builtins import IOError\n\nclass ImageFormaterModel(object):\n \n def setImageToConvert(self, img):\n self._image_to_convert = img\n \n def setKey(self, img):\n self._key = img\n \n def getKey(self):\n '''\n Retourne la clé\n '''\n if self._key is None:\n raise AssertionError(\"Pas de clé\")\n return self.image_to_convert \n \n def getImageConvert(self):\n '''\n Retourne l'image convertit.\n '''\n if self._image_to_convert is None:\n raise AssertionError(\"Pas d'image à chiffrer\")\n return self.image_convert\n \n '''\n Permet de changer l'image à convertir\n @precondition: image_path != None\n @postcondition: \n @raise IOError: Si le fichier de l'image n'est pas trouvé \n '''\n \n def changeImageToConvert(self,image_path):\n if image_path == None:\n raise AssertionError(\"Chemin null\")\n try: \n self.image_to_convert = Image.open(1,image_path)\n except IOError: \n print(\"Image non trouvé\")\n raise IOError\n self.image_convert = self.image_to_convert\n \n \n '''\n Convertit self.image_to_convert en une image de résolution 4 fois\n supérieur. \n @precondition: self.image_to_convert != None \n @postcondition: self.image_convert.width == 2 * self.image_to_convert.width\n self.image_convert.height == 2 * self.image_to_convert.height\n '''\n \n def uppImageResolution(self):\n if self.image_to_convert == None:\n raise AssertionError(\"Il n'y a pas d'image!\")\n self.image_convert = Image.new(1,\n (self.getImageToConvert().width * 2,\n self.getImageToConvert().height * 2))\n i=0\n while i < self.getImageToConvert().width:\n j=0\n while j < self.getImageToConvert().height:\n px = self.getImage().getpixel((i,j))\n self.getImageConvert().putpixel((2*i,2*j),px)\n self.getImageConvert().putpixel((2*i + 1,2*j),px)\n self.getImageConvert().putpixel((2*i,2*j + 1),px)\n self.getImageConvert().putpixel((2*i + 1,2*j + 1),px)\n ++j\n ++i \n \n '''\n Sauvegarde l'image convertit dans le fichier de chemin path_file\n @precondition: pathfile != None and getImageToConvert() != None\n @raise IOError: Si le fichier n'existe pas. \n ''' \n \n def saveImageConvert(self,path_file):\n if self.getImageToConvert() == None:\n raise AssertionError(\"Image à sauvegarder null\")\n if path_file == None:\n raise AssertionError(\"Chemin du fichier null\")\n try:\n self.getImageConvert().save(path_file,'PPM')\n except IOError:\n print (\"Probleme de lecture/écritue\")\n raise IOError ","sub_path":"Image-Encryption/plugins/ImageFormater/model/ImageFormaterModel.py","file_name":"ImageFormaterModel.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"49272328","text":"# coding=utf-8\n\nimport ConfigParser\nimport os\n\n\ndef shell():\n cf = ConfigParser.ConfigParser()\n cf.read(\"../../config.conf\")\n\n content_file = cf.get(\"louzhu\", \"louzhu_content\")\n nlp_host = cf.get(\"default\", \"nlp_host\")\n nlp_dir = cf.get(\"default\", \"nlp_dir\")\n\n if os.system('scp ' + content_file + ' ' + nlp_host + ':' + nlp_dir) == 0:\n return True\n else:\n return False\n","sub_path":"bin/Merge_louzhu/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"39628410","text":"# Copyright 2022 Cerebras Systems.\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\"\"\"\nRecall@K metric for PyTorch.\n\"\"\"\nfrom typing import Optional\n\nimport torch\n\nfrom modelzoo.common.pytorch.metrics.cb_metric import CBMetric\n\n\nclass _PipelineRecallAtKMetric(CBMetric):\n \"\"\"\n Recall@K takes the top K predictions and computes the true positive at K\n and false negative at K. For K = 1, it is the same as Recall.\n\n Recall@K is defined as follows:\n Recall@K = true_positive_at_k / (true_positive_at_k + false_negative_at_k).\n\n Internally, we keep track of true_positive_at_k and false_negative_at_k,\n weighted by `weights`.\n\n If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.\n\n Args:\n :param Tensor labels: A `Tensor` of ground truth labels of type `int32`\n or `int64` and shape (batch_size, num_labels).\n :param Tensor predictions: A `Tensor` of predicted logit values for\n each class in the last dimention. It is of type `float` and shape\n (batch_size, num_classes).\n :param int k: The number of predictions for @k metric.\n :param Tensor weights: Optional `Tensor` whose rank is either 0, or n-1,\n where n is the rank of `labels`. If the latter, it must be\n broadcastable to `labels` (i.e., all dimensions must be either `1`,\n or the same as the corresponding `labels` dimension).\n :param name: Optional `string` which indicates name of the metric.\n If None or empty string, it defaults to the name of the class.\n\n Returns:\n recall_at_k: A float representing Recall@K.\n\n Raises:\n ValueError: If `weights` is not `None` and its shape doesn't match `predictions`\n \"\"\"\n\n def __init__(self, k, name: Optional[str] = None):\n self.k = k\n self.num_classes = None\n super(_PipelineRecallAtKMetric, self).__init__(name=name)\n\n def init_state(self):\n self.reset_state()\n\n def update_on_host(self, labels, predictions, weights=None):\n if weights is not None:\n if len(weights.shape) != 0 and weights.numel() != labels.shape[0]:\n raise ValueError(\n f\"`labels`={labels.shape} and `weights`={weights.shape} so\"\n f\"`weights` must be a scalar or a vector of size \"\n f\"{labels.shape[0]}\"\n )\n weights = weights.detach()\n\n labels = labels.detach()\n predictions = predictions.detach()\n if self.num_classes is None:\n self.num_classes = predictions.shape[-1]\n\n _, topk_pred_idx = torch.topk(predictions, self.k, dim=-1)\n\n # Computer the number of true positives per row\n lbl = labels.repeat_interleave(self.k, dim=1)\n pred_idx = topk_pred_idx.repeat(1, labels.shape[-1])\n intersection_per_row = torch.sum(lbl == pred_idx, dim=-1).float()\n\n if weights is not None:\n tp = intersection_per_row * weights\n fn = (labels.shape[-1] - intersection_per_row) * weights\n else:\n tp = intersection_per_row\n fn = labels.shape[-1] - intersection_per_row\n\n self.true_positive_at_k += torch.sum(tp).numpy()\n self.false_negative_at_k += torch.sum(fn).numpy()\n\n def compute(self):\n \"\"\"Returns the Recall@K as a float.\"\"\"\n return float(\n self.true_positive_at_k\n / (self.true_positive_at_k + self.false_negative_at_k)\n )\n\n def reset_state(self):\n self.true_positive_at_k = 0.0\n self.false_negative_at_k = 0.0\n\n\n# Create a factory for creating a metric depending on execution strategy\nRecallAtKMetric = CBMetric.create_metric_impl_factory(\n pipeline_metric_cls=_PipelineRecallAtKMetric, ws_metric_cls=None,\n)\n","sub_path":"modelzoo/common/pytorch/metrics/recall_at_k.py","file_name":"recall_at_k.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"395812661","text":"from django.shortcuts import render\nfrom rest_framework import viewsets\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\nfrom .serializers import *\nfrom .permissions import *\n\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (OnlyOwnerEditOrDeleteUser, IsAuthenticated)\n authentication_classes = (JSONWebTokenAuthentication, )\n def get_queryset(self):\n queryset = User.objects.all()\n is_me = self.request.query_params.get('me', None)\n if is_me is not None:\n print(\"YES YES YES\")\n print(is_me)\n print(self.request.user)\n return queryset.filter(pk=self.request.user.pk)\n return queryset\n\n# testing api restriction\nclass RestrictedView(APIView):\n permission_classes = (IsAuthenticated,)\n authentication_classes = (JSONWebTokenAuthentication,)\n def get(self, request):\n data = {'foo': 'bar'}\n return Response(data)\n","sub_path":"backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"348015225","text":"\"\"\"\nbyceps.services.board.posting_query_service\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n:Copyright: 2006-2021 Jochen Kupperschmidt\n:License: Revised BSD (see `LICENSE` file for details)\n\"\"\"\n\nfrom typing import Dict, Optional, Set\n\nfrom ...database import db, Pagination\nfrom ...typing import PartyID, UserID\nfrom ...util.iterables import index_of\n\nfrom ..user import service as user_service\nfrom ..user.transfer.models import User\n\nfrom .dbmodels.category import Category as DbCategory\nfrom .dbmodels.posting import Posting as DbPosting\nfrom .dbmodels.topic import Topic as DbTopic\nfrom .transfer.models import BoardID, PostingID, TopicID\n\n\ndef count_postings_for_board(board_id: BoardID) -> int:\n \"\"\"Return the number of postings for that board.\"\"\"\n return DbPosting.query \\\n .join(DbTopic).join(DbCategory).filter(DbCategory.board_id == board_id) \\\n .count()\n\n\ndef find_posting_by_id(posting_id: PostingID) -> Optional[DbPosting]:\n \"\"\"Return the posting with that id, or `None` if not found.\"\"\"\n return DbPosting.query.get(posting_id)\n\n\ndef get_posting(posting_id: PostingID) -> DbPosting:\n \"\"\"Return the posting with that id.\"\"\"\n posting = find_posting_by_id(posting_id)\n\n if posting is None:\n raise ValueError(f'Unknown posting ID \"{posting_id}\"')\n\n return posting\n\n\ndef paginate_postings(\n topic_id: TopicID,\n include_hidden: bool,\n party_id: Optional[PartyID],\n page: int,\n postings_per_page: int,\n) -> Pagination:\n \"\"\"Paginate postings in that topic, as visible for the user.\"\"\"\n query = DbPosting.query \\\n .options(\n db.joinedload(DbPosting.topic),\n db.joinedload(DbPosting.last_edited_by).load_only('screen_name'),\n db.joinedload(DbPosting.hidden_by).load_only('screen_name'),\n ) \\\n .for_topic(topic_id)\n\n if not include_hidden:\n query = query.without_hidden()\n\n postings = query \\\n .earliest_to_latest() \\\n .paginate(page, postings_per_page)\n\n creator_ids = {posting.creator_id for posting in postings.items}\n creators_by_id = _get_users_by_id(creator_ids, party_id)\n\n for posting in postings.items:\n posting.creator = creators_by_id[posting.creator_id]\n\n return postings\n\n\ndef _get_users_by_id(\n user_ids: Set[UserID], party_id: Optional[PartyID]\n) -> Dict[UserID, User]:\n users = user_service.find_users(\n user_ids, include_avatars=True, include_orga_flags_for_party_id=party_id\n )\n return user_service.index_users_by_id(users)\n\n\ndef calculate_posting_page_number(\n posting: DbPosting, include_hidden: bool, postings_per_page: int\n) -> int:\n \"\"\"Return the number of the page the posting should appear on.\"\"\"\n query = DbPosting.query \\\n .for_topic(posting.topic_id)\n\n if not include_hidden:\n query = query.without_hidden()\n\n topic_postings = query \\\n .earliest_to_latest() \\\n .all()\n\n index = index_of(topic_postings, lambda p: p == posting)\n if index is None:\n return 1 # Shouldn't happen.\n\n return divmod(index, postings_per_page)[0] + 1\n","sub_path":"byceps/services/board/posting_query_service.py","file_name":"posting_query_service.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"236886569","text":"import datetime\r\nimport pytz\r\n\r\nfrom django.contrib.gis.db import models\r\nfrom django.contrib.gis.geos import Point, MultiPoint, Polygon\r\nfrom django.contrib.postgres.fields import JSONField\r\n\r\n\r\nclass Tweet(models.Model):\r\n coords = models.PointField(null=True)\r\n text = models.CharField(max_length=1000)\r\n preprocessed_text = models.CharField(max_length=1000, default='')\r\n uid = models.CharField(max_length=200)\r\n timestamp = models.DateTimeField()\r\n polarity = models.FloatField()\r\n sentiment = models.CharField(max_length=50)\r\n lang = models.CharField(max_length=20, blank=True)\r\n country = models.CharField(max_length=3, blank=True,default='')\r\n\r\n @classmethod\r\n def create(cls, uid, text, preprocessed_text, coords, timestamp, polarity, lang, country, sentiment_threshold=.2):\r\n \"\"\"\r\n Constructor method\r\n \"\"\"\r\n if polarity > sentiment_threshold:\r\n sentiment = 'Positive'\r\n elif polarity < -sentiment_threshold:\r\n sentiment = 'Negative'\r\n else:\r\n sentiment = 'Neutral'\r\n\r\n if coords is not None:\r\n coords = Point(coords[0], coords[1])\r\n else:\r\n coords = None\r\n timestamp = datetime.datetime.fromtimestamp(timestamp, tz=pytz.UTC)\r\n\r\n tweet = cls(uid=uid, text=text, preprocessed_text=preprocessed_text, coords=coords, timestamp=timestamp,\r\n polarity=polarity, lang=lang, sentiment=sentiment, country=country)\r\n return tweet\r\n\r\n def __str__(self):\r\n return self.uid\r\n\r\n def get_coords(self):\r\n lnglat = self.coords.coords\r\n return {'lat': lnglat[1], 'lng': lnglat[0]}\r\n\r\n class Meta:\r\n verbose_name_plural = 'Tweets'\r\n ordering = ['uid']\r\n unique_together = ('uid',)\r\n\r\n\r\nclass CountryInfo(models.Model):\r\n geojson = JSONField()\r\n name = models.CharField(max_length=200)\r\n name_iso = models.CharField(max_length=3)\r\n\r\n @classmethod\r\n def create(cls, name, name_iso, geojson):\r\n \"\"\"\r\n Constructor method\r\n \"\"\"\r\n\r\n info = cls(name=name, name_iso=name_iso, geojson=geojson)\r\n return info\r\n\r\n def __str__(self):\r\n return str(self.name)\r\n\r\n class Meta:\r\n verbose_name_plural = 'CountryInfos'\r\n ordering = ['name']\r\n unique_together = ('name_iso',)\r\n","sub_path":"app/locations/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"32571020","text":"from __future__ import division\nimport os\nimport sys\nimport time\nimport glob\nimport json\nimport logging\nimport argparse\nimport copy\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.utils\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom tensorboardX import SummaryWriter\n\nimport numpy as np\nfrom thop import profile\n\nfrom config_train import config\n\n# if config.is_eval:\n# config.save = '../OUTPUT/eval-{}-{}'.format(config.save, time.strftime(\"%Y%m%d-%H%M%S\"))\n# else:\n# config.save = '../OUTPUT/train-{}-{}'.format(config.save, time.strftime(\"%Y%m%d-%H%M%S\"))\n\nfrom dataloader import get_train_loader, CyclicIterator\nfrom datasets import Cityscapes, COCO\nfrom eval import SegEvaluator\n\nimport dataloaders\nfrom utils.init_func import init_weight\nfrom utils.lr_scheduler import Iter_LR_Scheduler\nfrom seg_opr.loss_opr import ProbOhemCrossEntropy2d\nfrom seg_opr.loss_opr import L1Loss, MSELoss, DeepLabCE, RegularCE\nfrom utils.darts_utils import create_exp_dir, save, plot_op, plot_path_width, objective_acc_lat\nfrom utils.dist_utils import reduce_tensor, ModelEma\nfrom hrtlab import HRTLab\nfrom collections import OrderedDict\nfrom utils.pyt_utils import AverageMeter\nfrom utils.dist_utils import reduce_tensor\n\nimport yaml\nimport timm\nfrom timm.optim import create_optimizer\nfrom utils.pyt_utils import AverageMeter, to_cuda, get_loss_info_str, compute_hist, compute_hist_np, load_pretrain\n\nfrom detectron2.config import get_cfg\nfrom detectron2.engine import launch, default_setup, default_argument_parser\nimport detectron2.data.transforms as T\nfrom detectron2.structures import BitMasks, ImageList, Instances\nfrom detectron2.data import MetadataCatalog, build_detection_train_loader\nfrom detectron2.projects.panoptic_deeplab import (\n PanopticDeeplabDatasetMapper,\n add_panoptic_deeplab_config,\n)\n\n## dist train\ntry:\n import apex\n from apex import amp\n from apex.parallel import DistributedDataParallel as DDP\n from apex.parallel import convert_syncbn_model\n has_apex = True\nexcept ImportError:\n from torch.nn.parallel import DistributedDataParallel as DDP\n has_apex = False\n\ndef adjust_learning_rate(base_lr, power, optimizer, epoch, total_epoch):\n for param_group in optimizer.param_groups:\n param_group['lr'] = param_group['lr'] * power\n\n\n# The first arg parser parses out only the --config argument, this argument is used to\n# load a yaml file containing key-values that override the defaults for the main parser below\nconfig_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False)\nparser.add_argument('-c', '--config', default='../configs/panoptic/512drop0.2.yaml', type=str, metavar='FILE',\n help='YAML config file specifying default arguments')\n\nparser = argparse.ArgumentParser(description='PyTorch Training')\nparser.add_argument('--det2_cfg', type=str, default='configs/Cityscapes-PanopticSegmentation/panoptic_deeplab_R_52_os16_mg124_poly_90k_bs32_crop_512_1024.yaml', help='')\nparser.add_argument('--save', type=str, default='../OUTPUT/train_', help='')\nparser.add_argument('--exp_name', type=str, default='3path799', help='')\nparser.add_argument('--pretrain', type=str, default=None, help='resume path')\nparser.add_argument('--resume', type=str, default='../OUTPUT/train/', help='resume path')\nparser.add_argument('--clip-grad', type=float, default=5., metavar='NORM',\n help='Clip gradient norm (default: None, no clipping)')\n\nparser.add_argument(\"--local_rank\", default=0, type=int)\nparser.add_argument(\"--world_size\", default=1, type=int)\nparser.add_argument(\"--eval_height\", default=1025, type=int, help='train height')\nparser.add_argument(\"--eval_width\", default=2049, type=int, help='train width')\nparser.add_argument(\"--test_epoch\", default=250, type=int, help='Epochs for test')\nparser.add_argument(\"--batch_size\", default=12, type=int, help='batch size')\nparser.add_argument(\"--Fch\", default=12, type=int, help='Fch')\nparser.add_argument('--stem_head_width', type=float, default=1.0, help='base learning rate')\n\n## new retrain ###\nparser.add_argument('--sched', default='step', type=str, metavar='SCHEDULER',\n help='LR scheduler (default: \"step\"')\nparser.add_argument('--epochs', type=int, default=4000, help='num of training epochs')\nparser.add_argument('--dataset', type=str, default='cityscapes', help='pascal or cityscapes')\nparser.add_argument('--base_lr', type=float, default=0.05, help='base learning rate')\nparser.add_argument('--warmup_start_lr', type=float, default=5e-6, help='warm up learning rate')\nparser.add_argument('--lr-step', type=float, default=None)\nparser.add_argument('--warmup-iters', type=int, default=1000)\nparser.add_argument('--min-lr', type=float, default=None)\nparser.add_argument('--crop_size', type=int, default=512, help='image crop size')\nparser.add_argument('--resize', type=int, default=512, help='image crop size')\nparser.add_argument(\"--image_height\", default=513, type=int, help='train height')\nparser.add_argument(\"--image_width\", default=1025, type=int, help='train width')\nparser.add_argument('--workers', type=int, default=4, help='number of data loading workers')\nparser.add_argument('--dist', type=bool, default=True)\nparser.add_argument('--autodeeplab', type=str, default='train_seg')\nparser.add_argument('--max-iteration', default=1000000, type=bool)\nparser.add_argument('--mode', default='poly', type=str, help='how lr decline')\nparser.add_argument('--train_mode', type=str, default='iter', choices=['iter', 'epoch'])\n\nparser.add_argument(\"--data_path\", default='/home/t-hongyuanyu/data/cityscapes', type=str, help='If specified, replace config.load_path')\nparser.add_argument(\"--load_path\", default='', type=str, help='If specified, replace config.load_path')\nparser.add_argument(\"--json_file\", default='jsons/0.json', type=str, help='model_arch')\nparser.add_argument(\"--seed\", default=12345, type=int, help=\"random seed\")\nparser.add_argument('--sync_bn', action='store_false',\n help='Enable NVIDIA Apex or Torch synchronized BatchNorm.')\nparser.add_argument('--random_sample', action='store_true',\n help='Random sample path.')\nparser.add_argument('--drop_path_prob', type=float, default=0.0, help='drop path prob')\n\n# Optimizer parameters\nparser.add_argument('--opt', default='sgd', type=str, metavar='OPTIMIZER',\n help='Optimizer (default: \"sgd\"')\nparser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON',\n help='Optimizer Epsilon (default: 1e-8)')\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='SGD momentum (default: 0.9)')\nparser.add_argument('--weight-decay', type=float, default=0.0001,\n help='weight decay (default: 0.0001)')\n\n# Model Exponential Moving Average\nparser.add_argument('--model-ema', action='store_true', default=False,\n help='Enable tracking moving average of model weights')\nparser.add_argument('--model-ema-force-cpu', action='store_true', default=False,\n help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.')\nparser.add_argument('--model-ema-decay', type=float, default=0.9998,\n help='decay factor for model weights moving average (default: 0.9998)')\n\nparser.add_argument('--eval_flag', action='store_true', default=False,\n help='semantic eval')\n# Loss\nparser.add_argument('--bn_momentum', type=float, default=0.01, help='bn momentum')\nparser.add_argument('--lamb', type=float, default=0.2, help='deep sup')\nparser.add_argument('--ignore', type=int, default=255, help='semantic ignore')\nparser.add_argument('--topk_percent', type=float, default=0.2, help='semantic topk_percent')\nparser.add_argument('--semantic_loss_weight', type=float, default=1.0, help='semantic loss weight')\nparser.add_argument('--center_loss_weight', type=float, default=200., help='center loss weight')\nparser.add_argument('--offset_loss_weight', type=float, default=0.01, help='offset loss weight')\n\n# train val\nparser.add_argument('--norm', type=str, default='naiveSyncBN', help='BN, SyncBN, naiveSyncBN')\nparser.add_argument('--sem_only', type=bool, default=False, help='sem_only')\nparser.add_argument('--use_aux', type=bool, default=True, help='use_aux')\nparser.add_argument('--align_corners', type=bool, default=False, help='align_corners')\nparser.add_argument('--model_type', type=int, default=1, help='0 s=8, no fusion, 1, fuse s4, 2 fuse s4, s8')\nparser.add_argument('--eval_flip', action='store_true', default=False,\n help='semantic eval flip')\n\ndef _parse_args():\n # Do we have a config file to parse?\n args_config, remaining = config_parser.parse_known_args()\n if args_config.config:\n with open(args_config.config, 'r') as f:\n cfg = yaml.safe_load(f)\n parser.set_defaults(**cfg)\n\n # The main arg parser parses the rest of the args, the usual\n # defaults will have been overridden if config file specified.\n args = parser.parse_args(remaining)\n\n # Cache the args as a text string to save them in the output dir later\n args_text = yaml.safe_dump(args.__dict__, default_flow_style=False)\n return args, args_text\n\ndef setup(args):\n \"\"\"\n Create configs and perform basic setups.\n \"\"\"\n cfg = get_cfg()\n add_panoptic_deeplab_config(cfg)\n cfg.merge_from_file(args.config_file)\n # cfg.merge_from_list(args.opts)\n cfg.freeze()\n default_setup(cfg, args)\n return cfg\n\n\ndef build_sem_seg_train_aug(cfg):\n augs = [\n T.ResizeShortestEdge(\n cfg.INPUT.MIN_SIZE_TRAIN, cfg.INPUT.MAX_SIZE_TRAIN, cfg.INPUT.MIN_SIZE_TRAIN_SAMPLING\n )\n ]\n if cfg.INPUT.CROP.ENABLED:\n augs.append(T.RandomCrop(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE))\n augs.append(T.RandomFlip())\n return augs\n\n\n\ndef main():\n args, args_text = _parse_args()\n\n # dist init\n torch.distributed.init_process_group(backend='nccl', init_method='env://')\n config.device = 'cuda:%d' % args.local_rank\n torch.cuda.set_device(args.local_rank)\n args.world_size = torch.distributed.get_world_size()\n args.local_rank = torch.distributed.get_rank()\n logging.info(\"rank: {} world_size: {}\".format(args.local_rank, args.world_size))\n\n # detectron2 data loader ###########################\n # det2_args = default_argument_parser().parse_args()\n det2_args = args\n det2_args.config_file = args.det2_cfg\n cfg = setup(det2_args)\n cfg.defrost()\n cfg.SOLVER.IMS_PER_BATCH = args.batch_size * args.world_size\n cfg.freeze()\n mapper = PanopticDeeplabDatasetMapper(cfg, augmentations=build_sem_seg_train_aug(cfg))\n det2_dataset = iter(build_detection_train_loader(cfg, mapper=mapper))\n \n if args.load_path:\n config.load_path = args.load_path\n\n config.batch_size = args.batch_size\n config.image_height = args.image_height\n config.image_width = args.image_width\n config.eval_height = args.eval_height\n config.eval_width = args.eval_width\n config.Fch = args.Fch\n config.dataset_path = args.data_path\n config.save = args.save + args.exp_name\n\n if args.local_rank == 0:\n create_exp_dir(config.save, scripts_to_save=glob.glob('*.py')+glob.glob('*.sh'))\n logger = SummaryWriter(config.save)\n log_format = '%(asctime)s %(message)s'\n logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p')\n fh = logging.FileHandler(os.path.join(config.save, 'log.txt'))\n fh.setFormatter(logging.Formatter(log_format))\n logging.getLogger().addHandler(fh)\n logging.info(\"args = %s\", str(config))\n else:\n logger = None\n\n # preparation ################\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n \n kwargs = {'num_workers': args.workers, 'pin_memory': True, 'drop_last': True}\n train_loader, train_sampler, val_loader, val_sampler, num_classes = dataloaders.make_data_loader(args, **kwargs)\n\n with open(args.json_file, 'r') as f:\n model_dict = json.loads(f.read())\n\n if args.dataset == \"cityscapes\":\n semantic_loss = DeepLabCE(ignore_label=args.ignore, top_k_percent_pixels=args.topk_percent)\n elif args.dataset == \"coco\":\n semantic_loss = RegularCE(ignore_label=args.ignore)\n\n semantic_loss_weight = args.semantic_loss_weight\n center_loss = MSELoss(reduction='none')\n center_loss_weight = args.center_loss_weight\n offset_loss = L1Loss(reduction='none')\n offset_loss_weight = args.offset_loss_weight\n\n model = HRTLab(model_dict[\"ops\"], model_dict[\"paths\"], model_dict[\"downs\"], model_dict[\"widths\"], model_dict[\"lasts\"],\n semantic_loss, semantic_loss_weight, center_loss, center_loss_weight, offset_loss, offset_loss_weight, lamb=args.lamb, eval_flag=args.eval_flag, num_classes=num_classes, layers=config.layers, Fch=config.Fch, width_mult_list=config.width_mult_list, stem_head_width=(args.stem_head_width, args.stem_head_width), norm=args.norm, align_corners=args.align_corners, pretrain=args.pretrain, model_type=args.model_type, sem_only=args.sem_only, use_aux=args.use_aux)\n\n last = model_dict[\"lasts\"]\n\n if args.local_rank == 0:\n logging.info(\"net: \" + str(model))\n for b in range(len(last)):\n if len(config.width_mult_list) > 1:\n plot_op(model.ops[b], model.paths[b], width=model.widths[b], head_width=args.stem_head_width, F_base=config.Fch).savefig(os.path.join(config.save, \"ops_%d_%d.png\"%(0,b)), bbox_inches=\"tight\")\n else:\n plot_op(model.ops[b], model.paths[b], F_base=config.Fch).savefig(os.path.join(config.save, \"ops_%d_%d.png\"%(0,b)), bbox_inches=\"tight\")\n plot_path_width(model.lasts, model.paths, model.widths).savefig(os.path.join(config.save, \"path_width%d.png\"%0))\n \n flops, params = profile(model, inputs=(torch.randn(1, 3, args.eval_height, args.eval_width),), verbose=False)\n logging.info(\"params = %fMB, FLOPs = %fGB\", params / 1e6, flops / 1e9)\n logging.info(\"ops:\" + str(model.ops))\n logging.info(\"path:\" + str(model.paths))\n logging.info(\"last:\" + str(model.lasts))\n with open(os.path.join(config.save, 'args.yaml'), 'w') as f:\n f.write(args_text)\n\n init_weight(model, nn.init.kaiming_normal_, torch.nn.BatchNorm2d, config.bn_eps, config.bn_momentum, mode='fan_in', nonlinearity='relu')\n\n\n # for m in model.modules():\n # if isinstance(m, nn.Conv2d):\n # nn.init.normal_(m.weight, std=0.001)\n # elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n # nn.init.constant_(m.weight, 1)\n # nn.init.constant_(m.bias, 0)\n\n # # set batchnorm momentum\n # for module in model.modules():\n # if isinstance(module, torch.nn.BatchNorm2d):\n # module.momentum = args.bn_momentum\n\n model = model.cuda()\n\n # Optimizer ###################################\n base_lr = args.base_lr\n\n if args.opt == \"sgd\":\n optimizer = torch.optim.SGD(model.parameters(), lr=base_lr, momentum=args.momentum, weight_decay=args.weight_decay)\n elif args.opt == \"adam\":\n optimizer = torch.optim.Adam(model.parameters(), lr=base_lr, betas=(0.9, 0.999), eps=1e-08)\n elif args.opt == \"adamw\":\n optimizer = torch.optim.AdamW(model.parameters(), lr=base_lr, betas=(0.9, 0.999), eps=1e-08, weight_decay=args.weight_decay)\n else:\n optimizer = create_optimizer(args, model)\n \n if args.sched == \"raw\":\n lr_scheduler = None\n else:\n max_iteration = len(train_loader) * args.epochs\n lr_scheduler = Iter_LR_Scheduler(args, max_iteration, len(train_loader))\n\n start_epoch = 0\n\n if os.path.exists(os.path.join(config.save, 'last.pth.tar')):\n args.resume = os.path.join(config.save, 'last.pth.tar')\n\n if args.resume:\n model_state_file = args.resume\n if os.path.isfile(model_state_file):\n checkpoint = torch.load(model_state_file, map_location=torch.device('cpu'))\n start_epoch = checkpoint['start_epoch']\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n # lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])\n logging.info('Loaded checkpoint (starting from iter {})'.format(checkpoint['start_epoch']))\n\n\n model_ema = None\n if args.model_ema:\n # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper\n model_ema = ModelEma(\n model,\n decay=args.model_ema_decay,\n device='cpu' if args.model_ema_force_cpu else '',\n resume=None)\n\n # if args.sync_bn:\n # if has_apex:\n # model = apex.parallel.convert_syncbn_model(model)\n # else:\n # model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\n \n if has_apex:\n model = DDP(model, delay_allreduce=True)\n else:\n model = DDP(model, device_ids=[args.local_rank])\n\n if model_ema:\n eval_model = model_ema.ema\n else:\n eval_model = model\n\n best_valid_iou = -9999.\n best_epoch = 0\n temp_iou = -99999\n avg_loss = 99999\n\n for epoch in range(start_epoch, args.epochs):\n train_sampler.set_epoch(epoch)\n val_sampler.set_epoch(epoch)\n if args.local_rank == 0:\n logging.info(config.load_path)\n logging.info(config.save)\n logging.info(\"lr: \" + str(optimizer.param_groups[0]['lr']))\n\n # training\n drop_prob = args.drop_path_prob * epoch / args.epochs\n model.module.backbone.drop_path_prob(drop_prob)\n\n train(train_loader, det2_dataset, model, model_ema, lr_scheduler, optimizer, logger, epoch, args, cfg)\n \n if args.dataset == 'coco':\n temp_iou, avg_loss = validation(val_loader, eval_model, semantic_loss, num_classes, args, cal_miou=True)\n else:\n # if (epoch + 1) >= args.epochs // 4:\n if (epoch + 1) >= args.epochs // 4:\n temp_iou, avg_loss = validation(val_loader, eval_model, semantic_loss, num_classes, args, cal_miou=True)\n else:\n temp_iou = 0.\n avg_loss = 99999.\n\n torch.cuda.empty_cache()\n if args.local_rank == 0:\n if temp_iou > best_valid_iou:\n best_valid_iou = temp_iou\n best_epoch = epoch\n\n if model_ema is not None:\n torch.save({\n 'start_epoch': epoch + 1,\n 'state_dict': model_ema.ema.state_dict(),\n 'optimizer': optimizer.state_dict(),\n # 'lr_scheduler': lr_scheduler.state_dict(),\n }, os.path.join(config.save, 'best_checkpoint.pth.tar'))\n else:\n torch.save({\n 'start_epoch': epoch + 1,\n 'state_dict': model.module.state_dict(),\n 'optimizer': optimizer.state_dict(),\n # 'lr_scheduler': lr_scheduler.state_dict(),\n }, os.path.join(config.save, 'best_checkpoint.pth.tar'))\n\n logger.add_scalar(\"mIoU/val\", temp_iou, epoch)\n logging.info(\"[Epoch %d/%d] valid mIoU %.4f eval loss %.4f\"%(epoch + 1, args.epochs, temp_iou, avg_loss))\n logging.info(\"Best valid mIoU %.4f Epoch %d\"%(best_valid_iou, best_epoch + 1 ))\n\n if model_ema is not None:\n torch.save({\n 'start_epoch': epoch + 1,\n 'state_dict': model_ema.ema.state_dict(),\n 'optimizer': optimizer.state_dict(),\n # 'lr_scheduler': lr_scheduler.state_dict(),\n }, os.path.join(config.save, 'last.pth.tar'))\n else:\n torch.save({\n 'start_epoch': epoch + 1,\n 'state_dict': model.module.state_dict(),\n 'optimizer': optimizer.state_dict(),\n # 'lr_scheduler': lr_scheduler.state_dict(),\n }, os.path.join(config.save, 'last.pth.tar'))\n\ndef train(train_loader, det2_dataset, model, model_ema, lr_scheduler, optimizer, logger, epoch, args, cfg):\n\n model.train()\n pixel_mean = cfg.MODEL.PIXEL_MEAN\n pixel_std = cfg.MODEL.PIXEL_STD\n # pixel_mean = [123.675, 116.28, 103.53]\n # pixel_std = [58.395, 57.12, 57.375]\n pixel_mean = torch.Tensor(pixel_mean).view(-1, 1, 1).cuda()\n pixel_std = torch.Tensor(pixel_std).view(-1, 1, 1).cuda()\n\n device = torch.device('cuda:{}'.format(args.local_rank))\n data_time = AverageMeter()\n batch_time = AverageMeter()\n\n loss_meter_dict = OrderedDict()\n loss_meter_dict['total'] = AverageMeter()\n loss_meter_dict['semantic'] = AverageMeter()\n loss_meter_dict['center'] = AverageMeter()\n loss_meter_dict['offset'] = AverageMeter()\n\n # for i, sample in enumerate(train_loader):\n for i in range(len(train_loader)):\n start_time = time.time()\n cur_iter = epoch * len(train_loader) + i\n lr_scheduler(optimizer, cur_iter)\n lr = lr_scheduler.get_lr(optimizer)\n\n # data = to_cuda(sample, device)\n # data_time.update(time.time() - start_time)\n\n det2_data = next(det2_dataset)\n det2_inputs = [x[\"image\"].cuda(non_blocking=True) for x in det2_data]\n det2_inputs = [(x - pixel_mean) / pixel_std for x in det2_inputs]\n det2_inputs = ImageList.from_tensors(det2_inputs, 0).tensor\n data = {}\n data['image'] = det2_inputs\n\n det2_targets = [x[\"sem_seg\"].cuda(non_blocking=True) for x in det2_data]\n det2_targets = ImageList.from_tensors(det2_targets, 0, args.ignore).tensor\n data['semantic'] = det2_targets\n \n det2_targets = [x[\"sem_seg_weights\"].cuda(non_blocking=True) for x in det2_data]\n det2_targets = ImageList.from_tensors(det2_targets, 0, args.ignore).tensor\n data['semantic_weights'] = det2_targets\n \n other_keys = ['center', 'center_weights', 'offset', 'offset_weights'] \n for k in other_keys:\n tmp_data = [x[k].cuda(non_blocking=True) for x in det2_data]\n tmp_data = ImageList.from_tensors(tmp_data, 0, args.ignore).tensor.squeeze(1)\n data[k] = tmp_data\n \n data['center'][data['center']==255] = 0.\n torch.cuda.synchronize()\n image = data.pop('image')\n\n loss_dict = model(image, data)\n loss = loss_dict['total']\n optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip_grad)\n optimizer.step()\n\n torch.cuda.synchronize()\n for key in loss_dict.keys():\n reduce_loss = reduce_tensor(loss_dict[key].detach().data, args.world_size)\n loss_meter_dict[key].update(reduce_loss.cpu().item(), image.size(0))\n batch_time.update(time.time() - start_time)\n \n if args.local_rank == 0 and i % 20 == 0:\n msg = '[{0}/{1}][{2}/{3}] LR: {4:.7f}\\t' \\\n 'Time: {batch_time.val:.3f}s ({batch_time.avg:.3f}s)\\t' \\\n 'Data: {data_time.val:.3f}s ({data_time.avg:.3f}s)\\t'.format(\n i + 1, len(train_loader), epoch+1, args.epochs, lr, batch_time=batch_time, data_time=data_time)\n msg += get_loss_info_str(loss_meter_dict)\n logging.info(msg)\n\n torch.cuda.synchronize()\n\n if args.local_rank == 0:\n logger.add_scalar(\"LR\", lr, cur_iter)\n for key in loss_meter_dict.keys():\n logger.add_scalar(\"Loss/{}\".format(key), loss_meter_dict[key].val, cur_iter)\n\n if model_ema is not None:\n model_ema.update(model)\n\ndef validation(val_loader, model, criterion, n_classes, args, cal_miou=True):\n device = torch.device('cuda:{}'.format(args.local_rank))\n model.eval()\n test_loss = 0.0\n\n hist_size = (n_classes, n_classes)\n hist = torch.zeros(hist_size, dtype=torch.float32).cuda()\n\n for i, sample in enumerate(val_loader):\n sample = to_cuda(sample, device)\n image = sample['image']\n if args.dataset == \"coco\":\n target = sample['semantic']\n # target = sample['label'].long()\n else:\n target = sample['semantic']\n N, H, W = target.shape\n probs = torch.zeros((N, n_classes, H, W)).cuda()\n probs.requires_grad = False\n\n torch.cuda.synchronize()\n if args.local_rank==0:\n logging.info(\"Evaluation [{}/{}]\".format(i+1, len(val_loader)))\n with torch.no_grad():\n output = model(image)\n prob = F.softmax(output, 1)\n probs += prob\n loss = criterion(output, target).detach().data\n dist.all_reduce(loss, dist.ReduceOp.SUM)\n test_loss += loss\n\n if args.eval_flip:\n output = model(torch.flip(image, dims=(3,)))\n output = torch.flip(output, dims=(3,))\n prob = F.softmax(output, 1)\n probs += prob\n loss = criterion(output, target).detach().data\n dist.all_reduce(loss, dist.ReduceOp.SUM)\n test_loss += loss\n\n if cal_miou:\n # probs = probs.data.numpy()\n preds = torch.argmax(probs, dim=1)\n hist_once = compute_hist(preds, target, n_classes, args.ignore)\n hist = hist + hist_once\n \n torch.cuda.synchronize()\n\n\n if args.eval_flip:\n avg_loss = test_loss / 2*len(val_loader)\n else:\n avg_loss = test_loss / len(val_loader)\n\n if cal_miou:\n # hist = torch.tensor(hist).cuda()\n dist.all_reduce(hist, dist.ReduceOp.SUM)\n hist = hist.cpu().numpy().astype(np.float32)\n IOUs = np.diag(hist) / (np.sum(hist, axis=0) + np.sum(hist, axis=1) - np.diag(hist))\n mIOU = np.mean(IOUs)\n else:\n mIOU = -avg_loss\n\n return mIOU*100, avg_loss\n\n\ndef validation_np(val_loader, model, criterion, n_classes, args, cal_miou=True):\n device = torch.device('cuda:{}'.format(args.local_rank))\n model.eval()\n test_loss = 0.0\n hist_size = (n_classes, n_classes)\n hist = np.zeros(hist_size, dtype=np.float32)\n\n for i, sample in enumerate(val_loader):\n sample = to_cuda(sample, device)\n image = sample['image']\n target = sample['semantic']\n N, H, W = target.shape\n probs = torch.zeros((N, n_classes, H, W))\n probs.requires_grad = False\n\n torch.cuda.synchronize()\n if args.local_rank==0:\n logging.info(\"Evaluation [{}/{}]\".format(i+1, len(val_loader)))\n\n with torch.no_grad():\n output = model(image)\n prob = F.softmax(output, 1)\n probs += prob.cpu()\n loss = criterion(output, target).detach().data\n dist.all_reduce(loss, dist.ReduceOp.SUM)\n test_loss += loss\n\n if args.eval_flip:\n output = model(torch.flip(image, dims=(3,)))\n output = torch.flip(output, dims=(3,))\n prob = F.softmax(output, 1)\n probs += prob.cpu()\n loss = criterion(output, target).detach().data\n dist.all_reduce(loss, dist.ReduceOp.SUM)\n test_loss += loss\n\n if cal_miou:\n probs = probs.data.numpy()\n preds = np.argmax(probs, axis=1)\n hist_once = compute_hist_np(preds.flatten(), target.data.cpu().numpy().flatten(), n_classes, args.ignore)\n hist = hist + hist_once\n \n torch.cuda.synchronize()\n\n if args.eval_flip:\n avg_loss = test_loss / 2*len(val_loader)\n else:\n avg_loss = test_loss / len(val_loader)\n\n if cal_miou:\n hist = torch.tensor(hist).cuda()\n dist.all_reduce(hist, dist.ReduceOp.SUM)\n hist = hist.cpu().numpy().astype(np.float32)\n IOUs = np.diag(hist) / (np.sum(hist, axis=0) + np.sum(hist, axis=1) - np.diag(hist))\n mIOU = np.mean(IOUs)\n else:\n mIOU = -avg_loss\n\n return mIOU*100, avg_loss\n\n\nif __name__ == '__main__':\n main() \n","sub_path":"train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":28507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"99972160","text":"import logging\n\nfrom GraphqlApiObject.GraphqlApi.gen_params import GenParams\n\nfrom Schema.GitHubSchema.github_schema import Mutation, github_schema\nfrom jsonschema import validate, draft7_format_checker\nimport allure\n\ninput_schema = {\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"input\": {\n \"type\": \"object\",\n \"properties\": {\n \"ownerId\": {\n \"type\": \"integer\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"body\": {\n \"type\": \"string\"\n },\n \"template\": {\n \"type\": \"string\",\n \"enum\": ['BASIC_KANBAN', 'AUTOMATED_KANBAN_V2', 'AUTOMATED_REVIEWS_KANBAN', 'BUG_TRIAGE']\n },\n \"repositoryIds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"integer\"\n }\n },\n \"clientMutationId\": {\n \"type\": \"string\"\n }\n }\n\n }\n }\n}\n\noption_schema = {\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"input\": {\n \"type\": \"object\",\n \"properties\": {\n \"ownerId\": {\n \"type\": \"integer\"\n },\n \"name\": {\n \"type\": \"string\"\n }\n }\n\n }\n }\n}\n\n\nclass TestGenParams:\n\n @allure.title(\"正常生成参数\")\n def test_gen(self):\n data = GenParams(github_schema).gen(Mutation.create_project).result\n validate(\n instance=GenParams(github_schema).gen(Mutation.create_project).result,\n schema=input_schema,\n format_checker=draft7_format_checker\n )\n logging.info(data)\n\n @allure.title(\"生成只有必填的参数\")\n def test_gen_not_optional_params(self):\n data = GenParams(github_schema).gen(Mutation.create_project, optional=True).result\n validate(\n instance=GenParams(github_schema).gen(Mutation.create_project).result,\n schema=option_schema,\n format_checker=draft7_format_checker\n )\n logging.info(data)\n\n @allure.title(\"改变参数,无路径\")\n def test_change_param(self):\n data = GenParams(github_schema).gen(Mutation.create_project).change(\"name\", \"ces\")\n logging.info(data)\n assert data[\"input\"][\"name\"] == \"ces\"\n\n @allure.title(\"改变参数,复杂路径\")\n def test_change_params2(self):\n data = GenParams(github_schema).gen(Mutation.create_project).change(\"input.template\", \"AUTOMATED_KANBAN_V2\")\n logging.info(data)\n assert data[\"input\"][\"template\"] == \"AUTOMATED_KANBAN_V2\"\n\n @allure.title(\"改变参数,列表简单路径\")\n def test_change_params3(self):\n data = GenParams(github_schema).gen(Mutation.create_project).change(\"repositoryIds[0]\", 0)\n logging.info(data)\n assert data[\"input\"][\"repositoryIds\"][0] == 0\n\n @allure.title(\"改变参数,列表复杂路径\")\n def test_change_params4(self):\n data = GenParams(github_schema).gen(Mutation.create_project).change(\"input.repositoryIds[1]\", 0)\n logging.info(data)\n assert data[\"input\"][\"repositoryIds\"][1] == 0\n\n @allure.title(\"改变参数,列表匹配所有\")\n def test_change_params5(self):\n data = GenParams(github_schema).gen(Mutation.create_project).change(\"input.repositoryIds[*]\", 0)\n logging.info(data)\n assert data[\"input\"][\"repositoryIds\"] == [0, 0, 0]\n\n @allure.title(\"改变参数,三层以上复杂参数\")\n def test_change_params6(self):\n from Schema.PlatformSchema.platform_schema import platform_schema, Mutation\n data = GenParams(platform_schema).gen(Mutation.create_user).change(\"role[*].id\", 2)\n logging.info(data)\n assert data[\"input\"][\"role\"][0][\"id\"] == 2\n assert data[\"input\"][\"role\"][1][\"id\"] == 2\n assert data[\"input\"][\"role\"][2][\"id\"] == 2\n\n @allure.title(\"改变参数,替换整个列表\")\n def test_change_params7(self):\n from Schema.PlatformSchema.platform_schema import platform_schema, Mutation\n data = GenParams(platform_schema).gen(Mutation.create_user).change(\"role\", [{\"id\": 10}])\n logging.info(data)\n assert data[\"input\"][\"role\"][0][\"id\"] == 10\n\n @allure.title(\"改变参数,替换列表为列表\")\n def test_change_params8(self):\n from Schema.PlatformSchema.platform_schema import platform_schema, Mutation\n data = GenParams(platform_schema).gen(Mutation.create_user).change(\"role[*].id\", [2, 3, 4])\n logging.info(data)\n assert data[\"input\"][\"role\"][0][\"id\"] == 2\n assert data[\"input\"][\"role\"][1][\"id\"] == 3\n assert data[\"input\"][\"role\"][2][\"id\"] == 4\n\n @allure.title(\"改变参数,替换列表为列表2\")\n def test_change_params8(self):\n from Schema.PlatformSchema.platform_schema import platform_schema, Mutation\n data = GenParams(platform_schema).gen(Mutation.create_user).change(\"role[*]\", [2, 3, 4])\n logging.info(data)\n assert data[\"input\"][\"role\"][0] == 2\n assert data[\"input\"][\"role\"][1] == 3\n assert data[\"input\"][\"role\"][2] == 4\n\n @allure.title(\"改变参数\")\n def test_change_params9(self):\n from Schema.PlatformSchema.platform_schema import platform_schema, Mutation\n data = GenParams(platform_schema).gen(Mutation.set_erp_order_check_config).change(\"editable\", True)\n logging.info(data)\n assert data[\"input\"][\"editable\"] == True\n\n def test(self):\n from Schema.PlatformSchema.platform_schema import platform_schema, Mutation,ErpProductionTaskInput\n data = GenParams(platform_schema).gen_part(ErpProductionTaskInput)\n logging.info(data)\n","sub_path":"Test/test_gen_params.py","file_name":"test_gen_params.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"310547811","text":"import unittest\n\ndef largest_subarray_length_k(arr, k):\n if len(arr) <= k:\n return arr\n\n for i in range(0, k):\n if compareArrays(arr, i, k):\n return arr[compareArrays(arr, i, k):compareArrays(arr, 0, k)+k]\n\n\ndef compareArrays(arr, start, k):\n maxStartingPoint = [float('-inf'), None]\n for i in range(start, len(arr)-k+1+start):\n if arr[i] > maxStartingPoint[0]:\n maxStartingPoint = [arr[i], i]\n elif arr[i] == maxStartingPoint[0]:\n return None\n return i\n\nassert largest_subarray_length_k([1,2,3,4], 4) == [1,2,3,4], \"Should be [1,2,3,4]\"\n\n\n\n","sub_path":"largest-subarray-length-k.py","file_name":"largest-subarray-length-k.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"231003291","text":"# Perceber que, foi adicionado um asterisco\n# precedendo o parametro lista_ou_tupla\n\ndef somatorio_asterisco_dois(*lista_ou_tupla):\n # Perceber que, foi criado uma variavel auxiliar logo\n # abaixo para que, NAO coincida com o nome da funcao\n somatorio_aux = 0\n for elemento in lista_ou_tupla:\n somatorio_aux = somatorio_aux + elemento\n return somatorio_aux\n# Quando o asterisco e inserido antes do parametro lista__ou_tupla,\n# NAO e necessario inserir a lista ou tupla dentro de\n# colchetes ou parentesis:\nprint(somatorio_asterisco_dois(1, 2, 3, 4, 5))\n# Faça o teste removendo o asterisco do paremtro da funcao\n","sub_path":"06_funcoes/10_somatorio_asterisk_dois.py","file_name":"10_somatorio_asterisk_dois.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"456228873","text":"import os\nimport base64\nimport uuid\n\nsettings = {\n \"static_path\" : os.path.join(os.path.dirname(__file__), \"static\"),\n \"template_path\" : os.path.join(os.path.dirname(__file__), \"templates\"),\n \"cookie_secret\" : base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes),\n \"login_url\" : \"/\",\n \"debug\" : \"True\"\n}","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"30501274","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndata = pd.read_csv('mycsv.csv',header = None)\r\ndata = np.array(data)\r\nX = data[:,:-1]\r\ny = data[:,-1]\r\nclf = SVC()\r\n\r\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2)\r\n\r\nclf.fit(X_train,y_train)\r\n\r\ny_pred = clf.predict(X_test)\r\n\r\npred = (y_pred==y_test)\r\n\r\ntot = np.sum(np.array(pred),dtype = int)\r\n\r\n\r\n\r\nacc = 100*tot/(pred.shape[0])\r\n\r\nprint(tot,acc)\r\n","sub_path":"Machine Learning/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"564246014","text":"import sqlite3\n\n\n\ndef delCadVal(name):\n \n #connecting with database -- these lines shouldn't edited\n connection = sqlite3.connect('quality.db')\n con = connection.cursor()\n\n con.execute(\"\"\"Delete from calendlyLinks where name='\"\"\" + str(name) +\"'\")\n \n connection.commit()\n connection.close()\n \n return","sub_path":"databaseFunctions/deleteData.py","file_name":"deleteData.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"354060629","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 23 22:47:47 2020\r\n\r\n@author: Leo\r\n\"\"\"\r\n\r\n# test\r\nimport time\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom keras.models import load_model\r\nfrom keras.models import model_from_json\r\nfrom keras.preprocessing import image\r\n\r\n\r\ndef array_img_reshape(array, target_shape):\r\n import PIL\r\n # PIL.Image.BILINEAR\r\n array = image.img_to_array(image.array_to_img(array).resize(target_shape, resample=PIL.Image.BILINEAR))\r\n return array\r\n\r\ndef preprocess_img(img_id,target_shape):\r\n '''\r\n 加载图片,切分,归一化\r\n 输出:子图集,最后一张子图的高度\r\n '''\r\n img = image.load_img(img_id)\r\n img = image.img_to_array(img)[...,:1]\r\n h, _, _ = np.shape(img)\r\n n = int(np.ceil(h/target_shape[0]))\r\n imgs = np.zeros((n, *target_shape, 1))\r\n for i in range(n):\r\n if i != n-1:\r\n imgs[i,...] = img[target_shape[0]*i:target_shape[0]*(i+1),...]\r\n else:\r\n imgs[i,...] = array_img_reshape(img[target_shape[0]*i:], target_shape)\r\n imgs = imgs/255.0\r\n return imgs, h-(n-1)*target_shape[0]\r\n\r\ndef plot_result(sort_list_i, result, delta_h, target_size):\r\n img1 = image.load_img(sort_list_i[1]) # src\r\n img2 = image.load_img(sort_list_i[2]) # label\r\n imgs1 = np.zeros_like(img2)[...,:1] # output1\r\n imgs2 = np.zeros_like(img2)[...,:1] # output2\r\n for k in range(np.shape(result[0])[0]):\r\n fig_k = result[0][k,...,:1]\r\n if k == np.shape(result[0])[0]-1:\r\n imgs1[target_size[0]*k:,...] = array_img_reshape(fig_k, (target_size[0], delta_h))\r\n else:\r\n imgs1[target_size[0]*k:target_size[0]*(k+1),...] = array_img_reshape(fig_k, target_size)\r\n for j in range(np.shape(result[0])[0]):\r\n fig_j = result[0][j,...,1:]\r\n if j == np.shape(result[0])[0]-1:\r\n imgs2[target_size[0]*j:,...] = array_img_reshape(fig_j, (target_size[0], delta_h))\r\n else:\r\n imgs2[target_size[0]*j:target_size[0]*(j+1),...] = array_img_reshape(fig_j, target_size)\r\n imgs2 = np.concatenate((imgs1,imgs2),axis=2)\r\n imgs2 = np.reshape(imgs2,(1,-1,2))\r\n imgs2 = np.argmax(imgs2,axis=2).astype(np.int8)\r\n imgs2 = np.reshape(imgs2,np.shape(imgs1))\r\n\r\n plt.figure(figsize=(10,10))\r\n plt.subplot(141)\r\n plt.imshow(img1)\r\n plt.title('src')\r\n plt.axis('off')\r\n plt.subplot(142)\r\n plt.imshow(img2)\r\n plt.title('label')\r\n plt.axis('off')\r\n plt.subplot(143)\r\n plt.imshow(255-imgs1[...,0],cmap='gray')\r\n plt.title('output')\r\n plt.axis('off')\r\n plt.subplot(144)\r\n plt.imshow(imgs2[...,0],cmap='gray')\r\n plt.title('result')\r\n plt.axis('off')\r\n #plt.show()\r\n return None\r\n\r\ndef load_model_from_json(model_path, model_name):\r\n with open(model_path+model_name+'.json', 'r') as file:\r\n model_json = file.read()\r\n model = model_from_json(model_json)\r\n model.load_weights(model_path+model_name+'_weights.h5')\r\n return model\r\n\r\nif __name__ == '__main__':\r\n # 加载测试数据\r\n import data_manager\r\n #test_set_path = './KolektorSDD/test_set'\r\n test_set_path = './KolektorSDD/all'\r\n sort_list = data_manager.data_manager(test_set_path)\r\n # 模型的输入形状\r\n target_size = (500, 500)\r\n output_size = (500, 500)\r\n n_label = 2\r\n # 加载模型 / 权重\r\n model_path = './model/'\r\n model_name = 'best_model_up_500'\r\n\r\n try:\r\n '''\r\n 两者选其一\r\n 1. 直接加载模型\r\n 2. 加载json文件和weights权重\r\n '''\r\n #model = load_model(model_path+model_name+'.h5') # 1.\r\n model = load_model_from_json(model_path, model_name) # 2.\r\n print('Model weights loaded!')\r\n except:\r\n raise FileNotFoundError('Model not found!')\r\n \r\n model.summary()\r\n TP, FP, FN, TN = 0, 0, 0, 0\r\n for i in range(len(sort_list)):\r\n print('开始处理第',str(i+1),'张图片...')\r\n t1 = time.time()\r\n img_set, delta_h = preprocess_img(sort_list[i][1],target_size)\r\n result = model.predict(img_set, verbose=0)\r\n # 判断所有子图中是否包含class为 1 的输出\r\n class_i = 0\r\n for j in range(np.shape(result[0])[0]):\r\n class_i = np.max((class_i, int(list(np.rint(result[1][j])).index(1)), 0))\r\n t2 = time.time()\r\n if class_i != sort_list[i][0]:\r\n print('第{}例分类错误!耗时:{:.4f}s'.format(i+1, t2-t1))\r\n # 画出分类错误的实例\r\n plot_result(sort_list[i], result, delta_h, target_size)\r\n else:\r\n print('第{}例分类正确!耗时:{:.4f}s'.format(i+1, t2-t1))\r\n # 画出分类正确的正例\r\n if class_i == 1:\r\n plot_result(sort_list[i], result, delta_h, target_size)\r\n # 统计 TP, FP, FN, TN\r\n if class_i == 1: # P\r\n if sort_list[i][0] == 1: # T\r\n TP += 1\r\n elif sort_list[i][0] == 0: # F\r\n FP += 1\r\n elif class_i == 0: # N\r\n if sort_list[i][0] == 1: # F\r\n FN += 1\r\n elif sort_list[i][0] == 0: # T\r\n TN += 1\r\n print('TP:{} FP:{} FN:{} TN:{}'.format(TP, FP, FN, TN))\r\n print('准确率:%.3f%%'%((TP+TN)/(TP+TN+FP+FN)*100))\r\n print('查准率:%.3f%%'%(TP/(TP+FP)*100))\r\n print('查全率:%.3f%%'%(TP/(TP+FN)*100))\r\n ","sub_path":"test_model_up.py","file_name":"test_model_up.py","file_ext":"py","file_size_in_byte":5491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"197571622","text":"import os\nimport cv2\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Flatten, Dense, MaxPooling2D, Dropout\n\nimgData = []\nlabels = []\n\nuniqueLabels = []\nlabelCnt = 0\n\n# flow from directories\nsubs = os.listdir('data')\nNUM_GESTURES = len(subs)\n\nfor subdir in subs:\n fullpath = 'data/' + subdir\n if os.path.isdir(fullpath):\n uniqueLabels.append(subdir)\n labelCnt += 1\n for file in os.listdir(fullpath):\n img = cv2.imread('{}/{}'.format(fullpath, file))\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = cv2.resize(img, (200, 200)) # (a, b)\n imgData.append(img)\n labels.append(labelCnt)\n\n\nimgData = np.array(imgData, dtype='uint8')\nimgData = imgData.reshape(len(labels), 200, 200, 1) # (b, a)\nlabels = np.array(labels)\n\nprint('loaded {} images with {} labels'.format(len(imgData), len(labels)))\nprint(uniqueLabels)\n\n\npercent_for_testing = 0.2\n\nx_train, x_test, y_train, y_test = train_test_split(imgData, labels, test_size=percent_for_testing)\n\n'''Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 1)), # (b, a)\n MaxPooling2D((2, 2)),\n Conv2D(64, (3, 3), activation='relu'),\n MaxPooling2D(2, 2),\n Flatten(),\n Dense(128, activation='relu'),\n Dense(64, activation='tanh'),\n Dense(NUM_GESTURES, activation='softmax')'''\n\nmodel = Sequential([\n Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 1)), # (b, a)\n MaxPooling2D((2, 2)),\n Conv2D(64, (3, 3), activation='relu'),\n MaxPooling2D(2, 2),\n Flatten(),\n Dense(128, activation='tanh'),\n Dense(64, activation='relu'),\n Dense(NUM_GESTURES, activation='softmax')\n\n])\n\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n\nmodel.fit(x_train, y_train, epochs=5, batch_size=1, verbose=1, validation_data=(x_test, y_test))\n\nmodel.save('model.h5')\n","sub_path":"gestures.py","file_name":"gestures.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"200589619","text":"#!/usr/bin/python\n\nimport logging\nimport time\nfrom threading import Thread, active_count\nfrom web3 import Web3, HTTPProvider\nfrom .crypto import privkey_to_addr\nfrom ...utils import create_signed_transaction\nfrom .manager import SpamManager\nfrom .worker import SpamWorker\n\n\nclass Spammer(Thread):\n '''\n The Spammer class can be used to generate a blockchain congestion.\n '''\n\n def __init__(\n self,\n private_key: str,\n rpc_addr: str='http://127.0.0.1',\n rpc_port: int=8545,\n number_threads: int=1,\n nonce_offset: int=0,\n target_block: int=None,\n block_size: int=220,\n ):\n self.logger = logging.getLogger('spam')\n\n # Initialize web3\n self.web3 = Web3(HTTPProvider('{}:{}'.format(rpc_addr, rpc_port)))\n self.network_id = int(self.web3.version.network)\n\n self.private_key = private_key\n self.account_address = privkey_to_addr(private_key)\n\n initial_nonce = self.web3.eth.getTransactionCount(self.account_address, 'pending') + nonce_offset\n\n # Initialize spam manager.\n self.manager = SpamManager(\n web3=self.web3,\n initial_nonce=initial_nonce,\n target_block=target_block,\n block_size=block_size,\n )\n\n # Initialize and start spamming worker threads\n self.threads = []\n for i in range(number_threads):\n thread = SpamWorker(\n web3=self.web3,\n manager=self.manager,\n private_key=private_key,\n )\n self.threads.append(thread)\n thread.start()\n\n Thread.__init__(self)\n\n def run(self):\n for thread in self.threads:\n thread.do_send = True\n\n self.logger.info('Start network spamming')\n self.do_run = True\n\n while self.do_run:\n num_pending_transactions = int(self.web3.txpool.status.pending, 16)\n desired_pending_txs = self.manager.desired_pending_txs()\n num_queued_transactions = len(self.manager.tx_queue)\n desired_queued_txs = self.manager.desired_queued_txs()\n remaining_blocks = self.manager.remaining_blocks()\n\n if (self.manager.target_block is not None) & (not self.is_target_block_reached()):\n self.logger.debug(\n 'Current block = {} / Target block = {}'.format(self.web3.eth.blockNumber, self.manager.target_block))\n self.logger.info('Pending transactions = {} / Desired Pending = {} / Queued transactions = {} / Desired queued = {} / Threads = {} / Remaining blocks = {}'.format(\n num_pending_transactions, desired_pending_txs, num_queued_transactions, desired_queued_txs, active_count(), remaining_blocks))\n else:\n self.logger.debug('Current block = {}'.format(self.web3.eth.blockNumber))\n self.logger.info('Pending transactions = {} / Desired Pending = {} / Queued transactions = {} / Threads = {}'.format(\n num_pending_transactions, desired_pending_txs, num_queued_transactions, active_count()))\n\n time.sleep(3)\n \n def spam_tx(self, num_tx):\n '''\n Spam the network with the given number of transactions at once.\n ''' \n # Create trigger transaction.\n nonce = self.manager.reserve_nonce()\n trigger_tx = create_signed_transaction(\n web3=self.web3,\n private_key=self.private_key,\n to=self.account_address,\n data=str(time.time()),\n gas_price=21000000000, # proxy sends transactions with 20000000000\n nonce=nonce,\n )\n\n self.sending_continue()\n\n self.logger.info(\n 'Spamming the network with {} transactions...'\n .format(num_tx)\n )\n self.manager.wait_num_transactions_sent(num_tx)\n\n self.sending_pause()\n\n # Send trigger transaction\n self.web3.eth.sendRawTransaction(trigger_tx)\n\n def stop(self):\n '''\n Stop the execution of this and all spam worker threads.\n '''\n self.do_run = False\n for thread in self.threads:\n thread.stop()\n self.logger.info('Stopped network spamming')\n\n def sending_pause(self):\n '''\n Stop to broadcast transactions.\n '''\n for thread in self.threads:\n thread.do_send = False\n self.logger.info('Pause spamming.')\n\n def sending_continue(self):\n '''\n Start to broadcast transactions.\n '''\n for thread in self.threads:\n thread.do_send = True\n self.logger.info('Start spamming.')\n\n def is_target_block_reached(self) -> bool:\n '''\n Returns True if the target block number has already been created.\n '''\n if self.manager.target_block is None:\n return False\n return self.web3.eth.blockNumber >= self.manager.target_block\n\n def update_target_block(self, target_block):\n '''\n Update the block until which the network should be spammed.\n '''\n self.manager.target_block = target_block\n","sub_path":"microraiden/stale_state_attack/spamming/spammer.py","file_name":"spammer.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"264803316","text":"\"\"\"\n\"\"\"\n\nimport contextlib\nimport logging\nimport ctypes\nfrom ctypes import wintypes\n\nfrom .constant import constant\nfrom ..kernel32 import kernel32\nfrom ..handle_resource import HandleResource\n\nfrom .flag import flag\n\n\nlogger = logging.getLogger('debugger.process_snapshot')\n\n\nclass Snapshot(HandleResource):\n\n def __init__(self, process_id):\n self.id_ = process_id\n\n def _open(self):\n logger.debug('Open process snapshot [kernel32.CreateToolhelp32Snapshot]')\n # https://docs.microsoft.com/en-us/windows/desktop/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot\n CreateToolhelp32Snapshot = kernel32.CreateToolhelp32Snapshot\n CreateToolhelp32Snapshot.argtypes = [\n wintypes.DWORD, # dwFlags\n wintypes.DWORD, # th32ProcessID\n ]\n CreateToolhelp32Snapshot.restype = wintypes.HANDLE\n\n snapshot_handle = kernel32.CreateToolhelp32Snapshot(\n flag.thread.th32cs.TH32CS_SNAPTHREAD,\n self.id_,\n )\n\n if snapshot_handle == constant.handle.INVALID_HANDLE_VALUE:\n logger.error('CreateToolhelp32Snapshot')\n raise ctypes.WinError()\n return snapshot_handle\n\n @contextlib.contextmanager\n def get(self):\n handle = self._open()\n yield handle\n self._close(handle)\n","sub_path":"debug/process/snapshot.py","file_name":"snapshot.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"18205461","text":"\"\"\"wishl URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom rest_framework import routers\nfrom wishl.wishl_api import views\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', views.UserViewSet)\nrouter.register(r'wishes', views.WishViewSet)\nrouter.register(r'moneyboxes', views.MoneyboxViewSet)\nrouter.register(r'shops', views.ShopViewSet)\nrouter.register(r'images', views.ImageViewSet)\nrouter.register(r'tags', views.TagViewSet)\n\n\nurlpatterns = [\n path('', include(router.urls)),\n path('api-auth', include('rest_framework.urls', namespace='rest_framework')),\n]\n","sub_path":"wishl/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"418759388","text":"from __future__ import annotations\nimport logging\nfrom io import BytesIO\nfrom soulstruct.utilities.core import BinaryStruct, read_chars_from_bytes, PACKAGE_PATH\nfrom soulstruct.bnd import BND3\n\n_LOGGER = logging.getLogger(__name__)\n\n# TODO: Pickle bundled ParamDef files.\n\n\nclass ParamDefBND(BND3):\n\n def __init__(self, paramdef_bnd_source=None):\n\n if paramdef_bnd_source is None:\n _LOGGER.warning(\n \"No ParamDef source was given, so Soulstruct will assume that you want the Dark Souls Remastered \"\n \"version. (Use `paramdef_bnd_source='ptde'` to get the PTDE version.)\")\n paramdef_bnd_source = 'dsr'\n\n if paramdef_bnd_source.lower() in {'ptde', 'dsr'}:\n # Use bundled (recommended).\n dcx = '.dcx' if paramdef_bnd_source.lower() == 'dsr' else ''\n paramdef_bnd_source = PACKAGE_PATH('params/resources/paramdef.paramdefbnd' + dcx)\n if not paramdef_bnd_source.is_file():\n raise FileNotFoundError(f\"Could not find bundled ParamDef files in {paramdef_bnd_source}.\\n\"\n \"Reinstall Soulstruct or copy the ParamDef files in yourself.\")\n\n super().__init__(paramdef_bnd_source)\n self.paramdefs = {}\n\n # Simple check for remastered.\n if 'INTERROOT_x64' in self._entries[0].path:\n self.remastered = True\n elif 'INTERROOT_win32' in self._entries[0].path:\n self.remastered = False\n else:\n raise ValueError(\"Malformed BND path: could not detect DS version (PTD/DSR).\")\n\n for param_name, param_base_name in PARAMDEF_BASE_NAMES.items():\n if not self.remastered and param_name in {\n 'LEVELSYNC_PARAM_ST', 'COOL_TIME_PARAM_ST', 'WHITE_COOL_TIME_PARAM_ST'}:\n continue\n self.paramdefs[param_name] = ParamDef(self.entries_by_basename[param_base_name + '.paramdef'])\n\n def __getitem__(self, param_name) -> ParamDef:\n try:\n return self.paramdefs[param_name]\n except KeyError:\n\n raise KeyError(f\"There is no ParamDef with name '{param_name}'. The available names are:\\n\"\n f\" {list(PARAMDEF_BASE_NAMES.keys())}\")\n\n\nclass ParamDef(object):\n # No pack/write methods; these are essentially hard-coded structures, and therefore read-only.\n\n HEADER_STRUCT = BinaryStruct(\n ('size', 'i'),\n ('field_table_offset', 'H', 48),\n ('unk1', 'H'),\n ('field_count', 'H'),\n ('field_size', 'H', 176),\n ('param_name', '32j'),\n ('unk2', 'h'),\n ('relative_field_description_offset', 'h', 104),\n )\n\n FIELD_STRUCT = BinaryStruct(\n ('debug_name', '64j'),\n ('debug_type', '8j'),\n ('debug_format', '8j'), # %i, %u, %d, etc.\n ('default', 'f'),\n ('minimum', 'f'),\n ('maximum', 'f'),\n ('increment', 'f'),\n ('debug_display', 'i'),\n ('size', 'i'),\n ('description_offset', 'i'), # offset of null-terminated string (unlimited length)\n ('internal_type', '32j'), # could be an enum name (see params.enums)\n ('name', '32j'),\n ('id', 'i'), # TODO: what is this?\n )\n\n def __init__(self, paramdef_source, param_name=None):\n\n self.param_name = None\n self.fields = []\n self.fields_by_name = {}\n\n if isinstance(paramdef_source, list):\n if param_name is None:\n raise ValueError(\"`param_name` must be given to ParamDef if a list of fields is passed.\")\n self.param_name = param_name\n self.fields = paramdef_source\n\n elif isinstance(paramdef_source, bytes):\n self.unpack(BytesIO(paramdef_source))\n\n elif isinstance(paramdef_source, str):\n if paramdef_source in PARAMDEF_BASE_NAMES:\n paramdef_source = PARAMDEF_BASE_NAMES[paramdef_source] + '.paramdef'\n self.paramdef_path = paramdef_source\n with open(paramdef_source, 'rb') as file:\n self.unpack(file)\n\n elif hasattr(paramdef_source, 'data'):\n # Try reading .data attribute (e.g. BNDEntry).\n self.unpack(BytesIO(paramdef_source.data))\n\n def unpack(self, paramdef_buffer):\n \"\"\"Convert a paramdef file to a dictionary, indexed by ID.\"\"\"\n header = self.HEADER_STRUCT.unpack(paramdef_buffer)\n self.param_name = header.param_name\n fields = self.FIELD_STRUCT.unpack(paramdef_buffer, count=header.field_count)\n description_table_offset = paramdef_buffer.tell()\n packed_desc_data = paramdef_buffer.read()\n\n for field_index, field in enumerate(fields):\n if field.description_offset != 0:\n fdo = field.description_offset - description_table_offset\n field.description = read_chars_from_bytes(packed_desc_data, offset=fdo, encoding='shift_jis_2004')\n else:\n field.description = ''\n\n # print(f\"{self.param_name} {field_index} | {field.internal_type} | {field.debug_type} | {field.name} | \"\n # f\"{field.debug_name} | {field.description}\")\n\n is_bits = field.name.find(': ')\n if is_bits == -1:\n is_bits = field.name.find(':')\n if is_bits != -1:\n try:\n bit_size = int(field.name[is_bits + 1])\n except ValueError:\n bit_size = int(field.name[is_bits + 2])\n elif field.internal_type == 'dummy8':\n is_pad = field.name.find('[')\n if is_pad != -1:\n bit_size = int(field.name[is_pad + 1]) * 8\n else:\n bit_size = 8\n else:\n bit_size = field.size * 8\n\n field.index = field_index\n field.bit_size = bit_size\n\n self.fields.append(field)\n if self.fields_by_name is not None:\n if field.name in self.fields_by_name:\n _LOGGER.warning(\n f\"ParamDef field with name '{field.name}' was unpacked more than once, so you will not be able \"\n f\"to access fields by name. (Should NOT happen in any known files.)\")\n else:\n self.fields_by_name[field.name] = field\n\n def __getitem__(self, field_name):\n if self.fields_by_name is None:\n return AttributeError(\"Cannot access ParamDef fields by name due to one or more repeated field names.\\n\"\n \"This should NOT happen unless you've edited the ParamDef for some ungodly reason.\")\n return self.fields_by_name[field_name]\n\n def __repr__(self):\n return f\"ParamDef {self.param_name}:\\n \" + \"\\n \".join(\n [f\"{field.index} | {field.debug_name} | {field.description}\" for field in self.fields])\n\n\n# Maps internal header names of ParamTables to their BND entry path base names. DO NOT EDIT THESE!\nPARAMDEF_BASE_NAMES = {\n # DrawParam\n 'FOG_BANK': 'FogBank',\n 'LIGHT_BANK': 'LightBank',\n 'LIGHT_SCATTERING_BANK': 'LightScatteringBank',\n 'POINT_LIGHT_BANK': 'PointLightBank',\n 'LENS_FLARE_BANK': 'LensFlareBank',\n 'LENS_FLARE_EX_BANK': 'LensFlareExBank',\n 'DOF_BANK': 'DofBank',\n 'TONE_MAP_BANK': 'ToneMapBank',\n 'TONE_CORRECT_BANK': 'ToneCorrectBank',\n 'SHADOW_BANK': 'ShadowBank',\n 'LENS_FLAG_EX_BANK': 'LensFlareExBank',\n 'ENV_LIGHT_TEX_BANK': 'EnvLightTexBank',\n 'LOD_BANK': 'LodBank',\n\n # GameParam\n 'ATK_PARAM_ST': 'AtkParam',\n 'BEHAVIOR_PARAM_ST': 'BehaviorParam',\n 'BULLET_PARAM_ST': 'BulletParam',\n 'CHARACTER_INIT_PARAM': 'CharaInitParam',\n 'EQUIP_MTRL_SET_PARAM_ST': 'EquipMtrlSetParam',\n 'EQUIP_PARAM_ACCESSORY_ST': 'EquipParamAccessory',\n 'EQUIP_PARAM_GOODS_ST': 'EquipParamGoods',\n 'EQUIP_PARAM_PROTECTOR_ST': 'EquipParamProtector',\n 'EQUIP_PARAM_WEAPON_ST': 'EquipParamWeapon',\n 'FACE_PARAM_ST': 'FaceGenParam',\n 'GAME_AREA_PARAM_ST': 'GameAreaParam',\n 'HIT_MTRL_PARAM_ST': 'HitMtrlParam',\n 'ITEMLOT_PARAM_ST': 'ItemLotParam',\n 'KNOCKBACK_PARAM_ST': 'KnockBackParam',\n 'LOCK_CAM_PARAM_ST': 'LockCamParam',\n 'MAGIC_PARAM_ST': 'MagicParam',\n 'MENU_PARAM_COLOR_TABLE_ST': 'MenuParamColorTable',\n 'MOVE_PARAM_ST': 'MoveParam',\n 'NPC_PARAM_ST': 'NpcParam',\n 'NPC_THINK_PARAM_ST': 'NpcThinkParam',\n 'OBJ_ACT_PARAM_ST': 'ObjActParam',\n 'OBJECT_PARAM_ST': 'ObjectParam',\n 'REINFORCE_PARAM_PROTECTOR_ST': 'ReinforceParamProtector',\n 'REINFORCE_PARAM_WEAPON_ST': 'ReinforceParamWeapon',\n 'SHOP_LINEUP_PARAM': 'ShopLineupParam',\n 'SKELETON_PARAM_ST': 'SkeletonParam',\n 'SP_EFFECT_PARAM_ST': 'SpEffect',\n 'SP_EFFECT_VFX_PARAM_ST': 'SpEffectVfx',\n 'TALK_PARAM_ST': 'TalkParam',\n 'THROW_INFO_BANK': 'ThrowParam',\n\n # DSR-only multiplayer params.\n 'LEVELSYNC_PARAM_ST': 'LevelSyncParam',\n 'COOL_TIME_PARAM_ST': 'CoolTimeParam',\n 'WHITE_COOL_TIME_PARAM_ST': 'WhiteCoolTimeParam',\n\n # Junk resources that only contain Demon's Souls remnants.\n 'AI_STANDARD_INFO_BANK': 'AiStandardInfo',\n 'CACL_CORRECT_GRAPH_ST': 'CalcCorrectGraph', # (sic)\n 'ENEMY_STANDARD_INFO_BANK': 'EnemyStandardInfo',\n 'RAGDOLL_PARAM_ST': 'RagdollParam',\n 'QWC_CHANGE_PARAM_ST': 'QwcChangeParam',\n 'QWC_JUDGE_PARAM_ST': 'QwcJudgeParam',\n}\n","sub_path":"soulstruct/params/paramdef.py","file_name":"paramdef.py","file_ext":"py","file_size_in_byte":9404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"38279555","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"DTSKIM1\")\n\nprocess.load(\"Configuration.StandardSequences.Geometry_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\nprocess.load(\"Configuration.StandardSequences.Reconstruction_cff\")\nprocess.load(\"Configuration.StandardSequences.DigiToRaw_cff\")\nprocess.load(\"Configuration.StandardSequences.RawToDigi_Data_cff\")\nprocess.load('Configuration.StandardSequences.VtxSmearedEarly10TeVCollision_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\n\nprocess.GlobalTag.globaltag = 'GR09_E_V6::All'\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_10.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_5.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_9.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_11.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_7.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_12.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_14.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_6.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_3.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_8.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_4.root',\n'file:/data/c/cerminar/Skim/r123596_V01/Skim_V01_2.root',\n)\n)\n\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(-1)\n)\n\n\n#process.load('FWCore.MessageService.MessageLogger_cfi')\n#from FWCore.MessageLogger.MessageLogger_cfi import *\n# message logger\n# process.MessageLogger = cms.Service(\"MessageLogger\",\n# destinations = cms.untracked.vstring('cout'),\n# cout = cms.untracked.PSet(threshold = cms.untracked.string('INFO'))\n# )\n\n\n# message logger\nprocess.MessageLogger = cms.Service(\"MessageLogger\",\n debugModules = cms.untracked.vstring('*'),\n destinations = cms.untracked.vstring('cout'),\n categories = cms.untracked.vstring('FwkSummary'),\n cout = cms.untracked.PSet(threshold = cms.untracked.string('INFO'),\n DEBUG = cms.untracked.PSet(\n limit = cms.untracked.int32(0)),\n INFO = cms.untracked.PSet(\n limit = cms.untracked.int32(0)),\n FwkSummary = cms.untracked.PSet(\n limit = cms.untracked.int32(-1))\n )\n )\n\n\n\n\nprocess.load(\"ISpy/Analyzers/ISpy_Producer_cff\")\n\nprocess.add_(\n cms.Service(\"ISpyService\",\n outputFileName = cms.untracked.string('Skim_V01.ig'),\n online = cms.untracked.bool(False),\n debug = cms.untracked.bool(True)\n )\n)\n\n#-------------------------------------------------------------------------------------------\n# filters\n\nprocess.dtNDigiFilter = cms.EDFilter(\"DTNDigiFilter\",\n threshold = cms.untracked.int32(10),\n debug = cms.untracked.bool(True),\n dtDigiLabel = cms.InputTag(\"muonDTDigis\"),\n granularity = cms.untracked.string('perChamber'),\n cutType = cms.untracked.string('moreThan')\n)\n\n# filter on L1 trigger bits:\n# select only events triggered by muon L1A\nprocess.load(\"L1Trigger.Skimmer.l1Filter_cfi\")\nprocess.l1Filter.algorithms = cms.vstring('L1_SingleMuOpen', 'L1_SingleMu0', 'L1_SingleMu3', 'L1_SingleMu5', 'L1_SingleMu7', 'L1_SingleMu10', 'L1_SingleMu14', 'L1_SingleMu20', 'L1_DoubleMuOpen', 'L1_DoubleMu3')\n\n\n\nprocess.hltL1sL1BPTX = cms.EDFilter(\"HLTLevel1GTSeed\",\n L1UseL1TriggerObjectMaps = cms.bool(True),\n L1NrBxInEvent = cms.int32(3),\n L1TechTriggerSeeding = cms.bool(True),\n L1UseAliasesForSeeding = cms.bool(True),\n L1SeedsLogicalExpression = cms.string(\"0 OR 1 OR 2 OR 3\"),\n L1GtReadoutRecordTag = cms.InputTag(\"gtDigis\"),\n L1GtObjectMapTag = cms.InputTag(\"gtObjectMap\"),\n L1CollectionsTag = cms.InputTag(\"l1extraParticles\"),\n L1MuonCollectionTag = cms.InputTag(\"l1extraParticles\")\n )\n\nprocess.load('L1TriggerConfig.L1GtConfigProducers.L1GtTriggerMaskTechTrigConfig_cff')\n\n#process.load('HLTrigger/HLTfilters/hltLevel1GTSeed_cfi')\n#process.hltLevel1GTSeed.L1TechTriggerSeeding = cms.bool(True)\n#process.hltLevel1GTSeed.L1SeedsLogicalExpression = cms.string('32 OR 33 OR 34 OR 35 OR 36 OR 37 OR 38 OR 39 OR 40 OR 41 OR 42 OR 43')\n\nprocess.hltL1sL1BSC = cms.EDFilter(\"HLTLevel1GTSeed\",\n L1SeedsLogicalExpression = cms.string('32 OR 33 OR 34 OR 35 OR 36 OR 37 OR 38 OR 39 OR 40 OR 41 OR 42 OR 43'),\n L1MuonCollectionTag = cms.InputTag(\"l1extraParticles\"),\n L1UseL1TriggerObjectMaps = cms.bool(True),\n L1UseAliasesForSeeding = cms.bool(True),\n L1GtReadoutRecordTag = cms.InputTag(\"gtDigis\"),\n L1CollectionsTag = cms.InputTag(\"l1extraParticles\"),\n L1NrBxInEvent = cms.int32(3),\n L1GtObjectMapTag = cms.InputTag(\"gtObjectMap\"),\n L1TechTriggerSeeding = cms.bool(True)\n)\n\nprocess.dtHLTActivity = cms.EDFilter(\"HLTHighLevel\",\n eventSetupPathsKey = cms.string(''),\n andOr = cms.bool(True),\n HLTPaths = cms.vstring('HLT_Activity_DT'),\n throw = cms.bool(False),\n TriggerResultsTag = cms.InputTag(\"TriggerResults\",\"\",\"HLT\")\n)\n\n\nprocess.largeSiStripClusterEvents = cms.EDFilter(\"LargeSiStripClusterEvents\",\n absoluteThreshold = cms.untracked.int32(50),\n collectionName = cms.InputTag(\"siStripClusters\"),\n moduleThreshold = cms.untracked.int32(1000)\n)\n\n\n#-------------------------------------------------------------------------------------------\n\n\nprocess.load(\"DQM.DTOfflineAnalysis.muonAnalysis_cff\")\n\n# process.dtBPTX = cms.Path(process.hltL1sL1BPTX*\n# process.muonDTDigis*\n# process.dtNDigiFilter*\n# process.largeSiStripClusterEvents*\n# process.iSpy_sequence)\n\nprocess.dtBSC = cms.Path(process.hltL1sL1BSC*\n process.muonDTDigis*\n process.largeSiStripClusterEvents*\n process.dtNDigiFilter*\n process.muonAnalysis*\n process.iSpy_sequence)\n\n\nprocess.dtHLTAct = cms.Path(process.dtHLTActivity*\n process.muonDTDigis*\n process.largeSiStripClusterEvents*\n process.muonAnalysis*\n process.iSpy_sequence)\n\n\n# process.p3 = cms.Path(process.RawToDigi)\n# process.p4 = cms.Path(process.reconstruction)\n\n# process.schedule = cms.Schedule(process.p3,process.p4,process.iSpy)\n\nprocess.out1 = cms.OutputModule(\"PoolOutputModule\",\n fileName = cms.untracked.string('Skim_V01.root'),\n SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('dtBSC', \n 'dtHLTAct')\n )\n )\n \n\n\nprocess.output = cms.EndPath(process.out1)\n\n\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(True)\n )\n","sub_path":"MySkims/MyFilters/test/skim_DigiActivity_cfg.py","file_name":"skim_DigiActivity_cfg.py","file_ext":"py","file_size_in_byte":7993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"314065969","text":"from astropy.io import ascii\nimport numpy as np\nfrom astropy.table import *\nimport os\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.style.use('classic')\n\nspin_bullock_calcs = []\nfor file in glob.iglob('/Users/catherinefielder/Documents/Research_Halos/Particle_Tables/Halo*/*'):\n if file.endswith('.list_complete'):\n values = ascii.read(file, format = 'commented_header') #Get full path and access file\n spin_bullock_calc = values[1]['spin_bullock']\n spin_bullock_calcs = np.append(spin_bullock_calcs,spin_bullock_calc)\n\nhost_spin_bullock = [] \nfor file in glob.iglob('/Users/catherinefielder/Documents/Research_Halos/HaloDetail/Halo*/*'):\n if file.endswith('.list_host'):\n values2 = ascii.read(file, format = 'commented_header')\n spin_bullock = values2[1]['host_spin_bullock']\n host_spin_bullock = np.append(host_spin_bullock,spin_bullock)\n \n \nfig = plt.figure()\nplt.scatter(spin_bullock_calcs,host_spin_bullock)\nplt.xlabel('Calculated Bullock Spin')\nplt.ylabel('Rockstar Bullock Spin')\nplt.show()","sub_path":"compare_bullock_spin.py","file_name":"compare_bullock_spin.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"610600791","text":"#!/usr/bin/python\n# -*- coding=utf-8 -*-\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nimport xml.dom.minidom\nfrom common.api.remote_config_get import confget\nimport pymssql\nimport json\n\n\ndef recruit_cut_show(request):\n\n return render(request, \"dbatools/recruit_db_cut.html\")\n\n\ndef get_connection():\n conn = pymssql.connect(host='10.22.2.30', user='user_app_BeisenStatistics', password='A83C33978044558',\n database='BeisenStatistics')\n return conn\n\ndef standby_info():\n conn = get_connection()\n cur = conn.cursor()\n\n sql = \"select * from [dbo].[tbl_MachineDbName]\"\n cur.execute(sql)\n sbinfo = {}\n for item in cur.fetchall():\n if item[2] == '':\n standby = '无'\n else:\n standby = item[2]\n try:\n sbinfo[item[1]]\n pass\n except:\n sbinfo[item[1]] = {'standby':standby,'ip':item[0]}\n return sbinfo\n\n\ndef recruit_db_cut(request):\n standby = standby_info()\n confget('DataBaseDividRules', 'General', './DataBaseDividRules.xml')\n path = './DataBaseDividRules.xml'\n dom = xml.dom.minidom.parse(path)\n root = dom.documentElement\n result = []\n for i in root.getElementsByTagName('RuleGroups'):\n resultdic = {}\n for m in i.getElementsByTagName('RuleGroup'):\n if m.getAttribute('Name') == 'RecruitmentCVRules':\n for n in m.getElementsByTagName('DividRules'):\n for p in n.getElementsByTagName('DividRule'):\n if p.getElementsByTagName('IncludeTenantIds'):\n for q in p.getElementsByTagName('add'):\n databasename = 'BeisenRecruitmentCVVip'+ p.getAttribute('Base')[1:]\n resultdic = {\n 'databasename':databasename,\n 'standby_ip':standby[databasename]['standby'],\n 'ip': standby[databasename]['ip'],\n 'talentid':q.getAttribute('value')\n }\n result.append(resultdic)\n\n elif m.getAttribute('Name') == 'RecruitmentRules':\n for n in m.getElementsByTagName('DividRules'):\n for p in n.getElementsByTagName('DividRule'):\n if p.getElementsByTagName('IncludeTenantIds'):\n for q in p.getElementsByTagName('add'):\n databasename = 'BeisenRecruitmentVip' + p.getAttribute('Base')[1:]\n resultdic = {\n 'databasename': databasename,\n 'standby_ip': standby[databasename]['standby'],\n 'ip':standby[databasename]['ip'],\n 'talentid': q.getAttribute('value')\n }\n result.append(resultdic)\n\n return HttpResponse(json.dumps(result))\n\n\nif __name__ == \"__main__\":\n recruit_db_cut()","sub_path":"dbatools/recruit_db_cut.py","file_name":"recruit_db_cut.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"219114657","text":"from tkinter import *\n\nroot = Tk()\n\ncanvas = Canvas(root, width='300', height='300')\ncanvas.pack()\n\n# create a square drawing function that takes 2 parameters:\n# the x and y coordinates of the square's top left corner\n# and draws a 50x50 square from that point.\n# draw 3 squares with that function.\n\ndef square_drawer(x_coordinate, y_coordinate):\n x_coordinate_extended = x_coordinate + 50\n y_coordinate_extended = y_coordinate + 50\n complete_line = canvas.create_rectangle(x_coordinate, y_coordinate, x_coordinate_extended, y_coordinate_extended, fill=\"red\")\n \nsquare_drawer(47,140)\nsquare_drawer(175,53)\nsquare_drawer(150,120)\n\nroot.mainloop()\n\nroot.mainloop()","sub_path":"Week-03/day-03/position_square.py","file_name":"position_square.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"189109254","text":"import factory\ndef main():\n\n json_factory = factory.connect_to(\"data.json\")\n\n json_data=json_factory.parsed_data\n print(json_data)\n print('dosyadaki parametre sayısı {}'.format(len(json_data)))\n\n\n print(\"********************************\")\n\n for i in json_data[\"type_of_donuts\"]:\n print(i[\"id\"] + \" ::: \"+ i[\"type\"])\n\nif __name__=='__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"248464642","text":"\"\"\"\nCli tool to convert 10x bam to per cell fastas\n\"\"\"\nimport itertools\nimport os\nimport glob\nimport logging\nimport time\nfrom functools import partial\n\nimport screed\nfrom pathos import multiprocessing\n\nfrom bam2fasta import tenx_utils\nfrom bam2fasta.bam2fasta_args import create_parser, Bam2FastaArgumentParser\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef info(args):\n \"Report bam2fasta version + version of installed dependencies.\"\n parser = Bam2FastaArgumentParser()\n parser.add_argument(\n '-v', '--verbose', action='store_true',\n help='report versions of pathos, pysam, and screed')\n args = parser.parse_args(args)\n\n from bam2fasta import VERSION\n logger.info('bam2fasta version %s', VERSION)\n logger.info('- loaded from path: %s', os.path.dirname(__file__))\n logger.info('')\n\n if args.verbose:\n import pathos\n logger.info('pathos version %s', pathos.__version__)\n logger.info('- loaded from path: %s', os.path.dirname(pathos.__file__))\n logger.info('')\n import pysam\n logger.info('pysam version %s', pysam.__version__)\n logger.info('- loaded from path: %s', os.path.dirname(pysam.__file__))\n logger.info('')\n\n logger.info('screed version %s', screed.__version__)\n logger.info('- loaded from path: %s', os.path.dirname(screed.__file__))\n\n\ndef count_umis_percell(args):\n if type(args) is list:\n parser = create_parser()\n args = parser.parse_args(args)\n logger.info(args)\n tenx_utils.count_umis_per_cell(\n args.filename,\n args.write_barcode_meta_csv,\n args.cell_barcode_pattern,\n args.molecular_barcode_pattern,\n args.min_umi_per_barcode,\n args.barcodes_significant_umis_file)\n\n\ndef make_fastqs_percell(args):\n if type(args) is list:\n parser = create_parser()\n args = parser.parse_args(args)\n logger.info(args)\n\n save_path = os.path.abspath(args.save_fastas)\n # Save fasta sequences for aligned and unaligned sequences in\n # separate folders with the following name in save_fastas\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n else:\n logger.info(\n \"Path {} already exists, might be overwriting data\".format(\n save_path))\n logger.info(\"Saving fastas at path {}\".format(save_path))\n\n fastqs = tenx_utils.make_per_cell_fastqs(\n args.filename,\n save_path,\n args.channel_id,\n args.output_format,\n args.cell_barcode_pattern,\n args.barcodes_significant_umis_file)\n\n return fastqs\n\n\ndef percell(args):\n \"\"\"Cli tool to convert bam to per cell fasta files\"\"\"\n parser = create_parser()\n args = parser.parse_args(args)\n\n logger.info(args)\n\n save_fastas = os.path.abspath(args.save_fastas)\n if not os.path.exists(save_fastas):\n os.makedirs(save_fastas)\n else:\n logger.info(\n \"Path {} already exists, might be overwriting data\".format(\n save_fastas))\n\n # Initializing time\n startt = time.time()\n\n save_intermediate_files = os.path.abspath(args.save_intermediate_files)\n if not os.path.exists(save_intermediate_files):\n os.makedirs(save_intermediate_files)\n else:\n logger.info(\n \"Path {} already exists, might be overwriting data\".format(\n save_intermediate_files))\n\n # Setting barcodes file, some 10x files don't have a filtered\n # barcode file\n if args.barcodes_file is not None:\n barcodes = tenx_utils.read_barcodes_file(args.barcodes_file)\n else:\n barcodes = None\n\n # Shard bam file to smaller bam file\n logger.info('... reading bam file from %s', args.filename)\n n_jobs = args.processes\n input_format = os.path.basename(args.filename).split(\".\")[-1]\n if input_format == \"bam\":\n filenames = tenx_utils.shard_bam_file(\n args.filename,\n args.shard_size,\n save_intermediate_files)\n\n # Create a per-cell fasta generator of sequences\n # If the reads should be filtered by barcodes and umis\n # umis are saved in fasta file as record name and name of\n # the fasta file is the barcode\n func = partial(\n tenx_utils.bam_to_temp_fasta,\n barcodes,\n args.rename_10x_barcodes,\n args.delimiter,\n save_intermediate_files)\n\n length_sharded_bam_files = len(filenames)\n chunksize = tenx_utils.calculate_chunksize(\n length_sharded_bam_files,\n n_jobs)\n pool = multiprocessing.Pool(processes=n_jobs)\n logger.info(\n \"multiprocessing pool processes {} & chunksize {}\".format(\n n_jobs, chunksize))\n # All the fastas are stored in a string instead of a list\n # This saves memory per element of the list by 8 bits\n # If we have unique barcodes in the order of 10^6 before\n # filtering that would result in a huge list if each barcode\n # is saved as a separate element, hence the string\n all_fastas = \",\" .join(itertools.chain(*(\n pool.imap_unordered(\n lambda x: func(x.encode('utf-8')),\n filenames, chunksize=chunksize))))\n\n # clean up the memmap and sharded intermediary bam files\n [os.unlink(file) for file in filenames if os.path.exists(file)]\n del filenames\n logger.info(\"Deleted intermediary bam\")\n\n all_fastas_sorted = tenx_utils.get_fastas_per_unique_barcodes(\n all_fastas)\n unique_barcodes = len(all_fastas_sorted)\n logger.info(\"Found %d unique barcodes\", unique_barcodes)\n # Cleaning up to retrieve memory from unused large variables\n del all_fastas\n\n # Gather all barcodes per umis to one fasta\n func = partial(\n tenx_utils.barcode_umi_seq_to_fasta,\n save_fastas,\n args.delimiter,\n args.write_barcode_meta_csv,\n args.min_umi_per_barcode,\n save_intermediate_files)\n\n chunksize = tenx_utils.calculate_chunksize(unique_barcodes, n_jobs)\n\n logger.info(\n \"Pooled %d and chunksize %d mapped for %d lists\",\n n_jobs, chunksize, len(all_fastas_sorted))\n list(pool.imap_unordered(\n lambda fasta: func([fasta]),\n all_fastas_sorted, chunksize=chunksize))\n\n pool.close()\n pool.join()\n\n # Write barcode meta csv\n if args.write_barcode_meta_csv:\n tenx_utils.write_to_barcode_meta_csv(\n save_intermediate_files, args.write_barcode_meta_csv)\n\n # Gather all the fastas\n fastas = glob.glob(os.path.join(save_fastas, \"*_bam2fasta.fasta\"))\n else:\n # if the fastq.gz file is already given\n assert input_format == \"gz\", \\\n (\"please convert\" +\n \"bam files to fastq.gz using samtools\")\n # Check if the good barcodes with significant umis is already given\n barcodes_significant_umis_file = args.barcodes_significant_umis_file\n logger.info(\"barcodes_significant_umis_file {}\".format(\n barcodes_significant_umis_file))\n # Find the good_barcodes file from the aligned sequences and use it\n # for unaligned.fastq.gz\n basename_wo_format = os.path.basename(\n args.filename).replace(\".fastq.gz\", \"__\")\n args.barcodes_significant_umis_file = os.path.join(\n save_fastas,\n \"barcodes_with_significant_umis.tsv\")\n count_umis_percell(args)\n args.channel_id = basename_wo_format\n fastas = make_fastqs_percell(args)\n logger.info(\n \"time taken to write fastas is %.5f seconds\",\n time.time() - startt)\n\n return fastas\n\n\ndef convert(args):\n # keeping back compatibility\n # bam2fasta 1.0.1 conversion of bam2fsta was called convert\n return percell(args)\n","sub_path":"bam2fasta/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":7934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"122541330","text":"\"\"\"Internal API endpoint constant library.\n\n _______ __ _______ __ __ __\n| _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----.\n|. 1___| _| _ | | | | _ | 1___| _| _| | <| -__|\n|. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____|\n|: 1 | |: 1 |\n|::.. . | CROWDSTRIKE FALCON |::.. . | FalconPy\n`-------' `-------'\n\nOAuth2 API - Customer SDK\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to \n\"\"\"\n\n_custom_ioa_endpoints = [\n [\n \"get-patterns\",\n \"GET\",\n \"/ioarules/entities/pattern-severities/v1\",\n \"Get pattern severities by ID.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"collectionFormat\": \"multi\",\n \"description\": \"The IDs of the entities\",\n \"name\": \"ids\",\n \"in\": \"query\",\n \"required\": True\n }\n ]\n ],\n [\n \"get-platformsMixin0\",\n \"GET\",\n \"/ioarules/entities/platforms/v1\",\n \"Get platforms by ID.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"collectionFormat\": \"multi\",\n \"description\": \"The IDs of the entities\",\n \"name\": \"ids\",\n \"in\": \"query\",\n \"required\": True\n }\n ]\n ],\n [\n \"get-rule-groupsMixin0\",\n \"GET\",\n \"/ioarules/entities/rule-groups/v1\",\n \"Get rule groups by ID.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"collectionFormat\": \"multi\",\n \"description\": \"The IDs of the entities\",\n \"name\": \"ids\",\n \"in\": \"query\",\n \"required\": True\n }\n ]\n ],\n [\n \"create-rule-groupMixin0\",\n \"POST\",\n \"/ioarules/entities/rule-groups/v1\",\n \"Create a rule group for a platform with a name and an optional description. Returns the rule group.\",\n \"custom_ioa\",\n [\n {\n \"name\": \"body\",\n \"in\": \"body\",\n \"required\": True\n }\n ]\n ],\n [\n \"update-rule-groupMixin0\",\n \"PATCH\",\n \"/ioarules/entities/rule-groups/v1\",\n \"Update a rule group. The following properties can be modified: name, description, enabled.\",\n \"custom_ioa\",\n [\n {\n \"name\": \"body\",\n \"in\": \"body\",\n \"required\": True\n }\n ]\n ],\n [\n \"delete-rule-groupsMixin0\",\n \"DELETE\",\n \"/ioarules/entities/rule-groups/v1\",\n \"Delete rule groups by ID.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"string\",\n \"description\": \"Explains why the entity is being deleted\",\n \"name\": \"comment\",\n \"in\": \"query\"\n },\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"collectionFormat\": \"multi\",\n \"description\": \"The IDs of the entities\",\n \"name\": \"ids\",\n \"in\": \"query\",\n \"required\": True\n }\n ]\n ],\n [\n \"get-rule-types\",\n \"GET\",\n \"/ioarules/entities/rule-types/v1\",\n \"Get rule types by ID.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"collectionFormat\": \"multi\",\n \"description\": \"The IDs of the entities\",\n \"name\": \"ids\",\n \"in\": \"query\",\n \"required\": True\n }\n ]\n ],\n [\n \"get-rules-get\",\n \"POST\",\n \"/ioarules/entities/rules/GET/v1\",\n \"Get rules by ID and optionally version in the following format: `ID[:version]`.\",\n \"custom_ioa\",\n [\n {\n \"description\": \"The \\\"ids\\\" field contains a list of the rules to retrieve.\",\n \"name\": \"body\",\n \"in\": \"body\",\n \"required\": True\n }\n ]\n ],\n [\n \"get-rulesMixin0\",\n \"GET\",\n \"/ioarules/entities/rules/v1\",\n \"Get rules by ID and optionally version in the following format: `ID[:version]`. \"\n \"The max number of IDs is constrained by URL size.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"collectionFormat\": \"multi\",\n \"description\": \"The IDs of the entities\",\n \"name\": \"ids\",\n \"in\": \"query\",\n \"required\": True\n }\n ]\n ],\n [\n \"create-rule\",\n \"POST\",\n \"/ioarules/entities/rules/v1\",\n \"Create a rule within a rule group. Returns the rule.\",\n \"custom_ioa\",\n [\n {\n \"name\": \"body\",\n \"in\": \"body\",\n \"required\": True\n }\n ]\n ],\n [\n \"update-rules\",\n \"PATCH\",\n \"/ioarules/entities/rules/v1\",\n \"Update rules within a rule group. Return the updated rules.\",\n \"custom_ioa\",\n [\n {\n \"name\": \"body\",\n \"in\": \"body\",\n \"required\": True\n }\n ]\n ],\n [\n \"delete-rules\",\n \"DELETE\",\n \"/ioarules/entities/rules/v1\",\n \"Delete rules from a rule group by ID.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"string\",\n \"description\": \"The parent rule group\",\n \"name\": \"rule_group_id\",\n \"in\": \"query\",\n \"required\": True\n },\n {\n \"type\": \"string\",\n \"description\": \"Explains why the entity is being deleted\",\n \"name\": \"comment\",\n \"in\": \"query\"\n },\n {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"collectionFormat\": \"multi\",\n \"description\": \"The IDs of the entities\",\n \"name\": \"ids\",\n \"in\": \"query\",\n \"required\": True\n }\n ]\n ],\n [\n \"query-patterns\",\n \"GET\",\n \"/ioarules/queries/pattern-severities/v1\",\n \"Get all pattern severity IDs.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"string\",\n \"description\": \"Starting index of overall result set from which to return IDs\",\n \"name\": \"offset\",\n \"in\": \"query\"\n },\n {\n \"type\": \"integer\",\n \"description\": \"Number of IDs to return\",\n \"name\": \"limit\",\n \"in\": \"query\"\n }\n ]\n ],\n [\n \"query-platformsMixin0\",\n \"GET\",\n \"/ioarules/queries/platforms/v1\",\n \"Get all platform IDs.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"string\",\n \"description\": \"Starting index of overall result set from which to return IDs\",\n \"name\": \"offset\",\n \"in\": \"query\"\n },\n {\n \"type\": \"integer\",\n \"description\": \"Number of IDs to return\",\n \"name\": \"limit\",\n \"in\": \"query\"\n }\n ]\n ],\n [\n \"query-rule-groups-full\",\n \"GET\",\n \"/ioarules/queries/rule-groups-full/v1\",\n \"Find all rule groups matching the query with optional filter.\",\n \"custom_ioa\",\n [\n {\n \"enum\": [\n \"created_by\",\n \"created_on\",\n \"enabled\",\n \"modified_by\",\n \"modified_on\",\n \"name\"\n ],\n \"type\": \"string\",\n \"description\": \"Possible order by fields: {created_by, created_on, modified_by, \"\n \"modified_on, enabled, name}\",\n \"name\": \"sort\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"FQL query specifying the filter parameters. Filter term criteria: \"\n \"[enabled platform name description rules.action_label rules.name rules.description \"\n \"rules.pattern_severity rules.ruletype_name rules.enabled]. Filter range criteria: \"\n \"created_on, modified_on; use any common date format, such as '2010-05-15T14:55:21.892315096Z'.\",\n \"name\": \"filter\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"Match query criteria, which includes all the filter string fields\",\n \"name\": \"q\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"Starting index of overall result set from which to return IDs\",\n \"name\": \"offset\",\n \"in\": \"query\"\n },\n {\n \"type\": \"integer\",\n \"description\": \"Number of IDs to return\",\n \"name\": \"limit\",\n \"in\": \"query\"\n }\n ]\n ],\n [\n \"query-rule-groupsMixin0\",\n \"GET\",\n \"/ioarules/queries/rule-groups/v1\",\n \"Finds all rule group IDs matching the query with optional filter.\",\n \"custom_ioa\",\n [\n {\n \"enum\": [\n \"created_by\",\n \"created_on\",\n \"enabled\",\n \"modified_by\",\n \"modified_on\",\n \"name\"\n ],\n \"type\": \"string\",\n \"description\": \"Possible order by fields: {created_by, created_on, modified_by, \"\n \"modified_on, enabled, name}\",\n \"name\": \"sort\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"FQL query specifying the filter parameters. Filter term criteria: \"\n \"[enabled platform name description rules.action_label rules.name rules.description \"\n \"rules.pattern_severity rules.ruletype_name rules.enabled]. Filter range criteria: \"\n \"created_on, modified_on; use any common date format, such as '2010-05-15T14:55:21.892315096Z'.\",\n \"name\": \"filter\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"Match query criteria, which includes all the filter string fields\",\n \"name\": \"q\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"Starting index of overall result set from which to return IDs\",\n \"name\": \"offset\",\n \"in\": \"query\"\n },\n {\n \"type\": \"integer\",\n \"description\": \"Number of IDs to return\",\n \"name\": \"limit\",\n \"in\": \"query\"\n }\n ]\n ],\n [\n \"query-rule-types\",\n \"GET\",\n \"/ioarules/queries/rule-types/v1\",\n \"Get all rule type IDs.\",\n \"custom_ioa\",\n [\n {\n \"type\": \"string\",\n \"description\": \"Starting index of overall result set from which to return IDs\",\n \"name\": \"offset\",\n \"in\": \"query\"\n },\n {\n \"type\": \"integer\",\n \"description\": \"Number of IDs to return\",\n \"name\": \"limit\",\n \"in\": \"query\"\n }\n ]\n ],\n [\n \"query-rulesMixin0\",\n \"GET\",\n \"/ioarules/queries/rules/v1\",\n \"Finds all rule IDs matching the query with optional filter.\",\n \"custom_ioa\",\n [\n {\n \"enum\": [\n \"rules.created_by\",\n \"rules.created_on\",\n \"rules.current_version.action_label\",\n \"rules.current_version.description\",\n \"rules.current_version.modified_by\",\n \"rules.current_version.modified_on\",\n \"rules.current_version.name\",\n \"rules.current_version.pattern_severity\",\n \"rules.enabled\",\n \"rules.ruletype_name\"\n ],\n \"type\": \"string\",\n \"description\": \"Possible order by fields: {rules.ruletype_name, rules.enabled, rules.created_by, \"\n \"rules.current_version.name, rules.current_version.modified_by, rules.created_on, \"\n \"rules.current_version.description, rules.current_version.pattern_severity, \"\n \"rules.current_version.action_label, rules.current_version.modified_on}\",\n \"name\": \"sort\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"FQL query specifying the filter parameters. Filter term criteria: \"\n \"[enabled platform name description rules.action_label rules.name rules.description \"\n \"rules.pattern_severity rules.ruletype_name rules.enabled]. Filter range criteria: \"\n \"created_on, modified_on; use any common date format, such as '2010-05-15T14:55:21.892315096Z'.\",\n \"name\": \"filter\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"Match query criteria, which includes all the filter string fields\",\n \"name\": \"q\",\n \"in\": \"query\"\n },\n {\n \"type\": \"string\",\n \"description\": \"Starting index of overall result set from which to return IDs\",\n \"name\": \"offset\",\n \"in\": \"query\"\n },\n {\n \"type\": \"integer\",\n \"description\": \"Number of IDs to return\",\n \"name\": \"limit\",\n \"in\": \"query\"\n }\n ]\n ]\n]\n","sub_path":"src/falconpy/_endpoint/deprecated/_custom_ioa.py","file_name":"_custom_ioa.py","file_ext":"py","file_size_in_byte":13207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"229846252","text":"\n\nimport pickle as pkl\nimport io\nimport numpy as np\n#import matplotlib as mpl\n#mpl.use('Agg')\n#import matplotlib.pyplot as plt\n#import matplotlib.image as mpimg\nfrom skimage import io as ios\nfrom ImageDataset import ImageDataset\nfrom Cifar10Dataset import Cifar10Dataset, countLabelInstances, splitSet\nfrom TinyCifar10Dataset import TinyCifar10Dataset\n\ndir = '../Data/cifar-10-batches-py'\n\n\ntrain = Cifar10Dataset(dir, 'train')\nval = Cifar10Dataset(dir, 'val')\ntest = Cifar10Dataset(dir, 'test')\n\nclass_num = 1\nprint(\"[train] \"+str(train.nclasses())+\" classes, name of class #\"+str(class_num)+\": \"+ train.classname(class_num))\nprint(\"[val] \"+str(val.nclasses())+\" classes, name of class #\"+str(class_num)+\": \"+ val.classname(class_num))\nprint(\"[test] \"+str(test.nclasses())+\" classes, name of class #\"+str(class_num)+\": \"+ test.classname(class_num))\n\nprint(\"[train] \"+str(train.size())+\" samples\")\ndata, labels, label_names = train.getDataset()\nlabelTotalCounts = countLabelInstances(labels)\nfor i in range(0, train.nclasses()):\n\tprint(\"Class #\"+str(i)+\": \"+str(labelTotalCounts[i])+\" samples\")\n\nprint(\"[val] \"+str(val.size())+\" samples\")\ndata, labels, label_names = val.getDataset()\nlabelTotalCounts = countLabelInstances(labels)\nfor i in range(0, val.nclasses()):\n\tprint(\"Class #\"+str(i)+\": \"+str(labelTotalCounts[i])+\" samples\")\n\nprint(\"[test] \"+str(test.size())+\" samples\")\ndata, labels, label_names = test.getDataset()\nlabelTotalCounts = countLabelInstances(labels)\nfor i in range(0, test.nclasses()):\n\tprint(\"Class #\"+str(i)+\": \"+str(labelTotalCounts[i])+\" samples\")\n\nsample_num = 499\ntrain_sample_img, train_sample_label = train.sample(499)\nim = train_sample_img\nios.imsave(\"00_normal_horse.png\", im)\n\neval_sample_img, eval_sample_label = val.sample(499)\nim = eval_sample_img\nios.imsave(\"00_normal_deer.png\", im)\n\ntest_sample_img, test_sample_label = test.sample(499)\nim = test_sample_img\nios.imsave(\"00_normal_airplane.png\", im)\n\n\nprint(\"[train] Sample #\"+str(sample_num)+\": \"+train.classname(train_sample_label))\nprint(\"[val] Sample #\"+str(sample_num)+\": \"+val.classname(eval_sample_label))\nprint(\"[test] Sample #\"+str(sample_num)+\": \"+test.classname(test_sample_label))\n\n\n","sub_path":"Assignment1/test_cifar10_dataset.py","file_name":"test_cifar10_dataset.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"162171133","text":"from setuptools import setup\nfrom Redy.Tools.Version import Version\nfrom Redy.Tools.PathLib import Path\n# with open('./README.rst', encoding='utf-8') as f:\n# readme = f.read()\nreadme = ''\n\nversion_filename = 'next_version'\nwith open(version_filename) as f:\n version = Version(f.read().strip())\n\nsetup(name='rbnf',\n version=str(version),\n keywords='parser-generator, context-sensitive, ebnf',\n description=\"context sensitive grammar parser generator\",\n long_description=readme,\n license='MIT',\n url='https://github.com/thautwarm/Ruiko',\n author='thautwarm',\n author_email='twshere@outlook.com',\n packages=['rbnf', 'rbnf.std', 'rbnf.AutoLexer', 'rbnf.zero'],\n package_data={\n \t'rbnf':[\n 'rbnf_libs/std/*.rbnf',\n 'rbnf_libs/*.rbnf'\n \t\t]},\n install_requires=[\n 'Redy'\n ],\n platforms='any',\n classifiers=[\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: Implementation :: CPython'],\n zip_safe=False)\n\nversion.increment(version_number_idx=2, increment=1)\nif version[2] is 42:\n version.increment(version_number_idx=1, increment=1)\nif version[1] is 42:\n version.increment(version_number_idx=0, increment=1)\n\nwith open(version_filename, 'w') as f:\n f.write(str(version))\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"47238421","text":"#!/home/kalyb/Desktop/py/myscripts/virtualenvs/freefoodfinder/bin/python3.7\n\"\"\"Find events on craigslist that offer free food.\n\"\"\"\n\nfrom craigslist import CraigslistEvents\n\ndef main():\n my_results = []\n cl_e = CraigslistEvents(site='kansascity', filters={'free': True, 'food': True})\n\n for result in cl_e.get_results(sort_by='newest', limit=5):\n my_results.append(result)\n\n for each_item in my_results:\n print(each_item)\n\nif __name__ == '__main__':\n main()\n","sub_path":"freefoodfinder.py","file_name":"freefoodfinder.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"368795415","text":"# -*- coding: utf-8 -*- #\n# Copyright 2019 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Provides common arguments for the Events command surface.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\ndef AddCategoryFlag(parser):\n \"\"\"Adds a source flag.\"\"\"\n parser.add_argument(\n '--category',\n required=False,\n help='Events type category by which to filter results.')\n\n\ndef AddEventTypePositionalArg(parser):\n \"\"\"Adds event type positional arg.\"\"\"\n parser.add_argument(\n 'event_type',\n help='Type of event (e.g. com.google.gc.object.finalize).')\n\n\ndef AddTargetServiceFlag(parser, required=False):\n \"\"\"Adds target service flag.\"\"\"\n parser.add_argument(\n '--target-service',\n required=required,\n help='Name of the Cloud Run service to receive events at.')\n","sub_path":"api/google-cloud-sdk/lib/googlecloudsdk/command_lib/events/flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"455557032","text":"\"\"\"\n Utility functions for formatting\n\"\"\"\n\nfrom qcelemental import constants as qcc\nfrom qcelemental import periodictable as ptab\nfrom automol import geom\n\n# Conversion factors\nBOHR2ANG = qcc.conversion_factor('bohr', 'angstrom')\n\n\n# Utility functions for the structure.inp writer\ndef determine_struct_type(geo):\n \"\"\" determines the linear string\n \"\"\"\n\n # Remove dummy atoms\n geo = [coords for coords in geo\n if coords[0] != 'X']\n\n if geom.is_atom(geo):\n struct_type = 'Monoatomic'\n else:\n if geom.is_linear(geo):\n struct_type = 'Linear'\n else:\n struct_type = 'Nonlinear'\n\n return struct_type\n\n\ndef format_coords(geo):\n \"\"\" format the coords section\n \"\"\"\n\n # Get the number of atoms\n natoms = len(geo)\n\n # Get the geometry information\n symbols = geom.symbols(geo)\n coordinates = geom.coordinates(geo)\n masses = [int(ptab.to_mass(symbol)) if symbol != 'X' else 0\n for symbol in symbols]\n\n # Build a string with the formatted coordinates string\n if geom.is_atom(geo):\n geo_str = '{0:<4s}{1:<6d}'.format(symbols[0], masses[0])\n else:\n geo_str = '{0} \\n'.format(str(natoms))\n for symbol, mass, coords in zip(symbols, masses, coordinates):\n coords = [coord * BOHR2ANG for coord in coords]\n coords_str = '{0:>14.8f}{1:>14.8f}{2:>14.8f}'.format(\n coords[0], coords[1], coords[2])\n geo_str += '{0:<4s}{1:<6d}{2}\\n'.format(\n symbol, mass, coords_str)\n # Remove final newline character from the string\n geo_str = geo_str.rstrip()\n\n return natoms, geo_str\n\n\n# Utility functions for the tst.inp writer\ndef format_grids_string(grid, name, units):\n \"\"\" format the string using the grids for\n energy and angular momentum for tst.inp file\n \"\"\"\n grid_str = '{0}_grid{1:>8d}{2:>9d}{3:>11.2f}{4:>7d}'.format(\n name, grid[0], grid[1], grid[2], grid[3])\n grid_str += ' {0:<8s}# {1} grid'.format(units, name)\n\n return grid_str\n\n\ndef format_faces_string(faces):\n \"\"\" format faces keywords\n \"\"\"\n faces_str = ' '.join(faces)\n\n return faces_str\n\n\n# Utility functions for the divsur.inp writer\ndef format_values_string(coord, values, conv_factor=1.0):\n \"\"\" format the values string for the divsur.inp file\n \"\"\"\n if values:\n values = ', '.join('{0:.3f}'.format(val * conv_factor)\n for val in values)\n values_string = '{0} = ({1})'.format(coord, values)\n else:\n values_string = ''\n\n return values_string\n\n\ndef format_pivot_xyz_string(idx, npivot, xyzp, phi_dependence=False):\n \"\"\" format the pivot point xyz\n \"\"\"\n\n assert npivot in (1, 2)\n\n atom_idx = idx\n if idx == 1:\n d_idx = 1\n else:\n d_idx = 2\n\n if npivot == 1:\n x_val = 'x{0} = {1:.3f}'.format(atom_idx, xyzp[0])\n y_val = ' y{0} = {1:.3f}'.format(atom_idx, xyzp[1])\n z_val = ' z{0} = {1:.3f}'.format(atom_idx, xyzp[2])\n pivot_xyz_string = (x_val + y_val + z_val)\n elif npivot > 1 and not phi_dependence:\n x_val1 = 'x{0} = {1:.3f} + d{2}*cos(t{0})'.format(\n atom_idx, xyzp[0], d_idx)\n y_val1 = ' y{0} = {1:.3f} + d{2}*sin(t{0})'.format(\n atom_idx, xyzp[1], d_idx)\n z_val1 = ' z{0} = 0.000'.format(\n atom_idx)\n x_val2 = 'x{0} = {1:.3f} - d{2}*cos(t{0})'.format(\n atom_idx+1, xyzp[0], d_idx)\n y_val2 = ' y{0} = {1:.3f} - d{2}*sin(t{0})'.format(\n atom_idx+1, xyzp[1], d_idx)\n z_val2 = ' z{0} = 0.000'.format(\n atom_idx+1)\n pivot_xyz_string = (x_val1 + y_val1 + z_val1 + '\\n' +\n x_val2 + y_val2 + z_val2)\n else:\n # Not sure if this implementation is any good\n x_val1 = 'x{0} = {1:.0f} + d{2}*sin(p{0})*cos(t{0})'.format(\n atom_idx, xyzp[0], d_idx)\n y_val1 = ' y{0} = {1:.0f} + d{2}*sin(p{0})*sin(t{0})'.format(\n atom_idx, xyzp[1], d_idx)\n z_val1 = ' z{0} = {1:.0f} + d{2}*cos(p{0})'.format(\n atom_idx, xyzp[2], d_idx)\n x_val2 = 'x{0} = {1:.0f} - d{2}*sin(p{0})*cos(t{0})'.format(\n atom_idx+1, xyzp[0], d_idx)\n y_val2 = ' y{0} = {1:.0f} - d{2}*sin(p{0})*sin(t{0})'.format(\n atom_idx+1, xyzp[1], d_idx)\n z_val2 = ' z{0} = {1:.0f} + d{2}*cos(p{0})'.format(\n atom_idx+1, xyzp[2], d_idx)\n pivot_xyz_string = (x_val1 + y_val1 + z_val1 + '\\n' +\n x_val2 + y_val2 + z_val2)\n\n return pivot_xyz_string\n\n\n# Utility functions for the species_corr.f correction potential writer\ndef format_corrpot_dist_string(aidx, bidx, asym, bsym):\n \"\"\" set distance string for two atoms for the file\n \"\"\"\n lasym, lbsym = asym.lower(), bsym.lower()\n\n dist_string = (\n \" n{0} = {4}\\n\" +\n \" n{1} = {5}\\n\" +\n \" r{2}{3} = dsqrt( (x(1,n{1})-x(1,n{0}))**2 +\\n\" +\n \" x (x(2,n{1})-x(2,n{0}))**2 +\\n\" +\n \" x (x(3,n{1})-x(3,n{0}))**2)\\n\" +\n \" r{2}{3} = r{2}{3}*0.52917\"\n ).format(lasym, lbsym, asym, bsym, aidx, bidx)\n\n return dist_string\n\n\ndef format_delmlt_string(asym, bsym):\n \"\"\" set distance string for two atoms for the file\n \"\"\"\n\n delmlt_string = (\n \" delmlt = 1.0d0\\n\" +\n \" if(r{0}{1}.le.r{0}{1}min) r{0}{1} = r{0}{1}min\\n\" +\n \" if(r{0}{1}.ge.r{0}{1}max) then\\n\" +\n \" delmlt = exp(-2.d0*(r{0}{1}-r{0}{1}max))\\n\" +\n \" r{0}{1}=r{0}{1}max\\n\" +\n \" endif\"\n ).format(asym, bsym)\n\n return delmlt_string\n\ndef format_comp_dist_string(sym1, sym2, name):\n \"\"\" build string that has the distance comparison\n \"\"\"\n\n comp_string = (\n \" if (r{0}{1}.lt.rAB) then\\n\" +\n \" {2}_corr = 100.0\\n\" +\n \" return\\n\" +\n \" endif\"\n ).format(sym1, sym2, name)\n\n return comp_string\n\n\ndef format_spline_strings(npot, sym1, sym2, species_name):\n \"\"\" spline fitting strings\n \"\"\"\n\n spline_str = ''\n for i in range(npot):\n if i == 0:\n ifstr = 'if'\n else:\n ifstr = 'else if'\n spline_str += ' {0} (ipot.eq.{1}) then\\n'.format(ifstr, str(i+1))\n spline_str += (\n ' call spline(rinp,dv{0},nrin,dvp1,dvpn,dv20)\\n' +\n ' call splint(rinp,dv{0},dv20,nrin,r{1}{2},{3})\\n'\n ).format(str(i+1), sym1, sym2, species_name+'_corr')\n spline_str += ' endif'\n\n return spline_str\n","sub_path":"varecof_io/writer/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"510225167","text":"import statistics\nimport csv \nimport matplotlib.pyplot as plt\nfrom datetime import datetime\n#se extrae la informacion del archivo csv\nwork=\"real.csv\"\n#se extrae todos los datos del archivo csv para determinar cada variable:\n#para Temperatura\nwith open(work) as f:\n read=csv.reader(f)\n cabezera=next(read)\n\n\n dates_t=[]\n temperatura=[]\n for row in read:\n current_date=datetime.strptime(row[0],'%d/%m/%Y')\n try:\n t=float(row[2])\n \n#codigo para eliminar datos vacios \n except ValueError:\n print(f\"Missing data for {current_date}\")\n#esos valores se añaden a las listas desde la linea 13 hasta la 19 \n else:\n dates_t.append(current_date)\n temperatura.append(t) \n###evaluamos anualmente\ncant_t=0\nfor i in dates_t:\n cant_t+=1\n \narreglo_cant_datos_anual_t=[]\npromedio_datos_anual_t=[]\ndatos_menores_anuales_t=[]\ndatos_mayores_anuales_t=[]\n\nfor a in range(2010,2020):\n #bucle para añadir informacion al arreglo: \n cant_datos_t=0\n ma=0\n me=1000\n cant_datos_t=0\n suma_datos_t=0\n \n for i in range(0,cant_t):\n if dates_t[i].year==a:\n cant_datos_t+=1\n suma_datos_t+=temperatura[i]\n if matemperatura[i]:\n me=temperatura[i]\n \n \n \n prom_datos_anual_t=suma_datos_t/cant_datos_t\n \n promedio_datos_anual_t.append(prom_datos_anual_t)\n datos_mayores_anuales_t.append(ma)\n datos_menores_anuales_t.append(me)\nprint(promedio_datos_anual_t)\n# print(datos_mayores_anuales_t)\n# print(datos_menores_anuales_t)\n\n# year=[]\n# for a in range(2009,2019):\n# a=a+1\n# year.append(a)\n\n# plt.style.use('seaborn')\n# fig,ax=plt.subplots()\n# ax.plot(year,datos_mayores_anuales_t,c=\"blue\",linewidth=5)\n# ax.plot(year,promedio_datos_anual_t,c=\"red\",linewidth=5)\n# ax.plot(year,datos_menores_anuales_t,c=\"green\",linewidth=5)\n# ax.set_title(\"Promedio anual de temperatura \\n E.'Campo de Marte'\",fontsize=20)\n# ax.set_xlabel(\"Años\",fontsize=15)\n# ax.set_ylabel(\"Temperatura °C\",fontsize=20)\n# ax.tick_params(axis=\"both\",which=\"major\",labelsize=15)\n# ax.axis([2010,2019,10,35])\n# plt.plot(datos_mayores_anuales_t, label = \"Tmax\")\n# plt.plot(datos_menores_anuales_t,label=\"Tmin\")\n# plt.plot(datos_mayores_anuales_t, label = \"Tprom\")\n# plt.legend()\n# plt.show()\n# ###evaluamos mensualmente\n# arreglo_cant_datos_mensuales_t=[]\n# promedio_datos_mensuales_t=[]\n# maximo_datos_mensuales_t=[]\n# minimo_datos_mensuales_t=[]\n# for i in range(1,13):\n# cant_datos_mensual_t=0\n# ma=0\n# me=1000 \n# suma_datos_mensual_t=0 \n# for a in range(0,cant_t):\n# if dates_t[a].month==i:\n# cant_datos_mensual_t+=1\n# suma_datos_mensual_t+=temperatura[a]\n \n# if matemperatura[a]:\n# me=temperatura[a]\n# promedio_datos_t=suma_datos_mensual_t/cant_datos_mensual_t\n# promedio_datos_mensuales_t.append(promedio_datos_t)\n# maximo_datos_mensuales_t.append(ma)\n# minimo_datos_mensuales_t.append(me)\n\n# t_mens=promedio_datos_mensuales_t\n# meses=[\"Ene\",\"Feb\",\"Mar\",\"Abr\",\"May\",\"Jun\",\"Jul\",\"Ago\",\"Sep\",\"Oct\",\"Nov\",\"Dic\"]\n# fig,ax=plt.subplots()\n# plt.style.use(\"seaborn\")\n# ax.plot(meses,promedio_datos_mensuales_t,linewidth=5,c=\"red\")\n# ax.plot(meses, maximo_datos_mensuales_t,linewidth=5,c=\"blue\")\n# ax.plot(meses,minimo_datos_mensuales_t,linewidth=5,c=\"green\")\n# ax.set_title(\"Promedio estacional de temperatura \\n E.'Campo de Marte'\",fontsize=20)\n# ax.set_xlabel(\"Meses\",fontsize=15)\n# ax.set_ylabel(\"Temperatura °C\",fontsize=20)\n# ax.tick_params(axis=\"both\",which=\"major\",labelsize=15)\n# plt.plot(maximo_datos_mensuales_t, label = \"T_mens_max\")\n# plt.plot(minimo_datos_mensuales_t,label=\"T_mens_min\")\n# plt.plot(promedio_datos_mensuales_t, label = \"T_mens_prom\")\n# plt.legend()\n# plt.show()\n# # =============================================================================\n# # \n# # # para humeadad\n# # =============================================================================\n# with open(work) as f: \n# dates_h=[]\n# humedad=[]\n \n# read=csv.reader(f)\n# cabezera=next(read)\n# for row in read:\n# current_date_h=datetime.strptime(row[0],'%d/%m/%Y') \n# try:\n \n# h=float(row[3])\n \n# #codigo para eliminar datos vacios \n# except ValueError:\n# print(f\"Missing data for {current_date}\")\n# #esos valores se añaden a las listas desde la linea 13 hasta la 19 \n# else:\n# dates_h.append(current_date_h)\n# humedad.append(h)\n# cant_h=0\n# for i in dates_h:\n# cant_h+=1 \n# arreglo_cant_datos_anual_h=[]\n# promedio_datos_anual_h=[]\n# datos_menores_anuales_h=[]\n# datos_mayores_anuales_h=[]\n# for a in range(2010,2020):\n# cant_datos_h=0\n# suma_datos_h=0\n# ma=0\n# me=1000\n \n# for i in range(0,cant_h):\n# if dates_h[i].year==a:\n# cant_datos_h+=1\n# suma_datos_h+=humedad[i]\n \n# if mahumedad[i]:\n# me=humedad[i]\n \n# prom_datos_anual_h=suma_datos_h/cant_datos_h\n \n# promedio_datos_anual_h.append(prom_datos_anual_h)\n# datos_mayores_anuales_h.append(ma)\n# datos_menores_anuales_h.append(me)\n \n \n# plt.style.use('seaborn')\n# fig,ax=plt.subplots()\n# ax.plot(year,datos_mayores_anuales_h,c=\"blue\",linewidth=5)\n# ax.plot(year,promedio_datos_anual_h,c=\"red\",linewidth=5)\n# ax.plot(year,datos_menores_anuales_h,c=\"green\",linewidth=5)\n# ax.set_title(\"Promedio anual de humedad \\n E.'Campo de Marte'\",fontsize=20)\n# ax.set_xlabel(\"Años\",fontsize=15)\n# ax.set_ylabel(\"Humedad %\",fontsize=20)\n# ax.tick_params(axis=\"both\",which=\"major\",labelsize=15)\n# plt.plot(datos_mayores_anuales_h, label = \"Hmax\")\n# plt.plot(datos_menores_anuales_h,label=\"Hmin\")\n# plt.plot(datos_mayores_anuales_h, label = \"Hprom\")\n# ax.axis([2010,2019,30,100])\n# plt.legend()\n# plt.show() \n\n\n\n# # ###evaluamos mensualmente\n# # arreglo_cant_datos_mensuales_h=[]\n# # promedio_datos_mensuales_h=[]\n# # maximo_datos_mensuales_h=[]\n# # minimo_datos_mensuales_h=[]\n# # for i in range(1,13):\n# # cant_datos_mensual_h=0\n# # ma=0\n# # me=1000 \n# # suma_datos_mensual_h=0 \n# # for a in range(0,cant_h):\n# # if dates_t[a].month==i:\n# # cant_datos_mensual_h+=1\n# # suma_datos_mensual_h+=humedad[a]\n \n# # if mahumedad[a]:\n# # me=humedad[a]\n# # promedio_datos_h=suma_datos_mensual_t/cant_datos_mensual_h\n# # promedio_datos_mensuales_h.append(promedio_datos_h)\n# # maximo_datos_mensuales_h.append(ma)\n# # minimo_datos_mensuales_h.append(me)\n# # fig,ax=plt.subplots()\n# # plt.style.use(\"seaborn\")\n# # ax.plot(meses,promedio_datos_mensuales_h,linewidth=5,c=\"red\")\n# # ax.plot(meses, maximo_datos_mensuales_h,linewidth=5,c=\"blue\")\n# # ax.plot(meses,minimo_datos_mensuales_h,linewidth=5,c=\"green\")\n# # ax.set_title(\"Promedio estacional de humedad\\n E.'Campo de Marte'\",fontsize=20)\n# # ax.set_xlabel(\"Meses\",fontsize=15)\n# # ax.set_ylabel(\"Humedad %\",fontsize=20)\n# # ax.tick_params(axis=\"both\",which=\"major\",labelsize=15)\n# # plt.plot(maximo_datos_mensuales_h, label = \"H_mens_max\")\n\n# # plt.plot(promedio_datos_mensuales_h, label = \"H_mens_prom\")\n# # plt.plot(minimo_datos_mensuales_h,label=\"H_mens_min\")\n# # plt.legend()\n# # plt.show()\n\n# # # para viento(dir y veloc)\n\n# with open(work) as f:\n# direccion_viento=[]\n# dates_dv=[]\n \n \n# read=csv.reader(f)\n# cabezera=next(read)\n# for row in read:\n# current_date_dv=datetime.strptime(row[0],'%d/%m/%Y') \n# try:\n \n \n# d_v=float(row[5])\n \n# #codigo para eliminar datos vacios \n# except ValueError:\n# print(f\"Missing data for {current_date}\") \n# else:\n# dates_dv.append(current_date_dv)\n# direccion_viento.append(d_v)\n\n\n# # datos dv\n# promedio_datos_anual_dv=[]\n# datos_menores_anuales_dv=[]\n# datos_mayores_anuales_dv=[]\n# cant_dv=0\n# for i in dates_dv:\n# cant_dv+=1\n \n# for a in range(2010,2020):\n# #bucle para añadir informacion al arreglo: \n\n# cant_datos_dv=0\n# suma_datos_dv=0 \n# ma=0\n# me=1000 \n# for i in range(0,cant_dv):\n# if dates_dv[i].year==a: \n# cant_datos_dv+=1\n# suma_datos_dv+=direccion_viento[i]\n# if madireccion_viento[i] :\n \n# me=direccion_viento[i]\n \n \n# prom_datos=suma_datos_dv/cant_datos_dv\n# promedio_datos_anual_dv.append(prom_datos)\n# datos_menores_anuales_dv.append(me)\n# datos_mayores_anuales_dv.append(ma)\n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n\n \n# # #velocidad del viento\n# # with open(work) as f:\n# # velocidad_viento=[]\n# # dates_vv=[]\n# # read=csv.reader(f)\n# # cabezera=next(read)\n# # for row in read:\n# # current_date_vv=datetime.strptime(row[0],'%d/%m/%Y') \n \n# # try:\n# # v_v=float(row[6])\n\n# # #codigo para eliminar datos vacios \n# # except ValueError:\n# # print(f\"Missing data for {current_date}\")\n# # #esos valores se añaden a las listas desde la linea 13 hasta la 19 \n# # else:\n# # dates_vv.append(current_date_vv) \n# # velocidad_viento.append(v_v)\n# # cant_dv=0\n# # for i in dates_dv:\n# # cant_dv+=1\n \n# # cant_vv=0\n# # for i in dates_vv:\n# # cant_vv+=1\n\n# # arreglo_cant_datos_anual_dv=[]\n# # arreglo_cant_datos_anual_vv=[]\n# # # datos dv\n# # promedio_datos_anual_dv=[]\n# # datos_menores_anuales_dv=[]\n# # datos_mayores_anuales_dv=[]\n# # for a in range(2010,2020):\n# # #bucle para añadir informacion al arreglo: \n\n# # cant_datos_dv=0\n# # suma_datos_dv=0\n \n \n# # ma=0\n# # me=1000 \n# # for i in range(0,cant_dv):\n# # if dates_dv[i].year==a:\n \n# # cant_datos_dv+=1\n# # suma_datos_dv+=direccion_viento[i]\n \n# # if madireccion_viento[i]:\n# # me=direccion_viento[i]\n \n# # prom_datos_anual_dv=suma_datos_dv/cant_datos_dv \n# # promedio_datos_anual_dv.append(prom_datos_anual_dv)\n# # datos_menores_anuales_dv.append(me)\n# # datos_mayores_anuales_dv.append(ma)\n\n\n# # print(datos_menores_anuales_dv) \n# # for a in range(2010,2020):\n# # #bucle para añadir informacion al arreglo: \n# # cant_datos_t=0\n# # ma=0\n# # me=100000\n# # cant_datos_t=0\n# # suma_datos_t=0\n \n# # for i in range(0,cant_t):\n# # if dates_t[i].year==a:\n# # cant_datos_t+=1\n# # suma_datos_t+=temperatura[i]\n# # if matemperatura[i]:\n# # me=temperatura[i]\n \n \n# # prom_datos_anual_t=suma_datos_t/cant_datos_t\n \n# # promedio_datos_anual_t.append(prom_datos_anual_t) \n# # datos_menores_anuales_t.append(me)\n# # datos_mayores_anuales_t.append(ma)\n\n\n\n\n# # # datos vv\n# # promedio_datos_anual_vv=[]\n# # datos_menores_anuales_vv=[]\n# # datos_mayores_anuales_vv=[]\n\n# # for a in range(2010,2020):\n# # #bucle para añadir informacion al arreglo: \n# # cant_datos_vv=0\n# # cant_datos_dv=0\n# # suma_datos_dv=0\n# # suma_datos_vv=0\n \n# # ma=0\n# # me=1000 \n# # for i in range(0,cant_dv):\n# # if dates_dv[i].year==a:\n \n# # cant_datos_dv+=1\n# # suma_datos_dv+=direccion_viento[i]\n \n# # if madireccion_viento[i]:\n# me=direccion_viento[i]\n \n# prom_datos_anual_dv=suma_datos_dv/cant_datos_dv \n# arreglo_cant_datos_anual_dv.append(cant_datos_dv)\n# promedio_datos_anual_dv.append(prom_datos_anual_dv)\n# datos_menores_anuales_dv.append(me)\n# datos_mayores_anuales_dv.append(ma)\n \n \n \n# for i in range(0,cant_vv):\n# if dates_vv[i].year==a:\n \n# cant_datos_vv+=1\n# suma_datos_vv+=velocidad_viento[i]\n \n# if mavelocidad_viento[i]:\n# me=velocidad_viento[i]\n \n \n \n# prom_datos_anual_vv=suma_datos_vv/cant_datos_vv \n# #agregamos los valores a las listas de las variables halladas\n# #Datos para vel. \n# promedio_datos_anual_vv.append(prom_datos_anual_vv)\n# arreglo_cant_datos_anual_vv.append(cant_datos_vv)\n# datos_menores_anuales_vv.append(me)\n# datos_mayores_anuales_vv.append(ma)\n \n \n# for i in range(0,cant_t):\n# if dates_t[i].year==a:\n# cant_datos_t+=1\n# suma_datos_t+=temperatura[i]\n# if matemperatura[i]:\n# me=temperatura[i]\n \n# prom_datos_anual_t=suma_datos_t/cant_datos_t\n \n# promedio_datos_anual_t.append(prom_datos_anual_t)\n# datos_menores_anuales_t.append(me)\n# datos_mayores_anuales_t.append(ma)\n \n \n# # print(datos_menores_anuales_dv)\n# # print(datos_mayores_anuales_dv)\n# # print(promedio_datos_anual_dv)\n \n \n\n","sub_path":"tempera.py","file_name":"tempera.py","file_ext":"py","file_size_in_byte":14478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"207442088","text":"import tkinter\n\nmain = tkinter.Tk()\n\ndef end(): main.destroy()\ndef show_option(): lb.configure(text = \"Room {0} {1}\".format(shower.get(), desk.get()))\n\nlb = tkinter.Label(main, text = \"Room \")\nlb.pack()\n\nshower = tkinter.StringVar()\nshower.set(\"with shower\")\ndesk = tkinter.StringVar()\ndesk.set(\"with desk\")\n\nshower_checkbutton = tkinter.Checkbutton(main, variable = shower, text = \"Shower\", onvalue = \"with shower\", offvalue = \"without shower\", command = show_option)\nshower_checkbutton.pack()\ndesk_checkbutton = tkinter.Checkbutton(main, variable = desk, text = \"Desk\", onvalue = \"with desk\", offvalue = \"without desk\", command = show_option)\ndesk_checkbutton.pack()\n\ntkinter.Button(main, text = \"Close\", command = end).pack()\n\nmain.mainloop()\n","sub_path":"Tk_Toolkit/OldBook/checkbox_2.py","file_name":"checkbox_2.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"317713037","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('loggrade', '0009_auto_20141027_2312'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='class',\n name='num',\n field=models.CharField(help_text=b'\\xe7\\x8f\\xad\\xe5\\x88\\xab,\\xe7\\x90\\x86\\xe8\\xae\\xba\\xe4\\xb8\\x8a\\xe5\\x90\\x8c\\xe4\\xb8\\x93\\xe4\\xb8\\x9a\\xe7\\x9a\\x84\\xe7\\x8f\\xad\\xe4\\xb8\\x8d\\xe4\\xbc\\x9a\\xe8\\xb6\\x85\\xe8\\xbf\\x87 90 \\xe4\\xb8\\xaa', max_length=1),\n ),\n ]\n","sub_path":"loggrade/migrations/0010_auto_20141028_0023.py","file_name":"0010_auto_20141028_0023.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"510931842","text":"#%%\nimport pandas as pd\nsal = pd.read_csv('SupportFiles/Salaries.csv')\nprint(sal.head())\nsal.info()\nprint(sal[sal['BasePay'] != 'Not Provided' ]['BasePay'].dropna().astype(float).mean())\nprint(sal[sal['OvertimePay'] != 'Not Provided' ]['OvertimePay'].dropna().astype(float).max())\nprint(sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['JobTitle'])\nprint(sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['TotalPayBenefits'])\nprint(sal[sal['TotalPayBenefits'] == sal['TotalPayBenefits'].max()]['EmployeeName'])\nprint(sal[sal['TotalPayBenefits'] == sal['TotalPayBenefits'].min()]['EmployeeName'])\nprint(sal[sal['BasePay'] != 'Not Provided' ][['BasePay','Year']].dropna().astype(float).groupby('Year').mean())\n\n#%%\nlen(sal['JobTitle'].unique())\nsal['JobTitle'].nunique()\nsal['JobTitle'].value_counts().head()\nsum(sal[sal['Year'] == 2013]['JobTitle'].value_counts() == 1)\nsal[sal['JobTitle'].str.contains('Chief', case=True)]['JobTitle']\n\n#%%\nimport pandas as pd\necom = pd.read_csv('SupportFiles/Ecommerce Purchases')\necom.head()\necom.info()\necom['Purchase Price'].mean()\necom['Purchase Price'].max()\necom['Purchase Price'].min()\n\n\n#%%\necom.info()\necom[ecom['Language'] == 'en'].count()\necom[ecom['Job']=='Lawyer'].count()\necom['AM or PM'].value_counts()\necom['Job'].value_counts().head(5)\n\n#%%\necom.info()\nfrom collections import Counter\necom[ecom['Lot']=='90 WT']['Purchase Price']\necom[ecom['Credit Card'] == 4926535242672853]['Email']\necom[(ecom['CC Provider'] == 'American Express') & (ecom['Purchase Price'] > 95.0)].count()\necom[ecom['CC Exp Date'].str.contains('/25')].count()\necom['Email'].apply(lambda email:email.split('@')[1]).value_counts().head(5)\n\n","sub_path":"Pandas_DataAnalysis_Exercise.py","file_name":"Pandas_DataAnalysis_Exercise.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"561684372","text":"import base64\nimport csv\nfrom datetime import datetime\nimport json\nimport os\nimport time\nimport zipfile\n\nfrom django.conf import settings\nfrom django.utils.text import slugify\nfrom pytz import reference\n\nfrom config.settings.default import BASE_DIR\n\ndefault_limit = 20\n\n\ndef get_date_now():\n return 'date'\n\n\ndef get_now():\n now = datetime.now().replace(tzinfo=reference.LocalTimezone())\n return now\n\n\n# return access token\ndef get_access_token(request):\n try:\n return request.auth.decode()\n except AttributeError:\n return None\n\n\ndef decode_authorization(request):\n try:\n basic_auth = request.META['HTTP_AUTHORIZATION']\n basic_token = basic_auth.split(' ')[1]\n basic_token_encode = base64.b64decode(basic_token).decode()\n user_name = basic_token_encode.split(':')[0]\n password = basic_token_encode.split(':')[1]\n return user_name, password\n except:\n return None, None\n\n\n# get epoch time now\ndef get_epoch_time_now():\n return time.time()\n\n\ndef today():\n return datetime.date.today\n\n\n# get all fields of model\ndef get_model_fields(model):\n return model._meta.fields\n\n\n# convert gen csv file from model\ndef model_to_csv(model, data, work_dir=None):\n current_work_dir = settings.MEDIA_ROOT if not work_dir else work_dir\n epoch_now = get_epoch_time_now()\n model_verbose_name = model._meta.verbose_name\n file_name = os.path.join(current_work_dir, '{}_{}.csv'.format(model_verbose_name, epoch_now))\n\n # fields of model\n fields = get_model_fields(model)\n\n # write csv file\n with open(file_name, 'w') as csvfile:\n writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)\n # write your header first\n field_names = [field.verbose_name for field in fields]\n writer.writerow(field_names)\n # write data\n for row in data:\n writer.writerow(row)\n return file_name\n\n\n# method archive a file\ndef zip_afile(file_path, work_dir=None):\n current_work_dir = settings.MEDIA_ROOT if not work_dir else work_dir\n csv_file = os.path.basename(file_path)\n file_name = os.path.join(current_work_dir, '{}.zip'.format(csv_file))\n # write a zip file\n with zipfile.ZipFile(file_name, 'w') as zip:\n zip.write(file_path, csv_file, compress_type=zipfile.ZIP_DEFLATED)\n return file_name\n\n\ndef get_unique_slug(model_instance, slugable_field_name, slug_field_name):\n \"\"\"\n Takes a model instance, sluggable field name (such as 'title') of that\n model as string, slug field name (such as 'slug') of the model as string;\n returns a unique slug as string.\n \"\"\"\n slug = slugify(getattr(model_instance, slugable_field_name))\n unique_slug = slug\n extension = 1\n model_class = model_instance.__class__\n\n while model_class._default_manager.filter(\n **{slug_field_name: unique_slug}\n ).exists():\n unique_slug = '{}-{}'.format(slug, extension)\n extension += 1\n\n return unique_slug\n\n\ndef get_price_setting(model_instance, price_filed):\n pass\n\n\ndef get_filename_ext(filepath):\n base_name = os.path.basename(filepath)\n name, ext = os.path.splitext(base_name)\n return name, ext\n\n\ndef upload_path_category(instance, filename):\n new_filename = time.time()\n name, ext = get_filename_ext(filename)\n final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)\n return \"category/image/{final_filename}\".format(\n new_filename=new_filename,\n final_filename=final_filename\n )\n\n\n# get now epoch tiem\ndef get_epoch_now():\n return time.time()\n\n\ndef listed_time_to_string(listed_time):\n now = get_epoch_time_now()\n delta_time = datetime.datetime.fromtimestamp(now) - datetime.datetime.fromtimestamp(listed_time)\n days = delta_time.days\n hours = delta_time.seconds // 3600\n minutes = (delta_time.seconds // 60) % 60\n if days > 0:\n time_string = '{} ngày trước'.format(days)\n elif hours > 0:\n time_string = '{} giờ trước'.format(hours)\n elif minutes == 0:\n time_string = 'vừa xong'\n else:\n time_string = '{} phút trước'.format(minutes)\n return time_string\n\n\n# load mapping fields\ndef load_mapping():\n data_path = os.path.join(os.path.dirname(BASE_DIR), 'data')\n file_path = os.path.join(data_path, 'mapping.json')\n with open(file_path) as json_file:\n data = json.load(json_file)\n return data\n\n\n# load mapping fields\ndef load_filter_types():\n data_path = os.path.join(os.path.dirname(BASE_DIR), 'data')\n file_path = os.path.join(data_path, 'filter_types.json')\n with open(file_path) as json_file:\n data = json.load(json_file)\n return data\n\n\ndef query_key_mapping(queries):\n queries_mapping = {}\n mapping_data = load_mapping()\n for key, value in queries.items():\n appended_key = key\n for key_mapping, value_mapping in mapping_data.items():\n if key in value_mapping:\n appended_key = key_mapping\n break\n queries_mapping[appended_key] = queries.getlist(key)\n\n return queries_mapping\n\n\ndef get_key_range(key):\n range_fields = [\"rooms\", \"mileage\", \"mf_date\", \"reg_date\"]\n if key in range_fields:\n return '{}.value'.format(key)\n return key\n\n\ndef build_query(queries):\n filters = []\n range_fields = [\"rooms\", \"mileage\", \"mf_date\", \"reg_date\", \"price\"]\n queries_mapping = query_key_mapping(queries)\n for key, value in queries_mapping.items():\n if key == 'title':\n filters.append({\"multi_match\": {\"query\": value, \"fields\": [\"title\", \"body\"]}})\n continue\n if key == 'g_category':\n filter_key = 'category.code'\n filters.append({\"match\": {filter_key: value[0]}})\n continue\n\n if key == 's_category':\n filter_key = 'category.global_category'\n filters.append({\"match\": {filter_key: value[0]}})\n continue\n\n if key == 'listed_time':\n continue\n\n if key in range_fields:\n filter_key = get_key_range(key)\n for v in value:\n filters.append({\"range\": {filter_key: {\"gte\": v}}})\n continue\n if type(value) is list:\n filter_key = '{}.value'.format(key)\n for v in value:\n filters.append({\"match\": {filter_key: v}})\n continue\n\n dict_query = {\"query\": {\"bool\": {\"must\": filters}}}\n return dict_query\n\n\ndef has_next(current_page, total):\n total_page = get_num_pages(total)\n if current_page < total_page:\n return True\n return False\n\n\ndef get_next_page(page, total):\n total_pages = get_num_pages(total)\n if page >= total_pages:\n return None\n return page + 1\n\n\ndef get_prev_page(page, total):\n total_pages = get_num_pages(total)\n if page <= 1 or total_pages == 1:\n return None\n return page - 1\n\n\ndef get_num_pages(total):\n total_page = (total // default_limit) if total % default_limit == 0 else (total // default_limit + 1)\n return total_page\n\n\ndef get_offset(page, total):\n total_page = get_num_pages(total)\n if page > total_page:\n page = total_page\n start_offset = ((page - 1) * default_limit) + 1\n end_offset = page * default_limit\n return start_offset, end_offset\n","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"215207311","text":"import numpy as np\nimport matplotlib.pyplot as plt\nnp.set_printoptions(precision=4, suppress=True)\n\ndef rotx(angle):\n return np.array([[1, 0, 0],\n [0, np.cos(angle), -np.sin(angle)],\n [0, np.sin(angle), np.cos(angle)]])\n\ndef task_a(): # Transforms ro to rc via Tco. Returns rc (not homog)\n rc_h = np.zeros((4, 4))\n \n for i in range(len(ro_h)):\n rc_h[i] = Tco @ ro_h[i]\n \n return rc_h[:, :-1]\n\n\ndef task_b(): # Converts rc into normalizes imgage coordinates, s\n s = np.zeros((4,3))\n rc = task_a()\n for i in range(len(rc)):\n s[i] = 1/rc[i, 2] * rc[i]\n return s\n\ndef task_c(ro, s):\n plt.scatter(ro[:,0], ro[:,1], label='rc')\n plt.scatter(s[:,0], s[:,1], label='s')\n plt.xlim([-1.1,1.1])\n plt.ylim([-1.1,1.1])\n plt.legend()\n plt.show()\n \n\nif __name__ == \"__main__\":\n Tco = np.block([[rotx(2*np.pi/3), np.array([[0, 0, 2]]).T],\n [np.zeros(3), 1]])\n \n ro = np.array([[0,0,0],\n [1,0,0],\n [1,1,0],\n [0,1,0]]) \n ro_h = np.block([ro, np.ones((4,1))])\n\n rc = task_a()\n for i in range(len(rc)):\n print('rc{}: '.format(i+1), rc[i])\n \n s = task_b()\n for i in range(len(rc)):\n print('s{}: '.format(i+1), s[i])\n \n task_c(ro, s)\n\n \n \n","sub_path":"Collection/plot_img_coordinates.py","file_name":"plot_img_coordinates.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"187811870","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/11/4 9:13\n# @Author : Yang Peihao\n# @Site : \n# @File : BubbleSort.py\n# @Software: PyCharm\n\n\n\n\n\n# 冒泡排序\nimport datetime\nimport time\n\nfrom pandas import np\n\n\ndef bubbleSort(arr):\n n = len(arr)\n\n # 遍历所有数组元素\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n\n\n\n\n# dt=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n# ts = int(time.mktime(time.strptime(dt, \"%Y-%m-%d %H:%M:%S\")))\n# np.random.seed(123)\n# arr=np.random.randint(ts,size=int(ts/100000))\n# arr=arr.tolist()\narr=[1,6,9,8,45,55,66,100,1025,1024,2,3,6,5,4,8,5,45]\nn = len(arr)\nnow_time = time.time() ##2##\nbubbleSort(arr)\ntotal_time = time.time() - now_time ##3##\nres=[]\nprint(\"排序后的数组:\")\nfor i in range(n):\n res.append(arr[i])\nprint(res)\nprint(f\"对于含有{n}个元素,采用冒泡排序算法消耗的时间为{total_time}\")","sub_path":"first/BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"371600940","text":"import cv2\nimport numpy as np\n# import matplotlib.pylab as plt \n\n\ndef combine_images(img_txt, foot_txt):\n\n print(img_txt)\n print(foot_txt) \n image = cv2.imread(f'raw_img/id_{img_txt}.png')\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n footer = cv2.imread(f'format_footer/{foot_txt}.jpg')\n # footer = cv2.cvtColor(footer, cv2.COLOR_BGR2RGB)\n print(image.shape[1])\n print(footer.shape[1])\n scale = footer.shape[1] / image.shape[1]\n\n if scale < 1:\n width = int(image.shape[1] * scale)\n height = int(image.shape[0] * scale)\n image = cv2.resize(image, (width, height), interpolation = cv2.INTER_AREA)\n else:\n width = int(footer.shape[1] / scale)\n height = int(footer.shape[0] / scale)\n footer = cv2.resize(footer, (width, height), interpolation = cv2.INTER_AREA)\n\n # Inspired by https://stackoverflow.com/a/24522170\n # combined = np.concatenate((image, footer), axis=2)\n h1, w1 = image.shape[:2]\n h2, w2 = footer.shape[:2]\n\n combined = np.zeros((h1+h2, max(w1, w2), 3), np.uint8)\n\n combined[:h1, :w1, :3] = image\n combined[h1:h1+h2, :w2, :3] = footer\n\n path = f'combined/{img_txt}+{foot_txt}.png'\n\n cv2.imwrite(path, combined)\n\n return path\n\nif __name__ == \"__main__\":\n combine_images(2157298, 'entire_stock')","sub_path":"image_combiner.py","file_name":"image_combiner.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"318569410","text":"import yaml\nimport pprint\n\nfrom skull.txn import *\nfrom skull.txndata import *\nfrom skull import logger as Logger\n\nfrom common import metrics as Metrics\nfrom common.proto import *\n\ndef module_init(config):\n print(\"py module init\")\n print(\"config: \", end=' ')\n pprint.pprint(config)\n\n Logger.trace('py module init: trace test')\n Logger.debug('py module init: debug test')\n Logger.info('1', 'py module init: info test')\n Logger.warn('2', 'py module init: warn test', 'no suggestion')\n Logger.error('3', 'py module init: error test', 'no solution')\n Logger.fatal('4', 'py module init: fatal test', 'no solution')\n return True\n\ndef module_release():\n print(\"py module release\")\n return\n\ndef module_unpack(txn, data):\n print(\"data: %s\" % data, end=' ')\n Logger.info('5', 'receive data: {}'.format(data.decode('UTF-8')))\n example_msg = txn.data()\n example_msg.data = data\n\n return len(data)\n\ndef module_pack(txn, txndata):\n mod_metrics = Metrics.module()\n mod_metrics.response.inc(1)\n\n mod_dymetrics = Metrics.transaction('test')\n mod_dymetrics.response.inc(1)\n\n if txn.status() != Txn.TXN_OK:\n txndata.append('error')\n Logger.error('6', 'module_pack error', 'no solution')\n else:\n example_msg = txn.data()\n print(\"pack data: %s\" % example_msg.data)\n Logger.info('7', 'module_pack: data sz: {}'.format(len(example_msg.data)))\n\n txndata.append(example_msg.data)\n\ndef module_run(txn):\n print(\"module_run\")\n mod_metrics = Metrics.module()\n mod_metrics.request.inc(1)\n\n mod_dymetrics = Metrics.transaction('test')\n mod_dymetrics.request.inc(1)\n\n # Assemble api request\n get_req_msg = service_s1_get_req_pto.get_req()\n get_req_msg.name = \"hello\"\n\n # invoke iocall to s1 service\n ret = txn.iocall('s1', 'get', get_req_msg, api_cb=_api_cb)\n print(\"iocall ret: {}\".format(ret))\n return True\n\ndef _api_cb(txn, iostatus, api_name, request_msg, response_msg):\n print(\"api_cb: iostatus: {}, api_name: {}, request_msg: {}, response_msg: {}\".format(\n iostatus, api_name, request_msg, response_msg))\n\n example_msg = txn.data()\n example_msg.data += (str(response_msg.response) + ', ').encode('UTF-8')\n\n # Assemble api request\n get_req_msg = service_s1_get_req_pto.get_req()\n get_req_msg.name = \"hello\"\n\n ret = txn.iocall('s1', 'get', get_req_msg, api_cb=_api_cb1)\n print(\"iocall ret: {}\".format(ret))\n return True\n\ndef _api_cb1(txn, iostatus, api_name, request_msg, response_msg):\n print(\"api_cb1: iostatus: {}, api_name: {}, request_msg: {}, response_msg: {}\".format(\n iostatus, api_name, request_msg, response_msg))\n\n example_msg = txn.data()\n example_msg.data += (str(response_msg.response) + ', ').encode('UTF-8')\n return True\n\n","sub_path":"tests/cases/py_chain_call_services/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"463297086","text":"from flask import Flask\nfrom flask import request, jsonify\nimport os\nimport pickle\nimport wikipedia\nfrom wikiparser import WikiParser, RelationContextManager\n\n# Load RCMs\nrcms_fn = \"rcms.p\"\nif os.path.exists(rcms_fn):\n rcms = pickle.load( open( rcms_fn, \"rb\" ) )\nelse:\n rcms = {}\n\nwp = WikiParser(load_data_cache=False)\n\napp = Flask(__name__)\n\n@app.route('/get_relationships')\ndef get_relationships():\n data = wp.grab(request.args['title'])\n rels = list(wp.match_contexts(data, rcms, request.args['title']))\n return jsonify(rels=rels)\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","sub_path":"api_example.py","file_name":"api_example.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"647876068","text":"\"\"\"\nWHAM=2D analysis helper functions.\n\"\"\"\nimport numpy as np\nimport subprocess\n\n\ndef run_wham(wham_args, verbose=False):\n wham_args = [str(i) for i in wham_args]\n wham_process = subprocess.run(wham_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if verbose:\n stdout, stderr = wham_process.stdout.decode(), wham_process.stderr.decode()\n print(\"Stdout:\\n\\n%s\\nStderr:\\n%s\" % (stdout, stderr))\n return read_wham_out(wham_args[-2])\n\n\ndef read_wham_out(filename):\n with open(filename, 'r') as f:\n lines = f.readlines()\n data = dict(x=[], y=[], free=[], prob=[])\n for line in lines[1:]:\n ls = line.split()\n if len(ls) > 0:\n data['x'].append(float(ls[0]))\n data['y'].append(float(ls[1]))\n data['free'].append(float(ls[2]))\n data['prob'].append(float(ls[3]))\n return data\n\n\ndef write_timeseries_file(filename, time, position_x, position_y):\n with open(filename, 'w') as f:\n for t, px, py in zip(time, position_x, position_y):\n f.write('%.2f %.5f %.5f\\n' % (t, px, py))\n\n\ndef timesteps_to_time(timesteps, dt=1, conversion=1e-3):\n \"\"\" Convert time steps to time \"\"\"\n return np.array(timesteps) * dt * conversion\n\n\ndef write_data_file(filename, tsfile, minimum_x, minimum_y, spring_x, spring_y):\n with open(filename, 'w') as f:\n for ts, mx, my, kx, ky in zip(tsfile, minimum_x, minimum_y, spring_x, spring_y):\n f.write('%s %.5f %.5f %.2f %.2f\\n' % (ts, mx, my, kx, ky))\n","sub_path":"scripts/surface-scan/wham2d.py","file_name":"wham2d.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"415271249","text":"\n\"\"\"\nLoad the data (use pandas) from the provided file buddymove_holidayiq.csv (the BuddyMove Data Set) - you should have 249 rows, 7 columns, and no missing values. The data reflects the number of place reviews by given users across a variety of categories (sports, parks, malls, etc.).\n\nUsing the standard sqlite3 module:\n\n Open a connection to a new (blank) database file buddymove_holidayiq.sqlite3\n Use df.to_sql (documentation) to insert the data into a new table review in the SQLite3 database\n\nThen write the following queries (also with sqlite3) to test:\n\n Count how many rows you have - it should be 249!\n How many users who reviewed at least 100 Nature in the category also reviewed at least 100 in the Shopping category?\n (Stretch) What are the average number of reviews for each category?\n\nYour code (to reproduce all above steps) should be saved in buddymove_holidayiq.py, and added to the repository along with the generated SQLite database.\n\n\"\"\"\n#Imports\nimport os #using os rather than string becasue it might not work on other computers\nimport sqlite3\nimport pandas as pd\nimport numpy as np\n\n#Checking csv to make sure it is imported correctly\nCSV_FILEPATH = os.path.join(os.path.dirname(__file__), \"buddymove_holidayiq.csv\")\nbuddymove_holidayiq = pd.read_csv(CSV_FILEPATH)\nprint(buddymove_holidayiq.head())\nprint(buddymove_holidayiq.shape)\n\n#code used to create new sqlite db\n# connection = sqlite3.connect('buddymove_holidayiq.sqlite3')\n# cursor.execute('CREATE TABLE buddymove_holidayiq (User ID, Sports, Religious, Nature, Theater, Shopping, Picnic)')\n# connection.commit()\n\n# buddymove_holidayiq.to_sql('buddymove_holidayiq', connection, if_exists = 'replace', index = True )\n\n\n# # construct a path to wherever your database exists\nDB_FILEPATH = os.path.join(os.path.dirname(__file__), \"buddymove_holidayiq.sqlite3\") # relative filepath directory\n\nconnection = sqlite3.connect(DB_FILEPATH)\nconnection.row_factory = sqlite3.Row # allow us to reference rows as dictionaries\nprint(\"CONNECTION:\", connection)\n\ncursor = connection.cursor()\nprint(\"CURSOR\", cursor)\n\n#Count how many rows you have - it should be 249!\nquery1 = \"SELECT COUNT(*) FROM buddymove_holidayiq\"\nresult1 = cursor.execute(query1).fetchall()\nprint(f\"QUESTION1: There are {result1[0][0]} rows. \\n\")\n\n#How many users who reviewed at least 100 Nature in the category also reviewed at least 100 in the Shopping category?\nquery2 = \"SELECT COUNT(Nature>=100), COUNT(Shopping>=100) FROM buddymove_holidayiq WHERE Nature = Shopping\"\nalt_query = \"\"\"\nSELECT COUNT (*)\nFROM buddymove_holidayiq\nWHERE NATURE >=100 AND Shopping >=100 \n\"\"\"\nresult_alt = cursor.execute(alt_query).fetchall()\nresult2 = cursor.execute(query2).fetchall()\nprint(f\"QUESTION 2:There are {result2[0][0]} where the review for Nature and Shopping are both at least 100.\\n\")\nprint(f\"QUESTION 2:There are {result_alt[0][0]} where the review for Nature and Shopping are both at least 100.\\n\")\n\n\n\n #(Stretch) What are the average number of reviews for each category?\nsports = \"SELECT AVG(Sports) FROM buddymove_holidayiq\"\nreligious = \"SELECT AVG(Religious) FROM buddymove_holidayiq\"\nnature = \"SELECT AVG(Nature) FROM buddymove_holidayiq\"\ntheatre = \"SELECT AVG(Theatre) FROM buddymove_holidayiq\"\nshopping = \"SELECT AVG(Shopping) FROM buddymove_holidayiq\"\npicnic = \"SELECT AVG(Picnic) FROM buddymove_holidayiq\"\n\nprint('STRETCH')\nsports_query = cursor.execute(sports).fetchall()\nprint(f\"There average sports review is {(sports_query[0][0]):.0f}\")\nreligious_query = cursor.execute(religious).fetchall()\nprint(f\"There average sports review is {(religious_query[0][0]):.0f}\")\nnature_query = cursor.execute(nature).fetchall()\nprint(f\"There average sports review is {(nature_query[0][0]):.0f}\")\ntheatre_query = cursor.execute(theatre).fetchall()\nprint(f\"There average sports review is {(theatre_query[0][0]):.0f}\")\nshopping_query = cursor.execute(shopping).fetchall()\nprint(f\"There average sports review is {(shopping_query[0][0]):.0f}\")\npicnic_query = cursor.execute(picnic).fetchall()\nprint(f\"There average sports review is {(picnic_query[0][0]):.0f}\")\n\n\n","sub_path":"module1-introduction-to-sql/buddy/buddymove_holidayiq.py","file_name":"buddymove_holidayiq.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"235061191","text":"from pulsar.predictor import Polyco\n\nt0 = fh.tell(unit='time')\nt_GP = Time('2015-10-18T23:41:53.316550')\n\npsr_polyco = Polyco('oct_polycob0531_ef.dat')\nphase_pol = psr_polyco.phasepol(t0)\n\nphase = np.remainder(phase_pol(t_GP.mjd), 1)\n\n","sub_path":"EVN_crab/PolycoExample.py","file_name":"PolycoExample.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"180477462","text":"\"\"\"\r\n create by Fred on 2018/8/22\r\n\"\"\"\r\nimport numpy as np\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.metrics import roc_curve\r\nfrom app.config.settings import GLOBAL_PAGE_SIZE\r\nfrom app.utils.json import to_json\r\nfrom app.utils.logger import Logger\r\nfrom app.dto.points import XYPoints\r\nfrom app.dto.rocaucresult import RocAucResult\r\nfrom app.repository.pymysql.modelestimatemysqlrepository import ModelEstimateMysqlRepository\r\nfrom app.repository.pymysql.samplemysqlrepository import SampleMysqlRepository\r\n\r\nimport json\r\n\r\n__author__ = 'Fred'\r\n\r\n\r\nrepository = ModelEstimateMysqlRepository()\r\n\r\n\r\n# calculate ROC and AUC\r\nclass ROCAUCCalculateService:\r\n\r\n @classmethod\r\n def cal_roc_auc(cls, v_sample_ids, v_model_id, v_strategy_id):\r\n sample_id_list = v_sample_ids.split(',')\r\n roc_auc_result = list()\r\n for sample_id in sample_id_list:\r\n roc_auc = ROCAUCCalculateService.cal_roc_auc_per_sample(sample_id, v_model_id, v_strategy_id)\r\n if roc_auc is not None:\r\n roc_auc_result.append(roc_auc)\r\n return roc_auc_result\r\n\r\n @classmethod\r\n def cal_roc_auc_per_sample(cls, v_sample_id, v_model_id, v_strategy_id):\r\n if v_strategy_id is not None and len(v_strategy_id) > 0:\r\n return ROCAUCCalculateService.cal_roc_auc_by_strategy(v_sample_id, v_model_id, v_strategy_id)\r\n else:\r\n return ROCAUCCalculateService.cal_roc_auc_by_model(v_sample_id, v_model_id)\r\n\r\n @classmethod\r\n def cal_roc_auc_by_model(cls, v_sample_id, v_model_id):\r\n # get data from data base\r\n current_page = 1\r\n all_sample_records = []\r\n while True:\r\n sample_page_list = ModelEstimateMysqlRepository\\\r\n .query_sample_model_records_paginate(v_sample_id, v_model_id, GLOBAL_PAGE_SIZE, current_page, False)\r\n if sample_page_list is not None and len(sample_page_list) > 0:\r\n for item in sample_page_list:\r\n all_sample_records.append(item)\r\n current_page = current_page + 1\r\n else:\r\n break\r\n # calculate\r\n return ROCAUCCalculateService.cal_roc_auc_by_all_sample(v_sample_id, all_sample_records)\r\n\r\n @classmethod\r\n def cal_roc_auc_by_strategy(cls, v_sample_id, v_model_id, v_strategy_id):\r\n # get data from data base\r\n current_page = 1\r\n all_sample_records = []\r\n while True:\r\n sample_page_list = ModelEstimateMysqlRepository.query_sample_model_strategy_records_paginate(\r\n v_sample_id, v_model_id, v_strategy_id, GLOBAL_PAGE_SIZE, current_page, False)\r\n if sample_page_list is not None and len(sample_page_list) > 0:\r\n for item in sample_page_list:\r\n all_sample_records.append(item)\r\n current_page = current_page + 1\r\n else:\r\n break\r\n # calculate\r\n return ROCAUCCalculateService.cal_roc_auc_by_all_sample(v_sample_id, all_sample_records)\r\n\r\n @classmethod\r\n def cal_roc_auc_by_all_sample(cls, v_sample_id, all_sample_records):\r\n\r\n if all_sample_records is None or len(all_sample_records) <= 0:\r\n return None\r\n\r\n # put sample result and pre estimate score to different list.\r\n y_true_result = []\r\n y_scores = []\r\n for item in all_sample_records:\r\n if item[1] is not None and item[2] is not None: # remove all invalid sample\r\n y_scores.append(item[1])\r\n y_true_result.append(int(item[2]))\r\n\r\n # call sklearn to calculate roc and auc, then put the result to RocAucResult and load as a json\r\n Logger.debug(to_json(y_true_result))\r\n Logger.debug(to_json(y_scores))\r\n fpr, tpr, _ = roc_curve(np.array(y_true_result), np.array(y_scores))\r\n Logger.debug(tpr)\r\n Logger.debug(fpr)\r\n\r\n auc = roc_auc_score(np.array(y_true_result), np.array(y_scores))\r\n Logger.debug(to_json(auc))\r\n\r\n # encapsulate fpr, tpr and auc to RocAucResult\r\n roc_points = []\r\n index = 0\r\n fpr_size = len(fpr)\r\n while index < fpr_size:\r\n point = XYPoints(round(fpr[index], 2), round(tpr[index], 2)) # fpr is x axis, tpr is y axis\r\n roc_points.append(json.loads(json.dumps(point, default=lambda o: o.__dict__, sort_keys=True, indent=4)))\r\n index = index + 1\r\n\r\n roc_auc = RocAucResult(None, None, roc_points, round(auc, 2))\r\n\r\n roc_auc.sample_id = v_sample_id\r\n sample_model = SampleMysqlRepository.query_sample_by_id(v_sample_id)\r\n roc_auc.sample_name = sample_model.name\r\n Logger.debug(to_json(json.loads(json.dumps(roc_auc, default=lambda o: o.__dict__, sort_keys=True, indent=4))))\r\n # return\r\n return roc_auc\r\n","sub_path":"pyaiservice_backup/app/service/rocauccalculateservice.py","file_name":"rocauccalculateservice.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"392093640","text":"#!/bin/python3\n\n########################################################################################################################\n# 功能:连接db2\n# 说明:connect必须携带参数\n#\n########################################################################################################################\n\nimport tools\nfrom AccuradSite import settings\n\n\ndef run(request, param):\n state, dbinfo = tools.getDBConf(\"DB\")\n if not state:\n return tools.response(-1, dbinfo)\n\n db = tools.database(**dbinfo)\n db.printing = True\n\n # 执行方式\n settings.LOCK.acquire()\n try:\n # ############################ 结构化操作数据库 ############################ #\n # 结构化查询select\n entries1 = db.select(\"test\", what=\"a,c,d\", where=\"a='fad'\", order=\"d desc\", limit=2)\n\n # 结构化单行插入insert\n entries2 = db.insert(\"test\", a=\"sigal\", b=\"n\", c=0, d=10.1)\n # print(\"entries2: \", entries2)\n\n # 结构化多行插入multiple_insert\n db.supports_multiple_insert = True\n values = [{\"A\": \"muti1\", \"B\": \"p\", \"C\": 6, \"D\": 11.1}, {\"A\": \"muti2\", \"B\": \"q\", \"C\": 6, \"D\": 11.2},\n {\"A\": \"muti3\", \"B\": \"r\", \"C\": 6, \"D\": 11.3}]\n entries3 = db.multiple_insert(\"test\", values=values)\n\n # 结构化更新update\n entries4 = db.update(\"test\", where=\"A='fad'\", B='mn', C=2)\n\n # 结构化删除delete\n entries5 = db.delete(\"test\", where=\"A='ferry'\")\n\n # ############################ 非结构化操作数据库, 可以执行复杂操作, 查询语句返回storage结果集, 其他返回影响行数 ############################ #\n sql = \"\"\"select m.A, m.B, m.C, m.D, n.F, n.G from test m, test1 n where m.A = n.E \"\"\"\n sql = \"\"\"INSERT INTO test(a, b, c, d) VALUES ('abc', 'n', 0, 10.1)\"\"\"\n entries6 = db.exec(sql)\n except Exception as e:\n print('执行sql failed! [%s]' % str(e))\n settings.LOCK.release()\n raise\n settings.LOCK.release()\n\n # 结果打包成json\n jsonData = tools.storage2Json(entries1)\n\n return tools.response(0, '', jsonData)\n\n","sub_path":"api/example/connectDB2.py","file_name":"connectDB2.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"226424499","text":"# -*- coding:utf-8 -*-\n# @Desc : \n# @Author : Administrator\n# @Date : 2019-07-18 11:27\n\n# 美化输出\n# import requests\n# from pprint import pprint # 格式化输入内容\n# headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0\"}\n# url = 'http://httpbin.org/get'\n# response = requests.get(url, headers=headers)\n# result = response.content.decode(\"utf-8\")\n# print(result, type(result)) # str\n\n################################################################################################\n\n# JSON支持数据格式:\n# 1. 对象(字典),使用{}\n# 2. 数组(列表),使用[]\n# 3. 整数(int),浮点数(float),布尔(boolean)\n# 4. 字符串类型(字符串必须要用双引号,不能使用单引号)\n# 多个数据之间用逗号分开,注:Json本质上就是一个字符串\n\n# Json: 用于各种语言之间的字符转换,对于Python语言只能对基本数据类型进行转换\n# 如: Python语言中的字典(dict),列表(list),元组(tuple),字符串(str)等基本数据类型\n# Json模块提供了四个方法: dumps()、dump()、loads()、load()\n\n# pickle: 仅支持Python语言,对于Python语言中的所有数据类型进行转换\n# 如: Python语言中的特殊数据类型: 对象等\n# pickle模块提供了四个方法:dumps()、dump()、loads()、load()\n\n# 序列化数据:(如,dumps()) Python数据 ---> 字符串\n# 反序列化数据:(如,loads()) 字符串 ---> Python数据\n\n\n\nimport json\nimport pickle\n\nbooks_dict = {\n \"1\":{\n \"title\": \"十万个为什么\",\n \"price\": 49\n },\n \"2\":{\n \"title\": \"学习Python编程\",\n \"price\": 49\n }\n}\nbooks_list = [\n {\n \"title\": \"十万个为什么\",\n \"price\": 49\n },\n {\n \"title\": \"学习Python编程\",\n \"price\": 49\n }\n]\n# print(books_dict,type(books_dict)) # \n# print(books_list,type(books_list)) # \n\n### json.dumps()把Python数据转换成Json字符串\n# 字典类型数据转换成Json数据\njson_str1 = json.dumps(books_dict,ensure_ascii=False)\n# print(json_str1,type(json_str1)) # \n# 列表类型数据转换成Json数据\njson_str2 = json.dumps(books_list,ensure_ascii=False)\n# print(json_str2,type(json_str2)) # \n\n### json.dump()把Python数据[字典]写入到文件中\nwith open(\"response_dict.json\",\"w\",encoding='utf-8') as fp:\n json.dump(books_dict,fp,ensure_ascii=False) # 把字典类型数据直接写入到文件中\n # fp.write(json_str1) # 把转换成json的数据写入文件中\n\n### json.dump()把Python数据[列表]写入到文件中\nwith open(\"response_list.json\",\"w\",encoding='utf-8') as fp:\n json.dump(books_list,fp,ensure_ascii=False) # 把字典类型数据直接写入到文件中\n # fp.write(json_str2) # 把转换成json的数据写入文件中\n\n\n\n### Json数据转换成字典,列表: json.loads()\n# Json数据转换成字典类型\njson_dict = json.loads(json_str1)\n# print(json_dict,type(json_dict))\n# Json数据转换成列表类型\njson_list = json.loads(json_str2)\n# print(json_list,type(json_list))\n\n### json.load()把文件中的数据提取出来转换成Python数据[字典]\nwith open(\"response_dict.json\",encoding='utf-8') as fp:\n fp_dict = json.load(fp) # 使用json从文件中读取出来的数据为Python数据格式[与写入时的数据类型一致]\n # fp_dict = fp.read() # 使用文件对象从文件中读取出来的数据为str字符串类型\n # print(fp_dict,type(fp_dict))\n\n### json.load()把文件中的数据提取出来转换成Python数据[列表]\nwith open(\"response_list.json\",encoding='utf-8') as fp:\n fp_list = json.load(fp) # 使用json从文件中读取出来的数据为Python数据格式[与写入时的数据类型一致]\n # fp_list = fp.read() # 使用文件对象从文件中读取出来的数据为str字符串类型\n # print(fp_list, type(fp_list))\n\n\n##########################################################################################################\n\n\n\n","sub_path":"[03]Python-基础知识部分/20Python-json与pickle数据转换.py","file_name":"20Python-json与pickle数据转换.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"437170961","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# Date: 2018/5/5\n\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nprint(logger.handlers)\n\nlogger.addHandler(\"添加你的 `handler`\")\n\nlogger.removeHandler(\"删除你的 `handler`\")\n\nlogger.pop()\n","sub_path":"20180504/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"64220006","text":"#!/usr/bin/env python\n\"\"\"\nEvaluate deep surface features by computing the minimum distance from each\nlabel border vertex to all of the feature vertices in the same sulcus.\nThe label borders run along the deepest parts of many sulci and\ncorrespond to fundi in the DKT cortical labeling protocol.\n\nExamples\n--------\n$ python evaluate_features.py\n\n\nAuthors:\n - Yrjo Hame, 2012 (yrjo.hame@gmail.com)\n - Arno Klein, 2012-2015 (arno@mindboggle.info) http://binarybottle.com\n\nCopyright 2015, Mindboggle team (http://mindboggle.info), Apache v2.0 License\n\n\"\"\"\n\ndef evaluate_deep_features(features_file, labels_file, sulci_file='', hemi='',\n excludeIDs=[-1], output_vtk_name='', verbose=True):\n \"\"\"\n Evaluate deep surface features by computing the minimum distance from each\n label border vertex to all of the feature vertices in the same sulcus,\n and from each feature vertex to all of the label border vertices in the\n same sulcus. The label borders run along the deepest parts of sulci\n and correspond to fundi in the DKT cortical labeling protocol.\n\n Parameters\n ----------\n features_file : string\n VTK surface file with feature numbers for vertex scalars\n labels_file : string\n VTK surface file with label numbers for vertex scalars\n sulci_file : string\n VTK surface file with sulcus numbers for vertex scalars\n excludeIDs : list of integers\n feature/sulcus/label IDs to exclude (background set to -1)\n output_vtk_name : Boolean\n if not empty, output a VTK file beginning with output_vtk_name that\n contains a surface with mean distances as scalars\n verbose : Boolean\n print mean distances to standard output?\n\n Returns\n -------\n feature_to_border_mean_distances : numpy array [number of features x 1]\n mean distance from each feature to sulcus label border\n feature_to_border_sd_distances : numpy array [number of features x 1]\n standard deviations of feature-to-border distances\n feature_to_border_distances_vtk : string\n VTK surface file containing feature-to-border distances\n border_to_feature_mean_distances : numpy array [number of features x 1]\n mean distances from each sulcus label border to feature\n border_to_feature_sd_distances : numpy array [number of features x 1]\n standard deviations of border-to-feature distances\n border_to_feature_distances_vtk : string\n VTK surface file containing border-to-feature distances\n\n \"\"\"\n import os\n import sys\n import numpy as np\n from mindboggle.mio.vtks import read_vtk, read_scalars, write_vtk\n from mindboggle.guts.mesh import find_neighbors, remove_faces\n from mindboggle.guts.segment import extract_borders\n from mindboggle.guts.compute import source_to_target_distances\n from mindboggle.mio.labels import DKTprotocol\n\n dkt = DKTprotocol()\n #-------------------------------------------------------------------------\n # Load labels, features, and sulci:\n #-------------------------------------------------------------------------\n faces, lines, indices, points, npoints, labels, scalar_names, \\\n input_vtk = read_vtk(labels_file, True, True)\n features, name = read_scalars(features_file, True, True)\n if sulci_file:\n sulci, name = read_scalars(sulci_file, True, True)\n # List of indices to sulcus vertices:\n sulcus_indices = [i for i,x in enumerate(sulci) if x != -1]\n segmentIDs = sulci\n sulcus_faces = remove_faces(faces, sulcus_indices)\n else:\n sulcus_indices = range(len(labels))\n segmentIDs = []\n sulcus_faces = faces\n\n #-------------------------------------------------------------------------\n # Prepare neighbors, label pairs, border IDs, and outputs:\n #-------------------------------------------------------------------------\n # Calculate neighbor lists for all points:\n print('Find neighbors for all vertices...')\n neighbor_lists = find_neighbors(faces, npoints)\n\n # Find label border points in any of the sulci:\n print('Find label border points in any of the sulci...')\n border_indices, border_label_tuples, unique_border_label_tuples = \\\n extract_borders(sulcus_indices, labels, neighbor_lists,\n ignore_values=[], return_label_pairs=True)\n if not len(border_indices):\n sys.exit('There are no label border points!')\n\n # Initialize an array of label border IDs\n # (label border vertices that define sulci in the labeling protocol):\n print('Build an array of label border IDs...')\n label_borders = -1 * np.ones(npoints)\n\n if hemi == 'lh':\n nsulcus_lists = len(dkt.left_sulcus_label_pair_lists)\n else:\n nsulcus_lists = len(dkt.right_sulcus_label_pair_lists)\n feature_to_border_mean_distances = -1 * np.ones(nsulcus_lists)\n feature_to_border_sd_distances = -1 * np.ones(nsulcus_lists)\n border_to_feature_mean_distances = -1 * np.ones(nsulcus_lists)\n border_to_feature_sd_distances = -1 * np.ones(nsulcus_lists)\n feature_to_border_distances_vtk = ''\n border_to_feature_distances_vtk = ''\n\n #-------------------------------------------------------------------------\n # Loop through sulci:\n #-------------------------------------------------------------------------\n # For each list of sorted label pairs (corresponding to a sulcus):\n for isulcus, label_pairs in enumerate(dkt.sulcus_label_pair_lists):\n\n # Keep the border points with label pair labels:\n label_pair_border_indices = [x for i,x in enumerate(border_indices)\n if np.unique(border_label_tuples[i]).tolist()\n in label_pairs]\n\n # Store the points as sulcus IDs in the border IDs array:\n if label_pair_border_indices:\n label_borders[label_pair_border_indices] = isulcus\n\n if len(np.unique(label_borders)) > 1:\n\n #---------------------------------------------------------------------\n # Construct a feature-to-border distance matrix and VTK file:\n #---------------------------------------------------------------------\n # Construct a distance matrix:\n print('Construct a feature-to-border distance matrix...')\n sourceIDs = features\n targetIDs = label_borders\n distances, distance_matrix = source_to_target_distances(\n sourceIDs, targetIDs, points, segmentIDs, excludeIDs)\n\n # Compute mean distances for each feature:\n nfeatures = min(np.shape(distance_matrix)[1], nsulcus_lists)\n for ifeature in range(nfeatures):\n feature_distances = [x for x in distance_matrix[:, ifeature]\n if x != -1]\n feature_to_border_mean_distances[ifeature] = \\\n np.mean(feature_distances)\n feature_to_border_sd_distances[ifeature] = \\\n np.std(feature_distances)\n\n if verbose:\n print('Feature-to-border mean distances:')\n print(feature_to_border_mean_distances)\n print('Feature-to-border standard deviations of distances:')\n print(feature_to_border_sd_distances)\n\n # Write resulting feature-label border distances to VTK file:\n if output_vtk_name:\n feature_to_border_distances_vtk = os.path.join(os.getcwd(),\n output_vtk_name + '_feature_to_border_mean_distances.vtk')\n print('Write feature-to-border distances to {0}...'.\n format(feature_to_border_distances_vtk))\n write_vtk(feature_to_border_distances_vtk, points,\n [], [], sulcus_faces, [distances],\n ['feature-to-border_distances'], 'float')\n\n #---------------------------------------------------------------------\n # Construct a border-to-feature distance matrix and VTK file:\n #---------------------------------------------------------------------\n # Construct a distance matrix:\n print('Construct a border-to-feature distance matrix...')\n sourceIDs = label_borders\n targetIDs = features\n distances, distance_matrix = source_to_target_distances(\n sourceIDs, targetIDs, points, segmentIDs, excludeIDs)\n\n # Compute mean distances for each feature:\n nfeatures = min(np.shape(distance_matrix)[1], nsulcus_lists)\n for ifeature in range(nfeatures):\n border_distances = [x for x in distance_matrix[:, ifeature]\n if x != -1]\n border_to_feature_mean_distances[ifeature] = \\\n np.mean(border_distances)\n border_to_feature_sd_distances[ifeature] = \\\n np.std(border_distances)\n\n if verbose:\n print('border-to-feature mean distances:')\n print(border_to_feature_mean_distances)\n print('border-to-feature standard deviations of distances:')\n print(border_to_feature_sd_distances)\n\n # Write resulting feature-label border distances to VTK file:\n if output_vtk_name:\n border_to_feature_distances_vtk = os.path.join(os.getcwd(),\n output_vtk_name + '_border_to_feature_mean_distances.vtk')\n print('Write border-to-feature distances to {0}...'.\n format(border_to_feature_distances_vtk))\n write_vtk(border_to_feature_distances_vtk, points,\n [], [], sulcus_faces, [distances],\n ['border-to-feature_distances'], 'float')\n\n #-------------------------------------------------------------------------\n # Return outputs:\n #-------------------------------------------------------------------------\n return feature_to_border_mean_distances, feature_to_border_sd_distances,\\\n feature_to_border_distances_vtk,\\\n border_to_feature_mean_distances, border_to_feature_sd_distances,\\\n border_to_feature_distances_vtk\n\n\n#-----------------------------------------------------------------------------\n# Run evaluate_deep_features() on fundi extracted from Mindboggle-101 data\n# by Mindboggle, and Forrest Bao's, Gang Li's, and Olivier Coulon's methods.\n#-----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\n import os\n import numpy as np\n\n from mindboggle.evaluate.evaluate_features import evaluate_deep_features\n\n #-------------------------------------------------------------------------\n # Set feature type ('fundi' or '' for every sulcus vertex), subjects:\n #-------------------------------------------------------------------------\n feature_type = 'fundi' #'sulci' # If 'fundi', select 'nmethod' below.\n names = ['OASIS-TRT-20', 'MMRR-21', 'NKI-RS-22', 'NKI-TRT-20',\n 'Afterthought', 'Colin27', 'Twins-2', 'MMRR-3T7T-2', 'HLN-12']\n numbers = [20,21,22,20, 1,1,2,2,12]\n mindboggled = '/mnt/nfs-share/Mindboggle101/mindboggled/manual'\n labels_dir = '/mnt/nfs-share/Mindboggle101/mindboggled/manual' \n\n #-------------------------------------------------------------------------\n # Feature-specific settings:\n #-------------------------------------------------------------------------\n if feature_type == 'fundi':\n # Features: fundus method:\n # 0 = mindboggle\n # 1 = forrest scalars\n # 2 = forrest lines\n # 3 = gang li\n # 4 = olivier coulon\n nmethod = 0\n feature_dir = '/homedir/fundus_evaluation_2014/fundi_vtk'\n fmethods = ['mindboggle_fundi',\n 'ForrestBao_scalar_fundi',\n 'ForrestBao_line_fundi',\n 'GangLi_fundi',\n 'OlivierCoulon_fundi']\n fmethod_dirs = [mindboggled,\n os.path.join(feature_dir, fmethods[1]),\n os.path.join(feature_dir, fmethods[2]),\n os.path.join(feature_dir, fmethods[3]),\n os.path.join(feature_dir, fmethods[4])]\n fmethod_dir = fmethod_dirs[nmethod]\n fmethod = fmethods[nmethod]\n else:\n fmethod = 'all'\n\n #-------------------------------------------------------------------------\n # Miscellaneous defaults:\n #-------------------------------------------------------------------------\n surfs = ['left_cortical_surface', 'right_cortical_surface']\n hemis = ['lh', 'rh']\n nsulci = 25\n\n #-------------------------------------------------------------------------\n # Loop through subjects and hemispheres:\n #-------------------------------------------------------------------------\n nsubjects = sum(numbers)\n feature_to_border_mean_distances_left = -1 * np.ones((nsubjects, nsulci))\n feature_to_border_sd_distances_left = -1 * np.ones((nsubjects, nsulci))\n border_to_feature_mean_distances_left = -1 * np.ones((nsubjects, nsulci))\n border_to_feature_sd_distances_left = -1 * np.ones((nsubjects, nsulci))\n feature_to_border_mean_distances_right = -1 * np.ones((nsubjects, nsulci))\n feature_to_border_sd_distances_right = -1 * np.ones((nsubjects, nsulci))\n border_to_feature_mean_distances_right = -1 * np.ones((nsubjects, nsulci))\n border_to_feature_sd_distances_right = -1 * np.ones((nsubjects, nsulci))\n isubject = 0\n for iname, name in enumerate(names):\n number = numbers[iname]\n for n in range(1, number+1):\n subject = name+'-'+str(n)\n for isurf, surf in enumerate(surfs):\n hemi = hemis[isurf]\n #print('{0}: {1}'.format(subject, hemi))\n #-------------------------------------------------------------\n # Identify surface files with labels and with sulci:\n #-------------------------------------------------------------\n mdir = os.path.join(mindboggled, subject)\n ldir = os.path.join(labels_dir, subject)\n sulci_file = os.path.join(mdir, 'features', surf, 'sulci.vtk')\n labels_file = os.path.join(ldir, 'labels', surf,\n 'relabeled_labels.DKT31.manual.vtk')\n #-------------------------------------------------------------\n # Identify features file:\n #-------------------------------------------------------------\n if feature_type == 'fundi':\n if nmethod == 0:\n features_file = os.path.join(mdir, 'features', surf,\n 'fundus_per_sulcus.vtk')\n else:\n features_file = os.path.join(fmethod_dir,\n '_hemi_' + hemi + '_subject_' + name + '-' + str(n),\n hemi + '.pial.fundi.vtk')\n else:\n features_file = sulci_file\n #if not os.path.exists(features_file):\n # print(features_file)\n\n #-------------------------------------------------------------\n # Compute distances between features and label borders\n # in sulci corresponding to fundi:\n #-------------------------------------------------------------\n if os.path.exists(features_file) \\\n and os.path.exists(labels_file) \\\n and os.path.exists(sulci_file):\n feature_to_border_mean_distances, \\\n feature_to_border_sd_distances,\\\n feature_to_border_distances_vtk,\\\n border_to_feature_mean_distances, \\\n border_to_feature_sd_distances,\\\n border_to_feature_distances_vtk = \\\n evaluate_deep_features(features_file, labels_file,\n sulci_file, hemi, excludeIDs=[-1],\n output_vtk_name=subject+'_'+hemi+'_'+fmethod,\n verbose=True)\n print('*' * 79)\n\n if isurf == 0:\n feature_to_border_mean_distances_left[isubject, :] = \\\n feature_to_border_mean_distances\n feature_to_border_sd_distances_left[isubject, :] = \\\n feature_to_border_sd_distances\n border_to_feature_mean_distances_left[isubject, :] = \\\n border_to_feature_mean_distances\n border_to_feature_sd_distances_left[isubject, :] = \\\n border_to_feature_sd_distances\n else:\n feature_to_border_mean_distances_right[isubject, :] = \\\n feature_to_border_mean_distances\n feature_to_border_sd_distances_right[isubject, :] = \\\n feature_to_border_sd_distances\n border_to_feature_mean_distances_right[isubject, :] = \\\n border_to_feature_mean_distances\n border_to_feature_sd_distances_right[isubject, :] = \\\n border_to_feature_sd_distances\n\n isubject += 1\n\n #-------------------------------------------------------------------------\n # Save tables of mean distances:\n #-------------------------------------------------------------------------\n np.savetxt(fmethod + '_mean_distances_to_border_left.csv',\n feature_to_border_mean_distances_left)\n np.savetxt(fmethod + '_sd_distances_to_border_left.csv',\n feature_to_border_sd_distances_left)\n np.savetxt(fmethod + '_mean_distances_from_border_left.csv',\n border_to_feature_mean_distances_left)\n np.savetxt(fmethod + '_sd_distances_from_border_left.csv',\n border_to_feature_sd_distances_left)\n\n np.savetxt(fmethod + '_mean_distances_to_border_right.csv',\n feature_to_border_mean_distances_right)\n np.savetxt(fmethod + '_sd_distances_to_border_right.csv',\n feature_to_border_sd_distances_right)\n np.savetxt(fmethod + '_mean_distances_from_border_right.csv',\n border_to_feature_mean_distances_right)\n np.savetxt(fmethod + '_sd_distances_from_border_right.csv',\n border_to_feature_sd_distances_right)\n\n # #-------------------------------------------------------------------------\n # # Save tables of mean distances averaged across all subjects:\n # # NOTE: np.mean() results in nan's if any element has a nan.\n # #-------------------------------------------------------------------------\n # mean_feature_to_border_mean_distances_left = \\\n # np.mean(feature_to_border_mean_distances_left, axis=0)\n # mean_feature_to_border_sd_distances_left = \\\n # np.mean(feature_to_border_mean_distances_left, axis=0)\n # mean_border_to_feature_mean_distances_left = \\\n # np.mean(border_to_feature_mean_distances_left, axis=0)\n # mean_border_to_feature_sd_distances_left = \\\n # np.mean(border_to_feature_mean_distances_left, axis=0)\n #\n # mean_feature_to_border_mean_distances_right = \\\n # np.mean(feature_to_border_mean_distances_right, axis=0)\n # mean_feature_to_border_sd_distances_right = \\\n # np.mean(feature_to_border_mean_distances_right, axis=0)\n # mean_border_to_feature_mean_distances_right = \\\n # np.mean(border_to_feature_mean_distances_right, axis=0)\n # mean_border_to_feature_sd_distances_right = \\\n # np.mean(border_to_feature_mean_distances_right, axis=0)\n #\n # np.savetxt('avg_per_fundus_' + fmethod + '_mean_distances_to_border_left.csv',\n # mean_feature_to_border_mean_distances_left)\n # np.savetxt('avg_per_fundus_' + fmethod + '_sd_distances_to_border_left.csv',\n # mean_feature_to_border_sd_distances_left)\n # np.savetxt('avg_per_fundus_' + fmethod + '_mean_distances_from_border_left.csv',\n # mean_border_to_feature_mean_distances_left)\n # np.savetxt('avg_per_fundus_' + fmethod + '_sd_distances_from_border_left.csv',\n # mean_border_to_feature_sd_distances_left)\n #\n # np.savetxt('avg_per_fundus_' + fmethod + '_mean_distances_to_border_right.csv',\n # mean_feature_to_border_mean_distances_right)\n # np.savetxt('avg_per_fundus_' + fmethod + '_sd_distances_to_border_right.csv',\n # mean_feature_to_border_sd_distances_right)\n # np.savetxt('avg_per_fundus_' + fmethod + '_mean_distances_from_border_right.csv',\n # mean_border_to_feature_mean_distances_right)\n # np.savetxt('avg_per_fundus_' + fmethod + '_sd_distances_from_border_right.csv',\n # mean_border_to_feature_sd_distances_right)\n","sub_path":"mindboggle/evaluate/evaluate_features.py","file_name":"evaluate_features.py","file_ext":"py","file_size_in_byte":20848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"518352670","text":"import argparse\nimport sys, os\nimport random\nimport csv, pandas\nimport numpy as np\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-t\", \"--template\", type=str, required=True)\n parser.add_argument(\"-d\", \"--directory\", type=str, default=\"full_data\")\n parser.add_argument(\"-o\", \"--output\", type=str, default=\"tasks\")\n parser.add_argument(\"-n\", \"--number\", type=int, default=600)\n args = parser.parse_args()\n\n path = f\"{args.directory}/{args.template}.tsv\"\n if not os.path.exists(path):\n sys.exit(f\"{args.template}.tsv does not exist in {args.directory}.\\n\"\\\n f\"Data for {args.template} can be generated with\\n\"\\\n f\"python generate_tasks.py -t {args.template}\")\n\n if not os.path.exists(args.output):\n os.makedirs(args.output)\n\n # Load data and convert all integers to strings\n data = pandas.read_csv(path, sep=\"\\t\", header=0).applymap(str)\n header = data.columns.values\n nums = sum(\"number\" in col for col in header)\n\n separated_conditions, amounts = [], []\n options = [\"singular\", \"plural\"]\n\n # First separate all conditions in a list by filtering on each combination\n # of grammatical numbers\n\n # E.g., simple, qnty_simple, namepp\n if nums == 1:\n for num1 in options:\n curr_condition = data.loc[data[\"number1\"] == num1]\n separated_conditions.append(curr_condition)\n amounts.append(min(args.number, len(curr_condition)))\n\n # E.g., nounpp, that\n elif nums == 2:\n for num1 in options:\n for num2 in options:\n curr_condition = data.loc[(data[\"number1\"] == num1) &\\\n (data[\"number2\"] == num2)]\n separated_conditions.append(curr_condition)\n amounts.append(min(args.number, len(curr_condition)))\n\n # E.g., that_nounpp\n elif nums == 3:\n for num1 in options:\n for num2 in options:\n for num3 in options:\n curr_condition = data.loc[(data[\"number1\"] == num1) &\\\n (data[\"number2\"] == num2) &\\\n (data[\"number3\"] == num3)]\n separated_conditions.append(curr_condition)\n amounts.append(min(args.number, len(curr_condition)))\n\n else:\n sys.exit(\"Number of conditions is incorrect. Please check the template.\")\n\n # Make sure the dataset is balanced, i.e. same amount for each condition\n max_allowed_per_condition = min(amounts)\n header = list(data)\n\n # For sentence sampling\n random.seed()\n\n with open(os.path.join(args.output, f\"{args.template}.tsv\"), \"w\") as f:\n f.write(\"\\t\".join(header) + \"\\n\")\n for c in separated_conditions:\n sentences = c.values.tolist()\n sampled = random.sample(sentences, max_allowed_per_condition)\n\n for s in sampled:\n f.write(\"\\t\".join(s) + \"\\n\")\n\n print(f\"Sampled {max_allowed_per_condition} sentences per condition\")\n","sub_path":"data/finalise_tasks.py","file_name":"finalise_tasks.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"34054749","text":"#!/usr/bin/env python3\n\nimport urequests\nimport machine\nimport utime\ntry:\n import usocket as socket\nexcept:\n import socket\ntry:\n import ustruct as struct\nexcept:\n import struct\n\nclass TimeTank:\n __resthost = ''\n __deviceid = ''\n\n # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60\n #addBST = 3600 # BST\n addBST = 0 # GMT\n \n NTP_DELTA = 3155673600 - addBST\n\n __hostpointer = 0\n __host = \"{0}.uk.pool.ntp.org\"\n\n def __init__(self, resthost='', deviceid=0):\n self.__resthost = resthost\n self.__deviceid = deviceid\n\n def __call__(self):\n pass\n\n def gettime(self):\n try:\n # cycle through the different uk.pool.ntp.org servers\n temphost = self.__host.replace('{0}', str(self.__hostpointer))\n print('Get time from: ' + temphost)\n\n self.__hostpointer += 1\n if self.__hostpointer > 3:\n self.__hostpointer = 0\n # cycle through the different uk.pool.ntp.org servers\n\n NTP_QUERY = bytearray(48)\n NTP_QUERY[0] = 0x1b\n addr = socket.getaddrinfo(temphost, 123)[0][-1]\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.settimeout(1)\n res = s.sendto(NTP_QUERY, addr)\n msg = s.recv(48)\n s.close()\n val = struct.unpack(\"!I\", msg[40:44])[0]\n\n return val - self.NTP_DELTA\n except OSError:\n\n return 0\n\n def settime(self, metheod=1):\n returnvalue = False\n\n if metheod == 0:\n url = \"http://192.168.86.240:5000/gettime/\"\n\n print(url)\n\n try:\n response = urequests.get(url)\n\n returnvalue = int(response.text.replace('\\\"', ''))\n\n response.close()\n except:\n print('Fail www connect: ' + url)\n\n # return returnvalue\n else:\n while self.gettime() == 0:\n print('Waiting for time...')\n\n t = self.gettime()\n try:\n tm = utime.localtime(t)\n tm = tm[0:3] + (0,) + tm[3:6] + (0,)\n\n machine.RTC().datetime(tm)\n\n print('tm[0:3]=' + str(tm[0:3]) + ' tm[3:6]=' + str(tm[3:6]))\n print('tm[0] = (' + str(tm[0]) + ')')\n print(utime.localtime())\n\n if int(tm[0]) != int(2000):\n returnvalue = True\n except:\n returnvalue = False\n\n return returnvalue\n\n","sub_path":"timeClass.py","file_name":"timeClass.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"20859798","text":"from django.shortcuts import render\nfrom .forms import *\nfrom products.models import *\n\n# Create your views here.\n\n\ndef landing(request):\n print(request.method)\n if request.POST:\n form = SubscriberForm(request.POST or None)\n if form.is_valid():\n form.save()\n print(form.cleaned_data)\n else:\n form = SubscriberForm()\n return render(request, 'landing/landing.html', locals())\n\n\ndef home(request):\n products_images = ProductImage.objects.filter(is_active=True, is_main=True, product__is_active=True)\n products_images_new = products_images[:4]\n products_images_phones = products_images.filter(product__product_category__category_name='Mobile Phones')\n products_images_laptops = products_images.filter(product__product_category__category_name='Laptops')\n return render(request, 'landing/home.html', locals())\n","sub_path":"landing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"607860669","text":"\"\"\"\nsnap.py - Building snaps from source and promoting them to snapstore\n\n\"\"\"\nimport sys\nimport click\nimport sh\nimport os\nimport yaml\nimport semver\nfrom urllib.parse import urlparse\nfrom jinja2 import Template\nfrom pathlib import Path\nfrom pymacaroons import Macaroon\nfrom lib import lp, idm, git, snapapi\n\n\ndef _render(tmpl_file, context):\n \"\"\" Renders a jinja template with context\n \"\"\"\n template = Template(tmpl_file.read_text(), keep_trailing_newline=True)\n return template.render(context)\n\n\n@click.group()\ndef cli():\n pass\n\n\ndef _sync_upstream(snap_list, starting_ver, force, patches, dry_run):\n \"\"\" Syncs the upstream k8s release tags with our snap branches\n\n Usage:\n snaps-source.py sync-upstream --snap-list includes/k8s-snap-list.inc\n \"\"\"\n supported_releases = []\n upstream_releases = git.remote_tags(\"https://github.com/kubernetes/kubernetes\")\n\n for rel in upstream_releases:\n _fmt_rel = rel.lstrip(\"v\")\n try:\n semver.parse(_fmt_rel)\n if semver.compare(_fmt_rel, starting_ver) >= 0:\n supported_releases.append(rel)\n except ValueError as error:\n click.echo(f\"Skipping invalid {_fmt_rel}: {error}\")\n\n snaps = yaml.safe_load(Path(snap_list).read_text(encoding=\"utf8\"))\n for snap in snaps:\n click.echo(f\"Checking: git+ssh://cdkbot@git.launchpad.net/snap-{snap}\")\n git_repo = f\"git+ssh://cdkbot@git.launchpad.net/snap-{snap}\"\n snap_releases = git.remote_branches(git_repo)\n if not set(supported_releases).issubset(set(snap_releases)):\n snap_releases = list(set(supported_releases).difference(set(snap_releases)))\n snap_releases.sort()\n for snap_rel in snap_releases:\n click.echo(f\"Creating branch for {snap}-{snap_rel}\")\n _create_branch(\n git_repo,\n \"master\",\n snap_rel,\n dry_run=False,\n force=force,\n patches=patches,\n )\n _fmt_version = semver.parse(snap_rel.lstrip(\"v\"))\n _fmt_version_str = f'{_fmt_version[\"major\"]}.{_fmt_version[\"minor\"]}'\n tracks_to_publish = []\n if _fmt_version[\"prerelease\"]:\n if \"rc\" in _fmt_version[\"prerelease\"]:\n click.echo(\n f\"This is a rc release, setting candidate tracks\"\n )\n tracks_to_publish = [\n f\"{_fmt_version_str}/candidate\",\n ]\n\n if \"beta\" in _fmt_version[\"prerelease\"]:\n click.echo(f\"This is a beta release, setting edge/beta tracks\")\n tracks_to_publish = [\n f\"{_fmt_version_str}/beta\",\n f\"{_fmt_version_str}/edge\",\n ]\n if \"alpha\" in _fmt_version[\"prerelease\"]:\n click.echo(f\"This is an alpha release, setting edge tracks\")\n tracks_to_publish = [f\"{_fmt_version_str}/edge\"]\n else:\n tracks_to_publish = [\n f\"{_fmt_version_str}/stable\",\n ]\n click.echo(f\"Generating recipe for {snap}-{_fmt_version_str}\")\n if not dry_run:\n _create_snap_recipe(\n snap=snap,\n version=_fmt_version_str,\n track=tracks_to_publish,\n owner=\"k8s-jenkaas-admins\",\n tag=snap_rel,\n repo=git_repo,\n dry_run=False,\n snap_recipe_email=os.environ.get(\"K8STEAMCI_USR\"),\n snap_recipe_password=os.environ.get(\"K8STEAMCI_PSW\"),\n )\n\n\n@cli.command()\n@click.option(\"--snap-list\", help=\"Path to supported snaps\", required=True)\n@click.option(\n \"--starting-ver\",\n help=\"Oldest k8s release to start from\",\n required=True,\n default=\"1.13.7\",\n)\n@click.option(\"--force\", is_flag=True)\n@click.option(\"--patches\", help=\"Path to patches list\", required=False)\n@click.option(\"--dry-run\", is_flag=True)\ndef sync_upstream(snap_list, starting_ver, force, patches, dry_run):\n return _sync_upstream(snap_list, starting_ver, force, patches, dry_run)\n\n\ndef _create_branch(repo, from_branch, to_branch, dry_run, force, patches):\n \"\"\" Creates a git branch based on the upstream snap repo and a version to branch as. This will also update\n the snapcraft.yaml with the correct version to build the snap from in that particular branch.\n\n These branches must already exist in https://github.com/kubernetes/kubernetes.\n\n Usage:\n\n snap.py branch --repo git+ssh://lp_git_user@git.launchpad.net/snap-kubectl \\\n --from-branch master \\\n --to-branch 1.13.2\n \"\"\"\n env = os.environ.copy()\n\n if git.branch_exists(repo, to_branch, env):\n click.echo(f\"{to_branch} already exists, skipping...\")\n sys.exit(0)\n\n snap_basename = urlparse(repo)\n snap_basename = Path(snap_basename.path).name\n if snap_basename.endswith(\".git\"):\n snap_basename = snap_basename.rstrip(\".git\")\n sh.rm(\"-rf\", snap_basename)\n sh.git.clone(repo, branch=from_branch, _env=env)\n sh.git.config(\"user.email\", \"cdkbot@gmail.com\", _cwd=snap_basename)\n sh.git.config(\"user.name\", \"cdkbot\", _cwd=snap_basename)\n sh.git.checkout(\"-b\", to_branch, _cwd=snap_basename)\n\n snapcraft_fn = Path(snap_basename) / \"snapcraft.yaml\"\n snapcraft_fn_tpl = Path(snap_basename) / \"snapcraft.yaml.in\"\n if not snapcraft_fn_tpl.exists():\n click.echo(f\"{snapcraft_fn_tpl} not found\")\n sys.exit(1)\n\n # Apply patches\n patches_list = []\n if patches:\n patches_path = Path(patches)\n if patches_path.exists():\n click.echo(\"Patches found, applying.\")\n patches_map = yaml.safe_load(patches_path.read_text(encoding=\"utf8\"))\n # TODO: cleanup\n if \"all\" in patches_map:\n for patch_fn in patches_map[\"all\"]:\n patch_fn = Path(patch_fn).absolute()\n shared_path = str(Path(\"shared\") / patch_fn.parts[-1])\n sh.cp(str(patch_fn), str(shared_path), _cwd=snap_basename)\n patches_list.append(shared_path)\n sh.git.add(shared_path, _cwd=snap_basename)\n if to_branch.lstrip(\"v\") in patches_map:\n for patch_fn in patches_map[to_branch.lstrip(\"v\")]:\n patch_fn = Path(patch_fn).absolute()\n shared_path = str(Path(\"shared\") / patch_fn.parts[-1])\n sh.cp(str(patch_fn), str(shared_path), _cwd=snap_basename)\n patches_list.append(shared_path)\n sh.git.add(shared_path, _cwd=snap_basename)\n\n snapcraft_yml = snapcraft_fn_tpl.read_text()\n snapcraft_yml = _render(\n snapcraft_fn_tpl,\n {\"snap_version\": to_branch.lstrip(\"v\"), \"patches\": patches_list},\n )\n snapcraft_fn.write_text(snapcraft_yml)\n if not dry_run:\n sh.git.add(\".\", _cwd=snap_basename)\n sh.git.commit(\"-m\", f\"Creating branch {to_branch}\", _cwd=snap_basename)\n sh.git.push(repo, to_branch, _cwd=snap_basename, _env=env)\n\n\n@cli.command()\n@click.option(\"--repo\", help=\"Git repository to create a new branch on\", required=True)\n@click.option(\n \"--from-branch\",\n help=\"Current git branch to checkout\",\n required=True,\n default=\"master\",\n)\n@click.option(\n \"--to-branch\",\n help=\"Git branch to create, this is typically upstream k8s version\",\n required=True,\n)\n@click.option(\"--dry-run\", is_flag=True)\n@click.option(\"--force\", is_flag=True)\n@click.option(\"--patches\", help=\"Path to patches list\", required=False)\ndef branch(repo, from_branch, to_branch, dry_run, force, patches):\n return _create_branch(repo, from_branch, to_branch, dry_run, force, patches)\n\n\ndef _create_snap_recipe(\n snap,\n version,\n track,\n owner,\n tag,\n repo,\n dry_run,\n snap_recipe_email,\n snap_recipe_password,\n):\n \"\"\" Creates an new snap recipe in Launchpad\n\n snap: Name of snap to create the recipe for (ie, kubectl)\n version: snap version channel apply this too (ie, Current patch is 1.13.3 but we want that to go in 1.13 snap channel)\n track: snap store version/risk/branch to publish to (ie, 1.13/edge/hotfix-LP123456)\n owner: launchpad owner of the snap recipe (ie, k8s-jenkaas-admins)\n tag: launchpad git tag to pull snapcraft instructions from (ie, git.launchpad.net/snap-kubectl)\n repo: launchpad git repo (git+ssh://$LPCREDS@git.launchpad.net/snap-kubectl)\n\n # Note: this account would need access granted to the snaps it want's to publish from the snapstore dashboard\n snap_recipe_email: snapstore email for being able to publish snap recipe from launchpad to snap store\n snap_recipe_password: snapstore password for account being able to publish snap recipe from launchpad to snap store\n\n Usage:\n\n snap.py create-snap-recipe --snap kubectl --version 1.13 --tag v1.13.2 \\\n --track 1.13/edge/hotfix-LP123456 \\\n --repo git+ssh://$LPCREDS@git.launchpad.net/snap-kubectl \\\n --owner k8s-jenkaas-admins \\\n --snap-recipe-email myuser@email.com \\\n --snap-recipe-password aabbccddee\n\n \"\"\"\n _client = lp.Client(stage=\"production\")\n _client.login()\n\n if not isinstance(track, list):\n track = [track]\n\n params = {\n \"name\": snap,\n \"owner\": owner,\n \"version\": version,\n \"branch\": tag,\n \"repo\": repo,\n \"track\": track,\n }\n\n click.echo(f\" > creating recipe for {params}\")\n if dry_run:\n click.echo(\"dry-run only, exiting.\")\n sys.exit(0)\n snap_recipe = _client.create_or_update_snap_recipe(**params)\n caveat_id = snap_recipe.beginAuthorization()\n cip = idm.CanonicalIdentityProvider(\n email=snap_recipe_email, password=snap_recipe_password\n )\n discharge_macaroon = cip.get_discharge(caveat_id).json()\n discharge_macaroon = Macaroon.deserialize(discharge_macaroon[\"discharge_macaroon\"])\n snap_recipe.completeAuthorization(discharge_macaroon=discharge_macaroon.serialize())\n snap_recipe.requestBuilds(archive=_client.archive(), pocket=\"Updates\")\n\n\n@cli.command()\n@click.option(\"--snap\", required=True, help=\"Snaps to build\")\n@click.option(\"--repo\", help=\"Git repository for snap to build\", required=True)\n@click.option(\"--version\", required=True, help=\"Version of k8s to build\")\n@click.option(\"--tag\", required=True, help=\"Tag to build from\")\n@click.option(\n \"--track\",\n required=True,\n help=\"Snap track to release to, format as: `[/][/]`\",\n)\n@click.option(\n \"--owner\",\n required=True,\n default=\"cdkbot\",\n help=\"LP owner with access to managing the snap builds\",\n)\n@click.option(\n \"--snap-recipe-email\", required=True, help=\"Snap store recipe authorized email\"\n)\n@click.option(\n \"--snap-recipe-password\",\n required=True,\n help=\"Snap store recipe authorized user password\",\n)\n@click.option(\n \"--owner\",\n required=True,\n default=\"cdkbot\",\n help=\"LP owner with access to managing the snap builds\",\n)\n@click.option(\"--dry-run\", is_flag=True)\ndef create_snap_recipe(\n snap,\n version,\n track,\n owner,\n tag,\n repo,\n dry_run,\n snap_recipe_email,\n snap_recipe_password,\n):\n return _create_snap_recipe(\n snap,\n version,\n track,\n owner,\n tag,\n repo,\n dry_run,\n snap_recipe_email,\n snap_recipe_password,\n )\n\n\ndef _promote_snaps(snap_list, arch, from_track, to_track, exclude_pre, dry_run):\n \"\"\" Promotes snaps from latest revision of version on architecture\n \"\"\"\n snap_list = Path(snap_list)\n if snap_list.exists():\n snap_list = yaml.safe_load(snap_list.read_text(encoding=\"utf8\"))\n else:\n snap_list = []\n for snap in snap_list:\n out = snapapi.latest(snap, from_track.split(\"/\")[0], arch, exclude_pre)\n if out:\n rev, uploaded, arch, version, channels = out\n for track in to_track:\n click.echo(f\"Promoting ({rev}) {snap} {version} -> {track}\")\n try:\n sh.snapcraft.release(snap, rev, track)\n except sh.ErrorReturnCode as error:\n click.echo(f\"Problem: {error}\")\n sys.exit(1)\n\n\n@cli.command()\n@click.option(\"--snap-list\", help=\"Path to supported snaps\", required=True)\n@click.option(\n \"--arch\",\n help=\"Architecture to use, amd64, arm64, ppc64le or s390x\",\n required=True,\n default=\"amd64\",\n)\n@click.option(\"--from-track\", required=True, help=\"Snap track to promote from\")\n@click.option(\n \"--to-track\",\n help=\"Snap track to promote to, format as: `[/][/]`\",\n required=True,\n multiple=True,\n)\n@click.option(\n \"--exclude-pre\",\n is_flag=True,\n help=\"Do not count preleases when determining latest snap to promote\",\n)\n@click.option(\"--dry-run\", is_flag=True)\ndef promote_snaps(snap_list, arch, from_track, to_track, exclude_pre, dry_run):\n \"\"\" Provides a way to promote the latest snaps for a particular version and a particular architecture\n\n\n Example:\n > snap.py promote-snaps --snap-list k8s-snap-list.yaml \\\n --arch amd64 \\\n --from-track 1.15/edge \\\n --to-track 1.15/stable \\\n --exclude-pre\n \"\"\"\n return _promote_snaps(snap_list, arch, from_track, to_track, exclude_pre, dry_run)\n\n\n@cli.command()\n@click.option(\"--name\", required=True, help=\"Snap name to release\")\n@click.option(\"--channel\", required=True, help=\"Snapstore channel to release to\")\n@click.option(\"--version\", required=True, help=\"Snap application version to release\")\n@click.option(\"--dry-run\", is_flag=True)\ndef release(name, channel, version, dry_run):\n \"\"\" Release the most current revision snap to channel\n \"\"\"\n latest_release = snapapi.latest(name, version)\n click.echo(latest_release)\n if dry_run:\n click.echo(\"dry-run only:\")\n click.echo(f\" > snapcraft release {name} {latest_release['rev']} {channel}\")\n else:\n click.echo(\n sh.snapcraft.release(name, latest_release[\"rev\"], channel, _err_to_out=True)\n )\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"jobs/build-snaps/snap.py","file_name":"snap.py","file_ext":"py","file_size_in_byte":14569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"44881173","text":"\n# coding: utf-8\n\n# In[5]:\n\nempty_list=[]\nweekdays =['monday', 'tuesday', 'wednesday', 'thursday', 'friday']\ntest = list()\nlen(empty_list)\n\n\n# In[2]:\n\nlen(weekdays)\n\n\n# In[6]:\n\ntest\n\n\n# In[7]:\n\nlist('abc')\n\n\n# In[8]:\n\natuple = ('aa','bb','cc')\nlist(atuple)\n\n\n# In[9]:\n\nbirthday = '1997/1/18'\nbirthday.split('/')\n\n\n# In[10]:\n\nsplitme = 'a/b//c/d//e'\nsplitme.split('/')\n\n\n# In[11]:\n\ntest=['1', '2', '3']\ntest[0]\n\n\n# In[12]:\n\ntest[-1]\n\n\n# In[14]:\n\ntest1=['0','1','2']\ntest3=['3','4','5']\ntest6=['6','7','8']\ntestlist = [test1,test3,test6]\ntestlist\n\n\n# In[15]:\n\ntestlist[0]\n\n\n# In[26]:\n\ntest = ['apple','sumsung','htc']\ntest[1] = 'asus'\ntest\n\n\n# In[20]:\n\ntest[:]\n\n\n# In[21]:\n\ntest[1:2]\n\n\n# In[22]:\n\ntest[::2]\n\n\n# In[27]:\n\ntest.append('nokia')\ntest\n\n\n# In[28]:\n\ntest2=['america','taiwan']\ntest.extend(test2)\ntest\n\n\n# In[29]:\n\ntest = ['apple','asus','htc']\ntest2=['america','taiwan']\ntest += test2\ntest\n\n\n# In[30]:\n\ntest = ['apple','asus','htc']\ntest2=['america','taiwan']\ntest.append(test2)\ntest\n\n\n# In[31]:\n\ntest=['taiwan','america']\ntest.insert(1,'japan')\ntest\n\n\n# In[32]:\n\ndel test[2]\ntest\n\n\n# In[48]:\n\ntest=['taiwan','america','japan']\ntest.remove('america')\ntest\n\n\n# In[40]:\n\ntest=['taiwan','japan','america']\ntest.pop(1)\n\n\n# In[41]:\n\ntest\n\n\n# In[43]:\n\ntest=['taiwan','japan','america']\ntest.pop()\n\n\n# In[44]:\n\ntest\n\n\n# In[45]:\n\ntest=['taiwan','japan','america']\ntest.pop(-1)\n\n\n# In[46]:\n\ntest=['taiwan','japan','america']\ntest.index('japan')\n\n\n# In[50]:\n\ncountry=['taiwan','japan','america']\n'taiwan' in country\n\n\n# In[51]:\n\n'korea' in country\n\n\n# In[52]:\n\ntest=['0','1','2','1','3']\n'1' in test\n\n\n# In[53]:\n\ntest.count('1')\n\n\n# In[54]:\n\n','.join(test)\n\n\n# In[56]:\n\ntest=['1','2','0','5','4']\ntest.sort()\ntest\n\n\n# In[58]:\n\ntest=['a','c','b','e','d']\ntestabc = sorted(test)\ntestabc\n\n\n# In[59]:\n\ntest\n\n\n# In[60]:\n\na = ['1','2','3']\na\n\n\n# In[61]:\n\nb = a\nb\n\n\n# In[62]:\n\na[0] = 't'\na\n\n\n# In[63]:\n\nb\n\n\n# In[64]:\n\nb[0] = 'pp'\nb\n\n\n# In[65]:\n\na\n\n\n# In[66]:\n\na = ['1','2','3']\nb = a.copy()\nc = list(a)\nd = a[:]\na[0] = 'change'\na\n\n\n# In[67]:\n\nb\n\n\n# In[68]:\n\nc\n\n\n# In[69]:\n\nd\n\n\n# In[70]:\n\nempty_tuple = ()\nempty_tuple\n\n\n# In[73]:\n\none_tuple ='a',\none_tuple\n\n\n# In[74]:\n\nmany = 'a','b','c'\nmany\n\n\n# In[75]:\n\nmany = ('a','b','c')\nmany\n\n\n# In[76]:\n\ntest = ('1','2','3')\na,b,c = test\na\n\n\n# In[77]:\n\nb\n\n\n# In[78]:\n\nc\n\n\n# In[79]:\n\na = '00'\nb = '11'\na,b = b,a\na\n\n\n# In[80]:\n\nb\n\n\n# In[81]:\n\ntestlist = ['a','b','c']\ntuple(testlist)\n\n\n# In[82]:\n\nempty_dic = {}\nempty_dic\n\n\n# In[83]:\n\nword = {'a':'apple' , 'b':'bank' , 'c':'cow'}\nword\n\n\n# In[84]:\n\nlol = [['a','apple'],['b','bank'],['c','cow']]\ndict(lol)\n\n\n# In[85]:\n\nlol = [('a','apple'),('b','bank'),('c','cow')]\ndict(lol)\n\n\n# In[86]:\n\nlol = (['a','apple'],['b','bank'],['c','cow'])\ndict(lol)\n\n\n# In[87]:\n\nlos = ['aa','bb','cc']\ndict(los)\n\n\n# In[88]:\n\ntest = {'A':'apple','B':'boom!','C':'cow'}\ntest['D']='dick'\ntest\n\n\n# In[89]:\n\ntest['D'] = 'drop'\ntest\n\n\n# In[91]:\n\ntest = {'A':'apple','B':'boom!'}\nother = {'C': 'cow', 'D': 'drop'}\ntest.update(other)\ntest\n\n\n# In[97]:\n\ntest = {'A':'apple','B':'boom!','D':'dick'}\nother = {'C': 'cow', 'D': 'drop'}\ntest.update(other)\ntest\n\n\n# In[99]:\n\ndel test['D']\ntest\n\n\n# In[100]:\n\ntest.clear()\ntest\n\n\n# In[102]:\n\ntest = {'A':'apple','B':'boom!'}\n'A' in test\n\n\n# In[103]:\n\ntest['B']\n\n\n# In[104]:\n\ntest = {'A':'apple','B':'boom!','C':'cow'}\ntest.get('B')\n\n\n# In[105]:\n\ntest.get('G', 'nothing')\n\n\n# In[107]:\n\ntest.get('G')\n\n\n# In[108]:\n\ntest = {'A':'apple','B':'boom!','C':'cow'}\ntest.keys()\n\n\n# In[111]:\n\ntest.values()\n\n\n# In[112]:\n\nlist(test.values())\n\n\n# In[113]:\n\nlist(test.items())\n\n\n# In[114]:\n\ncolor = {'R':'red','B':'blue','G':'green'}\nsavecolor = color\ncolor[\"G\"]='disappear'\nsavecolor\n\n\n# In[115]:\n\ncolor = {'R':'red','B':'blue','G':'green'}\nsavecolor = color.copy()\ncolor[\"G\"]='disappear'\nsavecolor\n\n\n# In[117]:\n\nempty_set=set()\nempty_set\n\n\n# In[118]:\n\neven_numbers = {0,2,4,6,8}\neven_numbers\n\n\n# In[120]:\n\nodd_numbers = {1,3,5,7,9}\nodd_numbers\n\n\n# In[121]:\n\nset('letters')\n\n\n# In[122]:\n\nlist('letters')\n\n\n# In[123]:\n\ntuple('letters')\n\n\n# In[127]:\n\nset(['l', 'e', 't', 't', 'e', 'r', 's'])\n\n\n# In[128]:\n\nset({'A':'apple','B':'bank'})\n\n\n# In[142]:\n\ndrinks = {'martini':{'vodka','vermouth'},\n 'black russian':{'vodka','kahlue'},\n 'white russian':{'cream','kahlue','vodka'},\n 'manhattan':{'rye','vermouth','bitters'},\n 'screwdriver':{'orange juice','vodka'}\n }\n\nfor name, contents in drinks.items():\n if 'vodka' in contents:\n print(name)\n\n\n# In[135]:\n\nfor a , x in drinks.items(): \n if x & {'vermouth', 'orange juice'}: \n print(a)\n\n\n# In[137]:\n\nfor name, contents in drinks.items():\n if 'vodka' in contents and not contents & {'vermouth','cream'}:\n print(name)\n\n\n# In[144]:\n\nbruss = drinks['black russian']\nwruss = drinks['white russian']\n\n\n# In[139]:\n\na = {1 , 2}\nb = {2 , 3}\na & b\n\n\n# In[140]:\n\na.intersection(b)\n\n\n# In[145]:\n\nbruss & wruss\n\n\n# In[146]:\n\na | b\n\n\n# In[147]:\n\na.union(b)\n\n\n# In[148]:\n\nbruss | wruss\n\n\n# In[149]:\n\na - b\n\n\n# In[150]:\n\na.difference(b)\n\n\n# In[151]:\n\nbruss - wruss\n\n\n# In[152]:\n\nwruss-bruss\n\n\n# In[153]:\n\na ^ b\n\n\n# In[154]:\n\nbruss ^ wruss\n\n\n# In[155]:\n\na <= b\n\n\n# In[156]:\n\nbruss <= wruss\n\n\n# In[157]:\n\na < b\n\n\n# In[158]:\n\na < a\n\n\n# In[159]:\n\nbruss < wruss\n\n\n# In[160]:\n\na >= b\n\n\n# In[161]:\n\na >= a\n\n\n# In[162]:\n\nbruss >= wruss\n\n\n# In[163]:\n\nwruss >= bruss\n\n\n# In[164]:\n\na > b\n\n\n# In[165]:\n\nwruss > bruss\n\n\n# In[166]:\n\nb > b\n\n\n# In[168]:\n\ntest_list = ['a','b','c']\ntest_tuple = ('a','b','c')\ntest_dict = {'a':'aaa','b':'bbb','c':'ccc'}\ntest_list[2]\n\n\n# In[169]:\n\ntest_tuple[1]\n\n\n# In[171]:\n\ntest_dict['a']\n\n\n# In[173]:\n\na = ['apple','asia']\nb = ['bank','boom!']\nc = ['cow','cross']\ntuple_list = a , b , c\ntuple_list\n\n\n# In[175]:\n\nlist_list = [a,b,c]\nlist_list\n\n\n# In[176]:\n\ndict_list = { 'a' : a , 'b' : b , 'c' : c }\ndict_list\n\n\n# In[278]:\n\nyearlist = [1997,1998,1999,2000,2001] #3-1\nyearlist\n\n\n# In[279]:\n\nyearlist[3] #3-2\n\n\n# In[280]:\n\nyearlist[-1] #3-3\n\n\n# In[187]:\n\nm = \"mozzarella\" #3-4\nc = \"cin derella\"\ns = \"salmonella\"\nthings = [m , c , s]\nthings\n\n\n# In[282]:\n\nthings = [m.title() , c.title() , s.title()] #3-5\nthings\n\n\n# In[192]:\n\nthings = [m.upper() , c.upper() , s] #3-6\nthings\n\n\n# In[284]:\n\nthings = [m , c , s] #3-7\ndel things_3_7[-1]\nthings.append('Nobel Prize')\nthings\n\n\n# In[285]:\n\ng = 'Groucho' #3-8\nc = 'Chico'\nh = 'Harpo'\nsurprise = [g,c,h]\nsurprise\n\n\n# In[286]:\n\nsurprise = [g,c,h.lower()[-1::-1].title()] #3-9\nsurprise\n\n\n# In[287]:\n\ne2f = {'dog':'chien', 'cat':'chat', 'walrus':'morse'} #3-10\ne2f\n\n\n# In[288]:\n\ne2f['walrus'] #3-11\n\n\n# In[289]:\n\na = list(e2f.keys()) #3-12\nb = list(e2f.values())\nf2e = {b[0]:a[0],b[1]:a[1],b[2]:a[2]}\nf2e.items()\n\n\n# In[290]:\n\nf2e['chien'] #3-14\n\n\n# In[291]:\n\ne2f = list(e2f.keys()) #3-14\nset(e2f)\n\n\n# In[292]:\n\ncatt = ['Henir','Grumpy','Lucy'] #3-15\nanimals = {'cat':catt, 'octopi':{}, 'emus':{}}\nlife = {'animals':animals, 'plants':{}, 'other':{}}\nlife\n\n\n# In[293]:\n\nlife.keys() #3-16\n\n\n# In[294]:\n\nlife['animals'].keys() #3-17\n\n\n# In[295]:\n\nlife['animals']['cat'] #3-18\n\n","sub_path":"第三章+待辦事項(練習題).py","file_name":"第三章+待辦事項(練習題).py","file_ext":"py","file_size_in_byte":7937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"321598459","text":"#!/usr/bin/env python3\nimport json\nimport sys\n\nsys.path.insert(1, '.')\nsys.path.insert(1, './python')\n\nfrom python import CFNZonesTransform\n\nwith open('test/CFNZonesTransform_awszones_test.json') as f:\n data = json.load(f)\n\ndata['templateParameterValues']['LocalTest'] = True\n\nresponse = CFNZonesTransform.create_template(data, None)\n\nprint(json.dumps(response))\n","sub_path":"test/CFNZonesTransform.py","file_name":"CFNZonesTransform.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"402535824","text":"# 7-edo Keyboard\n## Based on code from \"Making Music with Computers\"\nfrom music import *\nfrom gui import *\n\nPlay.setInstrument(74) # set desired MIDI instrument (0-127)\n\n# Create gui so we can use events\nd = Display(\"ET-7 Keyboard\", 300, 200)\n\n# lists of virtual keys and pitches corresponding to above piano keys\nvirtualKeys = [VK_A, VK_S, VK_D, VK_F, VK_J, VK_K, VK_L, VK_SEMICOLON]\nchannels = range(8)\n\n# Create pitches - this is the formula for 7-tone equal temperament\na = 2 ** (1/7.0)\npitches = [261.6 * (a ** n) for n in range(8)]\n\n#Here's an alternative set of pitches based on an Indian scale - use commenting to swap\n# pitches = [60, 61, 64, 65, 67, 68, 71, 72]\n\nkeysPressed = [] # holds which keys are currently pressed\n\n# define callback functions\ndef beginNote( key ):\n \"\"\"Called when a computer key is pressed. Implements the corresponding \n piano key press (i.e., adds key-down icon on display, and starts note).\n Also, counteracts the key-repeat function of computer keyboards.\n \"\"\"\n for i in range( len(virtualKeys) ): # loop through all known virtual keys\n \n # if this is a known key (and NOT already pressed)\n if key == virtualKeys[i] and key not in keysPressed: \n \n Play.setInstrument(74, channels[i])\n Play.noteOn( pitches[i], 100, channels[i] ) # play corresponding note\n keysPressed.append( key ) # and remember key (to avoid key-repeat)\n\ndef endNote( key ):\n \"\"\"Called when a computer key is released. Implements the corresponding \n piano key release (i.e., removes key-down icon, and stops note).\n \"\"\"\n for i in range( len(virtualKeys) ): # loop through known virtual keys\n \n # if this is a known key (we can assume it is already pressed)\n if key == virtualKeys[i]: \n \n Play.noteOff( pitches[i], channels[i] ) # stop corresponding note\n keysPressed.remove( key ) # and forget key (for key-repeat)\n\n# associate callback functions with GUI events\nd.onKeyDown( beginNote )\nd.onKeyUp( endNote )","sub_path":"3 -Equal Octave Divisions/7-edo-typing.py","file_name":"7-edo-typing.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"135430784","text":"import numpy as np\nimport pickle\nfrom distance import Distance\n\nclass Subtraj():\n def __init__(self, cand_train, query_train):\n self.action_space = ['0', '1']\n self.n_actions = len(self.action_space)\n self.n_features = 3\n self.cand_train_name = cand_train\n self.query_train_name = query_train\n self.presim = 0\n self.sufsim = 0\n self.RW = 0.0\n self._load()\n\n def _load(self):\n self.cand_train_data = pickle.load(open(self.cand_train_name, 'rb'), encoding='bytes')\n self.query_train_data = pickle.load(open(self.query_train_name, 'rb'), encoding='bytes')\n \n def reset(self, episode):\n # prefix_state --> [split_point, index]\n # suffix_state --> [index + 1, len - 1]\n # return observation\n self.split_point = 0\n self.DIS = Distance(len(self.cand_train_data[episode]), len(self.query_train_data[episode]))\n self.DIS_R = Distance(len(self.cand_train_data[episode]), len(self.query_train_data[episode]))\n self.length = len(self.cand_train_data[episode])\n \n self.presim = self.DIS.FRECHET(self.cand_train_data[episode][self.split_point:1], self.query_train_data[episode])\n self.sufsim = self.DIS_R.FRECHET(self.cand_train_data[episode][1:][::-1],self.query_train_data[episode][::-1])\n whole = self.DIS_R.FRECHET(self.cand_train_data[episode][::-1],self.query_train_data[episode][::-1]) #self.DIS.FRECHET(self.cand_train_data[episode], self.query_train_data[episode])\n observation = np.array([whole, self.presim, self.sufsim]).reshape(1,-1)\n \n self.subsim = min(whole, self.presim, self.sufsim)\n #print('episode', episode, whole, self.presim, self.sufsim)\n \n if self.subsim == whole:\n self.subtraj = [0, self.length - 1]\n \n if self.subsim == self.presim:\n self.subtraj = [0, 0]\n \n if self.subsim == self.sufsim:\n self.subtraj = [1, self.length - 1]\n \n return observation, self.length\n \n def step(self, episode, action, index):\n if action == 0: #non-split \n #state transfer\n self.presim = self.DIS.FRECHET(self.cand_train_data[episode][self.split_point:(index+1)], self.query_train_data[episode])\n self.sufsim = self.DIS_R.FRECHET(self.cand_train_data[episode][(index+1):][::-1],self.query_train_data[episode][::-1])\n if (index+1) == self.length:\n self.sufsim = self.presim\n observation = np.array([self.subsim, self.presim, self.sufsim]).reshape(1,-1)\n \n last_subsim = self.subsim\n \n if self.presim < self.subsim:\n self.subsim = self.presim\n self.subtraj = [self.split_point, index]\n \n if self.sufsim < self.subsim:\n self.subsim = self.sufsim\n self.subtraj = [index + 1, self.length - 1]\n \n self.RW = last_subsim - self.subsim \n #print('action0', self.RW)\n return observation, self.RW\n \n if action == 1: #split\n self.split_point = index\n self.DIS = Distance(len(self.cand_train_data[episode][self.split_point:]), len(self.query_train_data[episode]))\n #state transfer\n self.presim = self.DIS.FRECHET(self.cand_train_data[episode][self.split_point:(index+1)], self.query_train_data[episode])\n self.sufsim = self.DIS_R.FRECHET(self.cand_train_data[episode][(index+1):][::-1],self.query_train_data[episode][::-1]) \n if (index+1) == self.length:\n self.sufsim = self.presim\n observation = np.array([self.subsim, self.presim, self.sufsim]).reshape(1,-1)\n \n last_subsim = self.subsim\n \n if self.presim < self.subsim:\n self.subsim = self.presim\n self.subtraj = [self.split_point, index]\n \n if self.sufsim < self.subsim:\n self.subsim = self.sufsim\n self.subtraj = [index + 1, self.length - 1]\n \n self.RW = last_subsim - self.subsim \n #print('action1', self.RW)\n return observation, self.RW\n\n def output(self, index, episode):\n #print('check', self.subsim, self.subtraj)\n return [self.subsim, self.subtraj]","sub_path":"Frechet/RLS_env.py","file_name":"RLS_env.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"312109288","text":"__author__ = 'niklasbjornberg'\n\nPROTOCOL_PORT = 5005\n\nMOVE_CMD = \"MOVE_CMD\"\nMOVE_CMD_ROTR = \"ROTR\"\nMOVE_CMD_FWD = \"FWD\"\nMOVE_CMD_FWD_L = \"FWDL\"\nMOVE_CMD_FWD_R = \"FWDR\"\nMOVE_CMD_BWD = \"BWD\"\nMOVE_CMD_BWD_L = \"BWDL\"\nMOVE_CMD_BWD_R = \"BWDR\"\nMOVE_CMD_ROTL = \"ROTL\"\nMOVE_CMD_STOP = \"STOP\"\n\nSETSPEED_CMD = \"SETSPEED\"\n\nPING_CMD = \"PING_CMD\"\n\nSHUTDOWN_CMD = \"SHUTDOWN_CMD\"\n\ndef makeData(cmd,message=None):\n if message == None:\n return cmd\n else:\n mess = cmd + \" \" + message\n return mess\n\ndef parseData(data):\n data = str(data)\n words = data.split(\" \")\n if len(words) < 2:\n return\n cmd = words[0]\n arg = words[1]\n return (cmd,arg)","sub_path":"robot/commonSide/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"418688034","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter,\n AutoMinorLocator)\n# For Adobe illustrator text\nimport matplotlib as mpl\nmpl.rcParams['pdf.fonttype'] = 42\n\n\ndef plot_softness():\n#\n edf = [\"UNEDF0\", \"UNEDF1\",\"UNEDF2\",\"SV-MIN\",\"SLY4\", \"SKMS\", \"SKP\"]\n colors = ['r','b','k','y','m','c','g']\n markers = ['s','*','o','^','d','+','x']\n\n\n f,l,E_oct,f_gs,gs_def,l_gs = {},{},{},{},{},{}\n for e in edf:\n f[e] = open(\"octupole_energy/\"+e+\"_octupole_energy_050.dat\",\"r\")\n f_gs[e] = open(\"octupole_gs_reduced/\"+e+\"_reduced_beta2_3_050.dat\",\"r\")\n l[e] = f[e].readlines()\n l_gs[e] = f_gs[e].readlines()\n count = 0; E_oct[e] = {}\n for line in l[e]:\n if not count: count+=1;continue\n ss=line.split()\n Z,N,E,b2,b3 = int(ss[0]),int(ss[1]),float(ss[3]),float(ss[7]),float(ss[6])\n E_oct[e][(Z,N)] = (E,b2,b3)\n\n count = 0; gs_def[e] = {}\n for line in l_gs[e]:\n if not count: count+=1;continue\n ss=line.split()\n Z,N,b2,b3 = int(ss[0]),int(ss[1]),float(ss[4]),float(ss[5])\n gs_def[e][(Z,N)] = (b2,b3)\n f[e].close()\n f_gs[e].close()\n\n # plot isotope, 3 plots for one chain. Each edf gets one chain\n z_plot = 86; plt_title = \"Rn\"\n plt_list = []\n # (40,\"Zr\"),(38,\"Sr\"),(42,\"Mo\")\n plt_list = \\\n [(58,'Ce'),(60,\"Nd\"),(62,\"Sm\"),(64,\"Gd\")]\n # (56,\"Ba\"),(86,\"Rn\"),(88,\"Ra\"),(90,\"Th\"),(92,\"U\"),\n # (94,\"Pu\"),(96,\"Cm\"),(98,\"Cf\"),(100,\"Fm\"),(102,\"No\"),(104,\"Rf\"),(106,\"Sg\"),\n # (108,\"Hs\"),(110,\"Ds\"),(112,\"Cn\"),(114,\"Fl\"),(116,\"Lv\"),(118,\"Og\"),\n # (120,\"z120\"),(58,\"Ce\"),(54,\"Xe\"),(80,\"Hg\")\n\n x_range = {}\n for z_plot,plt_title in plt_list:\n x_range[z_plot] = (1000,0)\n for e in edf:\n for z,n in E_oct[e].keys():\n if z == z_plot:\n x_range[z_plot] = (min(x_range[z_plot][0],n),max(x_range[z_plot][1],n))\n\n for z_plot,plt_title in plt_list:\n fig, axes = plt.subplots(3,1, sharex = True, sharey = False)#, figsize = (10,30))\n axes[0].set_title(plt_title+\" chain\")\n for j,e in enumerate(edf):\n x_n, y_Eoct,y_b2, y_b3 = [] , [], [], []\n for N in range(x_range[z_plot][0],x_range[z_plot][1]+1,2):\n x_n.append(N)\n if (z_plot,N) in E_oct[e]:\n y_Eoct.append(E_oct[e][(z_plot,N)][0])\n y_b2.append(E_oct[e][(z_plot,N)][1])\n y_b3.append(E_oct[e][(z_plot,N)][2])\n else:\n y_Eoct.append(0)\n y_b2.append(gs_def[e][(z_plot,N)][0])\n y_b3.append(gs_def[e][(z_plot,N)][1])\n axes[0].plot(x_n,y_b2,c=colors[j],linestyle='-',linewidth=0.5,marker=markers[j],\n markersize=1,label=e,alpha=0.7)\n axes[1].plot(x_n,y_b3,c=colors[j],linestyle='-',linewidth=0.5,marker=markers[j],\n markersize=1,label=e,alpha=0.7)\n axes[2].plot(x_n,y_Eoct,c=colors[j],linestyle='-',linewidth=0.5,marker=markers[j],\n markersize=1,label=e,alpha=0.7)\n axes[0].set_ylabel(r\"$\\beta_2$\")\n axes[1].set_ylabel(r\"$\\beta_3$\")\n axes[2].set_ylabel(r\"$E_{oct} (MeV)$\")\n axes[2].xaxis.set_minor_locator(AutoMinorLocator(3))\n plt.xticks(range(x_range[z_plot][0],x_range[z_plot][1]+1,6),fontsize=6)\n plt.legend(prop={'size':4},loc=4)\n plt.savefig(\"plots/Z\"+str(z_plot)+\"_\"+plt_title+\".pdf\",format=\"pdf\")\n plt.clf()\nplot_softness()\n\n\n\n# Split neutron chain into 2 parts, for 2 different octupole regions\n# count = 0\n# for i in range(0,len(x_n)-1):\n# if x_n[i+1] - x_n[i] >=10:\n# print (x_n[i])\n# x_n_0,x_n_1 = x_n[:i+1],x_n[i+1:]\n# y_Eoct_0,y_Eoct_1 = y_Eoct[:i+1],y_Eoct[i+1:]\n# y_b2_0,y_b2_1 = y_b2[:i+1],y_b2[i+1:]\n# y_b3_0,y_b3_1 = y_b3[:i+1],y_b3[i+1:]\n# count=1\n# if count == 0 and i == len(x_n)-2:\n# x_n_0,y_Eoct_0,y_b2_0,y_b3_0 = x_n,y_Eoct,y_b2,y_b3\n#\n# x_n,y_Eoct,y_b2,y_b3 = zip(*E_oct[e][z_plot])\n# x_n = list(x_n); y_Eoct = list(y_Eoct); y_b2 = list(y_b2); y_b3 = list(y_b3)\n# shift = 0\n# for i in range(1,len(x_n)):\n# ind = shift+i\n# if x_n[ind] != x_n[ind-1]+2:\n# # change y's before x_n, otherwise insert array length will be 0\n# y_Eoct[ind:ind] = [0 for i in range(x_n[ind-1]+2,x_n[ind],2)]\n# y_b2[ind:ind] = [gs_def[e][(z_plot,N)][0] for N in range(x_n[ind-1]+2,x_n[ind],2)]\n# y_b3[ind:ind] = [gs_def[e][(z_plot,N)][1] for N in range(x_n[ind-1]+2,x_n[ind],2)]\n# shift += len([i for i in range(x_n[ind-1]+2,x_n[ind],2)])\n# x_n[ind:ind] = [i for i in range(x_n[ind-1]+2,x_n[ind],2)]\n","sub_path":"energy_softness/main/octupole_deformed_energy/no_LN_based_def_input_softness/050 beta filter/octupole_energy/plt_oct_softness.py","file_name":"plt_oct_softness.py","file_ext":"py","file_size_in_byte":5023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"30311651","text":"#!/usr/bin/env python\nfrom torchsummary import summary\nimport argparse\nimport datetime\nimport os\nimport os.path as osp\nimport torch\nimport torch.nn as nn\nimport yaml\nimport sys\nimport lovasz_losses as L\nsys.path.insert(0, '../../')\nimport torchfcn\nfrom train_fcn32s import get_parameters\nfrom train_fcn32s import git_hash\nimport datetime\nfrom distutils.version import LooseVersion\nimport math\nimport os\nimport os.path as osp\nimport shutil\nimport fcn\nimport numpy as np\nimport pytz\nimport scipy.misc\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport tqdm\nimport time\nimport datetime\nfrom statistics import mean\nimport skimage\nimport cv2\nimport random\nfrom early_stopping import EarlyStoppingIoU\nimport warnings\nfrom torchvision import models\nfrom weight_init import weight_init\nwarnings.filterwarnings(\"ignore\")\n\ntorch.manual_seed(12)\ntorch.cuda.manual_seed(12)\nnp.random.seed(12)\nrandom.seed(12)\ntorch.backends.cudnn.deterministic=True\n\n\nhere = osp.dirname(osp.abspath(__file__))\n\nn_class = 2\n\nuse_gpu = torch.cuda.is_available()\n\ndef get_free_gpu():\n os.system('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >tmp')\n memory_available = [int(x.split()[2]) for x in open('tmp', 'r').readlines()]\n return np.argmax(memory_available)\n\ngpu_used = int(get_free_gpu())\n\n\nvgg_model = torchfcn.models.VGGNet(requires_grad=True, remove_fc=True)\nfcn_model = torchfcn.models.FCN8s(pretrained_net=vgg_model, n_class=2)\nfcn_model.apply(weight_init)\n\nmodel2 = torchfcn.models.AutoEncoderConv2()\nmodel2.load_state_dict(torch.load(\"trained_models/autoencoder_best.pth\"), strict=False)\n\n\n\n\n#FREEZE DECODER\nfor p in model2.parameters():\n p.requires_grad = False\n\nearly_stopping = EarlyStoppingIoU(patience=7)\n\nif use_gpu:\n ts = time.time()\n vgg_model = vgg_model.cuda(gpu_used)\n fcn_model = fcn_model.cuda(gpu_used)\n model2 = model2.cuda(gpu_used)\n transform_conv = torchfcn.models.TransformConv().cuda(gpu_used)\n # fcn_model = nn.DataParallel(fcn_model, device_ids=num_gpu)\nprint(\"Finish cuda loading, time elapsed {}\".format(time.time() - ts))\n\n# vgg_model = nn.DataParallel(vgg_model)\n# fcn_model = nn.DataParallel(fcn_model)\n# model2 = nn.DataParallel(model2)\n\ndef train(args, optimizer, criterion, criterion2, scheduler, train_loader, val_loader, filename=None):\n epochs = args.epochs\n\n for epoch in range(epochs):\n if args.scheduler == True:\n scheduler.step()\n\n ts = time.time()\n\n for iter, (inputs, labels) in tqdm.tqdm(\n enumerate(train_loader), total=len(train_loader),\n desc='Train epoch=%d' % epoch, ncols=80, leave=False):\n\n optimizer.zero_grad()\n\n if use_gpu:\n inputs = Variable(inputs.cuda(gpu_used))\n labels = Variable(labels.cuda(gpu_used))\n else:\n inputs, labels = Variable(inputs), Variable(labels)\n\n N, c, h, w = inputs.shape\n\n intermediate_input_from_fcn = fcn_model.pretrained_net(inputs)['x5']\n intermediate_input_from_fcn = transform_conv(intermediate_input_from_fcn)\n\n outputs = fcn_model(inputs)\n\n #EXTRACT INTERMEDIATE INPUT\n outputs2 = model2.decode(intermediate_input_from_fcn, iter)\n\n if args.loss == \"CE\":\n loss1 = criterion(outputs, labels)\n loss2 = criterion2(outputs2, labels.float())\n # print(\"main loss: \", loss1)\n # print(\"aux loss: \", loss2)\n loss = loss1 + (args.loss2weight * loss2)\n else:\n loss1 = L.lovasz_softmax(outputs, labels, classes=[1])\n loss2 = criterion2(outputs2, labels.float())\n loss = loss1 + (args.loss2weight * loss2)\n\n #a = list(model2.parameters())[0].clone()\n\n loss.backward()\n\n optimizer.step()\n\n #b = list(model2.parameters())[0].clone()\n #CONFIRMATION THAT DECODER IS FROZEN\n #print(\"Equal?: \", torch.equal(a.data, b.data))\n\n print(\"Finish epoch {}, time elapsed {}\".format(epoch, time.time() - ts))\n print(\"epoch: {}, loss: {}\".format(epoch, loss.data.item()))\n\n if args.file == True:\n csv_file = open(filename, \"a\")\n csv_file.write(str(epoch) + \",\" + str(loss.data.item()) + \",\")\n csv_file.close()\n\n\n val(epoch, args, criterion, val_loader, filename)\n\ndef val(epoch, args, criterion, val_loader, filename=None):\n fcn_model.eval()\n total_ious = []\n pixel_accs = []\n iteration = 0\n val_loss = 0\n count = 0\n for iter, (data, target) in tqdm.tqdm(\n enumerate(val_loader), total=len(val_loader),\n desc='Valid iteration=%d' % iteration, ncols=80,\n leave=False):\n\n if use_gpu:\n inputs = Variable(data.cuda(gpu_used))\n else:\n inputs = Variable(data)\n\n output = fcn_model(inputs)\n\n if args.loss == \"CE\":\n val_loss += criterion(output, target.cuda(gpu_used)).item()\n else:\n val_loss += L.lovasz_softmax(output, target.cuda(gpu_used), classes=[1]).item()\n\n count = count + 1\n\n output = output.data.cpu().numpy()\n\n N, c, h, w = output.shape\n\n pred = output.transpose(0, 2, 3, 1).reshape(-1, n_class).argmax(axis=1).reshape(N, h, w)\n\n target = target.cpu().numpy().reshape(N, h, w)\n\n\n for p, t in zip(pred, target):\n\n total_ious.append(L.iou_binary(p, t))\n pixel_accs.append(pixel_acc(p, t))\n\n\n iteration += 1\n\n val_loss /= count\n pixel_accs = np.array(pixel_accs).mean()\n print(\"epoch: {}, pix_acc: {}, IoU: {}, val_loss: {}\".format(epoch, pixel_accs, np.mean(total_ious), val_loss))\n\n if args.file == True:\n csv_file = open(filename, \"a\")\n csv_file.write(str(pixel_accs) + \",\" + str(np.mean(total_ious)) + \",\" + str(val_loss) + \"\\n\")\n csv_file.close()\n\n early_stopping(np.mean(total_ious))#, model)\n\n if early_stopping.early_stop:\n print(\"Early stopping\")\n #test_set(test_loader)\n sys.exit()\n\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument(\n '--lr', type=float, default=0.0000001, help='Learning rate',\n )\n parser.add_argument(\n '--scheduler', nargs=\"?\", type=str2bool, default=False, help='Scheduler?',\n )\n parser.add_argument(\n '--optimiser', nargs=\"?\", type=str, default=\"RMSprop\", help='Optimiser used',\n )\n parser.add_argument(\n '--epochs', nargs=\"?\", type=int, default=100, help='The experiment\\'s epoch budget'\n )\n parser.add_argument(\n '--w_decay', type=float, default=0.00005, help='weight decay',\n )\n parser.add_argument(\n '--momentum', type=float, default=0.90, help='momentum',\n )\n parser.add_argument(\n '--file', type=str2bool, default=False, help='Do you want to output data to csv?',\n )\n parser.add_argument(\n '--loss', type=str, default=\"CE\", help='Loss function',\n )\n parser.add_argument(\n '--loss2weight', type=float, default=1.0, help='By what factor do you want to weight the auxiliary loss'\n )\n parser.add_argument(\n '--batch_size', type=int, default=16, help='input batch size for training (default: 16)'\n )\n\n args = parser.parse_args()\n print(args)\n\n train_loader = torch.utils.data.DataLoader(\n torchfcn.datasets.SatelliteDataset(split='train', transform=True),\n batch_size=args.batch_size, shuffle=True)\n\n val_loader = torch.utils.data.DataLoader(\n torchfcn.datasets.SatelliteDataset(split='val', transform=True),\n batch_size=args.batch_size, shuffle=True)\n\n if args.optimiser == \"RMSprop\":\n optimizer = torch.optim.RMSprop(fcn_model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.w_decay)\n elif args.optimiser == \"Adam\":\n optimizer = torch.optim.Adam(fcn_model.parameters(), lr=args.lr, betas=(0.9,0.999))\n\n criterion = nn.CrossEntropyLoss(weight=torch.Tensor([1,4.5]).cuda(gpu_used))\n criterion2 = nn.MSELoss()\n scheduler = None\n\n if args.file == True:\n filename = datetime.datetime.utcnow().strftime(\"%H:%M:%S\")\n filename = \"experiment_results_fcn_combined/\" + filename + \".csv\"\n csv_file = open(filename, \"a\")\n csv_file.write(str(args) + \"\\n\")\n csv_file.write(\"epoch,loss,pixel_acc,IoU,val_loss\\n\")\n csv_file.close()\n train(args, optimizer, criterion, criterion2, scheduler, train_loader, val_loader, filename)\n else:\n train(args, optimizer, criterion, criterion2, scheduler, train_loader, val_loader)\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\ndef pixel_acc(pred, target):\n correct = (pred == target).sum()\n total = (target == target).sum()\n return correct / total\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"project/pytorch-fcn/examples/satellite/fcn_combined.py","file_name":"fcn_combined.py","file_ext":"py","file_size_in_byte":9164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"459552060","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport requests\nimport os\n\n\ndef get(path, api_key, params=None):\n \"\"\"Make an HTTP request to get the data from path. Note that there are\n several possible returns with different types depending on the data received\n from the URL\n\n Parameters\n ----------\n :param path: The URL to request from\n :type path: str\n :param api_key: The key for accessing the Illustris API\n :type api_key: str\n :param params: Extra parameters to pass to `requests`. Default None\n :type params: dict or None\n\n Returns\n -------\n :return r: The :class:`Response` object from `requests`, if not JSON or binary data\n :rtype r: :class:`requests.Response`\n :return r.json(): JSON decoded response, if request was successful and \n response is JSON\n :rtype r.json(): dict\n :return filename: Filename for stored HDF5 table, if request was successful\n and response is binary\n :rtype filename: str\n\n Examples\n --------\n Getting JSON data from a higher level API page:\n\n >>> from mond_project import get\n >>> import os\n >>> api_key = os.getenv(\"ILL_KEY\")\n >>> base_url = \"http://www.illustris-project.org/api/\"\n >>> r = get(base_url, api_key)\n >>> r.keys()\n ['simulations']\n >>> len(r[\"simulations\"])\n 18\n >>> r[\"simulations\"][0]\n {'name': 'Illustris-1',\n 'num_snapshots': 134,\n 'url': 'http://www.illustris-project.org/api.Illustris-1/'}\n\n Getting the data saved in a file with a specific URL:\n\n >>> table_url = \"http://www.illustris-project.org/api/Illustris-3/snapshots/135/subhalos/1030/sublink/mpb.hdf5\"\n >>> filename = get(table_url, api_key)\n >>> print(filename)\n 'sublink_mpb_1030.hdf5'\n \"\"\"\n headers = {\"api-key\": api_key}\n\n r = requests.get(path, params=params, headers=headers)\n\n r.raise_for_status()\n\n if r.headers[\"content-type\"] == \"application/json\":\n return r.json()\n\n if \"content-disposition\" in r.headers:\n filename = r.headers[\"content-disposition\"].split(\"filename=\")[1]\n with open(filename, \"wb\") as f:\n f.write(r.content)\n return filename\n\n return r\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"mond_project/data_utils/data_read_utils.py","file_name":"data_read_utils.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"310434586","text":"import uuid\n\nfrom django.core.management import BaseCommand\n\nfrom api_v1.models.episode import Episode\nfrom api_v1.models.release import Release\nfrom api_v1.services.omdb_api import OMDBApiService\n\n\nclass Command(BaseCommand):\n help = 'Created dynamodb tables'\n\n api = OMDBApiService\n\n def handle(self, *args, **options):\n try:\n self.import_title_data()\n self.import_episodes()\n self.stdout.write(self.style.SUCCESS('Command ran successfully.'))\n except Exception as ex:\n self.stdout.write(f'ERROR > {ex}', )\n\n def import_title_data(self) -> None:\n data = self.api.get_title_data()\n self.save_title_data(data=data)\n\n def import_episodes(self) -> None:\n seasons = self.api.get_total_seasons()\n for season_number in range(1, seasons+1):\n episodes = self.api.get_season_detail(season=season_number)\n for episode in episodes['Episodes']:\n detail = self.api.get_episode_detail(episode_id=episode['imdbID'])\n self.save_episode_detail(data=detail)\n\n def save_title_data(self, data: dict):\n new_release = Release()\n new_release.id = f'{uuid.uuid4()}'\n new_release.name = data['Title']\n new_release.year = data['Year']\n new_release.writer = data['Writer']\n new_release.plot = data['Plot']\n new_release.thumbnail = data['Poster']\n new_release.imdb_id = data['imdbID']\n new_release.imdb_rating = data['imdbRating']\n new_release.save()\n\n def save_episode_detail(self, data: dict):\n new_episode = Episode()\n new_episode.id = f'{uuid.uuid4()}'\n new_episode.title = data['Title']\n new_episode.episode_number = int(data['Episode'])\n new_episode.season = int(data['Season'])\n new_episode.series_imdb_id = data['seriesID']\n new_episode.release = data['Released']\n new_episode.thumbnail = data['Poster']\n new_episode.plot = data['Plot']\n new_episode.imdb_id = data['imdbID']\n new_episode.imdb_rating = data['imdbRating']\n new_episode.save()\n","sub_path":"api_v1/management/commands/import_data_from_omdb.py","file_name":"import_data_from_omdb.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"243440694","text":"# -*- coding:utf-8 -*-\n\n# check extension objects and command ()\n# This program controls the electric hand in RC8.\n# COBOTTA hand control is another command.\n\n# b-cap Lib URL\n# https://github.com/DENSORobot/orin_bcap\n\nimport pybcapclient.bcapclient as bcapclient\n\n# set IP Address , Port number and Timeout of connected RC8\nhost = \"192.168.0.1\"\nport = 5007\ntimeout = 2000\n\n# Connection processing of tcp communication\nm_bcapclient = bcapclient.BCAPClient(host, port, timeout)\nprint(\"Open Connection\")\n\n# start b_cap Service\nm_bcapclient.service_start(\"\")\nprint(\"Send SERVICE_START packet\")\n\n# set Parameter\nName = \"\"\nProvider = \"CaoProv.DENSO.VRC\"\nMachine = (\"localhost\")\nOption = (\"\")\n\n# Connect to RC8 (RC8(VRC)provider)\nhCtrl = m_bcapclient.controller_connect(Name, Provider, Machine, Option)\nprint(\"Connect RC8\")\n\n# Get electric hand position Hand[0].CurPos\nparam = [0,100]\nret = m_bcapclient.controller_execute(hCtrl,'HandMoveA',param)\nparam = [30,100]\nret = m_bcapclient.controller_execute(hCtrl,'HandMoveA',param)\nparam = [15,100]\nret = m_bcapclient.controller_execute(hCtrl,'HandMoveA',param)\n\nparam = [5,100]\nret = m_bcapclient.controller_execute(hCtrl,'HandMoveR',param)\nparam = [-5,100]\nret = m_bcapclient.controller_execute(hCtrl,'HandMoveR',param)\n\nparam = [10,True]\nret = m_bcapclient.controller_execute(hCtrl,'HandMoveH',param)\n\n# Disconnect\nif(hCtrl != 0):\n m_bcapclient.controller_disconnect(hCtrl)\n print(\"Release Controller\")\n# End If\nm_bcapclient.service_stop()\nprint(\"B-CAP service Stop\")\n","sub_path":"others/COBOTTA_gripper.py","file_name":"COBOTTA_gripper.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"277506146","text":"\"\"\"\nSample Input 0\n\n1\n5 4 10\n4 2 4 6 1\n2 1 8 5\nSample Output 0\n\n4\n\"\"\"\n\nfor _ in range(int(input())):\n lenA, lenB, maxSum = [int(x) for x in input().split()]\n arrA = [int(x) for x in input().split()]\n arrB = [int(x) for x in input().split()]\n\n stkA = []\n sums = 0\n cnt = 0\n for i in range(lenA):\n sums += arrA[i]\n if sums >= maxSum: \n cnt += 1\n else:\n break\n cnt = i\n j = 0\n\n while j < lenB and i > 0:\n sums += arrB[j]\n j+= 1 \n while sums > maxSum and i > 0: \n sums -= arrA[i]\n i -= 1\n \n if sums < maxSum and i+j>cnt:\n count=i+j \n \n\n print(cnt) \n \n \n ","sub_path":"Hackerrank/game_of_two.py","file_name":"game_of_two.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"485740064","text":"print (\"BIENVENIDO A EMPAREJANDO.COM\")\n\nnombre= input(\"Tu nombre:\")\nano= int(input( \"¿Año de nacimiento?\" ))\ntegusta= input(\"¿Te gusta taburete?\")\n\nedad = 2020 - ano\n\nprint (\"hola\", nombre, \". Si no me equivoco tienes\", edad, \"años.\")\n\nif tegusta == \"si\" or tegusta == \"Si\":\n print('OK Boomer, lo tuyo va a ser un caso difícil.')\nelif tegusta == \"no\" or tegusta == \"No\":\n print('Bueno, al menos es un comienzo. Veremos qué se puede hacer contigo.')\n\n\n\n\ndiccionario={'nombre':nombre,'edad':edad,'Taburete?':tegusta}\nfor v in diccionario:\n print(diccionario[v])","sub_path":"ejercicio4.py","file_name":"ejercicio4.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"469882015","text":"from django.conf.urls import include, patterns, url\nfrom django.views.generic import RedirectView\nfrom django.core.urlresolvers import reverse\n\n\nurlpatterns = patterns(\n 'moocng.profile.views',\n url(r'^user/timeline$', 'profile_timeline',\n name='profile_timeline'),\n url(r'^user/groups$', 'profile_groups',\n name='profile_groups'),\n\n\n url(r'^user/courses/(?P[\\d]+)$', 'profile_courses',\n {'byid': True}, name='profile_courses_byid'),\n\n url(r'^user/courses/(?P[-\\+@\\w.]*)$', 'profile_courses',\n name='profile_courses'),\n\n url(r'^user/courses/$', 'profile_courses',\n name='profile_courses'),\n\n url(r'^user/badges/(?P[\\d]+)$', 'profile_badges',\n {'byid': True}, name='profile_badges_byid'),\n\n url(r'^user/badges/(?P[-\\+@\\w.]*)$', 'profile_badges',\n name='profile_badges'),\n\n url(r'^user/badges/$', 'profile_badges',\n name='profile_badges'),\n\n url(r'^user/badge/(?P[-\\+@\\w.]*)/(?P\\d+)$', 'profile_badge',\n name='profile_badge'),\n\n url(r'^user/badge/(?P\\d+)$', 'profile_badge',\n name='profile_badge'),\n\n url(r'^user/calendar/$', 'profile_calendar',\n name='profile_calendar'),\n \n url(r'^user/profile/(?P[\\d]+)$', 'profile_user',\n {'byid': True}, name='profile_user_byid'),\n\n url(r'^user/profile/(?P[-\\+@\\w.]*)$', 'profile_user',\n name='profile_user'),\n\n url(r'^user/profile/$', 'profile_user',\n name='profile_user'),\n\n url(r'^user/posts/(?P[\\d]+)$', 'profile_posts',\n {'byid': True}, name='profile_posts_byid'),\n\n url(r'^user/posts/(?P[-\\+@\\w.]*)$', 'profile_posts',\n name='profile_posts'),\n\n url(r'^user/posts/$', 'profile_posts',\n name='profile_posts'),\n\n url(r'^user/posts/search/(?P[-\\w.]+)$', 'profile_posts_search',\n name='profile_posts_search'),\n\n url(r'^user/posts/hashtag/(?P[-\\w.]+)$', 'profile_posts_search',\n {'hashtag': True}, name='profile_posts_hashtag'),\n\n url(r'^user/loadMorePosts/(?P[-\\w]+)/(?P[-\\w.]+)$', 'load_more_posts',\n name='load_more_posts'),\n\n url(r'^user/loadMorePosts/search/(?P[-\\w]+)/(?P[-\\w.]+)$', 'load_more_posts',\n {'search': True}, name='load_more_posts_search'),\n\n url(r'^user/loadMorePosts/hashtag/(?P[-\\w]+)/(?P[-\\w.]+)$', 'load_more_posts',\n {'search': True, 'hashtag': True}, name='load_more_posts_hashtag'),\n\n url(r'^user/userFollow/(?P[-\\w.]+)/(?P[-\\w.]+)$', 'user_follow',\n name='user_follow'),\n\n url(r'^user/retweet/(?P[-\\w.]+)$', 'retweet',\n name='retweet'),\n\n url(r'^user/reply/(?P[-\\w.]+)$', 'reply',\n name='reply'),\n\n url(r'^user/api/posts/(?P[\\d]+)$', 'profile_posts',\n {'api': True, 'byid': True}, name='profile_posts_api_byid'),\n\n url(r'^user/api/posts/(?P[-\\+@\\w.]*)$', 'profile_posts',\n {'api': True}, name='profile_posts_api'),\n\n url(r'^user/api/posts/$', 'profile_posts',\n {'api': True}, name='profile_posts_api'),\n\n url(r'^user/api/posts/search/(?P[-\\w.]+)$', 'profile_posts_search',\n {'hashtag': False, 'api': True}, name='profile_posts_search_api'),\n\n url(r'^user/api/posts/hashtag/(?P[-\\w.]+)$', 'profile_posts_search',\n {'hashtag': True, 'api': True}, name='profile_posts_hashtag_api'),\n)\n","sub_path":"moocng/profile/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"412142317","text":"import numpy as np\ndef calc_hist(img):\n histogram = np.zeros((256))\n for i in range(len(img)):\n for j in range(img[0].size):\n histogram[img[j][i]] += 1\n return histogram\n\ndef find_max(arr):\n maximum = 0\n for i in range(len(arr)):\n if arr[i]>maximum:\n maximum = arr[i]\n return maximum\n\ndef hist_filter(img):\n histogram = calc_hist(img)\n if find_max(histogram) > 900:\n return 0\n sum=0\n for i in range(25):\n sum += histogram[i]\n if sum >= 1400:\n return 0\n i=1\n j=25\n while j<256:\n sum -= histogram[i-1]\n sum += histogram[j]\n i += 1\n j += 1\n if sum >= 1400:\n return 0\n sum = 0\n for i in range(50):\n sum += histogram[i]\n if sum >= 1850:\n return 0\n i = 1\n j = 50\n while j < 256:\n sum -= histogram[i - 1]\n sum += histogram[j]\n i += 1\n j += 1\n if sum >= 1850:\n return 0\n return 1","sub_path":"submited for grading/hiatogram_filter.py","file_name":"hiatogram_filter.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"652794607","text":"#Will need to eventually get this script to automatically pull data off of the yahoo url.\n#DAVID THIS IS YOU!!\n# http://stackoverflow.com/questions/16283799/how-to-read-a-csv-file-from-a-url-python\n\n#Stock prices located at: http://chartapi.finance.yahoo.com/instrument/1.0/[TICKER]/chartdata;type=quote;range=[RANGE]d/csv\n\n\n\n# USAGE NOTE: YOU MUST CHOP OFF THE FIRST 32 OR SO ROWS FROM THE CSV RIGHT AFTER YOU DOWNLOAD IT FROM YAHOO (CHOP OFF THE HEADER THAT YAHOO AUTOMATICALLY GENERATES)\n\n\n\nimport csv\nexecfile('./ImportData.py') #Prepare existing data\n\n\n#IMPORT NEW DATA FROM CSVs WHICH WERE DOWNLOADED FROM YAHOO\n#IT IS ASSUMED THAT THE CSVs ARE IN OLD-TO-NEW ORDER (MORE RECENT PRICES ARE AT BOTTOM)\n#IT IS ALSO CRUCIAL THAT EXISTING DATA CSV FILES ARE STRICTLY ORDERED IN OLD-TO-NEW ORDER\nwith open('NewDataUPRO.csv') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n #Declare data arrays here\n New_UPRO_Prices = []\n New_UPRO_Datetimes = []\n for row in csvreader:\n New_UPRO_Prices.append(float(row[1]))\n New_UPRO_Datetimes.append(datetime.fromtimestamp(float(row[0])))\nfor n in range(0,len(New_UPRO_Prices)): #check every price to be imported\n if New_UPRO_Datetimes[n] > UPRO_Datetimes[len(UPRO_Datetimes) - 1]: #if it really is a new data point\n UPRO_Prices.append(New_UPRO_Prices[n]) #add it to the data\n UPRO_Datetimes.append(New_UPRO_Datetimes[n])\nwith open('DataTableUPRO.csv', 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n for n in range(0,len(UPRO_Prices)):\n csvwriter.writerow([int(UPRO_Datetimes[n].strftime(\"%s\")), UPRO_Prices[n]])\n\n\n\n\nwith open('NewDataSPXU.csv') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n #Declare data arrays here\n New_SPXU_Prices = []\n New_SPXU_Datetimes = []\n for row in csvreader:\n New_SPXU_Prices.append(float(row[1]))\n New_SPXU_Datetimes.append(datetime.fromtimestamp(float(row[0])))\nfor n in range(0,len(New_SPXU_Prices)): #check every price to be imported\n if New_SPXU_Datetimes[n] > SPXU_Datetimes[len(SPXU_Datetimes) - 1]: #if it really is a new data point\n SPXU_Prices.append(New_SPXU_Prices[n]) #add it to the data\n SPXU_Datetimes.append(New_SPXU_Datetimes[n])\nwith open('DataTableSPXU.csv', 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n for n in range(0,len(SPXU_Prices)):\n csvwriter.writerow([int(SPXU_Datetimes[n].strftime(\"%s\")), SPXU_Prices[n]])\n\n\nwith open('NewDataDUST.csv') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n New_DUST_Prices = []\n New_DUST_Datetimes = []\n for row in csvreader:\n New_DUST_Prices.append(float(row[1]))\n New_DUST_Datetimes.append(datetime.fromtimestamp(float(row[0])))\nfor n in range(0,len(New_DUST_Prices)): #check every price to be imported\n if New_DUST_Datetimes[n] > DUST_Datetimes[len(DUST_Datetimes) - 1]: #if it really is a new data point\n DUST_Prices.append(New_DUST_Prices[n]) #add it to the data\n DUST_Datetimes.append(New_DUST_Datetimes[n])\nwith open('DataTableDUST.csv', 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n for n in range(0,len(DUST_Prices)):\n csvwriter.writerow([int(DUST_Datetimes[n].strftime(\"%s\")), DUST_Prices[n]])\n\n \n\n\nwith open('NewDataNUGT.csv') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n New_NUGT_Prices = []\n New_NUGT_Datetimes = []\n for row in csvreader:\n New_NUGT_Prices.append(float(row[1]))\n New_NUGT_Datetimes.append(datetime.fromtimestamp(float(row[0])))\nfor n in range(0,len(New_NUGT_Prices)): #check every price to be imported\n if New_NUGT_Datetimes[n] > NUGT_Datetimes[len(NUGT_Datetimes) - 1]: #if it really is a new data point\n NUGT_Prices.append(New_NUGT_Prices[n]) #add it to the data\n NUGT_Datetimes.append(New_NUGT_Datetimes[n])\nwith open('DataTableNUGT.csv', 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n for n in range(0,len(NUGT_Prices)):\n csvwriter.writerow([int(NUGT_Datetimes[n].strftime(\"%s\")), NUGT_Prices[n]])\n","sub_path":"UpdateData.py","file_name":"UpdateData.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"240865167","text":"print(\"begin of work\")\r\n\r\nhelloString = \"\"\r\nfReadName = 'r.txt'\r\nfWriteName = 'w.txt'\r\n\r\nfileToWrite = open(fWriteName, 'w')\r\nfileToRead = open(fReadName, 'r')\r\n\r\n#with open('r.txt') as fileToRead:\r\nhelloString = fileToRead.read(100)\r\nfileToRead.seek(0,0)\r\nfor line in fileToRead:\r\n\tprint(line)\r\n#f.closed\r\nfileToWrite.write(helloString)\r\n\r\nfileToRead.close()\r\nfileToWrite.close()\r\n\r\nprint(\"end of work\")\r\n","sub_path":"readWriteFile/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"434827862","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('myuser', '0005_auto_20151218_1114'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='participant',\n name='affiliation',\n field=models.CharField(max_length=70, verbose_name=b'Work affiliation'),\n ),\n migrations.AlterField(\n model_name='participant',\n name='degree',\n field=models.CharField(help_text=b'If you have multiple degrees, please select the highest degree achieved, relevant to this study.', max_length=3, verbose_name=b'Highest relevant degree category', choices=[(b'MS', b'MS'), (b'MD', b'MD'), (b'PhD', b'PhD'), (b'DVM', b'DVM')]),\n ),\n migrations.AlterField(\n model_name='participant',\n name='degree_field',\n field=models.CharField(help_text=b'If you have multiple degrees, please describe the most relevant degree to this study.', max_length=30, verbose_name=b'Highest relevant degree'),\n ),\n migrations.AlterField(\n model_name='participant',\n name='experience',\n field=models.PositiveSmallIntegerField(help_text=b'Number of years of relevant work experience.', verbose_name=b'Relevant years of experience'),\n ),\n ]\n","sub_path":"project/myuser/migrations/0006_auto_20160104_1610.py","file_name":"0006_auto_20160104_1610.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"624525350","text":"import feedparser\nimport requests\n\nfrom time import mktime\nfrom datetime import datetime\nfrom urllib.parse import urlparse\nfrom bs4 import BeautifulSoup \nfrom django.utils.text import slugify\nfrom django.core.management.base import BaseCommand\n\nfrom blog.models import Post\nfrom locator.models import Category\nfrom django.contrib.auth.models import User\n\nclass Command(BaseCommand):\n args = ''\n help = 'Fetch list of blogs from rss feed'\n\n def handle(self, **options):\n\n feed = feedparser.parse('https://www.headphonezone.in/sitemap_products_1.xml?from=373372541&to=1398753460287')\n\n for post in Post.objects.all():\n post.delete()\n\n loop_max = len(feed['entries'])\n category = Category.objects.get(id=\"ce867a33-fddf-4e60-89ec-179c9792889d\")\n author = User.objects.get(pk=1)\n\n for i in range(0, loop_max):\n if feed['entries'][i]:\n blog_post = Post()\n blog_post.title = feed['entries'][i].title\n blog_post.slug = slugify(feed['entries'][i].title)\n link = self.parse_url(feed['entries'][i].link)\n blog_post.external_url = link\n blog_post.category = category\n blog_post.sender = \"indiafashionblogger\"\n blog_post.author = author\n blog_post.short_description = feed['entries'][i].description\n blog_post.body = self.get_content(link)\n blog_post.created = datetime.fromtimestamp(\n mktime(feed['entries'][i].published_parsed))\n print(blog_post.short_description)\n blog_post.save()\n\n def get_content(self, url):\n print(\"requesting url {}\".format(url))\n response = requests.get(url)\n content = BeautifulSoup(response.content, \"lxml\")\n return repr(content.find(class_=\"content-main\"))\n\n def parse_url(self, url):\n result = urlparse(url)\n print(\"url\", result)\n return \"\".join([\"https://\", result.netloc, result.path])\n# */30 * * * * /usr/bin/python3 /home/manage.py get_post 5\n","sub_path":"locator/management/commands/headphonesindia.py","file_name":"headphonesindia.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"264153631","text":"import logging\n\n# create logger\nlogger = logging.getLogger('custom_logger')\n\n\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nimport datetime\nimport json\nimport paho.mqtt.client as mqtt\nimport tensorflow as tf\nimport keras\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom json import JSONEncoder\nimport numpy\nimport math\n\nimport time\nimport re\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n\nimport pickle\nimport zlib\n\nMQTT_URL = '172.20.8.119'\nMQTT_PORT = 1883\n\n\n#IMAGENET_PATH = '/mnt/dataset/subset'\n#TOTAL_IMAGES = 82000\nTARGET_SIZE = (32, 32)\nBATCH_SIZE = 32\nEPOCHS = 1\n\nTOTAL_CLIENTS_NUMBER = 16\nCLIENT_NUMBER = 3\n\nGPU_INDEX = 0\nGPU_NAME = ''\n\nclass FederatedTask():\n\n def wait_for_update_from_server(self):\n while True:\n time.sleep(10)\n\n if self.new_weights['update'] is not None:\n # set new weights\n self.receive_update_from_server(self.new_weights['update'])\n \n # reset\n self.new_weights['update'] = None\n\n\n def receive_update_from_server(self, weights):\n logger.info(\"Updated weights received\")\n\n self.model.set_weights(weights)\n\n logger.info(\"Model weights updated successfully.\")\n\n self.training()\n\n self.send_local_update_to_server()\n\n\n def training(self):\n if GPU_NAME != '':\n with tf.device(GPU_NAME):\n self.training_core(self)\n else:\n self.training_core(self)\n\n\n def training_core(self):\n time_start = time.time()\n\n #train_history = self.model.fit_generator(self.train_it, steps_per_epoch=math.ceil(TOTAL_IMAGES / BATCH_SIZE), epochs=EPOCHS)\n train_history = self.model.fit(self.train_it[0], self.train_it[1], batch_size=BATCH_SIZE, epochs=EPOCHS)\n\n logger.info(f\"[TRAIN-TIME] Completed local training in {(time.time() - time_start) / 60} minutes.\")\n\n self.epoch += 1\n\n #SAVES CHECKPOINT\n self.save_checkpoint()\n \n #SAVES LOG\n print(train_history.history)\n self.save_log(train_history.history['loss'][-1], train_history.history['accuracy'][-1], (time.time() - time_start))\n \n return self.model\n\n\n def save_log(self, loss, accuracy, time):\n #log\n with open('./snapshots/log.csv', 'a') as fd:\n if self.epoch == 0:\n fd.write(\"epoch;accuracy;loss;time\\n\")\n\n fd.write(f\"{self.epoch};{accuracy};{loss};{time}\\n\")\n\n logger.info(f\"Saved log on 'snapshots/log.csv'.\")\n\n\n def save_checkpoint(self):\n self.model.save_weights(\"snapshots/Local-Weights-node01-MobileNetV2-{epoch:02d}.hdf5\".format(epoch=self.epoch))\n logger.info(\"Saved checkpoint 'Local-Weights-node01-MobileNetV2-{epoch:02d}.hdf5'.\".format(epoch=self.epoch))\n\n \n # UNUSED with compressed messages\n class NumpyArrayEncoder(JSONEncoder):\n def default(self, obj):\n if isinstance(obj, numpy.ndarray):\n return obj.tolist()\n return JSONEncoder.default(self, obj)\n\n\n def send_local_update_to_server(self):\n\n # select training data related to selected clients\n model_weights = self.model.get_weights()\n\n # build message object\n send_msg = {\n 'device': self.client_id,\n 'data': model_weights\n }\n\n # publishes on MQTT topic\n compressed = zlib.compress(pickle.dumps(send_msg))\n #publication = self.client.publish(\"topic/fl-broadcast\", json.dumps(send_msg, cls=self.NumpyArrayEncoder), qos=1)\n # send compressed message\n publication = self.client.publish(\"topic/fl-broadcast\", compressed, qos=1)\n\n logger.debug(f\"Result code: {publication[0]} Mid: {publication[1]}\")\n\n while publication[0] != 0:\n self.client.connect(MQTT_URL, MQTT_PORT, 60)\n publication = self.client.publish(\"topic/fl-broadcast\", json.dumps(send_msg, cls=self.NumpyArrayEncoder), qos=1)\n logger.debug(f\"Result code: {publication[0]} Mid: {publication[1]}\")\n\n\n @staticmethod\n def on_message(client, userdata, msg):\n logger.info(\"New model update received \")\n\n try:\n logger.info(\"Loading Weights from message ...\")\n #weights = json.loads(msg.payload)\n \n # Decompress weights\n userdata['new_weights']['update'] = pickle.loads(zlib.decompress(msg.payload))\n \n logger.info(\"Weights loaded successfully\")\n\n #userdata['new_weights']['update'] = weights\n \n\n except Exception as e:\n logger.warning(f'Error loading weights: {e}')\n\n\n @staticmethod\n def on_publish(client, userdata, mid):\n logger.info(f\"published message to 'topic/fl-broadcast' with mid: {mid}\")\n\n\n @staticmethod\n def on_connect(client, userdata, flags, rc):\n if rc == 0:\n logger.info(\"Connected to broker\")\n client.subscribe(\"topic/fl-update\")\n\n else: \n logger.info(\"Connection failed. Retrying in 1 second...\")\n time.sleep(1)\n client.connect(MQTT_URL, MQTT_PORT, 60)\n\n\n @staticmethod\n def on_subscribe(client, userdata, mid, granted_qos):\n logger.info(\"Subscribed to topic/fl-update\")\n\n\n def get_last_weights(self, path):\n weights = [join(path, f) for f in listdir(path)\n if isfile(join(path, f)) and 'Averaged-Weights' in f]\n\n weights.sort(reverse=True)\n\n return weights\n\n \n def main(self):\n self.client_id = client_id\n \n try:\n os.mkdir(\"snapshots\")\n except:\n pass\n\n # INIT MODEL\n self.model = keras.applications.mobilenet_v2.MobileNetV2(input_shape = TARGET_SIZE + (3,), classes = 10, weights = None)\n self.model = keras.applications.ResNet50V2(input_shape = TARGET_SIZE + (3,), classes = 10, weights = None)\n self.model.summary()\n # Compile the model\n self.model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n \n weights_checkpoints = self.get_last_weights('./snapshots')\n self.epoch = 0\n\n if len(weights_checkpoints) > 0:\n logging.info(f\"Loading Weights from {weights_checkpoints[0]} ...\")\n self.model.load_weights(weights_checkpoints[0])\n logging.info(\"Done.\\n\")\n\n # get last epoch number\n p = re.compile(\"-(\\w+).hdf5\")\n result = p.search(weights_checkpoints[0])\n self.epoch = int(result.group(1))\n\n \n # create generator\n #datagen = ImageDataGenerator()\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() \n\n # convert and preprocess\n y_train = keras.utils.to_categorical(y_train, 10) \n y_test = keras.utils.to_categorical(y_test, 10)\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n x_train /= 255\n x_test /= 255\n \n # prepare an iterators for each dataset\n section_length = math.ceil(len(x_train) / TOTAL_CLIENTS_NUMBER)\n\n starting_index = (section_length) * (CLIENT_NUMBER -1)\n\n ending_index = min(len(x_train), starting_index + section_length)\n logging.info(f\"starting_index: {starting_index}, ending_index: {ending_index}\")\n self.train_it = (x_train[starting_index : ending_index], y_train[starting_index : ending_index])\n\n # create mqtt client\n self.new_weights = {'update': None}\n\n self.client = mqtt.Client(userdata={'new_weights': self.new_weights})\n self.client.connect(MQTT_URL, MQTT_PORT, 60)\n # callbacks \n self.client.on_connect = self.on_connect\n self.client.on_subscribe = self.on_subscribe\n self.client.on_publish = self.on_publish\n self.client.on_message = self.on_message\n\n \n self.client.loop_start()\n\n\n def __init__(self, client_id=-1):\n try:\n GPU_NAME = tf.config.experimental.list_physical_devices('GPU')[GPU_INDEX]\n \n print(\"GPU_INDEX: \", GPU_INDEX, \"GPU_NAME: \", gpu_name)\n\n with tf.device(GPU_NAME):\n self.main()\n \n except:\n\n print(\"\\nNO GPU DETECTED!\\n\")\n self.main()","sub_path":"Client/fl_runtime_CIFAR10_multi_client.py","file_name":"fl_runtime_CIFAR10_multi_client.py","file_ext":"py","file_size_in_byte":8381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"29164508","text":"from django.test import TestCase\nfrom django.urls import reverse\n\nfrom waffle.models import Switch\n\nfrom . import forms\nfrom .models import Registrant, Location, EmailConfirmation\nfrom .utils import generate_random_key\nfrom django.contrib.messages import get_messages\nfrom portal.services import NotifyService\nfrom portal import container\n\n\nclass RegisterView(TestCase):\n def test_start_page(self):\n response = self.client.get(reverse(\"register:start\"))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, \"register/start.html\")\n\n def test_email_page(self):\n response = self.client.get(reverse(\"register:registrant_email\"))\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, \"register/registrant_email.html\")\n\n def test_name_page(self):\n r = Registrant.objects.create(email=\"test@test.com\")\n session = self.client.session\n session[\"registrant_id\"] = str(r.id)\n session.save()\n\n response = self.client.get(reverse(\"register:registrant_name\"))\n self.assertEqual(response.status_code, 200)\n\n def test_confirmation_page_logged_in(self):\n email = \"test@test.com\"\n r = Registrant.objects.create(email=email)\n\n # add id and email to session (happens at confirmation)\n session = self.client.session\n session[\"registrant_id\"] = str(r.id)\n session[\"registrant_email\"] = r.email\n session.save()\n\n response = self.client.get(reverse(\"register:confirmation\"))\n self.assertEqual(response.status_code, 200)\n\n\nclass RegisterEmailConfirmation(TestCase):\n def setUp(self):\n container.notify_service.override(NotifyService()) # Prevent sending emails\n\n def test_email_form_empty(self):\n form = forms.EmailForm(data={})\n\n self.assertEqual(form.errors[\"email\"], [\"This field is required.\"])\n\n def test_can_confirm_email(self):\n email = \"test@test.com\"\n # submit email\n response = self.client.post(\n reverse(\"register:registrant_email\"), data={\"email\": email}\n )\n self.assertEqual(response.status_code, 302)\n\n # confirmation screen\n response = self.client.get(reverse(\"register:email_submitted\"))\n\n self.assertContains(response, \"Confirm your email address\")\n self.assertContains(response, email)\n\n # check the confirmation record\n confirm = EmailConfirmation.objects.get(email=email)\n self.assertEquals(confirm.email, email)\n\n # generate the confirmation link\n confirm_url = reverse(\n \"register:email_confirm\",\n kwargs={\"pk\": confirm.pk},\n )\n\n # visit the confirmation link\n self.client.get(confirm_url)\n\n # confirmation record should be deleted\n self.assertIsNone(\n EmailConfirmation.objects.filter(email=email).first(),\n )\n\n # email confirmed, should be able to get to the name step\n self.client.get(reverse(\"register:registrant_name\"))\n self.assertEqual(response.status_code, 200)\n\n\nclass RegisterConfirmedEmailRequiredPages(TestCase):\n def test_registrant_name_not_logged_in(self):\n response = self.client.get(reverse(\"register:registrant_name\"))\n self.assertRedirects(response, reverse(\"register:registrant_email\"))\n message = list(get_messages(response.wsgi_request))[0]\n self.assertEqual(message.tags, \"error\")\n\n def test_location_address_not_logged_in(self):\n response = self.client.get(\n reverse(\"register:location_step\", kwargs={\"step\": \"address\"})\n )\n self.assertRedirects(response, reverse(\"register:registrant_email\"))\n message = list(get_messages(response.wsgi_request))[0]\n self.assertEqual(message.tags, \"error\")\n\n def test_location_category_not_logged_in(self):\n response = self.client.get(\n reverse(\"register:location_step\", kwargs={\"step\": \"category\"})\n )\n self.assertRedirects(response, reverse(\"register:registrant_email\"))\n message = list(get_messages(response.wsgi_request))[0]\n self.assertEqual(message.tags, \"error\")\n\n def test_location_name_not_logged_in(self):\n response = self.client.get(\n reverse(\"register:location_step\", kwargs={\"step\": \"name\"})\n )\n self.assertRedirects(response, reverse(\"register:registrant_email\"))\n message = list(get_messages(response.wsgi_request))[0]\n self.assertEqual(message.tags, \"error\")\n\n def test_location_contact_not_logged_in(self):\n response = self.client.get(\n reverse(\"register:location_step\", kwargs={\"step\": \"contact\"})\n )\n self.assertRedirects(response, reverse(\"register:registrant_email\"))\n message = list(get_messages(response.wsgi_request))[0]\n self.assertEqual(message.tags, \"error\")\n\n def test_location_summary_not_logged_in(self):\n response = self.client.get(\n reverse(\"register:location_step\", kwargs={\"step\": \"summary\"})\n )\n self.assertRedirects(response, reverse(\"register:registrant_email\"))\n message = list(get_messages(response.wsgi_request))[0]\n self.assertEqual(message.tags, \"error\")\n\n def test_confirmation_not_logged_in(self):\n response = self.client.get(reverse(\"register:confirmation\"))\n self.assertRedirects(response, reverse(\"register:registrant_email\"))\n message = list(get_messages(response.wsgi_request))[0]\n self.assertEqual(message.tags, \"error\")\n\n\nclass RegisterLocationDetailsValidation(TestCase):\n def test_location_category_empty(self):\n form = forms.LocationCategoryForm(data={})\n\n self.assertEqual(form.errors[\"category\"], [\"This field is required.\"])\n\n def test_location_name_empty(self):\n form = forms.LocationNameForm(data={})\n\n self.assertEqual(form.errors[\"name\"], [\"This field is required.\"])\n\n def test_location_address_address_field_empty(self):\n form = forms.LocationAddressForm(data={\"address\": \"\"})\n\n self.assertEqual(form.errors[\"address\"], [\"This field is required.\"])\n\n def test_location_address_city_field_empty(self):\n form = forms.LocationAddressForm(data={\"city\": \"\"})\n\n self.assertEqual(form.errors[\"city\"], [\"This field is required.\"])\n\n def test_location_address_province_field_empty(self):\n form = forms.LocationAddressForm(data={\"province\": \"\"})\n\n self.assertEqual(form.errors[\"province\"], [\"This field is required.\"])\n\n def test_location_address_postal_field_empty(self):\n form = forms.LocationAddressForm(data={\"postal_code\": \"\"})\n\n self.assertEqual(form.errors[\"postal_code\"], [\"This field is required.\"])\n\n def test_location_contact_email_empty(self):\n form = forms.LocationContactForm(data={\"contact_email\": \"\"})\n\n self.assertEqual(form.errors[\"contact_email\"], [\"This field is required.\"])\n\n def test_location_contact_email_format(self):\n form = forms.LocationContactForm(data={\"contact_email\": \"notanemail\"})\n\n self.assertEqual(form.errors[\"contact_email\"], [\"Enter a valid email address.\"])\n\n def test_location_contact_phone_empty(self):\n form = forms.LocationContactForm(data={\"contact_phone\": \"\"})\n\n self.assertEqual(form.errors[\"contact_phone\"], [\"This field is required.\"])\n\n def test_location_contact_phone_format(self):\n form = forms.LocationContactForm(data={\"contact_phone\": \"notaphonenumber\"})\n\n self.assertEqual(\n form.errors[\"contact_phone\"],\n [\"Enter a valid phone number (e.g. +12125552368).\"],\n )\n\n\nclass LocationModel(TestCase):\n def test_location_model_generates_short_code_on_save(self):\n location = Location.objects.create(\n category=\"category\",\n name=\"Name of venue\",\n address=\"Address line 1\",\n city=\"Ottawa\",\n province=\"ON\",\n postal_code=\"K1K 1K1\",\n contact_email=\"test@test.com\",\n contact_phone=\"613-555-5555\",\n )\n\n self.assertNotEqual(location.short_code, \"\")\n self.assertEqual(len(location.short_code), 8)\n self.assertTrue(location.short_code.isalnum)\n\n\nclass Utils(TestCase):\n def test_generate_short_code_default_length(self):\n code = generate_random_key()\n self.assertEqual(len(code), 8)\n\n def test_generate_short_code_custom_length(self):\n code = generate_random_key(5)\n self.assertEqual(len(code), 5)\n\n def test_generate_short_code_alphanumeric(self):\n code = generate_random_key()\n self.assertTrue(code.isalnum())\n","sub_path":"register/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"594514","text":"import zmq\nimport hashlib\nimport hash as hasher\nfrom math import ceil\nimport os\nimport json\nimport sys\n\n\n\n\ndef getHashis(archivo,size,MAX_BUFFER = 1024*1024*100):\n l = []\n hashcomplete=hasher.hasheador(archivo,size,MAX_BUFFER).encode()\n l.append(hashcomplete)\n rango = ceil(size/MAX_BUFFER)\n with open(archivo,'rb') as f:\n for i in range(0, rango):\n f.seek(i*MAX_BUFFER)\n data=f.read(MAX_BUFFER)\n hashi=hasher.hashitos(data)\n l.append(hashi.encode())\n print(l[-1].decode())\n return l\n\nif __name__ == \"__main__\":\n context=zmq.Context()\n socketproxy=context.socket(zmq.REQ)\n socketproxy.connect(\"tcp://192.168.8.181:5555\")\n\n MAX_BUFFER=1024*1024*100\n\n #socketproxy.send_multipart(hashlist)\n\n servers = {}\n print(\"=====================================\\n\")\n print('BIENVENIDO AL SERVIDOR DE ARCHIVOS\\n\\t')\n print('=====================================')\n identity = input('Ingrese su username:').encode()\n while True:\n print('=====================================')\n opc = input('Ingrese algun comando: (help para ayuda o exit para salir) \\n')\n op = opc.split(' ')\n if op[0] == 'exit':\n #socket.send_multipart([b'',b'exit'])\n #message = socket.recv()\n break\n elif op[0] == 'help':\n print('Lista de Comandos:\\n\\t')\n print('* send filename\\n')\n print('* download filename\\n')\n\n elif op[0] == 'send':\n archivo = op[1]\n filename, file_extension = os.path.splitext(archivo)\n size= os.path.getsize(archivo)\n\n print('Obteniendo lista de servidores')\n hashlist=[b'client',b'send',filename.encode(),file_extension.encode()]\n hashish = getHashis(archivo,size)\n hashlist +=hashish\n\n socketproxy.send_multipart(hashlist)\n status, *response = socketproxy.recv_multipart()\n if status == b'error':\n print(response[0].decode())\n else:\n print(\"Procesando\")\n i = 0\n for r in response:\n\n with open(archivo,'rb') as f:\n f.seek((i*MAX_BUFFER))\n data=f.read(MAX_BUFFER)\n hashname=hashish[i+1]\n if r.decode() in servers:\n servers[r.decode()].send_multipart([b'sending',hashname,data])\n servers[r.decode()].recv_multipart()\n else:\n servers[r.decode()] = context.socket(zmq.REQ)\n socket = servers[r.decode()]\n socket.identity = identity\n socket.connect(\"tcp://{}\".format(r.decode()))\n socket.send_multipart([b'sending',hashname,data])\n socket.recv_multipart()\n i+=1\n print(\"Terminado\\t\\n\")\n print(\"Archivo guardado como: {}\".format(hashish[0].decode()))\n elif op[0] == 'download':\n indice=0\n archivo = op[1]\n print('Obteniendo lista de servidores')\n lista = [b'client',b'download',archivo.encode()]\n socketproxy.send_multipart(lista)\n status, *response = socketproxy.recv_multipart()\n if status == b'error':\n print(response[0].decode())\n else:\n servers = {}\n serversend={}\n fullName, *ips = response\n for s in ips:\n print(s.decode())\n key,value = s.decode().split(';')\n servers[key] = value\n print(fullName.decode())\n print(servers.values())\n serverip = [values for values in servers.values()]\n serverhashis=[keys for keys in servers.keys()]\n for ip in serverip:\n \tif ip in serversend:\n \t\tserversend[ip].send_multipart([b'downloading',serverhashis[indice].encode()])\n \t\tprint('la ip es:{}, el hash almacenado es:{}'.format(ip, serverhashis[indice]))\n \t\tdata=serversend[ip].recv_multipart()\n \t\twith open(fullName, 'ab') as descarga:\n \t\t\tdescarga.write(data[1])\n \t\tindice+=1\n \t\tprint(indice)\n \telse:\n \t\tserversend[ip]=context.socket(zmq.REQ)\n \t\tsocket=serversend[ip]\n \t\tprint('la ip es:{}, el hash almacenado es:{}'.format(ip, serverhashis[indice]))\n \t\t#socket.identity=identity\n \t\tsocket.connect(\"tcp://{}\".format(ip))\n \t\tsocket.send_multipart([b'downloading', serverhashis[indice].encode()])\n \t\tdata=socket.recv_multipart()\n \t\t#print(data[1].decode())\n \t\twith open(fullName, 'ab') as descarga:\n \t\t\tdescarga.write(data[1])\n \t\tindice+=1\n \t\tprint(indice)\n","sub_path":"tarea3/tarea3/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"239239359","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn import preprocessing\nfrom sklearn import decomposition\nfrom sklearn.preprocessing import MinMaxScaler\n\nfile = 'train.csv'\n\n\ndef get_raw():\n\tdf = pd.read_csv(file)\n\treturn(df)\n\n\n\ndef get_cut():\n\tdf = get_raw()\n\tdf['SalePrice'] = np.log(df['SalePrice'])\n\n\t# Get rid of features missing >10% of rows\n\tmissing = df.isnull().sum() / df.shape[0]\n\tmissing_list = list(missing[missing > 0.1].index)\n\tdf_cut = df.drop(missing_list, axis=1)\n\n\t# Get other missing features\n\tmissing = df_cut.isnull().sum() / df_cut.shape[0]\n\tmissing = missing[missing > 0]\n\n\t# Remove significant features form new missing list\n\tmissing_list = list(missing.index)\n\tmissing_list.remove('BsmtQual')\n\tmissing_list.remove('GarageYrBlt')\n\tdf_cut = df_cut.drop(missing_list, axis=1)\n\n\t# Encode into numerical values\n\tdf_cut['BsmtQual'] = pd.Categorical(df_cut['BsmtQual']).codes\n\n\t# Imputing missing observations\n\t\t# Impute 'GarageYrBlt' using mean\n\timputer = preprocessing.Imputer(strategy='median')\n\tyrBlt = imputer.fit_transform(df_cut['GarageYrBlt'].reshape(-1,1))\n\tyrBlt = pd.DataFrame(yrBlt, columns=['GarageYrBlt'])\n\t\t# Impute BsmtQual using most frequent value\n\tbsmtQual = df_cut['BsmtQual'].replace({-1:3})\n\n\t# Concat dataframe together\n\tdf_cut['BsmtQual'] = bsmtQual \n\tdf_cut['GarageYrBlt'] = yrBlt\n\n\t# Removing outliers based on 'SalePrice'\n\toutliers = np.sort(df_cut['SalePrice'])[-2:]\n\tdf_cut = df_cut[df_cut['SalePrice'] < np.min(outliers)]\n\n\n\treturn(df_cut)\n\n\n# Returns normalized df of significant numerical features\ndef get_num():\n\tdf = get_cut()\n\n\tdf_num = df[['1stFlrSF', 'TotalBsmtSF', 'GarageArea',\n 'YearBuilt', 'GrLivArea', 'OpenPorchSF', 'YearRemodAdd', 'GarageYrBlt']]\n\n # PCA\n\tpca = decomposition.PCA(1)\n\tX = pca.fit_transform(df_num[['TotalBsmtSF', '1stFlrSF']])\n\tX = pd.DataFrame(X)\n\tX.columns = ['Bsmt1stFlrPCA']\n\tdf_num = df_num.drop(['1stFlrSF', 'TotalBsmtSF'], axis=1).reset_index()\n\tdf_num = pd.concat([df_num, X], axis=1)\n\n\tcol = df_num.columns\n\n\tscaler = preprocessing.MinMaxScaler()\n\tdf_num = scaler.fit_transform(df_num)\n\tdf_num = pd.DataFrame(df_num, columns = col)\n\treturn(df_num)\n\n\n\ndef get_cat():\n\tdf = get_cut()\n\n\t# Get significant categorical features\n\t# Significance determined by correlation and MIC\n\tdf_cat = df[['Neighborhood','OverallQual','ExterQual','BsmtQual','HeatingQC','FullBath','KitchenQual','TotRmsAbvGrd', 'Fireplaces','GarageCars']]\n\tdf_cat = pd.get_dummies(df_cat)\n\n\treturn(df_cat)\n\n\n\ndef split_train_test(df, frac=0.25):\n\tsplit_index = int(np.round(df.shape[0] * frac))\n\n\ttrain = df.iloc[split_index:, :]\n\ttest = df.iloc[:split_index, :]\n\n\ttrain_l = train['SalePrice']\n\ttrain_i = train.drop('SalePrice', axis=1)\n\ttest_l = test['SalePrice']\n\ttest_i = test.drop('SalePrice', axis=1)\n\t\n\n\treturn(train_i, train_l, test_i, test_l)\n\n\n\ndef get_data():\n\tnum = get_num().reset_index(drop=True)\n\tcat = get_cat().reset_index(drop=True)\n\tsale = get_cut()['SalePrice'].reset_index(drop=True)\n\n\tdf = pd.concat([num, cat, sale], axis=1)\n\tdf = df.drop(df.columns[0], axis=1)\n\treturn(df)\n\n\ndef score(x, y):\n score = np.power(np.mean(np.square(x-y)), 0.5)\n return(score)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"555962884","text":"#信号量\n# from threading import Semaphore,Thread\n# import time\n# def func(sem,a,b):\n# time.sleep(1)\n# sem.acquire()\n# print(a+b)\n# sem.release()\n#\n# sem = Semaphore(4)\n# for i in range(10):\n# t = Thread(target=func,args=(sem,i, i+5))\n# t.start()\n\n\n\n#事件\n#事件被创建的时候\n#False状态\n #wait() 阻塞\n#True\n #wait()非阻塞\n#clear 设置状态为False\n#set 状态设置为True\n\n#连接数据库\n#检测数据库的可连接情况\n#起两个线程\n#第一个线程:连接数据库\n #等待一个信号,告诉我们之间的网络是通的\n #连接数据库\n#第二个线程: 检测与数据库之间的网络是否连通\n #time.sleep(0,2)\n #将事件的状态设置为True\nimport time\nimport random\nfrom threading import Thread,Event\ndef connect_db(e):\n count = 0\n while count <3:\n e.wait(0.5) #状态为False的时候,等待1秒结束\n if e.is_set() == True:\n print('连接数据库')\n break\n else:\n count += 1\n print('第%s连接失败'%count)\n else:\n raise TimeoutError('数据库连接超时')\ndef check_web(e):\n time.sleep(random.randint(0,3))\n e.set()\n\ne = Event()\nt1 = Thread(target=connect_db,args=(e,))\nt2 = Thread(target=check_web,args=(e,))\nt1.start()\nt2.start()","sub_path":"Demo/s9-day42-3事件和信号量.py","file_name":"s9-day42-3事件和信号量.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"355130685","text":"from mgrd import PoseConstraint, SemanticConstraint\n\n\nclass MGRDKeyframeConstraint(PoseConstraint, SemanticConstraint):\n \"\"\" A combination of a PoseConstraint and a SemanticConstraint for the integration with interact.\n\n Attributes:\n point (Vec3F): point in global Cartesian space..\n orientation (Vec4F): global orientation of the point as quaternion.\n joint_name (str): name of the constrained joint.\n weight (float): an weight for a linear combination of errors by the motion filter.\n annotations (List): annotations that should be met\n time (float): the time in seconds on which the semantic annotation should be found. (None checks for occurrence)\n\n \"\"\"\n def __init__(self, pose_constraint, semantic_constraint):\n self.joint_name = pose_constraint.joint_name\n self.weight = pose_constraint.weight\n self.point = pose_constraint.point\n self.orientation = pose_constraint.orientation\n self.annotations = semantic_constraint.annotations\n self.time = semantic_constraint.time\n\n @staticmethod\n def from_json(json_data):\n pose_constraint = PoseConstraint.from_json(json_data)\n semantic_constraint = SemanticConstraint.from_json(json_data)\n return MGRDKeyframeConstraint(pose_constraint, semantic_constraint)\n","sub_path":"python_src/morphablegraphs/motion_generator/constraints/spatial_constraints/mgrd_constraint.py","file_name":"mgrd_constraint.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"1308265","text":"# Copyright (C) 2014 Hiroki Horiuchi \n#\n# [GNU all-permissive license]\n# Copying and distribution of this file, with or without modification,\n# are permitted in any medium without royalty provided the copyright\n# notice and this notice are preserved.\n# This file is offered as-is, without any warranty.\n\nfrom glob import glob\nfrom os.path import isdir\n\ndef primary_disk():\n if isdir('/dev/md'):\n return '/dev/md/'\n sd = glob('/dev/sd?')\n if sd:\n return sd[0]\n hd = glob('/dev/hd?')\n if hd:\n return hd[0]\n raise Exception()\n\nif __name__ == '__main__':\n raise Exception('making a module executable is a bad habit.')\n","sub_path":"lib/primarydisk.py","file_name":"primarydisk.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"648749300","text":"TARGET = \"criticalFound\"\nDATE = \"Inspection_Date\"\nLICENSE = \"License\"\nINSPECTION_ID = \"Inspection_ID\"\nBUSINESS_ID = \"Business_ID\"\nINSPECTORS = [\n \"Inspector_blue\",\n \"Inspector_brown\",\n \"Inspector_green\",\n \"Inspector_orange\",\n \"Inspector_purple\",\n \"Inspector_yellow\",\n]\nOTHER_PREDICTORS = [\n \"pastSerious\",\n \"pastCritical\",\n \"timeSinceLast\",\n \"ageAtInspection\",\n \"consumption_on_premises_incidental_activity\",\n \"tobacco_retail_over_counter\",\n \"temperatureMax\",\n \"heat_burglary\",\n \"heat_sanitation\",\n \"heat_garbage\",\n]\nDETAILS = [\n \"address\",\n \"aka_name\",\n \"city\",\n \"dba_name\",\n \"facility_type\",\n \"inspection_date\",\n \"inspection_type\",\n \"latitude\",\n \"license_id\",\n \"longitude\",\n \"results\",\n \"risk\",\n \"state\",\n \"violations\",\n \"zip\",\n]\nVIOLATIONS = [\n \"V1\",\n \"V2\",\n \"V3\",\n \"V4\",\n \"V5\",\n \"V6\",\n \"V7\",\n \"V8\",\n \"V9\",\n \"V10\",\n \"V11\",\n \"V12\",\n \"V13\",\n \"V14\",\n]\nMONTHS = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n]\nMETA = [DATE, LICENSE, INSPECTION_ID, BUSINESS_ID]\nPREDICTORS = INSPECTORS + OTHER_PREDICTORS\n","sub_path":"IIT/research/strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"456766023","text":"# -*- coding: UTF-8 -*-\n# \n# The MIT License\n# \n# Copyright (c) 2010 Felix Schwarz \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 deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# 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 FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport base64\nimport re\n\nfrom pycerberus.i18n import _\nfrom pycerberus.schema import SchemaValidator\nfrom pycerberus.validators import EmailAddressValidator, IntegerValidator, \\\n StringValidator\n\n__all__ = ['HeloSchema', 'MailFromSchema', 'RcptToSchema', \n 'SMTPCommandArgumentsSchema']\n\n\n# ------------------------------------------------------------------------------\n# General infrastructure\n\n\nclass SMTPCommandArgumentsSchema(SchemaValidator):\n \n def __init__(self, *args, **kwargs):\n self.super()\n self.set_internal_state_freeze(False)\n self.set_allow_additional_parameters(False)\n self.set_parameter_order(getattr(self.__class__, 'parameter_order', ()))\n self.set_internal_state_freeze(True)\n \n def messages(self):\n return {'additional_items': _('Syntactically invalid argument(s) %(additional_items)s')}\n \n def _parameter_names(self):\n return list(self._parameter_order)\n \n def _assign_names(self, arguments, context):\n parameter_names = self._parameter_names()\n nr_missing_parameters = max(len(parameter_names) - len(arguments), 0)\n nr_additional_parameters = max(len(arguments), len(parameter_names), 0)\n arguments.extend([None] * nr_missing_parameters)\n parameter_names.extend(['extra%d' % i for i in xrange(nr_additional_parameters)])\n return dict(zip(parameter_names, arguments))\n \n def _parse_parameters(self, value, context):\n arguments = []\n if len(value) > 0:\n arguments = re.split('\\s+', value.strip())\n return arguments\n \n def _map_arguments_to_named_fields(self, value, context):\n return self._assign_names(self._parse_parameters(value, context), context)\n \n def set_parameter_order(self, parameter_names):\n self._parameter_order = parameter_names\n \n def process(self, value, context=None):\n fields = self._map_arguments_to_named_fields(value, context or {})\n return self.super(fields, context=context)\n\n\nclass SMTPEmailValidator(EmailAddressValidator):\n \n def messages(self):\n return {'unbalanced_quotes': _(u'Invalid email address format - use balanced angle brackets.')}\n \n def convert(self, value, context):\n string_value = self.super()\n if string_value.startswith('<') or string_value.endswith('>'):\n match = re.search('^<(.+)>$', string_value)\n if match is None:\n self.error('unbalanced_quotes', string_value, context)\n string_value = match.group(1)\n return string_value\n\n# ------------------------------------------------------------------------------\n# MAIL FROM\n\nclass SizeExtensionValidator(IntegerValidator):\n \n def __init__(self, *args, **kwargs):\n kwargs.update({'required': False, 'min': 1})\n self.super()\n \n def messages(self):\n return {'too_low': _('Invalid size: Must be %(min)s or greater.')}\n\n\nclass MailFromSchema(SMTPCommandArgumentsSchema):\n email = SMTPEmailValidator()\n size = SizeExtensionValidator()\n \n parameter_order = ('email',)\n \n def messages(self):\n return {\n 'invalid_extension': _('Invalid extension: %(smtp_extension)s'),\n 'invalid_smtp_arguments': _('Invalid arguments: %(smtp_arguments)s'),\n 'no_extensions': _('No SMTP extensions allowed for plain SMTP.'),\n }\n \n # --------------------------------------------------------------------------\n # special implementations for SMTP extensions\n \n def uses_esmtp(self, context):\n return context.get('esmtp', False)\n \n def _assert_all_options_have_a_value_assigned(self, key_value_pairs, input_string, context):\n for option in key_value_pairs:\n if len(option) == 2:\n continue\n value = ''.join(option)\n self.error('invalid_smtp_arguments', value, context, smtp_arguments=repr(input_string))\n \n def _assert_only_known_extensions(self, key_value_pairs, input_string, context):\n for key, value in key_value_pairs:\n if key.lower() in self.fieldvalidators():\n continue\n value = '='.join((key, value))\n self.error('invalid_extension', value, context, smtp_extension=repr(input_string))\n \n def _validate_extension_arguments(self, key_value_pairs, input_string, context):\n self._assert_all_options_have_a_value_assigned(key_value_pairs, input_string, context)\n self._assert_only_known_extensions(key_value_pairs, input_string, context)\n \n def _assign_names(self, arguments, context):\n if len(arguments) <= 1:\n return self.super()\n \n key_value_pairs = map(lambda option: re.split('=', option, 1), arguments[1:])\n self._validate_extension_arguments(key_value_pairs, ' '.join(arguments[1:]), context)\n lower_case_key_value_pairs = map(lambda item: (item[0].lower(), item[1]), key_value_pairs)\n options = dict(lower_case_key_value_pairs)\n parameters = self.super(arguments[:1], context)\n options.update(parameters)\n return options\n \n def _process_fields(self, fields, context):\n if len(fields) > 1 and not self.uses_esmtp(context):\n self.error('no_extensions', '', context)\n return self.super()\n\n# ------------------------------------------------------------------------------\n\nclass HeloSchema(SMTPCommandArgumentsSchema):\n helo = StringValidator(strip=True)\n \n parameter_order = ('helo',)\n\n\nclass RcptToSchema(SMTPCommandArgumentsSchema):\n email = SMTPEmailValidator()\n \n parameter_order = ('email',)\n\n# ------------------------------------------------------------------------------\n# AUTH PLAIN\n\nclass AuthPlainSchema(SMTPCommandArgumentsSchema):\n authzid = StringValidator(required=False, default=None)\n username = StringValidator()\n password = StringValidator()\n \n parameter_order = ('authzid', 'username', 'password')\n \n def messages(self):\n return {\n 'invalid_base64': _('Garbled data sent'),\n 'invalid_format': _('Garbled data sent'),\n }\n \n # --------------------------------------------------------------------------\n # special implementations for SMTP extensions\n \n def _decode_base64(self, value, context):\n try:\n return base64.decodestring(value)\n except:\n self.error('invalid_base64', value, context)\n \n def _parse_parameters(self, value, context):\n match = re.search('=\\s(.+)$', value.strip())\n if match is not None:\n self.error('additional_items', value, context, additional_items=repr(match.group(1)))\n decoded_parameters = self._decode_base64(value, context)\n match = re.search('^([^\\x00]*)\\x00([^\\x00]*)\\x00([^\\x00]*)$', decoded_parameters)\n if not match:\n self.error('invalid_format', value, context)\n items = list(match.groups())\n if items[0] == '':\n items[0] = None\n return items\n\n","sub_path":"pymta/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"542533203","text":"\"\"\"\nPlot estimates of uncertainty field m before C_mu in inverse RANS problem.\nShiwei Lan @ U of Warwick, 2016\n\"\"\"\n\nimport os\nimport dolfin as dl\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mp\n\nfrom RANS import RANS\nimport sys\nsys.path.append( \"../../\" )\nfrom util import matplot4dolfin\nmatplot=matplot4dolfin()\n\nPARAMETER =1\n# define the PDE problem\nnozz_w=1.;nx=40;ny=80\nrans=RANS(nozz_w=nozz_w,nx=nx,ny=ny)\nrans.setup(seed=2017)\n\n# algorithms\n# algs=('pCN','infMALA','infHMC','DRinfmMALA','DRinfmHMC','DILI','aDRinfmMALA','aDRinfmHMC')\n# alg_names=('pCN','$\\infty$-MALA','$\\infty$-HMC','DR-$\\infty$-mMALA','DR-$\\infty$-mHMC','DILI','aDR-$\\infty$-mMALA','aDR-$\\infty$-mHMC')\nalgs=('pCN','infMALA','DRinfmMALA','DILI','aDRinfmMALA')\nalg_names=('pCN','$\\infty$-MALA','DR-$\\infty$-mMALA','DILI','aDR-$\\infty$-mMALA')\n\nnum_algs=len(algs)\n# preparation for estimates\nfolder = './analysis-L25W8-nofreshinit-yesparacont-2000'\nfnames=[f for f in os.listdir(folder) if f.endswith('.h5')]\nnum_samp=2000\n\n# plot\nnum_rows=2\nfig,axes = plt.subplots(nrows=num_rows,ncols=np.int(np.ceil((1+num_algs)/num_rows)),sharex=True,sharey=True,figsize=(16,6))\n\nfor i,ax in enumerate(axes.flat):\n plt.axes(ax)\n if i==0:\n # plot MAP\n try:\n f=dl.HDF5File(rans.mpi_comm, os.path.join(folder,\"map_solution.h5\"), \"r\")\n MAP=dl.Function(rans.Vh_PARAMETER,name=\"parameter\")\n f.read(MAP,\"parameter\")\n f.close()\n sub_fig=matplot.plot(MAP)\n ax.set_title('MAP')\n except:\n pass\n elif 1<=i<=num_algs:\n print('Working on '+alg_names[i-1]+' algorithm...')\n # plot posterior mean\n found=False\n samp_f=dl.Function(rans.Vh_PARAMETER,name=\"parameter\")\n samp_v=rans.model_stat.generate_vector(PARAMETER)\n samp_v.zero()\n num_read=0;bad_idx=[]\n for f_i in fnames:\n if '_samp_'+algs[i-1]+'_' in f_i:\n try:\n f=dl.HDF5File(rans.mpi_comm,os.path.join(folder,f_i),\"r\")\n samp_v.zero()\n for s in range(num_samp):\n try:\n f.read(samp_f,'sample_{0}'.format(s))\n# f.read(samp_f.vector(),'/VisualisationVector/{0}'.format(s),False)\n samp_v.axpy(1.,samp_f.vector())\n num_read+=1\n except:\n bad_idx.append(s)\n f.close()\n if len(bad_idx)>0:\n print('{0:d} bad samples encountered!'.format(len(bad_idx)))\n found=True\n except:\n pass\n if found and num_read>0:\n samp_mean=samp_v/num_read\n if any([s in algs[i-1] for s in ['DILI','aDRinf']]):\n samp_mean=rans.whtprior.v2u(samp_mean)\n samp_f.vector()[:]=samp_mean\n sub_fig=matplot.plot(samp_f)\n ax.set_title(alg_names[i-1])\n# plt.axis('tight')\n plt.axis(rans.box)\n\n# set color bar\ncax,kw = mp.colorbar.make_axes([ax for ax in axes.flat])\nplt.colorbar(sub_fig, cax=cax, **kw)\n\n# save plot\n# fig.tight_layout()\nplt.savefig(folder+'/estimates.png',bbox_inches='tight')\n\nplt.show()\n","sub_path":"RANS/dimension-reduced-geom-infmcmc/RANS/RANS_bip/plot_estimates.py","file_name":"plot_estimates.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"432035583","text":"from django.shortcuts import render,get_object_or_404\nfrom django.core.paginator import Paginator,EmptyPage\nfrom .models import Listings\nfrom listings.choices import price_choices,bedroom_choices,state_choices\n\ndef index(request):\n # order by used to show most recent home 1st\n listings = Listings.objects.order_by('-list_date').filter(is_published=True)\n\n paginator = Paginator(listings,6)\n page = request.GET.get('page')\n paged_listings = paginator.get_page(page)\n\n\n\n context ={\n 'listings':paged_listings\n }\n return render(request,'listings/listing.html',context)\n\n\ndef listing(request,listing_id):\n listing = get_object_or_404(Listings,pk=listing_id)\n context ={\n 'listing':listing\n }\n return render(request,'listings/listings.html',context)\n\n\ndef search(request):\n\n queryset_list = Listings.objects.order_by('-list_date')\n\n if 'keywords' in request.GET:\n keywords = request.GET['keywords']\n if keywords:\n queryset_list = queryset_list.filter(description__icontains = keywords)\n \n if 'city' in request.GET:\n city = request.GET['city']\n if city:\n queryset_list = queryset_list.filter(city__iexact = city)\n \n #lte is less than eqyual to\n if 'bedrooms' in request.GET:\n bedrooms = request.GET['bedrooms']\n if bedrooms:\n queryset_list = queryset_list.filter(bedrooms__lte = bedrooms)\n\n if 'price' in request.GET:\n price = request.GET['price']\n if price:\n queryset_list = queryset_list.filter(price__lte = price)\n\n context = {\n 'state_choices':state_choices,\n 'price_choices':price_choices,\n 'bedroom_choices':bedroom_choices,\n 'listings':queryset_list,\n 'values' : request.GET\n }\n return render(request,'listings/search.html',context)\n\n","sub_path":"Web/myapp/listings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"477651174","text":"\"\"\"\nDescription : Simple Python implementation of the Apriori Algorithm\n\nUsage:\n $python apriori.py -f DATASET.csv -s minSupport -c minConfidence\n\n $python apriori.py -f DATASET.csv -s 0.15 -c 0.6\n\"\"\"\n\nimport sys\nfrom operator import itemgetter\nfrom itertools import zip_longest\nfrom collections import defaultdict, deque\nfrom pandas import DataFrame\nfrom optparse import OptionParser\nfrom io import StringIO\nimport progressbar\nimport logging\nimport math\nimport time\nimport bisect\nimport sys\nfrom itertools import chain, combinations\nfrom multiprocessing import Process, Queue, queues\nfrom .items import AprioriSet, AprioriCollection, AprioriCounter, AprioriSession\n_print = print\n\nclass Logging(object):\n log_streams = None\n config = None\n @classmethod\n def print(cls, *args, **kwargs):\n if cls.log_streams is None:\n return _print(*args, **kwargs)\n\n if cls.config is None:\n handlers = list()\n for stream in cls.log_streams:\n if stream == 'stream':\n handlers.append(logging.StreamHandler(sys.stdout))\n else:\n handlers.append(logging.FileHandler(stream, mode='a'))\n\n logging.basicConfig(handlers=handlers, level=logging.INFO)\n cls.log_streams = handlers\n cls.config = True\n\n logging.info(*args, **kwargs)\nprint = Logging.print\n\nclass PBlogger(StringIO):\n real_logger = None\n\n def write(self, *args, **kwargs):\n pos = self.tell()\n super(PBlogger, self).write(*args, **kwargs)\n self.seek(pos)\n if self.real_logger is None:\n return sys.stderr.write(self.read())\n\n if 'strip' in self.real_logger:\n msg = self.read().strip('\\r')\n if 'print' not in self.real_logger:\n msg += '\\n'\n else:\n msg = self.read()\n\n if 'stdout' in self.real_logger:\n return sys.stdout.write(msg)\n\n if 'print' in self.real_logger:\n return print(msg)\n\n return sys.stderr.write(msg)\n\n\ndef prog_bar(maxval, message=''):\n class Message(progressbar.Widget):\n \"\"\"Displays the current count.\"\"\"\n __slots__ = ('message',)\n\n def __init__(self):\n self.message = message\n\n def __call__(self, msg):\n self.message = msg\n\n def update(self, pbar):\n return '\\t' + self.message\n\n msg_widget = Message()\n pb = progressbar.ProgressBar(maxval=maxval, widgets=[progressbar.widgets.Percentage(), ' '\n ' ',\n progressbar.widgets.Timer(),\n ' ',\n progressbar.widgets.ETA(),\n msg_widget], fd=PBlogger())\n return pb, msg_widget\n\n\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n\n\ndef returnItemsWithMinSupport(collect: AprioriCollection, transactions, min_support, n_workers):\n \"\"\"calculates the support for items in the itemSet and returns a subset\n of the itemSet each of whose elements satisfies the minimum support\"\"\"\n chunk_siz = max(5000, (collect.size // n_workers) // 25)\n\n MP = True\n\n if not MP:\n n_workers = 1\n\n intervals_q = Queue()\n counted_q = Queue()\n\n print('\\n\\tWorkers: {0}\\n\\tChunk size: {1}\\n\\tCollection size: {2}'.format(n_workers, chunk_siz, collect.size))\n def worker():\n while True:\n interv = intervals_q.get()\n if interv is StopIteration:\n counted_q.put(StopIteration)\n break\n start, end, i = interv\n counter = AprioriCounter(collect, start, end, transactions, min_support)\n counted_q.put((i, counter))\n\n print('init job queue')\n start = None\n n_chunks = 1\n for i, stop in enumerate(range(0, collect.size, chunk_siz)):\n if start is None:\n start = stop\n continue\n intervals_q.put((start, stop, i))\n n_chunks += 1\n start = stop\n intervals_q.put((start, collect.size, i + 1))\n\n for _ in range(n_workers):\n intervals_q.put(StopIteration)\n\n print('start workers')\n if MP:\n p = deque(Process(target=worker) for _ in range(n_workers))\n for proc in p:\n proc.start()\n else:\n worker()\n\n def get_results():\n sentinels = 0\n pb, msg = prog_bar(n_chunks + n_workers, 'counting baskets')\n result_cache = dict()\n\n def get_res():\n nonlocal sentinels\n try:\n result = counted_q.get(timeout=5)\n except queues.Empty:\n return\n\n if result is StopIteration:\n sentinels += 1\n return\n result_cache[result[0]] = result[1]\n\n i = 1\n pb.start()\n while sentinels < n_workers:\n pb.update(n_chunks - intervals_q.qsize() + n_workers)\n get_res()\n # print('##########################')\n # objgraph.show_growth()\n # msg('memory: {0}'.format(mem))\n while i in result_cache:\n res = result_cache.pop(i)\n if res:\n yield res\n i += 1\n pb.finish()\n if MP:\n for proc in p:\n proc.join()\n\n collect.filter_from_counters(get_results(), min_support, len(transactions))\n\n\ncompl_time_ratios = list()\n\n\ndef merge_worker(merge_collections, msg):\n ii = 0\n count = 0\n for i in range(len(merge_collections)):\n while len(merge_collections[i]) > 1:\n # pop 2 collections from i and append result to i + 1\n merge_collections[i + 1].append(merge_collections[i].pop().merge(merge_collections[i].pop()))\n ii += 1\n count += len(merge_collections[i])\n msg('merged {0} times'.format(ii))\n return count\n\n\ndef setGenerator(collection: AprioriCollection, n_workers):\n length = collection.k + 1\n MP = True\n l = collection.size\n\n if length == 2:\n set_list = list(AprioriSet(item_set) for item_set in combinations((item[0] for item in collection.set_list), 2))\n return AprioriCollection.from_lists(set_list, 2)\n\n if not MP:\n n_workers = 1\n chunk_sz = 2 ** 13\n chunks = (l // chunk_sz) + n_workers\n\n set_queue = Queue()\n filtered_sets_queue = Queue() # maxsize=(n_workers+1))\n collection.build_in_lists()\n items_sort = sorted(collection.in_lists)\n N = len(items_sort)\n hi_el = items_sort[-1] # item element with highest sort value\n hi_pad = (hi_el,) * collection.k\n sub_lists = collection.sub_set_lists()\n\n def worker():\n local_sets = [AprioriCollection(length)]\n _local_set = AprioriCollection(length)\n def new_local_set(old_set: AprioriCollection) -> AprioriCollection:\n \"\"\"\n put a local collection in merge queue and do as many merges as possible. return empry local collection\n :param old_set:\n :return:\n \"\"\"\n local_sets.append(old_set)\n # Merge last 2 collections in queue if last collection is larger than next to last\n while len(local_sets) > 1 and local_sets[-1].size >= local_sets[-2].size:\n local_sets.append(local_sets.pop().merge(local_sets.pop()))\n return AprioriCollection(length)\n\n while True:\n g = set_queue.get()\n if g is StopIteration:\n break\n i_start, i_end = g\n for out_k in range(collection.k):\n _local_set = new_local_set(_local_set)\n start = bisect.bisect_right(sub_lists[out_k], (i_start,))\n if i_end is None:\n end = collection.size\n else:\n end = bisect.bisect_left(sub_lists[out_k], (i_end,))\n\n recreate_item = lambda prefix, small_ending, large_ending: AprioriSet(chain(prefix[:out_k],\n (small_ending, large_ending),\n prefix[out_k:]))\n if start == end:\n continue\n sub_list = sub_lists[out_k][start:end]\n lo = 0\n hi = deque([len(sub_list)])\n first_item = sub_list[lo]\n small_ending, large_ending = items_sort[0], items_sort[0]\n prev_max_small_ending = (small_ending, large_ending)\n while True:\n nesting = len(hi)\n if nesting == collection.k - 1:\n _hi = hi.pop()\n nesting = len(hi)\n if _hi - lo > 1:\n item_prefix = sub_list[lo][:-1]\n item_endings = tuple(item[-1] for item in sub_list[lo:_hi])\n if prev_max_small_ending > item_endings[:2]:\n # the sorting of _local set will be broken if we append these items. do swap\n _local_set = new_local_set(_local_set)\n\n for i, small_ending in enumerate(item_endings[:-1]):\n for large_ending in item_endings[i+1:]:\n _local_set.append(recreate_item(item_prefix, small_ending, large_ending))\n prev_max_small_ending = (small_ending, large_ending)\n\n lo = _hi\n if lo >= len(sub_list):\n break\n first_item = sub_list[lo]\n\n if hi[-1] == lo:\n hi.pop()\n nesting = len(hi)\n _local_set = new_local_set(_local_set)\n prev_max_small_ending = (items_sort[0], items_sort[0])\n\n _hi = bisect.bisect_right(sub_list, tuple(chain(first_item[:nesting + 1], hi_pad)), lo=lo, hi=hi[-1])\n hi.append(_hi)\n\n local_sets.append(_local_set)\n while len(local_sets) > 1:\n local_sets.append(local_sets.pop().merge(local_sets.pop()))\n filtered_sets_queue.put(local_sets.pop())\n filtered_sets_queue.put(StopIteration)\n\n compl = l ** 2 * math.log(length - 1) * (length - 1)\n if compl_time_ratios:\n t_est = compl / (1 + compl_time_ratios[-1]) / 2\n else:\n t_est = 0\n print('Generating sets of length {0} with {1} starting sets'.format(length, l))\n print('\\tComplexity: {0:.0}\\n\\tEstimated completion time: {1:3.0f}\\n\\tworkers: {2}\\n\\tchunks: {3}'.format(compl,\n t_est,\n n_workers,\n chunks))\n t_start = time.time()\n # pb = maxval=len(itemSet))\n\n pb, msg = prog_bar(N + 1, 'initializing...')\n\n print('init job queue')\n if MP:\n p = deque(Process(target=worker) for _ in range(n_workers))\n for proc in p:\n proc.start()\n\n for j in zip(items_sort, items_sort[1:] + [None]):\n set_queue.put(j)\n\n pb.start()\n msg('started')\n print(set_queue.qsize())\n pb.update(N - set_queue.qsize() + 1)\n\n for _ in range(n_workers):\n set_queue.put(StopIteration)\n\n if not MP:\n worker()\n\n merge_collections = defaultdict(list)\n\n sentinels = 0\n results = 0\n print('collecting results from workers')\n while sentinels < n_workers:\n try:\n result = filtered_sets_queue.get(timeout=5)\n except queues.Empty:\n pb.update(N - set_queue.qsize() + 1)\n continue\n msg('{0} results received'.format(results))\n pb.update(N - set_queue.qsize() + 1)\n if result is StopIteration:\n sentinels += 1\n else:\n results += 1\n merge_collections[0].append(result)\n merge_worker(merge_collections, msg)\n pb.update(N - set_queue.qsize() + 1)\n\n if MP:\n for proc in p:\n assert isinstance(proc, Process)\n proc.join()\n\n\n collect_siz = merge_worker(merge_collections, msg)\n pb, msg = prog_bar(collect_siz, 'merging {0} collections'.format(collect_siz))\n pb.start()\n chunks = collect_siz\n merge_idx = 0\n current_merge = list()\n while True:\n pb.update(chunks - collect_siz)\n while len(current_merge) != 2:\n if collect_siz == 0:\n break\n\n if merge_collections[merge_idx]:\n current_merge.append(merge_collections[merge_idx].pop())\n collect_siz -= 1\n else:\n merge_idx += 1\n\n if len(current_merge) == 2:\n merge_collections[merge_idx + 1].append(current_merge.pop().merge(current_merge.pop()))\n collect_siz += 1\n else:\n full_set = current_merge[0]\n full_set.size = len(full_set.set_list)\n break\n pb.finish()\n t_delta = time.time() - t_start\n compl_time_ratios.append(compl / t_delta)\n print('\\nDone in {0:3.2f} seconds. complexity/time ratio: {1:.0f}\\n\\tproduced sets: {2}'.format(t_delta,\n compl_time_ratios[\n -1],\n full_set.size), )\n assert full_set.is_sorted()\n return full_set\n\n\ndef join_set(itemSet, n_workers):\n \"\"\"Join a set with itself and returns the n-element itemsets\"\"\"\n return setGenerator(itemSet, n_workers)\n\n\ndef getItemSetTransactionListFromRecord(data_iterator):\n transactionList = list()\n itemSet = set()\n for record in data_iterator:\n transaction = sorted(str(item) for item in record)\n transactionList.append(transaction)\n for item in transaction:\n itemSet.add((item,))\n\n itemSet = AprioriCollection.from_lists(sorted(list(itemSet)), 1)\n\n return transactionList, itemSet\n\n\ndef getItemSetTransactionListFromDataFrame(df: DataFrame):\n transactions = [tuple(sorted(int(el) for el in df.index[df[col] == 1].tolist())) for col in df.columns]\n item_set = AprioriCollection.from_lists(sorted(AprioriSet((int(el),)) for el in df.index.tolist()), 1)\n return transactions, item_set\n\n\ndef runApriori(data, min_support, minConfidence, max_k=None, fp=None, n_workers=4):\n \"\"\"\n run the apriori algorithm. data_iter is a record iterator\n Return both:\n - items (tuple, support)\n - rules ((pretuple, posttuple), confidence)\n \"\"\"\n print('Reading in data')\n if isinstance(data, DataFrame):\n large_set = AprioriSession.from_scratch(*getItemSetTransactionListFromDataFrame(data), fp=fp)\n elif hasattr(data, 'send'):\n large_set = AprioriSession.from_scratch(*getItemSetTransactionListFromRecord(data), fp=fp)\n else:\n large_set = AprioriSession.from_fp(data, fp=fp)\n\n print('Data set loaded - total_size: {}'.format(large_set.total_size))\n assert isinstance(large_set, AprioriSession)\n last_collect = large_set.last_collection()\n last_collect.sub_set_lists()\n while last_collect.size != 0:\n if max_k and max_k in large_set and large_set[max_k].counts:\n break\n\n try:\n if last_collect.counts:\n print('Joining sets...')\n large_set[last_collect.k + 1] = join_set(last_collect, n_workers)\n else:\n print('Counting...')\n returnItemsWithMinSupport(last_collect,\n large_set.transactions,\n min_support,\n n_workers)\n large_set.save()\n\n last_collect = large_set.last_collection()\n except KeyboardInterrupt:\n break\n\n n_transactions = len(large_set.transactions)\n\n def supports(counts):\n return [count / n_transactions for count in counts]\n\n def ret_items():\n for c in large_set.values():\n yield from zip(c.set_list, supports(c.counts))\n\n toRetItems = list(ret_items())\n\n toRetRules = []\n n_items = large_set.total_size\n pb, msg = prog_bar(n_items, 'generating rules')\n pb.start()\n for k, collect in large_set.items():\n if k == 1:\n continue\n\n for count, item in zip(collect.counts, collect.set_list):\n pb.update(pb.currval + 1)\n for subset in item.subsets():\n remain = AprioriSet(item.difference(subset))\n _k = len(subset)\n confidence = count / large_set[_k].get_count(subset)\n if confidence >= minConfidence:\n toRetRules.append(((subset, remain), confidence))\n return toRetItems, toRetRules\n\n\ndef printResults(items, rules):\n \"\"\"prints the generated itemsets sorted by support and the confidence rules sorted by confidence\"\"\"\n for item, support in sorted(items, key=itemgetter(1)):\n print(\"item: %s , %.3f\" % (str(item), support))\n print(\"\\n------------------------ RULES:\")\n for rule, confidence in sorted(rules, key=itemgetter(1)):\n pre, post = rule\n print(\"Rule: %s ==> %s , %.3f\" % (str(pre), str(post), confidence))\n\n\ndef dataFromFile(fname):\n \"\"\"Function which reads from the file and yields a generator\"\"\"\n file_iter = open(fname, 'rU')\n for line in file_iter:\n line = line.strip().rstrip(',') # Remove trailing comma\n record = frozenset(line.split(','))\n yield record\n\n\ndef main():\n optparser = OptionParser()\n optparser.add_option('-f', '--inputFile',\n dest='input',\n help='filename containing csv',\n default=None)\n optparser.add_option('-s', '--minSupport',\n dest='minS',\n help='minimum support value',\n default=0.15,\n type='float')\n optparser.add_option('-c', '--minConfidence',\n dest='minC',\n help='minimum confidence value',\n default=0.6,\n type='float')\n\n (options, args) = optparser.parse_args()\n\n inFile = None\n if options.input is None:\n inFile = sys.stdin\n elif options.input is not None:\n inFile = dataFromFile(options.input)\n else:\n print('No dataset filename specified, system with exit\\n')\n sys.exit('System will exit')\n\n minSupport = options.minS\n minConfidence = options.minC\n\n items, rules = runApriori(inFile, minSupport, minConfidence)\n\n printResults(items, rules)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"apriori.py","file_name":"apriori.py","file_ext":"py","file_size_in_byte":19591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"204640878","text":"import os\nimport sys\n\nimport pygame\n\nfrom macgyver.labyrinthe import Labyrinthe\nfrom macgyver.directions import right, left, up, down\nfrom macgyver.graphic.labyrinthe import LabyrintheDisplay\nfrom macgyver.graphic.hero import HeroSprite\nfrom macgyver.graphic.items import ItemSprite\nfrom macgyver.graphic.guardian import GuardianSprite\nfrom macgyver.constants import SPRITE_HEIGHT, SPRITE_WIDTH\n\n\nif not pygame.font:\n print('Attention, polices désactivées')\nif not pygame.mixer:\n print('Attention, son désactivé')\n\n\nclass Game:\n \"\"\"Créez la fenêtre de jeu et ajoutez le héros, les objets et le gardien.\"\"\"\n\n def __init__(self):\n pygame.init()\n\n self.labyrinthe = Labyrinthe()\n self.labyrinthe.read_file()\n self.screen = pygame.display.set_mode(\n (\n SPRITE_WIDTH * self.labyrinthe.width,\n SPRITE_HEIGHT * (self.labyrinthe.height + 1),\n )\n )\n self.screen.fill((0, 0, 0))\n self.background = LabyrintheDisplay(self.labyrinthe)\n self.allsprites = pygame.sprite.Group()\n self.allsprites.add(HeroSprite(self.labyrinthe.macgyver))\n for item in self.labyrinthe.items:\n self.allsprites.add(ItemSprite(item))\n self.allsprites.add(GuardianSprite(self.labyrinthe.guardian))\n self.clock = pygame.time.Clock()\n\n def start(self):\n \"\"\"Lancement du jeu et affectation des touches fléchées du héros.\"\"\"\n running = True\n while running:\n self.clock.tick(40)\n self.screen.blit(self.background, (0, 0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n running = self.labyrinthe.macgyver.move(left)\n elif event.key == pygame.K_RIGHT:\n running = self.labyrinthe.macgyver.move(right)\n elif event.key == pygame.K_UP:\n running = self.labyrinthe.macgyver.move(up)\n elif event.key == pygame.K_DOWN:\n running = self.labyrinthe.macgyver.move(down)\n self.allsprites.update()\n self.allsprites.draw(self.screen)\n pygame.display.update()\n\n if self.labyrinthe.macgyver.status == \"won\":\n self.display_victory_or_defeat('ressource/victoire.png')\n else:\n self.display_victory_or_defeat('ressource/defaite.png')\n\n def display_victory_or_defeat(self, image):\n \"\"\"Charge une image si le joueur gagne ou perd.\"\"\"\n running = True\n while running:\n self.clock.tick(20)\n self.screen.blit(pygame.image.load(image), (0, 0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n pygame.display.update()\n\n\ndef main():\n game = Game()\n game.start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"macgyver/graphic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"28037080","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nfrom uuid import uuid4\nfrom webscraper.models import googleNewsHeadlineCOV\n#from webscraping_0.spiders import *\n\nclass GooglenewsScraperPipeline(object):\n def process_item(self, item, spider):\n link_ = item.get('link')\n links = googleNewsHeadlineCOV.objects.filter(link=link_)\n if len(links) == 0:\n a_content = googleNewsHeadlineCOV()\n a_content.source_name = item.get('source_name')\n a_content.author_name = item.get('author_name')\n a_content.title = item.get('title')\n a_content.link = link_\n a_content.published_date = item.get('published_date')\n a_content.save()\n return item\n return \"\\n{} link already exists.\\n\".format(link_)\n","sub_path":"googlenews_scraper/googlenews_scraper/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"529763025","text":"from datetime import datetime as dt\nimport importlib\nimport os\nimport re\nimport time\nimport string \nfrom collections import OrderedDict\nimport h5py\nimport numpy as np\nimport pandas as pd\nimport yaml\nimport json\n\nfrom . import operations\nfrom . import workflows\n \nbad_chars = string.punctuation \nbad_chars = bad_chars.replace('_','')\nbad_chars = bad_chars.replace('-','')\nbad_chars = bad_chars.replace('.','')\nspace_chars = [' ','\\t','\\n',os.linesep]\n\np = os.path.abspath(__file__)\n# p = (pawsroot)/paws/pawstools.py\n\nd = os.path.dirname(p)\n# d = (pawsroot)/paws/\nsourcedir = str(d)\n\nd = os.path.dirname(d)\n# d = (pawsroot)/\nrootdir = str(d)\n\n# Get the code version from the config.py file.\n# Reference version string as pawstools.__version__\nwith open(os.path.join(sourcedir,'config.py')) as f: \n exec(f.read())\n\n# TODO: ensure this is valid cross-platform\nuser_homedir = os.path.expanduser(\"~\")\n\npaws_scratch_dir = os.path.join(user_homedir,'.paws_scratch')\npaws_cfg_dir = os.path.join(user_homedir,'.paws_cfg')\nif not os.path.exists(paws_cfg_dir):\n os.mkdir(paws_cfg_dir)\nif not os.path.exists(paws_scratch_dir):\n os.mkdir(paws_scratch_dir)\n\ndef primitives(v):\n if isinstance(v,dict):\n rd = {}\n for kk,vv in v.items():\n rd[kk] = primitives(vv)\n return rd\n elif isinstance(v,list):\n return [primitives(vv) for vv in v]\n elif isinstance(v,str):\n return str(v)\n elif isinstance(v,int):\n return int(v)\n elif isinstance(v,float):\n return float(v)\n else:\n return v\n\nclass WorkflowAborted(Exception):\n pass\n\nclass OperationDisabledError(Exception):\n pass\n\nclass WfNameError(Exception):\n pass\n\nclass PluginNameError(Exception):\n pass\n\nclass PluginLoadError(Exception):\n pass\n\nclass OperationLoadError(Exception):\n pass\n\ndef dtstr():\n \"\"\"Return date and time as a string\"\"\"\n return dt.strftime(dt.now(),'%Y %m %d, %H:%M:%S')\n\ndef timestr():\n \"\"\"Return time as a string\"\"\"\n return dt.strftime(dt.now(),'%H:%M:%S')\n\ndef save_file(filename,d):\n \"\"\"\n Create or replace file indicated by filename,\n as a yaml serialization of dict d.\n \"\"\"\n f = open(filename, 'w')\n yaml.dump(d, f)\n f.close()\n \ndef update_file(filename,d):\n \"\"\"\n Save the items in dict d into filename,\n without removing members not included in d.\n \"\"\"\n if os.path.exists(filename):\n f_old = open(filename,'r')\n d_old = yaml.load(f_old)\n f_old.close()\n d_old.update(d)\n d = d_old\n f = open(filename, 'w')\n yaml.dump(d, f)\n f.close()\n\nclass DictTree(object):\n \"\"\"A data structure for tree-like storage.\n\n A DictTree has a root (an ordered dictionary), \n which is extended by embedding other objects \n that are amenable to tree storage.\n Fetches items by keys (strings),\n which are sequences \n of parent item keys(), connected by '.'s.\n\n Child items (end nodes of the tree)\n can be anything.\n Parent items, in order to index their children,\n must be either lists, dicts, or objects implementing\n keys(), __getitem__(key) and __setitem__(key,value).\n\n This data structure was originally developed\n to interface with a TreeView in a Qt GUI.\n It is no longer used in PAWS;\n it is here because it's kind of neat.\n \"\"\"\n\n def __init__(self,data={}):\n super(DictTree,self).__init__()\n self._root = OrderedDict()\n if isinstance(data,dict):\n self._root = OrderedDict(data)\n\n def __getitem__(self,key):\n return self.get_data(key)\n\n def __setitem__(self,key,val):\n self.set_data(key,val)\n\n def root_keys(self):\n return self._root.keys()\n\n def keys(self):\n return self.subkeys()\n\n def subkeys(self,root_key=''):\n if not root_key:\n itm = self._root\n else:\n itm = self.get_data(root_key)\n itm_keys = []\n try:\n itm_keys = itm.keys()\n except:\n if isinstance(itm,list): \n itm_keys = [str(i) for i in range(len(itm))] \n else:\n # no itm_keys\n pass\n prefix = root_key\n if root_key: prefix += '.'\n sk = [prefix+s for s in itm_keys]\n for k in itm_keys:\n next_keys = self.subkeys(prefix+k) \n if any(next_keys):\n sk.extend(next_keys)\n return sk\n\n @ staticmethod\n def parent_key(key):\n # TODO: handle the possibility of subkeys containing periods\n if '.' in key:\n return key[:key.rfind('.')]\n else:\n return ''\n\n def delete_data(self,key=''):\n \"\"\"Attempts to de-reference the given key\"\"\"\n parent_itm = self._root\n if '.' in key:\n parent_itm = self.get_data(self.parent_key(key))\n itm_key = key.split('.')[-1]\n if itm_key:\n try: \n # parent implements __getitem__()?\n parent_itm.pop(itm_key)\n except:\n # parent item is list? \n parent_itm.pop(int(itm_key))\n\n def set_data(self,key='',val=None):\n \"\"\"Sets the data at the given key.\"\"\"\n parent_itm = self._root\n if '.' in key:\n parent_itm = self.get_data(self.parent_key(key))\n itm_key = key.split('.')[-1]\n if itm_key:\n try: \n parent_itm[itm_key] = val\n except:\n try: \n parent_itm[int(itm_key)] = val # list case\n except:\n parent_itm.append(val) # append to list case\n\n def get_data(self,key=''):\n \"\"\"Returns the data at the given key.\"\"\"\n path = key.split('.')\n itm = self._root \n for ik,k in enumerate(path):\n child_found = False\n try: \n itm = itm[k]\n child_found = True\n except:\n try: \n itm = itm[int(k)]\n child_found = True\n except:\n longer_key = k\n for kk in path[ik+1:]:\n longer_key += '.'\n try: \n itm = itm[longer_key]\n child_found = True\n except: \n pass\n longer_key += kk\n try: \n itm = itm[longer_key]\n child_found = True\n except: \n pass\n if not child_found:\n raise KeyError(key)\n return itm\n\n def is_key_valid(self,key):\n \"\"\"Check key validity.\n\n Keys may contain upper case letters, lower case letters, \n numbers, dashes (-), and underscores (_) and period (.) marks. \n Any whitespace or any character in the string.punctuation library\n (other than -, _, or .) results in an invalid key.\n \"\"\"\n if not key or any(map(lambda s: s in key,space_chars))\\\n or any(map(lambda s: s in key,bad_chars)):\n return False \n return True \n\n def key_error_message(self,key):\n \"\"\"Provide a human-readable error message for bad keys.\"\"\"\n if not key:\n return 'key is blank.'\n elif any(map(lambda s: s in key,space_chars)):\n return '\"{}\" contains whitespace.'.format(key)\n elif any(map(lambda s: s in key,bad_chars)):\n return '\"{}\" contains special characters.'.format(key)\n\n def print_tree(self,root_key='',offset=''):\n \"\"\"Print the tree content.\"\"\"\n itm = self._root\n if root_key:\n itm = self.get_data(root_key)\n tstr = os.linesep \n try: #if isinstance(itm,dict):\n for k in itm.keys():\n x_str = self.print_tree(root_key+'.'+k,offset+' ')\n tstr = tstr+offset+'{}: {}'.format(k,x_str)+os.linesep\n except:\n try: #elif isinstance(itm,list):\n for i,x in enumerate(itm):\n x_str = self.print_tree(root_key+'.'+str(i),offset+' ')\n tstr = tstr+offset+'{}: {}'.format(i,x_str)+os.linesep\n except:\n return '{}'.format(itm)\n return tstr\n\n\ndef data_to_h5(data, grp, key, encoder='yaml'):\n if data is None:\n grp.create_dataset(key, data=h5py.Empty(\"f\"))\n grp[key].attrs['encoded'] = 'None'\n\n elif type(data) == dict:\n new_grp = grp.create_group(key)\n new_grp.attrs['encoded'] = 'dict'\n dict_to_h5(data, new_grp)\n \n elif type(data) == str:\n grp.create_dataset(key, data=np.string_(data))\n grp[key].attrs['encoded'] = 'str'\n \n elif type(data) == pd.core.series.Series:\n new_grp = grp.create_group(key)\n new_grp.attrs['encoded'] = 'Series'\n new_grp.create_dataset('data', data=np.array(data))\n index_to_h5(data.index, 'index', new_grp)\n new_grp.create_dataset('name', data=np.string_(data.name))\n \n elif type(data) == pd.core.frame.DataFrame:\n new_grp = grp.create_group(key)\n new_grp.attrs['encoded'] = 'DataFrame'\n index_to_h5(data.index, 'index', new_grp)\n index_to_h5(data.columns, 'columns', new_grp)\n new_grp.create_dataset('data', data=np.array(data))\n \n else:\n try:\n grp.create_dataset(key, data=data)\n grp[key].attrs['encoded'] = 'data'\n \n except TypeError:\n print(f\"TypeError, encoding {key} using {encoder}\")\n try:\n if encoder == 'yaml':\n string = np.string_(yaml.dump(data))\n elif encoder == 'json':\n string = np.string_(json.dumps(data))\n grp.create_dataset(key, data=np.string_(string))\n grp[key].attrs['encoded'] = encoder\n except Exception as e:\n print(e)\n try:\n grp.create_dataset(key, data=np.string_(data))\n grp[key].attrs['encoded'] = 'unknown'\n except Exception as e:\n print(e)\n print(f\"Unable to dump {key}\")\n\n\ndef index_to_h5(index, key, grp):\n if index.dtype == 'object':\n grp.create_dataset(\n key, data=np.array([np.string_(str(x)) for x in index])\n )\n else:\n grp.create_dataset(key, data=np.array(index))\n\n\ndef dict_to_h5(data, grp, **kwargs):\n \"\"\"Adds dictionary data to hdf5 group with same keys as dictionary.\n See data_to_h5 for how datatypes are handled.\n\n args:\n data: dictionary to add to hdf5\n grp: h5py group object to add the data to\n \n returns:\n None\n \"\"\"\n for key in data:\n s_key = str(key)\n sub_data = data[key]\n data_to_h5(sub_data, grp, s_key, **kwargs)\n\n\ndef attributes_to_h5(obj, grp, lst_attr=None, priv=False, dpriv=False,\n **kwargs):\n \"\"\"Function which takes a list of class attributes and stores them\n in a provided h5py group. See data_to_h5 for how datatypes are\n handled.\n \"\"\"\n if lst_attr is None:\n if dpriv:\n lst_attr = list(obj.__dict__.keys())\n elif priv:\n lst_attr = [x for x in obj.__dict__.keys() if '__' not in x]\n else:\n lst_attr = [x for x in obj.__dict__.keys() if '_' not in x]\n for attr in lst_attr:\n if attr in grp.keys():\n del(grp[attr])\n data = getattr(obj, attr)\n data_to_h5(data, grp, attr, **kwargs)\n\n\ndef h5_to_data(grp, encoder=True, Loader=yaml.UnsafeLoader):\n if encoder and 'encoded' in grp.attrs:\n encoded = grp.attrs['encoded']\n if encoded == 'None':\n data = None\n\n elif encoded == 'dict':\n data = h5_to_dict(grp, encoder=encoder, Loader=Loader)\n\n elif encoded == 'str':\n data = grp[...].item().decode()\n \n elif encoded == 'Series':\n data = pd.Series(\n data = grp['data'][()],\n index = h5_to_index(grp['index']),\n name = grp['name'][...].item().decode()\n )\n \n elif encoded == 'DataFrame':\n data = pd.DataFrame(\n data = grp['data'][()],\n index = h5_to_index(grp['index']),\n columns = h5_to_index(grp['columns']),\n )\n\n elif encoded == 'data':\n if grp.shape == ():\n data = grp[...].item()\n else:\n data = grp[()]\n\n elif encoded == 'yaml':\n data = yaml.load(grp[...].item(), Loader=Loader)\n\n elif encoded == 'json':\n data = json.loads(grp[...].item())\n\n elif encoded == 'unknown':\n try:\n data = eval(grp[...].item())\n except:\n data = grp[...].item().decode()\n else:\n if type(grp) == h5py._hl.group.Group:\n data = h5_to_dict(grp, encoder=encoder, Loader=Loader)\n \n elif grp.shape == ():\n temp = grp[...].item()\n if type(temp) == bytes:\n temp = temp.decode()\n if temp == 'None':\n data = None\n else:\n data = temp\n\n elif grp.shape is None:\n data = None\n\n else:\n data = grp[()]\n \n return data\n\n\ndef h5_to_index(grp):\n if np.issubdtype(grp.dtype, np.number):\n return grp[()]\n else:\n return soft_list_eval(grp)\n\n\ndef h5_to_dict(grp, **kwargs):\n \"\"\"Converts h5py group to dictionary. See h5_to_data for how\n different datatypes are handled.\n\n args:\n grp: h5py group object\n \n returns:\n data: dictionary of data from h5py group\n \"\"\"\n data = {}\n for key in grp.keys():\n try:\n e_key = eval(key, {})\n except:\n e_key = key\n\n data[e_key] = h5_to_data(grp[key], **kwargs)\n \n return data\n\n\ndef h5_to_attributes(obj, grp, lst_attr=None, **kwargs):\n if lst_attr is None:\n lst_attr = grp.keys()\n for attr in lst_attr:\n if attr in obj.__dict__.keys():\n data = h5_to_data(grp[attr], **kwargs)\n setattr(obj, attr, data)\n\n\ndef div0( a, b ):\n \"\"\" ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] \"\"\"\n with np.errstate(divide='ignore', invalid='ignore'):\n c = np.true_divide( a, b )\n c[ ~ np.isfinite( c )] = 0 # -inf inf NaN\n return c\n\n\ndef soft_list_eval(data):\n \"\"\"Tries to create list of evaluated items in data. If exception\n is thrown by eval, it just adds the element as is to the list.\n \n args:\n data: list or array-like, input data to be evaluated\n \n returns:\n out: list of values in data with eval applied if possible\n \"\"\"\n out = []\n for x in data:\n try:\n out.append(eval(x, {}))\n except:\n try:\n out.append(x.decode())\n except (AttributeError, SyntaxError):\n out.append(x)\n \n return out\n\n\ndef catch_h5py_file(filename, *args, **kwargs):\n while True:\n try:\n hdf5_file = h5py.File(filename, *args, **kwargs)\n break # Success!\n except OSError:\n pass\n return hdf5_file\n\n","sub_path":"paws/pawstools.py","file_name":"pawstools.py","file_ext":"py","file_size_in_byte":15401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"513814154","text":"# This script plots the CIR pdp and the power over time. This script is intended\n# for plotting the results of the 2016_05_06 experiments where I did the \n# on, off, and nearby the link line experiments. These experiments only consider\n# a link in one location. Only the environment changed.\nimport numpy as np\nimport cir_class_master as cir\nimport matplotlib.pyplot as plt\nimport os\n\n# Parameters\nfname = 'cirs.txt'\nmy_cir_obj = cir.cir_power_class(N_up=8,adj_type='pl',sig_type='m')\npower_vec = []\npdp_mat = []\ntime_vec = []\n\nwith open('data/2016_05_07_ece_office/pos18/' + fname,'r') as f:\n for line in f:\n \n if my_cir_obj.observe(line) == 0:\n continue\n \n power_vec.append(my_cir_obj.get_full_power())\n pdp_mat.append(my_cir_obj.get_cir_mag().tolist())\n time_vec.append(my_cir_obj.get_rel_time())\n\npower_vec = np.array(power_vec)\npdp_mat = np.array(pdp_mat).T\ntime_vec = np.array(time_vec)\n\ny_max = my_cir_obj.num_taps\nxing_y_val = my_cir_obj.first_path_tap_idx\n\nif os.path.isfile('data/xings/' + fname):\n xings = np.loadtxt('data/xings/' + fname)\nelse:\n xings = None\n\nplt.subplot(2,1,1)\nplt.imshow(pdp_mat,origin='upper',aspect='auto',interpolation='none',\n extent = (time_vec[0],time_vec[-1],y_max,0))\nif xings is not None:\n plt.plot(xings,xing_y_val*np.ones(xings.size),'rx',ms=10,mew=10)\nplt.xlim(time_vec[0],time_vec[-1])\nplt.xlabel('Time (sec)')\nplt.ylabel('Time delay (ns)')\nplt.subplot(2,1,2)\nplt.plot(time_vec,power_vec)\nif xings is not None:\n plt.plot(xings,np.median(power_vec)*np.ones(xings.size),'rx',ms=10,mew=10)\nplt.xlim(time_vec[0],time_vec[-1])\nplt.xlabel('Time (sec)')\nplt.ylabel('Power (dB)')\nplt.show()\n\n\n\n\n\n\n\n\n\n","sub_path":"plot_power_vs_time.py","file_name":"plot_power_vs_time.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"596878494","text":"from shapely.geometry import Point, Polygon, LinearRing\nfrom shapely.ops import nearest_points\nfrom math import radians, cos, sin, asin, sqrt\n\n\ndef inside_area_effect(game_area, location):\n boundary_area = Polygon(game_area.area)\n loc = Point([location.lat, location.lon])\n \"\"\"Returns True if inside the valid area, False if not\"\"\"\n return boundary_area.contains(loc) is not game_area.reversed\n\n\ndef distance_to_border(game_area, location):\n border = LinearRing(game_area.area)\n loc = Point([location.lon, location.lat])\n p1, _ = nearest_points(border, loc)\n\n def haversine(lon1, lat1, lon2, lat2):\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2\n c = 2 * asin(sqrt(a))\n r = 6371000\n return c * r\n\n distance = haversine(loc.x, loc.y, p1.x, p1.y)\n return distance\n","sub_path":"games/gps_car/area/area_methods.py","file_name":"area_methods.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"580821729","text":"# -*- coding: utf-8 -*-\nfrom __future__ import (print_function, division, absolute_import, unicode_literals, )\n\nimport types\nfrom inspect import getargspec\n\nfrom .shorthand import Builder\nlambd = Builder.l\nfrom .match import Match, Wildcard\nfrom .utils import (\n expr,\n flip,\n identity,\n constant,\n compose,\n apply,\n)\n\n\nclass CurryContainer(object):\n '''\n >>> cur = CurryContainer(lambda a, b, c: print([a, b, c]))\n >>> _ = cur << 'aaa' << 'bbb'\n >>> cur('ccc')\n [u'aaa', u'bbb', u'ccc']\n >>> cur = CurryContainer(lambda a, b='hogeeee', c='foooo': print([a, b, c]))\n >>> _ = cur << 'a' << ('c', 'c')\n >>> cur('b')\n [u'a', u'b', u'c']\n '''\n\n __slots__ = ('func', 'maxarglen', 'args', 'argkw', )\n\n def __init__(self, func):\n self.func = func\n self.maxarglen = len(getargspec(func).args)\n self.args = []\n self.argkw = []\n\n def __push_arg(self, arg):\n if isinstance(arg, types.TupleType):\n self.argkw.append(arg)\n else:\n self.args.append(arg)\n\n def __lshift__(self, arg):\n self.__push_arg(arg)\n return self\n\n def __call__(self, arg=None):\n argslen = len(self.args + self.argkw) + bool(arg is not None)\n if self.maxarglen < argslen:\n raise TypeError('{0} takes at most {1} argument ({2} given)'.format(\n self.func.__name__, self.maxarglen, argslen))\n if arg:\n self.__push_arg(arg)\n return self.func(*self.args, **dict(self.argkw))\n\n def call(self, arg=None):\n return self.__call__(arg)\n\n\ncurried = CurryContainer\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","sub_path":"masala/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"251222890","text":"from celery.utils.log import get_task_logger\nfrom collections import defaultdict\nimport sqlite3\nfrom . import mergestrategy\nfrom dateutil.parser import parse\nimport datetime\nimport pytz\n\nlogger = get_task_logger(__name__)\n\nSQLITE_DB_PATH = '/home/maks/web/cqapi/db.sqlite3'\nPARAMETER_PLACEHOLDER = '?'\nRECOGNIZE_DATETIME = True\n\n\ndef now():\n return datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n\n\nclass Clusterizer:\n def __init__(self):\n self.user_nodes = {}\n self.vk_nodes = {}\n self.fb_nodes = {}\n self.tw_nodes = {}\n self.cluster_id_nodes = {}\n self.email_nodes = {}\n self.identity_nodes = {}\n self.external_uid_nodes = {}\n\n self.conn = sqlite3.connect(SQLITE_DB_PATH)\n self.conn.row_factory = sqlite3.Row\n self.cursor = self.conn.cursor()\n\n def _add_email(self, email, user_id):\n self._add(email, 'email', self.email_nodes, user_id)\n\n def _add_vk(self, vk_id, user_id):\n self._add(int(vk_id), 'vk', self.vk_nodes, user_id)\n\n def _add_fb(self, fb_id, user_id):\n self._add(int(fb_id), 'fb', self.fb_nodes, user_id)\n\n def _add_tw(self, tw_id, user_id):\n self._add(int(tw_id), 'tw', self.tw_nodes, user_id)\n\n def _add_cluster_id(self, cluster_id, user_id):\n self._add(int(cluster_id), 'cluster_id', self.cluster_id_nodes, user_id)\n\n def _add_identity(self, identity, user_id):\n self._add(identity, 'identity', self.identity_nodes, user_id)\n\n def _add_external_uid(self, external_uid, user_id):\n self._add(external_uid, 'external_uid', self.external_uid_nodes, user_id)\n\n def _add(self, object, graph_object_name, list, user_id):\n if not object:\n return\n\n if object not in list:\n list[object] = Clusterizer.GraphNode(graph_object_name, object)\n\n # Добавим связь (неориентированную, в обе стороны)\n list[object].add_link(self.user_nodes[user_id])\n\n def clusterize(self):\n # Сначала нужно составить граф\n self._build_graph()\n\n # Запустить алгоритм\n nodes = set(self.user_nodes.values())\n return self._connected_components(nodes)\n\n def _build_graph(self):\n # Узлы с юзерами\n self.cursor.execute(\"SELECT * FROM auth_user\")\n users = self.cursor.fetchall()\n logger.info('Started: %d users.' % len(users))\n self.user_nodes = {user['id']: Clusterizer.GraphNode('user', user['id']) for user in users}\n\n # Узлы с связями\n self.cursor.execute(\"SELECT * FROM users_user2userlink\")\n for link in self.cursor.fetchall():\n # Добавим, если нету\n id1 = link['user1_id']\n id2 = link['user2_id']\n if id1 not in self.user_nodes:\n self.user_nodes[id1] = Clusterizer.GraphNode('user', id1)\n if id2 not in self.user_nodes:\n self.user_nodes[id2] = Clusterizer.GraphNode('user', id2)\n\n # Добавим связь (неориентированную)\n self.user_nodes[id1].add_link(self.user_nodes[id2])\n\n # Узлы с VK\n self.cursor.execute(\"SELECT * FROM users_oauthvk\")\n for vk in self.cursor.fetchall():\n self._add_vk(vk['uid'], vk['user_id'])\n\n # Узлы с FB\n self.cursor.execute(\"SELECT * FROM users_oauthfb\")\n for fb in self.cursor.fetchall():\n self._add_fb(fb['uid'], fb['user_id'])\n\n # Узлы с TW\n self.cursor.execute(\"SELECT * FROM users_oauthtw\")\n for tw in self.cursor.fetchall():\n self._add_tw(tw['uid'], tw['user_id'])\n\n # Узлы с Email\n for user in users:\n self._add_email(user['email'], user['id'])\n\n # UserProperty: $email\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userpropertylist.value FROM users_userpropertylist\n JOIN users_userprofile ON users_userprofile.cluster_id = users_userpropertylist.cluster_id\n JOIN auth_user ON users_userprofile.user_id = auth_user.id\n WHERE key='$email'\"\"\")\n for data in self.cursor.fetchall():\n self._add_email(data['value'], data['id'])\n\n # UserProperty: $vkId\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userpropertyint.value FROM users_userpropertyint\n JOIN users_userprofile ON users_userprofile.cluster_id = users_userpropertyint.cluster_id\n JOIN auth_user ON users_userprofile.user_id = auth_user.id\n WHERE key='$vkId'\"\"\")\n for data in self.cursor.fetchall():\n self._add_vk(data['value'], data['id'])\n\n # UserProperty: $facebookId\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userpropertyint.value FROM users_userpropertyint\n JOIN users_userprofile ON users_userprofile.cluster_id = users_userpropertyint.cluster_id\n JOIN auth_user ON users_userprofile.user_id = auth_user.id\n WHERE key='$facebookId'\"\"\")\n for data in self.cursor.fetchall():\n self._add_fb(data['value'], data['id'])\n\n # UserProperty: $twitterId\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userpropertyint.value FROM users_userpropertyint\n JOIN users_userprofile ON users_userprofile.cluster_id = users_userpropertyint.cluster_id\n JOIN auth_user ON users_userprofile.user_id = auth_user.id\n WHERE key='$twitterId'\"\"\")\n for data in self.cursor.fetchall():\n self._add_tw(data['value'], data['id'])\n\n # UserProperty: $identity\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userpropertylist.value FROM users_userpropertylist\n JOIN users_userprofile ON users_userprofile.cluster_id = users_userpropertylist.cluster_id\n JOIN auth_user ON users_userprofile.user_id = auth_user.id\n WHERE key='$identity'\"\"\")\n for data in self.cursor.fetchall():\n self._add_identity(data['value'], data['id'])\n\n # UserProperty: $app_uid\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userpropertyint.value, users_userpropertyint.app_id FROM users_userpropertyint\n JOIN users_userprofile ON users_userprofile.cluster_id = users_userpropertyint.cluster_id\n JOIN auth_user ON users_userprofile.user_id = auth_user.id\n WHERE key='$app_uid'\"\"\")\n for data in self.cursor.fetchall():\n app_uid = str(data['app_id']) + \":\" + str(data['value'])\n self._add_external_uid(app_uid, data['id'])\n\n # UserProperty: $twitterId\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userpropertyint.value FROM users_userpropertyint\n JOIN users_userprofile ON users_userprofile.cluster_id = users_userpropertyint.cluster_id\n JOIN auth_user ON users_userprofile.user_id = auth_user.id\n WHERE key='$cluster_id'\"\"\")\n for data in self.cursor.fetchall():\n self._add_cluster_id(data['value'], data['id'])\n\n # The graph nodes.\n class GraphNode(object):\n def __init__(self, type, name):\n self.__type = type\n self.__name = name\n self.__links = set()\n\n @property\n def type(self):\n return self.__type\n\n @property\n def name(self):\n return self.__name\n\n @property\n def links(self):\n return set(self.__links)\n\n def add_link(self, other):\n self.__links.add(other)\n other.__links.add(self)\n\n def __str__(self):\n return str(self.__type) + \":\" + str(self.__name)\n\n def _connected_components(self, nodes):\n \"\"\"\n Поиск связанных компонент в графе\n \"\"\"\n result = []\n nodes = set(nodes)\n\n while nodes:\n n = nodes.pop()\n group = {n}\n queue = [n]\n\n while queue:\n n = queue.pop(0)\n neighbors = n.links\n\n neighbors.difference_update(group)\n nodes.difference_update(neighbors)\n\n group.update(neighbors)\n queue.extend(neighbors)\n\n result.append(group)\n\n return result\n\n\nclass Merger:\n def __init__(self):\n self.conn = sqlite3.connect(SQLITE_DB_PATH, detect_types=sqlite3.PARSE_DECLTYPES)\n self.conn.row_factory = sqlite3.Row\n self.cursor = self.conn.cursor()\n\n def merge_properties(self, clusters):\n self.cursor.execute(\"\"\"SELECT auth_user.id, users_userprofile.cluster_id FROM auth_user\n JOIN users_userprofile ON users_userprofile.user_id = auth_user.id\"\"\")\n\n cluster2users = defaultdict(list)\n user2cluster = {}\n for pair in self.cursor.fetchall():\n cluster2users[pair['cluster_id']].append(pair['id'])\n user2cluster[pair['id']] = pair['cluster_id']\n\n for cluster in clusters:\n ids = [node.name for node in cluster if node.type == 'user']\n\n # Смотрим номера кдастеров у всех ids (собираем в множество)\n current_clusters = set()\n for id in ids:\n current_clusters.add(user2cluster[id])\n \n if len(current_clusters) > 1:\n # записываем новый айди кластера всем членам кластера\n\n # Доабвляем пропертю всем членам кластера\n\n # Объекдиняем кластера, с номерами из множества\n self._merge_properties(current_clusters)\n\n # Save all changes\n self.conn.commit()\n self.conn.close()\n\n DEFAULT_STRATEGY = 'strategy_last_updated'\n\n def _merge_properties(self, ids):\n props = self.get_all_properties(ids)\n cluster_id = self.create_new_cluster(ids)\n logger.info('Merging for cluster %s properties: %s' % (str(ids), str(props)))\n for prop in props:\n merge_list = self.get_property_values(ids, prop) # Кортеж!\n logger.info('Values: %s' % str(merge_list))\n\n # Определяем стратегию сливания\n name = prop[1]\n if name == '$sessions' or name == '$sessions2' or name == '$last_seen' or name == '$qwe':\n strategy = 'strategy_sum'\n if name == '$email' or name == '$name':\n strategy = 'strategy_union'\n else:\n strategy = self.DEFAULT_STRATEGY\n\n try:\n merged = getattr(mergestrategy, strategy)(merge_list)\n except:\n # Если не удалось применить стратегию (неверные типы) то применяем стретегию последний установленный\n merged = getattr(mergestrategy, self.DEFAULT_STRATEGY)(merge_list)\n\n logger.info('Merged %s: %s (type: %s)' % (prop, str(merged), type(merged)))\n self.write_property(cluster_id, prop[0], prop[1], merged)\n\n self.write_cluster_id_property(cluster_id)\n self.remove_old_properties(ids)\n\n def create_new_cluster(self, ids):\n self.cursor.execute(\"INSERT INTO users_usercluster DEFAULT VALUES\")\n cluster_id = self.cursor.lastrowid\n\n sql = \"UPDATE users_userprofile SET cluster_id = %d WHERE cluster_id IN (%s)\"\n sql = sql % (cluster_id, ','.join([str(id) for id in ids]))\n self.cursor.execute(sql)\n\n return cluster_id\n\n def remove_old_properties(self, ids):\n ids = ','.join([str(id) for id in ids])\n\n self.cursor.execute(\"DELETE FROM users_userpropertyint WHERE cluster_id IN (%s)\" % ids)\n self.cursor.execute(\"DELETE FROM users_userpropertydatetime WHERE cluster_id IN (%s)\" % ids)\n self.cursor.execute(\"DELETE FROM users_userpropertylist WHERE cluster_id IN (%s)\" % ids)\n self.cursor.execute(\"DELETE FROM users_userpropertystr WHERE cluster_id IN (%s)\" % ids)\n\n def get_all_properties(self, clusters):\n sql = \"\"\"SELECT app_id, key FROM users_userpropertyint WHERE cluster_id IN ({0})\n UNION\n SELECT app_id, key FROM users_userpropertystr WHERE cluster_id IN ({0})\n UNION\n SELECT app_id, key FROM users_userpropertydatetime WHERE cluster_id IN ({0})\n UNION\n SELECT app_id, key FROM users_userpropertylist WHERE cluster_id IN ({0})\"\"\"\n sql = sql.format(','.join([str(c) for c in clusters]))\n self.cursor.execute(sql)\n return [(row['app_id'], row['key']) for row in self.cursor.fetchall()]\n\n def get_property_values(self, ids, prop):\n where_clause = \"cluster_id IN ({0}) AND key = {1}\"\n where_clause = where_clause.format(','.join([str(c) for c in ids]), PARAMETER_PLACEHOLDER)\n if prop[0] is None:\n where_clause += \" AND app_id IS NULL\"\n else:\n where_clause += \" AND app_id = %d\" % prop[0]\n\n sql = \"\"\"SELECT value, updated FROM users_userpropertyint WHERE {0}\n UNION\n SELECT value, updated FROM users_userpropertystr WHERE {0}\n UNION\n SELECT value, updated FROM users_userpropertydatetime WHERE {0}\n UNION\n SELECT value, updated FROM users_userpropertylist WHERE {0}\"\"\"\n sql = sql.format(where_clause)\n self.cursor.execute(sql, (prop[1],)*4)\n return [(self.recognize_datetime(row['value']), self.recognize_datetime(row['updated'])) for row in self.cursor.fetchall()]\n\n def recognize_datetime(self, value):\n if RECOGNIZE_DATETIME:\n try:\n return parse(value).replace(tzinfo=pytz.utc)\n except:\n return value\n else:\n return value\n\n def get_table_for_class(self, value):\n if isinstance(value, int):\n return \"users_userpropertyint\"\n elif isinstance(value, datetime.datetime):\n return \"users_userpropertydatetime\"\n elif isinstance(value, list):\n return \"users_userpropertylist\"\n else:\n return \"users_userpropertystr\"\n\n def write_property(self, cluster_id, app_id, key, value):\n table = self.get_table_for_class(value)\n if table != 'users_userpropertylist':\n sql = \"INSERT INTO {0} (cluster_id, app_id, key, value, updated) VALUES ({1}, {1}, {1}, {1}, {1})\"\n sql = sql.format(table, PARAMETER_PLACEHOLDER)\n self.cursor.execute(sql, (cluster_id, app_id, key, value, now()))\n logger.info(\"SQL: %s\" % sql)\n\n def write_cluster_id_property(self, cluster_id):\n sql = \"INSERT INTO users_userpropertyint(cluster_id, app_id, key, value, updated) VALUES ({0}, NULL, '$cluster_id', {0}, {0})\"\n sql = sql.format(PARAMETER_PLACEHOLDER)\n self.cursor.execute(sql, (cluster_id, cluster_id, now()))\n logger.info(\"SQL: %s\" % sql)\n\n\ndef run():\n clusterizer = Clusterizer()\n clusters = clusterizer.clusterize()\n logger.info('Finished: %d clusters' % len(clusters))\n\n #merge_properties(clusters)\n merger = Merger()\n merger.merge_properties(clusters)\n #response = _build_response(clusters)\n #return response\n\n\nif __name__ == '__main__':\n import logging\n logger = logging.getLogger(\"simple_log\")\n logger.setLevel(logging.INFO)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n logger.addHandler(ch)\n logger.info('sdd')\n\n run()\n","sub_path":"clusterize/clusterize.py","file_name":"clusterize.py","file_ext":"py","file_size_in_byte":15696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"589939343","text":"import pickle\nimport numbers\nimport tensorflow as tf\nfrom tensorflow.contrib.layers.python.layers import fully_connected\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import standard_ops\nfrom tensorflow.python.platform import tf_logging as logging\n\n\ndef add_fc(inputs, outdim, train_phase, scope_in):\n fc = fully_connected(inputs, outdim, activation_fn=None, weights_regularizer = tf.contrib.layers.l2_regularizer(0.0005), scope=scope_in + '/fc')\n fc_bnorm = tf.layers.batch_normalization(fc, momentum=0.1, epsilon=1e-5,\n training=train_phase, name=scope_in + '/bnorm')\n fc_relu = tf.nn.relu(fc_bnorm, name=scope_in + '/relu')\n fc_out = tf.layers.dropout(fc_relu, seed=0, training=train_phase, name=scope_in + '/dropout')\n return fc_out\n\ndef pdist(x1, x2):\n \"\"\"\n x1: Tensor of shape (h1, w)\n x2: Tensor of shape (h2, w)\n Return pairwise distance for each row vector in x1, x2 as\n a Tensor of shape (h1, h2)\n \"\"\"\n x1_square = tf.reshape(tf.reduce_sum(x1*x1, axis=1), [-1, 1])\n x2_square = tf.reshape(tf.reduce_sum(x2*x2, axis=1), [1, -1])\n return tf.sqrt(x1_square - 2 * tf.matmul(x1, tf.transpose(x2)) + x2_square + 1e-4)\n\ndef embedding_loss(im_embeds, sent_embeds, im_labels, args):\n \"\"\"\n im_embeds: (b, 512) image embedding tensors\n sent_embeds: (sample_size * b, 512) sentence embedding tensors\n where the order of sentence corresponds to the order of images and\n setnteces for the same image are next to each other\n im_labels: (sample_size * b, b) boolean tensor, where (i, j) entry is\n True if and only if sentence[i], image[j] is a positive pair\n \"\"\"\n # compute embedding loss\n sent_im_ratio = args.sample_size\n num_img = args.batch_size\n num_sent = num_img * sent_im_ratio\n\n sent_im_dist = pdist(sent_embeds, im_embeds)\n # image loss: sentence, positive image, and negative image\n pos_pair_dist = tf.reshape(tf.boolean_mask(sent_im_dist, im_labels), [num_sent, 1])\n neg_pair_dist = tf.reshape(tf.boolean_mask(sent_im_dist, ~im_labels), [num_sent, -1])\n im_loss = tf.clip_by_value(args.margin + pos_pair_dist - neg_pair_dist, 0, 1e6)\n im_loss = tf.reduce_mean(tf.nn.top_k(im_loss, k=args.num_neg_sample)[0])\n # sentence loss: image, positive sentence, and negative sentence\n neg_pair_dist = tf.reshape(tf.boolean_mask(tf.transpose(sent_im_dist), ~tf.transpose(im_labels)), [num_img, -1])\n neg_pair_dist = tf.reshape(tf.tile(neg_pair_dist, [1, sent_im_ratio]), [num_sent, -1])\n sent_loss = tf.clip_by_value(args.margin + pos_pair_dist - neg_pair_dist, 0, 1e6)\n sent_loss = tf.reduce_mean(tf.nn.top_k(sent_loss, k=args.num_neg_sample)[0])\n # sentence only loss (neighborhood-preserving constraints)\n sent_sent_dist = pdist(sent_embeds, sent_embeds)\n sent_sent_mask = tf.reshape(tf.tile(tf.transpose(im_labels), [1, sent_im_ratio]), [num_sent, num_sent])\n pos_pair_dist = tf.reshape(tf.boolean_mask(sent_sent_dist, sent_sent_mask), [-1, sent_im_ratio])\n pos_pair_dist = tf.reduce_max(pos_pair_dist, axis=1, keep_dims=True)\n neg_pair_dist = tf.reshape(tf.boolean_mask(sent_sent_dist, ~sent_sent_mask), [num_sent, -1])\n sent_only_loss = tf.clip_by_value(args.margin + pos_pair_dist - neg_pair_dist, 0, 1e6)\n sent_only_loss = tf.reduce_mean(tf.nn.top_k(sent_only_loss, k=args.num_neg_sample)[0])\n\n loss = im_loss * args.im_loss_factor + sent_loss + sent_only_loss * args.sent_only_loss_factor\n return loss\n\n\ndef recall_k(im_embeds, sent_embeds, im_labels, ks=None):\n \"\"\"\n Compute recall at given ks.\n \"\"\"\n sent_im_dist = pdist(sent_embeds, im_embeds)\n def retrieval_recall(dist, labels, k):\n # Use negative distance to find the index of\n # the smallest k elements in each row.\n pred = tf.nn.top_k(-dist, k=k)[1]\n # Create a boolean mask for each column (k value) in pred,\n # s.t. mask[i][j] is 1 iff pred[i][k] = j.\n pred_k_mask = lambda topk_idx: tf.one_hot(topk_idx, labels.shape[1],\n on_value=True, off_value=False, dtype=tf.bool)\n # Create a boolean mask for the predicted indicies\n # by taking logical or of boolean masks for each column,\n # s.t. mask[i][j] is 1 iff j is in pred[i].\n pred_mask = tf.reduce_any(tf.map_fn(\n pred_k_mask, tf.transpose(pred), dtype=tf.bool), axis=0)\n # Entry (i, j) is matched iff pred_mask[i][j] and labels[i][j] are 1.\n matched = tf.cast(tf.logical_and(pred_mask, labels), dtype=tf.float32)\n return tf.reduce_mean(tf.reduce_max(matched, axis=1))\n return tf.concat(\n [tf.map_fn(lambda k: retrieval_recall(tf.transpose(sent_im_dist), tf.transpose(im_labels), k),\n ks, dtype=tf.float32),\n tf.map_fn(lambda k: retrieval_recall(sent_im_dist, im_labels, k),\n ks, dtype=tf.float32)],\n axis=0), sent_im_dist\n\ndef extract_axis_1(data, ind):\n \"\"\"\n Get specified elements along the first axis of tensor.\n :param data: Tensorflow tensor that will be subsetted.\n :param ind: Indices to take (one for each element along axis 0 of data).\n :return: Subsetted tensor.\n\n function copied from - https://stackoverflow.com/questions/41273361/get-the-last-output-of-a-dynamic-rnn-in-tensorflow\n \"\"\"\n batch_range = tf.range(tf.shape(data)[0])\n indices = tf.stack([batch_range, ind], axis=1)\n res = tf.gather_nd(data, indices)\n \n return res\n\ndef weight_l2_regularizer(initial_weights, scale, scope=None):\n \"\"\"Returns a function that can be used to apply L2 regularization to weights.\n Small values of L2 can help prevent overfitting the training data.\n Args:\n scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer.\n scope: An optional scope name.\n Returns:\n A function with signature `l2(weights)` that applies L2 regularization.\n Raises:\n ValueError: If scale is negative or if scale is not a float.\n \"\"\"\n if isinstance(scale, numbers.Integral):\n raise ValueError('scale cannot be an integer: %s' % (scale,))\n if isinstance(scale, numbers.Real):\n if scale < 0.:\n raise ValueError('Setting a scale less than 0 on a regularizer: %g.' %\n scale)\n if scale == 0.:\n logging.info('Scale of 0 disables regularizer.')\n return lambda _: None\n\n def l2(weights):\n \"\"\"Applies l2 regularization to weights.\"\"\"\n with ops.name_scope(scope, 'l2_regularizer', [weights]) as name:\n my_scale = ops.convert_to_tensor(scale,\n dtype=weights.dtype.base_dtype,\n name='scale')\n weight_diff = initial_weights - weights\n return standard_ops.multiply(my_scale, nn.l2_loss(weight_diff), name=name)\n\n return l2\n\ndef setup_initialize_fc_layers(feats, parameters, scope_in, train_phase, args):\n for i, params in enumerate(parameters):\n scaling = params['scaling']\n outdim = len(scaling)\n cca_mean, cca_proj = params[scope_in + '_mean'], params[scope_in + '_proj']\n weights_init = tf.constant_initializer(cca_proj, dtype=tf.float32)\n weight_reg = weight_l2_regularizer(params[scope_in + '_proj'], args.cca_weight_reg)\n if (i + 1) < len(parameters):\n activation_fn = tf.nn.relu\n else:\n activation_fn = None\n\n feats = fully_connected(feats - cca_mean, outdim, activation_fn=activation_fn,\n weights_initializer = weights_init,\n weights_regularizer = weight_reg,\n scope = scope_in + '_embed_' + str(i)) * scaling\n\n feats = tf.nn.l2_normalize(feats, 1, epsilon=1e-10)\n return feats\n\ndef setup_sent_model(tokens, train_phase, vecs, max_length, args, fc_dim = 2048, embed_dim = 512):\n word_embeddings = tf.get_variable('word_embeddings', vecs.shape, initializer=tf.constant_initializer(vecs))\n embedded_words = tf.nn.embedding_lookup(word_embeddings, tokens)\n embed_l2reg = tf.nn.l2_loss(word_embeddings - vecs)\n\n if args.language_model == 'gru':\n source_sequence_length = tf.reduce_sum(tf.cast(tokens > 0, tf.int32), 1)\n encoder_cell = tf.nn.rnn_cell.GRUCell(fc_dim)\n encoder_outputs, encoder_state = tf.nn.dynamic_rnn(\n encoder_cell, embedded_words, dtype=tf.float32,\n sequence_length=source_sequence_length)\n\n final_outputs = extract_axis_1(encoder_outputs, source_sequence_length-1)\n outputs = fully_connected(final_outputs, embed_dim, activation_fn = None,\n weights_regularizer = tf.contrib.layers.l2_regularizer(0.005),\n scope = 'phrase_encoder')\n\n s_embed = tf.nn.l2_normalize(outputs, 1, epsilon=1e-10)\n else:\n num_words = tf.reduce_sum(tf.to_float(tokens > 0), 1, keep_dims=True) + 1e-10\n average_word_embedding = tf.nn.l2_normalize(tf.reduce_sum(embedded_words, 1) / num_words, 1)\n if args.language_model == 'attend':\n context_vector = tf.tile(tf.expand_dims(average_word_embedding, 1), (1, max_length, 1))\n attention_inputs = tf.concat((context_vector, embedded_words), 2)\n attention_weights = fully_connected(attention_inputs, 1, \n weights_regularizer = tf.contrib.layers.l2_regularizer(0.0005),\n scope='word_attention')\n \n attention_weights = tf.expand_dims(tf.nn.softmax(tf.squeeze(attention_weights)), 2)\n sent_feats = tf.reshape(tf.nn.l2_normalize(tf.reduce_sum(embedded_words * attention_weights, 1), 1), [-1, vecs.shape[1]])\n else:\n sent_feats = average_word_embedding\n\n if args.init_filename:\n parameters = pickle.load(open(args.init_filename, 'rb'))\n s_embed = setup_initialize_fc_layers(sent_feats, parameters, 'lang', train_phase, args)\n else:\n sent_fc1 = add_fc(sent_feats, fc_dim, train_phase,'sent_embed_1')\n sent_fc2 = fully_connected(sent_fc1, embed_dim, activation_fn=None,\n weights_regularizer = tf.contrib.layers.l2_regularizer(0.0005),\n scope = 'sent_embed_2')\n s_embed = tf.nn.l2_normalize(sent_fc2, 1, epsilon=1e-10)\n\n return s_embed, embed_l2reg\n\ndef setup_img_model(im_feats, train_phase, args, fc_dim = 2048, embed_dim = 512):\n if args.init_filename:\n parameters = pickle.load(open(args.init_filename, 'rb'))\n i_embed = setup_initialize_fc_layers(im_feats, parameters, 'vis', train_phase, args)\n else:\n im_fc1 = add_fc(im_feats, fc_dim, train_phase, 'im_embed_1')\n im_fc2 = fully_connected(im_fc1, embed_dim, activation_fn=None,\n weights_regularizer = tf.contrib.layers.l2_regularizer(0.0005),\n scope = 'im_embed_2')\n i_embed = tf.nn.l2_normalize(im_fc2, 1, epsilon=1e-10)\n\n return i_embed\n\ndef embedding_model(im_feats, tokens, train_phase, im_labels , vecs, \n max_length, args, fc_dim = 2048, embed_dim = 512):\n \"\"\"\n Build two-branch embedding networks.\n fc_dim: the output dimension of the first fc layer.\n embed_dim: the output dimension of the second fc layer, i.e.\n embedding space dimension.\n \"\"\"\n # Image branch.\n i_embed = setup_img_model(im_feats, train_phase, args, fc_dim, embed_dim)\n\n # Text branch.\n s_embed, embed_l2reg = setup_sent_model(tokens, train_phase, vecs, max_length, args, fc_dim, embed_dim)\n return i_embed, s_embed, embed_l2reg\n\ndef setup_train_model(im_feats, sent_feats, train_phase, im_labels, vecs, max_length, args):\n # im_feats b x image_feature_dim\n # sent_feats 5b x sent_feature_dim\n # train_phase bool (Should be True.)\n # im_labels 5b x b\n i_embed, s_embed, embed_l2reg = embedding_model(im_feats, sent_feats, train_phase, im_labels, vecs, max_length, args)\n loss = embedding_loss(i_embed, s_embed, im_labels, args) + args.word_embedding_reg * embed_l2reg\n return loss\n\n\n","sub_path":"retrieval_model.py","file_name":"retrieval_model.py","file_ext":"py","file_size_in_byte":12452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"52390004","text":"from data_processing.keys_generator import KeysGenerator\n\n\n# Keys Generator\n\ndef test_load_jobs():\n \"\"\"Loads a job from the database\"\"\"\n generator = KeysGenerator()\n id = generator.load_jobs(test = True)\n assert isinstance(generator.jobs[id][\"name\"], str)\n assert isinstance(generator.jobs[id][\"company\"], str)\n assert isinstance(generator.jobs[id][\"category\"], str)\n assert isinstance(generator.jobs[id][\"contents\"], list) \n assert isinstance(generator.jobs[id][\"contents\"][0], dict) \n assert isinstance(generator.jobs[id][\"contents\"][0][\"text\"], list)\n assert isinstance(generator.jobs[id][\"contents\"][0][\"score\"], int)\n assert isinstance(generator.jobs[id][\"contents\"][0][\"key\"], bool)\n\n\ndef test_calc_word_and_doc_frequency():\n \"\"\"Calculates document frequency, word frequency, and word total\"\"\"\n generator = KeysGenerator()\n id = generator.load_jobs(test = True)\n generator.calc_word_and_doc_frequency()\n\n assert len(generator.document_frequency) > 0\n assert len(generator.jobs[id][\"word_frequency\"]) > 0\n assert generator.jobs[id][\"word_total\"] > 0\n\n for word in generator.document_frequency:\n assert generator.document_frequency[word] >= 1\n\n for word in generator.jobs[id][\"word_frequency\"]:\n assert word in generator.document_frequency\n\n\ndef test_calc_tf_dif():\n \"\"\"Calculates tf-dif score for a job\"\"\"\n generator = KeysGenerator()\n id = generator.load_jobs(test = True)\n generator.calc_word_and_doc_frequency()\n generator.calc_tf_dif()\n\n assert len(generator.jobs[id][\"tf_dif\"]) < len(generator.jobs[id][\"word_frequency\"])\n\n for word in generator.jobs[id][\"tf_dif\"]:\n assert generator.jobs[id][\"tf_dif\"][word] >= 0\n\n\ndef test_determine_keywords():\n \"\"\"Creates list of keywords of correct length\"\"\"\n generator = KeysGenerator()\n id = generator.load_jobs(test = True)\n keywords = generator.determine_keywords(insert_into_db = False)\n\n assert 0 < len(keywords) < 21\n assert isinstance(keywords, list)\n\n\ndef test_determine_key_sentences():\n \"\"\"Flags key sentences\"\"\"\n generator = KeysGenerator()\n id = generator.load_jobs(test = True)\n keywords = generator.determine_keywords(insert_into_db = False)\n contents = generator.determine_key_sentences(insert_into_db = False)\n\n key_sentences = 0\n for sentence in contents:\n if sentence[\"key\"] == True:\n assert sentence[\"score\"] >= 0\n key_sentences += 1\n \n assert key_sentences > 0\n","sub_path":"tests/key_generator_test.py","file_name":"key_generator_test.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"191042183","text":"# 建立鏈結串列與遍歷此鏈結串列\nclass Node():\n '''節點'''\n\n def __init__(self, data=None):\n self.data = data # 資料\n self.next = None # 指標\n\n\nclass Linked_list():\n '''鏈結串列'''\n\n def __init__(self):\n self.head = None # 鏈結串列的第一個節點\n\n def print_list(self):\n '''列印鏈結串列'''\n ptr = self.head # 指標指向鏈結串列第一個節點\n while ptr:\n print(ptr.data) # 列印節點\n ptr = ptr.next # 移動指標到下一個節點\n\n def length(self):\n ptr = self.head\n count = 0\n while ptr:\n count += 1\n ptr = ptr.next\n return count\n\n\nlink = Linked_list()\nlink.head = Node(5) # 節點1\nn2 = Node(15) # 節點2\nn3 = Node(25) # 節點3\nlink.head.next = n2 # 節點1指向節點2\nn2.next = n3\nlink.print_list() # 列印鏈結串列 link\nprint(\"鏈結串列長度是:\", link.length())\n","sub_path":"Kingreturn_Algorithm/ch3-Linked_List/ch3t-1.py","file_name":"ch3t-1.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"25037711","text":"import torch\nimport torch.nn as nn\n\n\nclass PlantDiseaseNet(nn.Module):\n def __init__(self, training: bool = False):\n super(PlantDiseaseNet, self).__init__()\n self.conv1 = self.nnlayer(3, 24)\n self.conv2 = self.nnlayer(24, 24)\n self.conv3 = self.nnlayer(24, 48)\n\n self.pool1 = self.pool(2)\n self.drop1 = self.dropout(0.2)\n\n self.conv4 = self.nnlayer(48, 48)\n self.conv5 = self.nnlayer(48, 48)\n self.conv6 = self.nnlayer(48, 48)\n\n self.pool2 = self.pool(2)\n self.drop2 = self.dropout(0.2)\n\n self.dense1 = nn.Linear(48 * 50 * 50, 1024)\n self.drop3 = self.dropout(0.3)\n self.dense2 = nn.Linear(1024, 15)\n self.drop4 = self.dropout(0.3)\n\n def nnlayer(self, chans_in: int, chans_out: int):\n return nn.Sequential(\n nn.Conv2d(chans_in, chans_out, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(chans_out, eps=1e-5, momentum=0.9),\n nn.ReLU(inplace=True),\n )\n\n def pool(self, k_size: int):\n return nn.MaxPool2d(\n kernel_size=k_size, stride=k_size, dilation=1, ceil_mode=False\n )\n\n def dropout(self, p: float):\n return nn.Dropout2d(p)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.conv2(out)\n out = self.conv3(out)\n out = self.pool1(out)\n out = self.drop1(out)\n out = self.conv4(out)\n out = self.conv5(out)\n out = self.conv6(out)\n out = self.pool2(out)\n out = self.drop2(out)\n out = out.view(out.size(0), -1)\n out = self.dense1(out)\n out = self.drop3(out)\n out = self.dense2(out)\n out = self.drop4(out)\n return out\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"362320029","text":"#-*-coding=utf-8-*-\n# from PIL import Image\nfrom claptcha import Claptcha\n\ndef testcase():\n im=Image.open('captcha.gif')\n data=im.convert('P')\n hist= im.histogram()\n print(data)\n values={}\n for i in range(256):\n values[i]=hist[i]\n\n print(values)\n for k,v in sorted(values.items(),reverse=True):\n print(k,v)\n\n\ndef case3():\n c = Claptcha(\"8069\",'C:\\\\Windows\\winsxs\\\\amd64_microsoft-windows-f..etype-timesnewroman_31bf3856ad364e35_6.1.7601.17514_none_3b958c66aff6cdb7\\\\times.ttf')\n t,_ = c.write('code1.png')\n\ncase3()\n# testcase()\n\n","sub_path":"image_detect/yanzhengma.py","file_name":"yanzhengma.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"639036798","text":"\"\"\"\nhttps://www.hackerrank.com/challenges/the-love-letter-mystery\n\n\n\"\"\"\nimport sys\n\n\ndef get_palindrome_distance(s):\n \"\"\"\n Gets the number of operations required to turn a word into a palindrome.\n \n An operation is a replacement of a character for a lower-value character, e.g., 'b' -> 'a'\n :param s: string for which to calculate the distance\n :return: number of operations required to change `s` into a palindrome\n >>> get_palindrome_distance('abc')\n 2\n >>> get_palindrome_distance('adfb')\n 3\n \"\"\"\n counter = 0\n i, j = 0, len(s) - 1\n while i < j:\n counter += abs(ord(s[i]) - ord(s[j]))\n i += 1\n j -= 1\n return counter\n\n\nif __name__ == '__main__':\n lines = [line.strip() for line in sys.stdin.readlines()]\n n = int(lines[0])\n test_cases = lines[1:]\n\n for s in test_cases:\n print(get_palindrome_distance(s))\n","sub_path":"hackerrank/src/algorithms/strings/love_letter_mystery.py","file_name":"love_letter_mystery.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"48658708","text":"from itertools import groupby\nfrom datetime import datetime, timedelta, date\nfrom odoo import api, fields, models, tools, _\nfrom odoo.exceptions import UserError, ValidationError, except_orm \nfrom odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT\nfrom odoo.tools.misc import formatLang\nimport odoo.addons.decimal_precision as dp\nimport random\n\nimport itertools\nimport psycopg2\n\n\n\nclass ProductProduct(models.Model):\n _inherit = 'product.product'\n\n @api.onchange('categ_id')\n def _get_default_product_name(self):\n self.ensure_one()\n if self._context.get('categ_name') or self._context.get('default_categ_name'):\n cat_name = self._context.get('categ_name')\n cat_id = self.env['product.category'].search([('name', '=ilike', cat_name)], limit=1).id\n ra = ''\n \n if cat_name == 'Fabric':\n if not ra:\n rand = str(random.randint(10000000,99999999))\n ra += rand\n self.name = ra\n self.type = 'product'\n self.categ_id = cat_id \n self.sale_ok = False\n self.purchase_ok = True\n\n uom_line = self.env['product.uom'].search([('name', '=', 'Yards')])\n if uom_line:\n self.uom_id = uom_line.id\n else:\n self.uom_id = 1 \n elif cat_name == 'Trims' or cat_name == 'PandP':\n self.name = ''\n self.type = 'product'\n self.categ_id = cat_id \n self.sale_ok = False\n self.purchase_ok = True\n elif cat_name == 'Sample':\n self.sale_ok = True\n self.purchase_ok = False \n self.type = 'product' \n self.categ_id = cat_id \n else:\n self.name = '' \n\n @api.multi\n def write(self, values):\n ''' Store the standard price change in order to be able to retrieve the cost of a product for a given date'''\n cat_id = self.categ_id.id\n if cat_id == 3:\n values['barcode'] = self.name\n # raise UserError(_(cat_id))\n res = super(ProductProduct, self).write(values)\n if 'standard_price' in values:\n self._set_standard_price(values['standard_price'])\n return res \n\n\nclass ProductTemplate(models.Model):\n _inherit = 'product.template'\n\n # extra field for idls start \n account_id = fields.Many2one('sample.account', string=\"Account Of\")\n source_id = fields.Many2one('sample.source', string=\"Source Of\")\n style_id = fields.Many2one('sample.style', string=\"Buyer Style Name\")\n buyer_depertment_id = fields.Many2one('buyer.depertment', string=\"Buyer Depertment\")\n size_id = fields.Many2one('sample.size', string=\"Size\")\n type_id = fields.Many2one('sample.type', string=\"Sample Type\")\n wash_id = fields.Many2one('sample.wash', string=\"Wash\")\n color_id = fields.Many2one('sample.color', string=\"Color\")\n description = fields.Text(string=\"Description\")\n # logged_user = fields.Char(string='Current User', default=lambda self: self.env.uid),\n log_user = fields.Many2one('res.users',string='Merchandiser Name', default=lambda self: self.env.uid,readonly=True,store=True)\n buyeer_id = fields.Many2one('res.partner', string='Buyer Name', domain=[('customer', '=', True)])\n fabic = fields.Many2one('fabric.sale', string=\"Fabric Bar Code\")\n fabic_supplier = fields.Char(string=\"Fabric Supplier\")\n\n categ_name = fields.Char(string=\"Categ Name\")\n\n \n @api.model\n def create(self, vals):\n if vals.get('categ_id'):\n n = vals.get('categ_id')\n cat_name = self.env['product.category'].search([('id', '=', n)])\n vals['categ_name'] = cat_name.name\n return super(ProductTemplate, self).create(vals)\n \n \n\n\n # extra field for idls end\n\n @api.onchange('fabic')\n def _onchange_fabic(self):\n if self.fabic:\n supplier_name = self.fabic.supplier.name\n self.fabic_supplier = supplier_name\n\n @api.onchange('buyer_depertment_id')\n def _onchange_buyer_depertment_id(self):\n if self.buyer_depertment_id:\n buyer_depertment_name = self.buyer_depertment_id.name\n vaild_names = ['Boys','Girls','Man','Ladies','New Born']\n if buyer_depertment_name not in vaild_names:\n raise ValidationError(_(\"Please choose Between Boys, Girls, Man, Ladies, New Born. If those are not created then create those iteam first. \"))\n\n\n @api.depends('style_id','buyer_depertment_id','color_id')\n def concatenate_custom_fields_pro(self):\n \n \n style = str(self.style_id.name)\n if style:\n self.ensure_one()\n concat_name = \"\" \n buyer_depertment = str(self.buyer_depertment_id.name)\n\n if buyer_depertment == 'Boys' :\n self.combined_name = 'B-'\n elif buyer_depertment == 'Ladies': \n self.combined_name = 'L-'\n elif buyer_depertment == 'Man': \n self.combined_name = 'M-' \n elif buyer_depertment == 'New Born': \n self.combined_name = 'KB-' \n elif buyer_depertment == 'Girls': \n self.combined_name = 'G-' \n else: \n self.combined_name = ''\n\n color = str(self.color_id.name)\n\n if style:\n concat_name += str(style) + \"-\"\n else: \n concat_name += \"Style Name\"\n if self.combined_name:\n concat_name += str(self.combined_name) + \"\" + str(self.seque_no)\n else: \n concat_name += \"\" \n if color:\n concat_name += \"-\" + str(color)\n else: \n concat_name += \"Color\" \n # raise ValidationError(_(concat_name))\n\n self.name = concat_name\n combined_name = fields.Char(compute=concatenate_custom_fields_pro,store=True) \n \n\n def _get_con_seq(self):\n seq = self.env['ir.sequence'].next_by_code('product.template') or '/'\n return seq\n seque_no = fields.Char(default=_get_con_seq,store=True,string=\"sec_no\")\n\n def _default_barcode_for_sample(self):\n if not self._context.get('categ_id') or self._context.get('categ_id') == 6:\n rand = random.randint(10000000,99999999)\n # ean = barcode.get('ean13', str(rand))\n return rand \n else:\n return '' \n barcode = fields.Char('Barcode', oldname='ean13',default=_default_barcode_for_sample, related='product_variant_ids.barcode') \n\n\n\n @api.multi\n def action_view_costing(self):\n self.ensure_one()\n product_ids = self.with_context(active_test=False).product_variant_ids.ids\n\n return {\n 'name': _('costing.sale.form'),\n 'res_model': 'costing.sale',\n 'type': 'ir.actions.act_window',\n 'view_mode': 'form',\n 'view_type': 'form',\n 'target': 'new',\n 'context': \"{'design_reff_id': \" + str(product_ids[0]) + \"}\",\n \n } \n\n\n @api.onchange('categ_id')\n def _get_default_product_name(self):\n self.ensure_one()\n if self._context.get('categ_name') or self._context.get('default_categ_name'):\n cat_name = self._context.get('categ_name')\n cat_id = self.env['product.category'].search([('name', '=ilike', cat_name)], limit=1).id\n ra = ''\n \n if cat_name == 'Fabric':\n if not ra:\n rand = str(random.randint(10000000,99999999))\n ra += rand\n self.name = ra\n self.type = 'product'\n self.categ_id = cat_id \n self.sale_ok = False\n self.purchase_ok = True\n\n uom_line = self.env['product.uom'].search([('name', '=', 'Yards')])\n if uom_line:\n self.uom_id = uom_line.id\n else:\n self.uom_id = 1 \n elif cat_name == 'Trims' or cat_name == 'PandP':\n self.name = ''\n self.type = 'product'\n self.categ_id = cat_id \n self.sale_ok = False\n self.purchase_ok = True\n elif cat_name == 'Sample':\n self.sale_ok = True\n self.purchase_ok = False \n self.type = 'product' \n self.categ_id = cat_id \n else:\n self.name = ''","sub_path":"sample_tracking_and_costing/models/product_product.py","file_name":"product_product.py","file_ext":"py","file_size_in_byte":8749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"228964072","text":"import gzip\nimport ujson as json\n\nimport easytime\n\nfrom common import Text, Sample, Edit, normalize_infobox\n\n\ndef parse_date_string(s):\n return easytime.strptime(s, '%a %b %d %H:%M:%S +0000 %Y', 'utc')\n\n\ndef parse_matched_line(line):\n (label, rel, arg1, arg2, tweet_date, edit_date,\n time_since_tweet, tweet_str, edit_str) = line.strip().split('\\t')\n edit_json = json.loads(edit_str)\n tweet_json = json.loads(tweet_str)\n\n infobox = normalize_infobox(edit_json['infobox_name'])\n\n edit = Edit(id=edit_json['id'], timestamp=edit_json['timestamp'],\n relation=infobox + '/' + rel, args=(arg1, arg2))\n\n sid = tweet_json['sid']\n timestamp = parse_date_string(tweet_json['created_at'])\n\n words = tweet_json['words'].split(' ')\n pos = tweet_json['pos'].split(' ')\n ner = [s[0] for s in tweet_json['neTags'].split(' ')]\n text = Text(words=words, pos=pos, ner=ner)\n\n return Sample(id=sid, timestamp=timestamp, text=text,\n args=(arg1, arg2), edits=[edit], y=-1, features=None)\n\n\ndef read_matched(path):\n with open(path) as input_file:\n for line in input_file:\n yield parse_matched_line(line)\n\n\ndef parse_unmatched_line(line):\n tweet_json = json.loads(line)\n\n sid = tweet_json['sid']\n arg1, arg2 = tweet_json['arg1'], tweet_json['arg2']\n timestamp = tweet_json['created_at']\n\n words = tweet_json['words'].split(' ')\n pos = tweet_json['pos'].split(' ')\n ner = tweet_json['neTags'].split(' ')\n text = Text(words=words, pos=pos, ner=ner)\n\n return Sample(id=sid, timestamp=timestamp, text=text,\n args=(arg1, arg2), edits=[], y=-1, features=None)\n\n\ndef read_unmatched(path):\n with gzip.open(path) as input_file:\n for line in input_file:\n yield parse_unmatched_line(line)\n","sub_path":"cleanslate/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"127809599","text":"import numpy as np\nimport torch\nfrom torch import nn\nfrom typing import List\n\nimport spconv\nfrom pointnet2.pointnet2_utils import furthest_point_sample, gather_operation\n\nfrom .target_assigner import TargetAssigner\n\n\nclass Preprocessor(nn.Module):\n\n def __init__(self, cfg):\n super(Preprocessor, self).__init__()\n self.voxel_generator = self.build_voxel_generator(cfg)\n self.cfg = cfg\n\n def build_voxel_generator(self, cfg):\n \"\"\"Voxel-grid is reversed XYZ -> ZYX and padded in Z-axis.\"\"\"\n voxel_generator = spconv.utils.VoxelGenerator(\n voxel_size=cfg.VOXEL_SIZE,\n point_cloud_range=cfg.GRID_BOUNDS,\n max_voxels=cfg.MAX_VOXELS,\n max_num_points=cfg.MAX_OCCUPANCY,\n )\n self.grid_shape = np.r_[voxel_generator.grid_size[::-1]] + [1, 0, 0]\n return voxel_generator\n\n def generate_batch_voxels(self, points):\n \"\"\"Voxelize points and tag with batch index.\"\"\"\n features, coordinates, occupancy = [], [], []\n for i, p in enumerate(points):\n f, c, o = self.voxel_generator.generate(p)\n c = np.pad(c, ((0, 0), (1, 0)), constant_values=i)\n features += [f]; coordinates += [c]; occupancy += [o]\n return map(np.concatenate, (features, coordinates, occupancy))\n\n def pad_for_batch(self, points: List) -> np.ndarray:\n \"\"\"\n Pad with subsampled points to form dense minibatch.\n :return np.ndarray of shape (B, N, C)\n \"\"\"\n num_points = np.r_[[p.shape[0] for p in points]]\n pad = num_points.max() - num_points\n points_batch = []\n for points_i, pad_i in zip(points, pad):\n idx = np.random.choice(points_i.shape[0], pad_i)\n points_batch += [np.concatenate((points_i, points_i[idx]))]\n points = np.stack(points_batch, axis=0)\n return points\n\n def from_numpy(self, x):\n \"\"\"Make cuda tensor.\"\"\"\n return torch.from_numpy(x).cuda()\n\n def voxelize(self, points):\n \"\"\"\n Compute sparse voxel grid.\n :points_in list of np.ndarrays of shape (Np, 4)\n :points_out FloatTensor of shape (Np, 4)\n :features FloatTensor of shape (Nv, 1)\n :coordinates IntTensor of shape (Nv, 4)\n \"\"\"\n features, coordinates, occupancy = self.generate_batch_voxels(points)\n points = self.pad_for_batch(points)\n keys = ['points', 'features', 'coordinates', 'occupancy']\n vals = map(self.from_numpy, (points, features, coordinates, occupancy))\n input_dict = dict(zip(keys, vals))\n input_dict['batch_size'] = len(points)\n return input_dict\n\n def sample_keypoints(self, points):\n \"\"\"\n Sample keypoints from raw pointcloud.\n - fps expects points shape (B, N, 3)\n - fps returns indices shape (B, K)\n - gather expects features shape (B, C, N)\n \"\"\"\n points = points[..., :3].contiguous()\n indices = furthest_point_sample(points, self.cfg.NUM_KEYPOINTS)\n keypoints = gather_operation(points.transpose(1, 2).contiguous(), indices)\n keypoints = keypoints.transpose(1, 2).contiguous()\n return keypoints\n\n def forward(self, input_dict):\n input_dict.update(self.voxelize(input_dict['points']))\n input_dict['keypoints'] = self.sample_keypoints(input_dict['points'])\n return input_dict\n\n\nclass TrainPreprocessor(Preprocessor):\n\n def __init__(self, cfg):\n super(TrainPreprocessor, self).__init__(cfg)\n self.target_assigner = TargetAssigner(cfg)\n\n def forward(self, input_dict):\n input_dict.update(self.voxelize(input_dict['points']))\n input_dict['keypoints'] = self.sample_keypoints(input_dict['points'])\n input_dict = self.target_assigner(input_dict)\n return input_dict\n","sub_path":"pvrcnn/core/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"645883018","text":"\nclass AppReader:\n '''\n This app opens two text files as lists, then combines them together into a dictionary. The first file is a list of car makes, and the second file is a list of car models. the resulting dictionary has the car makes as keys, and the car models as items in the car make value list.\n\n methods: open_makes, open_models, make_dictionary, print_dictionary.\n '''\n\n def __init__(self):\n self.dictionary = {}\n\n def open_makes(self):\n '''\n opens the 'models.txt' file and prints each line. currently without the model initial and equals sign and without the newline, but that's likely to change.\n Arguments: none\n '''\n makes_list = []\n with open(\"makes.txt\", \"r\") as makes:\n for make in makes:\n makes_list.append(make[:-1])\n return makes_list\n\n def open_models(self):\n '''\n opens the 'models.txt' file and prints each line. currently without the model initial and equals sign and without the newline, but that's likely to change.\n Arguments: none\n '''\n models_list = []\n with open(\"models.txt\", \"r\") as models:\n for model in models:\n models_list.append(model[:-1])\n return models_list\n\n def make_dictionary(self):\n '''\n loops through the list of makes in the makes.txt file and creates a dictionary with each make.txt item as a key and an empty list as a value.\n loops through the list of models in the models.txt file and adds matching models as list items for the corresponting make.\n Arguments: None.\n '''\n makes = self.open_makes()\n models = self.open_models()\n\n for make in makes:\n # create a dictionary entry with an empty list for a value, for each make.\n self.dictionary[make] = []\n # then loop through the models list and add any models of the correct make to the list.\n for model in models:\n if model[0] == make[0]:\n # note here I'm taking off the '(first letter)=' from the model list items.\n self.dictionary[make].append(model[2:])\n\n def print_dictionary(self):\n '''\n prints the final dictionary in format. Run only after make_dictionary.\n arguments: none\n '''\n for (key, value) in self.dictionary.items():\n print(key.upper() + \": \" + \", \".join(value))\n\nif __name__ == '__main__':\n app = AppReader()\n app.make_dictionary()\n app.print_dictionary()\n","sub_path":"the_app.py","file_name":"the_app.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"489466808","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 17 15:32:09 2019\n\n@author: George\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io import wavfile\n\nfs, snd = wavfile.read(r\"C:\\Users\\George\\Dropbox\\code\\JavaScript_HTML_CSS\\soundTest\\audio\\bells_chimes\\gong.wav\")\n\nsnd = snd / (2.**15)\ns1 = snd[:,0]\n\nplt.figure(figsize=(20,8))\nplt.style.use(\"seaborn\")\n\ntime = np.arange(0, s1.shape[0], 1)\ntime = (time / fs) * 1000\n\nplt.plot(time, s1, color='b')\n\nplt.ylabel('Amplitude', fontsize=16)\nplt.xlabel('Time (ms)', fontsize=16)\nplt.xticks(fontsize=14)\nplt.yticks(fontsize=14)\n\nplt.show()","sub_path":"fourierTransform/fourierTransform 2.py","file_name":"fourierTransform 2.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"590501153","text":"#\r\n# === Introduction ===\r\n#\r\n# In this problem, you will build a planner that helps a robot\r\n# find the best path through a warehouse filled with boxes\r\n# that it has to pick up and deliver to a dropzone.\r\n# \r\n# Your file must be called `partA.py` and must have a class\r\n# called `DeliveryPlanner`.\r\n# This class must have an `__init__` function that takes three \r\n# arguments: `self`, `warehouse`, and `todo`.\r\n# The class must also have a function called `plan_delivery` that \r\n# takes a single argument, `self`.\r\n#\r\n# === Input Specifications ===\r\n# \r\n# `warehouse` will be a list of m strings, each with n characters,\r\n# corresponding to the layout of the warehouse. The warehouse is an\r\n# m x n grid. warehouse[i][j] corresponds to the spot in the ith row\r\n# and jth column of the warehouse, where the 0th row is the northern\r\n# end of the warehouse and the 0th column is the western end.\r\n#\r\n# The characters in each string will be one of the following:\r\n#\r\n# '.' (period) : traversable space. The robot may enter from any adjacent space.\r\n# '#' (hash) : a wall. The robot cannot enter this space.\r\n# '@' (dropzone): the starting point for the robot and the space where all boxes must be delivered.\r\n# The dropzone may be traversed like a '.' space.\r\n# [0-9a-zA-Z] (any alphanumeric character) : a box. At most one of each alphanumeric character \r\n# will be present in the warehouse (meaning there will be at most 62 boxes). A box may not\r\n# be traversed, but if the robot is adjacent to the box, the robot can pick up the box.\r\n# Once the box has been removed, the space functions as a '.' space.\r\n# \r\n# For example, \r\n# warehouse = ['1#2',\r\n# '.#.',\r\n# '..@']\r\n# is a 3x3 warehouse.\r\n# - The dropzone is at the warehouse cell in row 2, column 2.\r\n# - Box '1' is located in the warehouse cell in row 0, column 0.\r\n# - Box '2' is located in the warehouse cell in row 0, column 2.\r\n# - There are walls in the warehouse cells in row 0, column 1 and row 1, column 1.\r\n# - The remaining five warehouse cells contain empty space.\r\n#\r\n# The argument `todo` is a list of alphanumeric characters giving the order in which the \r\n# boxes must be delivered to the dropzone. For example, if \r\n# todo = ['1','2']\r\n# is given with the above example `warehouse`, then the robot must first deliver box '1'\r\n# to the dropzone, and then the robot must deliver box '2' to the dropzone.\r\n#\r\n# === Rules for Movement ===\r\n#\r\n# - Two spaces are considered adjacent if they share an edge or a corner.\r\n# - The robot may move horizontally or vertically at a cost of 2 per move.\r\n# - The robot may move diagonally at a cost of 3 per move.\r\n# - The robot may not move outside the warehouse.\r\n# - The warehouse does not \"wrap\" around.\r\n# - As described earlier, the robot may pick up a box that is in an adjacent square.\r\n# - The cost to pick up a box is 4, regardless of the direction the box is relative to the robot.\r\n# - While holding a box, the robot may not pick up another box.\r\n# - The robot may put a box down on an adjacent empty space ('.') or the dropzone ('@') at a cost\r\n# of 1 (regardless of the direction in which the robot puts down the box).\r\n# - If a box is placed on the '@' space, it is considered delivered and is removed from the ware-\r\n# house.\r\n# - The warehouse will be arranged so that it is always possible for the robot to move to the \r\n# next box on the todo list without having to rearrange any other boxes.\r\n#\r\n# An illegal move will incur a cost of 100, and the robot will not move (the standard costs for a \r\n# move will not be additionally incurred). Illegal moves include:\r\n# - attempting to move to a nonadjacent, nonexistent, or occupied space\r\n# - attempting to pick up a nonadjacent or nonexistent box\r\n# - attempting to pick up a box while holding one already\r\n# - attempting to put down a box on a nonadjacent, nonexistent, or occupied space\r\n# - attempting to put down a box while not holding one\r\n#\r\n# === Output Specifications ===\r\n#\r\n# `plan_delivery` should return a LIST of moves that minimizes the total cost of completing\r\n# the task successfully.\r\n# Each move should be a string formatted as follows:\r\n#\r\n# 'move {i} {j}', where '{i}' is replaced by the row-coordinate of the space the robot moves\r\n# to and '{j}' is replaced by the column-coordinate of the space the robot moves to\r\n# \r\n# 'lift {x}', where '{x}' is replaced by the alphanumeric character of the box being picked up\r\n#\r\n# 'down {i} {j}', where '{i}' is replaced by the row-coordinate of the space the robot puts \r\n# the box, and '{j}' is replaced by the column-coordinate of the space the robot puts the box\r\n#\r\n# For example, for the values of `warehouse` and `todo` given previously (reproduced below):\r\n# warehouse = ['1#2',\r\n# '.#.',\r\n# '..@']\r\n# todo = ['1','2']\r\n# `plan_delivery` might return the following:\r\n# ['move 2 1',\r\n# 'move 1 0',\r\n# 'lift 1',\r\n# 'move 2 1',\r\n# 'down 2 2',\r\n# 'move 1 2',\r\n# 'lift 2',\r\n# 'down 2 2']\r\n#\r\n# === Grading ===\r\n# \r\n# - Your planner will be graded against a set of test cases, each equally weighted.\r\n# - If your planner returns a list of moves of total cost that is K times the minimum cost of \r\n# successfully completing the task, you will receive 1/K of the credit for that test case.\r\n# - Otherwise, you will receive no credit for that test case. This could happen for one of several \r\n# reasons including (but not necessarily limited to):\r\n# - plan_delivery's moves do not deliver the boxes in the correct order.\r\n# - plan_delivery's output is not a list of strings in the prescribed format.\r\n# - plan_delivery does not return an output within the prescribed time limit.\r\n# - Your code raises an exception.\r\n#\r\n# === Additional Info ===\r\n# \r\n# - You may add additional classes and functions as needed provided they are all in the file `partA.py`.\r\n# - Upload partA.py to Project 2 on T-Square in the Assignments section. Do not put it into an \r\n# archive with other files.\r\n# - Ask any questions about the directions or specifications on Piazza.\r\n#\r\n\r\nclass DeliveryPlanner:\r\n\r\n def __init__(self, warehouse, todo):\r\n self.warehouse = warehouse\r\n self.todo = todo\r\n\r\n def plan_delivery(self):\r\n grid=[[]]\r\n m = len(self.warehouse)\r\n n = len(self.warehouse[0])\r\n grid=[[ ' ' for row in range(n)] for col in range(m)]\r\n moves=[]\r\n pick_up=[]\r\n loc=[]\r\n \r\n for i in range(m):\r\n for j in range(n):\r\n \r\n grid[i][j] = self.warehouse[i][j]\r\n \r\n for k in range(len(self.todo)):\r\n \r\n for i in range(m):\r\n for j in range(n):\r\n if grid[i][j] == self.todo[k]:\r\n \r\n pick_up.append([i,j])\r\n for i in range(m):\r\n for j in range(n):\r\n \r\n if grid[i][j] == '@':\r\n loc=[i,j]\r\n \r\n \r\n cost = [2,2,2,2,3,3,3,3]\r\n cost_load = 4\r\n cost_unload = 2\r\n delta = [[-1, 0 ], # go up\r\n [ 0, -1], # go left\r\n [ 1, 0 ], # go down\r\n [ 0, 1 ], # go right\r\n [-1, 1 ], # go up right (diagnol)\r\n [ 1, 1 ], # go down right (diagnol)\r\n [-1, -1], # go up left (diagnol)\r\n [ 1, -1]] # go down left(diagnol)\r\n\r\n delta_name = ['^', '<', 'v', '>', '^>', 'v>', '^<', 'v<']\r\n final_cost=0.0\r\n count=0\r\n m5=[]\r\n \r\n for n in range(len(pick_up)):\r\n cycle =0\r\n last_goal=[]\r\n if n==0:\r\n init = loc\r\n while cycle < 2 or count > 0:\r\n if cycle==0:\r\n \r\n goal = pick_up[n]\r\n \r\n \r\n p,x4,y4,tc,c1,m1 = (optimum_policy(grid,goal,cost,init,loc,count,delta,delta_name,cost_load,cost_unload))\r\n temp=[x4,y4]\r\n m5.append(m1)\r\n last_goal = goal\r\n goal = loc\r\n init=temp\r\n count = c1\r\n if goal == init:\r\n goal = last_goal\r\n \r\n \r\n final_cost = final_cost + tc\r\n \r\n \r\n cycle = cycle + 1\r\n for i in m5:\r\n for j in i:\r\n moves.append(j)\r\n return moves\r\ndef optimum_policy(grid,goal,cost,init,loc,count,delta,delta_name,cost_load,cost_unload):\r\n \r\n value = [[99 for row in range(len(grid[0]))] for col in range(len(grid))]\r\n policy = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]\r\n \r\n change = True\r\n moves=[]\r\n \r\n \r\n while change:\r\n change = False\r\n\r\n for x in range(len(grid)):\r\n \r\n for y in range(len(grid[0])):\r\n \r\n if goal[0] == x and goal[1] == y:\r\n \r\n if value[x][y] > 0:\r\n value[x][y] = 0\r\n policy[x][y]= '*'\r\n change = True\r\n \r\n elif grid[x][y] == '.' or grid[x][y] == '@':\r\n for a in range(len(delta)):\r\n x2 = x + delta[a][0]\r\n y2 = y + delta[a][1]\r\n \r\n if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]) and grid[x2][y2] != '#':\r\n \r\n \r\n if x2 == goal[0] and y2 == goal[1]:\r\n v2 = value[x2][y2] + cost_load\r\n if v2 < value[x][y]:\r\n change = True\r\n value[x][y] = v2\r\n \r\n policy[x][y]=delta_name[a]\r\n elif grid[x2][y2] == '.' or grid[x2][y2] == '@':\r\n v2 = value[x2][y2] + cost[a]\r\n \r\n \r\n if v2 < value[x][y]:\r\n change = True\r\n value[x][y] = v2\r\n \r\n policy[x][y]=delta_name[a]\r\n\r\n\r\n \r\n x = init[0]\r\n y = init[1]\r\n \r\n x3=0\r\n y3=0\r\n total_cost=0\r\n \r\n while x != goal[0] or y!=goal[1]:\r\n \r\n for c in range(len(delta_name)):\r\n \r\n if policy[x][y] == delta_name[c]:\r\n \r\n x2 = x + delta[c][0]\r\n y2 = y + delta[c][1]\r\n \r\n if x2==loc[0] and y2==loc[1] and x2==goal[0] and y2==goal[1]:\r\n moves.append('down ' + str(x2) +' ' +str(y2))\r\n total_cost = total_cost + cost_unload\r\n x3=x\r\n y3=y\r\n count = count -1\r\n elif x2 ==goal[0] and y2==goal[1] and count==0.0:\r\n moves.append('lift ' + str(grid[x2][y2]))\r\n grid[x2][y2] = '.'\r\n x3=x\r\n y3=y\r\n count = count + 1\r\n total_cost = total_cost + cost_load\r\n else:\r\n moves.append('move ' + str(x2) +' ' +str(y2))\r\n total_cost = total_cost + cost[c]\r\n x3=x2\r\n y3=y2\r\n x = x2\r\n y = y2\r\n \r\n \r\n \r\n return policy,x3,y3,total_cost,count,moves\r\n","sub_path":"Project2/partA.py","file_name":"partA.py","file_ext":"py","file_size_in_byte":11834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"483671941","text":"# Як змінювалась ціна на яблука? (графік)\nimport plotly\nimport plotly.graph_objs as go\nlist = []\n\nfrom Dat import dataset\nlist = []\nfor client in dataset:\n for product in dataset[client]:\n if product == \"apple\":\n for i in range(len(dataset[client][product][\"date\"])):\n list.append((product,dataset[client][product][\"date\"][i],dataset[client][product][\"price\"][i]))\n\nlist1 = [tup[1] for tup in list]\nlist2 = [tup[2] for tup in list]\n\nprint(list1)\nprint(list2)\n\ndicti =dict()\n\nfor i in range(len(list1)):\n dicti[list1[i]] = list2[i]\nprint(dicti)\nlist1 = [key for key in dicti]\nlist1.sort()\nlist2 = []\nfor date in list1:\n list2.append(dicti[date])\nprint(\"\\n\\n\\n\\n\\n\")\nprint(list1)\nprint(list2)\ndiagram = go.Bar(x = list1,y = list2)\nplotly.offline.plot([diagram],filename = \"diag.html\")\n\n\n","sub_path":"km-83/Larionov_Alexander/workshop5/source/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"505819361","text":"import json\nfrom json.decoder import JSONDecodeError\n\nfrom django.db.models import Model\nfrom django.http import HttpResponse, JsonResponse, HttpResponseBadRequest, HttpResponseNotAllowed\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom hero.models import Hero\n\n\ndef index(request):\n return HttpResponse('Hello, world!')\n\n\n@csrf_exempt\ndef hero_list(request):\n if request.method == 'GET':\n hero_all_list = [hero for hero in Hero.objects.all().values()]\n return JsonResponse(hero_all_list, safe=False)\n if request.method == 'POST':\n try:\n body = request.body.decode()\n hero_name = json.loads(body)['name']\n except (KeyError, JSONDecodeError) as e:\n return HttpResponseBadRequest()\n hero = Hero(name=hero_name)\n hero.save()\n response_dict = {'id': hero.id, 'name': hero.name, 'age': hero.age}\n return JsonResponse(response_dict, status=201)\n else:\n return HttpResponseNotAllowed(['GET', 'POST'])\n\n\n@csrf_exempt\ndef hero_info(request, hero_id=0):\n if request.method == 'GET':\n try:\n hero_get = Hero.objects.get(id=hero_id)\n except Model.DoesNotExist:\n return HttpResponseBadRequest()\n response_dict = {'id': hero_get.id, 'name': hero_get.name, 'age': hero_get.age}\n return JsonResponse(response_dict, status=200)\n if request.method == 'PUT':\n try:\n hero_target = Hero.objects.get(id=hero_id)\n except Model.DoesNotExist:\n return HttpResponseBadRequest()\n\n try:\n body = request.body.decode()\n hero_name = json.loads(body)['name']\n hero_age = json.loads(body)['age']\n except (KeyError, JSONDecodeError) as e:\n return HttpResponseBadRequest()\n\n hero_target.name = hero_name\n hero_target.age = hero_age\n hero_target.save()\n response_dict = {'id': hero_target.id, 'name': hero_target.name, 'age': hero_target.age}\n return JsonResponse(response_dict, status=200)\n else:\n return HttpResponseNotAllowed(['GET', 'PUT'])\n\n\ndef hero_name(request, hero_name=\"\"):\n return HttpResponse('Your name is ' + hero_name + '!')\n\n\ndef hero_id(request, hero_id=0):\n return HttpResponse('Your id is ' + str(hero_id) + '!')\n","sub_path":"toh/hero/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"400514777","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport collections\n\nimport numpy as np\nimport json\nfrom flags import parse_args\n\n\ndef read_data(filename):\n with open(filename, encoding=\"utf-8\") as f:\n data = f.read()\n data = list(data)\n return data\n\n\ndef index_data(sentences, dictionary):\n shape = sentences.shape\n sentences = sentences.reshape([-1])\n index = np.zeros_like(sentences, dtype=np.int32)\n for i in range(len(sentences)):\n try:\n index[i] = dictionary[sentences[i]]\n except KeyError:\n index[i] = dictionary['UNK']\n\n return index.reshape(shape)\n\n\nFLAGS, unparsed = parse_args()\nvocabulary = read_data(FLAGS.text)\nnum_classes = len(vocabulary)\nvocabulary_size = 5000\ndata_index = 0\nskip_window = 1 # How many words to consider left and right.\nnum_skips = 2 # How many times to reuse an input to generate a label.\n\ndef build_dataset(words, n_words):\n \"\"\"Process raw inputs into a dataset.\"\"\"\n count = [['UNK', -1]]\n count.extend(collections.Counter(words).most_common(n_words - 1))\n dictionary = dict()\n for word, _ in count:\n dictionary[word] = len(dictionary)\n data = list()\n unk_count = 0\n for word in words:\n index = dictionary.get(word, 0)\n if index == 0: # dictionary['UNK']\n unk_count += 1\n data.append(index)\n count[0][1] = unk_count\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n\n # with open('dictionary.json', 'w') as file_object:\n # json.dump(dictionary, file_object)\n # with open('reverse_dictionary.json', 'w') as file_object:\n # json.dump(reversed_dictionary, file_object)\n\n return data, count, dictionary, reversed_dictionary\n\n\ndata, count, dictionary, reverse_dictionary = build_dataset(vocabulary,\n vocabulary_size)\n\nraw_x = data\nraw_y = data[1:]\nraw_y.append(num_classes-1)\n\ndel vocabulary # Hint to reduce memory.\n\ndef get_train_data(vocabulary, batch_size, num_steps):\n ##################\n # My Code here\n ##################\n\n # print('Most common words (+UNK)', count[:5])\n # print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])\n\n # partition raw data into batches and stak them vertically in a data matrix\n batch_partition_length = len(vocabulary) // batch_size\n data_x = np.zeros([batch_size, batch_partition_length], dtype=np.int32)\n data_y = np.zeros([batch_size, batch_partition_length], dtype=np.int32)\n # do partition\n for i in range(batch_size):\n data_x[i] = raw_x[batch_partition_length * i: batch_partition_length * (i + 1)]\n data_y[i] = raw_y[batch_partition_length * i: batch_partition_length * (i + 1)]\n # do epoch\n epoch_size = batch_partition_length // num_steps\n\n for i in range(epoch_size):\n x = data_x[:, i * num_steps:(i + 1) * num_steps]\n y = data_y[:, i * num_steps:(i + 1) * num_steps]\n yield (x, y)\n\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"16961948","text":"from typing import Tuple\nimport numpy as np\nimport os\nimport re\nimport sqlparse\nfrom s3fs import S3FileSystem\nimport inspect\nimport boto3\nfrom botocore.credentials import InstanceMetadataProvider, InstanceMetadataFetcher\nimport awswrangler as wr\n\n# pydbtools will create a new a new S3 object (then delete it post read). In the first call read\n# the cache is empty but then filled. If pydbtools is called again the cache is referenced and\n# you get an NoFileError.\n# Setting cachable to false fixes this. cachable is class object from fsspec.AbstractFileSystem\n# which S3FileSystem inherits.\nS3FileSystem.cachable = False\n\n# Get role specific path for athena output\nbucket = \"mojap-athena-query-dump\"\n\ntemp_database_name_prefix = \"mojap_de_temp_\"\n\n\ndef get_default_args(func):\n signature = inspect.signature(func)\n return {\n k: v.default\n for k, v in signature.parameters.items()\n if v.default is not inspect.Parameter.empty\n }\n\n\ndef check_temp_query(sql: str):\n \"\"\"\n Checks if a query to a temporary table\n has had __temp__ wrapped in quote marks.\n\n Args:\n sql (str): an SQL query\n\n Raises:\n ValueError\n \"\"\"\n if re.findall(r'[\"|\\']__temp__[\"|\\']\\.', sql.lower()):\n raise ValueError(\n \"When querying a temporary database, __temp__ should not be wrapped in quotes\"\n )\n\n\ndef clean_query(sql: str) -> str:\n \"\"\"\n removes trailing whitespace, newlines and final\n semicolon from sql for use with\n sqlparse package\n\n Args:\n sql (str): The raw SQL query\n\n Returns:\n str: The cleaned SQL query\n \"\"\"\n return \" \".join(sql.splitlines()).strip().rstrip(\";\")\n\n\ndef replace_temp_database_name_reference(sql: str, database_name: str) -> str:\n \"\"\"\n Replaces references to the user's temp database __temp__\n with the database_name string provided.\n\n Args:\n sql (str): The raw SQL query as a string\n database_name (str): The database name to replace __temp__\n\n Returns:\n str: The new SQL query which is sent to Athena\n \"\"\"\n # check query is valid and clean\n parsed = sqlparse.parse(clean_query(sql))\n new_query = []\n for query in parsed:\n check_temp_query(str(query))\n for word in str(query).strip().split(\" \"):\n if \"__temp__.\" in word.lower():\n word = word.lower().replace(\"__temp__.\", f\"{database_name}.\")\n new_query.append(word)\n if \";\" not in new_query[-1]:\n last_entry = new_query[-1] + \";\"\n else:\n last_entry = new_query[-1]\n del new_query[-1]\n new_query.append(last_entry)\n return \" \".join(new_query)\n\n\ndef get_user_id_and_table_dir(\n boto3_session=None, force_ec2: bool = False, region_name: str = \"eu-west-1\"\n) -> Tuple[str, str]:\n\n if boto3_session is None:\n boto3_session = get_boto_session(force_ec2=force_ec2, region_name=region_name)\n\n sts_client = boto3_session.client(\"sts\")\n sts_resp = sts_client.get_caller_identity()\n out_path = os.path.join(\"s3://\", bucket, sts_resp[\"UserId\"])\n if out_path[-1] != \"/\":\n out_path += \"/\"\n\n return (sts_resp[\"UserId\"], out_path)\n\n\ndef get_database_name_from_userid(user_id: str) -> str:\n unique_db_name = user_id.split(\":\")[-1].split(\"-\", 1)[-1].replace(\"-\", \"_\")\n unique_db_name = temp_database_name_prefix + unique_db_name\n return unique_db_name\n\n\ndef get_boto_session(\n force_ec2: bool = False, region_name: str = \"eu-west-1\",\n):\n\n kwargs = {\"region_name\": region_name}\n if force_ec2:\n provider = InstanceMetadataProvider(\n iam_role_fetcher=InstanceMetadataFetcher(timeout=1000, num_attempts=2)\n )\n creds = provider.load().get_frozen_credentials()\n kwargs[\"aws_access_key_id\"] = creds.access_key\n kwargs[\"aws_secret_access_key\"] = creds.secret_key\n kwargs[\"aws_session_token\"] = creds.token\n\n return boto3.Session(**kwargs)\n\n\ndef get_boto_client(\n client_name: str,\n boto3_session=None,\n force_ec2: bool = False,\n region_name: str = \"eu-west-1\",\n):\n\n if boto3_session is None:\n boto3_session = get_boto_session(force_ec2=force_ec2, region_name=region_name)\n\n return boto3_session.client(client_name)\n\n\ndef get_file(s3_path: str, check_exists: bool = True):\n \"\"\"\n Returns an file using s3fs without caching objects (workaround for issue #10).\n\n s3_path: path to file in S3 e.g. s3://bucket/object/path.csv\n check_exists: If True (default) will check for s3 file existence before returning file.\n \"\"\"\n b, k = s3_path.replace(\"s3://\", \"\").split(\"/\", 1)\n if check_exists:\n if not wr.s3.does_object_exist(s3_path):\n raise FileNotFoundError(f\"File not found in S3. full path: {s3_path}\")\n fs = S3FileSystem()\n f = fs.open(os.path.join(b, k), \"rb\")\n\n return f\n\n\n# Some notes on the below:\n# - int and bigint: pandas doesn't allow nulls in int columns so have to use float\n# - date and datetime: pandas doesn't really have a datetime type it expects datetimes use parse_dates\n# - string is when athena output is just a text file e.g. SHOW COLUMNS FROM db. Setting as a character\n_athena_meta_conversions = {\n \"char\": {\"etl_manager\": \"character\", \"pandas\": \"object\"},\n \"varchar\": {\"etl_manager\": \"character\", \"pandas\": \"object\"},\n \"integer\": {\"etl_manager\": \"int\", \"pandas\": \"float\"},\n \"bigint\": {\"etl_manager\": \"long\", \"pandas\": \"float\"},\n \"date\": {\"etl_manager\": \"date\", \"pandas\": \"object\"},\n \"timestamp\": {\"etl_manager\": \"datetime\", \"pandas\": \"object\"},\n \"boolean\": {\"etl_manager\": \"boolean\", \"pandas\": \"bool\"},\n \"float\": {\"etl_manager\": \"float\", \"pandas\": \"float\"},\n \"double\": {\"etl_manager\": \"double\", \"pandas\": \"float\"},\n \"string\": {\"etl_manager\": \"character\", \"pandas\": \"object\"},\n \"decimal\": {\"etl_manager\": \"decimal\", \"pandas\": \"float\"},\n}\n\n\n# Two functions below stolen and altered from here:\n# https://github.com/moj-analytical-services/dataengineeringutils/blob/metadata_conformance/dataengineeringutils/pd_metadata_conformance.py\ndef _pd_dtype_dict_from_metadata(athena_meta: list):\n \"\"\"\n Convert the athena table metadata to the dtype dict that needs to be\n passed to the dtype argument of pd.read_csv. Also return list of columns that pandas needs to convert to dates/datetimes\n \"\"\"\n # see https://stackoverflow.com/questions/34881079/pandas-distinction-between-str-and-object-types\n\n parse_dates = []\n dtype = {}\n\n for c in athena_meta:\n colname = c[\"name\"]\n coltype = _athena_meta_conversions[c[\"type\"]][\"pandas\"]\n dtype[colname] = np.typeDict[coltype]\n if c[\"type\"] in [\"date\", \"timestamp\"]:\n parse_dates.append(colname)\n\n return (dtype, parse_dates)\n","sub_path":"pydbtools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"631876591","text":"# imports\nimport django\nimport hashlib\nfrom inspect import isfunction, signature\nimport json\nfrom lxml import etree, isoschematron\nimport os\nimport shutil\nimport sys\nfrom types import ModuleType\n\n# import Row from pyspark\nfrom pyspark.sql import Row\nfrom pyspark.sql.types import StringType, IntegerType\nfrom pyspark.sql.functions import udf\n\n# init django settings file to retrieve settings\nos.environ['DJANGO_SETTINGS_MODULE'] = 'combine.settings'\nsys.path.append('/opt/combine')\ndjango.setup()\nfrom django.conf import settings\nfrom django.db import connection\n\n# import select models from Core\nfrom core.models import Job, ValidationScenario\n\n\n\n####################################################################\n# Django DB Connection \t\t\t\t\t\t\t\t\t\t\t #\n####################################################################\ndef refresh_django_db_connection():\n\t\n\t'''\n\tFunction to refresh connection to Django DB.\n\t\n\tBehavior with python files uploaded to Spark context via Livy is atypical when\n\tit comes to opening/closing connections with MySQL. Specifically, if jobs are run farther \n\tapart than MySQL's `wait_timeout` setting, it will result in the error, (2006, 'MySQL server has gone away').\n\n\tRunning this function before jobs ensures that the connection is fresh between these python files\n\toperating in the Livy context, and Django's DB connection to MySQL.\n\n\tArgs:\n\t\tNone\n\n\tReturns:\n\t\tNone\n\t'''\n\n\tconnection.close()\n\tconnection.connect()\n\n\n\n####################################################################\n# Models for UDFs\t\t\t\t\t\t\t\t\t\t\t\t #\n####################################################################\n\nclass PythonUDFRecord(object):\n\n\t'''\n\tSimple class to provide an object with parsed metadata for user defined functions\n\t'''\n\n\tdef __init__(self, row):\n\n\t\t# row\n\t\tself._row = row\n\n\t\t# get combine id\n\t\tself.id = row.id\n\n\t\t# get record id\n\t\tself.record_id = row.record_id\n\n\t\t# document string\n\t\tself.document = row.document\n\n\t\t# parse XML string, save\n\t\tself.xml = etree.fromstring(self.document)\n\n\t\t# get namespace map, popping None values\n\t\t_nsmap = self.xml.nsmap.copy()\n\t\ttry:\n\t\t\t_nsmap.pop(None)\n\t\texcept:\n\t\t\tpass\n\t\tself.nsmap = _nsmap\n\n\n####################################################################\n# Record Validation\t\t\t\t\t\t\t\t\t\t\t\t #\n####################################################################\n\nclass ValidationScenarioSpark(object):\n\n\t'''\n\tClass to organize methods and attributes used for running validation scenarios\n\t'''\n\n\tdef __init__(self, spark=None, job=None, records_df=None, validation_scenarios=None):\n\n\t\t'''\n\t\tArgs:\n\t\t\tspark (pyspark.sql.session.SparkSession): spark instance from static job methods\n\t\t\tjob (core.models.Job): Job instance\t\t\n\t\t\trecords_df (pyspark.sql.DataFrame): records as pyspark DataFrame\n\t\t\tvalidation_scenarios (list): list of ValidationScenario job ids as integers\n\t\t'''\n\n\t\tself.spark = spark\n\t\tself.job = job\n\t\tself.records_df = records_df\n\t\tself.validation_scenarios = validation_scenarios\n\n\n\tdef run_record_validation_scenarios(self):\n\n\t\t'''\n\t\tFunction to run validation scenarios\n\t\tResults are written to RecordValidation table, one result, per record, per failed validation test.\n\n\t\tValidation tests may be of type:\n\t\t\t- 'sch': Schematron based validation, performed with lxml etree\n\t\t\t- 'python': custom python code snippets\n\n\t\tArgs:\n\t\t\tNone\n\n\t\tReturns:\n\t\t\tNone\n\t\t\t\t- writes validation fails to RecordValidation table\n\t\t'''\n\n\t\t# refresh Django DB Connection\n\t\trefresh_django_db_connection()\n\n\t\t# loop through validation scenarios and fire validation type specific method\n\t\tfor vs_id in self.validation_scenarios:\n\n\t\t\t# get validation scenario\n\t\t\tvs = ValidationScenario.objects.get(pk=vs_id)\n\t\t\tvs_id = vs.id\n\t\t\tvs_filepath = vs.filepath\n\n\t\t\t# schematron based validation scenario\n\t\t\tif vs.validation_type == 'sch':\n\n\t\t\t\t# run udf map\n\t\t\t\tudf_func = self.validate_schematron_udf # must pass static method not attached to self\n\t\t\t\tvalidation_fails_rdd = self.records_df.rdd.\\\n\t\t\t\t\tmap(lambda row: udf_func(vs_id, vs_filepath, row))\\\n\t\t\t\t\t.filter(lambda row: row is not None)\n\n\n\t\t\t# python based validation scenario\n\t\t\telif vs.validation_type == 'python':\n\n\t\t\t\t# parse user defined functions from validation scenario payload\n\t\t\t\ttemp_pyvs = ModuleType('temp_pyvs')\n\t\t\t\texec(vs.payload, temp_pyvs.__dict__)\n\n\t\t\t\t# get defined functions\n\t\t\t\tpyvs_funcs = []\n\t\t\t\ttest_labeled_attrs = [ attr for attr in dir(temp_pyvs) if attr.lower().startswith('test') ]\n\t\t\t\tfor attr in test_labeled_attrs:\n\t\t\t\t\tattr = getattr(temp_pyvs, attr)\n\t\t\t\t\tif isfunction(attr):\n\t\t\t\t\t\tpyvs_funcs.append(attr)\n\n\t\t\t\tudf_func = self.validate_python_udf # must pass static method not attached to self\t\t\t\t\n\t\t\t\tvalidation_fails_rdd = self.records_df.rdd.\\\n\t\t\t\t\tmap(lambda row: udf_func(vs_id, pyvs_funcs, row))\\\n\t\t\t\t\t.filter(lambda row: row is not None)\n\n\n\t\t\t# finally, write to DB if validation failures\n\t\t\tif not validation_fails_rdd.isEmpty():\n\t\t\t\tvalidation_fails_rdd.toDF().write.jdbc(\n\t\t\t\t\tsettings.COMBINE_DATABASE['jdbc_url'],\n\t\t\t\t\t'core_recordvalidation',\n\t\t\t\t\tproperties=settings.COMBINE_DATABASE,\n\t\t\t\t\tmode='append')\n\n\n\t@staticmethod\n\tdef validate_schematron_udf(vs_id, vs_filepath, row):\n\n\t\t\t# parse schematron\n\t\t\tsct_doc = etree.parse(vs_filepath)\n\t\t\tvalidator = isoschematron.Schematron(sct_doc, store_report=True)\n\n\t\t\t# get document xml\n\t\t\trecord_xml = etree.fromstring(row.document.encode('utf-8'))\n\n\t\t\t# validate\n\t\t\tis_valid = validator.validate(record_xml)\n\n\t\t\t# if not valid, prepare Row\n\t\t\tif not is_valid:\n\n\t\t\t\t# prepare results_dict\n\t\t\t\tresults_dict = {\n\t\t\t\t\t'fail_count':0,\n\t\t\t\t\t'failed':[]\n\t\t\t\t}\n\n\t\t\t\t# get failed\n\t\t\t\treport_root = validator.validation_report.getroot()\n\t\t\t\tfails = report_root.findall('svrl:failed-assert', namespaces=report_root.nsmap)\n\n\t\t\t\t# log fail_count\n\t\t\t\tresults_dict['fail_count'] = len(fails)\n\n\t\t\t\t# loop through fails and add to dictionary\n\t\t\t\tfor fail in fails:\n\t\t\t\t\tfail_text_elem = fail.find('svrl:text', namespaces=fail.nsmap)\n\t\t\t\t\tresults_dict['failed'].append(fail_text_elem.text)\n\t\t\t\t\n\t\t\t\treturn Row(\n\t\t\t\t\trecord_id=int(row.id),\n\t\t\t\t\tvalidation_scenario_id=int(vs_id),\n\t\t\t\t\tvalid=0,\n\t\t\t\t\tresults_payload=json.dumps(results_dict),\n\t\t\t\t\tfail_count=results_dict['fail_count']\n\t\t\t\t)\n\n\n\t@staticmethod\n\tdef validate_python_udf(vs_id, pyvs_funcs, row):\n\n\t\t'''\n\t\tLoop through test functions and aggregate in fail_dict to return with Row\n\n\t\tArgs:\n\t\t\tvs_id (int): integer of validation scenario\n\t\t\tpyvs_funcs (list): list of functions imported from user created python validation scenario payload\n\t\t\trow (): \n\t\t'''\n\n\t\t# prepare row as parsed document with PythonUDFRecord class\n\t\tprvb = PythonUDFRecord(row)\n\t\t\n\t\t# prepare results_dict\n\t\tresults_dict = {\n\t\t\t'fail_count':0,\n\t\t\t'failed':[]\n\t\t}\n\n\t\t# loop through functions\n\t\tfor func in pyvs_funcs:\n\n\t\t\t# get func test message\n\t\t\tfunc_signature = signature(func)\n\t\t\tt_msg = func_signature.parameters['test_message'].default\n\n\t\t\t# attempt to run user-defined validation function\n\t\t\ttry:\n\n\t\t\t\t# run test\n\t\t\t\ttest_result = func(prvb)\n\n\t\t\t\t# if fail, append\n\t\t\t\tif test_result != True:\n\t\t\t\t\tresults_dict['fail_count'] += 1\n\t\t\t\t\t# if custom message override provided, use\n\t\t\t\t\tif test_result != False:\n\t\t\t\t\t\tresults_dict['failed'].append(test_result)\n\t\t\t\t\t# else, default to test message\n\t\t\t\t\telse:\n\t\t\t\t\t\tresults_dict['failed'].append(t_msg)\n\n\t\t\t# if problem, report as failure with Exception string\n\t\t\texcept Exception as e:\n\t\t\t\tresults_dict['fail_count'] += 1\n\t\t\t\tresults_dict['failed'].append(\"test '%s' had exception: %s\" % (func.__name__, str(e)))\n\n\t\t# if failed, return Row\n\t\tif results_dict['fail_count'] > 0:\n\t\t\t# return row\n\t\t\treturn Row(\n\t\t\t\trecord_id=int(row.id),\n\t\t\t\tvalidation_scenario_id=int(vs_id),\n\t\t\t\tvalid=0,\n\t\t\t\tresults_payload=json.dumps(results_dict),\n\t\t\t\tfail_count=results_dict['fail_count']\n\t\t\t)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"core/spark/record_validation.py","file_name":"record_validation.py","file_ext":"py","file_size_in_byte":7779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"568303717","text":"# COMPANY NEWS\nimport uuid\nfrom django.db import models\n\n\nclass CompanyNews(models.Model):\n id = models.UUIDField(\n primary_key=True,\n default=uuid.uuid4,\n editable=False\n )\n company = models.ForeignKey(\n 'Company',\n related_name='about',\n blank=True,\n null=True,\n on_delete=models.PROTECT\n )\n news = models.ForeignKey(\n 'News',\n related_name='discussed',\n blank=True,\n null=True,\n on_delete=models.PROTECT\n )\n date_published = models.DateField(\n blank=True,\n null=True\n )\n\n class Meta:\n verbose_name_plural = \"Companies news\"\n ordering = [\"-date_published\"]\n","sub_path":"backend/daneo/api/models/company_news.py","file_name":"company_news.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"426481206","text":"\"\"\"This module contains class Queue for Queue-related methods.\"\"\"\nfrom .node import Node\n# from node import Node\n\n\nclass Queue(object):\n \"\"\"To create a node for a Queue and other related methods.\"\"\"\n\n def __init__(self, iterable=None):\n self.front = None\n self.rear = None\n self._size = 0\n\n if iterable is None:\n iterable = []\n\n if type(iterable) is not list:\n raise TypeError('Iterable is not a list.')\n\n for what in iterable:\n self.enqueue(what)\n\n def __str__(self):\n output = f'Queue: Value of the front Queue is: {self.front.value}'\n return output\n\n def __len__(self):\n return self._size\n\n def __repr__(self):\n return f''\n\n def enqueue(self, value):\n \"\"\"\n \"\"\"\n if self.front is None and self.rear is None:\n new_node = Node(value)\n self.front = new_node\n self.rear = new_node\n self._size += 1\n return self\n else:\n new_node = Node(value)\n self.rear.next_node = new_node\n self.rear = new_node\n self._size += 1\n return self\n\n def dequeue(self):\n \"\"\"\n \"\"\"\n if self.front is None or self.rear is None:\n return f'Input must be a non-empty queue.'\n else:\n temp = self.front\n self.front = self.front.next_node\n temp.next_node = None\n return temp\n\n def peek(self):\n \"\"\"\n \"\"\"\n try:\n return self.front.value\n except:\n return f'Input must be a non-empty queue.'\n\n\n################################################\n##### To print: ##### \n##### ##### \n################################################\n\nnew_queue = Queue([1, 2, 3, 4, 5, 6])\n\nnew_queue.enqueue(7)\nnew_queue.dequeue()\nnew_queue.dequeue()\n\n\nprint(new_queue.rear.value)\n","sub_path":"data_structures/queue/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"28610133","text":"#-*- coding:Utf-8 -*-\nfrom Content import Content\nimport Frame\nimport SlideShow\nimport TextStyle\nimport BoxStyle\nimport ItemizeStyle\n\nclass Itemize (Content):\n\t\n\tdef __init__(self, tstyle=None , style=None, istyle=None, x=None, y= None, width=None, height=None):\n\t\t\"\"\"Constructor of Itemize. tstyle expects a TextStyle. style inherits of Content and represents the BoxStyle (thus expects a BoxStyle). style is constructed with the constructor of Content. istyle expects an ItemizeStyle. x, y, width and height expect a string : positive float and the unit (ex:\"42px\" or \"115%\")\"\"\"\n\n\t\tself.listItem=[]\n\n\t\tif style is None:\n\t\t\tstyle = BoxStyle.BoxStyle.currentBoxStyle\t\t\t\n\t\tself.boxStyle = BoxStyle.BoxStyle(style, x=x, y=y, width=width, height=height)\n\t\tSlideShow.SlideShow.styleS.addBoxStyle(self.boxStyle)\n\t\tif tstyle is None:\n\t\t\tself.textStyle = SlideShow.SlideShow.styleS.textStyleSheet[TextStyle.TextStyle.currentID]\n\t\telse:\n\t\t\tself.textStyle = tstyle\n\t\tif istyle is None:\n\t\t\tself.itemizeStyle = SlideShow.SlideShow.styleS.itemizeStyleSheet[ItemizeStyle.ItemizeStyle.currentID]\n\t\telse:\n\t\t\tself.itemizeStyle = istyle\n\n\t\tContent.__init__(self, Frame.Frame.currentFrame, style=None, x=None, y= None, width=None, height=None)\n\t\t\"\"\"Content's constructor\"\"\"\n\t\t\n\n\t\t#if Frame.Frame.currentFrame is None:\n\t\t#\traise AttributeError(\"You have not defined a frame yet\")\n\t\t#else :\n\t\t#\tFrame.Frame.currentFrame.listContent.append(self) # add new Itemize to the currentFrame\n\t\t \n\tdef toHtml(self):\n\t\t\"\"\"Every Itemize object is contained in a div block. That method takes in consideration the BoxStyle, the TextStyle and the ItemizeStyle.\"\"\"\n\t\tres = \"\"\n\t\tfor i in range (0, len(self.listItem)):\n\t\t\tres = res + self.listItem[i]\n\t\t\n\t\tif self.itemizeStyle is not None:\n\t\t\tif self.itemizeStyle.ordonated :\n\t\t\t\tres = \"
    \\n{}\\n\\n\".format(self.itemizeStyle.name, res)\n\t\t\telse :\t\t\t\t\t\n\t\t\t\tres = \"
      \\n{}\\n
    \\n\".format(self.itemizeStyle.name, res)\n\t\telse:\n\t\t\tres = \"
      \\n{}
    \\n\".format(res)\n\t\t\n\t\tif self.boxStyle is not None:\n\t\t\treturn \"
    \\n{}
    \\n\".format(self.boxStyle.name, res)\t\t\n\t\telse:\n\t\t\treturn \"
    \\n{}
    \\n\".format(res)\n\t\n\t\n\tdef item(self, text):\n\t\t\"\"\"Add a text item in that particular itemize. Expects a string.\"\"\"\n\t\tself.textStyle = SlideShow.SlideShow.styleS.textStyleSheet[TextStyle.TextStyle.currentID]\n\n\t\tif self.textStyle is not None:\n\t\t\tself.listItem.append(\"
  1. {}
  2. \\n\".format(self.textStyle.name, text))\n\t\telse:\n\t\t\tself.listItem.append(\"
  3. {}
  4. \\n\".format(text))\n\n\tdef add(self, item):\n\t\t\"\"\"Add any content in that particular itemize. Expects a Content\"\"\"\n\t\tself.listItem.append(item.toHtml())\n\n","sub_path":"Python/SINP/trunk/dossierTravailGroupe/Text - groupe 2/Itemize.py","file_name":"Itemize.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"537064192","text":"from aip import AipNlp\nfrom aip import AipImageClassify\n\"\"\" 你的 APPID AK SK \"\"\"\nAPP_ID = '10933367'\nAPI_KEY = 'fTUW2Kkk9l0CB8zPFua1f3Ue'\nSECRET_KEY = 'CNgFXI8eCds2u5lOFth0OKSIu71dBgNW'\nclient = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)\n\n# client = AipNlp(APP_ID, API_KEY, SECRET_KEY)\ndef compare_words(word1,word2,method):\n if method == 1:\n for word1 in word_list:\n res = client.wordSimEmbedding(word1, word2)\n print([word1, word2, res[\"score\"]])\n elif method==2:\n for word1 in word_list:\n res = client.simnet(word1, word2)\n print([word1,word2,res[\"score\"]])\nword_list = [\"good\",\"happy\",\"happiness\",\"bad\",\"smile\"]\nword2 = \"beautiful\"\nmethod=2\n# compare_words(word_list,word2,method)\n\"\"\" 读取图片 \"\"\"\ndef get_file_content(filePath):\n with open(filePath, 'rb') as fp:\n return fp.read()\nimage = get_file_content('222.png')\n\n\"\"\" 调用车辆识别 \"\"\"\nprint(client.carDetect(image,options = {\"top_num\":1})[\"result\"][0][\"name\"])\n\n","sub_path":"公众号发文代码/汽车品牌识别.py","file_name":"汽车品牌识别.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"44867969","text":"from django.urls import path,include\nfrom . import views\n\n\nurlpatterns = [\n \n path('addtocart/', views.add_to_cart, name='addtocart'),\n path('removefromcart/', views.remove_from_cart, name='removefromcart'),\n path('carthome/', views.CartView, name='carthome'),\n path('decreasecart/', views.decreaseCart, name='decreasecart'),\n path('myorderhome/',views.myorderview, name='myorderhome'),\n path('ordereditems/',views.ordereditems, name='ordereditems'),\n path('cancelorder/',views.cancelorder,name='cancelorder'),\n]\n\n#path('myorderhome/',views.myorderview, name='myorderhome'),\n","sub_path":"cart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"137396665","text":"import Game.Screens.button as Button\nimport Game.Functions.Sounds as Sounds\nimport pygame\n\n\nclass Sound:\n def __init__(self, color, sub, size):\n self.Button = Button.Button(color, sub, \"Sound\", size[0] * 0.3, size[1] * 0.6, int(size[0] * 0.19), int(size[1] * 0.08))\n\n def action(self, game):\n if game.Sound == \"On\":\n game.Sound = \"Off\"\n pygame.mixer.music.fadeout(1500)\n else:\n game.Sound = \"On\"\n Sounds.Pausesound(game)\n","sub_path":"Game/Screens/Pauze/Sound.py","file_name":"Sound.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"653740117","text":"\"\"\"\n TEDDY\n\"\"\"\n\nfrom scapy.all import *\nfrom time import sleep\nfrom os import geteuid\nfrom sys import argv, exit\nfrom argparse import ArgumentParser\n\ndef exploit(source, target, iface=\"eth0\"):\n \"\"\"Teddy attack\"\"\"\n\n socket = conf.L2socket(iface=iface)\n packets=[]\n for i in xrange(1,100):\n packets.append(IP(dst=target,src=source)/ICMP(type=3,code=3))\n\n while True:\n sendp(packets)\n\nif __name__ == \"__main__\":\n ap = ArgumentParser(description=\"TEDDY ICMP DOS Attack\")\n ap.add_argument(\"-s\", \"--source\", required=True, help=\"Spoofed source IP address\")\n ap.add_argument(\"-t\", \"--target\", required=True, help=\"Target's IP address\")\n ap.add_argument(\"-i\", \"--interface\", required=False, help=\"Network interface to use\")\n args = vars(ap.parse_args())\n\n if not geteuid() == 0:\n exit(\"[!] Root you must be, meow\")\n\n try:\n print(\"[*] Starting TEDDY attack\")\n exploit(args[\"source\"], args[\"target\"], args[\"interface\"], args[\"interval\"])\n except IOError:\n exit(\"[!] Error sending packets\")\n except KeyboardInterrupt:\n print(\"\\n[*] Stopping TEDDY attack\")\n","sub_path":"teddy.py","file_name":"teddy.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"466163251","text":"class EmployeeList(object):\r\n \"\"\"\r\n creates the employee list object for editing\r\n \"\"\"\r\n\r\n def __init__(self, filename):\r\n self.employee_list = filename\r\n self.names = ''\r\n self.names_to_add = ''\r\n self.names_to_delete = ''\r\n self.list_of_employees = []\r\n\r\n # method used to read lines in the given file\r\n # adds names to self.names for editing purposes\r\n\r\n def open_file(self):\r\n employee_list = open(self.employee_list, 'r')\r\n self.names = employee_list.readlines()\r\n employee_list.close()\r\n\r\n print(self.names)\r\n\r\n # takes user input to add or delete a name in the text file\r\n def get_name(self):\r\n first_name = input(\"Employee first name: \").upper()\r\n last_name = input(\"Employee last name: \").upper()\r\n name = (first_name + \" \" + last_name)\r\n return name\r\n\r\n # method to add name and address to excel / text file\r\n\r\n def add_employee(self):\r\n self.open_file()\r\n self.names_to_add = self.get_name()\r\n\r\n print(self.names_to_add)\r\n\r\n employee_list = open(self.employee_list, 'w')\r\n employee_list.truncate()\r\n\r\n for name in self.names:\r\n employee_list.write(name)\r\n employee_list.write('\\n')\r\n employee_list.write(self.names_to_add)\r\n\r\n employee_list.close()\r\n\r\n # method to remove a name from the file\r\n\r\n def remove_employee(self):\r\n self.open_file()\r\n self.names_to_delete = self.get_name()\r\n\r\n employee_list = open(self.employee_list, 'w')\r\n employee_list.truncate()\r\n\r\n for name in self.names:\r\n if name != self.names_to_delete + '\\n' and name != self.names_to_delete:\r\n employee_list.write(name)\r\n\r\n employee_list.close()\r\n\r\n # method to print names in the file\r\n def print_employees(self):\r\n self.open_file()\r\n for name in self.names:\r\n print(name)\r\n\r\n # method to create a loop for user interaction\r\n # gets input to perform desired action\r\n\r\n def user_choice(self):\r\n choice = False\r\n while not choice:\r\n user_choice = input(\"What would you like to do?\" '\\n'\r\n \"'A' to add an employee\" '\\n'\r\n \"'D' to delete an employee\" '\\n'\r\n \"'P' to print current employees\" '\\n'\r\n \"'Q' to exit\" '\\n'\r\n \"input please: \").upper()\r\n\r\n if user_choice == 'A':\r\n self.add_employee()\r\n choice = True\r\n elif user_choice == 'D':\r\n self.remove_employee()\r\n choice = True\r\n elif user_choice == 'P':\r\n self.print_employees()\r\n choice = True\r\n elif user_choice == 'Q':\r\n self.open_file()\r\n print(\"Ending program\")\r\n choice = True\r\n else:\r\n print(\"error in user input, please try again\")\r\n\r\n # manages user interaction with file\r\n def run_it(self):\r\n done = False\r\n while not done:\r\n self.user_choice()\r\n\r\n finished = input(\"done? Y or N\")\r\n\r\n if finished.upper() == \"Y\":\r\n done = True\r\n else:\r\n done = False\r\n\r\n self.open_file()\r\n for name in self.names:\r\n name = name.replace('\\n', '')\r\n self.list_of_employees.append(name)\r\n\r\n print(self.list_of_employees)\r\n\r\n\r\nlist_of_employees = EmployeeList('test.txt')","sub_path":"employeelist.py","file_name":"employeelist.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"303578837","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 1 17:55:47 2018\n\n@author: celal258\n\"\"\"\n\nimport pandas as pd\n#Tarih kismi ay/gun seklinde tabloya cekilmistir. \ndataframe = pd.read_csv('./data.csv')\nx=dataframe.iloc[:,0:1].values\ny=dataframe.iloc[:,3:4].values\n\"\"\"\nfrom sklearn.preprocessing import StandardScaler\nscaled_x=StandardScaler().fit_transform(x)\nscaled_y=StandardScaler().fit_transform(y)\n\"\"\"\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)\n\nfrom sklearn.tree import DecisionTreeRegressor\nregressor=DecisionTreeRegressor()\nregressor.fit(x_train,y_train)\n\ny_predictions=regressor.predict(x_test)\n","sub_path":"kararagaci.py","file_name":"kararagaci.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"198872141","text":"from django.db import models\nfrom django.db.models.base import Model\nfrom django.db.models.enums import Choices\nfrom django.db.models.fields import BLANK_CHOICE_DASH, EmailField\nfrom django.forms import widgets\nfrom django.utils import tree\n\n# Create your models here.\n\nclass Edificio_Model (models.Model):\n creado = models.DateField(auto_now=True)\n nombre = models.CharField(max_length= 20)\n ubicacion = models.CharField(max_length=50)\n nit = models.CharField(max_length=15)\n contacto = models.CharField(max_length=20)\n email = models.EmailField()\n\n def __str__(self) :\n return self.nombre\n\n\n\nopciones_estado = [\n [0, 'Disponible'],\n [1, 'Ocupado']\n\n]\n\nopciones_cuenta =[\n [0, 'Propietario'],\n [1, 'Ocupante']\n\n]\n\nclass Propietario_Model(models.Model):\n nombre = models.CharField(max_length=30)\n edificio = models.ForeignKey(Edificio_Model, on_delete=models.PROTECT)\n tipo = models.BooleanField(choices=opciones_cuenta)\n apartamento = models.CharField(max_length=5)\n correo = models.EmailField()\n contacto_1 = models.CharField(max_length=14)\n contacto_2 = models.CharField(max_length=14, blank=True)\n estado = models.BooleanField(choices=opciones_estado)\n creado = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.apartamento\n\n\n\nopcion_vehiculo =[\n\n [0, \"Carro\"],\n [1, \"Moto\"]\n\n]\n\n\nclass Visitante_Model(models.Model):\n nombre = models.CharField(max_length=30)\n apartamento = models.ForeignKey(Propietario_Model, on_delete=models.CASCADE)\n vehiculo = models.BooleanField(choices=opcion_vehiculo, blank= True)\n placa = models.CharField(max_length=14, blank=True)\n creado = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.nombre\n\n\n\nclass Presupuesto_Cuenta(models.Model):\n nombre = models.CharField(max_length=50)\n creado = models.TimeField(auto_now=True)\n\n def __str__(self):\n return self.nombre\n\n\n\nopciones_frecuencia = [\n [1, 'Mesual'],\n [2, 'Semestral'],\n [3, 'Trimestral'],\n [4, 'Cuatrimestral'],\n [5, 'Semestral'],\n [6, 'Anual']\n \n]\n\nopciones_mes = [\n [1, 'Enero'],\n [2, 'Febrero'],\n [3, 'Marzo'],\n [4, 'Abril'],\n [5, 'Mayo'],\n [6, 'Junio'],\n [7, 'Julio'],\n [8, 'Agosto'],\n [9, 'Septiembre'],\n [10, 'Octubre'],\n [11, 'Noviembre'],\n [12, 'Diciembre'],\n \n]\n\n\nclass Presupuesto_Rubro(models.Model):\n nombre = models.CharField(max_length=50)\n tipo = models.ForeignKey(Presupuesto_Cuenta, on_delete=models.PROTECT)\n frecuencia = models.IntegerField(default=0, choices=opciones_frecuencia)\n mes = models.IntegerField(choices=opciones_mes)\n valor = models.DecimalField(max_digits=14, decimal_places=3)\n creado = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.nombre\n\n\n \n\n\n\n","sub_path":"edificios/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"630984412","text":"import itertools\n\nimport numpy as np\nfrom sklearn import preprocessing\n\nfrom gym_go import state_utils\nfrom gym_go.govars import BLACK, WHITE, INVD_CHNL, PASS_CHNL, DONE_CHNL\n\n\"\"\"\nThe state of the game is a numpy array\n* Are values are either 0 or 1\n\n* Shape [6, SIZE, SIZE]\n\n0 - Black pieces\n1 - White pieces\n2 - Turn (0 - black, 1 - white)\n3 - Invalid moves (including ko-protection)\n4 - Previous move was a pass\n5 - Game over\n\"\"\"\n\n\nclass GoGame:\n\n @staticmethod\n def get_init_board(size, black_first=True):\n # return initial board (numpy board)\n state = np.zeros((6, size, size))\n if not black_first:\n state_utils.set_turn(state)\n return state\n\n @staticmethod\n def get_next_state(state, action):\n \"\"\"\n Does not change the given state\n :param state:\n :param action:\n :return: The next state\n \"\"\"\n\n # check if game is already over\n if GoGame.get_game_ended(state) != 0:\n raise Exception('Attempt to step at {} after game is over'.format(action))\n\n state = np.copy(state)\n\n # if the current player passes\n if action == GoGame.get_action_size(state) - 1:\n # if two consecutive passes, game is over\n if GoGame.get_prev_player_passed(state):\n state_utils.set_game_ended(state)\n else:\n state_utils.set_prev_player_passed(state)\n\n # Update invalid channel\n state_utils.reset_invalid_moves(state)\n state_utils.add_invalid_moves(state)\n\n # Switch turn\n state_utils.set_turn(state)\n\n # Return event\n return state\n\n player = state_utils.get_turn(state)\n m, n = state_utils.get_board_size(state)\n\n # convert the move to 2d\n action = (action // m, action % n)\n\n # Check move is valid\n if not state_utils.is_within_bounds(state, action):\n raise Exception(\"{} Not Within bounds\".format(action))\n elif state[INVD_CHNL][action] > 0:\n raise Exception(\"Invalid Move\", action, state)\n\n state_utils.reset_invalid_moves(state)\n\n # Get all adjacent groups\n _, opponent_groups = state_utils.get_adjacent_groups(state, action)\n\n # Go through opponent groups\n killed_single_piece = None\n empty_adjacents_before_kill = state_utils.get_adjacent_locations(state, action)\n for group in opponent_groups:\n empty_adjacents_before_kill = empty_adjacents_before_kill - group.locations\n if len(group.liberties) <= 1:\n assert action in group.liberties\n\n # Remove group in board\n for loc in group.locations:\n # TODO: Hardcoded other player. Make more generic\n state[1 - player][loc] = 0\n\n # Metric for ko-protection\n if len(group.locations) <= 1:\n if killed_single_piece is not None:\n killed_single_piece = None\n else:\n killed_single_piece = group.locations.pop()\n\n # If group was one piece, and location is surrounded by opponents,\n # activate ko protection\n if killed_single_piece is not None and len(empty_adjacents_before_kill) <= 0:\n state[INVD_CHNL][killed_single_piece] = 1\n\n # Add the piece!\n state[player][action] = 1\n\n # Update illegal moves\n state_utils.add_invalid_moves(state)\n\n # This move was not a pass\n state_utils.set_prev_player_passed(state, 0)\n\n # Switch turn\n state_utils.set_turn(state)\n\n return state\n\n @staticmethod\n def get_action_size(state=None, board_size: int = None):\n # return number of actions\n if state is not None:\n m, n = state_utils.get_board_size(state)\n elif board_size is not None:\n m, n = board_size, board_size\n else:\n raise RuntimeError('No argument passed')\n return m * n + 1\n\n @staticmethod\n def get_prev_player_passed(state):\n m, n = state_utils.get_board_size(state)\n return np.count_nonzero(state[PASS_CHNL] == 1) == m * n\n\n @staticmethod\n def get_game_ended(state):\n \"\"\"\n :param state:\n :return: 0/1 = game not ended / game ended respectively\n \"\"\"\n m, n = state_utils.get_board_size(state)\n return int(np.count_nonzero(state[DONE_CHNL] == 1) == m * n)\n\n @staticmethod\n def get_turn(state):\n \"\"\"\n :param state:\n :return: Who's turn it is (BLACK/WHITE)\n \"\"\"\n return state_utils.get_turn(state)\n\n @staticmethod\n def get_valid_moves(state):\n # return a fixed size binary vector\n if GoGame.get_game_ended(state):\n return np.zeros(GoGame.get_action_size(state))\n return np.append(1 - state[INVD_CHNL].flatten(), 1)\n\n @staticmethod\n def action_2d_to_1d(action_2d, state):\n size = state.shape[1]\n if action_2d is None:\n action_1d = size ** 2\n else:\n action_1d = action_2d[0] * size + action_2d[1]\n return action_1d\n\n @staticmethod\n def get_num_liberties(state: np.ndarray):\n '''\n :param state:\n :return: Total black and white liberties\n '''\n blacks = state[BLACK]\n whites = state[WHITE]\n all_pieces = np.sum(state[[BLACK, WHITE]], axis=0)\n\n num_liberties = []\n for player_pieces in [blacks, whites]:\n liberties = np.zeros(player_pieces.shape)\n for shift, axis in [(1, 0), (-1, 0), (1, 1), (-1, 1)]:\n neighbors = np.roll(player_pieces, shift, axis=axis)\n pad_idx = 0 if shift == 1 else -1\n if axis == 0:\n neighbors[pad_idx, :] = 0\n else:\n neighbors[:, pad_idx] = 0\n\n liberties += neighbors\n liberties *= 1 - all_pieces\n num_liberties.append(np.sum(liberties > 0))\n\n return num_liberties[0], num_liberties[1]\n\n @staticmethod\n def get_areas(state):\n '''\n Return black area, white area\n Use DFS helper to find territory.\n '''\n\n m, n = state_utils.get_board_size(state)\n visited = np.zeros((m, n), dtype=np.bool)\n black_area = 0\n white_area = 0\n\n # loop through each intersection on board\n for r, c in itertools.product(range(m), range(n)):\n # count pieces towards area\n if state[BLACK][r, c] > 0:\n black_area += 1\n elif state[WHITE][r, c] > 0:\n white_area += 1\n\n # do DFS on unvisited territory\n elif not visited[r, c]:\n player, area = state_utils.explore_territory(state, (r, c), visited)\n\n # add area to corresponding player\n if player == BLACK: # BLACK\n black_area += area\n elif player == WHITE: # WHITE\n white_area += area\n\n return black_area, white_area\n\n @staticmethod\n def get_canonical_form(state):\n \"\"\"\n The returned state is a seperate copy of the given state\n :param state:\n :param player:\n :return:\n \"\"\"\n state = np.copy(state)\n\n player = GoGame.get_turn(state)\n if player == BLACK:\n return state\n else:\n assert player == WHITE\n num_channels = state.shape[0]\n channels = np.arange(num_channels)\n channels[BLACK] = WHITE\n channels[WHITE] = BLACK\n state = state[channels]\n state_utils.set_turn(state)\n return state\n\n @staticmethod\n def random_symmetry(chunk):\n \"\"\"\n Returns a random symmetry of the chunk\n :param chunk: A (C, BOARD_SIZE, BOARD_SIZE) numpy array, where C is any number\n :return:\n \"\"\"\n orientation = np.random.randint(0, 8)\n\n if (orientation >> 0) % 2:\n # Horizontal flip\n chunk = np.flip(chunk, 2)\n if (orientation >> 1) % 2:\n # Vertical flip\n chunk = np.flip(chunk, 1)\n if (orientation >> 2) % 2:\n # Rotate 90 degrees\n chunk = np.rot90(chunk, axes=(1, 2))\n\n return chunk\n\n @staticmethod\n def get_symmetries(chunk):\n \"\"\"\n :param chunk: A (C, BOARD_SIZE, BOARD_SIZE) numpy array, where C is any number\n :return: All 8 orientations that are symmetrical in a Go game over the 2nd and 3rd axes\n (i.e. rotations, flipping and combos of them)\n \"\"\"\n symmetries = []\n\n for i in range(8):\n x = chunk\n if (i >> 0) % 2:\n # Horizontal flip\n x = np.flip(x, 2)\n if (i >> 1) % 2:\n # Vertical flip\n x = np.flip(x, 1)\n if (i >> 2) % 2:\n # Rotation 90 degrees\n x = np.rot90(x, axes=(1, 2))\n symmetries.append(x)\n\n return symmetries\n\n @staticmethod\n def random_weighted_action(move_weights):\n \"\"\"\n Assumes all invalid moves have weight 0\n Action is 1D\n Expected shape is (NUM OF MOVES, )\n \"\"\"\n move_weights = preprocessing.normalize(move_weights[np.newaxis], norm='l1')\n return np.random.choice(np.arange(len(move_weights[0])), p=move_weights[0])\n\n @staticmethod\n def random_action(state):\n \"\"\"\n Assumed to be (6, BOARD_SIZE, BOARD_SIZE)\n Action is 1D\n \"\"\"\n invalid_moves = state[INVD_CHNL].flatten()\n invalid_moves = np.append(invalid_moves, 0)\n move_weights = 1 - invalid_moves\n\n return GoGame.random_weighted_action(move_weights)\n\n @staticmethod\n def str(state):\n board_str = ' '\n\n size = state.shape[1]\n for i in range(size):\n board_str += ' {}'.format(i)\n board_str += '\\n '\n board_str += '----' * size + '-'\n board_str += '\\n'\n for i in range(size):\n board_str += '{} |'.format(i)\n for j in range(size):\n if state[0][i, j] == 1:\n board_str += ' B'\n elif state[1][i, j] == 1:\n board_str += ' W'\n elif state[2][i, j] == 1:\n board_str += ' .'\n else:\n board_str += ' '\n\n board_str += ' |'\n\n board_str += '\\n '\n board_str += '----' * size + '-'\n board_str += '\\n'\n\n black_area, white_area = GoGame.get_areas(state)\n game_ended = GoGame.get_game_ended(state)\n prev_player_passed = GoGame.get_prev_player_passed(state)\n turn = GoGame.get_turn(state)\n board_str += '\\tTurn: {}, Last Turn Passed: {}, Game Over: {}\\n'.format('B' if turn == 0 else 'W',\n prev_player_passed,\n game_ended)\n board_str += '\\tBlack Area: {}, White Area: {}\\n'.format(black_area, white_area)\n return board_str\n","sub_path":"gym_go/gogame.py","file_name":"gogame.py","file_ext":"py","file_size_in_byte":11307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"367682811","text":"from torch.optim import Adam\nfrom all.agents import VAC\nfrom all.approximation import VNetwork, FeatureNetwork\nfrom all.logging import DummyWriter\nfrom all.policies import SoftmaxPolicy\nfrom .models import fc_relu_features, fc_policy_head, fc_value_head\n\n\ndef vac(\n # Common settings\n device=\"cpu\",\n discount_factor=0.99,\n # Adam optimizer settings\n lr_v=5e-3,\n lr_pi=1e-3,\n eps=1e-5,\n):\n \"\"\"\n Vanilla Actor-Critic classic control preset.\n\n Args:\n device (str): The device to load parameters and buffers onto for this agent.\n discount_factor (float): Discount factor for future rewards.\n lr_v (float): Learning rate for value network.\n lr_pi (float): Learning rate for policy network and feature network.\n eps (float): Stability parameters for the Adam optimizer.\n \"\"\"\n def _vac(env, writer=DummyWriter()):\n value_model = fc_value_head().to(device)\n policy_model = fc_policy_head(env).to(device)\n feature_model = fc_relu_features(env).to(device)\n\n value_optimizer = Adam(value_model.parameters(), lr=lr_v, eps=eps)\n policy_optimizer = Adam(policy_model.parameters(), lr=lr_pi, eps=eps)\n feature_optimizer = Adam(feature_model.parameters(), lr=lr_pi, eps=eps)\n\n v = VNetwork(value_model, value_optimizer, writer=writer)\n policy = SoftmaxPolicy(policy_model, policy_optimizer, writer=writer)\n features = FeatureNetwork(feature_model, feature_optimizer)\n\n return VAC(features, v, policy, discount_factor=discount_factor)\n return _vac\n","sub_path":"all/presets/classic_control/vac.py","file_name":"vac.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"654360681","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 29 13:37:56 2016\n\n@author: LY\n\"\"\"\n#import math\n#import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cmath\n\n\npath = r'D:\\Users\\LY\\Documents\\Python Scripts\\Data'\n\nfile_name1 = r'data_0829_S21_vers_freq_4_layers_H+T.txt'\n\nfile_path1 = path + '\\\\'+ file_name1\n\n\nf1 = open(file_path1, 'r')\ncol_13_5 = []\ncol_13 = []\ncol_14 = []\nphase_col_13_5 = []\nphase_col_13 = []\nphase_col_14 = []\n\nfor line in f1.readlines():\n if '\\t' in line:\n line = line.replace('\\n','').replace('\\t', ' ').split(' ') \n \n #print(line[0])\n \n if eval(line[0]) == 13:\n col_13.append(20*np.log10(np.sqrt(eval(line[1]) ** 2 + eval(line[2]) **2)))\n phase_col_13.append(cmath.phase(complex(eval(line[1]),eval(line[2])))/np.pi*180 % 360)\n elif eval(line[0]) == 13.5:\n col_13_5.append(20*np.log10(np.sqrt(eval(line[1]) ** 2 + eval(line[2]) **2)))\n phase_col_13_5.append(cmath.phase(complex(eval(line[1]),eval(line[2])))/np.pi*180 % 360)\n elif eval(line[0]) == 14:\n col_14.append(20*np.log10(np.sqrt(eval(line[1]) ** 2 + eval(line[2]) **2)))\n phase_col_14.append(cmath.phase(complex(eval(line[1]),eval(line[2])))/np.pi*180 % 360)\n\n\ncol_x = np.arange(7, 10.7, 0.2)\n\n\nf1.close()\n\nfig = plt.figure(1)\nplt.axis([7, 11,-30, 5 ])\nplt.plot(col_x, col_13,'*')\nplt.plot(col_x, col_13_5,'ro')\nplt.plot(col_x, col_14,'k+')\n\nplt.show()\nfig.set_size_inches(8, 6)\nfig.savefig('S21_vers_L1.png', dpi=200)\n\n\nfig_phase = plt.figure(2)\nplt.plot(col_x, phase_col_13,'b')\nplt.plot(col_x, phase_col_13_5,'r')\nplt.plot(col_x, phase_col_14,'k')\nplt.show()\nfig_phase.savefig('S21_Phase_vers_L1.png', dpi=200)","sub_path":"Python Scripts/2016_08_29_2243_data_process.py","file_name":"2016_08_29_2243_data_process.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"280274936","text":"from django.shortcuts import render\r\nfrom django.shortcuts import redirect\r\nfrom django.http import HttpResponse\r\nfrom reviewPage.models import reviewMovie,reviewGame,reviewTV\r\nfrom reviewPage.forms import movieReviewForm, gameReviewForm, tvReviewForm\r\nfrom django.views.generic.edit import FormView\r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\r\nfrom django.shortcuts import get_object_or_404\r\nfrom django.db.models import Q\r\nfrom ipware.ip import get_ip\r\nimport json\r\nimport re\r\n# Create your views here.\r\ndef validOrder(filter):\r\n if filter == \"date\":\r\n return \"-date\"\r\n if filter == \"recommend\":\r\n return \"-recommend\"\r\n if filter == \"score\":\r\n return \"-score\"\r\n if filter == \"-score\":\r\n return \"score\"\r\n\r\n\r\ndef reviews(request,type,id,filter,pid):\n query = Q()\n filter12 = filter.split(\"&\")\n if len(filter12) == 2:\r\n words = re.split(r\"[^A-Za-z가-힣']+\", filter12[1])\r\n print(words)\r\n for word in words:\r\n query &= Q(comment__icontains=word)\r\n query &= Q(contentsId=id)\r\n if type == \"m\":\n cmmtList = reviewMovie.objects.filter(query).order_by(validOrder(filter12[0]))\r\n if type == \"g\":\r\n cmmtList = reviewGame.objects.filter(query).order_by(validOrder(filter12[0]))\r\n if type == \"t\":\r\n cmmtList = reviewTV.objects.filter(query).order_by(validOrder(filter12[0]))\r\n\r\n lenCmmtList = len(cmmtList)\r\n pageHeadIdx = (int(pid)-1)*20\r\n pageTailIdx = pageHeadIdx+20\r\n if pageTailIdx > lenCmmtList:\r\n pageTailIdx = lenCmmtList\r\n\r\n return render(request,'reviewPage/reviewPage.html',{\"reviewList\":cmmtList[pageHeadIdx:pageTailIdx]})\r\n\r\n\r\ndef review_like(request):\r\n review_id = request.POST.get('pk', None)\r\n contentsType = request.POST.get('type', None)\r\n if contentsType == \"m\":\r\n review = get_object_or_404(reviewMovie, pk=review_id)\r\n if request.user not in review.votingUser.all():\r\n review.votingUser.add(request.user)\r\n review.recommend += 1\r\n review.save()\r\n context = {'like_count': review.recommend,'message':\"success\"}\r\n else:\r\n review.save()\r\n context = {'like_count': review.recommend,'message':\"이미 공감 또는 비공감 버튼을 누르셨습니다.\"}\r\n\r\n\r\n return HttpResponse(json.dumps(context), content_type=\"application/json\")\r\n\r\n\r\ndef review_dislike(request):\r\n review_id = request.POST.get('pk', None)\r\n contentsType = request.POST.get('type', None)\r\n if contentsType == \"m\":\r\n review = get_object_or_404(reviewMovie, pk=review_id)\r\n if request.user not in review.votingUser.all():\r\n review.votingUser.add(request.user)\r\n review.nonRecommend += 1\r\n review.save()\r\n context = {'dislike_count': review.nonRecommend,'message':\"success\"}\r\n else:\r\n review.save()\r\n context = {'dislike_count': review.nonRecommend,'message':\"이미 공감 또는 비공감 버튼을 누르셨습니다.\"}\r\n\r\n return HttpResponse(json.dumps(context), content_type=\"application/json\")\r\n","sub_path":"beekaveWebdev/reviewPage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"292869878","text":"from django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_POST\n\nfrom Article.forms import ArticleCategoryForm, ArticlePostForm\nfrom Article.models import ArticleCategory, ArticlePost\nimport redis\nfrom MyBlog import settings\n\nr = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)\n\n@login_required(login_url=\"/account/login\")\n@csrf_exempt\ndef article_category(request):\n if request.method == 'POST':\n cate_name = request.POST[\"cate_name\"]\n cates = ArticleCategory.objects.filter(user=request.user, category=cate_name)\n if cates:\n return HttpResponse(-1)\n else:\n ArticleCategory.objects.create(user=request.user, category=cate_name)\n return HttpResponse(1)\n else:\n cates = ArticleCategory.objects.filter(user=request.user)\n cate_form = ArticleCategoryForm()\n context = {\n \"cates\": cates,\n \"cate_form\": cate_form\n }\n return render(request, \"Article/article_category.html\", context)\n\n\n@login_required(login_url='/account/login')\n@require_POST\n@csrf_exempt\ndef rename_category(request):\n cate_id = request.POST[\"cate_id\"]\n cate_name = request.POST[\"cate_name\"]\n try:\n cate = ArticleCategory.objects.get(id=cate_id)\n cate.category = cate_name\n cate.save()\n return HttpResponse(\"1\")\n except:\n return HttpResponse(-1)\n\n\n@login_required(login_url='/account/login')\n@require_POST\n@csrf_exempt\ndef delete_category(request):\n cate_id = request.POST[\"cate_id\"]\n try:\n cate = ArticleCategory.objects.get(id=cate_id)\n cate.delete()\n return HttpResponse(\"1\")\n except:\n return HttpResponse(\"-1\")\n\n\n@login_required(login_url='/account/login')\n@csrf_exempt\ndef article_post(request):\n if request.method == 'POST':\n article_post_form = ArticlePostForm(request.POST)\n if article_post_form.is_valid():\n cd = article_post_form.cleaned_data\n try:\n new_article = article_post_form.save(False)\n new_article.author = request.user\n new_article.category = request.user.article_category.get(id=request.POST[\"cate_id\"])\n new_article.save()\n return HttpResponse(\"1\")\n except Exception as e:\n print(e)\n return HttpResponse(\"-1\")\n else:\n return HttpResponse(\"-1\")\n else:\n article_post_form = ArticlePostForm()\n article_cates = request.user.article_category.all()\n context = {\n \"article_post_form\": article_post_form,\n \"article_cates\": article_cates\n }\n return render(request, \"Article/article_post.html\", context)\n\n\n@login_required(login_url='/account/login')\ndef article_list(request):\n article_list = ArticlePost.objects.filter(author=request.user)\n paginator = Paginator(article_list, 2)\n page = request.GET.get('page')\n try:\n current = paginator.page(page)\n articles = current.object_list\n except PageNotAnInteger:\n current = paginator.page(1)\n articles = current.object_list\n except EmptyPage:\n current = paginator.page(paginator.num_pages)\n articles = current.object_list\n context = {\n \"articles\": articles,\n \"page\": current\n }\n return render(request, \"Article/article_list.html\", context)\n\n\n@login_required(login_url='/account/login')\ndef article_detail(request, id, slug):\n article = get_object_or_404(ArticlePost, id=id, slug=slug)\n total_views = r.incr(f\"article:{article.id}:views\")\n context = {\n \"article\": article,\n \"total_views\": total_views\n }\n return render(request, \"Article/article_detail.html\", context)\n\n\n@login_required(login_url='/account/login')\n@require_POST\n@csrf_exempt\ndef article_delete(request):\n article_id = request.POST[\"article_id\"]\n try:\n article = ArticlePost.objects.get(id=article_id)\n article.delete()\n return HttpResponse(\"1\")\n except Exception as e:\n print(e)\n return HttpResponse(\"-1\")\n\n\n@login_required(login_url='/account/login')\n@csrf_exempt\ndef article_edit(request, id):\n if request.method == 'POST':\n article = ArticlePost.objects.get(id=id)\n try:\n article.category = request.user.article_category.get(id=request.POST[\"cate_id\"])\n article.title = request.POST[\"title\"]\n article.body = request.POST[\"body\"]\n article.save()\n return HttpResponse(\"1\")\n\n except Exception as e:\n print(e)\n return HttpResponse(\"-1\")\n else:\n cates = ArticleCategory.objects.filter(user=request.user)\n article = get_object_or_404(ArticlePost, id=id)\n article_form = ArticlePostForm(initial={\n \"title\": article.title\n })\n article_category = article.category\n context = {\n 'cates': cates,\n 'article': article,\n 'article_form': article_form,\n 'article_category': article_category\n }\n return render(request, 'Article/article_edit.html', context)\n\n","sub_path":"Article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"340567740","text":"import sqlite3\r\n\r\n#Creating a connectrion object for DB\r\ndbname=\"Movies.db\"\r\nconnect=sqlite3.connect(dbname)\r\n\r\ncursor=connect.cursor()\r\n\r\ndef createTable():\r\n stmt=\" CREATE TABLE IF NOT EXISTS Movies (actor text, actress text, year integer, director text) \"\r\n\r\n cursor.execute(stmt)\r\n connect.commit()\r\n print(\"QUERY EXECUTED SUCCESSFULLY AND COMMITED TO MOVIES TABLE...\")\r\n\r\ndef addMovie(actor,actress,year,director):\r\n stmt=\" INSERT INTO Movies (actor,actress,year,director) VALUES (?,?,?,?)\"\r\n args=actor,actress,year,director\r\n cursor.execute(stmt,args)\r\n connect.commit()\r\n print(\"QUERY EXECUTED SUCCESSFULLY AND COMMITED TO MOVIES TABLE...\")\r\n\r\ndef retrieveMovieDetails(query):\r\n\r\n cursor.execute(query)\r\n connect.commit()\r\n print(\"QUERY EXECUTED SUCCESSFULLY AND COMMITED TO MOVIES TABLE...\")\r\n\r\n for row in cursor.execute(query):\r\n print(row)\r\n\r\n\r\ndef main():\r\n welcome=\"\"\" \r\n 1. CREATE TABLE\r\n \r\n 2. ADD MOVIE\r\n 3. QUERYING\r\n \"\"\"\r\n\r\n print(welcome)\r\n\r\n choice=int(input(\"ENTER 1, 2, 3 BASED ON YOUR NEED \\n\"))\r\n\r\n if choice == 1 :\r\n createTable()\r\n\r\n elif choice == 2 :\r\n actor=input(\"ENTER THE ACTOR NAME: \")\r\n actress=input(\"ENTER THE ACTRESS NAME: \")\r\n year=int(input(\"ENTER THE YEAR OF RELEASE: \"))\r\n director=input(\"ENTER THE DIRECTOR NAME: \")\r\n\r\n addMovie(actor,actress,year,director)\r\n\r\n elif choice == 3:\r\n\r\n query=input(\"TYPE THE QUERY IN CORRECT SYNTAX: \")\r\n retrieveMovieDetails(query)\r\n\r\n else:\r\n print(\"INVALID CHOICE\")\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n flag=\"y\"\r\n while(flag == \"y\"):\r\n main()\r\n flag=input(\"Do you wish to continue Y/N:\").lower()\r\n print(\"EXITING...\")\r\n","sub_path":"muleSoft.py","file_name":"muleSoft.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"89032018","text":"import requests, urllib.request, json\nfrom bs4 import BeautifulSoup\nfrom django.core.cache import cache\nfrom django.http import JsonResponse\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\nclass CurrencyConverter(APIView):\n \n def get(self,request):\n \"\"\"[converting currencies]\n\n Args:\n request ([GET]): [need to send from_currency, to_currency, amount]\n\n Returns:\n [Json]: [this api will return converted currency]\n \"\"\"\n from_currency = request.GET.get('from_currency')\n to_currency = request.GET.get('to_currency')\n amount = request.GET.get('amount')\n \n if not from_currency or not to_currency or not amount:\n return Response({'message':'from_currency, to_currency, amount are required'},status=400)\n \n url = f'https://free.currconv.com/api/v7/convert?q={from_currency}_{to_currency}&compact=ultra&callback=sampleCallback&apiKey=bc90e82d78f02e0aede1'\n \n response = json.loads(urllib.request.urlopen(url).read().decode(\"utf-8\").split('(')[-1].replace(')','').replace(';',''))\n \n converted_amount = float(amount)*response[f'{from_currency}_{to_currency}']\n \n return Response({\n 'from_currency':from_currency, \n 'to_currency':to_currency, \n 'amount':amount, \n 'converted_amount':converted_amount\n }, \n status=200\n )","sub_path":"converter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"252270581","text":"#!/usr/bin/python3.7\n\nfrom src.modules.nulsws_python.labels import Labels\n\n\nclass MakeMiddle(object):\n\n def make_middle_m(self, bottom_d, mid_section_vals=(1, 0, 0, 0, 0)): # return dict\n n = Labels.labs_field_d\n\n [rtyp, sevt, sper, srng, rmax] = [*mid_section_vals]\n\n req_middle_d = {\n n.get(\"msg_data_label\"): {\n n.get(\"request_type_label\"): rtyp,\n n.get(\"subscrip_evnt_ct_label\"): sevt,\n n.get(\"subscrip_period_label\"): sper,\n n.get(\"subscriptn_range_label\"): srng,\n n.get(\"response_max_size_label\"): rmax,\n n.get(\"req_methods_label\"): bottom_d\n }}\n return req_middle_d\n","sub_path":"src/modules/nulsws_python/make_middle.py","file_name":"make_middle.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"606490798","text":"#1\n'''Создать скрипт, который с помощью аргпарсера будет принимать ссылку,\nназвание файла для сохранения, параметр --to-file, который в случае наличия его в строке\nзаписывает в файл log.txt лог выполнения, иначе - пишет лог в консоль.\nСсылка и файл для сохранения - обязательные параметры (если они не переданы,\nдолжен выводиться help и сообщение, что чего-то не хватает). Если все хорошо -\nв файл записываетя контент страницы, которую нужно скачать по ссылке.'''\n\nimport argparse\nimport requests\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--link', required=True, help=\"Something don't write!\")\nparser.add_argument('--name', help='an integer for the accumulator')\nparser.add_argument('--to_file', required=True, action = 'store_true', help=\"Something don't write!\")\nargs = parser.parse_args()\n\nif args.to_file:\n ff = open('1.txt', 'r')\nelse:\n ff = sys.stdout()\n\n print('downloading', ff == file)\n\nr = requests.get('args.link')\nprint(r.text)\nwith open('args.name', 'w') as f:\n f.write(r.text)\n\nff.close()\n\n#2. http://httpbin.org/ - A simple HTTP Request & Response Service. Отправьте несколько запросов post, get.\n\nimport requests\n\nr = requests.get('http://httpbin.org/')\nprint(r.text)","sub_path":"module_reguests1.py","file_name":"module_reguests1.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"595789317","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n\"\"\"\nA simple tool to try optimizations on onnx graphs.\nThis makes use of the fact that tensorflow-onnx internal graph representation is onnx\nso all graph, rewrite, matching and utility libaries do work which makes things easy.\n\"\"\"\n\n# pylint: disable=invalid-name,missing-docstring, unused-argument\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport logging\nimport traceback\n\nimport numpy as np\nimport onnx\nfrom onnx import numpy_helper\n\nimport tf2onnx.utils\nfrom tf2onnx.graph import Graph\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(\"onnx-experiments\")\n\n\ndef get_args():\n \"\"\"Parse commandline.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input\", required=True, help=\"onnx input model file\")\n parser.add_argument(\"--output\", help=\"output model file\")\n args = parser.parse_args()\n return args\n\n\ndef load_graph(fname):\n with open(fname, \"rb\") as f:\n data = f.read()\n model_proto = onnx.ModelProto()\n model_proto.ParseFromString(data)\n onnx_nodes = model_proto.graph.node\n output_names = []\n\n # some pytorch model had empty names - make one up\n for node in onnx_nodes:\n if not node.name:\n node.name = tf2onnx.utils.make_name(\"was_empty\")\n\n g = Graph(onnx_nodes, output_shapes={}, dtypes={}, output_names=output_names)\n for i in model_proto.graph.initializer:\n v = numpy_helper.to_array(i)\n name = i.name\n g.initializers[name] = i\n dtype = i.data_type\n g.set_dtype(name, dtype)\n g.set_shape(name, v.shape)\n for i in model_proto.graph.input:\n name = i.name\n if name in g.initializers:\n # ignore if it is not a model input\n continue\n g.add_model_input(name, i)\n shape = [j.dim_value if hasattr(i.type.tensor_type, \"dim_value\") else -1\n for j in i.type.tensor_type.shape.dim]\n dtype = i.type.tensor_type.elem_type\n g.set_dtype(name, dtype)\n g.set_shape(name, shape)\n for i in model_proto.graph.output:\n name = i.name\n shape = [j.dim_value if hasattr(i.type.tensor_type, \"dim_value\") else -1\n for j in i.type.tensor_type.shape.dim]\n dtype = i.type.tensor_type.elem_type\n g.set_dtype(name, dtype)\n g.set_shape(name, shape)\n output_names.append(name)\n\n # TODO: this is a hack in case a output name does not follow tensorflow convention\n for node in g.get_nodes():\n for name in node.output:\n g._nodes_by_name[name] = node # pylint: disable=protected-access\n\n return g, model_proto.producer_name\n\n\ndef sample_rewrite(g, ops):\n return ops\n\n\ndef rewrite_constant_fold(g, ops):\n\n func_map = {\n \"Transpose\": not None,\n \"Unsqueeze\": not None,\n \"Slice\": not None,\n \"Add\": np.add,\n \"Cast\": np.cast,\n \"Mul\": np.multiply,\n \"Sqrt\": np.sqrt,\n \"Sub\": np.subtract,\n }\n\n # pylint: disable=too-many-nested-blocks\n keep_looking = True\n while keep_looking:\n keep_looking = False\n for idx, op in enumerate(ops):\n if op.is_deleted():\n continue\n\n inputs = []\n for node in op.inputs:\n if node and node.is_const():\n inputs.append(node.get_tensor())\n\n if inputs and len(op.input) == len(inputs):\n func = func_map.get(op.type)\n if func is None:\n log.info(\"can fold but don't know how, type=%s, name=%s\", op.type, op.name)\n continue\n try:\n log.info(\"folding node type=%s, name=%s\", op.type, op.name)\n if op.type == \"Cast\":\n dst = op.get_attr_int(\"to\")\n np_type = dst\n val = np.cast[np_type](*inputs)\n elif op.type == \"Transpose\":\n perm = op.get_attr(\"perm\").ints\n val = np.transpose(inputs[0], perm)\n elif op.type == \"Unsqueeze\":\n axis = op.get_attr_int(\"axis\")\n val = np.expand_dims(inputs[0], axis=axis)\n elif op.type == \"Slice\":\n axis = op.get_attr_int(\"axis\")\n if axis != 0:\n log.info(\"can fold slice with axis!=0, type=%s, name=%s\", op.type, op.name)\n continue\n starts = op.get_attr_int(\"starts\")\n ends = op.get_attr_int(\"ends\")\n if starts == 0 and ends == 0:\n val = inputs[0][starts:ends]\n else:\n val = inputs[0]\n else:\n val = func(*inputs)\n\n new_node_name = tf2onnx.utils.make_name(op.name)\n new_output_name = new_node_name\n old_output_name = op.output[0]\n old_node_name = op.name\n log.debug(\"create const node [%s] replacing [%s]\", new_node_name, old_node_name)\n ops[idx] = g.make_const(new_node_name, val)\n consumers = g.find_output_consumers(old_output_name)\n if consumers:\n for consumer in consumers:\n g.replace_input(consumer, old_output_name, new_output_name)\n for node in op.inputs:\n node.set_deleted()\n keep_looking = True\n except Exception as ex: # pylint: disable=broad-except\n tb = traceback.format_exc()\n log.info(\"exception: %s, details: %s\", ex, tb)\n # pylint: enable=too-many-nested-blocks\n return g.remove_deleted_nodes(ops)\n\n\ndef main():\n args = get_args()\n\n g, producer_name = load_graph(args.input)\n\n rewriters = [sample_rewrite,\n rewrite_constant_fold]\n ops = g.get_nodes()\n stats = g.dump_node_statistics()\n\n for rewrite in rewriters:\n ops = rewrite(g, ops)\n\n try:\n g.topological_sort(ops)\n except Exception as ex: # pylint: disable=broad-except,unused-variable\n log.error(\"graph has cycles, ignored ...\")\n\n model_proto = g.make_model(producer_name)\n\n print(\"before:\", stats)\n stats.subtract(g.dump_node_statistics())\n print(\"removed:\", stats)\n\n # write onnx graph\n if args.output:\n with open(args.output, \"wb\") as f:\n f.write(model_proto.SerializeToString())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/onnx-experiments.py","file_name":"onnx-experiments.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"610447560","text":"import os\nimport sys\nimport math\nimport socket\nimport helper\nimport L1\n\n\n# Test length of command line args for client\ndef testArgLength():\n if len(sys.argv) != 3:\n print(\"Must use 2 command line arguments for client, Exiting!\")\n sys.exit()\n\n\n# Test validity of arguments read in\ndef testArgs(sIP, inFile):\n sIP = helper.testIP(sIP)\n file = L1.testFile(inFile)\n return [sIP, file]\n\n\n# Main method\nif __name__ == '__main__':\n\n # Set port and buffer size\n port, buffSize = 25010, 1024\n\n # Parse all command line inputs, test them, then read data\n testArgLength()\n sIP, inFile = str(sys.argv[1]), str(sys.argv[2])\n sIP, file = testArgs(sIP, inFile)\n\n # Get file size and number of packets which need to be sent\n dirPath = os.getcwd()\n filePath = dirPath + \"/\" + inFile\n size = os.path.getsize(filePath)\n iterNum = math.ceil(size / buffSize)\n\n # Read 1024 bytes at a time from the file\n data = []\n for a in range(0, iterNum):\n data.append(file.read(buffSize))\n file.close()\n\n # Perform TCP socket programming for client side\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sInfo = (str(sIP), port)\n # sInfo = (socket.gethostname(), port)\n\n try:\n sock.connect(sInfo)\n print(\"Connection established. Sending File\\n\")\n for a in range(0, len(data)):\n message = str(data[a])[2:][:len(data[a])]\n print(\"Sending packet \" + str(a + 1) + \": \\\"{message}\\\"\".format(message=message))\n sock.send(data[a])\n servResp = sock.recv(buffSize)\n servResp = str(servResp)[2:][:len(servResp)]\n print(\"Received: \\\"{data}\\\"\".format(data=servResp))\n\n finally:\n print(\"Closing socket and connection\")\n sock.close()\n\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"259854784","text":"#Exercício: Números primos (algoritmo inteligente)\r\n#Revisão para os Testes\r\n\r\nimport math\r\n\r\ndef main():\r\n n = int(input(\"INFORME UM VALOR: \"))\r\n\r\n ehprimo = list (range(0,n+1))\r\n\r\n for i in range(2,n+1):\r\n ehprimo[i] = True\r\n\r\n limite = math.sqrt(n)\r\n\r\n j = 2\r\n\r\n while j <= int(limite):\r\n k = j*j\r\n while k <= n:\r\n ehprimo[k] = False\r\n k+=j\r\n j+=1\r\n\r\n l = 2\r\n while l<=n:\r\n if ehprimo[l] != False:\r\n print(l,end=\" \")\r\n l+=1\r\n\r\n print(\"\")\r\n\r\nmain()\r\n","sub_path":"03 Testes/01 Exercícios Revisão/02primo.py","file_name":"02primo.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"580904071","text":"from http.server import HTTPServer, BaseHTTPRequestHandler\r\nfrom io import BytesIO\r\nimport json\r\nimport psycopg2\r\nimport os\r\n\r\ndb_user = os.environ.get('DB_USER')\r\ndb_pass = os.environ.get('DB_PASSWORD')\r\n\r\ndef update_database(correct_json):\r\n\r\n con = psycopg2.connect(\r\n host='localhost',\r\n database='postgres',\r\n password=db_pass,\r\n port='5432',\r\n user=db_user)\r\n\r\n def track_exists():\r\n cur = con.cursor()\r\n insert_check_query = \"\"\"SELECT uuid FROM CallLog WHERE uuid = %s\"\"\"\r\n insert_id = [correct_json['UUID']]\r\n print(insert_id)\r\n cur.execute(insert_check_query, insert_id)\r\n\r\n truth = cur.fetchone()\r\n if truth is None:\r\n # print('didnt find')\r\n #Parametrized\r\n insert_query = \"\"\"insert into CallLog(UUID, CallStartTime, CallerID, Extension)\r\n VALUES (%s, %s, %s, %s)\"\"\"\r\n\r\n insert_tuple_1 = (correct_json['UUID'], correct_json['CallStartTime'], correct_json['CallerID'],\r\n correct_json['Extension'])\r\n\r\n cur.execute(insert_query, insert_tuple_1)\r\n\r\n con.commit()\r\n else:\r\n #add values or update Extension\r\n # print('found')\r\n if len(correct_json) > 9:\r\n insert_query2 = \"\"\"Update CallLog set CallEndTime=%s,\r\n Direction=%s,\r\n DialedNumber=%s,\r\n DestinationNumber=%s,\r\n Duration=%s,\r\n Billsec=%s,\r\n AnswerState=%s\r\n WHERE UUID = %s\"\"\"\r\n insert_tuple_2 = (correct_json['CallEndTime'], correct_json['Direction'], correct_json['DialedNumber'],\r\n correct_json['DestinationNumber'], correct_json['Duration'],\r\n correct_json['Billsec'], correct_json['AnswerState'], correct_json['UUID'])\r\n\r\n cur.execute(insert_query2, insert_tuple_2)\r\n\r\n con.commit()\r\n else:\r\n insert_query3 = \"\"\"Update CallLog set Extension = %s WHERE UUID = %s\"\"\"\r\n insert_tuple_3=(correct_json['Extension'], correct_json['UUID'])\r\n cur.execute(insert_query3,insert_tuple_3)\r\n\r\n con.commit()\r\n\r\n track_exists()\r\n\r\n con.close()\r\n\r\nclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):\r\n\r\n def do_POST(self):\r\n auth_key_db = os.environ.get('AUTH_KEY_DB')\r\n\r\n if(self.headers['Authenticator']) != auth_key_db:\r\n self.send_response(401)\r\n self.end_headers()\r\n response = BytesIO()\r\n response.write(b'This is POST request. ')\r\n response.write(b'Authentication failed, database is not updated')\r\n print('Authentication failed, database not updated')\r\n else:\r\n content_length = int(self.headers['Content-Length'])\r\n body = self.rfile.read(content_length)\r\n self.send_response(200)\r\n self.end_headers()\r\n response = BytesIO()\r\n response.write(b'This is POST request. ')\r\n response.write(b'Received: ')\r\n response.write(body)\r\n self.wfile.write(response.getvalue())\r\n\r\n #from bytes to string\r\n try:\r\n my_json = body.decode('utf-8')\r\n data = json.loads(my_json)\r\n print(data)\r\n except json.JSONDecodeError or ValueError:\r\n print('Json Decoding has failed')\r\n else:\r\n # call task function to update database with received json data\r\n update_database(correct_json=data)\r\n\r\nhttpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)\r\nhttpd.serve_forever()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"350686848","text":"from bs4 import BeautifulSoup as bs \nimport pandas as pd \nfrom splinter import Browser \nimport requests\nimport pymongo\nimport time\n\ndef scrape():\n executable_path = {'executable_path': '/Users/michaelduffner/chromedriver'}\n browser = Browser('chrome', **executable_path, headless=False)\n\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n\n html = browser.html \n soup = bs(html, 'html.parser')\n\n news_title = soup.find('div',class_ = \"content_title\").text\n news_p = soup.find('div',\"article_teaser_body\").text\n\n print(news_title)\n print(news_p)\n\n url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(url)\n browser.click_link_by_partial_text('FULL IMAGE')\n time.sleep(5)\n browser.click_link_by_partial_text('more info')\n html = browser.html\n soup = bs(html,'html.parser')\n\n image_url = soup.find('figure', class_='lede').a['href']\n featured_image_url = \"https://www.jpl.nasa.gov/\" + image_url\n\n print(featured_image_url)\n\n url = \"https://twitter.com/marswxreport?lang=en\"\n browser.visit(url)\n html = browser.html\n soup = bs(html,'html.parser')\n\n mars_weather = soup.find('p', class_ = \"js-tweet-text\").text\n\n print(mars_weather)\n\n url = \"http://space-facts.com/mars/\"\n\n fact_table = pd.read_html(url)\n fact_df = fact_table[0]\n fact_df = fact_df.rename(columns={0:\"Category\", 1:\"Value\"})\n fact_df = fact_df.set_index(\"Category\")\n fact_df\n\n hem = []\n\n url = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n\n browser.visit(url)\n\n html = browser.html\n soup = bs(html, 'html.parser')\n \n hemisphere = soup.findAll(\"div\", class_=\"description\")\n\n for x in hemisphere: \n name = x.a.h3.text\n print(name)\n browser.click_link_by_partial_text(name)\n time.sleep(3)\n browser.click_link_by_partial_text('Open')\n time.sleep(2)\n html = browser.html\n soup = bs(html, 'html.parser')\n img_src = soup.find('img', class_=\"wide-image\")['src']\n\n img_src_full = f\"https://astrogeology.usgs.gov\" + img_src\n print(img_src_full)\n name = name[:-9]\n info = {\"title\":name, \"img_url\":img_src_full}\n hem.append(info)\n print(hem)\n browser.click_link_by_partial_text('Close')\n time.sleep(3)\n browser.click_link_by_partial_text('Back')","sub_path":"Instructions/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"337190235","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@date: 2020/12/30 下午6:48\n@file: general_head_2d.py\n@author: zj\n@description: \n\"\"\"\nfrom abc import ABC\n\nimport torch\nimport torch.nn as nn\n\nfrom .. import registry\n\n\nclass GeneralHead3D(nn.Module, ABC):\n\n def __init__(self,\n feature_dims=2048,\n dropout_rate=0.,\n num_classes=1000\n ):\n \"\"\"\n AvgPool + Dropout + FC\n :param feature_dims: 输入特征维度\n :param dropout_rate: 随机失活概率\n :param num_classes: 类别数\n \"\"\"\n super(GeneralHead3D, self).__init__()\n\n self.pool = nn.AdaptiveAvgPool3d((1, 1, 1))\n self.dropout = nn.Dropout(p=dropout_rate)\n self.fc = nn.Linear(feature_dims, num_classes)\n\n self.init_weights()\n\n def init_weights(self):\n nn.init.normal_(self.fc.weight, 0, 0.01)\n nn.init.zeros_(self.fc.bias)\n\n def forward(self, x):\n x = self.pool(x)\n x = torch.flatten(x, 1)\n x = self.dropout(x)\n x = self.fc(x)\n\n return x\n\n\n@registry.HEAD.register('GeneralHead3D')\ndef build_general_head_3d(cfg):\n feature_dims = cfg.MODEL.HEAD.FEATURE_DIMS\n num_classes = cfg.MODEL.RECOGNIZER.PRETRAINED_NUM_CLASSES\n dropout_rate = cfg.MODEL.HEAD.DROPOUT_RATE\n\n return GeneralHead3D(feature_dims=feature_dims,\n num_classes=num_classes,\n dropout_rate=dropout_rate)\n","sub_path":"zcls/model/heads/general_head_3d.py","file_name":"general_head_3d.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"3271528","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n\n _, frame = cap.read()\n \n faceCascade = cv2.CascadeClassifier('..DATA/haarcascades/haarcascade_frontalface_default.xml')\n faceDetector = faceCascade.detectMultiScale(frame, minNeighbors = 15)\n \n for (x, y, w, h) in faceDetector:\n rectanglegFrame = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 4)\n \n cv2.imshow('Detected Image', frame)\n \n if len(tuple(faceDetector)) != 0:\n (faceX, faceY, w, h) = tuple(faceDetector[0])\n \n k = cv2.waitKey(1) & 0xff\n \n if k == 27 or k == ord('q'):\n break\n \ntrackWindow = (faceX, faceY, w, h)\n\nroi = frame[faceY:faceY+h, faceX:faceX+w]\n\nroiHsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\nroiHist = cv2.calcHist([roiHsv], [0], None, [180], [0, 180])\n\ncv2.normalize(roiHist, roiHist, 0, 255, cv2.NORM_MINMAX)\n\ntermCriteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)\n\nwhile True:\n \n _, framePrime = cap.read()\n\n hsv = cv2.cvtColor(framePrime, cv2.COLOR_BGR2HSV)\n \n dst = cv2.calcBackProject([hsv], [0], roiHist, [0, 180], 1)\n \n _, trackWindow = cv2.meanShift(dst, trackWindow, termCriteria)\n \n x, y, w, h = trackWindow\n \n rectangleFrame = cv2.rectangle(framePrime, (x, y), (x+w, y+h), (0, 255, 0), 4)\n cv2.imshow('Tracked Image', rectangleFrame)\n \n k = cv2.waitKey(1) & 0xff\n \n if k == 27 or k == ord('q'):\n break\n \ncap.release()\ncv2.destroyAllWindows()","sub_path":"Tracking/MeanShift.py","file_name":"MeanShift.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"312502272","text":"__author__ = 'dexter'\n\nfrom os import listdir, makedirs\nfrom os.path import isfile, isdir, join, abspath, dirname, exists, basename, splitext\nimport csv\nimport json\nfrom os import remove\nimport os\nimport sys\n\n# e_data persistence\n# This persistence system uses a local directory\n# has a structure of:\n#\n# e_sets\n# /e_set_name\n# /id_set_name.json\n#\n\ndef e_set_dir_name(e_set_name):\n current_directory = dirname(abspath(__file__))\n return join(current_directory, \"data\", e_set_name)\n\ndef e_data_dir_name():\n current_directory = dirname(abspath(__file__))\n return join(current_directory, \"data\")\n\ndef e_set_exists(e_set_name):\n return isdir(e_set_dir_path(e_set_name))\n\ndef e_set_dir_path(e_set_name):\n return join(e_data_dir_name(), e_set_name)\n\ndef get_e_set_names():\n return listdir(e_data_dir_name())\n\ndef get_id_set_file_names(e_set_name):\n path = e_set_dir_name(e_set_name)\n return listdir(path)\n\ndef ensure_e_set_dir(e_set_name):\n path = e_set_dir_path(e_set_name)\n if not e_set_exists(e_set_name):\n makedirs(path)\n return path\n\ndef save_id_set(e_set_name, id_set):\n e_set_dir = ensure_e_set_dir(e_set_name)\n filename = join(e_set_dir, id_set.name + \".json\")\n file = open(filename, \"w\")\n json.dump(id_set.to_dict(), file)\n file.close()\n\ndef save_e_set(e_set, e_set_name):\n for id_set_name, id_set in e_set.id_set_map:\n save_id_set(e_set_name, id_set)\n\ndef remove_id_set(e_set_name, id_set_name):\n e_set_dir = e_set_dir_name(e_set_name)\n filename = join(e_set_dir, id_set_name + \".json\")\n remove(filename)\n\ndef remove_all_id_sets(e_set_name):\n dirpath = e_set_dir_name(e_set_name)\n for filename in listdir(dirpath):\n path = join(dirpath, filename)\n remove(path)\n\ndef get_id_set_data(e_set_name, id_set_file_name):\n base = basename(id_set_file_name)\n name = splitext(base)[0]\n e_set_dir = e_set_dir_name(e_set_name)\n filename = join(e_set_dir, name + \".json\")\n if(isfile(filename)):\n file = open(filename, \"r\")\n data = json.load(file)\n file.close()\n return data\n else:\n return None\n\ndef save_id_set_dict(e_set_name, id_set_id, id_set_dict, alt_grp_path=None):\n e_set_dir = ensure_e_set_dir(e_set_name)\n filename = join(e_set_dir, id_set_id + \".json\")\n file = open(filename, \"w\")\n json.dump(id_set_dict, file)\n file.close()\n\n #===========================\n # Save GSEA file\n #===========================\n '''\n gseafilename = ''\n if alt_grp_path is not None:\n if not os.path.exists(alt_grp_path):\n os.makedirs(alt_grp_path)\n gseafilename = join(alt_grp_path, id_set_dict.get(\"name\") + \".grp\")\n else:\n if not os.path.exists(join(e_set_dir + '..','grp')):\n os.makedirs(join(e_set_dir + '..','grp'))\n gseafilename = join(e_set_dir + '..','grp', id_set_dict.get('name') + '.grp')\n gseafile = open(gseafilename, \"w\")\n if id_set_dict.get(\"ids\") is not None:\n for gene in id_set_dict.get(\"ids\"):\n gseafile.write(gene + \"\\n\")\n\n gseafile.close()\n '''\n\ndef get_e_set_configs(name=\"config\"):\n current_directory = dirname(abspath(__file__))\n filename = join(current_directory, \"e_service_configuration\", name + \".json\")\n file = open(filename, \"r\")\n data = json.load(file)\n file.close()\n return data\n\n\n# gene_report persistence\n\ndef gene_report_file_path(name):\n gene_report_dir = ensure_gene_report_dir()\n return join(gene_report_dir, name + \".txt\")\n\ndef ensure_gene_report_dir():\n current_directory = dirname(abspath(__file__))\n path = join(current_directory, \"gene_reports\")\n if not isdir(path):\n makedirs(path)\n return path\n\ndef gene_list_file_path(name):\n gene_list_dir = ensure_gene_list_dir()\n return join(gene_list_dir, name + \".txt\")\n\ndef ensure_gene_list_dir():\n current_directory = dirname(abspath(__file__))\n path = join(current_directory, \"gene_lists\")\n if not isdir(path):\n makedirs(path)\n return path\n\ndef save_gene_report(report, mode):\n if mode is 'tabular':\n path = gene_report_file_path(report.name)\n with open(path, 'w') as csvfile:\n fieldnames = report.fields\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore', dialect='excel-tab')\n writer.writeheader()\n for row in report.get_rows():\n writer.writerow(row)\n if mode is 'json':\n path = gene_list_file_path(report.name)\n with open(path, 'w') as file:\n file.write(json.dumps(report.get_network_summary(), indent=4))\n\n\n\n\n","sub_path":"webviewerwidgets/wgndexvestsummary/fake_persistence.py","file_name":"fake_persistence.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"333729869","text":"import csv\n\nfileName = \"demo_to_read.csv\"\nWRITE = \"w\"\nREAD = \"r\"\n#Open file\n# numberFile = open(fileName,READ)\n#Read all file contents\n# allFileContetnts = numberFile.read()\n# print(allFileContetnts)\n#Read first and secnd lines\n# firstLineContents = numberFile.readline()\n# print(firstLineContents)\n# secondLineContents = numberFile.readline()\n# print(secondLineContents)\n\n\nwith open(fileName,READ) as myCSVfile:\n dataFromFile = csv.reader(myCSVfile)\n\n for currentRow in dataFromFile:\n for currentWord in currentRow:\n print(currentWord)\n\n # print(currentRow)","sub_path":"WorkWithFileFolder/ReadTextFile.py","file_name":"ReadTextFile.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"562819290","text":"from django.shortcuts import render, redirect\nfrom Users.forms import CusUserCreation\nfrom profiles.forms import BusinessProForm, CustomerProForm, BusinessProfile, CustomerProfile\nfrom Users.models import CusUser\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom Recommend.models import Recommend\nfrom Clubsite.models import EventsPageModel,HomePageModel,TonightModel\nfrom Clubsite.forms import HomeForm,EventsForm,TonightForm\nfrom LiquorStore.models import LiquorHomePageModel, LiquorSalesModel\nfrom Cosmetics.models import CosmeticsHomePage,CosmeticsWork\nfrom FoodStore.models import FoodHomePageModel,FullMenuPageModel\nfrom Salon.models import SalonHomeModel,SalonPricesModel\n\n# Create your views here.\ndef HomeView(request):\n username = request.user.username\n CurrentUser = CusUser.objects.filter(username=username).first()\n return render(request, 'inside/home.html', {'currentuser': CurrentUser})\n\n@login_required\ndef BusinessProfilesView(request):\n return render(request, 'inside/My_businessprofile.html')\n\n@login_required\ndef CustomerProfilesView(request):\n return render(request, 'inside/My_customerprofile.html')\n\n\ndef signupView(request):\n if request.method == \"POST\":\n form = CusUserCreation(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request,'successfully signed up, you may login')\n return redirect('login')\n else:\n form = CusUserCreation()\n return render(request, 'Registration/signup.html', {'form': form})\n\n@login_required\ndef EditProfileView(request):\n\n pro= BusinessProfile.objects.get(user_id=request.user.id)\n if request.user.Account == \"Business\":\n if request.method == \"POST\":\n form = BusinessProForm(request.POST,request.FILES,instance=request.user.businesspro)\n if form.is_valid():\n form.instance.latitude = float(request.POST['lat'])\n form.instance.longitude = float(request.POST['long'])\n\n\n\n if pro.Complete == 0:\n\n if request.user.businesspro.type_of_business == \"Club\":\n homepage = HomePageModel()\n homepage.company_id = request.user.businesspro.id\n homepage.save()\n\n eventpage = EventsPageModel()\n eventpage.company_id = request.user.businesspro.id\n eventpage.save()\n\n tonight = TonightModel()\n tonight.company_id = request.user.businesspro.id\n tonight.save()\n\n elif request.user.businesspro.type_of_business == \"LiquorStore\":\n\n Liquorhome = LiquorHomePageModel()\n Liquorhome.company_id = request.user.businesspro.id\n Liquorhome.save()\n\n sales = LiquorSalesModel()\n sales.company_id = request.user.businesspro.id\n sales.save()\n\n elif request.user.businesspro.type_of_business == \"Cosmetics\":\n\n coshome = CosmeticsHomePage()\n coshome.company_id = request.user.businesspro.id\n coshome.save()\n\n coswork = CosmeticsWork()\n coswork.company_id = request.user.businesspro.id\n coswork.save()\n\n elif request.user.businesspro.type_of_business == \"Food\":\n\n foodhome = FoodHomePageModel()\n foodhome.company_id = request.user.businesspro.id\n foodhome.save()\n\n foodmenu = FullMenuPageModel()\n foodmenu.company_id = request.user.businesspro.id\n foodmenu.save()\n\n elif request.user.businesspro.type_of_business == \"Salon\":\n\n salonhome = SalonHomeModel()\n salonhome.company_id = request.user.businesspro.id\n salonhome.save()\n\n salonprices = SalonPricesModel()\n salonprices.company_id = request.user.businesspro.id\n salonprices.save()\n\n\n else:\n pass\n\n\n form.instance.Complete = 1\n form.save()\n\n\n messages.success(request, 'profile successfully updated')\n return redirect('BusinessPro')\n else:\n messages.warning(request, 'profile not updated')\n return redirect('BusinessPro')\n else:\n form = BusinessProForm(instance=request.user.businesspro)\n else:\n if request.method == \"POST\":\n form = CustomerProForm(request.POST,request.FILES,instance=request.user.customerpro)\n if form.is_valid():\n form.save()\n messages.success(request, 'profile successfully updated')\n return redirect('CustomerPro')\n else:\n messages.warning(request, 'profile not updated')\n return redirect('CustomerPro')\n else:\n form = CustomerProForm(instance=request.user.customerpro)\n\n\n\n\n return render(request, 'inside/editprofile.html', {'form': form,'pro':pro})\n\ndef CategoryMenu(request,cat):\n business_list = BusinessProfile.objects.filter(type_of_business = cat).order_by('-recommendations')\n business = Paginator(business_list,2)\n\n page = request.GET.get('page')\n businesses =business.get_page(page)\n\n return render(request,'inside/categoryMenu.html',{'type':cat,'businesses':businesses})\n\ndef SearchedView(request):\n\n location = request.GET['Location']\n bustype = request.GET['type']\n locationlist = location.split()\n province = locationlist[0]\n city = locationlist[-1]\n\n businesses = BusinessProfile.objects.filter(province=province).filter(city=city).filter(type_of_business=bustype).order_by('-recommendations')\n\n return render(request,'inside/searchedmenu.html',{'businesses':businesses})\n\n\ndef DetailPageView(request,tob,id):\n\n business = BusinessProfile.objects.filter(type_of_business=tob).filter(id=id).first()\n\n return render(request,'inside/detailspage.html',{'business':business})\n\n\ndef DirectionsView(request,tob,id):\n business = BusinessProfile.objects.filter(id=id).first()\n return render(request,'inside/directionspage.html',{'business':business})\n\ndef logoutview(request):\n return render(request,'Registration/logout.html')\n\n@login_required\ndef Dashboard(request,bizid):\n\n if request.user.id != bizid:\n messages.warning(request,\"you dont have access to this dashboard\")\n return redirect('home')\n\n else:\n buz = bizid\n businessId = BusinessProfile.objects.get(user_id=buz)\n recommended = Recommend.objects.filter(Recommended_company_id=buz)\n return render(request,'inside/dashboard.html',{'business':businessId,'recomandations':recommended})\n\ndef AboutPage(request):\n\n return render(request,'inside/about page.html')\n\n\ndef Editsite(request):\n\n if request.user.businesspro.type_of_business == \"Club\":\n return redirect('clubedithome')\n elif request.user.businesspro.type_of_business == \"LiquorStore\":\n return redirect('editliquorhome')\n elif request.user.businesspro.type_of_business == \"Cosmetics\":\n return redirect('cosmeticsedithome')\n elif request.user.businesspro.type_of_business == \"Food\":\n return redirect('Editfoodhome')\n elif request.user.businesspro.type_of_business == \"Salon\":\n return redirect('editsalonhome')\n\ndef VisitsiteView(request,typ,name):\n\n if typ == \"Club\":\n return redirect(\"clubhome\",name=name)\n elif typ == \"LiquorStore\":\n return redirect(\"liquorhome\",name=name)\n elif typ == \"Cosmetics\":\n return redirect(\"cosmeticshome\",name=name)\n elif typ == \"Food\":\n return redirect(\"foodhomepage\",name=name)\n elif typ == \"Salon\":\n return redirect(\"salonhomepage\",name=name)\n\ndef DomainView(request,typ,name):\n\n\n if typ == \"Club\":\n return redirect(\"clubhome\",name=name)\n elif typ == \"LiquorStore\":\n return redirect(\"liquorhome\",name=name)\n elif typ == \"Cosmetics\":\n return redirect(\"cosmeticshome\",name=name)\n elif typ == \"Food\":\n return redirect(\"foodhomepage\",name=name)\n elif typ == \"Salon\":\n return redirect(\"salonhomepage\",name=name)\n\ndef RecomendView(request):\n\n return render(request,'inside/recommend.html')\n\n\ndef NameSearchView(request):\n\n name = request.POST['business_name']\n bustype = request.POST['type']\n businesses = BusinessProfile.objects.filter(business_name__icontains=name).filter(type_of_business=bustype).order_by('-recommendations')\n\n return render(request,'inside/searchedmenu.html',{'businesses':businesses})\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Pages/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"44848162","text":"import os\nimport random\n'''Class for generating labels for test set '''\nclass Testing:\n\n def __init__(self,headtr,testdictf, prlabel = {}):\n \n self.dth = headtr \n #Preditced label, key is linenum, value is another dictionary. The inner dictionary has key as predicted value and value as number of times that the prediction happened in the past\n self.prlabel = prlabel\n self.ttdict = testdictf\n\n def parsetestfile(self):\n xp = 0\n \n for key, val in self.ttdict.items():\n xp = xp + 1 \n attval = val[1]\n node = self.dth\n #For each test case, traverse the tree until leaf node is reached\n while(node.type != 0): \n #Attribute is missing from test set, choose random child \n if node.attribute not in attval:\n #pick a random child\n rkey = random.choice(list(node.childnodes))\n nextnode = node.childnodes[rkey] \n #Attribute value in test set is unseen, choose random child\n elif attval[node.attribute] not in node.childnodes.keys():\n #pick a random child\n rkey = random.choice(list(node.childnodes))\n nextnode = node.childnodes[rkey] \n else:\n nextnode = node.childnodes[attval[node.attribute]]\n\n node = nextnode\n \n prlkdict = self.prlabel.get(key, dict())\n prlkdictval = prlkdict.get(node.label,0)\n prlkdict[node.label] = prlkdictval + 1 \n self.prlabel[key] = prlkdict \n\n return self.prlabel\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":"Testing.py","file_name":"Testing.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"569390709","text":"import cv2\r\nimport datetime\r\nimport os\r\nimport time\r\nimport numpy as np\r\nimport face_recognition\r\nimport face_rec.tracking as tracking\r\nfrom imutils import paths\r\nimport sqlite3 as sql\r\nimport io, errno\r\n\r\nfrom face_rec.mailer import Mailer\r\nfrom face_rec.database_handler import DatabaseHandler\r\nfrom face_rec.file_handler import FileHandler\r\nfrom face_rec.mqqt_handler import MqttHandler\r\n\r\nclass FaceHandler:\r\n resolutions = {\"vga\": [640, 480], \"qvga\": [320, 240], \"qqvga\": [160, 120], \"hd\": [1280, 720], \"fhd\": [1920, 1080]}\r\n font = cv2.FONT_HERSHEY_DUPLEX\r\n TIME_FORMAT = \"%Y_%m_%d__%H_%M_%S\"\r\n unknown_pic_folder_path = \"Static/unknown_pics\"\r\n\r\n def __init__(self,\r\n cascade_xml=\"haarcascade_frontalface_default.xml\",\r\n db_loc=\"facerecognition.db\",\r\n img_root=\"Images\"\r\n ):\r\n print(\"[INFO] FaceHandler init started\")\r\n self.database_location = db_loc\r\n self.settings = dict()\r\n self.load_settings_from_db()\r\n self.ct = tracking.CentroidTracker()\r\n cascade_path = os.path.dirname(os.path.realpath(__file__)) + \"/face_rec/\" + cascade_xml\r\n self.face_detector = cv2.CascadeClassifier(cascade_path)\r\n self.face_data = dict()\r\n self.unknown_face_data = dict()\r\n self.load_encodings_from_database()\r\n self.load_unknown_encodings_from_database()\r\n\r\n self.cam = cv2.VideoCapture(0)\r\n self.minW = 0.1 * self.cam.get(3)\r\n self.minH = 0.1 * self.cam.get(4)\r\n self.persons = dict()\r\n self.unknown_persons = dict()\r\n self.load_persons_from_database()\r\n self.load_unknown_persons_from_database()\r\n self.visible_persons = dict()\r\n self.prev_visible_persons = dict()\r\n self.id2name_dict = dict()\r\n self.cam_is_running = False\r\n\r\n self.db = DatabaseHandler(self.database_location)\r\n self.notification_settings = self.db.load_notification_settings()\r\n\r\n self.face_rec_settings = self.db.load_face_recognition_settings()\r\n\r\n self.mqtt = MqttHandler(self.database_location)\r\n self.mqtt.subscribe(self.notification_settings[\"topic\"])\r\n\r\n self.file = FileHandler(img_root)\r\n\r\n self.mail = Mailer(\"email@gmail.com\", \"emailpass\") # TODO\r\n self.mail.send_mail_cooldown_seconds = 120\r\n self.mail.last_mail_sent_date = None\r\n print(\"[INFO] FaceHandler init finished\")\r\n\r\n def load_settings_from_db(self):\r\n con = sql.connect(self.database_location)\r\n c = con.cursor()\r\n d = dict()\r\n for row in c.execute(\"SELECT * FROM face_recognition_settings\"):\r\n d[row[0]] = row[1]\r\n self.settings = d\r\n return d\r\n\r\n def load_encodings_from_database(self):\r\n conn = sql.connect(self.database_location)\r\n c = conn.cursor()\r\n names = list()\r\n encodings = list()\r\n for row in c.execute('SELECT * FROM encodings'):\r\n names.append(row[0])\r\n encodings.append(np.frombuffer(row[1]))\r\n self.face_data = {\"names\": names, \"encodings\": encodings}\r\n\r\n def load_unknown_encodings_from_database(self):\r\n conn = sql.connect(self.database_location)\r\n c = conn.cursor()\r\n names = list()\r\n encodings = list()\r\n for row in c.execute('SELECT * FROM unknown_encodings'):\r\n names.append(row[0])\r\n encodings.append(np.frombuffer(row[1]))\r\n self.unknown_face_data = {\"names\": names, \"encodings\": encodings}\r\n\r\n def load_persons_from_database(self):\r\n conn = sql.connect(self.database_location)\r\n c = conn.cursor()\r\n self.persons = dict()\r\n for row in c.execute('SELECT * FROM persons ORDER BY id'):\r\n encodings = list()\r\n for i, n in enumerate(self.face_data[\"names\"]):\r\n if n == row[1]:\r\n encodings.append(self.face_data[\"encodings\"][i])\r\n self.persons[row[1]] = Person(row[0], row[1], encodings, row[2], row[6])\r\n conn.close()\r\n\r\n def load_unknown_persons_from_database(self):\r\n conn = sql.connect(self.database_location)\r\n c = conn.cursor()\r\n for row in c.execute('SELECT * FROM recent_unknowns ORDER BY id'):\r\n encodings = list()\r\n for i, n in enumerate(self.unknown_face_data[\"names\"]):\r\n if n == row[1]:\r\n encodings.append(self.unknown_face_data[\"encodings\"][i])\r\n self.unknown_persons[row[1]] = Person(row[0], row[1], encodings, row[2])\r\n conn.close()\r\n\r\n def add_visible_person(self, name):\r\n if name[0:5] != \"_Unk_\":\r\n self.visible_persons[name] = self.persons[name]\r\n self.persons[name].is_visible = True\r\n else:\r\n try:\r\n self.visible_persons[name] = self.unknown_persons[name]\r\n except KeyError:\r\n print(\"[ERROR] KeyError in add_visible_person for key: \" + name + \"in dict: \" +\r\n str(self.unknown_persons.keys()))\r\n\r\n def remove_visible_person(self, name):\r\n del self.visible_persons[name]\r\n self.persons[name].is_visible = False\r\n\r\n def start_cam(self):\r\n if self.cam_is_running:\r\n return\r\n # try:\r\n self.cam = cv2.VideoCapture(int(self.settings[\"cam_id\"]))\r\n # except NameError:\r\n # self.cam = cv2.VideoCapture(int(self.settings[\"cam_id\"]))\r\n res = self.resolutions[self.settings[\"resolution\"]]\r\n self.cam.set(3, res[0]) # set video width\r\n self.cam.set(4, res[1]) # set video height\r\n self.minW = 0.1 * self.cam.get(3)\r\n self.minH = 0.1 * self.cam.get(4)\r\n self.cam_is_running = True\r\n\r\n def stop_cam(self):\r\n if self.cam_is_running:\r\n self.cam.release()\r\n self.cam_is_running = False\r\n\r\n def process_next_frame(self, use_dnn=False, show_preview=False, save_new_faces=False):\r\n \"\"\"\r\n If use_dnn is set, checks faces with a Neural Network, if not, then only detects the faces and tries to guess\r\n the owner by the positions on the previous frame. If the number of faces differs from the previous frame, or\r\n this is the first frame, than a NN scan always runs.\r\n\r\n It also:\r\n - keeps record of all the visible faces in the self.visible_faces\r\n - calls events when a person arrives, leaves\r\n\r\n :param save_new_faces: save a picture of the new face if parameter is true\r\n :param use_dnn: use more precise, more time consuming CNN method?\r\n :param show_preview: show pop-up preview?\r\n :return: the visible persons, the frame itself and the rectangles corresponding to the found faces\r\n \"\"\"\r\n start_t = time.time()\r\n ret, frame = self.cam.read()\r\n if self.settings[\"flip_cam\"] == \"on\":\r\n frame = cv2.flip(frame, -1)\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n\r\n face_rects = [(y, x + w, y + h, x) for (x, y, w, h) in self.detect_faces(gray)] # points from height and width\r\n\r\n # executing DNN face recognition on found faces\r\n if use_dnn or ((len(face_rects) != len(self.visible_persons)) and self.settings[\"force_dnn_on_new\"]):\r\n self.visible_persons = dict()\r\n found_names = self.recognize_faces(rgb, face_rects, frame, save_new_faces=save_new_faces)\r\n for name in found_names:\r\n if name != \"not a face\" : # and name[0:5] != \"_Unk_\"\r\n self.add_visible_person(name)\r\n\r\n centroid_objects = self.ct.update(face_rects, [pers.id for pers in self.visible_persons.values()])\r\n\r\n # drawing dots, rectangles and names on the frame\r\n if self.visible_persons:\r\n # drawing names\r\n for ((top, right, bottom, left), p) in zip(face_rects, self.visible_persons.values()):\r\n y = top - 15 if top - 15 > 15 else top + 15\r\n text = p.name\r\n if not text:\r\n text = self.persons[0].name\r\n cv2.putText(frame, text, (left, y), self.font, 0.4, (0, 255, 0), 2)\r\n # drawing rectangles\r\n for (top, right, bottom, left) in face_rects:\r\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)\r\n\r\n \"\"\"\r\n Checking for persons arrived, left by comparing the the visible persons list with the previous one\r\n The corresponding events are getting called here\r\n \"\"\"\r\n delta_arrived = {p.name: p for p in self.visible_persons.values() if p.name not in self.prev_visible_persons.keys()}\r\n if delta_arrived:\r\n self.on_known_face_enters(delta_arrived)\r\n\r\n delta_left = {p.name: p for p in self.prev_visible_persons.values() if p.name not in self.visible_persons.keys()}\r\n if delta_left:\r\n self.on_known_face_leaves(delta_left)\r\n\r\n self.prev_visible_persons = self.visible_persons\r\n\r\n # show preview, display FPS\r\n if show_preview:\r\n cv2.imshow('camera', frame)\r\n cv2.waitKey(25) & 0xff\r\n if use_dnn:\r\n print(\"DNN FPS: {:.4f}\".format(1/(time.time() - start_t)))\r\n return self.visible_persons, frame, face_rects # unknown_rects\r\n\r\n def detect_faces(self, gray):\r\n \"\"\"\r\n Detect faces with HOG from a grey image\r\n\r\n :param gray: grey image (numpy)\r\n :return: face rectangle (x, y, w, h)\r\n \"\"\"\r\n faces = self.face_detector.detectMultiScale(\r\n gray,\r\n scaleFactor=1.2,\r\n minNeighbors=5,\r\n minSize=(int(self.minW), int(self.minH)), )\r\n return faces # x, y, w, h\r\n\r\n def recognize_faces(self, rgb, face_rects, frame, save_new_faces=False):\r\n \"\"\"\r\n Make encodings from the found faces than check them against the stored encodings of known faces.\r\n 1st they are checked against known faces.\r\n 2nd if no match found check against recent unknowns\r\n 3rd if no match found check more precisely if it is a face or not\r\n if it is, add it to the recent unknowns\r\n\r\n Method: creates a 128d vector for every face and compares it to known vectors corresponding to known faces\r\n There's a name connected to every vector, if a match is found, the name gets +1pt\r\n Last, the name with the most points wins.\r\n\r\n :param rgb: numpy array corresponding to an RGB pic\r\n :param face_rects: rectangle coordinates for found faces\r\n :param frame: numpy array corresponding to the original BGR pic\r\n :return: a list for the found names\r\n \"\"\"\r\n face_encodings = face_recognition.face_encodings(rgb, face_rects)\r\n names = []\r\n # check every face\r\n for rect_count, e in enumerate(face_encodings):\r\n matches = face_recognition.compare_faces(\r\n self.face_data[\"encodings\"], e, tolerance=float(self.settings[\"dnn_tresh\"])\r\n )\r\n # if there was a match in knowns\r\n if True in matches:\r\n matched_indices = [i for (i, b) in enumerate(matches) if b]\r\n counts = {}\r\n\r\n for i in matched_indices:\r\n name = self.face_data[\"names\"][i]\r\n counts[name] = counts.get(name, 0) + 1\r\n else:\r\n name = max(counts, key=counts.get)\r\n names.append(name)\r\n # if no match found in knowns, check recent unknowns\r\n else:\r\n matches = face_recognition.compare_faces(\r\n self.unknown_face_data[\"encodings\"], e, tolerance=float(self.settings[\"dnn_tresh\"])\r\n )\r\n # if recent unknown\r\n if True in matches:\r\n\r\n matched_indices = [i for (i, b) in enumerate(matches) if b]\r\n counts = {}\r\n\r\n for i in matched_indices:\r\n try:\r\n name = self.unknown_face_data[\"names\"][i]\r\n counts[name] = counts.get(name, 0) + 1\r\n except IndexError:\r\n print(\"[ERROR] IndexError while recognizing previously seen unknown: \" +\r\n str(self.unknown_face_data[\"names\"]) + \" and index: \" + str(i))\r\n if counts:\r\n name = max(counts, key=counts.get)\r\n names.append(name)\r\n print(\"[INFO]Found a previously seen unknown: \" + name)\r\n self.on_unknown_face_found(name)\r\n name = name.replace(\"/\", \"_\").replace(\":\", \"_\")\r\n if save_new_faces:\r\n path = self.unknown_pic_folder_path + \"/\" + name\r\n self.take_cropped_pic(frame, face_rects[rect_count], path)\r\n # if nor in recent unknowns\r\n else:\r\n # overview HOG with CNN, is it really a face?\r\n if self.is_it_a_face(frame, face_rects[rect_count]):\r\n unk_name = self.next_unknown_name()\r\n self.save_unknown_encoding_to_db(unk_name, e)\r\n self.unknown_face_data[\"encodings\"].append(e)\r\n self.unknown_face_data[\"names\"].append(unk_name)\r\n con = sql.connect(self.database_location)\r\n c = con.cursor()\r\n c.execute(\"INSERT INTO recent_unknowns (name, first_seen) VALUES (?, ?)\", (unk_name, datetime.datetime.now()))\r\n con.commit()\r\n con.close()\r\n self.load_unknown_persons_from_database()\r\n print(\"[INFO]\" + unk_name + \" added to unknown database\")\r\n\r\n names.append(unk_name)\r\n self.on_unknown_face_found(unk_name)\r\n unk_name = unk_name.replace(\"/\", \"_\").replace(\":\", \"_\")\r\n path = self.unknown_pic_folder_path + \"/\" + unk_name\r\n self.take_cropped_pic(frame, face_rects[rect_count], path)\r\n else:\r\n names.append(\"not a face\") # to make correct indices\r\n print(\"[INFO] HOG method found a false positive or low quality face\")\r\n return names\r\n\r\n def is_it_a_face(self, img, r):\r\n if face_recognition.face_locations(img[r[0]:r[2], r[3]:r[1]], model='cnn'):\r\n return True\r\n return False\r\n\r\n def next_unknown_name(self):\r\n name = \"_Unk_\" + datetime.datetime.now().strftime(\"%m/%d_%H:%M:%S\")\r\n while name in self.unknown_face_data[\"names\"]:\r\n name = name + \"_\"\r\n return name\r\n\r\n def on_known_face_enters(self, persons):\r\n print(\"Entered: \" + str(persons.keys()))\r\n\r\n def on_known_face_leaves(self, persons):\r\n print(\"Left: \" + str(persons.keys()))\r\n\r\n def on_unknown_face_found(self, name):\r\n pass\r\n\r\n def gather_new_face_data(self, id):\r\n face_id = input('\\n enter user id end press ==> ')\r\n\r\n def save_unknown_encoding_to_db(self, name, encoding):\r\n con = sql.connect(self.database_location)\r\n c = con.cursor()\r\n c.execute('INSERT INTO unknown_encodings VALUES (?, ?, ?)', [name, encoding.tobytes(), datetime.datetime.now()])\r\n con.commit()\r\n con.close()\r\n\r\n def train_dnn(self, dataset=\"Static/dnn_data\"):\r\n if self.cam_is_running:\r\n self.stop_cam()\r\n print(\"[INFO] quantifying faces...\")\r\n con = sql.connect(self.database_location)\r\n con.row_factory = lambda cursor, row: row[0]\r\n c = con.cursor()\r\n c.execute(\"DELETE FROM encodings\")\r\n print(\"[INFO] Encodings table truncated\")\r\n\r\n image_paths = list(paths.list_images(dataset))\r\n\r\n # initialize the list of known encodings and known names\r\n known_encodings = []\r\n known_names = []\r\n for (i, image_path) in enumerate(image_paths):\r\n # extract the person name from the image path\r\n name = image_path.split(os.path.sep)[-2]\r\n print(\"[INFO] processing image {}/{} - {}\".format(i + 1, len(image_paths), name))\r\n\r\n image = cv2.imread(image_path)\r\n rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n\r\n boxes = face_recognition.face_locations(rgb, model=\"hog\")\r\n\r\n encodings = face_recognition.face_encodings(rgb, boxes)\r\n\r\n # loop over the encodings\r\n for encoding in encodings:\r\n # add each encoding + name to our set of known names and\r\n # encodings\r\n known_encodings.append(encoding)\r\n known_names.append(name)\r\n\r\n # dump the facial encodings + names to disk\r\n print(\"[INFO] Loading data into the DB...\")\r\n\r\n db_names = c.execute(\"SELECT name FROM persons\").fetchall()\r\n print(db_names)\r\n for n in known_names:\r\n if n not in db_names:\r\n print(\"[INFO] Inserting new name to DB: \" + n)\r\n c.execute(\"INSERT INTO persons (name) VALUES (?)\", (n,))\r\n db_names.append(n)\r\n\r\n for n, e in zip(known_names, known_encodings):\r\n c.execute('INSERT INTO encodings VALUES (?, ?)', [n, e.tobytes()])\r\n con.commit()\r\n self.reload_from_db()\r\n con.close()\r\n\r\n def reload_from_db(self):\r\n self.load_persons_from_database()\r\n self.load_unknown_persons_from_database()\r\n self.load_encodings_from_database()\r\n self.load_unknown_encodings_from_database()\r\n\r\n def move_to_sql(self):\r\n con = sql.connect(self.database_location)\r\n c = con.cursor()\r\n c.execute(\"\tDELETE FROM encodings\")\r\n for n, e in zip(self.face_data[\"names\"], self.face_data[\"encodings\"]):\r\n c.execute('INSERT INTO encodings VALUES (?, ?)', [n, e.tobytes()])\r\n con.commit()\r\n con.close()\r\n\r\n def take_cropped_pic(self, img, r, folder_path=\"Static/unknowns/\", name=None):\r\n if name is None:\r\n name = datetime.datetime.now().strftime(self.TIME_FORMAT)\r\n path = folder_path + \"/\" + name + '.png'\r\n try:\r\n os.makedirs(folder_path)\r\n except OSError as e:\r\n if e.errno != errno.EEXIST:\r\n raise\r\n cv2.imwrite(path, img[r[0]:r[2], r[3]:r[1]])\r\n print(\"[INFO] Picture taken: \" + path)\r\n\r\n\r\nclass Face:\r\n def __init__(self, rect):\r\n self.rect = rect\r\n self.person = Person(0, \"Unknown\", None)\r\n\r\n\r\nclass Person:\r\n def __init__(self, id, name, encodings, preference, thumbnail=None):\r\n self.id = id\r\n self.name = name\r\n self.encodings = encodings\r\n self.pref = preference\r\n self.is_visible = False\r\n self.thumbnail = thumbnail\r\n\r\n\r\nif __name__ == \"__main__\":\r\n fh = FaceHandler(\"haarcascade_frontalface_default.xml\")\r\n fh.start_cam()\r\n iter = 0\r\n while True:\r\n iter = iter + 1\r\n if iter >= 300:\r\n fh.detected_faces = fh.process_next_frame(True, True)\r\n iter = 0\r\n else:\r\n fh.detected_faces = fh.process_next_frame(False, True)\r\n\r\n k = cv2.waitKey(25) & 0xff # Press 'ESC' for exiting video\r\n if k == 27:\r\n break\r\n","sub_path":"FaceHandler.py","file_name":"FaceHandler.py","file_ext":"py","file_size_in_byte":19638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"511068982","text":"import adv.adv_test\nfrom core.advbase import *\nfrom slot.a import *\n#from slot.d import *\n\ndef module():\n return Nobunaga\n\nclass Nobunaga(Adv):\n a1 = ('a',0.2,'hit15')\n conf = {}\n conf['slot.a'] = RR()+Primal_Crisis()\n conf['acl'] = \"\"\"\n `s3, not this.s3_buff_on\n `s1\n `s2\n `fs, x=5\n \"\"\"\n\n def prerun(this):\n this.ba = 0\n \n def s1_proc(this, e):\n this.ba = 1\n\n def s2_proc(this, e):\n if this.ba == 1:\n this.ba = 0\n this.dmg_make('o_s1_boost',5.59)\n\n def fs_proc(this, e):\n if this.ba == 1:\n this.ba = 0\n this.dmg_make('o_s1_boost',5.59)\n\nif __name__ == '__main__':\n conf = {}\n adv.adv_test.test(module(), conf, verbose=-2, mass=0)\n","sub_path":"adv/nobunaga.py","file_name":"nobunaga.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"46746480","text":"import logging\nimport urllib.request\n\nclass SklItem:\n\t\"\"\"Skeleton Scene Item\"\"\"\n\tdef __init__(self,sceneId,timestamp,resourceURL):\n\t\tself.id = sceneId\n\t\tself.timestamp = timestamp\n\t\tself.processes = []\n\t\tself.resourceURL = resourceURL\n\n\tdef GetData(self):\n\t\tresponse = urllib.request.urlopen(self.resourceURL)\n\n\t\treadResponse = list(response.read())\n\n\t\treturn readResponse\n","sub_path":"SklItem.py","file_name":"SklItem.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"563474411","text":"import unittest\nimport sys\n\nfrom tornado.httputil import HTTPServerRequest\nfrom handler import MixinHandler\n\n\nclass TestMixinHandler(unittest.TestCase):\n\n def test_get_real_client_addr_without_nginx_config(self):\n handler = MixinHandler()\n handler.request = HTTPServerRequest(uri='/')\n self.assertIsNone(handler.get_real_client_addr())\n\n def test_get_real_client_addr_with_correct_nginx_config(self):\n handler = MixinHandler()\n handler.request = HTTPServerRequest(uri='/')\n\n ip = '127.0.0.1'\n handler.request.headers.add('X-Real-Ip', ip)\n handler.request.headers.add('X-Real-Port', '12345')\n self.assertEqual(handler.get_real_client_addr(), (ip, 12345))\n\n @unittest.skipIf(sys.version_info < (3,),\n reason='assertLogs not supported in Python 2')\n def test_get_real_client_addr_with_bad_nginx_config(self):\n handler = MixinHandler()\n handler.request = HTTPServerRequest(uri='/')\n\n ip = '127.0.0.1'\n handler.request.headers.add('X-Real-Ip', ip)\n with self.assertLogs() as cm:\n handler.get_real_client_addr()\n self.assertEqual(cm.output, ['WARNING:root:Bad nginx configuration.'])\n\n handler.request.headers.add('X-Real-Port', '12345x')\n with self.assertLogs() as cm:\n handler.get_real_client_addr()\n self.assertEqual(cm.output, ['WARNING:root:Bad nginx configuration.'])\n","sub_path":"tests/test_handler.py","file_name":"test_handler.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"613496088","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import views as auth_views\nfrom django.conf import settings\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\nimport datetime\nfrom memento_client import MementoClient\nimport requests\nfrom bs4 import BeautifulSoup\nfrom .models import URL\nfrom .forms import SearchForm\nfrom urllib import request as urllibreq\nimport json\nimport boto3\nfrom ratelimit.decorators import ratelimit\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom urlexpander.models import URL\nfrom urlexpander.serializers import URLSerializer\n\n# For phahtomjs cloud\napi_key = \"ak-53wg4-aq5mb-cahrf-t8s7s-ymzkq\"\n\n# Creates URL table and handles new URL creation\n@ratelimit(key=\"ip\", rate=\"10/m\", block=True)\n@login_required(login_url=\"/lab3/accounts/login/\")\ndef url_list(request):\n\tif request.method == \"POST\":\n\t\tform = SearchForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tnew_url = form.save(commit = False)\n\t\t\tnew_url.date = timezone.now()\n\t\t\t# Runs when URL is correct\n\t\t\ttry:\n\t\t\t\tresponse = requests.get(new_url)\n\t\t\t\tpage = BeautifulSoup(response.content, \"lxml\")\n\t\t\t\tif page.title is not None:\n\t\t\t\t\ttitle = page.title.string\n\t\t\t\telse:\n\t\t\t\t\ttitle = \"No Title Available\"\n\t\t\t\tnew_url.status = response.status_code\n\t\t\t\tnew_url.final_url = response.url\n\t\t\t\tnew_url.title = title\n\t\t\t\t# Wayback storing\n\t\t\t\tcurrent_date = datetime.datetime.now()\n\t\t\t\tmemento = MementoClient()\n\t\t\t\twayback_res = memento.get_memento_info(response.url, current_date).get(\"mementos\").get(\"closest\")\n\t\t\t\tnew_url.wayback = wayback_res.get(\"uri\")[0]\n\t\t\t\tif wayback_res.get(\"datetime\") is not None:\n\t\t\t\t\tnew_url.wayback_date = str(wayback_res.get(\"datetime\"))\n\t\t\t\telse:\n\t\t\t\t\tnew_url.wayback_date = str(current_date)\n\t\t\t\t# Picture archiving\n\t\t\t\t# Connecting to S3\n\t\t\t\ts3_connection = boto3.resource(\"s3\")\n\t\t\t\t# For image capture with PhahtomJS\n\t\t\t\tdata = json.dumps({\"url\":response.url, \"renderType\":\"jpeg\"}).encode(\"utf-8\")\n\t\t\t\theaders = {\"content-type\": \"application/json\"}\n\t\t\t\tapi_url = \"http://PhantomJScloud.com/api/browser/v2/\" + api_key + \"/\"\n\t\t\t\treq = urllibreq.Request(url=api_url, data=data, headers=headers)\n\t\t\t\tres = urllibreq.urlopen(req)\n\t\t\t\tresult = res.read()\n\t\t\t\t# Puts the generated image on S3\n\t\t\t\ts3_connection.Bucket(\"lab3pics\").put_object(Key=str(new_url.wayback_date) + \".jpg\", Body=result, ACL=\"public-read\", ContentType=\"image/jpeg\")\n\t\t\t\t# Generates a publicly accessible link to the image\n\t\t\t\tpic_url = \"http://s3.amazonaws.com/lab3pics/\" + str(new_url.wayback_date) + \".jpg\"\n\t\t\t\tnew_url.archive_link = pic_url\n\t\t\t# Sets up error message\n\t\t\texcept Exception as e:\n\t\t\t\tnew_url.status = \"None\"\n\t\t\t\tnew_url.final_url = \"Does not exist\"\n\t\t\t\tnew_url.title = \"This webpage does not exist\"\n\t\t\t\tnew_url.wayback = \"Not available\"\n\t\t\t\tnew_url.wayback_date = \"Not available\"\n\t\t\t\tnew_url.archive_link = \"Not available\"\n\t\t\t\t# Redirects to details page\n\t\t\tfinally:\n\t\t\t\tnew_url.save()\n\t\t\t\treturn redirect('url_detail', pk = new_url.pk)\n\telse:\n\t\turls = URL.objects.filter(date__lte = timezone.now()).order_by('-date')\n\t\tform = SearchForm\n\treturn render(request, 'urlexpander/url_list.html', {'urls': urls, 'form': SearchForm})\n\n# Sends information for the \"Detail\" page\n@ratelimit(key=\"ip\", rate=\"10/m\", block=True)\n@login_required(login_url=\"/lab3/accounts/login/\")\ndef url_detail(request, pk):\n\turl = get_object_or_404(URL, pk = pk)\n\treturn render(request, 'urlexpander/url_detail.html', {'url': url})\n\n# Handles the deletion of a URL from the list\n@ratelimit(key=\"ip\", rate=\"10/m\", block=True)\n@login_required(login_url=\"/lab3/accounts/login/\")\ndef delete_url(request, pk):\n\turl = get_object_or_404(URL, pk = pk)\n\turl_key = str(url.wayback_date) + \".jpg\"\n\t# Connection to S3 Bucket for pic storage\t\n\ts3_connection = boto3.client(\"s3\")\n\t# Check to see if the img exists in the bucket\n\ttry:\n\t\ts3_connection.get_object(Bucket=\"lab3pics\", Key=url_key)\n\t\texists = True\n\texcept:\n\t\texists = False\n\t# If the img exists within the bucket, delete it from S3\n\tif exists == True:\n\t\ts3_connection.delete_object(Bucket=\"lab3pics\", Key=url_key)\n\t# Remove the URL data from the database\n\turl.delete()\n\treturn\tHttpResponseRedirect('../')\n\n# Handles logging a user out\ndef logout_url(request):\n\tlogout(request)\n\treturn redirect('login')\n\n\"\"\" \n\nAPI Logic\n\n\"\"\"\n\n# GET a list of all current URLs or POST a new URL\n@ratelimit(key=\"ip\", rate=\"10/m\", block=True)\n@login_required(login_url=\"/lab3/accounts/login/\")\n@api_view(['GET', 'POST'])\ndef list_urls(request, format=None):\n\tif request.method == 'GET':\n\t\turls = URL.objects.all()\n\t\tserializer = URLSerializer(urls, many=True)\n\t\treturn Response(serializer.data)\n\telif request.method == 'POST':\n\t\tserializer = URLSerializer(data = request.data)\n\t\tif serializer.is_valid():\n\t\t\tserializer.save()\n\t\t\treturn Response(serializer.data, status = status.HTTP_201_CREATED)\n\telse:\n\t\treturn Response(status = status.HTTP_400_BAD_REQUEST)\n\n# GET a specific URL or DELETE a specific URL\n@ratelimit(key=\"ip\", rate=\"10/m\", block=True)\n@login_required(login_url=\"/lab3/accounts/login/\")\n@api_view(['GET', 'DELETE'])\ndef detail_url(request, pk, format=None):\n\ttry:\n\t\turl = URL.objects.get(pk = pk)\n\texcept URL.DoesNotExist:\n\t\treturn Response(status = status.HTTP_404_NOT_FOUND)\n\tif request.method == 'GET':\n\t\tserializer = URLSerializer(url)\n\t\treturn Response(serializer.data)\n\telif request.method == 'DELETE':\n\t\turl.delete()\n\t\treturn Response(status = status.HTTP_204_NO_CONTENT)\n\telse:\n\t\treturn Response(status = status.HTTP_400_BAD_REQUEST)\n","sub_path":"urlexpander/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"238374150","text":"from Poker_algorithm.EHS_compare import Analysis_class as An\nfrom Poker_algorithm.EHS_compare import compare_func as com\nimport random\n\n\nclass Forecaster():\n def __init__(self,my_cards,board_cards,simulate_times):\n self.my_cards = my_cards\n self.board_cards = board_cards\n self._type = [0]*10\n self.simulate_times = simulate_times\n a = self.HP()\n\n self.p_pot = a[0]\n self.n_pot = a[1]\n self.hand_strength = a[2]\n\n self.winning_p = self.hand_strength*(1-self.n_pot)+(1-self.hand_strength)*self.p_pot\n self.type = [x/self.simulate_times for x in self._type]\n\n def HP(self):\n cards = [_ for _ in range(52)]\n known_cards = self.my_cards + self.board_cards\n for _ in known_cards:\n cards.remove(_)\n hp = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # [ahead, tied, behind]\n hp_total = [0] * 3\n\n test = [0] * 3\n\n # enumerate all of the opponent hands\n for i in range(self.simulate_times):\n random.shuffle(cards)\n opp_cards = [cards[-1], cards[-2]]\n judge = com.Judgement(self.my_cards, opp_cards, self.board_cards)\n board_cards2 = self.board_cards + [cards[-3], cards[-4]]\n judge_2 = com.Judgement(self.my_cards, opp_cards, board_cards2)\n self._type[judge_2.type] += 1\n\n o = judge.status\n l = judge_2.status\n hp[o][l] += 1\n hp_total[judge.status] += 1\n test[l] += 1\n\n divis1 = (hp_total[2] + hp_total[1] / 2)\n divis2 = (hp_total[0] + hp_total[1] / 2)\n if divis1 != 0:\n p_pot = (hp[2][0] + hp[2][1] / 2 + hp[1][0] / 2) / divis1\n else:\n p_pot = 1\n if divis2 != 0:\n n_pot = (hp[0][2] + hp[1][2] / 2 + hp[0][1] / 2) / divis2\n else:\n n_pot = 1\n hand_strength = (hp_total[0] + hp_total[1] / 2) / sum(hp_total)\n for i in range(10):\n self._type[i] = self._type[i]/self.simulate_times\n return p_pot, n_pot, hand_strength, self._type\n\n","sub_path":"djangoProject/Poker_algorithm/MTC_BasedOn_EHS/Winning_p_forecast.py","file_name":"Winning_p_forecast.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"210238651","text":"from __future__ import print_function\nfrom bs4 import BeautifulSoup\nfrom urllib import urlopen\nimport pandas as pd\nimport multiprocessing\n\ndef grab_data(url):\n\ttry:\n\t\thtml_doc = urlopen(url).read()\n\t\t\t# connection might break and we need to restart, \n\t\t\t# need to come up with a way to support broken connection and continue from what we left behind\n\t\tsoup = BeautifulSoup(html_doc, \"html.parser\")\n\t\n\t\ttitle_num = soup.find(\"head\").find(\"title\").get_text().replace(\"Problem - \",\"\").replace(\" - Codeforces\", \"\")\n\t\t\n\t\tif title_num == \"Codeforces\":\n\t\t\treturn\n\t\tprint (title_num)\n\t\tps = soup.find('div', class_= \"problem-statement\")\n\n\t\ttitle = ps.find('div',class_= 'title').get_text()\n\n\t\ttime_limit = (ps.find('div', class_ = 'time-limit').get_text().split(\"test\",1)[1]).split()[0]\n\n\t\tmemory_limit = (ps.find('div', class_ = 'memory-limit').get_text().split(\"test\",1)[1]).split()[0]\n\n\t\tword = ps.find('div', class_=\"\").get_text()+\"\\n\"\n\n\t\tinput_spec = ps.find('div', class_ = \"input-specification\").get_text().split(\"Input\",1)[1]\n\t\toutput_spec = ps.find('div', class_ = \"output-specification\").get_text().split(\"Output\",1)[1]\n\n\t\tlabel = []\n\t\ttags = soup.find('div', id=\"sidebar\").find_all('span', class_=\"tag-box\")\n\t\tfor k in tags:\n\t\t\tlabel.append(k.get_text().replace(\"\\r\\n\", \"\").encode(\"utf-8\").replace(\" \",\"\"))\n\n\n\t\ttitle = title.split(\" \",1)[1]\n\t\tlabels = ', '.join(label)\n\t\tprint(labels)\n\t\tentry = {\"title-num\" :title_num, \"title\": title, \"time-limit\": time_limit, \"memory-limit\": memory_limit,\n\t\t\"word\":word, \"input-spec\": input_spec, \"output-spec\": output_spec, \"labels\": labels}\n\t\t\t\n\t\t\n\t\tdff = pd.DataFrame.from_dict(entry, orient='index')\n\t\treturn dff\n\texcept AttributeError:\n\t\tprint(\"error occured\")\n\t\treturn\n\nproblems = map(chr, range(65,80))\nID = list(range(1,910))\n\nheaders = ['title-num', 'title', 'time-limit','memory-limit', 'problem-statement', 'input-spec','output-spec', 'labels']\ndf = pd.DataFrame(columns=headers)\nurl = []\n\nfor i in ID:\n for j in problems:\n url.append(\"http://codeforces.com/problemset/problem/\"+str(i)+\"/\"+j)\n\npool = multiprocessing.Pool()\ndfs = pool.map(grab_data,url)\n\nfor i in dfs:\n\tdf.append(i)\n\ndf.to_csv(\"data.csv\")\n\n\n\n\n","sub_path":"predictor/data_grabbing/codeforces/codeForDownloadDataFromCodeFroces.py","file_name":"codeForDownloadDataFromCodeFroces.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"66257894","text":"fr = open(\"sequence.protein.gb\", \"r\")\nlines = fr.readlines()\nfr.close()\ns = []\nfor i in range(len(lines)):\n if lines[i].startswith(\"LOCUS\"):\n title = lines[i]\n elif lines[i].startswith(\"ORIGIN\"):\n for j in range(len(lines[i + 1 :])): # ORIGIN 다음 행부터 마지막 행까지 for문\n s.append(lines[i + 1 + j]) # s라는 list에 string 추가.\n seq = \"\".join(s) # list를 string으로.\nls = []\nresult = \"\"\nfor i in range(len(seq)):\n if seq[i].isalpha():\n ls.append(seq[i])\n result = \"\".join(ls)\nj = 0\nr = int(len(result) / 70) + 1\nfor i in range(r):\n print(result[j : j + 70])\n j += 70\n","sub_path":"bioinformatics_4_3.py","file_name":"bioinformatics_4_3.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"314950237","text":"from ...data_structures.linked_list.node import Node\n\n\nclass LinkedList(object):\n \"\"\"Instantiate a LinkedList.\"\"\"\n\n def __init__(self, iterable=None):\n self.head = None\n self.size = 0\n\n if iterable is None:\n iterable = []\n\n if type(iterable) is not list:\n raise TypeError('iterable must be a type of list')\n\n for val in iterable:\n self.insert(val)\n\n def __str__(self):\n output = f'Linked List Head val - { self.head }'\n return output\n\n def __repr__(self):\n output = f''\n return output\n\n def __len__(self):\n return self.size\n\n def insert(self, value):\n \"\"\"Insert values into a linked list.\"\"\"\n node = Node(value)\n node._next = self.head\n self.head = node\n # this line is the same as the three above it.\n # self.head - Node(value, self.head)\n self.size += 1\n\n def includes(self, value):\n \"\"\"Find method for linked list.\n\n Takes in a value as an argument and attempts to find that value in a ll\n \"\"\"\n current_node = self.head\n while current_node and current_node._next is not None:\n if current_node.val == value:\n return True\n current_node = current_node._next\n return False\n\n def insertBefore(self, value, newVal):\n \"\"\"Insert before a given value in a linked list.\"\"\"\n current_node = self.head\n previous_node = None\n while current_node:\n if current_node.val == value:\n if previous_node is None:\n self.insert(newVal)\n else:\n new_node = Node(newVal)\n new_node._next = current_node\n previous_node._next = new_node\n self.size += 1\n break\n previous_node = current_node\n current_node = current_node._next\n\n def insertAfter(self, value, newVal):\n \"\"\"Insert after a given value in a linked list.\"\"\"\n current_node = self.head\n while current_node:\n if current_node.val == value:\n position = current_node._next\n current_node._next = Node(newVal)\n current_node._next._next = position\n self.size += 1\n break\n current_node = current_node._next\n\n def append(self, value):\n \"\"\"Insert a value to the end of a linked list.\"\"\"\n if self.head is None:\n self.insert(value)\n else:\n current_node = self.head\n while current_node is not None:\n if current_node._next is None:\n current_node._next = Node(value)\n self.size += 1\n break\n current_node = current_node._next\n\n def kth_from_end(self, k):\n \"\"\"Find the value that is (k) from the end of the linked list class.\"\"\"\n if len(self) - k < 0:\n raise AttributeError\n\n current_node = self.head\n for i in range(len(self) - k - 1):\n current_node = current_node._next\n return current_node.val\n","sub_path":"challenges/ll_merge/ll_merge.py","file_name":"ll_merge.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"443092166","text":"# -*- coding: utf-8 -*-\nfrom django import template\nfrom django.template.defaultfilters import stringfilter\n\nregister = template.Library()\n\nlimited = [100]\nlimited_time = [200, 600]\n@register.filter(name='check_for_product_limited')\ndef check_for_product_limited(value):\n if int(value) in limited:\n return u'限量'\n elif int(value) in limited_time:\n return u'限时'\n else:\n return ''","sub_path":"website/product/templatetags/product_filters.py","file_name":"product_filters.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"626491866","text":"# import all libraries which are uses\nimport pygame\nimport random\nimport sys\nimport math\n\n# Define some colors\nBLACK = (20, 60, 20)\nWHITE = (255, 255, 255)\nGREEN = (0, 255, 0)\nYELLOW = (255, 255, 0)\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nfield1 = (105, 166, 52)\nfield2 = (105, 176, 52)\n\npygame.init()\n\n# Set the width and height of the screen [width, height]\nsize = (440, 445)\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption(\"ZMEKA\")\n\n\n#class GuideSettings():\n# def __init__(self, x, y, filename):\n# self.x = x\n# self.y = y\n# self.bitmap = pygame.image.load(filename).convert\n#\n# def page(self):\n# done = True\n# while done:\n# for event in pygame.event.get():\n# if event.type == pygame.QUIT:\n# done = False\n# elif event.type == pygame.KEYDOWN:\n# if event.key == pygame.K_ESCAPE:\n# sys.exit()\n# screen.blit(self.bitmap, (self.x, self.y))\n# pygame.display.flip()\n#\n#\n#guide = GuideSettings(0, 0, \"pictures/Main Menu/Control menu.png\")\n#guide.page()\n\n\n# --------- Creating main menu ---------\nclass Menu():\n def __init__(self, x, y, filename):\n self.x = x\n self.y = y\n self.bitmap = pygame.image.load(filename)\n self.done = True\n def menu(self):\n self.done = True\n # -- Pos button Start --\n # Left-up angle of Start\n start_pos = (120, 170)\n s_p_x = start_pos[0]\n s_p_y = start_pos[1]\n # Right-down angle of Start\n start_pos1 = (320, 210)\n s_p1_x = start_pos1[0]\n s_p1_y = start_pos1[1]\n # -- Pos button Quit --\n quit_pos = (120, 330)\n # Left-up angle of Quit\n q_p_x = quit_pos[0]\n q_p_y = quit_pos[1]\n quit_pos1 = (320, 371)\n # Right-down angle of Quit\n q_p1_x = quit_pos1[0]\n q_p1_y = quit_pos1[1]\n # -- pos button of Control --\n control = (120, 250)\n # Left-up angle of Control\n c_p_x = control[0]\n c_p_y = control[1]\n control1 = (320, 291)\n # Right-down angle of Control\n c_p1_x = control1[0]\n c_p1_y = control1[1]\n # ---- Main loop for main menu ----\n while self.done:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n done = False\n # Checer of mouse clicker\n if event.type == pygame.MOUSEBUTTONDOWN:\n # Detector of mouse pos\n pos = pygame.mouse.get_pos()\n posx = pos[0]\n posy = pos[1]\n # Check pos of mouse and button Start\n if s_p_x < posx < s_p1_x and s_p_y < posy < s_p1_y:\n done = False\n elif c_p_x < posx < c_p1_x and c_p_y < posy < c_p1_y:\n pass\n elif q_p_x < posx < q_p1_x and q_p_y < posy < q_p1_y:\n sys.exit()\n # Exit from the game when you press ESCAPE\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n sys.exit()\n # Start game when you press SPACE\n elif event.key == pygame.K_SPACE:\n self.done = False\n screen.blit(self.bitmap, (self.x, self.y))\n pygame.display.flip()\n\n\n# Creating main menu\nplunt = Menu(0, 0, \"pictures/Main Menu/main_menu.png\")\nplunt.menu()\n\n\n# Creating Snake\nclass Snake():\n # Adding pictures for changing picture by direction\n def __init__(self, image_pth):\n # x, y position head of snake\n self.head = [122, 202]\n # mass of x and y position of all body of snake\n self.body = [[122, 202], [102, 202], [82, 202]]\n # direction where snake goes\n self.direction = \"Right\"\n # sprite of snake\n self.image_pth = pygame.image.load(image_pth).convert()\n # mass for adding new part of body in the future\n self.segment = []\n self.Score = 0\n # variable for main loop\n self.done = False\n # x pos for food\n self.food_x = (random.randrange(0, 20) * 20) + 20\n # y pos for food\n self.food_y = (random.randrange(0, 20) * 20) + 20\n # wide for Blue line of WIN\n self.line_to_win = 1\n # detector for food, it won't spawn in snake\n self.detector = []\n # stoping time for few checks\n self.time_stop = True\n # variable for continuation or exit the game\n self.retry = \"\"\n\n def draw_head(self):\n pygame.draw.rect(screen, YELLOW, (self.head[0], self.head[1], 16, 16))\n\n # Control of head and by the way body\n def move(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.done = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RIGHT and self.direction != \"Left\":\n self.direction = \"Right\"\n elif event.key == pygame.K_LEFT and self.direction != \"Right\":\n self.direction = \"Left\"\n elif event.key == pygame.K_UP and self.direction != \"Down\":\n self.direction = \"Up\"\n elif event.key == pygame.K_DOWN and self.direction != \"Up\":\n self.direction = \"Down\"\n elif event.key == pygame.K_ESCAPE:\n self.time_stop = True\n plunt.done = True\n plunt.menu()\n # when you press SPACE game will start\n elif event.key == pygame.K_SPACE:\n self.time_stop = False\n\n elif event.key == pygame.K_r:\n self.head = [122, 202]\n self.body = [[122, 202], [102, 202], [82, 202]]\n self.direction = \"Right\"\n self.Score = 0\n self.food_x = (random.randrange(0, 20) * 20) + 20\n self.food_y = (random.randrange(0, 20) * 20) + 20\n self.retry = \"\"\n self.line_to_win = 1\n\n # detecting head and body crush\n def hit_body(self):\n if self.time_stop == False:\n for hit in self.body:\n if hit[0] == self.head[0] and hit[1] == self.head[1]:\n print(\"You lose!\")\n # Stoping time for check\n self.time_stop = True\n\n # detecting that food won't spawn in body\n def exclusion_stucking_food(self):\n for self.detector in self.body:\n if self.detector[0] == self.food_x + 2 and self.detector[1] == self.food_y + 2:\n self.food_x = (random.randrange(0, 20) * 20) + 20\n self.food_y = (random.randrange(0, 20) * 20) + 20\n\n # That is logic how snake goes on a field\n def logic_move(self):\n if self.time_stop == False:\n if self.direction == \"Right\":\n self.head[0] += 20\n if self.direction == \"Left\":\n self.head[0] -= 20\n if self.direction == \"Up\":\n self.head[1] -= 20\n if self.direction == \"Down\":\n self.head[1] += 20\n\n # That is logic where snake can't go\n def field_snake(self):\n if self.head[0] > 402:\n self.head[0] -= 20\n if self.head[0] < 22:\n self.head[0] += 20\n if self.head[1] > 402:\n self.head[1] -= 20\n if self.head[1] < 22:\n self.head[1] += 20\n\n # Changing sprites on snake depending on direction\n def sprites(self):\n if self.direction == \"Right\":\n screen.blit(head_right, (self.head[0], self.head[1]))\n if self.direction == \"Left\":\n screen.blit(head_left, (self.head[0], self.head[1]))\n if self.direction == \"Up\":\n screen.blit(head_up, (self.head[0], self.head[1]))\n if self.direction == \"Down\":\n screen.blit(head_down, (self.head[0], self.head[1]))\n\n # Every time when snake \"eat\" food: Change positions of food, Score + 1 and blue line up, +one body block\n def eating_food(self):\n if self.food_x < self.head[0] < self.food_x + 20 and self.food_y < self.head[1] < self.food_y + 20:\n self.food_x = (random.randrange(0, 20) * 20) + 20\n self.food_y = (random.randrange(0, 20) * 20) + 20\n # Score + 1\n self.Score += 1\n print(self.Score)\n # Random food everytime when snake get food\n self.body.append(self.body[0])\n self.line_to_win += 1\n\n def drawing_food(self):\n pygame.draw.rect(screen, RED, (self.food_x + 2, self.food_y + 2, 16, 16))\n\n # Logic that snake follow the head\n def animation(self):\n if self.time_stop == False:\n self.body.insert(0, list(self.head))\n self.body.pop()\n\n def draw_body(self):\n self.segment = []\n for segment in self.body:\n pygame.draw.rect(screen, YELLOW, pygame.Rect(segment[0], segment[1], 16, 16))\n\n\n# Creating snake\nsnake = Snake(\"pictures/Head/Head-right.png\")\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\nhead_right = pygame.image.load('pictures/Head/Head-right.png').convert()\nhead_left = pygame.image.load('pictures/Head/Head-left.png').convert()\nhead_up = pygame.image.load('pictures/Head/Head-up.png').convert()\nhead_down = pygame.image.load('pictures/Head/Head-down.png').convert()\n\n# -------- Main Program Loop -----------\nwhile not snake.done:\n # --- Main event loop and control\n snake.move()\n # --- Game logic should go here\n snake.logic_move()\n snake.field_snake()\n snake.hit_body()\n snake.exclusion_stucking_food()\n # --- Screen-clearing code goes here\n screen.fill(BLACK)\n\n # --- Drawing code should go here\n # Floop of field where snake goes\n # Actually i don't know how it's to explain but if you\n # interesting in this, look at the code down below =)(meme)\n row1 = [0, 0]\n for row in range(20):\n row1[0] += 20\n row1[1] = 20\n h = row1[0] / 2\n for column in range(20):\n pygame.draw.rect(screen, field2, (row1[0], row1[1], 20, 20))\n if math.fmod(row, 2) == 0:\n pygame.draw.rect(screen, field1, (row1[0], row1[1], 20, 20))\n if math.fmod(column, 2) == 1:\n pygame.draw.rect(screen, field1, (row1[0], row1[1], 20, 20))\n if math.fmod(row, 2) == 0 and math.fmod(column, 2) == 1:\n pygame.draw.rect(screen, field2, (row1[0], row1[1], 20, 20))\n row1[1] += 20\n # Body trucking head\n snake.animation()\n # Drawing Head of snake\n snake.draw_head()\n # Drawing body of snake\n snake.draw_body()\n # Drawing food\n snake.drawing_food()\n snake.eating_food()\n\n # \"LINE TO WIN\"\n pygame.draw.rect(screen, BLUE, (20, 425, snake.line_to_win, 15))\n # That is check when score goes 100+ points\n if snake.line_to_win > 100:\n print(\"You win!\")\n sys.exit()\n\n snake.sprites()\n\n pygame.display.flip()\n clock.tick(10)\npygame.quit()\n","sub_path":"Pygame/Projects/Snake from int/Zmeka.py","file_name":"Zmeka.py","file_ext":"py","file_size_in_byte":11268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"126957211","text":"#!/usr/bin/env python\n\n\"\"\"\n@package ion_functions.data.do2_functions\n@file ion_functions/data/do2_functions.py\n@author Stuart Pearce\n@brief Module containing Dissolved Oxygen family functions\n\"\"\"\nimport numpy as np\nimport pygsw.vectors as gsw\n\n\ndef do2_SVU(calphase, do_temp, csv):\n \"\"\"\n Description:\n\n Stern-Volmer-Uchida equation for calculating temperature\n corrected dissolved oxygen concentration. OOI L1 data product. \n\n\n Implemented by:\n\n 2013-04-26: Stuart Pearce. Initial Code.\n\n Usage:\n\n DO = do2_SVU(calphase, do_temp, csv)\n\n where\n\n DO = dissolved oxygen [micro-mole/L]\n calphase = calibrated phase from an Oxygen sensor [deg]\n (see DOCONCS DPS)\n do_temp = oxygen sensor temperature [deg C],\n (see DOCONCS DPS)\n csv = Stern-Volmer-Uchida Calibration Coefficients array.\n 7 element float array, (see DOCONCS DPS)\n\n Example:\n \n csv = np.array([0.002848, 0.000114, 1.51e-6, 70.42301, -0.10302,\n -12.9462, 1.265377])\n calphase = 27.799\n do_temp = 19.841\n \n DO = do2_SVU(calphase, do_temp, csv)\n print DO\n > 363.900534505\n\n References: \n \n OOI (2012). Data Product Specification for Oxygen Concentration\n from \"Stable\" Instruments. Document Control Number\n 1341-00520. https://alfresco.oceanobservatories.org/ (See:\n Company Home >> OOI >> Controlled >> 1000 System Level\n >> 1341-00520_Data_Product_SPEC_DOCONOCS_OOI.pdf)\n \"\"\"\n \n # Calculate DO using Stern-Volmer:\n Ksv = csv[0] + csv[1]*do_temp + csv[2]*(do_temp**2)\n P0 = csv[3] + csv[4]*do_temp\n Pc = csv[5] + csv[6]*calphase\n DO = ((P0/Pc) - 1) / Ksv\n return DO\n \n# TODO: the salinity correction is not finished. Ultimately it needs\n# TODO: two encapsulating-in-time CTD samples to be interpolated to O2\n# TODO: sample time. Waiting on Luke and Chris M. to determine how best\n# TODO: to do this. Note: the interpolation should be in another function\n# TODO: to accomodate the standalone DOSTA and CTDBP DOSTA.\ndef do2_salinity_correction(DO, do_t, P, T, SP, lat, lon, pref=0):\n \"\"\"\n Description:\n\n Salinity and pressure corrected dissolved oxygen concentration.\n OOI L2 data product DOCONCS.\n\n Implemented by:\n\n 2013-04-26: Stuart Pearce. Initial Code.\n\n Usage:\n\n DOc = do2_salinity_correction(DO,do_t,P,T,SP,lat,lon, pref=0)\n \n where\n \n DOc = corrected dissolved oxygen [micro-mole/kg].\n DO = uncorrected dissolved oxygen [micro-mole/L].\n do_t = Oxygen sensor temperature [deg C].\n P = PRESWAT water pressure [dbar]. (see\n 1341-00020_Data_Product_Spec_PRESWAT)\n T = TEMPWAT water temperature [deg C]. (see\n 1341-00010_Data_Product_Spec_TEMPWAT)\n SP = PRACSAL practical salinity [unitless]. (see\n 1341-00040_Data_Product_Spec_PRACSAL)\n lat, lon = latitude and longitude of the instrument [degrees].\n pref = pressure reference level for potential density [dbar].\n The default is 0 dbar.\n\n Example:\n DO = 433.88488978325478\n do_t = 1.97\n P = 5.4000000000000004\n T = 1.97\n SP = 33.716000000000001\n lat,lon = -52.82, 87.64\n \n DOc = do2_salinity_correction(DO,do_t,P,T,SP,lat,lon, pref=0)\n print DO\n > 335.967894709\n\n References: \n \n OOI (2012). Data Product Specification for Oxygen Concentration\n from \"Stable\" Instruments. Document Control Number\n 1341-00520. https://alfresco.oceanobservatories.org/ (See:\n Company Home >> OOI >> Controlled >> 1000 System Level\n >> 1341-00520_Data_Product_SPEC_DOCONOCS_OOI.pdf)\n \n \"\"\"\n \n # density calculation from GSW toolbox\n SA = gsw.sa_from_sp(SP, P, lon, lat)\n CT = gsw.ct_from_t(SA, T, P)\n pdens = gsw.rho(SA,CT,pref) # potential referenced to p=0\n \n # Convert from volume to mass units:\n DO = 1000*DO/pdens\n \n # Pressure correction:\n pcomp = 1 + (0.032*P)/1000\n DO = pcomp*DO\n \n # Salinity correction:\n S0 = 0\n ts = np.log((298.15-do_t)/(273.15+do_t))\n B = np.array([-6.24097e-3,\n -6.93498e-3,\n -6.90358e-3,\n -4.29155e-3])\n C0 = -3.11680e-7\n Bts = B[0] + B[1]*ts + B[2]*ts**2 + B[3]*ts**3\n scomp = np.exp((SP-S0)*Bts + C0*(SP**2-S0**2))\n DO = scomp*DO\n return DO","sub_path":"ion_functions/data/do2_functions.py","file_name":"do2_functions.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"297556893","text":"import tensorflow as tf\nimport imageio\nimport os\nimport numpy as np\nimport random\nfrom PIL import Image\nimport glob\nimport random\n# import scipy\n\ndef readimage(folder, index):\n path = os.path.join(folder, str(index)+'.png')\n image = imageio.imread(path)\n return image\n\ndef readmask(folder, index):\n path = os.path.join(folder, str(index)+'.png')\n image = imageio.imread(path)\n return image\n\ndef readnormal(folder, index):\n path = os.path.join(folder, str(index)+'.png')\n image = imageio.imread(path)\n return image\n\ndef normalize(x):\n # print(x.shape)\n res = np.zeros(x.shape)\n for i in range(3):\n max_val = np.max(x[:,:,i])\n min_val = np.min(x[:,:,i])\n res[:,:,i] = 1.0*(x[:,:,i] - min_val)/(max_val-min_val+1)\n return res\n\nbatch_size = 20\nsave_model_path = './best_model/surface_normal_est'\n\ntest_color = np.zeros(shape = (batch_size,128,128,3), dtype = 'float32')\ntest_mask = np.zeros(shape = (batch_size,128,128,3), dtype = 'float32')\n\n\n# build the graph\nloaded_graph = tf.Graph()\n\nwith tf.Session(graph=loaded_graph) as sess:\n\n\tloader = tf.train.import_meta_graph(save_model_path+'.meta')\n\tloader.restore(sess, save_model_path)\n\n\tloaded_x = loaded_graph.get_tensor_by_name('x:0')\n\tloaded_y = loaded_graph.get_tensor_by_name('y:0')\n\tloaded_z = loaded_graph.get_tensor_by_name('z:0')\n\t# loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n\tloaded_is_training = loaded_graph.get_tensor_by_name('is_training:0')\n\tloaded_output = loaded_graph.get_tensor_by_name('output:0')\n\n\tnum_test = len(glob.glob('./test/color/*.png'))\n\tbatches = num_test // batch_size\n\tfor i in range(batches):\n\t\tprint('{:d}/{:d}'.format(i,batches))\n\t\tfor j in range(batch_size):\n\t\t\t# print(j)\n\t\t\ttest_color[j,:,:,:] = readimage('./test/color',j + i*batch_size)\n\t\t\ttest_mask[j,:,:,0] = readmask('./test/mask', j + i*batch_size)\n\t\t\ttest_mask[j,:,:,1] = readmask('./test/mask', j + i*batch_size)\n\t\t\ttest_mask[j,:,:,2] = readmask('./test/mask', j + i*batch_size)\n\t\t\ttest_color[j,:,:,:] = normalize(test_color[j,:,:,:])\n\t\t\ttest_mask[j,:,:,:] = normalize(test_mask[j,:,:,:])\n\t\t\n\t\tpredictions = sess.run(loaded_output, feed_dict={loaded_x:test_color,loaded_y:test_mask,loaded_is_training:False})\n\t\t\n\t\tfor k in range(batch_size):\n\t\t\timage=Image.fromarray((255.0*predictions[k,:,:,:]).astype(np.uint8))\n\t\t\tprint(k+i*batch_size)\n\t\t\timage.save('./test/normal/'+str(k+i*batch_size)+'.png')","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"526148548","text":"'''THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND\nNON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE\nDISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,\nWHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.'''\n\n# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk\n# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB\n# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu\n# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd\n\n# contact :- github@jamessawyer.co.uk\n\n\n\n\"\"\"\nGiven a array of length n, max_subarray_sum() finds\nthe maximum of sum of contiguous sub-array using divide and conquer method.\n\nTime complexity : O(n log n)\n\nRef : INTRODUCTION TO ALGORITHMS THIRD EDITION\n(section : 4, sub-section : 4.1, page : 70)\n\n\"\"\"\n\n\ndef max_sum_from_start(array):\n \"\"\" This function finds the maximum contiguous sum of array from 0 index\n\n Parameters :\n array (list[int]) : given array\n\n Returns :\n max_sum (int) : maximum contiguous sum of array from 0 index\n\n \"\"\"\n array_sum = 0\n max_sum = float(\"-inf\")\n for num in array:\n array_sum += num\n if array_sum > max_sum:\n max_sum = array_sum\n return max_sum\n\n\ndef max_cross_array_sum(array, left, mid, right):\n \"\"\" This function finds the maximum contiguous sum of left and right arrays\n\n Parameters :\n array, left, mid, right (list[int], int, int, int)\n\n Returns :\n (int) : maximum of sum of contiguous sum of left and right arrays\n\n \"\"\"\n\n max_sum_of_left = max_sum_from_start(array[left: mid + 1][::-1])\n max_sum_of_right = max_sum_from_start(array[mid + 1: right + 1])\n return max_sum_of_left + max_sum_of_right\n\n\ndef max_subarray_sum(array, left, right):\n \"\"\" Maximum contiguous sub-array sum, using divide and conquer method\n\n Parameters :\n array, left, right (list[int], int, int) :\n given array, current left index and current right index\n\n Returns :\n int : maximum of sum of contiguous sub-array\n\n \"\"\"\n\n # base case: array has only one element\n if left == right:\n return array[right]\n\n # Recursion\n mid = (left + right) // 2\n left_half_sum = max_subarray_sum(array, left, mid)\n right_half_sum = max_subarray_sum(array, mid + 1, right)\n cross_sum = max_cross_array_sum(array, left, mid, right)\n return max(left_half_sum, right_half_sum, cross_sum)\n\n\narray = [-2, -5, 6, -2, -3, 1, 5, -6]\narray_length = len(array)\nprint(\"Maximum sum of contiguous subarray:\",\n max_subarray_sum(array, 0, array_length - 1))\n","sub_path":"divide_and_conquer/max_subarray_sum.py","file_name":"max_subarray_sum.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"180186883","text":"import bs4\r\nhtml_str = \"\"\"\r\n\r\n \r\n
      \r\n
    • hello
    • \r\n
    • bye
    • \r\n
    • welcome
    • \r\n
    \r\n \r\n\r\n\"\"\"\r\nbs_obj = bs4.BeautifulSoup(html_str, \"html.parser\")\r\n\r\nul = bs_obj.find(\"ul\")\r\nprint(ul)\r\n#
      \r\n#
    • hello
    • \r\n#
    • bye
    • \r\n#
    • welcome
    • \r\n#
    \r\n\r\nli = ul.find(\"li\")\r\nprint(li.text)\r\n# hello\r\n\r\nli = ul.find(\"li\")\r\nprint(li)\r\n#
  5. hello
  6. \r\n\r\nul = bs_obj.find(\"ul\")\r\nlis = ul.findAll(\"li\")\r\nprint(lis)\r\n#[
  7. hello
  8. ,
  9. bye
  10. ,
  11. welcome
  12. ]\r\n\r\nul = bs_obj.find(\"ul\")\r\nlis = ul.findAll(\"li\")\r\nprint(lis[1])\r\n#
  13. bye
  14. \r\n\r\nul = bs_obj.find(\"ul\")\r\nlis = ul.findAll(\"li\")\r\nprint(lis[2])\r\n#
  15. welcome
  16. \r\n\r\n\r\n","sub_path":"BeautifulSoup_2.py","file_name":"BeautifulSoup_2.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"565767032","text":"\"\"\" conroller for the example\n\"\"\"\n# pylint: disable=invalid-name\nimport os\nimport datetime\nimport pathlib\nimport numpy # pylint: disable=unused-import\nimport joblib\nimport super_batch\nfrom constants import (\n GLOBAL_CONFIG_FILE,\n WORKER_INPUTS_FILE,\n WORKER_OUTPUTS_FILE,\n LOCAL_INPUTS_PATTERN,\n LOCAL_OUTPUTS_PATTERN,\n)\n\n\n# --------------------------------------------------\n# CONSTANTS\n# --------------------------------------------------\n_TIMESTAMP: str = datetime.datetime.utcnow().strftime(\"%Y%m%d%H%M%S\")\nBATCH_DIRECTORY: str = os.path.expanduser(\"~/temp/super-batch-test\")\nNAME: str = \"superbatchtest\"\npathlib.Path(BATCH_DIRECTORY).mkdir(parents=True, exist_ok=True)\n\nbatch_client = super_batch.client(\n POOL_ID=NAME,\n JOB_ID=NAME + _TIMESTAMP,\n POOL_VM_SIZE=\"STANDARD_A1_v2\",\n POOL_NODE_COUNT=0,\n POOL_LOW_PRIORITY_NODE_COUNT=1,\n DELETE_POOL_WHEN_DONE=False,\n BLOB_CONTAINER_NAME=NAME,\n BATCH_DIRECTORY=BATCH_DIRECTORY,\n DOCKER_IMAGE=\"jdthorpe/super-batch-test-sum-of-powers:v1\",\n COMMAND_LINE=\"python /worker.py\",\n)\n\n\n# --------------------------------------------------\n# BUILD THE GLOBAL PARAMETER RESOURCE\n# --------------------------------------------------\nglobal_parameters = {\"power\": 3, \"size\": (10,)}\njoblib.dump(global_parameters, os.path.join(BATCH_DIRECTORY, GLOBAL_CONFIG_FILE))\nglobal_parameters_resource = batch_client.build_resource_file(\n GLOBAL_CONFIG_FILE, GLOBAL_CONFIG_FILE\n)\n\n# --------------------------------------------------\n# BUILD THE BATCH TASKS\n# --------------------------------------------------\n\nSEEDS = (1, 12, 123, 1234)\nfor i, seed in enumerate(SEEDS):\n # CREATE THE ITERATION PAREMTERS RESOURCE\n param_file = LOCAL_INPUTS_PATTERN.format(i)\n joblib.dump({\"seed\": seed}, os.path.join(BATCH_DIRECTORY, param_file))\n input_resource = batch_client.build_resource_file(param_file, WORKER_INPUTS_FILE)\n\n # CREATE AN OUTPUT RESOURCE\n output_resource = batch_client.build_output_file(\n WORKER_OUTPUTS_FILE, LOCAL_OUTPUTS_PATTERN.format(i)\n )\n\n # CREATE A TASK\n batch_client.add_task(\n [input_resource, global_parameters_resource], [output_resource]\n )\n\n# --------------------------------------------------\n# RUN THE BATCH JOB\n# --------------------------------------------------\nbatch_client.run()\n\n# --------------------------------------------------\n# AGGREGATE INTERMEDIATE STATISTICS\n# --------------------------------------------------\nout = [None] * len(SEEDS)\nfor i in range(len(SEEDS)):\n fpath = os.path.join(BATCH_DIRECTORY, LOCAL_OUTPUTS_PATTERN.format(i))\n out[i] = joblib.load(fpath)\n\nprint(sum(out))\n","sub_path":"test/sum-of-powers/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"376248897","text":"from django.shortcuts import render, redirect\nfrom .models import Post\nfrom .forms import PostForm, PostFormEdit\n\ndef index(request):\n data = {\n 'title': 'Лента новостей',\n 'user': 'temp_admin',\n 'posts': Post.objects.all()\n }\n return render(request, 'news/index.html', context=data)\n\ndef create(request):\n if request.method == \"GET\": \n data = {\n 'title': 'Добавление новости', \n 'form': PostForm()\n }\n return render(request, 'news/create.html', context=data)\n elif request.method == \"POST\":\n filled_form = PostForm(request.POST, request.FILES)\n filled_form.save()\n return redirect('/news') \n\ndef details(request, post_id):\n data = {\n 'title': 'Просмотр новости',\n 'post': Post.objects.get(id=post_id)\n }\n return render(request, 'news/details.html', context=data)\n\ndef edit(request, post_id):\n post = Post.objects.get(id=post_id)\n if request.method == \"GET\": \n data = {\n 'title': 'Редактирование новости',\n 'post': post,\n 'form': PostFormEdit(instance=post)\n }\n return render(request, 'news/edit.html', context=data)\n elif request.method == \"POST\":\n form = PostFormEdit(request.POST)\n if form.is_valid():\n post.title = form.cleaned_data['title']\n post.description = form.cleaned_data['description']\n post.content = form.cleaned_data['content']\n post.author = form.cleaned_data['author']\n post.source = form.cleaned_data['source']\n post.save() \n return redirect(\"/news\")\n\ndef delete(request, post_id):\n post = Post.objects.get(id=post_id)\n if request.method == \"GET\": \n data = {\n 'title': 'Удаление новости',\n 'post': post\n }\n return render(request, 'news/delete.html', context=data) \n else:\n post.delete()\n return redirect(\"/news\")","sub_path":"news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"537115666","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\nfrom gaebusiness.business import CommandExecutionException\nfrom tekton.gae.middleware.json_middleware import JsonResponse\nfrom emprestado_app import facade\n\n\ndef index():\n cmd = facade.list_emprestados_cmd()\n emprestado_list = cmd()\n short_form=facade.emprestado_short_form()\n emprestado_short = [short_form.fill_with_model(m) for m in emprestado_list]\n return JsonResponse(emprestado_short)\n\n\ndef save(**emprestado_properties):\n cmd = facade.save_emprestado_cmd(**emprestado_properties)\n return _save_or_update_json_response(cmd)\n\n\ndef update(emprestado_id, **emprestado_properties):\n cmd = facade.update_emprestado_cmd(emprestado_id, **emprestado_properties)\n return _save_or_update_json_response(cmd)\n\n\ndef delete(emprestado_id):\n facade.delete_emprestado_cmd(emprestado_id)()\n\n\ndef _save_or_update_json_response(cmd):\n try:\n emprestado = cmd()\n except CommandExecutionException:\n return JsonResponse({'errors': cmd.errors})\n short_form=facade.emprestado_short_form()\n return JsonResponse(short_form.fill_with_model(emprestado))\n\n","sub_path":"tekton/backend/appengine/routes/emprestados/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"363680385","text":"#! /usr/bin/env python3\n#\n# Copyright (C) 2018 Fx Bricks Inc.\n# This file is part of the legocad python module.\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge,\n# publish, distribute, sublicense, and/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# Crossing LEGO Track class\n\nimport math\nfrom math import sin, cos, radians, sqrt, atan\nimport cairo\nimport gi\ngi.require_version(\"Pango\", \"1.0\")\ngi.require_version(\"PangoCairo\", \"1.0\")\nfrom gi.repository import Pango\nfrom gi.repository import PangoCairo\n\nfrom .track import Track\n\nclass CrossingTrack(Track):\n\n def __init__ (self):\n super().__init__()\n self.length = 16\n self.length2 = 16\n self.angle = 90\n\n def __str__(self):\n print(\"Crossing Track, %f deg, length %f\" % (self.angle, self.length))\n\n def to_xml(self, fn):\n self.ComputeBBConnections()\n self.part.to_xml(fn)\n\n def ComputeExtents(self):\n ox, oy = GetBoundingRect(self.length2, self.metrics.width, self.angle)\n if ox > self.length:\n self.dvx = ox - self.length\n else:\n self.dvx = 0.0\n if oy > self.metrics.width:\n self.dvy = oy - self.metrics.width\n else:\n self.dvx = 0.0\n sw = self.length + self.dvx\n sh = self.metrics.width + self.dvy\n self.metrics.studRect.set_size(sw, sh)\n self.metrics.pixRect.set_size(sw * BB_SCALE, sh * BB_SCALE)\n\n def ComputeBBConnections(self):\n self.ComputeExtents()\n self.part.conn_points = []\n\n # first (left) connection\n bbc = BBConnexion()\n bbc.position_x = -self.metrics.studRect.width/2 + self.dvx/2\n bbc.position_y = 0.0\n bbc.angle = 180\n bbc.angleToPrev = 180\n bbc.angleToNext = 0\n bbc.connPref = 1\n bbc.electricPlug = 1\n self.part.conn_points.append(bbc)\n\n # second (right) connection\n bbc2 = BBConnexion()\n bbc2.position_x = self.metrics.studRect.width/2 - self.dvx/2\n bbc2.position_y = 0.0\n bbc2.angle = 0\n bbc2.angleToPrev = 0\n bbc2.angleToNext = 180\n bbc2.connPref = 0\n bbc2.electricPlug = -1\n self.part.conn_points.append(bbc2)\n\n # diverging route connection left\n bbc3 = BBConnexion()\n bbc3.position_x = self.length2/2 * cos(radians(-self.angle))\n bbc3.position_y = -self.length2/2 * sin(radians(-self.angle))\n bbc3.angle = self.angle\n bbc3.angleToPrev = -self.angle\n bbc3.angleToNext = 180.0 - abs(self.angle)\n bbc3.connPref = 0\n bbc3.electricPlug = 1\n self.part.conn_points.append(bbc3)\n\n # diverging route connection left\n bbc4 = BBConnexion()\n bbc4.position_x = -self.length2/2 * cos(radians(self.angle))\n bbc4.position_y = -self.length2/2 * sin(radians(self.angle))\n bbc4.angle = -180 + self.angle\n bbc4.angleToPrev = 180 - self.angle\n bbc4.angleToNext = 180.0 - abs(self.angle)\n bbc4.connPref = 0\n bbc4.electricPlug = -1\n self.part.conn_points.append(bbc4)\n\n def WritePNG(self, filename):\n\n self.ComputeExtents()\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(self.metrics.pixRect.width), int(self.metrics.pixRect.height))\n ctx = cairo.Context(surface)\n ctx.scale(BB_SCALE, BB_SCALE)\n\n if self.label == \"\":\n label = \"X\" + str(self.length)\n else:\n label = self.label\n label_text = PangoCairo.create_layout(ctx)\n label_text.set_text(label, -1)\n label_text.set_font_description(self.style.font_desc_normal())\n\n ctx.translate(self.metrics.studRect.width/2, self.metrics.studRect.height/2)\n xl = -self.length/2\n xr = xl + self.length\n xl2 = -self.length2/2\n xr2 = xl2 + self.length2\n yt = -self.metrics.width/2\n yb = self.metrics.width/2\n gt = -self.metrics.gauge/2\n gb = self.metrics.gauge/2\n\n # track rectangle\n ctx.set_line_width(0)\n ctx.move_to(xl, yt)\n ctx.line_to(xr, yt)\n ctx.line_to(xr, yb)\n ctx.line_to(xl, yb)\n ctx.close_path()\n self.style.FillColor(ctx)\n ctx.set_line_width(0)\n ctx.fill_preserve()\n ctx.stroke()\n\n ctx.save()\n ctx.rotate(radians(self.angle))\n ctx.move_to(xl2, yt)\n ctx.line_to(xr2, yt)\n ctx.line_to(xr2, yb)\n ctx.line_to(xl2, yb)\n ctx.close_path()\n self.style.FillColor(ctx)\n ctx.set_line_width(0)\n ctx.fill_preserve()\n ctx.stroke()\n ctx.restore()\n\n # rails\n self.style.RailColor(ctx)\n ctx.set_line_width(self.style.rail_width)\n ctx.move_to(xr, gt)\n ctx.line_to(xl, gt)\n ctx.move_to(xl, gb)\n ctx.line_to(xr, gb)\n ctx.stroke()\n\n ctx.save()\n ctx.set_line_width(self.style.rail_width)\n self.style.RailColor(ctx)\n ctx.rotate(radians(self.angle))\n ctx.move_to(xr2, gt)\n ctx.line_to(xl2, gt)\n ctx.move_to(xl2, gb)\n ctx.line_to(xr2, gb)\n ctx.restore()\n ctx.stroke()\n\n # end caps\n cw = self.style.cap_width\n self.style.CapColor(ctx)\n ctx.set_line_width(cw)\n ctx.move_to(xl, yt)\n ctx.line_to(xl, yb)\n ctx.move_to(xr, yt)\n ctx.line_to(xr, yb)\n ctx.stroke()\n\n ctx.save()\n ctx.rotate(radians(self.angle))\n self.style.CapColor(ctx)\n ctx.set_line_width(cw)\n ctx.move_to(xl2, yt)\n ctx.line_to(xl2, yb)\n ctx.move_to(xr2, yt)\n ctx.line_to(xr2, yb)\n ctx.restore()\n ctx.stroke()\n\n # label\n ctx.set_line_width(0)\n self.style.TextColor(ctx)\n ctx.save()\n ctx.move_to(0, 0)\n PangoCairo.update_layout(ctx, label_text)\n width, height = label_text.get_size()\n fw = float(width)/1024.0\n fh = float(height)/1024.0\n ctx.move_to(-fw/2, -fh/2)\n PangoCairo.update_layout(ctx, label_text)\n PangoCairo.show_layout(ctx, label_text)\n ctx.restore()\n\n surface.write_to_png(filename)\n","sub_path":"src/pybb/track_crossing.py","file_name":"track_crossing.py","file_ext":"py","file_size_in_byte":7095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"230749396","text":"from io import StringIO\nfrom textwrap import dedent\nfrom unittest import TestCase\n\nfrom cycy.interpreter import CyCy\nfrom cycy.parser.core import IncrementalParser\nfrom cycy.repl import REPL\n\n\nclass TestREPL(TestCase):\n def setUp(self):\n self.repl = REPL(\n interpreter=CyCy(\n parser=IncrementalParser(),\n stdin=StringIO(),\n stdout=StringIO(),\n stderr=StringIO(),\n )\n )\n\n def test_it_handles_errors(self):\n self.repl.interpret(\"asdf\\n\")\n self.assertEqual(\n self.repl.stdout.getvalue(), dedent(\n \"\"\"\\\n ParseError\n ----------\n\n asdf\n ^\n Unexpected IDENTIFIER 'asdf' at line 1, column 1\n \"\"\"\n ),\n )\n\n def test_it_buffers_incremental_input(self):\n self.repl.interpret(\"int main(void) {\\n\")\n self.repl.interpret(\"return 2;\\n\")\n self.repl.interpret(\"}\\n\")\n self.assertEqual(self.repl.stdout.getvalue(), \"2\")\n\n # and then gets rid of the buffer\n self.repl.interpret(\"int main(void) { return 3; }\\n\")\n self.assertEqual(self.repl.stdout.getvalue(), \"23\")\n","sub_path":"cycy/tests/test_repl.py","file_name":"test_repl.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"550729530","text":"# 책 풀이\nfrom typing import List\nimport collections\n\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n dict = collections.defaultdict(list) # list가 뭐지?\n for word in strs:\n dict[''.join(sorted(word))].append(word)\n return dict.values()\n\nsol = Solution()\nstrs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\nsol.groupAnagrams(strs)\n","sub_path":"algorithm/python_algorithm_interview_00/05_49.py","file_name":"05_49.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"421080341","text":"import h5py\nimport numpy as np\n\n\ndef h5read(fpath):\n rs = []\n h5 = h5py.File(fpath, 'r')\n for key in h5.keys():\n rs.append((key, np.array(h5.get(key))))\n h5.close()\n return rs\n\n\ndef h5write(fpath, keys, vals):\n h5 = h5py.File(fpath, 'w')\n for key, val in zip(keys, vals):\n h5[key] = np.array(val)\n h5.close()\n return fpath\n\n\ndef h5info(fpath):\n rs = []\n h5 = h5py.File(fpath, 'r')\n for key in h5.keys():\n rs.append((key, np.array(h5.get(key)).shape))\n h5.close()\n return rs","sub_path":"pyhej/data/io/h5.py","file_name":"h5.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"65579882","text":"def srednya_otcenka () :\n # Группа из 10 студентов сдала экзамен.\n # В вашем распоряжении имеются оценки (целые числа в диапазоне от 0 до 100),\n # полученные студентами на этом экзамене.\n # Определите среднюю оценку за экзамен для группы.\n\n # Входные данные:\n # 1. 10 оценок;\n # 2. Оценки известны пользователю;\n # 3. Оценки - целые числа в диапазоне от 0 до 100;\n # 4. Оценки вводятся с клавиатуры.\n\n # Основая цель программы:\n # Найти среднюю оценку группы за экзамен.\n\n # Промежуточные цели:\n # 1. Ввод данных; [x]\n # 2. Проверка на правильность ввода; [x]\n # 3. Организация алгоритма вычисления; [x]\n # 4. Вывод информации на экран; [x]\n # a. UI. [x]\n\n result = 0\n count = 0\n while count < 10 :\n while True :\n try :\n print(\"Введите\", count + 1, \"оценку:\", end=' ')\n mark = int(input())\n if mark >= 0 and mark <= 100 :\n break\n print(\"Вы ввели какую-то не ту оценку\")\n except ValueError :\n print(\"Вы ввели какую-то дичь.\")\n result = result + mark\n count = count + 1\n result = result / 10\n print(\"Средняя оценка за экзамен:\", result)\ndef look_theBiggest_call ():\n #С клавиатуры вводится натуральное число. Найти его наибольшую цифру.\n\n # Входные данные:\n # 1. 1 натуральное число;\n # 2. число известно пользователю;\n # 3. число вводится с клавиатуры.\n\n # Основая цель программы:\n # Найти наибольшую цифру числа.\n\n # Промежуточные цели:\n # 1. Ввод данных; []\n # 2. Проверка на правильность ввода; []\n # 3. Организация алгоритма вычисления; []\n # 4. Вывод информации на экран; []\n # a. UI. []\n\n result = \"\"\n otvet=0\n while True :\n try :\n print(\"Введите число :\")\n mark = int(input())\n if mark >= 0 :\n break\n print(\"Вы ввели какую-то не ту оценку\")\n except ValueError :\n print(\"Вы ввели какую-то дичь.\")\n result += str(mark)\n for i in result :\n if otvet value2):\n value1=value1-value2\n value2=0\n pos_dict.update({key1:value1})\n elif (value2>value1):\n value2=value2-value1\n value1=0\n neg_dict.update({key2:value2})\n\ntagged_neg_dict=[]\ntagged_pos_dict=[]\ntagged_neg_dict_list=[]\ntagged_pos_dict_list=[]\n\n\ntagged_pos_dict.append(nltk.pos_tag(pos_dict.keys()))\nfor i in range(len(tagged_pos_dict[0])):\n if tagged_pos_dict[0][i][1]==\"JJ\":\n tagged_pos_dict_list.append(tagged_pos_dict[0][i][0])\n \ntagged_neg_dict.append(nltk.pos_tag(neg_dict.keys()))\nfor i in range(len(tagged_neg_dict[0])):\n if tagged_neg_dict[0][i][1]==\"JJ\":\n tagged_neg_dict_list.append((tagged_neg_dict[0][i][0]))\n\n\npos_dict_updated={}\nneg_dict_updated={}\n\nfor key1, value1 in pos_dict.items():\n for i in range(len(tagged_pos_dict_list)):\n if key1==tagged_pos_dict_list[i]:\n pos_dict_updated.update({key1:value1})\n\nfor key1, value1 in neg_dict.items():\n for i in range(len(tagged_neg_dict_list)):\n if key1==tagged_neg_dict_list[i]:\n neg_dict_updated.update({key1:value1})\n\n\n \npickle_in=open(\"/Users/pushkarsingh/Desktop/twitter/pos-yy_adj.pickle\",\"wb\")\npickle.dump(pos_dict_updated,pickle_in)\npickle_in.close()\n\npickle_in=open(\"/Users/pushkarsingh/Desktop/twitter/neg-yy_adj.pickle\",\"wb\")\npickle.dump(neg_dict_updated,pickle_in)\npickle_in.close() \n","sub_path":"Preproccessing data.py","file_name":"Preproccessing data.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"312347001","text":"import numpy as np\nimport tensorflow as tf\nfrom keras import regularizers\nfrom keras.initializers import RandomUniform\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.layers.core import Flatten\nfrom keras.layers.core import Dropout\nfrom keras.layers import AlphaDropout\nfrom keras.layers import LSTM\nfrom keras.initializers import RandomNormal\nfrom keras.optimizers import SGD\nimport matplotlib.pyplot as plt\nimport argparse\nfrom learningratefinder import LearningRateFinder\nimport math\nimport MyFunctions as myf\n\nnum_samples = 250\nmyf.EPOCHS = 200\nmyf.model_description = 'PlayArea3 Test - 3 Layer 1 node Dense - RemoveRegulariserDefaultActivationDefaultInitializer'\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\n\n# define your custom callback for prediction\nclass PredictionCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs={}):\n y_pred = self.model.predict(self.validation_data[0])\n print('prediction: {} at epoch: {}'.format(y_pred, epoch))\n\n#### PlayPenCode\n#myf.parse_file(\"DAX4ML.csv\")\n#myf.parse_file(\"^GDAXI.csv\")\n\n# Disable GPU\nif True == True:\n physical_devices = tf.config.list_physical_devices('GPU')\n try:\n # Disable all GPUS\n tf.config.set_visible_devices([], 'GPU')\n visible_devices = tf.config.get_visible_devices()\n for device in visible_devices:\n assert device.device_type != 'GPU'\n except:\n # Invalid device or cannot modify virtual devices once initialized.\n pass\n\n\nmodel = Sequential()\n# Add flatten - may help?\nmodel.add(Flatten(input_shape=(num_samples, 4)))\nmodel.add(Dense(1, activation=\"sigmoid\", kernel_regularizer=regularizers.l2(0.01)))\n#model.add(Dropout(.25))\nmodel.add(Dense(1, activation=\"sigmoid\", kernel_regularizer=regularizers.l2(0.01)))\n#model.add(Dropout(.25))\nmodel.add(Dense(1)) # remove softmax, given we have multi-value output\n\n#MyFunctions.parse_process_plot(\"DAX_Prices_WithMLPercentages_Trimmed.csv\", \"BuyWeightingRule\", model, \"Model1_Percent_NewRandom_Trimmed\")\n#MyFunctions.parse_process_plot(\"DAX_Prices_WithMLPercentages.csv\", \"BuyWeightingRule\", model, \"Model1_Percent_NewRandom_Orig\")\n#MyFunctions.parse_process_plot(\".\\parsed_data\\DAX4ML.csv_parsed.csv\", \"BuyWeightingRule\", model, \"Model1_Percent_NewRandom_moredata\")\n#MyFunctions.parse_process_plot(\".\\parsed_data\\^GDAXI.csv\", \"BuyWeightingRule\", model, \"Model1_Percent_NewRandom_moredata_25dropout\")\n\n\n\nmodel2 = Sequential()\n# Add flatten - may help?\nmodel2.add(Flatten(input_shape=(num_samples, 4)))\nmodel2.add(Dense(512, activation=\"relu\", kernel_regularizer=regularizers.l2(0.01)))\nmodel2.add(Dropout(.4))\nmodel2.add(Dense(256, activation=\"relu\", kernel_regularizer=regularizers.l2(0.01)))\nmodel2.add(Dropout(.4))\nmodel2.add(Dense(1)) # remove softmax, given we have multi-value output\n\n#MyFunctions.parse_process_plot(\"DAX_Prices_WithMLPercentages.csv\", \"BuyWeightingRule\", model2, \"Model1_Relu_Percent_NewRandom\")\n\n#model3 = Sequential()\n#model3.add(Flatten(input_shape=(num_samples, 4)))\n#model3.add(Dense(512, activation=\"relu\", kernel_regularizer=regularizers.l2(0.01)))\n#model3.add(Dropout(.5))\n#model3.add(Dense(256, activation=\"relu\", kernel_regularizer=regularizers.l2(0.01)))\n#model3.add(Dropout(.5))\n#model3.add(Dense(128, activation=\"relu\", kernel_regularizer=regularizers.l2(0.01)))\n#model3.add(Dense(1)) # remove softmax, given we have multi-value output\n\n#MyFunctions.parse_process_plot(\"DAX_Prices_WithMLPercentages.csv\", \"BuyWeightingRule\", model3, \"Model1_ExtraLayer_Relu_Percent_NewRandom\")\n\n#model2 = Sequential()\n# Add flatten - may help?\n#model2.add(Flatten(input_shape=(num_samples, 4)))\n#model2.add(Dense(512, activation=\"relu\", kernel_regularizer=regularizers.l2(0.001)))\n#model2.add(Dropout(.4))\n#model2.add(Dense(256, activation=\"relu\", kernel_regularizer=regularizers.l2(0.001)))\n#model2.add(Dropout(.4))\n#model2.add(Dense(1)) # remove softmax, given we have multi-value output\n\n#MyFunctions.parse_process_plot(\"DAX_Prices_WithMLPercentages.csv\", \"BuyWeightingRule\", model2, \"Model1_Relu_Percent_NewRandom_001L2Reg\")\n\nLRR = 0\nBATCH_SIZE = 16\n\n# LRFinder code\nif LRR == 1:\n (trainX, testX, trainY, testY) = myf.parse_data_to_trainXY(\".\\parsed_data\\^GDAXI.csv\", \"SellWeightingRule\")\n\n model.compile(loss='mean_squared_error', optimizer='Nadam', metrics=[\"accuracy\"])\n print(\"[INFO] finding learning rate...\")\n lrf = LearningRateFinder(model)\n lrf.find((trainX, trainY), 1e-10, 1e+1,\n stepsPerEpoch=np.ceil((len(trainX) / float(BATCH_SIZE))),\n batchSize=BATCH_SIZE)\n lrf.plot_loss()\n\n # Risk here if there are two minimums - this will pick the lowest, not highest.\n lr_start_index = lrf.losses.index(min(lrf.losses))\n min_loss = min(lrf.losses)\n min_loss_lr = lrf.lrs[lrf.losses.index(min(lrf.losses))]\n\n print(\"[INFO] - lowest loss rate is \" + str(min_loss) + \" at LR of \" + str(min_loss_lr))\n\n # Work backwards to find where to 'start'\n step = math.floor(lrf.losses.index(min(lrf.losses))/10)\n max_loss = min_loss\n max_loss_lr = min_loss_lr\n for i in range(lr_start_index-step, 0, -step) :\n # Iterate backwards by 10% at a time. Stop when the loss increase is small\n current_loss = lrf.losses[i]\n if current_loss > (max_loss * 1.05): # 5% better\n max_loss = current_loss\n max_loss_lr = lrf.lrs[i]\n else:\n break\n # We're done! This is our min LR\n\n print(\"[INFO] min loss LR \" + str (min_loss_lr) + \" max loss LR \" + str(max_loss_lr))\n### End LRFinder Code\n\nactivation = 'selu' ## softmax, softplus, elu, tanh, selu, etctanh\n\nmodel_arr = []\nfor i in range (16, 32, 4) :\n\n print (i)\n myf.batch_size = i\n model_new =Sequential()\n\n model_new.add(Flatten(input_shape=(num_samples, 4)))\n# model_new.add(Dense(512, activation=\"relu\", kernel_regularizer=regularizers.l2(0.001 + i/1000)))\n# model_new.add(Dense(512, activation=\"relu\", kernel_initializer=RandomUniform(minval=-0.5, maxval=0.5, seed=None), kernel_regularizer=regularizers.l2(0.001 + i/1000)))\n# model_new.add(Dense(1, activation=\"relu\", kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None), kernel_regularizer=regularizers.l2(0.01 )))\n# model_new.add(Dense(1, activation=\"relu\", kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None),\n# kernel_regularizer=regularizers.l2(0.01)))\n# model_new.add(Dense(1, activation=\"relu\", kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None),\n# kernel_regularizer=regularizers.l2(0.01)))\n# model_new.add(Dense(1))\n# model_new.add(Dense(1))\n# model_new.add(Dense(1))\n\n# model_new.add(Dense(1024, activation=activation, kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None)))\n# model_new.add(Dense(1024, activation=activation, kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None)))\n# model_new.add(Dense(1024, activation=activation, kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None)))\n# model_new.add(Dense(1, activation=activation, kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None)))\n\n model_new.add(Dense(1024, activation=activation, kernel_initializer=\"lecun_normal\"))\n model_new.add(Dense(1024, activation=activation, kernel_initializer=\"lecun_normal\"))\n model_new.add(Dense(1024, activation=activation, kernel_initializer=\"lecun_normal\"))\n model_new.add(Dense(1)) # No activation - may make training better?\n\n # model_new.add(Dense(52, activation=\"relu\", kernel_initializer=RandomNormal(mean=0, stddev=0.1, seed=None), kernel_regularizer=regularizers.l2(0.01 )))\n #model_new.add(Dropout(.2))\n# model_new.add(Dense(256, activation=\"relu\", kernel_regularizer=regularizers.l2(0.01)))\n# model_new.add(Dense(26, activation=\"relu\", kernel_regularizer=regularizers.l2(0.01)))\n# model_new.add(Dropout(.2))\n# model_new.add(Dense(1)) # remove softmax, given we have multi-value output\n model_new.summary()\n myf.callbacks=[PredictionCallback()]\n myf.parse_process_plot(\".\\parsed_data\\^GDAXI.csv\", \"BuyWeightingRule\", model_new, \"PlayPen3_3Layer1024NodeDenseNoRegularizerActivtation\" + activation + \"RandomNormInit_Batch\" + str(i))\n# myf.parse_process_plot(\".\\parsed_data\\^GDAXI.csv\", \"SellWeightingRule\", model_new, \"Remove2ndDropout\\Model1_Relu_Percent_L2_MoreData_25Dropout_RandomNormal_Batch_NewSellRule\" + str(i))\n # Let's print some model stuff out - who knows what it will show?!\n for layer in model_new.layers: print(layer.get_config(), layer.get_weights())\n\n del model_new\n","sub_path":"PlayArea3.py","file_name":"PlayArea3.py","file_ext":"py","file_size_in_byte":8769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"242118441","text":"from collections import defaultdict\nimport tarfile\nimport score\nimport evaluate\nimport index\nimport tabulate\n\n\n\ndef parse_relevance_strings(strings):\n r\"\"\"\n Parse lines from TIME.REL.\n Params:\n strings...A list of strings, one per line, from TIME.REL\n Returns:\n A dict from query id to the list of relevant document ids, as ordered in the file.\n >>> strings = '''1 268 288 304\n ...\n ... 2 326 334'''\n >>> result = parse_relevance_strings(strings.split('\\n'))\n >>> sorted(result.items())\n [(1, [268, 288, 304]), (2, [326, 334])]\n \"\"\"\n query_docids = {}\n\n for index in range(0, len(strings)):\n temp_string = strings[index].replace('\\n', '')\n temp_string_list = (temp_string.strip()).split()\n temp_string_list = [int(i) for i in temp_string_list]\n if len(temp_string_list) > 0:\n query_docids[int(temp_string_list[0])] = temp_string_list[1:len(temp_string_list) + 1]\n\n return query_docids\n\n\ndef read_relevances(fname):\n \"\"\"\n Do not modify.\n Read a map from query ID to a list of relevant doc IDs.\n \"\"\"\n return parse_relevance_strings(open(fname).readlines())\n\n\ndef parse_query_strings(strings):\n r\"\"\"\n Parse lines from TIME.QUE.\n Params:\n strings...A list of strings, one per line, from TIME.QUE\n Returns:\n A dict from query id to query text string.\n >>> string = '''*FIND 1\n ...\n ... KENNEDY ADMINISTRATION PRESSURE ON NGO DINH DIEM TO STOP\n ...\n ... SUPPRESSING THE BUDDHISTS .\n ...\n ... *FIND 2\n ...\n ... EFFORTS OF AMBASSADOR HENRY CABOT LODGE TO GET VIET NAM'S\n ...\n ... PRESIDENT DIEM TO CHANGE HIS POLICIES OF POLITICAL REPRESSION .\n ...\n ... *STOP'''\n >>> res = parse_query_strings(string.split('\\n'))\n >>> print('%s' % res[1])\n KENNEDY ADMINISTRATION PRESSURE ON NGO DINH DIEM TO STOP SUPPRESSING THE BUDDHISTS .\n >>> print('%s' % res[2])\n EFFORTS OF AMBASSADOR HENRY CABOT LODGE TO GET VIET NAM'S PRESIDENT DIEM TO CHANGE HIS POLICIES OF POLITICAL REPRESSION .\n \"\"\"\n queryList = []\n i = 0\n while i < len(strings):\n if \"*FIND\" in strings[i]:\n j = i + 1\n tempString = \"\"\n while j < len(strings):\n if \"*FIND\" in strings[j] or \"*STOP\" in strings[j]:\n i = j\n break\n else:\n tempString = tempString.strip() + \" \" + remove_spaces_eof(strings[j])\n j += 1\n if tempString is not \"\":\n queryList.append(tempString.strip())\n else:\n i += 1\n return {k + 1: v for k, v in enumerate(queryList)}\n\ndef remove_spaces_eof(str):\n str = str.replace(\"\\n\",\"\")\n return str.strip()\n\ndef read_queries(fname):\n \"\"\" Do not modify. Read a map from query id to text.\"\"\"\n return parse_query_strings(open(fname).readlines())\n\n\ndef parse_document_strings(strings):\n r\"\"\"\n Parse lines from TIME.ALL.\n Params:\n strings...A list of strings, one per line, from TIME.ALL\n Returns:\n A list of strings, one per document.\n >>> string = '''*TEXT 017 01/04/63 PAGE 020\n ...\n ... THE ALLIES AFTER NASSAU\n ...\n ... *TEXT 020 01/04/63 PAGE 021\n ...\n ... THE ROAD TO JAIL IS PAVED WITH\n ...\n ... *STOP'''\n >>> parse_document_strings(string.split('\\n'))\n ['THE ALLIES AFTER NASSAU', 'THE ROAD TO JAIL IS PAVED WITH']\n \"\"\"\n documentList = []\n i = 0\n while i < len(strings):\n if \"*TEXT\" in strings[i]:\n j = i + 1\n tempString = \"\"\n while j < len(strings):\n if \"*TEXT\" in strings[j] or \"*STOP\" in strings[j]:\n i = j\n break\n else:\n tempString = tempString.strip() + \" \" + remove_spaces_eof(strings[j])\n j += 1\n if tempString is not \"\":\n documentList.append(tempString.strip())\n else:\n i += 1\n return documentList\n\n\ndef read_documents(fname):\n \"\"\" Do not modify. Read a list of documents.\"\"\"\n return parse_document_strings(open(fname).readlines())\n\n\ndef read_data():\n \"\"\" Do not modify. Read data.\"\"\"\n tarfile.open('time.tar.gz', mode='r').extractall()\n queries = read_queries('TIME.QUE')\n print('read %d queries.' % len(queries))\n relevances = read_relevances('TIME.REL')\n print('read %d relevance judgements.' % len(relevances))\n docs = read_documents('TIME.ALL')\n print('read %d documents.' % len(docs))\n return queries, relevances, docs\n\n\ndef write_results(all_results, fname):\n \"\"\" Do not modify. Write results. \"\"\"\n evals = sorted(list(all_results.values())[0].keys())\n headers = ['System'] + evals\n systems = sorted(all_results.keys())\n vals = []\n for system in systems:\n results = all_results[system]\n vals.append([system] + [results[e] for e in evals])\n f = open(fname, 'w')\n f.write(tabulate.tabulate(vals, headers, floatfmt=\".4f\"))\n f.write('\\n')\n\ndef search(query, scorer, index):\n \"\"\"\n Retrieve documents matching a query using the specified scorer.\n 1) Tokenize the query.\n 2) Convert the query tokens to a vector, using Index.query_to_vector.\n 3) Call the scorer's score function.\n 4) Return the list of document ids in descending order of relevance.\n NB: Due to the inconsistency of floating point arithmetic, when sorting,\n round the scores to 6 decimal places (e.g., round(x, 6)). This will ensure\n replicable results.\n Params:\n query....A string representing a search query.\n scorer...A ScoringFunction to retrieve documents.\n index....A Index storing postings lists.\n Returns:\n A list of document ids in descending order of relevance to the query.\n \"\"\"\n tokenized = index.tokenize(query)\n vector = index.query_to_vector(tokenized)\n tempResult = scorer.score(vector,index)\n tempResult = sorted(tempResult.items(), key=lambda key: round(key[1], 6), reverse=True)\n result = []\n for i in range(0, len(tempResult)):\n result.append(tempResult[i][0])\n return result\n\n\n\ndef run_all(queries, relevances, docs, indexer, scorers, evaluators, NHITS):\n \"\"\" Do not modify.\n For each query, run all scoring methods and evaluate the results.\n Returns:\n A dict from scoring method to results\n \"\"\"\n results = defaultdict(lambda: defaultdict(lambda: 0))\n for qid, qtext in queries.items():\n print('\\n-------\\nQUERY:%d %s' % (qid, qtext))\n relevant = sorted(list(relevances[qid]))\n print('RELEVANT: %s' % relevant)\n for scorer in scorers:\n hits = search(qtext, scorer, indexer)[:NHITS]\n print('\\t%s results: %s' % (scorer, hits))\n for evaluator in evaluators:\n evaluation = evaluator.evaluate(hits, relevant)\n results[str(scorer)][str(evaluator)] += evaluation\n for scorer in scorers:\n for evaluator in evaluators:\n results[str(scorer)][str(evaluator)] /= len(queries)\n return results\n\n\ndef main():\n \"\"\" Do not modify.\n Run and evaluate all methods.\n \"\"\"\n queries, relevances, docs = read_data()\n NHITS = 10\n indexer = index.Index(docs)\n\n scorers = [score.Cosine(),\n score.RSV(),\n score.BM25(k=1, b=.5),\n score.BM25(k=1, b=1),\n score.BM25(k=2, b=.5),\n score.BM25(k=2, b=1)]\n\n evaluators = [evaluate.Precision(),\n evaluate.Recall(),\n evaluate.F1(),\n evaluate.MAP()]\n\n all_results = run_all(queries, relevances, docs, indexer, scorers, evaluators, NHITS)\n write_results(all_results, 'Results.md')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"IIT/RankEngine2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"284313119","text":"# exec(open('offsetgraph.py').read())\r\n\r\nimport numpy as np\r\nimport quantities as pq\r\nimport matplotlib.pyplot as plt\r\nfrom neo.io import AxonIO\r\nimport os\r\nimport csv\r\nimport pandas as pd\r\nimport plotexp\r\nimport scipy.signal as scs\r\nfrom allensdk.ephys.ephys_extractor import EphysSweepFeatureExtractor\r\n\r\n# //////////////////////////////////////////////////////////////////\r\nfoldername = '../../Raw_data/Deepanjali_data/WT step input cells' #Name of the folder where files are stored\r\nfskip = ['Cell 2 of 21_3_2017.abf'] #List of files that need to be skipped\r\nseg_nol = [10,16] #list of segment numbers to evaluate the features for. Note that 0 refers to -100pA injection. 10 to 150pA, 16 to 300pA, 20 to 400pA.\r\n# //////////////////////////////////////////////////////////////////\r\n\r\ndef somefeatures(currAmp,Vtrace,stim_start,stim_end,sampling_rate):\r\n features = {}\r\n # i = np.zeros(len(Vtrace))\r\n # i[int(stim_start*sampling_rate):int(stim_end*sampling_rate)] = currAmp\r\n # i = np.array(i) #in A\r\n # v = np.array([float(V) for V in Vtrace]) #in V\r\n t = np.linspace(0,len(Vtrace)/sampling_rate, len(Vtrace))\r\n t = np.array(t) # in s\r\n # sweep_ext = EphysSweepFeatureExtractor(t=t, v=v*1e3, i=i*1e12, filter=4.9)\r\n # sweep_ext.process_spikes()\r\n features[f'E_rest'] = np.nanmean(Vtrace[(t<=stim_start) & (t>=stim_start-0.2)])\r\n # features[f'freq'] = len(sweep_ext.spike_feature(\"peak_t\"))/(stim_end - stim_start)\r\n features[f'freq'] = len(scs.find_peaks(Vtrace, height=-0.03, prominence=0.01)[0])/(stim_end - stim_start)\r\n features[f'offset'] = np.nanmin(Vtrace[(t<=stim_end-0.001) & (t>=stim_start+0.4)]) - features[f'E_rest']\r\n # features[f'find_peaks'] = scs.find_peaks(Vtrace, height=-0.03)\r\n \r\n return features\r\n\r\noffset = {}\r\n\r\nfor filename in os.listdir(foldername):\r\n stim1391 = ['Cell 3 of 181016.abf', 'cell 4 of 61016.abf', 'cell 4 of 111016.abf', 'cell 4 of 131016.abf', 'Cell 4 of 181016.abf', 'cell 5 of 61016.abf', 'Cell 5 of 181016.abf', 'Cell 2 of 19_10_2016', 'Cell 1 of 27_10_2016.abf', 'Cell 1 of 14_10_2016.abf', 'Cell 4 of 7_10_2016.abf', 'Cell 6 of 12_10_2016.abf', 'Cell 7 of 12_10_2016.abf']\r\n if filename in stim1391:\r\n stim_start = 139.1e-3\r\n stim_end = 639.1e-3\r\n else:\r\n stim_start = 81.4e-3 #in s\r\n stim_end = 581.4e-3 #in s\r\n\r\n if filename in fskip:\r\n print(f'{filename} skipped')\r\n continue\r\n\r\n if filename[-4:] == '.abf':\r\n\t offset[filename] = []\r\n\t for curramp in np.arange(-100e-12, 425e-12, 25e-12):\r\n\t \tt,v = plotexp.expdata('../../Raw_data/Deepanjali_data/WT step input cells/'+filename, curramp)\r\n\t \tfeatures = somefeatures(curramp,v,stim_start,stim_end,len(t)/t[-1])\r\n\t \toffset[filename].append(features['offset'])\r\n else:\r\n \tcontinue\r\n\r\noffsetl = []\r\nfor off in offset.keys():\r\n\toffsetl.append(offset[off])\r\nmedianoffset = np.median(offsetl,0)\r\navgoffset = np.nanmean(offsetl,0)\r\n\r\n\r\nI = np.arange(-100e-12, 425e-12, 25e-12)\r\nplt.plot(I, avgoffset)\r\nplt.plot(I, medianoffset)\r\nplt.show()\r\n\r\nplt.plot(I, np.transpose(offsetl))\r\nplt.title('Offset of all the expereimental cells')\r\nplt.xlabel('Injected current (A)')\r\nplt.ylabel('Offset (V)')\r\nplt.show()\r\n","sub_path":"2019-12-23-offset_graph/offsetgraph.py","file_name":"offsetgraph.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"555154811","text":"import Wrangle.settings as settings\nimport Wrangle.match_functions as functions\nfrom Wrangle.match_functions import Handler\nimport re\nimport pandas as pd\n\n'''\nSTANDARDIZE DATABASE COMPARISONS\n\nSTANDARDIZING TURBINE MODELS\nEnergy database's turbine models are of the form \n(quantity)(x)[manufacturer](model)(HH[0-9]+)[-](issue)[-](a-z)\nUsing regular expressions to extract just the model\n\n\n \nGET COLUMN MAPS IN FORMAT \n{db1_id_col: [id_col_name1..n], db2_id_col: [id_col_name1..n], compare_name1..n:[db1_col1..n,db2_col2..n]}\nCheck column data types\nif string then run match_functions get_string_partial_match and get_string_full_match\nif string is turbine model then extract model number with regex\nif latitude/longitude then run get_distance_km\nif number then run get_number_score\n'''\n\n\"\"\"TURN ON OR OFF DEBUG\"\"\"\ndebug_mode = False\n\n\"\"\"REGULAR EXPRESSIONS\"\"\"\n\n\"\"\"turbine quantity\"\"\"\nre_1 = \"^[0-9]+x\"\nregex_1 = re.compile(re_1, re.IGNORECASE)\n\n\"\"\"issue\"\"\"\n\nre_2 = \"[-]?[i][s][s][u][e][\\W]*[a-z]\"\nregex_2 = re.compile(re_2, re.IGNORECASE)\n\n\"\"\"hub height\"\"\"\n\nre_3 = \"[h]{1}[h]{1}[0-9\\.]{0,5}\"\n\nregex_3 = re.compile(re_3, re.IGNORECASE)\n\n\"\"\"To remove word like text\"\"\"\n\nre_4 = '[a-z\\-]+'\n\nregex_4 = re.compile(re_4, re.IGNORECASE)\n\n\"\"\"To extract turbine model\"\"\"\n\nre_5 = '[a-z]{0,3}[-]?[0-9]{1,3}[\\.]?[0-9]{0,3}[-\\\\]?[0-9]{1,3}[\\.]?' \\\n '[0-9]{0,3}[a-z]{0,3}'\n\nregex_5 = re.compile(re_5, re.IGNORECASE)\n\n_dont_work_on_these = ['name', 'db1_id', 'db2_id']\n\n\ndef compare(df1, df2, choice):\n comparison_matrix = {}\n handle = Handler()\n print(\"received choice: %s\" % choice)\n _weights = {}\n _temp_list = []\n '''RETRIEVE COMPARISON MATRIX FOR CHOICE'''\n\n if choice == '3':\n comparison_matrix = settings.COMPARE_MATRIX_CHOICE_3.copy()\n _weights = settings.WEIGHTS.copy()\n\n print(\"selected matrix: %s\" % comparison_matrix['name'])\n\n elif choice == '1':\n '''comparison_matrix = settings.COMPARE_MATRIX_CHOICE_1\n print(\"selected matrix: %s\" % comparison_matrix['name'])'''\n\n elif choice == '2':\n '''comparison_matrix = settings.COMPARE_MATRIX_CHOICE_2\n print(\"selected matrix: %s\" % comparison_matrix['name'])'''\n\n else:\n print(\"Comparison Matrix Not Found.\")\n\n '''CLEAN TURBINE MODEL DATA'''\n\n def clean_turbine_model(series):\n _series = series\n\n if not isinstance(_series, type(pd.Series())):\n raise TypeError(\n \"Turbine Model Standardization needs Series with Turbine Models, received %s\" % type(_series))\n\n elif series is None:\n print(\"Empty Series Received\")\n\n else:\n if debug_mode:\n print(\"Cleaning Turbine Models %s\" % ''.join(_temp_v for _temp_v in _series))\n _series = _series.str.lower().str.split().str.join('')\n\n for rx in [re_1, re_3, re_2]:\n _series.replace({rx: ''}, regex=True, inplace=True)\n return _series.apply(regex_5.findall).str.join(' ')\n\n \"\"\"Working with copies for convenience\"\"\"\n df1_c = df1.copy()\n df2_c = df2.copy()\n\n for df in [df1_c,df2_c]:\n df.fillna('0', inplace=True)\n\n \"\"\"Dealing with turbine model strings\"\"\"\n db1_turbine_model_header = comparison_matrix['model'][0]\n df1_c[db1_turbine_model_header] = clean_turbine_model(df1_c[db1_turbine_model_header])\n db2_turbine_model_header = comparison_matrix['model'][1]\n df2_c[db2_turbine_model_header] = clean_turbine_model(df2_c[db2_turbine_model_header])\n\n '''Retrieving ID fields'''\n db1_id = comparison_matrix['db1_id']\n db2_id = comparison_matrix['db2_id']\n\n if debug_mode:\n print(db1_id)\n\n \"\"\"temp dicts to store match results\"\"\"\n\n for index1, row1 in df1_c.iterrows():\n\n for index2, row2 in df2_c.iterrows():\n _temp_dict = {}\n _final_score = 0\n\n concatenated_db1_id_fields = ''.join(' ' + str(row1[value]) for value in db1_id)\n concatenated_db2_id_fields = ''.join(' ' + str(row2[value]) for value in db2_id)\n\n if debug_mode:\n print(\"ID 1 %s ID 2 %s\" % (concatenated_db1_id_fields, concatenated_db2_id_fields))\n _temp_dict.update({'ID1': concatenated_db1_id_fields})\n _temp_dict.update({'ID2': concatenated_db2_id_fields})\n\n for key, value in comparison_matrix.items():\n\n values_to_compare = []\n\n '''comparing just non ID fields'''\n if key not in _dont_work_on_these:\n _column_data_type = ''.join([i for i in key if not i.isdigit()])\n _weight = _weights[key]\n\n if debug_mode:\n print(\"Running comparison for key: %s value: %s\" % (_column_data_type, ' '.join(value)))\n\n for i in range(0, len(value)):\n\n if i % 2 == 0:\n values_to_compare.append(row1[value[i]])\n _temp_dict.update({value[i]: row1[value[i]]})\n\n else:\n values_to_compare.append(row2[value[i]])\n _temp_dict.update({value[i]: row2[value[i]]})\n\n if debug_mode:\n print(\"values being compared: %s \" % ('-'.join(str(v) for v in values_to_compare)))\n\n _score = handle.handle(_type=_column_data_type, *values_to_compare)\n _temp_dict.update({key + ' score': _score})\n _final_score = _final_score + ((float(_weight / 100)) * _score)\n\n if debug_mode:\n print(\"comparison score %s\" % _score)\n _temp_dict.update({'ratio': _final_score})\n _temp_list.append(_temp_dict)\n\n if debug_mode:\n print(\"\\n\\nFinal Score: %s\" % str(_final_score))\n _result = pd.DataFrame(_temp_list)\n if debug_mode:\n print(_temp_list)\n return _result\n","sub_path":"Wrangle/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":5974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"346956282","text":"import numpy as np\nfrom numpy import *\nfrom matplotlib import pyplot as plt\nimport random\n\n# DEFINE GRAPHIC OUTPUT WINDOW\nfig = plt.figure()\nkde, cmd = fig.add_subplot(211), fig.add_subplot(212)\n\n# DATA SELECTION/GENERATION--SORTED LIST AND ARRAY DTYPES\nLIST_OF_DATA = [random.randrange(0, 26, 1) for _ in range(350)]\nLIST_OF_DATA.sort()\nARRAY_OF_DATA = np.array(LIST_OF_DATA)\n\n\n# STANDARD DEVIATION CALCULATOR\ndef std_dev(lst):\n data_sum = 0\n mean_deviation_sum = 0\n for i in lst:\n data_sum += i\n data_mean = data_sum/len(lst)\n for i in lst:\n mean_deviation_sum += (data_mean-i)**2\n variance = mean_deviation_sum/(len(lst)-1)\n return sqrt(variance)\n\n\n# KERNEL DENSITY ESTIMATE PLOTTER WITH BAND-WITH ESTIMATION\ndef bandwith_estimator(lst):\n return 1.06*std_dev(lst)/len(lst)**0.2\n\n\ndef kde_plot(frame, bandwith, arr):\n dep = []\n ind = []\n for x in np.linspace(min(arr), max(arr), 100*(max(arr)-min(arr))):\n dep.append(x)\n ind.append(sum(exp(-0.5*((x-arr)/bandwith)**2)/sqrt(2*pi*bandwith**2)))\n dep = np.array(dep)\n ind = np.array(ind)\n return frame.plot(dep, ind)\n\n\n# CUMULATIVE DISTRIBUTION PLOTTER\ndef cmd_plot(frame, lst):\n lst.sort()\n incidence_ratios = []\n incidence_benchmarks = []\n for i in range(len(lst)):\n if i == len(lst)-1:\n incidence_ratio = 1\n incidence_ratios.append(incidence_ratio)\n incidence_benchmarks.append(lst[i])\n elif lst[i] != lst[i+1]:\n incidence_ratio = (i+1)/len(lst)\n incidence_ratios.append(incidence_ratio)\n incidence_benchmarks.append(lst[i])\n return frame.plot(incidence_benchmarks, incidence_ratios)\n\n# CALL PLOTS AND SHOW GRAPHIC OUTPUT-IF YOU DARE\nkde_plot(kde, bandwith_estimator(LIST_OF_DATA), ARRAY_OF_DATA)\ncmd_plot(cmd, LIST_OF_DATA)\nplt.show()\n","sub_path":"INSANE-ii.py","file_name":"INSANE-ii.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"330874192","text":"# This is the installation script\n# It assumes the default shell is bash and installs the \n# sending function in the .bash_profile file\n\nimport os\n\n\ndef sh(script, msg = 0):\n os.system(\"bash -c '%s'\" % script)\n\ndef install():\n HOME = os.getenv(\"HOME\")\n PATH = os.getcwd()\n\n\n os.chdir(HOME)\n bashFile = open(\".bash_profile\",\"r\")\n bashLines = bashFile.readlines()\n bashFile.close()\n bashFile = open(\".bash_profile\", \"a\")\n f = open(PATH + \"/bash_function.txt\", \"r\")\n\n found = False\n print(\"Installing 'send' program into bash...\")\n for line in f:\n if line not in bashLines:\n bashFile.write(line) \n else: \n found = True\n\n bashFile.close()\n\n if found:\n print(\"Already Installed\")\n sh(\"source .bash_profile\")\n os.chdir(PATH)\n\n\n print(\"---\")\n print(\"Installed sending capabilities (iMessage only).\")\n print(\"Please start a new terminal window (Cmd-T) to test the new capabilities.\")\n print(\"To send a message, type: in the command line.\")\n print(\"Alternatively, you can mess with the 'run.py' function to schedule your own messages.\")\n print(\"---\")\n print(\"By Gabe Schoenbach\")\n","sub_path":"morningProgram/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"230315013","text":"from Xs_generator_functions import *\n\n\nbatch = read_batch()\nlabels = list(batch.label)\nTypes = list(batch.type)\ndownload_raw_structure(labels)\nbatch_summary = []\nXs=[]\n#batch info stores the information of each enzyme, including label, type, number of atoms function for cat(catalysis),\n#bind(binding metals, cofactors, ligands, and etc.), het(metals, ligands, cofactors), and struct (structural, no documented function).\n#Enzymes that do not have documented site information are removed.\n\nfor i_enzyme in range(len(labels)):\n label = labels[i_enzyme]\n Type = Types[i_enzyme]\n struct, HasHet = parse_pdb(label)\n siteseq, siteinfo, HasSite = parse_cif(label)\n if HasSite or HasHet:\n atom_list = atom_list_generator(struct,siteinfo,siteseq,HasSite)\n write_atom_list(atom_list,label)\n print('enzyme:', label, i_enzyme+1,\"/\", len(labels))\n print(\" finish parsing the pdb file: site information acquired\")\n atom_list_pocket, center = build_atom_list_pocket(atom_list) #the atom list of pocket\n atom_list_shift = shift_center(atom_list_pocket, center) # shift the atom coordinates, such that they are centered at [0,0,0]\n atom_list_trunc = trunc_box(atom_list_shift) # truncate the atoms into a box\n batch_summary.append([label, Type] + atom_list_summary(atom_list_trunc))\n print(\" finish generating the pocket\")\n atom_list_grid = grid_atom(atom_list_trunc)\n X = channel_generator(atom_list_grid)\n Xs.append(X)\n write_X(X,label)\n print(\" finish generating the 3D atomic space with channels\")\n else:\n print('enzyme:', label, i_enzyme+1,\"/\", len(labels))\n print(\" finish parsing the pdb file: no site information\")\n\nwrite_batch_summary(batch_summary)\nXs = np.asarray(Xs)\nprint(\"finish generating Xs\")\n","sub_path":"Xs_generator/Xs_generator.py","file_name":"Xs_generator.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"300559992","text":"__all__ = ['test_accumulators',\n 'test_accumulator_factory',\n 'test_action',\n 'test_action_exec_strategy_factory',\n 'test_app_action_event_dispatcher',\n 'test_app_api_server',\n 'test_app_api_validation',\n 'test_app_base',\n 'test_app_blueprint',\n 'test_app_cache',\n 'test_app_cache_entry',\n 'test_app_database',\n 'test_app_event_dispatcher',\n 'test_app_instance',\n 'test_app_utilities',\n 'test_argument',\n 'test_authentication',\n 'test_branch',\n 'test_callback_container',\n 'test_conditional_expression',\n 'test_configuration_server',\n 'test_console_logging_handler',\n 'test_console_stream',\n 'test_decorators',\n 'test_device_database',\n 'test_device_field_database',\n 'test_device_server',\n 'test_device_validation',\n 'test_event_dispatcher',\n 'test_events',\n 'test_environment_variable',\n 'test_transform',\n 'test_condition',\n 'test_condition_transform_validation',\n 'test_filtered_sse_stream',\n 'test_health_endpoint',\n 'test_helper_functions',\n 'test_input_validation',\n 'test_interface_event_dispatch_helpers',\n 'test_interface_event_dispatcher',\n 'test_make_cache',\n 'test_message',\n 'test_message_db',\n 'test_message_history_database',\n 'test_messaging_endpoints',\n 'test_metrics',\n 'test_metrics_server',\n 'test_notification_stream',\n 'test_playbook',\n 'test_redis_cache_adapter',\n 'test_redis_subscription',\n 'test_problem',\n 'test_remote_action_exec_strategy',\n 'test_roles_pages_database',\n 'test_roles_server',\n 'test_scheduledtasks_database',\n 'test_scheduledtasks_server',\n 'test_scheduler_actions',\n 'test_scheduler',\n 'test_scheduler_utils',\n 'test_simple_workflow',\n 'test_sse_stream',\n 'test_streamable_blueprint',\n 'test_trigger_helpers',\n 'test_triggers_server',\n 'test_users_roles_database',\n 'test_users_server',\n 'test_validatable',\n 'test_walkoff_tag',\n 'test_workflow_communication_receiver',\n 'test_workflow_manipulation',\n 'test_workflow_communication_sender',\n 'test_workflow_receiver',\n 'test_workflow_results_handler',\n 'test_workflow_results_stream',\n 'test_workflow_server',\n 'test_workflow_status',\n 'test_zmq_communication',\n 'test_zmq_communication_server',\n 'testapps']\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"409044310","text":"#!/usr/bin/env python3\n\nfrom io import TextIOWrapper\nimport re, requests, time, os, pickle, logging\nfrom logging.handlers import RotatingFileHandler\nfrom requests.exceptions import ReadTimeout, ConnectionError, ChunkedEncodingError\nfrom copy import deepcopy\nfrom bs4 import BeautifulSoup\nfrom config import ANDHRA_TRACK_DIR, ANDHRA_PDF_ENGLISH_DIR, ANDHRA_PDF_TELUGU_DIR\nfrom helpers import getpath, timestamp, TRACK_FILE_TS, urlparse, urljoin, append_csv, relpath, randf, tailstr\nfrom selenium import webdriver\nimport json\nfrom PIL import Image\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.common.exceptions import NoSuchElementException\nfrom urllib.request import urlopen\nimport os\nimport cv2\nimport pytesseract\nfrom PIL import Image\nimport urllib.request\nimport time\n# Assignment\nASSIGNED_DISTRICTS = []\nASSIGNED_ID = 0\n\n# Tuning\nENABLE_RESUME = True\nTOTAL_RETRIES = 10 # times\nREQUEST_TIMEOUT = 20 # seconds\nRETRY_DELAY = 5 # seconds\nREFRESH_DELAY = 10 # seconds\nREFRESH_REQUEST_TIMEOUT = 30 # seconds\nREFRESH_TOTAL_RETRIES = 3\nDELAY_MIN = 0 # seconds\nDELAY_MAX = 0 # seconds\nDELAY_FRACTION = 999999\n\n# Connection settings\nUSER_AGENT = 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0'\nANDHRA_URL = 'https://ceoaperolls.ap.gov.in/AP_Eroll/Rolls'\nANDHRA_BASE_URL = 'https://ceoaperolls.ap.gov.in/AP_Eroll'\n\n# /html/body/form/table/tbody/tr[1]/td[2]/img\n# /html/body/form/table/tbody/tr[2]/td[2]/input\n\n\n# Parsing & saving\nFIND_PDF_REGEX = re.compile(r\"open\\('(.+)',\")\nOUTPUT_FILE = getpath(ANDHRA_TRACK_DIR, 'Andhra{}-{}.csv'.format(ASSIGNED_ID or '', timestamp(TRACK_FILE_TS)))\nDOWNLOAD_FAILED = 'Not available / Unable to download'\nTRACK_FILE = getpath('cache/andhra{}_track.bin'.format(ASSIGNED_ID or ''))\n\nprint(TRACK_FILE)\nCSV_HEADER = (\n 'district_name',\n 'ac_name',\n 'polling_station_number',\n 'polling_station_name',\n 'polling_station_location',\n 'telugu_file_name',\n 'eng_file_name'\n)\n\n# Log settings\nMAX_LOG_SIZE = 52428800\nLOG_BACKUP_COUNT = 5\nLOG_FILE = getpath('/Users/jalend15/PycharmProjects/electoral_rolls/andhra/logs/andhra{}.log'.format(ASSIGNED_ID or ''))\nprint(LOG_FILE)\n\ndef log_configurer():\n root = logging.getLogger()\n root.setLevel(logging.WARNING)\n formatter = logging.Formatter(fmt='%(message)s')\n\n consoleHandler = logging.StreamHandler()\n consoleHandler.setFormatter(formatter)\n\n fileHandler = RotatingFileHandler(getpath(LOG_FILE), maxBytes=MAX_LOG_SIZE, backupCount=LOG_BACKUP_COUNT)\n fileHandler.setFormatter(formatter)\n\n root.addHandler(consoleHandler)\n root.addHandler(fileHandler)\n\n return root\n\n\nclass ExitRequested(Exception):\n pass\n\n\nclass Track:\n\n def __init__(self):\n self._data = None\n self._done = False\n self.__load()\n\n def __load(self):\n self.initialize()\n if ENABLE_RESUME:\n if os.path.isfile(TRACK_FILE):\n try:\n with open(TRACK_FILE, 'rb') as file:\n self._data.update(pickle.load(file))\n except EOFError:\n self.data = None\n\n def initialize(self):\n self._data = {\n 'done:district': 0,\n 'done:ac': 0,\n 'done:station': 0,\n 'current:step': 0,\n 'current:district': 0,\n 'current:ac': 0,\n 'output': None\n }\n\n def set_done(self):\n self.initialize()\n self._done = True\n\n def save(self):\n if self._done:\n if os.path.isfile(TRACK_FILE):\n os.remove(TRACK_FILE)\n else:\n if ENABLE_RESUME:\n with open(TRACK_FILE, 'wb') as file:\n pickle.dump(self._data, file)\n\n @property\n def output(self):\n if self._data['output'] is None:\n self._data['output'] = OUTPUT_FILE\n return self._data['output']\n\n def get_done_dist(self):\n return self._data.get('done:district')\n\n def set_done_dist(self, value):\n self._data['done:district'] = int(value)\n self._data['done:ac'] = 0\n self._data['done:station'] = 0\n\n def get_done_ac(self):\n return self._data['done:ac']\n\n def set_done_ac(self, value):\n self._data['done:ac'] = int(value)\n self._data['done:station'] = 0\n\n def get_done_station(self):\n return self._data['done:station']\n\n def set_done_station(self, value):\n self._data['done:station'] = int(value)\n\n def get_cur_step(self):\n return self._data['current:step']\n\n def set_cur_step(self, value):\n self._data['current:step'] = int(value)\n\n def get_cur_dist(self):\n return self._data['current:district']\n\n def set_cur_dist(self, value):\n self._data['current:district'] = int(value)\n\n def get_cur_ac(self):\n return self._data['current:ac']\n\n def set_cur_ac(self, value):\n self._data['current:ac'] = int(value)\n\n\nclass Session:\n\n def __init__(self):\n self._delay = 0\n self.referer = None\n self.cookies = None\n self.state = None\n self.validation = None\n self.headers = {'user-agent': USER_AGENT}\n self.track = Track()\n\n def save_track(self):\n self.track.save()\n\n def __parse(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n\n state = soup.find('input', {'id': '__VIEWSTATE'})\n if state is None:\n logger.warning('Error parsing response!')\n raise AssertionError\n\n validation = soup.find('input', {'id': '__EVENTVALIDATION'})\n if validation is None:\n logger.warning('Error parsing response!')\n raise AssertionError\n\n self.state = state.get('value')\n self.validation = validation.get('value')\n\n self.referer = response.request.url\n if self.cookies is None:\n self.cookies = response.cookies\n\n return soup\n\n def __error(self):\n fmt = 'Errors occurred with session:\\n\\t+ Cookie: {}\\n\\t+ Validation: {}\\n\\t+ State: {}'\n logger.warning(fmt.format(\n self.cookies.get('ASP.NET_SessionId'), tailstr(self.validation, 50), tailstr(self.state, 50)))\n raise ExitRequested\n\n def __prep(self):\n headers = deepcopy(self.headers)\n if self.referer:\n headers['referer'] = self.referer\n ret = {'headers': headers}\n if self.cookies:\n ret['cookies'] = self.cookies\n return ret\n\n def __postdata(self, target, district, ac, get_stations):\n data = {\n '__EVENTTARGET': target,\n '__EVENTARGUMENT': '',\n '__LASTFOCUS': '',\n '__VIEWSTATE': self.state,\n '__EVENTVALIDATION': self.validation,\n 'ddlDist': str(district),\n 'ddlAC': str(ac),\n }\n if get_stations:\n data['btnGetPollingStations'] = 'Get+Polling+Stations'\n return data\n\n def __refresh(self):\n self.referer = None\n self.cookies = None\n headers = self.__prep()\n\n step = self.track.get_cur_step()\n dist_num = self.track.get_cur_dist()\n ac_num = self.track.get_cur_ac()\n\n logger.warning('Waiting %s seconds for refreshing...' % REFRESH_DELAY)\n time.sleep(REFRESH_DELAY)\n\n if 0 <= step:\n try:\n logger.warning('Loading Main page...')\n response = requests.get(ANDHRA_URL, timeout=REFRESH_REQUEST_TIMEOUT, **headers)\n except (ReadTimeout, ConnectionError, ChunkedEncodingError):\n logger.warning('Time out or connection error!')\n return False\n else:\n if response.status_code != requests.codes.OK:\n logger.warning('Could not load Main page: %s %s' % (response.status_code, response.reason))\n return False\n try:\n self.__parse(response)\n except AssertionError:\n return False\n else:\n logger.warning('Main page loaded successfully.')\n\n if 1 <= step:\n time.sleep(self.delay)\n headers = self.__prep()\n data = self.__postdata(target='ddlDist', district=str(dist_num), ac='0', get_stations=False)\n try:\n logger.warning('Listing District #%s...' % dist_num)\n response = requests.post(ANDHRA_URL, data=data, timeout=REFRESH_REQUEST_TIMEOUT, **headers)\n except (ReadTimeout, ConnectionError, ChunkedEncodingError):\n logger.warning('Time out or connection error!')\n return False\n else:\n if response.status_code != requests.codes.OK:\n logger.warning(\n 'Could not list District #%s: %s %s' % (dist_num, response.status_code, response.reason))\n return False\n try:\n self.__parse(response)\n except AssertionError:\n return False\n else:\n logger.warning('District #%s listed successfully.' % dist_num)\n\n if 2 <= step:\n time.sleep(self.delay)\n headers = self.__prep()\n data = self.__postdata(target='', district=str(dist_num), ac=str(ac_num), get_stations=True)\n try:\n logger.warning('Listing Stations for AC #%s of District #%s...' % (ac_num, dist_num))\n response = requests.post(ANDHRA_URL, data=data, timeout=REFRESH_REQUEST_TIMEOUT ** headers)\n except (ReadTimeout, ConnectionError, ChunkedEncodingError):\n logger.warning('Time out or connection error!')\n return False\n else:\n if response.status_code != requests.codes.OK:\n logger.warning('Could not list Stations for AC #%s of District #%s: %s %s' % (\n ac_num, dist_num, response.status_code, response.reason))\n return False\n try:\n self.__parse(response)\n except AssertionError:\n return False\n else:\n logger.warning('Stations listed successfully.')\n\n logger.warning('Successfully refreshed!')\n return True\n\n def __browse(self, method, url=None, parse=True, **kwargs):\n url = url or ANDHRA_URL\n headers = self.__prep()\n browser = getattr(requests, method)\n tried = 0\n while tried <= TOTAL_RETRIES:\n tried += 1\n time.sleep(self.delay)\n try:\n response = browser(url, timeout=REQUEST_TIMEOUT, **kwargs)\n except (ReadTimeout, ConnectionError, ChunkedEncodingError):\n logger.warning('Timeout or connection error!')\n if tried <= TOTAL_RETRIES:\n self.__retry()\n continue\n else:\n if response.status_code == requests.codes.OK:\n try:\n return self.__parse(response) if parse else response\n except AssertionError:\n break\n else:\n logger.warning('Error response: %s %s %s' % (\n response.request.method, response.status_code, response.reason))\n self.__error()\n\n def __retry(self, seconds=None):\n seconds = seconds or RETRY_DELAY\n logger.warning('Will retry in %s seconds...' % seconds)\n self._delay = seconds\n\n def __getfile(self, query):\n parsed = urlparse(query).query\n if parsed.startswith('urlPath=') and parsed.lower().endswith('.pdf'):\n return parsed[8:].split('\\\\')[-1]\n logger.warning('Could not parse file name. Unsupported query string: %s' % query)\n self.__error()\n\n @property\n def refreshed(self):\n while not self.__refresh():\n continue\n return True\n\n @property\n def delay(self):\n if self._delay > 0:\n ret = self._delay\n self._delay = 0\n return ret\n return randf(DELAY_MIN, DELAY_MAX, DELAY_FRACTION)\n\n def get(self):\n count = 0\n while count < REFRESH_TOTAL_RETRIES:\n try:\n return self.__browse(method='get')\n except ExitRequested:\n count += 1\n if count <= REFRESH_TOTAL_RETRIES:\n if self.refreshed:\n continue\n else:\n break\n self.__error()\n\n def post(self, target='', district='0', ac='0', get_stations=False):\n count = 0\n while count <= REFRESH_TOTAL_RETRIES:\n data = self.__postdata(target, district, ac, get_stations)\n try:\n return self.__browse(method='post', data=data)\n except ExitRequested:\n count += 1\n if count <= REFRESH_TOTAL_RETRIES:\n if self.refreshed:\n continue\n else:\n break\n self.__error()\n\n def fetch(self, query, dest):\n if os.path.isdir(dest):\n file = os.path.join(dest, self.__getfile(query))\n\n if os.path.isfile(file):\n logger.warning('--> File existed: %s' % file)\n return file\n\n else:\n url = urljoin(ANDHRA_BASE_URL, query)\n logger.warning('--> Downloading %s...' % url)\n\n count = 0\n while count <= REFRESH_TOTAL_RETRIES:\n try:\n response = self.__browse(method='get', url=url, parse=False)\n except ExitRequested:\n count += 1\n if count > REFRESH_TOTAL_RETRIES:\n return None\n if self.refreshed:\n continue\n else:\n break\n else:\n with open(file, 'wb') as f:\n f.write(response.content)\n return file\n else:\n logger.warning('Destination folder was not found: %s' % dest)\n self.__error()\n\n\nclass Andhra:\n\n def __init__(self, session):\n self.session = session\n self.soup = None\n self.districts = []\n\n def download(self):\n if not os.path.isfile(self.session.track.output):\n append_csv(self.session.track.output, CSV_HEADER)\n\n\n logger.warning('Finding Districts...')\n self.session.track.set_cur_step(0)\n self.soup = self.session.get()\n\n select = self.soup.find('select', {'id': 'ddlDist'})\n if select is None:\n logger.warning('Could not parse Districts in response!')\n raise ExitRequested\n\n options = select.find_all('option')\n if len(options) < 2:\n logger.warning('No District found!')\n raise ExitRequested\n\n logger.warning('Found %s Districts.' % (len(options) - 1))\n done_dist = self.session.track.get_done_dist()\n #done_dist = 2\n\n\n\n for option in options[1:]:\n dist_num = option.get('value')\n dist_name = option.text.strip()\n\n if ASSIGNED_DISTRICTS and int(dist_num) not in ASSIGNED_DISTRICTS:\n logger.warning('Skipped District \"%s\" (Not Assigned)' % dist_name)\n continue\n if int(dist_num) <= done_dist:\n logger.warning('Skipped District \"%s\" (Done Already)' % dist_name)\n continue\n District(num=dist_num, name=dist_name, session=self.session)\n\n logger.warning('Completed successfully.')\n self.session.track.set_done()\n\n\nclass District:\n\n def __init__(self, num, name, session):\n self.num = num\n self.name = name\n self.session = session\n self.soup = None\n self.acs = []\n self.download()\n\n def download(self):\n logger.warning('Finding ACs of District \"%s\"...' % self.name)\n self.session.track.set_cur_step(1)\n self.session.track.set_cur_dist(self.num)\n self.soup = self.session.post(target='ddlDist', district=self.num)\n\n select = self.soup.find('select', {'id': 'ddlAC'})\n if select is None:\n logger.warning('Could not parse ACs in response!')\n raise ExitRequested\n\n options = select.find_all('option')\n if len(options) < 2:\n logger.warning('No AC found for District \"%s\"!' % self.name)\n raise ExitRequested\n\n logger.warning('Found %s ACs for District \"%s\".' % (len(options) - 1, self.name))\n done_ac = self.session.track.get_done_ac()\n #done_ac = 12\n\n for option in options[1:]:\n ac_num = option.get('value')\n ac_name = option.text.strip()\n\n if int(ac_num) <= done_ac:\n logger.warning('Skipped AC \"%s\" of District \"%s\"' % (ac_name, self.name))\n continue\n\n AC(\n num=ac_num,\n name=ac_name,\n dist_num=self.num,\n dist_name=self.name,\n session=self.session\n )\n\n self.session.track.set_done_dist(self.num)\n\n\nclass AC:\n\n def __init__(self, num, name, dist_num, dist_name, session):\n self.num = num\n self.name = name\n self.dist_num = dist_num\n self.dist_name = dist_name\n self.session = session\n self.soup = None\n self.stations = []\n self.download()\n\n def download(self):\n logger.warning('Finding Stations of AC \"%s\" of District \"%s\"...' % (self.name, self.dist_name))\n self.session.track.set_cur_step(2)\n self.session.track.set_cur_dist(self.dist_num)\n self.session.track.set_cur_ac(self.num)\n self.soup = self.session.post(district=self.dist_num, ac=self.num, get_stations=True)\n\n table = self.soup.find('table', {'id': 'GridView1'})\n if table is None:\n logger.warning('Could not parse Stations in response!')\n raise ExitRequested\n\n tr = table.find_all('tr')\n\n if len(tr) < 2:\n logger.warning('No Stations found for AC \"%s\" of District \"%s\"!' % (self.name, self.dist_name))\n raise ExitRequested\n\n logger.warning('Found %s Stations for AC \"%s\" of District \"%s\".' % (len(tr) - 1, self.name, self.dist_name))\n\n done_station = self.session.track.get_done_station()\n #done_station=13\n\n for row in tr[1:]:\n\n td = row.find_all('td')\n\n if len(td) != 5:\n logger.warning('Unexpected row: %s' % row)\n continue\n num = td[0].text.strip()\n name = td[1].text\n loc = td[2].text\n telugu = td[3].find('a').get('id').replace('_', '$')\n english = td[4].find('a').get('id').replace('_', '$')\n\n if int(num) <= done_station:\n logger.warning(\n 'Skipped Station \"%s-%s\" of AC \"%s\" of District \"%s\"' % (num, name, self.name, self.dist_name))\n continue\n\n Station(num, name, loc, telugu, english, self.num, self.name, self.dist_num, self.dist_name, self.session)\n\n self.session.track.set_done_ac(self.num)\n\n\nclass Station:\n\n def __init__(self, num, name, loc, telugu, english, ac_num, ac_name, dist_num, dist_name, session):\n self.num = num\n self.name = name\n self.location = loc\n self.telugu = telugu\n self.english = english\n self.ac_num = ac_num\n self.ac_name = ac_name\n self.dist_num = dist_num\n self.dist_name = dist_name\n self.session = session\n self.telugu_dir = getpath(ANDHRA_PDF_TELUGU_DIR)\n self.english_dir = getpath(ANDHRA_PDF_ENGLISH_DIR)\n self.telugu_soup = None\n self.english_soup = None\n self.telugu_file = None\n self.english_file = None\n self.download()\n\n def expand_shadow_element(self,driver,element):\n shadow_root = driver.execute_script('return arguments[0].shadowRoot', element)\n return shadow_root\n\n def __bypass_captcha(self,url, language):\n\n\n while(1):\n chrome_options = webdriver.ChromeOptions()\n settings = {\n \"recentDestinations\": [{\n \"id\": \"Save as PDF\",\n \"origin\": \"local\",\n \"account\": \"\",\n }],\n \"selectedDestinationId\": \"Save as PDF\",\n \"version\": 2\n }\n prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings)}\n chrome_options.add_experimental_option('prefs', prefs)\n chrome_options.add_argument('--kiosk-printing')\n chrome_options.add_argument('headless');\n\n driver = webdriver.Chrome(options = chrome_options, executable_path=\"/Users/jalend15/opt/miniconda3/lib/python3.8/site-packages/selenium/webdriver/chrome/chromedriver\")\n driver.get(url)\n image = driver.find_element_by_id('form1').screenshot(\"/Users/jalend15/PycharmProjects/electoral_rolls/andhra/aa.png\")\n\n image = cv2.imread('/Users/jalend15/PycharmProjects/electoral_rolls/andhra/aa.png')\n image = cv2.resize(image, (0, 0), fx=1.2, fy=2)\n #cv2.imwrite(\"/Users/jalend15/PycharmProjects/electoral_rolls/andhra/cc.png\", image)\n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n #cv2.imwrite(\"/Users/jalend15/PycharmProjects/electoral_rolls/andhra/cc.png\", gray)\n\n gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\n #cv2.imwrite(\"/Users/jalend15/PycharmProjects/electoral_rolls/andhra/dd.png\", gray)\n\n filename = \"{}.png\".format(\"temp\")\n cv2.imwrite(filename, gray)\n text = pytesseract.image_to_string(Image.open('temp.png'))\n #print(text)\n\n captchaEntry = driver.find_element_by_id('txtVerificationCode')\n captchaEntry.send_keys(text[18:24])\n wait = WebDriverWait(driver, 10)\n element = wait.until(EC.element_to_be_clickable((By.ID, 'btnSubmit')))\n element.click()\n # submitButton = driver.find_element_by_id('btnSubmit')\n #\n #\n # submitButton.click()\n\n\n\n delay = 10 # seconds\n try:\n captchamsg = driver.find_element_by_id('lblCaptchaMessage');\n if(captchamsg):\n print('Captcha entered is incorrect')\n #self.__bypass_captcha(url)\n except NoSuchElementException:\n print(\"Captcha Passed\")\n try:\n secs= 20\n time.sleep(secs)\n driver.implicitly_wait(secs)\n\n\n driver.execute_script('window.print();')\n\n time.sleep(secs)\n\n\n\n old_file_name = \"/Users/jalend15/Downloads/Popuppage.pdf\"\n new_file_name = \"/Users/jalend15/Downloads/\" + language.capitalize() + \"_distno_\" + self.dist_num + \"_acno_\" + self.ac_num + \"_partno_\" + self.num+\".pdf\"\n if(os.path.isfile(old_file_name)):\n os.rename(old_file_name, new_file_name)\n driver.implicitly_wait(secs)\n break;\n else:\n print(\"Loading took too much time!\")\n\n\n except TimeoutException:\n print(\"Loading took too much time!\")\n driver.quit()\n\n def __fetch_pdf(self, lang):\n target = getattr(self, lang)\n dir_ = getattr(self, '%s_dir' % lang)\n # print(self.dist_name)\n # print(self.ac_num)\n # print(self.ac_name)\n # print(self.num)\n\n temp = self.ac_num\n\n\n URL = ANDHRA_BASE_URL + '/Popuppage?'\n partnumber = 'partNumber='+self.num\n roll = 'roll=' + lang.capitalize() + 'MotherRoll'\n districtname = 'districtName=DIST_'+ str(self.dist_num).zfill(2)\n acname ='acname='+ temp\n acnameeng = 'acnameeng=A'+ temp\n acno = 'acno='+ temp\n acnameurdu = 'acnameurdu=' + str(temp).zfill(3)\n\n finalurl = URL + partnumber + '&' + roll + '&' +districtname + '&' + acname + '&' + acnameeng + '&' + acno + '&' + acnameurdu\n\n print(finalurl)\n self.__bypass_captcha(finalurl,lang)\n\n logger.warning('Downloading %s PDF...' % lang.capitalize())\n\n\n soup = self.session.post(target=target, district=self.dist_num, ac=self.ac_num)\n\n script = soup.find('script')\n\n\n if script is None:\n logger.warning('Could not parse %s download link in response!' % lang.capitalize())\n raise ExitRequested\n\n try:\n link = FIND_PDF_REGEX.findall(script.text)[0]\n #link ='https://ceoaperolls.ap.gov.in/AP_Eroll/Popuppage?partNumber=1&roll=EnglishMotherRoll&districtName=DIST_02&acname=11&acnameeng=A11&acno=11&acnameurdu=011'\n\n except IndexError:\n logger.warning('No %s download link responded!' % lang.capitalize())\n file = None\n setattr(self, '%s_soup' % lang, soup)\n setattr(self, '%s_file' % lang, file)\n\n else:\n file = self.session.fetch(query=link, dest=dir_)\n setattr(self, '%s_soup' % lang, soup)\n setattr(self, '%s_file' % lang, file)\n\n def download(self):\n logger.warning('Processing: Station \"%s-%s\", AC \"%s\", District \"%s\"...' % (\n self.num, self.name, self.ac_name, self.dist_name))\n self.__fetch_pdf('telugu')\n self.__fetch_pdf('english')\n row = (\n self.dist_name,\n self.ac_name,\n self.num,\n self.name,\n self.location,\n relpath(self.telugu_file) if self.telugu_file is not None else DOWNLOAD_FAILED,\n relpath(self.english_file) if self.english_file is not None else DOWNLOAD_FAILED\n )\n append_csv(self.session.track.output, row)\n\n self.session.track.set_done_station(self.num)\n done_station = self.session.track.get_done_station()\n\n self.session.save_track()\n\n\n\ndef main():\n session = Session()\n site = Andhra(session)\n try:\n site.download()\n except (KeyboardInterrupt, ExitRequested):\n session.save_track()\n print(\"Keyboard interrupt\")\n pass\n finally:\n session.save_track()\n logger.warning('Exited!')\n\n\nif __name__ == '__main__':\n logger = log_configurer()\n main()\n","sub_path":"andhra/andhra.py","file_name":"andhra.py","file_ext":"py","file_size_in_byte":26819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"560965521","text":"import json\nfrom datetime import datetime, timedelta\nfrom random import randint\n\nfrom django.db import models as django_models\nfrom django.forms import Textarea\nfrom model_utils import FieldTracker\nfrom otree.api import (\n models,\n BaseConstants,\n BaseSubsession,\n BaseGroup,\n BasePlayer, widgets,\n)\n\nauthor = 'Your name here'\n\ndoc = \"\"\"\nYour app description\n\"\"\"\n\n\nclass Constants(BaseConstants):\n players_per_group = None\n name_in_url = 'experimiento_1'\n num_rounds = 1\n experiment_days = 15\n\n\nclass Subsession(BaseSubsession):\n tipo_de_juego = models.IntegerField(default=1)\n resultados_anteriores = models.StringField(blank=True)\n etapa_actual = models.IntegerField(default=1)\n\n def vars_for_admin_report(self):\n survey_keys = []\n survey_items = []\n cuestionario_items = []\n dataSession1_items = []\n dataSession2_items = []\n dataSession3_items = []\n for player in self.get_players():\n survey_data = json.loads(player.survey) if player.survey else {}\n cuestionario = json.loads(\n player.cuestionario) if player.cuestionario else {}\n dataSession1_variable = json.loads(\n player.dataSession1) if player.dataSession1 else {}\n dataSession2_variable = json.loads(\n player.dataSession2) if player.dataSession2 else {}\n dataSession3_variable = json.loads(\n player.dataSession3) if player.dataSession3 else {}\n dataSession1_items.append(dataSession1_variable)\n dataSession2_items.append(dataSession2_variable)\n dataSession3_items.append(dataSession3_variable)\n survey_items.append(survey_data)\n cuestionario_items.append(cuestionario)\n return dict(dataSession1=json.dumps(dataSession1_items), dataSession2=json.dumps(dataSession2_items), dataSession3=json.dumps(dataSession3_items), survey=json.dumps(survey_items), cuestionario=json.dumps(cuestionario_items), )\n\n\nclass Constants(BaseConstants):\n players_per_group = None\n name_in_url = 'experimiento_1'\n num_rounds = 1\n experiment_days = 15\n\n\nclass Group(BaseGroup):\n\n def players_info(self):\n query = Player.objects.filter(group_id=self.id)\n user_number = query.count()\n money_decisions_group = [\n query.filter(money_decision=0).count(),\n query.filter(money_decision=1).count(),\n query.filter(money_decision=2).count()\n ]\n\n return [int((value / user_number) * 100) for value in money_decisions_group]\n\n\nCONTRACT_TYPE = [\n (0, 'Contrato informal (CI)'),\n (1, 'Contrato formal (CF)'),\n]\n\nMONEY_DECISION_CHOICES = [\n (0, 'Recibir los $4.000 al finalizar el día.'),\n (1, 'Guardar una parte de su pago y por cada $100 que decida guardar '\n 'nosotros le daremos ${price_session} más. Podrá recibir en esta sesión una parte de su '\n 'pago y el monto guardado será transferido en la última sesión, es decir, entre {fecha_inicial} y {fecha_final} días a partir de hoy.'),\n (2, 'Guardar la totalidad de su pago y recibirlo al finalizar la tercera sesión; '\n 'es decir, entre {fecha_inicial} y {fecha_final} días a partir de hoy. '\n 'Recuerde que por cada $100 nosotros le daremos ${price_session} más.'),\n]\n\n\nclass Player(BasePlayer):\n\n # Variables\n decisionsesion1 = models.StringField()\n ahorrosesion1 = models.BooleanField(default=False)\n montoahorrosesion1 = models.IntegerField(default=0)\n pagoAhorroSession1 = models.IntegerField(default=0)\n\n decisionsesion2 = models.StringField()\n ahorrosesion2 = models.BooleanField(default=False)\n montoahorrosesion2 = models.IntegerField(default=0)\n pagoAhorroSession2 = models.IntegerField(default=0)\n\n montoTranscripcion1 = models.IntegerField(default=0)\n montoTranscripcion2 = models.IntegerField(default=0)\n montoTranscripcion3 = models.IntegerField(default=0)\n\n montoSesion1 = models.IntegerField(default=0)\n montoSesion2 = models.IntegerField(default=0)\n montoSesion3 = models.IntegerField(default=0)\n\n pagoMoneda = models.IntegerField(default=0)\n moneda = models.StringField()\n\n # def live_moneda(self, data):\n # # if (data['resultado'] == 'azul'):\n # # self.pagoMoneda = 5000 - int(data['monto'])\n # # elif (data['resultado'] == 'azul'):\n # # self.pagoMoneda = (5000-int(data['monto'])) + (int(data['monto'])*0.5) + int(data['monto'])\n\n # print(self.pagoMoneda)\n\n def live_intermedio(self, data):\n\n if (data['type'] == 'sesion1'):\n if (data['decision'] == 0):\n self.decisionsesion1 = MONEY_DECISION_CHOICES[0][1]\n elif (data['decision'] == 1):\n self.decisionsesion1 = MONEY_DECISION_CHOICES[1][1]\n self.ahorrosesion1 = True\n self.montoahorrosesion1 = int((4000*data['porcentaje'])/100)\n elif (data['decision'] == 2):\n self.decisionsesion1 = MONEY_DECISION_CHOICES[2][1]\n elif (data['type'] == 'sesion2'):\n if (data['decision'] == 0):\n self.decisionsesion2 = MONEY_DECISION_CHOICES[0][1]\n elif (data['decision'] == 1):\n self.decisionsesion2 = MONEY_DECISION_CHOICES[1][1]\n self.ahorrosesion2 = True\n self.montoahorrosesion2 = int((4000*data['porcentaje'])/100)\n elif (data['decision'] == 2):\n self.decisionsesion2 = MONEY_DECISION_CHOICES[2][1]\n\n # print(self.decisionsesion1)\n # print(self.ahorrosesion1)\n # print(self.montoahorrosesion1)\n\n # print(self.decisionsesion2)\n # print(self.ahorrosesion2)\n # print(self.montoahorrosesion2)\n\n sesion = models.IntegerField(default=0)\n\n codigo = models.StringField()\n\n terminos_actividad = models.BooleanField(\n label='¿Acepta los términos de esta actividad?',\n choices=[\n [True, \"Sí\"],\n [False, \"No\"],\n ],\n widget=widgets.RadioSelectHorizontal\n )\n\n is_final = models.BooleanField(initial=False)\n\n num_temporal = models.IntegerField(\n label=\"Por favor, ingrese el número de identificación temporal que le llegó en el mensaje de invitación\")\n accepts_data = models.BooleanField(\n label=\"¿Autoriza el uso de los datos recolectados para futuros estudios?\",\n choices=[\n [True, \"Sí\"],\n [False, \"No\"],\n ],\n default=True\n )\n accepts_terms = models.BooleanField()\n\n coin_select = models.IntegerField(null=True,\n label=\"Cara obtenida\",\n choices=[\n [0, \"Cara\"],\n [1, \"Sello\"],\n ]\n )\n\n money_decision = models.IntegerField(choices=MONEY_DECISION_CHOICES, blank=False,\n verbose_name=\"¿Cómo desea recibir el dinero de la sesión de hoy?\",\n widget=widgets.RadioSelect)\n contract_type = models.IntegerField(choices=CONTRACT_TYPE)\n experiment_start_date = django_models.DateTimeField(auto_now=True)\n intermedio = models.IntegerField(default=0)\n percentage_saved = models.IntegerField(\n max=100, min=0, default=0, verbose_name=\"Porcentaje guardado\")\n file_session_1 = models.LongStringField(default=\"\", verbose_name=\"Ingrese el texto del documento\",\n widget=Textarea(attrs={'rows': 40, 'cols': 40}))\n file_session_2 = models.LongStringField(default=\"\", verbose_name=\"Ingrese el texto del documento\",\n widget=Textarea(attrs={'rows': 40, 'cols': 40}))\n file_session_3 = models.LongStringField(default=\"\", verbose_name=\"Ingrese el texto del documento\",\n widget=Textarea(attrs={'rows': 40, 'cols': 40}))\n Monto = models.IntegerField(max=5000, min=0, default=0)\n updated_at = django_models.DateTimeField(auto_now=True)\n disbursement = models.CurrencyField(\n null=True, doc=\"Valor retirado\", default=0)\n survey = models.LongStringField()\n cuestionario = models.LongStringField()\n tracker = FieldTracker()\n\n dataSession1 = models.LongStringField()\n dataSession2 = models.LongStringField()\n dataSession3 = models.LongStringField()\n\n def start(self):\n if not self.contract_type:\n self.experiment_start_date = datetime.now()\n\n if self.session.config['tipo'] == \"linea_base_contrato_informal\":\n self.contract_type = 0\n self.save()\n elif self.session.config['tipo'] == \"linea_base_contrato_formal\":\n self.contract_type = 1\n self.save()\n\n # self.contract_type = randint(0, 1)\n # self.save()\n\n @property\n def intermedio_actual(self):\n return self.intermedio + 1\n\n intermedio2 = models.IntegerField(default=0)\n\n @property\n def intermedio_actual2(self):\n print(\"en intermedio actual 2 \", self.intermedio2)\n return self.intermedio2 + 1\n\n @property\n def experiment_end_date(self):\n return self.experiment_start_date + timedelta(days=Constants.experiment_days)\n","sub_path":"experimiento_1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"199713036","text":"import json\nimport os\n\nimport pendulum\nfrom django.db.models import Max, Min\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.generics import ListAPIView\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom gAPI.models import Geoname\nfrom gAPI.serializers import GeonameSerializer\nfrom geonames_API.settings import BASE_DIR\n\n\ndef get_data():\n json_data = os.path.join(BASE_DIR, 'static', '../static/geonames.json')\n response = open(json_data)\n if not response:\n return\n data_json = json.load(response)\n return data_json\n\n\nclass StandardResultsSetPagination(PageNumberPagination):\n page_size = 10\n page_size_query_param = 'page_size'\n max_page_size = 1000\n\n\nclass GeonamesListView(ListAPIView):\n queryset = Geoname.objects.all()\n serializer_class = GeonameSerializer\n pagination_class = StandardResultsSetPagination\n\n\nclass GeonamesDetailView(APIView):\n def get(self, request, id):\n geoname = get_object_or_404(Geoname, geonameid=id)\n serializer = GeonameSerializer(geoname)\n return Response(serializer.data)\n\n\nclass GeonamesSearchView(APIView):\n def get(self, request, search):\n\n # Gaining information about two cities from request\n\n city_1 = search.split(',')[0]\n city_2 = search.split(',')[1]\n\n query_1 = Geoname.objects.filter(alternatenames__icontains=city_1)\n query_2 = Geoname.objects.filter(alternatenames__icontains=city_2)\n\n # Gaining information about population in city 1\n\n query_1_max_population = query_1.aggregate(Max('population'))['population__max']\n query_1_min_population = query_1.aggregate(Min('population'))['population__min']\n\n # and city 2\n\n query_2_max_population = query_2.aggregate(Max('population'))['population__max']\n query_2_min_population = query_2.aggregate(Min('population'))['population__min']\n\n # Checking the quantity of cities(objects in queryset)\n # and doing needed operations to have only two cities\n\n if len(query_1) > 1:\n query_1 = Geoname.objects.filter(alternatenames__icontains=city_1, population=query_1_max_population)\n if query_1_max_population == query_1_min_population:\n query_1 = Geoname.objects.filter(alternatenames__icontains=city_1, geonameid=query_1[0].geonameid)\n if len(query_2) > 1:\n query_2 = Geoname.objects.filter(alternatenames__icontains=city_2, population=query_2_max_population)\n if query_2_max_population == query_2_min_population:\n query_2 = Geoname.objects.filter(alternatenames__icontains=city_2, geonameid=query_2[0].geonameid)\n\n # Queryset with two cities\n\n cities = query_1 | query_2\n\n # Checking max latitude for northern city and gaining northern city\n\n max_latitude = cities.values_list('latitude', flat=True).aggregate(Max('latitude'))['latitude__max']\n northern_city = cities.filter(latitude=max_latitude).values('name')[0]['name']\n\n # Collecting queryset in list for better manipulating\n\n result = []\n for data in cities.values():\n result.append(data)\n\n # Operation for gaining timezone difference in given cities\n\n timezone_comparison = result[0]['timezone'] == result[1]['timezone']\n city_1_timezone = result[0]['timezone']\n time_city_1 = pendulum.datetime(2000, 1, 1, tz=city_1_timezone)\n city_2_timezone = pendulum.timezone(result[1]['timezone'])\n time_city_2 = pendulum.datetime(2000, 1, 1, tz=city_2_timezone)\n time_difference = time_city_1.diff(time_city_2).in_hours()\n\n # Data for additional information about two cities\n\n comparison = {'northern_city': northern_city,\n 'equal_timezones': timezone_comparison,\n 'timezone_difference_in_hours': time_difference}\n result.append(comparison)\n\n return Response(result)\n","sub_path":"gAPI/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"109302307","text":"import os\nimport re\nimport time\n\nfrom rcGlobalEnv import *\nfrom rcUtilities import call, which, clear_cache\nimport rcStatus\nimport resDiskLoop as Res\nimport rcExceptions as ex\nfrom rcLoopSunOS import file_to_loop\nfrom lock import cmlock\n\nclass Disk(Res.Disk):\n def is_up(self):\n \"\"\"Returns True if the loop group is present and activated\n \"\"\"\n self.loop = file_to_loop(self.loopFile)\n if len(self.loop) == 0:\n return False\n return True\n\n def start(self):\n lockfile = os.path.join(rcEnv.paths.pathlock, \"disk.loop\")\n if self.is_up():\n self.log.info(\"%s is already up\" % self.label)\n return\n try:\n with cmlock(timeout=30, delay=1, lockfile=lockfile):\n cmd = ['lofiadm', '-a', self.loopFile]\n ret, out, err = self.vcall(cmd)\n except Exception as exc:\n raise ex.excError(str(exc))\n if ret != 0:\n raise ex.excError\n self.loop = file_to_loop(self.loopFile)\n if len(self.loop) == 0:\n raise ex.excError(\"loop device did not appear or disappeared\")\n time.sleep(1)\n self.log.info(\"%s now loops to %s\" % (self.loop, self.loopFile))\n self.can_rollback = True\n\n def stop(self):\n if not self.is_up():\n self.log.info(\"%s is already down\" % self.label)\n return 0\n cmd = ['lofiadm', '-d', self.loop]\n ret, out, err = self.vcall(cmd)\n if ret != 0:\n raise ex.excError\n\n def resource_handling_file(self):\n path = os.path.dirname(self.loopFile)\n return self.svc.resource_handling_dir(path)\n\n def _status(self, verbose=False):\n r = self.resource_handling_file()\n if self.is_provisioned() and not os.path.exists(self.loopFile):\n if r is None or (r and r.status() in (rcStatus.UP, rcStatus.STDBY_UP)):\n self.status_log(\"%s does not exist\" % self.loopFile)\n if self.is_up():\n return rcStatus.UP\n else:\n return rcStatus.DOWN\n\n def __init__(self, rid, loopFile, **kwargs):\n Res.Disk.__init__(self, rid, loopFile, **kwargs)\n\n def exposed_devs(self):\n self.loop = file_to_loop(self.loopFile)\n return set(self.loop)\n","sub_path":"lib/resDiskLoopSunOS.py","file_name":"resDiskLoopSunOS.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"278465520","text":"import math\r\nimport numpy as np\r\n\r\n\r\nclass ReplayBuffer(object):\r\n _data_pointer = 0\r\n _size = 0\r\n\r\n def __init__(self, batch_size, capacity):\r\n self.batch_size = batch_size\r\n self.capacity = capacity\r\n\r\n self._buffer = np.empty(capacity, dtype=object)\r\n\r\n def add(self, *args):\r\n # for arg in args:\r\n # assert len(arg.shape) == 2\r\n # assert len(arg) == len(args[0])\r\n\r\n for i in range(len(args[0])):\r\n self._buffer[self._data_pointer] = tuple(arg[i] for arg in args)\r\n self._data_pointer += 1\r\n\r\n if self._data_pointer >= self.capacity: # replace when exceed the capacity\r\n self._data_pointer = 0\r\n\r\n if self._size < self.capacity:\r\n self._size += 1\r\n\r\n def sample(self):\r\n n_sample = self.batch_size if self.is_lg_batch_size else self._size\r\n t = np.random.choice(self._buffer[:self._size], size=n_sample, replace=False)\r\n return [np.array(e) for e in zip(*t)]\r\n\r\n @property\r\n def is_full(self):\r\n return self._size == self.capacity\r\n\r\n @property\r\n def size(self):\r\n return self._size\r\n\r\n @property\r\n def is_lg_batch_size(self):\r\n return self._size > self.batch_size\r\n\r\n\r\nclass SumTree(object):\r\n \"\"\"\r\n This SumTree code is a modified version and the original code is from:\r\n https://github.com/jaara/AI-blog/blob/master/SumTree.py\r\n Story data with its priority in the tree.\r\n \"\"\"\r\n _data_pointer = 0\r\n _size = 0\r\n\r\n def __init__(self, capacity):\r\n self.capacity = capacity # for all priority values\r\n self._tree = np.zeros(2 * capacity - 1)\r\n # [--------------Parent nodes-------------][-------leaves to recode priority-------]\r\n # size: capacity - 1 size: capacity\r\n self._data = np.zeros(capacity, dtype=object) # for all transitions\r\n # [--------------data frame-------------]\r\n # size: capacity\r\n\r\n def add(self, p, data):\r\n tree_idx = self._data_pointer + self.capacity - 1\r\n self._data[self._data_pointer] = data # update data_frame\r\n self.update(tree_idx, p) # update tree_frame\r\n\r\n self._data_pointer += 1\r\n if self._data_pointer >= self.capacity: # replace when exceed the capacity\r\n self._data_pointer = 0\r\n\r\n if self._size < self.capacity:\r\n self._size += 1\r\n\r\n def update(self, tree_idx, p):\r\n change = p - self._tree[tree_idx]\r\n self._tree[tree_idx] = p\r\n # then propagate the change through tree\r\n while tree_idx != 0: # this method is faster than the recursive loop in the reference code\r\n tree_idx = (tree_idx - 1) // 2\r\n self._tree[tree_idx] += change\r\n\r\n def get_leaf(self, v):\r\n \"\"\"\r\n Tree structure and array storage:\r\n Tree index:\r\n 0 -> storing priority sum\r\n / \\\r\n 1 2\r\n / \\ / \\\r\n 3 4 5 6 -> storing priority for transitions\r\n Array type for storing:\r\n [0,1,2,3,4,5,6]\r\n \"\"\"\r\n parent_idx = 0\r\n while True: # the while loop is faster than the method in the reference code\r\n cl_idx = 2 * parent_idx + 1 # this leaf's left and right kids\r\n cr_idx = cl_idx + 1\r\n if cl_idx >= len(self._tree): # reach bottom, end search\r\n leaf_idx = parent_idx\r\n break\r\n else: # downward search, always search for a higher priority node\r\n if v <= self._tree[cl_idx]:\r\n parent_idx = cl_idx\r\n else:\r\n v -= self._tree[cl_idx]\r\n parent_idx = cr_idx\r\n\r\n data_idx = leaf_idx - self.capacity + 1\r\n return leaf_idx, self._tree[leaf_idx], self._data[data_idx]\r\n\r\n @property\r\n def total_p(self):\r\n return self._tree[0] # the root\r\n\r\n @property\r\n def max(self):\r\n if self._size == 0:\r\n return 0\r\n return np.max(self._tree[self.capacity - 1:self._size + self.capacity - 1])\r\n\r\n @property\r\n def min(self):\r\n return np.min(self._tree[self.capacity - 1:self._size + self.capacity - 1])\r\n\r\n @property\r\n def size(self):\r\n return self._size\r\n\r\n\r\nclass PrioritizedReplayBuffer(object): # stored as ( s, a, r, s_ ) in SumTree\r\n epsilon = 0.01 # small amount to avoid zero priority\r\n alpha = 0.6 # [0~1] convert the importance of TD error to priority\r\n beta = 0.4 # importance-sampling, from initial value increasing to 1\r\n beta_increment_per_sampling = 0.001\r\n abs_err_upper = 1. # clipped abs error\r\n\r\n def __init__(self, batch_size, capacity):\r\n self.batch_size = batch_size\r\n capacity = 2**math.floor(math.log2(capacity))\r\n self._tree = SumTree(capacity)\r\n\r\n def add(self, *args):\r\n max_p = self._tree.max\r\n if max_p == 0:\r\n max_p = self.abs_err_upper\r\n\r\n for i in range(len(args[0])):\r\n self._tree.add(max_p, tuple(arg[i] for arg in args))\r\n\r\n def sample(self):\r\n n_sample = self.batch_size if self.is_lg_batch_size else self.size\r\n\r\n points, transitions, is_weights = np.empty((n_sample,), dtype=np.int32), np.empty((n_sample,), dtype=object), np.empty((n_sample, 1))\r\n pri_seg = self._tree.total_p / n_sample # priority segment\r\n self.beta = np.min([1., self.beta + self.beta_increment_per_sampling]) # max = 1\r\n\r\n min_prob = self._tree.min / self._tree.total_p # for later calculate ISweight\r\n\r\n for i in range(n_sample):\r\n a, b = pri_seg * i, pri_seg * (i + 1)\r\n v = np.random.uniform(a, b)\r\n idx, p, data = self._tree.get_leaf(v)\r\n prob = p / self._tree.total_p\r\n is_weights[i, 0] = np.power(prob / min_prob, -self.beta)\r\n points[i], transitions[i] = idx, data\r\n return points, tuple(np.array(e) for e in zip(*transitions)), is_weights\r\n\r\n def update(self, tree_idx, abs_errors):\r\n abs_errors += self.epsilon # convert to abs and avoid 0\r\n clipped_errors = np.minimum(abs_errors, self.abs_err_upper)\r\n\r\n ps = np.power(clipped_errors, self.alpha)\r\n for ti, p in zip(tree_idx, ps):\r\n self._tree.update(ti, p)\r\n\r\n @property\r\n def size(self):\r\n return self._tree.size\r\n\r\n @property\r\n def is_lg_batch_size(self):\r\n return self.size > self.batch_size\r\n","sub_path":"utils/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"538444786","text":"# License: BSD 3 clause\n\nfrom functools import reduce\nfrom typing import Callable, Iterable, List, Tuple, Optional\n\nfrom pyspark.sql import DataFrame\nimport pyspark.sql.functions as sf\nfrom pyspark.ml.feature import StringIndexer\n\n\ndef fold_right(f: Callable, cohorts: Iterable):\n t = iter(cohorts)\n init_value = next(t)\n return reduce(f, t, init_value)\n\n\ndef data_frame_equality(df1: DataFrame, df2: Optional[DataFrame]) -> bool:\n if isinstance(df1, DataFrame) and (isinstance(df2, DataFrame)):\n return (df1.subtract(df2.select(df1.schema.fieldNames())).count() == 0) and (\n df2.subtract(df1.select(df2.schema.fieldNames())).count() == 0\n )\n else:\n return False\n\n\ndef is_same_struct_type(df1: DataFrame, df2: Optional[DataFrame]) -> bool:\n if isinstance(df1, DataFrame) and (isinstance(df2, DataFrame)):\n schema_1 = {field.name: field.dataType for field in df1.schema.fields}\n schema_2 = {field.name: field.dataType for field in df2.schema.fields}\n return schema_1 == schema_2\n else:\n return False\n\n\ndef rename_df_columns(\n df: DataFrame,\n new_names: List[str] = None,\n prefix: str = \"\",\n suffix: str = \"\",\n keys: Tuple[str] = (\"patientID\",),\n) -> DataFrame:\n \"\"\"Rename columns of a pyspark DataFrame.\n\n Parameters\n ----------\n df: dataframe whose columns will be renamed\n new_names: If not None, these name will replace the old ones.\n The order should be the same as df.columns where the keys has been\n removed.\n prefix: Prefix added to colnames.\n suffix: Suffix added to colnames.\n keys: Columns whose name will not be modified (useful for joining\n keys for example).\n\n Returns\n -------\n `pyspark.sql.DataFrame` with renamed columns.\n \"\"\"\n old_names = [c for c in df.columns if c not in keys]\n if new_names is None:\n new_names = [prefix + c + suffix for c in old_names]\n return df.select(\n *keys, *[sf.col(c).alias(new_names[i]) for i, c in enumerate(old_names)]\n )\n\n\ndef index_string_column(\n dataframe: DataFrame, input_col: str, output_col: str\n) -> Tuple[DataFrame, int, List[str]]:\n \"\"\"Add a column containing an index corresponding to a string column.\n\n Parameters\n ----------\n dataframe: Dataframe on which add index column.\n input_col: Name of the column to index\n output_col: Name of the index column in the resulting dataframe.\n\n Returns\n Tuple (resulting_dataframe, n_values_in_index, index_mapping)\n \"\"\"\n indexer = StringIndexer(\n inputCol=input_col, outputCol=output_col, stringOrderType=\"alphabetAsc\"\n )\n model = indexer.fit(dataframe)\n output = model.transform(dataframe)\n\n mapping = model.labels\n n_categories = len(mapping)\n\n return output, n_categories, mapping\n","sub_path":"scalpel/core/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"414851900","text":"import os\r\nimport sys\r\nfrom operator import itemgetter\r\nimport nltk\r\n\r\n#read the reviews and their polarities from a given file\r\ndef loadData(fname):\r\n reviews=[]\r\n labels=[]\r\n f=open(fname)\r\n for line in f:\r\n review,rating=line.strip().split('\\t')\r\n reviews.append(review.lower())\r\n labels.append(int(rating))\r\n f.close()\r\n return reviews,labels\r\n\r\n#function to load lexicons\r\ndef loadLexicon(fname):\r\n newLex=set()\r\n lex_conn=open(fname)\r\n #add every word in the file to the set\r\n for line in lex_conn:\r\n newLex.add(line.strip())# remember to strip to remove the lin-change character\r\n lex_conn.close()\r\n return newLex\r\n\r\ndef getCoordinate(review):\r\n xcord=0\r\n ycord=0\r\n review_class=0\r\n words=review.lower().strip().split(' ')\r\n for word in words:\r\n if word in posLex:\r\n ycord+=1\r\n elif word in negLex:\r\n xcord+=1\r\n if ycord > xcord:\r\n review_class=1\r\n return (xcord, ycord, review_class)\r\n\r\ndef calculateDistance(p1, p2):\r\n x2=p2[0]\r\n x1=p1[0]\r\n y2=p2[1]\r\n y1=p1[1]\r\n return (((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1))) ** 0.5\r\n\r\ndef getNeighbourDistance(test_coordinate, train_coordinates):\r\n result={}\r\n for train_cord in train_coordinates:\r\n #print(test_coordinate, train_cord)\r\n distance=calculateDistance(test_coordinate, train_cord)\r\n result[train_cord]=distance\r\n return result\r\n\r\ndef findNeighbours(neighbourDict, k):\r\n freq=neighbourDict\r\n sortedByValue=sorted(freq.items(),key=itemgetter(1))\r\n return sortedByValue[:k]\r\n\r\ndef voteLabels(topKNeighbours):\r\n vote={}\r\n for kn in topKNeighbours:\r\n #print(kn[0][2])\r\n rev_class = kn[0][2]\r\n vote[rev_class]=vote.get(rev_class, 0)+1\r\n #print(vote)\r\n sorting=sorted(vote.items(), key=itemgetter(1), reverse=True)\r\n return sorting[:1]\r\n\r\ndef getAccuracy(testList, predictions):\r\n correct = 0\r\n for x in range(len(testList)):\r\n if testList[x] is predictions[x]:\r\n correct += 1\r\n return (correct/float(len(testList))) * 100.0\r\n\r\n#load data\r\nrev_train,labels_train=loadData('reviews_train.txt')\r\nrev_test,labels_test=loadData('reviews_test.txt')\r\n\r\nrev_test2,labels_test2=loadData('reviews_test.txt')\r\nrev_train2,labels_train2=loadData('reviews_train.txt')\r\n#print(rev_train2,labels_train2)\r\n\r\n#get pos and neg lexicon\r\nposLex=loadLexicon('positive-words.txt')\r\nnegLex=loadLexicon('negative-words.txt')\r\n\r\n#find coordinates of rev_train\r\ntrain_coordinates=[]\r\nfor review_train in rev_train:\r\n coordinates=getCoordinate(review_train)\r\n train_coordinates.append(coordinates)\r\n\r\npredictions=[]\r\nfor r_test in rev_test:\r\n #print(r_test)\r\n r_test_cord=getCoordinate(r_test)\r\n neighbourDict=getNeighbourDistance(r_test_cord, train_coordinates)\r\n topKNeighbours=findNeighbours(neighbourDict, 5)\r\n answer=voteLabels(topKNeighbours)\r\n predictions.append(answer[0][0])\r\n\r\n#print(predictions)\r\nacc=getAccuracy(labels_test, predictions)\r\nprint(acc)\r\n#print(rev_train, labels_train)\r\n#print(posLex)","sub_path":"KNN/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"332434250","text":"syntax: fileObject.write(string);\n\n#!/usr/bin/python\n\n# Open a file\nfo = open(\"foo.txt\", \"wb\")\nfo.write( \"Python is a great language.\\nYeah Pret its great!!\\n\");\n\n# Close opend file\nfo.close()\n","sub_path":"#!/usr/bin/python/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"595743694","text":"import numpy as np\nimport pandas as pd\nimport os\nimport sys\nsys.path.append('./')\n\nimport subprocess\n\nfrom libs.andrew_utils import *\nfrom libs.feature_utils import get_columns, get_feature_columns\nfrom libs.get_dictionaries import *\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import mean_absolute_error\n\nimport lightgbm as lgb\nimport time\nimport datetime\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold, KFold, RepeatedKFold\nfrom sklearn import metrics\nfrom sklearn import linear_model\nimport gc\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom ipdb import set_trace\n\nimport argparse\n\n\nparser = argparse.ArgumentParser(description='Training Mol Models')\n\nparser.add_argument('tag')\nparser.add_argument('--model_type', type=str, default = 'lgb', help='choose model')\n\nargs = parser.parse_args()\n\nos.mkdir('log/'+args.tag)\n\nfeature_columns = get_feature_columns(1.0)\n#cmd = \"script ./log/\"+args.tag+\"/loss.log\"\n#subprocess.call(cmd.split())\n\nfile_folder = '../input/ultimate'\nprint('Load Train data')\ntrain = pd.read_hdf(file_folder+'/ultimate_train.h5', 'df', engine='python')\nprint('Load Test data')\ntest = pd.read_hdf(file_folder+'/ultimate_test.h5', 'df', engine='python')\nsub = pd.read_csv('../input/champsdata/sample_submission.csv')\n\n# Split 1JHC\n#train=train.loc[train['type']=='1JHC']\n#test=test.loc[test['type']=='1JHC']\ntrain['type'].where((train['type']=='1JHC')&(train['dist']>1.065),'1JHC_UPPER',inplace=True)\ntest['type'].where((test['type']=='1JHC')&(test['dist']>1.065),'1JHC_UPPER',inplace=True)\n\n\ny = train['scalar_coupling_constant']\ntrain = train.drop(columns = ['scalar_coupling_constant'])\n\ngiba_columns, qm9_columns, label_columns, index_columns, diff_columns = get_columns()\n\nprint(\"Encoding label features...\")\nfor f in label_columns:\n # 'type' has to be the last one\n # since the this label encoder is used later\n if f in train.columns:\n lbl = LabelEncoder()\n lbl.fit(list(train[f].values) + list(test[f].values))\n train[f] = lbl.transform(list(train[f].values))\n test[f] = lbl.transform(list(test[f].values))\ntrain = train.drop(['id','molecule_name'],axis=1)\ntest = test.drop(['id','molecule_name'],axis=1)\nn_fold = 2\nfolds = KFold(n_splits=n_fold, shuffle=True, random_state=11)\n\n\nparam_dict = get_params_dict()\nn_estimators_dict = get_estimators_dict()\nf = open('log/'+args.tag+'/param.txt', 'w')\nfor key,value in sorted(param_dict.items()):\n f.write(f'{key} {value}\\n')\nf.close()\n\nf = open('log/'+args.tag+'/n_estimators.txt', 'w')\nfor key,value in sorted(n_estimators_dict.items()):\n f.write(f'{key} {value}\\n')\nf.close()\n\nX_short = pd.DataFrame({'ind': list(train.index), 'type': train['type'].values, 'oof': [0] * len(train), 'target': y.values})\nX_short_test = pd.DataFrame({'ind': list(test.index), 'type': test['type'].values, 'prediction': [0] * len(test)})\n\nfor t in train['type'].unique():\n type_ = lbl.inverse_transform([t])[0]\n print('Training of type '+str(type_))\n X_t = train.loc[train['type'] == t]\n X_test_t = test.loc[test['type'] == t]\n y_t = X_short.loc[X_short['type'] == t, 'target']\n params = param_dict[str(type_)]\n n_estimators = n_estimators_dict[type_]\n\n # select features for each type\n X_t = X_t.loc[:,feature_columns[str(type_)]]\n X_test_t = X_test_t.loc[:,feature_columns[str(type_)]]\n result_dict_lgb = train_model_regression(args.tag, type_, X=X_t, X_test=X_test_t, y=y_t, params=params, folds=folds, model_type=args.model_type, eval_metric='group_mae', plot_feature_importance=True,\n verbose=500, early_stopping_rounds=200, n_estimators=n_estimators)\n X_short.loc[X_short['type'] == t, 'oof'] = result_dict_lgb['oof']\n X_short_test.loc[X_short_test['type'] == t, 'prediction'] = result_dict_lgb['prediction']\n result_dict_lgb['feature_importance'].to_csv('log/'+args.tag+'/'+str(type_)+'feature_importance.csv')\nsub['scalar_coupling_constant'] = X_short_test['prediction']\nsub.to_csv('log/' + args.tag +'/submission.csv', index=False)\n\nplot_data = pd.DataFrame(y)\nplot_data.index.name = 'id'\nplot_data['yhat'] = X_short['oof']\nplot_data['type'] = lbl.inverse_transform(X_short['type'])\n\ndef plot_oof_preds(ctype, llim, ulim):\n plt.figure(figsize=(6,6))\n sns.scatterplot(x='scalar_coupling_constant',y='yhat',\n data=plot_data.loc[plot_data['type']==ctype,\n ['scalar_coupling_constant', 'yhat']]);\n plt.xlim((llim, ulim))\n plt.ylim((llim, ulim))\n plt.plot([llim, ulim], [llim, ulim])\n plt.xlabel('scalar_coupling_constant')\n plt.ylabel('predicted')\n plt.title(str(ctype), fontsize=18)\n plt.savefig('log/'+args.tag+'/'+str(ctype)+'.png')\nplot_oof_preds('1JHC', 0, 250)\nplot_oof_preds('1JHC_UPPER', 0, 250)\nset_trace()\nplot_oof_preds('1JHN', 0, 100)\nplot_oof_preds('2JHC', -50, 50)\nplot_oof_preds('2JHH', -50, 50)\nplot_oof_preds('2JHN', -25, 25)\nplot_oof_preds('3JHC', -25, 100)\nplot_oof_preds('3JHH', -20, 20)\nplot_oof_preds('3JHN', -15, 15)\n\n","sub_path":"bin/search_1JHC.py","file_name":"search_1JHC.py","file_ext":"py","file_size_in_byte":5211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"207113864","text":"import tkinter as tk \r\nimport tkinter.ttk as ttk \r\n\r\nfrom PIL import ImageTk, Image\r\nimport pandas as pd \r\nimport numpy as np \r\nimport re\r\n\r\n# python scripts \r\nimport customer_page\r\nimport provide_credit_card\r\nimport complaint_page\r\nimport discussion_table\r\nimport purchase_history_page\r\nimport account_info_page\r\nimport search_info\r\nimport track_package\r\n\r\nclass setting_account(tk.Frame):\r\n \r\n def __init__( self, customer_name, customer_Id, customer_username, master = None ): #customer_name, customer_Id, customer_username ,\r\n tk.Frame.__init__(self, master) \r\n self.master.title( \"Setting Account Page\" )\r\n self.master.geometry( \"989x676\" )\r\n self.master.configure( background = \"light blue\" )\r\n \r\n \r\n # User account info \r\n self.customer_name = customer_name\r\n self.customer_username = customer_username \r\n self.customer_Id = customer_Id\r\n\r\n self.create_widgets()\r\n\r\n\r\n def create_widgets(self):\r\n self.top = self.winfo_toplevel()\r\n self.style = tk.ttk.Style() # Style\r\n \r\n #---------------------------------Title----------------------------------------\r\n self.style.configure( \r\n \"LabelTitle.TLabel\", \r\n relief = tk.SUNKEN,\r\n anchor = \"center\", \r\n font = (\"Helvetica\", 23),\r\n background = '#49A',\r\n foreground = \"black\" \r\n )\r\n self.LabelTitle = tk.ttk.Label( self.top, \r\n text = \"User Account Settings \", \r\n style = \"LabelTitle.TLabel\" \r\n ) \r\n self.LabelTitle.place( relx = 0.26, rely = 0.035, relwidth = 0.49, relheight = 0.085 )\r\n #----------------------------------------------------------------------------------\r\n\r\n #-------------------------Purchase History Section Button--------------------\r\n self.style.configure( \"Command_Purchase_History.TButton\", \r\n anchor = \"left\", \r\n font = ( \"Helvetica\", 14 ),\r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n \r\n self.Command_Purchase_History = tk.ttk.Button( self.top, \r\n text = \"Check My Purchase History\",\r\n command = self.Command_Purchase_History, \r\n style = \"Command_Purchase_History.TButton\" \r\n )\r\n self.Command_Purchase_History.place( relx = 0.1, rely = 0.2, relwidth = 0.300, relheight = 0.071 )\r\n #---------------------------------------------------------------------------------------\r\n\r\n #---------Provide/Update credit card information Section Button--------------------------------\r\n self.style.configure( \"Command_Credit_Card_Info.TButton\", \r\n anchor = \"left\", \r\n font = (\"Helvetica\", 14 ),\r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n self.Command_Credit_Card_Info = tk.ttk.Button( self.top, \r\n text = \"Provide/Update My Credit Card\", \r\n command = self.Command_Credit_Card_Info, \r\n style = \"Command_Credit_Card_Info.TButton\"\r\n )\r\n self.Command_Credit_Card_Info.place( relx = 0.1, rely = 0.35, relwidth = 0.300, relheight = 0.071)\r\n #-----------------------------------------------------------------------------------\r\n\r\n #-----------------------Track my current Package Section Button----------------------------\r\n self.style.configure( \"Command_Track_Package.TButton\", \r\n anchor = \"left\", \r\n font = ( \"Helvetica\", 14 ), \r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n self.Command_Track_Package = tk.ttk.Button( self.top, \r\n text = \"Track My Current Package\", \r\n command = self.Command_Track_Package,\r\n style = \"Command_Track_Package.TButton\"\r\n )\r\n self.Command_Track_Package.place( relx = 0.1, rely = 0.5, relwidth = 0.300, relheight = 0.071 )\r\n #-------------------------------------------------------------------------------\r\n\r\n\r\n #-----Search Info about clerks/delivery/companies Section Button------------------\r\n self.style.configure( \"Command_Search_info.TButton\", \r\n anchor = \"left\", \r\n font = ( \"Helvetica\", 14 ), \r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n self.Button_Search_info = tk.ttk.Button( self.top, \r\n text = \"Search Info\", \r\n command = self.Command_Search_info,\r\n style = \"Command_Search_info.TButton\"\r\n )\r\n self.Button_Search_info.place( relx = 0.1, rely = 0.65, relwidth = 0.300, relheight = 0.071 )\r\n #-------------------------------------------------------------------------------\r\n\r\n\r\n\r\n\r\n\r\n\r\n #----------------------View my account information Section Button--------------------\r\n self.style.configure( \"Command_Account_info.TButton\", \r\n anchor = \"left\", \r\n font = ( \"Helvetica\", 14 ),\r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n \r\n self.Button_account_info = tk.ttk.Button( self.top, \r\n text = \"View My Account Information\",\r\n command = self.command_account_info, \r\n style = \"Command_Account_info.TButton\" \r\n )\r\n self.Button_account_info.place( relx = 0.6, rely = 0.2, relwidth = 0.300, relheight = 0.071 )\r\n #---------------------------------------------------------------------------------------\r\n\r\n #---------Place a complaint Section Button--------------------------------\r\n self.style.configure( \"Command_Place_Complaint.TButton\", \r\n anchor = \"left\", \r\n font = (\"Helvetica\", 14 ),\r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n self.Command_Place_Complaint = tk.ttk.Button( self.top, \r\n text = \"Complaint and Report\", \r\n command = self.Command_Place_Complaint, \r\n style = \"Command_Place_Complaint.TButton\"\r\n )\r\n self.Command_Place_Complaint.place( relx = 0.6, rely = 0.35, relwidth = 0.300, relheight = 0.071)\r\n #-----------------------------------------------------------------------------------\r\n\r\n\r\n #-----------------View All My Review Section Button----------------------------\r\n self.style.configure( \"Command_Check_Review.TButton\", \r\n anchor = \"left\", \r\n font = ( \"Helvetica\", 14 ), \r\n background = \"green\",\r\n foreground = \"black\" \r\n )\r\n self.Command_Check_Review = tk.ttk.Button( self.top, \r\n text = \"Check All My Reviews\", \r\n command = self.Command_Check_Review,\r\n style = \"Command_Check_Review.TButton\"\r\n )\r\n self.Command_Check_Review.place( relx = 0.6, rely = 0.5, relwidth = 0.300, relheight = 0.071 )\r\n #-------------------------------------------------------------------------------\r\n\r\n #---------------------------Go Back Button---------------------------------------\r\n self.style.configure( \"Command_Go_Back.TButton\", font = (\"Helvetica\", 16),\r\n background = \"green\", foreground = \"black\" )\r\n self.CommandExit = tk.ttk.Button( self.top, \r\n text = \"Back\",\r\n command = self.Command_Go_Back,\r\n style = \"Command_Go_Back.TButton\" \r\n )\r\n self.CommandExit.place( relx = 0.86, rely = 0.92, relwidth = 0.119, relheight = 0.065)\r\n #---------------------------------------------------------------------------------\r\n\r\n\r\n def Command_Purchase_History(self):\r\n self.top.destroy() \r\n purchase_history_page.purchase_history_page(customer_name = self.customer_name, \r\n customer_Id = self.customer_Id, \r\n customer_username = self.customer_username)\r\n\r\n\r\n\r\n def Command_Credit_Card_Info(self):\r\n self.top.destroy()\r\n provide_credit_card.provide_credit_card(customer_name = self.customer_name, \r\n customer_Id = self.customer_Id, \r\n customer_username = self.customer_username )\r\n\r\n\r\n def Command_Track_Package(self):\r\n # Verify orders made before\r\n df = pd.read_excel(\"csv_files/orders.xlsx\")\r\n df = df[df['Username'] == self.customer_username]\r\n if len(df) == 0:\r\n tk.messagebox.showinfo(\"Info\", \"You haven't placed an order\")\r\n else:\r\n self.top.destroy()\r\n track_package.track_package(customer_name = self.customer_name, customer_username = self.customer_username, \r\n customer_Id = self.customer_Id)\r\n\r\n def command_account_info(self):\r\n self.top.destroy()\r\n account_info_page.account_info_page( customer_name = self.customer_name, \r\n customer_Id = self.customer_Id, customer_username = self.customer_username) \r\n \r\n\r\n def Command_Place_Complaint(self):\r\n self.top.destroy()\r\n complaint_page.complaint_page(self.customer_name, self.customer_Id, self.customer_username)\r\n\r\n def Command_Check_Review(self):\r\n discussion_type = \"Me All\"\r\n df = pd.read_excel( \"csv_files/discussions.xlsx\" )\r\n df_no_violated = df[df['Status'] == \"Non-Violated\"]\r\n df_me = df_no_violated[df_no_violated['Username'] == self.customer_username]\r\n if len(df_me) == 0:\r\n tk.messagebox.showinfo(\"Info\", \"You haven't posted any comment yet\")\r\n else:\r\n self.top.destroy()\r\n discussion_table.discussion_table(coming_from = None, \r\n coming_from_discuss = \"setting_account\",\r\n item_name = None, customer_name = self.customer_name, \r\n customer_Id = self.customer_Id, \r\n customer_username = self.customer_username, \r\n discussion_type = discussion_type, df = df_me)\r\n\r\n\r\n def Command_Go_Back(self):\r\n self.top.destroy()\r\n customer_page.customer_page(customer_name = self.customer_name, \r\n customer_username = self.customer_username, customer_Id = self.customer_Id)\r\n\r\n\r\n def Command_Search_info(self):\r\n self.top.destroy()\r\n search_info.search_info( customer_name = self.customer_name, \r\n customer_Id = self.customer_Id, \r\n customer_username = self.customer_username)\r\n\r\n# Test Only\r\n#---------------------Main----------\r\nif __name__ == \"__main__\":\r\n top = tk.Tk()\r\n setting_account(top).mainloop() ","sub_path":"setting_account.py","file_name":"setting_account.py","file_ext":"py","file_size_in_byte":12359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"523891244","text":"#####################################################################\n# #\n# ZJS @ Jan/08th/2021 #\n# #\n# excecute the main sh: sh *.sh #\n# #\n# change \"NPROC\" attribute to change core numbers #\n# #\n# #\n# This python script is intended to be run from the Maestro #\n# Command Input Area. #\n# #\n# While in the command input area enter: #\n# pythonimport \"title of this script\" #\n# #\n# If you can't see the command input area then open Maestro, #\n# select \"Window\" and check the box to the left of #\n# \"Command Input Area\" #\n# #\n#####################################################################\n\n\n\nfrom __future__ import print_function\nfrom schrodinger import maestro\nfrom schrodinger import structure\nfrom schrodinger import project\nimport os\nfrom math import exp as exp\n\ndef main ():\n# Dictionary holding column names for project table properties depending on the force field being used\n columns = {'mm2' : ['r_mmod_Potential_Energy-MM2*', 'r_mmod_Relative_Potential_Energy-MM2*'], \n 'mm3': ['r_mmod_Potential_Energy-MM3*', 'r_mmod_Relative_Potential_Energy-MM3*'], \n 'amber': ['r_mmod_Potential_Energy-AMBER*', 'r_mmod_Relative_Potential_Energy-AMBER*'], \n 'opls': ['r_mmod_Potential_Energy-OPLSA*', 'r_mmod_Relative_Potential_Energy-OPLSA*'], \n 'amber94': ['r_mmod_Potential_Energy-AMBER94', 'r_mmod_Relative_Potential_Energy-AMBER94'], \n 'mmff': ['r_mmod_Potential_Energy-MMFF94', 'r_mmod_Relative_Potential_Energy-MMFF94'], \n 'mmffs': ['r_mmod_Potential_Energy-MMFF94s', 'r_mmod_Relative_Potential_Energy-MMFF94s'], \n 'opls2001': ['r_mmod_Potential_Energy-OPLS-AA', 'r_mmod_Relative_Potential_Energy-OPLS-AA'], \n 'opls2005': ['r_mmod_Potential_Energy-OPLS-2005', 'r_mmod_Relative_Potential_Energy-OPLS-2005'], \n 'opls3': ['r_mmod_Potential_Energy-OPLS3', 'r_mmod_Relative_Potential_Energy-OPLS3'], \n 'opls3e': ['r_mmod_Potential_Energy-OPLS3e', 'r_mmod_Relative_Potential_Energy-OPLS3e']}\n\n# Start by selecting all entries in the project table, and making sure the first entry is in the workspace\n maestro.command(\"eplayergotofirst\")\n\n# Grab the entire project table\n pt = maestro.project_table_get()\n \n currentforcefield = ''\n for forcefield in list(columns):\n if not pt[1][columns[forcefield][0]] == None :\n currentforcefield = forcefield\n break\n\n# Create a directory to store the input files.\n os.popen( \"mkdir \" + str( pt[1]['s_m_title']+'-gaussian_files' ) )\n\n optsh_outputfile = str(pt[1]['s_m_title'])+'-opt_freq'\n energysh_outputfile = str(pt[1]['s_m_title'])+'-energy'\n\n opt_lst = []\n energy_lst = []\n \n# Create a dictionary with keys being each conformer name and a list of the\n# absolute and relative MM energies for the conformer.\n energies = {}\n \n# Make a loop to operate on every conformation in the project table.\n# This loop operates on one conformation.\n for row in pt.selected_rows:\n structure = maestro.workspace_get()\n conf_num = str(row).split(' ')[-1] \n \n# Open the output file for writing\n outputfile = open( row['s_m_title'] + \"-opt_freq-conf-\" + conf_num + \".com\", 'w' )\n energy_outputfile = open( row['s_m_title'] + \"-energy-conf-\" + conf_num + '.com', 'w' )\n\n opt_lst.append('g16 ' + row['s_m_title'] + \"-opt_freq-conf-\" + conf_num + \".com\")\n energy_lst.append('g16 ' + row['s_m_title'] + \"-energy-conf-\" + conf_num + \".com\")\n \n# Add the conformer energy to the dictionary of energies\n energies[ str( row['s_m_title'] + row['s_m_entry_id'] ) ] =[ row[columns[currentforcefield][0]], row[columns[currentforcefield][1]] ]\n \n# Write the Gaussian stuff that goes into every input deck.\n print(gaussian_input( \"link\", str( pt[1]['s_m_title']), str( conf_num )), file=outputfile) \n print(gaussian_energy_input( \"link\", str( pt[1]['s_m_title']), str( conf_num ) ), file=energy_outputfile) \n print(gaussian_input( \"route\" ), file=outputfile)\n print(gaussian_energy_input( \"route\" ), file=energy_outputfile)\n print(gaussian_input( \"title\", str( pt[1]['s_m_title']), str( conf_num )), file=outputfile)\n print(gaussian_energy_input( \"title\", str( pt[1]['s_m_title']), str( conf_num )), file=energy_outputfile)\n print(gaussian_input( \"molecule\" ), file=outputfile)\n print(gaussian_energy_input( \"molecule\" ), file=energy_outputfile)\n print(gaussian_energy_input( \"readline\" ), file=energy_outputfile)\n print(gaussian_energy_input( \"end\" ), file=energy_outputfile)\n\n# This loop operates on one atom.\n for atom in structure.atom:\n outputstring = \"%2s %10.6f %10.6f %10.6f\" % (atom.element, atom.x, atom.y, atom.z)\n print(outputstring, file=outputfile)\n\n print(gaussian_input( \"readline\" ), file=outputfile)\n print(gaussian_input(\"end\"), file=outputfile)\n \n# Close the opened output file.\n\n outputfile.flush()\n outputfile.close()\n energy_outputfile.flush()\n energy_outputfile.close()\n maestro.command(\"eplayerstepahead\")\n\n ######## to write_to\n write_optsh(opt_lst, optsh_outputfile)\n write_energysh(energy_lst, energysh_outputfile)\n\n # print('top',file=optsh_outputfile)\n # print('top',file=energysh_outputfile)\n \n # optsh_outputfile.flush()\n # optsh_outputfile.close()\n # energysh_outputfile.flush()\n # energysh_outputfile.close()\n\n# Move the created input files \"-gaussian_files\" directory.\n os.popen( \"mv \" + str(pt[1]['s_m_title'] + '*conf* ') + str(pt[1]['s_m_title']+'-gaussian_files'))\n os.popen( \"mv \" + str(pt[1]['s_m_title']+'*.sh ') + str(pt[1]['s_m_title']+'-gaussian_files'))\n \ndef convert_mmat_symbol(mmat):\n# mmat2Number = {1:'C',2:'C',3:'C',15:'O',16:'O',24:'N',25:'N',26:'N',41:'H',42:'H',43:'H',49:'S',56:'F',57:'Cl',58:'Br',59:'I'}\n# symbol = mmat2Number[mmat]\n# return symbol\n return {1:'C',2:'C',3:'C',15:'O',16:'O',24:'N',25:'N',26:'N',41:'H',42:'H',43:'H',49:'S',56:'F',57:'Cl',58:'Br',59:'I'}[mmat]\n\ndef gaussian_input(which_section,candidate_filename=\"X\", conformer_number=\"Y\"):\n\n NPROC = 8 # 4,8,16 are recommended\n ENDLINE = \"\\n\"\n LINK1 = \"%mem={}gb\\n\".format(2 * NPROC)\n LINK2 = \"%nproc={}\\n\".format(NPROC)\n LINK3 = \"%%chk=%s \\n\" % (candidate_filename +'-conf-' + conformer_number + \".chk\")\n LINK4 = \"\\nradii=UA0\\n\"\n ROUTE1 = \"# b3lyp/6-31G(d) opt freq=noraman em=gd3bj integral(ultrafinegrid) scrf=(iefpcm,read,solvent=methanol)\"\n TITLE1 = \"Candidate Structure: %s, Conformer: %s geometry optimization and frequency calculation with methanol solvation\" % (candidate_filename,conformer_number)\n MOL1 = \"0 1\"\n \n LINKZERO = LINK1 + LINK2 + LINK3\n ROUTE = ROUTE1 + ENDLINE\n TITLE = TITLE1 + ENDLINE\n MOLECULE = MOL1 \n READLINE = LINK4 +ENDLINE\n END = ENDLINE\n \n if (which_section == \"link\"): return LINKZERO\n if (which_section == \"route\"): return ROUTE\n if (which_section == \"title\"): return TITLE\n if (which_section == \"molecule\"): return MOLECULE\n if (which_section == \"readline\"): return READLINE\n if (which_section == \"end\"): return END\n if (which_section == \"NPROC\"): return NPROC\n\n return \"There is a problem generating the input files.\"\n \ndef gaussian_energy_input(which_section,candidate_filename=\"X\",conformer_number=\"Y\"):\n\n NPROC = 8 # 4,8,16 are recommended\n ENDLINE = \"\\n\"\n LINK1 = \"%mem={}gb\\n\".format(2 * NPROC)\n LINK2 = \"%nproc={}\\n\".format(NPROC)\n LINK3 = \"%%chk=%s \\n\" % (candidate_filename + '-conf-' + conformer_number + '.chk')\n LINK4 = \"radii=bondi\\n\"\n ROUTE1 = \"# td=(nstates=30,root=1) wb97xd/6-311g(d,p) guess=read geom=check integral(ultrafinegrid) scrf=(iefpcm,read,solvent=methanol)\"\n TITLE1 = \"Candidate Structure: %s, Conformer: %s, energy calculation with methanol solvation\" % (candidate_filename,conformer_number)\n MOL1 = \"0 1\"\n \n LINKZERO = LINK1 + LINK2 + LINK3\n ROUTE = ROUTE1 + ENDLINE\n TITLE = TITLE1 + ENDLINE\n MOLECULE = MOL1 + ENDLINE\n READLINE = LINK4 + ENDLINE\n END = ENDLINE\n\n if (which_section == \"link\"): return LINKZERO\n if (which_section == \"route\"): return ROUTE\n if (which_section == \"title\"): return TITLE\n if (which_section == \"molecule\"): return MOLECULE\n if (which_section == \"readline\"): return READLINE\n if (which_section == \"end\"): return END\n if (which_section == \"NPROC\"): return NPROC\n\n return \"There is a problem generating the input files.\"\n\ndef write_optsh(lst, file_to_write_to):\n \n nthread = int(64//gaussian_input(\"NPROC\"))\n i = 0\n opt_shlst = [str(file_to_write_to) + str('-') + str(m) + str('.sh') for m in range(1,65)]\n shcaller = str(file_to_write_to) + str('.sh')\n write_to_shcaller = ''\n\n while i < len(lst):\n temp = ''\n for j in range(nthread):\n if i + j < len(lst):\n temp += lst[i+j] + '&\\n'\n temp = temp[0:-2] + ';\\n'\n with open(opt_shlst[int(i//nthread)], 'w') as tempfile:\n print('#!/bin/sh\\n',file=tempfile)\n print('''echo \"{} Group {} is running. Please wait and do not add in new missions!\";\\n'''.format(file_to_write_to, int(i//nthread + 1)), file=tempfile)\n print(temp, file=tempfile)\n print('''echo \"{} Group {} is finished.\";\\n'''.format(file_to_write_to, int(i//nthread + 1)), file=tempfile)\n print('exit 0', file=tempfile)\n \n write_to_shcaller += str('sh ' + opt_shlst[int(i//nthread)] + ' && ')\n\n i += nthread\n\n write_to_shcaller = write_to_shcaller[0:-4]\n with open(shcaller, 'w') as sh:\n print('#!/bin/sh\\n', file=sh)\n print(write_to_shcaller, file=sh)\n\ndef write_energysh(lst, file_to_write_to):\n \n nthread = int(64//gaussian_energy_input(\"NPROC\"))\n i = 0\n energy_shlst = [str(file_to_write_to) + str('-') + str(m) + str('.sh') for m in range(1,65)]\n shcaller = str(file_to_write_to) + str('.sh')\n write_to_shcaller = ''\n\n while i < len(lst):\n temp = ''\n for j in range(nthread):\n if i + j < len(lst):\n temp += lst[i+j] + '&\\n'\n temp = temp[0:-2] + ';\\n'\n with open(energy_shlst[int(i//nthread)], 'w') as tempfile:\n print('#!/bin/sh\\n',file=tempfile)\n print('''echo \"{} Group {} is running. Please wait and do not add in new missions!\";\\n'''.format(file_to_write_to, int(i//nthread + 1)), file=tempfile)\n print(temp, file=tempfile)\n print('''echo \"{} Group {} is finished.\";\\n'''.format(file_to_write_to, int(i//nthread + 1)), file=tempfile)\n print('exit 0', file=tempfile)\n\n write_to_shcaller += str('sh ' + energy_shlst[int(i//nthread)] + ' && ')\n\n i += nthread\n \n write_to_shcaller = write_to_shcaller[0:-4]\n with open(shcaller, 'w') as sh:\n print('#!/bin/sh\\n', file=sh)\n print(write_to_shcaller, file=sh)\n\nmain()\n","sub_path":"g16-ecd-sh-v6.py","file_name":"g16-ecd-sh-v6.py","file_ext":"py","file_size_in_byte":11841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"624326602","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ct_accounts', '0006_auto_20150417_1325'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Ban',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('ban_start', models.DateTimeField(verbose_name='Ban start', default=django.utils.timezone.now)),\n ('ban_end', models.DateTimeField(blank=True, verbose_name='Ban end', null=True)),\n ('reason', models.TextField(verbose_name='Reason')),\n ('user', models.OneToOneField(verbose_name='Banned user', related_name='banned_accounts', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Ban',\n 'verbose_name_plural': 'Bans',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"apps/ct_accounts/migrations/0007_ban.py","file_name":"0007_ban.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"105065514","text":"from starlette.applications import Starlette\nfrom starlette.staticfiles import StaticFiles\nfrom starlette.responses import HTMLResponse\nimport uvicorn\n\n\napp = Starlette(debug=True, template_directory='templates')\napp.mount('/static', StaticFiles(directory='statics'), name='static')\n\n\n@app.route('/')\nasync def homepage(request):\n template = app.get_template('index.html')\n content = template.render(request=request)\n return HTMLResponse(content)\n\n\n@app.route('/error')\nasync def error(request):\n \"\"\"\n An example error. Switch the `debug` setting to see either tracebacks or 500 pages.\n \"\"\"\n raise RuntimeError(\"Oh no\")\n\n\n@app.exception_handler(404)\nasync def not_found(request, exc):\n \"\"\"\n Return an HTTP 404 page.\n \"\"\"\n template = app.get_template('404.html')\n content = template.render(request=request)\n return HTMLResponse(content, status_code=404)\n\n\n@app.exception_handler(500)\nasync def server_error(request, exc):\n \"\"\"\n Return an HTTP 500 page.\n \"\"\"\n template = app.get_template('500.html')\n content = template.render(request=request)\n return HTMLResponse(content, status_code=500)\n\n\nif __name__ == \"__main__\":\n uvicorn.run(app, host='0.0.0.0', port=8000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"157259267","text":"from collections import defaultdict\nfrom itertools import zip_longest\nimport operator\nfrom typing import DefaultDict, Dict, List, Optional, Set\nfrom typing import Tuple\n\n\nPoint = Tuple[int, int]\nDistDict = DefaultDict[int, List]\n\n\ndef compute_manhattan_dist(curr_point: Point) -> int:\n\n return abs(curr_point[0]) + abs(curr_point[1])\n\n\ndef traverse(start_point: Point, command: str, min_dist: Optional[int], dict_1: DistDict, dict_2: DistDict) -> \\\n (Point, int):\n\n direction, distance = command[0], int(command[1:])\n step = {'U': (0, 1), 'D': (0, -1), 'R': (1, 0), 'L': (-1, 0)}[direction]\n curr_point = start_point\n\n for i in range(1, distance + 1):\n curr_point = tuple(map(operator.add, curr_point, step))\n curr_dist = compute_manhattan_dist(curr_point)\n if min_dist and curr_dist >= min_dist:\n if curr_dist < compute_manhattan_dist(tuple(map(operator.add, curr_point, step))):\n break\n continue\n dict_1[curr_dist].append(curr_point)\n if curr_point in dict_2[curr_dist] and (not min_dist or curr_dist < min_dist):\n print(curr_point)\n min_dist = curr_dist\n\n return tuple(map(operator.add, start_point, (step[0] * distance, step[1] * distance))), min_dist\n\n\ndef traverse_2(start_point: Point, command: str, min_dist: Optional[int], dict_1: Dict[Tuple[int, int], int],\n dict_2: Dict[Tuple[int, int], Set], curr_dist: int) -> (Point, int, int):\n\n direction, distance = command[0], int(command[1:])\n step = {'U': (0, 1), 'D': (0, -1), 'R': (1, 0), 'L': (-1, 0)}[direction]\n curr_point = start_point\n\n for i in range(1, distance + 1):\n curr_point = tuple(map(operator.add, curr_point, step))\n curr_dist = curr_dist + 1\n if curr_point not in dict_1:\n dict_1[curr_point] = curr_dist\n if curr_point in dict_2:\n if not min_dist or curr_dist + dict_2[curr_point] < min_dist:\n min_dist = curr_dist + dict_2[curr_point]\n\n return curr_point, min_dist, curr_dist\n\n\ndef find_closest_cross(wire_paths_1: List[str], wire_paths_2: List[str]) -> int:\n\n dict_1 = defaultdict(list)\n dict_2 = defaultdict(list)\n min_dist = None\n curr_point_1 = (0, 0)\n curr_point_2 = (0, 0)\n\n for next_move_1, next_move_2 in zip_longest(wire_paths_1, wire_paths_2):\n if next_move_1:\n curr_point_1, min_dist = traverse(curr_point_1, next_move_1, min_dist, dict_1, dict_2)\n if next_move_2:\n curr_point_2, min_dist = traverse(curr_point_2, next_move_2, min_dist, dict_2, dict_1)\n\n return min_dist\n\n\ndef find_closest_cross_2(wire_paths_1: List[str], wire_paths_2: List[str]) -> int:\n\n dict_1 = {}\n dict_2 = {}\n min_dist = None\n curr_point_1 = (0, 0)\n curr_point_2 = (0, 0)\n curr_dist_1 = curr_dist_2 = 0\n\n for next_move_1, next_move_2 in zip_longest(wire_paths_1, wire_paths_2):\n if next_move_1:\n curr_point_1, min_dist, curr_dist_1 = traverse_2(curr_point_1, next_move_1, min_dist, dict_1, dict_2,\n curr_dist_1\n )\n if next_move_2:\n curr_point_2, min_dist, curr_dist_2 = traverse_2(curr_point_2, next_move_2, min_dist, dict_2, dict_1,\n curr_dist_2\n )\n\n return min_dist\n\n\nif __name__ == '__main__':\n\n lines = open('input1.txt').read().splitlines()\n wire_path_1 = lines[0].split(',')\n wire_path_2 = lines[1].split(',')\n\n print(find_closest_cross_2(wire_path_1, wire_path_2))\n","sub_path":"Problem_3/problem_3.py","file_name":"problem_3.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"129491917","text":"\nimport numpy as np\nfrom scipy.stats import multivariate_normal\nimport scipy\nfrom scipy.special import gamma \n\ndef marginal_likelihood_NIW(points):\n n=len(points)\n p=len(points[0])\n mean_data = np.mean(points, axis=0)\n sum_squares = np.sum([np.array(np.matrix(x - mean_data).T * np.matrix(x - mean_data)) for x in points], axis=0)\n k0=3.0\n v0=10\n sigma0=np.eye(p)\n mu0=[0]*p\n kn=k0+n\n vn=v0+n\n sigman=sigma0+sum_squares+(float(k0*n)/(k0+n))*np.dot((mean_data-mu0).reshape(p,1),(mean_data-mu0).reshape(1,p))\n gammadn=reduce(lambda x,y: x*y, map(lambda x:gamma((vn+1-x)*0.5),range(1,p+1)))\n gammad0=reduce(lambda x,y: x*y, map(lambda x:gamma((v0+1-x)*0.5),range(1,p+1)))\n mar_like=np.pi**(-p*n*0.5)*(np.linalg.det(sigma0))**(v0*0.5)*(k0/kn)**(0.5*p)*gammadn/(float(gammad0)*(np.linalg.det(sigman))**(vn*0.5))\n \n return mar_like\n\nclass bicluster:\n def __init__(self, point, left=None,right=None,probability=None,d=None,id=None):\n self.left = left\n self.right = right \n self.point = point \n self.id = id \n self.probability = probability\n self.d=d\n \ndef yezi(clust):\n if clust.left == None and clust.right == None :\n return [clust.id]\n return yezi(clust.left) + yezi(clust.right)\n \n \n#cluster function\ndef bcluster(data,function) :\n dim=len(data[0])\n alpha=3\n biclusters = [ bicluster(point = [data[i]], id = i ,probability=0.0000001,d=alpha) for i in range(len(data))] #initialize: each point is a cluster\n \n flag = None;\n currentclusted = -1 #id for the new cluster\n \n if len(biclusters) == 1:\n clusters = [yezi(biclusters[i]) for i in range(len(biclusters))] \n return biclusters,clusters\n \n while(len(biclusters) > 1) : \n max_prob = 0; \n biclusters_len = len(biclusters)\n for i in range(biclusters_len-1) :\n for j in range(i + 1, biclusters_len) :\n \n #calculate P_H1: MC method\n temp_cluster_points= biclusters[i].point + biclusters[j].point\n P_H1=function(temp_cluster_points)\n #P_H1=marginal_likelihood_DW(temp_cluster_points)\n pi=float(scipy.misc.factorial(len(temp_cluster_points)-1))*alpha/(float(scipy.misc.factorial(len(temp_cluster_points)-1))*alpha+biclusters[i].d*biclusters[j].d)\n marginal_prob=pi*P_H1+(1-pi)*biclusters[i].probability*biclusters[j].probability\n r = pi*P_H1/marginal_prob\n if r > max_prob :\n max_prob = r\n flag = (i,j)\n \n if max_prob<0.5: \n break\n \n bic1,bic2 = flag \n \n newpoint = biclusters[bic1].point + biclusters[bic2].point #combine the points of two clusters into the new cluster\n P_H1=function(newpoint)\n #P_H1=marginal_likelihood_DW(newpoint)\n \n newprob=pi*P_H1+(1-pi)*biclusters[bic1].probability*biclusters[bic2].probability\n newd=float(scipy.misc.factorial(len(newpoint)-1))*alpha+biclusters[bic1].d*biclusters[bic2].d\n newbic = bicluster(point=newpoint, left=biclusters[bic1], right=biclusters[bic2], probability=newprob, d=newd, id = currentclusted) \n currentclusted -= 1\n \n del biclusters[bic2] \n del biclusters[bic1]\n biclusters.append(newbic)\n clusters = [yezi(biclusters[i]) for i in range(len(biclusters))] \n \n return biclusters,clusters","sub_path":"STA663/Projects/Bayesian HC/Bayhiecluster.py","file_name":"Bayhiecluster.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"179927998","text":"#\r\n# This is a script to construct and play Tic Tac Toe\r\n#\r\n# define library\r\nimport random\r\nimport time\t# use time delays to view screens\r\nimport os\t# clear screen\r\nimport sys\r\n\r\n# yeah I won \r\ndef yeah_I_won():\r\n\tprint ('Yeah, I WonI, I Won!')\r\n\ttime.sleep(5)\r\n\tsys.exit(\"I win, I Win, exiting\")\r\n\r\n# Is the grid full\r\ndef is_the_grid_full():\r\n# Testing the full condition\r\n\t#board[1] = 'o'\r\n\t#board[2] = 'o'\r\n\t#board[3] ='o'\r\n\t#board[4] = 'o'\r\n\t#board[5] = 'o'\r\n\t#board[6] = 'o'\r\n\t#board[7] = 'o'\r\n\t#board[8] = 'o'\r\n\t#board[9] = 'o'\r\n\t\r\n\tcnt = 0\r\n\tlist = [1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n\tfor valu in list: # check all squares for x and y\r\n\t\tif (board[valu] == 'o'):\r\n\t\t\tcnt = cnt + 1\r\n\t\tif (board[valu] == 'x'):\r\n\t\t\tcnt = cnt + 1\r\n\t\t\t#print ('cnt', cnt)\r\n\t\tif cnt == 9 :\r\n\t\t\tprint('The game is a tie, Exiting')\r\n\t\t\ttime.sleep(5)\r\n\t\t\tsys.exit('The game is a tie, Exiting')\r\n\t\telse:\r\n\t\t\texit\r\n\treturn()\r\n\r\n#Check to see if we did win\r\ndef did_I_winO():\r\n\t#print ('Here in did_I_winO')\r\n\t#time.sleep(3)\r\n\tif (board[1] == 'o') and (board[4] == 'o') and (board[7] == 'o'):\r\n\t\tyeah_I_won()\r\n\t\t\r\n\tif (board[2] == 'o') and (board[5] == 'o') and (board[8] == 'o'):\r\n\t\tyeah_I_won()\t\r\n\t\r\n\tif (board[3] == 'o') and (board[6] == 'o') and (board[9] == 'o'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[1] == 'o') and (board[2] == 'o') and (board[3] == 'o'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[4] == 'o') and (board[5] == 'o') and (board[6] == 'o'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[7] == 'o') and (board[8] == 'o') and (board[9] == 'o'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[1] == 'o') and (board[5] == 'o') and (board[9] == 'o'):\r\n\t\tyeah_I_won()\r\n\t\t\r\n\tif (board[3] == 'o') and (board[5] == 'o') and (board[7] == 'o'):\r\n\t\tyeah_I_won()\r\n\t\t\r\n\t#print ('Exiting did_I_winO')\r\n\t#time.sleep(3)\r\n\t\r\n\treturn()\r\n\r\n#Check to see if we did win\r\ndef did_I_winX():\r\n\t#print ('Here in did_i_winX')\r\n\tif (board[1] == 'x') and (board[4] == 'x') and (board[7] == 'x'):\r\n\t\tyeah_I_won()\r\n\t\t\r\n\tif (board[2] == 'x') and (board[5] == 'x') and (board[8] == 'x'):\r\n\t\tyeah_I_won()\t\r\n\t\r\n\tif (board[3] == 'x') and (board[6] == 'x') and (board[9] == 'x'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[1] == 'x') and (board[2] == 'x') and (board[3] == 'x'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[4] == 'x') and (board[5] == 'x') and (board[6] == 'x'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[7] == 'x') and (board[8] == 'x') and (board[9] == 'x'):\r\n\t\tyeah_I_won()\r\n\r\n\tif (board[1] == 'x') and (board[5] == 'x') and (board[9] == 'x'):\r\n\t\tyeah_I_won()\r\n\t\t\r\n\tif (board[3] == 'x') and (board[5] == 'x') and (board[7] == 'x'):\r\n\t\tyeah_I_won()\r\n\t\t\r\n\t#print ('Exiting did_i_winX')\r\n\treturn()\r\n\r\n# Check to see if x is about to win if so block\r\ndef block_winX():\r\n\t#print ('Here in block_winX')\r\n\t#time.sleep(3)\r\n\tchange_made = 0\r\n#seq_spin1\r\n\tif (board[1] == 'x') and (board[4] == 'x') and (board[7] != 'x') and (board[7] != 'o'):\r\n\t\tboard[7] = 'o'\r\n\t\tchange_made = 1 \r\n\t\t\r\n\tif (board[3] == 'x') and (board[6] == 'x') and (board[9] != 'x') and (board[9] != 'o'):\r\n\t\tboard[9] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[2] == 'x') and (board[5] == 'x') and (board[8] != 'x') and (board[8] != 'o'):\r\n\t\tboard[8] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n#seq_spin2\r\n\tif (board[1] == 'x') and (board[2] == 'x') and (board[3] != 'x') and (board[3] != 'o'):\r\n\t\tboard[3] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[4] == 'x') and (board[5] == 'x') and (board[6] != 'x') and (board[6] != 'o'):\r\n\t\tboard[6] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[7] == 'x') and (board[8] == 'x') and (board[9] != 'x') and (board[9] != 'o'):\r\n\t\tboard[9] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n#seq_spin3\r\n\tif (board[2] == 'x') and (board[3] == 'x') and (board[1] != 'x') and (board[1] != 'o'):\r\n\t\tboard[1] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[5] == 'x') and (board[6] == 'x') and (board[4] != 'x') and (board[4] != 'o'):\r\n\t\tboard[4] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[8] == 'x') and (board[9] == 'x') and (board[7] != 'x') and (board[7] != 'o'):\r\n\t\tboard[7] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n#seq_spin4\r\n\tif (board[4] == 'x') and (board[7] == 'x') and (board[1] != 'x') and (board[1] != 'o'):\r\n\t\tboard[1] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[5] == 'x') and (board[8] == 'x') and (board[2] != 'x') and (board[2] != 'o'):\r\n\t\tboard[2] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[6] == 'x') and (board[9] == 'x') and (board[3] != 'x') and (board[3] != 'o'):\r\n\t\tboard[3] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n#edge_spin1\r\n\tif (board[1] == 'x') and (board[7] == 'x') and (board[4] != 'x') and (board[4] != 'o'):\r\n\t\tboard[4] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[2] == 'x') and (board[8] == 'x') and (board[5] != 'x') and (board[5] != 'o'):\r\n\t\tboard[5] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[3] == 'x') and (board[9] == 'x') and (board[6] != 'x') and (board[6] != 'o'):\r\n\t\tboard[6] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n#edge_spin2\r\n\tif (board[1] == 'x') and (board[3] == 'x') and (board[2] != 'x') and (board[2] != 'o'):\r\n\t\tboard[2] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[4] == 'x') and (board[6] == 'x') and (board[5] != 'x') and (board[5] != 'o'):\r\n\t\tboard[5] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[7] == 'x') and (board[9] == 'x') and (board[8] != 'x') and (board[8] != 'o'):\r\n\t\tboard[8] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n#center_spin1\r\n\tif (board[1] == 'x') and (board[9] == 'x') and (board[5] != 'x') and (board[5] != 'o'):\r\n\t\tboard[5] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[3] == 'x') and (board[7] == 'x') and (board[5] != 'x') and (board[5] != 'o'):\r\n\t\tboard[5] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[3] == 'x') and (board[5] == 'x') and (board[7] != 'x') and (board[7] != 'o'):\r\n\t\tboard[7] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[2] == 'x') and (board[5] == 'x') and (board[8] != 'x') and (board[8] != 'o'):\r\n\t\tboard[8] = 'o'\t\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[1] == 'x') and (board[5] == 'x') and (board[9] != 'x') and (board[9] != 'o'):\r\n\t\tboard[9] = 'o'\t\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[4] == 'x') and (board[5] == 'x') and (board[6] != 'x') and (board[6] != 'o'):\r\n\t\tboard[6] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[7] == 'x') and (board[5] == 'x') and (board[2] != 'x') and (board[2] != 'o'):\r\n\t\tboard[2] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[8] == 'x') and (board[5] == 'x') and (board[7] != 'x') and (board[7] != 'o'):\r\n\t\tboard[7] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[9] == 'x') and (board[5] == 'x') and (board[1] != 'x') and (board[1] != 'o'):\r\n\t\tboard[1] = 'o'\r\n\t\tchange_made = 1\r\n\t\t\r\n\tif (board[6] == 'x') and (board[5] == 'x') and (board[4] != 'x') and (board[4] != 'o'):\r\n\t\tboard[4] = 'o'\r\n\t\tchange_made = 1\r\n\t\r\n\t#print ('Exiting block_winX')\r\n\t#time.sleep(3)\r\n\treturn( change_made )\r\n\r\n# Place a character in grid\r\ndef place_char():\r\n\t#print('Here in place_char function')\r\n\t#time.sleep(3)\r\n# list of squares to choose from\r\n\tmy_list = [1, 3, 5, 7, 9, 2, 6, 8, 4]\r\n\tfor valu in my_list:\r\n# Make sure square is empty then apply value to square\r\n\t\tif (board[valu] != 'x') and (board[valu] != 'o'):\r\n# Apply value to square\r\n\t\t\t#time.sleep(3)\r\n\t\t\tboard[valu] = 'o'\r\n\t\t\t#time.sleep(3)\r\n\t\t\tos.system('cls')\r\n\t\t\tgrid()\r\n\t\t\tprint ('Computer (O) is now playing')\r\n\t\t\tprint ('Please Wait!: ')\r\n# Test the win codition\r\n\t\t\t#board[2] = 'o' \r\n\t\t\t#board[5] = 'o' \r\n\t\t\t#board[8] = 'o'\r\n\t\t\t#is_the_grid_full()\r\n\t\t\t#print('waiting 5 sec')\r\n\t\t\t#time.sleep(5)\r\n\t\t\treturn()\r\n\t\telse:\r\n\t\t\t#print('Here at if else')\r\n\t\t\texit\r\n\r\n# Execute the Computer player\r\ndef c_player():\r\n# Execute Computer player\r\n\tchange_made = block_winX()\r\n\t#print('Here in c_player')\r\n\t#print('chang_made', change made)\r\n\tos.system('cls')\r\n\tgrid()\r\n\tprint ('Computer (O) is now playing')\r\n\tprint ('Working!')\r\n\ttime.sleep(3)\r\n\tblock_winX()\r\n\tdid_I_winO()\r\n\t#print ('change_made =', change made)\r\n\t#time.sleep(3)\r\n\t#jump over if change made 1\r\n\tif (change_made == 0):\r\n\t\tplace_char()\r\n\tos.system('cls')\r\n\tgrid()\r\n\tprint ('Computer (O) is now playing')\r\n\tprint ('Working!')\t\r\n\tdid_I_winO()\r\n\tis_the_grid_full()\r\n\ttime.sleep(1)\r\n\t#print ('returning to main')\r\n\t#time.sleep(1)\r\n\r\n# Execute the x player\r\ndef x_player():\r\n# Place the entry into grid for X\r\n\tos.system('cls')\r\n\tgrid()\r\n\tprint ('Player (X) is now playing')\r\n\tval = input('\\tSelect a square for entry: ')\r\n\tval = int(val)\r\n# Make sure square is empty then apply value to square\r\n\tif (board[val] != 'x') and (board[val] != 'o'):\r\n\t# apply value to square\r\n\t\tboard[val] = 'x'\r\n#Test the Win condition\r\n\t\t#board[1] = 'x'\r\n\t\t#board[5] = 'x'\r\n\t\t#board[9] = 'x'\r\n\t\tos.system('cls')\r\n\t\tgrid()\r\n\t\tprint ('Player (X) is now playing')\r\n\t\tprint ('Working, Please Wait ! ')\r\n\t\t#print ('going to did I winX')\r\n\t\tdid_I_winX()\r\n\t\t#print ('return from did I winX')\r\n\t\t#print ('going to is the grill full')\r\n\t\tis_the_grid_full()\r\n\t\t#print ('return from is the grid full')\r\n\t\ttime.sleep(1)\r\n\telse:\r\n\t\tos.system('cls')\r\n\t\tgrid()\r\n\t\tprint ('player (X) is now playing')\r\n\t\tprint ('You are trying to overwrite an existing entry, select another entry')\r\n\t\ttime.sleep(3)\r\n\r\n\r\n# Create the grid\r\ndef grid():\r\n\tprint()\r\n\tprint(board[1], '|', board[2], '|', board[3])\r\n\tprint('----------')\r\n\tprint(board[4], '|', board[5], '|', board[6])\r\n\tprint('----------')\r\n\tprint(board[7], '|', board[8], '|', board[9])\r\n\tprint()\r\n\r\n\t\r\n#########################################\r\n\r\n# Script Introduction\r\nprint('\\nHello Convo Communications, Here is my Tic Tac Toe scripting \\nassignment written in Object Oriented form...')\r\ninput ('\\nPress Enter to continue....')\r\nos.system('cls')\r\nprint('\\nGame Rules: \\n1.You will always play againt the AI as X or O\\n2.You can choose to go 1st or 2nd: ')\r\ninput ('\\nPress Enter to continue....')\r\nos.system('cls')\r\n# Select players\r\na = 'y'\r\nos.system('cls')\r\nb = input('\\nDo you want to go First?__y/n ')\r\n\r\nboard = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\ngrid()\r\n\r\n# Call the players of the game\r\n\r\nif (a == \"y\") and (b == 'y'):\r\n\twhile (True) :\r\n\t\tprint('You are the X player')\r\n\t\tx_player()\r\n\t\t#print('returned from x_player')\r\n\t\ttime.sleep(3)\r\n\t\t#print('Computer is O player')\r\n\t\t#time.sleep(3)\r\n\t\tc_player()\r\n\t\t#print('returned from c_player')\r\n\t\t#time.sleep(3)\r\n\r\nif (a == \"y\") and (b =='n'):\r\n\twhile (True):\r\n\t\tprint('The Computer is the X player')\r\n\t\tc_player()\r\n\t\t#print('returned from x_player')\r\n\t\t#time.sleep(1)\r\n\t\tprint('You are the O player')\r\n\t\tx_player()\r\n\t\t#print('returned to main')\r\n\t\t#time.sleep(1)\r\n\r\n# Pause execution so the Users can see the results\r\ninput('Press Enter to Exit the script ...')\r\n","sub_path":"tic_tac_toe_V4_.py","file_name":"tic_tac_toe_V4_.py","file_ext":"py","file_size_in_byte":10295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"390578300","text":"import os\nimport cv2\nimport shutil\n\n\ndef main(input_path, result_path):\n image_names = os.listdir(input_path)\n for name in image_names:\n if any(i in name for i in ['MASK', 'COMBINE', 'PARSING']):\n name_split = name.replace('.JPG', '').split('_')\n dir_name = name_split[-6:]\n cur_result_path = os.path.join(result_path, dir_name[0],\n '_'.join(dir_name[0:5]),\n '_'.join(dir_name))\n shutil.copyfile(\n os.path.join(\n cur_result_path, '_'.join(name_split[:(\n 4 if name_split[4].startswith('2020') else 5)])) +\n '.JPG',\n os.path.join(\n input_path,\n name.replace('MASK', 'ZMASK').replace(\n 'COMBINE', 'ZCOMBINE').replace('PARSING', 'ZPARSING')))\n print(\n 'copy',\n os.path.join(cur_result_path, '_'.join(name_split[:-6])) +\n '.JPG', 'to',\n os.path.join(\n input_path,\n name.replace('MASK', 'ZMASK').replace(\n 'COMBINE', 'ZCOMBINE').replace('PARSING', 'ZPARSING')))\n\n\nif __name__ == '__main__':\n main('H:/images', 'F:/human/result/final')\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"374897710","text":"from typing import Iterable, Union, List, Dict, Optional, Callable, Tuple, Any\n\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoModelForMaskedLM, AutoTokenizer\n\nfrom collections import defaultdict\n\nfrom itertools import chain\nfrom re import sub\n\nclass LMScorer:\n \"\"\"\n Base LM scorer class intended to store models and tokenizers along\n with methods to facilitate the analysis of language model output scores.\n \"\"\"\n def __init__(self, model_name: str, device: Optional[str] = 'cpu') -> None:\n \"\"\"\n :param model_name: name of the model, should either be a path\n to a model (.pt or .bin file) stored locally, or a\n pretrained model stored on the Huggingface Model Hub.\n :type model_name: str\n :param device: device type that the model should be loaded on,\n options: `cpu or cuda:{0, 1, ...}`\n :type device: str, optional\n \"\"\"\n self.tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast = True)\n self.device = device\n self.vocab = defaultdict(list)\n {self.vocab[x.strip()].append(i) for x, i in [(self.tokenizer.decode([i]), i) for i in range(self.tokenizer.vocab_size)]}\n\n def add_special_tokens(self, text: Union[str, List[str]]) -> Union[str, List[str]]:\n raise NotImplementedError\n \n def distribution(self, batch: Iterable) -> torch.Tensor:\n raise NotImplementedError\n \n def topk(self, distribution: torch.Tensor, k: int = 1) -> Tuple:\n top_k = distribution.topk(k)\n \n probs = top_k.values.squeeze(1).exp().tolist()\n if k == 1:\n tokens = self.decode(top_k.indices.squeeze(1))\n else:\n tokens = [self.decode(x) for x in top_k.indices.squeeze(1)]\n \n return tokens, probs\n\n def query(self, distribution: torch.Tensor, queries: List[str]) -> Tuple:\n # this will be self.vocab tho\n query_ids = [self.vocab[a] for a in queries]\n maxlen = max(map(len, query_ids))\n query_ids = [q + [self.tokenizer.pad_token_id] * (maxlen - len(q)) if len(q) < maxlen else q for q in query_ids]\n current_batch_size = distribution.shape[0]\n probs = distribution[torch.arange(current_batch_size)[:, None], query_ids].max(1).values.exp().tolist()\n \n inv_ranks = distribution.argsort().argsort() + 1\n ranks = distribution.shape[1] - inv_ranks + 1\n token_ranks = ranks[torch.arange(current_batch_size)[:, None], query_ids].min(1).values.tolist()\n \n return probs, token_ranks\n\n def logprobs(self, batch: Iterable, rank: bool = False) -> Union[float, List[float]]:\n raise NotImplementedError\n\n def prepare_text(self, text: Union[str, List[str]]) -> Union[str, List[str]]:\n raise NotImplementedError\n\n def prime_text(self, preamble: Union[str, List[str]], stimuli: Union[str, List[str]]) -> Tuple:\n raise NotImplementedError\n\n def seq_score(self, batch: Iterable):\n raise NotImplementedError\n \n def score(self, batch: Union[str, List[str]], pool: Callable = torch.mean, *args) -> Union[float, List[float]]:\n '''\n Pooled estimates of sentence log probabilities, computed by the\n language model. Pooling is usually done using a function that\n is passed to the method.\n\n :param batch: a list of sentences that will be passed to the\n language model to score.\n :type batch: Union[str, List[str]]\n :param pool: Pooling function, is selected to be\n `torch.mean()` by default.\n :type pool: Callable\n :return: Float or list of floats specifying the log\n probabilities of the input sentence(s).\n :rtype: Union[float, List[float]]\n '''\n result = self.logprobs(self.prepare_text(batch))\n logprob, _ = list(zip(*result))\n pooled = list(map(lambda x: pool(x, *args).tolist(), logprob))\n \n return pooled\n \n def adapt_score(self, preamble: Union[str, List[str]], stimuli: Union[str, List[str]], pool: Callable = torch.mean, *args) -> Union[float, List[float]]:\n '''\n Pooled estimates of sequence log probabilities, given a\n preamble, computed by the language model. Pooling is usually\n done using a function that is passed to the method.\n\n :param preamble: a batch of preambles or primes passed to the\n language model. This is what the sequence is conditioned on,\n and the model ignores the word probabilities of this part\n of the input in estimating the overall score.\n :type preamble: Union[str, List[str]]\n :param stimuli: a batch of sequences (same length as preamble)\n that form the main input consisting of the sequence whose\n score you want to calculate.\n :type stimuli: Union[str, List[str]]\n :param pool: Pooling function, is selected to be\n `torch.mean()` by default.\n :type pool: Callable\n :return: Float or list of floats specifying the log\n probabilities of the input sentence(s). \n :rtype: Union[float, List[float]]\n '''\n result = self.logprobs(self.prime_text(preamble, stimuli))\n logprob, _ = list(zip(*result))\n poold = list(map(lambda x: pool(x, *args).tolist(), logprob))\n \n return poold\n\n def encode(self, text: Union[str, List[str]], manual_special: bool = True, return_tensors: Optional[str] = 'pt') -> Dict:\n \"\"\"\n Encode a batch of sentences using the model's tokenizer.\n Equivalent of calling `model.tokenizer(input)`\n\n :param ``Union[str, List[str]]`` text: Input batch/sentence to\n be encoded.\n :param manual_special: Specification of whether special tokens\n will be manually encoded.\n :type manual_special: bool\n :param return_tensors: returned tensor format. Default `'pt'`\n :type manual_special: str\n :return: Encoded batch \n \"\"\"\n sentences = [text] if isinstance(text, str) else text\n\n if manual_special:\n # manually add special tokens\n sentences = self.add_special_tokens(sentences)\n if return_tensors:\n tokens = self.tokenizer.batch_encode_plus(sentences, add_special_tokens = False, padding = 'longest', return_attention_mask = True, return_tensors = return_tensors)\n else:\n # mostly for masked LMs\n tokens = self.tokenizer.batch_encode_plus(sentences, padding = 'longest', return_attention_mask = True)\n\n return tokens\n \n def decode(self, idx):\n \"\"\"\n Decode input ids using the model's tokenizer.\n\n :param idx: list of ids.\n :return: Encoded batch \n \"\"\"\n return [self.tokenizer.decode([x]).strip() for x in self.tokenizer.convert_tokens_to_ids(self.tokenizer.convert_ids_to_tokens(idx))]\n\nclass MaskedLMScorer(LMScorer):\n \"\"\"\n Implements LM scoring and output probability analysis for masked\n language models such as BERT and RoBERTa.\n \"\"\"\n def __init__(self, model_name: str, device: Optional[str] = 'cpu') -> None:\n \"\"\"\n :param model_name: name of the model, should either be a path\n to a model (.pt or .bin file) stored locally, or a\n pretrained model stored on the Huggingface Model Hub.\n\n :type model_name: str\n :param device: device type that the model should be loaded on,\n options: `cpu or cuda:{0, 1, ...}`\n :type device: str, optional\n \"\"\"\n super(MaskedLMScorer, self).__init__(model_name, device)\n \n self.model = AutoModelForMaskedLM.from_pretrained(model_name, return_dict = True)\n self.model.to(self.device)\n self.model.eval()\n \n # define CLS and SEP tokens\n self.bos_token_id = self.tokenizer.cls_token_id\n self.eos_token_id = self.tokenizer.sep_token_id\n self.cls_token_id = self.tokenizer.cls_token_id\n self.sep_token_id = self.tokenizer.sep_token_id\n self.mask_token_id = self.tokenizer.mask_token_id\n self.pad_token_id = self.tokenizer.pad_token_id\n \n def add_special_tokens(self, text: Union[str, List[str]]) -> Union[str, List[str]]:\n \"\"\"\n Reformats input text to add special model-dependent tokens.\n\n :param text: single string or batch of strings to be\n modified.\n :type text: Union[str, List[str]]\n :return: Modified input, containing special tokens as per \n tokenizer specification\n :rtype: Union[float, List[float]]:\n \"\"\"\n sentences = [text] if isinstance(text, str) else text\n sentences = [self.tokenizer.cls_token + \" \" + sentence + \" \" + self.tokenizer.sep_token for sentence in sentences]\n\n return sentences\n\n def mask(self, sentence_words: Union[Tuple[str], List[Tuple[str]]]) -> Tuple:\n \"\"\"\n Processes a list of (sentence, word) into input that has the\n word masked out of the sentence. \n \n Note: only works for masked LMs.\n\n :param ``Union[Tuple[str], List[Tuple[str]]]`` sentence_words:\n Input consisting of `[(sentence, word)]`, where sentence\n is an input sentence, and word is a word present in the\n sentence that will be masked out.\n :return: Tuple `(sentence, word, length)`\n \"\"\"\n sentence_words = [sentence_words] if isinstance(sentence_words[0], str) else sentence_words\n sentences, words = list(zip(*sentence_words))\n words = list(words)\n length = len(words)\n\n sentences = [sub(rf'(? torch.Tensor:\n \"\"\"\n Runs inference on masked input. \n Note: only works for masked LMs.\n\n :param ``Union[Tuple[str], List[Tuple[str]]]`` sentence_words:\n Input consisting of `[(sentence, word)]`, where sentence\n is an input sentence, and word is a word present in the\n sentence that will be masked out and inferred.\n \n :return: A tensor with log probabilities for the desired word\n in context\n \"\"\"\n sentences, words, length = self.mask(sentence_words)\n\n encoded = self.tokenizer(sentences, return_tensors='pt')\n encoded = encoded.to(self.device)\n\n idx = torch.nonzero(encoded['input_ids'] == self.tokenizer.mask_token_id, as_tuple=False)[:,1].unsqueeze(1)\n word_idx = self.tokenizer(words, add_special_tokens=False)['input_ids']\n with torch.no_grad():\n masked_logits = self.model(**encoded).logits[torch.arange(length)[:, None], idx].squeeze().detach()\n if len(sentences) > 1:\n logprobs = masked_logits - masked_logits.logsumexp(1).unsqueeze(1)\n masked_logprobs = logprobs[torch.arange(len(sentences))[:, None], word_idx].exp().squeeze()\n else:\n logprobs = masked_logits - masked_logits.logsumexp(0)\n masked_logprobs = logprobs[word_idx].exp().squeeze()\n\n return masked_logprobs\n\n\n def prepare_text(self, text: Union[str, List[str]]) -> Iterable[Any]:\n \"\"\"\n Prepares a batch of input text into a format fit to run MLM\n scoring on. \n\n Borrows preprocessing algorithm from Salazar et al. (2020), and\n modifies code from the following github repository by simonpri:\n https://github.com/simonepri/lm-scorer\n \n :param text: batch of sentences to be prepared for scoring.\n :return: Batch of formatted input that can be passed to\n `logprob`\n \"\"\"\n # converts input text to batch of tensors with every position except the cls and sep token masked\n sentences = [text] if isinstance(text, str) else text\n \n # idea is to tokenize and then create batches of tokenized instances,\n # but with each token in the sequence replaced by the mask token. \n \n encoded = self.encode(sentences, manual_special = False)\n\n token_idx = encoded['input_ids']\n attention_masks = encoded['attention_mask']\n\n masked_tensors = [] # token ids, attention masks, lengths\n\n for token_ids, attention_mask in zip(token_idx, attention_masks):\n token_ids = torch.tensor(token_ids)\n # final_lengths = len(token_ids) - 2\n attention_mask = torch.tensor(attention_mask)\n \n token_ids_masked_list = []\n attention_masked_list = []\n\n effective_token_ids = [token for token in token_ids if token != self.pad_token_id and token != self.cls_token_id and token != self.sep_token_id]\n effective_length = len(effective_token_ids)\n \n\n mask_indices = []\n mask_indices = [[mask_pos] for mask_pos in range(effective_length+2)]\n\n # We don't mask the [CLS], [SEP] for now for PLL\n mask_indices = mask_indices[1:-1]\n\n mask_token_id = self.mask_token_id\n for mask_set in mask_indices:\n token_ids_masked = token_ids.clone()\n token_ids_masked[mask_set] = mask_token_id\n attention_masked = attention_mask.clone()\n \n attention_masked_list.append(attention_masked)\n token_ids_masked_list.append(token_ids_masked)\n masked_tensors.append((torch.stack(token_ids_masked_list), torch.stack(attention_masked_list), effective_token_ids, len(mask_indices), 1))\n \n return masked_tensors\n\n def prime_text(self, preamble: Union[str, List[str]] , stimuli: Union[str, List[str]]) -> Iterable[Any]:\n \"\"\"\n Prepares a batch of input text `(preamble, stimuli)` into a\n format fit for running MLM scoring on.\n This is different from `prepare_text()` as it runs a different\n preprocessing step, to ensure the preamble is only used as a\n condition for estimating stimuli word probabilities.\n\n Borrows preprocessing algorithm from Salazar et al. (2020), and\n modifies code from the following github repository by simonpri:\n https://github.com/simonepri/lm-scorer\n \n :param text: batch of sentences to be prepared for scoring.\n :return: Batch of formatted input that can be passed to\n `logprob`\n \"\"\"\n preamble_text = [preamble] if isinstance(preamble, str) else preamble\n preamble_encoded = self.encode(preamble_text, False)['input_ids']\n preamble_lens = []\n for preamble_tokens in preamble_encoded:\n preamble_lens.append(len([token for token in preamble_tokens if token != self.pad_token_id and token != self.sep_token_id]))\n \n sentences = [preamble + \" \" + stimuli] if isinstance(preamble, str) else [p + \" \" + s for p, s in list(zip(preamble, stimuli))]\n \n # idea is to tokenize and then create batches of tokenized instances,\n # but with each token in the sequence replaced by the mask token. \n\n encoded = self.encode(sentences, manual_special = False)\n\n token_idx = encoded['input_ids']\n attention_masks = encoded['attention_mask']\n\n masked_tensors = [] # token ids, attention masks, lengths\n\n for i, (token_ids, attention_mask) in enumerate(zip(token_idx, attention_masks)):\n token_ids = torch.tensor(token_ids)\n # final_lengths = len(token_ids) - 2\n attention_mask = torch.tensor(attention_mask)\n\n token_ids_masked_list = []\n attention_masked_list = []\n \n effective_token_ids = [token for j, token in enumerate(token_ids) if token != self.pad_token_id and token != self.cls_token_id and token != self.sep_token_id and j >= preamble_lens[i]]\n effective_length = len(effective_token_ids) + preamble_lens[i]\n\n\n mask_indices = []\n mask_indices = [[mask_pos] for mask_pos in range(preamble_lens[i], effective_length+1)]\n\n # We don't mask the [CLS], [SEP] for now for PLL\n mask_indices = mask_indices[:-1]\n\n mask_token_id = self.mask_token_id\n for mask_set in mask_indices:\n token_ids_masked = token_ids.clone()\n token_ids_masked[mask_set] = mask_token_id\n attention_masked = attention_mask.clone()\n\n attention_masked_list.append(attention_masked)\n token_ids_masked_list.append(token_ids_masked)\n masked_tensors.append((torch.stack(token_ids_masked_list), torch.stack(attention_masked_list), effective_token_ids, len(mask_indices), preamble_lens[i]))\n\n return masked_tensors\n\n def distribution(self, batch: Iterable) -> torch.Tensor:\n \"\"\"\n Returns a distribution over the vocabulary of the model.\n\n :param `Iterable` batch: A batch of inputs fit to pass to a\n transformer LM.\n\n :return: Tensor consisting of log probabilies over vocab items.\n \"\"\"\n # takes in prepared text and returns scores for each sentence in batch\n token_ids, attention_masks, effective_token_ids, lengths, offsets = list(zip(*batch))\n token_ids = torch.cat(token_ids)\n attention_masks = torch.cat(attention_masks)\n token_ids = token_ids.to(self.device)\n attention_masks = attention_masks.to(self.device)\n effective_token_ids = torch.cat([torch.tensor(x) for x in effective_token_ids])\n\n sent_tokens = list(map(lambda x: self.tokenizer.convert_ids_to_tokens(x.tolist()), effective_token_ids.split(lengths)))\n\n indices = list(chain.from_iterable([list(range(o,o+n)) for n, o in zip(lengths, offsets)]))\n with torch.no_grad():\n output = self.model(token_ids, attention_mask = attention_masks)\n logits = output.logits[torch.arange(sum(lengths)), indices]\n if self.device == 'cuda:0' or self.device == \"cuda:1\":\n logits.detach()\n\n return logits\n\n def cloze_distribution(self, queries: Iterable) -> torch.Tensor:\n \n '''\n Accepts as input batch of [(s_i, bw_i)] where s_i is a prompt with an\n abstract token (bw_i) representing a blank word and returns a distribution\n over the vocabulary of the model.\n\n :param `Iterable` queries: A batch of [(s_i, bw_i)] where s_i is a prompt\n with an abstract token (bw_i) representing a blank word\n\n :return: Tensor contisting of log probabilities over vocab items.\n '''\n \n queries = [queries] if isinstance(queries[0], str) else queries\n prompts, words = list(zip(*queries))\n \n modified_prompts = self.add_special_tokens(prompts)\n splits = [prompt.split(word) for prompt, word in zip(modified_prompts, words)]\n splits = [[x.strip() for x in s] for s in splits]\n pre, post = list(zip(*splits))\n pre_idx = self.tokenizer(list(pre), add_special_tokens = False, padding=False)['input_ids']\n mask_idx = [len(item) for item in pre_idx]\n masked = [m.replace(w, self.tokenizer.mask_token) for m, w in zip(modified_prompts, words)]\n \n with torch.no_grad():\n encoded = self.tokenizer(masked, add_special_tokens = False, return_tensors='pt', padding = True)\n encoded = encoded.to(self.device)\n logits = self.model(**encoded)\n presoftmax = logits.logits[torch.arange(len(queries)), mask_idx]\n if 'cuda' in self.device:\n presoftmax = presoftmax.detach().cpu()\n else:\n presoftmax = presoftmax.detach()\n \n logprobs = presoftmax - presoftmax.logsumexp(1).unsqueeze(1)\n \n return logprobs \n\n def logprobs(self, batch: Iterable, rank = False) -> Union[List[Tuple[torch.Tensor, str]], List[Tuple[torch.Tensor, str, int]]]:\n \"\"\"\n Returns log probabilities\n\n :param `Iterable` batch: A batch of inputs fit to pass to a\n transformer LM.\n :param rank: Specifies whether to also return ranks of words.\n :type rank: bool\n\n :return: List of MLM score metrics and tokens.\n :rtype: Union[List[Tuple[torch.Tensor, str]], List[Tuple[torch.Tensor, str, int]]]\n \"\"\"\n token_ids, attention_masks, effective_token_ids, lengths, offsets = list(zip(*batch))\n token_ids = torch.cat(token_ids)\n attention_masks = torch.cat(attention_masks)\n token_ids = token_ids.to(self.device)\n attention_masks = attention_masks.to(self.device)\n effective_token_ids = torch.cat([torch.tensor(x) for x in effective_token_ids])\n\n sent_tokens = list(map(lambda x: self.tokenizer.convert_ids_to_tokens(x.tolist()), effective_token_ids.split(lengths)))\n \n indices = list(chain.from_iterable([list(range(o,o+n)) for n, o in zip(lengths, offsets)]))\n with torch.no_grad():\n output = self.model(token_ids, attention_mask = attention_masks)\n logits = output.logits[torch.arange(sum(lengths)), indices]\n if self.device == 'cuda:0' or self.device == \"cuda:1\":\n logits.detach()\n \n sent_log_probs = logits - logits.logsumexp(1).unsqueeze(1)\n if rank:\n shape = sent_log_probs.shape\n inv_ranks = (sent_log_probs).argsort().argsort() + 1\n ranks = shape[1] - inv_ranks + 1\n word_ranks = ranks[torch.arange(shape[0]), effective_token_ids].split(lengths)\n sent_log_probs = sent_log_probs[torch.arange(sum(lengths)), effective_token_ids].type(torch.DoubleTensor).split(lengths)\n # sentence_scores = list(map(lambda x: x.sum().tolist(), logprobs))\n # outputs.append((logprobs, sent_tokens))\n if rank:\n return list(zip(sent_log_probs, sent_tokens, word_ranks))\n \n \n return list(zip(sent_log_probs, sent_tokens))\n\nclass IncrementalLMScorer(LMScorer):\n \"\"\"\n Implements LM scoring and output probability analysis for incremental\n LMs such as GPT and GPT2.\n \"\"\"\n def __init__(self, model_name: str, device: Optional[str] = 'cpu') -> None:\n \"\"\"\n :param model_name: name of the model, should either be a path\n to a model (.pt or .bin file) stored locally, or a\n pretrained model stored on the Huggingface Model Hub.\n\n :type model_name: str\n :param device: device type that the model should be loaded on,\n options: `cpu or cuda:{0, 1, ...}`\n :type device: str, optional\n \"\"\"\n super(IncrementalLMScorer, self).__init__(model_name, device)\n \n self.model = AutoModelForCausalLM.from_pretrained(model_name, return_dict = True)\n \n # define CLS and SEP tokens\n if self.tokenizer.pad_token is None:\n self.tokenizer.add_special_tokens({\"additional_special_tokens\": [\"<|pad|>\"]})\n self.tokenizer.pad_token = \"<|pad|>\"\n\n # if self.tokenizer.eos_token is None:\n # self.tokenizer.add_special_tokens({\"additional_special_tokens\": [\"<|eos|>\"]})\n # self.tokenizer.eos_token = \"<|eos|>\"\n\n if self.tokenizer.bos_token is None:\n self.tokenizer.add_special_tokens({\"additional_special_tokens\": [\"<|bos|>\"]})\n self.tokenizer.bos_token = \"<|bos|>\"\n\n self.model.resize_token_embeddings(len(self.tokenizer))\n self.model.to(self.device)\n self.model.eval()\n \n def add_special_tokens(self, text: Union[str, List[str]]) -> Union[str, List[str]]:\n \"\"\"\n Reformats input text to add special model-dependent tokens.\n\n :param text: single string or batch of strings to be\n modified.\n :type text: Union[str, List[str]]\n :return: Modified input, containing special tokens as per \n tokenizer specification\n :rtype: Union[float, List[float]]:\n \"\"\"\n sentences = [text] if isinstance(text, str) else text\n sentences = [self.tokenizer.bos_token + sentence for sentence in sentences]\n\n return sentences\n \n def prepare_text(self, text: Union[str, List[str]]) -> Tuple:\n \"\"\"\n Prepares a batch of input text into a format fit to run LM\n scoring on. \n\n :param text: batch of sentences to be prepared for scoring.\n :return: Batch of formatted input that can be passed to\n `logprob`\n \"\"\"\n encoded = self.encode(text)\n offsets = [0] * len(encoded['input_ids'])\n return encoded, offsets\n \n def prime_text(self, preamble: Union[str, List[str]], stimuli: Union[str, List[str]]) -> Tuple:\n \"\"\"\n Prepares a batch of input text into a format fit to run LM\n scoring on. \n\n :param text: batch of sentences to be prepared for scoring.\n :return: Batch of formatted input that can be passed to\n `logprob`\n \"\"\"\n preamble_text = [preamble] if isinstance(preamble, str) else preamble\n preamble_encoded = self.encode(preamble_text, False)['input_ids']\n preamble_lens = []\n for preamble_tokens in preamble_encoded:\n preamble_lens.append(len([token for token in preamble_tokens if token != self.tokenizer.pad_token_id and token != self.tokenizer.sep_token_id]))\n \n sentences = [preamble + \" \" + stimuli] if isinstance(preamble, str) else [p + \" \" + s for p , s in list(zip(preamble, stimuli))]\n \n return self.encode(sentences), preamble_lens\n \n def distribution(self, batch: Iterable) -> torch.Tensor:\n \"\"\"\n Returns a distribution over the vocabulary of the model.\n\n :param `Iterable` batch: A batch of inputs fit to pass to a\n transformer LM.\n\n :return: Tensor consisting of log probabilies over vocab items.\n \"\"\"\n batch, offsets = batch\n ids = batch[\"input_ids\"]\n ids = ids.to(self.device)\n attention_masks = batch[\"attention_mask\"]\n attention_masks = attention_masks.to(self.device)\n nopad_mask = ids != self.tokenizer.pad_token_id\n\n with torch.no_grad():\n outputs = self.model(ids, attention_mask=attention_masks)\n logits = outputs.logits\n if self.device == 'cuda:0' or self.device == \"cuda:1\":\n logits.detach()\n\n outputs = []\n for sent_index in range(len(ids)):\n sent_nopad_mask = nopad_mask[sent_index]\n # len(tokens) = len(text[sent_index]) + 1\n sent_tokens = [\n tok\n for i, tok in enumerate(batch.tokens(sent_index))\n if sent_nopad_mask[i] and i > offsets[sent_index]\n ]\n\n # sent_ids.shape = [len(text[sent_index]) + 1]\n # ignore first token (<|eos|>)\n sent_ids = ids[sent_index, sent_nopad_mask][1:]\n # logits.shape = [len(text[sent_index]) + 1, vocab_size]\n sent_logits = logits[sent_index, sent_nopad_mask][:-1, :]\n sent_logits[:, self.tokenizer.pad_token_id] = float(\"-inf\")\n\n outputs.append(sent_logits[-1])\n return torch.stack(outputs, 0)\n\n def next_word_distribution(self, queries: List):\n encoded = self.prime_text(queries, ['the'] * len(queries))\n logits = self.distribution(encoded)\n logprobs = logits - logits.logsumexp(1).unsqueeze(1)\n \n return logprobs\n\n def logprobs(self, batch: Iterable, rank = False) -> Union[float, List[float]]:\n \"\"\"\n Returns log probabilities\n\n :param `Iterable` batch: A batch of inputs fit to pass to a\n transformer LM.\n :param rank: Specifies whether to also return ranks of words.\n :type rank: bool\n\n :return: List of LM score metrics (probability and rank)\n and tokens.\n :rtype: Union[List[Tuple[torch.Tensor, str]], List[Tuple[torch.Tensor, str, int]]]\n \"\"\"\n batch, offsets = batch\n ids = batch[\"input_ids\"]\n ids = ids.to(self.device)\n attention_masks = batch[\"attention_mask\"]\n attention_masks = attention_masks.to(self.device)\n nopad_mask = ids != self.tokenizer.pad_token_id\n\n with torch.no_grad():\n outputs = self.model(ids, attention_mask=attention_masks)\n logits = outputs.logits\n if self.device == 'cuda:0' or self.device == \"cuda:1\":\n logits.detach()\n \n outputs = []\n for sent_index in range(len(ids)):\n sent_nopad_mask = nopad_mask[sent_index]\n # len(tokens) = len(text[sent_index]) + 1\n sent_tokens = [\n tok\n for i, tok in enumerate(batch.tokens(sent_index))\n if sent_nopad_mask[i] and i > offsets[sent_index]\n ]\n\n # sent_ids.shape = [len(text[sent_index]) + 1]\n # ignore first token (<|eos|>)\n sent_ids = ids[sent_index, sent_nopad_mask][1:]\n # logits.shape = [len(text[sent_index]) + 1, vocab_size]\n sent_logits = logits[sent_index, sent_nopad_mask][:-1, :]\n sent_logits[:, self.tokenizer.pad_token_id] = float(\"-inf\")\n # ids_scores.shape = [seq_len + 1]\n # select only the ids present in the sentence out of all vocab items (as a 2d array)\n sent_ids_scores = sent_logits.gather(1, sent_ids.unsqueeze(1)).squeeze(1)\n # log_prob.shape = [seq_len + 1]\n sent_log_probs = sent_ids_scores - sent_logits.logsumexp(1)\n \n sent_log_probs = sent_log_probs.type(torch.DoubleTensor)\n sent_log_probs = sent_log_probs[offsets[sent_index]:]\n lengths = len(sent_log_probs)\n if rank:\n shape = sent_logits.shape\n inv_ranks = (sent_logits).argsort().argsort() + 1\n ranks = shape[1] - inv_ranks + 1\n word_ranks = ranks[list(range(shape[0]))[offsets[sent_index]:], sent_ids[offsets[sent_index]: ].tolist()].split(lengths)\n word_ranks = [x[0] for x in word_ranks]\n outputs.append((sent_log_probs, sent_tokens, word_ranks))\n else:\n outputs.append((sent_log_probs, sent_tokens))\n # output = (sent_log_probs.sum(), sent_ids, sent_tokens)\n # outputs.append(output)\n return outputs","sub_path":"minicons/scorer.py","file_name":"scorer.py","file_ext":"py","file_size_in_byte":30670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"328082098","text":"from django.urls import path\nfrom .views import (\n package_container_log_trace,\n state_index,\n state_by_id,\n city_index,\n city_by_id,\n natural_person_index,\n natural_person_by_id,\n legal_person_index,\n legal_person_by_id,\n person_index,\n person_by_id,\n package_container_index,\n package_container_by_id,\n log_trace_index,\n log_trace_by_id\n)\n\n\n\nurlpatterns = [ \n path('log-traces', log_trace_index),\n path('log-traces/', log_trace_by_id),\n path('packages', package_container_index),\n path('packages/', package_container_by_id),\n path('packages//log', package_container_log_trace),\n path('person', person_index),\n path('person/', person_by_id),\n path('legal-person', legal_person_index),\n path('legal-person/', legal_person_by_id),\n path('natural-person', natural_person_index),\n path('natural-person/', natural_person_by_id),\n path('states', state_index),\n path('states/', state_by_id),\n path('cities', city_index),\n path('cities/', city_by_id),\n ]\n","sub_path":"tracker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"206961706","text":"from django.urls import reverse\nfrom django.test import RequestFactory, TestCase\nfrom django.utils.encoding import force_text\nfrom guardian.shortcuts import assign_perm\n\nfrom feder.main.tests import PermissionStatusMixin\nfrom feder.teryt.factories import JSTFactory\nfrom feder.users.factories import UserFactory\nfrom .factories import InstitutionFactory, TagFactory\nfrom .models import Institution\nfrom .serializers import InstitutionSerializer\nfrom .views import InstitutionAutocomplete, TagAutocomplete\n\n\nclass InstitutionTestCase(TestCase):\n def setUp(self):\n self.obj = InstitutionFactory(name=\"Example institution\")\n\n def test_get_absolute_url(self):\n self.assertEqual(self.obj.get_absolute_url(), \"/instytucje/example-institution\")\n\n def test_get_str(self):\n self.assertEqual(force_text(self.obj), \"Example institution\")\n\n\nclass InstitutionSerializerTestCase(TestCase):\n def setUp(self):\n self.data = {\n \"name\": \"xxx\",\n \"slug\": \"xxx\",\n \"tags\": [\"blabla\", \"X\", \"Z\"],\n \"regon\": \"0\" * 14,\n \"jst\": JSTFactory().pk,\n \"email\": \"example-2@example.com\",\n }\n\n def test_create_institution(self):\n serializer = InstitutionSerializer(\n data={\n \"name\": \"X\",\n \"email\": \"example-2@example.com\",\n \"regon\": \"0\" * 14,\n \"jst\": JSTFactory().pk,\n }\n )\n self.assertTrue(serializer.is_valid(), serializer.errors)\n self.assertTrue(serializer.save())\n\n def test_create_institution_with_tags(self):\n TagFactory(name=\"X\") # for colission tag name\n serializer = InstitutionSerializer(data=self.data)\n self.assertTrue(serializer.is_valid(), serializer.errors)\n obj = serializer.save()\n self.assertQuerysetEqual(\n qs=obj.tags.all(), values=[\"blabla\", \"X\", \"Z\"], transform=force_text\n )\n\n def test_update_institution_with_tags(self):\n institution = InstitutionFactory()\n\n self.data[\"pk\"] = institution.pk\n\n serializer = InstitutionSerializer(institution, data=self.data)\n self.assertTrue(serializer.is_valid(), serializer.errors)\n obj = serializer.save()\n self.assertQuerysetEqual(\n qs=obj.tags.all(), values=[\"blabla\", \"X\", \"Z\"], transform=force_text\n )\n self.assertEqual(Institution.objects.count(), 1) # updated\n\n\nclass ObjectMixin:\n def setUp(self):\n self.user = UserFactory(username=\"john\")\n self.institution = InstitutionFactory()\n\n\nclass InstitutionListViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n url = reverse(\"institutions:list\")\n status_anonymous = 200\n status_no_permission = 200\n permission = []\n\n def test_content(self):\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"institutions/institution_filter.html\")\n self.assertContains(response, self.institution.name)\n\n\nclass InstitutionDetailViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n status_anonymous = 200\n status_no_permission = 200\n permission = []\n\n def get_url(self):\n return self.institution.get_absolute_url()\n\n def test_content(self):\n response = self.client.get(self.get_url())\n self.assertTemplateUsed(response, \"institutions/institution_detail.html\")\n self.assertContains(response, self.institution.name)\n\n def test_can_view_edit_button_if_permitted(self):\n assign_perm(\"institutions.change_institution\", self.user)\n self.login_permitted_user()\n response = self.client.get(self.get_url())\n self.assertContains(\n response,\n reverse(\"institutions:update\", kwargs={\"slug\": self.institution.slug}),\n )\n\n\nclass InstitutionCreateViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n url = reverse(\"institutions:create\")\n permission = [\"institutions.add_institution\"]\n\n\nclass InstitutionUpdateViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n permission = [\"institutions.change_institution\"]\n\n def get_url(self):\n return reverse(\"institutions:update\", kwargs={\"slug\": self.institution.slug})\n\n\nclass InstitutionDeleteViewTestCase(ObjectMixin, PermissionStatusMixin, TestCase):\n permission = [\"institutions.delete_institution\"]\n\n def get_url(self):\n return reverse(\"institutions:delete\", kwargs={\"slug\": self.institution.slug})\n\n\nclass InstitutionViewSetTestCase(ObjectMixin, TestCase):\n def test_csv_renderer(self):\n response = self.client.get(\"{}?format=csv\".format(reverse(\"institution-list\")))\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"text/csv\", response[\"content-type\"])\n self.assertContains(response, self.institution.name)\n\n\nclass InstitutionAutocompleteTestCase(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_filter_by_name(self):\n InstitutionFactory(name=\"123\")\n InstitutionFactory(name=\"456\")\n request = self.factory.get(\"/customer/details\", data={\"q\": \"123\"})\n response = InstitutionAutocomplete.as_view()(request)\n self.assertContains(response, \"123\")\n self.assertNotContains(response, \"456\")\n\n\nclass TagAutocompleteTestCase(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_filter_by_name(self):\n TagFactory(name=\"123\")\n TagFactory(name=\"456\")\n request = self.factory.get(\"/customer/details\", data={\"q\": \"123\"})\n response = TagAutocomplete.as_view()(request)\n self.assertContains(response, \"123\")\n self.assertNotContains(response, \"456\")\n\n def test_get_result_label_without_institution(self):\n TagFactory(name=\"123\")\n request = self.factory.get(\"/customer/details\", data={\"q\": \"123\"})\n response = TagAutocomplete.as_view()(request)\n self.assertContains(response, \"123 (0)\")\n\n def test_get_result_label_with_institution(self):\n institution = InstitutionFactory()\n institution.tags.add(TagFactory(name=\"123\"))\n institution.save()\n\n request = self.factory.get(\"/customer/details\", data={\"q\": \"123\"})\n response = TagAutocomplete.as_view()(request)\n self.assertContains(response, \"123 (1)\")\n\n\nclass SitemapTestCase(ObjectMixin, TestCase):\n def test_institutions(self):\n url = reverse(\"sitemaps\", kwargs={\"section\": \"institutions\"})\n needle = reverse(\"institutions:details\", kwargs={\"slug\": self.institution})\n response = self.client.get(url)\n self.assertContains(response, needle)\n\n def test_tags(self):\n tag_used = TagFactory()\n institution = InstitutionFactory()\n institution.tags.add(tag_used)\n institution.save()\n tag_free = TagFactory()\n url = reverse(\"sitemaps\", kwargs={\"section\": \"institutions_tags\"})\n response = self.client.get(url)\n self.assertContains(response, tag_used.get_absolute_url())\n self.assertNotContains(response, tag_free.get_absolute_url())\n","sub_path":"feder/institutions/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"503883120","text":"from __future__ import division\nfrom collections import Counter\n\nfrom enum import IntEnum\n\nimport numpy as np\nfrom ConllTags import NERTag\n\n\nclass Feat(IntEnum):\n \"\"\"\n Enum of current features.\n \"\"\"\n POS = 0\n CHUNK = 1\n PREV_POS = 2\n PREV_PREV_POS = 3\n NEXT_POS = 4\n NEXT_NEXT_POS = 5\n BOW = 6\n BOW_PREV = 7\n BOW_PREV_PREV = 8\n BOW_NEXT = 9\n BOW_NEXT_NEXT = 10\n STEM = 11\n '''\n BOW = 0\n POS = 1\n CHUNK = 2\n '''\n\nclass Weight():\n \"\"\"\n Weight vector for a given NER tag.\n \"\"\"\n def __init__(self, n_tag):\n \"\"\"\n Create a new weight vector.\n :param n_tag: Number of NER tags.\n \"\"\"\n self.weights = []\n for vector in Feat:\n self.weights.append(Counter())\n\n self.additional_feats = Counter()\n self.prev_prediction = np.zeros(n_tag + 1)\n\n def dot_prev_prediction(self, assumed_prev):\n \"\"\"\n Dot product of only the previous prediction vectors.\n :param assumed_prev: Assumed previous NER tag.\n :return: The current weight value of the assumed previous prediction.\n \"\"\"\n if assumed_prev is not None:\n return self.prev_prediction[assumed_prev]\n else:\n return self.prev_prediction[-1]\n\n def dot(self, other, assumed_prev_tag, exclude_prev):\n \"\"\"\n Perform a dot product between the stored weights and a given Feature.\n :param other: Feature to dot product.\n :param assumed_prev_tag: The assumed NER tag of the previous word.\n :param exclude_prev: True to exclude the previous prediction feature.\n :return: Dot product of the stored weights and the given Feature.\n \"\"\"\n result = 0.0\n\n for vector in Feat:\n if other.values[vector] is not None:\n result += self.weights[vector][other.values[vector]]\n\n if not exclude_prev:\n if assumed_prev_tag is not None:\n result += self.prev_prediction[assumed_prev_tag]\n else:\n result += self.prev_prediction[-1]\n\n result += sum((self.additional_feats[key] * other.additional_feats[key]) for key in other.additional_feats)\n\n return result\n\n def subtract(self, other, assumed_prev_tag):\n \"\"\"\n Subtract a given Feature from the stored weights.\n :param other: Feature to subtract from the stored weights.\n :param assumed_prev_tag: The assumed NER tag of the previous word.\n \"\"\"\n for vector in Feat:\n if other.values[vector] is not None:\n self.weights[vector][other.values[vector]] -= 1\n\n if assumed_prev_tag is not None:\n self.prev_prediction[assumed_prev_tag] -= 1\n else:\n self.prev_prediction[-1] -= 1\n\n for key in other.additional_feats:\n self.additional_feats[key] -= other.additional_feats[key]\n\n def add(self, other, assumed_prev_tag):\n \"\"\"\n Add a given Feature to the stored weights.\n :param other: Feature to add to the stored weights.\n :param assumed_prev_tag: The assumed NER tag of the previous word.\n \"\"\"\n for vector in Feat:\n if other.values[vector] is not None:\n self.weights[vector][other.values[vector]] += 1\n\n if assumed_prev_tag is not None:\n self.prev_prediction[assumed_prev_tag] += 1\n else:\n self.prev_prediction[-1] += 1\n\n for key in other.additional_feats:\n self.additional_feats[key] += other.additional_feats[key]\n\n def combine(self, other):\n \"\"\"\n Combine the current weight vector with another weight vector.\n :param other: Other weight vector to merge in.\n \"\"\"\n for vector in Feat:\n self.weights[vector].update(other.weights[vector])\n\n self.additional_feats.update(other.additional_feats)\n\n for i in range(0, len(NERTag.__members__) + 1):\n self.prev_prediction[i] += other.prev_prediction[i]\n\n def divide(self, divisor):\n \"\"\"\n Divide all weights in the weight vector by a given divisor.\n :param divisor: Value to divide all weights by.\n \"\"\"\n for vector in Feat:\n self.weights[vector].update((word, int(round(count / divisor))) for word, count in self.weights[vector].items())\n\n self.additional_feats.update((key, int(round(count / divisor))) for key, count in self.additional_feats.items())\n\n for i in range(0, len(NERTag.__members__) + 1):\n self.prev_prediction[i] = int(round(self.prev_prediction[i] / divisor))\n\n def print_weights(self, threshold):\n \"\"\"\n Print the current weight values, if higher than a given threshold.\n :param threshold: Minimum weight value to print.\n \"\"\"\n for vector in Feat:\n print(vector.name)\n for word, count in self.weights[vector].iteritems():\n if abs(count) > threshold:\n print('{0}\\t{1}'.format(word, count))\n print('')\n\n print('History: ')\n for tag in NERTag:\n print(str(tag.name) + ' ' + str(self.prev_prediction[tag]),)\n print('\\n')\n\n print('Additional features:')\n for word, count in self.additional_feats.iteritems():\n if abs(count) > threshold:\n print('{0}\\t{1}'.format(word, count))\n print('\\n')\n","sub_path":"Weight.py","file_name":"Weight.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"315791987","text":"# -*- coding: utf-8 -*-\n\nimport random\nimport sympy\n\n#plain_textを数値にする,復号化で得られたdecodeを平文にする\ndef code( word ):\n result = []\n for letter in word:\n result.append( ord(letter) )\n return result\n\ndef make_prime( M, N ):\n while True:\n n = random.randint( M, N )\n i = 2\n flag = True\n while i*i <= n and flag:\n if n % i == 0:\n flag = False\n i += 1\n if flag:\n return n\n\n#modの計算\ndef calc_mod( a, b, p ):\n result = 1\n for i in range(b):\n result = ( result * a ) % p\n return result\n\n#pk(公開鍵の要素)、sk(秘密鍵の要素)を(p, g, y)としてランダムに生成する\ndef key_generate( k ):\n a = 1 << (k-1)\n b = 1 << k\n p = make_prime( a, b )\n g = sympy.primitive_root(p)\n x = random.randint( 0, p-1 )\n y = calc_mod( g, x, p )\n return ( p, g, y ), x\n\n# plain_textをpkを使って暗号化する\n\ndef encrypt(m, pk):\n cipher = []\n p, g, y = pk\n r = random.randint( 0, p-1 )\n c1 = calc_mod( g, r, p )\n for l in m:\n c2 = ( ord(l) * calc_mod( y, r, p ) ) % p\n cipher.append( c2 )\n return ( c1, cipher )\n\n# plain_textをcipher, pk, skを使って復号化する\ndef decrypt( c, pk, sk ):\n decode = ''\n c1, c2 = c\n p, g, y = pk\n x = sk\n d = calc_mod( c1, p-1-x, p )\n for cc in c2:\n m = ( cc * d ) % p\n decode += chr( m )\n return decode\n\n#main文\nif __name__ == '__main__':\n# pk, sk = key_generate(8)\n pk, sk = ((13, 2, 3),2)\n plain_text = 'You can always become better.'\n# plain_text = '1234567'\n plain_code = code(plain_text) # plain_textを文字コードにする\n# cipher = encrypt(plain_text, pk) # plain_textをpkを使って暗号化する\n cipher = encrypt(plain_text, ((13, 2, 3), 2)) # plain_textをpkを使って暗号化する\n decode = decrypt(cipher, pk, sk) # plain_textをcipher, pk, skを使って復号化する\n decode_code = code( decode ) # 復号化で得られたdecodeを平文にする\n\n print('公開鍵 ( p, g, y ) = ', pk)\n print('秘密鍵 x = ',sk) #ランダムな値が秘密鍵で与えられてもちゃんと復号できる。\n print('平文(文字コード) = ')\n print(plain_code)\n print('暗号 ( c1, c2 ) = ')\n print(cipher)\n print('復号(文字コード) = ')\n print(decode_code)\n print(\"復号 m'=\", decode)\n\n# print( '公開鍵 ( p, g, y ) = ', pk )\n# print( '秘密鍵 x = ', sk )\n# print( '平文(文字コード) = ', plain_code )\n# print( '暗号 ( c1, c2 ) = ', cipher )\n# print( '復号(文字コード) = ', decode_code )\n# print( \"復号 m'=\", decode )\n","sub_path":"kadai-elgamal.py","file_name":"kadai-elgamal.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"65062518","text":"#!/usr/bin/python\n\nimport sys\nfrom PyQt4 import QtCore, QtGui\nfrom PyQt4.QtGui import QTextEdit, QPushButton, QHBoxLayout, QVBoxLayout, QWidget\nfrom Codec.trans import dec\n\nclass clickableTextEdit(QTextEdit):\n\tdef __init__(self, readonly = False, parent = None):\n\t\tQTextEdit.__init__(self, parent)\n\t\tself.setReadOnly(readonly)\n\t\tself.doubleClicked_callback = None\n\n\t# re-implement mouseDoubleClickEvent\n\tdef mouseDoubleClickEvent(self, e): \n\t\tif self.doubleClicked_callback:\n\t\t\tself.doubleClicked_callback(self, e)\n\n\nclass viewlayout(QVBoxLayout):\n\tdef __init__(self, parent = None):\n\t\tQVBoxLayout.__init__(self, parent)\n\t\n\n\tdef prepare(self):\n\n\t\t# the first row\n\t\tfir_row = QHBoxLayout()\n\t\ttext = clickableTextEdit()\n\t\tdef input_double_callback(obj, e):\n\t\t\t# QClipboard.text() not toPlainText()\n\t\t\tobj.setText(app.clipboard().text())\n\t\ttext.doubleClicked_callback = input_double_callback\n\t\ttext.setGeometry(50, 50, 10, 100)\n\t\ttext.setReadOnly(False) # True in python, not true\n\t\tfir_row.addWidget(text)\n\n\t\tbtnlyt = QVBoxLayout()\n\n\t\ttrans = QPushButton('translate')\n\t\tdef translate():\n\t\t\tresult.setText(dec(text.toPlainText()))\n\t\ttrans.clicked.connect(lambda: translate())\n\t\tbtnlyt.addWidget(trans)\n\n\t\tdef clt():\n\t\t\ttext.clear()\n\t\t\tresult.clear()\n\t\tclean = QPushButton('clean')\n\t\tclean.clicked.connect(lambda: clt())\n\t\tbtnlyt.addWidget(clean)\n\n\t\tquit = QPushButton('quit')\n\t\tbtnlyt.addWidget(quit)\n\t\tself.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()'))\n\t\tfir_row.addLayout(btnlyt)\n\t\tself.addLayout(fir_row)\n\n\n\t\t# the second row\n\t\tsec_row = QHBoxLayout()\n\t\tresult = clickableTextEdit(True) \n\t\tdef output_double_callback(obj, e):\n\t\t\tapp.clipboard().setText(obj.toPlainText())\n\t\tresult.doubleClicked_callback = output_double_callback\n\t\tresult.setReadOnly(True)\n\t\tresult.setText('double click to paste input\\nEnter to translate\\ndouble click to clipboard')\n\t\tsec_row.addWidget(result)\n\t\tself.addLayout(sec_row)\n\n\nclass mainentry(QWidget):\n\tdef __init__(self, parent = None):\n\t\tQWidget.__init__(self, parent)\n\t\tself.setWindowTitle('Translator')\n\t\tself.setGeometry(100, 100, 600, 400)\n\t\tlayout = viewlayout(self)\n\t\tlayout.prepare()\n\nclass SystemTrayIcon(QtGui.QSystemTrayIcon):\n\tdef __init__(self, icon, parent = None):\n\t\tQtGui.QSystemTrayIcon.__init__(self, icon, parent) \n\t\tmenu = QtGui.QMenu(parent)\n\t\thideAction = menu.addAction(QtGui.QAction('&Hide', self, triggered = self.hide)) \n\t\texitAction = QtGui.QAction('&Quit', self, triggered = app.quit)\n\t\tmenu.addAction(exitAction)\n\t\tself.setContextMenu(menu)\n\t\n\tdef hide(self):\n\t\tif w.isHidden():\n\t\t\tw.show()\n\t\telse:\n\t\t\tw.hide()\n\n\nif __name__ == '__main__':\n\tapp = QtGui.QApplication(sys.argv)\n\tw = mainentry() \n\tif QtGui.QSystemTrayIcon.isSystemTrayAvailable():\n\t\t# trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon(\"Translator.xpm\"), w)\n\t\ttrayIcon = SystemTrayIcon(QtGui.QIcon(\"Translator.xpm\"), w)\n\t\ttrayIcon.show()\n\tw.show()\n\tsys.exit(app.exec_())\n\n","sub_path":"pyqt/Translator/Translator.py","file_name":"Translator.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"2010052","text":"# This file contains all CREATE TABLE queries, used to sync and test schema\nimport re\n\nfrom posthog.clickhouse.dead_letter_queue import *\nfrom posthog.clickhouse.plugin_log_entries import *\nfrom posthog.models.app_metrics.sql import *\nfrom posthog.models.cohort.sql import *\nfrom posthog.models.event.sql import *\nfrom posthog.models.group.sql import *\nfrom posthog.models.ingestion_warnings.sql import (\n DISTRIBUTED_INGESTION_WARNINGS_TABLE_SQL,\n INGESTION_WARNINGS_DATA_TABLE_SQL,\n INGESTION_WARNINGS_MV_TABLE_SQL,\n KAFKA_INGESTION_WARNINGS_TABLE_SQL,\n)\nfrom posthog.models.performance.sql import (\n DISTRIBUTED_PERFORMANCE_EVENTS_TABLE_SQL,\n KAFKA_PERFORMANCE_EVENTS_TABLE_SQL,\n PERFORMANCE_EVENTS_TABLE_MV_SQL,\n PERFORMANCE_EVENTS_TABLE_SQL,\n WRITABLE_PERFORMANCE_EVENTS_TABLE_SQL,\n)\nfrom posthog.models.person.sql import *\nfrom posthog.models.session_recording_event.sql import *\n\nCREATE_MERGETREE_TABLE_QUERIES = (\n CREATE_COHORTPEOPLE_TABLE_SQL,\n PERSON_STATIC_COHORT_TABLE_SQL,\n DEAD_LETTER_QUEUE_TABLE_SQL,\n EVENTS_TABLE_SQL,\n GROUPS_TABLE_SQL,\n PERSONS_TABLE_SQL,\n PERSONS_DISTINCT_ID_TABLE_SQL,\n PERSON_DISTINCT_ID2_TABLE_SQL,\n PLUGIN_LOG_ENTRIES_TABLE_SQL,\n SESSION_RECORDING_EVENTS_TABLE_SQL,\n INGESTION_WARNINGS_DATA_TABLE_SQL,\n APP_METRICS_DATA_TABLE_SQL,\n PERFORMANCE_EVENTS_TABLE_SQL,\n)\nCREATE_DISTRIBUTED_TABLE_QUERIES = (\n WRITABLE_EVENTS_TABLE_SQL,\n DISTRIBUTED_EVENTS_TABLE_SQL,\n WRITABLE_SESSION_RECORDING_EVENTS_TABLE_SQL,\n DISTRIBUTED_SESSION_RECORDING_EVENTS_TABLE_SQL,\n DISTRIBUTED_INGESTION_WARNINGS_TABLE_SQL,\n DISTRIBUTED_APP_METRICS_TABLE_SQL,\n WRITABLE_PERFORMANCE_EVENTS_TABLE_SQL,\n DISTRIBUTED_PERFORMANCE_EVENTS_TABLE_SQL,\n)\nCREATE_KAFKA_TABLE_QUERIES = (\n KAFKA_DEAD_LETTER_QUEUE_TABLE_SQL,\n KAFKA_EVENTS_TABLE_JSON_SQL,\n KAFKA_GROUPS_TABLE_SQL,\n KAFKA_PERSONS_TABLE_SQL,\n KAFKA_PERSONS_DISTINCT_ID_TABLE_SQL,\n KAFKA_PERSON_DISTINCT_ID2_TABLE_SQL,\n KAFKA_PLUGIN_LOG_ENTRIES_TABLE_SQL,\n KAFKA_SESSION_RECORDING_EVENTS_TABLE_SQL,\n KAFKA_INGESTION_WARNINGS_TABLE_SQL,\n KAFKA_APP_METRICS_TABLE_SQL,\n KAFKA_PERFORMANCE_EVENTS_TABLE_SQL,\n)\nCREATE_MV_TABLE_QUERIES = (\n DEAD_LETTER_QUEUE_TABLE_MV_SQL,\n EVENTS_TABLE_JSON_MV_SQL,\n GROUPS_TABLE_MV_SQL,\n PERSONS_TABLE_MV_SQL,\n PERSONS_DISTINCT_ID_TABLE_MV_SQL,\n PERSON_DISTINCT_ID2_MV_SQL,\n PLUGIN_LOG_ENTRIES_TABLE_MV_SQL,\n SESSION_RECORDING_EVENTS_TABLE_MV_SQL,\n INGESTION_WARNINGS_MV_TABLE_SQL,\n APP_METRICS_MV_TABLE_SQL,\n PERFORMANCE_EVENTS_TABLE_MV_SQL,\n)\n\nCREATE_TABLE_QUERIES = (\n CREATE_MERGETREE_TABLE_QUERIES\n + CREATE_DISTRIBUTED_TABLE_QUERIES\n + CREATE_KAFKA_TABLE_QUERIES\n + CREATE_MV_TABLE_QUERIES\n)\n\nbuild_query = lambda query: query if isinstance(query, str) else query()\nget_table_name = lambda query: re.findall(r\" ([a-z0-9_]+) ON CLUSTER\", build_query(query))[0]\n","sub_path":"posthog/clickhouse/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"576761956","text":"from simulations.simulation import Simulation\nfrom nodes.node import BS, IRS, Vehicle\nimport utils.comutils as utils\nfrom nodes.links import RayTracingLinks, RayTracingLosLinks\nimport numpy as np\nimport pandas as pd\nimport utils.arrayutils as arrayutils\nfrom joblib import load\n\n\nclass IRSV2XSimulation(Simulation):\n COL_POS_X = 'x'\n COL_POS_Y = 'y'\n COL_POS_Z = 'z'\n COL_SPEED = 'speed'\n COL_OUTAGE_IRS = 'outage probability with irs'\n COL_GAIN_IRS = 'channel gain with irs'\n COL_CAPACITY_IRS = 'capacity with irs'\n COL_OUTAGE_NIRS = 'outage probability without irs'\n COL_GAIN_NIRS = 'channel gain without irs'\n COL_CAPACITY_NIRS = 'capacity without irs'\n COL_PHASE = 'phase_'\n\n def __init__(self, id_bs, antennas_bs, pos_bs, id_irs, antennas_irs, pos_irs, id_v, antennas_v, pos_v, speed_v,\n sigma_n_sqr_dbm, sigma_sqr_db, gamma_th_db, p_dbm, data_path, irs_discrete_levels=16, start_point=1,\n num_points=1, error_threshold=1e-3, k_c=1, k_r=1, max_iterations=100, early_stop=False, fc=24.2,\n delta=0.5, enable_los_beamforming=False, ml_model=None):\n self.bs = BS(antennas_bs, pos_bs, id_bs)\n self.angles = np.linspace(0, 2*np.pi, irs_discrete_levels)\n self.irs = IRS(antennas_irs, pos_irs, id_irs)\n self.n_r_irs = self.irs.nz\n if self.irs.nx > 1:\n self.n_c_irs = self.irs.nx\n else:\n self.n_c_irs = self.irs.ny\n n_irs = self.n_r_irs * self.n_c_irs\n self.vehicle_positions = pos_v\n self.vehicle = Vehicle(antennas_v, (0, 0, 0), id_v, speed_v)\n self.sigma_n_sqr = utils.db2lin(sigma_n_sqr_dbm - 30)\n self.sigma_sqr = utils.db2lin(sigma_sqr_db)\n self.p_sig = utils.db2lin(p_dbm - 30)\n self.gamma_th = utils.db2lin(gamma_th_db)\n self.start = start_point\n self.error_threshold = error_threshold\n self.links = RayTracingLinks(data_path + 'hmatrix')\n self.links.add_link(self.vehicle, self.bs, start_point, 1)\n self.links.add_link(self.vehicle, self.irs, start_point, 1)\n self.links.add_link(self.irs, self.bs, 1, 1)\n self.num_points = num_points\n self.max_iterations = max_iterations\n self.early_stop = early_stop\n self.k_c = k_c\n self.k_r = k_r\n self.fc = fc\n self.delta = 0.5\n self.enable_los_beamforming = enable_los_beamforming\n if self.enable_los_beamforming:\n self.loslinks = RayTracingLosLinks(data_path + 'doa', fc, delta)\n self.loslinks.add_link(self.vehicle, self.bs, start_point, 1)\n self.loslinks.add_link(self.vehicle, self.irs, start_point, 1)\n self.loslinks.add_link(self.irs, self.bs, 1, 1)\n self.ml_model = ml_model\n if self.ml_model is not None:\n self.classifier = load(ml_model)\n\n def get_codebook_size(self):\n return self.codebook.shape[0]\n\n def simulate(self):\n index = self.start\n cols = [IRSV2XSimulation.COL_POS_X,\n IRSV2XSimulation.COL_POS_Y,\n IRSV2XSimulation.COL_POS_Z,\n IRSV2XSimulation.COL_SPEED,\n IRSV2XSimulation.COL_OUTAGE_IRS,\n IRSV2XSimulation.COL_GAIN_IRS,\n IRSV2XSimulation.COL_CAPACITY_IRS,\n IRSV2XSimulation.COL_OUTAGE_NIRS,\n IRSV2XSimulation.COL_GAIN_NIRS,\n IRSV2XSimulation.COL_CAPACITY_NIRS]\n for n in range(self.irs.antnum):\n cols.append(IRSV2XSimulation.COL_PHASE + str(n))\n output = pd.DataFrame(columns=cols)\n i = 0\n while i < self.num_points:\n pos = self.vehicle_positions[i]\n car = Vehicle(self.vehicle.get_antennas(), pos, self.vehicle.node_id, self.vehicle.speed)\n output = output.append(pd.Series(0, index=output.columns), ignore_index=True)\n output[IRSV2XSimulation.COL_POS_X].iloc[i] = pos[0]\n output[IRSV2XSimulation.COL_POS_Y].iloc[i] = pos[1]\n output[IRSV2XSimulation.COL_POS_Z].iloc[i] = pos[2]\n output[IRSV2XSimulation.COL_SPEED].iloc[i] = car.speed\n if index > self.start:\n self.links.modify_link(car, self.bs, index, 1)\n self.links.modify_link(car, self.irs, index, 1)\n if self.enable_los_beamforming:\n self.loslinks.modify_link(car, self.bs, index, 1)\n self.loslinks.modify_link(car, self.irs, index, 1)\n if self.ml_model is None:\n v, phase_indexes = self.subgroup_discrete_optimization(self.get_sumrate, minimization=False)\n else:\n x = np.array([pos[0], pos[1]]).reshape(1, -1)\n phase_indexes = self.classifier.predict(x)\n phase_indexes = phase_indexes.reshape(-1, 1)\n theta = np.zeros((self.irs.antnum, 1))\n for n in range(self.irs.antnum):\n theta[n, 0] = self.angles[phase_indexes[n, 0]-1]\n v = np.exp(1j * theta)\n outage_irs, outage_nirs = self.get_outage_probability(v)\n gain_irs, gain_nirs = self.get_channel_gains(v)\n capacity_irs, capacity_nirs = self.get_sumrate(v)\n output[IRSV2XSimulation.COL_OUTAGE_IRS].iloc[i] = outage_irs\n output[IRSV2XSimulation.COL_GAIN_IRS].iloc[i] = gain_irs\n output[IRSV2XSimulation.COL_CAPACITY_IRS].iloc[i] = capacity_irs\n output[IRSV2XSimulation.COL_OUTAGE_NIRS].iloc[i] = outage_nirs\n output[IRSV2XSimulation.COL_GAIN_NIRS].iloc[i] = gain_nirs\n output[IRSV2XSimulation.COL_CAPACITY_NIRS].iloc[i] = capacity_nirs\n for n in range(self.irs.antnum):\n output[IRSV2XSimulation.COL_PHASE + str(n)].iloc[i] = phase_indexes[n]\n print('Simulating vehicle position ', pos)\n print(output.iloc[0, :])\n print('\\n')\n i = i + 1\n index = index + 1\n return output\n\n def get_channel_vectors(self, shifts, h_d=None, h_r=None, h_v=None):\n theta = np.diag(shifts[:, 0])\n if h_d is None:\n h_d = self.links.get_link(self.vehicle, self.bs).hmatrix()\n if h_r is None:\n h_r = self.links.get_link(self.irs, self.bs).hmatrix()\n if h_v is None:\n h_v = self.links.get_link(self.vehicle, self.irs).hmatrix()\n g = h_d + np.matmul(h_r, np.matmul(theta, h_v))\n return g, h_d\n\n def get_outage_probability(self, shifts, h_d=None, h_r=None, h_v=None):\n g, h_d = self.get_channel_vectors(shifts, h_d, h_r, h_v)\n p_out_nirs = utils.calculate_rician_outage_probability(h_d, self.sigma_sqr, self.sigma_n_sqr, self.gamma_th,\n self.p_sig, self.bs.antnum)\n p_out_irs = utils.calculate_rician_outage_probability(g, self.sigma_sqr, self.sigma_n_sqr, self.gamma_th,\n self.p_sig, self.bs.antnum)\n return p_out_irs, p_out_nirs\n\n def get_channel_gains(self, shifts, h_d=None, h_r=None, h_v=None):\n g, h_d = self.get_channel_vectors(shifts, h_d, h_r, h_v)\n return np.square(np.linalg.norm(g)), np.square(np.linalg.norm(h_d))\n\n def get_sumrate(self, shifts, h_d=None, h_r=None, h_v=None):\n g, h_d = self.get_channel_vectors(shifts, h_d, h_r, h_v)\n return utils.calculate_sumrate(g, self.sigma_n_sqr, self.p_sig), \\\n utils.calculate_sumrate(h_d, self.sigma_n_sqr, self.p_sig)\n\n def discrete_optimizatiom(self, obj_function, h_d, h_r, h_v, minimization=True):\n Phi = np.matmul(h_r, np.diag(h_v[:, 0]))\n A = np.matmul(Phi.conj().T, Phi)\n b = np.matmul(Phi.conj().T, h_d)\n theta = np.zeros((h_v.shape[0], 1), dtype=complex)\n phase_indexes = np.zeros((h_v.shape[0], 1), dtype=int)\n for n in range(h_v.shape[0]):\n theta[n, 0] = self.angles[0]\n phase_indexes[n] = 1\n v = np.exp(1j * theta)\n obj_val, x = obj_function(v, h_d, h_r, h_v)\n if minimization:\n prev_obj_value = float('inf')\n else:\n prev_obj_value = float('-inf')\n for i in range(self.max_iterations):\n for n in range(h_v.shape[0]):\n tau_n = b[n, 0]\n for j in range(h_v.shape[0]):\n if j != n:\n tau_n = tau_n + A[n, j] * v[j]\n theta_n = np.angle(tau_n)\n min_diff = 1000\n phase_index = 1\n for ang in self.angles:\n alpha = np.angle(np.exp(1j*ang))\n diff = np.abs(alpha - theta_n)\n if diff < min_diff:\n min_diff = diff\n theta[n, 0] = ang\n phase_indexes[n] = phase_index\n phase_index = phase_index + 1\n v = np.exp(-1j * theta)\n prev_obj_value = obj_val\n obj_val, x = obj_function(v, h_d, h_r, h_v)\n if self.early_stop and np.abs(obj_val - prev_obj_value) < self.error_threshold:\n break\n v = np.exp(1j * theta)\n return v, phase_indexes\n\n def subgroup_discrete_optimization(self, obj_function, minimization=True):\n if not self.enable_los_beamforming:\n h_d = self.links.get_link(self.vehicle, self.bs).hmatrix()\n h_r = self.links.get_link(self.irs, self.bs).hmatrix()\n h_v = self.links.get_link(self.vehicle, self.irs).hmatrix()\n else:\n h_d = self.loslinks.get_link(self.vehicle, self.bs).hmatrix()\n h_r = self.loslinks.get_link(self.irs, self.bs).hmatrix()\n h_v = self.loslinks.get_link(self.vehicle, self.irs).hmatrix()\n if self.k_c == 1 and self.k_r == 1:\n return self.discrete_optimizatiom(obj_function, h_d, h_r, h_v, minimization)\n h_r_exp = np.zeros((self.n_r_irs, self.n_c_irs, self.bs.antnum), dtype=complex)\n for i in range(self.bs.antnum):\n h_r_exp[:, :, i] = np.reshape(h_r[i, :], (self.n_r_irs, self.n_c_irs))\n h_v_exp = np.reshape(h_v, (self.n_r_irs, self.n_c_irs))\n h_r1 = np.zeros((self.bs.antnum, int(self.irs.antnum/(self.k_r * self.k_c))), dtype=complex)\n for i in range(self.bs.antnum):\n h_r1[i, :] = np.reshape(h_r_exp[0:-1:self.k_r, 0:-1:self.k_c, i],\n (int(self.irs.antnum/(self.k_r * self.k_c)), 1))[:, 0]\n h_v1 = np.reshape(h_v_exp[0:-1:self.k_r, 0:-1:self.k_c], (int(self.irs.antnum/(self.k_r * self.k_c)), 1))\n v1, phase_indexes = self.discrete_optimizatiom(obj_function, h_d, h_r1, h_v1, minimization)\n v1_exp = np.reshape(v1, (int(self.n_r_irs/self.k_r), int(self.n_c_irs/self.k_c)))\n phase_indexes = np.reshape(phase_indexes, (int(self.n_r_irs / self.k_r), int(self.n_c_irs / self.k_c)))\n return np.reshape(arrayutils.resize_array(v1_exp, self.n_r_irs, self.n_c_irs), (self.irs.antnum, 1)), \\\n np.reshape(arrayutils.resize_array(phase_indexes, self.n_r_irs, self.n_c_irs), (self.irs.antnum, 1))\n\n def codebook_optimization(self, obj_function, minimization=True):\n pass\n","sub_path":"src/simulations/irs_v2x_simulation.py","file_name":"irs_v2x_simulation.py","file_ext":"py","file_size_in_byte":11278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"274189193","text":"import torch\nfrom abc import ABC, abstractmethod\nfrom visualizer import TensorboardWriter\n\n\nclass BaseTrainer(ABC):\n \"\"\"\n Base class for all trainers.\n \"\"\"\n def __init__(self, model, loss, metrics, optimizer, config):\n self._config = config\n\n self._logger = config.get_logger(\n 'trainer', config['trainer']['verbosity'])\n\n # Setup GPU for training if available\n self._device, gpu_ids = self._get_device(config['n_gpu'])\n self._model = model.to(self._device)\n if len(gpu_ids) > 1:\n self._model = torch.nn.DataParallel(model, device_ids=gpu_ids)\n\n self._loss = loss\n self._metrics = metrics\n self._optimizer = optimizer\n\n cfg_trainer = config['trainer']\n self._epochs = cfg_trainer['epochs']\n self._save_period = cfg_trainer['save_period']\n self._monitor = cfg_trainer.get('monitor', 'off')\n\n # Config for monitoring model performance and saving the best model\n if self._monitor == 'off':\n self._mnt_mode = 'off'\n self._mnt_best = 0\n else:\n self._mnt_mode, self._mnt_metric = self._monitor.split()\n\n assert self._mnt_mode in ['min', 'max']\n\n self._mnt_best = (float('inf') if self._mnt_mode == 'min'\n else -float('inf'))\n self._early_stop = cfg_trainer.get('early_stop', float('inf'))\n\n self._start_epoch = 1\n\n self._checkpoint_dir = config.save_dir\n\n # Setup visualization writer instance\n self._writer = TensorboardWriter(config.log_dir, self._logger,\n cfg_trainer['tensorboard'])\n\n if config.resume is not None:\n self._resume_checkpoint(config.resume)\n\n @abstractmethod\n def _train_epoch(self, epoch):\n \"\"\"\n Training logic for an epoch.\n Args:\n epoch: Current epoch number.\n Return:\n A log dict that contains all information you want to save.\n Note:\n 1. If you have additional information to record, for example:\n > additional_log = {'x': x, 'y': y}\n merge it with log before return. i.e.\n > log = {**log, **additional_log}\n > return log\n 2. The metrics in log must have the key 'metrics'.\n \"\"\"\n return NotImplemented\n\n def train(self):\n \"\"\"\n Full training logic.\n \"\"\"\n not_improved_count = 0\n for epoch in range(self._start_epoch, self._epochs + 1):\n raw_log = self._train_epoch(epoch)\n\n # Extract metrics and save results into dict\n log = {'epoch': epoch}\n for key, value in raw_log.items():\n if key == 'metrics':\n log.update({metric.__name__: value[i]\n for i, metric in enumerate(self._metrics)})\n elif key == 'val_metrics':\n log.update({'val_{}'.format(metric.__name__): value[i]\n for i, metric in enumerate(self._metrics)})\n else:\n log[key] = value\n\n # Print logged informations\n for key, value in log.items():\n self._logger.info(' {:15s}: {}'.format(str(key), value))\n\n # Evaluate model performance according to configured metric,\n # and save best checkpoint as model_best\n best = False\n if self._mnt_mode != 'off':\n try:\n # Check whether the performance of model is improved\n # or not by specified metric\n if self._mnt_mode == 'min':\n improved = (\n True if log[self._mnt_metric] <= self._mnt_best\n else False\n )\n else: # self._mnt_mode == 'max'\n improved = (\n True if log[self._mnt_metric] >= self._mnt_best\n else False\n )\n except KeyError:\n self._logger.warning(\n \"Warning: Metric '{}' not found. \"\n \"Model performance monitoring is disabled.\"\n .format(self._mnt_metric)\n )\n self._mnt_mode = 'off'\n improved = False\n\n if improved:\n self._mnt_best = log[self._mnt_metric]\n not_improved_count = 0\n best = True\n else:\n not_improved_count += 1\n\n if not_improved_count >= self._early_stop:\n self._logger.info(\n \"Validation performance didn't improve for {} \"\n \"epochs. Training stops.\"\n .format(not_improved_count)\n )\n break\n\n if epoch % self._save_period == 0 or best:\n self._save_checkpoint(epoch, save_best=best)\n\n def _get_device(self, n_gpu_use):\n \"\"\"\n Check the number of GPUs available and return the device and GPU list\n to use.\n \"\"\"\n n_gpu_avail = torch.cuda.device_count()\n\n if n_gpu_use > 0 and n_gpu_avail == 0:\n self._logger.warning('Warning: No GPU available, using CPU.')\n n_gpu_use = 0\n elif n_gpu_use > n_gpu_avail:\n self._logger.warning('Warning: The number of GPUs configured to '\n 'use is {}, but only {} available.'\n .format(n_gpu_use, n_gpu_avail))\n n_gpu_use = n_gpu_avail\n\n device = torch.device('cuda:0' if n_gpu_use > 0 else 'cpu')\n gpu_ids = list(range(n_gpu_use))\n\n return device, gpu_ids\n\n def _save_checkpoint(self, epoch, save_best=False):\n \"\"\"\n Saving checkpoints.\n \"\"\"\n state = {\n 'model': type(self._model).__name__,\n 'epoch': epoch,\n 'state_dict': self._model.state_dict(),\n 'optimizer': self._optimizer.state_dict(),\n 'monitor_best': self._mnt_best,\n 'config': self._config\n }\n\n if epoch % self._save_period == 0:\n ckeckpoint_path = str(\n self._checkpoint_dir / 'ckeckpoint_epoch{}.pth'.format(epoch))\n torch.save(state, ckeckpoint_path)\n\n self._logger.info('Saving checkpoint to {} ...'\n .format(ckeckpoint_path))\n\n if save_best:\n best_path = str(self._checkpoint_dir / 'model_best.pth')\n torch.save(state, best_path)\n self._logger.info('Saving current best to {} ...'\n .format(best_path))\n\n def _resume_checkpoint(self, resume_path):\n \"\"\"\n Resume from saved checkpoints.\n \"\"\"\n resume_path = str(resume_path)\n\n self._logger.info('Loading checkpoint from {} ...'.format(resume_path))\n checkpoint = torch.load(resume_path)\n\n self._start_epoch = checkpoint['epoch'] + 1\n self._mnt_best = checkpoint['monitor_best']\n\n # Load model state from checkpoint\n if checkpoint['config']['model'] != self._config['model']:\n self._logger.warning(\n 'Warning: Model configuration given in config is different '\n 'from that of the checkpoint. This may yield an exception '\n 'while loading model state.'\n )\n\n self._model.load_state_dict(checkpoint['state_dict'])\n\n # Load optimizer state from checkpoint only when optimizer type is\n # not changed\n if (checkpoint['config']['optimizer']['type']\n != self._config['optimizer']['type']):\n self._logger.warning(\n 'Warning: Optimizer is not resumed, since optimizer type '\n 'given in config is different from that of the checkpoint.'\n )\n else:\n self._optimizer.load_state_dict(checkpoint['optimizer'])\n\n self._logger.info('Checkpoint loaded. Resume training from epoch {}'\n .format(self._start_epoch))\n","sub_path":"src/WYN/model_total/base/base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"245105719","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# 取值0到1之间500个等距点\nx = np.linspace(0, 1, 500)\ny = np.sin(4 * np.pi * x) * np.exp(-5 * x)\nfig, ax = plt.subplots()\n# zorder作用是确定层次\nax.fill(x, y, zorder=10)\n# 画格子\nax.grid(True, zorder=5)\nplt.show()\n","sub_path":"Data_Visualization/fill_demo.py","file_name":"fill_demo.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"383047781","text":"class Node:\n def __init__(self,v):\n self.val = v\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.nodeCount=0\n self.head = None\n self.tail = None\n def __repr__(self):\n if self.nodeCount == 0:\n return \"empty\"\n s=''\n curr=self.head\n while curr is not None:\n s += repr(curr.val)\n if curr.next is not None:\n s += '->'\n curr = curr.next\n return s\n def getAt(self,pos):\n if pos <= 0 or pos > self.nodeCount:\n return None\n i=1\n curr = self.head\n while(i self.nodeCount+1:\n return False\n if pos ==1 :\n newNode.next=self.head\n self.head= newNode\n else:\n if pos == self.nodeCount+1:\n prev=self.tail\n else:\n prev=self.getAt(pos-1)\n newNode.next=prev.next\n prev.next=newNode\n if pos == self.nodeCount +1:\n self.tail=newNode\n self.nodeCount+=1\n return True\n\n \n\n\nlist = LinkedList()\nn1 = Node('t')\nn2 = Node('e')\nn3 = Node('s')\nn4 = Node('t')\n\nlist.insertAt(1,n1)\nlist.insertAt(2,n2)\nlist.insertAt(3,n3)\n\n\n\nprint(list.traverse())\nprint(list)\n","sub_path":"python/linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"602957560","text":"# MIT License\n#\n# Copyright (c) 2019 zaitra.io\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 deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# 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 all\n# 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 FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\nSentinel downloader configuration.\n\"\"\"\n\n\nfrom pathlib import Path\n\nfrom jsonschema import Draft4Validator, ValidationError\nfrom yaml import safe_load\n\nfrom sentinel_downloader.constants import CONFIG_FILE_NAME\nfrom sentinel_downloader.log import logger\nfrom sentinel_downloader.schema import CONFIG_SCHEMA\n\n\nclass Config:\n def __init__(self):\n self.debug = False\n self.times = []\n self.layers = []\n self.bounding_box = []\n self.width = 0\n self.height = 0\n self.max_cloud_percentage = 1 # take all images by default\n self.image_dir = \"\"\n\n @staticmethod\n def validate(raw_dict: dict) -> None:\n \"\"\"\n Validate config file according to validation schema defined in schema.py file.\n\n :param raw_dict: dictionary with config options\n :return: None\n \"\"\"\n try:\n Draft4Validator(CONFIG_SCHEMA).validate(raw_dict)\n except ValidationError as ex:\n logger.error(\"Provided configuration is not valid\", **raw_dict)\n raise Exception(f\"Provided configuration is not valid: {ex}.\")\n\n @staticmethod\n def get_from_dict(raw_dict: dict, validate=True) -> \"Config\":\n \"\"\"\n Get Config object from python dict.\n\n :param raw_dict: Dict loaded from file\n :param validate: validate if config is correct according to schema in schema.py\n :return: Config\n \"\"\"\n if validate:\n Config.validate(raw_dict)\n\n config = Config()\n\n config.debug = raw_dict.get(\"debug\", False)\n config.times = raw_dict.get(\"times\", None)\n config.layers = raw_dict.get(\"layers\", None)\n config.bounding_box = raw_dict.get(\"bounding_box\", None)\n config.width = raw_dict.get(\"width\", None)\n config.height = raw_dict.get(\"height\", None)\n config.max_cloud_percentage = raw_dict.get(\"max_cloud_percentage\", 1)\n config.image_dir = raw_dict.get(\"images_dir\", None)\n\n logger.debug(\"Loaded config\", **config.__dict__)\n\n return config\n\n @staticmethod\n def get_config(path=None) -> \"Config\":\n \"\"\"\n Load configuration file from provided path or current working directory.\n\n :param path: Absolute path to config file.\n :return: Config\n \"\"\"\n directory = Path(path) or Path.cwd()\n if not path:\n # try to find config in current directory with default name\n config_file_name_full = directory / CONFIG_FILE_NAME\n else:\n # full path to config is provided from command line\n config_file_name_full = directory\n\n logger.debug(\"Loading config\", directory=directory)\n\n try:\n loaded_config = safe_load(open(config_file_name_full))\n except Exception as ex:\n logger.error(\n \"Cannot load config\", config_file_name_full=config_file_name_full\n )\n raise Exception(f\"Cannot load config: {ex}.\")\n\n return Config.get_from_dict(raw_dict=loaded_config)\n","sub_path":"sentinel_downloader/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"628817141","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport datetime as dt\nimport json\nimport werkzeug\nfrom flask import jsonify, request, g\nfrom flask_restful import Resource, reqparse, abort, marshal_with, fields\n\n# from ..models import Club as ClubModel\nfrom ..models import UserDetail as UserDetailModel\n\nfrom ..utils.errors import ValidationError\nfrom ..utils.decorators import login_required\nfrom ..utils.helper import saveProfileImage, deleteProfileImage\n\n\nclass UserDetail(Resource):\n @login_required\n def get(self):\n userDetail = UserDetailModel.query.filter_by(user=g.user).first()\n if userDetail:\n return {'userDetail': userDetail.serialize()}\n abort(400, message='Алдаа -> {}'.format(str('Мэдээлэл байхгүй')))\n\n\nclass UserDetailUpdate(Resource):\n @login_required\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('register', type=unicode, help=\"Регистрийн дугаар оруулна уу!\", required=True)\n parser.add_argument('familyname', type=unicode, help=\"Ургийн овог оруулна уу!\", required=True)\n parser.add_argument('lastname', type=unicode, help=\"Овог оруулна уу!\", required=True)\n parser.add_argument('firstname', type=unicode, help=\"Нэр оруулна уу!\", required=True)\n parser.add_argument('sex', type=bool, help=\"Хүйс оруулна уу!\", required=True)\n parser.add_argument('birthday', type=str, help=\"Төрсөн өдөр оруулна уу!\", required=True)\n parser.add_argument('phone', type=str, help=\"Утас оруулна уу!\", required=True)\n parser.add_argument('address', type=unicode, help=\"Хаяг оруулна уу!\", required=True)\n parser.add_argument('email', type=str, help=\"Хаяг оруулна уу!\", required=True)\n parser.add_argument('sportTypeId', type=int, help=\"Спортын төрөл оруулна уу!\", required=True)\n parser.add_argument('clubId', type=int, help=\"Харьяа клуб оруулна уу!\", required=True)\n parser.add_argument('contactName', type=unicode, help=\"Холбоо барих хүний нэр оруулна уу!\", required=True)\n parser.add_argument('contactPhone', type=str, help=\"Холбоо барих хүний утас оруулна уу!\", required=True)\n parser.add_argument('contactAddress', type=unicode, help=\"Холбоо барих хүний хаяг оруулна уу!\", required=True)\n parser.add_argument('image', type=werkzeug.datastructures.FileStorage, location='files')\n\n args = parser.parse_args()\n\n register = args.get('register')\n familyname = args.get('familyname')\n lastname = args.get('lastname')\n firstname = args.get('firstname')\n sex = args.get('sex')\n birthday = args.get('birthday')\n phone = args.get('phone')\n address = args.get('address')\n email = args.get('email')\n sportTypeId = args.get('sportTypeId')\n clubId = args.get('clubId')\n contactName = args.get('contactName')\n contactPhone = args.get('contactPhone')\n contactAddress = args.get('contactAddress')\n image = args.get('image')\n\n birthday = dt.datetime.strptime(birthday, \"%Y-%m-%d\").date()\n\n try:\n userDetail = UserDetailModel.query.get(g.user.id)\n\n image = saveProfileImage(image) if image else userDetail.image\n deleteProfileImage(userDetail.image)\n userDetail.update(\n register=register,\n familyname=familyname,\n lastname=lastname,\n firstname=firstname,\n sex=sex,\n birthday=birthday,\n phone=phone,\n address=address,\n email=email,\n image=image,\n sportTypeId=sportTypeId,\n clubId=clubId,\n contactName=contactName,\n contactPhone=contactPhone,\n contactAddress=contactAddress,\n )\n return {'userDetail': userDetail.serialize()}\n except ValidationError as e:\n abort(400, message='Алдаа -> {}'.format(str(e)))\n","sub_path":"server/usport/api/userDetail.py","file_name":"userDetail.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"355030900","text":"# -*- coding: utf-8 -*-\n'''文件说明:极简日志系统-桌面版\n作者信息:yangshaoshun\n版本自述:v1.2\n更新:本地必须是有 mydiary.log;使用 text 插件显示内容,不用输入文件名称;main_me.py 使用 message 插件显示内容\n待解决问题1:因为 idle 编码问题,无法输入中文\n待解决问题2:考虑使用 单行显示的text + message 输入和展示\n待解决问题3:界面布局\n待解决问题4:不止输入一行字符,使用 txt 输入一段文字,甚至可以输入 md 格式,下面展示转换后的内容\n代办事项:书写 readme.md\n代办事项2:docopt 的使用\n'''\n#全局引用\nfrom Tkinter import *\nfrom ttk import *\nfrom sys import argv\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\n\n#script, filename = argv\n\n#开启窗口\nmaster = Tk()\nmaster.title('^--^')\n\n#提示信息\n#headname = StringVar()\n#w = Label(master, textvariable = headname)\n#w = Label(master, text = '^--^')\n#headname.set('编辑' + filename +'.txt')\n#w.pack()\n\n#通过按钮读取输入的内容,保存到本地文件中\ndef callback(*args): # *args 的具体含义不知道,不加的话,提示 callback() takes no arguments\n txt = v.get()\n #target = open(filename + '.txt', 'a')\n target = open('mydiary.log', 'a')\n target.write(txt + '\\n')\n target = open('mydiary.log')\n #s.set(target.read())\n with open('mydiary.log') as f:\n for line in f:\n lastline = line\n e.delete(0, END)\n e.focus_set()\n t.insert(END, lastline)\n #t.insert(END, lastline,'current_line')\n #t.tag_remove(\"current_line\", 1.0, \"end\")\n\n#输入框\nv = StringVar()\ne = Entry(master, textvariable = v , width=50)\ne.bind('',callback)\ne.pack(fill=\"x\")\n\n#b = Button(master, text=\"get\", width=10, command=callback)\n#b.pack()\n\n#读取文件内容\n#s = StringVar()\n#target = open('mydiary.log')\n#s.set(target.read())\n#展示文件内容\n#w = Message(master, textvariable=s, width=50)\n#w.pack()\n\n#def highlightline(Event=None):\n# t.tag_remove(\"current_line\", 1.0, \"end\")\n# t.tag_add(\"current_line\", \"current linestart\", \"current lineend+1c\")\n\nt = Text(master, width = 30)\nt.pack(anchor = W)\n#设置一个标签,叫做 当前行为灰色\n#t.tag_configure(\"current_line\", background=\"gray\")\n#t.bind(\"\", highlightline)\nwith open('mydiary.log') as f:\n for line in f:\n t.insert(END, line)\n lastline = line\n\nbu = Button(master, text = 'quit', command = master.quit) #退出按钮,添加成功\nbu.pack(side=LEFT)\n\nmainloop()","sub_path":"_src/om2py0w/0wex2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"222317509","text":"\"\"\"This contains the plotting and geo data management methods for the COVIDcast signals.\n\nShapefiles are sourced from the 2019 US Census Cartographic Boundary Files\nhttps://www.census.gov/geographies/mapping-files/time-series/geo/cartographic-boundary.html\nScale is 1:5,000,000\n\"\"\"\n\nimport geopandas as gpd\nimport pandas as pd\n\nimport pkg_resources\nfrom covidcast.covidcast import _detect_metadata\n\nSHAPEFILE_PATHS = {\"county\": \"shapefiles/cb_2019_us_county_5m.zip\",\n \"state\": \"shapefiles/cb_2019_us_state_5m.zip\"}\n\n\ndef get_geo_df(data: pd.DataFrame,\n geo_value_col: str = \"geo_value\",\n geo_type_col: str = \"geo_type\") -> gpd.GeoDataFrame:\n \"\"\"Append polygons to a dataframe for a given geography and return a geoDF with this info.\n\n This method takes in a pandas DataFrame object and returns a GeoDataFrame object from the\n `geopandas package `__.\n\n After detecting the geography type (either county or state) for the input, loads the\n GeoDataFrame which contains state and geometry information from the Census for that geography\n type. Left joins the input data to this, so all states/counties will always be present\n regardless of the input i.e. the output dimension for a given geo_type is always the same\n regardless of input. Finally, returns the columns containing the input columns along with a\n `geometry` (polygon for plotting) and `state_fips` (FIPS code which will be used in the\n plotting function to rearrange AK and HI) column. Coordinate system is GCS NAD83.\n\n Default arguments for column names correspond to return of :py:func:`covidcast.signal`.\n Currently only supports counties and states.\n\n :param data: DataFrame of values and geographies\n :param geo_value_col: name of column containing values of interest\n :param geo_type_col: name of column containing geography type\n :return: GeoDataFrame of all state and geometry info for given geo type w/ input data appended.\n \"\"\"\n geo_type = _detect_metadata(data, geo_type_col)[2] # pylint: disable=W0212\n output_cols = list(data.columns) + [\"geometry\", \"state_fips\"]\n\n shapefile_path = pkg_resources.resource_filename(__name__, SHAPEFILE_PATHS[geo_type])\n geo_info = gpd.read_file(\"zip://\" + shapefile_path)\n\n if geo_type == \"state\":\n output = _join_state_geo_df(data, geo_value_col, geo_info)\n elif geo_type == \"county\":\n output = _join_county_geo_df(data, geo_value_col, geo_info)\n else:\n raise ValueError(\"Unsupported geography type; only state and county supported.\")\n output.rename(columns={\"STATEFP\": \"state_fips\"}, inplace=True)\n return output[output_cols]\n\n\ndef _join_state_geo_df(data: pd.DataFrame,\n state_col: str,\n geo_info: gpd.GeoDataFrame) -> gpd.GeoDataFrame:\n \"\"\"Left join DF information to polygon information in a GeoDF at the state level.\n\n :param data: DF with state info\n :param state_col: cname of column in `data` containing state info to join on\n :param geo_info: GeoDF of state shape info read from Census shapefiles\n \"\"\"\n geo_info.STUSPS = [i.lower() for i in geo_info.STUSPS] # lowercase for consistency\n merged = geo_info.merge(data, how=\"left\", left_on=\"STUSPS\", right_on=state_col)\n # use full state list in the return\n merged[state_col] = merged.STUSPS\n return merged\n\n\ndef _join_county_geo_df(data: pd.DataFrame,\n county_col: str,\n geo_info: gpd.GeoDataFrame) -> gpd.GeoDataFrame:\n \"\"\"Left join DF information to polygon information in a GeoDF at the county level.\n\n Counties with no direct key in the data DF will have the megacounty value joined.\n\n :param data: DF with county info\n :param county_col: name of column in `data` containing county info to join on\n :param geo_info: GeoDF of county shape info read from Census shapefiles\n \"\"\"\n # create state FIPS code in copy, otherwise original gets modified\n data = data.assign(state=[i[:2] for i in data[county_col]])\n # join all counties with valid FIPS\n merged = geo_info.merge(data, how=\"left\", left_on=\"GEOID\", right_on=county_col)\n mega_county_df = data.loc[[i.endswith('000') for i in data[county_col]],\n [\"state\", \"value\"]]\n if not mega_county_df.empty:\n # if mega counties exist, join them on state, and then use that value if no original signal\n merged = merged.merge(mega_county_df, how=\"left\", left_on=\"STATEFP\", right_on=\"state\")\n merged[\"value\"] = [j if pd.isna(i) else i for i, j in zip(merged.value_x, merged.value_y)]\n # use the full county FIPS list in the return\n merged[county_col] = merged.GEOID\n return merged\n","sub_path":"Python-packages/covidcast-py/covidcast/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"320153707","text":"import requests\nfrom django.conf import settings\nfrom django.http import Http404\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\n\nfrom . import forms\nfrom django.views.generic.edit import FormView, DeleteView\nfrom .models import Subscriber, Drug, Reminder, Confirmation\nfrom django.contrib.auth.models import User\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import logout\n\nfrom datetime import time\n\n\ndef home(request):\n return render(request, 'accounts/home.html')\n\n\ndef logout_user(request):\n logout(request)\n messages.add_message(request, messages.SUCCESS, \"You are now logged out.\")\n return redirect('accounts:home')\n\n\nclass SignupForm(FormView):\n template_name = 'signup.html'\n form_class = forms.UserForm\n success_url = 'thanks.html'\n\n def post(self, request):\n form = forms.UserForm(request.POST)\n if form.is_valid():\n ''' RECAPTCHA VALIDATION '''\n recaptcha_response = request.POST.get('g-recaptcha-response')\n data = {\n 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,\n 'response': recaptcha_response\n }\n r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)\n result = r.json()\n\n if result['success']:\n user = form.save(commit=False)\n password = form.cleaned_data['password']\n user.set_password(password)\n user.save()\n messages.add_message(request, messages.SUCCESS, \"You have successfully signed up!\")\n return render(request, 'accounts/thanks.html')\n else:\n return render(request, 'accounts/robot.html')\n else:\n return render(request, 'accounts/whoops.html')\n\n def get(self, request):\n form = forms.UserForm()\n return render(request, 'accounts/signup.html', {'form':form})\n\n\n# Profile Views #\n#################\n@login_required(login_url=\"/accounts/login/\")\ndef profile(request):\n # Static List View of User Account and Subscription Info\n if request.user.is_authenticated:\n user = User.objects.get(pk=request.user.id)\n try:\n subscriber = Subscriber.objects.get(user=user)\n except Subscriber.DoesNotExist:\n subscriber = None\n\n if subscriber is None:\n messages.add_message(request, messages.WARNING,\n \"It looks like we still need your subscription info! \"\n \"Please click 'Edit' on your profile page and complete your info below to get started.\")\n else:\n render(request, \"/accounts/login/\")\n return render(request, 'accounts/profile.html', {\n 'user': user,\n 'subscriber': subscriber,\n })\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef edit_profile(request):\n if request.method == 'POST':\n user_form = forms.ProfileUserForm(request.POST, instance=request.user)\n try:\n user = User.objects.get(pk=request.user.id)\n subscriber, created = Subscriber.objects.get_or_create(user=user)\n subscriber_form = forms.SubscriberForm(request.POST, instance=subscriber)\n if user_form.is_valid() and subscriber_form.is_valid():\n user_form.save()\n subscriber_form.save()\n messages.add_message(request, messages.SUCCESS,\n \"Your profile information has been updated!\")\n except Subscriber.DoesNotExist:\n subscriber_form = forms.SubscriberForm(request.POST)\n if user_form.is_valid() and subscriber_form.is_valid():\n user_form.save()\n subscriber_form.save()\n messages.add_message(request, messages.SUCCESS,\n \"Your profile information has been updated!\")\n return render(request, 'accounts/profile.html', {\n 'subscriber': subscriber,\n })\n else:\n user_form = forms.ProfileUserForm(instance=request.user)\n try:\n user = User.objects.get(pk=request.user.id)\n subscriber, created = Subscriber.objects.get_or_create(user=user)\n subscriber_form = forms.SubscriberForm(instance=subscriber)\n except Subscriber.DoesNotExist:\n subscriber_form = forms.SubscriberForm()\n return render(request, 'accounts/edit_profile.html', {\n 'user_form': user_form,\n 'subscriber_form': subscriber_form,\n })\n\n\n# Medication Views #\n####################\n@login_required(login_url=\"/accounts/login/\")\ndef medications(request):\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n drugs = Drug.objects.filter(subscriber_id = subscriber.id)\n return render(request, 'accounts/medications.html', {\n 'drugs': drugs\n })\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef medication_detail(request, pk):\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n drugs = Drug.objects.filter(subscriber_id = subscriber.id)\n if drugs:\n drug = Drug.objects.get(pk=pk)\n return render(request, 'accounts/medication_detail.html', {\n 'drug': drug\n })\n\n\nclass MedicationForm(FormView):\n template_engine = 'accounts/add_medication.html'\n form_class = forms.MedicationForm\n\n def post(self, request):\n form = forms.MedicationForm(request.POST)\n if form.is_valid():\n drug = form.save(commit=False)\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n drug.subscriber_id = subscriber\n drug.save()\n messages.add_message(request, messages.SUCCESS,\n \"You have successfully added a new medication!\")\n return render(request, 'accounts/medication_detail.html', {\n 'drug': drug\n })\n else:\n return render(request, 'accounts/whoops.html') #UPDATE THIS TO DRUG VALIDATION ERRORS\n\n def get(self, request):\n form = forms.MedicationForm()\n return render(request, 'accounts/add_medication.html', {'form':form})\n\n\nclass DeleteMedication(DeleteView):\n model = Drug\n success_url = reverse_lazy('accounts:medications')\n template_name = 'accounts/delete_medication.html'\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef edit_medication(request, pk):\n drug = Drug.objects.get(pk=pk)\n if request.method == 'POST':\n drug_form = forms.MedicationForm(request.POST, instance=drug)\n if drug_form.is_valid():\n drug_form.save()\n messages.add_message(request, messages.SUCCESS,\n \"Your medication has been updated\")\n return render(request, 'accounts/medication_detail.html', {\n 'drug': drug,\n })\n else:\n drug_form = forms.MedicationForm(instance=drug)\n return render(request, 'accounts/edit_medication.html', {\n 'drug_form': drug_form\n })\n\n\n# Reminder Views #\n##################\nclass ReminderForm(FormView):\n template_engine = 'accounts/add_reminder.html'\n form_class = forms.ReminderForm\n\n def post(self, request):\n form = forms.ReminderForm(request.POST)\n if form.is_valid():\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n # drugs = Drug.objects.filter(subscriber_id=subscriber.id)\n reminder = form.save(commit=False)\n reminder.subscriber_id = subscriber\n reminder.save()\n messages.add_message(request, messages.SUCCESS,\n \"You have successfully added a new reminder!\")\n return render(request, 'accounts/reminder_detail.html', {\n 'reminder': reminder\n })\n else:\n return render(request, 'accounts/whoops.html') #UPDATE THIS TO DRUG VALIDATION ERRORS\n\n def get(self, request):\n form = forms.ReminderForm()\n return render(request, 'accounts/add_reminder.html', {'form':form})\n\n@login_required(login_url=\"/accounts/login/\")\ndef reminders_list(request):\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n reminders = Reminder.objects.filter(subscriber_id = subscriber.id)\n return render(request, 'accounts/reminders.html', {\n 'reminders': reminders\n })\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef reminder_detail(request, pk):\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n reminders = Reminder.objects.filter(subscriber_id = subscriber.id)\n if reminders:\n reminder = Reminder.objects.get(pk=pk)\n else:\n raise Http404\n return render(request, 'accounts/reminder_detail.html', {\n 'reminder': reminder,\n })\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef edit_reminder(request, pk):\n reminder = Reminder.objects.get(pk=pk)\n if request.method == 'POST':\n reminder_form = forms.ReminderForm(request.POST, instance=reminder)\n if reminder_form.is_valid():\n # reminder_form.drug = reminder_form.cleaned_data['drug']\n reminder_form.save()\n messages.add_message(request, messages.SUCCESS,\n \"Your reminder has been updated\")\n return render(request, 'accounts/reminder_detail.html', {\n 'reminder': reminder,\n })\n else:\n reminder_form = forms.ReminderForm(instance=reminder)\n return render(request, 'accounts/edit_reminder.html', {\n 'reminder_form': reminder_form\n })\n\n\nclass DeleteReminder(DeleteView):\n model = Reminder\n success_url = reverse_lazy('accounts:reminders_list')\n template_name = 'accounts/delete_reminder.html'\n\n\n# Confirmation Views #\n######################\nclass ConfirmationForm(FormView):\n template_engine = 'accounts/add_confirmation.html'\n form_class = forms.ConfirmationForm\n\n def post(self, request):\n form = forms.ConfirmationForm(request.POST)\n if form.is_valid():\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n confirmation = form.save(commit=False)\n confirmation.subscriber_id = subscriber\n confirmation.save()\n messages.add_message(request, messages.SUCCESS,\n \"You have successfully added a new reminder!\")\n return render(request, 'accounts/confirmation_detail.html', {\n 'confirmation': confirmation\n })\n else:\n return render(request, 'accounts/whoops.html') #UPDATE THIS WITH VALIDATION ERRORS\n\n def get(self, request):\n form = forms.ConfirmationForm()\n return render(request, 'accounts/add_confirmation.html', {'form':form})\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef confirmations_list(request):\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n confirmations = Confirmation.objects.filter(subscriber_id = subscriber.id)\n return render(request, 'accounts/confirmations.html', {\n 'confirmations': confirmations\n })\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef confirmation_detail(request, pk):\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n confirmations = Confirmation.objects.filter(subscriber_id = subscriber.id)\n if confirmations:\n confirmation = Confirmation.objects.get(pk=pk)\n else:\n raise Http404\n return render(request, 'accounts/confirmation_detail.html', {\n 'confirmation': confirmation,\n })\n\n\n@login_required(login_url=\"/accounts/login/\")\ndef edit_confirmation(request, pk):\n confirmation = Confirmation.objects.get(pk=pk)\n if request.method == 'POST':\n confirmation_form = forms.ConfirmationForm(request.POST, instance=confirmation)\n if confirmation_form.is_valid():\n confirmation_form.save()\n messages.add_message(request, messages.SUCCESS,\n \"Your reminder has been updated\")\n return render(request, 'accounts/confirmation_detail.html', {\n 'confirmation': confirmation,\n })\n else:\n confirmation_form = forms.ConfirmationForm(instance=confirmation)\n return render(request, 'accounts/edit_confirmation.html', {\n 'confirmation_form': confirmation_form\n })\n\n\nclass DeleteConfirmation(DeleteView):\n model = Confirmation\n success_url = reverse_lazy('accounts:confirmations_list')\n template_name = 'accounts/delete_confirmation.html'\n\n\n# Dashboard Views #\n###################\n@login_required(login_url=\"/accounts/login/\")\ndef dashboard(request):\n subscriber = Subscriber.objects.get(pk=request.user.subscriber.pk)\n reminders = Reminder.objects.filter(subscriber_id = subscriber.id)\n morning_reminders = []\n afternoon_reminders = []\n evening_reminders = []\n for reminder in reminders:\n if reminder.time_of_day < time(12):\n morning_reminders.append(reminder)\n elif reminder.time_of_day < time(17):\n afternoon_reminders.append(reminder)\n else:\n evening_reminders.append(reminder)\n return render(request, 'accounts/dashboard.html', {\n 'morning_reminders': morning_reminders,\n 'afternoon_reminders': afternoon_reminders,\n 'evening_reminders': evening_reminders,\n })\n\n\n# Support Views #\n#################\ndef support(request):\n return render(request, 'accounts/support.html')\n\n\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"40038214","text":"from argparse import ArgumentParser\nfrom Bio import SeqIO\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom operator import itemgetter\nfrom itertools import combinations\n\n\nparser = ArgumentParser()\nparser.add_argument(\"efile\", help=\"Error rate file\")\nparser.add_argument(\"summaryfile\", help=\"Contig Distance Summary file\")\nparser.add_argument(\"contigfile\", help=\"Contig File\")\nparser.add_argument(\"cellline\", help=\"Cell Line\")\n#parser.add_argument(\"--maxdev\", help=\"Maximal deviation\", type=float, default=2.0)\nparser.add_argument(\"--mindepth\", help=\"Minimal depth\", type=int, default=20)\n\nargs = parser.parse_args()\n\nreads = {}\ngreads = {}\ncgreads = []\ncontigs = {}\n\n\nfor read in SeqIO.parse(args.contigfile, \"fasta\"):\n contigs[read.id] = len(read.seq)\n\nprint(\"Nr. of scaffolds: \" + str(len(contigs)))\n\n\n# nanopore read info\nwith open(args.efile) as f:\n for line in f:\n sline = line.split()\n rid = sline[0]\n ctg = sline[1]\n strand = int(sline[8])\n scr = int(sline[5])\n ecr = int(sline[6])\n scc = int(sline[9])\n ecc = int(sline[10])\n lc = int(sline[11])\n payload = {\"contig\":ctg,\"strand\":strand,\"scr\":scr,\"ecr\":ecr,\"scc\":scc,\"ecc\":ecc,\"lc\":lc}\n if rid in reads:\n reads[rid][\"overlaps\"].append(payload)\n else:\n reads[rid] = {}\n reads[rid][\"length\"] = int(sline[7])\n reads[rid][\"overlaps\"] = [payload]\n\n# get interesting reads\n# and sort contigs by left coordinate\ngreadst = {}\nfor rid in reads:\n counter = 0\n for item in reads[rid][\"overlaps\"]:\n if item[\"contig\"].endswith(args.cellline):\n greadst[rid] = reads[rid]\n break\nfor rid in greadst:\n #print(reads[rid][\"overlaps\"])\n soverlaps = sorted(reads[rid][\"overlaps\"], key = itemgetter(\"scr\"))\n greads[rid] = greadst[rid]\n greads[rid][\"overlaps\"]=soverlaps\n\n\n\n\n# cluster np-reads \nprint(\"scaffolding long reads ....\")\ncontig2cluster = {}\ncreads = {}\nclusternr = 0\nwhile len(greads) > 0:\n clusternr += 1\n current_cluster = {}\n current_contigs = set()\n # take a random read and build a cluster from it\n cr = greads.popitem()\n current_cluster[cr[0]] = cr[1]\n olen = 0\n while len(current_cluster) != olen:\n olen = len(current_cluster)\n for contig in cr[1][\"overlaps\"]:\n if not contig[\"contig\"].startswith(\"chr\"):\n contigs.pop(contig[\"contig\"], None)\n current_contigs.add(contig[\"contig\"])\n contig2cluster[contig[\"contig\"]] = clusternr\n for readid,readval in greads.items():\n contig_found = False\n for contig in readval[\"overlaps\"]:\n if not contig[\"contig\"].startswith(\"chr\"):\n if contig[\"contig\"] in current_contigs:\n contig_found = True\n current_cluster[readid] = readval\n cr = (readid, greads.pop(readid))\n break\n \n if contig_found:\n break\n creads[clusternr] = current_cluster\nprint(\"Nr. of scaffolds: \" + str(clusternr+len(contigs)) + \" (\" + str(clusternr) + \" cluster + \" + str(len(contigs))+ \" contigs)\")\n\n# simpler data structure to collect contigs into scaffolds\nscaffolds={}\nfor i, cluster in creads.items():\n current_contigs = set([])\n for readid,read in cluster.items():\n #print(read)\n for contig in read[\"overlaps\"]:\n if not contig[\"contig\"].startswith(\"chr\"):\n current_contigs.add(contig[\"contig\"])\n scaffolds[i] = current_contigs\n#print(scaffolds)\n\ndef addcontig(ctg, cluster):\n contig2cluster[ctg] = cluster\n scaffolds[cluster].add(ctg)\n contigs.pop(ctg, None)\n \ndef mergecluster(cluster1, cluster2):\n for contig in scaffolds[cluster2]:\n contig2cluster[contig] = cluster1\n scaffolds[cluster1].add(contig)\n scaffolds.pop(cluster2)\n\n# very lenient clustering of short reads\nprint(\"scaffolding short reads ....\")\nwith open(args.summaryfile) as f:\n for line in f:\n sline = line.split()\n ctg1 = sline[0].split(\"_\")[0].strip(\"+\").strip(\"-\")\n ctg2 = sline[0].split(\"_\")[1].strip(\"+\").strip(\"-\")\n if sline[1] == \"NA\":\n continue\n if int(sline[2]) < args.mindepth:\n continue\n #moddist = float(sline[1])\n if ctg1 in contig2cluster:\n if ctg2 in contig2cluster:\n if contig2cluster[ctg1] != contig2cluster[ctg2]:\n #print(\"merging clusters \" + str(contig2cluster[ctg1]) + \" and \" + str(contig2cluster[ctg2]))\n mergecluster(contig2cluster[ctg1], contig2cluster[ctg2])\n else:\n addcontig(ctg2, contig2cluster[ctg1])\n #print(\"cluster of ctg1 (\" + ctg1 + \"): \" + str(contig2cluster[ctg1]))\n elif ctg2 in contig2cluster:\n addcontig(ctg1, contig2cluster[ctg2])\n else:\n clusternr += 1\n #print(\"new cluster: \" + str(clusternr))\n scaffolds[clusternr] = set([ctg1, ctg2])\n contig2cluster[ctg1] = clusternr\n contig2cluster[ctg2] = clusternr\n contigs.pop(ctg1, None)\n contigs.pop(ctg2, None)\n \n \nprint(\"Nr. of scaffolds: \" + str(len(scaffolds)+len(contigs)) + \" (\" + str(len(scaffolds)) + \" cluster + \" + str(len(contigs))+ \" contigs)\")\n#print(contigs)\nfor scaf in scaffolds:\n print(scaffolds[scaf])\n print(\"-\"*200)\n\ndef get_rightmost_contig(scaf_id):\n print(creads[scaf_id])\n if len(creads[scaf_id]) > 1:\n print(\"not implemented yet\")\n else:\n rid, read = creads[scaf_id].items()\n for ov in read[\"overlaps\"]:\n print(ov)\n\n#get_rightmost_contig(1)\n#sys.exit(0)\n","sub_path":"naive_scaffolding.py","file_name":"naive_scaffolding.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"575616201","text":"import requests\nimport pandas as pd\nfrom nltk.tokenize import RegexpTokenizer\nfrom bs4 import BeautifulSoup\nimport itertools\n\n\"\"\"\n\nMartin Shkreli is a great value investor with amazing insights into\nvaluating pharmaceutical companies. He still manages to analyze and\nrecommend stocks from the confines of his jail cell.\n\nThis code attempts to crape his blog posts in order to parse out the\nstock symbols of companies referenced.\n\nI found the following in the last scrape:\n\n{'ABEO', 'ACAD', 'ALNY', 'ALXN', 'ANY', 'BCRX', 'BGNE', 'BMRN',\n'BOLD', 'CERC', 'DNLI', 'GBT', 'GILD', 'INCY', 'MGI', 'MGNX', 'MNTA',\n'NKTR', 'ONCE', 'PBYI', 'PTC', 'PTCT', 'PTLA', 'QURE', 'RARE', 'RCKT',\n'REGN', 'RGNX', 'RYTM', 'SGMO', 'SLDB', 'SRPT', 'VYGR', 'WVE'}\n\n\"\"\"\n\nnyse = pd.read_csv('../data/input/stocks/nyse.csv', header = 0, names = ['symbol', 'name'], usecols = [0, 1])\nnasdaq = pd.read_csv('../data/input/stocks/nasdaq.csv', header = 0, names = ['symbol', 'name'], usecols = [0, 1])\n\ndef is_nyse_symbol(token):\n return not (nyse.loc[nyse['symbol'] == token]).empty\n\ndef is_nasdaq_symbol(token):\n return not (nasdaq.loc[nasdaq['symbol'] == token]).empty\n\ndef get_posts(url):\n url = \"http://martinshkreli.com/page/1/\"\n r = requests.get(url)\n data = r.text\n soup = BeautifulSoup(data, \"lxml\")\n posts = soup.findAll(\"div\",{\"class\":\"entry-content\"})\n\ndef find_stock_symbols(posts):\n posts = [post.text for post in posts]\n tokenized_sents = [word_tokenize(post.text) for post in posts]\n # flatten list of lists\n tokens = list(itertools.chain(*tokenized_sents))\n res0 = [x for x in tokens if is_nasdaq_symbol(x)]\n # uniquify\n set(res0)\n\n","sub_path":"data_wrangling/scrape_martin_shkreli.py","file_name":"scrape_martin_shkreli.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"215426177","text":"# coding: utf-8\n\nimport datetime\nimport unittest\n\nimport fastobo\n\n# --- TermFrame --------------------------------------------------------------\n\nclass TestTermFrame(unittest.TestCase):\n\n type = fastobo.term.TermFrame\n\n def setUp(self):\n self.id = fastobo.id.PrefixedIdent(\"MS\", \"1000031\")\n\n def test_init(self):\n try:\n frame = self.type(self.id)\n except Exception:\n self.fail(\"could not create `TermFrame` instances\")\n\n def test_init_iterable(self):\n try:\n frame = self.type(self.id, [])\n except Exception:\n self.fail(\"could not create `TermFrame` instances\")\n try:\n frame = self.type(self.id, [\n fastobo.term.NameClause(\"thing\"),\n fastobo.term.CreatedByClause(\"Martin Larralde\")\n ])\n except Exception:\n self.fail(\"could not create `TermFrame` from iterable\")\n\n def test_init_type_error(self):\n self.assertRaises(TypeError, self.type, 1)\n self.assertRaises(TypeError, self.type, [1])\n self.assertRaises(TypeError, self.type, [\"abc\"])\n self.assertRaises(TypeError, self.type, \"abc\")\n self.assertRaises(TypeError, self.type, self.id, 1)\n self.assertRaises(TypeError, self.type, self.id, [1])\n self.assertRaises(TypeError, self.type, self.id, [\"abc\"])\n self.assertRaises(TypeError, self.type, self.id, \"abc\")\n\n\n# --- DefClause ---------------------------------------------------------\n\nclass TestDefClause(unittest.TestCase):\n\n type = fastobo.term.DefClause\n\n def test_repr(self):\n clause = self.type(\"definition\")\n self.assertEqual(repr(clause), \"DefClause('definition')\")\n\n id_ = fastobo.id.PrefixedIdent('ISBN', '0321842685')\n desc = \"Hacker's Delight (2nd Edition)\"\n x = fastobo.xref.Xref(id_, desc)\n\n clause = self.type(\"definition\", fastobo.xref.XrefList([x]))\n self.assertEqual(repr(clause), \"DefClause('definition', XrefList([{!r}]))\".format(x))\n\n\n# --- ConsiderClause ---------------------------------------------------------\n\nclass TestConsiderClause(unittest.TestCase):\n\n type = fastobo.term.ConsiderClause\n\n def setUp(self):\n self.id = fastobo.id.PrefixedIdent(\"MS\", \"1000031\")\n self.id2 = fastobo.id.PrefixedIdent(\"MS\", \"1000032\")\n\n def test_init(self):\n try:\n frame = self.type(self.id)\n except Exception:\n self.fail(\"could not create `ConsiderClause` instances\")\n\n def test_init_type_error(self):\n self.assertRaises(TypeError, self.type)\n self.assertRaises(TypeError, self.type, 1)\n\n def test_eq(self):\n self.assertEqual(self.type(self.id), self.type(self.id))\n self.assertNotEqual(self.type(self.id), self.type(self.id2))\n\n\n# --- IsObsoleteClause -------------------------------------------------------\n\n\nclass TestIsObsoleteClause(unittest.TestCase):\n\n type = fastobo.term.IsObsoleteClause\n\n def test_init(self):\n try:\n frame = self.type(True)\n except Exception:\n self.fail(\"could not create `IsObsoleteClause` instances\")\n\n def test_property_obsolete(self):\n c = self.type(False)\n self.assertEqual(c.obsolete, False)\n c.obsolete = True\n self.assertEqual(c.obsolete, True)\n\n def test_repr(self):\n self.assertEqual(repr(self.type(False)), \"IsObsoleteClause(False)\")\n self.assertEqual(repr(self.type(True)), \"IsObsoleteClause(True)\")\n\n def test_str(self):\n self.assertEqual(str(self.type(False)), \"is_obsolete: false\")\n self.assertEqual(str(self.type(True)), \"is_obsolete: true\")\n\n def test_eq(self):\n self.assertEqual(self.type(True), self.type(True))\n self.assertEqual(self.type(False), self.type(False))\n self.assertNotEqual(self.type(False), self.type(True))\n","sub_path":"tests/test_term.py","file_name":"test_term.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"262343075","text":"class DataDashboard:\n \"\"\"class to get queryset and return information needed by template (charjs)\n example : average of temperatures on last 4 hours\"\"\"\n\n def __init__(self):\n self.message_to_display = str()\n self.list_temp = []\n self.list_hours = []\n self.average = float()\n self.last_update_hour = str()\n\n def get_average_temperature_4_hours(self, queryset):\n \"\"\"Average of 4 last temperatures\"\"\"\n list_temp = []\n number = 0\n if len(queryset) >= 4:\n for i in queryset[:4]:\n list_temp.append(i.temperature)\n\n for temp in list_temp:\n number = temp + number\n average = number / 4\n average = str(average)\n self.average = average[:4] + \"°C\"\n else:\n return \"Vide\"\n\n def get_information_for_chartjs(self, queryset):\n \"\"\"Get data from queryset and put informations into list for ChartJS\"\"\"\n if queryset.first(): # check if queryset is empty or not\n for i in queryset:\n date = str(i.date)\n date = date[11:13] + 'h' # change 19:12:20 to 19h\n self.list_temp.append(i.temperature)\n self.list_hours.append(date)\n else:\n self.message_to_display = 'Pas d''informations à afficher'\n self.list_temp.reverse(), self.list_hours.reverse()\n\n def get_last_hour_update(self, queryset):\n \"\"\"Get the hour of last temperature receive\"\"\"\n if queryset.first(): # check if queryset is empty or not\n for i in queryset[:1]:\n date = str(i.date)\n date = date[11:16] + 'h' # change 19:12:20 to 19h\n self.last_update_hour = date\n else:\n self.last_update_hour = 'Vide'\n\n def get_all_information_for_dashboard(self, queryset):\n \"\"\"execute of all methods in class\"\"\"\n self.get_information_for_chartjs(queryset)\n self.get_average_temperature_4_hours(queryset)\n self.get_last_hour_update(queryset)\n\n\n","sub_path":"pitemp/website/data_dashboard.py","file_name":"data_dashboard.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"79686298","text":"import pyomo.environ as po\nfrom data import BinPackingExample, Lister, FFD\nimport itertools\n\n\ndef bpp(s, B):\n n = len(s)\n U = len(FFD(s, B))\n model = po.ConcreteModel(\"bpp\")\n model.var_indices = po.Set(initialize=itertools.product(range(n), range(U)))\n model.x = model.Var(model.var_indices, within=po.Binary)\n model.y = model.Var(range(U), within=po.Binary)\n\n model.z = po.Objective(po.quicksum(model.y[j] for j in range(U)), sense=po.minimize)\n\n model.assign = model.ConstraintList()\n for i in range(n):\n model.assign.add(expr=po.quicksum(model.x[i, j] for j in range(U)) == 1)\n for j in range(U):\n model.add(po.quicksum(s[i]*model.x[i, j]\n for i in range(n)) <= B*model.y[j], \"Capac(%s)\" % j)\n # for j in range(U):\n # for i in range(n):\n # model.addCons(model.x[i, j] <= model.y[j], \"Strong(%s,%s)\" % (i, j))\n\n # model.data = x, y\n return model\n\n\ndef solveBinPacking(s, B):\n n = len(s)\n U = len(FFD(s, B))\n model = bpp(s, B)\n solver = po.SolverFactory('glpk')\n results = solver.solve(model)\n bins = [[] for i in range(U)]\n for (i, j) in model.var_indices:\n if model.x[i, j]() > .5:\n bins[j].append(s[i])\n for i in range(bins.count([])):\n bins.remove([])\n for b in bins:\n b.sort()\n bins.sort()\n return bins\n\n\nif __name__ == '__main__':\n # s, B = BinPackingExample()\n s, B = Lister()\n bins = solveBinPacking(s, B)\n print(len(bins))\n for b in bins:\n print((b, sum(b)))\n","sub_path":"BinPacking/pyomo/compact.py","file_name":"compact.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"255933252","text":"from rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom django.shortcuts import get_object_or_404\nfrom game.serializers import CategorySerializer\nfrom game.validators import CategoryValidator\nfrom game.models import Category\n\n\nclass CategoryView(viewsets.ViewSet):\n def list(self, request):\n categorys = Category.objects.all()\n return Response(data=CategorySerializer(categorys, many=True).data)\n\n def create(self, request):\n validator = CategoryValidator(data=request.data)\n validator.is_valid(raise_exception=True)\n validator.save()\n return Response({})\n\n def update(self, request, pk):\n category = get_object_or_404(Category, pk=pk)\n validator = CategoryValidator(data=request.data, instance=category)\n validator.is_valid(raise_exception=True)\n validator.save()\n\n return Response({})\n","sub_path":"score_system/game/views/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"447831440","text":"import numpy\nfrom matplotlib import pyplot\nimport time, sys\n\nnx = 41\ndx = 2 / (nx-1)\nnt = 25\ndt = 0.025\nc = 1\n\nu = numpy.ones(nx)\nu[int(0.5/dx):int(1/dx+1)] = 2 # setting u = 2 between 0.5 and 1, initial conditions\n\n\n\n\n#initialize temporary array for the n+1 timestep\nun = numpy.ones(nx)\n\nfor n in range (nt):\n\tun = u.copy() #copy existing array u into temporary array un\n\tfor i in range(1,nx):\n\t#for i in range(nx):\n\t\tu[i] = un[i] - c * dt /dx * (un[i] - un[i-1])\n\nprint(u)\npyplot.plot(numpy.linspace(0,2,nx),u)\npyplot.show()","sub_path":"Step_1_Linear Convection.py","file_name":"Step_1_Linear Convection.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"211851709","text":"class Solution(object):\n\tdef largestDivisibleSubset(self, nums):\n\t\tnums.sort()\n\t\tN = len(nums)\n\t\tdp = []\n\t\tpath = []\n\t\tMax = 0\n\t\tk = 0\n\t\tresult = []\n\t\tfor i in xrange(N):\n\t\t\tdp.append(1)\n\t\t\tpath.append(i)\n\t\tfor i in xrange(N):\n\t\t\tfor j in xrange(i):\n\t\t\t\tif nums[i]%nums[j] == 0:\n\t\t\t\t\tif dp[j] + 1 > dp[i]:\n\t\t\t\t\t\tdp[i] = dp[j] + 1\n\t\t\t\t\t\tpath[i] = j\n\t\t\t\t\tif dp[i] > Max:\n\t\t\t\t\t\tMax = dp[i]\n\t\t\t\t\t\tk = i\n\t\tif path != []:\n\t\t\twhile path[k] != k:\n\t\t\t\tresult.append(nums[k])\n\t\t\t\tk = path[k]\n\t\t\tresult.append(nums[k])\n\t\t\tresult.sort()\n\t\treturn result","sub_path":"368_Largest_Divisible_Subset.py","file_name":"368_Largest_Divisible_Subset.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"269687044","text":"from typing import Union, Callable, Dict\n\nfrom . import heuristics\nfrom .active_loop import ActiveLearningLoop\nfrom .dataset import ActiveLearningDataset\nfrom .file_dataset import FileDataset\nfrom .nlp_datasets import HuggingFaceDatasets\n\n\ndef get_heuristic(name: str, shuffle_prop: float = 0.0,\n reduction: Union[str, Callable] = 'none',\n **kwargs) -> heuristics.AbstractHeuristic:\n \"\"\"\n Create an heuristic object from the name.\n\n Args:\n name (str): Name of the heuristic.\n shuffle_prop (float): Shuffling proportion when getting ranks.\n reduction (Union[str, Callable]): Reduction used after computing the score.\n kwargs (dict): Complementary arguments.\n\n Returns:\n AbstractHeuristic object.\n \"\"\"\n return {\n 'random': heuristics.Random,\n 'certainty': heuristics.Certainty,\n 'entropy': heuristics.Entropy,\n 'margin': heuristics.Margin,\n 'bald': heuristics.BALD,\n 'variance': heuristics.Variance,\n 'precomputed': heuristics.Precomputed,\n 'batch_bald': heuristics.BatchBALD\n }[name](shuffle_prop=shuffle_prop, reduction=reduction, **kwargs)\n\n\ndef active_huggingface_dataset(dataset,\n tokenizer=None,\n target_key: str = \"label\",\n input_key: str = \"sentence\",\n max_seq_len: int = 128,\n **kwargs):\n \"\"\"\n Wrapping huggingface.datasets with baal.active.ActiveLearningDataset.\n\n Args:\n dataset (torch.utils.data.Dataset): a dataset provided by huggingface.\n tokenizer (transformers.PreTrainedTokenizer): a tokenizer provided by huggingface.\n target_key (str): target key used in the dataset's dictionary.\n input_key (str): input key used in the dataset's dictionary.\n max_seq_len (int): max length of a sequence to be used for padding the shorter sequences.\n kwargs (Dict): Parameters forwarded to 'ActiveLearningDataset'.\n\n Returns:\n an baal.active.ActiveLearningDataset object.\n \"\"\"\n\n return ActiveLearningDataset(HuggingFaceDatasets(dataset,\n tokenizer,\n target_key,\n input_key,\n max_seq_len), **kwargs)\n","sub_path":"src/baal/active/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"441300784","text":"import math\n\ndef main():\n neededFuel = 0\n with open('input.txt','r') as f:\n for line in f:\n neededFuel += calculateReqFuel(int(line))\n print(neededFuel)\n\ndef calculateReqFuel(mass):\n fuel = math.floor(mass/3)-2\n if fuel > 0:\n fuel += calculateReqFuel(fuel)\n return fuel\n else:\n return 0\n\nif __name__ == '__main__':\n main()","sub_path":"1/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"578592668","text":"# !/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nfrom urllib import request,parse\r\nfrom sys import argv\r\nimport re\r\n\r\ndytt = 'http://www.dytt8.net'\r\nrequestUrl = dytt+argv[1]\r\n\r\nreq = request.Request(requestUrl)\r\nreq.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')\r\nwith request.urlopen(req) as f:\r\n data = f.read().decode('gbk')\r\n\r\n download = re.findall(r'(ftp.*?)\">ftp:', data)\r\n download = download[0]\r\n name = re.findall(r'

    .*《(.*?)》.*', data)\r\n name = name[0]\r\n img = re.findall(r'(http.*?jpg)', data)\r\n cover = img[0]\r\n if len(cover) == 2:\r\n image = img[1]\r\n else:\r\n image = \"\"\r\n introduction = re.findall(r'介

    (.*?)

    ', data)\r\n if len(introduction) == 0:\r\n introduction = re.findall(r'介

    \\r\\n

    ((.|\\n)*?)', data)\r\n if len(introduction) == 0:\r\n introduction = re.findall(r'简  介(.*?)img', data)\r\n introduction = introduction[0]\r\n #补充电影详细信息\r\n realname = re.findall(r'片  名(.*?)
    ', data)\r\n if len(cast) == 0:\r\n cast = re.findall(r'主  演(.*?)

    \\r\\n

    ', data)\r\n cast = cast[0]\r\n\r\nlogin_data = parse.urlencode([\r\n ('name', name),\r\n ('cover', cover),\r\n ('image', image),\r\n ('introduction', introduction),\r\n ('download', download),\r\n #补充电影详细信息\r\n ('realname', realname),\r\n ('year', year),\r\n ('place', place),\r\n ('category', category),\r\n ('language', language),\r\n ('subtitle', subtitle),\r\n ('doubanScore', doubanScore),\r\n ('fileFormat', fileFormat),\r\n ('videoSize', videoSize),\r\n ('filmLength', filmLength),\r\n ('director', director),\r\n ('cast', cast),\r\n ('doubanScore', doubanScore),\r\n ('requestUrl', requestUrl)\r\n])\r\n\r\nreq1 = request.Request('http://www.tvapi.cn/movie/add')\r\n\r\nwith request.urlopen(req1, data=login_data.encode('utf-8')) as f:\r\n data = f.read()\r\n data = data.decode('utf-8')\r\n print(data)\r\n","sub_path":"Pythonapi/getMovieInfo.py","file_name":"getMovieInfo.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"366728311","text":"from collections import defaultdict\nimport os\nimport time\nimport multiprocessing\nimport json\n\nresolution_stat1 = defaultdict(int)\nresolution_stat2 = defaultdict(int)\n\n\ndef decode(q):\n while True:\n cmd = q.get()\n os.system(cmd)\n q.task_done()\n\n\ndef get_scale(filename):\n stream_info = os.popen('ffprobe -v quiet -print_format json -show_streams -i \"' + filename + '\"').read()\n\n js = json.loads(stream_info)\n scale = '480x360'\n for stream in js['streams']:\n if stream['codec_type'] == 'video':\n width = stream['width']\n height = stream['height']\n\n if width < height:\n width, height = height, width\n resolution_ratio = round(10.0 * width / height)\n resolution_stat1[resolution_ratio] += 1\n scale = '360x480' if resolution_ratio < 16 else '360x640'\n else:\n resolution_ratio = round(10.0 * width / height)\n resolution_stat2[resolution_ratio] += 1\n scale = '480x360' if resolution_ratio < 16 else '640x360'\n\n break\n\n return scale\n\nif __name__ == '__main__':\n cmd_queue = multiprocessing.JoinableQueue(6)\n\n processes = []\n for i in range(4):\n p = multiprocessing.Process(target=decode, args=(cmd_queue,))\n p.daemon = True\n processes.append(p)\n\n for p in processes:\n p.start()\n\n invalid_name = []\n input_file = open(\"list.txt\")\n lines = input_file.readlines()\n start_pos = 0\n for count, line in enumerate(lines[start_pos:]):\n print(\"#######################Processing {}########################\".format(start_pos + count))\n filename = line.strip()\n try:\n output_filename = \"output/\" + filename\n print(output_filename)\n scale = get_scale(filename)\n cmd = 'ffmpeg -i \"' + filename + \\\n '\" -y -map v:0 -c:v libx264 -crf 18 -pix_fmt yuv420p' \\\n ' -vf scale=' + scale + ' -g 3 -keyint_min 3 -profile:v high \"' + \\\n output_filename + '\"'\n\n cmd_queue.put(cmd)\n\n except Exception as e:\n invalid_name.append(filename)\n print(filename)\n\n cmd_queue.join()\n\n print(\"Total: \", len(lines))\n print(resolution_stat1)\n print(resolution_stat2)\n print(\"invalid:\")\n print(invalid_name)\n\n","sub_path":"pytorch/video-cls/tsn-pytorch/nvvl_preprocess_multi_convert.py","file_name":"nvvl_preprocess_multi_convert.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"315543139","text":"from gpiozero import Button, LED\nfrom signal import pause\n\ndef press():\n print ( \"Button PRESSED!\" )\n led.on()\n\ndef unpress():\n print ( \"Button unpressed!\" )\n led.off()\n\nled=LED(23)\nled.off()\nbutton=Button(24)\nbutton.when_released=unpress\nbutton.when_pressed=press\n\npause()\n","sub_path":"reaction/examples/led-button.py","file_name":"led-button.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"374811673","text":"from .. import _view_markup\nfrom .. import _view\n\nclass LayoutView(_view_markup.ViewMarkup):\n def __init__(self, tag_name, attributes, *args):\n self._views = [self._convert_to_view_markup(v) for v in args]\n self._tag_name = tag_name\n self._attributes = attributes\n self._view_html = ''.join([v._html_for_layout() for v in self._views])\n self._ = ''.join([v._html_for_layout() for v in self._views])\n # Top level layout component -- escape with html comments.\n # If the contents of the wrapper is not HTML commented, it renders into\n # the page in seemingly nondeterministic order, and the contents will\n # get rendered as-is, even if the outer component is supposed to hide\n # them or transform them.\n # If wrapped in an HTML comment, the browser doesn't interpret the\n # contents, but they still get passed to the parent component as\n # children and handled in React.\n # See:\n # https://github.com/greenish/react-mount/blob/f3bee05f34838a2b657fff5d5812ab73ed9a60bb/readme.md#nested-components\n # https://github.com/greenish/react-mount/blob/f3bee05f34838a2b657fff5d5812ab73ed9a60bb/readme.md#html-comments\n self.html = \"\"\"\n<%s %s>\n \n\n \"\"\" % (self._tag_name, self._attributes, self._view_html, self._tag_name)\n self._publish()\n\n def _convert_to_view_markup(self, v):\n if isinstance(v, _view.View):\n return v._publish() # publishes to local ViewServer\n if not(isinstance(v, _view_markup.ViewMarkup)):\n raise TypeError('Expected parameters to a layout view to be View or ViewMarkup. Found %s.' % type(v))\n return v\n\n def _html_for_layout(self):\n # overrides View._html_for_layout\n # don't escape inner contents with \n # if this method is being called, it means the comment wrapping\n # has already been done by a parent layout component.\n # This is to prevent double-nested-commenting, as follows:\n # end something -->\n # (nested comments are not supported in HTML).\n return \"\"\"\n<%s %s>\n %s\n\n \"\"\" % (self._tag_name, self._attributes, self._view_html, self._tag_name)\n","sub_path":"env/lib/python2.7/site-packages/graphlab/_beta/views/platform/layout/_layout.py","file_name":"_layout.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"626831593","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-intel/egg/marrow/templating/serialize/marshal.py\n# Compiled at: 2012-05-23 13:18:32\nfrom __future__ import unicode_literals, absolute_import\nimport marshal\n__all__ = [\n b'render']\n\ndef render(data, template=None, i18n=None, **kw):\n \"\"\"Serialize data using Python marshal standard library.\n \n Accepts the same extended arguments as the marshal.dumps() function, see:\n \n http://www.python.org/doc/2.6/library/marshal.html#marshal.dumps\n \n \"\"\"\n return (\n b'application/octet-stream', marshal.dumps(data, **kw))","sub_path":"pycfiles/marrow.templating-1.0.2-py2.6/marshal.py","file_name":"marshal.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"378939481","text":"import os\nimport itertools\nimport json\nimport matplotlib\nimport matplotlib.pyplot as mplplot\nimport pandas as pd\nimport numpy as np\n\n\nclass BBoxResultsPlotter:\n def __init__(\n self,\n aggregatedDataPath,\n imageMetaDataPath,\n inputAnnotations,\n imageDir=\".\",\n imagePathColumn=\"image_path\",\n imagePathSuffix=\".png\",\n ):\n \"\"\"\n Args:\n aggregatedDataPath - Path to a JSON-format aggregator output file.\n imageMetaDataPath - Path to a pickled `pandas.DataFrame` with columns\n that must include \"image_id\" providing a unique index for the image to\n be plotted and \"subject_id\", providing the unique ID generated by the\n Panoptes platform.\n inputAnnotations - A list containing the input annotations provided to\n the aggregator.\n imageDir - Path to directory containing the annotated images.\n imagePathColumn - The name of the column in the metadata DataFrame containing\n the subject image paths relative to `imageDir`.\n imagePathSuffix - Suffix to append to the values in `imagePathColumn` to form\n a valid image file name (default: '.png')\n \"\"\"\n with open(aggregatedDataPath) as aggregatedDataFile:\n self.aggregatedData = json.load(aggregatedDataFile)\n self.imageMetaData = pd.read_pickle(imageMetaDataPath)\n # self.inputData = inputData\n self.imageDir = imageDir\n self.imagePathColumn = imagePathColumn\n self.imagePathSuffix = imagePathSuffix\n self.risks = None\n self.imageDimensions = None\n self.completionStates = None\n self.annotations = None\n self.inputAnnotations = inputAnnotations\n self.inputAnnotationDict = {}\n\n def processInputData(self):\n for annotation in self.inputAnnotations:\n if annotation[\"image_id\"] in self.inputAnnotationDict:\n if (\n annotation[\"worker_id\"]\n in self.inputAnnotationDict[annotation[\"image_id\"]]\n ):\n self.inputAnnotationDict[annotation[\"image_id\"]][\n annotation[\"worker_id\"]\n ].append(annotation)\n else:\n self.inputAnnotationDict[annotation[\"image_id\"]][\n annotation[\"worker_id\"]\n ] = [annotation]\n else:\n self.inputAnnotationDict[annotation[\"image_id\"]] = {\n annotation[\"worker_id\"]: [annotation]\n }\n\n self.extractRisks()\n self.extractImageDimensions()\n self.extractCompletionStates()\n self.extractAnnotations()\n\n def extractRisks(self):\n self.risks = {\n int(imageId): image[\"risk\"]\n for imageId, image in self.aggregatedData[\"images\"].items()\n }\n\n def extractSkillSigmas(self):\n self.skillSigmas = {\n int(np.nan_to_num(float(workerId))): worker[\"sigma\"]\n for workerId, worker in self.aggregatedData[\"workers\"].items()\n }\n\n def extractSkillFalsePosProbs(self):\n self.skillFalsePosProbs = {\n int(np.nan_to_num(float(workerId))): worker[\"prob_fp\"]\n for workerId, worker in self.aggregatedData[\"workers\"].items()\n }\n\n def extractSkillFalseNegProbs(self):\n self.skillFalseNegProbs = {\n int(np.nan_to_num(float(workerId))): worker[\"prob_fn\"]\n for workerId, worker in self.aggregatedData[\"workers\"].items()\n }\n\n def extractSubjectClassificationCounts(self):\n self.subjectClassificationCounts = {\n int(subjectId): len(subjectAnnotations)\n for subjectId, subjectAnnotations in self.inputAnnotationDict.items()\n }\n\n def extractCompletionStates(self):\n self.completionStates = {\n int(imageId): image[\"finished\"]\n for imageId, image in self.aggregatedData[\"images\"].items()\n }\n\n def extractImageDimensions(self):\n self.imageDimensions = {\n int(imageId): (image[\"width\"], image[\"height\"])\n for imageId, image in self.aggregatedData[\"images\"].items()\n }\n\n def extractAnnotations(self):\n default_category_id = 0\n anno_id = itertools.count(0)\n\n self.annotations = [\n {\n \"image_id\": label[\"image_id\"],\n \"category_id\": default_category_id,\n \"bbox\": [\n bbox[\"x\"],\n bbox[\"y\"],\n bbox[\"x2\"] - bbox[\"x\"],\n bbox[\"y2\"] - bbox[\"y\"],\n ],\n \"id\": next(anno_id),\n }\n for labelCounter, label in enumerate(self.aggregatedData[\"combined_labels\"])\n for bbox in label[\"label\"][\"bboxes\"]\n ]\n\n def plotExamples(\n self,\n numExamples,\n gridWidth=3,\n showLegend=False,\n selector=None,\n invertColours=False,\n ):\n unifiedFigureShape = np.array([gridWidth, numExamples // gridWidth])\n unifiedFigurePadSize = 6\n\n unifiedFigure, unifiedPanels = mplplot.subplots(\n figsize=unifiedFigureShape * unifiedFigurePadSize,\n ncols=unifiedFigureShape[0],\n nrows=unifiedFigureShape[1],\n )\n\n if showLegend:\n panelSlice = slice(0, -1, 1)\n else:\n panelSlice = slice(None)\n\n if selector is not None:\n selectedImageMetaData = self.imageMetaData.loc[selector]\n else:\n selectedImageMetaData = self.imageMetaData\n\n selectedImageIds = np.random.choice(\n selectedImageMetaData.image_id.unique(),\n size=numExamples - int(showLegend),\n replace=False,\n )\n\n selectedImageMetaData = selectedImageMetaData[\n selectedImageMetaData.image_id.apply(\n lambda imageId: imageId in selectedImageIds\n )\n ]\n\n allLabels = []\n allHandles = []\n\n for unifiedPanel, (imageIndex, groundTruth) in zip(\n unifiedPanels.flatten()[panelSlice],\n selectedImageMetaData.groupby(by=\"image_id\"),\n ):\n\n groundTruth = groundTruth.sort_values(by=\"subject_id\").head(1)\n subjectId = np.asscalar(groundTruth.subject_id)\n\n imageAnnotations = [\n annotation\n for annotation in self.annotations\n if int(annotation[\"image_id\"]) == subjectId\n ]\n\n if self.imagePathColumn in groundTruth.columns:\n imagePath = str(groundTruth[self.imagePathColumn].values[0])\n if self.imagePathSuffix is not None:\n imagePath += self.imagePathSuffix\n # print(type(imagePath), imagePath)\n if not os.path.isabs(imagePath):\n imagePath = os.path.join(self.imageDir, imagePath)\n else:\n imagePath = os.path.join(\n self.imageDir, \"subject_{}.png\".format(imageIndex)\n )\n\n imageData = mplplot.imread(imagePath)\n if invertColours:\n imageData[..., :-1] = (\n np.ones_like(imageData[..., :-1]) - imageData[..., :-1]\n )\n unifiedPanel.imshow(imageData, origin=\"lower\", zorder=0)\n\n for imageAnnotation in imageAnnotations:\n unifiedPanel.add_patch(\n matplotlib.patches.Rectangle(\n [imageAnnotation[\"bbox\"][0], imageAnnotation[\"bbox\"][1]],\n imageAnnotation[\"bbox\"][2],\n imageAnnotation[\"bbox\"][3],\n ec=\"k\",\n fc=\"none\",\n alpha=1,\n zorder=50,\n lw=2,\n label=\"Consensus\",\n )\n )\n\n uniqueWorkerIds = np.unique(\n np.concatenate(\n [\n [int(np.nan_to_num(float(key))) for key in imageAnnos.keys()]\n for imageAnnos in self.inputAnnotationDict.values()\n ]\n )\n )\n for workerId, workerAnnotations in self.inputAnnotationDict[\n str(subjectId)\n ].items():\n workerIndex = np.asscalar(\n np.flatnonzero(\n uniqueWorkerIds == int(np.nan_to_num(float((workerId))))\n )\n )\n for bbox in workerAnnotations[0][\"anno\"][\"bboxes\"]:\n unifiedPanel.add_patch(\n matplotlib.patches.Rectangle(\n [bbox[\"x\"], bbox[\"y\"]],\n bbox[\"x2\"] - bbox[\"x\"],\n bbox[\"y2\"] - bbox[\"y\"],\n # Anticipate images being finished\n # within 10 annotations\n ec=\"C{}\".format(workerIndex % 10),\n fc=\"none\",\n alpha=1,\n zorder=10,\n label=str(workerIndex),\n )\n )\n\n unifiedPanel.text(\n 0.95,\n 0.95,\n \"$|\\mathcal{{W}}|$ = {}\".format(\n len(self.inputAnnotationDict[str(subjectId)])\n ),\n horizontalalignment=\"right\",\n verticalalignment=\"top\",\n fontdict=dict(color=\"k\" if invertColours else \"w\", fontsize=\"x-large\"),\n transform=unifiedPanel.transAxes,\n )\n\n if self.completionStates[subjectId]:\n unifiedPanel.text(\n 0.05,\n 0.95,\n \"COMPLETE\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n fontdict=dict(\n color=\"k\" if invertColours else \"w\", fontsize=\"x-large\"\n ),\n transform=unifiedPanel.transAxes,\n )\n else:\n unifiedPanel.text(\n 0.05,\n 0.95,\n \"INCOMPLETE\",\n horizontalalignment=\"left\",\n verticalalignment=\"top\",\n fontdict=dict(\n color=\"k\" if invertColours else \"w\", fontsize=\"x-large\"\n ),\n transform=unifiedPanel.transAxes,\n )\n\n unifiedPanel.set_title(\n \"Simulated Image {}.\\n Risk: {:.4e}\".format(\n subjectId, self.risks[subjectId]\n )\n )\n\n unifiedPanel.set_xlim(0, self.imageDimensions[subjectId][0])\n unifiedPanel.set_ylim(0, self.imageDimensions[subjectId][0])\n unifiedPanel.set_xticks([])\n unifiedPanel.set_yticks([])\n\n handles, labels = unifiedPanel.get_legend_handles_labels()\n allHandles.extend(handles)\n allLabels.extend(labels)\n\n uniqueLabels = np.unique(allLabels)\n uniqueLabelIndices = [\n allLabels.index(uniqueLabel) for uniqueLabel in uniqueLabels\n ]\n\n if showLegend:\n legendAxes = unifiedPanels.flatten()[-1]\n legendAxes.axis(\"off\")\n legendAxes.legend(\n np.array(allHandles)[uniqueLabelIndices],\n np.array(allLabels)[uniqueLabelIndices],\n loc=\"center\",\n fontsize=\"x-large\",\n title=\"Workers\",\n ).get_title().set_fontsize(\"xx-large\")\n\n mplplot.tight_layout()\n return unifiedFigure, unifiedPanels\n\n def plotRisks(self, threshold=None, logAxes=False):\n riskAxes = mplplot.figure(figsize=(6, 6)).add_subplot(1, 1, 1)\n riskData = np.fromiter(self.risks.values(), dtype=np.float64)\n\n incompleteRiskData = [\n risk\n for subjectId, risk in self.risks.items()\n if not self.completionStates[subjectId]\n ]\n\n completeRiskData = [\n risk\n for subjectId, risk in self.risks.items()\n if self.completionStates[subjectId]\n ]\n\n if logAxes:\n riskBins = np.logspace(\n np.log10(riskData.min()), np.log10(riskData.max()), riskData.size // 10\n )\n riskAxes.set_xscale(\"log\")\n else:\n riskBins = np.linspace(\n np.log10(riskData.min()), np.log10(riskData.max()), riskData.size // 10\n )\n\n thresholdInRange = (\n threshold is not None\n and threshold > riskData.min()\n and threshold < riskData.max()\n )\n\n if thresholdInRange:\n riskBins = np.sort(np.append(riskBins, threshold))\n\n riskAxes.hist(completeRiskData, bins=riskBins, label=\"Complete\")\n riskAxes.hist(incompleteRiskData, bins=riskBins, label=\"Incomplete\")\n\n if thresholdInRange:\n riskAxes.axvline(\n x=threshold,\n label=\"$R_{{thresh}}$ = {:.2e}\".format(threshold),\n c=\"r\",\n ls=\"--\",\n )\n\n riskAxes.set_xlabel(\"Risk\")\n riskAxes.set_ylabel(\"Subject Count\")\n if logAxes:\n riskAxes.set_xscale(\"log\")\n riskAxes.legend()\n mplplot.tight_layout()\n return riskAxes\n","sub_path":"bayesian_aggregation/BBoxResultsPlotter.py","file_name":"BBoxResultsPlotter.py","file_ext":"py","file_size_in_byte":13631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"337937031","text":"import queue\nfrom . import (\n attributes, construct, cleanup, defaults, event_queue, load, recurse)\nfrom .. util import exception, json\n\nEVENT_QUEUE_MAXSIZE = 1000\n\n\nclass Project:\n CHILDREN = 'maker', 'drivers', 'layout', 'animation', 'controls'\n\n @staticmethod\n def pre_recursion(desc):\n return cleanup.cleanup(desc)\n\n def construct_child(self, datatype, typename=None, **kwds):\n construct = getattr(datatype, 'construct', None)\n if construct:\n return construct(self, **kwds)\n return datatype(**kwds)\n\n def __init__(self, *,\n drivers, layout, maker, path, animation, controls,\n event_queue_maxsize=EVENT_QUEUE_MAXSIZE, **kwds):\n \"\"\"\n :param int event_queue_maxsize: maxsize parameter to queue.Queue.\n 0 means an unbounded queue.\n \"\"\"\n def post(desc):\n return self.construct_child(**desc)\n\n def create(root, name):\n with exception.add('Unable to create ' + name):\n return recurse.recurse(\n root,\n pre=None,\n post=post,\n python_path='bibliopixel.' + name)\n\n attributes.check(kwds, 'project')\n self.path = path\n layout = layout or cleanup.cleanup_layout(animation)\n\n self.maker = self.construct_child(**maker)\n self.drivers = [create(d, 'drivers') for d in drivers]\n with exception.add('Unable to create layout'):\n self.layout = self.construct_child(**layout)\n\n self.animation = create(animation, 'animation')\n\n eq = event_queue.EventQueue(maxsize=event_queue_maxsize)\n self.animation.event_queue = eq\n self.animation.preframe_callback = eq.get_and_run_events\n\n # Unfortunately, the whole animation cycle is controlled by methods on\n # the topmost animation - but we need to get called back at a certain\n # point in that animation cycle in order to run the event queue safely -\n # and animations don't know about the Project!\n #\n # So the monkey-patch above. Ugly. When we rewrite the\n # animation cycle, it will be freed from the topmost animation, and\n # this problem will go away. (Also, animations should have access to\n # the Project, but that's a whole separate issue.)\n\n self.controls = [create(c, 'control') for c in controls]\n\n def start(self):\n self.layout.start()\n for c in self.controls:\n c.start(self)\n self.animation.start()\n\n def cleanup(self):\n self.animation.cleanup()\n for c in self.controls:\n c.cleanup()\n self.layout.cleanup_drivers()\n\n def run(self):\n try:\n self.start()\n finally:\n self.cleanup()\n\n\ndef project(*descs, root_file=None):\n \"\"\"\n Make a project with recursion and alias resolution. Use this\n instead of calling Project() directly.\n \"\"\"\n desc = defaults.merge(*descs)\n\n load.ROOT_FILE = root_file\n with load.extender(desc.get('path', '')):\n desc = recurse.recurse(desc)\n\n project = construct.construct(**desc)\n project.desc = desc\n return project\n","sub_path":"bibliopixel/project/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"154454917","text":"from django.conf.urls import url\n\nfrom .views import (\n NewPlanView,\n UpdatePlanView,\n DeletePlanView,\n SaveAsPlanView,\n NewQuestionView,\n FirstQuestionView,\n AddCommentView,\n PlanListView,\n PlanDetailView,\n ValidatePlanView,\n LockPlanView,\n PublishPlanView,\n CreateNewVersionPlanView,\n UpdateLinearSectionView,\n SectionDetailView,\n GeneratedPlanPlainTextView,\n GeneratedPlanHTMLView,\n GeneratedPlanPDFView,\n PlanAccessView,\n UpdatePlanAccessView,\n DeletePlanAccessView,\n)\n\n\nPLAN_RE = r'(?P\\d+)'\nPLAN_PAGEROOT_RE = r'%s/' % PLAN_RE\nSECTION_RE = r'(?P

    \\d+)'\nSECTION_PAGEROOT_RE = r'%s/section/%s/' % (PLAN_RE, SECTION_RE)\nQUESTION_RE = r'(?P\\d+)'\nQUESTION_PAGEROOT_RE = r'^%s/%s/' % (PLAN_RE, QUESTION_RE)\n\nurlpatterns = [\n url(r'^$', PlanListView.as_view(), name='plan_list'),\n url(r'^new/$', NewPlanView.as_view(), name='new_plan'),\n\n url(r'access/(?P\\d+)/update/$', UpdatePlanAccessView.as_view(), name='update_planaccess'),\n url(r'access/(?P\\d+)/delete/$', DeletePlanAccessView.as_view(), name='leave_plan'),\n url(PLAN_PAGEROOT_RE + 'share/$', PlanAccessView.as_view(), name='share_plan'),\n\n url(SECTION_PAGEROOT_RE + r'update/$', UpdateLinearSectionView.as_view(), name='answer_linear_section'),\n url(SECTION_PAGEROOT_RE + r'$', SectionDetailView.as_view(), name='section_detail'),\n url(PLAN_PAGEROOT_RE + 'update/$', UpdatePlanView.as_view(), name='update_plan'),\n url(PLAN_PAGEROOT_RE + 'check/$', ValidatePlanView.as_view(), name='validate_plan'),\n url(PLAN_PAGEROOT_RE + 'lock/$', LockPlanView.as_view(), name='lock_plan'),\n url(PLAN_PAGEROOT_RE + 'publish/$', PublishPlanView.as_view(), name='publish_plan'),\n url(PLAN_PAGEROOT_RE + 'unlock/$', CreateNewVersionPlanView.as_view(), name='unlock_plan'),\n url(PLAN_PAGEROOT_RE + 'first/new/$', FirstQuestionView.as_view(), name='first_question'),\n url(QUESTION_PAGEROOT_RE + r'new/$', NewQuestionView.as_view(), name='new_question'),\n url(QUESTION_PAGEROOT_RE + r'comment/$', AddCommentView.as_view(), name='new_comment'),\n url(PLAN_PAGEROOT_RE + r'$', PlanDetailView.as_view(), name='plan_detail'),\n url(PLAN_PAGEROOT_RE + r'delete/$', DeletePlanView.as_view(), name='plan_delete'),\n url(PLAN_PAGEROOT_RE + r'save-as/$', SaveAsPlanView.as_view(), name='plan_saveas'),\n url(PLAN_PAGEROOT_RE + r'generated.txt$', GeneratedPlanPlainTextView.as_view(), name='generated_plan_text'),\n url(PLAN_PAGEROOT_RE + r'generated.html$', GeneratedPlanHTMLView.as_view(), name='generated_plan_html'),\n url(PLAN_PAGEROOT_RE + r'generated.pdf$', GeneratedPlanPDFView.as_view(), name='generated_plan_pdf'),\n]\n","sub_path":"src/easydmp/plan/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"551101052","text":"import speedtest\nst = speedtest.Speedtest()\noption = int(input('''What speed you want to test:\n1) Download speed\n2) Upload speed\n3) Ping\nYour choice: '''))\n\nif option == 1:\n print(st.download(), 'b/s')\nelif option == 2:\n print(st.upload(), 'b/s')\nelif option == 3:\n servername = []\n st.get_servers(servername)\n print(st.results.ping, 'b/s')\n","sub_path":"New_folder/Speed Test.py","file_name":"Speed Test.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"553508499","text":"import random as rand\nanumber = rand.randint(0, 100)\nprint(\"Try to gess our random number [1, 100] in a maximum of 5 turns !\")\nhistory = []\nfor i in range(10):\n try:\n g = int(input())\n history.append(g)\n print(history)\n if g < anumber:\n print(\"too low\")\n elif g > anumber:\n print(\"too high\")\n else:\n print(\"Excelent!\")\n break\n except:\n print(\"not an integer\")\n history.append(\"NaN\")\n print(history)\n continue\nif (history[len(history)-1] != anumber):\n print(\"Game Over\")\n print(f\"the number was : {g}\")\n","sub_path":"games/gessing/gess.py","file_name":"gess.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"232202015","text":"import pandas as pd\nimport datetime\nimport pytz\nimport sys\nimport logging\nfrom dataHandler import DataHandler\nfrom base import call\nfrom base import put\nfrom events import tickEvent\n\nclass CsvData(DataHandler):\n \"\"\"This class handles data from CSV files which will be used\n for backtesting sessions. The handling of the CSV file is through pandas.\n \"\"\"\n\n def __init__(self, csvDir, filename, dataProvider, eventQueue, chunkSize):\n \"\"\"\n csvDir: input CSV directory of files used in backtesting.\n filename: filename of CSV to process.\n dataProvider: historical data provider (e.g, provider of CSV).\n eventQueue: location to place new data tick event.\n chunkSize: number of rows to read from the CSV at one time.\n \"\"\"\n self.__csvDir = csvDir\n self.__curRow = 0\n self.__chunkSize = chunkSize\n self.__curTimeDate = None\n self.__dataAvailable = False\n self.__dataReader = None\n self.__dataFrame = None\n self.__dataProvider = dataProvider\n self.__eventQueue = eventQueue\n\n # Open data source. Raises exception if failure.\n self.openDataSource(filename)\n\n def openDataSource(self, filename):\n \"\"\"\n Used to connect to the data source for the first time.\n In the case of a CSV, this means opening the file.\n The directory used is determined during initialization.\n \n Args:\n filename: input CSV file which contains historical data.\n \"\"\"\n\n try:\n self.__dataReader = pd.read_csv(self.__csvDir + '/' + filename, iterator=True)\n # Get a chunk and store it in the dataFrame\n self.__dataFrame = self.__dataReader.get_chunk(self.__chunkSize)\n except IOError:\n print(\"Unable to open data source\")\n raise\n\n # Indicates to other methods that the data is now available.\n self.__dataAvailable = True\n\n # TODO: is there a function to get the table_width?\n # Check that the CSV has the right number of columns.\n if self.__dataProvider == \"iVolatility\":\n try:\n self.__dataReader._engine._reader.table_width == 25\n except:\n print(\"CSV did not have right number of columns\")\n raise\n else:\n print(\"Unknown data provider; exiting.\")\n sys.exit(1)\n\n def getOptionChain(self):\n \"\"\"\n Used to get the option chain data for the underlying.\n The option chain consists of all of the puts and calls\n at all strikes currently listed for the underlying.\n Returns true/false depending on whether or not we successfully\n were able to get the option chain data. On success, the\n the rows of the option chain are converted into option objects,\n and the objects are put into the eventQueue as one event.\n \"\"\"\n\n # Attempt to get option chain from CSV -- the way we determine\n # which strikes / data belong to the option chain for the current\n # tick is by keeping track of the time/date.\n\n # Used to store all rows in current option chain.\n optionChain = []\n\n # Used to store objects created for each row of the option chain\n optionChainObjs = []\n\n # Different data providers will have to be handled differently.\n if self.__dataProvider == \"iVolatility\":\n\n # Get the first N rows with the same time/date.\n # To do this, we get the time/data from the first row, and then\n # we add to this any rows with the same date/time.\n\n # Handle first row -- add to optionChain.\n try:\n optionChain.append(self.__dataFrame.iloc[self.__curRow])\n self.__curTimeDate = self.__dataFrame['date'].iloc[self.__curRow]\n self.__curRow += 1\n except:\n # Could not get the current row if we end up here; try chunking to get more data.\n try:\n self.__dataFrame = self.__dataReader.get_chunk(self.__chunkSize)\n self.__curRow = 0\n optionChain.append(self.__dataFrame.iloc[self.__curRow])\n self.__curTimeDate = self.__dataFrame['date'].iloc[self.__curRow]\n self.__curRow += 1\n except:\n return False\n\n # TODO: replace this while loop with something more efficient --\n # For example, can select all dates from dataframe and then iterate\n # through them; we would need to keep track of the curRow still so we\n # can get the next option chain. We do it in this manner since it\n # seems that it would be faster if we had a HUGE CSV and tried to\n # do a bunch of groups for different dates.\n while 1:\n try:\n curTimeDate = self.__dataFrame['date'].iloc[self.__curRow]\n except:\n # Try chunking to get more data since we couldn't get current row.\n try:\n self.__dataFrame = self.__dataReader.get_chunk(self.__chunkSize)\n self.__curRow = 0\n curTimeDate = self.__dataFrame['date'].iloc[self.__curRow]\n except:\n break\n\n if curTimeDate == self.__curTimeDate:\n optionChain.append(self.__dataFrame.iloc[self.__curRow])\n self.__curRow +=1\n else:\n break\n\n # Convert option chain to base types (calls, puts).\n for row in optionChain:\n currentObj = self.createBaseType(row)\n # Make sure currentObj is not None.\n if currentObj:\n optionChainObjs.append(currentObj)\n\n # Create event and add to queue\n event = tickEvent.TickEvent()\n event.createEvent(optionChainObjs)\n self.__eventQueue.put(event)\n\n return True\n\n def getNextTick(self):\n \"\"\"\n Used to get the next available piece of data from the data source.\n For the CSV example, this would likely be the next row or option chain.\n \"\"\"\n\n # Check that data source has been opened.\n if self.__dataAvailable:\n\n # Get option chain and create event.\n if self.getOptionChain():\n return True\n else:\n return False\n\n else:\n # No event will be created, so nothing to do here.\n return False\n\n def getCSVDir(self):\n \"\"\"\n Used to get the name of the CSV directory.\n \"\"\"\n return self.__csvDir\n\n def createBaseType(self, inputData):\n \"\"\"\n Used to take a tick (e.g., row from CSV) and create a base type \n such as a stock or option (call or put).\n \"\"\"\n if self.__dataProvider == \"iVolatility\":\n # CSV header\n # symbol, exchange, company_name, date, stock_price_close, option_symbol, expiration_date, strike,\n # call_put, style, ask, bid, mean_price, settlement, iv, volume, open_interest, stock_price_for_iv,\n # isinterpolated, delta, vega, gamma, theta, rho\n\n # Do type checking on fields.\n underlyingTicker = inputData['symbol']\n exchange = inputData['exchange']\n optionSymbol = inputData['option_symbol']\n\n # Check if style is American or European.\n style = inputData['style']\n if style != 'A' and style != 'E':\n return None\n\n # Check that underlyingTicker is a character string.\n if not underlyingTicker.isalpha():\n return None\n\n # Check that fields below are floating point numbers.\n try:\n strikePrice = float(inputData['strike'])\n underlyingPrice = float(inputData['stock_price_close'])\n underlyingTradePrice = underlyingPrice\n askPrice = float(inputData['ask'])\n bidPrice = float(inputData['bid'])\n tradePrice = (askPrice + bidPrice) / 2\n impliedVol = float(inputData['iv'])\n volume = float(inputData['volume'])\n openInterest = int(inputData['open_interest'])\n delta = float(inputData['delta'])\n theta = float(inputData['theta'])\n vega = float(inputData['vega'])\n gamma = float(inputData['gamma'])\n rho = float(inputData['rho'])\n\n except:\n return None\n\n # Convert current date and expiration date to a datetime object.\n try:\n local = pytz.timezone('US/Eastern')\n # Convert time zone of data 'US/Eastern' to UTC time.\n # Try and except here to handle two or four digit year format.\n try:\n DTE = datetime.datetime.strptime(inputData['option_expiration'], \"%m/%d/%y\")\n except:\n DTE = datetime.datetime.strptime(inputData['option_expiration'], \"%m/%d/%Y\")\n\n DTE = local.localize(DTE, is_dst=None)\n DTE = DTE.astimezone(pytz.utc)\n\n try:\n curDateTime = datetime.datetime.strptime(inputData['date'], \"%m/%d/%y\")\n except:\n curDateTime = datetime.datetime.strptime(inputData['date'], \"%m/%d/%Y\")\n\n curDateTime = local.localize(curDateTime, is_dst=None)\n curDateTime = curDateTime.astimezone(pytz.utc)\n except:\n logging.warning('Something went wrong when trying to read the option data from the CSV.')\n return None\n\n call_put = inputData['call/put']\n\n if call_put == 'C':\n return call.Call(underlyingTicker, strikePrice, delta, DTE, None, underlyingPrice, underlyingTradePrice,\n optionSymbol, None, bidPrice, askPrice, tradePrice, openInterest, volume, curDateTime,\n theta, gamma, rho, vega, impliedVol, exchange)\n\n elif call_put == 'P':\n return put.Put(underlyingTicker, strikePrice, delta, DTE, None, underlyingPrice, underlyingTradePrice,\n optionSymbol, None, bidPrice, askPrice, tradePrice, openInterest, volume, curDateTime,\n theta, gamma, rho, vega, impliedVol, exchange)\n\n else:\n return None\n\n else:\n print(\"Unrecognized CSV data source provider\")\n sys.exit(1)\n\n","sub_path":"dataHandler/csvData.py","file_name":"csvData.py","file_ext":"py","file_size_in_byte":10792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"242377017","text":"\"\"\"Responds all messages in threads\"\"\"\n\nfrom pprint import pprint\n\nfrom .handlers import handle_message\n\n\ndef respond_messages(entries):\n for entry in entries:\n for message in entry.get('messaging'):\n if 'message' in message:\n webhook_event = entry.get('messaging')[0]\n handle_message(webhook_event)\n pprint(webhook_event)\n","sub_path":"chatbot/services/responders.py","file_name":"responders.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"274439985","text":"# Copyright 2021, joshiayus Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of joshiayus Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Authentication Cookie-Repository Management Package.\"\"\"\n\nimport os\nimport time\nimport pickle\nimport pathlib\n\nfrom requests import cookies\n\nfrom api import settings, exceptions as linkedin_api_exceptions\n\n\nclass CookieRepository(object):\n \"\"\"Creates a 'Cookie Repository' in the given directory.\"\"\"\n\n def __init__(self, username: str, cookies_: cookies.RequestsCookieJar,\n cookie_dir: str) -> None:\n self.cookies = cookies_\n self.username = username\n\n if cookie_dir is None:\n cookie_dir = settings.INB_COOKIE_DIR\n self.cookie_dir = pathlib.Path(cookie_dir)\n\n def get_cookie_dir(self) -> str:\n \"\"\"Returns a 'fs' compatible path of the cookie directory.\"\"\"\n return os.fspath(self.cookie_dir)\n\n def _get_cookies_jar_file_path(self) -> pathlib.Path:\n \"\"\"Returns the cookies jar file path that is generated after combining the\n given cookie directory with the label 'username'.\n\n Returns:\n Cookies jar file path.\n \"\"\"\n return self.cookie_dir / self.username\n\n def save(self) -> None:\n \"\"\"Saves the constructor initialized cookies in the constructor initialized\n cookies directory path.\n \"\"\"\n if not os.path.exists(os.fspath(self.cookie_dir)):\n os.makedirs(os.fspath(self.cookie_dir))\n\n # Every user has a Cookie Repository in the 'cookies directory' with a file\n # name equal to their 'username'.\n cookie_jar_file_path = self._get_cookies_jar_file_path()\n with open(cookie_jar_file_path, 'wb') as jar_file:\n pickle.dump(self.cookies, jar_file)\n\n def get_cookies(self) -> cookies.RequestsCookieJar:\n \"\"\"Returns the 'RequestCookieJar' instance of the cookies saved in the\n cookies directory for the instantiated username.\n\n Returns:\n 'cookies.RequestsCookieJar' instance of user cookies.\n \"\"\"\n # Every user has a Cookie Repository in the 'cookies directory' with a file\n # name equal to their 'username'.\n cookie_jar_file_path = self._get_cookies_jar_file_path()\n if not os.path.exists(cookie_jar_file_path):\n return None\n\n cookies_ = None\n with open(cookie_jar_file_path, 'rb') as jar_file:\n cookies_ = pickle.load(jar_file)\n\n # We still need to check if the cookies have expired.\n for cookie in cookies_:\n if cookie.name == 'JSESSIONID' and cookie.value:\n if cookie.expires and cookie.expires > time.time():\n raise linkedin_api_exceptions.LinkedInSessionExpiredException()\n break\n return cookies_\n","sub_path":"inb/api/cookierepo.py","file_name":"cookierepo.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"315589223","text":"import random\nimport sys\nexp=0\nexplvlup=10\nname=input(\"Please enter your name\")\nnamehp=10\nnamestr=5\nnamelevel=1\nmonsterlist=[\"Uler Kadut\",\"Arden Pejuang Bangsa\",\"uler uleran\",\"Sexy Boiz\",\"Magnificient Fashion BOIZ\", \"Tante Vero\"]\nmonsterlvl=random.randint(1,6)\nmonsterhp=7+monsterlvl\nmonsterstr=7+monsterlvl\nb=random.choice(monsterlist)\nc=monsterlvl\ndef Mainmenu ():\n while(True):\n global name\n j = input(\"welcome \"+ name +\", do you want to fight or see your stats or quit?\")\n if (j == \"stats\"):\n menustat()\n if (j == \"fight\"):\n battle()\n if (j ==\"quit\"):\n break\n\ndef menustat ():\n print(\"Fighter:\",name)\n print(\"Level:\",namelevel)\n print(\"HP:\",namehp)\n print(\"STR\",namestr)\n print(\"EXP\",exp,\"/\",explvlup)\n Mainmenu()\ndef battle ():\n global b\n global c\n global monsterlist\n global monsterlvl\n monsterhp = 7 + monsterlvl\n monsterlvl = random.randint(1, 6)\n b=(random.choice(monsterlist))\n c= monsterlvl\n print(\"Enemy:\",b)\n print(\"Level:\",c)\n print(input(\"press enter to battle\"))\n if namehp>=monsterhp:\n print(\"you survive\")\n afterbattle()\n if namehp=explvlup:\n namehp=namehp+1\n namestr=namestr+1\n namelevel=namelevel+1\n print(\"you have leveled up\")\n print(\"Fighter:\",name)\n print(\"Level:\",namelevel)\n print(\"HP:\",namehp)\n print(\"STR:\",namestr)\n print(input(\"press enter to go back\"))\n Mainmenu()\n else:\n Mainmenu()\n return namehp,namestr,namelevel,\nMainmenu()\n\n\n\n\n\n\n\n\n\n","sub_path":"Gladiator.py","file_name":"Gladiator.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"155093175","text":"class Person:\n __name = \"Nama\"\n\n # python has access modifiers public, protected and private.\n # single '_'before variable name shows it's protected\n # double '__'before variable name shows it's private. if doesn't\n # have ani '_' symbols it is public.\n # have ani '_' symbols it is public.\n\n def __init__(self, name):\n self.__name = name\n # 'self' keyword is works like 'this' keyword in java\n print(\"Person name is : \", name)\n\n def ageofperson(self, age):\n if age < 0:\n print('Age can\"t be negative')\n return\n\n\nif __name__ == \"__main__\":\n p1 = Person(\"Pavan\")\n p1.ageofperson(-40)\n print(p1.ageofperson)\n","sub_path":"Ex_Files_Adv_Python/Exercise Files/01 Language/codingstyle_start.py","file_name":"codingstyle_start.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"91609785","text":"import unittest\r\n\r\ndef name_city(city, country, population=''):\r\n\t\"\"\"format name of city and country\"\"\"\r\n\tif population:\r\n\t\tlocation = f\"{city}, {country}: {population}\"\r\n\telse:\r\n\t\tlocation = f\"{city}, {country}\"\r\n\treturn location.title()\r\n\r\n\r\n\r\n\r\n\r\nclass CityCountryTest(unittest.TestCase):\r\n\r\n\tdef test_city_country(self):\r\n\t\tplace = name_city('calgary','canada')\r\n\t\tself.assertEqual(place, 'Calgary, Canada')\r\n\r\n\tdef test_city_country_pop(self):\r\n\t\tplace = name_city('calgary', 'canada', 1000)\r\n\t\tself.assertEqual(place, \"Calgary, Canada: 1000\")\r\nif __name__ == '__main__':\r\n\tunittest.main()\r\n","sub_path":"city_functions.py","file_name":"city_functions.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"115366423","text":"#!/usr/bin/env python\n\"\"\"\nAuthor: Matthew Bluteau \nVersion: 1.0\nDescription: An interacive command line program that speeds up the process of\n writing guitar tabs. The user enters chords/fingering count by count with\n the final result being written to a text file.\n\"\"\"\n\nimport argparse\nimport tab\nimport os\n\n\ndef main():\n\n print(\"Welcome to PyTablature, an interactive command line program that \"\n \"accelerates the tab writing process. Type -h or --help for \"\n \"details of how to run the program.\")\n\n allowed = ['-', 'h', 'p', 'x'] + [str(x) for x in range(25)]\n\n # define the argument parser object\n parser = argparse.ArgumentParser(prog='PyTablature',\n description='description of PyTablature')\n\n # TODO add an argument that can take in single letter chord names\n parser.add_argument('-c', '--chord', nargs=6, choices=allowed, help='The'\n ' chord/fingering for the current count. If'\n ' present, there must be 6 positional arguments'\n '--one for each string. Input order runs from high '\n 'e to low E.')\n parser.add_argument('-q', nargs='*', type=str,\n help='Save tab then quit PyTablature. Name of file'\n ' can be set as optional argument.')\n parser.add_argument('-d', action='store_true', help='Flag'\n ' to quit PyTablature without saving progress.')\n parser.add_argument('-p', action='store_true', help='Flag'\n ' to print the entirety of the current tab.')\n parser.add_argument('-b', nargs='?', const=1, type=int, help='The'\n ' number of counts to go back in the tab '\n '(the default is 1 if the flag is present).')\n parser.add_argument('-f', nargs='?', const=1, type=int, help='The'\n ' number of counts to go forward in the tab '\n '(the default is 1 if the flag is present).')\n parser.add_argument('-o', '--outfile', nargs='+', type=str,\n default=None, help='The file for the tab'\n ' to be written to.')\n parser.add_argument('-t', '--title', nargs='+', type=str,\n default=None, help='The title of the tab to be'\n ' stored in the output file.')\n parser.add_argument('-a', '--author', nargs='+', type=str,\n default=None, help='The name of the tab author to be'\n ' stored in the output file.')\n parser.add_argument('-D', '--date', nargs=1, type=str,\n default=None, help='The date associated with the tab '\n ' that will be stored in the output file. ISO format. '\n 'Today\\'s date will be used for tab if not set.')\n parser.add_argument('-s', '--save', nargs='*', type=str,\n help='Save the tab to file. Name of file'\n ' can be set as optional argument.')\n parser.add_argument('-l', '--load', nargs='+', type=str,\n default=None, help='Load a tab from the filename '\n 'argument. Any tab metadata (author, etc) from the '\n 'current PyTablature session will not be overwritten.')\n parser.add_argument('-L', '--loadall', nargs='+', type=str,\n default=None, help='Load a tab and all metadata from '\n 'the filename argument. Any tab metadata (author, etc)'\n ' from the current PyTablature session will be overwritten.')\n\n # Initialize the tab object and any other relevant variables (although\n # these should be soon implemented in the tab class itself) before entering\n # main program loop\n user_tab = tab.Tab()\n\n while True:\n\n inp = input('[tab]: ')\n\n try:\n args = parser.parse_args(inp.split())\n except:\n continue\n\n # Quit without saving\n if args.d:\n break\n\n # Set the file name\n if args.outfile:\n user_tab.set_info(filename=' '.join(args.outfile))\n\n # Set the author name\n if args.author:\n user_tab.set_info(author=' '.join(args.author))\n\n # Set the date\n if args.date:\n user_tab.set_info(date=args.date[0])\n\n # Set the title\n if args.title:\n user_tab.set_info(title=' '.join(args.title))\n\n # Save and quit\n if args.q is not None:\n if len(args.q) == 0:\n user_tab.save_tab()\n break\n else:\n user_tab.save_tab(filename=' '.join(args.q))\n break\n\n # Save file and set filename if given\n if args.save is not None:\n if len(args.save) == 0:\n user_tab.save_tab()\n else:\n user_tab.save_tab(filename=' '.join(args.save))\n \n # Print the entirety of the tab\n if args.p:\n pipe = os.popen('less', mode='w')\n print(user_tab, file=pipe)\n pipe.close()\n \n # Move current position backwards in tab\n if args.b:\n try:\n user_tab.backward(args.b)\n except (TypeError, IndexError) as inst:\n print(inst)\n continue\n user_tab.print()\n\n # Move current position forwards in tab\n if args.f:\n try:\n user_tab.forward(args.f)\n except TypeError as inst:\n print(inst)\n continue\n user_tab.print()\n\n # Write a chord to the current position\n if args.chord:\n try:\n user_tab.write(args.chord)\n except TypeError as inst:\n print(inst)\n continue\n user_tab.print()\n\n # Load the tab but don't overwrite metadata\n if args.load:\n user_tab.get_tab(' '.join(args.load), overwrite_info=False)\n\n # Load the tab and overwrite metadata\n if args.loadall:\n user_tab.get_tab(' '.join(args.loadall))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pytablature/pytablature.py","file_name":"pytablature.py","file_ext":"py","file_size_in_byte":6319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"519753733","text":"import time\n\ndef shuffle (arr, n):\n for i in range(n-1,0,-1):\n j= int(0 + int(round(time.time()*1000)) % (i - 0))\n arr[i],arr[j] = arr[j],arr[i]\n num=\"\"\n k=0\n l=10\n while l > 1:\n num=str(arr[k])+num\n k+=1\n l-=1\n return num\n\narr=[0,1,2,3,4,5,6,7,8,9]\n\ndef random_number(min, max):\n num = int(shuffle(arr, 10))\n return int(min + num % (max - min))\n\nmin = int(input(\"First Number: \"))\nmax = int(input(\"Second Number: \"))\ncount = int(input(\"How many random numbers you want? \"))\nrandom_num_list = []\nwhile count > 0:\n rand = random_number(min, max)\n random_num_list.append(rand)\n count -= 1\n\nprint(random_num_list)\n","sub_path":"random_numbers.py","file_name":"random_numbers.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"620329309","text":"\n\nimport sys\n\nif len(sys.argv) < 2:\n msg = '\\n'\n msg += \"Usage 1: %s $INPUT_TRAINING_FILE(s)\\n\" % sys.argv[0]\n msg += '\\n'\n sys.stderr.write(msg)\n sys.exit(1)\n\nfrom larlite import larlite as fmwk\nfrom ROOT import *\n\n# Create ana_processor instance\n# my_proc = fmwk.ana_processor()\n\n# # Set input root file\n# for x in xrange(len(sys.argv)-1):\n# my_proc.add_input_file(sys.argv[x+1])\n\n# Specify IO mode\n# my_proc.set_io_mode(fmwk.storage_manager.kREAD)\n\n# Specify output root file name\n# my_proc.set_ana_output_file(\"from_test_ana_you_can_remove_me.root\");\n\n# Attach an analysis unit ... here we use a base class which does nothing.\n# Replace with your analysis unit if you wish.\n\n# Configure the process:\nproc = cluster.TrainingModule()\n# proc.setUseCascade(True)\n# proc.addLayer(8)\n# proc.addLayer(8)\n\nproc.addLayer(7)\n\n\nproc.setFeatureVectorLength(7)\nproc.setOutputVectorLength(2)\nproc.setOutputFileName(\"trackShowerAnn.dat\")\n\nproc.init(sys.argv[-1])\n\nproc.train()\nproc.saveFANNToFile()\n\n\n# my_proc.add_process(proc)\n\n\n# print\n# print \"Finished configuring ana_processor. Start event loop!\"\n# print\n\n# Let's run it.\n# my_proc.run(0);\n\n# # done!\n# print\n# print \"Finished running ana_processor event loop!\"\n# print\n\nsys.exit(0)\n","sub_path":"utils/fann_training/train_fann.py","file_name":"train_fann.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"113097928","text":"import pygame\r\nSCREEN_SIZE = 16*32\r\npygame.init()\r\nRED = [0, 255, 0]\r\ngameDisplay = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE))\r\ngraphics = pygame.image.load(\"objects.png\")\r\nTILESIZE = 32\r\n\r\n\r\nclass Town_center:\r\n def __init__(self):\r\n self.HP = 100\r\n self.x = 0\r\n self.y = 0\r\n self.clicked = False\r\n self.spawned = 0\r\n def select(self):\r\n if click[0] == 1:\r\n if self.x < mouse_position[0] < self.x + 2*TILESIZE and self.y < mouse_position[1] < self.y + 2*TILESIZE:\r\n pygame.time.delay(100)\r\n self.clicked = True\r\n\r\n def spawn_vill(self):\r\n gameDisplay.blit(graphics, (self.x - 32, self.y + 32), dic[\"VILL\"])\r\n\r\n\r\nclass Villager:\r\n def __init__(self):\r\n self.HP = 10\r\n self.x = 0\r\n self.y = 0\r\n self.shift = 0\r\n self.hasAnimationEnded = True\r\n self.finalx = -1\r\n self.finaly = -1\r\n\r\n def move(self):\r\n if click[0] == 1:\r\n self.shift = 1\r\n if self.finaly > self.y:\r\n self.y += self.shift\r\n gameDisplay.blit(graphics, (self.x, self.y), dic[\"VILL\"])\r\n if self.finaly < self.y:\r\n self.y -= self.shift\r\n gameDisplay.blit(graphics, (self.x, self.y), dic[\"VILL\"])\r\n if self.finalx > self.x:\r\n self.finalx += self.shift\r\n gameDisplay.blit(graphics, (self.x, self.y), dic[\"VILL\"])\r\n if self.x > self.finalx:\r\n self.finalx -= self.shift\r\n gameDisplay.blit(graphics, (self.x, self.y), dic[\"VILL\"])\r\n if self.x == self.finalx and self.y == self.finaly:\r\n self.hasAnimationEnded = True\r\n\r\n def select(self):\r\n if click[0] == 1:\r\n if self.x < mouse_position[0] < self.x + TILESIZE and self.y < mouse_position[1] < self.y + TILESIZE:\r\n pygame.time.delay(100)\r\n\r\n\r\ntilemap = [[\"G\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"G\", \"G\", \"G\", \"T\", \"T\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"G\", \"G\", \"G\", \"G\", \"T\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"T\", \"G\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"T\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"T\", \"T\", \"T\", \"T\", \"T\", \"T\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"SPAWN\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"G\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"TC\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"T\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"T\", \"T\", \"T\", \"T\", \"T\", \"T\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"G\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"T\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"T\", \"T\", \"T\", \"T\", \"T\", \"T\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"G\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"T\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"T\", \"T\", \"T\", \"T\", \"T\", \"T\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"],\r\n [\"G\", \"T\", \"G\", \"T\", \"T\", \"G\", \"G\", \"T\", \"T\", \"T\", \"G\", \"G\", \"G\", \"T\", \"T\", \"T\"]]\r\n\r\ndic = {\"G\": (0, 13*32, 32, 32), \"T\": (8 * 32, 10*32, 32, 32), \"TC\": (9 * 32, 14 * 32, 32, 32),\r\n \"SPAWN\": (0, 14*32, 32, 32), \"VILL\": (0, 0, 32, 32)}\r\ntc = Town_center()\r\nvill = Villager()\r\nfor i in range(16):\r\n for j in range(16):\r\n if tilemap[i][j] == \"TC\":\r\n tc.x = i * 32\r\n tc.y = j * 32\r\n\r\n if tilemap[i][j] == \"VILL\":\r\n vill.x = i * 32\r\n vill.y = j * 32\r\nwhile True:\r\n for i in range(16):\r\n for j in range(16):\r\n gameDisplay.blit(graphics, (i*32, j*32), dic[\"G\"])\r\n gameDisplay.blit(graphics, (i*32, j*32), dic[tilemap[i][j]])\r\n mouse_position = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n # print(tc.x, tc.y, vill.x, vill.y, mouse_position[0], mouse_position[1])\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_ESCAPE:\r\n exit()\r\n tc.select()\r\n vill.select()\r\n if tc.clicked:\r\n vill.x = tc.x - 32\r\n vill.y = tc.y\r\n tc.spawn_vill()\r\n if not vill.select():\r\n vill.finalx = mouse_position[0]\r\n vill.finaly = mouse_position[1]\r\n vill.hasAnimationEnded = False\r\n while(not vill.hasAnimationEnded):\r\n vill.move()\r\n pygame.display.update()\r\n pygame.time.delay(100)\r\n\r\n\r\n pygame.display.update()\r\n clock = pygame.time.Clock()\r\n clock.tick(60)\r\n","sub_path":"rts.py","file_name":"rts.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"544429097","text":"from time import time\r\n\r\nfrom ui.widgets.text import TextWidget\r\n\r\n\r\nclass TimeWidget(TextWidget):\r\n def __init__(self, ctx, mod, **kwargs):\r\n super().__init__(ctx, mod, **kwargs)\r\n\r\n def gettext(self):\r\n ts = int(time() + 3 * 3600)\r\n minutes = (ts // 60) % 60\r\n hours = (ts // 3600) % 24\r\n return \"{:0>2}{}{:0>2}\".format(hours, \":\" if int(time()) % 2 else \" \", minutes)\r\n","sub_path":"ui/widgets/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"253598746","text":"class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n points = sorted(points, key=lambda x: x[0])\n arrows = 0\n cur_min = points[0][0]\n cur_max = points[0][1]\n for i in points:\n if i[0] > cur_max:\n cur_min = i[0]\n cur_max = i[1]\n arrows += 1\n else:\n cur_min = max(i[0], cur_min)\n cur_max = min(i[1], cur_max)\n arrows += 1\n return arrows","sub_path":"Greedy/minimumNumberOfArrowsToBurstBalloons.py","file_name":"minimumNumberOfArrowsToBurstBalloons.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"321495272","text":"# -*- coding: utf-8 -*-\n\"\"\"\nWritten by Daniel M. Aukes.\nEmail: danaukesseas.harvard.edu.\nPlease see LICENSE.txt for full license.\n\"\"\"\n\nfrom popupcad.filetypes.popupcad_file import popupCADFile\n\n\nclass ProgramSettings(popupCADFile):\n filetypes = {'popupcad': 'CAD Design'}\n defaultfiletype = 'popupcad'\n\n# display = ['*']\n editable = ['*']\n hidden = [\n 'filetypes',\n 'filters',\n 'filterstring',\n 'defaultfiletype',\n 'selectedfilter',\n 'id']\n# display = ['inkscape_path','pstoedit_path','nominal_width','nominal_height']\n# editable = ['inkscape_path','pstoedit_path','nominal_width','nominal_height']\n\n def __init__(self):\n super(ProgramSettings, self).__init__()\n\n self.inkscape_path = 'C:\\Program Files (x86)\\Inkscape\\inkscape.exe'\n self.pstoedit_path = 'C:\\Program Files\\pstoedit\\pstoedit.exe'\n self.toolbar_icon_size = 36\n self.id = id(self)\n self.nominal_width = 1280\n self.nominal_height = 720\n# self.deprecated_mode = False\n\n def copy(self, identical=True):\n new = type(self)()\n new.inkscape_path = self.inkscape_path\n new.pstoedit_path = self.pstoedit_path\n new.toolbar_icon_size = self.toolbar_icon_size\n new.nominal_width = self.nominal_width\n new.nominal_height = self.nominal_height\n# new.deprecated_mode=self.deprecated_mode\n if identical:\n new.id = self.id\n return new\n","sub_path":"popupcad/filetypes/programsettings.py","file_name":"programsettings.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"527137258","text":"\nTABLE = 'USStockPrice'\nimport pandas as pd\nimport os, sys\nimport platform\nif 'Windows' in platform.platform():\n PATH = \"\\\\\".join( os.path.abspath(__file__).split('\\\\')[:-1])\nelse:\n PATH = \"/\".join( os.path.abspath(__file__).split('/')[:-1])\nsys.path.append(PATH)\nfrom BasedClass import Load,execute_sql2\n\n\nclass ClassUSStockPrice(Load):\n def __init__(self):\n super(ClassUSStockPrice, self).__init__(TABLE,'stock_id')\n \n def load(self,select = '',date = ''):\n \n colname = execute_sql2( 'SHOW COLUMNS FROM `{}`'.format( select ),database = TABLE )\n colname = [ c[0] for c in colname if c[0] not in ['id','url'] ] \n \n sql = 'select `{}` from `{}`'.format( '`,`'.join( colname ) ,select)\n \n if date != '':\n sql = \"{} WHERE `date` >= '{}' \".format(sql,date)\n \n data = execute_sql2( sql ,database = TABLE)\n data = pd.DataFrame(list(data))\n if len(data)>0:\n \n data.columns = colname\n \n if self.select_variable in data.columns:\n data = data.sort_values([self.select_variable,'date'])\n else:\n data = data.sort_values('date')\n data.index = range(len(data))\n data['stock_id'] = select\n \n return data\n \n def get_data_list(self):\n tem = execute_sql2( 'SHOW TABLES',database = TABLE )\n return [ te[0] for te in tem ]\n \ndef USStockPrice(select = [],date = ''):\n \n self = ClassUSStockPrice() \n #stock = select\n if isinstance(select,int): select = str(select)\n \n if isinstance(select,str):\n return self.load(select,date)\n \n elif isinstance(select,list):\n return self.load_multi(select,date)\n \n else:\n raise(AttributeError, \"Hidden attribute\") \n","sub_path":"Data/USStockPrice.py","file_name":"USStockPrice.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"257059645","text":"import datetime\nimport requests\nimport json\nfrom bs4 import BeautifulSoup\n\nnow = datetime.datetime.now()\ndate = now.strftime(\"%d-%m-%Y\")\nurl = 'https://rozetked.me/news'\npath = \"articles.json\"\ndata = {\n\n \"url\": url,\n \"creationDate\": date,\n \"articles\": [\"None\"]\n}\n\n\n\ndef get_html_page(url):\n rozetked = requests.get(url)\n rozetked_html = rozetked.text\n return (rozetked_html)\n\n\ndef find_articles(rozetked_html):\n titles = []\n rozetked_parsed = BeautifulSoup(rozetked_html,'html.parser')\n rozedked_article = rozetked_parsed.find_all(class_='post_new-title')\n for title in rozedked_article:\n titles.append(title.text.strip())\n return (titles)\n\n\ndef publish_report(path, articles):\n c = []\n for i in articles:\n d = {\"title\": i,\n \"seconds\": now.strftime(\"%S\")}\n c.append(d)\n data[\"articles\"] = c\n with open(path, \"w\",encoding=\"utf-8\") as write_file:\n json.dump(data, write_file,indent = 2, ensure_ascii=False)\n return (data)\n\n\nrozetked_html = get_html_page(url)\narticles = find_articles(rozetked_html)\npublish_report(path,articles)\n\n\n\n\n\n\n\n","sub_path":"Lab_1.py","file_name":"Lab_1.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"208251068","text":"# Time: O((m + n) * 3^m) = O(n * 3^m)\n# Space: O(3^m)\n\nimport collections\n\n\n# worse complexity, but faster due to too small m\nclass Solution(object):\n def colorTheGrid(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n def backtracking(mask1, mask2, basis, result): # Time: O(2^m), Space: O(2^m)\n if not basis:\n result.append(mask2)\n return\n for i in xrange(3):\n if (mask1 == -1 or mask1//basis%3 != i) and (mask2 == -1 or mask2//(basis*3)%3 != i):\n backtracking(mask1, mask2+i*basis if mask2 != -1 else i*basis, basis//3, result)\n \n if m > n:\n m, n = n, m\n basis = 3**(m-1)\n masks = []\n backtracking(-1, -1, basis, masks) # Time: O(2^m), Space: O(2^m)\n adj = collections.defaultdict(list)\n for mask in masks: # O(3^m) leaves in depth O(m) => Time: O(m * 3^m), Space: O(3^m)\n backtracking(mask, -1, basis, adj[mask])\n # 'o' uses the same color with its bottom-left one, \n # 'x' uses the remaining color different from its left one and bottom-left one,\n # k is the cnt of 'o', \n # [2, 1(o), 1(x), 1(o), ..., 1(o), 1(x)] => nCr(m-1, k) * 3 * 2 * 2^k for k in xrange(m) = 3 * 2 * (2+1)^(m-1) = 2*3^m combinations\n # [3, 2, 1, 2, ..., 2, 1]\n assert(sum(len(v) for v in adj.itervalues()) == 2*3**m)\n dp = collections.Counter(masks)\n for _ in xrange(n-1): # Time: O(n * 3^m), Space: O(2^m)\n assert(len(dp) == 3*2**(m-1))\n new_dp = collections.Counter()\n for mask, v in dp.iteritems():\n for new_mask in adj[mask]:\n new_dp[new_mask] = (new_dp[new_mask] + v) % MOD\n dp = new_dp\n return reduce(lambda x,y: (x+y)%MOD, dp.itervalues(), 0) # Time: O(2^m)\n\n\n# Time: (m * n grids) * (O(3*3*2^(m-2)) possible states per grid) = O(n * m * 2^m)\n# Space: O(3*3*2^(m-2)) = O(2^m)\nimport collections\n\n\n# better complexity, but slower due to too small m\nclass Solution2(object):\n def colorTheGrid(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n MOD = 10**9+7\n if m > n:\n m, n = n, m\n basis = 3**(m-1)\n dp = collections.Counter({3**m-1: 1})\n for idx in xrange(m*n):\n r, c = divmod(idx, m)\n # sliding window with size m doesn't cross rows:\n # [3, 2, ..., 2] => 3*2^(m-1) combinations\n assert(r != 0 or c != 0 or len(dp) == 1)\n assert(r != 0 or c == 0 or len(dp) == 3*2**(c-1))\n assert(r == 0 or c != 0 or len(dp) == 3*2**(m-1))\n # sliding window with size m crosses rows:\n # [*, ..., *, *, 3, 2, ..., 2] => 3*3 * 2^(m-2) combinations\n # [2, ..., 2, 3, *, *, ..., *]\n assert(r == 0 or c == 0 or len(dp) == 3**2 * 2**(m-2))\n new_dp = collections.Counter()\n for mask, v in dp.iteritems():\n choices = {0, 1, 2}\n if r > 0:\n choices.discard(mask%3) # get up grid\n if c > 0:\n choices.discard(mask//basis) # get left grid\n for x in choices:\n new_mask = (x*basis)+(mask//3) # encoding mask\n new_dp[new_mask] = (new_dp[new_mask]+v)%MOD \n dp = new_dp\n return reduce(lambda x,y: (x+y)%MOD, dp.itervalues(), 0) # Time: O(2^m)\n","sub_path":"Python/painting-a-grid-with-three-different-colors.py","file_name":"painting-a-grid-with-three-different-colors.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"568109957","text":"__author__ = 'koohyh'\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef app():\n msg_str = \"\"\"\n ******** NOTE ***********\n This code is to investigate V gene usage per J. We have had 4 J genes (J1, 2, 4 and 5) for three FrD Young replciates.\n These 12 files have been imported to seqmonk. The probes have been made on IgK V genes.\n Feature generator using IgK_genes.bed duplicates removed Over feature from 200-0.\n Quantitated with Read Count Quantitation using All Reads duplicates ignored\n **************************\n \"\"\"\n print(msg_str)\n\n v_genes_coverage_fname = '/bi/group/sysgen/Hashem/VDJ_Analysis/VDJ_IgK/VDJ_IgK_2017/V_Coverage_over_all_Reps_and_Js.txt'\n get_V_genes_coverage(v_genes_coverage_fname)\n\ndef get_V_genes_coverage(vgenes_fname):\n names = ['Probe', 'FrD_YR1_J1', 'FrD_YR1_J2', 'FrD_YR1_J4', 'FrD_YR1_J5',\n 'FrD_YR2_J1', 'FrD_YR2_J2', 'FrD_YR2_J4', 'FrD_YR2_J5',\n 'FrD_YR3_J1', 'FrD_YR3_J2', 'FrD_YR3_J4', 'FrD_YR3_J5']\n\n df = pd.read_csv(vgenes_fname, sep='\\t', usecols=names, index_col='Probe')\n df = df +1 # add psudo count 1 to prevent log0\n df = df.apply(np.log, axis=0)\n\n g = sns.clustermap(df, metric=\"euclidean\", figsize=(10,15),\n col_cluster=True)\n plt.setp(g.ax_heatmap.get_yticklabels(), rotation=0) # For y axis\n plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90) # For x axis\n\n plt.show()\n\n\n\nif __name__ == '__main__':\n app()","sub_path":"pyVDJ/V_Coverage_Over_Js.py","file_name":"V_Coverage_Over_Js.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"252696105","text":"import json\nimport logging\nimport os\n\nimport boto3\nimport xmltodict\n\n# import pprint\n\n\nclass ArcticDEMExtractor:\n def __init__(self, uri, log):\n self.uri = uri\n self.log = log\n self.xml_uri = self.uri.lstrip('s3://')\n\n def extract(self):\n self.log.debug(\"Arctic extractor\")\n self.log.info('ArcticDEMExtractor(%s)' % self.uri)\n\n bucket = self.xml_uri.split('/')[0]\n key = self.xml_uri.lstrip(bucket).lstrip('/')\n\n s3client = boto3.client(\n 's3',\n region_name='us-east-1',\n # endpoint_url='http://s3.amazonaws.com',\n config=boto3.session.Config(signature_version='s3v4')\n )\n\n obj = s3client.get_object(\n Bucket=bucket,\n Key=key\n )\n\n data = obj['Body'].read().decode('utf-8')\n res = xmltodict.parse(data, encoding='utf-8')\n return res\n","sub_path":"extractor/GdalExtractor/ArcticDEM.py","file_name":"ArcticDEM.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"186441654","text":"import os\n\n\n# 普通用户\nclass Client:\n def __init__(self, data):\n print(data)\n self.id = data[0] # id\n self.password = data[1] # 密码\n self.level = data[2] # 级别\n self.money = data[3] # 金额\n self.stauts = data[4] # 状态\n\n # 查询 金额\n def chaxun(self):\n print(\"账号'%s',余额为%.2f$\" % (self.id, int(self.money)))\n return self.money\n\n # 取钱\n def qu(self):\n num = int(input(\"输入取走金额(以百为单位,最高5000):\"))\n while num % 100 != 0 or num > int(self.money) or num < 100 or num > 5000:\n num = int(input(\"输入错误,请重试:\"))\n data_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n data_list.append(line)\n with open(\"user_info(副本).txt\", 'w', encoding='utf8') as f1:\n for i in range(len(data_list)):\n detail_list = data_list[i].strip().split(',')\n if detail_list[0] == self.id:\n # 取完后的钱\n self.money = str(int(detail_list[3]) - num)\n detail_list[3] = self.money\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n else:\n info_str = ','.join(detail_list) + '\\n'\n f1.write(info_str)\n os.remove('user_info.txt')\n os.rename('user_info(副本).txt', 'user_info.txt')\n print(\"账号'%s',取走%.2f$,余额为%.2f$\" % (self.id, int(num), int(self.money)))\n return self.money\n # 存钱\n def cun(self):\n num = int(input(\"输入存入金额(以百为单位):\"))\n while num % 100 != 0 or num < 100:\n num = int(input(\"输入错误,请重试:\"))\n data_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n data_list.append(line)\n with open(\"user_info(副本).txt\", 'w', encoding='utf8') as f1:\n for i in range(len(data_list)):\n detail_list = data_list[i].strip().split(',')\n if detail_list[0] == self.id:\n # 存完之后的钱\n self.money = str(int(detail_list[3]) + num)\n detail_list[3] = self.money\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n else:\n info_str = ','.join(detail_list) + '\\n'\n f1.write(info_str)\n os.remove('user_info.txt')\n os.rename('user_info(副本).txt', 'user_info.txt')\n print(\"账号'%s',取走%.2f$,余额为%.2f$\" % (self.id, int(num), int(self.money)))\n return self.money\n\n # 转账\n def zhuan(self):\n id_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n info_list = line.strip().split(',')\n id_list.append(info_list[0])\n print(\"#ID列表\", id_list, )\n id = input(\"输入转账ID:\")\n while id not in id_list or id == self.id:\n id = input(\"ID输入错误,请重试:\")\n if id.lower() == 'q':\n return\n\n num = int(input(\"输入转账金额(以百为单位,最高5000):\"))\n while num % 100 != 0 or num > int(self.money) or num < 100 or num > 5000:\n num = int(input(\"金额输入错误,请重试:\"))\n\n data_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n data_list.append(line)\n\n with open(\"user_info(副本).txt\", 'w', encoding='utf8') as f1:\n for i in range(len(data_list)):\n detail_list = data_list[i].strip().split(',')\n if detail_list[0] == self.id: # 修改自己的 金额\n self.money = str(int(detail_list[3]) - num)\n detail_list[3] = self.money\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n elif detail_list[0] == id: # 增加 接收人的金额\n detail_list[3] = str(int(detail_list[3]) + num)\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n else:\n info_str = ','.join(detail_list) + '\\n'\n f1.write(info_str)\n os.remove('user_info.txt')\n os.rename('user_info(副本).txt', 'user_info.txt')\n print(\"转账成功,剩余余额%.2f\" % int(self.money))\n return self.money\n\n # 修改密码\n def xiugai(self, ):\n old_pwd = input(\"输入旧密码:\")\n while old_pwd != self.password:\n old_pwd = input(\"密码错误,请重试:\")\n\n new_pwd = input(\"输入新密码(q返回):\")\n if new_pwd.lower() == 'q':\n print(\"取消修改密码\")\n return\n\n while len(new_pwd) < 6 or len(set(new_pwd)) == 1:\n new_pwd = input(\"新密码不能小于6位或者6位完全相同,请重试:\")\n\n new_pwd_2 = input(\"确认新密码:\")\n while len(new_pwd_2) < 6 or len(set(new_pwd_2)) == 1:\n print(\"新密码不能小于6位或者6位完全相同,请重试:\")\n if new_pwd == new_pwd_2:\n data_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n data_list.append(line)\n\n with open(\"user_info(副本).txt\", 'w', encoding='utf8') as f1:\n for i in range(len(data_list)):\n detail_list = data_list[i].strip().split(',')\n if detail_list[0] == self.id: # 修改自己密码\n self.password = new_pwd\n detail_list[1] = self.password\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n else:\n info_str = ','.join(detail_list) + '\\n'\n f1.write(info_str)\n os.remove('user_info.txt')\n os.rename('user_info(副本).txt', 'user_info.txt')\n print(\"密码修改成功,新密码为%s\" % self.password)\n return self.password\n\n else:\n print(\"2次密码不一样,请重试\")\n return\n\n# 管理员\nclass Admin:\n def __init__(self):\n self.id = 'a0001'\n self.password = '112233'\n\n # 添加 用户\n def tianjia(self):\n id_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n info_list = line.strip().split(',')\n id_list.append(info_list[0])\n\n new_id = input(\"输入新账号ID:\")\n while new_id in id_list:\n new_id = input(\"ID已存在,请重试:\")\n\n with open(\"user_info.txt\", 'a', encoding='utf8') as f:\n f.write(new_id + ',' + '123456' + ',' + '1' + ',' + '10000' + ',' + '0' + '\\n')\n print(new_id, '添加成功')\n\n # 冻结\n def dongjie(self):\n id_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n info_list = line.strip().split(',')\n id_list.append(info_list[0])\n\n dongjie_id = input(\"输入冻结账号ID:\")\n while dongjie_id not in id_list:\n dongjie_id = input(\"ID不存在,请重试:\")\n\n data_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n data_list.append(line)\n\n with open(\"user_info(副本).txt\", 'w', encoding='utf8') as f1:\n for i in range(len(data_list)):\n detail_list = data_list[i].strip().split(',')\n if detail_list[0] == dongjie_id: # 修改自己密码\n detail_list[-1] = '1'\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n else:\n info_str = ','.join(detail_list) + '\\n'\n f1.write(info_str)\n os.remove('user_info.txt')\n os.rename('user_info(副本).txt', 'user_info.txt')\n print(dongjie_id, '以冻结')\n\n # 解冻\n def jiedong(self):\n id_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n info_list = line.strip().split(',')\n id_list.append(info_list[0])\n\n jiedong_id = input(\"输入解冻账号ID:\")\n while jiedong_id not in id_list:\n jiedong_id = input(\"ID不存在,请重试:\")\n\n data_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n data_list.append(line)\n\n with open(\"user_info(副本).txt\", 'w', encoding='utf8') as f1:\n for i in range(len(data_list)):\n detail_list = data_list[i].strip().split(',')\n if detail_list[0] == jiedong_id: # 修改自己密码\n detail_list[-1] = '0'\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n else:\n info_str = ','.join(detail_list) + '\\n'\n f1.write(info_str)\n os.remove('user_info.txt')\n os.rename('user_info(副本).txt', 'user_info.txt')\n print(jiedong_id, '已解冻')\n\n # 查询用户信息\n def chaxun(self):\n id_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n info_list = line.strip().split(',')\n id_list.append(info_list[0])\n print('ID列表', id_list)\n chaxun_id = input(\"查询ID:\")\n\n while chaxun_id not in id_list:\n print('ID列表', id_list)\n chaxun_id = input(\"ID不存在,请重试:\")\n\n l = ['账号', '密码', '级别(0管理员,1普通)', '金额', '状态(0正常,1冻结)']\n\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n info_list = line.strip().split(',')\n if chaxun_id == info_list[0]:\n for i in range(len(info_list)):\n print(l[i], \">>>\", info_list[i])\n return\n else:\n print(\"ID不存在,请重试:\")\n\n\n# ATM 系统\nclass ATM:\n\n def __init__(self):\n with open(\"user_info.txt\", 'w', encoding='utf8') as f:\n f.write(\"a0001,112233,0,10000,0\" + '\\n') # 管理员\n f.write(\"p0001,123456,0,10000,0\" + '\\n') # 普通账号1\n f.write(\"p0002,123456,0,10000,0\" + '\\n') # 普通账号2\n\n # 密码错三次冻结\n def dongjie(self, ID):\n data_list = []\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n for line in f:\n data_list.append(line)\n\n with open(\"user_info(副本).txt\", 'w', encoding='utf8') as f1:\n for i in range(len(data_list)):\n detail_list = data_list[i].strip().split(',')\n if detail_list[0] == ID: # 修改自己密码\n detail_list[-1] = '1'\n info_str = ','.join(detail_list) + \"\\n\"\n f1.write(info_str)\n else:\n info_str = ','.join(detail_list) + '\\n'\n f1.write(info_str)\n os.remove('user_info.txt')\n os.rename('user_info(副本).txt', 'user_info.txt')\n\n # z主程序运行\n def run(self):\n ID = input(\"请输入卡号:\")\n password = input(\"请输入密码:\")\n client = None\n admin = None\n\n # 管理员登录\n if ID == 'a0001':\n while password != '112233':\n password = input(\"密码错误,联系管理员(q退出系统):\")\n if password.lower() == 'q':\n print('退出系统...')\n return\n print(\"管理员登录成功\")\n admin = Admin()\n\n if admin != None:\n task = {'1': admin.tianjia, '2': admin.dongjie, '3': admin.jiedong, '4': admin.chaxun}\n menu = {'1': \"添加账号\", '2': \"冻结账号\", '3': \"解冻\", '4': \"查询信息\", '5': '退出系统'}\n\n while 1:\n for k, v in menu.items():\n print(k, v)\n\n choice = input(\"请输入你要执行的任务序号:\")\n if choice == '5':\n print('退出系统...')\n return\n try:\n task[choice]()\n except Exception as e:\n print(\"出错,请重试....\")\n print('\\n')\n\n with open(\"user_info.txt\", 'r', encoding='utf8') as f:\n data_list = []\n for line in f:\n data_list.append(line)\n\n for line in data_list:\n num = 1\n\n # 用户信息列表\n data = line.strip().split(\",\")\n if ID == data[0]: # 判断 账号是否存在\n if data[-1] == \"1\":\n print('该账号已冻结,请联系管理员解冻')\n return\n\n # 密码错三次 账号冻结\n while password != data[1] and num < 3:\n num += 1\n password = input(\"密码错误,请重试(第%s次尝试):\" % num)\n\n if ID == data[0] and password == data[1]:\n\n print('\"%s\",登录成功\\n' % ID)\n client = Client(data) # 实例化一个客户类 把用户信息传进去\n break # 跳出 for 循环\n\n else:\n self.dongjie(ID)\n print(\"该账号'%s'已冻结,联系管理员解冻\" % ID)\n break # 跳出 for 循环\n else:\n print(\"账号'%s'不存在,请联系管理员\" % ID)\n\n if client != None:\n task = {'1': client.chaxun, '2': client.qu, '3': client.cun, '4': client.zhuan, '5': client.xiugai}\n menu = {'1': \"查询余额\", '2': \"取款\", '3': \"存款\", '4': \"转账\", '5': \"修改个人密码\", '6': '退出系统'}\n while 1:\n for k, v in menu.items():\n print(k, v)\n\n choice = input(\"请输入你要执行的任务序号(默认为1):\")\n if choice == '6':\n print('退出系统...')\n return\n try:\n task[choice]()\n except Exception as e:\n print(\"出错,请重试...\")\n print('\\n')\n\n\nif __name__ == '__main__':\n ATM().run() # 程序的入口\n","sub_path":"ATM/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"231982793","text":"# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract\n# DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government\n# retains certain rights in this software.\n\nimport argparse\nimport couchdb\nimport logging\nimport sys\nimport time\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--database\", default=\"slycat\", help=\"Specify the database name. Default: %(default)s\")\nparser.add_argument(\"--host\", default=\"localhost\", help=\"CouchDB server. Default: %(default)s\")\nparser.add_argument(\"--port\", default=\"5984\", help=\"CouchDB port. Default: %(default)s\")\nparser.add_argument(\"--admin\", default=\"\", help=\"CouchDB admin user. Default: %(default)s\")\nparser.add_argument(\"--password\", default=\"\", help=\"CouchDB admin password. Default: %(default)s\")\narguments = parser.parse_args()\n\n\nlogFile = 'project-data_CleanupLog.txt'\nlogging.getLogger().setLevel(logging.INFO)\nlogging.getLogger().addHandler(logging.FileHandler(logFile))\nlogging.getLogger().handlers[0].setFormatter(logging.Formatter(\"{} - %(levelname)s - %(message)s\".format(sys.argv[0])))\n\n# assuming CouchDB initialization from local process to local server\ncreds = \"\"\nif arguments.admin != \"\":\n creds = arguments.admin + \":\" + arguments.password + \"@\"\n\nserverURL = \"http://\" + creds + arguments.host + \":\" + arguments.port + \"/\"\n\nwhile True:\n try:\n server = couchdb.Server(serverURL)\n version = server.version()\n break\n except:\n logging.warning(\"Waiting for couchdb.\")\n time.sleep(2)\n\nif arguments.database not in server:\n server.create(arguments.database)\ncouchdb = server[arguments.database]\nlogging.info('Connected to couchdb')\n\n\"\"\"\ncleans out project data that is not being pointed at\nby a parameter space model, and cleans up models that \nare not parameter space but point to project data\n\"\"\"\n\n# get a view list of all pd ids\nfor row in couchdb.view(\"slycat/project_datas\"):\n logging.info('Testing PD: {0}'.format(str(row.id)))\n pd_doc = couchdb.get(type=\"project_data\",id=row.id)\n delete_pd = True\n # go through model list in pd and start cleaning\n for model_id in pd_doc['mid']:\n model_doc = couchdb.get(type=\"model\",id=model_id)\n if model_doc is not None:\n if \"model-type\" in model_doc:\n #log.error(\"testing model type:[%s]\" % str(model_doc[\"model-type\"]))\n if model_doc[\"model-type\"] == \"parameter-image\":\n logging.info('Skipping deletion of parameter-image PD: {0}'.format(str(row.id)))\n delete_pd = False\n # clean up models that don't need pd\n elif \"project_data\" in model_doc:\n logging.info('Deleting non-parameter-image PD: {0}'.format(str(row.id)))\n del model_doc[\"project_data\"]\n couchdb.save(model_doc)\n # clean up models that don't have a type\n elif \"project_data\" in model_doc:\n logging.info('Deleting PD: {0} from model without a model-type'.format(str(row.id)))\n del model_doc[\"project_data\"]\n couchdb.save(model_doc)\n if delete_pd:\n # delete project data that doesn't have an associated model \n logging.info('Deleting PD with NO mid: {0}'.format(str(row.id)))\n couchdb.delete(pd_doc)\n \nlogging.info('Done deleting project datas')\n","sub_path":"web-server/slycat-clean-pd.py","file_name":"slycat-clean-pd.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"287167471","text":"# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-\n# ex: set sts=4 ts=4 sw=4 noet:\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the datalad package for the\n# copyright and license terms.\n#\n# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n\"\"\"Test implementation of class GitRepo\n\n\"\"\"\n\nimport os\nfrom os.path import join as opj, exists, realpath, curdir, pardir\n\nfrom nose.tools import assert_raises, assert_is_instance, assert_true, \\\n eq_, assert_in, assert_false, assert_not_equal\nfrom git.exc import GitCommandError, NoSuchPathError, InvalidGitRepositoryError\n\nfrom ..support.gitrepo import GitRepo, normalize_paths, _normalize_path\nfrom ..support.exceptions import FileNotInRepositoryError\nfrom ..cmd import Runner\nfrom ..utils import getpwd, chpwd\n\nfrom .utils import with_tempfile, with_testrepos, \\\n assert_cwd_unchanged, on_windows, with_tree, \\\n get_most_obscure_supported_name, ok_clean_git\nfrom .utils import swallow_logs\nfrom .utils import local_testrepo_flavors\nfrom .utils import skip_if_no_network\nfrom .utils import assert_re_in\nfrom .utils import ok_\nfrom .utils import SkipTest\nfrom .utils_testrepos import BasicAnnexTestRepo\n\n\n@assert_cwd_unchanged\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\ndef test_GitRepo_instance_from_clone(src, dst):\n\n gr = GitRepo(dst, src)\n assert_is_instance(gr, GitRepo, \"GitRepo was not created.\")\n assert_true(exists(opj(dst, '.git')))\n\n # do it again should raise GitCommandError since git will notice there's already a git-repo at that path\n # and therefore can't clone to `dst`\n with swallow_logs() as logs:\n assert_raises(GitCommandError, GitRepo, dst, src)\n\n\n@assert_cwd_unchanged\n@with_testrepos(flavors=local_testrepo_flavors)\ndef test_GitRepo_instance_from_existing(path):\n\n gr = GitRepo(path)\n assert_is_instance(gr, GitRepo, \"GitRepo was not created.\")\n assert_true(exists(opj(path, '.git')))\n\n\n@assert_cwd_unchanged\n@with_tempfile\n@with_tempfile\ndef test_GitRepo_instance_from_not_existing(path, path2):\n # 1. create=False and path doesn't exist:\n assert_raises(NoSuchPathError, GitRepo, path, create=False)\n assert_false(exists(path))\n\n # 2. create=False, path exists, but no git repo:\n os.mkdir(path)\n assert_true(exists(path))\n assert_raises(InvalidGitRepositoryError, GitRepo, path, create=False)\n assert_false(exists(opj(path, '.git')))\n\n # 3. create=True, path doesn't exist:\n gr = GitRepo(path2, create=True)\n assert_is_instance(gr, GitRepo, \"GitRepo was not created.\")\n assert_true(exists(opj(path2, '.git')))\n ok_clean_git(path2, annex=False)\n\n # 4. create=True, path exists, but no git repo:\n gr = GitRepo(path, create=True)\n assert_is_instance(gr, GitRepo, \"GitRepo was not created.\")\n assert_true(exists(opj(path, '.git')))\n ok_clean_git(path, annex=False)\n\n\n@with_tempfile\n@with_tempfile\ndef test_GitRepo_equals(path1, path2):\n\n repo1 = GitRepo(path1)\n repo2 = GitRepo(path1)\n ok_(repo1 == repo2)\n eq_(repo1, repo2)\n repo2 = GitRepo(path2)\n assert_not_equal(repo1, repo2)\n ok_(repo1 != repo2)\n\n\n@assert_cwd_unchanged\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\ndef test_GitRepo_add(src, path):\n\n gr = GitRepo(path, src)\n filename = get_most_obscure_supported_name()\n with open(opj(path, filename), 'w') as f:\n f.write(\"File to add to git\")\n gr.git_add(filename)\n\n assert_in(filename, gr.get_indexed_files(), \"%s not successfully added to %s\" % (filename, path))\n\n\n@assert_cwd_unchanged\n@with_tree(tree={\n 'd': {'f1': 'content1',\n 'f2': 'content2'},\n 'file': 'content3',\n 'd2': {'f1': 'content1',\n 'f2': 'content2'},\n 'file2': 'content3'\n\n })\ndef test_GitRepo_remove(path):\n\n gr = GitRepo(path, create=True)\n gr.git_add('*')\n gr.git_commit(\"committing all the files\")\n\n eq_(gr.git_remove('file'), ['file'])\n eq_(set(gr.git_remove('d', r=True, f=True)), {'d/f1', 'd/f2'})\n\n eq_(set(gr.git_remove('*', r=True, f=True)), {'file2', 'd2/f1', 'd2/f2'})\n\n@assert_cwd_unchanged\n@with_tempfile\ndef test_GitRepo_commit(path):\n\n gr = GitRepo(path)\n filename = get_most_obscure_supported_name()\n with open(opj(path, filename), 'w') as f:\n f.write(\"File to add to git\")\n\n gr.git_add(filename)\n gr.git_commit(\"Testing GitRepo.git_commit().\")\n ok_clean_git(path, annex=False, untracked=[])\n\n\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\ndef test_GitRepo_get_indexed_files(src, path):\n\n gr = GitRepo(path, src)\n idx_list = gr.get_indexed_files()\n\n runner = Runner()\n out = runner(['git', 'ls-files'], cwd=path)\n out_list = out[0].split()\n\n for item in idx_list:\n assert_in(item, out_list, \"%s not found in output of git ls-files in %s\" % (item, path))\n for item in out_list:\n assert_in(item, idx_list, \"%s not found in output of get_indexed_files in %s\" % (item, path))\n\n\n@with_tree([\n ('empty', ''),\n ('d1', (\n ('empty', ''),\n ('d2',\n (('empty', ''),\n )),\n )),\n ])\n@assert_cwd_unchanged(ok_to_chdir=True)\ndef test_normalize_path(git_path):\n\n gr = GitRepo(git_path)\n\n # cwd is currently outside the repo, so any relative path\n # should be interpreted as relative to `annex_path`\n assert_raises(FileNotInRepositoryError, _normalize_path, gr.path, getpwd())\n\n result = _normalize_path(gr.path, \"testfile\")\n eq_(result, \"testfile\", \"_normalize_path() returned %s\" % result)\n\n # result = _normalize_path(gr.path, opj('.', 'testfile'))\n # eq_(result, \"testfile\", \"_normalize_path() returned %s\" % result)\n #\n # result = _normalize_path(gr.path, opj('testdir', '..', 'testfile'))\n # eq_(result, \"testfile\", \"_normalize_path() returned %s\" % result)\n # Note: By now, normpath within normalize_paths() is disabled, therefore\n # disable these tests.\n\n result = _normalize_path(gr.path, opj('testdir', 'testfile'))\n eq_(result, opj(\"testdir\", \"testfile\"), \"_normalize_path() returned %s\" % result)\n\n result = _normalize_path(gr.path, opj(git_path, \"testfile\"))\n eq_(result, \"testfile\", \"_normalize_path() returned %s\" % result)\n\n # now we are inside, so\n # OLD PHILOSOPHY: relative paths are relative to cwd and have\n # to be converted to be relative to annex_path\n # NEW PHILOSOPHY: still relative to repo! unless starts with . (curdir) or .. (pardir)\n with chpwd(opj(git_path, 'd1', 'd2')):\n\n result = _normalize_path(gr.path, \"testfile\")\n eq_(result, 'testfile', \"_normalize_path() returned %s\" % result)\n\n # if not joined as directory name but just a prefix to the filename, should\n # behave correctly\n for d in (curdir, pardir):\n result = _normalize_path(gr.path, d + \"testfile\")\n eq_(result, d + 'testfile', \"_normalize_path() returned %s\" % result)\n\n result = _normalize_path(gr.path, opj(curdir, \"testfile\"))\n eq_(result, opj('d1', 'd2', 'testfile'), \"_normalize_path() returned %s\" % result)\n\n result = _normalize_path(gr.path, opj(pardir, 'testfile'))\n eq_(result, opj('d1', 'testfile'), \"_normalize_path() returned %s\" % result)\n\n assert_raises(FileNotInRepositoryError, _normalize_path, gr.path, opj(git_path, '..', 'outside'))\n\n result = _normalize_path(gr.path, opj(git_path, 'd1', 'testfile'))\n eq_(result, opj('d1', 'testfile'), \"_normalize_path() returned %s\" % result)\n\n\ndef test_GitRepo_files_decorator():\n\n class testclass(object):\n def __init__(self):\n self.path = opj('some', 'where')\n\n # TODO\n # yoh: logic is alien to me below why to have two since both look identical!\n @normalize_paths\n def decorated_many(self, files):\n return files\n\n @normalize_paths\n def decorated_one(self, file_):\n return file_\n\n test_instance = testclass()\n\n # When a single file passed -- single path returned\n obscure_filename = get_most_obscure_supported_name()\n file_to_test = opj(test_instance.path, 'deep', obscure_filename)\n # file doesn't exist\n eq_(test_instance.decorated_one(file_to_test),\n _normalize_path(test_instance.path, file_to_test))\n eq_(test_instance.decorated_one(file_to_test),\n _normalize_path(test_instance.path, file_to_test))\n\n file_to_test = obscure_filename\n eq_(test_instance.decorated_many(file_to_test),\n _normalize_path(test_instance.path, file_to_test))\n eq_(test_instance.decorated_one(file_to_test),\n _normalize_path(test_instance.path, file_to_test))\n\n\n file_to_test = opj(obscure_filename, 'beyond', 'obscure')\n eq_(test_instance.decorated_many(file_to_test),\n _normalize_path(test_instance.path, file_to_test))\n\n file_to_test = opj(getpwd(), 'somewhere', 'else', obscure_filename)\n assert_raises(FileNotInRepositoryError, test_instance.decorated_many,\n file_to_test)\n\n # If a list passed -- list returned\n files_to_test = ['now', opj('a list', 'of'), 'paths']\n expect = []\n for item in files_to_test:\n expect.append(_normalize_path(test_instance.path, item))\n eq_(test_instance.decorated_many(files_to_test), expect)\n\n eq_(test_instance.decorated_many(''), [])\n\n assert_raises(ValueError, test_instance.decorated_many, 1)\n assert_raises(ValueError, test_instance.decorated_one, 1)\n\n\n@skip_if_no_network\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\ndef test_GitRepo_remote_add(orig_path, path):\n\n gr = GitRepo(path, orig_path)\n out = gr.git_remote_show()\n assert_in('origin', out)\n eq_(len(out), 1)\n gr.git_remote_add('github', 'git://github.com/datalad/testrepo--basic--r1')\n out = gr.git_remote_show()\n assert_in('origin', out)\n assert_in('github', out)\n eq_(len(out), 2)\n out = gr.git_remote_show('github')\n assert_in(' Fetch URL: git://github.com/datalad/testrepo--basic--r1', out)\n\n\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\ndef test_GitRepo_remote_remove(orig_path, path):\n\n gr = GitRepo(path, orig_path)\n gr.git_remote_add('github', 'git://github.com/datalad/testrepo--basic--r1')\n gr.git_remote_remove('github')\n out = gr.git_remote_show()\n eq_(len(out), 1)\n assert_in('origin', out)\n\n\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\ndef test_GitRepo_remote_show(orig_path, path):\n\n gr = GitRepo(path, orig_path)\n gr.git_remote_add('github', 'git://github.com/datalad/testrepo--basic--r1')\n out = gr.git_remote_show(verbose=True)\n eq_(len(out), 4)\n assert_in('origin\\t%s (fetch)' % orig_path, out)\n assert_in('origin\\t%s (push)' % orig_path, out)\n # Some fellas might have some fancy rewrite rules for pushes, so we can't\n # just check for specific protocol\n assert_re_in('github\\tgit(://|@)github.com[:/]datalad/testrepo--basic--r1 \\(fetch\\)',\n out)\n assert_re_in('github\\tgit(://|@)github.com[:/]datalad/testrepo--basic--r1 \\(push\\)',\n out)\n\n\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\ndef test_GitRepo_get_remote_url(orig_path, path):\n\n gr = GitRepo(path, orig_path)\n gr.git_remote_add('github', 'git://github.com/datalad/testrepo--basic--r1')\n eq_(gr.git_get_remote_url('origin'), orig_path)\n eq_(gr.git_get_remote_url('github'),\n 'git://github.com/datalad/testrepo--basic--r1')\n\n\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile\n@with_tempfile\ndef test_GitRepo_pull(test_path, orig_path, clone_path):\n\n origin = GitRepo(orig_path, test_path)\n clone = GitRepo(clone_path, orig_path)\n filename = get_most_obscure_supported_name()\n\n with open(opj(orig_path, filename), 'w') as f:\n f.write(\"New file.\")\n origin.git_add(filename)\n origin.git_commit(\"new file added.\")\n clone.git_pull()\n assert_true(exists(opj(clone_path, filename)))\n\n\n@with_tempfile\n@with_tempfile\ndef test_GitRepo_push_n_checkout(orig_path, clone_path):\n\n origin = GitRepo(orig_path)\n clone = GitRepo(clone_path, orig_path)\n filename = get_most_obscure_supported_name()\n\n with open(opj(clone_path, filename), 'w') as f:\n f.write(\"New file.\")\n clone.git_add(filename)\n clone.git_commit(\"new file added.\")\n # TODO: need checkout first:\n clone.git_push('origin +master:new-branch')\n origin.git_checkout('new-branch')\n assert_true(exists(opj(orig_path, filename)))\n\n\n@with_tempfile\n@with_tempfile\n@with_tempfile\ndef test_GitRepo_remote_update(path1, path2, path3):\n\n git1 = GitRepo(path1)\n git2 = GitRepo(path2)\n git3 = GitRepo(path3)\n\n git1.git_remote_add('git2', path2)\n git1.git_remote_add('git3', path3)\n\n # Setting up remote 'git2'\n with open(opj(path2, 'masterfile'), 'w') as f:\n f.write(\"git2 in master\")\n git2.git_add('masterfile')\n git2.git_commit(\"Add something to master.\")\n git2.git_checkout('branch2', '-b')\n with open(opj(path2, 'branch2file'), 'w') as f:\n f.write(\"git2 in branch2\")\n git2.git_add('branch2file')\n git2.git_commit(\"Add something to branch2.\")\n\n # Setting up remote 'git3'\n with open(opj(path3, 'masterfile'), 'w') as f:\n f.write(\"git3 in master\")\n git3.git_add('masterfile')\n git3.git_commit(\"Add something to master.\")\n git3.git_checkout('branch3', '-b')\n with open(opj(path3, 'branch3file'), 'w') as f:\n f.write(\"git3 in branch3\")\n git3.git_add('branch3file')\n git3.git_commit(\"Add something to branch3.\")\n\n git1.git_remote_update()\n\n # checkouts are 'tests' themselves, since they'll raise CommandError\n # if something went wrong\n git1.git_checkout('branch2')\n git1.git_checkout('branch3')\n\n branches1 = git1.git_get_branches()\n eq_({'branch2', 'branch3'}, set(branches1))\n\n\n# TODO: Why was it \"flavors=local_testrepo_flavors\" ? What's the windows issue here?\n@with_testrepos('.*git.*', flavors=['clone'])\n@with_tempfile\ndef test_GitRepo_get_files(url, path):\n\n gr = GitRepo(path, url)\n\n # get the expected files via os for comparison:\n os_files = set()\n for (dirpath, dirnames, filenames) in os.walk(path):\n rel_dir = os.path.relpath(dirpath, start=path)\n if rel_dir.startswith(\".git\"):\n continue\n for file_ in filenames:\n os_files.add(opj(rel_dir, file_).lstrip(\"./\"))\n\n # get the files via GitRepo:\n local_files = set(gr.git_get_files())\n remote_files = set(gr.git_get_files(branch=\"origin/master\"))\n\n eq_(local_files, set(gr.get_indexed_files()))\n eq_(local_files, remote_files)\n eq_(local_files, os_files)\n\n # create a different branch:\n gr.git_checkout('new_branch', '-b')\n filename = 'another_file.dat'\n with open(opj(path, filename), 'w') as f:\n f.write(\"something\")\n gr.git_add(filename)\n gr.git_commit(\"Added.\")\n\n # now get the files again:\n local_files = set(gr.git_get_files())\n eq_(local_files, os_files.union({filename}))\n # retrieve remote branch again, which should not have changed:\n remote_files = set(gr.git_get_files(branch=\"origin/master\"))\n eq_(remote_files, os_files)\n eq_(set([filename]), local_files.difference(remote_files))\n\n # switch back and query non-active branch:\n gr.git_checkout('master')\n local_files = set(gr.git_get_files())\n branch_files = set(gr.git_get_files(branch=\"new_branch\"))\n eq_(set([filename]), branch_files.difference(local_files))\n\n\n@with_testrepos(flavors=local_testrepo_flavors)\n@with_tempfile(mkdir=True)\ndef test_GitRepo_get_toppath(repo, tempdir):\n reporeal = realpath(repo)\n eq_(GitRepo.get_toppath(repo), reporeal)\n # Generate some nested directory\n nested = opj(repo, \"d1\", \"d2\")\n os.makedirs(nested)\n eq_(GitRepo.get_toppath(nested), reporeal)\n # and if not under git, should return None\n eq_(GitRepo.get_toppath(tempdir), None)\n\ndef test_GitRepo_dirty():\n trepo = BasicAnnexTestRepo()\n repo = trepo.repo\n # empty at this point -- should not be dirty as well. TODO\n assert_false(repo.dirty)\n trepo.create()\n assert_false(repo.dirty)\n\n # new file added to index\n trepo.create_file('newfiletest.dat', '123\\n', annex=False)\n assert_true(repo.dirty)\n repo.git_commit(\"just a commit\")\n assert_false(repo.dirty)\n\n # file modified to be the same\n trepo.create_file('newfiletest.dat', '123\\n', annex=False)\n assert_false(repo.dirty)\n\n # file modified\n trepo.create_file('newfiletest.dat', '12\\n', annex=False)\n assert_true(repo.dirty)\n repo.git_commit(\"just a commit\")\n assert_false(repo.dirty)\n\n # new file not added to index\n trepo.create_file('newfiletest2.dat', '123\\n', add=False, annex=False)\n assert_true(repo.dirty)\n os.unlink(opj(repo.path, 'newfiletest2.dat'))\n assert_false(repo.dirty)\n\n # new annexed file\n trepo.create_file('newfiletest2.dat', '123\\n', annex=True)\n assert_true(repo.dirty)\n repo.git_commit(\"just a commit\")\n assert_false(repo.dirty)\n\n\n@with_tempfile(mkdir=True)\ndef test_GitRepo_get_merge_base(src):\n repo = GitRepo(src, create=True)\n with open(opj(src, 'file.txt'), 'w') as f:\n f.write('load')\n repo.git_add('*')\n repo.git_commit('committing')\n\n assert_raises(ValueError, repo.git_get_merge_base, [])\n branch1 = repo.git_get_active_branch()\n branch1_hexsha = repo.git_get_hexsha()\n eq_(len(branch1_hexsha), 40)\n eq_(repo.git_get_merge_base(branch1), branch1_hexsha)\n\n # Let's create a detached branch\n branch2 = \"_detach_\"\n repo.git_checkout(branch2, options=\"--orphan\")\n # it will have all the files\n # Must not do: https://github.com/gitpython-developers/GitPython/issues/375\n # repo.git_add('.')\n repo.git_add('*')\n # NOTE: fun part is that we should have at least a different commit message\n # so it results in a different checksum ;)\n repo.git_commit(\"committing again\")\n assert(repo.get_indexed_files()) # we did commit\n assert(repo.git_get_merge_base(branch1) is None)\n assert(repo.git_get_merge_base([branch2, branch1]) is None)\n\n # Let's merge them up -- then merge base should match the master\n repo.git_merge(branch1)\n eq_(repo.git_get_merge_base(branch1), branch1_hexsha)\n\n # if points to some empty/non-existing branch - should also be None\n assert(repo.git_get_merge_base(['nonexistent', branch2]) is None)\n\n@with_tempfile(mkdir=True)\ndef test_GitRepo_git_get_branch_commits(src):\n\n repo = GitRepo(src, create=True)\n with open(opj(src, 'file.txt'), 'w') as f:\n f.write('load')\n repo.git_add('*')\n repo.git_commit('committing')\n\n commits = list(repo.git_get_branch_commits('master'))\n eq_(len(commits), 1)\n commits_stop0 = list(repo.git_get_branch_commits('master', stop=commits[0].hexsha))\n eq_(commits_stop0, [])\n commits_hexsha = list(repo.git_get_branch_commits('master', value='hexsha'))\n commits_hexsha_left = list(repo.git_get_branch_commits('master', value='hexsha', limit='left-only'))\n eq_([commits[0].hexsha], commits_hexsha)\n # our unittest is rudimentary ;-)\n eq_(commits_hexsha_left, commits_hexsha)\n\n raise SkipTest(\"TODO: Was more of a smoke test -- improve testing\")\n\n# TODO:\n# def git_fetch(self, name, options=''):\n\n","sub_path":"datalad/tests/test_gitrepo.py","file_name":"test_gitrepo.py","file_ext":"py","file_size_in_byte":19447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"303121694","text":"#!/usr/bin/python3\n# https://stackoverflow.com/questions/31844713/python-convert-xml-to-csv-file\n\nfrom xml.etree import ElementTree\ntree = ElementTree.parse('curriculo.xml')\ndef recode(var):\n # Py2: return var.decode('iso-8859-1').encode('utf8')\n return bytes(var, 'iso-8859-1').decode('utf8')\nroot = tree.getroot()\nid_lattes = root.get('NUMERO-IDENTIFICADOR')\n\noutput = ''\n\nfor attrib in root:\n if attrib.tag == 'DADOS-GERAIS':\n nome = attrib.get('NOME-COMPLETO')\n papers = attrib.find('ARTIGOS-PUBLICADOS')\n if papers == None:\n continue\n #print(papers)\n for paper in papers:\n #print()\n #print(paper.tag)\n seq = paper.get('SEQUENCIA-PRODUCAO')\n id_seq = id_lattes + seq\n autores = []\n for detail in paper:\n #print(detail.tag)\n tag = detail.tag\n if tag == 'DADOS-BASICOS-DO-ARTIGO':\n titulo = detail.get('TITULO-DO-ARTIGO')\n ano = detail.get('ANO-DO-ARTIGO')\n url = detail.get('HOME-PAGE-DO-TRABALHO')\n url = url.strip('[]')\n doi = detail.get('DOI')\n if tag == 'DETALHAMENTO-DO-ARTIGO':\n periodico = detail.get('TITULO-DO-PERIODICO-OU-REVISTA')\n issn = detail.get('ISSN')\n vol = detail.get('VOLUME')\n issue = detail.get('SERIE')\n pgini = detail.get('PAGINA-INICIAL')\n pgfim = detail.get('PAGINA-FINAL')\n if tag == 'AUTORES':\n autor = detail.get('NOME-PARA-CITACAO')\n autor = autor.split(';')\n autor = autor[0]\n ordem = detail.get('ORDEM-DE-AUTORIA')\n autores.append((ordem, autor))\n\n #second = subatt.find('TITULO-DO-ARTIGO')\n autores = sorted(autores)\n autores = \"; \".join(\"%s\" % autor for (ordem, autor) in autores) \n #print('\"{}\",\"{}\",{},\"{}\",\"{}\"'.join(id_lattes, titulo, ano, periodico, issn))\n line = [id_lattes, seq, id_seq, nome, autores, ano, titulo, periodico, issn, doi,\n url, vol, issue, pgini, pgfim]\n #line = '\", \"'.join(line) never use spaces after delimiting commas!\n line = '\",\"'.join(line)\n line = '\"' + line + '\"\\n'\n output += line\nfn = id_lattes+'prd.csv'\nfile = open(fn, 'w')\nfile.write(output)\nfile.close()\nprint('File {} ({}) written'.format(fn,nome))\n\n","sub_path":"lattesprd.py","file_name":"lattesprd.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"562893416","text":"\"\"\"\nThis module provides standard routines for LV and BiV simulations.\n\"\"\"\n\nfrom dolfin import parameters, DirichletBC, project\nfrom dolfin.cpp.common import mpi_comm_world, MPI, info\nfrom dolfin.cpp.io import HDF5File\n\nimport cvbtk\nfrom cvbtk.utils import print_once, reset_values, read_dict_from_csv, \\\n build_nullspace, info_once, vector_space_to_scalar_space, save_to_disk\nfrom cvbtk.mechanics import ArtsKerckhoffsActiveStress, KerckhoffsMaterial, \\\n BovendeerdMaterial, fiber_stretch_ratio, ArtsBovendeerdActiveStress\nfrom cvbtk.geometries import LeftVentricleGeometry, BiventricleGeometry\nfrom cvbtk.models import BiventricleModel, LeftVentricleModel\nfrom cvbtk.windkessel import LifetecWindkesselModel, GeneralWindkesselModel, WindkesselModel, get_phase, get_phase_dc, \\\n HeartMateII\nfrom cvbtk.solvers import VolumeSolver, VolumeSolverBiV\nfrom cvbtk.dataset import Dataset\n\nfrom cvbtk.resources import reference_biventricle, reference_left_ventricle_pluijmert\n\nimport os\nimport time\n\n\n__all__ = [\n 'check_heart_type',\n 'check_heart_type_from_inputs',\n 'create_materials',\n 'create_model',\n 'create_windkessel_biv',\n 'create_windkessel_lv',\n 'load_model_state_from_hdf5',\n 'preprocess_biv',\n 'preprocess_lv',\n 'ReloadState',\n 'reset_model_state',\n 'set_boundary_conditions',\n 'set_initial_conditions_biv',\n 'set_initial_conditions_lv',\n 'simulate',\n 'timestep_biv',\n 'timestep_lv',\n 'write_data_biv',\n 'write_data_lv'\n]\n\n\ndef check_heart_type(geometry):\n \"\"\"\n Returns the heart type, based on the geometry.\n\n Args:\n geometry (cvbtk Geometry): geometry object (LeftVentricleGeometry or BiventricleGeometry)\n\n Returns:\n heart_type (str): 'LeftVentricle' or 'Biventricle'\n \"\"\"\n # Test something from the geometry to figure out whether we have a\n # LV or a BiV geometry.\n if hasattr(geometry, 'rv_endocardium'):\n return 'Biventricle'\n else:\n return 'LeftVentricle'\n\n\ndef check_heart_type_from_inputs(inputs):\n \"\"\"\n Returns the heart type, based on the simulation inputs.\n\n Args:\n inputs (dict): Dictionary with simulation inputs.\n\n Returns:\n heart_type (str): 'LeftVentricle' or 'Biventricle'\n \"\"\"\n # Test something from the inputs to figure out whether we have a\n # LV or a BiV circulation.\n if 'wk_pul' in inputs.keys():\n heart_type = 'Biventricle'\n else:\n heart_type = 'LeftVentricle'\n return heart_type\n\n\ndef create_materials(model, inputs):\n \"\"\"\n Adds passive and active materials to a model (LV or BiV).\n\n Args:\n model (cvbtk Model): Model object (e.g. LeftVentricleModel or BiventricleModel).\n inputs (dict): Simulation inputs.\n \"\"\"\n # Extract fiber vectors.\n fsn = model.geometry.fiber_vectors()\n\n # Material models all take u, fsn, and arbitrary inputs for arguments.\n # It needs to be set by assigning it to the ``material`` attribute.\n u = model.u\n\n # Material models all take u, fsn, and arbitrary inputs for arguments.\n # It needs to be set by assigning it to the ``material`` attribute.\n law = inputs.get('material_law', 'BovendeerdMaterial') # Default to BovendeerdMaterial.\n if law == 'KerckhoffsMaterial':\n model.material = KerckhoffsMaterial(u, fsn, **inputs['material_model'])\n elif law == 'BovendeerdMaterial':\n model.material = BovendeerdMaterial(u, fsn, **inputs['material_model'])\n else:\n raise ValueError('Unknown passive stress model specified.')\n\n # Active stress model.\n active_stress_model = inputs.get('active_stress_model', 'ArtsKerckhoffsActiveStress') # Default to ArtsKerckhoffsActiveStress.\n if active_stress_model == 'ArtsBovendeerdActiveStress':\n act = ArtsBovendeerdActiveStress(u, fsn, **inputs['active_stress'])\n elif active_stress_model == 'ArtsKerckhoffsActiveStress':\n act = ArtsKerckhoffsActiveStress(u, fsn, **inputs['active_stress'])\n elif active_stress_model is None:\n act = None\n else:\n raise ValueError('Unknown active stress model specified.')\n\n model.active_stress = act\n\n\ndef create_model(geometry, inputs, heart_type):\n \"\"\"\n Returns a model object (LV or BiV).\n\n Args:\n geometry (cvbtk Geometry): Geometry object (e.g. LeftVentricleGeometry or BiventricleGeometry).\n inputs (dict): Simulation inputs.\n heart_type (str): 'Biventricle' or 'LeftVentricle', specifying what kind of model to create.\n\n Returns:\n model (cvbtk Model): Model object (either BiventricleModel or LeftVentricleModel).\n \"\"\"\n if heart_type == 'Biventricle':\n model = BiventricleModel(geometry, **inputs.get('model', {}))\n elif heart_type == 'LeftVentricle':\n model = LeftVentricleModel(geometry, **inputs.get('model', {}))\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n # Check parameters.\n info_once(model.parameters, True)\n\n return model\n\n\ndef create_windkessel_biv(inputs):\n \"\"\"\n Returns cvbtk Windkessel objects for the systemic and pulmonary circulations.\n\n Args:\n inputs (dict): Simulation inputs.\n\n Returns:\n Dictionary with cvbtk Windkessel objects for systemic ('sys') and pulmonary ('pul') circulation.\n \"\"\"\n # Create the windkessel model for the systemic circulation part with the loaded inputs.\n wk_sys = GeneralWindkesselModel('systemic_windkessel', **inputs['wk_sys'])\n\n # Create the windkessel model for the pulmonary circulation part with the loaded inputs.\n wk_pul = GeneralWindkesselModel('pulmonary_windkessel', **inputs['wk_pul'])\n\n # Add LVAD.\n if inputs.get('attach_lvad', False):\n wk_sys.lvad = HeartMateII(**inputs['lvad_model'])\n\n # Print parameters.\n info_once(wk_sys.parameters, True)\n info_once(wk_pul.parameters, True)\n\n return {'sys': wk_sys, 'pul': wk_pul}\n\n\ndef create_windkessel_lv(inputs):\n \"\"\"\n Returns cvbtk Windkessel object for the systemic circulation.\n\n Args:\n inputs (dict): Simulation inputs.\n\n Returns:\n Dictionary with cvbtk Windkessel object for systemic ('sys') circulation.\n \"\"\"\n # Create the windkessel model for the circulation/boundary condition part.\n wk_type = inputs.get('windkessel_type', 'WindkesselModel')\n if wk_type == 'WindkesselModel':\n wk = WindkesselModel(**inputs['windkessel_model'])\n elif wk_type == 'LifetecWindkesselModel':\n wk = LifetecWindkesselModel(**inputs['windkessel_model'])\n else:\n raise ValueError('Unknown wk_type \"{}\"'.format(wk_type))\n\n # Add LVAD.\n if inputs.get('attach_lvad', False):\n wk.lvad = HeartMateII(**inputs['lvad_model'])\n\n # Print parameters.\n info_once(wk.parameters, True)\n\n return {'sys': wk}\n\n\ndef load_model_state_from_hdf5(model, results_hdf5, vector_number, fiber_reorientation=False):\n \"\"\"\n Loads a model state into a cvbtk Model object.\n\n Args:\n model (cvbtk Model): Model object (e.g. LeftVentricleModel or BiventricleModel).\n results_hdf5 (str): Filename to HDF5 file containing displacement and\n optionally contractile element length and fiber vectors.\n vector_number (int): Vector number in HDF5 file to load.\n fiber_reorientation (boolean): Specify whether fiber reorientation was on during simulation.\n \"\"\"\n with HDF5File(mpi_comm_world(), results_hdf5, 'r') as f:\n\n # Displacement\n u_vector = 'displacement/vector_{}'.format(vector_number)\n f.read(model.u, u_vector)\n\n if vector_number-1 <= 0:\n raise ValueError('Cannot reload u_old from results file. Vector number = {}.'.format(vector_number-1))\n\n u_old_vector = 'displacement/vector_{}'.format(vector_number-1)\n f.read(model.u_old, u_old_vector)\n\n if vector_number-2 >= 0:\n u_old_old_vector = 'displacement/vector_{}'.format(vector_number-2)\n f.read(model.u_old_old, u_old_old_vector)\n else:\n print_once('Warning: Cannot reload u_old_old from results file. Vector number = {}'.format(vector_number-2))\n\n # If fiber vectors are changing (reorienting), we need the old fiber vectors (at previous timestep) to\n # compute ls_old.\n if fiber_reorientation:\n # Fiber vectors are saved in results file.\n model.geometry.load_fiber_field(openfile=f, vector_number=vector_number - 1)\n\n # Old sarcomere length.\n ef = model.active_stress.fiber_vectors[0]\n u_old = model.u_old\n model.active_stress.ls_old = model.active_stress.parameters['ls0']*fiber_stretch_ratio(u_old, ef)\n\n # Contractile element length\n if isinstance(model.active_stress, ArtsKerckhoffsActiveStress):\n # Load lc_old.\n lc_vector = 'contractile_element/vector_{}'.format(vector_number)\n f.read(model.active_stress.lc_old, lc_vector)\n\n # Now, load current fiber vectors.\n if fiber_reorientation:\n # Fiber vectors are saved in results file.\n model.geometry.load_fiber_field(openfile=f, vector_number=vector_number)\n\n\ndef preprocess_biv(inputs):\n \"\"\"\n Pre-processing routine for biventricular simulations.\n\n Args:\n inputs(dict): Simulation inputs.\n\n Returns:\n wk (dict): Dictionary with initialized cvbtk Windkessel objects\n for systemic ('sys') and pulmonary ('pul') circulation.\n biv (cvbtk Model): Initialized BiventricleModel.\n results (cvbtk.Dataset): Dataset for the results.\n \"\"\"\n # ------------------------------------------------------------------------ #\n # Create a dataset container to store state values. #\n # ------------------------------------------------------------------------ #\n dataset_keys = ['time', 't_cycle', 't_act', 'cycle', 'phase_s', 'phase_p',\n 'pcav_s', 'part_s', 'pven_s', 'qart_s', 'qper_s', 'qven_s', 'vcav_s', 'vart_s', 'vven_s',\n 'pcav_p', 'part_p', 'pven_p', 'qart_p', 'qper_p', 'qven_p', 'vcav_p', 'vart_p', 'vven_p',\n 'a_s', 'b_s', 'c_s', 'a_p', 'b_p', 'c_p',\n 'est', 'accuracy', 'vector_number']\n\n if inputs.get('attach_lvad', False):\n dataset_keys.append('qlvad') # flowrate of lvad\n\n # Create the dataset.\n results = Dataset(keys=dataset_keys)\n\n # ------------------------------------------------------------------------ #\n # Set the proper global FEniCS parameters. #\n # ------------------------------------------------------------------------ #\n parameters.update({'form_compiler': inputs['form_compiler']})\n\n # ------------------------------------------------------------------------ #\n # Create the windkessel models for the systemic and pulmonary circulation. #\n # ------------------------------------------------------------------------ #\n wk = create_windkessel_biv(inputs)\n\n # ------------------------------------------------------------------------ #\n # Create the finite element biventricle. #\n # ------------------------------------------------------------------------ #\n # TODO BiV geometry to load is hardcoded. Could be specified in inputs if there a more BiV geometries.\n # For the geometry we re-use the reference mesh.\n res = inputs['geometry']['mesh_resolution']\n geometry = reference_biventricle(resolution=res, **inputs['geometry'])\n\n # Create model and set boundary conditions.\n biv = create_model(geometry, inputs, 'Biventricle')\n set_boundary_conditions(biv)\n\n # Add material laws to the model.\n create_materials(biv, inputs)\n\n # ------------------------------------------------------------------------ #\n # Inspect the parameters of the windkessel and BiV models: #\n # ------------------------------------------------------------------------ #\n if MPI.rank(mpi_comm_world()) == 0:\n info(wk['sys'].parameters, True)\n info(wk['pul'].parameters, True)\n info(biv.parameters, True)\n info(biv.geometry.parameters, True)\n\n # ------------------------------------------------------------------------ #\n # Set the initial conditions. #\n # ------------------------------------------------------------------------ #\n set_initial_conditions_biv(wk, biv, inputs)\n\n # Print out the current (initial) state just to double check the values:\n if MPI.rank(mpi_comm_world()) == 0:\n print('The initial systemic WK state is V = {}.'.format(wk['sys'].volume))\n print('The initial systemic WK state is p = {}.'.format(wk['sys'].pressure))\n print('The initial systemic WK state is q = {}.'.format(wk['sys'].flowrate))\n\n print('The initial pulmonary WK state is V = {}.'.format(wk['pul'].volume))\n print('The initial pulmonary WK state is p = {}.'.format(wk['pul'].pressure))\n print('The initial pulmonary WK state is q = {}.'.format(wk['pul'].flowrate))\n print('The initial BiV state is V = {}.'.format(biv.volume))\n print('The initial BiV state is p = {}.'.format(biv.pressure))\n\n return wk, biv, results\n\n\ndef preprocess_lv(inputs):\n \"\"\"\n Pre-processing routine for leftventricle simulations.\n\n Args:\n inputs(dict): Simulation inputs.\n\n Returns:\n wk (dict): Dictionary with initialized cvbtk Windkessel object\n for systemic ('sys') circulation.\n lv (cvbtk Model): Initialized LeftVentricleModel.\n results (cvbtk.Dataset): Dataset for the results.\n \"\"\"\n # ------------------------------------------------------------------------ #\n # Create a dataset container to store state values. #\n # ------------------------------------------------------------------------ #\n # Populate it with the same keys (columns) as the Sepran data.\n sepran_keys = cvbtk.resources.reference_hemodynamics().keys()\n\n # Add the following additional keys.\n sepran_keys.append('t_act') # time before/since activation\n sepran_keys.append('t_cycle') # time in the current cycle\n sepran_keys.append('vector_number') # corresponds to the HDF5 output\n if inputs.get('attach_lvad', False):\n sepran_keys.append('qlvad') # flowrate of lvad\n\n # Create the dataset.\n results = Dataset(keys=sepran_keys)\n\n # ------------------------------------------------------------------------ #\n # Set the proper global FEniCS parameters. #\n # ------------------------------------------------------------------------ #\n parameters.update({'form_compiler': inputs['form_compiler']})\n\n # ------------------------------------------------------------------------ #\n # Create the windkessel model for the circulation/boundary condition part. #\n # ------------------------------------------------------------------------ #\n wk = create_windkessel_lv(inputs)\n\n # ------------------------------------------------------------------------ #\n # Create the finite element model for the left ventricle. #\n # ------------------------------------------------------------------------ #\n # For the geometry we re-use the reference mesh.\n res = inputs['geometry']['mesh_resolution']\n\n # Reference mesh name is specified in inputs. Else default is 'reference_left_ventricle_pluijmert'.\n geometry_type = inputs.get('geometry_type', 'reference_left_ventricle_pluijmert')\n print_once('Loading geometry type \"{}\"...'.format(geometry_type))\n\n # Load the desired mesh.\n if geometry_type == 'reference_left_ventricle_pluijmert':\n geometry = cvbtk.resources.reference_left_ventricle_pluijmert(resolution=res, **inputs['geometry'])\n elif geometry_type == 'reference_left_ventricle':\n geometry = cvbtk.resources.reference_left_ventricle(resolution=res, **inputs['geometry'])\n else:\n raise ValueError('Unknwon geometry type.')\n\n # Check parameters.\n info_once(geometry.parameters, True)\n\n # Create model and set boundary conditions.\n lv = create_model(geometry, inputs, 'LeftVentricle')\n set_boundary_conditions(lv)\n\n # Add material laws to the model.\n create_materials(lv, inputs)\n\n # ------------------------------------------------------------------------ #\n # Set the initial conditions. #\n # ------------------------------------------------------------------------ #\n set_initial_conditions_lv(wk, lv, inputs)\n\n # Print out the current (initial) state just to double check the values:\n if MPI.rank(mpi_comm_world()) == 0:\n print('Initialized state: p = {}, {}.'.format(wk['sys'].pressure, lv.pressure))\n print('Initialized state: V = {}, {}.'.format(wk['sys'].volume, lv.volume))\n print('Initialized state: q = {}.'.format(wk['sys'].flowrate))\n\n return wk, lv, results\n\n\nclass ReloadState(object):\n \"\"\"\n Reloads a state to the LeftVentricleModel or BiventricleModel.\n\n Use the main function 'reload' to do the reloading, e.g.:\n wk, lv, results, inputs = ReloadState().reload('output/stopped_simulation', 'latest')\n See the 'reload' function for more details on inputs and outputs.\n \"\"\"\n\n def __init__(self):\n self.inputs = None\n self.results_csv = None\n self.results_hdf5 = None\n self.heart_type = None\n\n def reload(self, directory, t, **kwargs):\n \"\"\"\n Main function.\n Reloads a state (compatible with LeftVentricleModel and BiventricleModel).\n\n Args:\n directory: Directory in which the inputs.csv, results_cycle_x.hdf5 and results.csv files\n exists from which to reload a state.\n t: The time (in ms) of the state to be reloaded, or -1.\n If the last saved timestep should be reloaded, set t to -1.\n **kwargs: Optional key-worded arguments to overrule loaded inputs\n (by default the saved inputs from the reloaded simulation are used).\n\n Returns:\n wk (dict), model (cvbtk.Model), results (cvbtk.Dataset), inputs (dict)\n Using these as inputs for 'simulate' will resume the simulation.\n \"\"\"\n # TODO validate for LVAD simulations.\n print_once('Reloading state from {} directory at t = {} ...'.format(directory, t))\n\n # Read inputs CSV.\n self.inputs = read_dict_from_csv(os.path.join(directory, 'inputs.csv'))\n\n # Overrule loaded inputs with key-worded input arguments.\n self.inputs.update(kwargs)\n\n # Read results CSV.\n self.results_csv = Dataset(filename=os.path.join(directory, 'results.csv'))\n\n # Default timestep to reload.\n if t == -1:\n # Select latest timestep in CSV file.\n t = self.results_csv['time'].values.tolist()[-1]\n\n # Find the index for the csvfile and vector number for the hdf5file of the state to reload.\n idx, cycle, vector_number = self._get_index_and_vector_number(t)\n\n # Store path to results HDF5 file.\n self.results_hdf5 = os.path.join(directory, 'results_cycle_{}.hdf5'.format(cycle))\n\n # Set the proper global FEniCS parameters.\n parameters.update({'form_compiler': self.inputs['form_compiler']})\n\n # Deduct type of model for the heart from inputs.\n heart_type = check_heart_type_from_inputs(self.inputs)\n\n # Set the 'load_fiber_field_from_meshfile' parameter to True.\n self.inputs['geometry']['load_fiber_field_from_meshfile'] = True\n\n # Create the windkessel model(s) and the geometry.\n # Note that wk is a dictionary with keys 'sys' (and 'pul' in case of a Biventricle).\n # Here, 'sys' contains the systemic circulation windkessel\n # and 'pul' the pulmonary circulation windkessel.\n if heart_type == 'Biventricle':\n wk = create_windkessel_biv(self.inputs)\n geometry = self._load_geometry_biv()\n elif heart_type == 'LeftVentricle':\n wk = create_windkessel_lv(self.inputs)\n geometry = self._load_geometry_lv()\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n # Create the model and set boundary conditions.\n model = create_model(geometry, self.inputs, heart_type)\n set_boundary_conditions(model)\n\n # Create materials.\n create_materials(model, self.inputs)\n\n # Load initial state at specified timestep and set initial conditions and create a Dataset.\n if heart_type == 'Biventricle':\n # Load state.\n self._load_state_biv(model, idx, vector_number)\n set_initial_conditions_biv(wk, model, self.inputs)\n elif heart_type == 'LeftVentricle':\n # Load state.\n self._load_state_lv(model, idx, vector_number)\n set_initial_conditions_lv(wk, model, self.inputs)\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n dataset_keys = self.results_csv.keys()\n\n # Create the dataset.\n results = Dataset(keys=dataset_keys)\n\n # Inspect the parameters of the models:\n if MPI.rank(mpi_comm_world()) == 0:\n info(wk['sys'].parameters, True)\n if 'pul' in wk.keys():\n info(wk['pul'].parameters, True)\n info(model.parameters, True)\n info(model.geometry.parameters, True)\n\n return wk, model, results, self.inputs\n\n def _get_index_and_vector_number(self, t):\n # Extract the time array.\n time = self.results_csv['time'].values.tolist()\n\n # Get the index of the state to be reloaded.\n idx = time.index(float(t))\n if idx < 2:\n raise RuntimeError('Cannot reload the first timestep. Consider not reloading a state.')\n\n cycle = list(self.results_csv['cycle'])[idx]\n vector_number = list(self.results_csv['vector_number'])[idx]\n\n return idx, cycle, vector_number\n\n def _load_geometry_biv(self):\n geometry_inputs = self.inputs['geometry']\n try:\n geometry = BiventricleGeometry(meshfile=self.results_hdf5, **geometry_inputs)\n except RuntimeError as error_detail:\n print_once('Except RuntimeError: {}'.format(error_detail))\n print_once('Failed to load mesh from result.hdf5 file. Loading reference mesh...')\n # Load the reference geometry otherwise.\n res = self.inputs['geometry']['mesh_resolution']\n geometry = reference_biventricle(resolution=res, **geometry_inputs)\n return geometry\n\n def _load_geometry_lv(self):\n geometry_inputs = self.inputs['geometry']\n try:\n geometry = LeftVentricleGeometry(meshfile=self.results_hdf5, **geometry_inputs)\n except RuntimeError as error_detail:\n print_once('Except RuntimeError: {}'.format(error_detail))\n print_once('Failed to load mesh from result.hdf5 file. Loading reference mesh...')\n # Load the reference geometry otherwise.\n res = self.inputs['geometry']['mesh_resolution']\n geometry = reference_left_ventricle_pluijmert(resolution=res, **geometry_inputs)\n return geometry\n\n def _load_state_biv(self, biv, idx, vector_number):\n\n inputs = self.inputs\n results_csv = self.results_csv\n results_hdf5 = self.results_hdf5\n\n # Extract data from CSV at timestep t and save it to the inputs for the windkessel models.\n initial_conditions = {'p_art_sys': results_csv['part_s'].values.tolist()[idx],\n 'p_art_pul': results_csv['part_p'].values.tolist()[idx],\n 'p_ven_pul': results_csv['pven_p'].values.tolist()[idx]}\n inputs['initial_conditions'] = initial_conditions\n\n # Extract data from CSV at timestep t and save it to the BiV model.\n # Pressure\n biv._plv = results_csv['pcav_s'].values.tolist()[idx]\n biv._prv = results_csv['pcav_p'].values.tolist()[idx]\n\n # Pressure old\n biv._plv_old = results_csv['pcav_s'].values.tolist()[idx-1]\n biv._prv_old = results_csv['pcav_p'].values.tolist()[idx-1]\n\n # Pressure old old\n biv._plv_old_old = results_csv['pcav_s'].values.tolist()[idx-2]\n biv._prv_old_old = results_csv['pcav_p'].values.tolist()[idx-2]\n\n # Load time variables.\n self._load_times(biv, inputs, results_csv, idx)\n\n # Extract data from HDF5 at timestep t.\n fiber_reorientation = True if inputs['model']['fiber_reorientation']['ncycles_reorient'] > 0 else False\n load_model_state_from_hdf5(biv, results_hdf5, vector_number, fiber_reorientation)\n\n def _load_state_lv(self, lv, idx, vector_number):\n\n inputs = self.inputs\n results_csv = self.results_csv\n results_hdf5 = self.results_hdf5\n\n # Extract data from CSV at timestep t and save it to the inputs for the windkessel models.\n initial_conditions = {'arterial_pressure': results_csv['part'].values.tolist()[idx]}\n inputs['initial_conditions'] = initial_conditions\n\n # Extract data from CSV at timestep t and save it to the LV model.\n # Pressure\n lv._plv = results_csv['plv'].values.tolist()[idx]\n\n # Pressure old\n lv._plv_old = results_csv['plv'].values.tolist()[idx-1]\n\n # Load time variables.\n self._load_times(lv, inputs, results_csv, idx)\n\n # Extract data from HDF5 at timestep t.\n fiber_reorientation = True if inputs['model']['fiber_reorientation']['ncycles_reorient'] > 0 else False\n load_model_state_from_hdf5(lv, results_hdf5, vector_number, fiber_reorientation)\n\n @staticmethod\n def _load_times(model, inputs, results_csv, idx):\n # Update the time variables of the FE model\n # dt\n time = results_csv['time'].values.tolist()\n model.dt = time[idx] - time[idx - 1] # using the setter, the dt of the active stress model is set, too.\n\n # dt old\n model._dt_old = time[idx - 1] - time[idx - 2]\n model._dt_old_old = time[idx - 2] - time[idx - 3]\n\n # Activation time.\n if model.active_stress is not None:\n model.active_stress.activation_time = float(\n results_csv['t_act'].values.tolist()[idx] + model.active_stress.parameters['tdep'])\n\n # Load the global starting time, cycle time, activation time, cycle number and phase.\n heart_type = check_heart_type_from_inputs(inputs)\n if heart_type == 'Biventricle':\n reloaded_phase = {'lv': results_csv['phase_s'].values.tolist()[idx],\n 'rv': results_csv['phase_p'].values.tolist()[idx]}\n elif heart_type == 'LeftVentricle':\n reloaded_phase = {'lv': results_csv['phase'].values.tolist()[idx]}\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n inputs['state']['phase'] = reloaded_phase\n inputs['time']['t0'] = results_csv['time'].values.tolist()[idx]\n inputs['state']['t_cycle'] = results_csv['t_cycle'].values.tolist()[idx]\n inputs['state']['cycle'] = results_csv['cycle'].values.tolist()[idx]\n if model.active_stress is not None:\n inputs['state']['t_active_stress'] = float(\n results_csv['t_act'].values.tolist()[idx] + model.active_stress.parameters['tdep'])\n else:\n inputs['state']['t_active_stress'] = 0.\n\n # TODO verify that we do not need to return inputs.\n\n\ndef reset_model_state(model, dt_old, activation_time_old, u_array, u_old_array, ls_old_array, lc_old_array=None,\n ef_old_array=None, es_old_array=None, en_old_array=None):\n \"\"\"\n Helper function to reset a model state.\n \"\"\"\n # Reset time.\n model.dt = dt_old\n model.active_stress.activation_time = activation_time_old\n\n # Reset FEniCS functions:\n reset_values(model.u, u_array)\n reset_values(model.u_old, u_old_array)\n reset_values(model.active_stress.ls_old, ls_old_array)\n\n # Reset lc_old if a copy was saved.\n if lc_old_array is not None:\n reset_values(model.active_stress.lc_old, lc_old_array)\n\n # Reset the fiber vectors if a copy was saved.\n if ef_old_array is not None:\n model.geometry.set_fiber_vectors(ef_old_array, es_old_array, en_old_array)\n\n\ndef save_model_state_to_hdf5(model, hdf5_filename, t, new=False, save_fiber_vector=False):\n \"\"\"\n Helper function to save a model state to a HDF5 file (works for LV and Biv).\n\n Args:\n model (cvbtk Model): Model object (e.g. LeftVentricleModel or BiventricleModel).\n hdf5_filename (str): Filename to HDF5 file.\n t (int, float): Time stamp.\n new (boolean): Specify whether a new file must be created (True) or if the\n state must be appended to an existing file (False).\n save_fiber_vector (boolean): Specify whether to save the fiber vector (True) or not (False).\n \"\"\"\n\n # Create a new HDF5 record saving the mesh and geometric parameters.\n if new:\n model.geometry.save_mesh_to_hdf5(hdf5_filename, save_fiber_vector=False)\n\n # Write the displacement and contractile element to disk.\n with HDF5File(mpi_comm_world(), hdf5_filename, 'a') as f:\n\n # Write the primary displacement unknown.\n f.write(model.u, 'displacement', t)\n\n if model.active_stress is not None:\n if isinstance(model.active_stress, ArtsKerckhoffsActiveStress):\n # Save contractile element length.\n f.write(model.active_stress.lc_old, 'contractile_element', t)\n\n # Write the fiber vectors if requested. Always save the initial fiber vector (if new==True).\n if new or save_fiber_vector:\n ef = model.geometry.fiber_vectors()[0].to_function(None)\n f.write(ef, 'fiber_vector', t)\n\n # For the CSV file:\n vector_number = f.attributes('displacement')['count'] - 1\n\n return vector_number\n\n\ndef set_boundary_conditions(model):\n \"\"\"\n Helper function to add boundary conditions to a cvbtk Model.\n\n Args:\n model (cvbtk Model): Model object (e.g. LeftVentricleModel or BiventricleModel).\n \"\"\"\n # Model defines u, from which V can be collected.\n u = model.u\n V = u.ufl_function_space()\n\n # Dirichlet boundary conditions fix the base.\n model.bcs = DirichletBC(V.sub(2), 0.0, model.geometry.tags(), model.geometry.base)\n\n # We have not fully eliminated rigid body motion yet. To do so, we will\n # define a nullspace of rigid body motions and use a iterative method which\n # can eliminate rigid body motions using this nullspace.\n model.nullspace = build_nullspace(u, modes=['x', 'y', 'xy'])\n\n\ndef set_initial_conditions_biv(wk_dict, biv, inputs):\n \"\"\"\n Initializes cvbtk Windkessel and Model objects with initial conditions for biventricular simulations.\n\n Args:\n wk_dict (dict): Dictionary with cvbtk Windkessel objects for systemic ('sys')\n and pulmonary ('pul') circulation.\n biv (cvbtk Model): BiventricleModel.\n inputs (dict): Simulation inputs.\n \"\"\"\n # Extract the windkessel objects.\n wk_sys = wk_dict['sys']\n wk_pul = wk_dict['pul']\n\n # Determine initial state by setting initial pressures (in kPa).\n wk_sys.pressure = {'art': inputs['initial_conditions']['p_art_sys']}\n\n wk_pul.pressure = {'art': inputs['initial_conditions']['p_art_pul'],\n 'ven': inputs['initial_conditions']['p_ven_pul']}\n\n # Compute initial volumes from initial pressures\n biv.volume = biv.compute_volume()\n wk_sys.volume = wk_sys.compute_volume()\n wk_pul.volume = wk_pul.compute_volume()\n\n # Compute initial venous volume (systemic) from mass conservation.\n vven_sys = inputs['total_volume'] - biv.volume['lv'] - biv.volume['rv'] - wk_sys.volume['art'] - wk_pul.volume[\n 'art'] - wk_pul.volume['ven'] - wk_sys.volume.get('lvad', 0)\n wk_sys.volume = {'ven': vven_sys}\n\n # Compute venous pressure (systemic) from venous volume.\n wk_sys.pressure = {'ven': wk_sys.compute_pressure()['ven']}\n\n # Compute initial flowrates from initial pressures.\n p_boundary_sys = {'in': biv.pressure['lv'],\n 'out': biv.pressure['rv']}\n wk_sys.flowrate = wk_sys.compute_flowrate(p_boundary_sys)\n\n p_boundary_pul = {'in': biv.pressure['rv'],\n 'out': biv.pressure['lv']}\n wk_pul.flowrate = wk_pul.compute_flowrate(p_boundary_pul)\n\n # Print out the current (initial) state just to double check the values:\n if MPI.rank(mpi_comm_world()) == 0:\n print('The initial systemic WK state is V = {}.'.format(wk_sys.volume))\n print('The initial systemic WK state is p = {}.'.format(wk_sys.pressure))\n print('The initial systemic WK state is q = {}.'.format(wk_sys.flowrate))\n\n print('The initial pulmonary WK state is V = {}.'.format(wk_pul.volume))\n print('The initial pulmonary WK state is p = {}.'.format(wk_pul.pressure))\n print('The initial pulmonary WK state is q = {}.'.format(wk_pul.flowrate))\n print('The initial BiV state is V = {}.'.format(biv.volume))\n print('The initial BiV state is p = {}.'.format(biv.pressure))\n\n\ndef set_initial_conditions_lv(wk_dict, lv, inputs):\n \"\"\"\n Initializes cvbtk Windkessel and Model objects with initial conditions for leftventricle simulations.\n\n Args:\n wk_dict (dict): Dictionary with cvbtk Windkessel object for systemic ('sys') circulation.\n lv (cvbtk Model): LeftVentricleModel.\n inputs (dict): Simulation inputs.\n \"\"\"\n # Extract the windkessel object.\n wk = wk_dict['sys']\n\n # Set the initial conditions.\n lv.volume = {'lv': lv.compute_volume()}\n\n # We've defined the initial arterial pressure , from which\n # the initial arterial volume can be computed and set:\n wk.pressure = {'art': inputs['initial_conditions']['arterial_pressure']}\n wk.volume = wk.compute_volume(wk.pressure)\n\n # The missing volume is the venous volume, which comes from conservation:\n vven = wk.parameters['total_volume'] - wk.volume['art'] - lv.volume['lv'] \\\n - wk.volume.get('lvad', 0)\n wk.volume = {'ven': vven}\n\n # The resulting venous pressure can be computed from the venous volume:\n # Note that for the LifetecWindkessel the venous pressure is constant\n # and not depending on venous volume.\n wk.pressure = {'ven': wk.compute_pressure(wk.volume)['ven']}\n\n # The resulting initial flowrate can be computed from the initial pressures:\n wk.flowrate = wk.compute_flowrate(wk.pressure, lv.pressure)\n\n\ndef simulate(wk, model, results, inputs, heart_type=None, solver=None, dir_out='output/'):\n \"\"\"\n Routine for simulating the circulation modelled by\n 0D windkessel models and the heart by a FEM model.\n\n Args:\n wk (dict): Dictionary with the windkessel model for the systemic circulation ('sys'),\n and optionally a windkessel model for the pulmonary cirulation ('pul').\n model (cvbtk Model): Model object (e.g. LeftVentricleModel or BiventricleModel).\n results (cvbtk.Dataset): Dataset for the results.\n inputs (dict): Dictionary with inputs.\n heart_type (str): Either 'LeftVentricle' or 'Biventricle'.\n solver (optionally): cvbtk Volume solver.\n dir_out (str, optionally): Output directory.\n \"\"\"\n if heart_type is None:\n # Deduct type of model for the heart from inputs.\n heart_type = check_heart_type_from_inputs(inputs)\n\n # ------------------------------------------------------------------------ #\n # Set up the simulation loop. #\n # ------------------------------------------------------------------------ #\n dt = inputs['time']['dt']\n t0 = inputs['time']['t0']\n t1 = inputs['time']['t1']\n\n phase = inputs['state']['phase']\n cycle = inputs['state']['cycle']\n t_cycle = inputs['state']['t_cycle']\n t_active_stress = inputs['state']['t_active_stress']\n\n t = t0\n\n fiber_reorientation = True if inputs['model']['fiber_reorientation']['ncycles_reorient'] > 0 else False\n\n if heart_type == 'Biventricle':\n # Create the output data files.\n write_data_biv(t, t_cycle, phase, cycle, wk, model, 0, 0, results, new=True, dir_out=dir_out,\n save_fiber_vector=fiber_reorientation)\n\n # Create the volume solver to solve the system if not already given.\n if solver is None:\n solver = VolumeSolverBiV(**inputs['volume_solver'])\n\n elif heart_type == 'LeftVentricle':\n # Create the output data files.\n write_data_lv(t, t_cycle, phase, cycle, wk, model, 0, 0, results, new=True, dir_out=dir_out,\n save_fiber_vector=fiber_reorientation)\n\n # Create the volume solver to solve the system. #\n if solver is None:\n solver = VolumeSolver(**inputs['volume_solver'])\n\n # ------------------------------------------------------------------------ #\n # The time loop is below. #\n # ------------------------------------------------------------------------ #\n while t < t1:\n # -------------------------------------------------------------------- #\n # t = n #\n # t = n #\n # -------------------------------------------------------------------- #\n # Store a copy/backup of the state values and unknowns at t = n:\n u_array = model.u.vector().get_local()()\n u_old_array = model.u_old.vector().get_local()()\n ls_old_array = model.active_stress.ls_old.vector().get_local()()\n\n if isinstance(model.active_stress, ArtsKerckhoffsActiveStress):\n lc_old_array = model.active_stress.lc_old.vector().get_local()()\n else:\n lc_old_array = None\n\n if fiber_reorientation:\n ef_old_array, es_old_array, en_old_array = [_.to_array(None) for _ in model.geometry.fiber_vectors()]\n else:\n ef_old_array, es_old_array, en_old_array = None, None, None\n\n dt_old = model.dt*1\n activation_time_old = t_active_stress\n\n # Define this boolean, to be able to force to disable fiber reorientation per timestep\n # if it fails. At the start of a timestep, do not disable.\n disable_reorientation = False\n\n # -------------------------------------------------------------------- #\n # timestep #\n # -------------------------------------------------------------------- #\n try_again = True\n while try_again:\n # By default do not try again, assuming the simulation does not fail.\n # If it fails in the end with fiber reorientation enabled,\n # we reset this bool to True and retry without fiber reorientation.\n # This retrying with disabling fiber reorientation may not be needed anymore,\n # it was used to make older simulations run. In retro-sepct, those simulations\n # failed in the first place due to a problem with fiber vector definition.\n # Now, the fiber vectors are fixed and this retrying option may be redundant.\n try_again = False\n\n # Since it's possible for the FEM solver to fail, it's better if we\n # make the rest of the time-loop its own function so that we can take\n # advantage of Python's try/except construct.\n # The idea is if the solution fails, then we'll reset u, ls, lc, etc.,\n # lower the dt, and call the time-step routine again.\n try:\n # Attempt to solve.\n if heart_type == 'Biventricle':\n accuracy = timestep_biv(t_active_stress, dt, cycle, wk, model, solver, inputs['total_volume'],\n fiber_reorientation, disable_reorientation=disable_reorientation)\n elif heart_type == 'LeftVentricle':\n accuracy = timestep_lv(t_active_stress, dt, cycle, wk, model, solver,\n fiber_reorientation, disable_reorientation=disable_reorientation)\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n # Update time states after successful solutions.\n t += dt\n t_cycle += dt\n t_active_stress += dt\n\n except RuntimeError as error_detail:\n print_once('Except RuntimeError: {}'.format(error_detail))\n print_once('Failed to solve. Halving dt and re-attempting...')\n # Reset values from backup:\n reset_model_state(model, dt_old, activation_time_old, u_array, u_old_array, ls_old_array, lc_old_array,\n ef_old_array, es_old_array, en_old_array)\n\n # Re-attempt to solve.\n try:\n # Attempt to solve.\n if heart_type == 'Biventricle':\n accuracy = timestep_biv(t_active_stress, 0.5*dt, cycle, wk, model, solver, inputs['total_volume'],\n fiber_reorientation, disable_reorientation=disable_reorientation)\n elif heart_type == 'LeftVentricle':\n accuracy = timestep_lv(t_active_stress, 0.5*dt, cycle, wk, model, solver,\n fiber_reorientation, disable_reorientation=disable_reorientation)\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n # Update time states after successful solutions.\n t += 0.5*dt\n t_cycle += 0.5*dt\n t_active_stress += 0.5*dt\n\n except RuntimeError as error_detail:\n print_once('Except RuntimeError: {}'.format(error_detail))\n print_once('Failed to solve. Halving dt again and re-attempting...')\n # Reset values from backup:\n reset_model_state(model, dt_old, activation_time_old, u_array, u_old_array, ls_old_array,\n lc_old_array, ef_old_array, es_old_array, en_old_array)\n\n # Re-attempt to solve.\n try:\n # Attempt to solve.\n if heart_type == 'Biventricle':\n accuracy = timestep_biv(t_active_stress, 0.25*dt, cycle, wk, model, solver,\n inputs['total_volume'],\n fiber_reorientation, disable_reorientation=disable_reorientation)\n elif heart_type == 'LeftVentricle':\n accuracy = timestep_lv(t_active_stress, 0.25*dt, cycle, wk, model, solver,\n fiber_reorientation, disable_reorientation=disable_reorientation)\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n # Update time states after successful solutions.\n t += 0.25*dt\n t_cycle += 0.25*dt\n t_active_stress += 0.25*dt\n\n except RuntimeError as error_detail:\n print_once('Except RuntimeError: {}'.format(error_detail))\n if fiber_reorientation and not disable_reorientation:\n # Disable reorientation and try again.\n # Reset values from backup:\n reset_model_state(model, dt_old, activation_time_old, u_array, u_old_array, ls_old_array,\n lc_old_array, ef_old_array, es_old_array, en_old_array)\n\n try_again = True\n disable_reorientation = True\n print_once('Simulation failed. Trying without fiber reorientation.')\n else:\n raise RuntimeError('Simulation failed.')\n\n # -------------------------------------------------------------------- #\n # t = n + 1 #\n # -------------------------------------------------------------------- #\n # Check what the new phases are.\n phase_old = phase\n if heart_type == 'Biventricle':\n phase = get_phase_dc(model.pressure_old, wk['sys'].pressure, wk['pul'].pressure, model.pressure)\n elif heart_type == 'LeftVentricle':\n phase = {'lv': get_phase(model.pressure_old, wk['sys'].pressure, model.pressure)}\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n # Increment cycle count if needed.\n if phase['lv'] == 1 and phase_old['lv'] == 4:\n cycle += 1\n t_cycle = 0.0\n\n # For output file.\n new = True\n\n else:\n # For output file.\n new = False\n\n # Append selected data to the file records.\n est = solver.iteration()\n if heart_type == 'Biventricle':\n write_data_biv(t, t_cycle, phase, cycle, wk, model, est, accuracy, results, new=new, dir_out=dir_out,\n save_fiber_vector=fiber_reorientation)\n\n # Print some state information about the completed timestep:\n if MPI.rank(mpi_comm_world()) == 0:\n msg = ('*** [Cycle {}/{} - Phase LV = {}/4 - Phase RV = {}/4]:'\n ' t = {} ms, t_cycle = {} ms,'\n ' p_lv = {:5.2f} kPa, V_lv = {:6.2f} ml'\n ' p_rv = {:5.2f} kPa, V_rv = {:6.2f} ml')\n print(msg.format(cycle, inputs['number_of_cycles'], phase['lv'], phase['rv'],\n t, t_cycle,\n model.pressure['lv'], model.volume['lv'],\n model.pressure['rv'], model.volume['rv']))\n\n elif heart_type == 'LeftVentricle':\n write_data_lv(t, t_cycle, phase, cycle, wk, model, est, accuracy, results, new=new, dir_out=dir_out,\n save_fiber_vector=fiber_reorientation)\n\n # Print some state information about the completed timestep:\n if MPI.rank(mpi_comm_world()) == 0:\n msg = ('*** [Cycle {}/{} - Phase = {}/4]:'\n ' t = {} ms, t_cycle = {} ms,'\n ' p_lv = {:5.2f} kPa, V_lv = {:6.2f} ml')\n print(msg.format(cycle, inputs['number_of_cycles'], phase['lv'],\n t, t_cycle,\n model.pressure['lv'], model.volume['lv']))\n else:\n raise ValueError('Unknown heart_type \"{}\".'.format(heart_type))\n\n # Check if the active stress's internal time needs to be reset. (Based on LV phase).\n if phase['lv'] < 3 and t_active_stress >= inputs['time']['tc']:\n t_active_stress = t_active_stress - inputs['time']['tc']\n\n # Exit if maximum cycles reached:\n if cycle > inputs['number_of_cycles']:\n if MPI.rank(mpi_comm_world()) == 0:\n print('Maximum number of cycles simulated!')\n break\n\n\ndef timestep_biv(t_active_stress, dt, cycle, wk_dict, biv, solver, total_volume, fiber_reorientation,\n disable_reorientation=False):\n \"\"\"\n Routine for a timestep for biventricular simulations.\n \"\"\"\n # Extract windkessel objects.\n wk_sys = wk_dict['sys']\n wk_pul = wk_dict['pul']\n\n # -------------------------------------------------------------------- #\n # t = n #\n # -------------------------------------------------------------------- #\n # Store a copy/backup of the state values and unknowns at t = n:\n v_old_sys = wk_sys.volume\n q_old_sys = wk_sys.flowrate\n\n v_old_pul = wk_pul.volume\n q_old_pul = wk_pul.flowrate\n\n vbiv_old = biv.volume\n u_array = biv.u.vector().get_local()()\n u_old_array = biv.u_old.vector().get_local()()\n\n # Update the old ls (and lc) values with most recently computed values.\n biv.active_stress.upkeep()\n\n # -------------------------------------------------------------------- #\n # time increment #\n # -------------------------------------------------------------------- #\n biv.dt = dt\n biv.active_stress.activation_time = t_active_stress + dt\n\n # -------------------------------------------------------------------- #\n # t = n + 1 #\n # -------------------------------------------------------------------- #\n # Compute the new ventricular volumes and solve for the pressures.\n vlv_new = vbiv_old['lv'] + dt*(q_old_pul['ven'] - q_old_sys['art'] - q_old_sys.get('lvad', 0))\n vrv_new = vbiv_old['rv'] + dt*(q_old_sys['ven'] - q_old_pul['art'])\n v_target = {'lv': vlv_new,\n 'rv': vrv_new}\n\n # Compute new fibers in case of fiber reorientation.\n if fiber_reorientation and not disable_reorientation:\n t_fr = time.time()\n biv.reorient_fibers(cycle)\n print_once('Fibers reoriented in {} s.'.format(time.time() - t_fr))\n\n # Estimate new displacement field.\n # biv.u = biv.estimate_displacement()\n\n print_once('Target volume: {}'.format(v_target))\n\n # Solve to determine pressure.\n pbiv_new, vbiv_new, accuracy, _ = solver.solve(biv, v_target)\n\n # Save.\n biv.pressure = pbiv_new\n biv.volume = vbiv_new\n\n # Update u_old with the values of u at t = n.\n biv.u_old = u_array\n biv.u_old_old = u_old_array\n\n # Compute the new windkessel model state:\n # Compute the new volumes with a simple forward Euler scheme:\n vart_new_sys = v_old_sys['art'] + dt*(q_old_sys['art'] - q_old_sys['per'] + q_old_sys.get('lvad', 0))\n vart_new_pul = v_old_pul['art'] + dt*(q_old_pul['art'] - q_old_pul['per'])\n vven_new_pul = v_old_pul['ven'] + dt*(q_old_pul['per'] - q_old_pul['ven'])\n vven_new_sys = total_volume - vlv_new - vart_new_sys - vrv_new - vart_new_pul - vven_new_pul \\\n - wk_sys.volume.get('lvad', 0)\n wk_sys.volume = {'art': vart_new_sys, 'ven': vven_new_sys}\n wk_pul.volume = {'art': vart_new_pul, 'ven': vven_new_pul}\n\n # Compute new pressures from new volumes.\n wk_sys.pressure = wk_sys.compute_pressure()\n wk_pul.pressure = wk_pul.compute_pressure()\n\n # Compute new flowrates from new pressures.\n # Systemic wk\n p_boundary_sys = {'in': biv.pressure['lv'],\n 'out': biv.pressure['rv']}\n q_new_sys = wk_sys.compute_flowrate(p_boundary_sys)\n wk_sys.flowrate = q_new_sys\n\n # Pulmonary wk\n p_boundary_pul = {'in': biv.pressure['rv'],\n 'out': biv.pressure['lv']}\n q_new_pul = wk_pul.compute_flowrate(p_boundary_pul)\n wk_pul.flowrate = q_new_pul\n\n return accuracy\n\n\ndef timestep_lv(t_active_stress, dt, cycle, wk_dict, lv, solver, fiber_reorientation, disable_reorientation=False):\n \"\"\"\n Routine for a timestep for left ventricular simulations.\n \"\"\"\n # Extract windkessel model.\n wk = wk_dict['sys']\n\n # -------------------------------------------------------------------- #\n # t = n #\n # -------------------------------------------------------------------- #\n # Store a copy/backup of the state values and unknowns at t = n:\n v_old = wk.volume\n q_old = wk.flowrate\n vlv_old = lv.volume\n u_array = lv.u.vector().get_local()()\n u_old_array = lv.u_old.vector().get_local()()\n\n # Update the old ls (and lc) values with most recently computed values.\n lv.active_stress.upkeep()\n\n # -------------------------------------------------------------------- #\n # time increment #\n # -------------------------------------------------------------------- #\n lv.dt = dt\n lv.active_stress.activation_time = t_active_stress + dt\n\n # -------------------------------------------------------------------- #\n # t = n + 1 #\n # -------------------------------------------------------------------- #\n # Compute the new LV volume and solve for the LV pressure.\n v_target = vlv_old['lv'] + dt*(q_old['mv'] - q_old['ao'] - q_old.get('lvad', 0))\n\n # Compute new fibers in case of fiber reorientation.\n if fiber_reorientation and not disable_reorientation:\n t_fr = time.time()\n lv.reorient_fibers(cycle)\n print_once('Fibers reoriented in {} s.'.format(time.time() - t_fr))\n\n # Estimate new displacement field.\n # lv.u = lv.estimate_displacement()\n\n # Solve to determine pressure.\n plv_new, vlv_new, accuracy, _ = solver.solve(lv, v_target)\n\n # Save.\n lv.volume = {'lv': vlv_new}\n lv.pressure = {'lv': plv_new}\n\n # Update u_old with the values of u at t = n.\n lv.u_old = u_array\n lv.u_old_old = u_old_array\n\n # Compute the new windkessel model state:\n # Compute the new volumes with a simple forward Euler scheme:\n vart_new = v_old['art'] + dt*(q_old['ao'] - q_old['per'] + q_old.get('lvad', 0))\n vven_new = wk.parameters['total_volume'] - vart_new - vlv_new - wk.volume.get('lvad', 0)\n wk.volume = {'art': vart_new, 'ven': vven_new}\n\n # Compute new pressures from new volumes .\n wk.pressure = wk.compute_pressure(wk.volume)\n\n # Compute new flowrates from new pressures.\n wk.flowrate = wk.compute_flowrate(wk.pressure, lv.pressure)\n\n return accuracy\n\n\ndef write_data_biv(t, t_cycle, phase, cycle, wk_dict, biv, est, accuracy, results, new=False, dir_out='.',\n save_fiber_vector=False):\n \"\"\"\n Helper function to write data to the HDF5 and CSV records for biventricular simulations.\n \"\"\"\n\n hdf5_filename = os.path.join(dir_out, 'results_cycle_{}.hdf5'.format(cycle))\n\n vector_number = save_model_state_to_hdf5(biv, hdf5_filename, t, new, save_fiber_vector)\n\n # Extract windkessel objects.\n wk_sys = wk_dict['sys']\n wk_pul = wk_dict['pul']\n\n data_timestep = {\n 'time': t,\n 't_cycle': t_cycle,\n 't_act': float(biv.active_stress.activation_time),\n\n 'cycle': cycle,\n 'phase_s': phase['lv'],\n 'phase_p': phase['rv'],\n\n 'pcav_s': biv.pressure['lv'],\n 'vcav_s': biv.volume['lv'],\n\n 'vart_s': wk_sys.volume['art'],\n 'vven_s': wk_sys.volume['ven'],\n\n 'part_s': wk_sys.pressure['art'],\n 'pven_s': wk_sys.pressure['ven'],\n\n 'qart_s': wk_sys.flowrate['art']*1000,\n 'qven_s': wk_sys.flowrate['ven']*1000,\n 'qper_s': wk_sys.flowrate['per']*1000,\n\n 'pcav_p': biv.pressure['rv'],\n 'vcav_p': biv.volume['rv'],\n\n 'vart_p': wk_pul.volume['art'],\n 'vven_p': wk_pul.volume['ven'],\n\n 'part_p': wk_pul.pressure['art'],\n 'pven_p': wk_pul.pressure['ven'],\n\n 'qart_p': wk_pul.flowrate['art']*1000,\n 'qven_p': wk_pul.flowrate['ven']*1000,\n 'qper_p': wk_pul.flowrate['per']*1000,\n\n 'est': est,\n 'accuracy': accuracy,\n 'vector_number': vector_number}\n\n if 'qlvad' in results.keys():\n data_timestep['qlvad'] = wk_sys.flowrate['lvad']*1000\n\n results.append(**data_timestep)\n\n # Save the CSV data file.\n if MPI.rank(mpi_comm_world()) == 0:\n results.save(os.path.join(dir_out, 'results.csv'))\n\n\ndef write_data_lv(t, t_cycle, phase, cycle, wk_dict, lv, est, acc, results, new=False, dir_out='.',\n save_fiber_vector=False):\n \"\"\"\n Helper function to write data to the HDF5 and CSV records for left ventricular simulations.\n \"\"\"\n\n hdf5_filename = os.path.join(dir_out, 'results_cycle_{}.hdf5'.format(cycle))\n\n vector_number = save_model_state_to_hdf5(lv, hdf5_filename, t, new, save_fiber_vector)\n\n # Extract windkessel object.\n wk = wk_dict['sys']\n\n data_timestep = {'time': t,\n 't_cycle': t_cycle,\n 't_act': float(lv.active_stress.activation_time),\n\n 'cycle': cycle,\n 'phase': phase['lv'],\n\n 'part': wk.pressure['art'],\n 'pven': wk.pressure['ven'],\n 'plv': lv.pressure['lv'],\n\n 'vart': wk.volume['art'],\n 'vven': wk.volume['ven'],\n 'vlv': lv.volume['lv'],\n\n 'qao': wk.flowrate['ao']*1000,\n 'qmv': wk.flowrate['mv']*1000,\n 'qper': wk.flowrate['per']*1000,\n\n 'est': est,\n 'accuracy': acc,\n 'vector_number': vector_number}\n\n if 'qlvad' in results.keys():\n data_timestep['qlvad'] = wk.flowrate['lvad']*1000\n\n # This one only appends data to the record in memory.\n results.append(**data_timestep)\n\n # Save the CSV data file.\n if MPI.rank(mpi_comm_world()) == 0:\n results.save(os.path.join(dir_out, 'results.csv'))\n","sub_path":"cvbtk/routines_new.py","file_name":"routines_new.py","file_ext":"py","file_size_in_byte":57845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"534507130","text":"#!/usr/bin/python\n\n# Import Adafruit Motor HAT Library\nfrom Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor\n# Import additional libraries that support MotorHAT\nimport time\nimport atexit\n\n# create a default MotorHAT object, no changes to I2C address or frequency\nmh = Adafruit_MotorHAT(addr=0x60)\nlmotor = mh.getMotor(1)\nrmotor = mh.getMotor(2)\n\n\n# recommended for auto-disabling motors on shutdown!\ndef turnOffMotors():\n mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE)\n mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE)\n\n\natexit.register(turnOffMotors)\n\n\n# Complete this function so:\n# 1. values in the range 1 to 32768 make the motor spin forward faster\n# 2. values in the range -1 to -32768 make the motor spin backward faster\n# 3. any value equal to 0 makes the motor BRAKE.\n# 4. any values less than -32768 and greater than 32768 use the max speed\ndef runMotor(motor, speed):\n \"\"\" motor - the motor object to control.\n speed - a number from -32768 (reverse) to 32768 (forward) \"\"\"\n\n print(\"Running motor\")\n\n motorSpeed = int(speed / 128.501960784313725)\n print(motorSpeed)\n\n if(motorSpeed < 0):\n movement = Adafruit_MotorHAT.BACKWARD\n motorSpeed = motorSpeed * -1\n else:\n movement = Adafruit_MotorHAT.FORWARD\n\n if(motorSpeed > 255):\n motorSpeed = 255\n\n print(\"Speed is \" + str(motorSpeed))\n\n if(motorSpeed == 0):\n motor.run(Adafruit_MotorHAT.RELEASE)\n if(motorSpeed > 0):\n motor.run(movement)\n if(motorSpeed < 0):\n motor.run(movement)\n\n motor.setSpeed(motorSpeed)\n return\n\n\nwhile True:\n rightValue = int(raw_input(\"What should the right wheel value be?\"))\n leftValue = int(raw_input(\"What should the left wheel value be?\"))\n\n print(\"Running with right value \" + str(rightValue))\n print(\"Running with left value \" + str(leftValue))\n\n runMotor(lmotor, leftValue)\n runMotor(rmotor, rightValue)\n\n time.sleep(2)\n\n runMotor(lmotor, 0)\n runMotor(rmotor, 0)\n","sub_path":"archive/driveStraightAnswer.py","file_name":"driveStraightAnswer.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"1595818","text":"import configparser\nimport json\nimport time\nfrom telethon.errors import SessionPasswordNeededError\nfrom telethon import TelegramClient, events, sync\nfrom telethon.tl.functions.messages import (GetHistoryRequest)\nfrom telethon.tl.types import (\nPeerChannel\n)\nimport firebase_admin\nfrom firebase_admin import credentials, firestore\n\n# Firebase setup\ncred = credentials.Certificate(\"../../../keys/serviceAccountKey.json\")\nfirebase_admin.initialize_app(cred)\ndb = firestore.client()\n\n# Telegram Auth\ntelegramKeys = open(\"../../../keys/telegramKeys.json\")\ndata = json.load(telegramKeys)\n\napi_id = data['api_id']\napi_hash = data['api_hash']\n\n# Here you define the target channel that you want to listen to:\nuser_input_channel = data['portal_channel']\n\n# Not sure if 'anon' is the correct here\nclient = TelegramClient('anon', api_id, api_hash)\n\n# Listen to messages from target channel\n@client.on(events.NewMessage(chats=user_input_channel))\nasync def newMessageListener(event):\n # Get message text\n newMessage = event.message.message\n\n print(newMessage)\n\n postID = 'PortalMasterAccount' + str(int(time.time() * 1000))\n db.collection('posts').document('PortalMasterAccount').collection('userPosts').document(postID).set({\n 'userId': 'PortalMasterAccount',\n 'postId': postID,\n 'post': newMessage,\n 'postImg': None,\n 'postTime': firestore.SERVER_TIMESTAMP,\n 'likeCount': 0,\n 'commentCount': 0\n })\n# await client.forward_messages(entity='me', messages=event.message)\n\nwith client:\n client.run_until_disconnected()","sub_path":"src/helpers/telegramListener/portalMasterListener.py","file_name":"portalMasterListener.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"131386560","text":"import time\nimport numpy as np\n\nimport rospy\nimport roslaunch\nfrom std_srvs.srv import Empty\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Pose\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\nfrom gazebo_msgs.srv import SetModelState\nfrom gazebo_msgs.msg import ModelState\n\nimport gym\nfrom gym.utils import seeding\nfrom gym import utils, spaces\n\nfrom gym_vehicle.envs import gazebo_env\n\n\nclass GazeboCircuitLargeCatvehicleLidarEnv(gazebo_env.GazeboEnv):\n\n def __init__(self):\n # Launch the simulation with the given launchfile name\n gazebo_env.GazeboEnv.__init__(self, \"GazeboCircuitLargeCatvehicleLidar_v0.launch\")\n\n\n self.vel_pub = rospy.Publisher('/catvehicle/cmd_vel', Twist, queue_size=5)\n\n self.unpause = rospy.ServiceProxy('/gazebo/unpause_physics', Empty)\n self.pause = rospy.ServiceProxy('/gazebo/pause_physics', Empty)\n self.reset_proxy = rospy.ServiceProxy('/gazebo/reset_simulation', Empty)\n\n self.action_space = spaces.Discrete(3) #F,L,R\n self.reward_range = (-np.inf, np.inf)\n\n self._seed()\n\n def discretize_observation(self,data,new_ranges):\n discretized_ranges = []\n min_range = 2.0\n done = False\n mod = len(data.ranges)/new_ranges\n for i, item in enumerate(data.ranges):\n if (i%mod==0):\n if data.ranges[i] == float ('Inf') or np.isinf(data.ranges[i]):\n discretized_ranges.append(6)\n elif np.isnan(data.ranges[i]):\n discretized_ranges.append(0)\n else:\n discretized_ranges.append(int(data.ranges[i]))\n if (min_range > data.ranges[i] > 0):\n done = True\n return discretized_ranges,done\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _step(self, action):\n\n rospy.wait_for_service('/gazebo/unpause_physics')\n try:\n self.unpause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/unpause_physics service call failed\")\n\n if action == 0: #FORWARD\n vel_cmd = Twist()\n vel_cmd.linear.x = 2.0\n vel_cmd.angular.z = 0.0\n self.vel_pub.publish(vel_cmd)\n elif action == 1: #LEFT\n vel_cmd = Twist()\n vel_cmd.linear.x = 1.0\n vel_cmd.angular.z = 1.0\n self.vel_pub.publish(vel_cmd)\n elif action == 2: #RIGHT\n vel_cmd = Twist()\n vel_cmd.linear.x = 1.0\n vel_cmd.angular.z = -1.0\n self.vel_pub.publish(vel_cmd)\n\n data = None\n while data is None:\n try:\n data = rospy.wait_for_message('/catvehicle/front_laser_points', LaserScan, timeout=5)\n except:\n pass\n\n rospy.wait_for_service('/gazebo/pause_physics')\n try:\n #resp_pause = pause.call()\n self.pause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/pause_physics service call failed\")\n\n state,done = self.discretize_observation(data,5)\n\n if not done:\n if action == 0:\n reward = 5\n else:\n reward = 1\n else:\n reward = -200\n\n return state, reward, done, {}\n\n def _reset(self):\n\n # # Resets the state of the environment and returns an initial observation.\n # rospy.wait_for_service('/gazebo/reset_simulation')\n # try:\n # #reset_proxy.call()\n # self.reset_proxy()\n # except (rospy.ServiceException) as e:\n # print (\"/gazebo/reset_simulation service call failed\")\n\n # define initial pose for later use\n pose = Pose()\n pose.position.x = -35.0\n pose.position.y = 35.0\n pose.position.z = 0.0\n pose.orientation.x = 0.0\n pose.orientation.y = 0.0\n pose.orientation.z = 0.0\n pose.orientation.w = 0.0\n\n # set initial model state\n model_state = ModelState()\n model_state.model_name = \"catvehicle\"\n model_state.pose = pose\n\n rospy.wait_for_service('/gazebo/set_model_state')\n try:\n set_model_state = rospy.ServiceProxy('/gazebo/set_model_state', SetModelState)\n ret = set_model_state(model_state)\n print(ret.status_message)\n except (rospy.ServiceException) as e:\n print(\"Service \\'set_model_state\\' call failed: %s\" % e)\n\n rospy.wait_for_service('/gazebo/pause_physics')\n try:\n #resp_pause = pause.call()\n self.pause()\n except (rospy.ServiceException) as e:\n print(\"/gazebo/pause_physics service call failed\")\n\n # Unpause simulation to make observation\n rospy.wait_for_service('/gazebo/unpause_physics')\n try:\n #resp_pause = pause.call()\n self.unpause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/unpause_physics service call failed\")\n\n #read laser data\n data = None\n while data is None:\n try:\n data = rospy.wait_for_message('/catvehicle/front_laser_points', LaserScan, timeout=5)\n except:\n pass\n\n state = self.discretize_observation(data,5)\n\n return state\n","sub_path":"gym-vehicle/gym_vehicle/envs/catvehicle/gazebo_circuit_large_catvehicle_lidar.py","file_name":"gazebo_circuit_large_catvehicle_lidar.py","file_ext":"py","file_size_in_byte":5430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"590965162","text":"from os.path import dirname\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils.translation import ugettext as _\n\nfrom cms.models.pluginmodel import CMSPlugin\n\n\nclass Carousel(CMSPlugin):\n domid = models.CharField(max_length=50, verbose_name=_('Name'))\n interval = models.IntegerField(default=5000)\n INDICATOR_CHOICES = (\n (0, 'Default', ),\n (1, 'Thumbnails', ),\n )\n indicator = models.IntegerField(choices=INDICATOR_CHOICES, default=0)\n\n @property\n def indicator_template(self):\n if 'filer' in settings.INSTALLED_APPS:\n THUMBNAILS_TEMPLATE = 'easy_thumbnails.inc.html'\n else:\n THUMBNAILS_TEMPLATE = 'thumbnails.inc.html'\n\n INDICATOR_TEMPLATES = {\n 0: 'default.inc.html',\n 1: THUMBNAILS_TEMPLATE,\n }\n return 'cmsplugin_bootstrap_carousel/inc/indicator_{}'.format(INDICATOR_TEMPLATES[self.indicator])\n\n def copy_relations(self, oldinstance):\n for item in oldinstance.carouselitem_set.all():\n item.pk = None\n item.carousel = self\n item.save()\n\n def __unicode__(self):\n return self.domid\n\n\nif 'filer' in settings.INSTALLED_APPS:\n execfile(dirname(__file__)+\"/models_filer.py\")\nelse:\n execfile(dirname(__file__)+\"/models_default.py\")\n","sub_path":"cmsplugin_bootstrap_carousel/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"559733252","text":"from selenium import webdriver\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n#import pandas as pd\nimport pymysql\nimport datetime\n\ndriver = webdriver.Chrome('C:/Users/multicampus/Downloads/chromedriver_win32/chromedriver')\ndriver.implicitly_wait(3)\ndriver.get('https://sports.news.naver.com/esports/schedule/index.nhn?year=2020&leagueCode=ck_2020_spring&month=02&category=lol')\nhtml = driver.page_source\nsoup = BeautifulSoup(html, 'html.parser')\ndb=pymysql.connect(\"localhost\",\"ssafy\",\"ssafy\",\"forchannel\",charset=\"utf8\")\ncursor = db.cursor()\n# print(soup)\nday=[]\ntime=[]\nleft_team=[]\nright_team=[]\nplace=[]\ncontent=[]\ndata_result=soup.find('tbody',{'id':'_monthlyScheduleList'}).findAll('tr')\nfor tr_data in data_result:\n if tr_data.find('em')!=None:\n day_tmp=tr_data.find('em')\n if tr_data.find('td',{'class':'time'})==None:\n continue\n day.append(str(day_tmp).replace('', '').replace('',''))\n time.append(str(tr_data.find('td',{'class':'time'})).replace('\\n', '').replace('\\n',''))\n place.append(str(tr_data.find('td',{'class':'game_content'})).replace('\\n', '').replace('\\n',''))\n content.append(tr_data.find('td',{'class':'season'}).span.text)\n left_team.append(str(tr_data.find('span',{'class':'team_left'}).find('span',{'class':'name'})).replace('', '').replace('',''))\n right_team.append(str(tr_data.find('span',{'class':'team_right'}).find('span',{'class':'name'})).replace('', '').replace('',''))\ndt=[]\nfor i in range(len(day)):\n dt.append(datetime.datetime(2020,2,int(day[i].split('.')[1]),int(time[i].split(':')[0]),int(time[i].split(':')[1]),0,0))\n#값 넣을때 년/월을 중요하게 할 것!\ndata=[]\nfor i in range(len(day)):\n data.append((dt[i],dt[i]+datetime.timedelta(hours=3),left_team[i]+\" vs \"+right_team[i],place[i],content[i],3,datetime.datetime.now(),datetime.datetime.now()))\nprint(data)\nquery=\"\"\"insert into schedules(sdate,edate,title,place,contents,ch_no,created_date,modified_date) values (%s,%s,%s,%s,%s,%s,%s,%s)\"\"\"\ncursor.executemany(query, tuple(data))\ndb.commit()","sub_path":"Shalendar/소스코드/Back-End/crawling/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"27783431","text":"# Evaluate an agent on a maze task\n\ndef evaluator(a,m,steps):\n b = []\n for s in range(steps):\n a.sense(m)\n a.sensors\n a.brain.activation\n #print a.brain.numHidden\n #print a.brain.weights\n b.append(a.sensors[:])\n a.act(m)\n if m.found_goal():\n return b,1\n #elif m.stuck:\n # return b,0\n return b,0\n \n \n","sub_path":"exps/maze_eval.py","file_name":"maze_eval.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"113494741","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 21 16:10:09 2018\n\n@author: alkj\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\ndef fingerprint_co_value(df):\n \"\"\"get dict of company values\"\"\"\n\n val_dict = df.set_index('fingerprints_name')['capital_value'].to_dict()\n\n\n return {k:v for k, v in val_dict.items() if v}\n\ndef value_per_share(company_owners, val_dict):\n \"\"\"calc the value of the company per number of shareholders\"\"\"\n num_owners = {k:len(v) for k, v in company_owners.items() if v}\n num_owners = {k:v for k, v in num_owners.items() if k in val_dict.keys()}\n\n value_per_share = {k:val_dict.get(k, 0) / num_owners.get(k, 1) for\n k, v in company_owners.items()}\n\n return {k:v for k, v in value_per_share.items() if v > 0}\n\n\ndef owned_company_dict(centralities):\n\n centralities = centralities.fillna('')\n two_more_comp = centralities[centralities.loc[:, 'CompaniesOwned'].str.contains(',')]\n one_comp = centralities.loc[~centralities.index.isin(two_more_comp.index)]\n\n owned_one = one_comp.loc[:, 'CompaniesOwned'].to_dict()\n\n owned_two_more = \\\n two_more_comp.loc[:, 'CompaniesOwned'].str.split(', ').to_dict()\n\n owned_two_more = {k:tuple(x.strip(\"'\") for x in v) for\n k, v in owned_two_more.items()}\n owned_two_more = {k:tuple(x.strip(\"'\") for x in v) for\n k, v in owned_two_more.items()}\n\n owned_companies = {**owned_one, **owned_two_more}\n owned_companies = {k.strip('\"'):v for k, v in owned_companies.items()}\n\n return owned_companies\n\ndef calc_total_per_owner(centralities, value_per_share):\n \"\"\"centralities frame\"\"\"\n\n\n owned_companies = owned_company_dict(centralities)\n\n tot_val_per_owner = {}\n\n for k, v in owned_companies.items():\n tot_val_per_owner[k] = sum(value_per_share.get(x, 0) for x in v)\n\n return {k:v for k, v in tot_val_per_owner.items() if v > 0}\n\ndef map_vals_per_shareholder(df, centralities, company_owners):\n\n val_dict = fingerprint_co_value(df)\n val_per_share = value_per_share(company_owners, val_dict)\n tot_val_per_owner = calc_total_per_owner(centralities, val_per_share)\n\n centralities.index.name = 'owner'\n centralities = centralities.reset_index()\n centralities['total_value_by_shareholder'] = \\\n centralities['owner'].map(tot_val_per_owner)\n centralities = centralities.set_index('owner')\n\n centralities.loc[centralities.loc[:, 'NoCompanies'] == ''] = \\\n centralities.loc[centralities.loc[:, 'NoCompanies'] == 0]\n centralities.loc[centralities.loc[:, 'total_value_by_shareholder'] == ''] = \\\n centralities.loc[centralities.loc[:, 'total_value_by_shareholder'] == np.nan]\n\n return centralities\n\ndef create_year_frame(df, centralities):\n\n finger_name_year = df.set_index('fingerprints_name')['year'].astype(int).to_dict()\n\n finger_name_location = df.set_index('fingerprints_name')['location'].to_dict()\n\n owned_companies = owned_company_dict(centralities)\n\n owner_year = {}\n for k, v in owned_companies.items():\n owner_year[k] = tuple(finger_name_year.get(x, 0) for x in v)\n\n owner_location = {}\n for k, v in owned_companies.items():\n owner_location[k] = tuple(finger_name_location.get(x, '') for x in v)\n\n\n out_frame1 = pd.DataFrame.from_dict(owner_year, orient='index')\n out_frame1 = out_frame1.stack().reset_index(level=1)\n\n out_frame2 = pd.DataFrame.from_dict(owner_location, orient='index')\n out_frame2 = out_frame2.stack().reset_index(level=1)\n\n\n return out_frame1, out_frame2\n\n\n\n","sub_path":"AddValueCentralitiesAndTimeDistribution.py","file_name":"AddValueCentralitiesAndTimeDistribution.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"514676217","text":"'''\nAn alternative to fiddling with Jupyter notebooks.\nRun experiments with repeated trials at one specific hyperparameter configuration,\nand store the output statistics to pickle files for later visualization.\nIn every case, we perform both upstream meta-learning and downstream training\non separate network instances with transferred rules.\nCreated by Basile Van Hoorick, December 2020.\n'''\n\n# Library imports.\nimport argparse\nimport datetime\nimport pickle\nimport shutil\nimport sys\n\n# Repository imports.\nfrom eval_util import *\n\n\n# https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\n# Process arguments.\nparser = argparse.ArgumentParser()\n\n# General network architecture.\nparser.add_argument('--model', default='table_prepost', type=str,\n help='Type of architecture and rule to use (rnn / '\n 'table_prepost / table_prepostcount / table_prepostpercent / table_postcount / '\n 'reg_oneprepost / reg_oneprepostall / reg_onepostall / reg_allpostall / ff) '\n '(default: rnn).')\nparser.add_argument('--use_graph_rule', default=True, type=str2bool,\n help='Meta-learn and use plasticity rules for hidden layers instead of '\n 'backprop (default: True).')\nparser.add_argument('--use_output_rule', default=True, type=str2bool,\n help='Meta-learn and use plasticity rules for output layer instead of '\n 'backprop (default: True).')\nparser.add_argument('--num_hidden_layers', default=2, type=int,\n help='Number of hidden layers for FF, or T (= rounds + 1) for RNN '\n '(default: 2).')\nparser.add_argument('--hidden_width', default=100, type=int,\n help='Width of every hidden layer (or number of vertices in graph for RNN) '\n '(default: 100).')\nparser.add_argument('--conn_prob', default=0.5, type=float,\n help='Probability of synapse existence between every pair of eligible neurons '\n '(default: 0.5).')\nparser.add_argument('--proj_cap', default=50, type=int,\n help='Upper bound number of firing neurons at every hidden layer '\n '(or time step) to this value; recommended = width // 2 (default: 50).')\nparser.add_argument('--universal', default=True, type=str2bool,\n help='Use universal plasticity rule instead of per-later specialized ones. '\n '(default: False).')\n\n# Dataset and dimensionality.\nparser.add_argument('--dataset_up', default='halfspace', type=str,\n help='Meta-learning dataset name (halfspace / relu / mnist) '\n '(default: halfspace).')\nparser.add_argument('--dataset_down', default='halfspace', type=str,\n help='Downstream task dataset name (halfspace / relu / mnist) '\n '(default: halfspace).')\nparser.add_argument('--n_up', default=10, type=int,\n help='Upstream dataset size (a.k.a. dimensionality of input layer) '\n '(default: 10).')\nparser.add_argument('--n_down', default=20, type=int,\n help='Downstream dataset size (a.k.a. dimensionality of input layer) '\n '(default: 20).')\nparser.add_argument('--m_up', default=2, type=int,\n help='Upstream label count (a.k.a. dimensionality of output layer) '\n '(default: 2).')\nparser.add_argument('--m_down', default=2, type=int,\n help='Downstream label count (a.k.a. dimensionality of output layer) '\n '(default: 2).')\nparser.add_argument('--data_size', default=10000, type=int,\n help='Total number of elements in halfspace or relu dataset (default: 10000). '\n 'Note that the train/test split after generation is 0.75.')\n\n# Training and loss.\nparser.add_argument('--num_runs', default=5, type=int,\n help='Number of times to repeat the experiment for more reliable statistics. '\n '(default: 5).')\nparser.add_argument('--num_rule_epochs', default=10, type=int,\n help='Number of upstream outer epochs. '\n '(default: 10).')\nparser.add_argument('--num_epochs_upstream', default=1, type=int,\n help='Number of upstream inner epochs. '\n '(default: 1).')\nparser.add_argument('--num_epochs_downstream', default=1, type=int,\n help='Number of downstream epochs. '\n '(default: 1).')\nparser.add_argument('--batch_size', default=100, type=int,\n help='Mini-batch size at all times. '\n '(default: 100).')\nparser.add_argument('--learn_rate', default=1e-2, type=float,\n help='Learning rate at all times. '\n '(default: 1e-2).')\nparser.add_argument('--vanilla', default=False, type=str2bool,\n help='Discard rule options and train everything with regular backprop '\n '(default: False).')\nparser.add_argument('--downstream_backprop', default=True, type=str2bool,\n help='Train with gradient descent and backpropagation on the downstream '\n 'network instance (NOTE: not supported by RNN) (default: True).')\nparser.add_argument('--upstream_only', default=False, type=str2bool,\n help='If True, meta-learn only and ignore downstream task training.')\n\n# Miscellaneous.\nparser.add_argument('--ignore_if_exist', default=True, type=str2bool,\n help='If True, do not run experiment if the results file already exists.')\nparser.add_argument('--use_gpu', default=False, type=str2bool,\n help='If True, try to use CUDA on an NVIDIA GPU.')\nparser.add_argument('--store_rules', default=False, type=str2bool,\n help='If True, store meta-learned plasticity rules in numpy format to the results directory.')\n\n\ndef _create_table_rules(args):\n if args.model == 'table_prepost':\n if args.universal:\n hl_rules = TableRule_PrePost()\n else:\n hl_rules = [TableRule_PrePost() for _ in range(args.num_hidden_layers - 1)]\n output_rule = TableRule_PrePost()\n\n elif args.model == 'table_prepostcount':\n if args.universal:\n hl_rules = TableRule_PrePostCount()\n else:\n hl_rules = [TableRule_PrePostCount() for _ in range(args.num_hidden_layers - 1)]\n output_rule = TableRule_PrePostCount()\n\n elif args.model == 'table_prepostpercent':\n if args.universal:\n hl_rules = TableRule_PrePostPercent()\n else:\n hl_rules = [TableRule_PrePostPercent() for _ in range(args.num_hidden_layers - 1)]\n output_rule = TableRule_PrePostPercent()\n\n elif args.model == 'table_postcount':\n if args.universal:\n hl_rules = TableRule_PostCount()\n else:\n hl_rules = [TableRule_PostCount() for _ in range(args.num_hidden_layers - 1)]\n output_rule = TableRule_PostCount()\n\n else:\n raise ValueError('Unknown model / table rule type:', args.model)\n\n # Discard rules that are not needed.\n if not args.use_graph_rule:\n hl_rules = None\n if not args.use_output_rule:\n output_rule = None\n\n return hl_rules, output_rule\n\n\ndef _create_regression_rules(args):\n if args.model == 'reg_oneprepost':\n if args.universal:\n hl_rules = OneBetaANNRule_PrePost()\n else:\n hl_rules = [OneBetaANNRule_PrePost() for _ in range(args.num_hidden_layers - 1)]\n output_rule = OneBetaANNRule_PrePost()\n\n elif args.model == 'reg_oneprepostall':\n if args.universal:\n hl_rules = OneBetaANNRule_PrePostAll()\n else:\n hl_rules = [OneBetaANNRule_PrePostAll() for _ in range(args.num_hidden_layers - 1)]\n output_rule = OneBetaANNRule_PrePostAll()\n\n elif args.model == 'reg_onepostall':\n if args.universal:\n hl_rules = OneBetaANNRule_PostAll()\n else:\n hl_rules = [OneBetaANNRule_PostAll() for _ in range(args.num_hidden_layers - 1)]\n output_rule = OneBetaANNRule_PostAll()\n\n elif args.model == 'reg_allpostall':\n if args.universal:\n hl_rules = AllBetasANNRule_PostAll()\n else:\n hl_rules = [AllBetasANNRule_PostAll() for _ in range(args.num_hidden_layers - 1)]\n output_rule = AllBetasANNRule_PostAll()\n\n else:\n raise ValueError('Unknown model / regression rule type:', args.model)\n\n # Discard rules that are not needed.\n if not args.use_graph_rule:\n hl_rules = None\n if not args.use_output_rule:\n output_rule = None\n\n return hl_rules, output_rule\n\n\ndef _create_brain_factories(args, opts_up, opts_down, scheme):\n rounds = args.num_hidden_layers - 1\n\n if args.model == 'rnn':\n # Graph RNN from paper.\n\n def brain_up_fact():\n model = LocalNet(args.n_up, args.m_up, args.hidden_width, args.conn_prob,\n args.proj_cap, rounds, options=opts_up, update_scheme=scheme)\n if args.use_gpu:\n model.cuda()\n return model\n\n def brain_down_fact():\n model = LocalNet(args.n_down, args.m_down, args.hidden_width, args.conn_prob,\n args.proj_cap, rounds, options=opts_down, update_scheme=scheme)\n if args.use_gpu:\n model.cuda()\n return model\n\n else:\n # Feed-forward neural networks.\n\n if 'table_' in args.model:\n # Feed-forward neural networks with table-based plasticity rules.\n def rule_fact(): return _create_table_rules(args)\n\n elif 'reg_' in args.model:\n # Feed-forward neural networks with small-ANN-based plasticity rules.\n def rule_fact(): return _create_regression_rules(args)\n\n else:\n raise ValueError('Unknown model / rule type:', args.model)\n\n def brain_up_fact():\n hl_rules, output_rule = rule_fact()\n model = FFLocalNet(\n args.n_up, args.m_up, args.num_hidden_layers, args.hidden_width,\n args.conn_prob, args.proj_cap, hl_rules=hl_rules, output_rule=output_rule,\n options=opts_up, update_scheme=scheme, use_gpu=args.use_gpu)\n if args.use_gpu:\n model.cuda()\n return model\n\n def brain_down_fact():\n hl_rules, output_rule = rule_fact()\n model = FFLocalNet(\n args.n_down, args.m_down, args.num_hidden_layers, args.hidden_width,\n args.conn_prob, args.proj_cap, hl_rules=hl_rules, output_rule=output_rule,\n options=opts_down, update_scheme=scheme, use_gpu=args.use_gpu)\n if args.use_gpu:\n model.cuda()\n return model\n\n return brain_up_fact, brain_down_fact\n\n\ndef main(args):\n\n if args.use_gpu:\n torch.set_default_tensor_type(torch.cuda.FloatTensor)\n\n # Correct invalid or irrelevant parameters.\n args.model = args.model.lower()\n if args.num_hidden_layers == 1 and args.use_graph_rule:\n print('===> WARNING: Forcing use_graph_rule to False because num_hidden_layers is 1!')\n args.use_graph_rule = False\n if args.model == 'rnn' and args.downstream_backprop:\n print('===> WARNING: Forcing downstream_backprop to False because model is rnn!')\n args.downstream_backprop = False\n \n if args.dataset_up == 'mnist':\n args.n_up = 28 * 28\n if args.dataset_down == 'mnist':\n args.n_down = 28 * 28\n \n if args.vanilla:\n print('===> NOTE: Vanilla is enabled, so we do not care about rules, '\n 'and only the FF versus RNN distinction matters.')\n args.downstream_backprop = False\n if args.model != 'rnn':\n print('===> Renaming model parameter to ff because it is not rnn.')\n args.model = 'ff'\n if args.upstream_only:\n raise ValueError('Vanilla GD is downstream-only by nature, so enabling upstream_only does not make sense.')\n if args.store_rules:\n raise ValueError('Vanilla GD does not have plasticity rules, so cannot store them.')\n\n if args.upstream_only:\n args.downstream_backprop = False\n\n # Construct experiment tag for results file name.\n exp_tag = args.model\n if not args.vanilla:\n if args.use_graph_rule:\n exp_tag += '_gr'\n if args.use_output_rule:\n exp_tag += '_or'\n exp_tag += f'_nhl{args.num_hidden_layers}'\n exp_tag += f'_hw{args.hidden_width}'\n exp_tag += f'_cp{args.conn_prob:.1f}'\n exp_tag += f'_pc{args.proj_cap}'\n if args.universal:\n exp_tag += '_uni'\n if not args.vanilla:\n exp_tag += f'_dup{args.dataset_up}'\n exp_tag += f'_nup{args.n_up}'\n exp_tag += f'_mup{args.m_up}'\n exp_tag += f'_nre{args.num_rule_epochs}'\n exp_tag += f'_neu{args.num_epochs_upstream}'\n exp_tag += f'_ddo{args.dataset_down}'\n exp_tag += f'_ndo{args.n_down}'\n exp_tag += f'_mdo{args.m_down}'\n exp_tag += f'_ds{args.data_size}'\n exp_tag += f'_runs{args.num_runs}'\n exp_tag += f'_ned{args.num_epochs_downstream}'\n exp_tag += f'_bs{args.batch_size}'\n exp_tag += f'_lr{args.learn_rate:.3f}'\n if args.vanilla:\n exp_tag += f'_van'\n if args.downstream_backprop:\n exp_tag += f'_dsbp'\n if args.upstream_only:\n exp_tag += f'_upo'\n print('Experiment tag:', exp_tag)\n\n # Get destination file path for results.\n stats_dst_path = results_filepath(exp_tag + '.p')\n if os.path.isfile(stats_dst_path) and args.ignore_if_exist:\n print('===> Already exists! Skipping...')\n sys.exit(0)\n rules_dst_path = rules_filepath(exp_tag + '_rules.p')\n\n # Get meta-learning and training options.\n opts_up = Options(gd_input=True,\n use_graph_rule=args.use_graph_rule,\n gd_graph_rule=args.use_graph_rule,\n use_output_rule=args.use_output_rule,\n gd_output_rule=args.use_output_rule,\n gd_output=not(args.use_output_rule))\n opts_down = Options(gd_input=True,\n use_graph_rule=args.use_graph_rule,\n gd_graph_rule=False, # Not meta-trainable anymore!\n use_output_rule=args.use_output_rule,\n gd_output_rule=False, # Not meta-trainable anymore!\n gd_output=not(args.use_output_rule))\n\n # Get weight update scheme.\n # Deviates from paper (works for FF but not for RNN).\n scheme_ff = UpdateScheme(cross_entropy_loss=True,\n mse_loss=False,\n update_misclassified_only=False,\n update_all_edges=True)\n # Same as paper (works for RNN but not for FF).\n scheme_rnn = UpdateScheme(cross_entropy_loss=True,\n mse_loss=False,\n update_misclassified_only=True,\n update_all_edges=False)\n if args.model == 'rnn':\n print('Model is RNN so selected update scheme will have:')\n print('update_misclassified_only = True')\n print('update_all_edges = False')\n scheme = scheme_rnn\n else:\n print('Model is FF so selected update scheme will have:')\n print('update_misclassified_only = False')\n print('update_all_edges = True')\n scheme = scheme_ff\n\n if not args.vanilla:\n\n # Instantiate brain factories.\n brain_fact_up, brain_fact_down = _create_brain_factories(args, opts_up, opts_down, scheme)\n min_upstream_acc = 0.4 if args.model in ['table_postcount', 'reg_onepostall'] else 0.7\n\n # Start evaluation.\n eval_returned = evaluate_up_down(\n brain_fact_up, brain_fact_down, args.n_up, args.n_down,\n dataset_up=args.dataset_up, dataset_down=args.dataset_down,\n downstream_backprop=args.downstream_backprop,\n num_runs=args.num_runs, num_rule_epochs=args.num_rule_epochs,\n num_epochs_upstream=args.num_epochs_upstream,\n num_epochs_downstream=args.num_epochs_downstream,\n num_downstream_subruns=2,\n min_upstream_acc=min_upstream_acc,\n batch_size=args.batch_size, learn_rate=args.learn_rate,\n data_size=args.data_size, relu_k=1000,\n use_gpu=args.use_gpu, upstream_only=args.upstream_only,\n return_upstream_brains=args.store_rules)\n if args.store_rules:\n (stats_up, stats_down), upstream_brains = eval_returned\n else:\n (stats_up, stats_down) = eval_returned\n\n else:\n\n # Instantiate brain directly.\n if args.model == 'rnn':\n def brain_fact(): return BrainNet(\n n=args.n_down, m=args.m_down, num_v=args.hidden_width, cap=args.proj_cap,\n p=args.conn_prob, rounds=args.num_hidden_layers-1, full_gd=True)\n elif args.model == 'ff':\n def brain_fact(): return FFBrainNet(\n n=args.n_down, m=args.m_down, l=args.num_hidden_layers, w=args.hidden_width,\n p=args.conn_prob, cap=args.proj_cap, full_gd=True)\n else:\n raise ValueError('Unknown model type:', args.model)\n multi_stats = evaluate_vanilla(\n brain_fact, args.n_down, dataset=args.dataset_down,\n num_runs=args.num_runs, num_epochs=args.num_epochs_downstream,\n batch_size=args.batch_size, learn_rate=args.learn_rate,\n data_size=args.data_size, relu_k=1000,\n use_gpu=args.use_gpu)\n stats_up, stats_down = None, multi_stats\n\n # Store all stats.\n with open(stats_dst_path, 'wb') as f:\n pickle.dump((stats_up, stats_down), f)\n print('Stored all stats to:', stats_dst_path)\n\n # Store rules if desired.\n if args.store_rules:\n all_rules = []\n for network in upstream_brains:\n try:\n hidden_rule = network.get_hidden_layer_rule()\n except:\n print('No (single) hidden rule available!')\n hidden_rule = None\n try:\n output_rule = network.get_output_rule()\n except:\n print('No output rule available!')\n output_rule = None\n all_rules.append((hidden_rule, output_rule))\n with open(rules_dst_path, 'wb') as f:\n pickle.dump(all_rules, f)\n print('Stored all rules to:', rules_dst_path)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n main(args)\n","sub_path":"BrainNet/run_eval.py","file_name":"run_eval.py","file_ext":"py","file_size_in_byte":19085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"150065348","text":"import random\nimport sys\n\nclass GuessingGame:\n\n def __init__(self, low = 1, high = 99):\n self.__low = low\n self.__high = high\n self.__magic_number = random.randint(low, high)\n self.__number_of_guesses = 0\n\n def guess(self, guess):\n self.__number_of_guesses += 1\n if guess > self.__magic_number:\n return 1 # is larger => lower\n elif guess < self.__magic_number:\n return -1 # is smaller => higher\n elif guess == self.__magic_number:\n return 0\n\n def get_number_of_guesses(self):\n return self.__number_of_guesses\n\n\nclass PlayGuessingGame:\n\n def __init__(self, low=1, high=99):\n self._low = low\n self._high = high\n self.__game = GuessingGame(low, high)\n\n def guess_input(self):\n return int(input(\"What is your next guess? \"))\n\n def play(self):\n\n print(\"Guess a number between %d and %d\" % (self._low, self._high))\n while True:\n myGuess = self.guess_input()\n\n result = self.__game.guess(myGuess);\n\n if result == 1:\n print(\"lower ...\")\n elif result == -1:\n print(\"higher ...\")\n elif result == 0:\n print(\"YEAAAH! You guessed it in {} guesses\".format(self.__game.get_number_of_guesses()))\n break\n\n\nclass AutoPlayGuessingGame:\n\n def __init__(self, low = 1, high = 99, verbose = True):\n self._low = low\n self._high = high\n self.__game = GuessingGame(low, high)\n self.__verbose = verbose\n\n def guess(self):\n return self._low + (self._high - self._low) // 2\n\n def play(self):\n\n while True:\n myGuess = self.guess()\n if self.__verbose: print(myGuess)\n \n result = self.__game.guess(myGuess);\n\n if result == 1:\n self._high = myGuess - 1\n elif result == -1:\n self._low = myGuess + 1\n elif result == 0:\n if self.__verbose: print(\"YEAAAH! You guessed it in {} guesses\".format(self.__game.get_number_of_guesses()))\n break\n\n # if self._highest_possible_number == self._lowest_possible_number:\n # if self.__verbose: print(\"You cheated! I quit!\")\n # sys.exit()\n\n return self.__game.get_number_of_guesses();\n\n\nclass AutoPlayGuessingGameRandom(AutoPlayGuessingGame):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \n def guess(self):\n return random.randint(self._low, self._high)\n\n\n# ----------------------------------------------------------\n\ndef simulation(number_of_games = 3000, auto_play = AutoPlayGuessingGame):\n\n number_of_guesses_counter = dict()\n for i in range(number_of_games):\n\n game = auto_play(verbose = False)\n # game = AutoPlayGuessingGame(verbose = False)\n # game = AutoPlayGuessingGameRandom(verbose = False)\n\n number_of_guesses = game.play()\n number_of_guesses_counter[number_of_guesses] = number_of_guesses_counter.get(number_of_guesses, 0) + 1\n\n for guess, freq in sorted(number_of_guesses_counter.items(), key=lambda item: item[0]):\n freqperc = freq / number_of_games * 100\n print(\"%3d %s %.1f%%\" % (guess, \"\\u2588\" * int(freqperc), freqperc))\n\n\nif __name__ == '__main__':\n\n # game = PlayGuessingGame()\n\n # game = AutoPlayGuessingGame()\n # game = AutoPlayGuessingGameRandom()\n\n # game.play()\n\n\n #simulation()\n simulation(auto_play = AutoPlayGuessingGame)\n # simulation(auto_play = AutoPlayGuessingGameRandom)\n","sub_path":"guessing-game-oo.py","file_name":"guessing-game-oo.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"95253869","text":"'''\nCreated on Jul 19, 2014\n\n@author: kasimsert\n'''\n\nimport os\nimport time\n\nsource=['/Users/kasimsert/Documents/python']\ntarget='/Users/kasimsert/Documents/pythonBackup'\n\ntarget = target+os.sep+time.strftime('%Y%m%d%H%M%S')+'.zip'\n\nif not os.path.exists(target):\n os.mkdir(target)\n print('target dir %s created' % target)\n \nzip_command = 'zip -r {0} -b {1}'.format(target, ' '.join(source))\n\nprint('zip command is %s ' % zip_command)\n\nprint('zip started..')\n\nif os.system(zip_command) == 0:\n print('zip succedded')\nelse:\n print('error')\n","sub_path":"Backup.py","file_name":"Backup.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"417190298","text":"from timeit import default_timer as timer\n\n\ndef fit_classifier(model, x, y):\n model.fit(x, y)\n return model\n\n\ndef measure_classifiers_runtime_train_perf(classifier_list, x, y):\n runtime_results = []\n repeat = 5\n\n for model in classifier_list:\n time_spent = 0\n for i in range(repeat):\n start = timer()\n fit_classifier(model, x, y)\n end = timer()\n time_spent += end - start\n runtime_results.append(time_spent / repeat)\n\n return runtime_results\n\n\ndef measure_classifiers_runtime_eval_perf(classifier_list, x):\n runtime_results = []\n repeat = 5\n for model in classifier_list:\n time_spent = 0\n for _ in range(repeat):\n start = timer()\n model.predict(x)\n end = timer()\n time_spent += end - start\n runtime_results.append(time_spent / repeat)\n\n return runtime_results","sub_path":"ML assignment 1/ModelPerformance.py","file_name":"ModelPerformance.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"408634161","text":"from flask import Flask, request\r\nfrom flask_restful import Resource, Api, reqparse\r\nfrom bson.json_util import dumps\r\nimport pymongo\r\nfrom flask_jwt import JWT, jwt_required\r\n#from security import identity, authenticate\r\nimport json\r\nfrom config import mycolu\r\n\r\nclass User(Resource):\r\n \r\n def get(self, username):\r\n try:\r\n user = list(mycolu.find({\"username\":username}))\r\n if user:\r\n return dumps(user), 200\r\n else:\r\n return None, 404\r\n except Exception as e:\r\n return {\"error\": str(e)}, 400\r\n\r\n #@jwt_required()\r\n def post(self, username): \r\n try:\r\n request_data = request.get_json()\r\n new_user = {\r\n \"username\": request_data[\"username\"],\r\n \"password\": request_data[\"password\"],\r\n \"email\": request_data[\"email\"],\r\n \"role\": request_data[\"role\"],\r\n \"product\": request_data[\"product\"]\r\n }\r\n mycolu.insert_one(new_user)\r\n return dumps(new_user), 201\r\n except Exception as e:\r\n return {\"error\": str(e)}, 400\r\n \r\n #@jwt_required()\r\n def delete(self, username):\r\n try:\r\n user = mycolu.find_one_and_delete({\"username\": username})\r\n if user:\r\n return {\"message\": \"User deleted.\"}, 200\r\n else:\r\n return {\"message\": \"User with this name not found.\"}, 404\r\n except Exception as e:\r\n return {\"error\": str(e)}, 400\r\n\r\nclass UserList(Resource):\r\n def get(self):\r\n try:\r\n users = list(mycolu.find())\r\n if users:\r\n return dumps(users), 200\r\n else:\r\n return None, 404\r\n except Exception as e:\r\n return dumps({\"error\": str(e)})","sub_path":"users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"549746806","text":"customer = {\n \"name\": \"John Smith\",\n \"age\": 30,\n \"is_verified\": True\n}\n\nprint(customer[\"name\"])\nprint(customer.get(\"Name\", \"Matt\"))\n\"\"\"\ndoesn't shout an error even if the key is missing in dict. Instead it returns defaul val\"Matt\"\n\"\"\"\n\ncustomer[\"birthday\"] = \"01.01.2001\" # Setting new key:value pair\nprint(customer[\"birthday\"])\n\ndigits = {\n 1: \"one\",\n 2: \"two\",\n 3: \"three\",\n 4: \"four\",\n 5: \"five\",\n 6: \"six\",\n 7: \"seven\",\n 8: \"eight\",\n 9: \"nine\",\n 0: \"zero\"\n}\nphone_number = input(\"Provide your phone number\")\nfor digit in phone_number:\n print(digits[int(digit)], end= \" \")\n","sub_path":"Python_6h/Dicts.py","file_name":"Dicts.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"351237036","text":"class Employee():\n\t# This is a class variable\n\tpay_raise = 0.20\n\n\t# This is an instance variable\n\tdef __init__(self, first_name, last_name, pay):\n\t\tself.first_name = first_name\n\t\tself.last_name = last_name\n\t\tself.pay = pay\n\t\tself.full_email = self.last_name+'.'+self.first_name+'@'+'company.com'\n\t\tself.email = self.full_email.lower()\n\n\tdef full_name(self):\n\t\treturn self.first_name+' '+self.last_name\n\n\tdef salary(self):\n\t\tincrement = self.pay * self.pay_raise\n\t\tsalary = self.pay + increment\n\t\treturn salary\n\n# emp1 = Employee('Jack', 'Dorsey', 1000)\n# emp2 = Employee('John', 'Doe', 2000)\n\n# print(emp2.pay)\n# print(emp2.salary())\n\nclass Developer(Employee):\n\n\tdef __init__(self, first_name, last_name, pay, prog_lang):\n\t\tsuper().__init__(first_name, last_name, pay)\n\t\tself.prog_lang = prog_lang\n\n\nd1 = Developer('Shugbomi', 'Adewale', 1000, 'PHP')\nd2 = Developer('Sam', 'Haruna', 1200, 'Python')\n\nprint(d2.salary())\nprint(d2.full_name())","sub_path":"day4/chapter7/employee2.py","file_name":"employee2.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"202044800","text":"# import ROOT\nimport os\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\nimport pprint\nfrom collections import defaultdict\nfrom decimal import Decimal\n\ntry:\n import ROOT\n from ROOT import RooRealVar, RooGaussian, RooChebychev, RooAddPdf, RooArgList, RooArgSet, RooFit, RooAddition\nexcept:\n pass\nimport progressbar\nimport yaml\nimport zfit\nimport zfit.minimizers.baseminimizer\nimport numpy as np\n\nimport zfit_benchmark\n\nzfit.run.numeric_checks = False\nrun_name = \"gpu_tol1_grad_new\"\n\ndef toy_run(n_params, n_gauss, n_toys, toys_nevents, run_zfit, intermediate_result_factory=None):\n # pdf = chebys[0]\n\n # zfit.settings.set_verbosity(10)\n\n performance = {}\n performance[\"column\"] = \"number of events\"\n for nevents in toys_nevents:\n # n_toys = 30 if nevents < 50000 else 10\n\n if run_zfit:\n zfit.run.create_session(reset_graph=True)\n # zfit.sess.close()\n # zfit.sess = tf.Session\n # initial_param_val, obs, pdf = build_pdf(n_gauss, n_params, run_zfit)\n\n lower = -1\n upper = 1\n # create observables\n if run_zfit:\n obs = zfit.Space(\"obs1\", limits=(lower, upper))\n else:\n obs = RooRealVar(\"obs\", \"obs1\", lower, upper)\n ROOT.SetOwnership(obs, False)\n # create parameters\n params = []\n params_initial = []\n mu_lower, mu_upper = 1, 3\n sigma_lower, sigma_upper = 0.5, 2\n # step_size = 0.003\n for i in range(n_params):\n if run_zfit:\n mu = zfit.Parameter(f\"mu_{i}_{nevents}\", np.random.uniform(low=mu_lower, high=mu_upper), mu_lower,\n mu_upper,\n # step_size=step_size\n )\n sigma = zfit.Parameter(f\"sigma_{i}_{nevents}\", np.random.uniform(low=sigma_lower, high=sigma_upper),\n sigma_lower, sigma_upper,\n # step_size=step_size\n )\n else:\n mu_initial = np.random.uniform(mu_lower, mu_upper)\n mu = RooRealVar(f\"mu_{i}_{nevents}\", \"Mean of Gaussian\", mu_initial, mu_lower, mu_upper)\n ROOT.SetOwnership(mu, False)\n sigma_initial = np.random.uniform(mu_lower, mu_upper)\n sigma = RooRealVar(f\"sigma_{i}_{nevents}\", \"Width of Gaussian\", sigma_initial, sigma_lower, sigma_upper)\n ROOT.SetOwnership(sigma, False)\n params_initial.append((mu_initial, sigma_initial))\n params.append((mu, sigma))\n # create pdfs\n pdfs = []\n for i in range(n_gauss):\n mu, sigma = params[i % n_params]\n if run_zfit:\n shifted_mu = mu + 0.3 * i\n shifted_sigma = sigma + 0.1 * i\n pdf = zfit.pdf.Gauss(obs=obs, mu=shifted_mu, sigma=shifted_sigma)\n # from zfit.models.basic import CustomGaussOLD\n # pdf = CustomGaussOLD(obs=obs, mu=shifted_mu, sigma=shifted_sigma)\n # pdf.update_integration_options(mc_sampler=tf.random_uniform)\n else:\n shift1 = RooFit.RooConst(float(0.3 * i))\n shifted_mu = RooAddition(f\"mu_shifted_{i}_{nevents}\", f\"Shifted mu {i}\", RooArgList(mu, shift1))\n shift2 = RooFit.RooConst(float(0.1 * i))\n shifted_sigma = RooAddition(f\"sigma_shifted_{i}_{nevents}\", f\"Shifted sigma {i}\",\n RooArgList(sigma, shift2))\n pdf = RooGaussian(f\"pdf_{i}_{nevents}\", \"Gaussian pdf\", obs, shifted_mu, shifted_sigma)\n ROOT.SetOwnership(pdf, False)\n ROOT.SetOwnership(shift1, False)\n ROOT.SetOwnership(shifted_mu, False)\n ROOT.SetOwnership(shift2, False)\n ROOT.SetOwnership(shifted_sigma, False)\n pdfs.append(pdf)\n initial_param_val = 1 / n_gauss\n fracs = []\n for i in range(n_gauss - 1):\n frac_value = 1 / n_gauss\n lower_value = 0.0001\n upper_value = 1.5 / n_gauss\n if run_zfit:\n frac = zfit.Parameter(f\"frac_{i}\", value=1 / n_gauss, lower_limit=lower_value, upper_limit=upper_value)\n frac.floating = False\n else:\n frac = RooRealVar(f\"frac_{i}_{nevents}\", \"Fraction of a gauss\", frac_value)\n ROOT.SetOwnership(frac, False)\n fracs.append(frac)\n if run_zfit:\n sum_pdf = zfit.pdf.SumPDF(pdfs=pdfs, fracs=fracs)\n # sum_pdf.update_integration_options(mc_sampler=tf.random_uniform)\n\n else:\n sum_pdf = RooAddPdf(f\"sum_pdf_{nevents}\", \"sum of pdfs\", RooArgList(*pdfs), RooArgList(*fracs))\n ROOT.SetOwnership(sum_pdf, False)\n pdf = sum_pdf\n\n # Create dictionary to save fit results\n failed_fits = 0\n successful_fits = 0\n performance[nevents] = {\"success\": [], \"fail\": []}\n\n if run_zfit:\n sampler = pdf.create_sampler(n=nevents, fixed_params=True)\n sampler.set_data_range(obs)\n nll = zfit.loss.UnbinnedNLL(pdf, sampler)\n\n minimizer = zfit.minimize.MinuitMinimizer(zfit.minimizers.baseminimizer.ToyStrategyFail(), verbosity=5,\n minimize_strategy=1)\n # minimizer.minimizer_options['tol'] = 100\n\n # minimizer._use_tfgrad = False\n\n timer = zfit_benchmark.timer.Timer(f\"Toys {nevents}\")\n if run_zfit:\n sampler.resample()\n # with tf.device(\"/device:GPU:0\"):\n jit_scope = tf.contrib.compiler.jit.experimental_jit_scope\n # with jit_scope():\n to_run = [nll.value(), nll.gradients()]\n zfit.run(to_run)\n dependents = pdf.get_dependents()\n else:\n mgr = ROOT.RooMCStudy(pdf, RooArgSet(obs), RooFit.Silence())\n ROOT.SetOwnership(mgr, False)\n run_toystudy = False\n with progressbar.ProgressBar(max_value=n_toys) as bar:\n ident = 0\n with timer:\n if not run_toystudy:\n while successful_fits < n_toys:\n # print(f\"starting run number {len(fitResults)}\")\n if run_zfit:\n sampler.resample()\n\n for param in dependents:\n param.randomize()\n else:\n for (mu, sigma), (mu_val, sigma_val) in zip(params, params_initial):\n mu.setVal(mu_val)\n sigma.setVal(sigma_val)\n\n data = pdf.generate(RooArgSet(obs), nevents)\n\n for mu, sigma in params:\n mu.setVal(np.random.uniform(mu_lower, mu_upper))\n sigma.setVal(np.random.uniform(sigma_lower, sigma_upper))\n\n with timer.child(f\"toy number {successful_fits} {ident}\") as child:\n if run_zfit:\n # sampler.resample()\n\n # with tf.device(\"/device:GPU:0\"):\n minimum = minimizer.minimize(nll)\n # print(minimum.hesse())\n else:\n\n # for mu, sigma in params:\n # mu.setVal(np.random.uniform(mu_lower, mu_upper))\n # sigma.setVal(np.random.uniform(sigma_lower, sigma_upper))\n # for frac in fracs:\n # frac.setVal(np.random.uniform(lower_value, upper_value))\n result = pdf.fitTo(data, RooFit.NumCPU(12), RooFit.Save(True),\n RooFit.Hesse(False), RooFit.Minos(False))\n if ident == 0:\n ident += 1\n continue # warm up run\n if run_zfit:\n if minimum.converged:\n bar.update(successful_fits)\n successful_fits += 1\n fail_or_success = \"success\"\n else:\n child.elapsed = Decimal()\n failed_fits += 1\n fail_or_success = \"fail\"\n else:\n if result.status() == 0:\n bar.update(successful_fits)\n successful_fits += 1\n fail_or_success = \"success\"\n else:\n child.elapsed = Decimal()\n failed_fits += 1\n fail_or_success = \"fail\"\n\n ident += 1\n performance[nevents][fail_or_success].append(float(child.elapsed))\n else:\n\n mgr.generateAndFit(n_toys, nevents)\n performance[nevents][\"success\"].append([float(timer.elapsed) / n_toys for _ in range(n_toys)])\n\n with open(f\"{run_name}tmp.yaml\", \"w\") as f:\n if intermediate_result_factory:\n dump_result = intermediate_result_factory(performance)\n else:\n dump_result = performance.copy()\n dump_result[\"ATTENTION\"] = \"NOT FINISHED\"\n yaml.dump(dump_result, f)\n return performance\n\n\nif __name__ == '__main__':\n import tensorflow as tf\n\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n # sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n config = tf.ConfigProto(intra_op_parallelism_threads=12, inter_op_parallelism_threads=2,\n allow_soft_placement=True)\n #\n sess = tf.Session(config=config)\n zfit.run.sess = sess\n # zfit.run.run_metadata = run_metadata\n # zfit.run.run_options = run_options\n # zfit.settings.set_verbosity(10)\n\n # testing = False\n testing = True\n # run_zfit = False\n run_zfit = True\n n_gauss_max = 9\n n_params_max = n_gauss_max\n # toys_nevents = [2 ** i for i in list(range(7, 18, 2)) + list(range(19, 24, 2))]\n toys_nevents = [2 ** i for i in list(range(7, 22, 2))]\n n_toys = 20\n\n if testing:\n n_gauss_max = 9\n # toys_nevents = [2**23]\n toys_nevents = [2097152]\n n_toys = 30\n results = {}\n results[\"n_toys\"] = n_toys\n results[\"column\"] = \"number of gaussians\"\n just_one = 0\n # for n_gauss in range(2, n_gauss_max + 1):\n # HACK START\n for n_gauss in [n_gauss_max]:\n # HACK END\n\n if n_gauss > n_gauss_max:\n break\n results[n_gauss] = {}\n results[n_gauss][\"column\"] = \"number of free params\"\n # for n_params in (1, n_gauss):\n # for n_params in (1,):\n for n_params in (n_gauss,):\n # HACK START\n # if just_one > 0:\n # break\n # just_one += 1\n # HACK END\n if n_gauss < n_gauss_max and n_params not in (1, n_gauss):\n # HACK START\n pass\n # HACK END\n # continue # only test the parameter scan for full params\n results_copy = results.copy()\n\n\n def intermediate_result_factory(res_tmp):\n results_copy[n_gauss][n_params] = res_tmp\n return results_copy\n\n\n # with tf.device(\"/device:GPU:0\"):\n results[n_gauss][n_params] = toy_run(n_params=n_params, n_gauss=n_gauss,\n n_toys=n_toys, toys_nevents=toys_nevents,\n run_zfit=run_zfit,\n intermediate_result_factory=intermediate_result_factory)\n\n # writer = tf.summary.FileWriter(\"tensorboard_log\", graph=sess.graph)\n # writer.add_run_metadata(run_metadata, \"my_session1\")\n # writer.close()\n pprint.pprint(results)\n with open(f\"{run_name}_{np.random.randint(low=0, high=int(1e1))}.yaml\", \"w\") as f:\n yaml.dump(results, f)\n","sub_path":"toys/gaussians/gaussians.py","file_name":"gaussians.py","file_ext":"py","file_size_in_byte":12525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"347718373","text":"import time\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nimport random\nimport common_functions as cf\n\n################# define functions\ndef weight_variable(shape, given):\n initial = tf.truncated_normal(shape, stddev=0.01)\n return tf.Variable(initial, name = given)\n\ndef bias_variable(shape, given):\n initial = tf.constant(0.0, shape=shape)\n return tf.Variable(initial, name = given)\n\ndef AppCCIm_valid(sess, Im, label, pad_x, pad_y, pad_z):\n Im = np.pad(Im, ((pad_x,pad_x),(pad_y,pad_y),(pad_z,pad_z)), 'constant', constant_values=0)\n label = np.pad(label, ((pad_x,pad_x),(pad_y,pad_y),(pad_z,pad_z)), 'constant', constant_values=0)\n win_x = 2*pad_x + 1\n win_y = 2*pad_y + 1\n win_z = 2*pad_z + 1\n output = np.zeros([Im.shape[0]-win_x+1,Im.shape[1]-win_y+1,Im.shape[2]-win_z+1])\n input_batch = np.zeros([output.size,win_x*win_y*win_z])\n label_batch = np.zeros([output.size,1])\n ind = 0\n for k in range(output.shape[2]):\n for i in range(output.shape[1]):\n for j in range(output.shape[0]):\n input_batch[ind,:] = Im[i:i+win_x,j:j+win_y,k:k+win_z].flatten('F')\n label_batch[ind,0] = label[i+(win_x-1)//2,j+(win_y-1)//2,k+(win_z-1)//2]\n ind = ind + 1\n feed = {x: input_batch, y_: label_batch, keep_prob: 1}\n temp, temp_loss, merged_ = sess.run([y, loss, merged], feed_dict=feed)\n output = temp.reshape(output.shape[0],output.shape[1],output.shape[2], order = 'F')\n return output, temp_loss, merged_\n\n################### parameters\npad_x = 10 # padding in x\npad_y = 10 # padding in y\npad_z = 3 # padding in z\nlearning_rate = 0.1\nkeep_p = 1 # 1 - drop out probability\nbatch_size = 50 # batch size\nmax_train_steps = int(5e6) # maximum number of training steps\nplotting_step = int(1e5) # update of the loss plot \n\n################### paths\ndata_dir = '../../data/L1/'\ntrain_IM_list = ['image_1.tif','image_2.tif','image_3.tif','image_6.tif']\ntrain_label_list = ['label_1.tif','label_2.tif','label_3.tif','label_6.tif']\nvalid_IM_name = 'image_4.tif'\nvalid_label_name = 'label_4.tif'\n\nmodel_dir = '../../data/training_result/'\nfolder_name = 'CC_1'\ncf.createFolder(model_dir + folder_name)\n\n###################\nwin_x = 2*pad_x + 1\nwin_y = 2*pad_y + 1\nwin_z = 2*pad_z + 1\n\n###################\nIM_size_list = [None] * len(train_IM_list)\nfor i in range(len(train_IM_list)):\n phantom_IM, phantom_label = cf.get_data(data_dir+train_IM_list[i],data_dir+train_label_list[i])\n IM_size_list[i] = phantom_IM.size\nN_total = sum(IM_size_list)\nIM_ind = list(range(len(train_IM_list)))\n\n################### creating network\nx = tf.placeholder(tf.float32, [None, win_x*win_y*win_z], name=\"x\")\ny_ = tf.placeholder(tf.float32, [None, 1], name=\"y_\")\nkeep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n\nW1 = weight_variable([win_x*win_y*win_z, 100], \"W1\")\nb1 = bias_variable([100], \"b1\")\n\nact1 = tf.add(tf.matmul(x, W1), b1, name = \"act1\")\nh1 = tf.nn.sigmoid(act1, name=\"h1\")\nh1d = tf.nn.dropout(h1, keep_prob)\n\nW2 = weight_variable([100, 1], \"W2\")\nb2 = bias_variable([1], \"b2\")\n\ny = tf.nn.sigmoid((tf.matmul(h1d, W2) + b2), name=\"y\")\n\nloss = tf.reduce_mean(y_ * -tf.log(y) + (1 - y_) * -tf.log(1 - y))\nmerged = tf.summary.scalar('loss', loss)\n\ntrain_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n\n################### generating validation data\nvalid_IM, valid_label = cf.get_data(data_dir+valid_IM_name,data_dir+valid_label_name)\nvalid_IM = valid_IM[370:498,210:338,21:37]\nvalid_label = valid_label[370:498,210:338,21:37]\n\np_I = plt.figure(1)\nplt.imshow(cf.max_proj(valid_IM), cmap = 'gray')\np_I.show()\nplt.pause(1)\n\np_L = plt.figure(2)\nplt.imshow(cf.max_proj(valid_label), cmap = 'gray')\np_L.show()\nplt.pause(1)\n\nvalid_label = np.pad(valid_label, ((pad_x,pad_x),(pad_y,pad_y),(pad_z,pad_z)), 'constant', constant_values=0)\nvalid_IM = np.pad(valid_IM, ((pad_x,pad_x),(pad_y,pad_y),(pad_z,pad_z)), 'constant', constant_values=0)\n \n################### training \nstart_time = time.time() \n\n# Add ops to save and restore all the variables.\nsaver = tf.train.Saver(max_to_keep = (max_train_steps//plotting_step + 1))\nsess = tf.InteractiveSession()\ntrain_writer = tf.summary.FileWriter( model_dir+folder_name+'/train', sess.graph)\nsess.run(tf.global_variables_initializer())\n\ncurrent_ind = -1\nz = 0\ns = 0\nwhile s < max_train_steps:\n dummy_train = np.zeros([batch_size, win_x*win_y*win_z])\n dummy_label = np.zeros([batch_size,1])\n bi = 0\n while bi < batch_size:\n m = z % N_total\n ind = 0\n while m >= IM_size_list[IM_ind[ind]]:\n m = m - IM_size_list[IM_ind[ind]]\n ind = ind + 1\n if ind != current_ind:\n train_IM, train_label = cf.get_data(data_dir+train_IM_list[IM_ind[ind]],data_dir+train_label_list[IM_ind[ind]])\n train_IM = np.pad(train_IM, ((pad_x,pad_x),(pad_y,pad_y),(pad_z,pad_z)), 'constant', constant_values=0)\n train_label = np.pad(train_label, ((pad_x,pad_x),(pad_y,pad_y),(pad_z,pad_z)), 'constant', constant_values=0)\n current_ind = ind\n pixel_ind = np.arange((train_IM.shape[0] - 2*pad_x)*(train_IM.shape[1] - 2*pad_y)*(train_IM.shape[2] - 2*pad_z))\n random.shuffle(pixel_ind)\n i = pixel_ind[m] // ((train_IM.shape[1] - 2*pad_y)*(train_IM.shape[2] - 2*pad_z))\n j = ( pixel_ind[m] // (train_IM.shape[2] - 2*pad_z) ) % (train_IM.shape[1] - 2*pad_y)\n k = pixel_ind[m] % (train_IM.shape[2] - 2*pad_z)\n if train_label[i+pad_x,j+pad_y,k+pad_z] != 0.5:\n temp_train = train_IM[i:i+win_x,j:j+win_y,k:k+win_z]\n ind_trans = random.randrange(8)\n if ind_trans > 3:\n temp_train = np.flip(temp_train, 0)\n temp_train = np.rot90(temp_train, ind_trans % 4 )\n dummy_train[bi,:] = temp_train.flatten('F')\n dummy_label[bi,0] = train_label[i+win_x//2,j+win_y//2,k+win_z//2]\n bi = bi + 1 \n z = z + 1\n feed={x: dummy_train, y_: dummy_label, keep_prob: keep_p} \n train_step.run(feed_dict=feed)\n s = s + 1\n if s % plotting_step == 0:\n saver.save(sess, model_dir+folder_name+'/model'+str(s))\n train_out, train_loss, summary = AppCCIm_valid(sess, valid_IM, valid_label, pad_x, pad_y, pad_z)\n train_writer.add_summary(summary,s)\n print(\"step %d, training loss: %g\" % (s, train_loss))\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n########### Save session\nsaver.save(sess, model_dir+folder_name+'/model')\nnp.savez(model_dir+folder_name+'/var.npz', pad_x = pad_x, pad_y = pad_y, pad_z = pad_z, keep_p=keep_p, learning_rate = learning_rate, batch_size = batch_size, plotting_step = plotting_step, z = z, s = s)","sub_path":"codes/python/CC_train.py","file_name":"CC_train.py","file_ext":"py","file_size_in_byte":6600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"145466996","text":"\n\ndef test_admin_page(app):\n wd = app.wd\n sidebar = wd.find_element_by_xpath(\"//td[@id='sidebar']\")\n main_button_qty = len(sidebar.find_elements_by_css_selector(\"li#app-\")) # кол-во основных кнопок меню\n for i in range(1, main_button_qty + 1):\n wd.find_element_by_xpath(\"//li[@id='app-'][%s]\" % i).click() # проходим по основным кнопкам #wd.find_element_by_css_selector(\"li#app-:nth-child(%s)\" % i).click()\n app.navigation.is_element_present(\"h1\") # так тоже работает\n sidebar = wd.find_element_by_xpath(\"//td[@id='sidebar']\") # необходимо снова найти sidebar так как после нажатия кнопок страница обновляется\n if len(sidebar.find_elements_by_css_selector(\"[id^=doc-]\")) > 0:\n sub_button_qty = len(sidebar.find_elements_by_css_selector(\"[id^=doc-]\")) # кол-во доп кнопок меню\n for j in range(1, sub_button_qty + 1):\n wd.find_element_by_xpath(\"//*[starts-with(@id,'doc-')][%s]\" % j).click() # проходим по доп кнопкам\n app.navigation.is_element_present(\"h1\")\n\n\n\n\n","sub_path":"Tests/test_admin_page.py","file_name":"test_admin_page.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"579514354","text":"# -*- coding:utf-8 -*-\n\ndef get_index(string,substring):\n length_string = len(string)\n for l in range(length_string):\n if is_in_string(string,substring,l):\n return l\n return -1\n\n\ndef is_in_string(string,substring,l):\n length_string = len(string)\n length_sub = len(substring)\n if (l+length_sub) <= (length_string -1) and string[l:l+length_sub] == substring:\n return True\n else:\n return False\n\ndef main():\n string = \"hello google\"\n sub_string = \"oo\"\n if string == \"\" or sub_string == \"\":\n print(\"000\")\n return 0\n for i in range(len(string)):\n if is_in_string(string,sub_string,i) and get_index(string,sub_string)!= -1:\n index = get_index(string,sub_string)\n return index\n return -2\n\n\nif __name__ == '__main__':\n print(main())\n ","sub_path":"Easy/Python/impl_strStr.py","file_name":"impl_strStr.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"99160606","text":"import json as js\nimport httplib\n\ndef jsonCall(verb, url, data=None):\n print (\"%s on %s with %s\"%(verb, url, data))\n if(url[:7] == 'http://'):\n url = url[7:]\n safe = False\n elif (url[:8] == 'https://'):\n url = url[8:]\n safe = True\n else:\n print('I only handle urls that start with http or https in this snippet, sorry.')\n return\n headers = {'Content-Type': 'application/json'}\n (baseurl, extendedurl) = url.split('/', 1)\n extendedurl = '/' + extendedurl\n conn = httplib.HTTPConnection(baseurl) if not safe else httplib.HTTPSConnection(baseurl)\n if (data is None):\n conn.request(verb, extendedurl, headers=headers)\n else:\n conn.request(verb, extendedurl, js.dumps(data), headers)\n resp = conn.getresponse()\n if (resp.status != 200):\n return ((resp.status, \"Error %d: %s\\n%s\"%(resp.status, resp.reason, bytes.decode(resp.read()))))\n ret = bytes.decode(resp.read())\n if (len(ret) == 0):\n ret = \"null\"\n return (resp.status, js.loads(ret))\n","sub_path":"py/jsonCall/jsonCall.py","file_name":"jsonCall.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"581255642","text":"import os\nimport multiprocessing\n\n\nclass FileOperator2:\n output_dir = os.path.abspath(os.path.join(os.getcwd(), \"PageData\"))\n tar_file_size = 100 * 1024 * 1024\n count = 0\n\n def __init__(self, output_dir=output_dir, tar_file_size=tar_file_size, count=count):\n self.output_dir = output_dir\n self.tar_file_size = tar_file_size\n self.count = count\n\n def write_data(self, mode: str = 'a', data: dict = None):\n if data is None:\n return\n tar_file = os.path.join(self.output_dir, \"%07d.txt\" % self.count)\n file_check(tar_file)\n data_size = os.path.getsize(tar_file)\n while data_size > self.tar_file_size:\n self.count += 1\n tar_file = os.path.join(self.output_dir, \"%07d.txt\" % self.count)\n file_check(tar_file)\n data_size = os.path.getsize(tar_file)\n with open(tar_file, mode, encoding='utf8') as f:\n f.write(\"url:\" + data.get(\"url\") + '\\n')\n f.write(\"title:\" + data.get(\"title\") + '\\n')\n f.write(\"date:\" + data.get(\"date\") + '\\n')\n f.write(\"page_content:\\n\" + data.get(\"page_content\") + \"\\n\")\n print(\"%s has writen one page(url:%s) into file: %s\" % (\n multiprocessing.current_process(), data.get('url'), tar_file))\n\n def write_url(self, mode: str = 'a', url: str = None):\n if url is None:\n return\n tar_file = os.path.join(self.output_dir, \"url_list.txt\")\n file_check(tar_file)\n with open(tar_file, mode, encoding='utf8') as f:\n f.write(url + '\\n')\n print(\"%s has writen one url:%s into url_list file\" % (multiprocessing.current_process, url))\n\n def read_url(self, mode: str = 'r'):\n url_list = []\n tar_file = os.path.join(self.output_dir, \"url_list.txt\")\n if not os.path.exists(tar_file):\n return url_list\n with open(tar_file, mode, encoding='utf8') as f:\n for url in f:\n url_list.append(url)\n return url_list\n\n\ndef file_check(file_path):\n file_dir = os.path.split(file_path)[0]\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n if not os.path.exists(file_path):\n os.system(r'touch %s' % file_path)\n\n\nif __name__ == \"__main__\":\n file_o = FileOperator()\n","sub_path":"file_operator2.py","file_name":"file_operator2.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"446867889","text":"\"\"\"\nYou have two numbers represented by a linked list, where each node contains a single\ndigit. The digits are stored in reverse order, such that the 1's digit is at the head of the list.\nWrite a function that adds the 2 numbers and returns the sum as a linked list.\n\nExample:\n Input: (7->1->6) + (5->9->2). That is 617 + 295\n Output: (2->1->9). That is 912\n\nFollow Up:\n Suppose the digits are are stored in forward order. Repeat the above problem.\n\n Input: (6->1->7) + (2->9->5). That is 617 + 295\n Output: (9->1->2). That is 912\n\"\"\"\n\nimport unittest\n\n\nclass Node(object):\n\n def __init__(self, data):\n self.data = data\n self._next = None\n\n def append_to_tail(self, data):\n n = self\n while n._next is not None:\n n = n._next\n\n n._next = Node(data)\n return n._next\n\n def tolist(self):\n retval = []\n n = self\n while n is not None:\n retval.append(n.data)\n n = n._next\n return retval\n\n\ndef sum_lists(l1, l2):\n n1, n2 = l1, l2\n ll = index = None\n carry = 0\n while n1 is not None or n2 is not None:\n num1 = num2 = 0\n if n1 is not None:\n num1 = n1.data\n n1 = n1._next\n if n2 is not None:\n num2 = n2.data\n n2 = n2._next\n\n the_sum = num1 + num2 + carry\n carry = 1 if the_sum > 9 else 0\n\n node = Node(the_sum % 10)\n if index is None:\n ll = index = node\n else:\n index._next = node\n index = node\n\n return ll\n\n\ndef sum_lists_follow_up(l1, l2):\n pass\n\n\nclass TestSumLists(unittest.TestCase):\n\n def test_sum_lists(self):\n l1 = Node(7)\n l1.append_to_tail(1)\n l1.append_to_tail(6)\n\n l2 = Node(5)\n l2.append_to_tail(9)\n l2.append_to_tail(2)\n self.assertEqual(\n [2, 1, 9],\n sum_lists(l1, l2).tolist()\n )\n\n def test_sum_lists_with_different_size(self):\n l1 = Node(7)\n l1.append_to_tail(1)\n l1.append_to_tail(6)\n\n l2 = Node(1)\n self.assertEqual(\n [8, 1, 6],\n sum_lists(l1, l2).tolist()\n )\n\n def test_sum_lists_follow_up(self):\n l1 = Node(6)\n l1.append_to_tail(1)\n l1.append_to_tail(7)\n\n l2 = Node(2)\n l2.append_to_tail(9)\n l2.append_to_tail(5)\n self.assertEqual(\n [9, 1, 2],\n sum_lists_follow_up(l1, l2)[0].tolist()\n )\n\n def test_sum_lists_follow_up_with_different_size(self):\n l1 = Node(6)\n l1.append_to_tail(1)\n l1.append_to_tail(7)\n\n l2 = Node(1)\n self.assertEqual(\n [6, 1, 8],\n sum_lists_follow_up(l1, l2)[0].tolist()\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cracking_the_coding_interview/q2.5.py","file_name":"q2.5.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"634543361","text":"from __future__ import unicode_literals\nimport scrapy\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\nfrom scrapy.utils.project import get_project_settings\nimport youtube_dl\n\n\nydl = youtube_dl.YoutubeDL({'playlist_items': '1', 'outtmpl': '/downloadedsongs/%(title)s.%(ext)s', 'format': 'mp3', 'audio_format': 'mp3', 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': '192',\n }]})\n\nclass playlist_spider(scrapy.Spider):\n name =\"playlist\"\n\n def __init__(self):\n settings=get_project_settings()\n chrome_options = webdriver.ChromeOptions()\n if settings.get('HEADLESS'):\n chrome_options.add_argument('--headless')\n if settings.get('DOWNLOAD_IMGS'):\n prefs = {\"profile.managed_default_content_settings.images\": 2}\n chrome_options.add_experimental_option(\"prefs\", prefs)\n self.driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)\n \n def start_requests(self):\n \n url = open(\"playlist.txt\", \"r\")\n url = url.read()\n yield scrapy.Request(url=url, callback=self.parse)\n \n def parse(self, response):\n self.driver.get(response.url)\n urls = []\n for (song, artist) in zip(self.driver.find_elements_by_class_name(\"tracklist-name\"), self.driver.find_elements_by_class_name(\"tracklist-row__artist-name-link\")):\n urls.append(self.parse_for_youtube_url(song.text, artist.text))\n\n with ydl:\n ydl.download(urls)\n\n def youtube_parse(self, response):\n print(response.xpath('//h3[@class=\"yt-lockup-title\"]').get())\n \n def parse_for_youtube_url(self, song, artist):\n misc = song + \" \" + artist\n return 'https://www.youtube.com/results?search_query=' + misc.replace(\" \", \"%20\")\n","sub_path":"spotify_playlist_downloader/spiders/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"620945239","text":"import numpy as np\nimport cv2\nimport os\nimport re\nimport pytube\nimport matplotlib.pyplot as plt\n\n# DEFINE SOME CONSTANTS\nVIDEO_FOLDER = \"./video/\"\nFRAMES_FOLDER = \"./frames/\"\nMAX_MOUSE_POINTS = 7\nMAX_POINTS_ROI = 4\nMAX_DANGEROUS_DISTANCE = 150\nMAX_WARNING_DISTANCE = 180\nCOLOR_SAFE = (0,255,0)\nCOLOR_WARNING = (0,255,255)\nCOLOR_DANGEROUS = (0,0,255)\n\n\ndef download_from_youtube(video_url, folder_path, video_name=None):\n '''\n Method used to download video from Youtube\n :param video_url: the url of the video to download\n :param folder_path: the folder path where save the video\n :param video_name: the name to give to the save file\n :return:\n '''\n youtube = pytube.YouTube(video_url)\n video = youtube.streams.first()\n\n video.download(folder_path) # path, where to video download.\n # #if u want to rename the video\n # if not video_name is None:\n # os.rename(folder_path + video.title + \".mp4\", video_name + \".mp4\")\n # return video_name\n return video.title\n\n\ndef get_frame_rate(video_capture):\n '''\n Method that return the FPS of a video\n :param video_capture: the Videocapture object of a video\n :return: the number of FPS\n '''\n FPS = video_capture.get(cv2.CAP_PROP_FPS)\n print(\"frame_rate: \" + str(FPS))\n return FPS\n\n\ndef save_frames_from_video(video_path, max_frames = 750):\n '''\n Method that takes the path of a video, read the video\n and create all the frames of the video, saving them on\n the specific folder of the video inside the frames folder\n :param video_path: path of the input video\n :return: the video name and FPS\n '''\n if not os.path.isfile(video_path):\n IOError(\"File video doesn't exists!\")\n return\n\n # check if exists frames dir, otherwise create it\n if not os.path.isdir(FRAMES_FOLDER):\n os.mkdir(FRAMES_FOLDER)\n\n # take video name to rename save folder\n video_name = get_video_name(video_path)\n\n # define where save the frames and create\n # the folder if not exists yet\n save_path_folder = FRAMES_FOLDER + video_name + \"/\"\n if not os.path.isdir(save_path_folder):\n os.mkdir(save_path_folder)\n\n print(\"Save frames from \" + video_path + \" ...\")\n # capture video\n cap = cv2.VideoCapture(video_path)\n cnt = 0\n\n # check frame rate\n FPS = get_frame_rate(cap)\n\n # Check if video file is opened successfully\n if (cap.isOpened() == False):\n IOError(\"Error opening video stream or file\")\n\n # read first frame\n ret, first_frame = cap.read()\n\n # Read until video is completed\n while (cap.isOpened()):\n\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n if ret == True:\n\n # save each frame to folder\n cv2.imwrite(save_path_folder + str(cnt) + '.png', frame)\n cnt = cnt + 1\n\n if cnt >= max_frames:\n print(\"Done! \" + str(cnt) + \" frames saved in\" + save_path_folder)\n return video_name, FPS\n\n # Break the loop\n else:\n print(\"Done! \" + str(cnt) + \" frames saved in\" + save_path_folder)\n return video_name, FPS\n\n\ndef get_frames(frames_dir):\n '''\n Method that returns from frames_folder passed in input\n the sorted list of frame_names\n :param frames_dir: the path of the frames_dir\n :return: the sorted list of frame_names\n '''\n frames = os.listdir(frames_dir)\n frames.sort(key=lambda f: int(re.sub('\\D', '', f)))\n return frames\n\n\ndef get_video_name(video_path):\n '''\n Method that returns the video name from path\n :param video_path: path of the video\n :return: the video name\n '''\n return video_path.split(\"/\")[-1].split(\".\")[0]\n\n\ndef compute_perspective_transform(corner_points, width, height, image):\n ''' Compute the transformation matrix useful for the bird eye view image\n\t:param corner_points : 4 corner points selected from the image, that indicates the ROI\n\t:param height, width : size of the image\n\treturn : transformation matrix and the transformed image\n\t'''\n # Create an array out of the 4 corner points\n corner_points_array = np.float32(corner_points)\n # Create an array with the parameters (the dimensions) required to build the matrix\n # order is left-bottom, right-bottom, right-top, left-top\n img_params = np.float32([[0, height], [width, height], [width, 0], [0, 0]])\n # Compute and return the transformation matrix\n matrix = cv2.getPerspectiveTransform(corner_points_array, img_params)\n img_transformed = cv2.warpPerspective(image, matrix, (width, height))\n return matrix, img_transformed\n\n\ndef compute_perspective_unit_distances(unit_points, matrix_transformation):\n '''\n Compute the perspective trasformation of the points used to take the right distances.\n Points must be: central, width, height order\n :param unit_points: list of 3 points\n :param matrix_transformation: matrix trasformation used to transform the points\n :return: the distances in horizontal and vertical used to calculates distance between two humans\n through the midpoints\n '''\n # using next 3 points for horizontal and vertical unit length(in this case 180 cm)\n points_distance = np.float32(np.array([unit_points]))\n warped_pt = cv2.perspectiveTransform(points_distance, matrix_transformation)[0]\n\n # since bird eye view has property that all points are equidistant in horizontal and vertical direction.\n # distance_w and distance_h will give us 180 cm distance in both horizontal and vertical directions\n # (how many pixels will be there in 180cm length in horizontal and vertical direction of birds eye view),\n # which we can use to calculate distance between two humans in transformed view or bird eye view\n distance_w = np.sqrt((warped_pt[0][0] - warped_pt[1][0]) ** 2 + (warped_pt[0][1] - warped_pt[1][1]) ** 2)\n distance_h = np.sqrt((warped_pt[0][0] - warped_pt[2][0]) ** 2 + (warped_pt[0][1] - warped_pt[2][1]) ** 2)\n return distance_w, distance_h\n\n\ndef compute_point_perspective_transformation(matrix, list_midpoints):\n ''' Apply the perspective transformation to every ground point which have been detected on the main frame.\n\t:param matrix : the 3x3 matrix\n\t:param list_midpoints : list that contains the points to transform\n\treturn : list containing all the new points\n\t'''\n # Compute the new coordinates of our points\n list_points_to_detect = np.float32(list_midpoints).reshape(-1, 1, 2)\n transformed_points = cv2.perspectiveTransform(list_points_to_detect, matrix)\n # Loop over the points and add them to the list that will be returned\n transformed_points_list = list()\n for i in range(0, transformed_points.shape[0]):\n transformed_points_list.append([transformed_points[i][0][0], transformed_points[i][0][1]])\n return transformed_points_list\n\n\ndef mid_point(person):\n '''\n Method used to return the bottom midpoint of a bbox of a singular person\n :param person: the bbox of the person\n :return: the bottom midpoint (x,y)\n '''\n # get the coordinates\n x1, y1, x2, y2 = person\n # compute bottom center of bbox\n x_mid = int((x1 + x2) / 2)\n y_mid = int(y2)\n mid = (x_mid, y_mid)\n return mid\n\n\ndef calculate_euclidean_distance(p1, p2, distance_w=None, distance_h=None):\n '''\n Method used to calculate euclidean distance between two people represented by bottom midpoints.\n THe method can calculate both the normal euclidean distance if are not turned in input\n the horizontal distance and the vertical distance calculated using the perspective transformation,\n and also the euclidean distance of the midpoints after the transformation through the matrix perspective\n transformation.\n :param p1: first people represented by a midpoint (x1,y1)\n :param p2: second people represented by a midpoint (x1,y1)\n :param distance_w: if is None, calculate euclidean distance over midpoints taken from the frame, otherwise\n calculate distance after perspective transformation of the midpoints on bird eye view\n :param distance_h: if is None, calculate euclidean distance over midpoints taken from the frame, otherwise\n calculate distance after perspective transformation of the midpoints on bird eye view\n :return: the euclidean distance between p1 and p2\n '''\n if distance_h is not None and distance_w is not None:\n h = abs(p2[1] - p1[1])\n w = abs(p2[0] - p1[0])\n\n dis_w = float((w / distance_w) * 180)\n dis_h = float((h / distance_h) * 180)\n\n return int(np.sqrt(((dis_h) ** 2) + ((dis_w) ** 2)))\n else:\n return int(np.sqrt(((p2[1] - p1[1]) ** 2) + ((p2[0] - p1[0]) ** 2)))\n\n\ndef compute_distances(midpoints, distance_w=None, distance_h=None):\n '''\n Method that takes in input a list of all people of a frame (represented by midpoints)\n and calculate for each pair of midpoints, the euclidean distance between us. The method\n creates a list of distance between people where each people is indicated by tuple (index_of_midpoint, distance).\n The method sort the tuples by distances. Is also calculated a list of distance line composed by tuple of\n (index_first_person,index_second_person,distance) and then is sorted also this list.\n :param midpoints: list of midpoints (x1,y1)\n :param distance_w: if is None, calculate euclidean distance over midpoints taken from the frame, otherwise\n calculate distance after perspective transformation of the midpoints on bird eye view\n :param distance_h: if is None, calculate euclidean distance over midpoints taken from the frame, otherwise\n calculate distance after perspective transformation of the midpoints on bird eye view\n :return: a sorted list of distances and a sorted list of distances line.\n '''\n num_people = len(midpoints)\n distances = []\n distancesLine = []\n for i in range(num_people):\n for j in range(i + 1, num_people):\n if i < j:\n dist = calculate_euclidean_distance(midpoints[i], midpoints[j],\n distance_w, distance_h)\n\n # add to list\n distances.append((i, dist))\n distances.append((j, dist))\n distancesLine.append((i, j, dist))\n\n sorted_distances = sorted(distances, key=lambda tup: tup[1])\n sorted_dist_line = sorted(distancesLine, key=lambda tup: tup[2])\n\n return sorted_distances, sorted_dist_line\n\n\ndef return_people_ids(bboxes):\n '''\n Method that takes the bboxes of the people detected\n to check how many people are present in a frame\n and create a list of indices of people.\n :param bboxes: a list of tuple (x1,y1,x2,y2)\n :return: a list of people indices\n '''\n people_ids = [x for x in range(len(bboxes))]\n return people_ids\n\n\ndef check_risks_people(distances, people_ids):\n '''\n Method used to separate people detected in the right sets based on the order of the distances in the list\n turned in input.\n There are three sets: safe,warning,dangerous.\n Each person can be only in one set. If the person has a distance less then the MAX_DANGEROUS_DISTANCE, is placed\n inside the dangerous set, else if the distance is between the MAX_DANGEROUS_DISTANCE and the MAX_WARNING_DISTANCE, is\n paced inside the warning set, otherwise in safe set.\n\n :param distances: a sorted list composed by (index_of_person,distance_between_other_person)\n :param people_ids: a list of the indices of the person\n :return: 3 sets composed by the indices of the people\n '''\n set_safe = set()\n set_warning = set()\n set_dangerous = set()\n\n list_people = people_ids\n\n # if is detected only one person, put directly in safe set\n if len(list_people) == 1:\n set_safe.add(0)\n return set_safe, set_warning, set_dangerous\n\n # otherwise assign each person based on distance in the right set\n for d in distances:\n p, dist = d\n if len(list_people) == 0:\n break\n\n if p in list_people:\n if dist <= MAX_DANGEROUS_DISTANCE:\n set_dangerous.add(p)\n elif dist > MAX_DANGEROUS_DISTANCE and dist <= MAX_WARNING_DISTANCE:\n set_warning.add(p)\n else:\n set_safe.add(p)\n\n list_people.remove(p)\n\n return set_safe, set_warning, set_dangerous\n\n\ndef write_results(file_txt, video_name, FPS, width, height, mouse_points):\n '''\n Method used to save all the information after the trace_ROI operation on the frame.\n :param file_txt: file where write the results\n :param video_name: the name of the video\n :param FPS: the number of Frame per seconds\n :param width: the width of the frame\n :param height: the heigth of the frame\n :param mouse_points: a list of points where the first four points indicate the ROI traced on the frame\n and the last three points indicates the unit distances.\n '''\n # create file .txt and write results\n f = open(file_txt, \"w+\")\n\n f.write(\"video name:\" + video_name + '\\n')\n f.write(\"FPS:\" + str(FPS) + '\\n')\n f.write(\"width:\" + str(width) + '\\n')\n f.write(\"height:\" + str(height) + '\\n')\n f.write(\"points of ROI:\\n\")\n for p in mouse_points[:4]:\n x, y = p\n f.write(str(x) + \",\" + str(y) + \"\\n\")\n\n f.write(\"points of distance:\\n\")\n for p in mouse_points[4:7]:\n x, y = p\n f.write(str(x) + \",\" + str(y) + \"\\n\")\n f.close()\n\n\ndef read_results(file_txt):\n '''\n Method used to read the info of specific video, like the name, the FPS, width,height,\n points of ROI, points of unit distance.\n :param file_txt: file where read the informations\n :return: name of the video, the FPS, width, height, points_of ROI, points of unit distances.\n '''\n b_take_ROI = False\n b_take_distance = False\n points_ROI = []\n points_distance = []\n video_name = \"\"\n FPS = 0.0\n width = 0\n height = 0\n\n with open(file_txt) as fr:\n for line in fr.readlines():\n if \"video_name\" in line:\n video_name = line.split(\":\")[1]\n elif \"FPS:\" in line:\n FPS = float(line.split(\":\")[1])\n elif \"width:\" in line:\n width = int(line.split(\":\")[1])\n elif \"height:\" in line:\n height = int(line.split(\":\")[1])\n elif \"points of ROI:\" in line:\n b_take_ROI = True\n elif \"points of distance:\" in line:\n b_take_ROI = False\n b_take_distance = True\n elif b_take_ROI:\n point = line.split(\",\")\n points_ROI.append([int(point[0]), int(point[1])])\n elif b_take_distance:\n point = line.split(\",\")\n points_distance.append([int(point[0]), int(point[1])])\n\n fr.close()\n return video_name, FPS, width, height, points_ROI, points_distance\n\n\ndef create_video(frames_dir, video_name, FPS):\n '''\n Method that read all the edit frames inside the directory, sort them\n and then create a video.\n :param frames_dir: path of the folder where get the frames\n :param video_name: the name of the video to create\n :param FPS: the number of FPS used to compose the video\n '''\n frames = os.listdir(frames_dir)\n frames.sort(key=lambda f: int(re.sub('\\D', '', f)))\n frame_array = []\n\n for i in range(len(frames)):\n # reading each files\n img = cv2.imread(frames_dir + frames[i])\n height, width, _ = img.shape\n size = (width, height)\n # inserting the frames into an image array\n frame_array.append(img)\n\n out = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), FPS, size)\n\n for i in range(len(frame_array)):\n # writing to a image array\n out.write(frame_array[i])\n out.release()\n\n\ndef resize_and_pad(img, size, pad_color=0):\n '''\n Method used to resize the bird eye view to fit on the final mosaic output.\n :param img: the bird eye image\n :param size: size to set the image resized\n :param pad_color: color used to fill the pad around the image\n :return: the bird eye view image resized\n '''\n h, w = img.shape[:2]\n sh, sw = size\n\n # interpolation method\n if h > sh or w > sw: # shrinking image\n interp = cv2.INTER_AREA\n else: # stretching image\n interp = cv2.INTER_CUBIC\n\n # aspect ratio of image\n aspect = w / h # if on Python 2, you might need to cast as a float: float(w)/h\n\n # compute scaling and pad sizing\n if aspect > 1: # horizontal image\n new_w = sw\n new_h = np.round(new_w / aspect).astype(int)\n pad_vert = (sh - new_h) / 2\n pad_top, pad_bot = np.floor(pad_vert).astype(int), np.ceil(pad_vert).astype(int)\n pad_left, pad_right = 0, 0\n elif aspect < 1: # vertical image\n new_h = sh\n new_w = np.round(new_h * aspect).astype(int)\n pad_horz = (sw - new_w) / 2\n pad_left, pad_right = np.floor(pad_horz).astype(int), np.ceil(pad_horz).astype(int)\n pad_top, pad_bot = 0, 0\n else: # square image\n new_h, new_w = sh, sw\n pad_left, pad_right, pad_top, pad_bot = 0, 0, 0, 0\n\n # set pad color\n if len(img.shape) is 3 and not isinstance(pad_color,(list, tuple, np.ndarray)): # color image but only one color provided\n pad_color = [pad_color] * 3\n\n # scale and pad\n scaled_img = cv2.resize(img, (new_w, new_h), interpolation=interp)\n scaled_img = cv2.copyMakeBorder(scaled_img, pad_top, pad_bot, pad_left, pad_right,\n borderType=cv2.BORDER_CONSTANT, value=pad_color)\n\n return scaled_img\n\n\ndef create_plot_contagion(contagion_map, title, modality=\"h\"):\n '''\n Method used to create a plot of contagion during the video analysis and save it on image.\n The plot is organized in --> x: frames, y: n_of people.\n The plot draw the lines based on the number of people detected in each frame, the number of people in the various\n state divided by colors.\n :param contagion_map: a list that contains a number of tuples composed by (n_people_detected,n_safe,n_low_risk,n_high_risk)\n equal to the number of frames.\n :param title: title to give to the plot and used to save the image.\n :param modality: is possible to compose a string of modality.\n The options are:\n - 'h' --> draw the line of high risk people (red line)\n - 'l' --> draw the line of low risk people (yellow line)\n - 's' --> draw the line of safe people (green line)\n Is possible to create different compositions with options.\n Example --> 'hl' draw lines relative to high risk people and low risk people ( red, yellow lines).\n '''\n plt.style.use('seaborn-whitegrid')\n fig = plt.figure(figsize=[27, 9])\n ax = plt.axes()\n # set info axes\n plt.title(title, fontsize=20)\n plt.xlabel(\"frames\", fontsize=18)\n plt.ylabel(\"n° people\", fontsize=18)\n\n people_detected = []\n safe_people = []\n warning_people = []\n dangerous_people = []\n\n # x are frames\n frames = np.arange(0, len(contagion_map))\n\n # get data from contagion_map\n for f in frames:\n p, s, w, d = contagion_map[f]\n # set in right lists\n people_detected.append(p)\n safe_people.append(s)\n warning_people.append(w)\n dangerous_people.append(d)\n\n # set limits to plot\n plt.xlim(0, len(contagion_map))\n plt.ylim(min(people_detected), max(people_detected) + 2)\n\n # plot based on modality chosen\n plt.plot(frames, people_detected, color='black', linestyle='-', label=\"detected\")\n if 'h' in modality:\n plt.plot(frames, dangerous_people, color=\"red\", linestyle='-', label=\"high-risk\")\n if 'l' in modality:\n plt.plot(frames, warning_people, color=\"yellow\", linestyle='-', label=\"low-risk\")\n if 's' in modality:\n plt.plot(frames, safe_people, color=\"green\", linestyle='-', label=\"safe\")\n\n # set legend and save figure plot\n plt.legend(fontsize=18)\n fig.savefig(title + '.jpg')\n\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":20083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"540447478","text":"from django.forms import ModelForm\r\nfrom app.models import ticket, host_history\r\n\r\nclass problemForm(ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = ticket\r\n\t\tfields = ['title', 'description', 'host', 'category', 'reported_by']\r\n\r\n#reuse the form for ticket history as well, used for input cleaning/validation only\r\nclass descriptionForm(ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = host_history\r\n\t\tfields = ['description']\r\n","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"494000720","text":"import json\nfrom pathlib import PosixPath, Path\n\nfrom .. import settings\n\n\nVERSION = 1\n\nDIRECTORIES = (\n settings.SOURCES_PATH,\n settings.RECIPES_PATH,\n)\n\nCONFIG_FILE = 'config'\nMETADATA_FILE = '.metadata'\n\n\ndef create_directories(directories_names):\n for dir_name in directories_names:\n path = PosixPath(dir_name)\n if not path.is_dir():\n path.mkdir()\n\n\ndef create_file(file_path, content=None):\n path = PosixPath(file_path)\n if not path.exists():\n if content is None:\n path.touch()\n else:\n with path.open('w') as file_object:\n file_object.write(content)\n\n\ndef create_config_file():\n home = Path.home()\n content = json.dumps({\n 'sources_repos_dir': f'{home}/.ct/sources-repos'\n })\n create_file(CONFIG_FILE, f'{content}\\n')\n\n\ndef create_metadata_file(version):\n content = json.dumps({\n 'version': version,\n })\n create_file(METADATA_FILE, f'{content}\\n')\n\n\ndef main():\n create_directories(DIRECTORIES)\n create_config_file(CONFIG_FILE)\n create_metadata_file(VERSION)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ct/commands/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"391521655","text":"# example of calculating the frechet inception distance in Keras\nimport numpy\nimport glob\nimport random\nimport os\nfrom PIL import Image\nfrom numpy import cov\nfrom numpy import trace\nfrom numpy import iscomplexobj\nfrom numpy import asarray\nfrom numpy.random import randint\nfrom scipy.linalg import sqrtm\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\nfrom tensorflow.keras.datasets.mnist import load_data\nfrom skimage.transform import resize\n\n\ndef get_images(paths):\n images = []\n for path in paths:\n img = Image.open(path)\n img = numpy.asarray(img)\n if img.shape[2] == 4:\n img = img[:, :, :3]\n images.append(img)\n images = numpy.array(images)\n return images\n\n\n#calculate frechet inception distance\ndef calculate_fid_activations(model, paths1, paths2):\n\n curr_length = len(paths1)\n\n images_random = randint(0, 255, curr_length * size * size * 3)\n images_random = images_random.reshape((curr_length, size, size, 3))\n images_random = images_random.astype('float32')\n\n images_real = get_images(paths1)\n images_gen = get_images(paths2)\n\n # pre-process images\n images_real = preprocess_input(images_real)\n images_gen = preprocess_input(images_gen)\n images_random = preprocess_input(images_random)\n\n images_real = numpy.array(images_real)\n images_gen = numpy.array(images_gen)\n\n # calculate activations\n act_real = model.predict(images_real)\n act_gen = model.predict(images_gen)\n act_random = model.predict(images_random)\n\n return act_real,act_gen,act_random\n\n\ndef calculate_fid_scores(act1,act2):\n # calculate mean and covariance statistics\n mu1, sigma1 = act1.mean(axis=0), cov(act1, rowvar=False)\n mu2, sigma2 = act2.mean(axis=0), cov(act2, rowvar=False)\n # calculate sum squared difference between means\n ssdiff = numpy.sum((mu1 - mu2)**2.0)\n # calculate sqrt of product between cov\n covmean = sqrtm(sigma1.dot(sigma2))\n # check and correct imaginary numbers from sqrt\n if iscomplexobj(covmean):\n covmean = covmean.real\n # calculate score\n fid = ssdiff + trace(sigma1 + sigma2 - 2.0 * covmean)\n return fid\n\n\nfolder_1 = \"F:/Datasets/DigestPath/safron/Benign/test/3/4096_2000/images\"\nfolder_2 = \"F:/Datasets/DigestPath/safron/Benign/test/3/4096_2000/multiscalegan_output\"\nscale = 0\nsize = 4096\nmax_file_num = 100\nbatch_size = 3\n\npaths1 = glob.glob(os.path.join(folder_1,\"*.png\"))\npaths2 = glob.glob(os.path.join(folder_2,\"*.png\"))\n\npaths1 = random.sample(paths1,max_file_num)\npaths2 = random.sample(paths2,max_file_num)\n\n#paths2 = [x.replace(\"-outputs\",\"\") for x in paths2]\n\n#file_names = list(set(paths1) & set(paths2))\n\nlength = len(paths1)\n\nprint(\"Number of files to be processed: \",length)\n\npaths1_list = [paths1[i:i + batch_size] for i in range(0, length, batch_size)]\npaths2_list = [paths2[i:i + batch_size] for i in range(0, length, batch_size)]\n\n# prepare the inception v3 model\nmodel = InceptionV3(weights='imagenet', include_top=False, pooling='avg', input_shape=(size,size,3))\n\nreal_act_net,gen_act_net,random_act_net = calculate_fid_activations(model,paths1_list[0],paths2_list[0])\n\nfor i in range(1,len(paths1_list)):\n real_act, gen_act, random_act = calculate_fid_activations(model,paths1_list[i],paths2_list[i])\n real_act_net = numpy.concatenate((real_act_net,real_act),axis=0)\n gen_act_net = numpy.concatenate((gen_act_net,gen_act),axis=0)\n random_act_net = numpy.concatenate((random_act_net,random_act),axis=0)\n print(i)\n\nfid = calculate_fid_scores(real_act_net, real_act_net)\nprint('FID (same): %.3f' % fid)\n\nfid = calculate_fid_scores(real_act_net, random_act_net)\nprint('FID (random): %.3f' % fid)\n\nfid = calculate_fid_scores(real_act_net, gen_act_net)\nprint('FID (predicted) : %.3f' % fid)","sub_path":"Assistance/fid_2folders_batch.py","file_name":"fid_2folders_batch.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"346184737","text":"#!/usr/bin/env python\n\"\"\"Tests for the ``utils`` module.\n\nAuthors\n-------\n\n - Lauren Chambers\n\nUse\n---\n\n These tests can be run via the command line (omit the -s to\n suppress verbose output to stdout):\n\n ::\n\n pytest -s test_utils.py\n\"\"\"\n\nimport pytest\n\nfrom jwql.utils.utils import get_config, filename_parser\n\n@pytest.mark.xfail\ndef test_get_config():\n '''Assert that the ``get_config`` function successfuly creates a\n dictionary.\n '''\n settings = get_config()\n assert isinstance(settings, dict)\n\n\ndef test_filename_parser_filename():\n '''Generate a dictionary with parameters from a JWST filename.\n Assert that the dictionary matches what is expected.\n '''\n filename = 'jw00327001001_02101_00002_nrca1_rate.fits'\n filename_dict = filename_parser(filename)\n\n correct_dict = {'activity': '01',\n 'detector': 'nrca1',\n 'exposure_id': '00002',\n 'observation': '001',\n 'parallel_seq_id': '1',\n 'program_id': '00327',\n 'suffix': 'rate',\n 'visit': '001',\n 'visit_group': '02'}\n\n assert filename_dict == correct_dict\n\n\ndef test_filename_parser_filepath():\n '''Generate a dictionary with parameters from a JWST filepath\n (not just the basename). Assert that the dictionary matches what\n is expected.\n '''\n filepath = '/test/dir/to/the/file/jw90002/jw90002001001_02102_00001_nis_rateints.fits'\n filename_dict = filename_parser(filepath)\n\n correct_dict = {'activity': '02',\n 'detector': 'nis',\n 'exposure_id': '00001',\n 'observation': '001',\n 'parallel_seq_id': '1',\n 'program_id': '90002',\n 'suffix': 'rateints',\n 'visit': '001',\n 'visit_group': '02'}\n\n assert filename_dict == correct_dict\n\n\ndef test_filename_parser_nonJWST():\n '''Attempt to generate a file parameter dictionary from a file\n that is not formatted in the JWST naming convention. Ensure the\n appropriate error is raised.\n '''\n with pytest.raises(ValueError,\n match=r'Provided file .+ does not follow JWST naming conventions \\(jw____\\.fits\\)'):\n filename = 'not_a_jwst_file.fits'\n filename_parser(filename)\n","sub_path":"jwql/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"547081046","text":"import cv2\nimport numpy as np\nimport requests\n\nimport pkg_resources\nresource_package = __name__\nclass MAPS:\n \"\"\"List of available maps [Yerevan,Dilijan]\"\"\"\n def __init__(self,mapName='Yerevan',scale = 12000):\n self.mapName = mapName\n if mapName == 'Yerevan':\n resource_path = '/'.join(('YerevanMap.bmp',)) \n Map = pkg_resources.resource_stream(resource_package, resource_path)\n pass\n elif mapName == 'Dilijan':\n resource_path = '/'.join(('DilijanMap.jpg',)) \n Map = pkg_resources.resource_stream(resource_package, resource_path)\n self.boundaries={'north':40.756399,'south':40.738668,'west':44.829089 ,'east':44.905993}\n self.Map = cv2.imread(Map.name)[150:735,435:2970]#[104:759,424:2831]\n self.scale = scale\n self.map_shape = tuple((int((self.Map.shape[1]*(scale/12000))),int((self.Map.shape[0]*(scale/12000)))))\n self.Map = cv2.resize(self.Map,self.map_shape)\n else:\n raise Exception('We dont supprt this map: {}'.format(mapName))\n\n def ltop(self,point):\n x = int((point[0]-self.boundaries['west'])/(self.boundaries['east']-self.boundaries['west'])*self.map_shape[0])\n y = int(abs(point[1]-self.boundaries['north'])/(self.boundaries['north']-self.boundaries['south'])*self.map_shape[1])\n return (x,y)\n\n def ptol(point):#takes x,y returns lon,lat\n return [point[0]/self.scale+self.boundaries['west'],(self.map_shape[1]-point[1])/scale+self.boundaries['south']]\n\n def check_boundaries(self,loc):\n if loc[0]self.boundaries['north'] or loc[1]self.boundaries['east']:\n return False\n return True\n\n def show_location(self,location,size=2,color=(255,0,0)):\n '''Takes (lat,lng)\n Draws on map'''\n board = self.Map.copy()\n point = self.ltop(location[::-1])\n cv2.circle(board,point,size,color,-1)\n cv2.imshow('Map',board)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \n def show_trip(self,waypoints,size=2,color=(255,0,0),animation = False,delay = 40,zoom = True,spaces = 0):#TODO implement spaces\n '''Takes (lat,lng,...) waypoints\n Draws on map'''\n minx,maxx,miny,maxy = 0,self.map_shape[0],0,self.map_shape[1]\n\n points = [self.ltop((waypoint[1],waypoint[0])) for waypoint in waypoints]\n if zoom:\n margin = 50\n x_ = [p[0] for p in points]\n y_ = [p[1] for p in points]\n minx,maxx = min(x_)-margin,max(x_)+margin\n miny,maxy = min(y_)-margin,max(y_)+margin\n minx = minx if minx>0 else 0\n maxx = maxx if maxx0 else 0\n maxy = maxy if maxy=8 length locations array\n Returns -4th locations snapped location and nodes\n Some error when returns [0,0],[0,0]'''\n if len(locations)<8:\n return [0,0],[0,0]\n res = self.match(locations[-8:],)\n if res['code'] != 'Ok':\n return [0,0],[0,0]\n try:\n nodes = res['matchings'][0]['legs'][-4]['annotation']['nodes']\n snapped_location = res['tracepoints'][-4]['location'][::-1]\n except:\n return [0,0],[0,0]\n if len(nodes)>2:\n s,nodes1,_ = self.nearby(snapped_location)\n node1,node2 = nodes1\n if node1==0 or node2 == 0:\n return snapped_location,[0,0]\n else:\n try:\n nodes = [node1,node2] if nodes.index(node1)\n # GET\n #\n def postProvisioning(self):\n\n if self.mainId and re.match(\"^[0-9A-Za-z@_\\-.]*$\", self.mainId):\n self.myFields['email'] = self.mainId\n else:\n raise self.utils.BaseExceptionError(\n self.appConfig['statusCode']['invalidKeyE']['code'],\n self.appConfig['statusCode']['invalidKeyE']['message'])\n\n # Sempre 'I'\n self.myFields['accountType'] = 'I'\n\n if 'lang' not in self.myFields.keys():\n self.myFields['lang'] = 'pt-BR'\n\n if 'autoRenew' not in self.myFields.keys():\n self.myFields['autoRenew'] = 1\n self.myFields['autoRenewMonths'] = 12\n self.myFields['autoRenewDays'] = 31\n\n return self.requestRest('%sCreateValidatedAccount.cgi' % (self.urlRestBase))\n\n #\n # Funcao para desativar um cliente\n # resquest de Retorno de sucesso\n # 200 - \n # GET\n #\n def putProvisioning(self):\n\n if self.mainId and re.match(\"^[0-9A-Za-z@_\\-.]*$\", self.mainId):\n self.myFields['email'] = self.mainId\n else:\n raise self.utils.BaseExceptionError(\n self.appConfig['statusCode']['invalidKeyE']['code'],\n self.appConfig['statusCode']['invalidKeyE']['message'])\n\n if 'clear' not in self.myFields.keys():\n self.myFields['clear'] = 1\n\n dictReturn = None\n if 'password' in self.myFields.keys():\n self.myFields['accountPass'] = self.myFields['password']\n del self.myFields['password']\n dictReturn = self.requestRest('%sSetAccountPassword.cgi' % (self.urlRestBase))\n\n # Troca do tamanho da licenca do usuario\n if 'registrationCounter' in self.myFields.keys():\n self.myFields['showRegistrationAllowed'] = 1\n getUser = self.requestRest('%sUsersStatusReport.cgi' % (self.urlRestBase))\n\n if 'data' in getUser:\n licenseSize = int(getUser['data']['registrationAllowed']) - int(self.myFields['registrationCounter'])\n if licenseSize == 0:\n dictReturn = {'return': 'OK', 'data': {}}\n else:\n if licenseSize > 0:\n self.myFields['decrease'] = 1\n self.myFields['registrationCounter'] = licenseSize\n elif licenseSize < 0:\n self.myFields['decrease'] = 0\n self.myFields['registrationCounter'] = abs(licenseSize)\n\n dictReturn = self.requestRest('%sAddRegistrationToAccount.cgi' % (self.urlRestBase))\n del self.myFields['registrationCounter']\n\n # abilita o usuario\n if 'enabled' in self.myFields.keys() and self.myFields['enabled'] == '1':\n del self.myFields['enabled']\n\n if 'activationPeriodMonths' not in self.myFields.keys():\n self.myFields['activationPeriodMonths'] = 12\n\n if 'activationPeriodDays' not in self.myFields.keys():\n self.myFields['activationPeriodDays'] = 31\n\n if 'autoRenew' not in self.myFields.keys():\n self.myFields['autoRenew'] = 1\n self.myFields['autoRenewMonths'] = 12\n self.myFields['autoRenewDays'] = 31\n\n dictReturn = self.requestRest('%sActivateAccount.cgi' % (self.urlRestBase))\n # desabilita o usuario\n elif 'enabled' in self.myFields.keys() and self.myFields['enabled'] == '0':\n del self.myFields['enabled']\n self.myFields['endActivationDate'] = time.strftime('%Y-%m-%d')\n dictReturn = self.requestRest('%sDeactivateAccount.cgi' % (self.urlRestBase))\n # troca o email primario(KEY)\n elif 'newEmail' in self.myFields.keys():\n dictReturn = self.requestRest('%sChangeAccountEmail.cgi' % (self.urlRestBase))\n # troca o email secundario(tambem usado para logar)\n elif 'newEmailSecondary' in self.myFields.keys():\n dictReturn = self.requestRest('%sChangeAccountEmail.cgi' % (self.urlRestBase))\n\n if dictReturn:\n return dictReturn\n else:\n raise self.utils.BaseExceptionError(\n self.appConfig['statusCode']['missingFields']['code'],\n self.appConfig['statusCode']['missingFields']['message'])\n\n #\n # Funcao para desativar um cliente\n # resquest de Retorno de sucesso\n # 200 - \n # GET\n #\n def deleteProvisioning(self):\n\n if self.mainId and re.match(\"^[0-9A-Za-z@_\\-.]*$\", self.mainId):\n self.myFields['email'] = self.mainId\n else:\n raise self.utils.BaseExceptionError(\n self.appConfig['statusCode']['invalidKeyE']['code'],\n self.appConfig['statusCode']['invalidKeyE']['message'])\n\n if 'endActivationDate' not in self.myFields:\n self.myFields['endActivationDate'] = time.strftime('%Y-%m-%d')\n\n return self.requestRest('%sDeactivateAccount.cgi' % (self.urlRestBase))\n\n # https://hero.puresight.com/src/Manage/ProductAdmin/DeleteAccount.cgi?adminUser=FAST-jh87tFFrD&adminPassword=ghEEw3218&email=marco@fs.com\n # Funcao para incluir uma licensa ah um clientes\n # resquest de Retorno de sucesso\n # 200 - \n # GET\n #\n def postLicenses(self):\n\n if self.mainId and re.match(\"^[0-9A-Za-z@_\\-.]*$\", self.mainId):\n self.myFields['email'] = self.mainId\n else:\n raise self.utils.BaseExceptionError(\n self.appConfig['statusCode']['invalidKeyE']['code'],\n self.appConfig['statusCode']['invalidKeyE']['message'])\n\n # Pega as informacoes do usuario\n self.myFields['showRegistrationAllowed'] = 1\n getUser = self.requestRest('%sUsersStatusReport.cgi' % (self.urlRestBase))\n\n if not self.myFields['registrationCounter'].isdigit():\n raise self.utils.BaseExceptionError(\n self.appConfig['statusCode']['invalidFields']['code'],\n self.appConfig['statusCode']['invalidFields']['message'])\n\n if 'data' in getUser:\n licenseSize = int(getUser['data']['registrationAllowed']) - int(self.myFields['registrationCounter'])\n if licenseSize > 0:\n self.myFields['decrease'] = 1\n self.myFields['registrationCounter'] = licenseSize\n elif licenseSize < 0:\n self.myFields['decrease'] = 0\n self.myFields['registrationCounter'] = abs(licenseSize)\n else:\n return {'return': 'OK', 'data': {}}\n\n return self.requestRest('%sAddRegistrationToAccount.cgi' % (self.urlRestBase))\n else:\n return getUser\n\n def status(self):\n\n self.myFields['email'] = '1'\n return self.requestRest('%sUsersStatusReport.cgi' % (self.urlRestBase))\n","sub_path":"toth/Code/vendors/v2/puresight/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"103848399","text":"\"\"\"\nDefault abstract models for models in app.\n\"\"\"\nfrom abc import ABCMeta\nimport json\nfrom sqlalchemy.ext.declarative import declared_attr\nfrom kpir.core import db\n\n__author__ = \"Dawid Pych \"\n__date__ = \"$2015-07-05 14:07:00$\"\n\n\nclass CoreModel(object):\n \"\"\"\n Abstract model for template table to use in SQLAlchemy ORM.\n \"\"\"\n\n # Declaration of abstract class.\n __metaclass__ = ABCMeta\n\n # Place for generated table name.\n __table__ = None\n\n # Default id column for table\n id = db.Column(db.Integer, primary_key=True)\n\n # Default params column where data are holds in json\n params = db.Column(db.Text)\n\n def __init__(self, model=None):\n \"\"\"\n Constructor.\n :return:\n \"\"\"\n self.__table__ = self.__name__.lower()\n\n @declared_attr\n def __tablename__(cls):\n \"\"\"\n Return table name write in lowercase\n :param cls:\n :return:\n \"\"\"\n return cls.__name__.lower()\n\n def __repr__(self):\n return '<%s %r>' % (self.__class__.__name__, self.name)\n\n def get_params(self):\n \"\"\"\n Convert json params to dictionary.\n :return:\n \"\"\"\n return json.loads(self.params)\n\n @property\n def serialize(self):\n \"\"\"\n Serialize model\n :return:\n \"\"\"\n ret = {}\n for column in self.__table__.columns:\n if column.name == 'params' and getattr(self, column.name) and getattr(self, column.name) != '':\n ret[column.name] = json.loads(getattr(self, column.name, '{}'))\n else:\n ret[column.name] = getattr(self, column.name)\n return ret\n\n def add_row(self, data):\n \"\"\"\n Method to add new row\n\n :param dict data:\n :return object:\n \"\"\"\n if data:\n save = True\n\n for k in self.__table__.columns:\n name = getattr(k, 'name')\n required = not getattr(k, 'nullable')\n if name in data:\n if name == 'params':\n setattr(self, name, json.dumps(data.get(name)))\n else:\n setattr(self, name, data.get(name))\n else:\n if required and name != 'id':\n save = False\n\n if save:\n db.session.add(self)\n db.session.commit()\n\n return self\n\n def edit_row(self, data):\n \"\"\"\n Edit row\n\n :param dict data:\n :return object:\n \"\"\"\n if data:\n save = True\n\n for k in self.__table__.columns:\n name = getattr(k, 'name')\n required = not getattr(k, 'nullable')\n\n if name in data:\n if name == 'params':\n setattr(self, name, json.dumps(data.get(name)))\n else:\n setattr(self, name, data.get(name))\n else:\n if required:\n save = False\n if save:\n db.session.commit()\n\n return self\n\n def delete_row(self, id):\n \"\"\"\n Remove row\n\n :param int id:\n :return bool:\n \"\"\"\n if id:\n self.query.get(int(id))\n if self.id:\n db.session.delete(self)\n db.session.commit()\n return True\n else:\n return False\n else:\n return False\n","sub_path":"src/kpir/core/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"366712832","text":"import os\nimport json\nimport flask\nimport requests\nimport chardet\nimport re\nimport functools\nfrom mastodon import Mastodon\nfrom .utils import (\n apply_kw,\n get_default_args,\n get_by_path,\n)\n\n\ndef index(mastodon=None, *args, **kwargs):\n try:\n action = getattr(mastodon, kwargs.get('action', ['timeline'])[0])\n data = apply_kw(action, **kwargs)\n json_str = json.dumps({\"data\": data})\n callback = kwargs.get('callback', ['callback'])[0]\n return '%s(%s)' % (callback, json_str)\n except Exception as err:\n print(err)\n return str(err)\n\n\ndef wrapper(fn, *args, **kwargs):\n @functools.wraps(fn)\n def _wrapper(*_args, **_kwargs):\n res = fn(\n *args + _args,\n **dict(dict(kwargs, **_kwargs), **flask.request.args))\n return res\n return _wrapper\n\n\ndef run(*args, **kwargs):\n mastodon_kw = get_default_args(Mastodon.__init__, **kwargs)\n mastodon = Mastodon(**mastodon_kw)\n app = flask.Flask(__name__)\n app.route('/')(wrapper(index, mastodon=mastodon))\n app.run(host='0.0.0.0', port=8887)\n\n\n","sub_path":"mastodon_simple_command/jsonp_server.py","file_name":"jsonp_server.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"444482971","text":"def arithmetic_arranger(listOfProblems, display_results=False):\n if len(listOfProblems) > 5:\n return \"Error: Too many problems.\"\n\n problemObjs = [Problem(problem) for problem in listOfProblems]\n\n for problem in problemObjs:\n error = problem.validate_problem()\n if error:\n return error\n\n problemPrinters = [problem.create_ProblemPrinter() for problem in problemObjs]\n\n return sum(problemPrinters).createDisplayString(display_results)\nclass Problem:\n valid_operators = [\"+\", \"-\"]\n distanceForOperator = 1\n \n fillFormatTemplate = '{msg: >{width}}'\n\n def __init__(self, problem):\n\n splitted_problem = problem.split(\" \")\n\n self.number1 = splitted_problem[0]\n self.number2 = splitted_problem[2]\n self.operator = splitted_problem[1]\n\n self._boxWidth = self._get_required_width()\n \n def validate_problem(self):\n if self.operator not in self.valid_operators:\n return \"Error: Operator must be \\'{validatorsOr}\\'.\".format(validatorsOr=\"\\' or \\'\".join(self.valid_operators)) \n elif not self.number1.isdigit() or not self.number2.isdigit():\n return \"Error: Numbers must only contain digits.\"\n elif len(self.number1) > 4:\n return \"Error: Numbers cannot be more than four digits.\"\n elif len(self.number2) > 4:\n return \"Error: Numbers cannot be more than four digits.\"\n else:\n pass\n\n def _calculate_result(self):\n number1 = int(self.number1)\n number2 = int(self.number2)\n\n if self.operator == \"+\":\n return number1 + number2\n \n elif self.operator == \"-\":\n return number1 - number2\n \n def _get_required_width(self):\n numMaxChar = max(len(self.number1), len(self.number2))\n return numMaxChar + self.distanceForOperator + len(self.operator)\n \n def _generate_number_line(self, operator, number):\n return operator + self.fillFormatTemplate.format(msg=number, width=self._boxWidth - len(operator))\n \n def create_ProblemPrinter(self):\n \n line1 = self._generate_number_line('', self.number1)\n line2 = self._generate_number_line(self.operator, self.number2)\n lineDashed = \"-\" * self._boxWidth\n lineResult = self._generate_number_line('', self._calculate_result())\n\n problemPrinter = ProblemPrinter(line1, line2, lineDashed, lineResult)\n\n return problemPrinter\n\nclass ProblemPrinter:\n distanceBetweenProblems = 4\n\n def __init__(self, line1, line2, lineDashed, lineResult):\n self.line1 = line1\n self.line2 = line2\n self.lineDashed = lineDashed\n self.lineResult = lineResult\n \n def __add__(self, other):\n new_line1 = self.line1 + \" \" * ProblemPrinter.distanceBetweenProblems + other.line1\n new_line2 = self.line2 + \" \" * ProblemPrinter.distanceBetweenProblems + other.line2\n new_lineDashed = self.lineDashed + \" \" * ProblemPrinter.distanceBetweenProblems + other.lineDashed\n new_lineResult = self.lineResult + \" \" * ProblemPrinter.distanceBetweenProblems + other.lineResult\n\n return ProblemPrinter(new_line1, new_line2, new_lineDashed, new_lineResult)\n\n def __radd__(self, other):\n if other == 0:\n return self\n else:\n return self.__add__(other)\n\n def createDisplayString(self, display_results):\n all_lines = [self.line1, self.line2, self.lineDashed, self.lineResult] if display_results else [self.line1, self.line2, self.lineDashed]\n return \"\\n\".join(all_lines)\n\n def __repr__(self):\n return self.createDisplayString(True)\n","sub_path":"arithmetic_arranger.py","file_name":"arithmetic_arranger.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"134211059","text":"\r\nfrom clawpack.geoclaw import topotools\r\nfrom pylab import *\r\n\r\ndx=.0025;\r\n\r\ndef maketopo():\r\n \"\"\"\r\n Output topography files\r\n \"\"\"\r\n nxpoints = 201\r\n nypoints = 21\r\n xlower = 0.\r\n xupper = 20.\r\n ylower = 0.\r\n yupper = 1.52\r\n outfile= \"domain.tt1\"\r\n topotools.topo1writer(outfile,topo,xlower,xupper,ylower,yupper,nxpoints,nypoints)\r\n\r\n nxpoints = 201\r\n nypoints = 201\r\n xlower = 4.5\r\n xupper = 5.5\r\n ylower = 0.25\r\n yupper = 1.25\r\n outfile= \"hump.tt1\"\r\n topotools.topo1writer(outfile,topo,xlower,xupper,ylower,yupper,nxpoints,nypoints)\r\n\r\n\r\ndef topo(x,y):\r\n \"\"\"\r\n flat with hump\r\n \"\"\"\r\n\r\n z = zeros(x.shape)\r\n\r\n # island addition\r\n # from paper\r\n xo=5.0;\r\n yo=1.52/2;\r\n slope_d=8;\r\n base_r=0.75/2;\r\n top_r=0.05/2;\r\n hi=0.049;\r\n\r\n dist = sqrt( (x-xo)**2+(y-yo)**2 );\r\n zz = hi*(1-(dist-top_r)/(base_r-top_r))\r\n zz = where(zz1.07*np.average(I1/I0, axis=0):\n\t\t#\tprint(\"Jet was unstable in this scan.\") #Jet stability check\n\n\t\tif uI0[0]==0.: #I0 before sample all recorded?\n\t\t\tprint(\"This scan contains I0=0.\")\n\t\t\tprint(\"and Index(indices): {}\".format(indexlist3))\n\t\telif uI1[0]==0.: #I1(TFY) after sample all recorded?\n\t\t\tprint(\"This scan contains TFY=0.\")\n\t\t\tprint(\"and Index(indices): {}\".format(indexlist4))\n\t\telse:\n\t\t\tpass\n\n\t\tprint(\"Number of tags: {}\".format(len(path)))\n\t\tprint(\"Onoffs: {}\".format(onoffd))\n\t\tif len(udelay)==1:\n\t\t\tprint(\"Only one delay: {}\".format(str(udelay)))\t#One delay foot-to-foot jitter = 1.5 ps\n\t\telse:\n\t\t\tprint(\"First delay: {}\".format(str(delay[0])))\n\t\t\tprint(\"Last delay: {}\".format(str(delay[-1])))\n\t\t\tprint(\"Delays: {}\".format(delayd))\n\n\t\t### Signal-to-Noise Ratio check, rejecting bad pulses?\n\t\t#plt.plot(I0, I1, 'bo')\n\t\t#plt.show()\n\t\t#plt.plot(I1I0, 'bo') #if jet was fluctuating, excited fraction might differ as well...\n\t\t#plt.show()\n\n\t\ttempset=[None]*len(path)\n\t\tfor j, tag in enumerate(path): #raw data into tempset with normalization\n\t\t\tif uI1[0]!=0.:\n\t\t\t\ttempset[j]=np.array(f.get('/run_'+str(scan)+'/detector_data/'+tag+'/signal'))/I1[j]\n\t\t\telif cI1[j]!=0:\n\t\t\t\ttempset[j]=np.array(f.get('/run_'+str(scan)+'/detector_data/'+tag+'/signal'))/I1[j]\n\t\t\telse: #this is NaN anyway... exclude it later\n\t\t\t\ttempset[j]=np.array(f.get('/run_'+str(scan)+'/detector_data/'+tag+'/signal'))\n\n\t\t#shot-to-shot counts on VHS detector at pixel number 120 to 220\n\t\tsts=np.average(np.array(tempset).transpose()[120:220], axis=0)\n\t\t#usts, csts=np.unique(sts, return_counts=True)\n\t\t#plt.plot(usts, csts)\n\t\t#plt.show()\n\n\t\t#Properly normalized?\n\t\t#plt.plot(I0, sts, 'bo')\n\t\t#plt.show()\n\t\t#plt.plot(I1, sts, 'bo')\n\t\t#plt.show()\n\n\t\t#corrected probe delay distribution for re-binning\n\t\t#utmx, ctmx=np.unique(tmx, return_counts=True)\n\t\t#plt.plot(utmx, ctmx)\n\t\t#plt.show()\n\n\t\t''' ###This is without time sorting###\n\t\tdelayset=[]\n\t\tdelayx=udelay\n\n\t\tdelaycount=0\n\t\ton=[]\n\t\toff=[]\n\t\tfor l, pulse in enumerate(tempset):\n\t\t\tif delay[l]==udelay[delaycount]:\n\t\t\t\tif I1[l]==0.:\n\t\t\t\t\tpass\n\t\t\t\telif onoff[l]==1:\n\t\t\t\t\ton.append(pulse)\n\t\t\t\telse:\n\t\t\t\t\toff.append(pulse)\n\t\t\telse:\n\t\t\t\tdelayset.append([np.average(off, axis=0), np.average(on, axis=0)])\n\t\t\t\ton=[]\n\t\t\t\toff=[]\n\t\t\t\tif I1[l]==0.:\n\t\t\t\t\tpass\n\t\t\t\telif onoff[l]==1:\n\t\t\t\t\ton.append(pulse)\n\t\t\t\telse:\n\t\t\t\t\toff.append(pulse)\n\n\t\t\t\tdelaycount+=1\n\n\t\tdelayset.append([np.average(off, axis=0), np.average(on, axis=0)])\n\n\t\tprint(\"delayset length: {}\".format(int(len(delayset))))\n\n\t\tdset[i]=delayset\n\t\t'''\n\n\t\t#time sorting\n\t\tif max(tma)>2222:\n\t\t\tprint(\"Timing Feedback was partially out in this scan.\")\n\t\t\tplt.plot(tma)\n\t\t\tplt.show()\n\n\t\ton=[[],[],[]]\n\t\toff=[]\n\t\tfiltered=0\n\n\t\tfor k, pulse in enumerate(tempset): #outliers rejection, sts 3000 to 25000 for Kb, 60 to 1500 for VtC, 5000 to 10000 for Ka246, 2000 to 7000 for Ka135\n\t\t\tif I1[k]<0.01 or math.isnan(tmx[k]) or tma[k]>2222 or I1[k]/I0[k]avrI10+0.01 or sts[k]<5000 or sts[k]>10000:\n\t\t\t\tfiltered+=1\n\t\t\t\tpass\n\t\t\telif onoff[k]==1:\n\t\t\t\tif pump[k]!=0:\n\t\t\t\t\ton[0].append(tmx[k]) #corrected probe delay\n\t\t\t\t\ton[1].append(pulse) #tempset data\n\t\t\t\t\ton[2].append(pump[k]) #pump laser intensity\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Shot number {} is laser-on but intensity 0\".format(k))\n\t\t\telse:\n\t\t\t\toff.append(pulse)\n\n\t\tprint(\"Filtered shots: {}\".format(str(filtered)))\n\t\toffset[i]=np.average(off, axis=0)\n\t\t#plt.plot(offset[i])\n\t\t#plt.show()\n\n\t\toncounts+=len(on[1])\n\n\t\tfor e, zeit in enumerate(on[0]): #re-binning\n\t\t\tif -1500<=zeit<=19500: #our hard-limit of re-binning for -1ps to 19ps\n\t\t\t\tif -1025<=zeit<=2575: #our hard-limit of re-binning for -1ps to 2ps\n\t\t\t\t\tbin50set[[round(l) for l in (bin50-zeit)/50].index(0)].append(on[1][e])\n\t\t\t\t\tpump50[[round(l) for l in (bin50-zeit)/50].index(0)].append(on[2][e])\n\n\t\t\t\tif 18500<=zeit:\n\t\t\t\t\tdelay19.append(on[1][e])\n\t\t\t\t\tpump19.append(on[2][e])\n\n\t\t\t\tbin500set[[round(m) for m in (bin500-zeit)/1000].index(0)].append(on[1][e])\n\t\t\t\tpump500[[round(m) for m in (bin500-zeit)/1000].index(0)].append(on[2][e])\n\t\t\telse:\n\t\t\t\tpass\n\n\t\t'''\n\t\tfor s, zeit in enumerate(tuonset[0]):\n\t\t\ttry:\n\t\t\t\tdiffset.append([zeit, (tuonset[1][s]-tuoffset[1][tuoffset[0].index(zeit)])[200]])\n\t\t\texcept ValueError:\n\t\t\t\tpass\n\t\t'''\n\nprint(\"\\nAll sorted on-counts: {}\".format(oncounts))\nprint(\"On-counts at 19ps: {}\".format(len(delay19)))\n'''\nfor offscan in offset:\n\tplt.plot(offscan)\n\nplt.show()\n'''\navr19=np.average(delay19, axis=0) #19ps data average\navr19p=np.average(pump19, axis=0)\noffavr=np.average(offset, axis=0)\n\nplt.plot(avr19-offavr)\nplt.show()\n#np.savetxt('C:/data/sacla/absolute_19ps_Ka135_739134-159,181-255.txt', (offavr, avr19))\nprint(avr19p)\n\ncount500=[len(n) for n in bin500set] #counts at each delay point of kinetics\ncount50=[len(o) for o in bin50set]\n\nplt.plot(bin500, count500)\nplt.show()\nplt.plot(bin50, count50)\nplt.show()\n'''\nfor p500 in pump500:\n\tplt.plot(p500)\n\tplt.show()\n\nfor p50 in pump50:\n\tplt.plot(p50)\n\tplt.show()\n'''\navr500=[np.average(v,axis=0) for v in bin500set] #average of kinetics\navr50=[np.average(x,axis=0) for x in bin50set]\navr500p=[np.average(ad,axis=0) for ad in pump500]\navr50p=[np.average(ae,axis=0) for ae in pump50]\n'''\nplt.plot(bin500,avr500p) #fluctuation of pump laser intensity\nplt.show()\nplt.plot(bin50,avr50p)\nplt.show()\n\nfor avrscan in avr50:\n plt.plot(offavr)\n plt.plot(avrscan)\n plt.show()\n'''\ndiff500=[(q-offavr)/avr500p[p] for p,q in enumerate(avr500)]\ndiff50=[(s-offavr)/avr50p[r] for r,s in enumerate(avr50)]\n\nfor diff in diff50:\n plt.plot(diff)\n plt.show()\n\n#np.savetxt('C:/data/sacla/-1ps_to_2ps_Cudmp_Ka135_50fs_absolute2.txt', ([bin50, count50, avr50p]))\n#np.savetxt('C:/data/sacla/-1ps_to_2ps_Cudmp_Ka135_50fs_absolute2_on.txt', (avr50))\n#np.savetxt('C:/data/sacla/-1ps_to_2ps_Cudmp_Ka135_50fs_absolute2_off.txt', (offavr))\n#np.savetxt('C:/data/sacla/-1ps_to_2ps_Cudmp_Ka135_50fs_absolute2_tr.txt', ([bin50, [np.trapz(af[150:180])+np.trapz(af[205:220]) for af in diff50]]))\n\nplt.plot(bin500, [np.trapz(t[150:180])+np.trapz(t[205:220]) for t in diff500], 'bo')\nplt.show()\nplt.plot(bin50, [np.trapz(u[150:180])+np.trapz(u[205:220]) for u in diff50], 'bo')\nplt.show()\n\n'''\ndef gui():\n\ty = 0\n\twhile y < 1:\n\t\topt = int(input(\"\\nPlease select an option\\n0. All scan numbers\\n1. \\n2. Global fitting\\n3. New samples\\n4. Saving data\\n5. Exit\\n\"))\n\t\tif opt == 0:\n\t\t\tprint(items)\n\t\telif opt == 1:\n\t\t\tplot = [int(x) for x in input(\"\\nPlease input sample # and plot method\\n0. Single plot(before time zero)\\n1. Single plot(before time zero_after GVD)\\n2. Single plot(singular values)\\n3. Single plot(global fit_kinetics)\\n4. Single plot(global fit_spectra)\\n5. Multiple plot(UV-vis)\\n6. Multiple plot(spectra traces_cut)\\n7. Multiple plot(spectra traces_svd)\\n8. Multiple plot(spectra traces_rec)\\n9. Multiple plot(kinetic traces_final)\\n10. Multiple plot(kinetic traces_rec)\\n11. Multiple plot(each singular vectors)\\n12. Multiple plot(DAS)\\n13. 2D plot(background subtraction)\\n14. 2D plot(GVD correction)\\n15. 2D plot(OD calibrated)\\n16. 2D plot(noise subtraction)\\n17. 2D plot(reconstructed)\\n18. 2D plot(residual)\\n19. 2D plot(final difference)\\n\").split()]\n\t\t\tplotting(filedic[plot[0]][0], plot[1])\n\t\telif opt == 2:\n\t\t\tfitt = int(input(\"\\nPlease input sample# \"))\n\t\t\tj = 0\n\t\t\twhile j < 1:\n\t\t\t\tprint(\"{} sample global fitting.\".format(str(fitt)))\n\t\t\t\ttimeguess = [float(x) for x in input(\"Please enter time constants \").split()]\n\t\t\t\tfiledic[fitt][0].globalfit(fitt, timeguess)\n\t\t\t\tplotting(filedic[fitt][0], 3)\n\t\t\t\tans = input(\"Satisfied with the fitting?(y/n) \")\n\t\t\t\tif ans == 'y' : j += 1\n\t\t\t\telse: continue\n\t\telif opt == 3:\n\t\t\tnsample = 0\n\t\t\twhile nsample < len(newset):\n\t\t\t\ttemp = nsample+24\n\t\t\t\tfiledic[temp] = ['raw']\n\t\t\t\tfiledic[temp][0] = maryam(temp, newset[nsample])\n\t\t\t\tprint(\"{} sample loaded.\".format(str(temp)))\n\t\t\t\tfiledic[temp][0].nogvd(temp)\n\t\t\t\tprint(\"{} sample GVD corrected.\".format(str(temp)))\n\t\t\t\tfiledic[temp][0].odcali(temp)\n\t\t\t\tprint(\"{} sample OD calibrated.\".format(str(temp)))\n\n\t\t\t\tplt.imshow(filedic[temp][0].cali, cmap='terrain', aspect=\"auto\", clim=(-0.025, 0.02), origin='lower')\n\t\t\t\tplt.colorbar()\n\t\t\t\tplt.show()\n\n\t\t\t\ttemp2 = np.transpose(filedic[temp][0].cali)\n\t\t\t\tplt.plot(temp2[38])\n\t\t\t\tplt.show()\n\n\t\t\t\tnsample += 1\n\n\t\telse: y = 1\n\ngui()\n\n\nif len(dset[0])==2:\n\tprint(\"All on-counts: {}\".format(oncounts))\n\tavrdset=np.average(dset, axis=0)\n\tplt.plot(avrdset[0])\n\tplt.plot(avrdset[1])\n\tplt.show()\n\tplt.plot((avrdset[1]-avrdset[0]))\n\tplt.show()\n\n\t#np.savetxt('C:/data/sacla/delay1600_Cudmp_Kb.txt', (avrdset))\nelse:\n\tfor offscan in offset:\n\t\tplt.plot(offscan)\n\n\tplt.show()\n\ttoff = np.average(offset, axis=0)\n\ttotalbin = np.sum([e[0] for e in dset], axis=0)\n\n\ttonn = np.average([u[1] for u in dset], axis=0)\n\ttpump = np.average([u[2] for u in dset], axis=0)\n\n\tdiffset=[(v-toff)/tpump[s] for s,v in enumerate(tonn)]\n\n\n\ttempon=None\n\ttemppump=None\n\ttonn=[]\n\ttpump=[]\n\n\tfor u in dset:\n\t\tif u[0][-1]!=0:\n\t\t\ttonn.append(u[1])\n\t\t\ttpump.append(u[2])\n\t\telse:\n\t\t\ttempon=u[1]\n\t\t\ttemppump=u[2]\n\t\t\tprint(\"this notice should appear only once\")\n\n\ttonnavr=np.average(tonn,axis=0)\n\ttpumpavr=np.average(tpump,axis=0)\n\n\tshort=np.average([tonnavr[:50], tempon[:50]], axis=0)\n\tshortpump=np.average([tpumpavr[:50], temppump[:50]], axis=0)\n\tshortdiff=[(v-toff)/shortpump[s] for s,v in enumerate(short)]\n\tlongdiff=[(g-toff)/tpumpavr[50+h] for h,g in enumerate(tonnavr[50:])]\n\n\tdiffset=shortdiff+longdiff\n\n\n\tplt.plot(delayx, totalbin) #re-binned delay vs. counts\n\tplt.show()\n\tplt.plot(delayx, [np.trapz(t[180:215]) for t in diffset], 'bo')\n\tplt.show()\n\n\t#for scan in diffset:\n\t#\tplt.plot(scan)\n\t#\tplt.show()\n\n'''\n","sub_path":"1dsacla_ka.py","file_name":"1dsacla_ka.py","file_ext":"py","file_size_in_byte":12927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"69307426","text":"# 使用动态规划解法\n# 初始化\n# i=0时,只有一个阶梯,因此到达该阶梯顶部需要的能量即为到达该阶梯所需能量,为cost[0];\n# i=1时,有两个阶梯,我们可以迈两步,跳过第一级台阶,到达该阶梯所需要的能量为到达第二级台阶所需能量,为cost[1];\n# dp[i]表示到达下标为i的阶梯需要消耗的最小能量。这里需要注意,顶部阶梯实际上是被题目缺省掉的,\n# 即到达顶部阶梯所需要消耗的能量为零,我们需要补回来\n\n# 状态转移方程\n# i>1时,到达第i级台阶只有两种选择,一种是从第i-1级台阶迈一步,另一种是从i-2级台阶迈两步,\n# 这两种选择消耗的最少能量分别是dp[i-1]+cost[i]和dp[i-2]+cost[i],我们取两者的最小值,即为到达下标为i的台阶所需的最少能量:\n# dp[i] = min(dp[i-1], dp[i-2]) + cost[i]\ndef minCostClimbingStairs(cost: list):\n if not cost:\n return 0\n if len(cost) <= 2:\n return min(cost)\n\n cost.append(0)\n dp = [None for _ in range(len(cost))]\n dp[0], dp[1] = cost[0], cost[1]\n for i in range(2, len(cost)):\n dp[i] = min(dp[i - 2], dp[i - 1]) + cost[i]\n print(dp)\n return dp[-1]\n","sub_path":"Fei_LeetCode/Array/0926/746-Min Cost Climbing Stairs.py","file_name":"746-Min Cost Climbing Stairs.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"403468884","text":"#!/usr/bin/python3\n\nimport networkx as nx\nimport csv\nimport networkx as nx\nimport pickle\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport collections\nfrom random import randint\nfrom random import choice\nimport statistics\n\n\n# create graph from the edgeList\ndef create_multi_graph(edgeList, is_directed):\n if is_directed==0:\n G=nx.MultiGraph()\n else:\n G = nx.DiGraph() \n for edge in edgeList:\n G.add_edge(edge[0], edge[1])\n return G\n \n # if edge not in G.edges():\n # G.add_edge(edge[0], edge[1], weight = 1)\n # else:\n # G[edge[0]][edge[1]]['weight']+=1\n #return G\n\n# create graph from the edgeList\ndef create_graph(edgeList, is_directed):\n if is_directed==0:\n G=nx.Graph()\n else:\n G = nx.DiGraph() \n for edge in edgeList:\n G.add_edge(edge[0], edge[1])\n return G\n\ndef create_aggr_network(file):\n G=nx.Graph() \n\n #create graph from csv\n with open(file, \"rt\") as csvfile:\n mydata = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in mydata:\n if row[0]!=\"\" and row[1]!=\"\" and row[2]!=\"\": \n vertex1 = int(row[0])\n vertex2 = int(row[1])\n G.add_edge(vertex1,vertex2)\n return G \n\ndef create_aggr_network_multi(file):\n G=nx.MultiGraph() \n\n #create graph from csv\n with open(file, \"rt\") as csvfile:\n mydata = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in mydata:\n if row[0]!=\"\" and row[1]!=\"\" and row[2]!=\"\": \n vertex1 = int(row[0])\n vertex2 = int(row[1])\n G.add_edge(vertex1,vertex2)\n return G \n\ndef create_edgelist_per_time(file): #create edgelist \n timeD = {} # Dictionary with the edgelist per time {\"0\":[(1,2),(5,6)...], \"1\":[(4,7)...]...}\n with open(file, \"rt\") as csvfile:\n mydata = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in mydata:\n if row[0]!=\"\" and row[1]!=\"\" and row[2]!=\"\":\n\n vertex1 = int(row[0])\n vertex2 = int(row[1])\n t = int(row[2])\n \n # Create edgelist per time - Adding one edge at a time\n if t in timeD:\n timeD[t].append((vertex1, vertex2))\n else:\n timeD[t]=[]\n timeD[t].append((vertex1, vertex2))\n return timeD\n\ndef plot_Dict(d, mycolor, topic, label):\n lists = sorted(d.items()) # sorted by key, return a list of tuples\n x, y = zip(*lists) # unpack a list of pairs into two tuples\n x = list(range(1,len(d)+1))\n plt.figure()\n plt.plot(x, y,\"-o\", color=mycolor)\n plt.ylabel(label)\n plt.xlabel('Year-Month')\n path = 'images_qa/' + topic + '/' + label + '.png'\n plt.savefig(path)\n plt.close(\"all\")\n\n\ndef average_dict(dictionary):\n #d=[float(sum(values)) / len(values) for key, values in degree_dictionary.items()]\n numbers = [dictionary[key] for key in dictionary]\n mean_ = statistics.mean(numbers)\n return mean_\n\ndef writeToCsv(csvList, topic, file):\n csv_sorted = [csvList[0]]\n csv_sorted.extend(sorted(csvList[1:], key = lambda tup:tup[0]))\n csvfile = file + \"/temporalMetrics_\"+ topic + \".csv\"\n g = open(csvfile, 'w+' ,newline='') \n csvwriter = csv.writer(g)\n zip(*csv_sorted)\n for row in csv_sorted:\n csvwriter.writerow(row)\n g.close()\n\n\n\ndef main():\n # My code here\n pass\n\nif __name__ == \"__main__\":\n main()","sub_path":"assignment_2/networkFunctions.py","file_name":"networkFunctions.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"521422051","text":"import serial \nimport MySQLdb\nimport time \nfrom flask import Flask, render_template\n\nimport paho.mqtt.client as paho\nimport os\nimport socket\nimport ssl\nimport random\nimport string\nimport json\nfrom time import sleep\nfrom random import uniform\n \nconnflag = False\n\ndevice = '/dev/ttyACM0'\nser = serial.Serial(device, 9600, timeout=1)\n\n# Dictionary of pins with name of pin and state ON/OFF \npins = {\n 3: {'name' : 'PIN 3', 'state' : 0}\n}\n\nvalueDist = 0\nvalueLight = 0\npreLight = 0\n\ndef on_connect(client, userdata, flags, rc): # func for making connection\n global connflag\n print(\"Connected to AWS\")\n connflag = True\n print(\"Connection returned result: \" + str(rc) )\n client.subscribe(\"lightSensor\")\n \ndef on_message(client, userdata, msg): # Func for Sending msg\n item = json.loads(msg.payload)\n if \"state\" in item:\n if(item['state'] == 1):\n ser.write(b\"1\") \n else:\n ser.write(b\"2\")\n print(msg.topic+\" \"+str(msg.payload))\n \n \nmqttc = paho.Client() # mqttc object\nmqttc.on_connect = on_connect # assign on_connect func\nmqttc.on_message = on_message # assign on_message func\n\n#### Change following parameters #### \nawshost = \"ashixvhkiwhi7-ats.iot.ap-southeast-1.amazonaws.com\" # Endpoint\nawsport = 8883 # Port no. \nclientId = \"node_smartLight\" # Thing_Name\nthingName = \"node_smartLight\" # Thing_Name\ncaPath = \"AmazonRootCA1.pem\" # Root_CA_Certificate_Name\ncertPath = \"ac69e3dec7-certificate.pem.crt\" # .cert.pem\nkeyPath = \"ac69e3dec7-private.pem.key\" # .private.key\n \nmqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) # pass parameters\n \nmqttc.connect(awshost, awsport, keepalive=60) # connect to aws server\n \nmqttc.loop_start() \n\nwhile 1==1:\n sleep(3)\n \n preLight = valueLight\n line = ser.readline()\n print(line)\n valueDist = int(line[18:21])\n valueLight = int(line[24:27])\n state = int(line[30:31])\n print(valueDist)\n print(valueLight)\n print(line)\n \n if connflag == True:\n paylodmsg0=\"{\"\n paylodmsg1=\"\\\"id\\\":\\\"light\\\"\"\n paylodmsg2 = \",\\\"distance\\\":\"\n paylodmsg3 = \",\\\"light\\\":\"\n paylodmsg4= \",\\\"state\\\":\"\n paylodmsg5= \"}\"\n paylodmsg = \"{} {} {} {} {} {} {} {} {}\".format(paylodmsg0,paylodmsg1, paylodmsg2, valueDist,\n paylodmsg3, valueLight, paylodmsg4, state, paylodmsg5)\n paylodmsg = json.dumps(paylodmsg) \n paylodmsg_json = json.loads(paylodmsg) \n mqttc.publish(\"node_smartLight\", paylodmsg_json , qos=1) # topic: temperature # Publishing Temperature values\n print(\"msg sent: node_smartLight\" ) # Print sent temperature msg on console\n print(paylodmsg_json)\n\n else:\n print(\"waiting for connection...\")\n","sub_path":"node_smartLight/edge.py","file_name":"edge.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"619338440","text":"# Akachukwu Obi, 2018\n# Project Euler #10\n\n# Solution 1: check for primes then sum them\n\nimport math\n\n# check for primes\ndef isPrime(n):\n\tif n == 1:\n\t\treturn False\n\telif n < 4:\n\t\treturn True # 2 and 3 are prime\n\telif (n % 2 == 0) or (n % 3 == 0): # a single '|' or 'or' could represent 'or'\n\t\treturn False\n\telif n < 9: # just applies to 7 at this point\n\t\treturn True\n\telse:\n\t\tf = 5\n\t\tr = math.floor(math.sqrt(n))\n\t\twhile f <= r:\n\t\t\tif (n % f == 0) or (n % (f + 2) == 0):\n\t\t\t\treturn False\n\t\t\tf += 6 # all primes greater than 3 are in the form of 6k +/- 1 where k is an integer\n\n\t\treturn True # if there is no prime factor less than sqrt(n), then n must be prime\n\n# sum the primes, calls isPrime\ndef sumPrimes(limit):\n\tprimeSet = [2]\n\tsums = primeSet[0]\n\tfor count in range(1, limit, 2): # sum primes less than some limit\n\t\tif (isPrime(count)):\n\t\t\tprimeSet.append(count)\n\t\t\tsums += count\n\n\treturn sums\n\n# test\n# print(sumPrimes(2000000)) # 142913828922; took 9.9s\n\n\n# Solution 2: Sieve of Eratosthenes\ndef sumPrimesLessThan(limit):\n\thalfLimit = (limit - 1) // 2 # // is used to ensure floor\n\ta = []; # initialize set to hold numbers\n\n\tfor i in range(0, halfLimit): # create a set up to halfLimit and\n\t\ta.append(True) # initialize all its members to True\n\n\tsqrt = int(math.sqrt(limit))\n\tfor i in range(0, sqrt):\n\t\tif a[i]: # all a[i] are already true\n\t\t\tj = 2 * i + 3 # all primes can be represented as 2k + 3 (though not for all integer k)\n\t\t\tk = i + j # k is a multiple of 3; i + 2i + 3 = 3(i + 1)\n\t\t\twhile k < halfLimit:\n\t\t\t\ta[k] = False\n\t\t\t\tk += j\n\n\tprimeSum = 2\n\tfor i in range(0, halfLimit):\n\t\tif a[i]:\n\t\t\tprimeSum += 2 * i + 3\n\n\treturn primeSum\n\n# test\nprint(sumPrimesLessThan(2000000)) # 142913828922; took 0.6s\n# this is certainly not Sieve of Eras, and I don't yet completely understand the code myself\n\n\n\n\n\n\n","sub_path":"project-euler/py/e10.py","file_name":"e10.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"458527824","text":"from importlib import import_module\nfrom glob import glob\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom metadata.models import Tag\nfrom ..logger import Logger\n\nclass Command(BaseCommand):\n\thelp = 'Populate the Metadata and DataLocation for a dataset from Fits files on disk'\n\t\n\tdef add_arguments(self, parser):\n\t\tparser.add_argument('dataset', help='The id of the dataset')\n\t\tparser.add_argument('files', nargs='+', metavar='file', help='Path to a fits file')\n\t\tparser.add_argument('--HDU', type=int, help='The HDU of the fits file to read')\n\t\tparser.add_argument('--update', default = False, action='store_true', help='Update metadata even if already present in DB')\n\t\tparser.add_argument('--tags', default = [], nargs='*', help='A list of tag names to set to the metadata')\n\t\tparser.add_argument('--debug', default = False, action='store_true', help='Show debugging info')\n\t\t\n\tdef handle(self, **options):\n\t\t\n\t\tlog = Logger(self, debug=options['debug'])\n\t\t\n\t\t# Import the record classes for the dataset\n\t\ttry:\n\t\t\trecords = import_module('metadata.management.records.' + options['dataset'])\n\t\t\tRecord = records.Record\n\t\texcept (ImportError, AttributeError):\n\t\t\traise CommandError('No Record class for dataset %s' % options['dataset'])\n\t\t\n\t\ttags = list()\n\t\tfor tag_name in options['tags']:\n\t\t\ttag, created = Tag.objects.get_or_create(name=tag_name)\n\t\t\tif created:\n\t\t\t\tlog.info('Created Tag %s', tag_name)\n\t\t\ttags.append(tag)\n\t\t\n\t\t# Glob the file paths\n\t\tfile_paths = list()\n\t\tfor path in options['files']:\n\t\t\tfile_paths.extend(glob(path))\n\t\tfile_paths.sort()\n\t\t\n\t\t# Populate the dataset\n\t\tfor file_path in file_paths:\n\t\t\ttry:\n\t\t\t\trecord = Record(file_path, hdu = options['HDU'], log=log)\n\t\t\t\trecord.create(tags=tags, update=options['update'])\n\t\t\texcept Exception as why:\n\t\t\t\tlog.error('Error creating record for \"%s\": %s', file_path, why)\n","sub_path":"metadata/management/commands/populate_disk.py","file_name":"populate_disk.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"142471731","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2009, George Hunt \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport gtk\nimport gobject\nimport os\n#import gconf\n\nfrom sugar.graphics.toolbox import Toolbox\nfrom sugar.graphics.xocolor import XoColor\nfrom sugar.graphics.icon import Icon\nfrom sugar.graphics.toolcombobox import ToolComboBox\nfrom sugar.graphics.toolbutton import ToolButton\nfrom gettext import gettext as _\n\nimport display\n\nclass ActivityToolbar(gtk.Toolbar):\n \"\"\"The Activity toolbar with the Journal entry title, sharing,\n Keep and Stop buttons\n \n All activities should have this toolbar. It is easiest to add it to your\n Activity by using the ActivityToolbox.\n \"\"\"\n def __init__(self, activity):\n gtk.Toolbar.__init__(self)\n\n self._activity = activity\n self._updating_share = False\n \"\"\"\n activity.connect('shared', self.__activity_shared_cb)\n activity.connect('joined', self.__activity_shared_cb)\n activity.connect('notify::max_participants',\n self.__max_participants_changed_cb)\n \"\"\"\n #if activity.metadata:\n if True:\n self.label = gtk.Label(display.menu_journal_label)\n self.label.show()\n self._add_widget(self.label)\n\n self.title = gtk.Entry()\n self.title.set_size_request(int(gtk.gdk.screen_width() / 6), -1)\n if activity.metadata:\n self.title.set_text(activity.metadata['title'])\n #activity.metadata.connect('updated', self.__jobject_updated_cb)\n self.title.connect('changed', self.__title_changed_cb)\n self.title.connect('activate', self.__update_title_cb)\n self._add_widget(self.title)\n \n fn = os.path.join(os.getcwd(),'assets','stack_new.png')\n button = ImageButton()\n tooltip = _(\"Add Album Stack\")\n button.set_image(fn,tip=tooltip)\n self.add_album = button\n self.add_album.show()\n self.add_album.connect('clicked', self.__add_album_clicked_cb)\n self.insert(self.add_album,-1)\n \n fn = os.path.join(os.getcwd(),'assets','stack_del.png')\n button = ImageButton()\n tooltip = _(\"Delete Album Stack\")\n button.set_image(fn,tip=tooltip)\n button.connect('clicked', self.__delete_album_clicked_cb)\n self.insert(button,-1)\n\n fn = os.path.join(os.getcwd(),'assets','trash_del.png')\n button = ImageButton()\n tooltip = _(\"Remove Trash Images from XO\")\n button.set_image(fn,tip=tooltip)\n self.empty_journal_button = button\n self.empty_journal_button.hide()\n self.empty_journal_button.connect('clicked',self.__empty_trash_clicked_cb)\n self.insert(self.empty_journal_button,-1)\n \n\n\n \"\"\"\n separator = gtk.SeparatorToolItem()\n separator.props.draw = False\n separator.set_expand(True)\n self.insert(separator, -1)\n separator.show()\n \n self.share = ToolComboBox(label_text=_('Traceback:'))\n self.share.combo.connect('changed', self.__traceback_changed_cb)\n self.share.combo.append_item(\"traceback_plain\", _('Plain'))\n self.share.combo.append_item('traceback_context', _('Context'))\n self.share.combo.append_item('traceback_verbose', _('Verbose'))\n self.insert(self.share, -1)\n self.share.show()\n\n self._update_share()\n \"\"\"\n separator = gtk.SeparatorToolItem()\n separator.props.draw = False\n separator.set_expand(True)\n self.insert(separator, -1)\n separator.show()\n\n self.keep = ToolButton()\n self.keep.set_tooltip(_('Save and Start New'))\n #client = gconf.client_get_default()\n #color = XoColor(client.get_string('/desktop/sugar/user/color'))\n #keep_icon = Icon(icon_name='document-save', xo_color=color)\n keep_icon = Icon(icon_name='document-save')\n keep_icon.show()\n self.keep.set_icon_widget(keep_icon)\n #self.keep.props.accelerator = 'S'\n self.keep.connect('clicked', self.__keep_clicked_cb)\n self.insert(self.keep, -1)\n self.keep.show()\n \n self.stop = ToolButton('activity-stop')\n self.stop.set_tooltip(_('Stop'))\n #self.stop.props.accelerator = 'Q'\n self.stop.connect('clicked', self.__stop_clicked_cb)\n self.insert(self.stop, -1)\n self.stop.show()\n self._update_title_sid = None\n \n def set_label(self,text,visible=True):\n self.label.set_text(text)\n if not visible:\n self.title.set_sensitive(False)\n else:\n self.title.set_sensitive(True)\n \n def _update_share(self):\n self._updating_share = True\n\n if self._activity.props.max_participants == 1:\n self.share.hide()\n\n if self._activity.get_shared():\n self.share.set_sensitive(False)\n self.share.combo.set_active(1)\n else:\n self.share.set_sensitive(True)\n self.share.combo.set_active(0)\n\n self._updating_share = False\n \n def __add_album_clicked_cb (self,button):\n title = self.title.get_text()\n self._activity.activity_toolbar_add_album_cb(title)\n \n def __delete_album_clicked_cb (self,button):\n self._activity.activity_toolbar_delete_album_cb()\n \n def __empty_trash_clicked_cb(self,button):\n self._activity.activity_toolbar_empty_trash_cb()\n \n def __traceback_changed_cb(self, combo):\n model = self.share.combo.get_model()\n it = self.share.combo.get_active_iter()\n (scope, ) = model.get(it, 0)\n if scope == 'traceback_plain':\n self._activity.traceback = 'Plain'\n self._activity.debug_dict['traceback'] = 'plain'\n elif scope == 'traceback_context':\n self._activity.traceback = 'Context' \n self._activity.debug_dict['traceback'] = 'context'\n elif scope == 'traceback_verbose':\n self._activity.traceback = 'Verbose'\n self._activity.debug_dict['traceback'] = 'verbose'\n self._activity.set_ipython_traceback()\n \n def __keep_clicked_cb(self, button):\n self._activity.save_icon_clicked = True\n self._activity.copy()\n\n def __stop_clicked_cb(self, button):\n self._activity.stop()\n\n def __jobject_updated_cb(self, jobject):\n self.title.set_text(jobject['title'])\n\n def __title_changed_cb(self, entry):\n if not self._update_title_sid:\n self._update_title_sid = gobject.timeout_add(\n 1000, self.__update_title_cb)\n\n def __update_title_cb(self, entry=None):\n title = self.title.get_text()\n if self._activity.game.is_journal():\n self._activity.metadata['title'] = title\n self._activity.metadata['title_set_by_user'] = '1'\n else:\n self._activity.game.change_album_name(title)\n title_set_by_user = self._activity.metadata.get('title_set_by_user')\n if not title_set_by_user: #let the journal title reflect the most recent stack\n self._activity.metadata['title'] = title \n self._update_title_sid = None\n \n return False\n\n def _add_widget(self, widget, expand=False):\n tool_item = gtk.ToolItem()\n tool_item.set_expand(expand)\n\n tool_item.add(widget)\n widget.show()\n\n self.insert(tool_item, -1)\n tool_item.show()\n\n def __activity_shared_cb(self, activity):\n self._update_share()\n\n def __max_participants_changed_cb(self, activity, pspec):\n self._update_share()\n\nclass ImageButton(ToolButton):\n def __init__(self):\n ToolButton.__init__(self)\n \n def set_image(self,from_file,tip=None,x=60,y=60):\n pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(from_file,x,y)\n self.image = gtk.Image()\n self.image.set_from_pixbuf(pixbuf)\n self.image.show()\n self.set_icon_widget(self.image)\n if tip:\n self.set_tooltip(tip)\n self.show()\n \nclass ActivityToolbox(Toolbox):\n \"\"\"Creates the Toolbox for the Activity\n \n By default, the toolbox contains only the ActivityToolbar. After creating\n the toolbox, you can add your activity specific toolbars, for example the\n EditToolbar.\n \n To add the ActivityToolbox to your Activity in MyActivity.__init__() do:\n \n # Create the Toolbar with the ActivityToolbar: \n toolbox = activity.ActivityToolbox(self)\n ... your code, inserting all other toolbars you need, like EditToolbar\n \n # Add the toolbox to the activity frame:\n self.set_toolbox(toolbox)\n # And make it visible:\n toolbox.show()\n \"\"\"\n def __init__(self, activity):\n Toolbox.__init__(self)\n \n self._activity_toolbar = ActivityToolbar(activity)\n self.add_toolbar(_('Activity'), self._activity_toolbar)\n self._activity_toolbar.show()\n\n def get_activity_toolbar(self):\n return self._activity_toolbar\n\n\n","sub_path":"photo_toolbar.py","file_name":"photo_toolbar.py","file_ext":"py","file_size_in_byte":10013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"198304639","text":"from micropython import const\nfrom microbit import *\nimport neopixel\n\n\n# config\nr = const(0)\ng = const(64)\nb = const(0)\npx = const(12)\nd = const(30)\nm = const(5)\n\ndef gesture_captured(x):\n pin0.write_digital(x)\n\n\n# ring\nnp = neopixel.NeoPixel(pin1, px)\nnp.clear()\n\n\nwhile True:\n\n if accelerometer.was_gesture('shake') is True:\n gesture_captured(True)\n\n deactivate = False\n accelerometer.get_gestures()\n\n while True:\n for i in range(0, px - 1):\n np[i] = (r, g, b)\n np.show()\n sleep(d)\n np.clear()\n if accelerometer.was_gesture('shake') is True:\n accelerometer.get_gestures()\n gesture_captured(False)\n deactivate = True\n break\n\n if deactivate:\n break\n\n sleep(d * m)\n","sub_path":"tests/features/steps/source/microbit.py","file_name":"microbit.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"66717180","text":"from aredis import StrictRedis\n\nclass RedisUtil(object):\n\n _instance = None\n\n @classmethod\n def instance(cls):\n if not cls._instance:\n cls._instance = cls()\n return cls._instance\n\n\n def __init__(self):\n print(\"创建RedisUtil实例\")\n self._redis_conn = StrictRedis(host='localhost',port=6379,decode_responses=True)\n \n async def get(self,key):\n res = await self._redis_conn.get(key)\n return res","sub_path":"python/benchmark/fastapi/redisUtil.py","file_name":"redisUtil.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"357151567","text":"import threading\n\nclass SocketReadUtils(threading.Thread):\n \n def __init__(self, socket, name, stopper):\n threading.Thread.__init__(self)\n self.name = name\n self.socket = socket\n self.callbacks = {}\n self.stopper = stopper\n\n def registerCallback(self, registrationObject):\n if registrationObject.getArgument not in self.callbacks:\n self.callbacks[registrationObject.getArgument()] = registrationObject.getFunction()\n return True\n return False\n\n def triggerCallBack(self, triggerString):\n if triggerString not in self.callbacks:\n return False\n\n self.callbacks[triggerString]()\n return True\n \n def run(self):\n while True:\n data = self.socket.recv(1024).decode('utf-8')\n if self.triggerCallBack(data):\n print(\"Successfully\")\n \n","sub_path":"Hardware/Utils/SocketReadUtils.py","file_name":"SocketReadUtils.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"41616323","text":"from bayesdend.inf_method.inference import *\nfrom bayesdend.inf_method.optimizer_factory import *\nfrom bayesdend.utils.debug_util import *\n\n\nclass GUMBEL(Inference):\n \"\"\"\n GUMBEL inference method\n \"\"\"\n\n def __init__(self, Nb, data_ph, *args, **kargs):\n super().__init__(*args, **kargs)\n self.Nb = Nb\n self.data_ph = data_ph\n\n def objective(self, from_rec, from_gen):\n \"\"\"\n get the train op and obj op\n :return:\n \"\"\"\n logPrior = from_rec[0]\n logPost = from_rec[1]\n logLikhood = from_gen\n\n beta = 1.0\n # elbo\n self.elbo = tf.reduce_mean(1.0 / beta * logLikhood + logPrior - logPost)\n variable_summaries(self.elbo, 'obj/elbo')\n\n # multi-sample objective\n # [num_samples, batch_size]\n minibatch_obj = tf.reduce_logsumexp(1.0 / beta * logLikhood + logPrior - logPost, axis=0) - np.log(self.Nb)\n obj = tf.reduce_mean(minibatch_obj)\n\n # adding summary\n variable_summaries(logPrior, 'obj/Prior')\n variable_summaries(logLikhood, 'obj/Liklihood')\n variable_summaries(logPost, 'obj/Posterior')\n tf.summary.scalar('obj/Obj', obj)\n tf.summary.scalar('obj/ELBO', self.elbo)\n\n return obj\n\n def optimizer1(self, obj):\n # separate the variables, so that we can save, and restore them differently\n opt_func = optimizer_factory[self.optim](learning_rate=self.learning_rate,\n momentum=self.momentum)\n\n # generative variables\n g_grads = tf.gradients(-obj, [v._ref() for v in self.g_var_list])\n assert len(g_grads) == len(self.g_var_list)\n\n # recognition variables\n r_grads = tf.gradients(-obj, [v._ref() for v in self.r_var_list])\n assert len(r_grads) == len(self.r_var_list)\n\n self.tvars = self.g_var_list + self.r_var_list\n grads = g_grads + r_grads\n self.grads, _ = tf.clip_by_global_norm(grads, 1.)\n train = opt_func.apply_gradients(zip(self.grads, self.tvars))\n return train\n\n def optimizer_dend(self, obj):\n # train later the generative model\n opt_func = optimizer_factory[self.optim](learning_rate=self.learning_rate,\n momentum=self.momentum)\n # generative variables\n g_grads = []\n #for v in self.g_var_list:\n #if 'sigma_spine' in v.name:\n #g_grads.append(tf.gradients(-obj, v)[0] * self.data_ph['control_flag'])\n #else:\n for v in self.g_var_list:\n g_grads.append(tf.gradients(-obj, v)[0])\n\n # recognition variables\n r_grads = tf.gradients(-obj, [v for v in self.r_var_list])\n\n grads = g_grads + r_grads\n self.tvars = self.g_var_list + self.r_var_list\n self.grads, _ = tf.clip_by_global_norm(grads, 1.)\n\n train = opt_func.apply_gradients(zip(self.grads, self.tvars))\n return train\n\n\n def optimizer(self, obj):\n # train later the generative model\n opt_func = optimizer_factory[self.optim](learning_rate=self.learning_rate,\n momentum=self.momentum)\n tvars = self.g_var_list + self.r_var_list\n grads, self.tvars = zip(*opt_func.compute_gradients(-obj, var_list=tvars))\n self.grads, _ = tf.clip_by_global_norm(grads, 1.)\n grads_and_vars = list(zip(self.grads, self.tvars))\n train = opt_func.apply_gradients(grads_and_vars)\n return train\n","sub_path":"bayesdend/inf_method/gumbel.py","file_name":"gumbel.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"248188542","text":"import logging\n\ndef send_log(module_name):\n\n logger = logging.getLogger(module_name)\n logger.setLevel(logging.DEBUG)\n\n# console = logging.StreamHandler()\n# console.setLevel(logging.DEBUG)\n logfile = logging.FileHandler('logfile_test1.log')\n logfile.setLevel(logging.DEBUG)\n\n# formatter_console = logging.Formatter('{asctime} - {name} - {levelname} - {message}',\n# datefmt='%H:%M:%S', style='{')\n message = \"\\n{} - {}:\\n{}\\n{}\".format('{asctime}',\n '{levelname}','{message}','-'*80)\n\n formatter_logfile = logging.Formatter(message, datefmt='%H:%M:%S', style='{')\n\n\n# console.setFormatter(formatter_console)\n# logger.addHandler(console)\n\n logfile.setFormatter(formatter_logfile)\n logger.addHandler(logfile)\n\n return logger\n","sub_path":"olt_logging.py","file_name":"olt_logging.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"388803271","text":"'''\r\nName: part4.py\r\nAuthor: Zhengchao Yu \r\nDate: 10/1/2014\r\nSection: 4\r\nE-Mail: zy3@umbc.edu\r\nAssignment Description:\r\nWrite a program that prints out a triangle made of the * character.\r\n'''\r\ndef main():\r\n\r\n triangle = 0\r\n\r\n # Prompt the user to enter the height of the triangle.\r\n # Cast input to an int\r\n triangHeight = int(input(\"Please enter the height of your triangle: \"))\r\n\r\n # Assign triangle characer \r\n triangleCharacter = '*'\r\n rightTriangle = ''\r\n\r\n # This while loop will take user input and print triangle\r\n while triangle < triangHeight:\r\n rightTriangle = rightTriangle + triangleCharacter\r\n print (rightTriangle)\r\n print()\r\n triangle = triangle + 1\r\n\r\nmain()\r\n","sub_path":"HW03/part4.py","file_name":"part4.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"206128759","text":"from gym import Env\nfrom gym.spaces import Discrete, MultiDiscrete \nimport numpy as np\n\nfrom scenario_stepper import ScenarioStepper\n\nclass ScenarioEnv(Env):\n def __init__(self, numberOfMissles, tD1, tD2, tD3, tD4, tD5, tD6):\n # Actions we can take: 0 - Do Nothing, 1 - Launch\n self.action_space = Discrete(7)\n # Target Damage state array: 0 - Untouched, 1 - Disabled, 2 - Destroyed\n self.observation_space = MultiDiscrete([100, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14])\n # store initial state\n self.numberOfMissles = numberOfMissles\n self.tD1 = tD1\n self.tD2 = tD2\n self.tD3 = tD3\n self.tD4 = tD4\n self.tD5 = tD5\n self.tD6 = tD6\n # Set start state\n self.state = np.array([self.numberOfMissles, self.tD1, self.tD2, self.tD3, self.tD4, self.tD5, self.tD6, 0, 0, 0 ,0 ,0 ,0])\n self.stepper = ScenarioStepper()\n\n def step(self, action):\n # Return step information\n return self.stepper.step(self.state, action)\n\n def render(self):\n # Implement viz\n pass\n\n def reset(self):\n # Reset shower temperature\n self.state = np.array([self.numberOfMissles, self.tD1, self.tD2, self.tD3, self.tD4, self.tD5, self.tD6, 0, 0, 0 ,0 ,0 ,0])\n return self.state\n","sub_path":"Backend/agent-server/scenario_env.py","file_name":"scenario_env.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"490564929","text":"import pandas as pd\nfrom sqlalchemy import create_engine\n\ndef co2_emission(total_co2_emission):\n co2_dataframe = pd.DataFrame.from_dict(total_co2_emission, orient='index', columns=['CO2'])\n co2_dataframe.reset_index(level=0, inplace=True)\n co2_dataframe = co2_dataframe.rename(columns={'index': 'DateTime'})\n co2_dataframe['DateTime'] = co2_dataframe['DateTime'].astype('datetime64')\n engine = create_engine('mysql+mysqlconnector://root:Pravi123@localhost/generation_data', echo=True)\n co2_dataframe.to_sql(con=engine, name='test1', if_exists='replace')","sub_path":"data_parsing/emission_factor.py","file_name":"emission_factor.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"289020888","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nimport time\nimport random\nimport scrapy\n\nfrom ..items import AccountItem\n\nbase_headers = {\n \"Connection\": \"keep-alive\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/78.0.3904.108 Safari/537.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,\"\n \"application/signed-exchange;v=b3\",\n}\n\n\nclass WechatSpider(scrapy.Spider):\n name = 'wechat'\n allowed_domains = ['weixin.sogou.com']\n\n # '搜公众号'url格式\n page_account_url = 'https://weixin.sogou.com/weixin?' \\\n 'type=1&query={word}&_sug_type_=&s_from=input&_sug_=y&ie=utf8&page={page}'\n\n def start_requests(self):\n from . import get_keywords\n keyrords = get_keywords()\n\n account_headers = base_headers\n account_headers[\"Sec-Fetch-Site\"] = \"same-origin\"\n account_headers[\"Referer\"] = \"https://weixin.sogou.com/\"\n\n word = '牛顿'\n for page in range(1, 3):\n time.sleep(random.uniform(3, 6))\n yield scrapy.Request(url=self.page_account_url.format(word=word, page=page), headers=account_headers,\n dont_filter=True, callback=self.parse)\n\n def parse(self, response):\n \"\"\"\n '搜公众号'之帐号解析\n \"\"\"\n self.logger.debug(response)\n infos = response.xpath('//div[@class=\"news-box\"]/ul[@class=\"news-list2\"]//li')\n for info in infos:\n item = AccountItem()\n item['name'] = ''.join(info.xpath('./div//a//text()').extract())\n item['account'] = info.xpath('./div//label[@name=\"em_weixinhao\"]/text()').extract_first()\n dls = info.xpath('./dl')\n for dl in dls:\n key = dl.xpath('./dt/text()').extract_first()\n if key == '功能介绍:':\n item['introduction'] = ''.join(dl.xpath('./dd//text()').extract())\n elif key == '微信认证:':\n item['authentication'] = ''.join(dl.xpath('./dd//text()').extract())\n elif key == '最近文章:':\n item['recent_article'] = ''.join(dl.xpath('./dd/a//text()').extract())\n timestamp = dl.xpath('./dd/span//text()').re_first('document.write\\(timeConvert\\(\\'(.*?)\\'\\)\\)')\n if timestamp:\n d_time = datetime.fromtimestamp(int(timestamp))\n time_str = d_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n item['update_time'] = time_str\n yield item\n","sub_path":"spider_niu_dun/niu_dun/spiders/wechat.py","file_name":"wechat.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"328694628","text":"#coding:utf8\nimport markdown\nfrom django import template\nfrom django.template.defaultfilters import stringfilter\nfrom django.utils.encoding import force_unicode\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library() # 自定义filter时必须加上\n@register.filter(is_safe=True) # 注册template filter\n@stringfilter # 希望字符串作为参数\ndef custom_markdown(value):\n extensions = [\n 'markdown.extensions.fenced_code', # 解析代码块\n 'markdown.extensions.codehilite', # codehilite即为代码高亮准备\n # 'markdown.extensions.table', # 解析表格\n # 'markdown.extensions.toc', # 解析目录TOC\n ]\n return mark_safe(markdown.markdown(force_unicode(value),\n extensions,\n safe_mode=True,\n enable_attributes=False))\n","sub_path":"Blog/templatetags/custom_markdown.py","file_name":"custom_markdown.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"532061222","text":"#coding=utf-8\nimport re # 正则表达式\nimport bs4 # Beautiful Soup 4 解析模块\nimport urllib # 网络访问模块\nimport News #自己定义的新闻结构\nimport pymysql\nimport sys #1解决不同页面编码问题\nreload(sys) # 2\nsys.setdefaultencoding('utf-8') # 3\n\n# 从首页获取所有链接\ndef GetAllUrl(home):\n html = urllib.urlopen(home).read()\n soup = bs4.BeautifulSoup(html, 'html.parser')\n pattern ='http://news.163.com/(.*?)/(.*?)/(.*?)/(.*?)'\n links = soup.find_all('a', href=re.compile(pattern))\n for link in links:\n url_set.add(link['href'])\n\ndef GetNews():\n while len(url_set) != 0:\n try:\n # 获取链接\n url = url_set.pop()\n url_old.add(url)\n # 获取信息\n article = News.News()\n article.url = url # URL信息\n html = urllib.urlopen(article.url).read()\n html = html.decode('gbk')\n html=html.encode('utf8')\n soup = bs4.BeautifulSoup(html, 'html.parser')\n article.title = soup.find('title').get_text() # 标题信息\n keywords='keywords'\n res0 = re.compile(keywords)\n if soup.find('meta', {'name': res0}).__getitem__('name') == \"keywords\":\n article.keywords = soup.find('meta', {'name': res0}).__getitem__('content') # 作者\n else:\n article.keywords = \"\"\n author = 'article:author'\n res = re.compile(author)\n if soup.find('meta', {'property': res}).__getitem__('property') == \"article:author\":\n article.author = soup.find('meta', {'property': res}).__getitem__('content') # 作者\n else:\n article.author = \"\"\n published_time = 'article:published_time'\n res1 = re.compile(published_time)\n if soup.find('meta', {'property': res1}).__getitem__('property') == \"article:published_time\":\n article.date = soup.find('meta', {'property': res1}).__getitem__('content') # 作者\n else:\n article.date = \"\"\n content = soup.select('.post_text')\n article.content = content[0].text\n SaveNews(article)\n except Exception as e:\n print(e)\n continue\n\ndef SaveNews(object):\n try:\n conn = pymysql.connect(host='localhost', user='root', passwd='', db='web_data', port=3306, charset='utf8')\n cur = conn.cursor()\n cur.execute('insert into data(title,content, author,date,url,keywords) values(%s,%s,%s,%s,%s,%s)',\n (object.title, object.content, object.author, object.date, object.url, object.keywords))\n conn.commit()\n cur.close()\n conn.close()\n except Exception:\n print('error')\n\ndef showNews():\n try:\n conn = pymysql.connect(host='localhost', user='root', passwd='', db='web_data', port=3306, charset='utf8')\n cur = conn.cursor()\n cur.execute('select * from data ')\n news_data = cur.fetchall()\n for j in news_data:\n print(\"title:\" + str(j[1]) + '\\n' + 'content:' + j[2] + '\\n' + \"author:\" + str(j[3]) + '\\n' + \"date:\" + j[\n 4] + '\\n' + \"url:\" + j[5] + 'keywords:' + str(j[6]))\n print (\"*****************************************************************\")\n except Exception:\n print('error')\n\n\nurl_set = set() # url集合\nurl_old = set() # 爬过的url集合\nhome ='http://news.163.com/' # 起始位置\nGetAllUrl(home)\nprint(url_set)\nGetNews()\n#showNews()\n\n","sub_path":"Spider/spider_163.py","file_name":"spider_163.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"16032076","text":"import numpy as np\n\nfrom PySide2.QtCore import *\n\nclass BufferedSource(QObject):\n update = Signal()\n rowsChanged = Signal()\n colsChanged = Signal()\n \n def __init__(self, length, channels, shared=False, parent=None):\n QObject.__init__(self, parent)\n self._shared = shared\n\n self.init(length, channels)\n\n @Property(int, notify=colsChanged)\n def channels(self):\n return self._arr.shape[0]\n\n @Property(int, notify=rowsChanged)\n def length(self):\n return self._arr.shape[1]\n\n @Property(QByteArray, notify=update)\n def array(self):\n if self._shared:\n return self._buf\n else:\n return QByteArray(self._arr.tobytes())\n\n @property\n def shared(self):\n return self._shared\n\n def copy_from(self, arr):\n self.init(arr.shape[1], arr.shape[0])\n self._arr[:] = arr\n\n self.rowsChanged.emit()\n self.colsChanged.emit()\n self.update.emit()\n\n def init(self, length, channels):\n if self._shared:\n self._buf = QByteArray(length*channels*4, 0)\n self._arr = np.frombuffer(memoryview(self._buf), dtype=np.float32).reshape(channels, length)\n else:\n self._arr = np.zeros((channels, length), dtype=np.float32)\n\n def consume(self, buf):\n # channels must match\n assert buf.shape[0] == self._arr.shape[0]\n\n l = buf.shape[1]\n self._arr[..., :-l] = self._arr[..., l:]\n self._arr[..., -l:] = buf\n\n self.update.emit()","sub_path":"Buffer.py","file_name":"Buffer.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"261304500","text":"from ime_fgs.basic_nodes import MatrixNode, AdditionNode, PriorNode, EqualityNode\r\nfrom ime_fgs.messages import GaussianMeanCovMessage, GaussianWeightedMeanInfoMessage\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nfrom ime_fgs.plot import draw_graph\r\nfrom ime_fgs.utils import col_vec, row_vec\r\n\r\n## Initial position of drone\r\nx_d = np.array([1, 2])\r\n# x_d = x_d.reshape(1,2)\r\nprint(x_d)\r\n## Initial position of anchors\r\nx_A1 = np.array([0,0])\r\nx_A2 = np.array([4,0])\r\nx_A3 = np.array([2,4])\r\n## Ground truth distance: Here x=(x_co-ordinate, y_co-ordinate)\r\nz_12 = np.linalg.norm(x_A1-x_d)- np.linalg.norm(x_A2-x_d)\r\nz_13 = np.linalg.norm(x_A1-x_d)- np.linalg.norm(x_A3-x_d)\r\nz_23 = np.linalg.norm(x_A2-x_d)- np.linalg.norm(x_A3-x_d)\r\nprint(z_12,z_13,z_23 )\r\n\r\n## Measurement Variance\r\nmeas_var = 0.1**2\r\n\r\n##Sample noise for each measurement\r\nz_12 =z_12 + np.random.multivariate_normal([0], [[meas_var]])\r\nz_13 =z_13 + np.random.multivariate_normal([0], [[meas_var]])\r\nz_23 =z_23 + np.random.multivariate_normal([0], [[meas_var]])\r\n\r\nz_12_msg = GaussianMeanCovMessage(np.atleast_2d(z_12), [[meas_var]])\r\nz_13_msg = GaussianMeanCovMessage(np.atleast_2d(z_13), [[meas_var]])\r\nz_23_msg = GaussianMeanCovMessage(np.atleast_2d(z_23), [[meas_var]])\r\n\r\npos_var = 1 * np.eye(2)\r\nx_d0 = x_d + np.random.multivariate_normal([0, 0], pos_var)\r\n#initial position with the corresponding covariance matrix for the message\r\nx_d_msg = GaussianMeanCovMessage(col_vec(x_d0), pos_var)\r\n\r\n# Create all relevant nodes\r\nx_dtilted = np.array([3, 3])\r\n\r\nD_12 = np.linalg.norm(x_A1-x_dtilted)- np.linalg.norm(x_A2-x_dtilted) - row_vec((((x_A2-x_dtilted)/np.linalg.norm(x_A2-x_dtilted))-((x_A1-x_dtilted)/np.linalg.norm(x_A1-x_dtilted))))@col_vec(x_dtilted)\r\nB_12 = row_vec((x_A2-x_dtilted)/np.linalg.norm(x_A2-x_dtilted)-(x_A1-x_dtilted)/np.linalg.norm(x_A1-x_dtilted))\r\nD_13 = np.linalg.norm(x_A1-x_dtilted)- np.linalg.norm(x_A3-x_dtilted) - row_vec((((x_A3-x_dtilted)/np.linalg.norm(x_A3-x_dtilted))-((x_A1-x_dtilted)/np.linalg.norm(x_A1-x_dtilted))))@col_vec(x_dtilted)\r\nB_13 = row_vec(((x_A3-x_dtilted)/np.linalg.norm(x_A3-x_dtilted)-(x_A1-x_dtilted)/np.linalg.norm(x_A1-x_dtilted)))\r\nD_23 = np.linalg.norm(x_A2-x_dtilted)- np.linalg.norm(x_A3-x_dtilted) - row_vec((((x_A3-x_dtilted)/np.linalg.norm(x_A3-x_dtilted))-((x_A2-x_dtilted)/np.linalg.norm(x_A2-x_dtilted))))@col_vec(x_dtilted)\r\nB_23 = row_vec(((x_A3-x_dtilted)/np.linalg.norm(x_A3-x_dtilted)-(x_A2-x_dtilted)/np.linalg.norm(x_A2-x_dtilted)))\r\n\r\n\r\n\r\nz_12_node = PriorNode(name = \"z_12_node\")\r\nz_13_node = PriorNode(name = \"z_13_node\")\r\nz_23_node = PriorNode(name = \"z_23_node\")\r\n\r\nD_12_node = PriorNode(name=\"D_12\")\r\nD_13_node = PriorNode(name=\"D_13\")\r\nD_23_node = PriorNode(name=\"D_23\")\r\n#D_12_node = MatrixNode(D_12, name = \"D_12\")\r\n#D_13_node = MatrixNode(D_13, name = \"D_13\")\r\n#D_23_node = MatrixNode(D_23, name = \"D_23\")\r\n\r\nB_12_node = MatrixNode(B_12, name = \"B_12\")\r\nB_13_node = MatrixNode(B_13, name = \"B_13\")\r\nB_23_node = MatrixNode(B_23, name = \"B_23\")\r\n\r\nadd_function12_node = AdditionNode(name = \"add_function_node\")\r\nadd_function13_node = AdditionNode(name = \"add_function_node\")\r\nadd_function23_node = AdditionNode(name = \"add_function_node\")\r\nequality_node = EqualityNode(name=\"=\", number_of_ports=4)\r\nx_d_node = PriorNode(name=\"x_d\")\r\n\r\n# Connect the nodes together with the .connect function\r\nx_d_node.port_a.connect(equality_node.ports[0])\r\nz_12_node.port_a.connect(add_function12_node.port_c)\r\nz_13_node.port_a.connect(add_function13_node.port_c)\r\nz_23_node.port_a.connect(add_function23_node.port_c)\r\n\r\nD_12_node.port_a.connect(add_function12_node.port_b)\r\nD_13_node.port_a.connect(add_function13_node.port_b)\r\nD_23_node.port_a.connect(add_function23_node.port_b)\r\n\r\nB_12_node.port_b.connect(add_function12_node.port_a)\r\nB_13_node.port_b.connect(add_function13_node.port_a)\r\nB_23_node.port_b.connect(add_function23_node.port_a)\r\n\r\nB_12_node.port_a.connect(equality_node.ports[1])\r\nB_13_node.port_a.connect(equality_node.ports[2])\r\nB_23_node.port_a.connect(equality_node.ports[3])\r\n\r\ndraw_graph(x_d_node)\r\n\r\n# pass message through graph and relinearize\r\nestimated_state_list12 = []\r\nestimated_state_list13 = []\r\nestimated_state_list23 = []\r\n\r\n# use last state estimation for new state estimation\r\nz = z_12_node.update_prior(z_12_msg)\r\nadd_function12_node.port_c.update(z)\r\nd = D_12_node.port_a.update(D_12)\r\nadd_function12_node.port_b.update(d)\r\nadd_function12_node.port_a.update(z+d)\r\nB_12_node.port_a.update(z+d)\r\nb = B_12_node.port_b.update((z-d)/B_12)\r\nequality_node.ports[1].update(b)\r\n\r\nz = z_13_node.update_prior(z_13_msg)\r\nadd_function13_node.port_c.update(z)\r\nd = D_13_node.port_a.update(D_13)\r\nadd_function13_node.port_b.update(d)\r\nadd_function13_node.port_a.update(z+d)\r\nB_13_node.port_a.update(z+d)\r\nb = B_13_node.port_b.update((z-d)/B_13)\r\nequality_node.ports[2].update(b)\r\n\r\nz = z_23_node.update_prior(z_23_msg)\r\nadd_function23_node.port_c.update(z)\r\nd = D_23_node.port_a.update(D_23)\r\nadd_function23_node.port_b.update(d)\r\nadd_function23_node.port_a.update(z+d)\r\nB_23_node.port_a.update(z+d)\r\nb = B_23_node.port_b.update((z-d)/B_23)\r\nequality_node.ports[3].update(b)\r\n\r\nequality_node.ports[0].update(x_d_msg)\r\n\r\n","sub_path":"Project/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"97775203","text":"#상, 하, 좌, 우 검색하고 연못이 있고(1이고) and 방문하지 않았으면 이동해서 다시 검사하기.\ndef dfs(x,y):\n visited.append((x,y))\n for d in range(4):\n new_x = x + d_x[d]\n new_y = y + d_y[d]\n if 0 <= new_x < M and 0 <= new_y < N and pond[new_x][new_y] == 1 and (new_x, new_y) not in visited:\n dfs(new_x, new_y)\n\n\n\n# 0으로 채워진 이차배열 초기화 후 연못 개수와 좌표를 받아서 1로 바꾸기.\nfor tc in range(1, int(input()) + 1):\n N, M, K = map(int, input().split())\n pond = [[0]*N for _ in range(M)]\n #입력받는 좌표가 가로좌표 열 먼저 행 나중임으로 이를 주의해서 입력받는다.\n for _ in range(K):\n b, a = map(int,input().split())\n pond[a][b] = 1\n # 연못이 연결되었는지 여부는 위, 아래 양옆(오른쪽, 왼쪽)이 연결되어있는지 여부이다.\n # dfs 함수를 통해 연결된 연못을 센다.\n # 이 때 이미 방문한 연못은 visited에 저장하고 세지 않는다.\n visited = []\n #상, 하, 좌, 우 델타이동 하기\n d_x = [0, 0, 1, -1]\n d_y = [-1, 1, 0, 0]\n #물고기 수\n cnt = 0\n #배열을 돌면서 1이면서 방문하지 않은 연못이 있다면 함수 ��출해서 이어진 연못이 있는지 체크\n # 체크가 끝나면 cnt += 1 해줌(물고기 수)\n for c in range(M):\n for d in range(N):\n if pond[c][d] == 1 and (c,d) not in visited:\n dfs(c,d)\n cnt += 1\n\n print('{}'.format(cnt))","sub_path":"9월 알고리즘/요리사.py","file_name":"요리사.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"438843148","text":"import numpy as np \nfrom numpy.linalg import inv\nfrom math import *\n\nclass MyLinearRegression(object):\n\t\"\"\" Description: My personnal linear regression class to fit like a boss. \n\t\"\"\"\n\tdef __init__(self, theta):\n\t\t\"\"\" Description:\n\t\tgenerator of the class, initialize self.\n\t\tArgs:\n\t\t\ttheta: has to be a list or a numpy array,\n\t\t\tit is a vector ofdimension (number of features + 1, 1).\n\t\t\tRaises:\n\t\t This method should noot raise any Exception. \n\t\t\"\"\"\n\t\tif (not isinstance(theta, list) and not isinstance(theta, np.ndarray)\n\t\tand theta.shape[1] != 1):\n\t\t\tprint(\"error\")\n\t\tif isinstance(theta, list):\n\t\t\ttheta = np.array(theta).reshape(-1,1)\n\t\tself.theta = theta\n\tdef setTheta(self, theta):\n\t\tif (not isinstance(theta, list) and not isinstance(theta, np.ndarray)\n\t\tand theta.shape[1] != 1):\n\t\t\tprint(\"error\")\n\t\tif isinstance(theta, list):\n\t\t\ttheta = np.array(theta)\n\t\tself.theta = theta\t\n\tdef\tconcat(self, X):\n\t\tM = X.shape[0]\n\t\tones = np.ones((M,1))\n\t\tX = np.concatenate((ones,X),axis=1)\n\t\treturn X\n\tdef predict_(self, X):\n\t\tX = self.concat(X)\n\t\treturn X.dot(self.theta)\n\tdef cost_elem_(self, X, Y):\n\t\tM = Y.shape[0]\n\t\tpred = X.dot(self.theta)\n\t\treturn np.power((pred - Y),2) * (0.5 / M)\n\tdef cost_(self, X, Y):\n\t\treturn float(sum(self.cost_elem_(X, Y)))\n\tdef grad_(self, error, X):\n\t\tX = self.concat(X)\n\t\treturn (X.transpose()).dot(error)\n\tdef mse_(self,X, Y):\n\t\tX = self.concat(X)\n\t\terror = X.dot(self.theta) - Y\n\t\tM = float(Y.shape[0])\n\t\treturn float(sum(np.power(error,2)) / M)\n\tdef fit_(self, X, Y, alpha=1.6e-4,n_cycle=200000):\n\t\t# Y = Y.reshape(Y.shape[0],1)\n\t\t# print(\"traning........\")\n\t\tM = Y.shape[0]\n\t\tX = self.concat(X)\n\t\tfor _ in range(int(n_cycle)):\n\t\t\terror = X.dot(self.theta) - Y\n\t\t\tgrad = (X.transpose()).dot(error)\n\t\t\tself.theta = self.theta - alpha * (1. / M ) * 0.5 * grad\n\t\t\tprint(\"cost: {}\".format(self.cost_(X, Y)),end='\\r')\n\t\treturn self.theta\n\tdef normalequation_(self, X, Y):\n\t\tX = self.concat(X)\n\t\tX_t = X.transpose()\n\t\txx_t = X_t.dot(X).astype(np.int)\n\t\tX_ty = X_t.dot(Y)\n\t\txx_ti = inv(xx_t)\n\t\tprint(self.theta.shape)\n\t\tself.theta = (xx_ti.transpose()).dot(X_ty)\n\t\tprint(self.theta.shape)\n\t\treturn self.theta\n\tdef rmse_(self, X, Y):\n\t\treturn float(sqrt(self.mse_(X,Y)))\n\tdef r2score_(self, X, Y):\n\t\tYp = self.predict_(X)\n\t\tmeanY = np.mean(Y)\n\t\tSStot = np.power(Y - meanY, 2)\n\t\tSSres = np.power(Y - Yp, 2)\n\t\treturn float(1 - float(SSres / SStot))\n","sub_path":"day03/mylinearregression.py","file_name":"mylinearregression.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"601250219","text":"from sqlalchemy import Column, Integer, String, Float, create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\n\nBase = declarative_base()\n\n\nclass Foodbank(Base):\n __tablename__ = \"foodbank\"\n id = Column(Integer, primary_key=True)\n name = Column(String)\n address = Column(String)\n postcode = Column(String)\n latitude = Column(Float)\n longitude = Column(Float)\n tel_no = Column(String)\n website = Column(String)\n\n def as_dict(self):\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n\n\nclass FoodbankDatabase(object):\n\n def __init__(self, db_file):\n self.db_engine = create_engine(\"sqlite:///\" + db_file)\n Base.metadata.bind = self.db_engine\n DBSession = sessionmaker(bind=self.db_engine)\n self.session = DBSession()\n\n def create(self, recreate=True):\n print(\"Dropping all database tables.\")\n Base.metadata.drop_all(self.db_engine)\n print(\"Creating database tables.\")\n Base.metadata.create_all(self.db_engine)\n\n def populate(self, foodbanks):\n print(\"Populating database...\")\n for foodbank in foodbanks:\n self.session.add(Foodbank(\n name=foodbank[\"name\"],\n address=foodbank[\"address\"],\n postcode=foodbank[\"postcode\"],\n latitude=foodbank[\"latitude\"],\n longitude=foodbank[\"longitude\"],\n tel_no=foodbank[\"tel_no\"],\n website=foodbank[\"website\"]\n ))\n self.session.commit()\n print(\"Finished populating database.\")\n\n def get_all_foodbanks(self):\n result = self.session.query(Foodbank).all()\n return [f.as_dict() for f in result]\n","sub_path":"src/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"646335967","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\nfrom openeye import oechem\nfrom openeye import oedepict\n\n###############################################################\n# USED TO GENERATE CODE SNIPPETS FOR THE OEDEPICT DOCUMENTATION\n###############################################################\n\n\ndef DrawCubicBezier():\n # @ \n image = oedepict.OEImage(100, 100)\n\n b = oedepict.OE2DPoint(20, 70)\n e = oedepict.OE2DPoint(60, 70)\n c1 = b + oedepict.OE2DPoint(50, -60)\n c2 = e + oedepict.OE2DPoint(50, -60)\n\n pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)\n image.DrawCubicBezier(b, c1, c2, e, pen)\n\n # @ \n oedepict.OEWriteImage(\"DrawCubicBezier.png\", image)\n oedepict.OEWriteImage(\"DrawCubicBezier.pdf\", image)\n\n\ndef DrawPath():\n # @ \n image = oedepict.OEImage(100, 100)\n\n path = oedepict.OE2DPath(oedepict.OE2DPoint(20, 80))\n path.AddLineSegment(oedepict.OE2DPoint(80, 80))\n path.AddLineSegment(oedepict.OE2DPoint(80, 40))\n path.AddCurveSegment(oedepict.OE2DPoint(80, 10), oedepict.OE2DPoint(20, 10),\n oedepict.OE2DPoint(20, 40))\n\n pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)\n image.DrawPath(path, pen)\n\n # @ \n oedepict.OEWriteImage(\"DrawPath.png\", image)\n oedepict.OEWriteImage(\"DrawPath.pdf\", image)\n\n # @ \n for p in path.GetPoints():\n pos = p.GetPoint()\n print(\" %.1f %.1f %d\" % (pos.GetX(), pos.GetY(), p.GetPointType()))\n # @ \n\n\ndef DrawPolygon():\n # @ \n image = oedepict.OEImage(100, 100)\n\n polygon = []\n polygon.append(oedepict.OE2DPoint(20, 20))\n polygon.append(oedepict.OE2DPoint(40, 40))\n polygon.append(oedepict.OE2DPoint(60, 20))\n polygon.append(oedepict.OE2DPoint(80, 40))\n polygon.append(oedepict.OE2DPoint(80, 80))\n polygon.append(oedepict.OE2DPoint(20, 80))\n\n pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)\n image.DrawPolygon(polygon, pen)\n # @ \n oedepict.OEWriteImage(\"DrawPolygon.png\", image)\n oedepict.OEWriteImage(\"DrawPolygon.pdf\", image)\n\n\ndef DrawQuadraticBezier():\n # @ \n image = oedepict.OEImage(100, 100)\n\n b = oedepict.OE2DPoint(20, 70)\n e = oedepict.OE2DPoint(80, 70)\n c = b + oedepict.OE2DPoint(30, -80)\n\n pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)\n image.DrawQuadraticBezier(b, c, e, pen)\n # @ \n oedepict.OEWriteImage(\"DrawQuadraticBezier.png\", image)\n oedepict.OEWriteImage(\"DrawQuadraticBezier.pdf\", image)\n\n\nDrawCubicBezier()\nDrawPath()\nDrawPolygon()\nDrawQuadraticBezier()\n","sub_path":"venv/Lib/site-packages/openeye/docexamples/depict/DrawObjects.py","file_name":"DrawObjects.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"321647776","text":"import os\nfrom os.path import join\n\nfrom bt.source import SRC_URL\nfrom ll.utils import download\n\n\nBASE_URL = SRC_URL + '/nsis/ansi/'\nDST_DIR = join(os.environ['PREFIX'], 'NSIS', 'Plugins', 'x86-ansi')\n\nfor line in [\n '431e5b960aa15af5d153bae6ba6b7e87 UAC.dll',\n '6f7a35da92ba3ebe04a4fc9abe9d6255 untgz.dll',\n '7178d69ded53b7683dd52cd1ca0a20ff elevate.exe',\n '7597202a271542d50e9d1e305a96e485 nsPython.dll',\n ]:\n md5, fn = line.split()\n download(BASE_URL + fn, join(DST_DIR, fn), md5, verbose=True)\n","sub_path":"nsis/add_deps.py","file_name":"add_deps.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"268581544","text":"from flask import Flask, render_template, request, session, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\nfrom flask_mail import Mail\nimport json\nimport math\n\nlocal_server = True\nwith open('config.json', 'r') as c:\n params_data = json.load(c)[\"params\"]\n\napp = Flask(__name__)\napp.secret_key = params_data['secret-key']\napp.config.update(\n MAIL_SERVER='smtp.gmail.com',\n MAIL_PORT='465',\n MAIL_USE_SSL=True,\n MAIL_USERNAME=params_data[\"gmail-user\"],\n MAIL_PASSWORD=params_data[\"gmail-password\"]\n)\nmail = Mail(app)\n\nif (local_server):\n app.config['SQLALCHEMY_DATABASE_URI'] = params_data['local_uri']\nelse:\n app.config['SQLALCHEMY_DATABASE_URI'] = params_data['prod_uri']\n\ndb = SQLAlchemy(app)\n\n\nclass Contacts(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), nullable=False)\n phone_num = db.Column(db.String(12), nullable=False)\n msg = db.Column(db.String(120), nullable=False)\n date = db.Column(db.String(12), nullable=False)\n email = db.Column(db.String(20), nullable=False)\n\nclass Posts(db.Model):\n sno = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(80), nullable=False)\n tagline = db.Column(db.String(120), nullable=False)\n slug = db.Column(db.String(21), nullable=False)\n content = db.Column(db.String(120), nullable=False)\n img_file = db.Column(db.String(12), nullable=False)\n date = db.Column(db.String(12), nullable=True)\n\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef home():\n posts = Posts.query.filter_by().all()\n last = math.ceil(len(posts)/int(params_data['no_of_posts']))\n page = request.args.get('page')\n if(not str(page).isnumeric()):\n page = 1\n page = int(page)\n posts = posts[(page-1)*int(params_data['no_of_posts']):(page-1)*int(params_data['no_of_posts']) + int(params_data['no_of_posts'])]\n\n if (page ==1):\n prev = \"#\"\n next = \"/?page=\" + str(page+1)\n elif(page==last):\n prev = \"/?page=\" + str(page-1)\n next = \"#\"\n else:\n prev = \"/?page=\" + str(page-1)\n next = \"/?page=\" + str(page+1)\n\n return render_template('index.html', posts=posts, params=params_data, prev=prev, next=next)\n\n@app.route(\"/dashboard\", methods=['GET', 'POST'])\ndef dashboard():\n if 'user' in session and session['user'] == params_data['admin-user']:\n posts = Posts.query.all()\n return render_template('dashboard.html',params=params_data, posts=posts)\n\n if request.method == 'POST':\n username = request.form.get('uname')\n userpass = request.form.get('pass')\n if (username== params_data['admin-user'] and userpass == params_data['admin-password']):\n session['user'] = username\n posts = Posts.query.all()\n return render_template('dashboard.html', params=params_data, posts=posts)\n else:\n return render_template('login.html', params=params_data)\n\n\n else:\n return render_template('login.html', params=params_data)\n\n\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html', params=params_data)\n\n\n@app.route(\"/post/\", methods =['GET'])\ndef post_route(post_slug ):\n post = Posts.query.filter_by(slug=post_slug).first()\n return render_template('post.html', params=params_data, post_html=post)\n\n@app.route(\"/logout\")\ndef logout():\n session.pop(\"user\")\n return redirect(\"/dashboard\")\n\n\n@app.route(\"/contact\", methods=['GET', 'POST'])\ndef contacts():\n if (request.method == 'POST'):\n '''add entery to the database'''\n name = request.form.get('name')\n email = request.form.get('email')\n phone = request.form.get('phone')\n message = request.form.get('message')\n entry = Contacts(name=name, phone_num=phone, msg=message, date=datetime.now(), email=email)\n db.session.add(entry)\n db.session.commit()\n mail.send_message('New Message from Blog' + name,\n sender=params_data[\"gmail-user\"],\n recipients=[email] ,\n body=message + \"\\n\" + phone\n )\n\n return render_template('contact.html', params=params_data)\n\n@app.route(\"/edit/\", methods= ['GET', 'POST'])\ndef edit(sno):\n if ('user' in session and session['user'] == params_data['admin-user']):\n if request.method == 'POST':\n box_title = request.form.get('Title')\n tline = request. form.get('tagline')\n slug = request.form.get('slug')\n content = request.form.get('Content')\n image = request.form.get('Image')\n\n if sno == '0':\n post = Posts(title = box_title, slug=slug, content = content, tagline=tline, img_file = image, date =datetime.now())\n db.session.add(post)\n db.session.commit()\n else:\n post = Posts.query.filter_by(sno=sno).first()\n post.title = box_title\n post.slug = slug\n post.content = content\n post.tagline = tline\n post.img_file = image\n post.date = datetime.now()\n db.session.commit()\n return redirect('/edit/'+sno)\n post = Posts.query.filter_by(sno=sno).first()\n return render_template('edit.html', params =params_data, post=post)\n\n@app.route(\"/delete/\", methods = ['GET', 'POST'])\ndef delete(sno):\n if ('user' in session and session['user'] == params_data['admin-user']):\n post = Posts.query.filter_by(sno=sno).first()\n db.session.delete(post)\n db.session.commit()\n return redirect('/dashboard')\n\n\n\n\n\napp.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"325951675","text":"import mysql.connector\r\n\r\ncon=mysql.connector.connect(host='localhost',user='root',password='roshani1306',database='bookstoredb')\r\ncurs=con.cursor()\r\ntry:\r\n bcode=int(input('Enter bookcode number : '))\r\n\r\n curs.execute(\"select * from books where bookcode=%d\" %bcode)\r\n rec=curs.fetchone()\r\n\r\n if rec:\r\n tr=input('Enter price (increase/decrease) : ')\r\n price=float(input('Enter New price: '))\r\n\r\n if tr.lower().startswith('i'):\r\n curs.execute(\"update books set price=price+%.2f where bookcode=%d\" %(price,bcode))\r\n else:\r\n curs.execute(\"update books set price=price-%.2f where bookcode=%d\" %(price,bcode))\r\n\r\n con.commit()\r\n print('PRICE UPDATED SUCCESSFULLY..')\r\n\r\n con.close()\r\n else:\r\n print('Bookcode does not EXIST..')\r\nexcept:\r\n print('Invalid input...')","sub_path":"07UpdatePrice.py","file_name":"07UpdatePrice.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"127490792","text":"import os\nimport ssl\nimport json\nimport time\nimport logging\nfrom tqdm import tqdm\nfrom datetime import datetime\n\nimport pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms, datasets\nfrom torch.optim.lr_scheduler import (ReduceLROnPlateau, CosineAnnealingLR)\n\nimport data_loader\nfrom data_loader import transform\nfrom data_loader.dataloader import data_split\n\nfrom models import classification as model\nfrom torchvision import models\nfrom utils import metrics as metrics\nfrom utils import logger\nfrom utils import custom_loss\nfrom utils import general\n\nimport trainer\nimport test as tester\nimport argparse\n\n# from torchsampler import ImbalancedDatasetSampler\n\n\ndef main(\n model,\n dataset,\n validation_flag,\n comment=\"No comment\",\n checkpoint=None,\n num_of_class = 2\n ):\n\n # Checking cuda\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n logging.info(\"Using device: {} \".format(device))\n\n if checkpoint is not None:\n print(\"...Load checkpoint from {}\".format(checkpoint))\n checkpoint = torch.load(checkpoint)\n model.load_state_dict(checkpoint['state_dict'])\n print(\"...Checkpoint loaded\")\n \n # Convert to suitable device\n model = model.to(device)\n print(\"Number of parameters: \",sum(p.numel() for p in model.parameters()))\n logging.info(\"Model created...\")\n\n # using parsed configurations to create a dataset\n data = cfg[\"data\"][\"data_csv_name\"]\n print(\"Reading training data from file: \", data)\n training_set = pd.read_csv(data)\n\n # check if validation flag is on\n if validation_flag == 0:\n # using custom validation set\n print(\"Creating validation set from file\")\n valid = cfg[\"data\"][\"validation_csv_name\"]\n print(\"Reading validation data from file: \", valid)\n valid_set = pd.read_csv(valid)\n else:\n # auto divide validation set\n print(\"Splitting dataset into train and valid....\")\n validation_split = float(cfg[\"data\"][\"validation_ratio\"])\n training_set, valid_set, _, _ = data_split(training_set, validation_split)\n print(\"Done Splitting !!!\")\n \n data_path = cfg[\"data\"][\"data_path\"]\n batch_size = int(cfg[\"data\"][\"batch_size\"])\n \n # Create dataset\n training_set = dataset(training_set, data_path, transform.train_transform)\n valid_set = dataset(valid_set, data_path, transform.val_transform)\n\n # End sampler\n train_loader = torch.utils.data.DataLoader(\n training_set, batch_size=batch_size, shuffle=True\n )\n val_loader = torch.utils.data.DataLoader(\n valid_set, batch_size=batch_size, shuffle=False\n )\n logging.info(\"Dataset and Dataloaders created\")\n\n # create a metric for evaluating\n # global train_metrics\n # global val_metrics\n train_metrics = metrics.Metrics(cfg[\"train\"][\"metrics\"])\n val_metrics = metrics.Metrics(cfg[\"train\"][\"metrics\"])\n print(\"Metrics implemented successfully\")\n\n # method to optimize the model\n # read settings from json file\n loss_function = cfg[\"optimizer\"][\"loss\"]\n optimizers = cfg[\"optimizer\"][\"name\"]\n learning_rate = cfg[\"optimizer\"][\"lr\"]\n\n # initlize optimizing methods : lr, scheduler of lr, optimizer\n try:\n # if the loss function comes from nn package\n criterion = getattr(\n nn, loss_function, \"The loss {} is not available\".format(loss_function)\n )\n except:\n # use custom loss\n criterion = getattr(\n custom_loss,\n loss_function,\n \"The loss {} is not available\".format(loss_function),\n )\n criterion = criterion()\n optimizer = getattr(\n torch.optim, optimizers, \"The optimizer {} is not available\".format(optimizers)\n )\n max_lr = 3e-3 # Maximum LR\n min_lr = 1e-5 # Minimum LR\n t_max = 10 # How many epochs to go from max_lr to min_lr\n # optimizer = torch.optim.Adam(\n # params=model.parameters(), lr=max_lr, amsgrad=False)\n optimizer = optimizer(model.parameters(), lr=learning_rate)\n save_method = cfg[\"train\"][\"lr_scheduler_factor\"]\n patiences = cfg[\"train\"][\"patience\"]\n lr_factor = cfg[\"train\"][\"reduce_lr_factor\"]\n scheduler = ReduceLROnPlateau(optimizer, mode = save_method, min_lr = min_lr, patience = patiences, factor = lr_factor)\n # scheduler = CosineAnnealingLR(optimizer, T_max=t_max, eta_min=min_lr)\n\n print(\"\\nTraing shape: {} samples\".format(len(train_loader.dataset)))\n print(\"Validation shape: {} samples\".format(len(val_loader.dataset)))\n print(\"Beginning training...\")\n \n # export the result to log file\n logging.info(\"--------------------------------\")\n logging.info(\"session name: {}\".format(cfg[\"session\"][\"sess_name\"]))\n # logging.info(model)\n logging.info(\"CONFIGS:\")\n logging.info(cfg)\n\n # training models\n num_epoch = int(cfg[\"train\"][\"num_epoch\"])\n best_val_acc = 0\n t0 = time.time()\n for epoch in range(0, num_epoch):\n t1 = time.time()\n print(('\\n' + '%13s' * 3) % ('Epoch', 'gpu_mem', 'mean_loss'))\n train_loss, val_loss, train_result, val_result = trainer.train_one_epoch(\n epoch, num_epoch,\n model, device,\n train_loader, val_loader,\n criterion, optimizer,\n train_metrics, val_metrics, \n )\n scheduler.step(val_loss)\n\n # lr scheduling\n logging.info(\"\\n------Epoch %d / %d, Training time: %.4f seconds------\" % (epoch + 1, num_epoch, (time.time() - t1)))\n logging.info(\"Training loss: {} - Other training metrics: {}\".format(train_loss, train_result))\n logging.info(\"Validation loss: {} - Other validation metrics: {}\".format(val_loss, val_result))\n \n tb_writer.add_scalar(\"Training Loss\", train_loss, epoch + 1)\n tb_writer.add_scalar(\"Valid Loss\", val_loss, epoch + 1)\n tb_writer.add_scalar(\"Training Accuracy\", train_result[\"accuracy_score\"], epoch + 1)\n tb_writer.add_scalar(\"Valid Accuracy\", val_result[\"accuracy_score\"], epoch + 1)\n # tb_writer.add_scalar(\"training f1_score\", train_result[\"f1_score\"], epoch + 1)\n # tb_writer.add_scalar(\"valid f1_score\", val_result[\"f1_score\"], epoch + 1)\n \n # saving epoch with best validation accuracy\n if best_val_acc < float(val_result[\"accuracy_score\"]):\n logging.info(\"Validation accuracy= \"+ str(val_result[\"accuracy_score\"]))\n logging.info(\"====> Save best at epoch {}\".format(epoch+1))\n best_val_acc = val_result[\"accuracy_score\"]\n checkpoint = {\n 'epoch': epoch + 1,\n 'valid_loss': val_loss,\n 'model': model,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }\n torch.save(checkpoint, log_dir + \"/Checkpoint.pt\")\n \n \n # testing on test set\n test_data = cfg[\"data\"][\"test_csv_name\"]\n data_path = cfg[\"data\"][\"data_path\"]\n test_df = pd.read_csv(test_data)\n\n # prepare the dataset\n testing_set = dataset(test_df, data_path, transform.val_transform)\n test_loader = torch.utils.data.DataLoader(testing_set, batch_size=32, shuffle=False)\n print(\"\\nInference on the testing set\")\n\n # load the test model and making inference\n checkpoint = torch.load(log_dir + \"/Checkpoint.pt\")\n test_model = checkpoint['model']\n test_model.load_state_dict(checkpoint['state_dict'])\n test_model = test_model.to(device)\n\n # logging report\n report = tester.test_result(test_model, test_loader, device, cfg)\n logging.info(\"\\nClassification Report: \\n {}\".format(report))\n logging.info('%d epochs completed in %.3f seconds.' % (num_epoch , (time.time() - t0)))\n\n print(\"Classification Report: \\n{}\".format(report))\n print('%d epochs completed in %.3f seconds.' % (num_epoch , (time.time() - t0)))\n print(f'Start Tensorboard with \"tensorboard --logdir {log_dir}\", view at http://localhost:6006/')\n # # saving torch models\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='NA')\n parser.add_argument('-c', '--configure', default='cfgs/tenes.cfg', help='JSON file')\n parser.add_argument('-cp', '--checkpoint', default=None, help = 'checkpoint path')\n args = parser.parse_args()\n checkpoint = args.checkpoint\n\n # read configure file\n with open(args.configure) as f:\n cfg = json.load(f)\n \n # comment for this experiment: leave here\n comment = cfg[\"session\"][\"sess_name\"]\n\n # automate the validation split or not\n if ( float(cfg[\"data\"][\"validation_ratio\"]) > 0 and cfg[\"data\"][\"validation_csv_name\"] == \"\"):\n print(\"No validation set available, auto split the training into validation\")\n validation_flag = cfg[\"data\"][\"validation_ratio\"]\n else:\n validation_flag = 0\n\n # choose dataloader type\n module_name = cfg[\"data\"][\"data.class\"]\n try:\n dataset = getattr(data_loader.dataloader, module_name)\n print(\"Successfully imported data loader module\")\n\n except:\n print(\"Cannot import data loader module\".format(module_name))\n\n # # choose model classification\n # module_name = cfg[\"train\"][\"model.class\"]\n # try:\n # cls = getattr(model, module_name)\n # print(\"Successfully imported model module\")\n # except:\n # print(\"Cannot import model module\".format(module_name))\n\n cls = models.resnet50(pretrained=True)\n cls.fc = torch.nn.Linear(cls.fc.in_features,2)\n print(\"Successfully imported model module\")\n\n # get num of class\n num_of_class = len(cfg[\"data\"][\"label_dict\"])\n\n # create dir to save log and checkpoint\n save_path = cfg['train']['save_path']\n time_str = str(datetime.now().strftime(\"%Y%m%d-%H%M\"))\n sess_name = cfg[\"session\"][\"sess_name\"]\n log_dir = general.make_dir_epoch_time(save_path, sess_name, time_str)\n \n # create logger\n log_file = logger.make_file(log_dir, 'result.txt')\n logger.log_initilize(log_file)\n tb_writer = logger.make_writer(log_dir = log_dir)\n logging.info(f'Start Tensorboard with \"tensorboard --logdir {log_dir}\", view at http://localhost:6006/')\n print(\"All checkpoint will be saved to {}\".format(log_dir))\n print(\"Done Loading!!!\\n\")\n \n main(\n model=cls,\n dataset=dataset,\n validation_flag=validation_flag,\n comment=comment,\n checkpoint=checkpoint,\n num_of_class=num_of_class,\n )","sub_path":"run_exp_3.py","file_name":"run_exp_3.py","file_ext":"py","file_size_in_byte":10568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"27600895","text":"from tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\nimport tensorflow as tf\nimport numpy as np\nimport math\n\n\ndef onlyBinary(inputs, labels):\n new_lab = []\n new_in = []\n for i in range(len(labels)):\n if labels[i][0] > 0:\n new_lab.append([0])\n new_in.append(inputs[i])\n elif labels[i][1] > 0:\n new_lab.append([1])\n new_in.append(inputs[i])\n return [new_in, new_lab]\n\ndef train(epoch):\n sess = tf.Session()\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n images = mnist.train.images\n labels = mnist.train.labels\n train_batch = onlyBinary(images, labels)\n images = mnist.test.images\n labels = mnist.test.labels\n test_batch = onlyBinary(images, labels)\n model = SVM(len(test_batch[1]), len(train_batch[1]), 784, 0.2, False, Klinear)\n sess.run(tf.initialize_all_variables())\n for i in range(epoch):\n out = model.step(sess, test_batch[0], test_batch[1], train_batch[0], train_batch[1], False)\n print(\"loss=\"+str(out[1]) + \" cons1=\"+str(out[4]) + \" cons2=\"+str(out[5]) + \" b=\"+str(out[6]))\n\n out = model.step(sess, test_batch[0], test_batch[1], train_batch[0], train_batch[1], True)\n pred = out[1]\n #for i in range(len(out[0])):\n # print(str(out[0][i]) + \" \" + str(test_batch[1][i]))\n print(pred)\n\n\n\nclass SVM:\n def __init__(self, test_len, data_len, data_size, rate, forward_only, kernel):\n self.data = tf.placeholder(tf.float32, [data_len, data_size])\n self.inputs = tf.placeholder(tf.float32, [test_len, data_size])\n self.labels = tf.placeholder(tf.float32, [data_len, 1])\n self.test_labels = tf.placeholder(tf.float32, [test_len, 1])\n alphas = tf.Variable(tf.random_normal([data_len, 1], stddev=1/math.sqrt(data_len)))\n #alphas = tf.Variable(tf.ones([data_len, 1]))\n self.b = tf.Variable(0)\n if not forward_only:\n p = tf.reduce_sum(tf.matmul(alphas,\n tf.matmul(tf.transpose(alphas),\n tf.matmul(self.labels,\n tf.matmul(tf.transpose(self.labels),\n kernel(self.data, self.data))))))\n self.q = tf.reduce_sum(alphas) - p/2\n self.b = tf.reduce_mean(self.labels - tf.reduce_sum(tf.matmul(alphas, tf.matmul(tf.transpose(self.labels), kernel(self.data, self.data))), 0))\n cons1 = -tf.minimum(tf.reduce_min(alphas), 0)\n cons2 = tf.abs(tf.matmul(tf.transpose(alphas), self.labels))\n self.loss = -self.q + cons1 + cons2\n self.train_step = tf.train.GradientDescentOptimizer(rate).minimize(self.loss, var_list=[alphas])\n prod = tf.reduce_sum(tf.matmul(alphas, tf.matmul(tf.transpose(self.labels), kernel(self.data, self.inputs))), 0)\n self.outputs = tf.sign(tf.sign(prod + self.b) + 1)\n correct_prediction = tf.equal(self.outputs, self.test_labels)\n self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n self.alphas = alphas\n self.cons1 = cons1\n self.cons2 = cons2\n\n def step(self, session, inputs, t_labels, data, labels, forward_only):\n input_feed = {self.inputs: inputs, self.test_labels: t_labels, self.data: data, self.labels: labels}\n if forward_only:\n output_feed = [self.outputs, self.accuracy]\n else:\n output_feed = [self.q, self.loss, self.q, self.alphas, self.cons1, self.cons2, self.b]\n outputs = session.run(output_feed, input_feed)\n return outputs\n\ndef Klinear(x, y):\n return tf.matmul(x, tf.transpose(y))\n\ndef Kpoly(x, y, d=2):\n mat = tf.matmul(x, tf.transpose(y)) + 1\n if d%2 == 0:\n for i in range(d-1):\n mat = (tf.matmul(mat, tf.transpose(mat)) + 1)\n elif d%2 == 1:\n for i in range(d-2):\n mat = (tf.matmul(mat, tf.transpose(mat)) + 1)\n mat = tf.matmul(tf.matmul(x, tf.transpose(y)) + 1, tf.transpose(mat)) + 1\n return mat\n\n\n\ntrain(1)\n","sub_path":"tp6/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"9789090","text":"\"\"\"High level plotting functions using matplotlib.\"\"\"\n\n# There are two different kind of functions here. Some are very high level and\n# expect to have full reign of their figure to draw subplot grids or marginals.\n# Others are constrained to a single axis and should take and return an `ax`\n# argument. When `ax` is None, these functions should grab the current axis and\n# plot into that. These two types of functions may be split into different\n# modules to make the division a little bit more obvious.\n\nfrom __future__ import division\nimport colorsys\nimport itertools\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats, interpolate\nimport statsmodels.api as sm\nimport statsmodels.formula.api as sf\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport moss\n\nfrom seaborn.utils import (color_palette, ci_to_errsize,\n husl_palette, desaturate, _kde_support)\n\n\ndef tsplot(x, data, err_style=\"ci_band\", ci=68, interpolate=True,\n estimator=np.mean, n_boot=10000, smooth=False,\n err_palette=None, ax=None, err_kws=None, **kwargs):\n \"\"\"Plot timeseries from a set of observations.\n\n Parameters\n ----------\n x : n_tp array\n x values\n data : n_obs x n_tp array\n array of timeseries data where first axis is observations. other\n objects (e.g. DataFrames) are converted to an array if possible\n err_style : string or list of strings\n names of ways to plot uncertainty across observations from set of\n {ci_band, ci_bars, boot_traces, book_kde, obs_traces, obs_points}\n ci : int or list of ints\n confidence interaval size(s). if a list, it will stack the error\n plots for each confidence interval\n estimator : callable\n function to determine centralt tendency and to pass to bootstrap\n must take an ``axis`` argument\n n_boot : int\n number of bootstrap iterations\n smooth : boolean\n whether to perform a smooth bootstrap (resample from KDE)\n ax : axis object, optional\n plot in given axis; if None creates a new figure\n err_kws : dict, optional\n keyword argument dictionary passed through to matplotlib\n function generating the error plot\n kwargs : further keyword arguments for main call to plot()\n\n Returns\n -------\n ax : matplotlib axis\n axis with plot data\n\n \"\"\"\n if ax is None:\n ax = plt.gca()\n\n if err_kws is None:\n err_kws = {}\n\n # Bootstrap the data for confidence intervals\n data = np.asarray(data)\n boot_data = moss.bootstrap(data, n_boot=n_boot, smooth=smooth,\n axis=0, func=estimator)\n ci_list = hasattr(ci, \"__iter__\")\n if not ci_list:\n ci = [ci]\n ci_vals = [(50 - w / 2, 50 + w / 2) for w in ci]\n cis = [moss.percentiles(boot_data, v, axis=0) for v in ci_vals]\n central_data = estimator(data, axis=0)\n\n # Plot the timeseries line to get its color\n line, = ax.plot(x, central_data, **kwargs)\n color = line.get_color()\n line.remove()\n kwargs.pop(\"color\", None)\n\n # Use subroutines to plot the uncertainty\n if not hasattr(err_style, \"__iter__\"):\n err_style = [err_style]\n for style in err_style:\n\n # Grab the function from the global environment\n try:\n plot_func = globals()[\"_plot_%s\" % style]\n except KeyError:\n raise ValueError(\"%s is not a valid err_style\" % style)\n\n # Possibly set up to plot each observation in a different color\n if err_palette is not None and \"obs\" in style:\n orig_color = color\n color = color_palette(err_palette, len(data), desat=.99)\n\n plot_kwargs = dict(ax=ax, x=x, data=data,\n boot_data=boot_data,\n central_data=central_data,\n color=color, err_kws=err_kws)\n\n for ci_i in cis:\n plot_kwargs[\"ci\"] = ci_i\n plot_func(**plot_kwargs)\n\n if err_palette is not None and \"obs\" in style:\n color = orig_color\n # Replot the central trace so it is prominent\n marker = kwargs.pop(\"marker\", \"\" if interpolate else \"o\")\n linestyle = kwargs.pop(\"linestyle\", \"-\" if interpolate else \"\")\n ax.plot(x, central_data, color=color,\n marker=marker, linestyle=linestyle, **kwargs)\n\n return ax\n\n# Subroutines for tsplot errorbar plotting\n# ----------------------------------------\n\n\ndef _plot_ci_band(ax, x, ci, color, err_kws, **kwargs):\n \"\"\"Plot translucent error bands around the central tendancy.\"\"\"\n low, high = ci\n ax.fill_between(x, low, high, color=color, alpha=0.2, **err_kws)\n\n\ndef _plot_ci_bars(ax, x, central_data, ci, color, err_kws, **kwargs):\n \"\"\"Plot error bars at each data point.\"\"\"\n err = ci_to_errsize(ci, central_data)\n ax.errorbar(x, central_data, yerr=err, fmt=None, ecolor=color,\n label=\"_nolegend_\", **err_kws)\n\n\ndef _plot_boot_traces(ax, x, boot_data, color, err_kws, **kwargs):\n \"\"\"Plot 250 traces from bootstrap.\"\"\"\n ax.plot(x, boot_data[:250].T, color=color, alpha=0.25,\n linewidth=0.25, label=\"_nolegend_\", **err_kws)\n\n\ndef _plot_obs_traces(ax, x, data, ci, color, err_kws, **kwargs):\n \"\"\"Plot a trace for each observation in the original data.\"\"\"\n if isinstance(color, list):\n for i, obs in enumerate(data):\n ax.plot(x, obs, color=color[i], alpha=0.5,\n label=\"_nolegend_\", **err_kws)\n else:\n ax.plot(x, data.T, color=color, alpha=0.2,\n label=\"_nolegend_\", **err_kws)\n\n\ndef _plot_obs_points(ax, x, data, color, err_kws, **kwargs):\n \"\"\"Plot each original data point discretely.\"\"\"\n if isinstance(color, list):\n for i, obs in enumerate(data):\n ax.plot(x, obs, \"o\", color=color[i], alpha=0.8, markersize=4,\n label=\"_nolegend_\", **err_kws)\n else:\n ax.plot(x, data.T, \"o\", color=color, alpha=0.5, markersize=4,\n label=\"_nolegend_\", **err_kws)\n\n\ndef _plot_boot_kde(ax, x, boot_data, color, **kwargs):\n \"\"\"Plot the kernal density estimate of the bootstrap distribution.\"\"\"\n kwargs.pop(\"data\")\n _ts_kde(ax, x, boot_data, color, **kwargs)\n\n\ndef _plot_obs_kde(ax, x, data, color, **kwargs):\n \"\"\"Plot the kernal density estimate over the sample.\"\"\"\n _ts_kde(ax, x, data, color, **kwargs)\n\n\ndef _ts_kde(ax, x, data, color, **kwargs):\n \"\"\"Upsample over time and plot a KDE of the bootstrap distribution.\"\"\"\n kde_data = []\n y_min, y_max = moss.percentiles(data, [1, 99])\n y_vals = np.linspace(y_min, y_max, 100)\n upsampler = interpolate.interp1d(x, data)\n data_upsample = upsampler(np.linspace(x.min(), x.max(), 100))\n for pt_data in data_upsample.T:\n pt_kde = stats.kde.gaussian_kde(pt_data)\n kde_data.append(pt_kde(y_vals))\n kde_data = np.transpose(kde_data)\n rgb = mpl.colors.ColorConverter().to_rgb(color)\n img = np.zeros((kde_data.shape[0], kde_data.shape[1], 4))\n img[:, :, :3] = rgb\n kde_data /= kde_data.max(axis=0)\n kde_data[kde_data > 1] = 1\n img[:, :, 3] = kde_data\n ax.imshow(img, interpolation=\"spline16\", zorder=1,\n extent=(x.min(), x.max(), y_min, y_max),\n aspect=\"auto\", origin=\"lower\")\n\n\ndef lmplot(x, y, data, color=None, row=None, col=None, col_wrap=None,\n x_estimator=None, x_ci=95, n_boot=5000, fit_reg=True,\n order=1, ci=95, logistic=False, truncate=False,\n x_partial=None, y_partial=None, x_jitter=None, y_jitter=None,\n sharex=True, sharey=True, palette=\"husl\", size=None,\n scatter_kws=None, line_kws=None, palette_kws=None):\n \"\"\"Plot a linear model from a DataFrame.\n\n Parameters\n ----------\n x, y : strings\n column names in `data` DataFrame for x and y variables\n data : DataFrame\n source of data for the model\n color : string, optional\n DataFrame column name to group the model by color\n row, col : strings, optional\n DataFrame column names to make separate plot facets\n col_wrap : int, optional\n wrap col variable at this width - cannot be used with row facet\n x_estimator : callable, optional\n Interpret X values as factor labels and use this function\n to plot the point estimate and bootstrapped CI\n x_ci : int optional\n size of confidence interval for x_estimator error bars\n n_boot : int, optional\n number of bootstrap iterations to perform\n fit_reg : bool, optional\n if True fit a regression model by color/row/col and plot\n order : int, optional\n order of the regression polynomial to fit (default = 1)\n ci : int, optional\n confidence interval for the regression line\n logistic : bool, optional\n fit the regression line with logistic regression\n truncate : bool, optional\n if True, only fit line from data min to data max\n {x, y}_partial : string or list of strings, optional\n regress these variables out of the factors before plotting\n {x, y}_jitter : float, optional\n parameters for uniformly distributed random noise added to positions\n sharex, sharey : bools, optional\n only relevant if faceting; passed to plt.subplots\n palette : seaborn color palette argument\n if using separate plots by color, draw with this color palette\n size : float, optional\n size (plots are square) for each plot facet\n {scatter, line}_kws : dictionary\n keyword arguments to pass to the underlying plot functions\n palette_kws : dictionary\n keyword arguments for seaborn.color_palette\n\n \"\"\"\n # TODO\n # - legend when fit_line is False\n # - wrap title when wide\n\n # First sort out the general figure layout\n if size is None:\n size = mpl.rcParams[\"figure.figsize\"][1]\n\n if col is None and col_wrap is not None:\n raise ValueError(\"Need column facet variable for `col_wrap`\")\n if row is not None and col_wrap is not None:\n raise ValueError(\"Cannot facet rows when using `col_wrap`\")\n\n nrow = 1 if row is None else len(data[row].unique())\n ncol = 1 if col is None else len(data[col].unique())\n\n if col_wrap is not None:\n ncol = col_wrap\n nrow = int(np.ceil(len(data[col].unique()) / col_wrap))\n\n f, axes = plt.subplots(nrow, ncol, sharex=sharex, sharey=sharey,\n figsize=(size * ncol, size * nrow))\n axes = np.atleast_2d(axes).reshape(nrow, ncol)\n\n if nrow == 1 or col_wrap is not None:\n row_masks = [np.repeat(True, len(data))]\n else:\n row_vals = np.sort(data[row].unique())\n row_masks = [data[row] == val for val in row_vals]\n\n if ncol == 1:\n col_masks = [np.repeat(True, len(data))]\n else:\n col_vals = np.sort(data[col].unique())\n col_masks = [data[col] == val for val in col_vals]\n\n if x_partial is not None:\n if not isinstance(x_partial, list):\n x_partial = [x_partial]\n if y_partial is not None:\n if not isinstance(y_partial, list):\n y_partial = [y_partial]\n\n if palette_kws is None:\n palette_kws = {}\n\n # Sort out the plot colors\n color_factor = color\n if color is None:\n hue_masks = [np.repeat(True, len(data))]\n colors = [\"#222222\"]\n else:\n hue_vals = np.sort(data[color].unique())\n hue_masks = [data[color] == val for val in hue_vals]\n colors = color_palette(palette, len(hue_masks), **palette_kws)\n\n # Default keyword arguments for plot components\n if scatter_kws is None:\n scatter_kws = {}\n if line_kws is None:\n line_kws = {}\n\n # First walk through the facets and plot the scatters\n scatter_ms = scatter_kws.pop(\"ms\", 4)\n scatter_mew = mew = scatter_kws.pop(\"mew\", 0)\n scatter_alpha = mew = scatter_kws.pop(\"alpha\", .77)\n for row_i, row_mask in enumerate(row_masks):\n for col_j, col_mask in enumerate(col_masks):\n if col_wrap is not None:\n f_row = col_j // ncol\n f_col = col_j % ncol\n else:\n f_row, f_col = row_i, col_j\n ax = axes[f_row, f_col]\n if f_row + 1 == nrow:\n ax.set_xlabel(x)\n if f_col == 0:\n ax.set_ylabel(y)\n\n # Title the plot if we are faceting\n title = \"\"\n if row is not None:\n title += \"%s = %s\" % (row, row_vals[row_i])\n if row is not None and col is not None:\n title += \" | \"\n if col is not None:\n title += \"%s = %s\" % (col, col_vals[col_j])\n ax.set_title(title)\n\n for hue_k, hue_mask in enumerate(hue_masks):\n color = colors[hue_k]\n data_ijk = data[row_mask & col_mask & hue_mask]\n\n if x_estimator is not None:\n ms = scatter_kws.pop(\"ms\", 7)\n mew = scatter_kws.pop(\"mew\", 0)\n x_vals = data_ijk[x].unique()\n y_vals = data_ijk[y]\n\n if y_partial is not None:\n for var in y_partial:\n conf = data_ijk[var]\n conf -= conf.mean()\n y_mean = y_vals.mean()\n y_vals = moss.vector_reject(y_vals - y_mean, conf)\n y_vals += y_mean\n\n y_grouped = [np.array(y_vals[data_ijk[x] == v])\n for v in x_vals]\n\n y_est = [x_estimator(y_i) for y_i in y_grouped]\n y_boots = [moss.bootstrap(np.array(y_i),\n func=x_estimator,\n n_boot=n_boot)\n for y_i in y_grouped]\n ci_lims = [50 - x_ci / 2., 50 + x_ci / 2.]\n y_ci = [moss.percentiles(y_i, ci_lims) for y_i in y_boots]\n y_error = ci_to_errsize(np.transpose(y_ci), y_est)\n\n ax.plot(x_vals, y_est, \"o\", mew=mew, ms=ms,\n color=color, **scatter_kws)\n ax.errorbar(x_vals, y_est, y_error,\n fmt=None, ecolor=color)\n else:\n x_ = data_ijk[x]\n y_ = data_ijk[y]\n\n if x_partial is not None:\n for var in x_partial:\n conf = data_ijk[var]\n conf -= conf.mean()\n x_mean = x_.mean()\n x_ = moss.vector_reject(x_ - x_mean, conf)\n x_ += x_mean\n if y_partial is not None:\n for var in y_partial:\n conf = data_ijk[var]\n conf -= conf.mean()\n y_mean = y_.mean()\n y_ = moss.vector_reject(y_ - y_mean, conf)\n y_ += y_mean\n\n if x_jitter is not None:\n x_ += np.random.uniform(-x_jitter, x_jitter, x_.shape)\n if y_jitter is not None:\n y_ += np.random.uniform(-y_jitter, y_jitter, y_.shape)\n ax.plot(x_, y_, \"o\", color=color, alpha=scatter_alpha,\n mew=scatter_mew, ms=scatter_ms, **scatter_kws)\n\n for ax_i in np.ravel(axes):\n ax_i.set_xmargin(.05)\n ax_i.autoscale_view()\n\n # Now walk through again and plot the regression estimate\n # and a confidence interval for the regression line\n if fit_reg:\n for row_i, row_mask in enumerate(row_masks):\n for col_j, col_mask in enumerate(col_masks):\n if col_wrap is not None:\n f_row = col_j // ncol\n f_col = col_j % ncol\n else:\n f_row, f_col = row_i, col_j\n ax = axes[f_row, f_col]\n xlim = ax.get_xlim()\n\n for hue_k, hue_mask in enumerate(hue_masks):\n color = colors[hue_k]\n data_ijk = data[row_mask & col_mask & hue_mask]\n x_vals = np.array(data_ijk[x])\n y_vals = np.array(data_ijk[y])\n if not len(x_vals):\n continue\n\n # Sort out the limit of the fit\n if truncate:\n xx = np.linspace(x_vals.min(),\n x_vals.max(), 100)\n else:\n xx = np.linspace(xlim[0], xlim[1], 100)\n xx_ = sm.add_constant(xx, prepend=True)\n\n # Inner function to bootstrap the regression\n def _regress(x, y):\n if logistic:\n x_ = sm.add_constant(x, prepend=True)\n fit = sm.GLM(y, x_,\n family=sm.families.Binomial()).fit()\n reg = fit.predict(xx_)\n else:\n fit = np.polyfit(x, y, order)\n reg = np.polyval(fit, xx)\n return reg\n\n # Remove nuisance variables with vector rejection\n if x_partial is not None:\n for var in x_partial:\n conf = data_ijk[var]\n conf -= conf.mean()\n x_mean = x_vals.mean()\n x_vals = moss.vector_reject(x_vals - x_mean, conf)\n x_vals += x_mean\n if y_partial is not None:\n for var in y_partial:\n conf = data_ijk[var]\n conf -= conf.mean()\n y_mean = y_vals.mean()\n y_vals = moss.vector_reject(y_vals - y_mean, conf)\n y_vals += y_mean\n\n # Regression line confidence interval\n if ci is not None:\n ci_lims = [50 - ci / 2., 50 + ci / 2.]\n boots = moss.bootstrap(x_vals, y_vals,\n func=_regress,\n n_boot=n_boot)\n ci_band = moss.percentiles(boots, ci_lims, axis=0)\n ax.fill_between(xx, *ci_band, color=color, alpha=.15)\n\n # Regression line\n reg = _regress(x_vals, y_vals)\n if color_factor is None:\n label = \"\"\n else:\n label = hue_vals[hue_k]\n ax.plot(xx, reg, color=color,\n label=str(label), **line_kws)\n ax.set_xlim(xlim)\n\n # Plot the legend on the upper left facet and adjust the layout\n if color_factor is not None and color_factor not in [row, col]:\n axes[0, 0].legend(loc=\"best\", title=color_factor)\n plt.tight_layout()\n\n\ndef regplot(x, y, data=None, corr_func=stats.pearsonr, func_name=None,\n xlabel=\"\", ylabel=\"\", ci=95, size=None, annotloc=None, color=None,\n reg_kws=None, scatter_kws=None, dist_kws=None, text_kws=None):\n \"\"\"Scatterplot with regreesion line, marginals, and correlation value.\n\n Parameters\n ----------\n x : sequence\n independent variables\n y : sequence\n dependent variables\n data : dataframe, optional\n if dataframe is given, x, and y are interpreted as\n string keys mapping to dataframe column names\n corr_func : callable, optional\n correlation function; expected to take two arrays\n and return a numeric or (statistic, pval) tuple\n func_name : string, optional\n use for fit statistic annotation in lieu of function name\n xlabel, ylabel : string, optional\n label names\n ci : int or None\n confidence interval for the regression line\n size: int\n figure size (will be a square; only need one int)\n annotloc : two or three tuple\n (xpos, ypos [, horizontalalignment])\n color : matplotlib color scheme\n color of everything but the regression line\n overridden by passing `color` to subfunc kwargs\n {reg, scatter, dist, text}_kws: dicts\n further keyword arguments for the constituent plots\n\n\n \"\"\"\n # Interperet inputs\n if data is not None:\n if not any(map(bool, [xlabel, ylabel])):\n xlabel, ylabel = x, y\n x = np.array(data[x])\n y = np.array(data[y])\n\n # Set up the figure and axes\n size = 6 if size is None else size\n fig = plt.figure(figsize=(size, size))\n ax_scatter = fig.add_axes([0.05, 0.05, 0.75, 0.75])\n ax_x_marg = fig.add_axes([0.05, 0.82, 0.75, 0.13])\n ax_y_marg = fig.add_axes([0.82, 0.05, 0.13, 0.75])\n\n # Plot the scatter\n if scatter_kws is None:\n scatter_kws = {}\n if color is not None and \"color\" not in scatter_kws:\n scatter_kws.update(color=color)\n marker = scatter_kws.pop(\"markerstyle\", \"o\")\n alpha_maker = stats.norm(0, 100)\n alpha = alpha_maker.pdf(len(x)) / alpha_maker.pdf(0)\n alpha = max(alpha, .1)\n alpha = scatter_kws.pop(\"alpha\", alpha)\n ax_scatter.plot(x, y, marker, alpha=alpha, mew=0, **scatter_kws)\n ax_scatter.set_xlabel(xlabel)\n ax_scatter.set_ylabel(ylabel)\n\n # Marginal plots using our distplot function\n if dist_kws is None:\n dist_kws = {}\n if color is not None and \"color\" not in dist_kws:\n dist_kws.update(color=color)\n if \"legend\" not in dist_kws:\n dist_kws[\"legend\"] = False\n dist_kws[\"xlabel\"] = False\n distplot(x, ax=ax_x_marg, **dist_kws)\n distplot(y, ax=ax_y_marg, vertical=True, **dist_kws)\n for ax in [ax_x_marg, ax_y_marg]:\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n\n # Regression line plot\n xlim = ax_scatter.get_xlim()\n a, b = np.polyfit(x, y, 1)\n if reg_kws is None:\n reg_kws = {}\n reg_color = reg_kws.pop(\"color\", \"#222222\")\n ax_scatter.plot(xlim, np.polyval([a, b], xlim),\n color=reg_color, **reg_kws)\n\n # Bootstrapped regression standard error\n if ci is not None:\n xx = np.linspace(xlim[0], xlim[1], 100)\n\n def _bootstrap_reg(x, y):\n fit = np.polyfit(x, y, 1)\n return np.polyval(fit, xx)\n\n boots = moss.bootstrap(x, y, func=_bootstrap_reg)\n ci_lims = [50 - ci / 2., 50 + ci / 2.]\n ci_band = moss.percentiles(boots, ci_lims, axis=0)\n ax_scatter.fill_between(xx, *ci_band, color=reg_color, alpha=.15)\n ax_scatter.set_xlim(xlim)\n\n # Calcluate a fit statistic and p value\n if func_name is None:\n func_name = corr_func.__name__\n out = corr_func(x, y)\n try:\n s, p = out\n msg = \"%s: %.3f (p=%.3g%s)\" % (func_name, s, p, moss.sig_stars(p))\n except TypeError:\n s = corr_func(x, y)\n msg = \"%s: %.3f\" % (func_name, s)\n\n if annotloc is None:\n xmin, xmax = xlim\n x_range = xmax - xmin\n # Assume the fit statistic is correlation-esque for some\n # intuition on where the fit annotation should go\n if s < 0:\n xloc, align = xmax - x_range * .02, \"right\"\n else:\n xloc, align = xmin + x_range * .02, \"left\"\n ymin, ymax = ax_scatter.get_ylim()\n y_range = ymax - ymin\n yloc = ymax - y_range * .02\n else:\n if len(annotloc) == 3:\n xloc, yloc, align = annotloc\n else:\n xloc, yloc = annotloc\n align = \"left\"\n if text_kws is None:\n text_kws = {}\n ax_scatter.text(xloc, yloc, msg, ha=align, va=\"top\", **text_kws)\n\n # Set the axes on the marginal plots\n ax_x_marg.set_xlim(ax_scatter.get_xlim())\n ax_x_marg.set_yticks([])\n ax_y_marg.set_ylim(ax_scatter.get_ylim())\n ax_y_marg.set_xticks([])\n\n\ndef coefplot(formula, data, groupby=None, intercept=False, ci=95,\n palette=\"husl\"):\n \"\"\"Plot the coefficients from a linear model.\n\n Parameters\n ----------\n formula : string\n patsy formula for ols model\n data : dataframe\n data for the plot; formula terms must appear in columns\n groupby : grouping object, optional\n object to group data with to fit conditional models\n intercept : bool, optional\n if False, strips the intercept term before plotting\n ci : float, optional\n size of confidence intervals\n palette : seaborn color palette, optional\n palette for the horizonal plots\n\n \"\"\"\n alpha = 1 - ci / 100\n if groupby is None:\n coefs = sf.ols(formula, data).fit().params\n cis = sf.ols(formula, data).fit().conf_int(alpha)\n else:\n grouped = data.groupby(groupby)\n coefs = grouped.apply(lambda d: sf.ols(formula, d).fit().params).T\n cis = grouped.apply(lambda d: sf.ols(formula, d).fit().conf_int(alpha))\n\n # Possibly ignore the intercept\n if not intercept:\n coefs = coefs.ix[1:]\n\n n_terms = len(coefs)\n\n # Plot seperately depending on groupby\n w, h = mpl.rcParams[\"figure.figsize\"]\n hsize = lambda n: n * (h / 2)\n wsize = lambda n: n * (w / (4 * (n / 5)))\n if groupby is None:\n colors = itertools.cycle(color_palette(palette, n_terms))\n f, ax = plt.subplots(1, 1, figsize=(wsize(n_terms), hsize(1)))\n for i, term in enumerate(coefs.index):\n color = colors.next()\n low, high = cis.ix[term]\n ax.plot([i, i], [low, high], c=color,\n solid_capstyle=\"round\", lw=2.5)\n ax.plot(i, coefs.ix[term], \"o\", c=color, ms=8)\n ax.set_xlim(-.5, n_terms - .5)\n ax.axhline(0, ls=\"--\", c=\"dimgray\")\n ax.set_xticks(range(n_terms))\n ax.set_xticklabels(coefs.index)\n\n else:\n n_groups = len(coefs.columns)\n f, axes = plt.subplots(n_terms, 1, sharex=True,\n figsize=(wsize(n_groups), hsize(n_terms)))\n if n_terms == 1:\n axes = [axes]\n colors = itertools.cycle(color_palette(palette, n_groups))\n for ax, term in zip(axes, coefs.index):\n for i, group in enumerate(coefs.columns):\n color = colors.next()\n low, high = cis.ix[(group, term)]\n ax.plot([i, i], [low, high], c=color,\n solid_capstyle=\"round\", lw=2.5)\n ax.plot(i, coefs.loc[term, group], \"o\", c=color, ms=8)\n ax.set_xlim(-.5, n_groups - .5)\n ax.axhline(0, ls=\"--\", c=\"dimgray\")\n ax.set_title(term)\n ax.set_xlabel(groupby)\n ax.set_xticks(range(n_groups))\n ax.set_xticklabels(coefs.columns)\n\n\ndef boxplot(vals, groupby=None, names=None, join_rm=False, color=None,\n alpha=None, fliersize=3, linewidth=1.5, widths=.8, ax=None,\n **kwargs):\n \"\"\"Wrapper for matplotlib boxplot that allows better color control.\n\n Parameters\n ----------\n vals : sequence of data containers\n data for plot\n groupby : grouping object\n if `vals` is a Series, this is used to group\n names : list of strings, optional\n names to plot on x axis, otherwise plots numbers\n join_rm : boolean, optional\n if True, positions in the input arrays are treated as repeated\n measures and are joined with a line plot\n color : mpl color, sequence of colors, or seaborn palette name\n inner box color\n alpha : float\n transparancy of the inner box color\n fliersize : float, optional\n markersize for the fliers\n linewidth : float, optional\n width for the box outlines and whiskers\n ax : matplotlib axis, optional\n will plot in axis, or create new figure axis\n kwargs : additional keyword arguments to boxplot\n\n Returns\n -------\n ax : matplotlib axis\n axis where boxplot is plotted\n\n \"\"\"\n if ax is None:\n ax = plt.gca()\n\n if isinstance(vals, pd.DataFrame):\n if names is None:\n names = vals.columns\n if vals.columns.name is not None:\n xlabel = vals.columns.name\n else:\n xlabel = None\n vals = vals.values\n ylabel = None\n\n elif isinstance(vals, pd.Series) and groupby is not None:\n if names is None:\n names = np.sort(pd.unique(groupby))\n if hasattr(groupby, \"name\"):\n xlabel = groupby.name\n ylabel = vals.name\n grouped_vals = pd.groupby(vals, groupby).values\n vals = grouped_vals.values\n else:\n xlabel = None\n ylabel = None\n\n boxes = ax.boxplot(vals, patch_artist=True, widths=widths, **kwargs)\n vals = np.atleast_2d(vals).T\n\n if color is None:\n colors = husl_palette(len(vals), l=.7)\n else:\n if hasattr(color, \"__iter__\") and not isinstance(color, tuple):\n colors = color\n else:\n try:\n color = mpl.colors.colorConverter.to_rgb(color)\n colors = [color for _ in vals]\n except ValueError:\n colors = color_palette(color, len(vals))\n\n colors = [mpl.colors.colorConverter.to_rgb(c) for c in colors]\n colors = [desaturate(c, .7) for c in colors]\n\n light_vals = [colorsys.rgb_to_hls(*c)[1] for c in colors]\n l = min(light_vals) * .6\n gray = (l, l, l)\n\n for i, box in enumerate(boxes[\"boxes\"]):\n box.set_color(colors[i])\n if alpha is not None:\n box.set_alpha(alpha)\n box.set_edgecolor(gray)\n box.set_linewidth(linewidth)\n for i, whisk in enumerate(boxes[\"whiskers\"]):\n whisk.set_color(gray)\n whisk.set_linewidth(linewidth)\n whisk.set_linestyle(\"-\")\n for i, cap in enumerate(boxes[\"caps\"]):\n cap.set_color(gray)\n cap.set_linewidth(linewidth)\n for i, med in enumerate(boxes[\"medians\"]):\n med.set_color(gray)\n med.set_linewidth(linewidth)\n for i, fly in enumerate(boxes[\"fliers\"]):\n fly.set_color(gray)\n fly.set_marker(\"d\")\n fly.set_markeredgecolor(gray)\n fly.set_markersize(fliersize)\n\n if join_rm:\n ax.plot(range(1, len(vals.T) + 1), vals.T,\n color=gray, alpha=2. / 3)\n\n if names is not None:\n ax.set_xticklabels(names)\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n\n ax.xaxis.grid(False)\n return ax\n\n\ndef distplot(a, bins=None, hist=True, kde=True, rug=False, fit=None,\n hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,\n color=None, vertical=False, legend=False, xlabel=None, ax=None):\n \"\"\"Flexibly plot a distribution of observations.\n\n Parameters\n ----------\n a : (squeezable to) 1d array\n observed data\n bins : argument for matplotlib hist(), or None\n specification of bins or None to use Freedman-Diaconis rule\n hist : bool, default True\n whether to plot a (normed) histogram\n kde : bool, defualt True\n whether to plot a gaussian kernel density estimate\n rug : bool, default False\n whether to draw a rugplot on the support axis\n fit : random variable object\n object with `fit` method returning a tuple that can be\n passed to a `pdf` method a positional arguments following\n an array of values to evaluate the pdf at\n {hist, kde, rug, fit}_kws : dictionaries\n keyword arguments for underlying plotting functions\n color : matplotlib color, optional\n color to plot everything but the fitted curve in\n vertical : bool, default False\n if True, oberved values are on y-axis\n legend : bool, default True\n if True, add a legend to the plot with what the plotted lines are\n xlabel : string, False, or None\n name for the x axis label. if None, will try to get it from a.name\n if False, do not set the x label\n ax : matplotlib axis, optional\n if provided, plot on this axis\n\n Returns\n -------\n ax : matplotlib axis\n\n \"\"\"\n if ax is None:\n ax = plt.gca()\n\n # Intelligently label the axis\n label_x = bool(xlabel)\n if xlabel is None and hasattr(a, \"name\"):\n xlabel = a.name\n if xlabel is not None:\n label_x = True\n\n # Make a a 1-d array\n a = np.asarray(a).squeeze()\n\n # Handle dictionary defaults\n if hist_kws is None:\n hist_kws = dict()\n if kde_kws is None:\n kde_kws = dict()\n if rug_kws is None:\n rug_kws = dict()\n if fit_kws is None:\n fit_kws = dict()\n\n # Get the color from the current color cycle\n if color is None:\n if vertical:\n line, = ax.plot(0, a.mean())\n else:\n line, = ax.plot(a.mean(), 0)\n color = line.get_color()\n line.remove()\n\n if hist:\n if bins is None:\n # From http://stats.stackexchange.com/questions/798/\n h = 2 * moss.iqr(a) * len(a) ** -(1 / 3)\n bins = (a.max() - a.min()) / h\n hist_alpha = hist_kws.pop(\"alpha\", 0.4)\n orientation = \"horizontal\" if vertical else \"vertical\"\n hist_color = hist_kws.pop(\"color\", color)\n ax.hist(a, bins, normed=True, color=hist_color, alpha=hist_alpha,\n orientation=orientation, **hist_kws)\n\n if kde:\n kde_color = kde_kws.pop(\"color\", color)\n kde_kws[\"label\"] = \"kde\"\n kdeplot(a, vertical=vertical, color=kde_color, ax=ax, **kde_kws)\n\n if rug:\n rug_color = rug_kws.pop(\"color\", color)\n axis = \"y\" if vertical else \"x\"\n rugplot(a, axis=axis, color=rug_color, ax=ax, **rug_kws)\n\n if fit is not None:\n fit_color = fit_kws.pop(\"color\", \"#282828\")\n npts = fit_kws.pop(\"npts\", 1000)\n support_thresh = fit_kws.pop(\"support_thresh\", 1e-4)\n params = fit.fit(a)\n pdf = lambda x: fit.pdf(x, *params)\n x = _kde_support(a, pdf, npts, support_thresh)\n y = pdf(x)\n if vertical:\n x, y = y, x\n fit_kws[\"label\"] = fit.name\n ax.plot(x, y, color=fit_color, **fit_kws)\n\n if legend:\n ax.legend(loc=\"best\")\n\n if label_x:\n ax.set_xlabel(xlabel)\n\n return ax\n\n\ndef kdeplot(a, npts=1000, shade=False, support_thresh=1e-4,\n support_min=-np.inf, support_max=np.inf,\n vertical=False, ax=None, **kwargs):\n \"\"\"Calculate and plot kernel density estimate.\n\n Parameters\n ----------\n a : ndarray\n input data\n npts : int, optional\n number of x points\n shade : bool, optional\n whether to shade under kde curve\n support_thresh : float, default 1e-4\n draw density for values up to support_thresh * max(density)\n support_{min, max}: float, default to (-) inf\n if given, do not draw above or below these values\n (does not affect the actual estimation)\n vertical : bool, defualt False\n if True, density is on x-axis\n ax : matplotlib axis, optional\n axis to plot on, otherwise creates new one\n kwargs : other keyword arguments for plot()\n\n Returns\n -------\n ax : matplotlib axis\n axis with plot\n\n \"\"\"\n if ax is None:\n ax = plt.gca()\n a = np.asarray(a)\n kde = stats.gaussian_kde(a.astype(float).ravel())\n x = _kde_support(a, kde, npts, support_thresh)\n x = x[x >= support_min]\n x = x[x <= support_max]\n y = kde(x)\n if vertical:\n y, x = x, y\n\n line, = ax.plot(x, y, **kwargs)\n color = line.get_color()\n line.remove()\n kwargs.pop(\"color\", None)\n\n ax.plot(x, y, color=color, **kwargs)\n if shade:\n ax.fill_between(x, 0, y, color=color, alpha=0.25)\n return ax\n\n\ndef rugplot(a, height=None, axis=\"x\", ax=None, **kwargs):\n \"\"\"Plot datapoints in an array as sticks on an axis.\"\"\"\n if ax is None:\n ax = plt.gca()\n other_axis = dict(x=\"y\", y=\"x\")[axis]\n min, max = getattr(ax, \"get_%slim\" % other_axis)()\n if height is None:\n range = max - min\n height = range * .05\n if axis == \"x\":\n ax.plot([a, a], [min, min + height], **kwargs)\n else:\n ax.plot([min, min + height], [a, a], **kwargs)\n return ax\n\n\ndef violin(vals, groupby=None, inner=\"box\", color=None, positions=None,\n names=None, widths=.8, alpha=None, join_rm=False, kde_thresh=1e-2,\n inner_kws=None, ax=None, **kwargs):\n \"\"\"Create a violin plot (a combination of boxplot and KDE plot).\n\n Parameters\n ----------\n vals : array or sequence of arrays\n data to plot\n groupby : grouping object\n if `vals` is a Series, this is used to group\n inner : box | sticks | points\n plot quartiles or individual sample values inside violin\n color : mpl color, sequence of colors, or seaborn palette name\n inner violin colors\n positions : number or sequence of numbers\n position of first violin or positions of each violin\n widths : float\n width of each violin at maximum density\n alpha : float, optional\n transparancy of violin fill\n join_rm : boolean, optional\n if True, positions in the input arrays are treated as repeated\n measures and are joined with a line plot\n names : list of strings, optional\n names to plot on x axis, otherwise plots numbers\n kde_thresh : float, optional\n proportion of maximum at which to threshold the KDE curve\n inner_kws : dict, optional\n keyword arugments for inner plot\n ax : matplotlib axis, optional\n axis to plot on, otherwise creates new one\n\n Returns\n -------\n ax : matplotlib axis\n axis with violin plot\n\n \"\"\"\n if ax is None:\n ax = plt.gca()\n\n if isinstance(vals, pd.DataFrame):\n if names is None:\n names = vals.columns\n if vals.columns.name is not None:\n xlabel = vals.columns.name\n else:\n xlabel = None\n ylabel = None\n vals = vals.values\n\n elif isinstance(vals, pd.Series) and groupby is not None:\n if hasattr(groupby, \"name\"):\n xlabel = groupby.name\n if names is None:\n names = np.sort(pd.unique(groupby))\n ylabel = vals.name\n grouped_vals = pd.groupby(vals, groupby).values\n vals = grouped_vals.values\n else:\n xlabel = None\n ylabel = None\n\n if hasattr(vals, 'shape'):\n if len(vals.shape) == 1:\n if hasattr(vals[0], 'shape'):\n vals = list(vals)\n else:\n vals = [vals]\n elif len(vals.shape) == 2:\n nr, nc = vals.shape\n if nr == 1:\n vals = [vals]\n elif nc == 1:\n vals = [vals.ravel()]\n else:\n vals = [vals[:, i] for i in xrange(nc)]\n else:\n raise ValueError(\"Input x can have no more than 2 dimensions\")\n if not hasattr(vals[0], '__len__'):\n vals = [vals]\n\n vals = [np.asarray(a, float) for a in vals]\n\n if color is None:\n colors = husl_palette(len(vals), l=.7)\n else:\n if hasattr(color, \"__iter__\") and not isinstance(color, tuple):\n colors = color\n else:\n try:\n color = mpl.colors.colorConverter.to_rgb(color)\n colors = [color for _ in vals]\n except ValueError:\n colors = color_palette(color, len(vals))\n\n colors = [mpl.colors.colorConverter.to_rgb(c) for c in colors]\n colors = [desaturate(c, .7) for c in colors]\n\n light_vals = [colorsys.rgb_to_hls(*c)[1] for c in colors]\n l = min(light_vals) * .6\n gray = (l, l, l)\n\n if inner_kws is None:\n inner_kws = {}\n\n if positions is None:\n positions = np.arange(1, len(vals) + 1)\n elif not hasattr(positions, \"__iter__\"):\n positions = np.arange(positions, len(vals) + positions)\n\n in_alpha = inner_kws.pop(\"alpha\", .6 if inner == \"points\" else 1)\n in_alpha *= 1 if alpha is None else alpha\n in_color = inner_kws.pop(\"color\", gray)\n in_marker = inner_kws.pop(\"marker\", \".\")\n in_lw = inner_kws.pop(\"lw\", 1.5 if inner == \"box\" else .8)\n\n for i, a in enumerate(vals):\n x = positions[i]\n kde = stats.gaussian_kde(a)\n y = _kde_support(a, kde, 1000, kde_thresh)\n dens = kde(y)\n scl = 1 / (dens.max() / (widths / 2))\n dens *= scl\n\n ax.fill_betweenx(y, x - dens, x + dens, alpha=alpha, color=colors[i])\n if inner == \"box\":\n for quant in moss.percentiles(a, [25, 75]):\n q_x = kde(quant) * scl\n q_x = [x - q_x, x + q_x]\n ax.plot(q_x, [quant, quant], color=in_color,\n linestyle=\":\", linewidth=in_lw, **inner_kws)\n med = np.median(a)\n m_x = kde(med) * scl\n m_x = [x - m_x, x + m_x]\n ax.plot(m_x, [med, med], color=in_color,\n linestyle=\"--\", linewidth=in_lw, **inner_kws)\n elif inner == \"stick\":\n x_vals = kde(a) * scl\n x_vals = [x - x_vals, x + x_vals]\n ax.plot(x_vals, [a, a], color=in_color,\n linewidth=in_lw, alpha=in_alpha, **inner_kws)\n elif inner == \"points\":\n x_vals = [x for _ in a]\n ax.plot(x_vals, a, in_marker, color=in_color,\n alpha=in_alpha, mew=0, **inner_kws)\n for side in [-1, 1]:\n ax.plot((side * dens) + x, y, c=gray, linewidth=1.5)\n\n if join_rm:\n ax.plot(range(1, len(vals) + 1), vals,\n color=in_color, alpha=2. / 3)\n\n ax.set_xticks(positions)\n if names is not None:\n if len(vals) != len(names):\n raise ValueError(\"Length of names list must match nuber of bins\")\n ax.set_xticklabels(names)\n ax.set_xlim(positions[0] - .5, positions[-1] + .5)\n\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n\n ax.xaxis.grid(False)\n return ax\n\n\ndef corrplot(data, names=None, sig_stars=True, sig_tail=\"both\", sig_corr=True,\n cmap=\"coolwarm\", cmap_range=None, cbar=True, ax=None, **kwargs):\n \"\"\"Plot a correlation matrix with colormap and r values.\n\n Parameters\n ----------\n data : Dataframe or nobs x nvars array\n input data\n names : sequence of strings\n names to associate with variables; should be short\n sig_stars : bool\n if True, get significance with permutation test and denote with stars\n sig_tail : both | upper | lower\n direction for significance test\n sig_corr : bool\n if True, use FWE-corrected significance\n cmap : colormap\n colormap name as string or colormap object\n cmap_range : None, \"full\", (low, high)\n either truncate colormap at (-max(abs(r)), max(abs(r))), use the\n full range (-1, 1), or specify (min, max) values for the colormap\n cbar : boolean\n if true, plots the colorbar legend\n kwargs : other keyword arguments\n passed to ax.matshow()\n\n Returns\n -------\n ax : matplotlib axis\n axis object with plot\n\n \"\"\"\n if not isinstance(data, pd.DataFrame):\n if names is None:\n names = [\"var_%d\" % i for i in range(data.shape[1])]\n data = pd.DataFrame(data, columns=names, dtype=np.float)\n\n # Calculate the correlation matrix of the dataframe\n corrmat = data.corr()\n\n # Pandas will drop non-numeric columns; let's keep track of that operation\n names = corrmat.columns\n data = data[names]\n\n # Get p values with a permutation test\n if sig_stars:\n p_mat = moss.randomize_corrmat(data.values.T, sig_tail, sig_corr)\n else:\n p_mat = None\n\n # Paternalism\n if cmap == \"jet\":\n raise ValueError(\"Never use the 'jet' colormap!\")\n\n # Sort out the color range\n if cmap_range is None:\n triu = np.triu_indices(len(corrmat), 1)\n vmax = min(1, np.max(np.abs(corrmat.values[triu])) * 1.15)\n vmin = -vmax\n cmap_range = vmin, vmax\n elif cmap_range == \"full\":\n cmap_range = (-1, 1)\n\n # Plot using the more general symmatplot function\n ax = symmatplot(corrmat, p_mat, names, cmap, cmap_range,\n cbar, ax, **kwargs)\n\n return ax\n\n\ndef symmatplot(mat, p_mat=None, names=None, cmap=\"coolwarm\", cmap_range=None,\n cbar=True, ax=None, **kwargs):\n \"\"\"Plot a symettric matrix with colormap and statistic values.\"\"\"\n if ax is None:\n ax = plt.gca()\n\n nvars = len(mat)\n if isinstance(mat, pd.DataFrame):\n plotmat = mat.values.copy()\n mat = mat.values\n else:\n plotmat = mat.copy()\n plotmat[np.triu_indices(nvars)] = np.nan\n\n if cmap_range is None:\n vmax = np.nanmax(plotmat) * 1.15\n vmin = np.nanmin(plotmat) * 1.15\n elif len(cmap_range) == 2:\n vmin, vmax = cmap_range\n else:\n raise ValueError(\"cmap_range argument not understood\")\n\n mat_img = ax.matshow(plotmat, cmap=cmap, vmin=vmin, vmax=vmax, **kwargs)\n\n if cbar:\n plt.colorbar(mat_img, shrink=.75)\n\n if p_mat is None:\n p_mat = np.ones((nvars, nvars))\n\n for i, j in zip(*np.triu_indices(nvars, 1)):\n val = mat[i, j]\n stars = moss.sig_stars(p_mat[i, j])\n ax.text(j, i, \"\\n%.3g\\n%s\" % (val, stars),\n fontdict=dict(ha=\"center\", va=\"center\"))\n\n if names is None:\n names = [\"var%d\" % i for i in range(nvars)]\n for i, name in enumerate(names):\n ax.text(i, i, name, fontdict=dict(ha=\"center\", va=\"center\",\n weight=\"bold\", rotation=45))\n\n ticks = np.linspace(.5, nvars - .5, nvars)\n ax.set_xticks(ticks)\n ax.set_yticks(ticks)\n ax.set_xticklabels(())\n ax.set_yticklabels(())\n ax.grid(True, linestyle=\"-\")\n\n return ax\n\n\ndef palplot(pal, size=1):\n \"\"\"Plot the values in a color palette as a horizontal array.\n\n Parameters\n ----------\n pal : sequence of matplotlib colors\n colors, i.e. as returned by seaborn.color_palette()\n size :\n scaling factor for size of plot\n\n \"\"\"\n n = len(pal)\n f, ax = plt.subplots(1, 1, figsize=(n * size, size))\n ax.imshow(np.arange(n).reshape(1, n),\n cmap=mpl.colors.ListedColormap(list(pal)),\n interpolation=\"nearest\", aspect=\"auto\")\n ax.set_xticks(np.arange(n) - .5)\n ax.set_yticks([-.5, .5])\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n","sub_path":"seaborn/plotobjs.py","file_name":"plotobjs.py","file_ext":"py","file_size_in_byte":46688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"95580990","text":"from selenium import webdriver;\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nimport time\n\n#webdriver driver = new ChromeDriver()\nbrowser= webdriver.Chrome();\nbrowser.get('file:///S:/Summer\\'18/Study/html_code_03_02.html');\n#user_id = browser.find_element_by_id('q')\n\nselect =Select(browser.find_element_by_name('numReturnSelect'))\nselect.select_by_index(4)\ntime.sleep(3)\n\nselect.select_by_visible_text(\"200\")\ntime.sleep(3)\n\nselect.select_by_value(\"250\")\ntime.sleep(3)\n\n\nsubmit_button = browser.find_element_by_name(\"continue\")\nsubmit_button.submit()\n#user_name.send_keys(\"pycon\")\n#user_name.send_keys(Keys.RETURN)\n\n#time.sleep(3)\nbrowser.close()","sub_path":"select_drop_down.py","file_name":"select_drop_down.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"323525045","text":"if __name__ == \"__main__\":\n\n \n params_dict = {'X_d':1.81,'X1d':0.3,'T1d0':8.0,\n 'X_q':1.76,'X1q':0.65,'T1q0':1.0,\n 'R_a':0.003,'X_l': 0.05, \n 'H':3.5,'D':1.0,\n 'Omega_b':2*np.pi*50,'omega_s':1.0,\n 'v_0':0.9008,'theta_0':0.0}\n \n \n u_ini_dict = {'P_t':0.8, 'Q_t':0.2} # for the initialization problem\n u_run_dict = {'p_m':0.8,'e1q':1.0} # for the running problem (here initialization and running problem are the same)\n \n \n x_list = ['delta','omega'] # [inductor current, PI integrator]\n y_ini_list = ['i_d','i_q','v_1','theta_1','p_m','e1q'] # for the initialization problem\n y_run_list = ['i_d','i_q','v_1','theta_1','P_t','Q_t'] # for the running problem (here initialization and running problem are the same)\n \n sys_vars = {'params':params_dict,\n 'u_list':u_run_dict,\n 'x_list':x_list,\n 'y_list':y_run_list}\n \n exec(sym_gen_str()) # exec to generate the required symbolic varables and constants\n \n\n\n","sub_path":"src/pydae/templates/unit_test_template.py","file_name":"unit_test_template.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"626559531","text":"# build\nimport json\nfrom xmlstats import XMLStats\n# django\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.http import HttpResponse\nfrom django.core import serializers\nfrom django.conf import settings\n\n\nstats = XMLStats(access_token=settings.ACCESS_TOKEN,\n email='chezar1995@gmail.com')\n\ndict_leaders = {\n 'points_per_game': 'Очків за гру',\n 'assists_per_game': 'Допомог за гру',\n 'rebounds_per_game': 'Підбирань за гру',\n 'off_rebounds_per_game': 'Підбирань за гру чуже кільце',\n 'def_rebounds_per_game': 'Підбирань за гру свое кільце',\n # 'field_goal_pct': '',\n # 'free_throw_pct': '',\n 'three_point_pct': 'Триочкових за гру',\n 'blocks_per_game': 'Блоків за гру',\n 'steals_per_game': 'Перехоплень за гру',\n 'games_played': 'Зіграно ігор'\n}\n\ndef get_all_categories(request):\n return JsonResponse(dict_leaders, safe=False)\n\ndef get_leaders_stat(request, category_id):\n leaders = stats.make_request(host=\"erikberg.com\", sport='nba',\n method=\"leaders\", id=category_id,\n format=\"json\",\n parameters={})\n return JsonResponse(leaders, safe=False)\n","sub_path":"NBA/leaders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"347294815","text":"import datetime, json\nfrom flask import Flask, Blueprint, session, redirect, render_template, request, views,url_for\n\n\nfrom .. import db\nfrom .. import models\n\nblue_conference = Blueprint('blue_book', __name__, template_folder='templates', static_folder='static')\n\n\nclass Conference(views.MethodView):\n methods = ['GET', 'POST', 'DELETE']\n\n def get(self):\n \"\"\"展示\"\"\"\n try:\n current_user_id = session.get('user_id')\n current_user = session.get('user_info')[0]\n\n # 获取url中date数据,没有则取当天\n ctime = request.args.get('date')\n ctime = ctime or datetime.date.today()\n\n # 时间段表\n time_list = db.session.query(models.ConferenceTime).all()\n\n # 房间表\n homes_list = db.session.query(models.Homes).all()\n\n # 记录表\n record_list = db.session.query(models.Record).filter(models.Record.conference_date == ctime).all()\n record_dict = {(i.homes_id, i.conference_time_id): {'user_id': i.user_id, 'record_id': i.id} for i in\n record_list}\n\n return render_template('book.html',\n record_dict=record_dict,\n time_list=time_list,\n homes_list=homes_list,\n current_user_id=current_user_id,\n current_user=current_user,\n ctime=ctime, )\n except Exception as e:\n return '请求异常'\n\n def post(self):\n \"\"\"添加\"\"\"\n ret = {'status': None, 'msg': ''}\n try:\n # 选定按钮,添加到数据库\n data_list = json.loads(request.form.get('data_list'))\n user_id = session.get('user_id')\n\n conference_date_str = data_list[0].get('conference_date')\n conference_date = datetime.datetime.strptime(conference_date_str, \"%Y-%m-%d\").date()\n\n if conference_date < datetime.date.today():\n raise ValueError('不能预订以前的')\n\n # 添加数据\n\n record_list = [models.Record(**data,user_id=user_id) for data in data_list]\n db.session.add_all(record_list)\n db.session.commit()\n db.session.close()\n ret['status'] = True\n\n except ValueError as e:\n ret['msg'] = str(e)\n\n except Exception as e:\n ret['msg'] = '预订异常'\n\n return json.dumps(ret)\n\n def delete(self):\n \"\"\"取消\"\"\"\n ret = {'status': None, 'msg': ''}\n try:\n record_id = request.form.get('record_id')\n user_id = session.get('user_id')\n\n record = db.session.query(models.Record).filter(models.Record.id == record_id,\n models.Record.user_id == user_id)\n if record[0].conference_date < datetime.date.today():\n raise ValueError('已过期,不能取消')\n else:\n record.delete()\n db.session.commit()\n db.session.close()\n ret['status'] = True\n\n except ValueError as e:\n ret['msg'] = str(e)\n\n except Exception as e:\n ret['msg'] = str(e)\n\n return json.dumps(ret)\n\n\nblue_conference.add_url_rule('/conference', view_func=Conference.as_view(name='conference'),endpoint=\"conference\")\n\n\n@blue_conference.before_request\ndef is_login(*args, **kwargs):\n user = session.get('user_info')\n if user:\n return None\n url = url_for(\"login\")\n return redirect(url)\n","sub_path":"conference/views/conference.py","file_name":"conference.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"323196839","text":"import heapq\nfrom collections import deque\n\nclass Blizzard:\n \n def __init__(self,pos,d):\n dirs = {'>':(1,0),\n '<':(-1,0),\n 'v':(0,1),\n '^':(0,-1)}\n self.pos = pos\n self.icon = d\n self.d = dirs[d]\n\n def copy(self):\n return Blizzard(self.pos,self.icon)\n \n def move(self, walls):\n x,y = self.pos\n a,b = self.d\n self.pos = (x+a,y+b)\n \n if self.pos in walls:\n self.pos = walls[self.pos]\n\n def __eq__(self, other):\n if isinstance(other,Blizzard): return self.pos==other.pos\n if isinstance(other,tuple): return self.pos==other\n return False\n\n\ndef moveBlizzards(blizzards, walls): \n blizzards = [b.copy() for b in blizzards]\n for b in blizzards:\n b.move(walls)\n return blizzards\n \ndef printMap(areaSize,blizzards):\n \n screen = [[\"#\"]+['.']*(areaSize[0]-1)+[\"#\"] for i in range(areaSize[1]-1)]\n screen.insert(0,[\"#\"*(areaSize[0]+1)])\n screen.append([\"#\"*(areaSize[0]+1)])\n\n for b in blizzards:\n try:\n x,y = b.pos\n except:\n x,y = b\n try:\n screen[y][x] = b.icon\n except:\n print(x,y,len(screen),len(screen[0]))\n \n for line in screen:\n print(\"\".join(line))\n print()\n\ndef distance(pos, target):\n x,y = pos\n tx,ty = target\n return abs(x-tx)+abs(y-ty)\n\ndef score(pos, steps, target):\n return distance(pos,target)+steps\n \nblizzards = []\nwalls = {}\nwith open(\"data.txt\") as f:\n for y,line in enumerate(f):\n for x,c in enumerate(line):\n if c in \"<>v^\":\n blizzards.append(Blizzard((x,y),c))\n areaSize = (x,y)\n target = (len(line)-2,y)\n\nfor y in range(areaSize[1]+1):\n walls[(0,y)] = (areaSize[0]-1,y)\n walls[(areaSize[0],y)] = (1,y)\n\nfor x in range(areaSize[0]+1):\n walls[(x,0)] = (x,areaSize[1]-1)\n walls[(x,areaSize[1])] = (x,1)\n\nstart = (1,0)\ndel walls[start]\ndel walls[target]\nprintMap(areaSize,blizzards)\n\nstack = []\npush = lambda pos, step: heapq.heappush(stack,(score(pos,step,target),(pos,step)))\npop = lambda: heapq.heappop(stack)\nup = lambda a:(a[0],a[1]-1)\ndown = lambda a:(a[0],a[1]+1)\nleft = lambda a:(a[0]-1,a[1])\nright = lambda a:(a[0]+1,a[1])\n\nblizzardCache = {}\ncycle = (areaSize[0]-1)*(areaSize[1]-1)\nprint(\"cycle length:\",cycle)\nfor c in range(cycle+1):\n for b in blizzards:\n b.move(walls)\n blizzardCache[c] = set(b.pos for b in blizzards)\n\nprint(\"Starting simulation\")\ncounter = 0\npush((1,0),0)\nmemoize = set()\nwhile stack:\n priority,(pos, step) = pop()\n if (pos,step) in memoize:\n continue\n memoize.add((pos,step))\n if pos == target:\n print(step+1)\n break\n \n newBlizzards = blizzardCache[(step+1)%cycle]\n positions = [pos, up(pos), down(pos), left(pos), right(pos)]\n\n for p in positions:\n x,y = p\n if p in walls:\n continue\n elif x<0 or x>areaSize[0] or y < 0 or y > areaSize[1]:\n continue\n elif p not in newBlizzards:\n push(p,step+1)\n\n if counter%10000==0:\n print(f\"{priority},{pos},{step}\")\n counter +=1\n \n \nprint(\"finished\")\n","sub_path":"code2022/day24/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"298254524","text":"\nfrom tqdm import tqdm\nent_dict = {}\nwordnet_dict = {}\nalltag_dict = {}\nwith open('/work/smt3/wwang/TAC2019/qihui_data/yago/yagoTypes.tsv', 'r') as fin:\n lines = tqdm(fin,desc='lines')\n for line in lines:\n entity = line.split('\\t')[1]\n tag = line.split('\\t')[3]\n if entity not in ent_dict:\n ent_dict[entity] = 1\n if (not tag.startswith(' os.path.getmtime(xnat_file):\n return True\n except:\n # Something went wrong with open and/or read, so say file doesn't exist\n pass\n\n return False\n\n\n#\n# Export one series to pipeline tree, unless it already exists there\n#\n# Returns - True if new files were created, False if not\n#\n\ndef export_series( redcap_visit_id, xnat, redcap_key, session_and_scan_list, to_directory, filename_pattern, xnat_dir, verbose=False, timer_label=None):\n (subject_label, event_label) = redcap_key\n # List should have at least one \"SESSION/SCAN\" entry\n if not '/' in session_and_scan_list:\n return False\n\n # Put together target directory and filename pattern\n to_path_pattern = os.path.join( to_directory, filename_pattern )\n\n # If filename is a pattern with substitution, check whether entire directory exists\n if '%' in filename_pattern:\n pipeline_file_pattern = re.sub('%T%N','*',re.sub( '%n', '*', to_path_pattern)) + \".xml\"\n eid_file_path = os.path.join( to_directory, 'eid' )\n else:\n pipeline_file_pattern = to_path_pattern + \".xml\"\n eid_file_path = re.sub( '\\.[^/]*', '.eid', to_path_pattern )\n\n # Check if EID is still the same \n eid_unchanged_flag = check_eid_file( eid_file_path, session_and_scan_list )\n \n # Check if files are already created \n pipeline_file_list= glob.glob(pipeline_file_pattern)\n\n dicom_path_list = []\n CreateDicomFlag=False\n for session_and_scan in session_and_scan_list.split( ' ' ):\n [ session, scan ] = session_and_scan.split( '/' )\n match = re.match( '.*(' + xnat_dir +'/.*)scan_.*_catalog.xml.*', xnat.raw_text(xnat.select.experiments[ session ].scans[ scan ]), re.DOTALL )\n if match:\n dicom_path = match.group(1)\n if not os.path.exists( dicom_path ):\n dicom_path = re.sub( 'storage/XNAT', 'ncanda-xnat', dicom_path )\n dicom_path_list.append( dicom_path )\n\n # If pipeline already has created file check date to xnat file - assumes that check_new_sessions is always run before this script otherwise pipeline is run twice ! If not created then or eid changed then create dicoms \n if eid_unchanged_flag and len(pipeline_file_list) : \n # Look for xnat file \n xnat_file_pattern = re.sub('/DICOM/','_*/image*.nii.xml',re.sub( '/SCANS/', '/RESOURCES/nifti/', dicom_path))\n xnat_file_search = glob.glob(xnat_file_pattern)\n\n # If date of xnat file is newer than in pipeline then update \n if xnat_file_search != [] and not check_file_date(pipeline_file_list[0],xnat_file_search[0]):\n CreateDicomFlag=True\n else:\n CreateDicomFlag=True\n\n if CreateDicomFlag == False :\n return False\n\n\n if len(pipeline_file_list) :\n [ session, scan ] = session_and_scan_list.split( ' ' )[0].split('/')\n slog.info(redcap_visit_id + \"_\" + scan,\"Warning: existing MR images of the pipeline are updated\",\n file = to_path_pattern,\n experiment_xnat_id=session,\n session_scan_list = session_and_scan_list )\n # Remove existing files of that type to make sure we start with clean slate\n for xml_file in pipeline_file_list:\n os.remove(xml_file)\n nii_file = re.sub('.nii.xml','.nii',xml_file)\n if os.path.exists(nii_file):\n os.remove(nii_file)\n nii_file += \".gz\"\n if os.path.exists(nii_file):\n os.remove(nii_file)\n\n if len( dicom_path_list ):\n temp_dir = tempfile.mkdtemp()\n # to_path_pattern = os.path.join( to_directory, filename_pattern )\n tmp_path_pattern = os.path.join(temp_dir, filename_pattern )\n if timer_label :\n slog.startTimer2() \n\n args= '--tolerance 1e-3 --write-single-slices --include-ndar --strict-xml --no-progress -rxO %s %s 2>&1' % ( tmp_path_pattern, ' '.join( dicom_path_list ))\n (ecode, sout, eout) = sutils.dcm2image(args)\n if ecode :\n slog.info(redcap_visit_id + \"_\" + scan,\"Error: Unable to create dicom file\",\n experiment_site_id=session,\n cmd=sutils.dcm2image_cmd + \" \" + args,\n err_msg = str(eout))\n shutil.rmtree(temp_dir)\n return False\n\n if timer_label:\n slog.takeTimer2('convert_dicom_to_nifti', timer_label) \n\n try:\n if not os.path.exists(to_directory):\n os.makedirs(to_directory)\n\n open( eid_file_path, 'w' ).writelines( session_and_scan_list )\n except:\n error = \"ERROR: unable to write EID file\"\n slog.info(redcap_visit_id + \"_\" + scan,error,\n experiment_site_id=session,\n eid_file_path = eid_file_path)\n\n try: \n for f in os.listdir(temp_dir):\n shutil.move(os.path.join(temp_dir,f),to_directory)\n\n except Exception as err_msg: \n error = \"ERROR: unable to move files\"\n slog.info(redcap_visit_id + \"_\" + scan,error,\n experiment_site_id = session,\n src_dir = temp_dir ,\n dest_dir = to_directory,\n err_msg = str(err_msg))\n shutil.rmtree(temp_dir)\n return False\n\n shutil.rmtree(temp_dir)\n return True\n return False\n\n#\n# Copy ADNI phantom T1w image file for structural session\n#\n# Returns - True if new file as created, False if not\n#\ndef copy_adni_phantom_t1w( redcap_visit_id, xnat, xnat_eid, to_directory ):\n # Check if target file already exists\n phantom_path = os.path.join( to_directory, 'phantom_t1.nii.gz' )\n if os.path.exists( phantom_path ):\n return False\n\n # Get XNAT experiment object\n experiment = xnat.select.experiments[ xnat_eid ]\n\n # Get list of resource files that match the T1w image file name pattern\n experiment_files = []\n resource_list=get_resource_list(redcap_visit_id,xnat,xnat_eid,experiment.resources)\n for resource in resource_list:\n experiment_files += [ (file['cat_ID'], re.sub( '.*\\/files\\/', '', file['URI']) ) for file in resource if re.match( '^t1.nii.gz$', file['Name'] ) ]\n\n # No matching files - nothing to do\n if len( experiment_files ) == 0:\n return False\n\n # Get first file from list, warn if more files\n (phantom_resource, phantom_file) = experiment_files[0]\n experiment.resources[phantom_resource].files[ phantom_file ].download( phantom_path, verbose=False )\n\n return True\n\n#\n# Copy ADNI phantom XML file for structural session\n#\n# Returns - True if new file as created, False if not\n#\ndef copy_adni_phantom_xml( redcap_visit_id, xnat, xnat_eid, to_directory ):\n # Check if target file already exists\n phantom_path = os.path.join( to_directory, 'phantom.xml' )\n if os.path.exists( phantom_path ):\n return False\n\n # Get XNAT experiment object\n experiment = xnat.select.experiments[ xnat_eid ]\n\n # Get list of resource files that match the phantom XML file name pattern\n experiment_files = []\n resource_list=get_resource_list(redcap_visit_id,xnat,xnat_eid,experiment.resources)\n for resource in resource_list:\n experiment_files += [ (file['cat_ID'], re.sub( '.*\\/files\\/', '', file['URI']) ) for file in resource if re.match( '^phantom.xml$', file['Name'] ) ]\n\n # No matching files - nothing to do\n if len( experiment_files ) == 0:\n return False\n\n # Get first file from list, warn if more files\n (phantom_resource, phantom_file) = experiment_files[0]\n experiment.resources[ phantom_resource ].files[ phantom_file ].download( phantom_path, verbose=False )\n\n return True\n\n#\n# Compress physio file in pipeline workdir\n#\ndef gzip_physio( physio_file_path ):\n (ecode,sout,eout) = sutils.gzip('-9f ' + str(physio_file_path))\n if ecode : \n error = \"ERROR: unable to compress physio file\"\n slog.info(physio_file_path,error, err_msg = str(eout))\n\ndef get_resource_list(redcap_visit_id,xnat,xnat_eid,exp_resources):\n\n resource_list=[]\n for resource in exp_resources.listing:\n uri='/data/experiments/%s/resources/%s/files' % ( xnat_eid, resource.id )\n try : \n json_data=xnat._get_json(uri)\n resource_list.append(json_data)\n\n # ==== test code === \n for file in json_data:\n if file['cat_ID'] != resource.id :\n raise RuntimeError(\"cat_id was different than resource.id for\", uri,str(file))\n \n except Exception as err_msg:\n slog.info(redcap_visit_id, \"WARNING: Could not retrieve\" + uri + \" from xnat.\", error_msg=str(err_msg),info=\"Modt likely file data of session is outdated - to update file data load session in xnat, select 'Manage Files', and press 'Update File Data'!\", resource_dir=resource.label,resource_id=resource.id)\n\n return resource_list\n\n# Copy physio files (cardio and respiratory) for resting-state fMRI session\n#\n# Returns - True if new file as created, False if not\n#\ndef copy_rsfmri_physio_files( redcap_visit_id, xnat, xnat_eid_and_scan, to_directory ):\n # Extract EID and scan from EID/Scan string\n match = re.match( '^(NCANDA_E[0-9]*)/([0-9]+).*', xnat_eid_and_scan )\n if not match:\n return False\n else:\n xnat_eid = match.group( 1 )\n xnat_scan = match.group( 2 )\n\n # Get XNAT experiment object\n experiment = xnat.select.experiments[ xnat_eid ]\n\n # Until we can look for \"physio\" tagged files, define list of filename patterns. Note that one type of files needs the scan number in the pattern to pick the right one\n physio_filename_patterns = { '.*\\.puls' : 'card_data_50hz',\n '.*\\.resp' : 'resp_data_50hz',\n 'cardiac_.*_%s' % xnat_scan : 'card_time_data_100hz',\n 'respir_.*_%s' % xnat_scan : 'resp_time_data_100hz',\n 'D.*\\.txt' : 'card_trig_data_resp_data_1000hz',\n 'PPGData.*_epiRT' : 'card_data_100hz',\n 'PPGTrig.*_epiRT' : 'card_trig_100hz',\n 'RESPData.*_epiRT' : 'resp_data_25hz',\n 'RESPTrig.*_epiRT' : 'resp_trig_25hz' }\n\n # Get list of resource files that match one of the physio file name patterns\n physio_files = []\n resource_list=get_resource_list(redcap_visit_id,xnat,xnat_eid,experiment.resources)\n for resource in resource_list:\n for (pattern,outfile_name) in list(physio_filename_patterns.items()):\n physio_files += [ (file['cat_ID'], re.sub( '.*\\/files\\/', '', file['URI']), outfile_name ) for file in resource if re.match( pattern, file['Name'] ) ]\n\n # No matching files - nothing to do\n if len( physio_files ) == 0:\n return False\n\n files_created = False\n for physio in physio_files:\n (physio_resource, physio_file, outfile_name) = physio\n\n # What will be the output file name? Does it already exist?\n physio_file_path = os.path.join( to_directory, outfile_name )\n if not ( os.path.exists( physio_file_path ) or os.path.exists( physio_file_path+'.gz' ) ):\n # Does output directory exist? Create if not\n if not os.path.exists( to_directory ):\n os.makedirs( to_directory )\n\n # determine a temporary target location\n (fh, physio_file_path_cache) = tempfile.mkstemp(suffix='physio_cache')\n # fh is integer - if object is needed use tempfile.TemporaryFile()\n # fh.close()\n\n experiment.resources[ physio_resource ].files[ physio_file ].download(physio_file_path_cache, verbose=False)\n\n if not '.txt' in physio_file:\n shutil.move( physio_file_path_cache, physio_file_path )\n gzip_physio( physio_file_path )\n files_created = True\n elif not 'Stroop' in physio_file:\n # Siemens add-on single file\n try:\n to_file = open( physio_file_path, 'w' )\n for line in open( physio_file_path_cache ).readlines():\n match = re.match( '^.* - Voltage - (.*)\\t.* - Voltage - (.*)\\t.* - Voltage - (.*)$', line )\n if match:\n to_file.write( '%s\\t%s\\t%s\\n' % ( match.group(1), match.group(2), match.group(3) ) )\n else:\n match = re.match( '^[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,4}\\s+(.*)\\s+[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,4}\\s+(.*)\\s+[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,4}\\s+(.*)$', line )\n if match:\n to_file.write( '%s\\t%s\\t%s\\n' % ( match.group(1), match.group(2), match.group(3) ) )\n else:\n to_file.write( line )\n\n gzip_physio( physio_file_path )\n files_created = True\n finally:\n to_file.close()\n \n # remove cached file\n shutil.rmtree(physio_file_path_cache, ignore_errors=True)\n\n return files_created\n\n#\n# Copy manual pipeline override files\n#\n# Returns - True if new file as created, False if not\n#\ndef copy_manual_pipeline_files( redcap_visit_id, xnat, xnat_eid, to_directory ):\n # Get XNAT experiment object\n experiment = xnat.select.experiments[ xnat_eid ]\n\n # Get list of resource files that match one of the physio file name patterns\n files = []\n resource_list=get_resource_list(redcap_visit_id,xnat,xnat_eid,experiment.resources)\n for resource in resource_list:\n files += [ (file['cat_ID'], re.sub( '.*\\/files\\/', '', file['URI']) ) for file in resource if file['collection'] == 'pipeline' ]\n\n # No matching files - nothing to do\n if len( files ) == 0:\n return False\n\n files_created = False\n for (resource,file_name) in files:\n file_path = os.path.join( to_directory, file_name )\n file_dir = os.path.dirname( file_path )\n if not os.path.exists( file_path ):\n # Does output directory exist? Create if not\n if not os.path.exists( file_dir ):\n os.makedirs( file_dir )\n\n experiment.resources[resource].files[file_name].download(file_path, verbose=False)\n \n files_created = True\n\n return files_created\n\n\ndef delete_workdir(workdir,redcap_visit_id,verbose=False): \n if os.path.exists(workdir):\n if verbose :\n print(\"Deleting \" + workdir)\n try :\n shutil.rmtree(workdir) \n except Exception as err_msg: \n slog.info(redcap_visit_id,\"Error: Could not delete directory \" + workdir, \n err_msg = str(err_msg))\n\n#\n# Export MR images and associated data to pipeline directory tree.\n#\n# Returns - True if new file as created, False if not\n#\ndef export_to_workdir( redcap_visit_id, xnat, session_data, pipeline_workdir, redcap_key, xnat_dir, stroop=(None,None,None), verbose=False, timerFlag=False):\n new_files_created = False\n\n # Export structural data\n pipeline_workdir_structural_main = os.path.join( pipeline_workdir, 'structural');\n pipeline_workdir_structural_native = os.path.join( pipeline_workdir_structural_main, 'native' );\n if session_data['mri_series_t1'] != '' and session_data['mri_series_t2'] != '' :\n if timerFlag :\n timerLabel = 't1'\n else :\n timerLabel = None\n\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_t1'], pipeline_workdir_structural_native, 't1.nii', xnat_dir, verbose=verbose, timer_label= timerLabel ) or new_files_created\n\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_t2'], pipeline_workdir_structural_native, 't2.nii', xnat_dir, verbose=verbose) or new_files_created\n\n # Copy ADNI phantom XML file\n if 'NCANDA_E' in session_data['mri_adni_phantom_eid']:\n new_files_created = copy_adni_phantom_xml( redcap_visit_id, xnat, session_data['mri_adni_phantom_eid'], pipeline_workdir_structural_native ) or new_files_created\n new_files_created = copy_adni_phantom_t1w( redcap_visit_id, xnat, session_data['mri_adni_phantom_eid'], pipeline_workdir_structural_native ) or new_files_created\n\n else :\n delete_workdir(pipeline_workdir_structural_main,redcap_visit_id,verbose)\n\n # Export diffusion data\n pipeline_workdir_diffusion_main = os.path.join( pipeline_workdir, 'diffusion' );\n pipeline_workdir_diffusion_native = os.path.join(pipeline_workdir_diffusion_main, 'native' );\n if session_data['mri_series_dti6b500pepolar'] != '' and session_data['mri_series_dti60b1000'] != '':\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_dti6b500pepolar'], os.path.join( pipeline_workdir_diffusion_native, 'dti6b500pepolar' ), 'dti6-%n.nii', xnat_dir, verbose=verbose ) or new_files_created\n\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_dti60b1000'], os.path.join( pipeline_workdir_diffusion_native, 'dti60b1000' ), 'dti60-%n.nii', xnat_dir, verbose=verbose ) or new_files_created\n\n if session_data['mri_series_dti30b400'] != '' :\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_dti30b400'], os.path.join( pipeline_workdir_diffusion_native, 'dti30b400' ), 'dti30-%n.nii', xnat_dir, verbose=verbose ) or new_files_created\n\n if session_data['mri_series_dti_fieldmap'] != '':\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_dti_fieldmap'], os.path.join( pipeline_workdir_diffusion_native, 'fieldmap' ), 'fieldmap-%T%N.nii', xnat_dir, verbose=verbose ) or new_files_created\n \n\n else :\n delete_workdir(pipeline_workdir_diffusion_main,redcap_visit_id,verbose)\n\n # Export EPI functional data (from DICOM files)\n pipeline_workdir_functional_main = os.path.join( pipeline_workdir, 'restingstate');\n pipeline_workdir_functional_native = os.path.join( pipeline_workdir_functional_main, 'native' );\n if session_data['mri_series_rsfmri'] != '' and session_data['mri_series_rsfmri_fieldmap'] != '':\n if timerFlag :\n timerLabel = 'rsfmri' \n else :\n timerLabel = None\n\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_rsfmri'], os.path.join( pipeline_workdir_functional_native, 'rs-fMRI' ), 'bold-%n.nii', xnat_dir, verbose=verbose, timer_label = timerLabel ) or new_files_created\n # Copy rs-fMRI physio files\n new_files_created = copy_rsfmri_physio_files( redcap_visit_id, xnat, session_data['mri_series_rsfmri'], os.path.join( pipeline_workdir_functional_native, 'physio' ) ) or new_files_created\n\n new_files_created = export_series( redcap_visit_id, xnat, redcap_key, session_data['mri_series_rsfmri_fieldmap'], os.path.join( pipeline_workdir_functional_native, 'fieldmap' ), 'fieldmap-%T%N.nii', xnat_dir, verbose=verbose ) or new_files_created\n\n else :\n delete_workdir(pipeline_workdir_functional_main,redcap_visit_id,verbose)\n\n # Export spiral functional data (from uploaded resources)\n pipeline_workdir_spiralstroop = os.path.join( pipeline_workdir, 'spiralstroop' )\n if session_data['mri_eid_spiral_stroop'] != '':\n new_files_created = export_spiral_files( redcap_visit_id, xnat, redcap_key, session_data['mri_eid_spiral_stroop'], pipeline_workdir_spiralstroop, stroop=stroop, verbose=verbose ) or new_files_created\n else :\n delete_workdir(pipeline_workdir_spiralstroop,redcap_visit_id,verbose)\n\n pipeline_workdir_spiralrest = os.path.join( pipeline_workdir, 'spiralrest')\n if session_data['mri_eid_spiral_rest'] != '':\n new_files_created = export_spiral_files(redcap_visit_id, xnat, redcap_key, session_data['mri_eid_spiral_rest'], pipeline_workdir_spiralrest, verbose=verbose) or new_files_created\n else :\n delete_workdir(pipeline_workdir_spiralrest,redcap_visit_id,verbose)\n\n\n # Copy any manual pipeline override files from all involved experiments\n # First, extract \"Experiment ID\" part from each \"EID/SCAN\" string, unless empty, then make into set of unique IDs.\n all_sessions = set( [ eid for eid in [ re.sub( '/.*', '', session_data[series] ) for series in list(session_data.keys()) if 'mri_series_' in series ] if 'NCANDA_E' in eid ] )\n for session in all_sessions:\n new_files_created = copy_manual_pipeline_files( redcap_visit_id, xnat, session, pipeline_workdir ) or new_files_created\n\n return new_files_created\n\n#\n# Translate subject code (ID) and REDCap event name to arm and visit name for file system\n#\n\n#\n# Export MR session and run pipeline if so instructed\n#\ndef export_and_queue(red2cas, redcap_visit_id, xnat, session_data, redcap_key, pipeline_root_dir, xnat_dir,stroop=(None,None,None), run_pipeline_script=None, verbose=False, timerFlag = False ):\n (subject_label, event_label) = redcap_key\n # Put together pipeline work directory for this subject and visit\n subject_code = session_data['mri_xnat_sid']\n (arm_code,visit_code,pipeline_workdir_rel) = (None, None, None)\n try:\n (arm_code,visit_code,pipeline_workdir_rel) = red2cas.translate_subject_and_event( subject_code, event_label )\n except:\n slog.info(redcap_visit_id, \"ERROR: Event \" + event_label + \" is not supported yet.\")\n return None\n\n if not arm_code:\n return None \n\n pipeline_workdir = os.path.join( pipeline_root_dir, pipeline_workdir_rel )\n \n if verbose:\n print(subject_label,'/',subject_code,'/',event_label,'to',pipeline_workdir)\n\n new_files_created = export_to_workdir(redcap_visit_id,xnat, session_data, pipeline_workdir, redcap_key, xnat_dir, stroop=stroop, verbose=verbose, timerFlag= timerFlag)\n\n if (new_files_created and run_pipeline_script):\n if verbose:\n print('Submitting script',run_pipeline_script,'to process',pipeline_workdir)\n just_pipeline_script=os.path.basename(run_pipeline_script)\n qsub_exe = 'cd %s; %s %s' % ( pipeline_root_dir,run_pipeline_script,pipeline_workdir_rel)\n # Changed title so it is informative when displayed in short form through qsub\n\n job_title = subject_code[7:] + visit_code[0] + visit_code[9:] + '-' + just_pipeline_script\n log_file = '/fs/ncanda-share/log/export_mr_sessions_pipeline/' + job_title + '.txt'\n red2cas.schedule_cluster_job(qsub_exe,'N%s-Nightly' % (job_title),submit_log=log_file, verbose = verbose)\n \n # It is very important to clear the PyXNAT cache, lest we run out of disk space and shut down all databases in the process\n try:\n xnat.client.clearcache()\n except:\n slog.info(\"export_mr_sessions_pipeline\",\"WARNING: clearing PyXNAT cache threw an exception - are you running multiple copies of this script?\")\n\n return new_files_created\n \n\n#\n# Check to make sure no pipeline data exist for \"excluded\" subjects\n#\ndef check_excluded_subjects( excluded_subjects, pipeline_root_dir ):\n for subject in excluded_subjects:\n subject_dir = os.path.join( pipeline_root_dir, subject )\n if os.path.exists( subject_dir ):\n error = \"ERROR: pipeline directory is from an *excluded* subject and should probable be deleted\"\n slog.info(subject_dir,error)\n","sub_path":"scripts/redcap/export_mr_sessions_pipeline.py","file_name":"export_mr_sessions_pipeline.py","file_ext":"py","file_size_in_byte":24951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"106188395","text":"'''\n@Description: \n@Author: fangn\n@Github: \n@Date: 2019-11-22 17:10:27\n@LastEditors: fangn\n@LastEditTime: 2019-11-25 09:31:01\n'''\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"图像锐化\")\n\nparser.add_argument('--lap', action='store_true', help='使用拉普拉斯算子进行边缘检测')\nparser.add_argument('--sobel', action='store_true', help='使用Sobel算子进行边缘检测')\nparser.add_argument('--fangnan',\n action='store_true',\n help='使用我的fangnan算子进行边缘检测')\nparser.add_argument('--dir', default='x', help='Sobel算子的边缘检测方向 x or y')\nparser.add_argument('--fdir',\n default='left',\n help='我的fangnan算子的边缘检测方向 left or right')\nparser.add_argument('--rgb', default=\"0\", help=\"选择你需要进行RGB直方图均衡化处理的图片(1~5)\")\n\nargs = parser.parse_args()\n\nfor arg in vars(args):\n if vars(args)[arg] == 'True':\n vars(args)[arg] = True\n elif vars(args)[arg] == 'False':\n vars(args)[arg] = False","sub_path":"作业一/work3/option.py","file_name":"option.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"163936603","text":"import logging\nimport platform\nimport sys\n\nimport linux\n\n\nlog = logging.getLogger(__name__)\n\n\ndef detect_init(*args, **kwargs):\n \"\"\"Detect the service manager running on this box\n args/kwargs match those of service.Service\n :return: The appropriate Service object for this system\n \"\"\"\n detected_os = platform.system()\n if detected_os == 'Linux':\n supported_linux_flavors = ['ubuntu', 'debian']\n flavor = platform.linux_distribution()[0]\n if flavor.lower() not in supported_linux_flavors:\n log.warn('{0} is not a support Linux distribution'.format(flavor))\n return detect_linux_init(*args, **kwargs)\n else:\n print(\"{0} is not currently supported by the Monasca Agent\".format(detected_os))\n sys.exit(1)\n\n # Service enable, includes setup of users/config directories so must be\n # done before configuration\n\n\ndef detect_linux_init(*args, **kwargs):\n \"\"\"Detect which of the linux inits is running\n :return: Return a valid Linux service manager object\n \"\"\"\n with open('/proc/1/comm', 'r') as init_proc:\n init = init_proc.readline().strip()\n if init == 'systemd':\n return linux.Systemd(*args, **kwargs)\n else:\n return linux.SysV(*args, **kwargs)\n","sub_path":"monasca_setup/service/detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"592753658","text":"# Copyright 2013 OpenStack Foundation\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nML2 Mechanism Driver for Cisco Nexus platforms.\n\"\"\"\n\nfrom oslo.config import cfg\n\nfrom neutron.common import constants as n_const\nfrom neutron.db import api as db_api\nfrom neutron.extensions import portbindings\nfrom neutron.openstack.common import log as logging\nfrom neutron.plugins.common import constants as p_const\nfrom neutron.plugins.ml2 import db as ml2_db\nfrom neutron.plugins.ml2 import driver_api as api\nfrom neutron.plugins.ml2.drivers.cisco.nexus import config as conf\nfrom neutron.plugins.ml2.drivers.cisco.nexus import constants as const\nfrom neutron.plugins.ml2.drivers.cisco.nexus import exceptions as excep\nfrom neutron.plugins.ml2.drivers.cisco.nexus import nexus_db_v2 as nxos_db\nfrom neutron.plugins.ml2.drivers.cisco.nexus import nexus_network_driver\n\nLOG = logging.getLogger(__name__)\n\n\nclass CiscoNexusMechanismDriver(api.MechanismDriver):\n\n \"\"\"Cisco Nexus ML2 Mechanism Driver.\"\"\"\n\n def initialize(self):\n # Create ML2 device dictionary from ml2_conf.ini entries.\n conf.ML2MechCiscoConfig()\n\n # Extract configuration parameters from the configuration file.\n self._nexus_switches = conf.ML2MechCiscoConfig.nexus_dict\n LOG.debug(\"nexus_switches found = %s\", self._nexus_switches)\n\n self.driver = nexus_network_driver.CiscoNexusDriver()\n\n def _valid_network_segment(self, segment):\n return (cfg.CONF.ml2_cisco.managed_physical_network is None or\n cfg.CONF.ml2_cisco.managed_physical_network ==\n segment[api.PHYSICAL_NETWORK])\n\n def _get_vlanid(self, segment):\n if (segment and segment[api.NETWORK_TYPE] == p_const.TYPE_VLAN and\n self._valid_network_segment(segment)):\n return segment.get(api.SEGMENTATION_ID)\n\n def _is_deviceowner_compute(self, port):\n return port['device_owner'].startswith('compute')\n\n def _is_status_active(self, port):\n return port['status'] == n_const.PORT_STATUS_ACTIVE\n\n def _get_switch_info(self, host_id):\n host_connections = []\n for switch_ip, attr in self._nexus_switches:\n if str(attr) == str(host_id):\n for port_id in (\n self._nexus_switches[switch_ip, attr].split(',')):\n if ':' in port_id:\n intf_type, port = port_id.split(':')\n else:\n intf_type, port = 'ethernet', port_id\n host_connections.append((switch_ip, intf_type, port))\n\n if host_connections:\n return host_connections\n else:\n raise excep.NexusComputeHostNotConfigured(host=host_id)\n\n def _configure_nve_db(self, vni, device_id, mcast_group, host_id):\n \"\"\"Create the nexus NVE database entry.\n\n Called during update precommit port event.\n \"\"\"\n host_connections = self._get_switch_info(host_id)\n for switch_ip, intf_type, nexus_port in host_connections:\n nxos_db.add_nexusnve_binding(vni, switch_ip, device_id,\n mcast_group)\n\n def _configure_nve_member(self, vni, device_id, mcast_group, host_id):\n \"\"\"Add \"member vni\" configuration to the NVE interface.\n\n Called during update postcommit port event.\n \"\"\"\n host_connections = self._get_switch_info(host_id)\n\n for switch_ip, intf_type, nexus_port in host_connections:\n # If configured to set global VXLAN values then\n # If this is the first database entry for this switch_ip\n # then configure the \"interface nve\" entry on the switch.\n if cfg.CONF.ml2_cisco.vxlan_global_config:\n nve_bindings = nxos_db.get_nve_switch_bindings(switch_ip)\n if len(nve_bindings) == 1:\n LOG.debug(\"Nexus: create NVE interface\")\n loopback = self._nexus_switches.get(\n (switch_ip, 'nve_src_intf'), '0')\n self.driver.enable_vxlan_feature(switch_ip,\n const.NVE_INT_NUM, loopback)\n\n # If this is the first database entry for this (VNI, switch_ip)\n # then configure the \"member vni #\" entry on the switch.\n member_bindings = nxos_db.get_nve_vni_switch_bindings(vni,\n switch_ip)\n if len(member_bindings) == 1:\n LOG.debug(\"Nexus: add member\")\n self.driver.create_nve_member(switch_ip, const.NVE_INT_NUM,\n vni, mcast_group)\n\n def _delete_nve_db(self, vni, device_id, mcast_group, host_id):\n \"\"\"Delete the nexus NVE database entry.\n\n Called during delete precommit port event.\n \"\"\"\n rows = nxos_db.get_nve_vni_deviceid_bindings(vni, device_id)\n for row in rows:\n nxos_db.remove_nexusnve_binding(vni, row.switch_ip, device_id)\n\n def _delete_nve_member(self, vni, device_id, mcast_group, host_id):\n \"\"\"Remove \"member vni\" configuration from the NVE interface.\n\n Called during delete postcommit port event.\n \"\"\"\n host_connections = self._get_switch_info(host_id)\n for switch_ip, intf_type, nexus_port in host_connections:\n if not nxos_db.get_nve_vni_switch_bindings(vni, switch_ip):\n self.driver.delete_nve_member(switch_ip, const.NVE_INT_NUM,\n vni)\n if (cfg.CONF.ml2_cisco.vxlan_global_config and\n not nxos_db.get_nve_switch_bindings(switch_ip)):\n self.driver.disable_vxlan_feature(switch_ip)\n\n def _configure_nxos_db(self, vlan_id, device_id, host_id, vni,\n is_provider_vlan):\n \"\"\"Create the nexus database entry.\n\n Called during update precommit port event.\n \"\"\"\n host_connections = self._get_switch_info(host_id)\n for switch_ip, intf_type, nexus_port in host_connections:\n port_id = '%s:%s' % (intf_type, nexus_port)\n nxos_db.add_nexusport_binding(port_id, str(vlan_id), str(vni),\n switch_ip, device_id)\n\n def _configure_switch_entry(self, vlan_id, device_id, host_id, vni,\n is_provider_vlan):\n \"\"\"Create a nexus switch entry.\n\n if needed, create a VLAN in the appropriate switch/port and\n configure the appropriate interfaces for this VLAN.\n\n Called during update postcommit port event.\n \"\"\"\n vlan_name = cfg.CONF.ml2_cisco.vlan_name_prefix + str(vlan_id)\n host_connections = self._get_switch_info(host_id)\n auto_create = True\n auto_trunk = True\n if is_provider_vlan:\n vlan_name = (cfg.CONF.ml2_cisco.provider_vlan_name_prefix\n + str(vlan_id))\n auto_create = cfg.CONF.ml2_cisco.provider_vlan_auto_create\n auto_trunk = cfg.CONF.ml2_cisco.provider_vlan_auto_trunk\n\n # (nexus_port,switch_ip) will be unique in each iteration.\n # But switch_ip will repeat if host has >1 connection to same switch.\n # So track which switch_ips already have vlan created in this loop.\n vlan_already_created = []\n for switch_ip, intf_type, nexus_port in host_connections:\n\n # The VLAN needs to be created on the switch if no other\n # instance has been placed in this VLAN on a different host\n # attached to this switch. Search the existing bindings in the\n # database. If all the instance_id in the database match the\n # current device_id, then create the VLAN, but only once per\n # switch_ip. Otherwise, just trunk.\n all_bindings = nxos_db.get_nexusvlan_binding(vlan_id, switch_ip)\n previous_bindings = [row for row in all_bindings\n if row.instance_id != device_id]\n if previous_bindings or (switch_ip in vlan_already_created):\n if auto_trunk:\n LOG.debug(\"Nexus: trunk vlan %s\"), vlan_name\n self.driver.enable_vlan_on_trunk_int(switch_ip, vlan_id,\n intf_type, nexus_port)\n else:\n vlan_already_created.append(switch_ip)\n if auto_create and auto_trunk:\n LOG.debug(\"Nexus: create & trunk vlan %s\"), vlan_name\n self.driver.create_and_trunk_vlan(\n switch_ip, vlan_id, vlan_name, intf_type, nexus_port,\n vni)\n elif auto_create:\n LOG.debug(\"Nexus: create vlan %s\"), vlan_name\n self.driver.create_vlan(switch_ip, vlan_id, vlan_name, vni)\n elif auto_trunk:\n LOG.debug(\"Nexus: trunk vlan %s\"), vlan_name\n self.driver.enable_vlan_on_trunk_int(switch_ip, vlan_id,\n intf_type, nexus_port)\n\n def _delete_nxos_db(self, vlan_id, device_id, host_id, vni,\n is_provider_vlan):\n \"\"\"Delete the nexus database entry.\n\n Called during delete precommit port event.\n \"\"\"\n try:\n rows = nxos_db.get_nexusvm_bindings(vlan_id, device_id)\n for row in rows:\n nxos_db.remove_nexusport_binding(row.port_id, row.vlan_id,\n row.vni, row.switch_ip, row.instance_id)\n except excep.NexusPortBindingNotFound:\n return\n\n def _delete_switch_entry(self, vlan_id, device_id, host_id, vni,\n is_provider_vlan):\n \"\"\"Delete the nexus switch entry.\n\n By accessing the current db entries determine if switch\n configuration can be removed.\n\n Called during delete postcommit port event.\n \"\"\"\n host_connections = self._get_switch_info(host_id)\n\n # (nexus_port,switch_ip) will be unique in each iteration.\n # But switch_ip will repeat if host has >1 connection to same switch.\n # So track which switch_ips already have vlan removed in this loop.\n vlan_already_removed = []\n for switch_ip, intf_type, nexus_port in host_connections:\n\n # if there are no remaining db entries using this vlan on this\n # nexus switch port then remove vlan from the switchport trunk.\n port_id = '%s:%s' % (intf_type, nexus_port)\n auto_create = True\n auto_trunk = True\n if is_provider_vlan:\n auto_create = cfg.CONF.ml2_cisco.provider_vlan_auto_create\n auto_trunk = cfg.CONF.ml2_cisco.provider_vlan_auto_trunk\n try:\n nxos_db.get_port_vlan_switch_binding(port_id, vlan_id,\n switch_ip)\n except excep.NexusPortBindingNotFound:\n if auto_trunk:\n self.driver.disable_vlan_on_trunk_int(switch_ip, vlan_id,\n intf_type, nexus_port)\n\n # if there are no remaining db entries using this vlan on this\n # nexus switch then remove the vlan.\n if auto_create:\n try:\n nxos_db.get_nexusvlan_binding(vlan_id, switch_ip)\n except excep.NexusPortBindingNotFound:\n\n # Do not perform a second time on same switch\n if switch_ip not in vlan_already_removed:\n self.driver.delete_vlan(switch_ip, vlan_id)\n vlan_already_removed.append(switch_ip)\n\n def _is_segment_nexus_vxlan(self, segment):\n return segment[api.NETWORK_TYPE] == p_const.TYPE_NEXUS_VXLAN\n\n def _get_segments(self, top_segment, bottom_segment):\n # Return vlan segment and vxlan segment (if configured).\n if top_segment is None:\n return None, None\n elif self._is_segment_nexus_vxlan(top_segment):\n return bottom_segment, top_segment\n else:\n return top_segment, None\n\n def _is_vm_migrating(self, context, vlan_segment, orig_vlan_segment):\n if not vlan_segment and orig_vlan_segment:\n return (context.current.get(portbindings.HOST_ID) !=\n context.original.get(portbindings.HOST_ID))\n\n def _port_action_vlan(self, port, segment, func, vni):\n \"\"\"Verify configuration and then process event.\"\"\"\n device_id = port.get('device_id')\n host_id = port.get(portbindings.HOST_ID)\n vlan_id = self._get_vlanid(segment)\n is_provider_vlan = segment.get(api.PROVIDER_SEGMENT)\n\n if vlan_id and device_id and host_id:\n func(vlan_id, device_id, host_id, vni, is_provider_vlan)\n else:\n fields = \"vlan_id \" if not vlan_id else \"\"\n fields += \"device_id \" if not device_id else \"\"\n fields += \"host_id\" if not host_id else \"\"\n raise excep.NexusMissingRequiredFields(fields=fields)\n\n def _port_action_vxlan(self, port, segment, func):\n \"\"\"Verify configuration and then process event.\"\"\"\n device_id = port.get('device_id')\n mcast_group = segment.get(api.PHYSICAL_NETWORK)\n host_id = port.get(portbindings.HOST_ID)\n vni = segment.get(api.SEGMENTATION_ID)\n\n if vni and device_id and mcast_group and host_id:\n func(vni, device_id, mcast_group, host_id)\n return vni\n else:\n fields = \"vni \" if not vni else \"\"\n fields += \"device_id \" if not device_id else \"\"\n fields += \"mcast_group \" if not mcast_group else \"\"\n fields += \"host_id\" if not host_id else \"\"\n raise excep.NexusMissingRequiredFields(fields=fields)\n\n def update_port_precommit(self, context):\n \"\"\"Update port pre-database transaction commit event.\"\"\"\n vlan_segment, vxlan_segment = self._get_segments(\n context.top_bound_segment,\n context.bottom_bound_segment)\n orig_vlan_segment, orig_vxlan_segment = self._get_segments(\n context.original_top_bound_segment,\n context.original_bottom_bound_segment)\n\n # if VM migration is occurring then remove previous database entry\n # else process update event.\n if self._is_vm_migrating(context, vlan_segment, orig_vlan_segment):\n vni = self._port_action_vxlan(context.original, orig_vxlan_segment,\n self._delete_nve_db) if orig_vxlan_segment else 0\n self._port_action_vlan(context.original, orig_vlan_segment,\n self._delete_nxos_db, vni)\n else:\n if (self._is_deviceowner_compute(context.current) and\n self._is_status_active(context.current)):\n vni = self._port_action_vxlan(context.current, vxlan_segment,\n self._configure_nve_db) if vxlan_segment else 0\n self._port_action_vlan(context.current, vlan_segment,\n self._configure_nxos_db, vni)\n\n def update_port_postcommit(self, context):\n \"\"\"Update port non-database commit event.\"\"\"\n vlan_segment, vxlan_segment = self._get_segments(\n context.top_bound_segment,\n context.bottom_bound_segment)\n orig_vlan_segment, orig_vxlan_segment = self._get_segments(\n context.original_top_bound_segment,\n context.original_bottom_bound_segment)\n\n # if VM migration is occurring then remove previous nexus switch entry\n # else process update event.\n if self._is_vm_migrating(context, vlan_segment, orig_vlan_segment):\n vni = self._port_action_vxlan(context.original, orig_vxlan_segment,\n self._delete_nve_member) if orig_vxlan_segment else 0\n self._port_action_vlan(context.original, orig_vlan_segment,\n self._delete_switch_entry, vni)\n else:\n if (self._is_deviceowner_compute(context.current) and\n self._is_status_active(context.current)):\n vni = self._port_action_vxlan(context.current, vxlan_segment,\n self._configure_nve_member) if vxlan_segment else 0\n self._port_action_vlan(context.current, vlan_segment,\n self._configure_switch_entry, vni)\n\n def delete_port_precommit(self, context):\n \"\"\"Delete port pre-database commit event.\"\"\"\n if self._is_deviceowner_compute(context.current):\n vlan_segment, vxlan_segment = self._get_segments(\n context.top_bound_segment,\n context.bottom_bound_segment)\n vni = self._port_action_vxlan(context.current, vxlan_segment,\n self._delete_nve_db) if vxlan_segment else 0\n self._port_action_vlan(context.current, vlan_segment,\n self._delete_nxos_db, vni)\n\n def delete_port_postcommit(self, context):\n \"\"\"Delete port non-database commit event.\"\"\"\n if self._is_deviceowner_compute(context.current):\n vlan_segment, vxlan_segment = self._get_segments(\n context.top_bound_segment,\n context.bottom_bound_segment)\n vni = self._port_action_vxlan(context.current, vxlan_segment,\n self._delete_nve_member) if vxlan_segment else 0\n self._port_action_vlan(context.current, vlan_segment,\n self._delete_switch_entry, vni)\n\n def bind_port(self, context):\n LOG.debug(\"Attempting to bind port %(port)s on network %(network)s\",\n {'port': context.current['id'],\n 'network': context.network.current['id']})\n for segment in context.segments_to_bind:\n if self._is_segment_nexus_vxlan(segment):\n\n # Find physical network setting for this host.\n host_id = context.current.get(portbindings.HOST_ID)\n host_connections = self._get_switch_info(host_id)\n for switch_ip, attr2, attr3 in host_connections:\n physnet = self._nexus_switches.get((switch_ip, 'physnet'))\n if physnet:\n break\n else:\n raise excep.PhysnetNotConfigured(host_id=host_id,\n host_connections=host_connections)\n\n # Allocate dynamic vlan segment.\n vlan_segment = {api.NETWORK_TYPE: p_const.TYPE_VLAN,\n api.PHYSICAL_NETWORK: physnet}\n context.allocate_dynamic_segment(vlan_segment)\n\n # Retrieve the dynamically allocated segment.\n # Database has provider_segment dictionary key.\n network_id = context.current['network_id']\n dynamic_segment = ml2_db.get_dynamic_segment(\n db_api.get_session(), network_id, physnet)\n\n # Have other drivers bind the VLAN dynamic segment.\n if dynamic_segment:\n context.continue_binding(segment[api.ID],\n [dynamic_segment])\n else:\n raise excep.NoDynamicSegmentAllocated(\n network_id=network_id, physnet=physnet)\n else:\n LOG.debug(\"No binding required for segment ID %(id)s, \"\n \"segment %(seg)s, phys net %(physnet)s, and \"\n \"network type %(nettype)s\",\n {'id': segment[api.ID],\n 'seg': segment[api.SEGMENTATION_ID],\n 'physnet': segment[api.PHYSICAL_NETWORK],\n 'nettype': segment[api.NETWORK_TYPE]})\n","sub_path":"neutron/plugins/ml2/drivers/cisco/nexus/mech_cisco_nexus.py","file_name":"mech_cisco_nexus.py","file_ext":"py","file_size_in_byte":21036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"309406227","text":"#-*- coding:utf-8 _*- \n\"\"\" \n@author:Administrator\n@file: xgboost_test.py\n@time: 2018/8/10\n\"\"\"\nimport numpy as np\n\nnp.set_printoptions(suppress=False)\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom scipy.stats import skew\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import cross_val_score\n\n# pandas 的显示设置函数:\nmpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 SimHei为黑体\nmpl.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n\npd.set_option('max_columns', 200)\npd.set_option('display.width', 1000)\n\n# train_data = pd.read_csv('./final_process_train_6.csv')\n# test_data = pd.read_csv('./final_process_test_6.csv')\n\ntrain_data = pd.read_csv('./month_6_train_1.csv')\ntest_data = pd.read_csv('./test_data_1.csv')\n\n# log 变换\ntrain_data['price'] = np.log1p(train_data['price'])\ntest_data['price'] = np.log1p(test_data['price'])\n\ntrain_data['daysOnMarket'] = np.log1p(train_data['daysOnMarket'])\ntest_data['daysOnMarket'] = np.log1p(test_data['daysOnMarket'])\n\n\ntrain = train_data.drop(columns='daysOnMarket')\ntest = test_data.drop(columns='daysOnMarket')\n\n\ntrain_label = train_data['daysOnMarket']\ntest_label = np.expm1(test_data['daysOnMarket'])\n\n\nprint(train.head())\nprint(test.head())\n\nfrom xgboost import XGBRegressor\nfrom sklearn.model_selection import GridSearchCV,KFold\n# print(help(XGBRegressor))\n\n# 寻找超参数\nparams = {\n # 'n_estimators': [100,300,500,1000,5000],# 300\n 'max_depth':[x for x in range(5,6,1)],#5\n # 'max_depth':[x for x in range(3,10,1)],#5\n # 'learning_rate':[0.001,0.01,0.05,0.1,0.3,0.5,0.7,0.9], # 0.3\n # 'reg_alpha':[1e-5,1e-2,0.1,1,100],#1\n # 'gamma':[x for x in range(0,10,1)],#0\n # 'min_child_weight':[x for x in range(1,10,1)],# 5\n # 'subsample':[x for x in np.arange(0,1,0.01)], # 0.65\n }\n'''\n eta –> learning_rate\n lambda –> reg_lambda\n alpha –> reg_alpha\n'''\nkfold = KFold(n_splits=10)\ngrid = GridSearchCV(estimator=XGBRegressor(),param_grid=params,scoring='neg_mean_absolute_error',cv=kfold)\n\n# 训练\ngrid.fit(train,train_label)\n# print(len(grid.cv_results_.values()))\n# print(help(grid.))\n# 打印最好参数和最好的得分值\nprint('best_params',grid.best_params_)\nprint('best_scoring',grid.best_score_)\nprint('best:%f use:%r'%(grid.best_score_,grid.best_params_))\nfor params, mean_score, scores in grid.grid_scores_:\n print(\"%f (%f) with: %r\" % (scores.mean(), scores.std(), params))\nmodel = grid.best_estimator_\nprint(model)\n\n\n\n# 预测\npreds = np.expm1(model.predict(test))\n\npreds_Series = pd.Series(preds)\nprint(preds_Series.describe())\nprint('error',mean_absolute_error(test_label,preds))\nprint('pred_mean',preds.mean())\nprint('true_mean',test_label.mean())\n\n# 画图\n\nplt.figure(figsize=(12,9))\nplt.ylabel(\"Target--variance%f\"%(test_label.var()))\nplt.xlabel(\"Prediction--variance%f\"%(preds.var()))\nplt.title(\"Target vs. Prediction\")\nlim = max(test_label)\nlim *= 1.05\nplt.xlim(0, lim)\nplt.ylim(0, lim)\nplt.plot([0, lim], [0, lim], alpha=0.5, color='red')\nplt.scatter(preds, test_label, alpha=0.5, label=\"training\")\nplt.legend()\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n\n\n\n\n\n# plt.figure(figsize=(12,9))\n#\n# plt.plot(preds[0:100],c='blue',label='pred')\n# plt.plot(test_label[0:100],c='red',label='true')\n# plt.title(\"RandomForest preds and true daysOnMarket distribution circumstance\")\n# plt.legend()\n# plt.show()\n\n'''\n\n'''\n\n'''\n\n'''\n\n\n\n","sub_path":"buildingTypeId_no_reducing_demensions/first_process/xgboost_test.py","file_name":"xgboost_test.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"642113368","text":"\n#basics\nimport random\nimport pandas as pd\nimport torch\n\n\nfrom nltk.tokenize import RegexpTokenizer\nimport os\nimport xml.etree.ElementTree as ET\nimport re\nfrom random import choice\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom venn import venn\n\npd.options.mode.chained_assignment = None\n\ndevice = torch.device(\"cuda:1\")\n\nclass DataLoaderBase:\n\n #### DO NOT CHANGE ANYTHING IN THIS CLASS ### !!!!\n\n def __init__(self, data_dir:str, device=None):\n self._parse_data(data_dir)\n assert list(self.data_df.columns) == [\n \"sentence_id\",\n \"token_id\",\n \"char_start_id\",\n \"char_end_id\",\n \"split\"\n ]\n\n assert list(self.ner_df.columns) == [\n \"sentence_id\",\n \"ner_id\",\n \"char_start_id\",\n \"char_end_id\",\n ]\n self.device = device\n \n\n def get_random_sample(self):\n # DO NOT TOUCH THIS\n # simply picks a random sample from the dataset, labels and formats it.\n # Meant to be used as a naive check to see if the data looks ok\n sentence_id = random.choice(list(self.data_df[\"sentence_id\"].unique()))\n sample_ners = self.ner_df[self.ner_df[\"sentence_id\"]==sentence_id]\n sample_tokens = self.data_df[self.data_df[\"sentence_id\"]==sentence_id]\n\n decode_word = lambda x: self.id2word[x]\n sample_tokens[\"token\"] = sample_tokens.loc[:,\"token_id\"].apply(decode_word)\n\n sample = \"\"\n for i,t_row in sample_tokens.iterrows():\n\n is_ner = False\n for i, l_row in sample_ners.iterrows():\n if t_row[\"char_start_id\"] >= l_row[\"char_start_id\"] and t_row[\"char_start_id\"] <= l_row[\"char_end_id\"]:\n sample += f'{self.id2ner[l_row[\"ner_id\"]].upper()}:{t_row[\"token\"]} '\n is_ner = True\n \n if not is_ner:\n sample += t_row[\"token\"] + \" \"\n\n return sample.rstrip()\n\n\n\nclass DataLoader(DataLoaderBase):\n\n\n def __init__(self, data_dir:str, device=None):\n super().__init__(data_dir=data_dir, device=device)\n\n \n def get_paths(self, rootdir):\n # fetches a list of absolute paths to all xml files in subdirectories in rootdir\n # helper to parse_xmls\n file_paths = []\n for folder, _, files in os.walk(rootdir):\n for filename in files:\n if filename.endswith('xml'):\n file_paths.append(os.path.abspath(os.path.join(folder, filename)))\n return file_paths\n \n def string_to_span(self, s):\n # creates a tokenized version and a span version of a string\n # helper to parse_xmls\n punctuation = \"-,.?!:;\"\n tokenizer = RegexpTokenizer(\"\\s|:|;\", gaps=True)\n tokenized = tokenizer.tokenize(s.lower())\n tokenized = [word.strip(punctuation) if word[-1] in punctuation else word for word in tokenized] # removing punctuation if it's the last char in a word\n span = list(tokenizer.span_tokenize(s)) # gets the pythonic span i e (start, stop_but_not_including)\n new_span = []\n for tpl in span:\n new_span.append((tpl[0], (tpl[1]-1))) # to get non-pythonic span i e (start,last_char)\n return new_span, tokenized\n\n def pad_sentences(self, sentences, max_length):\n # pads sentences to be of length max_length\n # helper to parse_xmls\n data_df_list = []\n for sent in sentences:\n split = sent[0][4]\n pad_len = max_length - len(sent) # how many padding token are needed to make len(sent) == max_length\n pad_rows = pad_len * [(0, 0, 0, 0, split)] # list of padding rows made to fit dataframe ie four 0's are for 'sent_id', 'token_id', 'char_start', 'char_end'\n sent.extend(pad_rows) # if sent_id is specified, get_random_sample doesn't work properly\n data_df_list.extend(sent)\n return data_df_list\n \n def parse_xmls(self, fileList):\n\n data_df_list = [] \n ner_df_list = []\n all_sentences = [] # will contain a list of tuples where each list represents a sentence and each tuple inside the lists represents a word\n self.ner2id = {\n 'other/pad' : 0,\n 'drug' : 1,\n 'drug_n' : 2,\n 'group' : 3, \n 'brand' : 4\n }\n self.word2id = {}\n\n for file in fileList:\n tree = ET.parse(file)\n root = tree.getroot()\n for sentence in root:\n one_sentence = []\n sent_id = sentence.attrib['id']\n sent_txt = sentence.attrib['text']\n if sent_txt == \"\": # to exclude completely empty sentences i e DDI-DrugBank.d228.s4 in Train/DrugBank/Fomepizole_ddi.xml\n continue\n if 'test' in file.lower():\n split = 'test'\n else:\n split = choice([\"train\", \"train\", \"train\", \"train\", \"val\"]) # making it a 20% chance that it's val and 80% chance that it's train\n char_ids, tokenized = self.string_to_span(sent_txt)\n for i, word in enumerate(tokenized): # creating data_df_list, one_sentence\n if word in self.word2id.keys(): # creating word2id, vocab\n word = self.word2id[word]\n else:\n w_id = 1 + len(self.word2id) # zero is pad\n self.word2id[word] = w_id\n word = w_id\n word_tpl = (sent_id, word, int(char_ids[i][0]), int(char_ids[i][1]), split) # one row in data_df \n one_sentence.append(word_tpl)\n for entity in sentence: # creating the ner_df_list\n if entity.tag == 'entity':\n ent_type = (entity.attrib['type']).lower()\n ent_type = self.ner2id[ent_type]\n char_offset = entity.attrib['charOffset']\n char_span = (re.sub(r\"[^0-9]+\",' ', char_offset)).split(' ') # substituting everything in char_offset that is not a number with a space\n # to be able to split on spaces \n if len(char_span) > 2: # for multi-word entities \n char_pairs = (list(zip(char_span[::2], char_span[1::2])))\n for pair in char_pairs:\n entity_tpl = (sent_id, ent_type, int(pair[0]), int(pair[1]))\n ner_df_list.append(entity_tpl)\n else:\n ent_start_id, ent_end_id = char_span \n entity_tpl = (sent_id, ent_type, int(ent_start_id), int(ent_end_id))\n ner_df_list.append(entity_tpl)\n all_sentences.append(one_sentence)\n\n \n self.max_sample_length = max([len(x) for x in all_sentences])\n data_df_list = self.pad_sentences(all_sentences, self.max_sample_length)\n \n return data_df_list, ner_df_list\n \n def _parse_data(self, data_dir):\n \n allFiles = self.get_paths(data_dir)\n data_df_list, ner_df_list = self.parse_xmls(allFiles)\n \n # creating dataframes\n self.data_df = pd.DataFrame(data_df_list, columns=['sentence_id', 'token_id', 'char_start_id', 'char_end_id', 'split'])\n self.ner_df = pd.DataFrame(ner_df_list, columns=['sentence_id', 'ner_id', 'char_start_id', 'char_end_id'])\n \n # adding 'pad' to word2id, reversing dictionaries, getting vocab\n self.word2id[''] = 0 \n self.id2word = {v:k for k, v in self.word2id.items()}\n self.id2ner = {v:k for k, v in self.ner2id.items()}\n self.vocab = list(self.word2id.keys())\n\n\n def get_ners(self, df):\n # constructs label tensors with the help of ner_id\n # returns labellist: a list of all labels, and nested_lists: a list of list where each inner list represents a sentence. Each inner list contains labels for that particular sentence\n #helper to get_y\n \n data_sentence_ids = list(df.sentence_id)\n data_start = list(df.char_start_id)\n data_end = list(df.char_end_id)\n data_token = list(df.token_id)\n data_tpls = [(data_sentence_ids[i], data_token[i], data_start[i], data_end[i]) for i, elem in enumerate(data_sentence_ids)]\n\n labellist = []\n for tpl in data_tpls: # for every word in data_df, give it a label\n data_sent_id, data_token, data_char_start, data_char_end = tpl\n tpl = (data_sent_id, data_char_start, data_char_end)\n if data_token == 0: # if it's padding\n label = 0 # add 0 label for padding/other\n labellist.append(label)\n continue\n for i, ner in enumerate(self.ner_tpls): # enumerate ensures that we get correct label for row\n ner_sent_id, ner_char_start, ner_char_end = ner\n if tpl == ner: \n label = self.ner_id[i]\n continue\n if data_sent_id == ner_sent_id: # if the two tuples (tpls and ner) aren't exactly the same ie when the ner contains multiple words\n if (data_char_start >= ner_char_start) and (data_char_end <= ner_char_end): # if the word's start character is greater or equal to the ner start AND word end character is smaller or equal to the ner end, then it counts as part of that ner\n label = self.ner_id[i]\n else:\n label = 0\n labellist.append(label)\n nested_lists = [labellist[x:x+(self.max_sample_length)] for x in range(0, len(labellist), (self.max_sample_length))] # same as labellist but divided into number of sentences\n return labellist, nested_lists\n \n \n \n def get_y(self):\n # returns a tensor containing the ner labels for all samples in each split.\n \n # constructing ner tuples (sentence_id, ner_start, ner_end) and list of ner_ids\n ner_sentence_ids = list(self.ner_df.sentence_id)\n ner_start = list(self.ner_df.char_start_id)\n ner_end = list(self.ner_df.char_end_id)\n self.ner_id = list(self.ner_df.ner_id)\n self.ner_tpls = [(ner_sentence_ids[i], ner_start[i], ner_end[i]) for i, elem in enumerate(ner_sentence_ids)]\n \n # splitting dataframes into train, test, val \n train_df = self.data_df.loc[self.data_df.split == 'train']\n test_df = self.data_df.loc[self.data_df.split == 'test']\n val_df = self.data_df.loc[self.data_df.split == 'val']\n \n # getting list of labels and list of labels divided into sentences for each split\n self.train_labels, self.train_get_y = self.get_ners(train_df)\n self.test_labels, self.test_get_y = self.get_ners(test_df)\n self.val_labels, self.val_get_y = self.get_ners(val_df)\n \n # putting list of labels divided into sentences on the gpu\n self.train_y = torch.Tensor(self.train_get_y).to(device)\n self.test_y = torch.Tensor(self.test_get_y).to(device)\n self.val_y = torch.Tensor(self.val_get_y).to(device)\n \n print('get_y done')\n return self.train_y, self.val_y, self.test_y\n \n\n def plot_split_ner_distribution(self):\n # plots a histogram displaying ner label counts for each split\n self.get_y()\n \n # counting label excluding 0 since keeping it hides distribution of other labels\n train_counts = Counter([self.id2ner[l] for l in self.train_labels if l != 0])\n test_counts = Counter([self.id2ner[l] for l in self.test_labels if l != 0])\n val_counts = Counter([self.id2ner[l] for l in self.val_labels if l != 0])\n \n pd.DataFrame([train_counts, test_counts, val_counts], index=['train', 'test', 'val']).plot(kind='bar')\n \n pass\n \n\n\n def plot_sample_length_distribution(self):\n #plots a histogram displaying the distribution of sample lengths in number tokens\n \n # removing 0's (padding), converting to series with index 'sentence_id' and values 'token_id' (which second column doesn't matter), group by 'sentence_id' and count, convert counts to list. converting to series is done to enable converting to list of counts\n sentence_length = self.data_df.loc[self.data_df.token_id != 0].set_index('sentence_id')['token_id'].groupby('sentence_id').count().to_list()\n\n #plotting\n plt.style.use('ggplot') # plot style\n plt.rcParams['figure.figsize'] = [20/2.54, 16/2.54] # making plot bigger\n plt.hist(sentence_length, bins=45, color='#C25A7C')\n plt.xlabel('Length of sentence')\n plt.ylabel('No. of sentences')\n plt.show()\n \n \n\n\n def plot_ner_per_sample_distribution(self): \n # plots a histogram displaying the distribution of number of NERs in sentences\n \n ners_per_sentence = self.ner_df.set_index('sentence_id')['ner_id'].groupby(['sentence_id']).count().to_list() # similar to plot_sample_length_distribution, but not removing 0's (since they don't exist as labels in ner_df) \n no_ners = (self.data_df['sentence_id'].nunique()) - (self.ner_df['sentence_id'].nunique()) # number of sentences with no ners\n no_ners = [0] * no_ners \n ners_per_sentence.extend(no_ners) # adding the same number 0's as sentences that don't contain ners\n \n #plotting\n plt.style.use('ggplot')\n plt.rcParams['figure.figsize'] = [20/2.54, 16/2.54]\n plt.hist(ners_per_sentence, bins=45, color='#5ac26c')\n plt.xlabel('No. of ners')\n plt.ylabel('No. of sentences')\n plt.show()\n \n\n\n\n def plot_ner_cooccurence_venndiagram(self):\n # plots a ven-diagram displaying how the ner labels co-occur\n \n df_dict = self.ner_df.groupby('ner_id').apply(lambda x: set(x['sentence_id'])).to_dict() # makes a dictionary of {label1 : set(sentence1, sentence2, ...)}\n for i, ner in self.id2ner.items(): # changing the label id's to label names\n if i in df_dict:\n df_dict[self.id2ner[i]] = df_dict.pop(i)\n \n venn(df_dict)\n\n\n\n","sub_path":"aa/data_loading.py","file_name":"data_loading.py","file_ext":"py","file_size_in_byte":14843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"468654043","text":"def regioni_rosse(lista):\n def intersezione(nodo, check):\n '''Restituisce vero se 'nodo' e 'check' si intersecano'''\n (x, y), base, altezza = nodo\n (x_check, y_check), base_check, altezza_check = check\n\n return (y + altezza) >= y_check \\\n and y <= (y_check + altezza_check) \\\n and (x + base) >= x \\\n and x <= (x_check + base_check)\n\n def dfs(nodo):\n for adiacente in grafo[nodo]:\n if componenti[adiacente] == -1:\n componenti[adiacente] = componenti[nodo]\n dfs(adiacente)\n\n grafo = {nodo:[] for nodo in lista}\n\n # Creazione del grafo.\n for nodo in grafo:\n for check in grafo:\n if check != nodo:\n if intersezione(nodo, check):\n grafo[nodo].append(check)\n grafo[check].append(nodo)\n\n # -1 -> nessuna componente assegnata\n componenti = {nodo:-1 for nodo in lista}\n ultima_comp = -1\n\n for nodo in grafo:\n if componenti[nodo] == -1:\n ultima_comp += 1\n componenti[nodo] = ultima_comp\n dfs(nodo)\n\n return len(set(componenti.values()))\n","sub_path":"Progettazione di Algoritmi/canale2/2018_2019/esercizi/rettangoli.py","file_name":"rettangoli.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"601880397","text":"import os\n\nimport torch\n\nfrom ncc import LOGGER\nfrom ncc import tasks\nfrom ncc.eval.summarization import summarization_metrics\nfrom ncc.utils import checkpoint_utils\nfrom ncc.utils import utils\nfrom ncc.utils.file_ops.yaml_io import load_yaml\nfrom ncc.utils.logging import progress_bar\nfrom ncc.utils.logging.meters import StopwatchMeter\n\n\ndef main(args, out_file=None):\n use_cuda = torch.cuda.is_available() and not args['common']['cpu']\n # use_cuda = False\n\n # Load dataset splits\n task = tasks.setup_task(args)\n task.load_dataset(args['dataset']['gen_subset'])\n\n # Set dictionaries\n src_dict = task.source_dictionary\n tgt_dict = task.target_dictionary\n\n # Load ensemble\n LOGGER.info('loading model(s) from {}'.format(args['eval']['path']))\n models, model_args = checkpoint_utils.load_model_ensemble(\n utils.split_paths(args['eval']['path']),\n arg_overrides=eval(args['eval']['model_overrides']),\n task=task,\n )\n\n # Optimize ensemble for generation\n for model in models:\n model.make_generation_fast_(\n beamable_mm_beam_size=None if args['eval']['no_beamable_mm'] else args['eval']['beam'],\n need_attn=args['eval']['print_alignment'],\n )\n\n if use_cuda:\n model = model.cuda()\n if model_args['common']['fp16'] and use_cuda:\n model.half()\n\n # Load dataset (possibly sharded)\n itr = task.get_batch_iterator(\n dataset=task.dataset(args['dataset']['gen_subset']),\n max_tokens=args['dataset']['max_tokens'],\n max_sentences=args['eval']['max_sentences'],\n max_positions=utils.resolve_max_positions(\n task.max_positions(),\n # *[model.max_positions() for model in models]\n ),\n ignore_invalid_inputs=model_args['dataset']['skip_invalid_size_inputs_valid_test'],\n required_batch_size_multiple=model_args['dataset']['required_batch_size_multiple'],\n num_shards=model_args['dataset']['num_shards'],\n shard_id=model_args['dataset']['shard_id'],\n num_workers=model_args['dataset']['num_workers'],\n ).next_epoch_itr(shuffle=False)\n progress = progress_bar.progress_bar(\n itr,\n log_format=model_args['common']['log_format'],\n log_interval=model_args['common']['log_interval'],\n default_log_format=('tqdm' if not model_args['common']['no_progress_bar'] else 'none'),\n )\n\n # Initialize generator\n gen_timer = StopwatchMeter()\n generator = task.build_generator(models, args)\n\n sources, hypotheses, references = dict(), dict(), dict()\n\n for sample in progress:\n torch.cuda.empty_cache()\n\n sample = utils.move_to_cuda(sample) if use_cuda else sample\n if 'net_input' not in sample:\n continue\n\n gen_timer.start()\n hypos = task.inference_step(generator, models, sample)\n num_generated_tokens = sum(len(h[0]['tokens']) for h in hypos) # TODO: warning\n gen_timer.stop(num_generated_tokens)\n\n for i, sample_id in enumerate(sample['id'].tolist()):\n has_target = sample['target'] is not None\n\n # Remove padding\n target_tokens = None\n if has_target:\n target_tokens = utils.strip_pad(sample['target'][i, :], tgt_dict.pad()).int().cpu()\n\n hypos_tokens = utils.strip_eos(hypos[i][0]['tokens'], tgt_dict.eos()).int().cpu()\n # bin_ast has no code_tokens, set \"0\" for any bin_ast\n src_str = \"0\"\n if has_target:\n target_str = tgt_dict.string(target_tokens, args['eval']['remove_bpe'], escape_unk=True)\n\n hypo_str = tgt_dict.string(hypos_tokens, args['eval']['remove_bpe'])\n\n sources[sample_id] = [src_str]\n hypotheses[sample_id] = [hypo_str]\n references[sample_id] = [target_str]\n\n bleu, rouge_l, meteor = \\\n summarization_metrics.eval_accuracies(hypotheses, references, filename=out_file, mode='test')\n LOGGER.info('BLEU: {:.2f}\\t ROUGE-L: {:.2f}\\t METEOR: {:.2f}'.format(bleu, rouge_l, meteor))\n\n\ndef cli_main():\n import argparse\n parser = argparse.ArgumentParser(\n description=\"Downloading/Decompressing CodeSearchNet dataset(s) or Tree-Sitter Library(ies)\")\n parser.add_argument(\n \"--yaml_file\", \"-f\", type=str, help=\"load {yaml_file}.yml for train\",\n )\n parser.add_argument(\n '--out_file', '-o', type=str, help='output generated file', default=None,\n )\n args = parser.parse_args()\n yaml_file = os.path.join(os.path.dirname(__file__), '{}.yml'.format(args.yaml_file))\n out_file = args.out_file\n if out_file:\n dirname = os.path.dirname(out_file)\n assert os.path.isdir(dirname)\n os.makedirs(dirname, exist_ok=True)\n LOGGER.info('Load arguments in {}, output gnerated sentences at {}(if None, it won\\'t record prediction).' \\\n .format(yaml_file, out_file))\n args = load_yaml(yaml_file)\n LOGGER.info(args)\n\n torch.cuda.set_device(args['distributed_training']['device_id'])\n main(args, out_file)\n\n\nif __name__ == '__main__':\n cli_main()\n","sub_path":"run/summarization/tree2seq/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"345168531","text":"import numpy as np\r\nimport math\r\nn=5\r\n\r\ny=np.random.randint(0,2,n)\r\ny_cap=np.random.rand(100)\r\n\r\nO=0\r\nfor i in range(n):\r\n O=O+(y[i]*math.log(y_cap[i],2)+(1-y[i])*math.log(1-y_cap[i],2))\r\n\r\nO=(O/n)*(-1)\r\nprint(O)","sub_path":"Akranth_ME20B100/question_1.py","file_name":"question_1.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"619116499","text":"# coding:utf-8\n\n\"\"\"\nCreated on Thu Aug 21 15:57:00 2020\n20200821 基本功能\n@author: huang\n\"\"\"\nfrom bs4 import BeautifulSoup # 引用BeautifulSoup库\nimport requests # 引用requests\nimport os # os\n\nroot = 'D://pydown//img//' # 配置存储路径\n\nfor page in range(1, 5): # 配置爬取页码,我这边配置的是5个人的图片\n for p in range(1, 20): # 配置爬取每个人多少张的参数,我这边配置的是每个人20张\n url = 'http://www.win4000.com/meinv'+str(page)+'_'+str(p)+'.html'\n r = requests.get(url) # 使用requests中的get方法获取整个网页\n r.encoding = 'utf-8' # 设定网页所使用的编码方式,错误的编码方式会导致乱码\n if r.status_code != 404: # 判断生成后的链接是不是能访问,只有能访问才能爬取下载\n demo = r.text # 将爬取后的对象通过text方法提取出所有的html\n # 使用BeautifulSoup库进行整合,第二个参数使用lxml一样的,lxml兼容性好较好,速度较快\n soup = BeautifulSoup(demo, \"html.parser\")\n # 选取整合后我们需要的部分内容,选取后的数据为list数组\n text = soup.find_all('img', class_='pic-large')\n for img in text:\n # 取出img标签中data-original中的值\n imagr_url = img.get('data-original')\n # 取出图片地址中文件及文件扩展名与本地存储路径进行拼接\n file_name = root + imagr_url.split('/')[-1]\n try:\n if not os.path.exists(root): # 判断文件夹是否存在,不存在则创建文件夹\n os.mkdir(root)\n if not os.path.exists(file_name): # 判断图片文件是否存在,存在则进行提示\n s = requests.get(imagr_url) # 通过requests.get方式获取文件\n # 使用with语句可以不用自己手动关闭已经打开的文件流\n with open(file_name, \"wb\") as f: # 开始写文件,wb代表写二进制文件\n f.write(s.content)\n print(\"爬取完成\")\n else:\n print(\"文件已存在\")\n except Exception as e:\n print(\"爬取失败:\" + str(e))\n\n","sub_path":"Python/Crawler/python爬虫爬取小姐姐图片.py","file_name":"python爬虫爬取小姐姐图片.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"618456960","text":"#!/usr/bin/env python\nimport os\n\nall_commands={}\n\nmy_dir = os.path.dirname(__file__)\nfor py in os.listdir(my_dir):\n if py == '__init__.py' or py == 'command.py':\n continue\n\n if py.endswith('.py'):\n name = py[:-3]\n mod = __import__(__name__,\n globals(),\n locals(),\n ['%s' % name])\n mod = getattr(mod, name)\n try:\n cmdn = getattr(mod, 'cmdName')\n clsn = getattr(mod, 'className')\n cmd = getattr(mod, clsn)()\n all_commands[cmdn] = cmd\n except AttributeError:\n raise SyntaxError('%s/%s does not define class %s' % (\n __name__, py, clsn))","sub_path":"cikit/cmds/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"306771792","text":"\nimport requests\n\nclass WGApplication():\n def __init__(self, id:str):\n self.__id = id\n\n\n def make_request(self, url:str, id_required=False, **kwargs):\n \"\"\"Make a request to a given URL with the given query paremeters\n\n Arguments:\n url:str URL to be queries\n kwargs Query paremeters\n\n Returns:\n resp Response JSON\n error Any errors that occorded\n \"\"\"\n if kwargs: # Add query parameters\n if id_required:\n kwargs['application_id'] = self.__id\n url = f\"{url}?{'&'.join([ f'{key}={kwargs[key]}' for key in kwargs])}\"\n elif id_required:\n url = f\"{url}?application_id={self.__id}\"\n\n print(url)\n\n req = requests.get(url)\n\n if req.status_code != 200:\n return None, f\"Unable to access wargaming API ({req.status_code})\"\n\n return req.json(), None","sub_path":"core/api/wgapi.py","file_name":"wgapi.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"519359133","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nHeader\r\n\r\n@author: Christoph\r\nVersion : 0.1\r\n\r\nHistory:\r\n[2016.03.31, CS]: start with the basic layout of the GUI; insert the status, \r\n insert the commands, insert a input field, insert a button,\r\n insert a label field;\r\n ERROR#8: make a history of commands given to the program \r\n by the player;\r\n scrollbar postponed to 'GUI - version 2';\r\n[2016.04.04, CS]: add the second window with the loplevel;\r\n update der name variable funzt nicht;\r\n \r\nSources:\r\n http://sebsauvage.net/python/gui/#add_text_entry\r\n http://effbot.org/tkinterbook/scrollbar.htm\r\n http://effbot.org/tkinterbook/listbox.htm\r\n \r\n http://www.tutorialspoint.com/python/python_gui_programming.htm\r\n http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html\r\n\"\"\"\r\n\r\n\r\n\r\nimport tkinter\r\n\r\nimport main_RPG\r\nimport functions_RPG\r\nimport parameter_RPG\r\n\r\ndef game_init():\r\n window = tkinter.Tk()\r\n \r\n root.grid() \r\n \r\n tkinter.Label(window, text='Name your Hero please:').grid(sticky='EW') \r\n \r\n print(\"Name your Hero please:\")\r\n playerstatus_dummy[\"name\"] = input(\">\")\r\n\r\n value = 0\r\n while (value != 8):\r\n value = 0\r\n print_lines(\"you can distribute 8 points onto the following 4 attributes:\\n\", \r\n \"clever, social, strong, fast\", \r\n \"seperate them by comma (eg:2,2,3,1)\",\r\n \"no atttribute should have more than 3 points\")\r\n data = input(\">\").split(sep= \",\")\r\n for index in range(4):\r\n # check if the values from the user are between 0 and 3\r\n if int(data[index]) <= 3 and int(data[index]) >= 0:\r\n value = value + int(data[index])\r\n if value != 8:\r\n print(\"you distributed the values false\")\r\n else:\r\n playerstatus_dummy[\"clever\"] = int(data[0])\r\n playerstatus_dummy[\"social\"] = int(data[1])\r\n playerstatus_dummy[\"strong\"] = int(data[2])\r\n playerstatus_dummy[\"fast\"] = int(data[3])\r\n playerstatus_dummy[\"life\"] = int(data[2])*3\r\n print(\"your char was created, now the game can begin\")\r\n return(playerstatus_dummy)\r\n\r\ndef simpleapp_tk(playerstatus):\r\n playerstatus = functions_RPG.generate_char()\r\n \r\n root = tkinter.Tk()\r\n root.grid()\r\n root.title('GUI: Ratten!')\r\n # set the window size to 600px x 400px \r\n root.geometry(\"600x400\")\r\n # set the window icon, must be in the same folder as the script\r\n root.wm_iconbitmap('logo_black.ico')\r\n \r\n # status of the player\r\n # labels for names\r\n text = ['name', 'life', 'clever', 'fast', 'social', 'strong', 'pack', 'talents', 'tricks', 'pros', 'cons'] \r\n \r\n for index in range(len(text)):\r\n tkinter.Label(root, text=text[index], anchor='e',width=10, fg=\"white\",bg=\"black\").grid(column=0,row=index,sticky='EW')\r\n tkinter.Label(root, text=playerstatus[text[index]],anchor='w', width=60).grid(column=1,row=index,sticky='w') \r\n \r\n root.mainloop()\r\n \r\n'''\r\nnew start\r\n'''\r\n \r\nglobal playerstatus \r\nplayerstatus_global = {\r\n \"name\" : 'global',\r\n \"clever\" : [],\r\n \"social\" : [],\r\n \"strong\" : [],\r\n \"fast\" : [],\r\n \"life\" : [],\r\n \"tricks\" : [],\r\n \"talents\" : [],\r\n \"pack\" : [],\r\n \"pros\" : [],\r\n \"cons\" : []\r\n } \r\n \r\nclass main_window:\r\n def __init__(self, master):\r\n self.master = master\r\n # The Frame widget is used as a container widget to organize other widgets.\r\n self.frame = tkinter.Frame(self.master)\r\n var = tkinter.StringVar()\r\n var.set(playerstatus_global['name'])\r\n self.name_lbl = tkinter.Label(self.frame, textvariable = var)\r\n self.button1 = tkinter.Button(self.frame, text='click me' , width = 25, command = self.new_window)\r\n # pack: This geometry manager organizes widgets in blocks before placing\r\n self.name_lbl.pack()\r\n self.button1.pack()\r\n self.frame.pack()\r\n #self.name_lbl.config(textvariable = var)\r\n \r\n def new_window(self):\r\n self.newWindow = tkinter.Toplevel(self.master)\r\n self.app = char_gen(self.newWindow)\r\n\r\nclass char_gen:\r\n\r\n def __init__(self, master):\r\n self.master = master\r\n \r\n # The Frame widget is used as a container widget to organize other widgets.\r\n self.frame = tkinter.Frame(self.master)\r\n #The Label widget is used to provide a single-line caption for other widgets. It can also contain images.\r\n # text: To display one or more lines of text in a label widget, Internal newlines (\"\\n\") will force a line break.\r\n # bd: The size of the border around the indicator. Default is 2 pixels.\r\n # wraplength: limit the number of characters in each line by setting this option to the desired number\r\n var = tkinter.StringVar()\r\n var.set(\"used for the char gen!\\nname hero:\")\r\n self.lbl = tkinter.Label(self.frame, textvariable=var, bd=5, wraplength=200)\r\n # Entry: widget is used to display a single-line text field for accepting values from a user.\r\n self.name_entry = tkinter.Entry(self.frame)\r\n self.quitButton = tkinter.Button(self.frame, text = 'set name', width = 25, command = self.close_windows)\r\n # pack: This geometry manager organizes widgets in blocks before placing \r\n self.lbl.pack()\r\n self.name_entry.pack(side=tkinter.LEFT)\r\n self.quitButton.pack()\r\n self.frame.pack()\r\n self.lbl.update_idletasks()\r\n \r\n def close_windows(self):\r\n playerstatus_global['name'] = self.name_entry.get()\r\n self.master.destroy()\r\n \r\ndef main():\r\n # start the player in room 1\r\n currentRoom = 11\r\n # an inventory, which is initially empty\r\n inventory = []\r\n # initialize the turns\r\n turn = 1\r\n root = tkinter.Tk()\r\n app = main_window(root)\r\n # grid: This geometry manager organizes widgets in a table-like structure \r\n # in the parent widget. \r\n # them in the parent widget\r\n #root.grid()\r\n \r\n\r\n root.mainloop()\r\n\r\nif __name__ == \"__main__\": \r\n #playerstatus = game_init()\r\n \r\n main()\r\n #simpleapp_tk(playerstatus)\r\n \r\n","sub_path":"GUI_RPG.py","file_name":"GUI_RPG.py","file_ext":"py","file_size_in_byte":6480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"55202747","text":"from django import forms\nfrom .models import report\nfrom tempus_dominus.widgets import DateTimePicker\n\n\nclass ReportCrime(forms.ModelForm):\n\n #image = forms.ImageField(upload_to='report_images')\n title = forms.CharField(max_length=50, required=False)\n description = forms.CharField(max_length=100, required=False)\n location_lat = forms.FloatField(required=True)\n location_lng = forms.FloatField(required=True)\n user_id = forms.EmailField(required=True)\n event_time = forms.DateTimeField(label=\"Event Time\", widget=DateTimePicker(\n options={\n 'useCurrent': True,\n 'collapse': True,\n },\n attrs={\n 'append': 'fa fa-calendar',\n 'icon_toggle': True,\n }\n ))\n #event_report = forms.DateTimeField(label=\"Report Time\", required=False)\n\n class Meta:\n model = report\n # ['fname', 'lname', 'email', 'phone_number', 'password1']\n fields = ['event_time', 'title', 'description',\n 'location_lat', 'location_lng', 'user_id', 'image'] # 'event_time', 'event_report',\n","sub_path":"report/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"631039388","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/tests/test_wordpiece_tokenizer.py\n# Compiled at: 2020-05-03 12:37:34\n# Size of source mod 2**32: 728 bytes\nimport pytest\nfrom konduit import *\nfrom konduit.load import server_from_file, client_from_file\nimport numpy as np\n\n@pytest.mark.integration\ndef test_wordpiece_tokenizer_serving_minimal():\n file_path = 'yaml/konduit_wordpiece_tokenizer_minimal.yaml'\n server = server_from_file(file_path)\n try:\n running_server = server_from_file(file_path, start_server=True)\n finally:\n running_server.stop()\n\n\n@pytest.mark.integration\ndef test_wordpiece_tokenizer_serving_two_steps():\n file_path = 'yaml/konduit_wordpiece_tokenizer_two_steps.yaml'\n server = server_from_file(file_path)\n try:\n running_server = server_from_file(file_path, start_server=True)\n finally:\n running_server.stop()","sub_path":"pycfiles/konduit-0.1.8-py3.7/test_wordpiece_tokenizer.cpython-37.py","file_name":"test_wordpiece_tokenizer.cpython-37.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"339232954","text":"# -*- coding: utf-8 -*-\r\nimport logging\r\nimport platform\r\n\r\nfrom openerp import tools\r\nimport openerp.modules\r\nimport subprocess\r\nfrom exceptions import Warning\r\nfrom openerp.osv import osv\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\n\r\nclass feosco_translate(osv.osv_memory):\r\n _name = \"si.translate\"\r\n\r\n def act_translate(self, cr, uid, ids, context={}):\r\n _logger.info('act_translate() BEGIN')\r\n modpath = openerp.modules.get_module_path('si_translate_v8')\r\n cr.execute(\"delete from ir_translation\")\r\n cr.commit\r\n arg = '*.po'\r\n os_system = str(platform.system())\r\n paths = os_system != 'Windows' and \\\r\n subprocess.check_output(['find', modpath + '/i18n', '-name', arg], shell=False) or \\\r\n subprocess.check_output(['dir', '/s/b', modpath + '\\i18n\\%s' % arg], shell=True) or \"\"\r\n if not paths:\r\n raise Warning(\"Please check your os again! Os Should be Windows or Ubuntu\")\r\n paths = paths.split('\\n')\r\n for path in paths:\r\n module_name = os_system == 'Windows' and path.split(\"\\\\\").pop().split(\".\")[0] or \\\r\n path.split(\"/\").pop().split(\".\")[0]\r\n path = os_system == 'Windows' and path.replace('\\\\', '/').replace('\\r','') or path\r\n _logger.info('Begin loading and translate file: %s with module_name %s' % (path, module_name))\r\n context = {'overwrite': True}\r\n tools.trans_load(\r\n cr, path, u'vi_VN',\r\n False, module_name, context=context)\r\n _logger.info('act_translate() END')\r\n return True\r\n","sub_path":"study/addons_diff/diff_dir/si_translate_v8/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"82693875","text":"def _odd_iter():\n n = 1\n while True:\n n += 2\n yield n\n\n\ndef _not_divisible(n):\n return lambda x: x % n > 0\n\n\ndef primes():\n yield 2\n it = _odd_iter() # 初始序列\n while True:\n n = next(it) # 返回序列的第一个数\n yield n\n it = filter(_not_divisible(n), it) # 构造新序列\n\nfor n in primes():\n if n < 5:\n print(n)\n else:\n exit()\n\n\n\ndef is_palindrome(n):\n s = str(n)\n return s == s[::-1]\n\noutput = filter(is_palindrome, range(1, 1000))\nprint(list(output))\n\n","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"37635878","text":"#!/usr/bin/python3\nimport requests\nimport requests.auth\n\n\ndef top_ten(subreddit):\n \"\"\"Return number of subscribers in subreddit\"\"\"\n url = 'https://www.reddit.com'\n user_agent = 'windows:com.holbertonschool:v0.1 (by /u/xarloz)'\n headers = {'User-Agent': user_agent}\n try:\n response = requests.get(\n '{}/r/{}/hot.json?limit=10'.format(url, subreddit),\n headers=headers, allow_redirects=False).json()\n data = response.get('data')\n for child in data.get('children'):\n data_child = child.get('data')\n print(data_child.get('title'))\n except:\n print(None)\n","sub_path":"0x16-api_advanced/1-top_ten.py","file_name":"1-top_ten.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"560431357","text":"import control\n\nm = 1.0\nM = 20.0\nl = 1.0\ng = 9.8\n\nA = [[0, 1, 0, 0],\n [0, 0, -m*g/M, 0],\n [0, 0, 0, 1],\n [0, 0, (M+m)*g/(M*l), 0]]\nB = [[0],\n [1/M],\n [0],\n [-1/(M * l)]]\nC = [[1, 0, 0, 0],\n [0, 0, 1, 0]]\nD = [[0], [0]]\n\nsystem = control.StateSpace(A, B, C, D)\nprint(\"System {0}\".format(system))\n\ntf = control.tf(system)\nprint(\"Transfer Function {0}\".format(tf))\n\npoles, zeros = tf.poles, tf.zeros\nprint(\"Poles {0}\\nZeros {1}\".format(poles, zeros))\n\n# print(\"Poles: {0}\".format(system.poles))\n# print(\"Zeros: {0}\".format(system.zeros))\n","sub_path":"code/scipy/swing_up.py","file_name":"swing_up.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"307857782","text":"# -*- coding: utf-8 -*-\n\"\"\"\n jQuery Example\n ~~~~~~~~~~~~~~\n\n A simple application that shows how Flask and jQuery get along.\n\n :copyright: (c) 2010 by Armin Ronacher.\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\n\nfrom __future__ import with_statement\n#from sqlite3 import dbapi2 as sqlite3\nfrom contextlib import closing\nfrom tools.file_tools import make_dictionary_list_from_file\nfrom flask import Flask, request, session, g, redirect, url_for, abort, \\\n render_template, flash\nfrom tools.text_tools import get_verses\n \nimport os\nimport sys\nimport sqlite3\n#import logging\n#log = logging.getLogger('werkzeug')\n\nDATABASE = './static/data/religion.sqlite'\nDEBUG = True #never leave True on production system\nSECRET_KEY = 'salt and swepper'\nUSERNAME = 'admin6z'\nPASSWORD = 'default6z'\n\n# create our little application :)\napp = Flask(__name__)\napp.config.from_object(__name__)\n\nbook_list = [{'title':'New Testament', 'file_name':'Bible - King James - New Testament.txt'}, \n {'title':'Old Testament', 'file_name':'Bible - King James - Old Testament.txt'}, \n {'title':'Book of Mormon', 'file_name':'Book of Mormon.txt'},\n {'title':'Koran', 'file_name':'Koran.txt'}]\n\n@app.before_request\ndef before_request():\n \"\"\"Make sure we are connected to the database each request.\"\"\"\n g.db = sqlite3.connect(app.config['DATABASE'])\n \n@app.teardown_request\ndef teardown_request(exception):\n \"\"\"Closes the database again at the end of the request.\"\"\"\n if hasattr(g, 'db'):\n g.db.close() \n\n@app.route('/')\ndef index():\n# return calendar()\n# return render_template('force.html')\n return render_template('religion_home.html')\n\n@app.route('/book_commands')\ndef book_commands():\n return render_template('book_commands.html', books=book_list) \n\n@app.route('/dlg_books.html')\ndef dlg_books():\n chapter_list = make_dictionary_list_from_file('../data/books/Koran-chp.txt')\n return render_template('dlg_books.html', books=book_list, chapters=chapter_list) \n \n@app.route('/get_books')\ndef get_books():\n# cursor = g.db.cursor()\n cur = g.db.execute('select title from books order by title desc')\n books = [dict(title=row[0]) for row in cur.fetchall()]\n app.logger.warning('user %s', books)\n return render_template('book_list.html', books=books) \n\n@app.route('/get_file')\ndef get_file():\n file_name = request.args.get('file_name')\n# with app.open_resource('./static/data/books/analysis/Koran_words_unigram_pos.txt') as f:\n with app.open_resource(file_name) as f:\n contents = f.read()\n return contents \n\n\n@app.route('/get_verses')\ndef srv_get_verses():\n book = request.args.get('book')\n chapters = request.args.getlist('chapters')\n# return str(request.args)\n# return str(book)\n return str(len(chapters)) #0\n# return get_verses(DATABASE, book, chapters)\n\n# first_shop = True\n# if 'shop_select' in request.args:\n# shops = request.args.getlist('shop_select')\n# for i in range(len(shops)):\n# if shops[i] == 'ALL':\n# str_shops = ''\n# break\n# else:\n# if first_shop:\n# first_shop = False\n# str_shops+=\" FAMIS_LABOR.CREW = '\" + shops[i] + \"' \"\n# else:\n# str_shops+=\" OR FAMIS_LABOR.CREW = '\" + shops[i] + \"' \" \n#\n# if 'start_date' in request.args:\n# start_date = request.args['start_date']\n# else:\n# return 'No start_date' \n#\n# if 'end_date' in request.args:\n# end_date = request.args['end_date']\n# else:\n# return 'No start_date' \n#\n# file_name = '../data/word_cloud.txt'\n## return 'Yes'\n# get_word_clouds(start_date, end_date, file_name, date_format='%m/%d/%Y')\n# with app.open_resource(file_name) as f:\n# contents = f.read()\n# return contents \n\n\n@app.route('/get_words')\ndef get_words():\n# with app.open_resource('./static/data/books/analysis/Koran_words_unigram_pos.txt') as f:\n with app.open_resource('../data/books/analysis/Koran_words_unigram_pos.txt') as f:\n contents = f.read()\n return contents \n\n#@app.route('/html_form_action_test', methods=['POST', 'GET'])\n@app.route('/html_form_action_test')\ndef html_form_action_test():\n user = request.args.get('user')\n app.logger.warning('user %s', type(user))\n return str(user)\n \n@app.route('/list_religious_texts')\ndef list_religious_texts():\n files = os.listdir('./static/data/books/')\n return render_template('books.html', books=files) \n\n@app.route('/run_sql')\ndef run_sql():\n sql = request.args.get('sql_statement')\n cur = g.db.execute(sql)\n books = [dict(title=row[0]) for row in cur.fetchall()]\n app.logger.warning('user %s', books)\n return render_template('book_list.html', books=books) \n\n@app.route('/text_analysis')\ndef text_analysis():\n chapter_list = make_dictionary_list_from_file('../data/books/Koran-chp.txt')\n return render_template('text_analysis.html', books=book_list, chapters=chapter_list) \n\n@app.route('/test_logging')\ndef test_logging():\n app.logger.debug('A value for debugging')\n app.logger.warning('A warning occurred (%d apples)', 42)\n app.logger.error('An error occurred')\n return 'done'\n\n@app.route('/scatter/data/')\ndef scatter_data(data_name):\n with app.open_resource('static/scatter/data/' + data_name) as f:\n contents = f.read()\n return contents\n\n@app.route('/site_info')\ndef site_info():\n# return 'Site Info'\n return str(app.config['APPLICATION_ROOT'])\n\n\nif __name__ == '__main__':\n app.run()\n \n","sub_path":"src/religion_server.py","file_name":"religion_server.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"637722113","text":"import logging, json, random\nfrom flask import Blueprint\nfrom flask_restful import Api, Resource, reqparse, marshal\n# ===== Untuk import db =====\nfrom blueprints import db\nfrom flask_jwt_extended import jwt_required, get_jwt_claims\nfrom blueprints.client import *\nfrom blueprints.auth import *\n\n# ===== Untuk import __init__.py =====\nfrom . import *\nfrom ..stuff import *\n# from ..stuff import *\n\nbp_cart = Blueprint('cart', __name__)\napi = Api(bp_cart)\n\n\n#### book RESOURCE CLASS\n#### All Data\nclass CartResource(Resource):\n @jwt_required\n def get(self, id=None):\n if id == None:\n parser = reqparse.RequestParser()\n parser.add_argument('p', location='args', type=int, default=1)\n parser.add_argument('rp', location='args', type=int, default=5)\n args = parser.parse_args()\n\n # Rumus (p*rp)-rp\n offset = (args['p'] * args['rp']) - args['rp']\n \n # Memunculkan data semua (ditampilkan sesuai jumlah rp)\n cart_all = Carts.query\n get_all = []\n\n if get_jwt_claims()['type'] == 'client':\n for get_data in cart_all:\n if get_data.username == get_jwt_claims()['username']:\n get_all.append(marshal(get_data, Carts.response_field))\n return get_all, 200, { 'Content-Type': 'application/json' }\n\n if get_jwt_claims()['type'] == 'admin' or get_jwt_claims()['type'] == \"superadmin\":\n for get_data in cart_all.limit(args['rp']).offset(offset).all():\n get_all.append(marshal(get_data, Carts.response_field))\n return get_all, 200, { 'Content-Type': 'application/json' }\n\n else:\n if get_jwt_claims()['type'] == 'client':\n cart = Carts.query.get(id)\n if cart is not None and cart.username == get_jwt_claims()['username']:\n return marshal(cart, Carts.response_field), 200, { 'Content-Type': 'application/json' }\n return {'status': 'NOT_FOUND', 'message': 'Anda belum membeli apapun'}, 404, { 'Content-Type': 'application/json' }\n\n @jwt_required\n def post(self):\n if get_jwt_claims()['type'] == 'client' or get_jwt_claims()['type'] == 'admin' or get_jwt_claims()['type'] == \"superadmin\":\n parser = reqparse.RequestParser()\n parser.add_argument('resi', location='json', type=int, required=True)\n parser.add_argument('jumlah', location='json', type=int, required=True)\n args = parser.parse_args()\n \n # Fungsi memanggil tabel barang\n barang = Stuffs.query.get(args['resi'])\n cart = Carts.query\n cart_data = []\n for get_data in cart:\n cart_data.append(marshal(get_data, Carts.response_field))\n # return cart_data, 200, { 'Content-Type': 'application/json' }\n \n # ==========(sentralize)==========\n calc_cart = args['jumlah']\n cart_belanja = []\n cart_other = []\n id_cart = 0\n pjg_data = len(cart_data)\n # return len(cart_data)\n # return cart[0].username\n # return cart_data[0]\n\n if pjg_data > 1:\n for get_data in cart:\n # return get_data.username\n if get_data.username == get_jwt_claims()['username']:\n if get_data.resi == args['resi']:\n calc_cart = get_data.jumlah + calc_cart\n id_cart = get_data.id\n db.session.delete(get_data)\n if get_data.resi != args['resi']:\n id_cart = args['resi']\n cart_belanja.append(marshal(get_data, Carts.response_field))\n if get_data.username != get_jwt_claims()['username']:\n continue\n # return cart_belanja\n # return \"TES\"\n if pjg_data == 1 and cart[0].username == get_jwt_claims()['username'] and cart[0].resi == args['resi']:\n calc_cart = cart.jumlah + calc_cart\n id_cart = args['resi']\n\n if pjg_data == 0 or id_cart == 0 or id_cart == []:\n id_cart = None\n\n \n # Kalkulasi sisa barang \n calc_barang = barang.jumlah - args['jumlah']\n # return \"OKE\"\n if calc_barang < 0:\n return {'status':'NOT_AVAILABLE', 'message':'The quantity stuff that requested is too many'}, 200, { 'Content-Type': 'application/json' }\n if calc_barang > barang.jumlah:\n return {'status':'INVALID', 'message':\"Too many stuff that you've input. Please check again\"}, 200, { 'Content-Type': 'application/json' }\n\n barang.barang = barang.barang\n barang.image = barang.image\n barang.deskripsi = barang.deskripsi\n barang.jenis = barang.jenis\n barang.harga = barang.harga\n\n # jika sisa 0, maka not available\n if calc_barang == 0:\n barang.status = \"Not Available\"\n barang.jumlah = 0\n \n barang.status = barang.status\n barang.jumlah = calc_barang\n # return \"TEST\"\n db.session.commit()\n\n # untuk cart\n cart_add = Carts(id_cart, args['resi'], None, None, None, None, None, None, None, None)\n # return \"OI\"\n cart_add.username = get_jwt_claims()['username']\n cart_add.barang = barang.barang\n cart_add.image = barang.image\n cart_add.deskripsi = barang.deskripsi\n cart_add.jenis = barang.jenis\n cart_add.harga = barang.harga\n cart_add.status = \"Success\"\n cart_add.jumlah = calc_cart\n db.session.add(cart_add)\n db.session.commit()\n\n return marshal(cart_add, Carts.response_field), 200, { 'Content-Type': 'application/json' }\n return {'status': 'USERS_ONLY', 'message': 'Only for users'}, 404, { 'Content-Type': 'application/json' }\n\n @jwt_required\n def put(self, id=None):\n if get_jwt_claims()['type'] == 'client' or get_jwt_claims()['type'] == 'admin' or get_jwt_claims()['type'] == \"superadmin\":\n parser = reqparse.RequestParser()\n parser.add_argument('id', location='json', type=int, required=True)\n parser.add_argument('jumlah_tambah', location='json', type=int)\n parser.add_argument('jumlah_kurang', location='json', type=int)\n args = parser.parse_args()\n \n # ambil dari resi json\n cart = Carts.query.get(args['id'])\n # return marshal(cart, Carts.response_field), 200, { 'Content-Type': 'application/json' }\n barang = Stuffs.query.get(cart.resi)\n # return marshal(cart, Carts.response_field), 200, { 'Content-Type': 'application/json' }\n # return get_jwt_claims()['username']\n if cart.username != get_jwt_claims()['username'] or cart == None:\n return { 'status':'NOT_FOUND', 'message': 'Please check again your ID input' }, 200, { 'Content-Type': 'application/json' }\n\n if cart.username == get_jwt_claims()['username']:\n total_barang = barang.jumlah + cart.jumlah\n \n\n if args['jumlah_kurang'] != None:\n calc_barang = barang.jumlah + args['jumlah_kurang']\n calc_cart = cart.jumlah - args['jumlah_kurang']\n\n if args['jumlah_tambah'] != None:\n calc_barang = barang.jumlah - args['jumlah_tambah']\n calc_cart = cart.jumlah + args['jumlah_tambah']\n \n # ==========(sentralize)========= \n if calc_barang < 0:\n return {'status':'NOT_AVAILABLE', 'message':'This item is no longer available right now'}, 200, { 'Content-Type': 'application/json' }\n\n if calc_barang > total_barang:\n return {'status':'INVALID', 'message':\"Too many stuff that you've input. Please check again\"}, 200, { 'Content-Type': 'application/json' }\n\n # Untuk barang\n barang.barang = barang.barang\n barang.image = barang.image\n barang.deskripsi = barang.deskripsi\n barang.jenis = barang.jenis\n barang.harga = barang.harga\n\n # jika sisa 0, maka not available\n if calc_barang == 0:\n barang.status = \"Not Available\"\n barang.jumlah = 0\n \n if barang.status == 'Not Available' and calc_barang > 0:\n barang.status = 'Available'\n barang.jumlah = calc_barang\n\n if barang.jumlah > 0:\n barang.jumlah = calc_barang\n\n db.session.commit()\n\n # untuk cart\n cart.resi = cart.resi\n cart.username = cart.username\n cart.barang = cart.barang\n cart.image = cart.image\n cart.deskripsi = cart.deskripsi\n cart.jenis = cart.jenis\n cart.harga = cart.harga\n cart.status = \"Success\"\n cart.jumlah = calc_cart\n if cart.jumlah == 0:\n db.session.delete(cart) \n db.session.commit()\n\n return marshal(cart, Carts.response_field), 200, { 'Content-Type': 'application/json' }\n return {'status': 'USERS_ONLY', 'message': 'Only for users'}, 404, { 'Content-Type': 'application/json' }\n\n @jwt_required\n def delete(self, id=None):\n if get_jwt_claims()['type'] == 'client' or get_jwt_claims()['type'] == 'admin' or get_jwt_claims()['type'] == \"superadmin\":\n parser = reqparse.RequestParser()\n parser.add_argument('id', location='json', type=int)\n parser.add_argument('username', location='args')\n args = parser.parse_args()\n\n cart_all = Carts.query\n get_all = []\n temp = []\n\n # return cart_all[1].username\n for get_data in cart_all:\n if get_data.id == args['id'] or get_data.id == id:\n if get_data.username == args['username'] or get_data.username == get_jwt_claims()['username']:\n get_all.append(get_data)\n \n # temp.append(get_data)\n \n # return marshal(get_all, Carts.response_field)\n # return get_all[0].jumlah\n if get_all == [] or get_all == None:\n return { 'status':'NOT_FOUND', 'message': 'Stuff in cart not found' }, 200, { 'Content-Type': 'application/json' }\n # return get_all, 200, { 'Content-Type': 'application/json' }\n # return \"OKE\"\n\n # if id == None:\n # cart = Carts.query.get(args['id'])\n # if id != None:\n barang = Stuffs.query.get(get_all[0].resi)\n # return \"OKE\"\n # cart = Carts.query.get(id)\n \n # if get_jwt_claims()['type'] == 'admin':\n # if cart.username == args['username']:\n # total_barang = barang.jumlah + cart.jumlah \n\n # if get_jwt_claims()['type'] == 'client':\n # if cart.username == get_jwt_claims()['username']:\n total_barang = barang.jumlah + get_all[0].jumlah\n\n barang.barang = barang.barang\n barang.image = barang.image\n barang.deskripsi = barang.deskripsi\n barang.jenis = barang.jenis\n barang.harga = barang.harga\n barang.status = barang.status\n barang.jumlah = total_barang\n db.session.commit()\n\n db.session.delete(get_all[0])\n db.session.commit()\n return { 'status':'COMPLETE', 'message': 'Delete complete' }, 200, { 'Content-Type': 'application/json' }\n return {'status': 'USERS_ONLY', 'message': 'Only for users'}, 404, { 'Content-Type': 'application/json' }\n\n\napi.add_resource(CartResource,'', '/')","sub_path":"blueprints/cart/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":12358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"607374404","text":"import json\n\nimport Formatter\nimport Config\nimport Arguments\nimport Logger\n\nargs = Arguments.Parse()\ncfg = Config.Get()\n\n\n@Formatter.Register(\"json\")\ndef json_formatter(components):\n \"\"\" Formats the component list as JSON \"\"\"\n columns = cfg['columns']\n\n newList = [] # New list of only dictionaries with column attributes to marshall\n\n for component in components:\n newComp = {}\n\n for column in columns:\n try:\n newComp[column] = component[column]\n except:\n newComp[column] = cfg['emptyValue']\n\n newList.append(newComp)\n\n result = json.dumps(newList)\n\n # Save the json file\n save_path = args.output_file\n try:\n with open(save_path, \"w\") as file:\n file.write(result)\n\n Logger.Debug(\"Output saved to\", save_path)\n\n return save_path\n\n except:\n Logger.Error(\"Could not save output to\", save_path)\n","sub_path":"Formatter/json_formatter.py","file_name":"json_formatter.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"605887070","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\ntraining_inputs = [2,4,6,10,16,20,40]\nplt.title('hebbian vs storkey')\nplt.plot(training_inputs,[0.571287617168229,0.6526887025160335,0.6635421805624075,0.6921558954119388,0.6877158362111495,0.7671435619141589,0.4410458806117415])\nplt.plot(training_inputs,[0.571287617168229,0.6526887025160335,0.6635421805624075,0.7005426739023187,0.7242229896398619,0.5599407992106561,0.5801677355698076])\nplt.show()\n\nclass Hopfield_Network(object):\n def __init__(self, num_units, total=0, scope='hopfield_network'):\n self.weights = np.zeros([num_units, num_units])\n self.total = total\n\n def update(self, input, type='hebbian'):\n if type == 'hebbian':\n self.hebbian_update(input)\n elif type=='storkey':\n self.storkey_update(input)\n return\n\n def hebbian_update(self, input):\n self.weights += np.outer(input, input) / self.total\n np.fill_diagonal(self.weights, 0)\n\n def storkey_update(self, input):\n self.weights += np.outer(input, input) / self.total\n net = np.dot(self.weights, input)\n pre = np.outer(input, net)\n post = pre.T\n self.weights -= np.add(pre, post) / self.total\n np.fill_diagonal(self.weights, 0)\n\n def activate(self, input):\n converged = False\n while not converged:\n Oldinput = input\n indexes = list(range(0,len(input)))\n random.shuffle(indexes)\n for i in indexes:\n if input[i] > 0:\n sum = 0\n for w in range(0,len(self.weights)):\n sum += self.weights[w][i]\n if sum > 0:\n input[i] = 1\n else:\n input[i] = 0\n if np.allclose(Oldinput, input):\n converged = True\n return input\n\ndef compare_result(result, ones, fives, i):\n lowest_ones_error = np.inf\n lowest_fives_error = np.inf\n for index in range(0,i):\n ones_error = np.linalg.norm(ones[index]-result)\n fives_error = np.linalg.norm(fives[index]-result)\n if lowest_ones_error > ones_error:\n lowest_ones_error = ones_error\n if lowest_fives_error > fives_error:\n lowest_fives_error = fives_error\n if (lowest_ones_error > lowest_fives_error):\n return 5\n elif (lowest_fives_error > lowest_ones_error):\n return 1\n else:\n return 0\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\ntrX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\n\nones = trY[:, 1]\nfives = trY[:, 5]\nones_input = [trX[i] for i in range(0,len(trX)) if ones[i] != 0]\nfives_input = [trX[i] for i in range(0,len(trX)) if fives[i] != 0]\n\nt_ones = teY[:, 1]\nt_fives = teY[:, 5]\nt_output_ones_fives = np.vstack((t_ones,t_fives)).T\nt_output_ones_fives = [t_output_ones_fives[i] for i in range(0,len(t_output_ones_fives)) if t_fives[i] != 0 or t_ones[i] != 0]\nt_input_ones_fives = [teX[i] for i in range(0,len(teX)) if t_ones[i] != 0 or t_fives[i] != 0]\n\ndef hopfield_test(training_type='hebbian'):\n training_inputs = [1,2,3,5,8,10,20]\n results = []\n for n in training_inputs:\n hopfield = Hopfield_Network(784, n*2)\n culmulative_accuracy = 0.\n order = list(range(0,len(t_input_ones_fives)))\n for i in range(0,n):\n hopfield.update(ones_input[i], training_type)\n hopfield.update(fives_input[i], training_type)\n for o in order:\n result = hopfield.activate(t_input_ones_fives[o])\n answer = 5\n if t_output_ones_fives[o][0] == 1:\n answer = 1\n guess = compare_result(result, ones_input, fives_input, n)\n if guess == answer:\n culmulative_accuracy += 1\n accuracy = culmulative_accuracy / len(order)\n results.append(accuracy)\n print(training_type,': inputs: ', n*2, ' accuracy: ', accuracy)\n return results\n\n\nrandom.shuffle(ones_input)\nrandom.shuffle(fives_input)\n\nheb_results = hopfield_test('hebbian')\nstorkey_results = hopfield_test('storkey')\ntraining_inputs = [1,2,3,5,8,10,20]\nplt.title('hebbian vs storkey')\nplt.plot(training_inputs,heb_results)\nplt.plot(training_inputs,storkey_results)\nplt.show()\n","sub_path":"Assignment3-Robin-Naz-100998216-100809967/question1/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"577726643","text":"\"\"\"\nCopyright (C) 2017 Open Source Robotics Foundation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport math\n\nfrom geometry.circle import Circle\nfrom geometry.point import Point\n# Avoid module circular dependencies\nimport geometry.line_segment\n\n\nclass Arc(object):\n\n def __init__(self, start_point, theta, radius, angular_length):\n \"\"\"\n start_point: The point in the circumference where the arc starts\n theta: The heading of the tangent in start_point\n radius: The radius of the circular arc\n angular_length: The angle formed between then center -> start point\n and center -> end point. If the angular_length is > 0 the arc direction\n is considered counter-clockwise\n \"\"\"\n self._start_point = start_point\n self._theta = theta\n self._radius = radius\n self._angular_length = angular_length\n self._end_point = self._compute_point_at(angular_length)\n\n def start_point(self):\n return self._start_point\n\n def end_point(self):\n return self._end_point\n\n def start_heading(self):\n return self._theta\n\n def end_heading(self):\n return self._theta + self._angular_length\n\n def theta(self):\n return self._theta\n\n def radius(self):\n return self._radius\n\n def angular_length(self):\n return self._angular_length\n\n def center_point(self):\n \"\"\"\n Answers the point that is the center of the circular arc\n \"\"\"\n theta_in_radians = math.radians(self._theta)\n direction_multiplier = math.copysign(1, self._angular_length)\n vector = Point(-self._radius * direction_multiplier * math.sin(theta_in_radians),\n self._radius * direction_multiplier * math.cos(theta_in_radians))\n return self._start_point + vector\n\n def length(self):\n \"\"\"\n The length of the perimeter of the arc\n \"\"\"\n return abs(math.pi * self._radius * self._angular_length / 180.0)\n\n def find_intersection(self, other):\n # TODO: Remove this switch statement and make a proper polymorphic delegation\n if isinstance(other, Arc):\n return self._find_arc_intersection(other)\n elif isinstance(other, geometry.line_segment.LineSegment):\n return other._find_arc_intersection(self)\n else:\n raise ValueError(\"Intersection between {0} and {1} not supported\".format(self, other))\n\n def _find_arc_intersection(self, other):\n circle1 = Circle(self.center_point(), self.radius())\n circle2 = Circle(other.center_point(), other.radius())\n candidates = circle1.intersection(circle2)\n return filter(lambda point: self.includes_point(point) and other.includes_point(point), candidates)\n\n def includes_point(self, point, buffer=1e-7):\n \"\"\"\n Answer if a given point is part of the arc's perimeter. Allow to\n parametrize with a given buffer to contemplate rounding errors\n \"\"\"\n center = self.center_point()\n center_start = self._start_point - center\n center_point = point - center\n if abs(center_point.norm() - self._radius) > buffer:\n return False\n angle_between_vectors = center_start.angle(center_point)\n if angle_between_vectors == 0:\n return True\n angular_delta = abs(angle_between_vectors) - abs(self._angular_length)\n return (angle_between_vectors < 0) == (self._angular_length < 0) and angular_delta < buffer\n\n def extend(self, distance):\n \"\"\"\n Extend the arc by a given distance, following the arc's direction\n \"\"\"\n angular_delta = 180 * distance / (math.pi * self._radius)\n return Arc(self._start_point, self._theta, self._radius, self._angular_length + angular_delta)\n\n def point_at_offset(self, offset):\n \"\"\"\n Returns a point in the arc taken as an offset from the start of the arc.\n \"\"\"\n if offset > self.length():\n raise ValueError(\"Offset ({0})is greater than arc length ({1})\".format(offset, self.length()))\n angular_offset = math.copysign(offset, self._angular_length) * 180 / (math.pi * self._radius)\n return self._compute_point_at(angular_offset)\n\n def offset_for_point(self, point):\n \"\"\"\n Answer how far is a given point from the start of the arc, measured as\n a distance on the arc's perimeter.\n \"\"\"\n angle = self._angular_offset_for_point(point)\n return abs(math.pi * self._radius * angle / 180.0)\n\n def point_at_linear_offset(self, reference_point, offset):\n circle1 = Circle(self.center_point(), self.radius())\n circle2 = Circle(reference_point, abs(offset))\n intersections = circle1.intersection(circle2)\n candidates = filter(lambda point: self.includes_point(point), intersections)\n\n if not candidates:\n return None\n elif len(candidates) == 1:\n return candidates[0]\n else:\n candidates = sorted(candidates,\n key=lambda point: self.offset_for_point(point))\n if offset < 0:\n return candidates[0]\n else:\n return candidates[1]\n\n def split_into(self, pairs):\n arcs = []\n for start, end in pairs:\n start_angular_offset = self._angular_offset_for_point(start)\n end_angular_offset = self._angular_offset_for_point(end)\n start_heading = self._theta + start_angular_offset\n arc = Arc(start, start_heading, self._radius, end_angular_offset - start_angular_offset)\n arcs.append(arc)\n return arcs\n\n def can_be_merged_with(self, other):\n return self.__class__ is other.__class__ and \\\n self.radius() == other.radius() and \\\n self.end_heading() == other.start_heading() and \\\n self.end_point().almost_equal_to(other.start_point(), 5) and \\\n self.center_point().almost_equal_to(other.center_point(), 5)\n\n def merge(self, other):\n return Arc(self.start_point(),\n self.theta(),\n self.radius(),\n self.angular_length() + other.angular_length())\n\n def line_interpolation_points(self, step=1):\n \"\"\"\n Return a collection of points used to interpolate the arc.\n \"\"\"\n points = []\n length = self.length()\n last_point = length - step\n traversed = 0\n while traversed <= last_point:\n points.append(self.point_at_offset(traversed))\n traversed += step\n if length - traversed > step / 2:\n points.append(self.point_at_offset(traversed))\n points.append(self.end_point().clone())\n return points\n\n def heading_at_offset(self, offset):\n \"\"\"\n Answer the heading of a point at a given offset.\n \"\"\"\n if offset > self.length():\n raise ValueError(\"Offset ({0}) is greater than segment length ({1})\".format(offset, self.length()))\n angular_offset = math.copysign(offset, self._angular_length) * 180 / (math.pi * self._radius)\n return self._theta + angular_offset\n\n def _compute_point_at(self, angular_offset):\n \"\"\"\n Great explanation on some of the math here:\n http://math.stackexchange.com/questions/275201/how-to-find-an-end-point-of-an-arc-given-another-end-point-radius-and-arc-dire\n \"\"\"\n theta_in_radians = math.radians(self._theta)\n angular_length_in_radians = math.radians(angular_offset)\n direction_multiplier = math.copysign(1, angular_offset)\n start_end_angle = theta_in_radians + angular_length_in_radians\n start_end_vector = Point(self._radius * direction_multiplier * (math.sin(start_end_angle) - math.sin(theta_in_radians)),\n self._radius * direction_multiplier * (math.cos(theta_in_radians) - math.cos(start_end_angle)))\n return self._start_point + start_end_vector\n\n def _angular_offset_for_point(self, point):\n if not self.includes_point(point):\n raise ValueError(\"{0} is not included in arc {1}\".format(point, self))\n center = self.center_point()\n center_start = self._start_point - center\n center_point = point - center\n return center_start.angle(center_point)\n\n def is_valid_path_connection(self):\n return self.radius() > 4.0\n\n def __eq__(self, other):\n return self._start_point == other._start_point and \\\n self._theta == other._theta and \\\n self._radius == other._radius and \\\n self._angular_length == other._angular_length\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash((self._start_point, self._theta, self._radius, self._angular_length))\n\n def __repr__(self):\n return \"Arc({0}, {1}, {2}, {3})\".format(self._start_point, self._theta, self._radius, self._angular_length)\n","sub_path":"terminus/geometry/arc.py","file_name":"arc.py","file_ext":"py","file_size_in_byte":9509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"121371568","text":"# -*- coding: utf-8 -*-\nfrom django import forms\n\nDEPARTMENTS = (\n\t('', 'Departamento'),\n\t('atioquia', 'Antioquia',), \n\t('amazonas', 'Amazonas',)\n)\n\nTOWNS = (\n\t('', 'Municipio'),\n\t('medellin', 'Medellín',),\n\t('cali', 'Cali',),\n\t('bogota', 'Bogotá',)\n)\n\n\nclass ActivityForm(forms.Form):\n\tname = forms.CharField(label=\"Nombre\", required=True)\n\t\n\taddress = forms.CharField(label=\"Dirección\", required=False)\n\t\n\timg = forms.ImageField(label=\"Imagen\", required=False)\n\t\n\tdescription = forms.CharField(label=\"Descripción\", required=True, \n\t\twidget=forms.Textarea)\n\t\t\n\tprice = forms.IntegerField(label=\"Precio\", required=False)\n\t\n\ttitle = forms.CharField(label=\"Título\", required=False)\n\t\n\tdepartment = forms.ChoiceField(label=\"Departamento\", required=True, \n\t\tchoices=DEPARTMENTS)\n\t\t\n\ttown = forms.ChoiceField(label=\"Municipio\", required=True, \n\t\tchoices=TOWNS)\n\t\t\n\tstart = forms.DateField(label=\"Fecha Inicio\", required=True,\n\t\twidget=forms.DateInput(attrs={'placeholder': '(mm/dd/aaaa)', 'type': 'date', 'class': 'big-input'}))\n\t#poner clase en los formularios python. \n\t\n\tend = forms.DateField(label=\"Fecha Fin\", required=True)\n","sub_path":"backend/forms/activity.py","file_name":"activity.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"311161318","text":"a=b=c=10\r\nd=a/10\r\ne=b*50\r\nf=c+60\r\nprint(d,e,f)\r\n\r\nstr=\"haris\"\r\nprint(str[:2]+\"G\"+str[3:])\r\n\r\nr=10;\r\nl=20.5;\r\n\r\nprint(int(l));\r\nprint(float(r));","sub_path":"second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"472573491","text":"import os\nimport pytorch_lightning as pl\n\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as transforms\n\nfrom dataset import FacialKeypointsDataset\nfrom transforms import Rescale, RandomCrop, Normalize, ToTensor\n\nclass FacialKeypointsDatamodule(pl.LightningDataModule):\n def __init__(self,\n train_csv_file = '/data/training_frames_keypoints.csv',\n test_csv_file = './data/test_frames_keypoints.csv',\n root_dir = './data/',\n batch_size = 32,\n num_workers = 0\n ):\n \"\"\"Constructor\n\n Args:\n train_csv_file: Path to the csv file with annotations for train data.\n test_csv_file: Path to the csv file with annotations for test data.\n root_dir: Directory with all the images.\n batch_size: Batch size\n \"\"\"\n super().__init__()\n\n self.train_csv_file = train_csv_file\n self.test_csv_file = test_csv_file\n self.root_dir = root_dir\n self.batch_size = batch_size\n self.num_workers = num_workers\n\n def train_dataloader(self):\n transformations = transforms.Compose([\n Rescale(250),\n RandomCrop(224),\n Normalize(),\n ToTensor()\n ])\n\n train_images_path = os.path.join(self.root_dir, 'training')\n\n train_dataset = FacialKeypointsDataset(\n self.train_csv_file,\n train_images_path,\n transform=transformations,\n )\n\n data_loader = DataLoader(train_dataset,\n batch_size = self.batch_size,\n shuffle = True,\n num_workers = self.num_workers)\n \n return data_loader\n\n def test_dataloader(self):\n transformations = transforms.Compose([\n Rescale(250),\n RandomCrop(224),\n Normalize(),\n ToTensor()\n ])\n\n train_images_path = os.path.join(self.root_dir, 'test')\n\n train_dataset = FacialKeypointsDataset(\n self.test_csv_file,\n train_images_path,\n transform=transformations\n )\n\n data_loader = DataLoader(train_dataset,\n batch_size = self.batch_size,\n shuffle = True,\n num_workers = self.num_workers)\n \n return data_loader\n","sub_path":"datamodule.py","file_name":"datamodule.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"142229504","text":"import tensorflow as tf\r\nimport numpy as np\r\n\r\ndef create(input,bn=False):\r\n tf.summary.image('input',input,1)\r\n if bn:\r\n input=tf.cast(input,tf.float32)*(1./255)-0.5\r\n net_1=block1(input)\r\n net_2=block2(net_1)\r\n\r\n return net_2\r\n\r\n\r\ndef block1(input):\r\n with tf.variable_scope('block1'):\r\n conv_1=conv(input,name='conv_1',kernel_size=5,filters=24)\r\n pool_1=pool(conv_1,name='pool_1',kernel_size=2,strides=2)\r\n conv_2=conv(pool_1,name='conv_2',kernel_size=3,filters=48)\r\n pool_2=pool(conv_2,name='pool_2',kernel_size=2,strides=2)\r\n conv_3=conv(pool_2,name='conv_3',kernel_size=3,filters=24)\r\n conv_4=conv(conv_3,name='conv_4',kernel_size=3,filters=12)\r\n return conv_4\r\n\r\ndef block2(input):\r\n # this block contains 4 dilated convs\r\n with tf.variable_scope('block2'):\r\n conv_dia_1=conv_dila(input,'cov_dia_1',3,12,rate=2)\r\n conv_dia_2 = conv_dila(input, 'cov_dia_2', 3, 10, rate=4)\r\n conv_dia_3 = conv_dila(input, 'cov_dia_3', 3, 8, rate=6)\r\n conv_dia_4 = conv_dila(input, 'cov_dia_4', 3, 6, rate=8)\r\n res=tf.concat([conv_dia_1,conv_dia_2,conv_dia_3,conv_dia_4],axis=3)\r\n output=conv(res,'con_fusd',1,1)\r\n return output\r\n\r\n\r\ndef conv(input,name,kernel_size,filters,strides=1,activation=tf.nn.relu):\r\n input_shape=input.get_shape()[-1].value\r\n\r\n with tf.variable_scope(name):\r\n weight=tf.Variable(tf.truncated_normal([kernel_size,kernel_size,input_shape,filters],\r\n stddev=0.01),dtype=tf.float32,name='w')\r\n bias = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[filters]), dtype=tf.float32, name='b')\r\n conv=tf.nn.conv2d(input,weight,strides=[1,strides,strides,1],padding='SAME')\r\n output=activation(tf.nn.bias_add(conv,bias))\r\n return output\r\n\r\n\r\n\r\ndef conv_dila(input,name,kernel_size,filters,rate,strides=1,activation=tf.nn.relu):\r\n input_shape=input.get_shape()[-1].value\r\n with tf.variable_scope(name):\r\n weight = tf.Variable(tf.truncated_normal([kernel_size, kernel_size, input_shape, filters],\r\n stddev=0.01), dtype=tf.float32, name='w')\r\n bias=tf.Variable(tf.constant(0.0,dtype=tf.float32,shape=[filters]),dtype=tf.float32,name='b')\r\n conv=tf.nn.atrous_conv2d(input,weight,rate=rate,padding='SAME')\r\n output=activation(tf.nn.bias_add(conv,bias))\r\n\r\n return output\r\n\r\n\r\ndef pool(input,name,kernel_size,strides):\r\n with tf.variable_scope(name):\r\n output=tf.nn.max_pool(input,ksize=[1,kernel_size,kernel_size,1],\r\n strides=[1,strides,strides,1],\r\n padding='SAME')\r\n return output","sub_path":"RHNet.py","file_name":"RHNet.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"248348727","text":"import sys\nimport sqlite3\nfrom PyQt5 import Qt\nfrom PyQt5.QtGui import QImage, QPalette, QBrush\nfrom PyQt5.QtWidgets import QWidget, QLineEdit, QPushButton, QApplication, QRadioButton, QButtonGroup, QSpacerItem\nfrom PyQt5.QtCore import QSize, QRect\nfrom PyQt5 import QtWidgets, QtCore\nfrom Classes import BOX, ITEM, split, PushButtonRight, ACCEPTDELETE\n\ncon = sqlite3.connect(\"KilterAndBox.db\")\ncur = con.cursor()\n\ndistanceBetweenButtons = 10\nbuttonsHeight = 30\nbuttonsWidth = 80\n\ncon = sqlite3.connect(\"testbox.db\")\ncur = con.cursor()\n\n\nclass KilterAndBox(QWidget):\n def __init__(self):\n super().__init__()\n self.buttons = []\n self.upBox = []\n self.currentBox = 0\n self.currentListStuff = []\n self.idTable = []\n self.findFlag = False\n oImage = QImage(\"BoxTexture.jpg\")\n sImage = oImage.scaled(QSize(300, 200))\n palette = QPalette()\n palette.setBrush(10, QBrush(sImage))\n self.setPalette(palette)\n\n self.initUI()\n self.drawStuff()\n\n def initUI(self):\n self.setGeometry(200, 200, 500, 500)\n self.setMinimumWidth(260)\n self.setMinimumHeight(245)\n self.setWindowTitle('KilterAndBox')\n\n self.fullBackButton = QPushButton(self)\n self.fullBackButton.setVisible(False)\n self.fullBackButton.move(distanceBetweenButtons, distanceBetweenButtons)\n self.fullBackButton.resize(buttonsWidth, buttonsHeight)\n self.fullBackButton.setText(\"на гла��ную\")\n self.fullBackButton.clicked.connect(self.fullBack)\n self.fullBackButton.setStyleSheet('background: rgb(245, 222, 179);') # предмет\n self.fullBackButton.setStyleSheet('background: rgb(229, 184, 135);') # кнопка или коробка\n\n self.backButton = QPushButton(self)\n self.backButton.setVisible(False)\n self.backButton.move(distanceBetweenButtons, buttonsHeight + distanceBetweenButtons * 2)\n self.backButton.resize(buttonsWidth, buttonsHeight)\n self.backButton.setText(\"назад\")\n self.backButton.clicked.connect(self.back)\n self.backButton.setStyleSheet('background: rgb(229, 184, 135);')\n\n self.addBoxButton = QPushButton(self)\n self.addBoxButton.move(distanceBetweenButtons, distanceBetweenButtons)\n self.addBoxButton.resize(buttonsWidth, buttonsHeight)\n self.addBoxButton.setText(\"нов.коробка\")\n self.addBoxButton.clicked.connect(self.addBox)\n self.addBoxButton.setStyleSheet('background: rgb(229, 184, 135);')\n\n self.addItemButton = QPushButton(self)\n self.addItemButton.move(distanceBetweenButtons, buttonsHeight + distanceBetweenButtons * 2)\n self.addItemButton.resize(buttonsWidth, buttonsHeight)\n self.addItemButton.setText(\"нов.предмет\")\n self.addItemButton.clicked.connect(self.addItem)\n self.addItemButton.setStyleSheet('background: rgb(229, 184, 135);')\n\n self.openRadioButton = QRadioButton(self)\n self.openRadioButton.move(buttonsWidth * 1 + distanceBetweenButtons * 2, distanceBetweenButtons)\n self.openRadioButton.resize(buttonsWidth, buttonsHeight)\n self.openRadioButton.setText(\"делать\")\n\n self.deleteRadioButton = QRadioButton(self)\n self.deleteRadioButton.move(buttonsWidth * 1 + distanceBetweenButtons * 2,\n buttonsHeight + distanceBetweenButtons * 2)\n self.deleteRadioButton.resize(buttonsWidth, buttonsHeight)\n self.deleteRadioButton.setText(\"удалить\")\n\n self.openDeleteButtonGroup = QButtonGroup()\n self.openDeleteButtonGroup.addButton(self.openRadioButton)\n self.openDeleteButtonGroup.addButton(self.deleteRadioButton)\n self.openRadioButton.toggle()\n\n self.cancel = QPushButton(self)\n self.cancel.setVisible(False)\n self.cancel.move(distanceBetweenButtons, buttonsHeight * 2 + distanceBetweenButtons * 3)\n self.cancel.resize(buttonsWidth, buttonsHeight)\n self.cancel.setText(\"отмена\")\n self.cancel.clicked.connect(self.dontFind)\n self.cancel.setStyleSheet('background: rgb(229, 184, 135);')\n\n self.findButton = QPushButton(self)\n self.findButton.move(distanceBetweenButtons, buttonsHeight * 2 + distanceBetweenButtons * 3)\n self.findButton.resize(buttonsWidth, buttonsHeight)\n self.findButton.setText(\"найти\")\n self.findButton.clicked.connect(self.findStuff)\n self.findButton.setStyleSheet('background: rgb(240, 240, 240);;')\n\n self.findLineEdit = QLineEdit(self)\n self.findLineEdit.move(buttonsWidth * 1 + distanceBetweenButtons * 2,\n buttonsHeight * 2 + distanceBetweenButtons * 3)\n self.findLineEdit.resize(self.size().width() - (buttonsWidth * 1 + distanceBetweenButtons * 3), buttonsHeight)\n self.findLineEdit.setStyleSheet('background: rgb(240, 240, 240);;')\n\n self.Glayout = Qt.QGridLayout(self)\n self.Glayout.setSpacing(distanceBetweenButtons)\n\n self.but = QPushButton()\n self.but.resize(50, 50)\n\n self.Widget = QWidget(self)\n self.Widget.setGeometry(distanceBetweenButtons, distanceBetweenButtons * 4 + buttonsHeight * 3,\n self.size().width() - distanceBetweenButtons * 2,\n self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4))\n self.Widget.setStyleSheet('background: rgb(240, 240, 240);;')\n\n self.WidgetScroll = QWidget(self)\n self.WidgetScroll.setLayout(self.Glayout)\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2 - 10,\n self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4))\n\n self.Scroll = Qt.QScrollArea(self.Widget)\n self.Scroll.setWidget(self.WidgetScroll)\n self.Scroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2,\n self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4))\n self.Scroll.setStyleSheet('background: rgb(240, 240, 240);;')\n\n def resizeEvent(self, event):\n self.findLineEdit.resize(self.size().width() - (buttonsWidth * 1 + distanceBetweenButtons * 3), buttonsHeight)\n self.Widget.setGeometry(distanceBetweenButtons, distanceBetweenButtons * 4 + buttonsHeight * 3,\n self.size().width() - distanceBetweenButtons * 2,\n self.size().height() - (distanceBetweenButtons * 5 + buttonsHeight * 3))\n self.Scroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2,\n self.size().height() - (distanceBetweenButtons * 5 + buttonsHeight * 3))\n\n hight = 80 * self.highItem + 10 * (self.highItem + 1)\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2,\n hight)\n if hight < self.size().height() - (distanceBetweenButtons * 5 + buttonsHeight * 3):\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2 - 19,\n self.size().height() - (distanceBetweenButtons * 5 + buttonsHeight * 3))\n self.moveStuff()\n\n def drawStuff(self):\n while self.Glayout.count():\n child = self.Glayout.takeAt(0)\n if child.widget():\n child.widget().close()\n\n if self.currentBox == -1 and self.windowTitle() == \"архив\" or len(self.upBox) >= 2 and self.upBox[1] == [\n -1, \"архив\"]:\n self.isInTrash = True\n else:\n self.isInTrash = False\n\n if self.windowTitle() == \"архив\":\n boxId = cur.execute(\"SELECT id FROM stuff WHERE isBox IS 1\")\n boxExist = [0]\n for i in boxId:\n boxExist.append(*i)\n stuff = cur.execute(\n f\"SELECT id, name, isBox, amount, inBox FROM stuff WHERE inBox NOT IN ({(', ').join(list(map(str, boxExist)))})\")\n self.currentListStuff = []\n for i in stuff:\n self.currentListStuff.append(i)\n else:\n stuff = cur.execute(\"SELECT id, name, isBox, amount, inBox FROM stuff WHERE inBox IS ?\", (self.currentBox,))\n self.currentListStuff = []\n for i in stuff:\n self.currentListStuff.append(i)\n\n if not self.upBox:\n self.currentListStuff.append([-1, \"архив\", 1])\n\n if self.currentListStuff:\n self.widthItem = (self.size().width() - distanceBetweenButtons * 2 + 15) // 95\n if self.widthItem > len(self.currentListStuff):\n self.widthItem = len(self.currentListStuff)\n self.highItem = int((len(self.currentListStuff) / self.widthItem) + 0.99999)\n self.idTable = split(self.currentListStuff, self.widthItem)\n for i in range(self.highItem):\n for j in range(self.widthItem):\n if self.idTable[i][j] != 0:\n button = PushButtonRight(self.idTable[i][j][1])\n button.setFixedSize(80, 80)\n if self.idTable[i][j][1] == \"архив\" and self.idTable[i][j][0] == -1:\n button.setFixedSize(80, 80)\n button.setStyleSheet('background: rgb(191, 191, 191);;')\n button.left_click.connect(self.leftClickBox)\n button.right_click.connect(self.rightClickBox)\n elif self.idTable[i][j][2]:\n button.setStyleSheet('background: rgb(229, 184, 135);;')\n button.left_click.connect(self.leftClickBox)\n button.right_click.connect(self.rightClickBox)\n else:\n button.setStyleSheet('background: rgb(245, 222, 179);')\n button.left_click.connect(self.leftClickItem)\n button.right_click.connect(self.rightClickItem)\n self.Glayout.addWidget(button, i, j)\n spacerItem = QtWidgets.QSpacerItem(9, 44, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.Glayout.addItem(spacerItem, 0, self.widthItem, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.Glayout.addItem(spacerItem1, self.highItem, 0, 1, 1)\n else:\n self.highItem = 0\n\n def moveStuff(self):\n while self.Glayout.count():\n child = self.Glayout.takeAt(0)\n if child.widget():\n child.widget().close()\n\n if self.currentListStuff:\n self.widthItem = (self.size().width() - distanceBetweenButtons * 2 + 15) // 95\n if self.widthItem > len(self.currentListStuff):\n self.widthItem = len(self.currentListStuff)\n self.highItem = int((len(self.currentListStuff) / self.widthItem) + 0.99999)\n self.idTable = split(self.currentListStuff, self.widthItem)\n for i in range(self.highItem):\n for j in range(self.widthItem):\n if self.idTable[i][j] != 0:\n button = PushButtonRight(self.idTable[i][j][1])\n button.setFixedSize(80, 80)\n if self.idTable[i][j][1] == \"архив\" and self.idTable[i][j][0] == -1:\n button.setFixedSize(80, 80)\n button.setStyleSheet('background: rgb(191, 191, 191);;')\n button.left_click.connect(self.leftClickBox)\n button.right_click.connect(self.rightClickBox)\n elif self.idTable[i][j][2]:\n button.setStyleSheet('background: rgb(229, 184, 135);;')\n button.left_click.connect(self.leftClickBox)\n button.right_click.connect(self.rightClickBox)\n else:\n button.setStyleSheet('background: rgb(245, 222, 179);')\n button.left_click.connect(self.leftClickItem)\n button.right_click.connect(self.rightClickItem)\n self.Glayout.addWidget(button, i, j)\n spacerItem = QtWidgets.QSpacerItem(9, 44, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.Glayout.addItem(spacerItem, 0, self.widthItem, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.Glayout.addItem(spacerItem1, self.highItem, 0, 1, 1)\n\n def leftClickBox(self):\n sender = self.sender()\n index = self.Glayout.indexOf(sender)\n pos = self.Glayout.getItemPosition(index)\n if self.findFlag:\n print(self.idTable)\n print(self.idTable[pos[0]])\n print(self.idTable[pos[0]][pos[1]])\n self.currentBox = self.idTable[pos[0]][pos[1]][4]\n self.findPath(self.currentBox)\n self.cancel.setVisible(False)\n self.findButton.setVisible(True)\n self.findFlag = False\n else:\n if self.openDeleteButtonGroup.checkedId() == -2:\n self.upBox.append([self.currentBox, self.windowTitle()])\n self.setWindowTitle(self.idTable[pos[0]][pos[1]][1])\n self.currentBox = self.idTable[pos[0]][pos[1]][0]\n self.drawUI()\n self.drawStuff()\n hight = 80 * self.highItem + 10 * (self.highItem + 1)\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2,\n hight)\n if hight < self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4):\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2 - 19,\n self.size().height() - (\n distanceBetweenButtons * 6 + buttonsHeight * 4))\n else:\n self.delete = ACCEPTDELETE(self.idTable[pos[0]][pos[1]][0], self.idTable[pos[0]][pos[1]][1],\n self.isInTrash)\n self.delete.show()\n\n def leftClickItem(self):\n sender = self.sender()\n index = self.Glayout.indexOf(sender)\n pos = self.Glayout.getItemPosition(index)\n if self.findFlag:\n self.currentBox = self.idTable[pos[0]][pos[1]][4]\n self.findPath(self.currentBox)\n self.cancel.setVisible(False)\n self.findButton.setVisible(True)\n self.findFlag = False\n else:\n if self.openDeleteButtonGroup.checkedId() == -2:\n self.addbox = ITEM(self.currentBox, True, self.idTable[pos[0]][pos[1]][0],\n [self.idTable[pos[0]][pos[1]][1], self.idTable[pos[0]][pos[1]][3]])\n self.addbox.show()\n else:\n self.delete = ACCEPTDELETE(self.idTable[pos[0]][pos[1]][0], self.idTable[pos[0]][pos[1]][1],\n self.isInTrash)\n self.delete.show()\n\n def rightClickBox(self):\n sender = self.sender()\n index = self.Glayout.indexOf(sender)\n pos = self.Glayout.getItemPosition(index)\n self.addbox = BOX(self.currentBox, self.idTable[pos[0]][pos[1]][0], self.idTable[pos[0]][pos[1]][1], True)\n self.addbox.show()\n\n def rightClickItem(self):\n sender = self.sender()\n index = self.Glayout.indexOf(sender)\n pos = self.Glayout.getItemPosition(index)\n self.addbox = ITEM(self.currentBox, False, self.idTable[pos[0]][pos[1]][0],\n [self.idTable[pos[0]][pos[1]][1], self.idTable[pos[0]][pos[1]][3]], True)\n self.addbox.show()\n\n def drawUI(self):\n if self.upBox:\n self.backButton.setVisible(True)\n self.fullBackButton.setVisible(True)\n self.addBoxButton.move(buttonsWidth + distanceBetweenButtons * 2, distanceBetweenButtons)\n self.addItemButton.move(buttonsWidth + distanceBetweenButtons * 2,\n buttonsHeight + distanceBetweenButtons * 2)\n self.openRadioButton.move(buttonsWidth * 2 + distanceBetweenButtons * 3, distanceBetweenButtons)\n self.deleteRadioButton.move(buttonsWidth * 2 + distanceBetweenButtons * 3,\n buttonsHeight + distanceBetweenButtons * 2)\n else:\n self.backButton.setVisible(False)\n self.fullBackButton.setVisible(False)\n self.addBoxButton.move(distanceBetweenButtons, distanceBetweenButtons)\n self.addItemButton.move(distanceBetweenButtons, buttonsHeight + distanceBetweenButtons * 2)\n self.openRadioButton.move(buttonsWidth * 1 + distanceBetweenButtons * 2, distanceBetweenButtons)\n self.deleteRadioButton.move(buttonsWidth * 1 + distanceBetweenButtons * 2,\n buttonsHeight + distanceBetweenButtons * 2)\n\n def back(self):\n self.setWindowTitle(self.upBox[-1][1])\n self.currentBox = self.upBox[-1][0]\n self.upBox.pop()\n self.drawStuff()\n self.drawUI()\n hight = 80 * self.highItem + 10 * (self.highItem + 1)\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2,\n hight)\n if hight < self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4):\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2 - 19,\n self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4))\n print(self.upBox)\n\n def fullBack(self):\n self.setWindowTitle(\"KilterAndBox\")\n self.currentBox = 0\n self.upBox.clear()\n self.drawStuff()\n self.drawUI()\n hight = 80 * self.highItem + 10 * (self.highItem + 1)\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2,\n hight)\n if hight < self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4):\n self.WidgetScroll.setGeometry(0, 0, self.size().width() - distanceBetweenButtons * 2 - 19,\n self.size().height() - (distanceBetweenButtons * 6 + buttonsHeight * 4))\n\n def addBox(self):\n self.addbox = BOX(self.currentBox)\n self.addbox.show()\n\n def addItem(self):\n self.additem = ITEM(self.currentBox, False)\n self.additem.show()\n\n def findStuff(self):\n while self.Glayout.count():\n child = self.Glayout.takeAt(0)\n if child.widget():\n child.widget().close()\n\n self.findFlag = True\n self.cancel.setVisible(True)\n self.findButton.setVisible(False)\n\n request = self.findLineEdit.text()\n allStuff = cur.execute(\"SELECT id, name, isBox, amount, inBox FROM stuff\")\n self.currentListStuff = []\n for i in allStuff:\n if request in i[1]:\n self.currentListStuff.append(i)\n\n if self.currentListStuff:\n print(self.idTable)\n self.widthItem = (self.size().width() - distanceBetweenButtons * 2 + 15) // 95\n if self.widthItem > len(self.currentListStuff):\n self.widthItem = len(self.currentListStuff)\n self.highItem = int((len(self.currentListStuff) / self.widthItem) + 0.99999)\n print(self.idTable)\n self.idTable = split(self.currentListStuff, self.widthItem)\n print(self.idTable)\n for i in range(self.highItem):\n for j in range(self.widthItem):\n if self.idTable[i][j] != 0:\n button = PushButtonRight(self.idTable[i][j][1])\n button.setFixedSize(80, 80)\n if self.idTable[i][j][1] == \"архив\" and self.idTable[i][j][0] == -1:\n button.setFixedSize(80, 80)\n button.setStyleSheet('background: rgb(191, 191, 191);;')\n button.left_click.connect(self.leftClickBox)\n button.right_click.connect(self.rightClickBox)\n elif self.idTable[i][j][2]:\n button.setStyleSheet('background: rgb(229, 184, 135);;')\n button.left_click.connect(self.leftClickBox)\n button.right_click.connect(self.rightClickBox)\n else:\n button.setStyleSheet('background: rgb(245, 222, 179);')\n button.left_click.connect(self.leftClickItem)\n button.right_click.connect(self.rightClickItem)\n self.Glayout.addWidget(button, i, j)\n spacerItem = QtWidgets.QSpacerItem(9, 44, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.Glayout.addItem(spacerItem, 0, self.widthItem, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.Glayout.addItem(spacerItem1, self.highItem, 0, 1, 1)\n else:\n self.highItem = 0\n\n def dontFind(self):\n self.cancel.setVisible(False)\n self.findButton.setVisible(True)\n self.drawStuff()\n self.findFlag = False\n\n def findPath(self, inBox):\n way = []\n self.currentBox = inBox\n if inBox != 0:\n box = cur.execute(\"SELECT id, name, inBox FROM stuff Where id = ?\", (inBox,))\n data = box.fetchone()\n self.setWindowTitle(data[1])\n needBox = data[2]\n while needBox != 0:\n box = cur.execute(\"SELECT id, name, inBox FROM stuff Where id = ?\", (needBox,))\n data = box.fetchone()\n way.append([data[0], data[1]])\n needBox = data[2]\n if self.currentBox != 0:\n way.append([0, \"KilterAndBox\"])\n way.reverse()\n self.upBox = way\n print(self.upBox)\n self.drawStuff()\n self.drawUI()\n else:\n self.setWindowTitle('KilterAndBox')\n self.upBox = []\n self.drawStuff()\n self.drawUI()\n\n def keyPressEvent(self, event):\n self.drawStuff()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = KilterAndBox()\n ex.show()\n sys.exit(app.exec())\n","sub_path":"KilterAndBox2.0.py","file_name":"KilterAndBox2.0.py","file_ext":"py","file_size_in_byte":23118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"336007663","text":"import json, cherrypy\nfrom authcontroller import require\n\nclass ServerRcon:\n\tdef __init__(self, webserver, updater):\n\t\tself.webserver = webserver\n\t\tself.updater = updater\n\n\t@require()\n\t@cherrypy.expose\n\tdef index(self,command=None):\n\t\tself.updater.serverRcon.sendCommand(command)\n\n\t\treturn json.dumps({'status':'OK'})\n\n\t@cherrypy.expose\n\tdef players(self):\n\t\tplayers = self.updater.serverRcon.getPlayers()\n\n\t\tcherrypy.response.headers['content-type'] = 'application/json'\n\t\treturn json.dumps(players)","sub_path":"src/webserver/serverrcon.py","file_name":"serverrcon.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"583310456","text":"class GameStats:\r\n\tdef __init__(self,ai_game):\r\n\t\tself.settings = ai_game.settings\r\n\t\tself.reset_stats()\r\n\t\tself.game_active = False\r\n\t\twith open('highest_score.txt') as file_object:\r\n\t\t\tcontent = file_object.read()\r\n\t\tself.highest_score = float(content)\r\n\r\n\tdef reset_stats(self):\r\n\t\tself.ships_left = self.settings.ship_limit\r\n\t\tself.score = 0\r\n\t\tself.level = 1","sub_path":"alien_invasion/game_stats.py","file_name":"game_stats.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"433766898","text":"#!/usr/bin/env python\n\n\ndef select_sort(_array):\n x = len(_array)\n count = 0\n for i in range(x - 1):\n min = _array[i]\n n = i\n for j in range(i + 1, x):\n if _array[j] < min:\n min = _array[j]\n n = j\n _array[n] = _array[i]\n _array[i] = min\n count += 1\n print('{}: {}'.format(count, _array))\n return _array\n\n\nif __name__ == '__main__':\n import random\n list1 = [random.randint(0, 100) for i in range(10)]\n print(\"Data:\", list1)\n print(\"Sorted :\", select_sort(list1))\n","sub_path":"sort/select_sort.py","file_name":"select_sort.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"30948273","text":"# -*- coding: cp1252 -*-\r\n# -*- coding: UTF-8 -*-\r\n#from __future__ import unicode_literals\r\n\r\nfrom Tkinter import *\r\n\r\nclass Nivel6:\r\n\tdef __init__(self, j):\r\n\r\n\t\tself.s = False\r\n\t\tmain.resizable(0,0)\r\n\t\tj.title(\"Digitando Palavras - v. 0.1\")\r\n\r\n\t\tself.lbl1 = Label(j, text=\"Nível 6\", fg=\"blue\", font=('Times','20', 'bold'))\r\n\t\tself.lbl2 = Label(j, text=\"VOcê é MUITO.. Linda.\", fg=\"black\", font=('Times','20', 'bold'))\r\n\t\tself.lbl3 = Label(j, text=\"Confira aqui se a palavra foi digitada corretamente:\", fg=\"red\", font=('Times','20', 'bold'))\r\n\t\tself.lbl4 = Label(j, text=\"\", font=('Times','20', 'bold'))\r\n\r\n\t\tself.btn1 = Button(j, text=\"Próximo Nível\", command=self.proximoNivel, fg=\"black\", font=('Times','15', 'bold'))\r\n\t\tself.btn2 = Button(j, text=\"Clique aqui para confirmar a palavra\", command=self.resposta, fg=\"black\", font=('Times','15', 'bold'))\r\n\r\n\t\tself.palavra = StringVar()\r\n\t\tself.txt = Entry(j, textvariable=self.palavra, fg=\"black\", font=('Times','20', 'bold'))\r\n\r\n\t\tself.lbl1.pack()\r\n\t\tself.lbl2.pack()\r\n\t\tself.txt.pack(ipadx=20, ipady=10)\r\n\t\tself.lbl3.pack()\r\n\t\tself.lbl4.pack()\r\n\r\n\t\tself.btn1.pack(side=LEFT)\r\n\t\tself.btn2.pack(side=RIGHT)\r\n\r\n\tdef resposta(self):\r\n\t\tif self.lbl2[\"text\"] == self.palavra.get():\r\n\t\t\tself.lbl4[\"text\"] = \"A palavra foi digitada corretamente.\"\r\n\t\t\tself.s = True\r\n\t\telse:\r\n\t\t\tself.lbl4[\"text\"]= \"Existem um ou mais erros na digitação.\"\r\n\t\t\tself.s = False\r\n\tdef proximoNivel(self):\r\n\t\tif self.s == True:\r\n\t\t\tmain.destroy()\r\n\t\t\timport nivel7\r\n\r\nif __name__ == '__main__':\r\n\tmain = Tk()\r\n\tmain.geometry('635x260+50+50')\r\n\tNivel6(main)\r\n\tmain.mainloop()","sub_path":"nivel6.py","file_name":"nivel6.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"507833462","text":"# To funkcijo prijazno podarjam vsem, ki bodo programirali v eni vrstici. :)\n# Kako jo uporabiti, je v navodilih. Kdor je ne potrebuje, naj jo ignorira.\nfrom collections import*\ndef vsa_polja(s, v):\n \"\"\"\n Generiraj vse koordinate (x, y) za polje s podano širino in višino\n Args:\n s (int): širina\n v (int): višina\n\n Returns:\n generator parov polj\n \"\"\"\n return ((x, y) for x in range(s) for y in range(v))\n\n\n########################\n# Za oceno 6\n\ndef sosedov(x, y, mine):\n counter = 0\n uzyn = range(x-1, x+2)\n gapdal = range(y-1, y+2)\n for j in uzyn:\n for k in gapdal:\n if (j,k) in mine:\n if (j,k) != (x,y):\n counter += 1\n return counter\n\n\ndef najvec_sosedov(mine, s, v):\n\n max = 0\n kx = 0\n ky = 0\n uzyn = range(s)\n gapdal = range(v)\n\n for j in uzyn:\n for k in gapdal:\n counter = sosedov(j,k, mine)\n while counter > max:\n max = counter\n kx = j\n ky = k\n return (kx, ky)\n\ndef brez_sosedov(mine, s, v):\n lop = set()\n uzyn = range(s)\n gapdal = range(v)\n nol = 0\n\n for j in uzyn:\n for k in gapdal:\n counter = sosedov(j, k, mine)\n if counter == nol:\n lop.add((j,k))\n return lop\n\ndef po_sosedih(mine, s, v):\n neigh = defaultdict(set)\n lis = []\n uzyn = range(s)\n gapdal = range(v)\n total = range(0, 9)\n\n for j in uzyn:\n for k in gapdal:\n lis.append((j,k))\n\n for a in total:\n neigh[a]\n for one, two in lis:\n num = sosedov(one, two, mine)\n neigh[num].add((one, two))\n return dict(neigh)\n\n\n########################\n# Za oceno 7\n\ndef dolzina_poti(pot):\n \"\"\"\n Vrni dolžino podane poti, vključno z vmesnimi polji.\n\n Args:\n pot (list of tuple): seznam koordinat polj\n\n Returns:\n int: dolžina poti\n \"\"\"\n\n\ndef varen_premik(x0, y0, x1, y1, mine):\n \"\"\"\n Vrni `True`, če je pomik z (x0, y0) and (x1, y1) varen, `False`, če ni.\n\n Args:\n x0 (int): koordinata x začetnega polja\n y0 (int): koordinata y začetnega polja\n x1 (int): koordinata x končnega polja\n y1 (int): koordinata y končnega polja\n mine (set of tuple of int): koordinate min\n\n Returns:\n bool: `True`, če je premik varen, `False`, če ni.\n \"\"\"\n\n\ndef varna_pot(pot, mine):\n \"\"\"\n Vrni `True`, če je podana pot varna, `False`, če ni.\n\n Args:\n pot (list of tuple of int): koordinate točk na poti (brez vmesnih točk)\n mine (set of tuple of int): koordinate min\n\n Returns:\n bool: `True`, če je pot varna, `False`, če ni.\n \"\"\"\n\n\n########################\n# Za oceno 8\n\ndef polje_v_mine(polje):\n \"\"\"\n Vrni koordinate min v podanem polju.\n\n Niz polje opisuje polje tako, da so vodoravne \"vrstice\" polja ločene s\n presledki. Prosta polja so označena z znako `.`, mine z `X`.\n\n Args:\n polje (str): polje\n\n Returns:\n mine (set of tuple of int): koordinate min\n s (int): širina polja\n v (int): višina polja.\n \"\"\"\n\n\n########################\n# Za oceno 9\n#\n# Vse funkcije za oceno 6 in 7 morajo biti napisane v eni vrstici.\n\n\n########################\n# Za oceno 10\n\ndef preberi_pot(ukazi):\n \"\"\"\n Za podani seznam ukazov (glej navodila naloge) vrni pot.\n\n Args:\n ukazi (str): ukazi, napisani po vrsticah\n\n Returns:\n list of tuple of int: pot\n \"\"\"\n\n\ndef zapisi_pot(pot):\n \"\"\"\n Za podano pot vrni seznam ukazov (glej navodila naloge).\n\n Args:\n pot (list of tuple of int): pot\n\n Returns:\n str: ukazi, napisani po vrsticah\n \"\"\"\n\n\n","sub_path":"code/batch-1/vse-naloge-brez-testov/DN7-M-17.py","file_name":"DN7-M-17.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"577614355","text":"from __future__ import division, print_function\n\nimport sys\nimport os\nsys.path.append('.')\nsys.path.append('/data2/ynli/natural-language/Interaction')\nimport util\nfrom util.timer import Timer\nimport numpy as np\n\nimport nltk\nfrom nltk.corpus import wordnet\nfrom collections import Counter\nfrom multiprocessing import Pool\n\n\nclass Vocabulary :\n # define consts\n pos_mapping = {'NNS':'NN', 'NNP': 'NN', 'NNPS': 'NN', 'NN': 'NN',\\\n 'VB': 'VB', 'VBD': 'VB', 'VBN': 'VB', 'VBZ': 'VB', 'VBP': 'VB', 'VBG': 'VB',\\\n 'JJR': 'JJ', 'JJS': 'JJ', 'JJ': 'JJ', 'DT': 'DT', 'PRP': 'PRP', 'PRP$': 'PRP', 'IN':'IN',\\\n 'RB': 'RB', 'RBR': 'RB', 'RBS': 'RB'}\n punctuations = [\"''\", \"'\", \"``\", \"`\", \"-LRB-\", \"-RRB-\", \"-LCB-\", \"-RCB-\", \".\", \"?\", \"!\",\\\n \",\", \"-\", \"--\", \"...\", \";\"]\n def __init__(self, filename = None):\n '''\n Create vocabulary from .pkl file\n '''\n\n # properties:\n # _words : list(str), list of all words\n # _counts : list(int), list of word frequency for each word in _words\n # _poss : list(str), list of part-of-speech tags for each word in _words\n # _map : list(int), map i-th word to _map[i]-th word, _map[k] = -1 means no mapping for k-th word\n # _lemmatized : bool, if do lemmatization in 1) compiling dictionary, 2) converting vector\n self._wnl = nltk.WordNetLemmatizer()\n\n if filename != None:\n vocab_data = util.io.load_variables(filename)\n self.set_vocab_data(vocab_data)\n else:\n self._words = []\n self._poss = []\n self._counts = []\n self._tag = []\n self._map = None\n self._lemmatized = False\n self._openclass = False\n\n def __getitem__(self, index):\n '''\n Use vocab[key] to get vocab_data[key]. For example, vocab['words'] = vocab_data['words']\n This is for compatibility of Vocabulary class and old dict-type vocab\n '''\n return self.get_vocab_data()[index]\n\n def get_vocab_data(self):\n vocab_data = {}\n vocab_data['words'] = self._words\n vocab_data['poss'] = self._poss\n vocab_data['counts'] = self._counts\n vocab_data['tag'] = self._tag\n vocab_data['map'] = self._map\n vocab_data['lemmatized'] = self._lemmatized\n vocab_data['openclass'] = self._openclass\n return vocab_data\n\n def set_vocab_data(self, vocab_data):\n self._words = vocab_data['words']\n self._counts = vocab_data['counts']\n self._poss = vocab_data['poss']\n self._tag = vocab_data['tag'] if 'tag' in vocab_data \\\n else [(self._words[i], self._poss[i]) for i in xrange(self.len())]\n self._map = vocab_data['map'] if 'map' in vocab_data else None\n self._lemmatized = vocab_data['lemmatized'] if 'lemmatized' in vocab_data else False\n self._openclass = vocab_data['openclass'] if 'openclass' in vocab_data else False\n return\n\n def len(self):\n return len(self._words)\n\n def dim(self):\n return len(self._words) if self._map == None else self._map.count(-1)\n\n def mapping_transform(self, vec):\n \n vec_out = vec.copy()\n if self._map != None:\n assert(vec.shape[1] == self.len())\n del_list = []\n for src, dest in enumerate(self._map):\n if dest != -1:\n vec_out[:, dest] = np.max(vec_out[:, (src, dest)], axis = 1)\n del_list.append(src)\n vec_out = np.delete(vec_out, del_list, axis = 1)\n assert(vec_out.shape[1] == self.dim())\n return vec_out\n\n def _arrange_map(self):\n '''\n arrange the self._map to ensure that:\n (1) _map[i] < i, or, low-frequency word mapping to high-frequency word.\n (2) _map[_map[i]] = -1, or, no mapping like word1 -> word2 -> word3\n '''\n if self._map != None:\n for i in xrange(len(self._map)):\n if self._map[i] != -1:\n k = self._map[i]\n group = set()\n while (k != -1) and (k not in group):\n group.add(k)\n k = self._map[k]\n min_idx = min(group)\n for j in group:\n self._map[j] = min_idx\n self._map[min_idx] = -1\n\n\n\n def reduce_len_to(self, num_word):\n if num_word < self.len():\n self._words = self._words[0: num_word]\n self._counts = self._counts[0: num_word]\n self._poss = self._poss[0: num_word]\n self._tag = self._tag[0:num_word]\n if self._map != None:\n self._arrange_map()\n self._map = self._map[0: num_word]\n\n def captions_to_vec(self, captions):\n if not isinstance(captions, list):\n captions = [captions]\n vec = np.zeros((len(captions), self.len()), dtype = np.float)\n # pool = Pool()\n # captions = [unicode(sent).lower() for sent in captions]\n # captions = pool.map(nltk.word_tokenize, captions)\n captions = [nltk.word_tokenize(unicode(sent).lower()) for sent in captions]\n if self._lemmatized :\n captions = [self._lemmatize_untagged_words(sent) for sent in captions]\n # captions = pool.map(self._lemmatize_untagged_words, captions)\n \n for i, words in enumerate(captions):\n pos = [self._words.index(w) for w in words if w in self._words]\n pos = list(set(pos))\n vec[i, pos] = 1.0\n if self._map != None:\n vec = self.mapping_transform(vec)\n return vec\n\n def idx_to_words(self, idxs):\n if not isinstance(idxs, list):\n idxs = [idxs]\n return [self._words[idx] for idx in idxs]\n\n def save(self, filename):\n vocab_data = self.get_vocab_data()\n util.io.save_variables(filename, vocab_data, info = None, overwrite = True)\n\n def _lemmatize_tagged_words(self, input_tagged_words):\n # noun\n tagged_words = [(self._wnl.lemmatize(w, wordnet.NOUN), p) if p == 'NN' else (w, p) for (w, p) in input_tagged_words]\n # verb\n tagged_words = [(self._wnl.lemmatize(w, wordnet.VERB), p) if p == 'VB' else (w, p) for (w, p) in tagged_words]\n # adjective\n tagged_words = [(self._wnl.lemmatize(w, wordnet.ADJ), p) if p == 'JJ' else (w, p) for (w, p) in tagged_words]\n # adverb\n tagged_words = [(self._wnl.lemmatize(w, wordnet.ADV), p) if p == 'RB' else (w, p) for (w, p) in tagged_words]\n return tagged_words\n\n def _lemmatize_untagged_words(self, input_words):\n tagged_words = nltk.pos_tag(input_words)\n tagged_words = [(w,self.pos_mapping[p]) if p in self.pos_mapping else (w, 'other') for (w, p) in tagged_words]\n tagged_words = self._lemmatize_tagged_words(tagged_words)\n return [w for (w, p) in tagged_words]\n\n def compile_from_corpus(self, corpus, opts = None):\n '''\n Compile vocabulary from corpus\n input:\n corpus: list(str), list of sentences(str)\n opts: dict\n num_word: int, max number of words in vocabulary\n lemmatized: bool, use nltk to lemmatize words\n openclass: bool, only include open-class words\n Note:\n If one word has more than one pos, they are combined and labeled as the most common pos\n '''\n\n # argument parsing\n timer = Timer()\n\n if opts == None: opts = {}\n num_word = opts['num_word'] if 'num_word' in opts else 1000\n lemmatized = opts['lemmatized'] if 'lemmatized' in opts else False\n openclass = opts['openclass'] if 'openclass' in opts else False\n self._lemmatized = lemmatized\n self._openclass = openclass\n\n # tokenize\n print('tokenizing corpus ...')\n timer.tic()\n tagged_sentences = [nltk.pos_tag(nltk.word_tokenize(unicode(sent).lower())) for sent in corpus]\n tagged_words = [word for sent in tagged_sentences for word in sent]\n tagged_words = [(w, self.pos_mapping[p]) if p in self.pos_mapping else (w, 'other') for (w, p) in tagged_words]\n # remove punctuations\n tagged_words = [(w, p) for (w, p) in tagged_words if w not in self.punctuations]\n # open-class\n if openclass:\n tagged_words = [(w, p) for (w, p) in tagged_words if p in ['NN', 'VB', 'JJ', 'RB']]\n timer.toc()\n\n # lemmatization\n \n if lemmatized:\n print('lematizing ...')\n timer.tic()\n tagged_words = self._lemmatize_tagged_words(tagged_words)\n timer.toc()\n\n # count words\n print('counting words ...')\n timer.tic()\n tag_counter = Counter(tagged_words)\n tag_counter = tag_counter.most_common()\n\n words_t = [w for ((w, p), c) in tag_counter]\n poss_t = [p for ((w, p), c) in tag_counter]\n # counts_t = [c for ((w, p), c) in tag_counter]\n \n timer.toc()\n\n # combine different pos of same word\n print('combining pos ...')\n timer.tic()\n word_counter = Counter([w for (w,p) in tagged_words])\n word_counter = word_counter.most_common()\n words = [w for (w, c) in word_counter]\n counts = [c for (w, c) in word_counter]\n poss = [poss_t[words_t.index(w)] for w in words]\n # words_u = list(set(words))\n # index_u = [[idx for idx, w in enumerate(words) if w == w_u] for w_u in words_u]\n # poss_u = [poss[min(idx_list)] for idx_list in index_u]\n # counts_u = np.array(counts, dtype = np.int32)\n # counts_u = [counts_u[idx_list].sum() for idx_list in index_u]\n # idx = np.argsort(np.array(counts_u, dtype=np.int32))[::-1]\n # words = [words_u[i] for i in idx]\n # poss = [poss_u[i] for i in idx]\n # counts = [counts_u[i] for i in idx]\n timer.toc()\n\n tag = [(words[i], poss[i]) for i in xrange(len(words))]\n num_word = min(num_word, len(words))\n self._words = words[0:num_word]\n self._poss = poss[0:num_word]\n self._counts = counts[0:num_word]\n self._tag = tag[0:num_word]\n self._map = None\n\n\n\n\n\n\n","sub_path":"modules/vocab/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":10324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"359297372","text":"#Modules to use\nimport re\nimport os\nimport glob\nimport pandas as pd\nimport matplotlib as mt\nfrom matplotlib import pyplot as plt\n\n#TO DO:\n# - Include the search of positive score values into get_scores funtion\n# - Incluide a funtion to find and save GOLD\n\n\n# NOW TO THE FUNTIONS\nclass get_scores ():\n\n def __init__ (self,path=None,docker=None, save_csv=True, sort=True):\n self.path = path\n self.docker = docker\n self.save_csv = save_csv\n self.sort = sort\n if docker == 'autodockvina':\n os.chdir (path) #Path where *.pdbqt output files are located\n files=[]\n scores=[]\n for file in glob.glob('*.pdbqt'):\n with open(file,'rt') as file:\n for line in file:\n line = line.strip()\n if \"VINA RESULT\" in line:\n neg = re.search(r'-\\d.\\d', line)\n if neg:\n files.append (file.name)\n scores.append (neg.group())\n d={'file':pd.Series(files),'score':pd.Series(scores)}\n print ('Raw score values')\n table=pd.DataFrame (d)\n print (table)\n\n pass\n\n if docker== 'gold':\n os.chdir (path) #Path where *.pdbqt output files are located\n files=[]\n scores=[]\n for file in glob.glob('*.mol2'):\n with open(file,'rt') as file:\n for line in file:\n line = line.strip()\n if \"\" in line:\n neg = re.search(r'\\d\\d.\\d\\d', line)\n if neg:\n files.append (file.name)\n scores.append (neg.group())\n d={'file':pd.Series(files),'score':pd.Series(scores)}\n print ('Raw score values')\n table=pd.DataFrame (d)\n print (table)\n pass\n\n if sort == True:\n print ('Sorted score values')\n sort=table.sort_values ('score',ascending=False)\n print (sort)\n if save_csv == True:\n table.to_csv ('no_sorted_scores.csv')\n sort.to_csv ('sorted_scores.csv')\n","sub_path":"Docking_analyzer/scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"123729470","text":"#!/usr/bin/python3\n\"\"\" Module with the all the function to run the web server\n\nThis module has 16 functions:\n - showLogin();\n - google_connect();\n - google_disconnect();\n - catalogJSON();\n - showCategories();\n - newCategory();\n - editCategory(category_name);\n - deleteCategory(category_name);\n - showItems(category_name);\n - newCategoryItem(category_name);\n - showItem(category_name, item_title);\n - editCategoryItem(category_name, item_title);\n - deleteCategoryItem(category_name, item_title);\n - getUserId(email);\n - getUserInfo(user_id);\n - createUser(login_session);\n\nRunning this file will start the web server.\n\"\"\"\n\nfrom flask import Flask, jsonify, render_template, request\nfrom flask import flash, make_response, redirect, url_for\nfrom models import app, db, Category, CategoryItem, User\nfrom flask import session as login_session\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nimport random\nimport string\nimport json\nimport httplib2\nimport requests\n\n# Google's Client ID\nCLIENT_ID = json.loads(\n open('/var/www/catalog/catalog/client_secrets.json', 'r').read())['web']['client_id']\n\n# Create anti-forgery state token\n@app.route('/login')\ndef showLogin():\n state = ''.join(random.choice(string.ascii_uppercase + string.digits)\n for x in range(32))\n login_session['state'] = state\n return render_template('login.html', STATE=state)\n\n\n# Connect to Google Account\n@app.route('/google_connect', methods=['POST'])\ndef google_connect():\n # Validate state token\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Obtain authorization code\n code = request.data\n\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets('/var/www/catalog/catalog/client_secrets.json', scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n response = make_response(\n json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check that the access token is valid.\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1].decode('utf-8'))\n\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user.\n google_id = credentials.id_token['sub']\n if result['user_id'] != google_id:\n response = make_response(\n json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(\n json.dumps(\"Token's client ID does not match app's.\"), 401)\n print(\"Token's client ID does not match app's.\")\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_access_token = login_session.get('access_token')\n stored_google_id = login_session.get('google_id')\n if stored_access_token is not None and google_id == stored_google_id:\n response = make_response(\n json.dumps('Current user is already connected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Store the access token in the session for later use.\n login_session['access_token'] = credentials.access_token\n login_session['google_id'] = google_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n\n user_id = getUserId(login_session['email'])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n flash(\"You are now logged in as %s\" % login_session['username'])\n print(\"done!\")\n output = 'ok'\n return output\n\n\n# Disconnect from Google Account\n@app.route('/google_disconnect')\ndef google_disconnect():\n access_token = login_session.get('access_token')\n # Verify if there is a token\n if access_token is None:\n print('Access Token is None')\n response = make_response(\n json.dumps('Current user not connected.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n print('In gdisconnect access token is %s', access_token)\n print('User name is: ')\n print(login_session['username'])\n url = 'https://accounts.google.com/o/oauth2/revoke?token={token}'\n url = url.format(token=login_session['access_token'])\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n print('result is ')\n print(result)\n\n # Verify if the account was successfuly disconnected\n if result['status'] == '200':\n # delete the information about the user in the login_session\n del login_session['access_token']\n del login_session['google_id']\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n response = make_response(json.dumps('Successfully disconnected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n flash(\"Successfully disconnected!\")\n else:\n # delete the information about the user in the login_session\n del login_session['access_token']\n del login_session['google_id']\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n response = make_response(\n json.dumps('Failed to revoke token for given user.', 400))\n response.headers['Content-Type'] = 'application/json'\n flash(\"Failed to disconnected!\")\n return render_template('logout.html', response=response)\n\n\n# Create a json with all informations about categories and items\n@app.route('/catalog.json')\ndef catalogJSON():\n catalog = {'Category': []}\n categories = Category.query.all()\n for category in categories:\n categ_items = category.serialize\n items = CategoryItem.query.filter_by(cat_id=category.id).all()\n categ_items['Items'] = [item.serialize for item in items]\n catalog['Category'].append(categ_items)\n return jsonify(catalog)\n\n\n# JSON APIs to view Category Information\n@app.route('/catalog//items/JSON')\ndef showItemsJSON(category_name):\n catalog = {'Category': []}\n category = Category.query.filter_by(name=category_name).first()\n categ_items = category.serialize\n items = CategoryItem.query.filter_by(cat_id=category.id).all()\n categ_items['Items'] = [item.serialize for item in items]\n catalog['Category'].append(categ_items)\n return jsonify(catalog)\n\n\n# JSON APIs to view Item Information\n@app.route('/catalog///JSON')\ndef showItemJSON(category_name, item_title):\n catalog = {'Category': []}\n category = Category.query.filter_by(name=category_name).first()\n categ_items = category.serialize\n item = CategoryItem.query.filter_by(\n title=item_title, cat_id=category.id).first()\n categ_items['Items'] = [item.serialize]\n catalog['Category'].append(categ_items)\n return jsonify(catalog)\n\n\n# Show all Categories\n@app.route('/')\ndef showCategories():\n categories = Category.query.order_by(Category.name.asc()).all()\n\n # Create a list of dictionaries with 5 latest item created.\n latest_items = []\n for item in CategoryItem.query.order_by(CategoryItem.id.desc()).limit(5):\n latest_items.append(\n {'Title': item.title,\n 'Category': Category.query.filter_by(\n id=item.cat_id).first().name})\n\n # Verify if a user not is logged\n if 'username' not in login_session:\n return render_template(\n 'categories.html',\n categories=categories,\n latest_items=latest_items)\n\n # Enable CRUD operations\n else:\n return render_template(\n 'auth_categories.html',\n categories=categories,\n latest_items=latest_items)\n\n\n# Create a new category\n@app.route('/catalog/new/', methods=['GET', 'POST'])\ndef newCategory():\n # Verify if a user is logged\n if 'username' not in login_session:\n return redirect('/login')\n\n # Execute if is a POST method\n if request.method == 'POST':\n\n # Verify if the name was informed to create the category\n if request.form['name']:\n newCategory = Category(\n name=request.form['name'],\n user_id=login_session['user_id'])\n db.session.add(newCategory)\n db.session.commit()\n flash('New Category %s Successfully Created!' % newCategory.name)\n return redirect(url_for('showCategories'))\n\n # Show a message to inform the name\n else:\n flash('You need to inform a name!')\n return render_template('new_category.html')\n\n # Execute if is a GET method\n else:\n return render_template('new_category.html')\n\n\n# Edit a category\n@app.route('/catalog//edit/', methods=['GET', 'POST'])\ndef editCategory(category_name):\n # Verify if a user is logged\n if 'username' not in login_session:\n return redirect('/login')\n editedCategory = Category.query.filter_by(name=category_name).first()\n\n # Verify if the category was created by the current user\n if editedCategory.user_id != login_session['user_id']:\n return render_template(\n 'not_authorized.html',\n msg='You are not authorized to edit this category!')\n\n # Execute if is a POST method\n if request.method == 'POST':\n # Verify if the name was informed to create the category\n if request.form['name']:\n editedCategory.name = request.form['name']\n db.session.commit()\n flash('Category Successfully Edited %s!' % editedCategory.name)\n return redirect(url_for(\n 'showItems', category_name=editedCategory.name))\n # Show a message to inform the name\n else:\n flash('You need to inform a name!')\n return render_template(\n 'edit_category.html', category=editedCategory)\n\n # Execute if is a GET method\n else:\n return render_template('edit_category.html', category=editedCategory)\n\n\n# Delete a category\n@app.route('/catalog//delete/', methods=['GET', 'POST'])\ndef deleteCategory(category_name):\n # Verify if a user is logged\n if 'username' not in login_session:\n return redirect('/login')\n categoryToDelete = Category.query.filter_by(name=category_name).first()\n\n # Verify if the category was created by the current user\n if categoryToDelete.user_id != login_session['user_id']:\n return render_template(\n 'not_authorized.html',\n msg='You are not authorized to delete this category!')\n\n # Execute if is a POST method\n if request.method == 'POST':\n db.session.delete(categoryToDelete)\n db.session.commit()\n flash('%s Successfully Deleted' % categoryToDelete.name)\n return redirect(url_for('showCategories'))\n\n # Execute if is a GET method\n else:\n return render_template(\n 'delete_category.html', category=categoryToDelete)\n\n\n# Show the items of the category\n@app.route('/catalog//items/')\ndef showItems(category_name):\n categories = Category.query.order_by(Category.name.asc()).all()\n category = Category.query.filter_by(name=category_name).first()\n category_items = CategoryItem.query.filter_by(\n cat_id=category.id).order_by(CategoryItem.title.asc()).all()\n\n # Verify if a user not is logged\n if 'username' not in login_session:\n return render_template(\n 'items.html',\n categories=categories,\n category=category,\n category_items=category_items)\n\n # Enable CRUD operations\n else:\n return render_template(\n 'auth_items.html',\n categories=categories,\n category=category,\n category_items=category_items)\n\n\n# Create a new item\n@app.route('/catalog//items/new/', methods=['GET', 'POST'])\ndef newCategoryItem(category_name):\n # Verify if a user is logged\n if 'username' not in login_session:\n return redirect('/login')\n categories = Category.query.order_by(Category.name.asc()).all()\n\n # Execute if is a POST method\n if request.method == 'POST':\n\n # Verify if the title was informed to create the item\n # The description is optional to create the item\n if request.form['title']:\n category = Category.query.filter_by(\n name=request.form['select_category']).first()\n newCategoryItem = CategoryItem(\n title=request.form['title'],\n description=request.form['description'],\n cat_id=category.id,\n user_id=login_session['user_id'])\n db.session.add(newCategoryItem)\n db.session.commit()\n flash('New Item %s Successfully Created!' % newCategoryItem.title)\n return redirect(url_for('showItems', category_name=category.name))\n\n # Show a message to inform the name\n else:\n flash('You need to inform a title!')\n category = Category.query.filter_by(name=category_name).first()\n return render_template(\n 'new_item.html',\n categories=categories,\n category=category)\n\n # Execute if is a GET method\n else:\n category = Category.query.filter_by(name=category_name).first()\n return render_template(\n 'new_item.html',\n categories=categories,\n category=category)\n\n\n# Show specific item\n@app.route('/catalog//')\ndef showItem(category_name, item_title):\n category = Category.query.filter_by(name=category_name).first()\n item = CategoryItem.query.filter_by(\n title=item_title, cat_id=category.id).first()\n\n # Verify if a user not is logged\n if 'username' not in login_session:\n return render_template('item.html', category=category, item=item)\n\n # Enable CRUD operations\n else:\n return render_template('auth_item.html', category=category, item=item)\n\n\n# Edit a category item\n@app.route(\n '/catalog//items//edit',\n methods=['GET', 'POST'])\ndef editCategoryItem(category_name, item_title):\n # Verify if a user is logged\n if 'username' not in login_session:\n return redirect('/login')\n categories = Category.query.order_by(Category.name.asc()).all()\n editedItem = CategoryItem.query.filter_by(title=item_title).first()\n\n # Verify if the item was created by the current user\n if editedItem.user_id != login_session['user_id']:\n return render_template(\n 'not_authorized.html',\n msg='You are not authorized to edit this item!')\n\n # Execute if is a POST method\n if request.method == 'POST':\n\n # Verify if the title was informed to create the item\n # The description is optional to create the item\n if request.form['title']:\n category = Category.query.filter_by(\n name=request.form['select_category']).first()\n editedItem.title = request.form['title']\n editedItem.description = request.form['description']\n editedItem.cat_id = category.id\n db.session.commit()\n flash('Item Successfully Edited %s!' % editedItem.title)\n return redirect(url_for('showItems', category_name=category.name))\n\n # Show a message to inform the name\n else:\n flash('You need to inform a title!')\n category = Category.query.filter_by(name=category_name).first()\n return render_template(\n 'edit_item.html',\n item=editedItem,\n category=category,\n categories=categories)\n\n # Execute if is a GET method\n else:\n category = Category.query.filter_by(name=category_name).first()\n return render_template(\n 'edit_item.html',\n item=editedItem,\n category=category,\n categories=categories)\n\n\n# Delete a category item\n@app.route(\n '/catalog//items//delete',\n methods=['GET', 'POST'])\ndef deleteCategoryItem(category_name, item_title):\n # Verify if a user is logged\n if 'username' not in login_session:\n return redirect('/login')\n itemToDelete = CategoryItem.query.filter_by(title=item_title).first()\n category = Category.query.filter_by(name=category_name).first()\n\n # Verify if the item was created by the current user\n if itemToDelete.user_id != login_session['user_id']:\n return render_template(\n 'not_authorized.html',\n msg='You are not authorized to delete this item!')\n\n # Execute if is a POST method\n if request.method == 'POST':\n db.session.delete(itemToDelete)\n db.session.commit()\n flash('%s Successfully Deleted' % itemToDelete.title)\n return redirect(url_for(\n 'showItems',\n category_name=category_name,\n item_title=itemToDelete.title))\n\n # Execute if is a GET method\n else:\n return render_template(\n 'delete_item.html',\n item=itemToDelete,\n category=category)\n\n\n# Get User id, search the e-mail\ndef getUserId(email):\n try:\n user = User.query.filter_by(email=email).first()\n return user.id\n except:\n return None\n\n\n# Get User Information\ndef getUserInfo(user_id):\n user = User.query.filter_by(id=user_id).first()\n return user\n\n\n# Create New User with info of Google Account\ndef createUser(login_session):\n newUser = User(\n name=login_session['username'],\n email=login_session['email'],\n picture=login_session['picture'])\n db.session.add(newUser)\n db.session.commit()\n user = User.query.filter_by(email=login_session['email']).first()\n return user.id\n\n\n# If run this module will start the server.\nif __name__ == '__main__':\n app.secret_key = '##THIS_IS_THE_SECRET_KEY_FOR_THIS_APPLICATION##'\n app.debug = False\n app.run(host='0.0.0.0', port=8000)\n","sub_path":"catalog/catalog.py","file_name":"catalog.py","file_ext":"py","file_size_in_byte":19262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"330065424","text":"\"\"\"\nA simple script to start tensorflow servers with different roles.\n\"\"\"\nimport os\n\nimport tensorflow as tf\n\n# define the command line flags that can be sent\ntf.app.flags.DEFINE_integer(\"task_index\", 0, \"Index of task with in the job.\")\ntf.app.flags.DEFINE_string(\"job_name\", \"worker\", \"either worker or ps\")\ntf.app.flags.DEFINE_string(\"deploy_mode\", \"single\", \"either single or cluster\")\nFLAGS = tf.app.flags.FLAGS\n\n#\ntf.logging.set_verbosity(tf.logging.DEBUG)\n\nclusterSpec_single = tf.train.ClusterSpec({\n \"worker\" : [\n \"localhost:2222\"\n ]\n})\n\nclusterSpec_2proc = tf.train.ClusterSpec({\n \"ps\": [\n \"localhost:2222\"\n ],\n \"worker\": [\n \"localhost:2223\",\n \"localhost:2224\"\n ]\n})\n\nclusterSpec_2dev_2proc = tf.train.ClusterSpec({\n \"ps\": [\n \"salat0:2222\"\n ],\n \"worker\": [\n \"salat1:2223\",\n \"salat1:2224\"\n ]\n})\nclusterSpec_cluster = tf.train.ClusterSpec({\n \"ps\" : [\n \"node-0:2222\"\n ],\n \"worker\" : [\n \"node-1:2222\",\n \"node-2:2222\"\n ]\n})\n\nclusterSpec_cluster2 = tf.train.ClusterSpec({\n \"ps\" : [\n \"node-0:2222\"\n ],\n \"worker\" : [\n \"node-1:2222\",\n \"node-2:2222\",\n \"node-3:2222\",\n \"node-4:2222\"\n ]\n})\n\nclusterSpec = {\n \"single\": clusterSpec_single,\n '1dev-2proc': clusterSpec_2proc,\n '2dev-2proc': clusterSpec_2dev_2proc,\n \"cluster\": clusterSpec_cluster,\n \"cluster2\": clusterSpec_cluster2\n}\n\nclusterinfo = clusterSpec[FLAGS.deploy_mode]\nserver = tf.train.Server(clusterinfo, job_name=FLAGS.job_name, task_index=FLAGS.task_index)\nserver.join()\n","sub_path":"startserver.py","file_name":"startserver.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"35877501","text":"#!\"usr/local/bin/python3.2\"\n#This file asks the user for the name of a file.\n#The program will display the first 5 lines of the file.\n#If there are more than 5 lines to the file, the whole file will be printed.\n#Define main function\ndef main():\n #Create a bool value to use as a flag.\n found = False\n #Get the search value\n search = input(\"Enter the name of the file: \")\n #Open the file.\n numbers_file = open(\"numbers.txt\", \"r\")\n #Read the first line\n numbers = numbers_file.readline()\n #Determine if search value matches file.\n if numbers_file == search:\n print(\"File exists\")\n print(numbers)\n #Set found flag to true.\n found = True\n #Read the next line.\n numbers = numbers_file.readline()\n #Close the file\n numbers_file.close()\n#Call main function\nmain()","sub_path":"file_head_display.py","file_name":"file_head_display.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"450610112","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app, supports_credentials=True)\n\napp.config.from_pyfile('config.py')\n\n# instantiate the db and LoginManager\ndb = SQLAlchemy()\nlogin_manager = LoginManager()\n\n# Set up extensions\ndb.init_app(app)\nlogin_manager.init_app(app)\n\n@app.route('/create')\ndef create():\n\tdb.create_all()\n\treturn 'All tables created'\n\nfrom routes import *\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"134410977","text":"#encoding: utf-8\n\nfrom exts import db\nfrom datetime import datetime\n\nclass User(db.Model):\n __tablename__ = 'user'\n id = db.Column(db.Integer,primary_key = True,autoincrement=True)\n telephone = db.Column(db.String(11),nullable=False)\n username = db.Column(db.String(25),nullable=False)\n password = db.Column(db.String(30),nullable=False)\n\nclass Video(db.Model):\n __tablename__ = 'video'\n id = db.Column(db.Integer,primary_key=True,autoincrement=True)\n title = db.Column(db.String(100),nullable=False)\n content = db.Column(db.Text,nullable=False)\n create_time = db.Column(db.DateTime,default=datetime.now)\n author_id = db.Column(db.Integer,db.ForeignKey('user.id'))\n author = db.relationship('User',backref=db.backref('videos'))\n\nclass Answer(db.Model):\n __tablename__ = 'answer'\n id = db.Column(db.Integer,primary_key=True,autoincrement=True)\n content = db.Column(db.Text,nullable=False)\n create_time = db.Column(db.DateTime,default=datetime.now)\n video_id = db.Column(db.Integer,db.ForeignKey('video.id'))\n author_id = db.Column(db.Integer,db.ForeignKey('user.id'))\n\n video = db.relationship('Video',backref=db.backref('answers',order_by=id.desc()))\n author = db.relationship('User',backref=db.backref('answers'))\n\n\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"630300772","text":"import numpy as np\nimport cv2\n\nimport time\n# 你可以用这个file对各步骤对时间消耗进行测试\n\nt = time.time()\ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FPS, 60)\ncap.set(3,640)\ncap.set(4,480)\nwhile(True):\n t1 = time.time()\n ret, frame = cap.read() #这一步是最费时的,需要50-90ms\n print(time.time() - t1)\n if ret == True:\n \n cv2.imshow('frame',frame) #这一步小于1ms\n \n \n if cv2.waitKey(1) & 0xFF == ord('q'): #这一步居然要大概15ms\n break\n \n # newt = time.time()\n # print(newt-t)\n # t = newt\n else:\n print('no %f' % (time.time() - t))\n \ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"4708370","text":"import uuid\nimport logging\n\nimport esia_client\n\nlogger = logging.getLogger(__name__)\n\n__all__ = ['AsyncAuth', 'AsyncUserInfo']\n\n\nclass AsyncUserInfo(esia_client.UserInfo):\n async def _request(self, url: str) -> dict:\n \"\"\"\n Делает асинхронный запрос пользовательской информации в ЕСИА\n\n Args:\n url: URL запроса пользовательских данных\n\n Raises:\n IncorrectJsonError: неверный формат ответа\n HttpError: ошибка сети или сервера\n\n \"\"\"\n headers = {'Authorization': \"Bearer %s\" % self.token, 'Accept': 'application/json'}\n logger.info(f'Sending info request to; {url}')\n\n return await esia_client.utils.make_async_request(url=url, headers=headers)\n\n async def get_person_main_info(self) -> dict:\n \"\"\"\n Получение общей информации о пользователе\n \"\"\"\n\n url = '{base}/prns/{oid}'.format(base=self._rest_base_url, oid=self.oid)\n return await self._request(url=url)\n\n async def get_person_addresses(self) -> dict:\n \"\"\"\n Получение адресов регистрации пользователя\n \"\"\"\n\n url = '{base}/prns/{oid}/addrs?embed=(elements)'.format(base=self._rest_base_url, oid=self.oid)\n return await self._request(url=url)\n\n async def get_person_contacts(self) -> dict:\n \"\"\"\n Получение пользовательский контактов\n \"\"\"\n url = '{base}/prns/{oid}/ctts?embed=(elements)'.format(base=self._rest_base_url, oid=self.oid)\n return await self._request(url=url)\n\n async def get_person_documents(self) -> dict:\n \"\"\"\n Получение пользовательских документов\n \"\"\"\n url = '{base}/prns/{oid}/docs?embed=(elements)'.format(base=self._rest_base_url, oid=self.oid)\n return await self._request(url=url)\n\n async def get_person_passport(self, doc_id: int) -> dict:\n \"\"\"\n Получение документа удостоверяющего личность пользователя\n \"\"\"\n url = '{base}/prns/{oid}/docs/{doc_id}'.format(base=self._rest_base_url, oid=self.oid, doc_id=doc_id)\n return await self._request(url=url)\n\n\nclass AsyncAuth(esia_client.Auth):\n\n async def complete_authorization(self, code, state: str = None, redirect_uri: str = None) -> AsyncUserInfo:\n \"\"\"\n Полученение токена авторизации и клиента запроса информации\n\n Args:\n code: код авторизации\n state: идентификатор сессии авторизации в формате `uuid.UUID`\n redirect_uri: URL для переадресации после авторизации\n\n Raises:\n\n IncorrectJsonError: Неверный формат JSON-ответа\n HttpError: Ошибка сети или сервера\n IncorrectMarkerError: Неверный формат токена\n \"\"\"\n\n if not state:\n state = str(uuid.uuid4())\n logger.info(f'Complete authorisation with state {state}')\n\n params = {\n 'client_id': self.settings.esia_client_id,\n 'code': code,\n 'grant_type': 'authorization_code',\n 'redirect_uri': redirect_uri or self.settings.redirect_uri,\n 'timestamp': esia_client.utils.get_timestamp(),\n 'token_type': 'Bearer',\n 'scope': self.settings.scope_string,\n 'state': state,\n }\n\n self._sign_params(params)\n\n response_json = await esia_client.utils.make_async_request(\n url=f\"{self.settings.esia_service_url}{self._TOKEN_EXCHANGE_URL}\",\n method='POST', data=params, timeout=self.settings.timeout\n )\n\n access_token = response_json['access_token']\n id_token = response_json['id_token']\n payload = esia_client.utils.decode_payload(id_token.split('.')[1])\n logger.debug(f'Access token: {access_token}, id token: {id_token}')\n\n return AsyncUserInfo(access_token=access_token,\n oid=self._get_user_id(payload),\n settings=self.settings)\n","sub_path":"esia_client/async_client.py","file_name":"async_client.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"470804157","text":"import json\nimport urllib2\n\nimport webapp2\nfrom google.appengine.api import urlfetch\n\nfrom commands import commands_map, valid_command\nfrom settings import BASE_URL\n\n\nclass MeHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getMe'))))\n\n\nclass GetUpdatesHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n self.response.write(json.dumps(json.load(urllib2.urlopen(BASE_URL + 'getUpdates'))))\n\n\nclass SetWebhookHandler(webapp2.RequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(60)\n url = self.request.get('url')\n host = self.request.host\n if url:\n link = BASE_URL + 'setWebhook?url=https://%s/webhook' % host\n self.response.write(\n json.dumps(\n json.load(urllib2.urlopen(link))))\n\n\nclass WebhookHandler(webapp2.RequestHandler):\n def post(self):\n urlfetch.set_default_fetch_deadline(60)\n body = json.loads(self.request.body)\n self.response.write(json.dumps(body))\n\n update_id = body['update_id']\n try:\n details = body['message']\n except:\n details = body['edited_message']\n message_id = details['message_id']\n date = details['date']\n text = details.get('text')\n fr = details['from']\n chat = details['chat']\n chat_id = chat['id']\n\n if text is None or not text.startswith('/'):\n return\n\n text = text.lower().strip().replace(\"@myhungrybot\", \"\")\n\n command = text.split()[0]\n if command.startswith('/help'):\n commands_map['/help']['function'](text, details)\n elif valid_command(command, details):\n commands_map[command]['function'](text, details)\n\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/me', handler = MeHandler),\n webapp2.Route('/updates', handler = GetUpdatesHandler),\n webapp2.Route('/set_webhook', handler = SetWebhookHandler),\n webapp2.Route('/webhook', handler = WebhookHandler)\n], debug = True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"233472281","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\n\r\ndef display_full_name():\r\n messagebox.showinfo(\"GUI Python\", \" имя: \"+FIO.get() + \"\\n телефон: \" + str(phone.get())+\"\\n почта: \"+email.get()+\"\\n коментарий: \"+text_box.get(\"1.0\",END)) \r\n\r\nroot = Tk()\r\nroot.title(\"GUI на Python\")\r\nroot.geometry(\"340x250\")\r\n \r\nFIO = StringVar()\r\nphone = IntVar()\r\nemail = StringVar()\r\ntext = StringVar()\r\n \r\nname_label = Label(text=\"Введите имя:\")\r\nphone_label = Label(text=\"Введите телефон:\")\r\nemail_label = Label(text=\"Введите email:\")\r\ntext_label =Label(text=\"Введите ваш \\n коментарий:\")\r\n \r\nname_label.grid(row=0, column=0, sticky=\"w\")\r\nphone_label.grid(row=1, column=0, sticky=\"w\")\r\nemail_label.grid(row=2,column=0, sticky=\"w\")\r\ntext_label.grid(row=3,column=0, sticky=\"w\")\r\n\r\nname_entry = Entry(textvariable=FIO)\r\nphone_entry = Entry(textvariable=phone)\r\nemail_entry = Entry(textvariable=email)\r\ntext_box = Text(root,width=23, height=5,\r\n font=\"Arial 8\",\r\n wrap=WORD)\r\n\r\nname_entry.insert(INSERT, \"Семен Семеныч\")\r\nphone_entry.insert(INSERT, \"8950000559\")\r\nemail_entry.insert(INSERT, \"semen@mailbox.ru\")\r\ntext_box.insert(INSERT, \"Hellow\")\r\n \r\nname_entry.grid(row=0,column=1, padx=5, pady=5)\r\nphone_entry.grid(row=1,column=1, padx=5, pady=5)\r\nemail_entry.grid(row=2,column=1, padx=5, pady=5) \r\ntext_box.grid(row=3, column=1, padx=5, pady=5)\r\n \r\nmessage_button = Button(text=\"Отправить\", command=display_full_name)\r\nmessage_button.grid(row=4,column=1, padx=5, pady=5, sticky=\"e\")\r\n \r\nroot.mainloop()\r\n","sub_path":"comment_form.py","file_name":"comment_form.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"466627583","text":"import numpy as np\nfrom numpy import array\nimport tensorflow as tf\nimport keras\nimport scipy\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.text import one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Input, Dropout, LSTM, Activation\nfrom keras import optimizers\nfrom keras.layers import Flatten\nfrom keras.layers.embeddings import Embedding\nfrom keras.models import load_model\nfrom keras import metrics\nimport config\nimport os\nimport logging\nimport multiprocessing\nfrom joblib import Parallel, delayed\nfrom keras.models import model_from_json\nfrom keras.callbacks import EarlyStopping, Callback\nfrom sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score\nfrom keras.layers.normalization import BatchNormalization\nfrom pre_processing_ref import load_data_from_csv, seg_words, train_vec, train_tencent_model, convert_to_onehot, sentence_to_indice, embedding_data, wordToIndex, convert_prob_to_cls_name, convert_oh_to_cls_name\n\n# define documents\ntrain=load_data_from_csv(config.train_data_path)\nval = load_data_from_csv(config.validate_data_path)\nprint(\"finish loading data\")\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] <%(processName)s> (%(threadName)s) %(message)s')\nlogger = logging.getLogger(__name__)\n#test = load_data_from_csv(config.test_data_path)\n\n#val dataset as hold-out val set and test dataset; do cv on train dataset\nm_val = val.shape[0]\n'''train_doc = train.iloc[:, 1]\nval_doc = val.iloc[0:7500, 1]\ntest_doc = val.iloc[7501:m_val-1, 1]\ntrain_doc = train.iloc[1:10, 1]\nval_doc = val.iloc[0:5, 1]\ntest_doc = val.iloc[6:10, 1]\nprint(\"finish splitting\")\nprint(train_doc.shape)\nprint(val_doc.shape)\nprint(test_doc.shape)'''\n\n# define class labels\n#train_labels = array(train[:, 2:])\n#val_labels = array(val[0:7500, 2:])\n#test_labels = array(val[7501:m_val-1, 2:])\ntrain_labels = array(train.iloc[:, 2:])\nval_labels = array(val.iloc[0:7500, 2:])\ntest_labels = array(val.iloc[7501:m_val-1, 2:])\n#print(\"test number\"+str(test_labels.shape[0]))\nprint(\"finish loading labels\")\nprint(train_labels.shape)\nprint(val_labels.shape)\nprint(test_labels.shape)\n\ntrain_indices = np.load(\"train_indices_w2v.dat\")\nval_indices = np.load(\"val_indices_w2v.dat\")\ntest_indices = np.load(\"test_indices_w2v.dat\")\nmax_length=train_indices.shape[1]\nprint(\"max_length\")\nprint(max_length)\n\n#debug part\n'''train_indices = train_indices[1:20, :]\nval_indices = val_indices[1:10, :]\ntest_indices = test_indices[11:20, :]\n\ntrain_labels=train_labels[1:20,:]\nval_labels=val_labels[1:10, :]\ntest_labels=test_labels[11:20,:]'''\n\nembedding_matrix=np.load(\"/scratch/users/qingyin/output/embedding_matrix_w2v.dat\")\nvocab_len = embedding_matrix.shape[0]\nemb_dim = embedding_matrix.shape[1]\nprint(\"vocab_len\")\nprint(vocab_len)\nprint(\"emb_dim\")\nprint(emb_dim)\n\ncolumns = [1,5, 9, 10, 13, 14,15, 16, 19]\n\ndef loopone(i):\n def f1(y_true, y_pred):\n y_pred_label = convert_prob_to_cls_name(y_pred)\n y_true_label = convert_oh_to_cls_name(y_true)\n #print(y_pred_label)\n\t #print(y_true_label)\n f1score = f1_score(y_true_label, y_pred_label, average='weighted')\n #f1score_wt = f1_score(y_true_label, y_pred_label, average=weighted)\n f1_ave = np.average(f1score)\n return f1_ave\n\n logger.info(\"start train column\" +str(i))\n if i == 15 or i == 18:\n class_weight = {\n 0: 14.0/37.0,\n 1: 14.0/37.0,\n 2: 5.0/37.0,\n 3: 4.0/37.0\n\t\t}\n else:\n class_weight = {\n 0: 1.0/37.0,\n 1: 12.0/37.0,\n 2: 12.0/37.0,\n 3: 12.0/37.0\n }\n\n '''model_path = \"/scratch/users/qingyin/output/\" +str(i) + 'th w2v epoch20 model.h5'\n new_model = load_model(model_path)\n # fit the model\n n = train_labels.shape[1]\n\t#one_hot y\n y_train=np.array(convert_to_onehot(train_labels[:, i], 4))\n y_val=np.array(convert_to_onehot(val_labels[:, i], 4))\n history = new_model.fit(train_indices, y_train, validation_data=(val_indices, y_val),class_weight=class_weight, batch_size = 64, epochs=20, verbose=2)\n print(new_model.summary())'''\n\n if i == 1 or i == 5:\n lunit = 256\n DROPOUT=0.2\n RDROP = 0.2\n LR = 0.01\n DECAY = 1.6/60000\n BCHSIZE = 64\n else:\n lunit = 256\n DROPOUT=0.2\n RDROP = 0.2\n LR = 0.001\n DECAY = 0\n BCHSIZE = 32\n\n model = Sequential()\n\t#model.add(Input(shape=(max_length,), dtype='int32'))\n model.add(Embedding(vocab_len, emb_dim, input_length=max_length, weights=[embedding_matrix], trainable=False))\n model.add(LSTM(lunit, dropout=DROPOUT, recurrent_dropout=RDROP,return_sequences=True))\n model.add(LSTM(lunit, dropout=DROPOUT, recurrent_dropout=RDROP,return_sequences=False))\n #model.add(Flatten())\n model.add(Dense(4))\n model.add(BatchNormalization())\n model.add(Activation('softmax'))\n # compile the model\n adam = optimizers.Adam(lr=LR, beta_1=0.9, beta_2=0.999, epsilon=1e-8, decay=DECAY, amsgrad=True)\n model.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['acc'])\n # summarize the model\n print(model.summary())\n # fit the model\n n = train_labels.shape[1]\n #one_hot y\n y_train=np.array(convert_to_onehot(train_labels[:, i], 4))\n y_val=np.array(convert_to_onehot(val_labels[:, i], 4))\n\t#print(y)\n\t#val_f1 = f1(y_val, model.predict(val_indices, verbose = 2))\n early_stopping =EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=False)\n history = model.fit(train_indices, y_train, validation_data=(val_indices, y_val),class_weight=class_weight, batch_size = BCHSIZE, epochs=20, verbose=2, callbacks = [early_stopping])\n\n model.save(\"/scratch/users/qingyin/output/\" +str(i) + 'th retrain w2v epoch20 model.h5')\n print(\"complete saving model \" + str(i))\n \n\t# Plot training & validation accuracy values\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title(str(i)+'th Model accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.savefig(str(i)+'_retrain_acc_e20_ctn.png')\n\n# Plot training & validation loss values\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title(str(i)+'th Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.savefig(str(i)+'_retrain_loss_e20_ctn.png')\n\t# evaluate the model\n y_test=np.array(convert_to_onehot(test_labels[:, i], 4))\n y_test_pred = model.predict(test_indices, verbose=2)\n\t#print(str(i)+\"th y_test_pred shape: \")\n\t#print(y_test_pred.shape)\n\t#print(y_test_pred)\n f1_test = f1(y_test, y_test_pred)\n logger.info(str(i)+\"th f1 score: \")\n print(str(i)+\"th weighted f1 score: \")\n print(f1_test)\n\t#logger.info(f1_test)\n\n\t#logger.info(\"model \"+str(i)+ model.metrics_names)\n scores = model.evaluate(test_indices, y_test, verbose=2)\n logger.info(\"model \"+str(i) + \":\")\n print(\"model \"+str(i) + \"metrics:\")\n print(model.metrics_names)\n print(scores)\n\t#print(str(i)+'th model w2v '+'Accuracy: %f' % (accuracy*100))\n\t#logger.info(str(i)+'th model tenc '+'Accuracy: %f' % (accuracy*100))\n\t#logger.info(str(i)+'th model tenc f1_score:' + f1_score(y_test, y_test_pred))\n logger.info(\"complete train model\" + str(i))\n del model\n\t#model[i] = model #store model to dict\n\nnum_cores = multiprocessing.cpu_count()\nParallel(n_jobs=num_cores)(delayed(loopone)(i) for i in columns)\nlogger.info(\"complete train model\")\n","sub_path":"Continue_w2v.py","file_name":"Continue_w2v.py","file_ext":"py","file_size_in_byte":7615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"130806371","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom ds_utils.imports import *\n\n\n# In[4]:\n\ndata = pd.read_csv('data/south_park.csv')\n\n\n# In[36]:\n\ndata.head()\n\n\n# In[50]:\n\ncharacter_lines = data.Character.value_counts()\n\n\n# In[51]:\n\ncharacters = character_lines.index.values\n\n\n# In[52]:\n\ncharacters\n\n\n# In[61]:\n\ncharacters_ind = dict((c, i) for i,c in enumerate(characters))\nind_characters = dict((i, c) for i,c in enumerate(characters))\n\n\n# In[57]:\n\ncharacters_idx = [characters_ind[c] for c in data['Character']]\n\n\n# In[70]:\n\nlines = ' '.join(data['Line'])\n\n\n# In[72]:\n\nlines[:100]\n\n\n# In[73]:\n\nfrom nltk.tokenize import word_tokenize\n\n\n# In[74]:\n\nlines_tokenized = word_tokenize(lines)\n\n\n# In[80]:\n\nfrom collections import Counter\n\n\n# In[87]:\n\ntoken_count = dict(Counter(lines_tokenized))\n\n\n# In[89]:\n\ntoken_big = [k for k,v in token_count.items() if v>500]\n\n\n# In[90]:\n\ntoken_big\n\n\n# In[78]:\n\nwords = list(set(lines_tokenized))\n\n\n# In[79]:\n\nwords\n\n","sub_path":"predict_character.py","file_name":"predict_character.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"136088190","text":"\"\"\"\nButtons allow users to execute actions with a single tap\n\"\"\"\n\nfrom kivycupertino.uix.label import CupertinoLabel\nfrom kivycupertino.uix.symbol import CupertinoSymbol\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.properties import StringProperty, BooleanProperty, ColorProperty\nfrom kivy.lang.builder import Builder\n\n__all__ = [\n 'CupertinoButton',\n 'CupertinoSystemButton',\n 'CupertinoSymbolButton'\n]\n\nBuilder.load_string(f\"\"\"\n:\n font_size: 17\n color: root.text_color\n \n canvas.before:\n Color:\n rgba: root.color_down if self.state == 'down' else root.color_disabled if root.disabled else root.color_normal\n RoundedRectangle:\n radius: self.height/5,\n size: self.size\n pos: self.pos\n\n:\n color: root.color_down if self.state == 'down' else root.color_disabled if root.disabled else root.color_normal\n\n:\n color: root.symbol_color\n \n canvas.before:\n Color:\n rgba: root.background_down if self.state == 'down' else root.background_disabled if root.disabled else root.background_normal\n Rectangle:\n size: self.size\n pos: self.pos\n\"\"\")\n\n\nclass CupertinoButton(ButtonBehavior, CupertinoLabel):\n \"\"\"\n iOS style button\n\n .. image:: ../_static/button.gif\n \"\"\"\n\n text = StringProperty(' ')\n \"\"\"\n A :class:`~kivy.properties.StringProperty` defining the text of\n :class:`~kivycupertino.uix.button.CupertinoButton`\n \"\"\"\n\n disabled = BooleanProperty(False)\n \"\"\"\n A :class:`~kivy.properties.BooleanProperty` defining if\n :class:`~kivycupertino.uix.button.CupertinoButton` is disabled\n \"\"\"\n\n color_normal = ColorProperty([0, 0.5, 1, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the background color of\n :class:`~kivycupertino.uix.button.CupertinoButton` when not pressed or disabled\n \"\"\"\n\n color_down = ColorProperty([0, 0.15, 0.8, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the background color of\n :class:`~kivycupertino.uix.button.CupertinoButton` when pressed\n \"\"\"\n\n color_disabled = ColorProperty([0, 0.35, 0.7, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the background color of\n :class:`~kivycupertino.uix.button.CupertinoButton` when disabled \n \"\"\"\n\n text_color = ColorProperty([1, 1, 1, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the color of text of\n :class:`~kivycupertino.uix.button.CupertinoButton` \n \"\"\"\n\n\nclass CupertinoSystemButton(ButtonBehavior, CupertinoLabel):\n \"\"\"\n iOS style System Button\n\n .. image:: ../_static/system_button.gif\n \"\"\"\n\n text = StringProperty(' ')\n \"\"\"\n A :class:`~kivy.properties.StringProperty` defining the text of\n :class:`~kivycupertino.uix.button.CupertinoSystemButton`\n \"\"\"\n\n disabled = BooleanProperty(False)\n \"\"\"\n A :class:`~kivy.properties.BooleanProperty` defining if\n :class:`~kivycupertino.uix.button.CupertinoSystemButton` is disabled\n \"\"\"\n\n color_normal = ColorProperty([0.05, 0.5, 0.95, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the color of\n :class:`~kivycupertino.uix.button.CupertinoSystemButton` when not pressed or disabled\n \"\"\"\n\n color_down = ColorProperty([0, 0.15, 0.3, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the color of\n :class:`~kivycupertino.uix.button.CupertinoSystemButton` when disabled\n \"\"\"\n\n color_disabled = ColorProperty([0, 0.3, 0.4, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the color of\n :class:`~kivycupertino.uix.button.CupertinoSystemButton` when disabled\n \"\"\"\n\n\nclass CupertinoSymbolButton(ButtonBehavior, CupertinoSymbol):\n \"\"\"\n iOS style button that displays an symbol\n\n .. image:: ../_static/symbol_button.gif\n \"\"\"\n\n symbol = StringProperty(' ')\n \"\"\"\n A :class:`~kivy.properties.StringProperty` defining the symbol of\n :class:`~kivycupertino.uix.button.CupertinoSymbolButton`\n \"\"\"\n\n disabled = BooleanProperty(False)\n \"\"\"\n A :class:`~kivy.properties.BooleanProperty` defining if\n :class:`~kivycupertino.uix.button.CupertinoSymbolButton` is disabled\n \"\"\"\n\n symbol_color = ColorProperty([0, 0, 0, 1])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty`defining the color of the icon of\n :class:`~kivycupertino.uix.button.CupertinoSymbolButton` when not pressed or disabled\n \"\"\"\n\n background_normal = ColorProperty([0, 0, 0, 0])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty`defining the background color of\n :class:`~kivycupertino.uix.button.CupertinoSymbolButton` when not pressed or disabled\n \"\"\"\n\n background_down = ColorProperty([0, 0, 0, 0.3])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the background color of\n :class:`~kivycupertino.uix.button.CupertinoSymbolButton` when pressed\n \"\"\"\n\n background_disabled = ColorProperty([0, 0, 0, 0.2])\n \"\"\"\n A :class:`~kivy.properties.ColorProperty` defining the background color of\n :class:`~kivycupertino.uix.button.CupertinoSymbolButton` when disabled\n \"\"\"\n","sub_path":"kivycupertino/uix/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"77165769","text":"from django.shortcuts import render\r\nfrom django.urls import reverse_lazy\r\nfrom django.views.generic import CreateView\r\nfrom .forms import AddEmployeeSkillScore\r\nfrom .models import *\r\nimport plotly.graph_objects as go\r\nimport plotly.offline as opy\r\n\r\n\r\nclass AddEmployeeSkillScoreView(CreateView):\r\n model = EmployeeSkillChart\r\n form_class = AddEmployeeSkillScore\r\n success_url = reverse_lazy('add_employee_skill')\r\n template_name = \"hr/add_skill_form.html\"\r\n\r\n\r\ndef generate_skill_chart(request):\r\n categories = ['Technology Know How', 'Growth', 'Ideas', 'Skills', 'Vision', 'Problem Solving']\r\n emp = EmployeeSkillChart.objects.all()\r\n fig = go.Figure()\r\n\r\n for i in emp:\r\n employee_id = i.Employee_id\r\n employee = Employee.objects.get(employee_id=employee_id)\r\n\r\n fig.add_trace(go.Scatterpolar(\r\n r=[i.technology, i.growth, i.ideas, i.skill, i.vision, i.problem_solving],\r\n theta=categories,\r\n fill='toself',\r\n name=employee.employee_name\r\n ))\r\n\r\n fig.update_layout(\r\n polar=dict(\r\n radialaxis=dict(\r\n visible=True,\r\n range=[0, 10],\r\n\r\n )),\r\n showlegend=True\r\n )\r\n graph = fig.to_html(full_html=False, default_height=500, default_width=700)\r\n\r\n return render(request, \"hr/trial.html\", context={'graph': graph})\r\n","sub_path":"MAS/hr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"619461998","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.95303.com/production/details.html?productionId=15&type=3\"\nhtml = webdriver.Chrome()\nhtml.get(url)\n\n#selenium的page_source方法可以直接获取到页面源码\nsoup = BeautifulSoup(html.page_source, 'lxml')\n\nquestion = soup.find_all('div', 'question')\nanswer = soup.find_all('div', 'answer')\n\nQA = []\nfor i in range(len(question)):\n QA += [[question[i].text , answer[i].text]]\n\n#存储在txt文本中\nfile = open('C:/Users/xiaohaixia/Desktop/111.txt', 'w')\nfor i in range(len(QA)):\n file.write('Q: ' + QA[i][0] + '\\n')\n file.write('A: ' + QA[i][1] + '\\n')\n\t\n\t\n#存储在csv文件中\n# df = pd.DataFrame(QA)\n# df.columns = ['question','answer']\n#df.to_csv('C:/Users/xiaohaixia/Desktop/result.csv',index=False,sep=',',encoding='gbk')\ndf = pd.DataFrame(QA, columns = ['question','answer'])\ndf.to_csv('C:/Users/xiaohaixia/Desktop/result.csv',index=False,sep=',',encoding='gbk')\n\nhtml.close()","sub_path":"Automation_Code/爬虫/study/Crawl_QA.py","file_name":"Crawl_QA.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"35982380","text":"\n\n# CLUSTERING \n#import matplotlib \n#matplotlib.use('TkAgg') \n#import matplotlib.pyplot as plt \n#from matplotlib.colors import ListedColormap\n#from sklearn import metrics\n#from sklearn.cluster import KMeans\n#from sklearn.datasets import load_digits\n#from sklearn.decomposition import PCA\n#from sklearn.preprocessing import scale\n\n\n\n\n\n# crf.state_features_\n\n# CLUSTERING: \ndef clustering():\n sequence_length_sec = 15\n sub_seq_length_sec = 15\n data_frequency = 4\n n_neighbors = 15\n no_lable_vs_lable = 0.7\n training_vs_testing = 0.8\n # Sort and feature extract:\n training_data = load_q_data(no_lable_vs_lable)\n sequences,labels = data2seq(training_data,sequence_length_sec*data_frequency)\n norm_sequences,normalization_constants = normalize_train(sequences)\n X,y = seq2seqfeatures(norm_sequences, labels, sub_seq_length_sec*data_frequency,False)\n X = [item for sublist in X for item in sublist]\n y = [item for sublist in y for item in sublist]\n X_train,X_test,y_train,y_test = shuffle_and_cut(X,y,training_vs_testing)\n X, y = shuffle(X, y, random_state=0)\n n_samples = len(X)\n n_features = len(X[0])\n n_clusters = len(np.unique(y))\n print(\"n_clusters: %d, \\t n_samples %d, \\t n_features %d\"\n % (n_clusters, n_samples, n_features))\n print(79 * '_')\n print('% 9s' % 'init time inertia homo compl v-meas ARI AMI silhouette')\n score11, score12 = bench_k_means(KMeans(init='k-means++', n_clusters = n_clusters, n_init = 10),\"k-means++\",X,y,n_samples)\n score21, score22 = bench_k_means(KMeans(init='random', n_clusters=n_clusters, n_init=10),\"random\",X,y,n_samples)\n print(79 * '_')\n return\n\n\n\n\ndef bench_k_means(estimator, name, X, y, sample_size):\n t0 = time()\n estimator.fit(X)\n rand_score = metrics.adjusted_rand_score(y, estimator.labels_)\n mutual_info = metrics.adjusted_mutual_info_score(y, estimator.labels_)\n\n print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f' # %.3f'\n % (name, (time() - t0), estimator.inertia_,\n metrics.homogeneity_score(y, estimator.labels_),\n metrics.completeness_score(y, estimator.labels_),\n metrics.v_measure_score(y, estimator.labels_),\n rand_score,\n mutual_info))\n return rand_score,mutual_info\n","sub_path":"oldfiles/old_methods.py","file_name":"old_methods.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"291595972","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def averageOfLevels0(self, root):\n count = []\n res = []\n\n def average(t, i, sum, count):\n if not t:\n return\n if i < len(sum):\n sum[i] = sum[i] + t.val\n count[i] = count[i] + 1\n else:\n sum.append(t.val)\n count.append(1)\n\n average(t.left, i + 1, sum, count)\n average(t.right, i + 1, sum, count)\n\n average(root, 0, res, count)\n for i in range(0, len(res)):\n res[i] = res[i] / count[i]\n\n return res\n\n def averageOfLevels(self, root):\n res = []\n if root is None:\n return res\n levels = [root]\n res.append(float(root.val))\n while levels:\n nextLevel = []\n temp = []\n while levels:\n # As the nodes have to printed from left to right, we should always pop the left node first\n # hence we have the pop(0), so that the first node is popped out\n node = levels.pop(0)\n if node.left:\n # Here we are passing a pointer on to an object in a memory location\n nextLevel.append(node.left)\n # So we have to append the value of the node so that we can present it in desired format\n temp.append(node.left.val)\n if node.right:\n nextLevel.append(node.right)\n temp.append(node.right.val)\n\n if temp:\n s = sum(temp) / float(len(temp))\n res.append(s)\n\n levels = nextLevel\n return res\n\n\ndef stringToTreeNode(input):\n input = input.strip()\n input = input[1:-1]\n if not input:\n return None\n\n inputValues = [s.strip() for s in input.split(',')]\n root = TreeNode(int(inputValues[0]))\n nodeQueue = [root]\n front = 0\n index = 1\n while index < len(inputValues):\n node = nodeQueue[front]\n front = front + 1\n\n item = inputValues[index]\n index = index + 1\n if item != \"null\":\n leftNumber = int(item)\n node.left = TreeNode(leftNumber)\n nodeQueue.append(node.left)\n\n if index >= len(inputValues):\n break\n\n item = inputValues[index]\n index = index + 1\n if item != \"null\":\n rightNumber = int(item)\n node.right = TreeNode(rightNumber)\n nodeQueue.append(node.right)\n return root\n\n\ndef treeNodeToString(root):\n if not root:\n return \"[]\"\n output = \"\"\n queue = [root]\n current = 0\n while current != len(queue):\n node = queue[current]\n current = current + 1\n\n if not node:\n output += \"null, \"\n continue\n\n output += str(node.val) + \", \"\n queue.append(node.left)\n queue.append(node.right)\n return \"[\" + output[:-2] + \"]\"\n\n\ndef main():\n import sys\n def readlines():\n for line in sys.stdin:\n yield line.strip('\\n')\n\n lines = readlines()\n while True:\n try:\n line = next(lines)\n t1 = stringToTreeNode(line)\n\n ret = Solution().averageOfLevels(t1)\n\n print(ret)\n except StopIteration:\n break\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Solutions/637. Average of Levels in Binary Tree/637.py","file_name":"637.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"115133839","text":"#! /usr/bin/python2.7 -u\n# -*- coding: utf-8 -*-\n\n\"\"\"Wrapper for CloudRT ray tracing matlab simulator.\n\nWarning: This is written in python 2.7 for matlab engine compatibility (beurk).\n\nUsage:\n CloudRT.py\n\nArguments:\n\nOptions:\n -h, --help\n\"\"\"\nimport matlab.engine\nimport os\nimport StringIO\nimport tempfile\n\n\nclass CloudRT():\n \"\"\"docstring for CloudRT wrapper\"\"\"\n\n CLOUDRT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"CloudRT_app\")\n\n def __init__(self, resultDir, scenario=\"Plank.json\", quiteMode=False):\n self.resultDir = resultDir\n self.confFile = tempfile.NamedTemporaryFile(suffix='.json').name\n\n self.opt = {}\n if quiteMode:\n self.opt = {\"stdout\": StringIO.StringIO()}\n\n self.eng = matlab.engine.start_matlab()\n self.eng.cd(self.CLOUDRT_DIR)\n\n self.conf = self.eng.initConf(self.confFile, resultDir,\n scenario, **self.opt)\n\n self.setTxPose(0, 0, 0, 0, 0, 0)\n self.setRxPose(0, 0, 0, 0, 0, 0)\n\n def simulate(self, simId):\n self.conf, CTF_Re, CTF_Im = self.eng.simulate(self.conf,\n self.confFile,\n self.resultDir,\n simId,\n nargout=3, **self.opt)\n\n return CTF_Re, CTF_Im\n\n def setTxPose(self, x, y, z, u, v, w):\n self.conf = self.eng.setTxPose(self.conf, self.confFile,\n self.resultDir,\n x, y, z, u, v, w, **self.opt)\n\n def setRxPose(self, x, y, z, u, v, w):\n self.conf = self.eng.setRxPose(self.conf, self.confFile,\n self.resultDir,\n x, y, z, u, v, w, **self.opt)\n","sub_path":"myTools/simulator/CloudRT.py","file_name":"CloudRT.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"623841714","text":"# Author: anonymous, found on www\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n# this plots 50 random (x,y) points between (0,0) and (1,1)\n# each with random radius up to 15 point size \n\nN = 50\n\n# get and print the x values\nx = np.random.rand(N)\nprint('\\nx', x)\n\n# get and print the y values\ny = np.random.rand(N)\nprint('\\ny', y)\n\n# calculate and print the sizes of the circles\narea = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses\nprint('\\narea', area)\n\n# plot the 50 circles\nplt.scatter(x, y, s=area, alpha=0.5)\nplt.show()","sub_path":"SamplePlot.py","file_name":"SamplePlot.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"112192902","text":"import pymysql\nimport time\n\ndef get_conn(db):\n return pymysql.connect(\n # host='35.221.66.161',\n host = '127.0.0.1',\n user='dooo',\n password='dooo!',\n port=3306,\n db=db,\n charset='utf8')\n\n\nisStart = True\ndef save(sql_truncate, sql_insert, lst):\n try:\n conn = get_conn('melondb')\n conn.autocommit = False\n cur = conn.cursor()\n global isStart\n if isStart:\n cur.execute(sql_truncate)\n isStart = False\n\n cur.executemany(sql_insert, lst)\n conn.commit()\n print(\"Affected RowCount is\", cur.rowcount, \"/\", len(lst))\n\n except Exception as err:\n conn.rollback()\n print(\"Error!!\", err)\n\n finally:\n try:\n cur.close()\n except:\n print(\"Error on close cursor\")\n\n try:\n conn.close()\n except Exception as err2:\n print(\"Fail to connect!!\", err2)","sub_path":"20190129exam/naverAPI_SQL.py","file_name":"naverAPI_SQL.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"60088131","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/7/28 18:15\n# @Author : pankui\n# @Site : https://github.com/pankui\n# @File : enum_demo.py\n# @Software: PyCharm\n\n\nfrom enum import Enum\n\nMonth = Enum(\"Month\",(\"Jan\",\"Feb\"))\n\nfor name,member in Month.__members__.items():\n print(name,'=>',member,',',member.value)\n\n\n\nfrom enum import Enum,unique\n\n@unique\nclass Weekday(Enum):\n Sum = 0\n Mon = 1\n Tue = 2\n Wed = 3\n Thu = 4\n Fri = 5\n Sat = 6\n\n\nfor name,member in Weekday.__members__.items():\n print(name)\n\n\nday1 = Weekday.Mon\nprint(day1.name)\n\nprint(day1.value)\n\n\n\n\n\n\nprint(Weekday['Tue'])","sub_path":"python-learn/basis/object-oriented_programming/enum_demo.py","file_name":"enum_demo.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"641736358","text":"#导入需要的模块\nimport os\nimport re\nimport time\nimport random\n\nimport gui\nimport functions\nimport cartoonmad\nfrom setting import Setting\n\n\n#目前爬一张图片的时间在2~4秒左右,可以使用异步之类的操作来提高下载速度,可是下载频率高了后可能会被该网站视为爬虫,要改进的话只能使用多个ip。\n#获取某本漫画的界面源代码,并进行转码,由于网站使用big5编码,所以此处也这么用,否则会乱码\ninfo = gui.Get_info()\ninput_url = info.url\ninput_folder_path = info.folder_path\n\n\n\n\n\ndownload_info = Setting()\nurl_return = functions.get_html_resource(input_url,download_info.headers)\nurl_return.encoding = cartoonmad.html_encoding()\n\ninfo_dict = cartoonmad.extract_comic_info(url_return)\nimage_url_prefixion = cartoonmad.get_image_url_prefixion(input_url) \ntotal_info_dict = cartoonmad.form_image_url(info_dict,input_folder_path,image_url_prefixion) \ntm = gui.Choose_chapter(total_info_dict.keys())\nchoosed_chapter_list = tm.choosed_chapter_list \n\nprint(choosed_chapter_list)\n\nfor chapter_info,page_url in total_info_dict.items():\n if not chapter_info in choosed_chapter_list:\n continue\n folder_path = input_folder_path+'/'+chapter_info \n folder_status = os.path.exists(folder_path)\n if not folder_status :\n os.makedirs(folder_path) #创建每一话文件夹的路径,已存在的话跳过\n pages = len(page_url.keys()) #用于提示进度\n print('目前正在下载 '+chapter_info+'----------------------------------') \n image_list = os.listdir(folder_path+'/')\n image_total_num = len(image_list) #确定该文件下已有多少张图片\n print('进度-------------------------'+' '+str(image_total_num)+' / '+str(pages)) \n for page,image_url in page_url.items():\n try:\n image_path = folder_path+'/'+chapter_info+'-'+str(page)+'.jpg' \n image_status = os.path.exists(image_path)\n if not image_status: #检测图片是否已下载,未下载的话会进行下载,否则会跳过\n image = functions.get_html_resource(image_url,download_info.headers)\n functions.save_image(image_path,image)\n else:\n print(chapter_info+'-'+str(page)+'.jpg'+' 已下载')\n continue\n except:\n print('\\n异常发生,暂停10秒后继续>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\n print('此异常会导致有一张图片的下载被跳过,重新运行此程序后便可补上这张图片>>>>>>>>>>>>>>>>>>>>>\\n')\n time.sleep(10)\n continue\n else:\n print(chapter_info+'-'+str(page)+'.jpg'+' 下载完成')\n time.sleep(random.uniform(0.7,2))\n print(chapter_info+' 已完成下载')\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":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"581348823","text":"from django.shortcuts import redirect\n\nclass AdminGroupRequired:\n redirect_url = ''\n\n def dispatch(self, request, *args, **kwargs):\n if request.user.has_perms(\n [\n 'productsapp.add_product',\n 'productsapp.change_product',\n 'productsapp.delete_product',\n 'categoriesapp.add_category',\n 'categoriesapp.change_category',\n 'categoriesapp.delete_category',\n ]\n ):\n return super(AdminGroupRequired, self).dispatch(request, *args, **kwargs)\n return redirect(self.redirect_url)\n","sub_path":"myshop/customers/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"195392459","text":"from preprocessing import parse_annotation,BatchGenerator\nfrom st_utils import BatchGenerator_for_USTB\nimport json\nimport cv2\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\n\nif __name__ == \"__main__\":\n config_path = './config_USTB.json'\n with open(config_path) as config_buffer:\n config = json.loads(config_buffer.read())\n train_imgs, train_labels = parse_annotation(config['train']['train_annot_folder'],\n config['train']['train_image_folder'],\n config['model']['labels'])\n generator_config = {\n 'IMAGE_H' : config['model']['input_size'],\n 'IMAGE_W' : config['model']['input_size'],\n 'GRID_H' : 13,\n 'GRID_W' : 13,\n 'BOX' : len(config['model']['anchors'])//2,#取整运算\n 'LABELS' : config['model']['labels'],\n 'CLASS' : len(config['model']['labels']),\n 'ANCHORS' : config['model']['anchors'],\n 'BATCH_SIZE' : config['train']['batch_size'],\n 'TRUE_BOX_BUFFER' : config['model']['max_box_per_image'],\n }\n generator = BatchGenerator_for_USTB(images=train_imgs,config=generator_config,shuffle=False)\n\n def test_load_image():\n result = generator.load_image(2)\n cv2.imshow('img_0', result['aug']['image'])\n print(result['aug']['annotation'])\n def test_getitem():\n # print(train_imgs,train_labels)\n generator.debug = False\n d = generator.__getitem__(0)\n # image = d[0][0][2].astype('uint8')\n # cv2.imshow('output',image)\n\n #绘制bbox需要先project on 已padding的黑边图像,然后再on到原图\n # test load image\n\n # test_getitem()\n test_load_image()\n\n cv2.waitKey(0)\n\n","sub_path":"keras-yolo2/test/test_Generator.py","file_name":"test_Generator.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"388695216","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\" \nfinding the frequency of specific words in texts in the tibetan canon for Kangyur only\n\"\"\"\n\nimport re\nimport os\nimport json\n\npath = os.environ['HOME']+'/segmented-tibetan/files/'\n\n# WORD_PATTERN = r\"([pm]a ning|'dod 'gro)\"\n\nWORD_PATTERN = r\"(mtshan gnyis [mp]a)\"\n\ntotalworddict = {}\n\nCOLLECTION_PATTERN = r\"^([A-Z]+[0-9]+)\"\n\n\nfor root, dirs, files in os.walk(path):\n for name in files:\n filetext = open(root+\"/\"+name).read()\n collectionname = re.search(COLLECTION_PATTERN, name[:-5]).group()\n category = collectionname\n\n jsonobject = json.loads(filetext)\n for item in jsonobject.items():\n cleaneditem = re.sub(r'[+–/]', ' ', item[1])\n if re.search(WORD_PATTERN, cleaneditem):\n cleanedword = re.search(WORD_PATTERN, cleaneditem.strip()).group()\n if cleanedword not in totalworddict: \n if category.startswith('K'):\n category_nr = int(category[1:])\n totalworddict[cleanedword] = [1,0,0,0,0,0,0,0,0,0,0,0,0,0]\n totalworddict[cleanedword][category_nr] = 1\n else:\n if category.startswith('K'):\n category_nr = int(category[1:])\n totalworddict[cleanedword][0] += 1\n totalworddict[cleanedword][category_nr] += 1\n\nfilepath_Out = open('frequency.json','w', encoding='utf8')\nfilepath_Out.write(json.dumps(totalworddict, ensure_ascii=False, indent=0))\n\n","sub_path":"wordfrequency/wordfrequency4_Kg.py","file_name":"wordfrequency4_Kg.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"573102848","text":"\"\"\"Module for data transformations and internal conventions.\"\"\"\n\nTEAM_TRANSLATIONS = {\n \"Tigers\": \"Richmond\",\n \"Blues\": \"Carlton\",\n \"Demons\": \"Melbourne\",\n \"Giants\": \"GWS\",\n \"GWS Giants\": \"GWS\",\n \"Greater Western Sydney\": \"GWS\",\n \"Suns\": \"Gold Coast\",\n \"Bombers\": \"Essendon\",\n \"Swans\": \"Sydney\",\n \"Magpies\": \"Collingwood\",\n \"Kangaroos\": \"North Melbourne\",\n \"Crows\": \"Adelaide\",\n \"Bulldogs\": \"Western Bulldogs\",\n \"Footscray\": \"Western Bulldogs\",\n \"Dockers\": \"Fremantle\",\n \"Power\": \"Port Adelaide\",\n \"Saints\": \"St Kilda\",\n \"Eagles\": \"West Coast\",\n \"Lions\": \"Brisbane\",\n \"Cats\": \"Geelong\",\n \"Hawks\": \"Hawthorn\",\n \"Adelaide Crows\": \"Adelaide\",\n \"Brisbane Lions\": \"Brisbane\",\n \"Brisbane Bears\": \"Brisbane\",\n \"Gold Coast Suns\": \"Gold Coast\",\n \"Geelong Cats\": \"Geelong\",\n \"West Coast Eagles\": \"West Coast\",\n \"Sydney Swans\": \"Sydney\",\n # Monash footy tipping team names\n \"G_W_Sydney\": \"GWS\",\n \"W_Bulldogs\": \"Western Bulldogs\",\n \"P_Adelaide\": \"Port Adelaide\",\n \"Gold_Coast\": \"Gold Coast\",\n \"St_Kilda\": \"St Kilda\",\n \"W_Coast\": \"West Coast\",\n}\n\nVENUE_CITIES = {\n # AFL Tables venues\n \"Football Park\": \"Adelaide\",\n \"S.C.G.\": \"Sydney\",\n \"Windy Hill\": \"Melbourne\",\n \"Subiaco\": \"Perth\",\n \"Moorabbin Oval\": \"Melbourne\",\n \"M.C.G.\": \"Melbourne\",\n \"Kardinia Park\": \"Geelong\",\n \"Victoria Park\": \"Melbourne\",\n \"Waverley Park\": \"Melbourne\",\n \"Princes Park\": \"Melbourne\",\n \"Western Oval\": \"Melbourne\",\n \"W.A.C.A.\": \"Perth\",\n \"Carrara\": \"Gold Coast\",\n \"Gabba\": \"Brisbane\",\n \"Docklands\": \"Melbourne\",\n \"York Park\": \"Launceston\",\n \"Manuka Oval\": \"Canberra\",\n \"Sydney Showground\": \"Sydney\",\n \"Adelaide Oval\": \"Adelaide\",\n \"Bellerive Oval\": \"Hobart\",\n \"Marrara Oval\": \"Darwin\",\n \"Traeger Park\": \"Alice Springs\",\n \"Perth Stadium\": \"Perth\",\n \"Stadium Australia\": \"Sydney\",\n \"Wellington\": \"Wellington\",\n \"Lake Oval\": \"Melbourne\",\n \"East Melbourne\": \"Melbourne\",\n \"Corio Oval\": \"Geelong\",\n \"Junction Oval\": \"Melbourne\",\n \"Brunswick St\": \"Melbourne\",\n \"Punt Rd\": \"Melbourne\",\n \"Glenferrie Oval\": \"Melbourne\",\n \"Arden St\": \"Melbourne\",\n \"Olympic Park\": \"Melbourne\",\n \"Yarraville Oval\": \"Melbourne\",\n \"Toorak Park\": \"Melbourne\",\n \"Euroa\": \"Euroa\",\n \"Coburg Oval\": \"Melbourne\",\n \"Brisbane Exhibition\": \"Brisbane\",\n \"North Hobart\": \"Hobart\",\n \"Bruce Stadium\": \"Canberra\",\n \"Yallourn\": \"Yallourn\",\n \"Cazaly's Stadium\": \"Cairns\",\n \"Eureka Stadium\": \"Ballarat\",\n \"Blacktown\": \"Sydney\",\n \"Jiangwan Stadium\": \"Shanghai\",\n \"Albury\": \"Albury\",\n \"Riverway Stadium\": \"Townsville\",\n # Footywire venues\n \"AAMI Stadium\": \"Adelaide\",\n \"ANZ Stadium\": \"Sydney\",\n \"UTAS Stadium\": \"Launceston\",\n \"Blacktown International\": \"Sydney\",\n \"Blundstone Arena\": \"Hobart\",\n \"Domain Stadium\": \"Perth\",\n \"Etihad Stadium\": \"Melbourne\",\n \"GMHBA Stadium\": \"Geelong\",\n \"MCG\": \"Melbourne\",\n \"Mars Stadium\": \"Ballarat\",\n \"Metricon Stadium\": \"Gold Coast\",\n \"Optus Stadium\": \"Perth\",\n \"SCG\": \"Sydney\",\n \"Spotless Stadium\": \"Sydney\",\n \"TIO Stadium\": \"Darwin\",\n \"Westpac Stadium\": \"Wellington\",\n \"Marvel Stadium\": \"Melbourne\",\n \"Canberra Oval\": \"Canberra\",\n \"TIO Traeger Park\": \"Alice Springs\",\n # Correct spelling is 'Traeger', but footywire.com is spelling it 'Traegar' in its\n # fixtures, so including both in case they eventually fix the misspelling\n \"TIO Traegar Park\": \"Alice Springs\",\n}\n\nDEFUNCT_TEAM_NAMES = [\"Fitzroy\", \"University\"]\nTEAM_NAMES = sorted(DEFUNCT_TEAM_NAMES + list(set(TEAM_TRANSLATIONS.values())))\nVENUES = list(set(VENUE_CITIES.keys()))\n","sub_path":"backend/project/settings/data_config.py","file_name":"data_config.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"583638338","text":"from .command import Command\n\nclass Add(Command):\n '''\n Add a member the group\n Params\n members: array - objects described below. nickname is required. You must use one of the following identifiers: user_id, phone_number, or email.\n object\n nickname (string) required\n user_id (string)\n phone_number (string)\n email (string)\n guid (string)\n '''\n\n def __init__(self, groupmeAccessToken, groupId, **kwargs):\n self.args = kwargs\n self.groupId = groupId\n super(Add, self).__init__(groupmeAccessToken, 'POST') \n\n def createUrl(self):\n print(self.groupId)\n return self.URL_BASE + '/groups/' + str(self.groupId) + '/members/add' + self.TOKEN_QUERY_STRING\n \n def createLoad(self):\n load = {}\n members = []\n array = []\n for key, value in self.args.items():\n if key == 'members':\n members = value\n hasNickname = False\n hasRequiredFields = False\n for member in members:\n if 'nickname' in member:\n hasNickname = True\n if 'user_id' in member:\n hasRequiredFields = True\n if 'phone_number' in member:\n hasRequiredFields = True\n if 'email' in member:\n hasRequiredFields = True\n if hasNickname and hasRequiredFields:\n array.append(member)\n load['members'] = array\n return load\n\n def makeCall(self):\n return super(Add, self).makeCall()\n\n def prepareMemberObject(self, nickname=None, user_id=None, phone_number=None, email=None):\n '''A helper method for preparing Member objects which can be passed as array members to the Add command'''\n member = {}\n if nickname is None:\n raise Exception(\"Nickname is required to create Member object\")\n else:\n member['nickname'] = nickname\n if user_id is not None:\n member['user_id'] = user_id\n if phone_number is not None:\n member['phone_number'] = phone_number\n if email is not None:\n member['email'] = email\n return member\n \n\nclass Remove(Command):\n '''\n Remove a member from a grup\n NOTE: Creator cannot be removed\n Params\n membership_id: string — Please note that this isn't the same as the user ID. In the members key in the group JSON, this is the id value, not the user_id.\n '''\n\n def __init__(self, groupmeAccessToken, groupId, membership_id=None, **kwargs):\n self.args = kwargs\n self.groupId = groupId\n self.membership_id = membership_id\n super(Remove, self).__init__(groupmeAccessToken, 'POST') \n \n def createUrl(self): \n if self.membership_id is None:\n raise Exception('membership_id is required') \n url = self.URL_BASE + '/groups/' + str(self.groupId) + '/members/' + str(self.membership_id) + '/remove' + self.TOKEN_QUERY_STRING\n return url\n \n def makeCall(self):\n return super(Remove, self).makeCall()\n\n\nclass Update(Command):\n '''\n Update YOUR nickname in a group. The nickname must be between 1 and 50 chars\n Params\n nickname: string - YOUR new nickname\n '''\n\n def __init__(self, groupmeAccessToken, groupId, nickname=None, **kwargs):\n self.args = kwargs\n self.groupId = groupId\n self.nickname = nickname\n super(Update, self).__init__(groupmeAccessToken, 'POST') \n\n def createUrl(self):\n return self.URL_BASE + '/groups/' + str(self.groupId) + '/memberships/update' + self.TOKEN_QUERY_STRING\n\n def createLoad(self):\n load = {}\n load['membership'] = {'nickname': self.nickname}\n return load\n\n def makeCall(self):\n super(Update, self).makeCall()\n\n\n","sub_path":"GroupmeClient/ApiWrapper/membersCommands.py","file_name":"membersCommands.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"578139486","text":"from Products.CMFCore.utils import getToolByName\nfrom Products.PluggableAuthService.interfaces.plugins import IUserEnumerationPlugin\nfrom Products.Carousel.utils import unregisterViewlet\n\n\ndef setupVarious(context):\n if context.readDataFile(\"deployment-various.txt\") is None:\n return\n\n logger=context.getLogger(\"Products.PloneOrg\")\n site=context.getSite()\n\n pas=getToolByName(site, \"acl_users\")\n pas.ZCacheable_setManagerId(manager_id=\"MemcachedManager\")\n\n plugins=pas._getOb( 'plugins' )\n enumerators=plugins.listPluginIds(IUserEnumerationPlugin)\n # mutable_properties is very slow and we only need to search for\n # userids in source_users or in LDAP.\n for plugin in ('mutable_properties',):\n if plugin in enumerators:\n plugins.deactivatePlugin(IUserEnumerationPlugin, plugin)\n\n gtool = getToolByName(site, 'portal_groups', None)\n props = getToolByName(site, 'portal_properties', None)\n for group in props.site_properties.getProperty('allowedPublicGroups'):\n gtool.addGroup(group)\n\n # make sure the default Carousel viewlet is unregistered\n unregisterViewlet()\n","sub_path":"src/Products/PloneOrg/setuphandlers.py","file_name":"setuphandlers.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"165854827","text":"import random\nfrom collections import deque\nfrom itertools import combinations\n\nclass User:\n def __init__(self, name):\n self.name = name\n\nclass SocialGraph:\n def __init__(self):\n self.last_id = 0\n self.users = {}\n self.friendships = {}\n\n def add_friendship(self, user_id, friend_id):\n \"\"\"\n Creates a bi-directional friendship\n \"\"\"\n if user_id == friend_id:\n print(\"WARNING: You cannot be friends with yourself\")\n elif friend_id in self.friendships[user_id] or user_id in self.friendships[friend_id]:\n print(\"WARNING: Friendship already exists\")\n else:\n self.friendships[user_id].add(friend_id)\n self.friendships[friend_id].add(user_id)\n\n def add_user(self, name):\n \"\"\"\n Create a new user with a sequential integer ID\n \"\"\"\n self.last_id += 1 # automatically increment the ID to assign the new user\n self.users[self.last_id] = User(name)\n self.friendships[self.last_id] = set()\n\n def populate_graph(self, num_users, avg_friendships):\n \"\"\"\n Takes a number of users and an average number of friendships\n as arguments\n\n Creates that number of users and a randomly distributed friendships\n between those users.\n\n The number of users must be greater than the average number of friendships.\n \"\"\"\n # Reset graph\n self.last_id = 0\n self.users = {}\n self.friendships = {}\n\n # Add users and edges between a user and themself \n for i in range(1, num_users+1):\n self.add_user(f\"User {i}\")\n self.friendships[i] = set([i])\n\n # Create friendships\n # plan:\n # create a list with all possible friendship combos\n # shuffle the list, then get the first n elements\n\n #### O(n^2)\n # possible_friendships = []\n # for user_id in self.users:\n # for friend_id in range(user_id + 1, self.last_id + 1):\n # possible_friendships.append((user_id, friend_id))\n\n #### O(nCk) or O(n choose k). k=2 in this case. ppl usually call k \"r\",\n # because the default param name is called \"r\" --> itertools.combinations(iterable, r)\n # possible_friendships = list(combinations(self.users, 2))\n\n # random.shuffle(possible_friendships)\n\n # Create n friendships where n = avg_frindships * num_users // 2\n # avg_frindships = total_friendships / num_users\n # total_frindships = avg_friendships * num_users\n # for i in range(num_users * avg_friendships // 2):\n # f1, f2 = possible_friendships[i]\n # self.add_friendship(f1, f2)\n\n #### O(n)\n def guess(): return random.randint(1, self.last_id)\n\n for _ in range(num_users * avg_friendships // 2):\n added = False\n while not added:\n f1, f2 = (guess(), guess())\n if f2 not in self.friendships[f1]:\n self.add_friendship(f1, f2)\n added = True\n\n \n\n\n def get_all_social_paths(self, user_id):\n \"\"\"\n Takes a user's user_id as an argument\n\n Returns a dictionary containing every user in that user's\n extended network with the shortest friendship path between them.\n\n The key is the friend's ID and the value is the path.\n \"\"\"\n visited = {} # Note that this is a dictionary, not a set\n # do a bfs\n # add each path to visited dict as value, and each last fren in path as key\n q = deque([[user_id]])\n while len(q)>0:\n path = q.pop()\n v = path[-1]\n if v not in visited:\n visited[v] = path\n for n in self.friendships[v]:\n q.appendleft(path + [n])\n return visited\n\n\nif __name__ == '__main__':\n sg = SocialGraph()\n sg.populate_graph(10, 2)\n print(sg.friendships)\n connections = sg.get_all_social_paths(1)\n print(connections)\n\n# 3. Questions\n# To create 100 users with an average of 10 friends each, \n# how many times would you need to call add_friendship()? Why?\n# 500 times, there's 500 pairs of friends. add_frindhsip() takes care of on pair each time\n\n# If you create 1000 users with an average of 5 random friends each, \n# what percentage of other users will be in a particular user's extended social network? \n# What is the average degree of separation between a user and those in his/her extended network?\n\n# 4. Stretch Goal\n# You might have found the results from question #2 above to be surprising. \n# Would you expect results like this in real life? \n# If not, what are some ways you could improve your friendship \n# distribution model for more realistic results?\n\n# If you followed the hints for part 1, your populate_graph() will run in O(n^2) time. \n# Refactor your code to run in O(n) time. \n# Are there any tradeoffs that come with this implementation?\n","sub_path":"projects/social/social.py","file_name":"social.py","file_ext":"py","file_size_in_byte":4992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"404461599","text":"from PIL import Image\nimport time\n\nclass Stego():\n def __init__(self):\n self.hide_size = Image.open(self.hide)\n self.hide_size = self.hide_size.size\n print(self.hide_size)\n\n def ImageAnalyser(self,carrier):\n self.userin = Image.open(carrier)\n self.RGB_userin = self.userin.convert('RGB')\n self.width, self.height = self.userin.size\n self.new_array = []\n\n for h in range(self.height):\n for w in range((self.width)):\n self.r,self.g,self.b = self.RGB_userin.getpixel((w,h))\n self.ip = (self.r,self.g,self.b)\n self.new_array.append(self.ip)\n return self.new_array\n\n def ArrayConverter(self,RGB_array):\n self.bin_array = []\n for item in range(len(RGB_array)):\n self.colour = RGB_array[item]\n self.r,self.g,self.b = self.colour[0],self.colour[1],self.colour[2]\n self.r_bin,self.g_bin,self.b_bin = bin(self.r),bin(self.g),bin(self.b)\n self.r_bin = self.r_bin.replace('0b', '')\n self.g_bin = self.g_bin.replace('0b', '')\n self.b_bin = self.b_bin.replace('0b', '')\n self.r_bin = self.r_bin.zfill(8)\n self.g_bin = self.g_bin.zfill(8)\n self.b_bin = self.b_bin.zfill(8)\n self.bin_array.append(self.r_bin)\n self.bin_array.append(self.g_bin)\n self.bin_array.append(self.b_bin)\n return self.bin_array\n\nclass Encode(Stego):\n def __init__(self,cover,hide,outfile):\n self.cover = cover\n self.hide = hide\n self.outfile = outfile\n Stego.__init__(self)\n \n def ImageEncoder(self,cover,hide,outfile):\n self.hide = hide\n self.cover_size = Image.open(self.cover)\n self.cover_size = self.cover_size.size\n self.cover_RGB = self.ImageAnalyser(self.cover)\n self.hide_RGB = self.ImageAnalyser(self.hide)\n self.cover_bin = self.ArrayConverter(self.cover_RGB)\n self.hide_bin = self.ArrayConverter(self.hide_RGB)\n self.make = Image.new('RGB', self.cover_size, 'white')\n self.binary_array,self.hide_array,self.op_array,self.RGB = [],[],[],[]\n self.timer = 0\n self.count = 3\n\n for item in range(len(self.hide_bin)):\n self.hide_bit = self.hide_bin[item]\n self.hide_bit_1 = self.hide_bit[0:2]\n self.hide_bit_2 = self.hide_bit[2:4]\n self.hide_bit_3 = self.hide_bit[4:6]\n self.hide_bit_4 = self.hide_bit[6:8]\n self.hide_array.append(self.hide_bit_1)\n self.hide_array.append(self.hide_bit_2)\n self.hide_array.append(self.hide_bit_3)\n self.hide_array.append(self.hide_bit_4)\n \n for val in range(len(self.cover_bin)):\n self.cover_bit = str(self.cover_bin[val])\n self.cover_bit_1 = self.cover_bit[0:6]\n self.binary_val = self.cover_bit_1 + self.hide_array[self.timer]\n self.binary_array.append(self.binary_val)\n self.timer += 1\n\n for i in range(0,len(self.binary_array)-2,3):\n self.binary_1 = self.binary_array[i:self.count]\n self.RGB_1 = int(str(self.binary_1[0]), 2)\n self.RGB_2 = int(str(self.binary_1[1]), 2)\n self.RGB_3 = int(str(self.binary_1[2]), 2)\n self.Tup = tuple([self.RGB_1,self.RGB_2,self.RGB_3])\n self.op_array.append(self.Tup)\n self.count += 3\n\n self.im = self.make.putdata(self.op_array)\n self.im = self.make.save(outfile)\n\n output = ImageEncoder(self,cover,hide,outfile)\n\nclass Decode(Stego):\n def __init__(self,hide,Object,output):\n self.hide = hide\n self.object = Object\n self.output = output\n Stego.__init__(self)\n self.object_RGB = self.ImageAnalyser(self.object)\n self.object_bin = self.ArrayConverter(self.object_RGB)\n\n def ImageDecoder(self,hide,Object,output):\n self.make = Image.new('RGB', self.hide_size, 'white')\n self.hidden_seq = []\n self.hidden_array = []\n self.time = 12\n\n for j in range(len(self.object_bin)):\n self.object_val = self.object_bin[j]\n self.val = self.object_val[6:8]\n self.hidden_seq.append(self.val)\n\n for k in range(0,len(self.hidden_seq),12):\n self.bit = self.hidden_seq[k:self.time]\n self.bit_RGB_1 = self.bit[0]+self.bit[1]+self.bit[2]+self.bit[3]\n self.bit_RGB_2 = self.bit[4]+self.bit[5]+self.bit[6]+self.bit[7]\n self.bit_RGB_3 = self.bit[8]+self.bit[9]+self.bit[10]+self.bit[11]\n self.bit_RGB_1 = int(self.bit_RGB_1, 2)\n self.bit_RGB_2 = int(self.bit_RGB_2, 2)\n self.bit_RGB_3 = int(self.bit_RGB_3, 2)\n self.tuple = tuple([self.bit_RGB_1,self.bit_RGB_2,self.bit_RGB_3])\n self.hidden_array.append(self.tuple)\n self.time +=12\n\n self.im = self.make.putdata(self.hidden_array)\n self.im = self.make.save(\"retrieved.bmp\")\n\n decoded = ImageDecoder(self,hide,Object,output)\n\n#Im_Encoded = Encode('Images/cover.bmp','Images/hide.bmp','Images/object.bmp')\n#Im_Decoded = Decode('Images/hide.bmp','Images/object.bmp','Images/retrieved.bmp')\n\nIm_Encoded = Encode(\"P:\\Programs\\Fork\\Steganography\\Semester 2 Project - Steganography\\Images\\cover.bmp\",\"P:\\Programs\\Fork\\Steganography\\Semester 2 Project - Steganography\\Images\\hide.bmp\",\"P:\\Programs\\Fork\\Steganography\\Semester 2 Project - Steganography\\Images\\object.bmp\")\nIm_Decoded = Decode(\"P:\\Programs\\Fork\\Steganography\\Semester 2 Project - Steganography\\Images\\hide.bmp\",\"P:\\Programs\\Fork\\Steganography\\Semester 2 Project - Steganography\\Images\\object.bmp\",\"P:\\Programs\\Fork\\Steganography\\Semester 2 Project - Steganography\\Images\\retrieved.bmp\")","sub_path":"Semester 2 Project - Steganography/Steganography_old.py","file_name":"Steganography_old.py","file_ext":"py","file_size_in_byte":6075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"302683744","text":"def normalize(word):\n word = word.upper()\n new_word = ''.join([char for char in word if (char == \" \") or (char.isalpha() == True)])\n return new_word\n\n\ndef longest_substring(s1, s2):\n max_count = 0\n strings = []\n\n # find the length of the strings\n m = len(s1)\n n = len(s2)\n\n # declaring the array for storing the dp values\n L = [[None] * (n + 1) for i in range(m + 1)]\n\n for i in range(m + 1):\n for k in range(n + 1):\n if i == 0 or k == 0:\n L[i][k] = 0\n elif s1[i - 1] == s2[k - 1] and s1[i - 1] != \" \" and s2[k - 1] != \" \": # if match and not equal to a space\n L[i][k] = L[i - 1][k - 1] + 1 # increase that spots count\n if L[i][k] > max_count: # to keep track of max count\n max_count = L[i][k]\n temp = \"\"\n for b in reversed(range(L[i][k])):\n temp += s1[i - b - 1]\n strings = [] # bc new max count\n if (temp in strings) == False:\n strings.append(temp)\n elif L[i][k] == max_count:\n temp = \"\"\n for b in reversed(range(L[i][k])):\n temp += s1[i - b - 1]\n if (temp in strings) == False:\n strings.append(temp) # add to strings\n else:\n L[i][k] = 0\n\n if len(strings) == 0:\n return 0, \"!nO WORD!\"\n else:\n word = sorted(strings)[0]\n return len(word), word\n\n\ndef doit(s1, s2):\n length, string = longest_substring(s1, s2)\n if length == 0:\n return 0\n else:\n list_of_halves_s1 = s1.split(string, 1)\n list_of_halves_s2 = s2.split(string, 1)\n return length + doit(list_of_halves_s1[0], list_of_halves_s2[0]) + doit(list_of_halves_s1[1],\n list_of_halves_s2[1])\n\n\nfor x in range(5):\n string_1 = normalize(input())\n string_2 = normalize(input())\n print(doit(string_1, string_2))\n\n","sub_path":"computerclub/ACSL Difference Factor.py","file_name":"ACSL Difference Factor.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"264522376","text":"\"\"\"\nhttp://www.cnblogs.com/eaglet/archive/2010/09/16/1828016.html\nhttps://zh.wikipedia.org/wiki/%E8%AE%A1%E6%95%B0%E6%8E%92%E5%BA%8F\n\"\"\"\n\ndef count_sort(lst):\n count_lst = []\n max_index = 0\n min_index = 0\n length = len(lst)\n for i in range(length):\n max_num = lst[max_index]\n min_num = lst[min_index]\n temp = lst[i]\n if temp > max_num:\n max_index = i\n if temp < min_num:\n min_index = i\n print(lst[max_index],lst[min_index])\n\n #创建一个数组, 最大值是max_index, 最小值是min_index\n new_array = [0 for o in range(lst[max_index]+1)]\n #然后一趟扫描数组A,得到A中各个元素的总数,并保持到数组C的对应单元中。\n #比如0 的出现次数为2次,则 C[0] = 2;1 的出现次数为4次,则C[1] = 4\n for i in lst:\n new_array[i] += 1\n print(new_array)\n # result\n res = []\n for index, value in enumerate(new_array):\n if value > 0:\n temp = [index for j in range(value)]\n res.extend(temp)\n print(res)\n\n\nif __name__ == '__main__':\n res = [1,3,2,5,4]\n count_sort(res)","sub_path":"sort/count_sort.py","file_name":"count_sort.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"420784626","text":"import numpy as np\r\nimport warnings\r\nimport pandas as pd\r\nfrom sklearn.base import BaseEstimator, ClassifierMixin\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.linear_model import SGDClassifier\r\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder, PolynomialFeatures\r\nfrom functools import reduce\r\nimport lightgbm as lgbm\r\nimport pickle\r\n\r\n\r\nclass RFLGB(BaseEstimator, ClassifierMixin):\r\n\r\n def __init__(self, seed=0):\r\n self.models = [\r\n lgbm.LGBMClassifier(class_weight='balanced', max_bin=210, max_depth=10,\r\n min_child_samples=6, min_child_weight=5,\r\n n_estimators=40, n_jobs=-1, num_leaves=93, random_state = 1),\r\n lgbm.LGBMClassifier(class_weight='balanced', max_bin=220, max_depth=11,\r\n min_child_samples=6, min_child_weight=5,\r\n n_estimators=40, n_jobs=-1, num_leaves=94, random_state = 42),\r\n lgbm.LGBMClassifier(class_weight='balanced', max_bin=211, max_depth=12,\r\n min_child_samples=5, min_child_weight=5,\r\n n_estimators=40, n_jobs=-1, num_leaves=95, random_state = 651),\r\n lgbm.LGBMClassifier(class_weight='balanced', max_bin=210, max_depth=13,\r\n min_child_samples=5, min_child_weight=5,\r\n n_estimators=40, n_jobs=-1, num_leaves=96, random_state = 561),\r\n RandomForestClassifier(class_weight='balanced',\r\n criterion='gini', max_depth=10, max_features=566, min_samples_split=2,\r\n n_estimators=40, n_jobs=-1, random_state=1\r\n ),\r\n RandomForestClassifier(class_weight='balanced',\r\n criterion='gini', max_depth=11, max_features=600, min_samples_split=3,\r\n n_estimators=45, n_jobs=-1, random_state=314\r\n ),\r\n RandomForestClassifier(class_weight='balanced',\r\n criterion='gini', max_depth=12, max_features=570, min_samples_split=5,\r\n n_estimators=41, n_jobs=-1, random_state=974\r\n ),\r\n RandomForestClassifier(class_weight='balanced',\r\n criterion='gini', max_depth=20, max_features=560, min_samples_split=4,\r\n n_estimators=43, n_jobs=-1, random_state=3\r\n )\r\n ]\r\n def fit(self, X, y=None):\r\n self.n_class = len(np.unique(y))\r\n for t, clf in enumerate(self.models):\r\n #print('train ', t)\r\n clf.fit(X, y)\r\n return self\r\n\r\n def predict(self, X):\r\n summa = np.zeros((X.shape[0], self.n_class))\r\n for i, clf in enumerate(self.models):\r\n print(clf.predict_proba(X).shape)\r\n summa += clf.predict_proba(X) \r\n return clf.classes_[np.argmax(summa, axis = 1)]\r\n \r\n \r\nclass Model:\r\n\tdef __init__(self, degree = 2):\r\n\t\tself.pf = PolynomialFeatures(degree = degree)\r\n\t\tself.encoder = OneHotEncoder(sparse=False)\r\n\t\tself.ss = StandardScaler()\r\n\t\tself.clf = RFLGB()\r\n\t\t\r\n\tdef poly_fit(self, data):\r\n\t\tself.pf.fit(data)\r\n\t\t\r\n\tdef encoder_fit(self, data):\r\n\t\tself.encoder.fit(data)\r\n\t\t\r\n\tdef binning_fit(self, data, bin = 4):\r\n\t\tself.bins = {}\r\n\t\tfor i, row in enumerate(data.columns):\r\n\t\t\tbinning = np.linspace(data[row].min(), data[row].max(), bin)\r\n\t\t\tself.bins[row] = binning\r\n\t\t\t\r\n\tdef standarscaler_fit(self, data):\r\n\t\tself.ss.fit(data)\r\n\t\t\t\r\n\tdef get_encoder(self, data):\r\n\t\treturn self.encoder.transform(data)\r\n\t\t\t\t\r\n\tdef get_poly(self, data):\r\n\t\treturn self.pf.transform(data)\r\n\t\t\r\n\tdef get_binning(self, data):\r\n\t\tmatrix_binning = np.zeros_like(data)\r\n\t\tfor i, row in enumerate(data.columns):\r\n\t\t\tmatrix_binning[:, i] = np.digitize(data[row], bins=self.bins[row])\r\n\t\treturn matrix_binning\r\n\t\t\t\r\n\tdef get_angle(self, data, enc):\r\n\t\treturn np.hstack([enc * data[row][:, np.newaxis] for row in data.columns])\r\n\t\t\r\n\tdef get_standartscaler(self, data):\r\n\t\treturn self.ss.transform(data)\r\n\t\t\r\n\tdef train(self, data, target):\r\n\t\tself.clf.fit(data, target)\r\n\t\t\r\n\tdef predict(self, data):\r\n\t\treturn self.clf.predict(data)\r\n\t\r\n\t\t\r\n\tdef pickle_clf(self, path='clf.pkl'):\r\n\t\twith open(path, 'wb') as f:\r\n\t\t\tpickle.dump(self.clf, f)\r\n\t\t\tprint(\"Pickled classifier at {}\".format(path))\r\n\t\t\t\r\n\tdef pickle_standartscaler(self, path='ss.pkl'):\r\n\t\twith open(path, 'wb') as f:\r\n\t\t\tpickle.dump(self.ss, f)\r\n\t\t\tprint(\"Pickled ss at {}\".format(path))\r\n\t\t\t\r\n\tdef pickle_encoder(self, path='encoder.pkl'):\r\n\t\twith open(path, 'wb') as f:\r\n\t\t\tpickle.dump(self.encoder, f)\r\n\t\t\tprint(\"Pickled encoder at {}\".format(path))\r\n\t\t\t\r\n\tdef pickle_pf(self, path='pf.pkl'):\r\n\t\twith open(path, 'wb') as f:\r\n\t\t\tpickle.dump(self.pf, f)\r\n\t\t\tprint(\"Pickled pf at {}\".format(path))\r\n\t\t\t\r\n\tdef json_bins(self, path='bins.json'):\r\n\t\tpd.DataFrame.from_dict(self.bins).to_csv('bins.csv')\t\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":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"35336829","text":"def read_sudoku(filename):\r\n \"\"\" Прочитать Судоку из указанного файла \"\"\"\r\n digits = [c for c in open('puzzle1.txt').read() if c in '123456789.']\r\n grid = group(digits, 9)\r\n return grid\r\n\r\n\r\ndef display(grid):\r\n \"\"\" Вывод Судоку \"\"\"\r\n width = 2\r\n line = '+'.join(['-' * (width * 3)] * 3)\r\n for row in range(9):\r\n print(''.join(grid[row][col].center(width) + ('|' if str(col) in '25' else '') for col in range(9)))\r\n if str(row) in '25':\r\n print(line)\r\n print()\r\n\r\n\r\ndef group(values, n):\r\n \"\"\"\r\n Сгруппировать значения values в список, состоящий из списков по n элементов\r\n >>> group([1,2,3,4], 2)\r\n [[1, 2], [3, 4]]\r\n >>> group([1,2,3,4,5,6,7,8,9], 3)\r\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\r\n \"\"\"\r\n s = 0\r\n matrix = []\r\n while len(values) > s:\r\n l = [i for i in values[s:s + n]]\r\n matrix.append(l)\r\n s += n\r\n return matrix\r\n\r\n\r\ndef get_row(grid,pos):\r\n \"\"\" Возвращает все значения для номера строки, указанной в pos\r\n >>> get_row([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (0, 0))\r\n ['1', '2', '.']\r\n >>> get_row([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (1, 0))\r\n ['4', '.', '6']\r\n >>> get_row([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (2, 0))\r\n ['.', '8', '9']\r\n \"\"\"\r\n row, col = pos\r\n return grid[row]\r\n\r\n\r\ndef get_col(grid,pos):\r\n \"\"\" Возвращает все значения для номера столбца, указанного в pos\r\n >>> get_col([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (0, 0))\r\n ['1', '4', '7']\r\n >>> get_col([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (0, 1))\r\n ['2', '.', '8']\r\n >>> get_col([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (0, 2))\r\n ['3', '6', '9']\r\n \"\"\"\r\n row, col = pos\r\n l = []\r\n for i in grid:\r\n l.append(i[col])\r\n return l\r\n\r\n\r\ndef get_block(grid,pos):\r\n \"\"\" Возвращает все значения из квадрата, в который попадает позиция pos\r\n >>> grid = read_sudoku('puzzle1.txt')\r\n >>> get_block(grid, (0, 1))\r\n ['5', '3', '.', '6', '.', '.', '.', '9', '8']\r\n >>> get_block(grid, (4, 7))\r\n ['.', '.', '3', '.', '.', '1', '.', '.', '6']\r\n >>> get_block(grid, (8, 8))\r\n ['2', '8', '.', '.', '.', '5', '.', '7', '9']\r\n \"\"\"\r\n row, col = pos\r\n block = []\r\n frow = 0\r\n lrow = 0\r\n fcol = 0\r\n lcol = 0\r\n if 0 <= row <= 2:\r\n frow = 0\r\n lrow = 3\r\n if 3 <= row <= 5:\r\n frow = 3\r\n lrow = 6\r\n if 6 <= row <= 8:\r\n frow = 6\r\n lrow = 9\r\n if 0 <= col <= 2:\r\n fcol = 0\r\n lcol = 3\r\n if 3 <= col <= 5:\r\n fcol = 3\r\n lcol = 6\r\n if 6 <= col <= 8:\r\n fcol = 6\r\n lcol = 9\r\n\r\n for i in grid[frow:lrow]:\r\n for m in i[fcol:lcol]:\r\n block.append(m)\r\n return block\r\n\r\n\r\ndef find_empty_positions(grid):\r\n \"\"\" Найти первую сво��одную позицию в пазле\r\n >>> find_empty_positions([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']])\r\n (0, 2)\r\n >>> find_empty_positions([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']])\r\n (1, 1)\r\n >>> find_empty_positions([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']])\r\n (2, 0)\r\n \"\"\"\r\n row = 0\r\n empty_positions = []\r\n for i in grid:\r\n col = 0\r\n for z in i:\r\n if z == \".\":\r\n empty_positions.append([row, col])\r\n col += 1\r\n row += 1\r\n empty = (empty_positions[0][0], empty_positions[0][1])\r\n return empty\r\n\r\n\r\ndef find_possible_values(grid,pos):\r\n \"\"\" Вернуть множество возможных значения для указанной позиции\r\n >>> grid = read_sudoku('puzzle1.txt')\r\n >>> values = find_possible_values(grid, (0,2))\r\n >>> values == {'1', '2', '4'}\r\n True\r\n >>> values = find_possible_values(grid, (4,7))\r\n >>> values == {'2', '5', '9'}\r\n True\r\n \"\"\"\r\n all_values = get_row(grid, pos) + get_col(grid, pos) + get_block(grid, pos)\r\n possible_values = {str(i) for i in range(1, 10)}\r\n for i in all_values:\r\n if i != '.':\r\n possible_values.discard(i)\r\n return possible_values\r\n\r\n\r\ndef solve(grid):\r\n \"\"\" Решение пазла, заданного в grid \"\"\"\r\n \"\"\" Как решать Судоку?\r\n 1. Найти свободную позицию\r\n 2. Найти все возможные значения, которые могут находиться на этой позиции\r\n 3. Для каждого возможного значения:\r\n 3.1. Поместить это значение на эту позицию\r\n 3.2. Продолжить решать оставшуюся часть пазла\r\n >>> grid = read_sudoku('puzzle1.txt')\r\n >>> solve(grid)\r\n [['5', '3', '4', '6', '7', '8', '9', '1', '2'], ['6', '7', '2', '1', '9', '5', '3', '4', '8'], ['1', '9', '8', '3', '4', '2', '5', '6', '7'], ['8', '5', '9', '7', '6', '1', '4', '2', '3'], ['4', '2', '6', '8', '5', '3', '7', '9', '1'], ['7', '1', '3', '9', '2', '4', '8', '5', '6'], ['9', '6', '1', '5', '3', '7', '2', '8', '4'], ['2', '8', '7', '4', '1', '9', '6', '3', '5'], ['3', '4', '5', '2', '8', '6', '1', '7', '9']]\r\n \"\"\"\r\n try:\r\n empty_position = find_empty_positions(grid)\r\n except IndexError:\r\n return grid\r\n\r\n possible_values = find_possible_values(grid, empty_position)\r\n for i in possible_values:\r\n grid[empty_position[0]][empty_position[1]] = i\r\n maybe = solve(grid)\r\n if maybe:\r\n return maybe\r\n\r\n grid[empty_position[0]][empty_position[1]] = '.'\r\n return None\r\n\r\n\r\ndef check_solution(solution):\r\n \"\"\" Если решение solution верно, то вернуть True, в противном случае False\r\n >>> a = [['4', '3', '4', '6', '7', '8', '9', '1', '2'], ['6', '7', '2', '1', '9', '5', '3', '4', '8'], ['1', '9', '8', '3', '4', '2', '5', '6', '7'], ['8', '5', '9', '7', '6', '1', '4', '2', '3'], ['4', '2', '6', '8', '5', '3', '7', '9', '1'], ['7', '1', '3', '9', '2', '4', '8', '5', '6'], ['9', '6', '1', '5', '3', '7', '2', '8', '4'], ['2', '8', '7', '4', '1', '9', '6', '3', '5'], ['3', '4', '5', '2', '8', '6', '1', '7', '9']]\r\n >>> check_solution(a)\r\n False\r\n >>> grid = read_sudoku('puzzle1.txt')\r\n >>> solution = solve(grid)\r\n >>> check_solution(solution)\r\n True\r\n \"\"\"\r\n for i in solution:\r\n values = [_ for _ in range(1, 10)]\r\n for m in i:\r\n try:\r\n values.remove(int(m))\r\n except ValueError:\r\n return False\r\n\r\n col = 0\r\n while col < 8:\r\n values = [_ for _ in range(1, 10)]\r\n cols = get_col(solution, (0, col))\r\n for i in cols:\r\n try:\r\n values.remove(int(i))\r\n except ValueError:\r\n return False\r\n col += 1\r\n\r\n blocks = [(0, 0), (0, 3), (0, 6), (3, 0), (3, 3), (3, 6), (6, 0), (6, 3), (6, 6)]\r\n for i in blocks:\r\n values = [_ for _ in range(1, 10)]\r\n block = get_block(solution, i)\r\n for v in block:\r\n try:\r\n values.remove(int(v))\r\n except ValueError:\r\n return False\r\n\r\n return True\r\n\r\nimport random \r\n\r\ndef generate_sudoku(N):\r\n \"\"\" Генерация судоку заполненного на N элементов\r\n >>> grid = generate_sudoku(40)\r\n >>> sum(1 for row in grid for e in row if e == '.')\r\n 41\r\n >>> solution = solve(grid)\r\n >>> check_solution(solution)\r\n True\r\n >>> grid = generate_sudoku(1000)\r\n >>> sum(1 for row in grid for e in row if e == '.')\r\n 0\r\n >>> solution = solve(grid)\r\n >>> check_solution(solution)\r\n True\r\n >>> grid = generate_sudoku(0)\r\n >>> sum(1 for row in grid for e in row if e == '.')\r\n 81\r\n >>> solution = solve(grid)\r\n >>> check_solution(solution)\r\n True\r\n \"\"\"\r\n table = [['1', '2', '3', '4', '5', '6', '7', '8', '9'], ['4', '5', '6', '7', '8', '9', '1', '2', '3'],\r\n ['7', '8', '9', '1', '2', '3', '4', '5', '6'], ['2', '3', '4', '5', '6', '7', '8', '9', '1'],\r\n ['5', '6', '7', '8', '9', '1', '2', '3', '4'], ['8', '9', '1', '2', '3', '4', '5', '6', '7'],\r\n ['3', '4', '5', '6', '7', '8', '9', '1', '2'], ['6', '7', '8', '9', '1', '2', '3', '4', '5'],\r\n ['9', '1', '2', '3', '4', '5', '6', '7', '8']]\r\n \r\n score = 81\r\n while score > N:\r\n row = random.randint(0, 8)\r\n col = random.randint(0, 8)\r\n if table[row][col] != '.':\r\n table[row][col] = '.'\r\n score -= 1\r\n return table\r\n\r\nif __name__ == '__main__':\r\n for fname in ['puzzle1.txt', 'puzzle2.txt', 'puzzle3.txt']:\r\n grid = read_sudoku(fname)\r\n display(grid)\r\n solution = solve(grid)\r\n if not solution:\r\n print(f\"Puzzle {fname} can't be solved\")\r\n else:\r\n display(solution)","sub_path":"homework02/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":9272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"418949019","text":"from datetime import datetime\nfrom datetime import time\nfrom datetime import date\ndef main():\n today=date.today()\n \n print('today date is :',today)\n print('date components: ',today.day,today.month,today.year)\n print('today weekday is :',today.weekday())\n \n days=['mon','tue','wed','thu','fri','sat','sun']\n print('which is a: ',days[today.weekday()])\n \n today=datetime.now()\n print('the current date and time is',today)\n \n t=datetime.time(datetime.now())\nmain()\n","sub_path":"date&time/datetime1.py","file_name":"datetime1.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"441746104","text":"import pkgutil\nimport time\n\n__path__ = pkgutil.extend_path(__path__, __name__)\n\n\nfrom contextlib import contextmanager\nfrom datetime import (\n date,\n datetime,\n time,\n)\nfrom functools import partial\nimport re\nfrom typing import (\n Any,\n Iterator,\n Sequence,\n cast,\n overload,\n)\nimport warnings\n\nimport numpy as np\n\nimport pandas._libs.lib as lib\nfrom pandas.compat._optional import import_optional_dependency\nfrom pandas.errors import AbstractMethodError\n\nfrom pandas.core.dtypes.common import (\n is_datetime64tz_dtype,\n is_dict_like,\n is_list_like,\n)\nfrom pandas.core.dtypes.dtypes import DatetimeTZDtype\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas import get_option\nfrom pandas.core.api import (\n DataFrame,\n Series,\n)\nfrom pandas.core.base import PandasObject\nfrom pandas.core.tools.datetimes import to_datetime\n\n\nfrom sharkbite import AuthInfo, Range, Configuration, ZookeeperInstance, AccumuloConnector, AccumuloScanner, Authorizations, AccumuloIterator, Key, AccumuloBase\nfrom . import pandassharkbite\n\n\n@overload\ndef read_accumulo(\n connector : AccumuloBase,\n ranges : list,\n columns=None,\n index_col=None,\n chunksize : int= 1000\n):\n scanner = connector.to_scanner()\n scanner.fetch_ranges(ranges)\n return read_accumulo(scanner,columns,index_col,chunksize)\n\n\ndef read_accumulo(\n scanner : AccumuloScanner,\n columns=None,\n index_col=None,\n chunksize : int= 1000\n):\n \"\"\"\n \n\n Parameters\n ----------\n sql : AccumuloBase\n columns : list, default: None\n List of column names to select from SQL table (only used when reading\n a table).\n chunksize : int, default None\n If specified, return an iterator where `chunksize` is the\n number of rows to include in each chunk.\n\n Returns\n -------\n DataFrame or Iterator[DataFrame]\n\n \"\"\"\n ## assume that scanner is established previously\n print(f\"chunk size is {chunksize}\")\n if columns is not None:\n for column in columns:\n scanner.select_column(column)\n iterator = pandassharkbite.DataFrameIterator(scanner.get(chunksize))\n iterator.__iter__()\n cols = iterator.get_columns()\n\n frame = iterator.__next__()\n return frame\n\ndef read_accumulo_nex(\n iterator : AccumuloIterator,\n columns=None,\n index_col=None,\n chunksize : int= 1000\n):\n \"\"\"\n \n \"\"\"\n frame = iterator.__next__()\n return frame\n\n","sub_path":"pandashark/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"571380150","text":"#一.py���建字典\n#1.使用{}创建字典\n#使用字符串作为key\nscores = {'数学': 95, '英语': 92, '语文': 84}\nprint(scores)\n#使用元组和数字作为key\ndict1 = {(20, 30): 'great', 30: [1,2,3]}\nprint(dict1)\n#创建空元组\ndict2 = {}\nprint(dict2)\n\n#2.通过fromkeys()方法创建字典\nknowledge = ['语文', '数学', '英语']\nscores = dict.fromkeys(knowledge,60)\nprint(scores)\n\n#3.通过dict()映射函数创建字典\n# 创建空的字典\nd = dict()\nprint(d)\n\n#二.py访问字典\ntup = (['two',26], ['one',88], ['three',100], ['four',-59])\ndic = dict(tup)\nprint(dic)\n\ndict1={'name':'Lara','age':18}\n#判断键在不在字典中\nfor one in dict1:\n if 'name' in dict1:#或dict1.keys()\n print('key在字典中!')\n break\n#判断值在不在字典中\nfor one in dict1:\n if 'Lara' in dict1.values():\n print('value在字典中!')\n break\n# 除了上面这种方式外,Python 更推荐使用 dict 类型提供的 get() 方法来获取指定键对应的值。当指定的键不存在时,get() 方法不会抛出异常。\n# get() 方法的语法格式为:\n# dictname.get(key[,default])\n# 其中,dictname 表示字典变量的名字;key 表示指定的键;default 用于指定要查询的键不存在时,此方法返回的默认值,如果不手动指定,会返回 None。\na = dict(two=0.65, one=88, three=100, four=-59)\nprint(a.get('one'))\na = dict(two=0.65, one=88, three=100, four=-59)\nprint(a.get('five', '该键不存在'))\n\n# 三.py删除字典\na = dict(two=0.65, one=88, three=100, four=-59)\nprint(a)\ndel a\n\n\n","sub_path":"c语言中文网/py/4.列表,元组,字典和集合/4.13py_dict字典/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"235993061","text":"from pyspark import SparkContext\nfrom datetime import datetime, timedelta\nimport csv\nimport functools\nimport json\nimport numpy as np\nimport sys\n \ndef main(sc):\n '''\n Transfer our code from the notebook here, however, remember to replace\n the file paths with the ones provided in the problem description.\n '''\n rddPlaces = sc.textFile('hdfs:///data/share/bdm/core-places-nyc.csv')\n rddPattern = sc.textFile('hdfs:///data/share/bdm/weekly-patterns-nyc-2019-2020/*')\n OUTPUT_PREFIX = sys.argv[1]\n \n CAT_CODES = {'445210', '445110', '722410', '452311', '722513', '445120', '446110', '445299', '722515', '311811', '722511', '445230', '446191', '445291', '445220', '452210', '445292'}\n CAT_GROUP = {'452210': 0, '452311': 0, '445120': 1, '722410': 2, '722511': 3, '722513': 4, '446110': 5, '446191': 5, '722515': 6, '311811': 6, '445210': 7, '445299': 7, '445230': 7, '445291': 7, '445220': 7, '445292': 7, '445110': 8}\n\n def filterPOIs(_, lines):\n for line in lines:\n line = line.split(',')\n if line[9] in CAT_CODES:\n yield (line[0], CAT_GROUP[line[9]])\n \n rddD = rddPlaces.mapPartitionsWithIndex(filterPOIs) \\\n .cache()\n\n storeGroup = dict(rddD.collect())\n groupCount = rddD \\\n .map(lambda x: (x[1], 1)) \\\n .reduceByKey(lambda x,y: x+y) \\\n .sortBy(lambda x: x) \\\n .map(lambda x: x[1]) \\\n .collect()\n\n def extractVisits(storeGroup, _, lines):\n for line in lines:\n line = next(csv.reader([line]))\n if line[0] in storeGroup:\n dates = [str(datetime.strptime(line[12][:10],'%Y-%m-%d') + timedelta(days=i))[:10] for i in range(7)]\n for i, date in enumerate(dates):\n if date[:4] in ['2019', '2020']:\n date = (datetime.strptime(date,'%Y-%m-%d') - datetime.strptime('2019-01-01', '%Y-%m-%d')).days\n visit_of_the_day = line[16][1:-1].split(',')\n yield ((storeGroup[line[0]], date), int(visit_of_the_day[i]))\n \n\n rddG = rddPattern \\\n .mapPartitionsWithIndex(functools.partial(extractVisits, storeGroup))\n\n def computeStats(groupCount, _, records):\n for record in records:\n key, value = record[0], list(record[1])\n if len(value) < groupCount[key[0]]:\n padding = [0]*(groupCount[key[0]] - len(value))\n value.extend(padding)\n median = int(np.median(value))\n stdv = np.std(value)\n low = 0 if (median-stdv) <0 else int(median-stdv)\n high = int(median+stdv)\n yield (key, (median, low, high))\n \n\n rddH = rddG.groupByKey() \\\n .mapPartitionsWithIndex(functools.partial(computeStats, groupCount))\n\n def padding(record):\n key, value = record[0], list(record[1])\n if len(value) < groupCount[key[0]]:\n padding = [0]*(groupCount[key[0]] - len(value))\n value.extend(padding)\n return key, value\n\n rddI = rddG.groupByKey() \\\n .map(lambda x: padding(x)) \\\n .map(lambda x: (x[0], np.median(list(x[1])), np.std(list(x[1])) )) \\\n .map(lambda x: (x[0][0], x[0][1], int(x[1]), int(x[1]- x[2]), int(x[1]+x[2]) )) \\\n .map(lambda x: (x[0], str(datetime.strptime('2019-01-01', '%Y-%m-%d')+timedelta(days = x[1]))[:10], x[2], x[3]if x[3]>0 else 0, x[4])) \\\n .map(lambda x: (x[0], x[1][:4], '2020-'+x[1][5:], x[2], x[3], x[4])) \\\n .map(lambda x: (x[0], ','.join([str(cell) for cell in x[1:]])))\n\n rddJ = rddI.sortBy(lambda x: x[1][:15])\n header = sc.parallelize([(-1, 'year,date,median,low,high')]).coalesce(1)\n rddJ = (header + rddJ).coalesce(10).cache()\n\n\n filenames = ['big_box_grocers',\n 'convenience_stores',\n 'drinking_places',\n 'full_service_restaurants',\n 'limited_service_restaurants',\n 'pharmacies_and_drug_stores',\n 'snack_and_bakeries',\n 'specialty_food_stores',\n 'supermarkets_except_convenience_stores']\n for i, name in enumerate(filenames):\n rddJ.filter(lambda x: x[0]==i or x[0]==-(i+1)).values() \\\n .saveAsTextFile(f'{OUTPUT_PREFIX}/{name}')\n\n \nif __name__=='__main__':\n sc = SparkContext()\n main(sc)","sub_path":"BDM_HW4_rdd_v3.py","file_name":"BDM_HW4_rdd_v3.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"505414998","text":"\"\"\"\nA string is said to be a special string if either of two conditions is met:\n\n * All of the characters are the same, e.g. aaa.\n * All characters except the middle one are the same, e.g. aadaa.\n\nA special substring is any substring of a string which meets one of those criteria. Given a string, determine how many\nspecial substrings can be formed from it.\n\nFor example, given the string s=\"mnonopoo\", we have the following special substrings: {m,n,o,n,o,p,o,o,non,ono,opo,oo}.\n\"\"\"\n\nclass StateMachine():\n def __init__(self):\n self.handlers = {}\n self.start_state = None\n self.end_states = []\n\n def add_state(self, name, handler, end_state=0):\n self.handlers[name.lower()] = handler\n if end_state:\n self.end_states.append(name.lower())\n\n def set_start(self, name):\n self.start_state = name.lower()\n\n def run(self, *args):\n handler = self.handlers[self.start_state]\n while True:\n args = handler(*args)\n new_state = args[0]\n args = args[1]\n if new_state in self.end_states:\n return args\n else:\n handler = self.handlers[new_state]\n\ndef start_subs(s, i = 0, count = 0, len_subs=0):\n c = s[i]\n next_state = \"eos\"\n while i < len(s) - 1:\n i += 1\n len_subs += 1\n if c != s[i]:\n next_state = \"pivot\"\n break\n count += ((len_subs + 1) * len_subs) // 2\n if i >= len(s) - 1:\n args = count + 1\n else:\n args = s, i, c, count, len_subs\n return next_state, args\n\ndef pivot_char(s, i, c, count, len_subs=0):\n\n if i < len(s) - 1:\n if s[i+1] == c: #Palindrome\n next_state = \"palindrome_found\"\n args = s, i+1, count+1, len_subs\n elif s[i+1] != s[i]: # New substring following the pivot\n next_state = \"start_subs\"\n args = s, i+1, count+1\n else: # The pivot is part of a new substring\n next_state = \"start_subs\"\n args = s, i, count\n else:\n next_state = \"eos\"\n args = count+1\n return next_state, args\n\ndef palindrome(s, i, count, len_subs=0):\n # Is it a palindrome, and also a pivot for the pivot before?\n if i < len(s) - 1:\n if s[i+1] != s[i]: #Pivot. Account for palindrome of size 1 and currenc char and move on\n count += 2\n next_state = \"pivot\"\n args = s, i, s[i-1], count, 1\n else:\n c = s[i]\n next_state = \"eos\"\n max_pal = len_subs\n len_subs = 0\n while i < len(s) - 1 and max_pal:\n i += 1\n len_subs += 1\n max_pal -= 1\n if c != s[i]:\n next_state = \"pivot\"\n c = s[i-2]\n break\n count += len_subs + ((len_subs + 1) * len_subs) // 2\n if i >= len(s)-1:\n args = count+1\n elif len_subs == 1: # Possible palindrome for the pivot before\n if s[i] == s[i-2]:\n next_state = \"palindrome_found\"\n args = s, i, count+1, 1\n else:\n args = s, i, c, count, len_subs\n else:\n next_state = \"eos\"\n args = count+1\n return next_state, args\n\ndef substrCount(n, s):\n \"\"\"\n\n :param n: integer, the length of string s\n :param s: a string\n :return: return an integer representing the number of special substrings that can be formed from the given string.\n \"\"\"\n\n sm = StateMachine()\n sm.add_state(\"start_subs\", start_subs)\n sm.add_state(\"pivot\", pivot_char)\n sm.add_state(\"palindrome_found\", palindrome)\n sm.add_state(\"eos\", None, 1)\n sm.set_start(\"start_subs\")\n\n return sm.run(s)\n\nif __name__==\"__main__\":\n print(substrCount(5, 'asasd')) # exp. 7\n print(substrCount(7,'abcbaba')) # exp. 10","sub_path":"Strings/substring.py","file_name":"substring.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"499535158","text":"\"\"\"ss_portal URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^', include('sitehome.urls', namespace='sitehome')),\n url(r'^', include('loginmgmt.urls', namespace='loginmgmt')),\n url(r'^', include('opportunities.urls', namespace='opportunities')),\n url(r'^', include('discovery.urls', namespace='discovery')),\n url(r'^', include('custom_features.urls', namespace='custom_features')),\n]\n","sub_path":"ss_portal/settings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"102535385","text":"#!/usr/bin/env python\n# author: samantha monteiro\n\nclass Solution(object):\n\tdef hasCycle(self, head):\n\t\tslow = head\n\t\tfast = head\n\n\t\twhile fast != None and fast.next != None:\n\t\t\tslow = slow.next\n\t\t\tfast = fast.next.next\n\n\t\t\tif (slow == fast): return True\n\n\t\treturn False\n","sub_path":"141.py","file_name":"141.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"308218790","text":"class IntegerObject():\n\n def __init__(self, value):\n self.set_value(value)\n\n def get_value(self):\n return self.value\n\n def set_value(self, value):\n v = int(value)\n if v >= 10:\n print(\"Too big, setting to 9.\")\n v = int(9)\n self.value = v\n\n def print_value(self):\n print(str(self.value))\n\n\nclass StringObject():\n\n def __init__(self, s):\n self.value = str(s)\n\n def get_value(self):\n return self.value\n\n def set_value(self, s):\n s = str(s)\n if len(s) >= 10:\n s = s[0:9]\n print(\"Too big, truncating to \" + s)\n self.value = str(s)\n\n def print_value(self):\n print(str(self.value))\n\n\ndef total_value(list_of_integer_objects):\n sum = 0\n for int_obj in list_of_integer_objects:\n value = int_obj.get_value()\n sum = sum + value\n return sum\n\ndef print_sorted_list(list_of_integer_objects):\n list_of_integer_objects.sort(key=lambda x: x.value, reverse=True)\n for int_obj in list_of_integer_objects:\n int_obj.print_value()\n\nint_object_list = list()\nstr_object_list = list()\ncheese_list = [\"Tilsit\", \"Stilton\", \"Emmental\", \"Cheshire\"]\n\nfor i in range(1,5):\n int_object_list.append(IntegerObject(i))\n\nfor cheese in cheese_list:\n str_object_list.append(StringObject(cheese))\n\nfor int_object in int_object_list:\n int_object.print_value()\n\nfor str_object in str_object_list:\n str_object.print_value()\n\nprint(total_value(int_object_list))\nprint_sorted_list(int_object_list)\n\nfor int_object in int_object_list:\n int_object.print_value()\n\nint_object_list[0].set_value(10)\nint_object_list[1].value = 1000\nint_object_list[2].value = \"Cheddar\"\n\nstr_object_list[0].set_value(\"Wensleydale\")\nstr_object_list[1].value = \"Norwegian Jarlsberg\"\nstr_object_list[2].value = 5\n\nfor int_object in int_object_list:\n int_object.print_value()\n\nfor str_object in str_object_list:\n str_object.print_value()\n\n","sub_path":"_site/sessions/2014/bestpractices/badcode2.py","file_name":"badcode2.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"34853741","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport random\nfrom datetime import datetime\nfrom uuid import uuid4\n\nfrom flywheel import Model, Field\n\nlog = logging.getLogger(__name__)\n\nlog.debug(\"##### MODEL DATA #####\")\n\n\nclass User(Model):\n \"\"\" Usuários do game \"\"\"\n\n id = Field(data_type=str, range_key=True)\n name = Field(data_type=str, nullable=False)\n email = Field(data_type=str, nullable=False, index='email-index')\n facebook_id = Field(data_type=int, nullable=False, hash_key=True)\n facebook_token = Field(data_type=str, nullable=True)\n facebook_data = Field(data_type=dict, nullable=True)\n cpf = Field(data_type=str, nullable=True)\n mobile = Field(data_type=str, nullable=True)\n cep = Field(data_type=str, nullable=True)\n state = Field(data_type=str, nullable=True)\n city = Field(data_type=str, nullable=True)\n optin = Field(data_type=str, nullable=True)\n neighborhood = Field(data_type=str, nullable=True)\n address = Field(data_type=str, nullable=True)\n numb = Field(data_type=str, nullable=True)\n compl = Field(data_type=str, nullable=True)\n media_data = Field(data_type=str, nullable=True)\n firstAccess = Field(data_type=int, default=1)\n created_at = Field(data_type=datetime)\n updated_at = Field(data_type=datetime, nullable=True)\n deleted_at = Field(data_type=datetime, nullable=True, index='create-index')\n referral = Field(data_type=str, default='')\n avatar = Field(data_type=dict, nullable=True)\n win = Field(data_type=dict, nullable=True)\n win_email = Field(data_type=list, nullable=True)\n is_dirty = Field(data_type=bool, default=False)\n is_admin = Field(data_type=int, default=0, index='admin-index')\n\n\nclass UserRequest(Model):\n \"\"\" Tentativas de acertos \"\"\"\n\n id = Field(data_type=str, range_key=True)\n user_id = Field(data_type=str, hash_key=True, nullable=False)\n sequence = Field(data_type=str, index='sequence-index')\n game_level = Field(data_type=str, index='level-index')\n created_at = Field(data_type=datetime, index='create-index')\n\n\nclass Challenge(Model):\n \"\"\" Desafios possíveis \"\"\"\n\n id = Field(data_type=str, range_key=True)\n game_level = Field(data_type=str, hash_key=True, nullable=False)\n order = Field(data_type=int, index='order-index')\n icons = Field(data_type=dict, nullable=False)\n active = Field(data_type=int, default=0, index='active-index')\n created_at = Field(data_type=datetime, default=datetime.utcnow())\n updated_at = Field(data_type=datetime, nullable=True)\n\n\nclass Reward(Model):\n \"\"\" Premios \"\"\"\n\n id = Field(data_type=str)\n sequence = Field(data_type=str, nullable=False, range_key=True)\n game_level = Field(data_type=str, nullable=False, hash_key=True)\n week = Field(data_type=int, nullable=False, index='week-index')\n prize = Field(data_type=str, nullable=False, index='reward-index')\n user_id = Field(data_type=str, nullable=True, index='user-index')\n signup = Field(data_type=datetime, nullable=True)\n created_at = Field(data_type=datetime, index='created-index')\n updated_at = Field(data_type=datetime, nullable=True, index='updated-index')\n\n\nclass Prize(Model):\n id = Field(data_type=str, range_key=True)\n game_level = Field(data_type=str, hash_key=True)\n name = Field(data_type=str, nullable=True)\n img = Field(data_type=str, nullable=True)\n ico = Field(data_type=str, nullable=True)\n details = Field(data_type=list, nullable=True)\n created_at = Field(data_type=datetime, index='created-index')\n updated_at = Field(data_type=datetime, index='updated-index', nullable=True)\n\n\nclass Life(Model):\n \"\"\" Vidas dos usuários \"\"\"\n\n rr = Field(data_type=str, hash_key=True, default='life')\n user_id = Field(data_type=str, range_key=True, nullable=False)\n life_qtd = Field(data_type=int, index='life-index', default=3)\n created_at = Field(data_type=datetime, index='created-index')\n updated_at = Field(data_type=datetime, index='updated-index', nullable=True)\n last_dec = Field(data_type=datetime, index='last_dec', nullable=True)\n\n\ndef create_schemas(engine):\n engine.register(User, UserRequest, Challenge, Reward, Life, Prize)\n # engine.delete_schema()\n # engine.create_schema()\n\n\ndef create_data(engine):\n uuid = lambda: uuid4().hex\n now = lambda: datetime.utcnow()\n\n prize = [{'id': str(uuid()),\n 'name': 'premio 1',\n 'game_level': 'easy',\n 'img': \"https://67.media.tumblr.com/0b24856a940f06f90d46add91e9f8294/tumblr_inline_nhrgjlwFez1t183w3.png\",\n 'details': ['detalhe 1', 'detalhe 1 1', 'detalhe 1 1 1'],\n 'created_at': now()},\n {'id': str(uuid()),\n 'name': 'premio 2',\n 'game_level': 'medium',\n 'img': \"https://67.media.tumblr.com/0b24856a940f06f90d46add91e9f8294/tumblr_inline_nhrgjlwFez1t183w3.png\",\n 'details': ['detalhe 2', 'detalhe 2', 'detalhe 2'],\n 'created_at': now()},\n {'id': str(uuid()),\n 'name': 'premio 3',\n 'game_level': 'hard',\n 'img': \"https://67.media.tumblr.com/0b24856a940f06f90d46add91e9f8294/tumblr_inline_nhrgjlwFez1t183w3.png\",\n 'details': ['detalhe 3', 'detalhe 3', 'detalhe 3'],\n 'created_at': now()},\n {'id': str(uuid()),\n 'name': 'premio 1',\n 'game_level': 'impossible',\n 'img': \"https://67.media.tumblr.com/0b24856a940f06f90d46add91e9f8294/tumblr_inline_nhrgjlwFez1t183w3.png\",\n 'details': ['detalhe 4', 'detalhe 4', 'detalhe 4'],\n 'created_at': now()}]\n reward = []\n reward = [{'id': uuid(),\n 'game_level': 'easy',\n 'sequence': rand_sequence(reward),\n 'prize': prize[0]['id'],\n 'week': 5,\n 'created_at': datetime.utcnow()},\n {'id': uuid(),\n 'game_level': 'medium',\n 'sequence': rand_sequence(reward, 6),\n 'prize': prize[1]['id'],\n 'week': 5,\n 'created_at': datetime.utcnow()},\n {'id': uuid(),\n 'game_level': 'hard',\n 'sequence': rand_sequence(reward, 9),\n 'prize': prize[2]['id'],\n 'week': 5,\n 'created_at': datetime.utcnow()},\n {'id': uuid(),\n 'game_level': 'impossible',\n 'sequence': rand_sequence(reward, 11),\n 'prize': prize[3]['id'],\n 'week': 5,\n 'created_at': datetime.utcnow()}]\n icons = {'icons': [{'code': '1', 'key': 'ico1'},\n {'code': '2', 'key': 'ico2'},\n {'code': '3', 'key': 'ico3'},\n {'code': '4', 'key': 'ico4'},\n {'code': '5', 'key': 'ico5'},\n {'code': '6', 'key': 'ico6'},\n {'code': '7', 'key': 'ico7'},\n {'code': '8', 'key': 'ico8'},\n {'code': '9', 'key': 'ico9'},\n {'code': '10', 'key': 'ico10'},\n {'code': '11', 'key': 'ico11'},\n {'code': '12', 'key': 'ico12'}]}\n\n challenge = [{'id': uuid(),\n 'game_level': 'easy',\n 'icons': icons.copy(),\n \"active\": 1,\n 'order': 0,\n 'created_at': now()\n },\n {'id': uuid(),\n 'game_level': 'medium',\n 'icons': icons.copy(),\n 'order': 1,\n \"active\": 1,\n 'created_at': now()\n },\n {'id': uuid(),\n 'game_level': 'hard',\n 'icons': icons.copy(),\n 'order': 2,\n \"active\": 1,\n 'created_at': now()\n },\n {'id': uuid(),\n 'game_level': 'impossible',\n 'icons': icons.copy(),\n 'order': 3,\n \"active\": 1,\n 'created_at': now()\n }]\n\n log.debug(prize)\n for i in prize:\n tmpi = Prize()\n for k, w in i.items():\n log.debug('{} : {}'.format(k, w))\n setattr(tmpi, k, w)\n log.debug(tmpi)\n engine.sync(tmpi)\n\n log.debug(reward)\n for i in reward:\n tmpi = Reward()\n for k, w in i.items():\n setattr(tmpi, k, w)\n engine.sync(tmpi)\n\n log.debug(challenge)\n for i in challenge:\n tmpi = Challenge()\n for k, w in i.items():\n setattr(tmpi, k, w)\n engine.sync(tmpi)\n\n\ndef rand_sequence(reward, items=4, max_items=12):\n seq = []\n for i in range(0, items):\n while True:\n item = random.randint(0, max_items)\n if str(item) not in seq:\n seq.append(str(item))\n break\n\n return '|'.join(seq)\n","sub_path":"backend/server/game/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"541779538","text":"def ans(aux):\n a = False\n d = False\n temp = aux[0]\n for n in aux[1:]:\n if temp > n:\n a = True\n else:\n d = True\n temp = n\n return a and d\n\n\ndef main():\n n = int(input())\n print('Lumberjacks:')\n for _ in range(n):\n aux = list(map(int, input().split()))\n print('Unordered' if ans(aux) else 'Ordered')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"UVA/11942.py","file_name":"11942.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"256292592","text":"#adv.py\n\n\n\n#Imports\n\nfrom room import Room\nfrom player import Player\nfrom item import Item\n\n\n# Declare all the items\n\nitems = {\n \"Applesauce\": Item(\"Applesauce\",\n \"So sweet and so good!\"),\n\n \"LambdaLabsTensorbook\": Item(\"Lambda Labs Tensorbook\",\n \"GPU laptop built for deep learning. Powered by the NVIDIA RTX 2080 Super Max-Q GPU. Pre-installed with TensorFlow, PyTorch, Keras, CUDA, and cuDNN\"),\n\n \"SolarPanels\": Item(\"Solar Panels\",\n \"This 2000 Watt portable solar array could be useful for your Tensorbook, or whatever you want to power\"),\n\n \"JetPack\": Item(\"Jet Pack\",\n \"USAF jetpack, full of fuel and ready to fly\"),\n\n \"LaserPickaxe\": Item(\"Laser Pickaxe\",\n \"A laser pickaxe designed for mining gold\"),\n\n \"TeslaCybertruck\": Item(\"Tesla Cybertruck\",\n \"Fully loaded Cybertruck, great for finding treasure!\")\n}\n\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\",\n [items[\"LambdaLabsTensorbook\"]]),\n\n 'foyer': Room(\"Foyer\", \n \"\"\"Dim light filters in from the south. Dusty passages run north and east.\"\"\",\n [items[\"SolarPanels\"]]),\n\n 'overlook': Room(\"Grand Overlook\", \n \"\"\"A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in\n the distance, but there is no way across the chasm.\"\"\",\n [items[\"JetPack\"]]),\n\n 'narrow': Room(\"Narrow Passage\", \n \"\"\"The narrow passage bends here from west to north. The smell of gold permeates the air.\"\"\",\n [items[\"LaserPickaxe\"]]),\n\n 'treasure': Room(\"Treasure Chamber\", \n \"\"\"You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by\n earlier adventurers. The only exit is to the south.\"\"\",\n [items[\"TeslaCybertruck\"]]),\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n\n#\n# Main\n#\n\n\n# Make a new player object that is currently in the 'outside' room.\n\nplayer_1 = Player(\"Data Scientist\", room[(\"outside\")], [\"Applesauce\"])\n\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\n\n# Write a loop that:\n\nwhile True:\n player_1.current_room\n\n\n # * Prints the current room name\n\n print(\"\\nYou are currently at location:\\n\", player_1.current_room.name)\n \n\n # * Prints the current description (the textwrap module might be useful here).\n\n print(\"\\nDescription:\\n\", player_1.current_room.description)\n\n\n # * Prints the items in the current room\n\n #print(\"\\nItems in this location:\\n\", player_1.current_room.items) # Using below logic to avoid items persisting\n\n available_items = []\n for item in player_1.current_room.items:\n available_items.append(item.name)\n if len(available_items)==0:\n print(\"\\nItems in this location: None\")\n else:\n print(\"\\nItems in this location:\")\n for item in available_items:\n print(item)\n\n\n # * Waits for user input and decides what to do.\n\n cmd = input(\"\\nPress 'N', 'S', 'E', 'W' to move to a different room, 'I' to access your inventory, 'take [item]' to pick up an item, 'drop [item]' to drop an item, or 'Q' to quit the game\\n\")\n\n\n # If the user enters a cardinal direction, attempt to move to the room there.\n # Print an error message if the movement isn't allowed.\n\n if cmd == \"n\":\n print(\"\\nGoing north...\\n\")\n if player_1.current_room.n_to is None:\n print(\"### There is no room north of you, select a different direction. ###\")\n else:\n player_1.current_room = player_1.current_room.n_to\n\n elif cmd == \"s\":\n print(\"\\Going south...\\n\")\n if player_1.current_room.s_to is None:\n print(\"### There is no room south of you, select a different direction. ###\")\n else:\n player_1.current_room = player_1.current_room.s_to\n\n elif cmd == \"e\":\n print(\"\\Going east...\\n\")\n if player_1.current_room.e_to is None:\n print(\"### There is no room east of you, select a different direction. ###\")\n else:\n player_1.current_room = player_1.current_room.e_to\n\n elif cmd == \"w\":\n print(\"\\Going west...\\n\")\n if player_1.current_room.w_to is None:\n print(\"### There is no room west of you, select a different direction. ###\")\n else:\n player_1.current_room = player_1.current_room.w_to\n\n\n # Open the player inventory\n\n elif (cmd == 'i') | (cmd == \"inventory\"):\n print(\"Your Inventory:\", player_1.inventory)\n\n\n # Take and drop items\n\n elif cmd == f'take {item}':\n player_1.current_room.remove_item(player_1.current_room.items[0])\n player_1.add_item(item)\n print(f\"Added {item} to your inventory.\")\n\n elif cmd == f'drop {item}':\n #player_1.current_room.add_item(player_1.inventory[1])\n player_1.remove_item(item)\n print(f'Dropped {item} from your inventory.')\n\n \n # If the user enters \"q\", quit the game.\n\n elif cmd == 'q':\n print(\"Quitter's never win!\")\n break\n\n\n # Print an error message if the movement isn't allowed.\n\n else:\n print(\"That movement is not allowed. Try another move\")\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"128590685","text":"plant = [\n {'nama':'Mesin Listrik2','plant_id':2},\n {'nama':'Mesin Listrik1','plant_id':1}\n]\n\"\"\"\nplant_id = db.Column(db.Integer, db.ForeignKey('plant.plant_id'))\n plant = db.relationship('Plant', backref='connectors')\n nama = db.Column(db.String)\n tipe = db.Column(db.String)\n port = db.Column(db.String)\n baudrate = db.Column(db.Integer, default = 9600)\n method = db.Column(db.String)\n ismodbus = db.Column(db.Boolean, default = False)\n\"\"\"\nconn = [\n {'nama':'Konektor Modbus', 'tipe':'modbus', 'port':'/dev/ttyUSB0','baudrate':9600,'method':'rtu'},\n {'nama':'Konektor Serial', 'tipe':'serial', 'port':'/dev/ttyUSB1','baudrate':9600}\n]\n\n''' \n sensor_id = db.Column(db.Integer, primary_key = True)\n nama = db.Column(db.String)\n functioncode = db.Column(db.Integer)\n address = db.Column(db.Integer)\n connector_id = db.Column(db.Integer, db.ForeignKey(\"connector.connector_id\"))\n connector = db.relationship(\"Connector\", backref= 'sensors')\n unit = db.Column(db.Integer, nullable = False)\n '''\nsensor = [\n {\n 'nama' :'SensorTemperatur', \n 'functioncode':4,\n 'address':1000,\n 'connector_id':1,\n 'unit':1\n },\n {\n 'nama' :'Sensor Level', \n 'functioncode':2,\n 'address':1,\n 'connector_id':1,\n 'unit':1\n }\n]\n\nimport random\nfrom datetime import datetime\nfrom .main.service import save_change\nfrom .main.models import Telemetry\n\ndef randomdata(a,b):\n return random.random() + random.randrange(a,b)\n\ndef dumydata(count,id):\n for i in range(count):\n d = {\n 'sensor_id':id,\n 'value':randomdata(20,40),\n 'timestamp': datetime.now()\n }\n t = Telemetry(**d) \n save_change(t)\n\ndef st(count,id):\n for i in range(count):\n d = {\n 'sensor_id':id,\n 'value':randomdata(20,40),\n 'timestamp': datetime.now()\n }\n t = Telemetry(**d) \n save_change(t)\n\n","sub_path":"dumydata.py","file_name":"dumydata.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"243490594","text":"from collections import defaultdict\nfrom itertools import islice\nimport traceback\n\nfrom pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import HtmlFormatter\n\nfrom celery.utils.mail import ErrorMail\nfrom django.core import mail\nfrom django.utils.log import AdminEmailHandler\nfrom django.views.debug import SafeExceptionReporterFilter, get_exception_reporter_filter\nfrom django.template.loader import render_to_string\n\n\ndef clean_exception(exception):\n \"\"\"\n Takes an Exception instance and strips potentially sensitive information\n \"\"\"\n from django.conf import settings\n if settings.DEBUG:\n return exception\n\n # couchdbkit doesn't provide a better way for us to catch this exception\n if (\n isinstance(exception, AssertionError) and\n exception.message.startswith('received an invalid response of type')\n ):\n message = (\"It looks like couch returned an invalid response to \"\n \"couchdbkit. This could contain sensitive information, \"\n \"so it's being redacted.\")\n return exception.__class__(message)\n\n return exception\n\n\nclass HqAdminEmailHandler(AdminEmailHandler):\n \"\"\"\n Custom AdminEmailHandler to include additional details which can be supplied as follows:\n\n logger.error(message,\n extra={\n 'details': {'domain': 'demo', 'user': 'user1'}\n }\n )\n \"\"\"\n def get_context(self, record):\n request = None\n try:\n request = record.request\n filter = get_exception_reporter_filter(request)\n request_repr = filter.get_request_repr(request)\n except Exception:\n request_repr = \"Request repr() unavailable.\"\n\n tb_list = []\n code = None\n if record.exc_info:\n etype, _value, tb = record.exc_info\n value = clean_exception(_value)\n tb_list = ['Traceback (most recent call first):\\n']\n formatted_exception = traceback.format_exception_only(etype, value)\n tb_list.extend(formatted_exception)\n extracted_tb = list(reversed(traceback.extract_tb(tb)))\n code = self.get_code(extracted_tb)\n tb_list.extend(traceback.format_list(extracted_tb))\n stack_trace = '\\n'.join(tb_list)\n subject = '%s: %s' % (record.levelname,\n formatted_exception[0].strip() if formatted_exception else record.getMessage())\n else:\n stack_trace = 'No stack trace available'\n subject = '%s: %s' % (\n record.levelname,\n record.getMessage()\n )\n context = defaultdict(lambda: '')\n context.update({\n 'subject': self.format_subject(subject),\n 'message': record.getMessage(),\n 'details': getattr(record, 'details', None),\n 'tb_list': tb_list,\n 'request_repr': request_repr,\n 'stack_trace': stack_trace,\n 'code': code,\n })\n if request:\n context.update({\n 'get': request.GET,\n 'post': SafeExceptionReporterFilter().get_post_parameters(request),\n 'method': request.method,\n 'url': request.build_absolute_uri(),\n })\n return context\n\n def emit(self, record):\n context = self.get_context(record)\n\n message = \"\\n\\n\".join(filter(None, [\n context['message'],\n self.format_details(context['details']),\n context['stack_trace'],\n context['request_repr'],\n ]))\n html_message = render_to_string('hqadmin/email/error_email.html', context)\n mail.mail_admins(self._clean_subject(context['subject']), message, fail_silently=True,\n html_message=html_message)\n\n def format_details(self, details):\n if details:\n formatted = '\\n'.join('{item[0]}: {item[1]}'.format(item=item) for item in details.items())\n return 'Details:\\n{}'.format(formatted)\n\n def get_code(self, extracted_tb):\n trace = next((trace for trace in extracted_tb if 'site-packages' not in trace[0]), None)\n if not trace:\n return None\n\n filename = trace[0]\n lineno = trace[1]\n offset = 10\n with open(filename) as f:\n code_context = list(islice(f, lineno - offset, lineno + offset))\n\n return highlight(''.join(code_context),\n PythonLexer(),\n HtmlFormatter(\n noclasses=True,\n linenos='table',\n hl_lines=[offset, offset],\n linenostart=(lineno - offset + 1),\n )\n )\n\n @classmethod\n def _clean_subject(cls, subject):\n # Django raises BadHeaderError if subject contains following bad_strings\n # to guard against Header Inejction.\n # see https://docs.djangoproject.com/en/1.8/topics/email/#preventing-header-injection\n # bad-strings list from http://nyphp.org/phundamentals/8_Preventing-Email-Header-Injection\n bad_strings = [\"\\r\", \"\\n\", \"%0a\", \"%0d\", \"Content-Type:\", \"bcc:\", \"to:\", \"cc:\"]\n replacement = \"-\"\n for i in bad_strings:\n subject.replace(i, replacement)\n return subject\n\n\nclass NotifyExceptionEmailer(HqAdminEmailHandler):\n def get_context(self, record):\n context = super(NotifyExceptionEmailer, self).get_context(record)\n context['subject'] = record.getMessage()\n return context\n\n\nclass SensitiveErrorMail(ErrorMail):\n \"\"\"\n Extends Celery's ErrorMail class to prevents task args and kwargs from being printed in error emails.\n \"\"\"\n replacement = '(excluded due to sensitive nature)'\n\n def format_body(self, context):\n context['args'] = self.replacement\n context['kwargs'] = self.replacement\n return self.body.strip() % context\n","sub_path":"corehq/util/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"513555625","text":"#!usr/bin/env python \n#-*- coding:utf-8 -*-\nfrom selenium import webdriver\nimport parsel,time\nimport json,csv\nimport pymongo\nclass Douyu:\n def __init__(self):\n self.start_url = 'https://www.douyu.com/directory/all'\n self.driver = webdriver.Chrome()\n def get_content_list(self):\n source = self.driver.page_source\n sel = parsel.Selector(source)\n content_list = []\n for li in sel.xpath('//section[contains(@class,\"layout-Module\")]//ul[@class=\"layout-Cover-list\"]/li'):\n item = {}\n item['title'] = li.xpath('.//h3/@title').get()\n item['watch_num'] = li.xpath('.//span[contains(@class,\"DyListCover-hot\")]//text()').get()\n item['author_name'] = li.xpath('.//h2[contains(@class,\"DyListCover-user\")]//text()').get()\n item['root_cate'] = li.xpath('.//span[contains(@class,\"DyListCover-zone\")]/text()').get()\n item['root_img'] = li.xpath('.//img[@class=\"DyImg-content is-normal\"]/@src').get()\n print(item)\n content_list.append(item)\n next_url = self.driver.find_elements_by_xpath('//span[text()=\"下一页\"]')\n next_url = next_url[0] if len(next_url)>0 else None\n return content_list, next_url\n def save_content(self,content_list):\n with open('douyu.json','a',encoding='utf-8') as fp:\n for content in content_list:\n fp.write(json.dumps(content,ensure_ascii=False))\n fp.write('\\n')\n def run(self):\n self.driver.get(self.start_url)\n time.sleep(5)\n content_list,next_url = self.get_content_list()\n self.save_content(content_list)\n while next_url is not None:\n next_url.click()\n time.sleep(5)\n content_list,next_url = self.get_content_list()\n self.save_content(content_list)\nif __name__ == '__main__':\n douyu = Douyu()\n douyu.run()","sub_path":"spider/ArticleSpider/spiderproject/douyu.py","file_name":"douyu.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"319364650","text":"\nfrom bs4 import BeautifulSoup\nimport requests\nimport os\nimport pandas as pd\nimport textwrap\nimport pymongo\nimport datetime as datetime\n#import requests\nfrom splinter import Browser\n#from bs4 import BeautifulSoup\n#from selenium import webdriver\n#from selenium.webdriver.common.by import By\n#from selenium.webdriver.support.ui import WebDriverWait\n#from selenium.webdriver.support import expected_conditions as EC\nexecutable_path = {\"executable_path\": \"chromedriver\"}\nbrowser=Browser(\"chrome\", **executable_path, headless=False)\n\n\n#mongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_data\")\ndef scrape():\n mars_data={}\n ##conn = 'mongodb://localhost:27017'\n conn ='mongodb+srv://arinmuk:amarji123!@cluster0-omshy.mongodb.net/test?retryWrites=true'\n client = pymongo.MongoClient(conn)\n db = client.mars_data\n mars_scrape_col = db.mars_scrape.find()\n mars_data[\"scrape_time\"]=str(datetime.datetime.now())\n url1='https://mars.nasa.gov/news/'\n browser.visit(url1)\n browser.is_element_present_by_id(\"grid_gallery module list_view\", 1)\n html = browser.html\n news_soup = BeautifulSoup(html, \"html.parser\")\n #print(news_soup.prettify())\n results1 = news_soup.find_all('div', class_=\"content_title\")\n #results = soup.find_all('section', class_=\"grid_gallery module list_view\")\n results1\n news_headlines=[]\n for newst in results1:\n news_headlines.append(newst.text)\n #print(newst.text)\n #news_headlines\n #print(news_headlines[0])\n mars_data[\"news_title\"] = news_headlines[0]\n results = news_soup.find_all('div', class_=\"image_and_description_container\")\n results\n title=[]\n description=[]\n for result in results:\n # Error handling\n try:\n # Identify and return title of listing\n #desc = result.find('div', class_=\"rollover_description_inner\").text\n desc = result.find('div', class_=\"rollover_description_inner\").text\n # Identify and return price of listing\n title.append(result.a[\"href\"])\n description.append(desc)\n\n # Print results only if title, price, and link are available\n \n except AttributeError as e:\n print(e)\n #print(title[0])\n #print(description[0])\n #print(news_headlines[0])\n news_headlines\n\n mars_data[\"news_det\"] = description[0]\n\n\n\n\n ##*************************************\n url2='https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n part_urlstr='https://www.jpl.nasa.gov'\n response = requests.get(url2)\n soup2 = BeautifulSoup(response.text, 'html.parser')\n #img_res= soup2.find_all('a', class_=\"fancybox\")\n img_res= soup2.find_all('li', class_=\"slide\")\n img_res\n #img_res= soup2.find_all('div', class_=\"img\")\n #img_res\n pic=[]\n for data in img_res:\n #print(data.a[\"data-fancybox-href\"])\n try:\n pic.append(data.a[\"data-fancybox-href\"])\n except:\n print(\"done\")\n picture_url='https://www.jpl.nasa.gov' + pic[0]\n print(picture_url) \n mars_data[\"picture_url\"]=picture_url\n url3='https://twitter.com/marswxreport?lang=en'\n part_urlstr='https://twitter.com/marswxreport?lang=en'\n response = requests.get(url3)\n soup3 = BeautifulSoup(response.text, 'html.parser')\n mars_wea= soup3.find_all('p', class_=\"TweetTextSize TweetTextSize--normal js-tweet-text tweet-text\")\n mwea=[]\n for wea_res in mars_wea:\n \n #print(wea_res.text)\n #print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx')\n #if(search_string in wea_res.text ):\n #weather_data=wea_res.text\n mwea.append(wea_res.text)\n weather_mars=mwea[0] \n str_remove=weather_mars.find('pi')\n #str_len=len(weather_data)\n #cutoff= str_len-str_len\n #print(str_remove)\n #print(str_len)\n #print(cutoff)\n weather_data = weather_mars[:str_remove]\n print(weather_data)\n mars_data[\"weather\"]=weather_data\n url4='https://space-facts.com/mars/'\n table= pd.read_html(url4)\n df = table[0]\n\n #df.columns = ['Equatorial Diameter', 'Polar Diameter', 'Mass', 'Moons','Orbit Distance', 'Orbit Period', 'Surface Temperature ', 'First Record','Recorded By']\n df=df.rename(columns={0:'description',1:'value'})\n #df=df.set_index('description')\n #print(list(df.columns))\n #df.head(9)\n html_table = df.to_html()\n #html_table\n mars_data[\"fact_html\"]=html_table\n url5='https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n suburl5='https://astrogeology.usgs.gov'\n response = requests.get(url5)\n soup5 = BeautifulSoup(response.text, 'html.parser')\n hemis_pic= soup5.find_all('a', class_=\"itemLink product-item\")\n hemisphere_image_urls=[]\n dict_build={}\n for results in hemis_pic:\n dict_build={}\n txt_fix=results.text\n rmv_string=txt_fix.find(\"Enhance\")\n picture_title=txt_fix[:rmv_string]\n dict_build[\"title\"]=picture_title\n \n #print(dict_build)\n hemisphere_image_urls.append(dict_build)\n url7=suburl5+results[\"href\"]\n response = requests.get(url7)\n soup7 = BeautifulSoup(response.text, 'html.parser')\n #print(soup7.prettify())\n grab_pic= soup7.find_all('img', class_=\"wide-image\")\n #grab_pic\n for pic in grab_pic:\n #print(pic[\"src\"])\n imgtext=pic[\"src\"]\n dict_build[\"img_url\"]=suburl5+imgtext\n if hemisphere_image_urls==[]:\n hemisphere_image_urls = [\n {\"title\": \"Valles Marineris Hemisphere\", \"img_url\": \"https://astrogeology.usgs.gov/cache/images/7cf2da4bf549ed01c17f206327be4db7_valles_marineris_enhanced.tif_full.jpg\"},\n {\"title\": \"Cerberus Hemisphere\", \"img_url\": \"https://astrogeology.usgs.gov/cache/images/cfa62af2557222a02478f1fcd781d445_cerberus_enhanced.tif_full.jpg\"},\n {\"title\": \"Schiaparelli Hemisphere\", \"img_url\": \"https://astrogeology.usgs.gov/cache/images/3cdd1cbf5e0813bba925c9030d13b62e_schiaparelli_enhanced.tif_full.jpg\"},\n {\"title\": \"Syrtis Major Hemisphere\", \"img_url\": \"https://astrogeology.usgs.gov/cache/images/ae209b4e408bb6c3e67b6af38168cf28_syrtis_major_enhanced.tif_full.jpg\"},\n ]\n hemisphere_image_urls \n mars_data['hemisphere']=hemisphere_image_urls\n db.mars_scrape.update_one({},{\"$set\":mars_data},upsert=True)\n return mars_data\n\nscrape()","sub_path":"scrape_marswith_splinter.py","file_name":"scrape_marswith_splinter.py","file_ext":"py","file_size_in_byte":7081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"228569281","text":"import os\nfrom itertools import permutations\n\n\nfiles = []\n\n\ndef getFiles(fold):\n\tglobal files\n\tfor i in os.listdir(fold):\n\t\tnew = fold+'/'+i\n\t\tif os.path.isfile(new):\n\t\t\tfiles.append(new)\n\t\telse:\n\t\t\tgetFiles(new)\n\n\ndef isDup(f1, f2):\n\tf1_ext = f1.split('.')[-1]\n\tf2_ext = f2.split('.')[-1]\n\t\n\tif f1_ext == f2_ext:\n\t\treturn (f2 in [\".\".join(f1.split('.')[:-1])+'('+str(i)+').'+f1_ext for i in range(1, 6)] or\n\t\t\tf2 in [\".\".join(f1.split('.')[:-1])+' ('+str(i)+').'+f1_ext for i in range(1, 6)]\n\t\t\t)\n\treturn 0\n\n\ndef remove(fold):\n\tglobal files\n\tgetFiles(fold)\n\tfiles.sort(key=lambda x:len(x))\n\tfor i in permutations(files, 2):\n\t\tout = isDup(*i)\n\t\tif out:\n\t\t\tprint('removing ', i[1])\n\t\t\tos.system('rm -rf \"' + i[1] + '\"')\n\tfiles = []\n\n","sub_path":"removeDups.py","file_name":"removeDups.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"156192745","text":"import pygame\n\n\nclass SnakeSegment(pygame.sprite.Sprite):\n def __init__(self, position, *groups):\n pygame.sprite.Sprite.__init__(self)\n super().__init__(*groups)\n self.__size__ = (16, 16)\n self.image = pygame.Surface(self.__size__)\n self.image.fill(pygame.Color('LIGHTPINK'))\n self.rect = self.image.get_rect()\n self.position = position # used for tracking\n self.rect.topleft = self.position\n","sub_path":"src/snake_segment.py","file_name":"snake_segment.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"317799316","text":"import numpy\nimport genetic_calc\n\nclass Genetic:\n def __init__(self):\n self.initial_values = None\n\n def calculatePopulation(self,initial_values):\n\n # Pass game parameters here\n initial_values = initial_values#[4,-2,3.5,5,-11,-4.7]\n\n # Each step characteristics should represent here\n # start state of puke/disk\n # end state of disk\n # behavior- movements\n step_genes = len(initial_values)\n\n \"\"\"\n Genetic algorithm parameters:\n Mating pool size\n Population size\n \"\"\"\n sol_per_pop = 8\n num_parents_mating = 4\n\n # Defining the population size.\n pop_size = (sol_per_pop,step_genes) # The population will have sol_per_pop chromosome where each chromosome has step_genes genes.\n #Creating the initial population.\n new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size)\n print(new_population)\n\n \"\"\"\n new_population[0, :] = [2.4, 0.7, 8, -2, 5, 1.1]\n new_population[1, :] = [-0.4, 2.7, 5, -1, 7, 0.1]\n new_population[2, :] = [-1, 2, 2, -3, 2, 0.9]\n new_population[3, :] = [4, 7, 12, 6.1, 1.4, -4]\n new_population[4, :] = [3.1, 4, 0, 2.4, 4.8, 0]\n new_population[5, :] = [-2, 3, -7, 6, 3, 3]\n \"\"\"\n\n best_outputs = []\n num_generations = 1000\n for generation in range(num_generations):\n print(\"Generation : \", generation)\n # Measuring the fitness of each chromosome in the population.\n fitness = genetic_calc.cal_pop_fitness(initial_values, new_population)\n print(\"Fitness\")\n print(fitness)\n\n best_outputs.append(numpy.max(numpy.sum(new_population*initial_values, axis=1)))\n # The best result in the current iteration.\n print(\"Best result : \", numpy.max(numpy.sum(new_population*initial_values, axis=1)))\n \n # Selecting the best parents in the population for mating.\n parents = genetic_calc.select_mating_pool(new_population, fitness, \n num_parents_mating)\n print(\"Parents\")\n print(parents)\n\n # Generating next generation using crossover.\n offspring_crossover = genetic_calc.crossover(parents,\n offspring_size=(pop_size[0]-parents.shape[0], step_genes))\n print(\"Crossover\")\n print(offspring_crossover)\n\n # Adding some variations to the offspring using mutation.\n offspring_mutation = genetic_calc.mutation(offspring_crossover)\n print(\"Mutation\")\n print(offspring_mutation)\n\n # Creating the new population based on the parents and offspring.\n new_population[0:parents.shape[0], :] = parents\n new_population[parents.shape[0]:, :] = offspring_mutation\n \n # Getting the best solution after iterating finishing all generations.\n #At first, the fitness is calculated for each solution in the final generation.\n fitness = genetic_calc.cal_pop_fitness(initial_values, new_population)\n # Then return the index of that solution corresponding to the best fitness.\n best_match_idx = numpy.where(fitness == numpy.max(fitness))\n\n print(\"Best solution : \", new_population[best_match_idx, :])\n print(\"Best solution fitness : \", fitness[best_match_idx])\n\n\n import matplotlib.pyplot\n matplotlib.pyplot.plot(best_outputs)\n matplotlib.pyplot.xlabel(\"Iteration\")\n matplotlib.pyplot.ylabel(\"Fitness\")\n matplotlib.pyplot.show()","sub_path":"xkon_hockey/envs/genetic_env/genetic_env.py","file_name":"genetic_env.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"382909392","text":"import os\nimport csv\nimport tensorflow as tf\nimport numpy as np\nimport random\n\ndata = []\n\niterations = 5000\nbatch_size = 100\nplot_period = 100\ntraining_range_lower_bound = 12000\ntraining_range_upper_bound = 14000\nnum_inputs = 7\nnum_outputs = 1\nstep_size = 0.000005\n\nmuscle_activation = []\nf_out = []\n\ndef pullData():\n global data\n with open('data/matrix.csv') as csvfile:\n rowReader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for row in rowReader:\n data.append(', '.join(row).split(','))\n\n data = data[1:]\n\n #muscle_activation = np.array([])\n #f_out = np.array([])\n\n for i in data:\n #a = np.array([i[2], i[4], i[6], i[8], i[10], i[12], i[14]])\n #np.append(muscle_activation, a)\n #np.append(f_out, i[18])\n a = []\n for j in range(15):\n if j%2==0 and j!=0:\n a.append(i[j])\n muscle_activation.append(a)\n #muscle_activation.append([tf.placeholder(i[2]), i[4], i[6], i[8], i[10], i[12], i[14]])\n #f_out.append([i[18], i[16], i[21], i[17], i[20], i[19]]) # F_x, F_y, F_z, M_x, M_y, M_z\n f_out.append([i[18]])\n\ndef trainData():\n global W_arr\n global bias\n x = tf.placeholder(tf.float32, shape=(None, num_inputs))\n W = tf.Variable(tf.zeros([num_inputs,num_outputs]))\n b = tf.Variable(tf.zeros([num_outputs]))\n\n y = tf.matmul(x,W) + b\n\n y_ = tf.placeholder(tf.float32, shape=(None,num_outputs))\n\n cost = tf.reduce_sum(tf.square(y-y_))\n #cost = -tf.reduce_sum(y_*tf.log(y) + (1-y_) * tf.log(1-y))\n #cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))\n\n\n W_arr = 0\n bias = 0\n\n train_step = tf.train.GradientDescentOptimizer(step_size).minimize(cost)\n init = tf.initialize_all_variables()\n\n sess = tf.Session()\n sess.run(init)\n\n if os.path.isfile('linear_14k.txt'):\n os.remove('linear_14k.txt')\n f = open('linear_14k.txt', 'w')\n for i in range(iterations): #iterations\n muscle_activation_batch = []\n f_out_batch = []\n for k in range(batch_size):\n temprand = random.randint(1,training_range_lower_bound)\n muscle_activation_batch.append(muscle_activation[temprand])\n f_out_batch.append(f_out[temprand])\n\n feed = {x: muscle_activation_batch, y_: f_out_batch}\n sess.run(train_step, feed_dict=feed)\n\n if i%100==0:\n print(\"After %d iteration:\" %i)\n print(\"W:\")\n print(sess.run(W))\n print(\"b\")\n print(sess.run(b))\n\n W_arr = sess.run(W)\n bias = sess.run(b)[0]\n\n if i%plot_period==0:\n f.write(str(getError()[0]))\n f.write('\\n')\n\n\n\n\n#validation set\ndef getError():\n print(\"ERROR: \")\n\n mean_square_sum_error = 0\n average_percentage_error = 0\n\n for i in range(training_range_lower_bound, training_range_upper_bound):\n expected_value = float(data[i][18])\n predicted_value = 0\n predicted_muscle_activations = []\n for j in range(15):\n if j%2==0 and j!=0:\n predicted_muscle_activations.append(float(data[i][j]))\n\n for j,k in enumerate(W_arr):\n predicted_value += predicted_muscle_activations[j]*k\n\n predicted_value+=bias\n average_percentage_error += abs(predicted_value-expected_value)/expected_value\n mean_square_sum_error += (predicted_value-expected_value)**2\n #print \"predicted: \" , predicted_value , \" actual: \" , expected_value\n\n #mean_square_sum_error/=(training_range_upper_bound-training_range_lower_bound+1)\n average_percentage_error/=(training_range_upper_bound-training_range_lower_bound+1)\n #mean_square_sum_error = mean_square_sum_error/(training_range_upper_bound-training_range_lower_bound+1)\n\n print(\"Sum of Square Error: \")\n print(mean_square_sum_error)\n return mean_square_sum_error\n\n #print \"Average Error: \"\n #print average_percentage_error\n\npullData()\ntrainData()\ngetError()\n","sub_path":"linear_regression_14k.py","file_name":"linear_regression_14k.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"541248307","text":"from sqlalchemy.orm import sessionmaker\nfrom persistence_layer import Base\nfrom sqlalchemy import create_engine\nimport logging\nimport traceback\nfrom sqlalchemy.exc import IntegrityError\nfrom persistence_layer import User\n\n__author__ = 'bryson'\n\nengine = create_engine(\"sqlite:////vagrant/database/database.db\")\n\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\n\n\ndef save_user(user):\n try:\n session = DBSession()\n session.add(user)\n session.commit()\n session.close()\n except IntegrityError:\n tb = traceback.format_exc()\n logging.error(\"Failed to save user: \" +\n str(user.username) + \"\\n\" +\n str(tb))\n return False\n return True\n\n\ndef get_user(username):\n \"\"\"\n :param username:\n :return: The User with the corresponding username\n \"\"\"\n session = DBSession()\n user = session.query(User).filter_by(username=username).first()\n session.close()\n return user","sub_path":"src/database/user_dao.py","file_name":"user_dao.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"138464560","text":"\"\"\"\nDIR=$(ls -d /home/satsingh/plume/plumezoo/latest/fly/memory/*VRNN*/ | head -n 1)\necho $DIR\npython -u postEvalCli.py --model_dir $DIR --viz_episodes 2 \n\n\n# Batch\nMODELDIRS=$(ls -d /home/satsingh/plume/plumezoo/latest/fly/memory/*VRNN*seed3199993/)\nMODELDIRS=$(ls -d /home/satsingh/plume/plumezoo/latest/fly/memory/*VRNN*seed9781ba/)\nMODELDIRS=$(ls -d /home/satsingh/plume/plumezoo/latest/fly/memory/*VRNN*seed3307e9/)\nMODELDIRS=$(ls -d /home/satsingh/plume/plumezoo/latest/fly/memory/*VRNN*/)\necho $MODELDIRS\nfor DIR in $MODELDIRS; do\n LOGFILE=${DIR}/posteval.log\n python -u postEvalCli.py --model_dir $DIR \\\n --viz_episodes 20 >> $LOGFILE 2>&1 &\ndone\n# --walking False # does NOT work that way!\n#tail -f /home/satsingh/plume/plumezoo/latest/fly/memory/*VRNN*/posteval.log\n\n# Sparse\nfor DIR in $MODELDIRS; do\n LOGFILE=${DIR}/posteval.log\n python -u postEvalCli.py --model_dir $DIR \\\n --viz_episodes 20 --birthxs 0.4 >> $LOGFILE 2>&1 &\ndone\n\ntail -f $LOGFILE\n\n# Stitch videos side-by-side: see vid_stitch_cli for more options\nfor FNEURAL in $(find /home/satsingh/plume/plumezoo/latest/fly/memory/ -name \"*pca3d_common_ep*.mp4\"); do \n FTRAJ=$(echo $FNEURAL | sed s/_pca3d_common//g) \n # echo $FNEURAL $FTRAJ\n python -u ~/plume/plume2/vid_stitch_cli.py --fneural $FNEURAL --ftraj $FTRAJ\ndone\n\n# Stitch videos side-by-side: see vid_stitch_cli for more options\nMAXJOBS=20\nfor FNEURAL in $(find /home/satsingh/plume/plumezoo/latest/fly/memory/ -name \"*pca3d_common_ep*.mp4\"); do \n while (( $(jobs -p | wc -l) >= MAXJOBS )); do sleep 10; done \n FTRAJ=$(echo $FNEURAL | sed s/_pca3d_common//g) \n # echo $FNEURAL $FTRAJ\n python -u ~/plume/plume2/vid_stitch_cli.py --fneural $FNEURAL --ftraj $FTRAJ &\ndone\n\n\n\"\"\"\nfrom __future__ import division\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nimport os\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\"\n\nimport torch\nimport argparse\nimport os\nimport sys\nimport numpy as np\nimport torch\nimport pandas as pd\nimport pickle\n\nimport glob\nimport pickle\nfrom natsort import natsorted\n\nimport traceback\n\nimport matplotlib \nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nfrom pprint import pprint\nimport glob\nimport sys\nsys.path.append('../')\n# sys.path.append('/home/satsingh/plume/plume2/')\nfrom plume_env import PlumeEnvironment, PlumeFrameStackEnvironment\nimport agents\nimport agent_analysis\nimport os\nimport log_analysis\nimport arch_utils as archu\nimport vid_stitch_cli\n\nimport sklearn.decomposition as skld\n\n\ndef post_eval(model_dir, use_datasets, n_episodes_home, n_episodes_other, viz_episodes):\n is_recurrent = True if ('GRU' in model_dir) or ('VRNN' in model_dir) else False\n\n selected_df = log_analysis.get_selected_df(model_dir, \n use_datasets, \n n_episodes_home=60, \n n_episodes_other=60,\n min_ep_steps=0)\n\n\n # Generate common PCA\n h_episodes = []\n traj_dfs = []\n squash_action = True\n\n for episode_log in selected_df['log']:\n ep_activity = log_analysis.get_activity(episode_log, \n is_recurrent, do_plot=False)\n h_episodes.append(ep_activity)\n \n h_episodes_stacked = np.vstack(h_episodes)\n # print(h_episodes_stacked.shape)\n\n pca_common = skld.PCA(3, whiten=False)\n pca_common.fit(h_episodes_stacked)\n\n # Get neural net \n try:\n model_fname = model_dir[:-1] + \".pt\"\n is_recurrent = True if ('GRU' in model_dir) or ('VRNN' in model_dir) else False\n actor_critic, ob_rms = \\\n torch.load(model_fname, map_location=torch.device('cpu'))\n net = actor_critic.base.rnn #.weight_hh_l0.detach().numpy()\n J0 = net.weight_hh_l0.detach().numpy()\n except Exception as e:\n print(f\"Exception: {e}\")\n\n\n # Animate (1) trajectory, (2) Neural on common subspace, (3) eigen \n # subset_df = selected_df.groupby(['dataset', 'outcome']).sample(viz_episodes)\n # subset_df = selected_df.query(\"outcome == 'HOME' and dataset == 'noisy3x5b5'\").sample(viz_episodes)\n # subset_df = selected_df.query(\"outcome == 'HOME' and dataset == 'constantx5b5'\").sample(viz_episodes)\n # subset_df = selected_df.query(\"outcome == 'HOME' and dataset == 'switch45x5b5'\").sample(viz_episodes)\n # subset_df = selected_df.query(\"outcome == 'OOB' and dataset == 'noisy3x5b5'\").sample(viz_episodes)\n # subset_df = selected_df.query(\"outcome == 'OOB' and dataset == 'constantx5b5'\").sample(viz_episodes)\n # subset_df = selected_df.query(\"outcome == 'OOB' and dataset == 'switch45x5b5'\").sample(viz_episodes)\n # subset_df = selected_df.query(\"dataset == 'noisy3x5b5'\").groupby(['dataset', 'outcome']).sample(viz_episodes)\n # subset_df = selected_df.query(\"dataset == 'constantx5b5'\").groupby(['dataset', 'outcome']).sample(viz_episodes)\n # subset_df = selected_df.query(\"dataset == 'switch45x5b5'\").groupby(['dataset', 'outcome']).sample(viz_episodes)\n subset_df = selected_df.groupby(['dataset', 'outcome']).head(viz_episodes)\n for idx, row in subset_df.iterrows():\n if args.birthxs is not None: # HACK!!!!\n continue\n\n ep_activity = log_analysis.get_activity(row['log'], \n is_recurrent, \n do_plot=False)\n traj_df = log_analysis.get_traj_df(row['log'], \n extended_metadata=False, \n squash_action=squash_action)\n OUTPREFIX = model_dir\n dataset = row['dataset']\n outcome = row['outcome']\n fprefix = f'{row[\"dataset\"]}_{outcome}'\n\n try:\n # Need to regenerate since no guarantee present already?\n zoom = 1 if 'constant' in dataset else 2 \n zoom = 4 if ('constant' in dataset) and ('HOME' not in outcome) else zoom \n # zoom = 0 \n zoom = 3 if args.walking else zoom\n agent_analysis.visualize_episodes(episode_logs=[row['log']], \n episode_idxs=[row['idx']],\n zoom=zoom, \n dataset=row['dataset'],\n animate=True,\n fprefix=fprefix,\n diffusionx=args.diffusionx,\n outprefix=OUTPREFIX,\n ) \n\n log_analysis.animate_activity_1episode(ep_activity, \n traj_df, \n row['idx'], \n fprefix=fprefix,\n outprefix=OUTPREFIX,\n pca_dims=3,\n pca_common=pca_common)\n\n # eig animations/plots\n eig_df = archu.get_eig_df_episode(net, row['log'])\n fname_suffix = f\"{fprefix}_ep{row['idx']}\"\n archu.animate_Jh_episode(eig_df, \n fname_suffix=fname_suffix, \n outprefix=OUTPREFIX)\n eig_vals, eig_vecs = np.linalg.eig(J0)\n archu.plot_eigvec_projections(eig_vals, \n eig_vecs, \n ep_activity, \n fname_suffix=fname_suffix, \n outprefix=OUTPREFIX)\n\n except Exception as e:\n print(f\"Exception: {e}\", traceback.print_exc())\n\n\n # DIRTY Hack to add sparse videos\n logfiles = natsorted(glob.glob(model_dir + '*.pkl'))\n if args.birthxs is not None:\n for birthx in args.birthxs:\n sparse_dataset = [f'constantx5b5_{birthx}']\n try:\n sparse_selected_df = log_analysis.get_selected_df(model_dir, \n sparse_dataset, \n n_episodes_home=60, \n n_episodes_other=60,\n min_ep_steps=0)\n except Exception as e:\n print(f\"Exception: {e}\", traceback.print_exc())\n continue\n\n sparse_subset_df = sparse_selected_df.groupby(['dataset', 'outcome']).sample(viz_episodes)\n # sparse_subset_df = sparse_selected_df.query(\"outcome == 'OOB'\").sample(viz_episodes)\n for idx, row in sparse_subset_df.iterrows():\n ep_activity = log_analysis.get_activity(row['log'], \n is_recurrent, \n do_plot=False)\n traj_df = log_analysis.get_traj_df(row['log'], \n extended_metadata=False, \n squash_action=squash_action)\n OUTPREFIX = model_dir\n dataset = row['dataset'].split('_')[0]\n outcome = row['outcome']\n fprefix = f'{row[\"dataset\"]}_{outcome}'\n print(\"dataset\",dataset)\n\n try:\n # Need to regenerate since no guarantee present already?\n zoom = 1 if 'constant' in dataset else 2 \n zoom = 4 if ('constant' in dataset) and ('HOME' not in outcome) else zoom \n # zoom = 0 \n zoom = 3 if args.walking else zoom\n agent_analysis.visualize_episodes(episode_logs=[row['log']], \n episode_idxs=[row['idx']],\n zoom=zoom, \n dataset=dataset,\n animate=True,\n fprefix=fprefix,\n outprefix=OUTPREFIX,\n birthx=float(birthx),\n diffusionx=args.diffusionx,\n ) \n\n log_analysis.animate_activity_1episode(ep_activity, \n traj_df, \n row['idx'], \n fprefix=fprefix,\n outprefix=OUTPREFIX,\n pca_dims=3,\n pca_common=pca_common)\n\n # eig animations/plots\n eig_df = archu.get_eig_df_episode(net, row['log'])\n fname_suffix = f\"{fprefix}_ep{row['idx']}\"\n archu.animate_Jh_episode(eig_df, \n fname_suffix=fname_suffix, \n outprefix=OUTPREFIX)\n eig_vals, eig_vecs = np.linalg.eig(J0)\n archu.plot_eigvec_projections(eig_vals, \n eig_vecs, \n ep_activity, \n fname_suffix=fname_suffix, \n outprefix=OUTPREFIX)\n\n except Exception as e:\n print(f\"Exception: {e}\", traceback.print_exc())\n\n\n### MAIN ###\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Common neural subspace plots/animations')\n parser.add_argument('--model_dir', default=None)\n parser.add_argument('--viz_episodes', type=int, default=2)\n parser.add_argument('--walking', type=bool, default=False)\n parser.add_argument('--birthxs', type=str, nargs='+', default=None)\n parser.add_argument('--diffusionx', type=float, default=1.0)\n\n args = parser.parse_args()\n print(args)\n use_datasets = ['constantx5b5', 'switch45x5b5', 'noisy3x5b5']\n n_episodes_home = 30\n n_episodes_other = 30\n\n post_eval(args.model_dir, \n use_datasets, \n n_episodes_home, \n n_episodes_other, \n args.viz_episodes)","sub_path":"code/ppo/postEvalCli.py","file_name":"postEvalCli.py","file_ext":"py","file_size_in_byte":11865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"202500908","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport sys,os,json,requests,copy,logging\nimport traceback\nfrom datetime import datetime\n\n\nfrom aiohttp import web\nfrom aiohttp.web import Request, Response, json_response\nfrom botbuilder.core import (\n BotFrameworkAdapterSettings,\n TurnContext,\n BotFrameworkAdapter,\n)\nfrom botbuilder.core.integration import aiohttp_error_middleware\nfrom botbuilder.schema import Activity, ActivityTypes\n\nfrom bot import MyBot\nfrom config import DefaultConfig\nfrom cards.reminderCard import prepareReminderCard\n\nCONFIG = DefaultConfig()\n\n# Create adapter.\n# See https://aka.ms/about-bot-adapter to learn more about how bots work.\nSETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)\nADAPTER = BotFrameworkAdapter(SETTINGS)\n\n\n# Catch-all for errors.\nasync def on_error(context: TurnContext, error: Exception):\n # This check writes out errors to console log .vs. app insights.\n # NOTE: In production environment, you should consider logging this to Azure\n # application insights.\n print(f\"\\n [on_turn_error] unhandled error: {error}\", file=sys.stderr)\n traceback.print_exc()\n\n # Send a message to the user\n await context.send_activity(\"The bot encountered an error or bug.\")\n await context.send_activity(\n \"To continue to run this bot, please fix the bot source code.\"\n )\n # Send a trace activity if we're talking to the Bot Framework Emulator\n if context.activity.channel_id == \"emulator\":\n # Create a trace activity that contains the error object\n trace_activity = Activity(\n label=\"TurnError\",\n name=\"on_turn_error Trace\",\n timestamp=datetime.utcnow(),\n type=ActivityTypes.trace,\n value=f\"{error}\",\n value_type=\"https://www.botframework.com/schemas/error\",\n )\n # Send a trace activity, which will be displayed in Bot Framework Emulator\n await context.send_activity(trace_activity)\n\n\nADAPTER.on_turn_error = on_error\n\n# Create the Bot\nBOT = MyBot()\n\n\n# Listen for incoming requests on /api/messages\nasync def messages(req: Request) -> Response:\n # Main bot message handler.\n if \"application/json\" in req.headers[\"Content-Type\"]:\n body = await req.json()\n else:\n return Response(status=415)\n activity = Activity().deserialize(body)\n auth_header = req.headers[\"Authorization\"] if \"Authorization\" in req.headers else \"\"\n\n response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)\n if response:\n return json_response(data=response.body, status=response.status)\n return Response(status=201)\n\nroutes = web.RouteTableDef()\n@routes.post('/api/v1/cron-messages')\nasync def sendReminder(request):\n try:\n todoInfo = await request.json() # suppose a dict now \n # {'tenant_id': '98fb227d-9ccb-46af-bbc7-7adfb3090fa6', \n # 'user_id': '29:1EHxt_msQczs0jFpTh3HUdDzzbQhOQLsins3m8VHWjctZ2DF7Htq-89Dmv3T-t6KhnJxn2uzoNL1r5qNEu3myiQ', \n # 'todo': {'todo_id': 'Gq31ES4ipg', 'todo_name': 'test_cronjob', \n # 'todo_date': datetime.datetime(2021, 8, 6, 2, 0), \n # 'todo_contents': 'test_cronjob', 'todo_update_date': '2021/08/05', \n # 'todo_completed': False, 'employee_id': '109491'}}\n teams_appid='30eba4f2-6e15-458b-9fdf-f8bbf25efb4f'\n appSecret='ElizaHuangTaigidian2021'\n botId='28:30eba4f2-6e15-458b-9fdf-f8bbf25efb4f'\n userId=todoInfo['user_id'] \n tenant_id=todoInfo['tenant_id']\n cardToSend=prepareReminderCard(todoInfo[\"todo\"])\n ## access token\n url='https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token'\n payload = {'Host': 'login.microsoftonline.com',\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n 'grant_type':'client_credentials',\n 'client_id':teams_appid,\n 'client_secret':appSecret,\n 'scope':'https://api.botframework.com/.default'}\n \n r=requests.post(url, data=(payload))\n response=json.loads(r.content.decode('utf-8')) \n access_token=response['access_token'] \n print('access_token:\\n',access_token) \n \n ## get conversationId\n header={'Authorization': 'Bearer ' + access_token} #, 'content-type':'application/json'\n url=f'https://smba.trafficmanager.net/apac/v3/conversations'\n payload={\n \"bot\": {\n \"id\": botId,#30eba4f2-6e15-458b-9fdf-f8bbf25efb4f\n # \"name\": \"AzureBot001_Regis\"\n },\n \"isGroup\": False,\n \"members\": [\n {\n \"id\": userId, #usesrid_office,\n \"name\":\"\" #\"Yi Huang 黃懿\"\n }\n ],\n \"tenantId\": tenant_id,\n \"topicName\": \"proactive msg\"\n }\n conversation_response=json.loads(requests.post(url,json=(payload), headers=header).content.decode('utf-8'))\n conversation_id=conversation_response[\"id\"]\n print('conversation_id: \\n',conversation_id)\n\n url=f'https://smba.trafficmanager.net/apac/v3/conversations/%s/activities'%(conversation_id)\n payload_template={\n \"type\": \"message\",\n \"from\": {\n \"id\": botId,\n \"name\": \"AzureBot001_Regis\"\n },\n \"conversation\": {\n \"id\": conversation_id,\n \"name\": \"send proactive msg now\"\n },\n \"recipient\": {\n \"id\": userId,\n \"name\":\"\",# \"Yi Huang 黃懿\"\n },\n \"attachments\": []\n }\n payload=copy.deepcopy(payload_template)\n payload[\"attachments\"]+=[cardToSend]\n response_forSendMsg =requests.post(url, json=(payload), headers=header).content.decode('utf-8')\n print('response_forSendMsg',response_forSendMsg)\n \n return Response(status=200)\n \n except Exception as e:\n logging.error('Error Msg: ', exc_info=e)\n return Response(status=500)\n \n\n\nAPP = web.Application(middlewares=[aiohttp_error_middleware])\nAPP.router.add_post(\"/api/messages\", messages)\nAPP.add_routes(routes)\n# APP.router.add_post(\"/api/v1/cron-messages\",sendReminder)\n\n\nif __name__ == \"__main__\":\n try:\n # web.run_app(APP, host=\"localhost\", port=CONFIG.PORT)\n port = os.getenv('PORT', default=CONFIG.PORT)\n web.run_app(APP,port=port)\n except Exception as error:\n raise error\n","sub_path":"azure_chatbot/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"532706503","text":"\nfrom Tkinter import *\nimport Main\n#from RefreshCamList import *\nimport Image, ImageTk\n\nCamNameSelected=''\n\nclass ComboBox():\n\tdef __init__(self,x,y):\n\t\tself.Names=x\n\t\tself.Dict=y\n\tdef ValueSelected(self):\n\t\tTempString=''\n\t\tTempString=self.Dict[self.z.get()]\n\t\td=int(TempString[5:6])\n\t\tself.window1.destroy()\n\t\tMain.Main(d)\t\t\n\tdef CreateComboBox(self):\n\t\tself.window1=Tk() #A window is created\n\t\tself.window1.geometry(\"270x60\") \n\t\tself.z= StringVar(self.window1) #object of StringVar() class that will store the value selected from combo box\n\t\tself.window1.title(\"Select Webcam\") #Title of the window is declared here\n\t\tself.z.set(self.Names[0])\n\t\tself.w =OptionMenu(self.window1,self.z,*self.Names)\n\t\tself.w.pack()\n\t\tself.b1 = Button(self.window1, text=\"OK\", command=self.ValueSelected)\n\t\tself.b1.pack()\n\t\tself.window1.mainloop() #the window which was created is started\n\t\t\n\t\t\n","sub_path":"ValueSelected.py","file_name":"ValueSelected.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"27570150","text":"class Group(object):\n def __init__(self, _name):\n self.name = _name\n self.groups = []\n self.users = []\n\n def add_group(self, group):\n self.groups.append(group)\n\n def add_user(self, user):\n self.users.append(user)\n\n def get_groups(self):\n return self.groups\n\n def get_users(self):\n return self.users\n\n def get_name(self):\n return self.name\n\n def is_user_in_group(self, user, group):\n if not hasattr(group, 'users'):\n return False\n if group == None:\n return False\n for u in group.users :\n if u == user :\n print (\"user {\" + u + \"}\" + \" is in group {\" + group.name + \"} \")\n return True\n\n for g in group.groups :\n self.is_user_in_group(user, g)\n return False\n \n\nclass TestCase() :\n def case1 (self):\n parent = Group(\"parent\")\n child = Group(\"child\")\n sub_child = Group(\"subchild\")\n\n sub_child_user = \"sub_child_user\"\n sub_child.add_user(sub_child_user)\n\n child.add_group(sub_child)\n parent.add_group(child)\n print ('is_user_in_group:')\n print(parent.is_user_in_group(sub_child_user, parent))\n\n\n def case2 (self):\n parent = Group(\"parent\")\n child = Group(\"child\")\n sub_child = Group(\"subchild\")\n\n sub_child_user = \"sub_child_user\"\n sub_child.add_user(sub_child_user)\n parent_user = \"parent_user\"\n child.add_group(sub_child)\n parent.add_group(child)\n parent.add_user(parent_user)\n print ('is_user_in_group:')\n print(parent.is_user_in_group(None, None))\n\n\n def case3 (self):\n parent = Group(\"parent\")\n child = Group(\"child\")\n sub_child = Group(\"subchild\")\n ssub_child = Group(\"ssubchild\")\n sub_child_user = \"sub_child_user\"\n sub_child.add_user(sub_child_user)\n ssub_child_user = \"ssub_child_user\"\n ssub_child.add_group(ssub_child)\n child.add_group(sub_child)\n parent.add_group(child)\n ssub_child.add_user(ssub_child_user)\n print ('is_user_in_group:')\n print(parent.is_user_in_group(sub_child_user, sub_child_user))\n\nif __name__ == \"__main__\":\n # Test case 1 :\n TestCase().case1()\n # Test case 2 :\n TestCase().case2()\n # Test case 3 :\n TestCase().case3()\n # #console output you expect to see:\n '''\n is_user_in_group:\n user {sub_child_user} is in group {subchild} \n False\n is_user_in_group:\n False\n is_user_in_group:\n False\n '''","sub_path":"P2/problem_4.py","file_name":"problem_4.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"151430959","text":"from components import *\nimport numpy as np\nimport copy\nfrom linsolve import LinearSystem\nimport math\nfrom utils import timer_decorator\n\nclass Circuit(object):\n\t\"\"\"\n\tClass to represent a circuit, which is effectively a collection\n\tof components. This class also provides mechanisms to perform\n\tvarious analyses on the circuit, such as the transient analysis which\n\tis required for the guitar pedal simulator.\n\t\"\"\"\n\n\tdef __init__(self, components):\n\t\t\"\"\"\n\t\tInitialize the circuit object based on a collection of components\n\t\tthat make up the circuit.\n\t\t\"\"\"\n\n\t\t# register all components, tracking relevant unknowns as we go\n\t\tself.unknowns = dict()\n\t\tself.next_unknown = 0\n\t\tself.components = components\n\t\tfor component in self.components:\n\t\t\tself.register_component(component)\n\n\t\t# start at t = 0, with our initial guesses zerod out\n\t\tself.current_time = 0.0\n\t\tself.soln = np.zeros((self.total_unknowns, 1))\n\t\tself.prev_soln = np.zeros((self.total_unknowns, 1))\n\n\tdef timescale(self):\n\t\t\"\"\"\n\t\tReturns the time axis values used in the simulation of this\n\t\tcircuit.\n\t\t\"\"\"\n\t\treturn self.voltage_in.timescale()\n\n\tdef register_component(self, component):\n\t\t\"\"\"\n\t\tRegisters a component by updating any necessary metadata and\n\t\trecording any new unknowns that this component may introduce.\n\t\t\"\"\"\n\n\t\t# check to see if this is a registered ground\n\t\tif isinstance(component, Ground):\n\t\t\tself.ground = component.node_id\n\n\t\tif isinstance(component, VoltageIn):\n\t\t\tself.voltage_in = component\n\n\t\tif isinstance(component, VoltageOut):\n\t\t\tout_pos, out_neg = component.terminals()\n\t\t\tself.out_pos_id = self.unknowns[out_pos]\n\t\t\tself.out_neg_id = self.unknowns[out_neg]\n\n\t\t# find all unknowns that this element contributes to\n\t\t# the system of equations we'll need to solve for this\n\t\t# circuit\n\t\tfor unknown in component.unknowns():\n\t\t\tif unknown not in self.unknowns:\n\t\t\t\tself.unknowns[unknown] = self.next_unknown\n\t\t\t\tself.next_unknown += 1\n\n\t\tself.total_unknowns = len(self.unknowns)\n\n\tdef build_matrix(self, time, dt):\n\t\t\"\"\"\n\t\tBuilds and returns the matrix of KCL equations and voltage constraints\n\t\tbased on this circuit and the current operating points of all\n\t\tcomponents.\n\t\t\"\"\"\n\t\tsystem = LinearSystem(self.unknowns, self.ground)\n\t\tfor component in self.components:\n\t\t\tcomponent.add_matrix_contribution(\n\t\t\t\tsystem,\n\t\t\t\tself.soln,\n\t\t\t\tself.prev_soln,\n\t\t\t\tdt,\n\t\t\t\ttime)\n\t\treturn system\n\n\tdef process_deltas(self, deltas, tolerance=1e-8):\n\t\tmax_delta = max(abs(deltas[i][0]) for i in range(self.total_unknowns))\n\t\tconverged = max_delta < tolerance or math.isnan(max_delta)\n\t\tfor i in range(self.total_unknowns):\n\t\t\tself.prev_soln[i][0] += deltas[i][0]\n\t\treturn converged\n\n\t@timer_decorator\n\tdef transient(self, max_iterations=100):\n\n\t\tsolution = [] # the output voltages\n\t\tinput_signal = [] # the input voltages\n\t\ttimescale = [] # the timestamp associated with each sample\n\n\t\tdt = self.voltage_in.timestep()\n\n\t\tfor (time, voltage) in self.voltage_in:\n\n\t\t\t# record timestamp and input signal\n\t\t\ttimescale.append(time)\n\t\t\tinput_signal.append(voltage)\n\n\t\t\t# copy solution from prev iteration into prev_soln\n\t\t\tself.prev_soln[:] = self.soln\n\n\t\t\t# perform newton's method until convergence,\n\t\t\t# reconstructing KCL/constraint matrix each time\n\t\t\tfor iteration in range(max_iterations):\n\t\t\t\tsystem = self.build_matrix(time, dt)\n\t\t\t\tdeltas = system.solve()\n\t\t\t\tconverged = self.process_deltas(deltas)\n\t\t\t\tif converged: break\n\n\t\t\t# now we have final solution for all the unknowns\n\t\t\tself.soln[:] = self.prev_soln\n\n\t\t\t# calculate and record output voltage at this timestamp\n\t\t\tvpos = self.soln[self.out_pos_id][0]\n\t\t\tvneg = self.soln[self.out_neg_id][0]\n\t\t\tvout = vpos - vneg\n\t\t\tsolution.append(vout)\n\n\t\treturn timescale, input_signal, solution\n","sub_path":"pysim/circuit.py","file_name":"circuit.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"409949247","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 3 14:03:33 2018\n\n@author: gracielaaguilar\n\"\"\"\n\nfrom socket import * # used for socket configurations \nimport sys # used to get arguments on command line\nimport time # used to find current time\nimport networkx as nx\nimport numpy as np\nimport pickle\n\ngraph = np.array([[0,4,3,0,7,0,0,0],[4,0,6,0,0,0,0,5], [3,6,0,11,0,0,0,0],\n [0,0,11,0,0,6,10,9], [7,0,0,0,0,0,5,0], [0,0,0,6,0,0,0,5],\n [0,0,0,10,5,0,0,0],[0,5,0,9,0,5,0,0]])\n\n\nG = nx.from_numpy_matrix(graph, create_using=nx.DiGraph())\ndef dijAlg(route, node):\n \n print(\"for Router\",route[node], \":\")\n \n \n print(\"Destination Distance Shortest Path\")\n for i in range(8):\n \n result = []\n path = nx.dijkstra_path(G, node, i)\n ix =[[path[i],path[i+1]] for i in range(len(path)-1)]\n total = sum([graph[i[0]][i[1]] for i in ix])\n for j in range (0, len(path)):\n num = path[j]\n \n #print(counter)\n result.append(route[num]) \n print(route[i],\" \", total, \" \", result)\n total = 0\n \nrouters = ['A','B','C','D','E','F','G','L']\n\ndijAlg (routers, 6)\n\nport = 8089 # this router, F, gets connected to port 8083 as a client \nserverName = \"localhost\"\n\nclientSocket = socket(AF_INET, SOCK_STREAM) # AF_INET = IPv4, SOCK_STREAM = TCP socket\nclientSocket.connect((serverName, port)) # connects the client and the server together\n\n\ndef getPathAndMessage(data):\n # extract path from data\n #data = data.decode() # decode message because the data is coming as a bytes \n data = data.split('/')\n path = data[0]\n message = data[1]\n \n return (path, message)\n\ndef getNextData(path, message):\n nextPath = path.split()\n port = int(nextPath[0])\n\n # fix path; pop from list\n newPath = \"\"\n i = 1\n while i < len(nextPath):\n newPath = newPath + \" \" + nextPath[i]\n i += 1\n path = newPath + \"/\"\n data = path + message\n\n return data, port\n\n# send and receive data\nconnectedFlag = False # use to check is server is already in use\n\nwhile 1:\n #**************************************************\n receivedData = clientSocket.recv(1024) # recieve message from sender\n receivedDataList = pickle.loads(receivedData) # convert data in list format: [destination[0], pathMessage, flags]\n path, message = getPathAndMessage(receivedDataList[2]) # sends data for processing\n print (\"Destination: \", receivedDataList[0])\n print(\"path = \", path)\n print(\"message = \", message)\n #displayDataFlags(receivedDataList[2])\n #*************************************************\n receivedDataList[2], port = getNextData(path, message) # get next path for which the message should go\n\n if (connectedFlag != True):\n #prepare server socket\n serverSocket = socket(AF_INET,SOCK_STREAM) # AF_INET = IPv4, SOCK_STREAM = TCP socket\n serverSocket.bind((serverName, port)) # bind the socket to the local address\n serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n serverSocket.listen(5)\n connectionSocket, addr = serverSocket.accept()\n connectedFlag = True\n\n # send data to next client/server\n receivedDataList = pickle.dumps(receivedDataList)\n connectionSocket.send(receivedDataList)\n\n # recieve data and send it to next port\n #**************************************************\n receivedData = clientSocket.recv(1024) # recieve message from sender\n receivedDataList = pickle.loads(receivedData) # convert data in list format: [destination[0], pathMessage, flags]\n path, message = getPathAndMessage(receivedDataList[2]) # sends data for processing\n print (\"Source: \", receivedDataList[0])\n print (\"Destination: \", receivedDataList[1])\n print(\"path = \", path)\n print(\"message = \", message)\n #displayDataFlags(receivedDataList[2])\n #************************************************* \n\n # since we got the data using the server, we send it using the client\n receivedDataList[2], port = getNextData(path, message) # get next path for which the message should go\n receivedDataList = pickle.dumps(receivedDataList)\n clientSocket.send(receivedDataList) \n ","sub_path":"routerG.py","file_name":"routerG.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"286398316","text":"\"\"\"Utilities for reading the current status of the tip presence photointerrupter.\"\"\"\nimport asyncio\nimport logging\n\nfrom typing_extensions import Literal\n\nfrom opentrons_hardware.firmware_bindings.arbitration_id import ArbitrationId\n\nfrom opentrons_hardware.firmware_bindings.messages.messages import MessageDefinition\nfrom opentrons_hardware.drivers.can_bus.can_messenger import CanMessenger\nfrom opentrons_hardware.firmware_bindings.messages.message_definitions import (\n TipStatusQueryRequest,\n PushTipPresenceNotification,\n)\n\nfrom opentrons_hardware.firmware_bindings.constants import MessageId, NodeId\n\nlog = logging.getLogger(__name__)\n\n\nasync def get_tip_ejector_state(\n can_messenger: CanMessenger,\n node: Literal[NodeId.pipette_left, NodeId.pipette_right],\n) -> int:\n \"\"\"Get the state of the tip presence interrupter.\n\n When the tip ejector flag is occuluded, then we\n know that there is a tip on the pipette.\n \"\"\"\n tip_ejector_state = 0\n\n event = asyncio.Event()\n\n def _listener(message: MessageDefinition, arb_id: ArbitrationId) -> None:\n nonlocal tip_ejector_state\n if isinstance(message, PushTipPresenceNotification):\n event.set()\n tip_ejector_state = message.payload.ejector_flag_status.value\n\n def _filter(arbitration_id: ArbitrationId) -> bool:\n return (NodeId(arbitration_id.parts.originating_node_id) == node) and (\n MessageId(arbitration_id.parts.message_id)\n == MessageId.tip_presence_notification\n )\n\n can_messenger.add_listener(_listener, _filter)\n await can_messenger.send(node_id=node, message=TipStatusQueryRequest())\n\n try:\n await asyncio.wait_for(event.wait(), 1.0)\n except asyncio.TimeoutError:\n log.error(\"tip ejector state request timed out before expected nodes responded\")\n finally:\n can_messenger.remove_listener(_listener)\n return tip_ejector_state\n","sub_path":"hardware/opentrons_hardware/hardware_control/tip_presence.py","file_name":"tip_presence.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"205930239","text":"#!/usr/bin/env pybricks-micropython\n\n\"\"\"\nExample LEGO® MINDSTORMS® EV3 Robot Educator Color Sensor Down Program\n----------------------------------------------------------------------\n\nThis program requires LEGO® EV3 MicroPython v2.0.\nDownload: https://education.lego.com/en-us/support/mindstorms-ev3/python-for-ev3\n\nBuilding instructions can be found at:\nhttps://education.lego.com/en-us/support/mindstorms-ev3/building-instructions#robot\n\"\"\"\n\nfrom pybricks.ev3devices import Motor, ColorSensor\nfrom pybricks.parameters import Port\nfrom pybricks.tools import wait\nfrom pybricks.robotics import DriveBase\n\n# Initialize the motors.\nleft_motor = Motor(Port.B)\nright_motor = Motor(Port.D)\n\n# Initialize the color sensor.\nline_sensor = ColorSensor(Port.S1)\n\n# Initialize the drive base.\nrobot = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=104)\nmotor = Motor(port=Port.A)\n\n# Calculate the light threshold. Choose values based on your measurements.\nBLACK = 4\nWHITE = 65\nthreshold = (BLACK + WHITE) / 2\n\n\n# Set the drive speed at 100 millimeters per second.\nDRIVE_SPEED = 35\n\n# Set the gain of the proportional line controller. This means that for every\n# percentage point of light deviating from the threshold, we set the turn\n# rate of the drivebase to 1.2 degrees per second.\n\n# For example, if the light value deviates from the threshold by 10, the robot\n# steers at 10*1.2 = 12 degrees per second.\nKp = 2 #1 +- 0.5\nKi = 0 #0.5 +- 0.05\nkd = 2 #1 +- 0.5\nintegral = 0\nerror = 0\nlast_error = 0\nps = +1\n\n\n\ndef start1():\n while(1):\n DRIVE_SPEED = 50\n turn_rate=0\n robot.drive(DRIVE_SPEED, turn_rate)\n detect_obstacle()\n #apres une certaine distance, il tourne à gauche\ndef start():\n DRIVE_SPEED = 150\n turn_rate_1=0 \n turn_rate_2=100 \n \n robot.drive(DRIVE_SPEED, turn_rate_1)\n #robot.run_time(speed, time, then=Stop.HOLD, wait=True) \n robot.drive_time(speed, 0,time) #mm/sec; steeringdegrees/sec for timemilliseconds\n robot.drive(DRIVE_SPEED, turn_rate_2) #mm/sec; steeringDeg/sec \n detect_obstacle() \n #apres une certaine distance, il tourne à gauche \n\n\ndef detect_obstacle():\n while obstacle_sensor.distance() < 150:\n DRIVE_SPEED=-300\n turn_rate = 80\n robot.drive(DRIVE_SPEED, turn_rate)\n wait(10) \n\n\n\ndef main():\n start()\n\n\nprint(1)\n\nmain()\n\n","sub_path":"program/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"464644535","text":"import cv2\nimport time\nimport numpy as np\nimport glob\nimport os\nfrom matplotlib import pyplot as plt\nimport rospy \n\nfrom sensor_msgs.msg import Joy\n\nimage_list = glob.glob(\"../store/*/*.bmp\")\nimage_list.sort()\ni = 0\nthreshold = 128\nmouse_x, mouse_y,width = (500,500,100)\ncsrt = cv2.TrackerCSRT_create()\ncsrt_state = False\nif_update_csrt = False\ndraw_previous = 0\nhave_record = 0\nthreshold_bias = 0\nadd_i = True\nunsure_flag = 0\n\n\ndef draw_text(image, txt, color):\n font = cv2.FONT_HERSHEY_SIMPLEX \n org = (20, 30) \n fontScale = 0.7\n thickness = 2\n image = cv2.putText(image, txt, org, font, \n fontScale, color, thickness, cv2.LINE_AA) \n return image \n\ndef mouse_callback(event,x,y,flags,param):\n global mouse_x, mouse_y, pt1, pt2\n if event == cv2.EVENT_MOUSEMOVE:\n mouse_x = x\n mouse_y = y\n\ndef caculate_box_points(x,y,width,img_shape): \n d = width // 2\n if csrt_state == True:\n x = int(csrt_box[0] + csrt_box[2] / 2)\n y = int(csrt_box[1] + csrt_box[3] / 2)\n a1,a2 = max(0, x - d), max(y - d, 0)\n b1,b2 = min(img_shape[1], x + d), min(img_shape[0], y+d)\n pt1 = (a1,a2)\n pt2 = (b1,b2)\n return pt1,pt2\n\ndef get_hist_graph(roi):\n global threshold\n hist = cv2.calcHist([roi],[0],None,[256],[0,256])\n for j in range(256):\n if j < 60:\n continue\n if hist[j][0] > 1000:\n threshold = j + threshold_bias\n break\n lines = plt.plot(hist,color='r')\n fig.canvas.draw()\n lines[0].remove() \n hist_img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8,\n sep='')\n hist_img = hist_img.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n hist_img = cv2.cvtColor(hist_img,cv2.COLOR_RGB2BGR)\n line_pos = int(threshold / 256.0 * 496 + 81)\n cv2.line(hist_img, (line_pos, 61), (line_pos, 428), (255, 0, 0), 2)\n return hist_img\n\ndef update_csrt(color_image):\n global csrt_state,if_update_csrt,csrt_box,draw_previous\n if csrt_state == True:\n if if_update_csrt:\n csrt_state, csrt_box = csrt.update(color_image)\n if_update_csrt = 0\n mash = (int(csrt_box[0]),int(csrt_box[1]))\n bar = (int(csrt_box[0]+csrt_box[2]),int(csrt_box[1]+csrt_box[3]))\n if draw_previous == 0:\n cv2.rectangle(color_image,mash,bar,(0,255,0),2)\n else:\n draw_previous = 1\n if unsure_flag == 1:\n font = cv2.FONT_HERSHEY_SIMPLEX \n org = (20, 30) \n fontScale = 0.7\n color = (0, 0, 255) \n thickness = 2\n cv2.putText(color_image, 'unsure', org, font, \n fontScale, color, thickness, cv2.LINE_AA) \n return color_image\n\n\ndef joy_callback(a):\n global width,threshold_bias\n width = int(a.axes[2] * 500 + 520)\n threshold_bias = a.axes[4] * 20\n #use_traking_data = a.buttons[3]\n\nfig = plt.figure()\nplt.title(\"Grayscale Histogram\")\nplt.xlabel(\"Bins\")\nplt.ylabel(\"# of Pixels\")\nplt.xlim([0,256])\nplt.ylim([0,10000])\n\ncv2.namedWindow(\"color\", cv2.WINDOW_NORMAL);\ncv2.moveWindow(\"color\", 2000,0);\ncv2.setWindowProperty(\"color\", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN);\ncv2.namedWindow(\"roi\", cv2.WINDOW_NORMAL);\ncv2.moveWindow(\"roi\", 0,0);\ncv2.setWindowProperty(\"roi\", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN);\ncv2.namedWindow(\"hist\");\ncv2.moveWindow(\"hist\", 0,0);\ncv2.namedWindow(\"thr\");\ncv2.moveWindow(\"thr\", 0,600);\nrospy.init_node('manual_label')\nrospy.Subscriber(\"joy\", Joy, joy_callback)\ncv2.setMouseCallback('color',mouse_callback)\n\n\nwhile(True):\n time0 = time.time() * 1000######################\n flag_path = image_list[i][:-3] + 'no'\n pos_path = image_list[i][:-3] + 'pos'\n if os.path.exists(flag_path):\n if add_i:\n i = i + 1\n else:\n i = i - 1\n continue\n if os.path.exists(pos_path):\n f = open(pos_path)\n pos_txt = f.readlines()[0]\n if 'unsure' not in pos_txt:\n unsure_flag = 0\n x1,y1,w1,h1 = pos_txt.split(' ')\n x1,y1,w1,h1 = int(x1), int(y1), int(w1), int(h1)\n #x1,y1 = x1 - pt1[0], y1 - pt1[1]\n have_record = 1\n else:\n unsure_flag = 1\n\n\n raw_image = cv2.imread(image_list[i], 0)\n color_image = cv2.cvtColor(raw_image, cv2.COLOR_BAYER_BG2BGR)\n raw_color_image = color_image.copy()\n grey_image = cv2.cvtColor(raw_image, cv2.COLOR_BAYER_BG2GRAY)\n color_image = update_csrt(color_image)\n if draw_previous == 1 and have_record:\n cv2.rectangle(color_image,(x1,y1),(x1+w1,y1+h1),(255,0,0),2)\n pt1,pt2 = caculate_box_points(mouse_x, mouse_y, width, grey_image.shape)\n roi = grey_image[pt1[1]:pt2[1],pt1[0]:pt2[0]].copy()\n cv2.rectangle(color_image,pt1,pt2,(255,0,0),3)\n\n hist_graph = get_hist_graph(roi)\n\n\n _,thr= cv2.threshold(roi,threshold,255,cv2.THRESH_BINARY_INV)\n contours, hierarchy = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n if len(contours) is not 0:\n contour = max(contours, key = cv2.contourArea)\n x,y,w,h = cv2.boundingRect(contour)\n thr = cv2.resize(thr,(480,480))\n roi = cv2.cvtColor(roi, cv2.COLOR_GRAY2BGR) \n if len(contours) is not 0:\n cv2.rectangle(roi,(x,y),(x+w,y+h),(0,255,0),1)\n\n\n cv2.imshow('color',color_image)\n cv2.imshow('hist', hist_graph)\n cv2.imshow('thr', thr)\n cv2.imshow('roi',roi)\n\n key = cv2.waitKey(1)\n \n if key == ord('q'):\n break\n if key == ord('1'):\n print(i)\n add_i = 0\n if_update_csrt = 1\n i -= 1\n if key == ord('3'):\n print(i)\n add_i = 1\n i += 1\n if_update_csrt = 1\n if key == ord('4'):\n add_i = 0\n i -= 10\n if key == ord('6'):\n add_i = 1\n i += 10\n if key == ord('7'):\n add_i = 0\n i -= 100\n if key == ord('9'):\n add_i = 1\n i += 100\n if key == ord('2'):\n add_i = 1\n if_update_csrt = 1\n draw_previous = 0\n f = open(pos_path,'w')\n f.write('%d %d %d %d'%(csrt_box[0],csrt_box[1],csrt_box[2],csrt_box[3]))\n f.close()\n i += 1\n if key == ord('/'):\n add_i = 1\n f = open(pos_path,'w')\n f.write('unsure')\n f.close()\n i += 1\n if key == ord('8'):\n add_i = 1\n f = open(pos_path,'w')\n f.write('%d %d %d %d'%(x+pt1[0],y+pt1[1],w,h))\n f.close()\n i += 1\n if key == ord('5'):\n add_i = 1\n if_update_csrt = 1\n f = open(pos_path,'w')\n draw_previous = 0\n i += 1\n csrt = cv2.TrackerCSRT_create()\n csrt_settings = cv2.FileStorage(\"csrt_settings.yaml\",cv2.FILE_STORAGE_READ) \n csrt.read(csrt_settings.root())\n # csrt_settings = cv2.FileStorage(\"csrt_settings1.yaml\",cv2.FILE_STORAGE_WRITE) \n # csrt.write(csrt_settings)\n csrt_box = (x+pt1[0],y+pt1[1],w,h)\n csrt.init(raw_color_image, csrt_box)\n csrt_state = True \n f.write('%d %d %d %d'%(x+pt1[0],y+pt1[1],w,h))\n f.close()\n if key == ord('*'):\n add_i = 1\n draw_previous = (draw_previous + 1) % 2\n\n if key == ord('.'):\n add_i = 1\n csrt_state = False\n\n if i < 0:\n i = 0\n if i >= len(image_list):\n i = image_list - 1\n time3 = time.time() * 1000######################\n #print(time1 - time0, time3 - time2)\n\n","sub_path":"manual_label/location.py","file_name":"location.py","file_ext":"py","file_size_in_byte":7363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"215772907","text":"import math\nfrom simanim import *\n\n# konstante:\nscena_w, scena_h = 4.6, 6\nh1 = 2.11 # Rastojanje izmedju Romeove i Julijine sake\n\ndef setup(m):\n PixelsPerUnit(72)\n ViewBox((0, 0), 4.6, 6)\n FramesPerSecond(30)\n UpdatesPerFrame(5)\n\n m.v0 = InputFloat(5.1, (3.1, 9.9))\n m.H = InputFloat(2.6,(1.2, 4.2)) # rastojanje izmedju Julijine i Romeove sake\n\n m.y_gornje_sl = m.H - h1\n\n m.h = 0 # visina slike ruze\n m.v = m.v0 # m.v ce biti brzina ruze navise (ako je negativna, nanize)\n m.g = 10 # koristimo g = 10 da bi se rezultat slagao sa jednostavnijim racunanjem\n\ndef update(m):\n dv = - m.g * m.dt\n dh = m.v * m.dt - m.g * m.dt * m.dt / 2\n\n m.h += dh\n m.v += dv\n\n if m.h <= 0 or (abs(m.h - m.H) < 0.05 and abs(m.v) <= 0.1):\n if m.h < 0:\n m.h = 0 # ne nize od Romeove ruke\n m.v = m.v0\n Finish()\n\n\ndef draw(m):\n gornji_deo = Image(\"romeo2_upper.png\", (0, m.y_gornje_sl), scena_w, scena_h)\n donji_deo = Image(\"romeo2_lower.png\", (0, 0), scena_w, scena_h)\n ruza = Image(\"rose.png\", (0, m.h), scena_w, scena_h)\n romeo = Image(\"romeo1_romeo.png\", (0, 0), scena_w, scena_h)\n\n tekst_t = Text((3, 5.7), f't ={m.t:6.2f}s')\n tekst_t.pen_color = '#000000'\n tekst_t.font_size = 0.2\n tekst_v = Text((3, 5.5), f'v ={abs(m.v):6.2f}m/s')\n tekst_h = Text((3, 5.3), f'h ={(m.h):6.2f}m')\n\n Draw(donji_deo, gornji_deo, ruza, romeo, tekst_t, tekst_v, tekst_h)\n\nRun(setup, update, draw)","sub_path":"03_vertikalan_hitac/02_hitac1_romeo2.py","file_name":"02_hitac1_romeo2.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"39117173","text":"# https://codility.com/programmers/lessons/1-iterations/binary_gap/\n# python 2.7.13\ndef solution(N):\n maxGap = 0\n currentGap = 0\n # skip zeros at tail, assume that N > 0\n while (N & 0x1) == 0:\n N = N >> 1\n # calculate the gap\n while N != 0:\n lsb = N & 0x1\n if lsb == 0x1:\n maxGap = max(maxGap, currentGap)\n currentGap = 0\n else:\n currentGap += 1\n N = N >> 1\n return maxGap\n\nif __name__ == '__main__':\n assert solution(9) == 2\n assert solution(529) == 4\n assert solution(20) == 1\n assert solution(15) == 0\n\n","sub_path":"lessons/1.iterations/BinaryGap.py","file_name":"BinaryGap.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"193898989","text":"from anthill.framework.conf import settings\nfrom anthill.framework.utils.module_loading import import_string\nfrom anthill.platform.services.update.exceptions import UpdateError\nfrom anthill.framework.utils.asynchronous import as_future\nfrom typing import Optional\nimport logging\nimport os\n\n\nlogger = logging.getLogger('anthill.application')\n\n\nUPDATES_SETTINGS = getattr(settings, 'UPDATES', {})\nUPDATE_MANAGER = UPDATES_SETTINGS.get(\n 'MANAGER', 'anthill.platform.services.update.backends.git.GitUpdateManager')\n\n\nclass UpdateManager:\n def __init__(self):\n self.manager = import_string(UPDATE_MANAGER)()\n\n async def update(self, version: Optional[str] = None):\n await self.update_system_requirements()\n await self.update_pip_requirements()\n await self.update_service(version)\n\n async def update_service(self, version):\n await self.manager.update(version)\n logger.info('Service has been updated successfully.')\n\n @as_future\n def update_pip_requirements(self):\n from pip import _internal\n req_file = os.path.join(settings.BASE_DIR, 'requirements.txt')\n _internal.main(['install', '-r', req_file])\n logger.info('Pip requirements installed successfully.')\n\n @as_future\n def update_system_requirements(self):\n logger.info('System requirements installed successfully.')\n","sub_path":"services/update/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"389489910","text":"'''\nstr()\n快速存成文件\n'''\n\n\n# 泡菜, 序列化,反序列化(一般是针对对象和字符串之间)\nimport pickle\n\nnames = ['小巧','大桥','曹操','周瑜','李白','杜甫']\nstring = str(names) # 在names值两边加上引号,变成字符串\nprint(string)\n\n# 第一种,将python存入文件中.\n# pickle.dumps(names)\n# print(pickle.dumps(names)) #dumps命令将python对象变成二进制\n\n# dump将python对象存入文件\n# pickle.dump(names,open('pickle.txt','wb')) #输入模块名后可以alt+回车 快速导入模块\n\n# 取出\nobj = pickle.load(open('pickle.txt','rb'))\nprint(obj)\n\n","sub_path":"LearnPython/day15/pickle泡菜.py","file_name":"pickle泡菜.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"418942445","text":"\n\n###################################################################################\n########################## Data Prepartion - Event Generation #####################\n###################################################################################\n\n# Notes\n# Each Data Source will be dowloaded independently\n\n\n\n\n# Initialize Variables\n\n# Datafile Name\ndatafile = \"ifttt.csv\"\ndatetimename = 'DateTime'\ncolumncount = 5\n\nannoyingColumns = [datetimename ,'_index', '_source.time' , '_source.timestamp']\nperson = False\n\n# Import Libraries\nimport pandas as pd\nfrom summarizeDataFrame import summarizeDataset\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import scatter_matrix\nimport sys\nimport numpy as np\nimport math\n\n# baseline = pd.read_csv(\"time_taken2.csv\")\n#\n#baseline['date'] = '2018-04-03'\n#\n# # baseline['Front Motion Sent'] = pd.to_datetime(baseline['Front Motion Sent']).dt.time\n# # baseline['Motion Sensor 2 Received'] = pd.to_datetime(baseline['Motion Sensor 2 Received']).dt.time\n# # print(baseline.dtypes)\n\n# baseline['starttime'] = pd.to_datetime(baseline['date'] + ' ' + baseline['Front Motion Sent (Sequence Start)'])\n# baseline['endtime'] = pd.to_datetime(baseline['date'] + ' ' + baseline['Lock Received'])\n#\n# # baseline = baseline.dropna()\n# # starttime = baseline.loc[:,'Front Motion Sent'].values\n# # endtime = baseline.loc[:,'Motion Sensor 2 Received'].values\n#\n#\n# # print(starttime)\n#\n# # print(baseline.head())\n#\n#\n#\n#\n# # Need to inlcude for Pots\n# #get_ipython().magic(u'matplotlib inline')\n\n\n\n# import Data\ndf = pd.read_csv(datafile)\n\n# make datetime to datetime format\ndf[datetimename] = pd.to_datetime(df[datetimename]).values.astype(' starttime) & (df['datetimename'] <= endtime)]\n\ndf = df[(df[datetimename] > starttime) & (df[datetimename] <= endtime)]\n\n#print(df1.head())\n\n\n\ndf1 = df.drop([\"_id\" ,\"_index\" , '_score' , '_source.time','DateTime' ,'_source.timestamp'], axis=1)\n#\ndf1=df1.astype(str)\ndf1['sequence'] = df1.apply(''.join, axis=1)\n#print(df1.head())\ndf1['transactionID'] = \"\"\n\n\nlist = []\n\ncount = 0\nrow = 0\nfor x in df1['sequence']:\n\n if x == 'nannannannannanFrontLock1nannannannanUnlockednannannan Manny Kinwebhook':\n count = count + 1\n\n\n #df1.loc[row, 'ID'] = count\n #df1.ix[row, 'ID'] = count\n df1.iloc[row, df1.columns.get_loc('transactionID')] = count\n #df1['ID'] == count\n #print(row,count)\n row = row + 1\n\n\n#print(df1.head())\n\ndf2=df1[['transactionID','sequence']]\n#df3=df2.loc[df2['transactionID']] != 0\ndf3=df2[(df2['transactionID'] > 0)]\n#df3=df2.loc[:, df2.loc['transactionID'] >= 0 ]\nprint(df3)\ndf3.to_csv(\"test3.csv\", index=False)\n\n'''\n\n\n\n#df2=df1['sequence'].astype(str)\n\n\n# Make data set divisible by wanted column\n# rowCount = (int(len(df2.index)))\n# columnCountRows = math.floor(rowCount/ columncount)\n# newRowCount = math.floor(rowCount/ columncount) * columncount\n#df2 = df2[:newRowCount].astype(str)\n#df3 =pd.DataFrame(np.reshape(df2.values,(columnCountRows,5)))\n#df2=df1['sequence']\ndf1['nextone']=df1['sequence'].shift(-1)\ndf1['nextwo']=df1['sequence'].shift(-2)\ndf1['nextthree']=df1['sequence'].shift(-3)\ndf1['nextfour']=df1['sequence'].shift(-4)\ndf1['nextfive']=df1['sequence'].shift(-5)\ndf1['nextsix']=df1['sequence'].shift(-6)\ndf1['nextseven']=df1['sequence'].shift(-7)\ndf1['nexteight']=df1['sequence'].shift(-8)\n#df1.drop(df1.tail(9).index,inplace=True)\ndf2 = df1.reset_index()\n\n\ndf3 = df2[df2.columns[-9:]]\n# print(df3)\ndf3=df3.loc[df3['sequence'] == 'nannannannannanFrontLock1nannannannanUnlockednannannan Manny Kinwebhook']\n\ndf3.reset_index( inplace=True)\n#print(df3.head())\n#df3.to_csv(\"sequence-ifttt2.csv\", index=False)\ndf3['transactionID'] = df3.index\n#print(df3.head())\ndf4 = pd.melt(df3, id_vars=['transactionID'], value_vars=['sequence', 'nextone' , 'nextwo' , 'nextthree' , 'nextfour' , 'nextfive' , 'nextsix' , 'nextseven' , 'nexteight'])\n#print(df3)\n#print(df4.head())\n\ndf11 = df3.head(1)\ndf12 = pd.melt(df11, id_vars=['transactionID'], value_vars=['sequence', 'nextone' , 'nextwo' , 'nextthree' , 'nextfour' , 'nextfive' , 'nextsix' , 'nextseven' , 'nexteight'])\n\ndel df4['variable']\ndel df12['variable']\n#print(df11)\ndf4.to_csv(\"test3.csv\", index=False)\n#df4.to_csv(\"sequence-ifttt.csv\", index=False)\ndf12.to_csv(\"test.csv\", index=False)\n\n\n\n\n#new.df <- data.frame(s1 = head(df$regions,-1), s2 = tail(df$regions,-1))\n\n\n#print(df3.head())\n\n\n# print (pd.DataFrame(df2.values.reshape(-1, 5),\n# columns=['Name','School','Music','Mentor1','Mentor2']))\n#print(np.reshape(df2.values,(len(df2.index),5)))\n\n#print(df2)\n\n# df[datetimename]= df[datetimename].apply(lambda x:x.strfdatetime( '%Y-%d-%m %H:%M:%S'))\n\n# Initialize Scenario count Variable\n# df['desired_output'] = \"\"\n#\n# # Start and endtime data\n# # array = [\"2018-03-26 18:16:16.658\",\"2018-03-20 18:16:17.696\",\"2018-03-20 18:16:18.707\"]\n# # array2 = [\"2018-04-02 18:16:19.732\",\"2018-03-20 18:16:19.732\",\"2018-03-20 18:16:19.732\"]\n# array = baseline['starttime'].values\n# array2 = baseline['endtime'].values\n#\n# # Create unique identifier for scenario aggregation\n# count = 1\n#\n# for i, x in zip(array, array2):\n# df['desired_output'] = np.where(\n# np.logical_and(df[datetimename] >= pd.to_datetime(i), df[datetimename] <= pd.to_datetime(x)), count,\n# df['desired_output'])\n#\n# count = count + 1\n#\n# # print(df)\n#\n# # Filter Data for no unique and high unique\n# if person == True:\n#\n# df2 = df.loc[:, df.apply(pd.Series.nunique) != int(len(df.index))]\n#\n# else:\n#\n# do = df.loc[:, 'desired_output']\n# df1 = df.loc[:, df.apply(pd.Series.nunique) != 1]\n#\n# df2 = df1.loc[:, df1.apply(pd.Series.nunique) != int(len(df1.index))]\n#\n# if 'desired_output' not in df2.columns:\n# df2 = pd.concat([do, df2], axis=1)\n\n# # Remove Unessary Columns\n# if all([item in df2.columns for item in annoyingColumns]):\n#\n# df3 = df2.drop(annoyingColumns, axis=1)\n#\n# else:\n#\n# df3 = df2\n#\n#\n#\n# # Get names of column aggregation\n# names = list(df3)\n# if 'desired_output' in names:\n#\n# names.remove('desired_output')\n#\n# else:\n#\n# print(\"Scenario Not in Dataset\")\n# print(list(df2))\n# sys.exit()\n#\n# # print(df3)\n#\n# # Create Dummy Variable for Dataset\n# df5 = pd.get_dummies(df3, columns=names)\n# df5.index = df[datetimename]\n#\n# # df6=df5.resample(\"5T\").count()\n#\n# df6 = df5.groupby(['desired_output'], as_index=False)[list(df5)].nunique()\n\n# df2 = df1.groupby(['_source.device']).agg({'_source.action': [ min , max ,'first', 'nunique','count']})\n\n\n\n# summarizeDataset(df3)\n\n\n# print(list(df4))\n# print(type(names1))\n# print(df5.head())\n# # print(baseline)\n# # print(array2[2])\n# df6.to_csv(\"features-ifttt.csv\", index=False)\n#\n#\n#\n# print(baseline[['starttime', 'endtime']])\n#\n# # print(df5.groupby(['desired_output'])[list(df5)].count())\n# #\n# print(df6)\n# # print(list(df))\n\n\n'''","sub_path":"Combine/ifttt-sequence.py","file_name":"ifttt-sequence.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"410122812","text":"from ..example_code import super_function_i_want_to_test\nfrom pytest_cases import cases_data, CaseDataGetter\ntry:\n from pytest_cases import CaseData\nexcept ImportError:\n pass\n\n\ndef case_simple():\n # type: (...) -> CaseData\n ins = dict(a=1, b=2)\n outs = 2, 3\n return ins, outs, None\n\n\ndef case_simple2():\n # type: (...) -> CaseData\n ins = dict(a=1, b=2)\n outs = 2, 3\n return ins, outs, None\n\n\n@cases_data(cases=case_simple)\ndef test_with_cases_decorated(case_data # type: CaseDataGetter\n ):\n\n # 1- Grab the test case data\n i, expected_o, expected_e = case_data.get()\n\n # 2- Use it: nominal test only\n assert expected_e is None\n outs = super_function_i_want_to_test(**i)\n assert outs == expected_o\n\n\n@cases_data(cases=[case_simple, case_simple2])\ndef test_with_cases_decorated2(case_data # type: CaseDataGetter\n ):\n\n # 1- Grab the test case data\n i, expected_o, expected_e = case_data.get()\n\n # 2- Use it: nominal test only\n assert expected_e is None\n outs = super_function_i_want_to_test(**i)\n assert outs == expected_o\n\n\n# from https://stackoverflow.com/a/51199035/7262247\ntry: # python 3.2+\n from functools import lru_cache\nexcept ImportError:\n from functools32 import lru_cache\n\n\n@lru_cache(maxsize=3)\ndef load_file(file_name):\n \"\"\" This function loads the file and returns contents\"\"\"\n print(\"loading file \" + file_name)\n return \"\"\n\n\ndef case_1():\n # type: (...) -> CaseData\n ins = load_file('file1')\n outs, err = None, None\n return ins, outs, err\n\n\ndef case_2():\n # type: (...) -> CaseData\n ins = load_file('file2')\n outs, err = None, None\n return ins, outs, err\n\n\ndef case_3():\n # type: (...) -> CaseData\n ins = load_file('file3')\n outs, err = None, None\n return ins, outs, err\n\n\n@cases_data(cases=[case_1, case_2])\ndef test_a(case_data # type: CaseDataGetter\n ):\n # 1- Grab the test case data\n i, expected_o, expected_e = case_data.get()\n\n # 2- Use it\n # see pytest-cases usage page for suggestions\n\n\n@cases_data(cases=[case_2, case_3])\ndef test_b(case_data # type: CaseDataGetter\n ):\n # 1- Grab the test case data\n i, expected_o, expected_e = case_data.get()\n\n # 2- Use it\n # see pytest-cases usage page for suggestions\n\n\n@cases_data(cases=[case_1, case_2, case_3])\ndef test_c(case_data # type: CaseDataGetter\n ):\n # 1- Grab the test case data\n i, expected_o, expected_e = case_data.get()\n\n # 2- Use it\n # see pytest-cases usage page for suggestions\n","sub_path":"pytest_cases/tests/cases/legacy/advanced/test_stackoverflow.py","file_name":"test_stackoverflow.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"457463919","text":"# Problem [2814] : 최장 경로\n\nimport sys\nsys.stdin = open('input.txt')\n\ndef DFS(v, depth):\n global m\n\n if depth > m:\n m = depth\n\n visited[v] = 1\n\n for w in G[v]:\n if not visited[w]:\n DFS(w, depth+1)\n \n visited[v] = 0\n\n\n\nif __name__ == \"__main__\":\n T = int(input())\n for tc in range(1, T+1):\n V, E = map(int,input().split())\n G = [[] for _ in range(V+1)]\n m = 0\n visited = [0]*(V+1)\n for _ in range(E):\n u, v = map(int,input().split())\n G[u].append(v)\n G[v].append(u)\n \n for i in range(1, V+1):\n DFS(i,1)\n \n print('#{} {}'.format(tc, m))","sub_path":"SWEA/D3/SWEA_2814/SWEA_2814.py","file_name":"SWEA_2814.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"85354652","text":"from lib import *\n# Comparative performance in the unsupervised setting on simulateddata\ndataset = joblib.load('data/all_mutational.pkl.gz')\nn_iter = 500\nlayers = 10\nfig_6 = pd.DataFrame()\nlst = {}\nkf = KFold(n_splits=5, random_state=1, shuffle=True)\n\nfor k, v in dataset.items():\n lst[\"dnmf_0\"] = []\n lst[\"dnmf_1\"] = []\n lst[\"dnmf_2\"] = []\n lst[\"mu_0\"] = []\n lst[\"mu_1\"] = []\n lst[\"mu_2\"] = []\n for train_index, test_index in kf.split(v[\"V\"].T):\n\n data, n_components, features, samples = util.build_data(\n v[\"V\"], v[\"W\"], v[\"H\"], index = train_index\n )\n\n for lam in range(3):\n L1 = lam\n L2 = lam\n ##################### unsupervised performance #############################\n _, _, dnmf_error, _ = util.train_unsupervised(\n data, layers, n_iter, n_components, l_1=L1, l_2=L2\n )\n ###### MU ################\n # train\n h_mu = data.h_0_train.mat.copy() # k*n\n w_mu = data.w_init.mat.copy() # f*k\n for i in range(n_iter):\n w_mu, h_mu = util.mu_update(data.v_train.mat, w_mu, h_mu, l_1=L1, l_2=L2)\n # test\n mu_test_iter = 10\n h_mu_test = data.h_0_test.mat.copy()\n for i in range(mu_test_iter):\n _, h_mu_test = util.mu_update(\n data.v_test.mat, w_mu, h_mu_test, update_W=False\n )\n mu_error = util.cost_mat(data.v_test.mat, w_mu, h_mu_test)\n\n lst[f\"dnmf_{lam}\"].append(dnmf_error[-1])\n lst[f\"mu_{lam}\"].append(mu_error)\n \n fig_6[f\"dnmf_0_{k}\"] = lst[\"dnmf_0\"]\n fig_6[f\"dnmf_1_{k}\"] = lst[\"dnmf_1\"]\n fig_6[f\"dnmf_2_{k}\"] = lst[\"dnmf_2\"]\n fig_6[f\"mu_0_{k}\"] = lst[\"mu_0\"]\n fig_6[f\"mu_1_{k}\"] = lst[\"mu_1\"]\n fig_6[f\"mu_2_{k}\"] = lst[\"mu_2\"]\nfig_6.to_csv('data/outputs/fig_6.csv', index=False)\n\nfig_6 = pd.read_csv('data/outputs/fig_6.csv')\nfor x in range(1, 13):\n df = fig_6[[f\"dnmf_0_{x}\", f\"mu_0_{x}\", f\"dnmf_1_{x}\", f\"mu_1_{x}\", f\"dnmf_2_{x}\", f\"mu_2_{x}\"]]\n df = pd.melt(df)\n df['method'] = df.apply(lambda row: 'DNMF 'if row.variable.startswith('dnmf') else 'MU', axis = 1)\n if x>9:\n df['lambda'] = df.apply(lambda row: row.variable[-4:-3], axis = 1)\n else:\n df['lambda'] = df.apply(lambda row: row.variable[-3], axis = 1)\n df['value'] = np.log(df['value'].values)\n plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\n sns.boxplot(x='lambda',y='value',data=df,hue='method')\n plt.ylabel(\"$\\log({MSE})$\")\n plt.xlabel(\"${\\lambda_1,\\lambda_2}$\")\n plt.legend([],[], frameon=False)\n plt.savefig(f\"plots/fig6/unsupervised_performance_{x}.pdf\")\n plt.show()","sub_path":"ongoing_research/fig3.4_unsupervised_perf.py","file_name":"fig3.4_unsupervised_perf.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"70562047","text":"# Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to O\n\ndef zeroColumn(matrix, col_index):\n for item in matrix:\n item[col_index] = 0\n return matrix\n\ndef zeroRow(matrix, row_index):\n for index, item in enumerate(matrix[row_index]):\n matrix[row_index][index] = 0\n return matrix\n\ndef zeroMatrix():\n rows_to_zero = []\n cols_to_zero = []\n matrix = [\n [1, 2, 3, 4, 0],\n [1, 2, 0, 3, 4],\n [2, 3, 5, 2, 1],\n [4, 3, 2, 1, 5]\n ]\n for row_index, row in enumerate(matrix):\n for col_index, item in enumerate(row):\n if item == 0:\n rows_to_zero.append(row_index)\n cols_to_zero.append(col_index)\n\n rows_to_zero = list(set(rows_to_zero))\n cols_to_zero = list(set(cols_to_zero))\n\n for row in rows_to_zero:\n matrix = zeroRow(matrix, row)\n for col in cols_to_zero:\n matrix = zeroColumn(matrix, col)\n return matrix\n","sub_path":"crackingCodingInterview.py","file_name":"crackingCodingInterview.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"113133396","text":"import json\n\nfrom flask import Blueprint, request, flash, abort, make_response\nfrom flask import render_template, redirect, url_for\nfrom flask.ext.login import current_user, login_required\n\nfrom portality.core import app, ssl_required, restrict_to_role\nimport portality.models as models\n\nfrom portality import journal as journal_handler\nfrom portality import suggestion as suggestion_handler\nfrom portality.view.forms import EditorGroupForm\n\nblueprint = Blueprint('admin', __name__)\n\n# restrict everything in admin to logged in users with the \"admin\" role\n@blueprint.before_request\ndef restrict():\n return restrict_to_role('admin')\n\n# build an admin page where things can be done\n@blueprint.route('/')\n@login_required\n@ssl_required\ndef index():\n return render_template('admin/index.html', admin_page=True)\n\n@blueprint.route(\"/journals\")\n@login_required\n@ssl_required\ndef journals():\n if not current_user.has_role(\"admin_journals\"):\n abort(401)\n return render_template('admin/journals.html',\n search_page=True,\n facetviews=['journals'],\n admin_page=True\n )\n\n@blueprint.route(\"/article/\", methods=[\"POST\"])\n@login_required\n@ssl_required\ndef article_endpoint(article_id):\n if not current_user.has_role(\"delete_article\"):\n abort(401)\n a = models.Article.pull(article_id)\n if a is None:\n abort(404)\n delete = request.values.get(\"delete\", \"false\")\n if delete != \"true\":\n abort(400)\n a.snapshot()\n a.delete()\n # return a json response\n resp = make_response(json.dumps({\"success\" : True}))\n resp.mimetype = \"application/json\"\n return resp\n\n@blueprint.route(\"/journal/\", methods=[\"GET\", \"POST\"])\n@login_required\n@ssl_required\ndef journal_page(journal_id):\n return journal_handler.request_handler(request, journal_id, activate_deactivate=True, group_editable=True, editorial_available=True)\n\n@blueprint.route(\"/journal//activate\", methods=[\"GET\", \"POST\"])\n@login_required\n@ssl_required\ndef journal_activate(journal_id):\n j = journal_handler.get_journal(journal_id)\n if j is None:\n abort(404)\n j.bibjson().active = True\n j.set_in_doaj(True)\n j.save()\n j.propagate_in_doaj_status_to_articles() # will save each article, could take a while\n return redirect(url_for('.journal_page', journal_id=journal_id))\n\n@blueprint.route(\"/journal//deactivate\", methods=[\"GET\", \"POST\"])\n@login_required\n@ssl_required\ndef journal_deactivate(journal_id):\n j = journal_handler.get_journal(journal_id)\n if j is None:\n abort(404)\n j.bibjson().active = False\n j.set_in_doaj(False)\n j.save()\n j.propagate_in_doaj_status_to_articles() # will save each article, could take a while\n return redirect(url_for('.journal_page', journal_id=journal_id))\n\n@blueprint.route(\"/applications\")\n@login_required\n@ssl_required\ndef suggestions():\n return render_template('admin/suggestions.html',\n search_page=True,\n facetviews=['suggestions'],\n admin_page=True\n )\n\n@blueprint.route(\"/suggestion/\", methods=[\"GET\", \"POST\"])\n@login_required\n@ssl_required\ndef suggestion_page(suggestion_id):\n return suggestion_handler.request_handler(request, suggestion_id, group_editable=True, editorial_available=True, status_options=\"admin\")\n\n@blueprint.route(\"/admin_site_search\")\n@login_required\n@ssl_required\ndef admin_site_search():\n return render_template(\"admin/admin_site_search.html\", admin_page=True, search_page=True, facetviews=['admin_journals_and_articles'])\n\n@blueprint.route(\"/editor_groups\")\n@login_required\n@ssl_required\ndef editor_group_search():\n return render_template(\"admin/editor_group_search.html\", admin_page=True, search_page=True, facetviews=['editor_group'])\n\n@blueprint.route(\"/editor_group\", methods=[\"GET\", \"POST\"])\n@blueprint.route(\"/editor_group/\", methods=[\"GET\", \"POST\"])\n@login_required\n@ssl_required\ndef editor_group(group_id=None):\n if not current_user.has_role(\"modify_editor_groups\"):\n abort(401)\n\n if request.method == \"GET\":\n form = EditorGroupForm()\n if group_id is not None:\n eg = models.EditorGroup.pull(group_id)\n form.group_id.data = eg.id\n form.name.data = eg.name\n form.editor.data = eg.editor\n form.associates.data = \",\".join(eg.associates)\n return render_template(\"admin/editor_group.html\", admin_page=True, form=form)\n\n elif request.method == \"POST\":\n\n if request.values.get(\"delete\", \"false\") == \"true\":\n # we have been asked to delete the id\n if group_id is None:\n # we can only delete things that exist\n abort(400)\n eg = models.EditorGroup.pull(group_id)\n if eg is None:\n abort(404)\n\n eg.delete()\n\n # return a json response\n resp = make_response(json.dumps({\"success\" : True}))\n resp.mimetype = \"application/json\"\n return resp\n\n # otherwise, we want to edit the content of the form or the object\n form = EditorGroupForm(request.form)\n\n if form.validate():\n # get the group id from the url or from the request parameters\n if group_id is None:\n group_id = request.values.get(\"group_id\")\n group_id = group_id if group_id != \"\" else None\n\n # if we have a group id, this is an edit, so get the existing group\n if group_id is not None:\n eg = models.EditorGroup.pull(group_id)\n if eg is None:\n abort(404)\n else:\n eg = models.EditorGroup()\n\n associates = form.associates.data\n if associates is not None:\n associates = [a.strip() for a in associates.split(\",\") if a.strip() != \"\"]\n\n # prep the user accounts with the correct role(s)\n ed = models.Account.pull(form.editor.data)\n ed.add_role(\"editor\")\n ed.save()\n if associates is not None:\n for a in associates:\n ae = models.Account.pull(a)\n ae.add_role(\"associate_editor\")\n ae.save()\n\n eg.set_name(form.name.data)\n eg.set_editor(form.editor.data)\n if associates is not None:\n eg.set_associates(associates)\n eg.save()\n\n flash(\"Group was updated - changes may not be reflected below immediately. Reload the page to see the update.\", \"success\")\n return redirect(url_for('admin.editor_group_search'))\n else:\n return render_template(\"admin/editor_group.html\", admin_page=True, form=form)\n\n@blueprint.route(\"/autocomplete/user\")\n@login_required\n@ssl_required\ndef user_autocomplete():\n q = request.values.get(\"q\")\n s = request.values.get(\"s\", 10)\n ac = models.Account.autocomplete(\"id\", q, size=s)\n\n # return a json response\n resp = make_response(json.dumps(ac))\n resp.mimetype = \"application/json\"\n return resp","sub_path":"portality/view/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":7155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"556836031","text":"from flask import Flask, render_template\napp= Flask(__name__)\n\n@app.route('/')\ndef result():\n\tdict1={'physics':88, 'chemistry':90, 'maths':85}\n\treturn render_template('result.html', sub=dict1)\n\nif __name__=='__main__':\n\tapp.run(debug=True)","sub_path":"result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"419954219","text":"import logging\nimport numpy as np\nimport seaborn as sns\nfrom abc import abstractmethod, ABC\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom typing import List, Sequence\n\nfrom .eval_stats_base import PredictionEvalStats, Metric, EvalStatsCollection, PredictionArray\n\nlog = logging.getLogger(__name__)\n\n\nclass RegressionMetric(Metric[\"RegressionEvalStats\"], ABC):\n def computeValueForEvalStats(self, evalStats: \"RegressionEvalStats\"):\n return self.computeValue(np.array(evalStats.y_true), np.array(evalStats.y_predicted))\n\n @classmethod\n @abstractmethod\n def computeValue(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n pass\n\n @classmethod\n def computeErrors(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n return y_predicted - y_true\n\n @classmethod\n def computeAbsErrors(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n return np.abs(cls.computeErrors(y_true, y_predicted))\n\n\nclass RegressionMetricMAE(RegressionMetric):\n name = \"MAE\"\n\n @classmethod\n def computeValue(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n return cls.computeAbsErrors(y_true, y_predicted)\n\n\nclass RegressionMetricMSE(RegressionMetric):\n name = \"MSE\"\n\n @classmethod\n def computeValue(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n residuals = y_predicted - y_true\n return np.sum(residuals * residuals) / len(residuals)\n\n\nclass RegressionMetricRMSE(RegressionMetric):\n name = \"RMSE\"\n\n @classmethod\n def computeValue(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n errors = cls.computeErrors(y_true, y_predicted)\n return np.sqrt(np.mean(errors * errors))\n\n\nclass RegressionMetricRRSE(RegressionMetric):\n name = \"RRSE\"\n\n @classmethod\n def computeValue(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n mean_y = np.mean(y_true)\n residuals = y_predicted - y_true\n mean_deviation = y_true - mean_y\n return np.sqrt(np.sum(residuals * residuals) / np.sum(mean_deviation * mean_deviation))\n\n\nclass RegressionMetricR2(RegressionMetric):\n name = \"R2\"\n\n def computeValue(self, y_true: np.ndarray, y_predicted: np.ndarray):\n rrse = RegressionMetricRRSE.computeValue(y_true, y_predicted)\n return 1.0 - rrse*rrse\n\n\nclass RegressionMetricPCC(RegressionMetric):\n name = \"PCC\"\n\n def computeValue(self, y_true: np.ndarray, y_predicted: np.ndarray):\n cov = np.cov([y_true, y_predicted])\n return cov[0][1] / np.sqrt(cov[0][0] * cov[1][1])\n\n\nclass RegressionMetricStdDevAE(RegressionMetric):\n name = \"StdDevAE\"\n\n @classmethod\n def computeValue(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n return np.std(cls.computeAbsErrors(y_true, y_predicted))\n\n\nclass RegressionMetricMedianAE(RegressionMetric):\n name = \"MedianAE\"\n\n @classmethod\n def computeValue(cls, y_true: np.ndarray, y_predicted: np.ndarray):\n return np.median(cls.computeAbsErrors(y_true, y_predicted))\n\n\nclass RegressionEvalStats(PredictionEvalStats[\"RegressionMetric\"]):\n \"\"\"\n Collects data for the evaluation of predicted continuous values and computes corresponding metrics\n \"\"\"\n def __init__(self, y_predicted: PredictionArray, y_true: PredictionArray,\n metrics: Sequence[\"RegressionMetric\"] = None, additionalMetrics: Sequence[\"RegressionMetric\"] = None):\n \"\"\"\n :param y_predicted: the predicted values\n :param y_true: the true values\n :param metrics: the metrics to compute for evaluation; if None, use default metrics\n :param additionalMetrics: the metrics to additionally compute\n \"\"\"\n\n if metrics is None:\n metrics = [RegressionMetricRRSE(), RegressionMetricR2(), RegressionMetricPCC(),\n RegressionMetricMAE(), RegressionMetricMSE(), RegressionMetricRMSE(),\n RegressionMetricStdDevAE()]\n metrics = list(metrics)\n\n super().__init__(y_predicted, y_true, metrics, additionalMetrics=additionalMetrics)\n\n def getMSE(self):\n return self.computeMetricValue(RegressionMetricMSE())\n\n def getRRSE(self):\n \"\"\"Gets the root relative squared error\"\"\"\n return self.computeMetricValue(RegressionMetricRRSE())\n\n def getCorrelationCoeff(self):\n \"\"\"Gets the Pearson correlation coefficient (PCC)\"\"\"\n return self.computeMetricValue(RegressionMetricPCC())\n\n def getR2(self):\n \"\"\"Gets the R^2 score\"\"\"\n return self.computeMetricValue(RegressionMetricR2())\n\n def getMAE(self):\n \"\"\"Gets the mean absolute error\"\"\"\n return self.computeMetricValue(RegressionMetricMAE())\n\n def getRMSE(self):\n \"\"\"Gets the root mean squared error\"\"\"\n return self.computeMetricValue(RegressionMetricRMSE())\n\n def getStdDevAE(self):\n \"\"\"Gets the standard deviation of the absolute error\"\"\"\n return self.computeMetricValue(RegressionMetricStdDevAE())\n\n def getEvalStatsCollection(self):\n \"\"\"\n For the case where we collected data on multiple dimensions, obtain a stats collection where\n each object in the collection holds stats on just one dimension\n \"\"\"\n if self.y_true_multidim is None:\n raise Exception(\"No multi-dimensional data was collected\")\n dim = len(self.y_true_multidim)\n statsList = []\n for i in range(dim):\n stats = RegressionEvalStats(self.y_predicted_multidim[i], self.y_true_multidim[i])\n statsList.append(stats)\n return RegressionEvalStatsCollection(statsList)\n\n def plotErrorDistribution(self, bins=None, figure=True, titleAdd=None):\n \"\"\"\n :param bins: if None, seaborns default binning will be used\n :param figure: whether to plot in a separate figure\n :param titleAdd: a string to add to the title (on a second line)\n\n :return: the resulting figure object or None\n \"\"\"\n errors = np.array(self.y_predicted) - np.array(self.y_true)\n fig = None\n title = \"Prediction Error Distribution\"\n if titleAdd is not None:\n title += \"\\n\" + titleAdd\n if figure:\n fig = plt.figure(title.replace(\"\\n\", \" \"))\n sns.distplot(errors, bins=bins)\n plt.title(title)\n plt.xlabel(\"error (prediction - ground truth)\")\n plt.ylabel(\"probability density\")\n return fig\n\n def plotScatterGroundTruthPredictions(self, figure=True, titleAdd=None, **kwargs):\n \"\"\"\n :param figure: whether to plot in a separate figure\n :param kwargs: will be passed to plt.scatter()\n\n :return: the resulting figure object or None\n \"\"\"\n fig = None\n title = \"Scatter Plot of Ground Truth vs. Predicted Values\"\n if titleAdd is not None:\n title += \"\\n\" + titleAdd\n if figure:\n fig = plt.figure(title.replace(\"\\n\", \" \"))\n y_range = [min(self.y_true), max(self.y_true)]\n plt.scatter(self.y_true, self.y_predicted, **kwargs)\n plt.plot(y_range, y_range, 'k-', lw=2, label=\"_not in legend\", color=\"r\")\n plt.xlabel(\"ground truth\")\n plt.ylabel(\"prediction\")\n plt.title(title)\n return fig\n\n def plotHeatmapGroundTruthPredictions(self, figure=True, cmap=None, bins=60, titleAdd=None, **kwargs):\n \"\"\"\n :param figure: whether to plot in a separate figure\n :param cmap: value for corresponding parameter of plt.imshow() or None\n :param bins: how many bins to use for construncting the heatmap\n :param titleAdd: a string to add to the title (on a second line)\n :param kwargs: will be passed to plt.imshow()\n\n :return: the resulting figure object or None\n \"\"\"\n fig = None\n title = \"Heat Map of Ground Truth vs. Predicted Values\"\n if titleAdd:\n title += \"\\n\" + titleAdd\n if figure:\n fig = plt.figure(title.replace(\"\\n\", \" \"))\n y_range = [min(min(self.y_true), min(self.y_predicted)), max(max(self.y_true), max(self.y_predicted))]\n plt.plot(y_range, y_range, 'k-', lw=0.75, label=\"_not in legend\", color=\"green\", zorder=2)\n heatmap, _, _ = np.histogram2d(self.y_true, self.y_predicted, range=[y_range, y_range], bins=bins)\n extent = [y_range[0], y_range[1], y_range[0], y_range[1]]\n if cmap is None:\n cmap = LinearSegmentedColormap.from_list(\"whiteToRed\", ((1, 1, 1), (0.7, 0, 0)))\n plt.imshow(heatmap.T, extent=extent, origin='lower', cmap=cmap, zorder=1, **kwargs)\n\n plt.xlabel(\"ground truth\")\n plt.ylabel(\"prediction\")\n plt.title(title)\n return fig\n\n\nclass RegressionEvalStatsCollection(EvalStatsCollection):\n def __init__(self, evalStatsList: List[RegressionEvalStats]):\n super().__init__(evalStatsList)\n self.globalStats = None\n\n def getGlobalStats(self) -> RegressionEvalStats:\n \"\"\"\n Gets an evaluation statistics object that combines the data from all contained eval stats objects\n \"\"\"\n if self.globalStats is None:\n y_true = np.concatenate([evalStats.y_true for evalStats in self.statsList])\n y_predicted = np.concatenate([evalStats.y_predicted for evalStats in self.statsList])\n self.globalStats = RegressionEvalStats(y_predicted, y_true)\n return self.globalStats\n","sub_path":"src/sensai/evaluation/eval_stats/eval_stats_regression.py","file_name":"eval_stats_regression.py","file_ext":"py","file_size_in_byte":9405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"297397337","text":"import numpy as np\n\n\ndef read_write_line(path_from, path_to):\n ms = open(path_from)\n for line in ms.readlines():\n line = line.strip().split(\" \")[0:2]\n line = str(line[0])+\" \"+str(line[1])+\"\\n\"\n print(line)\n with open(path_to, \"a\") as mon:\n mon.write(line)\n\n\ndef produce_text_info(path_to):\n a = np.random.randint(0, 2, size=(2405, 10))\n for i, line in enumerate(a):\n with open(path_to, \"a\") as mon:\n mon.write(str(i)+\" \"+str(line)[1:-1]+\"\\n\")\n\n\nif __name__ == '__main__':\n # read_write_line(b\"D:\\workspace\\pycharm\\paper_algorithm\\FindSimilarityCommunity\\src\\data\\preprocessData\\M1.edges\",\n # b\"D:\\workspace\\pycharm\\paper_algorithm\\FindSimilarityCommunity\\src\\data\\preprocessData\\M1_1.edges\")\n produce_text_info(b\"D:\\workspace\\pycharm\\paper_algorithm\\FindSimilarityCommunity\\src\\data\\preprocessData\\info_2045\")","sub_path":"FindSimilarityCommunity/src/data/preprocessData/process_file.py","file_name":"process_file.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"80585785","text":"#import optunity\n#from optunity.solvers import RandomSearch\nfrom hyperopt import hp, fmin, tpe\nfrom math import log\nimport argparse\nfrom get_data_no_crf import samples_no_vec, get_batches, get_emb_vocab, pad_data\nfrom train_opt_v2 import train_fold\nimport logging\nimport codecs\nimport os\nimport json\nimport csv\nfrom time import time\n\nrun_counter = 0\ndef run_wrapper(params):\n global run_counter\n global output_file\n\n run_counter += 1\n logging.info(\"run: %s\" % run_counter)\n s = time()\n fscore_prop = run_test(params)\n\n \"elapsed: {}s \\n\".format(int(round(time() - s)))\n\n writer.writerow([fscore_prop] + list(params))\n output_file.flush()\n return fscore_prop\n\n\ndef run_test(params):\n global argv\n hidden_size, grad_clip, word_freq, reg_coef, lr, keep_cell, keep_input, keep_output = params\n parser.add_argument('--hidden_size', type=int, default=int(hidden_size), help='dimension of LSTM hidden layer')\n parser.add_argument(\"--grad_clip\", type=float, default=grad_clip, help=\"clip gradients to this value\")\n parser.add_argument('--word_freq', type=int, default=word_freq, help='word frequency')\n parser.add_argument('--reg_coef', type=float, default=reg_coef, help='L2 Reg rate')\n parser.add_argument('--lr', type=float, default=lr, help='learning rate')\n parser.add_argument('--keep_cell', type=float, default=keep_cell, help='keep cell rate')\n parser.add_argument('--keep_input', type=float, default=keep_input, help='keep input rate')\n parser.add_argument('--keep_output', type=float, default=keep_output, help='keep output rate')\n trail_id = int(argv.trail_id) + 1\n parser.add_argument(\"--trail_id\", type=str, default=str(trail_id), help=\"model_id\")\n argv = parser.parse_args()\n #################################\n # Get vocabulary and embeddings#\n #################################\n json_name = os.path.join(os.path.abspath(os.curdir), \"..\", \"..\", \"corpora\", \"mpqa_jsons\", \"train_fold_0.json\")\n with open(json_name) as data_file:\n train_corpus = json.load(data_file)\n json_name = os.path.join(os.path.abspath(os.curdir), \"..\", \"..\", \"corpora\", \"mpqa_jsons\", \"test_fold_0.json\")\n with open(json_name) as data_file:\n test_corpus = json.load(data_file)\n\n json_name = os.path.join(os.path.abspath(os.curdir), \"..\", \"..\", \"corpora\", \"mpqa_jsons\", \"dev.json\")\n with open(json_name) as data_file:\n dev_corpus = json.load(data_file)\n\n sentences = []\n for corpus in [train_corpus, test_corpus, dev_corpus]:\n for doc_num in range(corpus['documents_num']):\n document_name = \"document\" + str(doc_num)\n doc = corpus[document_name]\n for sent_num in range(doc['sentences_num']):\n sentence_name = \"sentence\" + str(sent_num)\n sentence_lower = map(lambda x: x.lower(), doc[sentence_name]['sentence_tokenized'])\n sentences.append(sentence_lower)\n logging.info('total number of sentences: %s' % len(sentences))\n\n embeddings, vocabulary = get_emb_vocab(sentences, argv.emb_type, argv.emb_size, argv.word_freq)\n logging.info('size of the vocabulary; %s' % len(vocabulary))\n\n parser.add_argument('--embeddings', default=embeddings, help=\"embeddings matrix\")\n parser.add_argument(\"--vocabulary\", default=vocabulary, help=\"vocabulary\")\n\n # get train/dev/test batches\n logging.info('creating train/test/dev samples...')\n json_name = os.path.join(os.path.abspath(os.curdir), \"..\", \"..\", \"corpora\", \"mpqa_jsons\",\n \"train_fold_0.json\")\n with open(json_name) as data_file:\n train_corpus = json.load(data_file)\n json_name = os.path.join(os.path.abspath(os.curdir), \"..\", \"..\", \"corpora\", \"mpqa_jsons\",\n \"test_fold_0.json\")\n with open(json_name) as data_file:\n test_corpus = json.load(data_file)\n\n data_train = samples_no_vec(train_corpus, vocabulary)\n train_batches = get_batches(data_train, argv.batch_size, vocabulary, argv.sort_batches, argv.bucket_batches)\n\n data_test = samples_no_vec(test_corpus, vocabulary)\n test_batches = get_batches(data_test, argv.batch_size, vocabulary, argv.sort_batches, argv.bucket_batches)\n\n dev_data = samples_no_vec(dev_corpus, vocabulary)\n dev_batches = get_batches(dev_data, argv.batch_size, vocabulary, argv.sort_batches, argv.bucket_batches)\n\n logging.info('train size: %s' % len(data_train))\n logging.info('dev size: %s' % len(dev_data))\n logging.info('test size: %s' % len(data_test))\n\n parser.add_argument('--train_batches', default=train_batches, help='train batches')\n parser.add_argument('--test_batches', default=test_batches, help='test batches')\n parser.add_argument('--dev_batches', default=dev_batches, help='dev batches')\n argv = parser.parse_args()\n # train & eval\n # ==================================================\n prop_fscore = train_fold(argv)\n return prop_fscore\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='opinion/ds extraction', add_help=False, conflict_handler='resolve')\n\n \"\"\" architecture \"\"\"\n parser.add_argument('--emb_size', type=int, default=100, help='dimension of embeddings')\n parser.add_argument('--emb_type', default=\"glove\", help=\"type of embeddings\")\n parser.add_argument('--relu_output', default=\"True\", help=\"use relu for output\")\n parser.add_argument(\"--pretrained_emb\", type=str, default=\"True\", help=\"pretrained emb or not\")\n\n \"\"\" training options \"\"\"\n parser.add_argument('--opt', default='adam', help='optimization method')\n parser.add_argument('--batch_size', type=int, default=64, help='batch size')\n parser.add_argument('--num_epoch', type=int, default=80, help='number of epochs to train')\n parser.add_argument('--sort_batches', default=\"False\", help='sort batches w.r.t. the max sequence length')\n parser.add_argument('--bucket_batches', default=\"False\", help='bucket batches w.r.t. the max sequence length')\n parser.add_argument(\"--learning_rate_fixed\", default=\"True\", help=\"learning rate fixed or not\")\n parser.add_argument(\"--train_emb\", default=\"False\", help=\"train embeddings or not\")\n parser.add_argument('--num_layer', type=int, default=1, help='number of layers')\n\n \"\"\" misc \"\"\"\n parser.add_argument(\"--allow_soft_placement\", default=\"True\", help=\"allow device soft device placement\")\n parser.add_argument(\"--log_device_placement\", default=\"True\", help=\"log placement of ops on devices\")\n parser.add_argument(\"--trail_id\", type=str, default=\"0\", help=\"model_id\")\n parser.add_argument(\"--max_evals\", type=int, default=80, help=\"max eval #\")\n\n argv = parser.parse_args()\n\n logging.basicConfig(\n filename=\"logs/random_search_opinion_extraction_v2.log\",\n level=logging.DEBUG)\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n logging.getLogger('').addHandler(console)\n\n rs_file = codecs.open(\"random_search_opinion_extraction_v2.txt\", \"a\")\n rs_file.write(\"eval id\\thidden size\\tgradient clip.\\tnum layers\\tword freq\\treg. coef.\\t\"\n \"keep cell prob.\\tkeep input prob.\\tkeep output prob.\\tnum of params\\tavg. train. time\\t\"\n \"the best prop. dev fscore\\tthe best binary dev fscore\\ttest prop. fscore\\ttest binary fscore\\n\")\n rs_file.close()\n\n headers = ['hidden size', 'gradient clip.', 'num layers', 'word freq', 'reg. coef.', 'lr',\n 'keep cell prob.', 'keep input prob.', 'keep output prob.', 'num of params', 'avg. train. time',\n 'the best prop. dev fscore', 'the best binary dev fscore', 'test prop. fscore', 'test binary fscore']\n output_file = open('random_search_opinion_extraction_v2', 'wb' )\n writer = csv.writer(output_file)\n writer.writerow(headers)\n\n space = (hp.qloguniform('hidden_size', log(30), log(200), 1),\n hp.uniform('grad_clip', 1.0, 10.0),\n hp.uniform('word_freq', 1, 8),\n hp.loguniform('reg_coef', 1e-7, 1e-2),\n hp.loguniform('lr', 0.001, 1),\n hp.uniform('keep_cell', 0.65, 1.0),\n hp.uniform('keep_input', 0.5, 1.0),\n hp.uniform('keep_output', 0.65, 1.0))\n\n start_time = time()\n best = fmin(run_wrapper, space, algo = tpe.suggest, max_evals=argv.max_evals)\n end_time = time()\n\n logging.info(\"seconds passed: %s\" % int(round(end_time-start_time)))\n logging.info(\"best: %s\" % best)\n\n\n\n","sub_path":"tpe_optimization.py","file_name":"tpe_optimization.py","file_ext":"py","file_size_in_byte":8457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"567055481","text":"import subprocess\nimport sys\n\nimport requests\nfrom requests.models import Response\n\nfrom .exceptions import DejavuError, LinkError\nfrom .helpers import custom_headers, format_header, new_url, post_options\nfrom .messages import check_buttonurl\nfrom .settings import BASE_DIR\n\n\nclass ClinetSession:\n def __init__(self) -> None:\n self.session = requests.Session()\n\n def get(self, url, timeout=5) -> tuple[Response, str]:\n resp = self.session.get(url, timeout=timeout)\n return resp, resp.text.lower()\n\n def post(self, url, data, headers, timeout=5) -> tuple[str, int]:\n resp = self.session.post(\n url,\n data=data,\n headers=headers,\n timeout=timeout,\n )\n return resp.text, resp.status_code\n\n\ndef do_visit_site(chat_summary: dict) -> None:\n \"\"\"Perform HTTP requests accordingly.\n\n Args:\n chat_summary (dict): Summary/details of the bot's message.\n\n Raises:\n LinkError: Can't perform operations on the URL.\n DejavuError: Loop encounters a client-sent message.\n \"\"\"\n\n cf = \"challenge-form\"\n tl = \"timeleft\"\n clientuser_msg = \"/visit\"\n page_indicator = \"action=\"\n\n url = check_buttonurl(chat_summary)[\"url\"]\n if not new_url(url=url):\n raise LinkError\n\n session: ClinetSession = ClinetSession()\n get_res, resp_text = session.get(url)\n\n if clientuser_msg in resp_text and page_indicator not in resp_text:\n raise DejavuError\n if tl in resp_text:\n opt = post_options(get_res.text, url)\n hed = format_header(custom_headers(), opt)\n _ = session.post(opt[\"redirect\"], opt[\"payload\"], hed)\n elif cf in resp_text:\n subprocess.Popen([sys.executable, f\"{BASE_DIR}/utils/openurl.py\", url])\n\n new_url(url=url, write=True)\n\n\ndef do_join_chat():\n pass\n\n\ndef do_message_bot():\n pass\n","sub_path":"telegram_cb/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"595588933","text":"from mqttsn_transport_udp import MQTTSNTransportUDP\nfrom mqttsn_client import MQTTSNClient, MQTTSNState, MQTTSNGWInfo, MQTTSNPubTopic, MQTTSNSubTopic\nfrom mqttsn_messages import MQTTSNFlags\nimport time\n\n# list of gateways\ngateways = [MQTTSNGWInfo(1, b'\\x01')]\n\n# setup transport info\nport = 20000\ntransport = MQTTSNTransportUDP(port, b'\\x04')\n\nprint(\"Starting client.\")\n\n# create client and connect\nclnt = MQTTSNClient(b'TestClient', transport)\nclnt.add_gateways(gateways)\nclnt.connect(gwid=1)\n\n# wait till we're connected\nwhile not clnt.is_connected() or clnt.state == MQTTSNState.CONNECTING:\n time.sleep(0.05)\n\n# pub and sub topics\nsub_topics = [MQTTSNSubTopic(b'button')]\npub_topics = [MQTTSNPubTopic(b'led')]\n\n\ndef message_callback(topic: bytes, data: bytes, flags: MQTTSNFlags):\n out = 'Topic: {}, Data: {}, Flags: {}'.format(topic, data, flags.union)\n print(out)\n\n\n# register callback for incoming publish\nclnt.on_message(message_callback)\n\n\ndef init_tasks():\n if not clnt.register_topics(pub_topics):\n return False\n\n if not clnt.subscribe_topics(sub_topics):\n return False\n\n return True\n\n\nled_state = bytearray([0])\nlast_publish = time.time()\n\nprint('Entering client loop.')\nwhile True:\n try:\n time.sleep(0.05)\n clnt.loop()\n\n if clnt.state in (MQTTSNState.DISCONNECTED, MQTTSNState.LOST):\n print(\"Gateway connection lost.\")\n\n # check if all the pubs and subs are done\n if not init_tasks():\n continue\n\n # toggle led state and publish every 5 secs\n if time.time() - last_publish > 5:\n led_state[0] ^= 1\n clnt.publish(b'led', led_state)\n last_publish = time.time()\n except KeyboardInterrupt:\n break\n","sub_path":"pubsub_client_test.py","file_name":"pubsub_client_test.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"258250822","text":"# -*- coding: utf-8 -*-\n\nfrom term import TerminalController, ProgressBar\n\n\nterm = TerminalController()\nprint(term.render('${YELLOW}Warning:${NORMAL}'), 'paper is crinkled')\nprint(term.render('${RED}Error${NORMAL}'), 'paper is ripped')\n\n\nimport time\nterm = TerminalController()\nprogress = ProgressBar(term, 'Processing some files')\nfilenames = ['this', 'that', 'other', 'foo', 'bar', 'baz']\nfor i, filename in zip(list(range(len(filenames))), filenames):\n progress.update(float(i)/len(filenames), 'working on %s' % filename)\n time.sleep(.3)\nprogress.clear()\n","sub_path":"demo/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"91126650","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nGiven a 32-bit signed integer, reverse digits of an integer.\n\nExample 1:\n Input: 123\n Output: 321\n\nExample 2:\n Input: -123\n Output: -321\n\nExample 3:\n Input: 120\n Output: 21\n\nNote:\nAssume we are dealing with an environment which could only store integers within\nthe 32-bit signed integer range: [−231, 231 − 1].\nFor the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.\n\"\"\"\n\n\nclass Solution(object):\n @staticmethod\n def reverse(x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n strings = list(str(x))\n if strings[0] is not '-':\n reverse_num = int(''.join(strings[::-1]))\n else:\n reverse_num = int(''.join(strings[1:][::-1])) * (-1)\n\n if (reverse_num > (2 ** 31 - 1)) | (reverse_num < (2 ** 31 * (-1))):\n return 0\n else:\n return reverse_num\n\n\nif __name__ == '__main__':\n test_num = 120\n print(Solution.reverse(test_num))\n","sub_path":"ReverseInteger.py","file_name":"ReverseInteger.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"240638861","text":"import numpy as np\r\nfrom scipy.optimize import curve_fit\r\nimport matplotlib.pyplot as mpl\r\nimport os\r\nimport datetime\r\n\r\n#Klasa odpowiedzialna za rysowanie wykresu funkcji oraz zapisywanie wykresow do pliku\r\nclass Plotter:\r\n counter = 0\r\n poczatkowa = True\r\n dopasowana = True\r\n dane = True\r\n xlim_min = 0\r\n xlim_max = 10\r\n def __init__(self):\r\n self.fig = mpl.figure(facecolor=\"white\",figsize=(10, 6))\r\n self.i = datetime.datetime.now()\r\n\r\n #Funkcja rysujaca wykres\r\n #Argumenty: wartosci x, wartosci y(funkcji poczatkowej), wartosci yn(wartosci zaszumione), wartosci dopasowanej funkcji\r\n def plot(self,x,y,yn,fitted_data):\r\n mpl.clf()\r\n mpl.close()\r\n self.fig = mpl.figure(facecolor=\"white\",figsize=(10, 6))\r\n ax = self.fig.add_subplot(111)\r\n #Rysuje na wykresie zaszumione dane, jesli opcja jest zaznaczona\r\n if(Plotter.dane):\r\n ax.scatter(x, yn,c='g',s=10,edgecolor='green',label='Dane')\r\n #Rysuje na wykresie funkcje dopasowana, jesli opcja jest zaznaczona\r\n if(Plotter.dopasowana):\r\n ax.plot(x, fitted_data, c='r',linewidth=4.0, label='Dopasowanie')\r\n #Rysuje na wykresie funkcje poczatkowa, jesli opcja jest zaznaczona\r\n if(Plotter.poczatkowa):\r\n ax.plot(x, y, c='b',linewidth=1.0, label='Funkcja podst.')\r\n ax.legend(prop={'size':10})\r\n mpl.xlim((Plotter.xlim_min,Plotter.xlim_max))\r\n\r\n self.timePlot = str(self.i.strftime('%Y-%m-%d_%H_%M_%S'))\r\n self.CheckDirectory()\r\n mpl.savefig(\"images/\" + self.timePlot + \"/plot_\"+str(Plotter.counter)+\".png\")\r\n Plotter.counter += 1\r\n return self.fig\r\n\r\n #Funckja tworzaca foldery images(jesli nie ma) oraz foldery z aktualna data (tworzona przy uruchomieniu programu)\r\n #do ktorego zapisuje wykresy.\r\n #Przy kazdym uruchomieniu programu tworzy nowy folder\r\n def CheckDirectory(self):\r\n if not os.path.exists(\"images\"):\r\n os.makedirs(\"images\")\r\n if not os.path.exists(\"images/\"+self.timePlot):\r\n os.makedirs(\"images/\"+self.timePlot)\r\n","sub_path":"fitter/Plotter.py","file_name":"Plotter.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"409726282","text":"import time\nfrom typing import List, Dict\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom environments import VRPSolver, VRPEnvironment\nfrom instances import VRPInstance\n\n\nclass Stats(Dict[VRPSolver, Dict[VRPInstance, dict]]):\n def __init__(self, solvers: List[VRPSolver]):\n super().__init__([(solver, {}) for solver in solvers])\n\n def mean_cost(self) -> Dict[str, float]:\n return {solver.name: np.mean([info[\"cost\"] for info in self[solver].values()]) for solver in self.keys()}\n\n\nclass Evaluator:\n def __init__(self, solvers: List[VRPSolver], render=False):\n self.solvers = solvers\n self.render = render\n\n def compare(self, instances: List[VRPInstance], max_steps: int, time_limit: int) -> Stats:\n stats = Stats(self.solvers)\n if self.render:\n fig, axes = plt.subplots(len(instances), len(self.solvers),\n sharex=True, sharey=True, squeeze=False,\n figsize=(3*len(self.solvers), 2*len(instances)))\n for i, inst in enumerate(instances):\n for j, solver in enumerate(self.solvers):\n stats[solver][inst] = {}\n inst_stats = stats[solver][inst]\n start_time = time.time()\n sol = solver.solve(inst, max_steps=max_steps, time_limit=time_limit)\n solve_time = time.time() - start_time\n sol.verify()\n if self.render:\n axes[i, j].set_aspect(\"equal\")\n inst.plot(sol, axes[i, j])\n inst_stats[\"solution\"] = sol\n inst_stats[\"n_vehicles\"] = len(sol.routes)\n inst_stats[\"cost\"] = sol.cost()\n inst_stats[\"time\"] = solve_time\n if isinstance(solver, VRPEnvironment):\n inst_stats[\"steps\"] = solver.n_steps\n inst_stats[\"improvements\"] = solver.improvements\n print(f\"Instance {i} solved by {solver.name} with cost {inst_stats['cost']}\")\n solver.render()\n if self.render:\n plt.show()\n return stats\n","sub_path":"src/main/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"285744799","text":"#!/usr/bin/python\n#\n\nimport numpy\nimport os\nimport sys\nfrom scipy import stats\n\naValues = [10, 20, 30]\netaValues = [20, 41, 82]\ncflValues = [60, 70, 80, 90, 99]\npValues = [1, 2]\nerrorTypes = [\"L1\", \"L2\", \"Li\"]\n\nresultsPath = str(sys.argv[1])\ndeployPath = str(sys.argv[2])\n\np_e_path = deployPath + '/table_error_3'\nif not os.path.isdir(p_e_path) :\n\n os.mkdir(p_e_path)\n os.chdir(p_e_path)\n\n data_path = deployPath + '/dr_error_collect'\n\n error = numpy.fromfile(data_path + \"/error.npy\")\n\n # This is dangerous, a change in the saved shape must be\n # reproduced here.\n error = error.reshape((len(etaValues),len(cflValues),len(pValues),len(aValues),len(errorTypes)))\n \n type2 = numpy.dtype([\n ('error_type', str, 10),\n ('a', str, 10),\n ('rate_last_best', numpy.float64, 1),\n ('rate_last_worst', numpy.float64, 1),\n ('rate_last_mean', numpy.float64, 1),\n ('rate_reg_best', numpy.float64, 1),\n ('rate_reg_worst', numpy.float64, 1),\n ('rate_reg_mean', numpy.float64, 1),\n ('R2_reg_worst', numpy.float64, 1),\n ('finest_best', numpy.float64, 1),\n ('finest_worst', numpy.float64, 1)])\n\n for pIndex, pV in enumerate(pValues) :\n \n proc_data_2 = numpy.empty([0,1],dtype=type2)\n\n for aIndex, aV in enumerate(aValues) : \n for etIndex, error_type in enumerate(errorTypes) :\n\n rate_last_sum = 0\n rate_last_best = 0\n rate_last_worst = \"inf\"\n rate_reg_sum = 0\n rate_reg_best = 0\n rate_reg_worst = \"inf\"\n R2_worst = \"inf\"\n finest_worst = 0\n finest_best = \"inf\"\n counter = 0\n\n for cflIndex, cflV in enumerate(cflValues) :\n\n counter += 1\n \n rate_last = (1/numpy.log(2)) * numpy.log( error[-2,cflIndex,pIndex,aIndex,etIndex] \\\n / error[-1,cflIndex,pIndex,aIndex,etIndex] )\n rate_last_sum += rate_last\n rate_last_worst = min(rate_last_worst, rate_last) \n rate_last_best = max(rate_last_best, rate_last) \n\n rate_reg, intercept, R, p_value, std_err \\\n = stats.linregress(-numpy.log(etaValues), numpy.log(error[:,cflIndex,pIndex,aIndex,etIndex]))\n R2 = R**2\n rate_reg_sum += rate_reg\n rate_reg_worst = min(rate_reg_worst, rate_reg) \n rate_reg_best = max(rate_reg_best, rate_reg) \n R2_worst = min(R2_worst, R2)\n\n finest_worst = max(error[-1,cflIndex,pIndex,aIndex,etIndex],finest_worst)\n finest_best = min(error[-1,cflIndex,pIndex,aIndex,etIndex],finest_best)\n \n rate_last_mean = rate_last_sum / counter\n rate_reg_mean = rate_reg_sum / counter\n\n proc_data_2 = numpy.row_stack((proc_data_2,\n numpy.array(\n [(error_type,\n aV,\n rate_last_best,\n rate_last_worst,\n rate_last_mean,\n rate_reg_best,\n rate_reg_worst,\n rate_reg_mean,\n R2_worst,\n finest_best,\n finest_worst)],\n dtype=type2)))\n\n header = ' '.join(proc_data_2.dtype.names)\n outfile_name = \"conv_rates_stats_as-p\" + str(pV) + \".dat\"\n with open(outfile_name,'w') as outfile :\n outfile.write(\"# \" + header + '\\n')\n prev_a = \"\"\n for row in proc_data_2 :\n if row['a'] != prev_a :\n outfile.write('# ------------------------ \\n')\n prev_a = row['a']\n numpy.savetxt(outfile,\n row,\n fmt=\"%s %s %f %f %f %f %f %f %f %f %f \")\n outfile.close()\n","sub_path":"apps/hifu-beam/plots/error_table_3.py","file_name":"error_table_3.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"322019659","text":"############\n# Part 1 #\n############\n\n\nclass MelonType(object):\n \"\"\"A species of melon at a melon farm.\"\"\"\n\n def __init__(self, code, first_harvest, color, is_seedless, is_bestseller, \n name):\n \"\"\"Initialize a melon.\"\"\"\n\n self.pairings = []\n\n # Fill in the rest\n self.code = code\n self.first_harvest = first_harvest\n self.color = color\n self.is_seedless = is_seedless\n self.is_bestseller = is_bestseller\n self.name = name\n\n def add_pairing(self, pairing):\n \"\"\"Add a food pairing to the instance's pairings list.\"\"\"\n\n # Fill in the rest\n self.pairings.append(pairing)\n\n def update_code(self, new_code):\n \"\"\"Replace the reporting code with the new_code.\"\"\"\n\n # Fill in the rest\n self.code = new_code\n\n\ndef make_melon_types():\n \"\"\"Returns a list of current melon types.\"\"\"\n\n all_melon_types = []\n\n # Fill in the rest\n musk = MelonType('musk', 1988, 'green', True, True, 'Muskmelon')\n musk.add_pairing('mint')\n\n cas = MelonType('cas', 2003, 'orange', False, False, 'Casaba')\n cas.add_pairing('strawberries')\n cas.add_pairing('mint')\n\n cren = MelonType('cren', 1996, 'green', False, False, 'Crenshaw')\n cren.add_pairing('prosciutto')\n\n yw = MelonType('yw', 2013, 'yellow', False, True, 'Yellow Watermelon')\n yw.add_pairing('ice cream')\n\n all_melon_types.extend([musk, cas, cren, yw])\n\n return all_melon_types\n\n\ndef print_pairing_info(melon_types):\n \"\"\"Prints information about each melon type's pairings.\"\"\"\n\n # Fill in the rest\n for melon_type in melon_types:\n # Print header part of pairing for one melon type\n print(f\"{melon_type.name} pairs with\")\n\n # Go through all the pairings the melon type has and print one per line\n for pairing in melon_type.pairings:\n print(f\"- {pairing}\")\n\n # Add a line break between different melon types\n print()\n\n\ndef make_melon_type_lookup(melon_types):\n \"\"\"Takes a list of MelonTypes and returns a dictionary of melon type by code.\"\"\"\n\n # Fill in the rest\n melon_type_lookup = {}\n\n for melon_type in melon_types:\n melon_type_lookup[melon_type.code] = melon_type\n\n return melon_type_lookup\n\n\n############\n# Part 2 #\n############\n\nclass Melon(object):\n \"\"\"A melon in a melon harvest.\"\"\"\n\n # Fill in the rest\n # Needs __init__ and is_sellable methods\n\n def __init__(self, melon_type, shape_rating, color_rating,\n harvest_location, harvested_by):\n self.melon_type = melon_type\n self.shape_rating = shape_rating\n self.color_rating = color_rating\n self.harvest_location = harvest_location\n self.harvested_by = harvested_by\n\n def is_sellable(self):\n \"\"\"Check whether melon meets conditions and return True or False\n based on the check.\n\n Current conditions are:\n - shape rating greater than 5\n - color rating greater than 5\n - harvest location NOT from field 3\"\"\"\n\n good_shape = self.shape_rating > 5\n good_color = self.color_rating > 5\n unpoisoned = not self.harvest_location == 3\n\n if good_shape and good_color and unpoisoned:\n return True\n \n return False\n\n\ndef make_melons(melon_types):\n \"\"\"Returns a list of Melon objects.\"\"\"\n\n # Fill in the rest\n melons = []\n\n melons_by_id = make_melon_type_lookup(melon_types)\n\n melon_1 = Melon(melons_by_id['yw'], 8, 7, 2, 'Sheila')\n melon_2 = Melon(melons_by_id['yw'], 3, 4, 2, 'Sheila')\n melon_3 = Melon(melons_by_id['yw'], 9, 8, 3, 'Sheila')\n melon_4 = Melon(melons_by_id['cas'], 10, 6, 35, 'Sheila')\n melon_5 = Melon(melons_by_id['cren'], 8, 9, 35, 'Michael')\n melon_6 = Melon(melons_by_id['cren'], 8, 2, 35, 'Michael')\n melon_7 = Melon(melons_by_id['cren'], 2, 3, 4, 'Michael')\n melon_8 = Melon(melons_by_id['musk'], 6, 7, 4, 'Michael')\n melon_9 = Melon(melons_by_id['yw'], 7, 10, 3, 'Sheila')\n\n melons.extend([melon_1, melon_2, melon_3, melon_4, melon_5,\n melon_6, melon_7, melon_8, melon_9])\n\n return melons\n\n\ndef get_sellability_report(melons):\n \"\"\"Given a list of melon object, prints whether each one is sellable.\"\"\"\n\n # Fill in the rest\n # Go through each melon\n for melon in melons:\n harvester = melon.harvested_by\n field = f\"Field {str(melon.harvest_location)}\"\n\n # By default, assume not sellable\n sellability = \"NOT SELLABLE\"\n\n # If melon is in fact sellable, update sellability message\n if melon.is_sellable():\n sellability = \"CAN BE SOLD\"\n\n # Put together the sellability report for a single melon\n print(f\"Harvested by {harvester} from {field} ({sellability})\")\n\n\n\n","sub_path":"oo-practice-melons/harvest.py","file_name":"harvest.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"169293379","text":"from flask import Flask, render_template, request,redirect,url_for\n\napp = Flask(__name__)\n@app.route('/',methods=['GET','POST'])\n\n@app.route('/login',methods=['GET','POST'])\ndef login():\n if request.method == 'POST':\n return redirect(url_for('login'))\n\n return render_template(\"login.html\")\n\n@app.route('/registration',methods=['GET','POST'])\ndef registration():\n if request.method == 'POST':\n return redirect(url_for('registration'))\n\n return render_template(\"registration.html\")\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\",port=5000, debug=True)","sub_path":"midterm_app.py","file_name":"midterm_app.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"95096520","text":"import os\nimport numpy as np\nimport cv2\n\nnormal = '\\033[0m'\nkirmizi= '\\033[31m'\nyesil= '\\033[32m'\nsari= '\\033[33m'\nlacivert= '\\033[34m'\nmor= '\\033[35m'\nmavi= '\\033[36m'\npmavi = '\\033[96m'#p --> parlak\npkirmizi= '\\033[91m'\npyesil = '\\033[92m'\npsari = '\\033[93m'\nsiyah = '\\033[90m'\nasiyah= '\\033[40m'#a --> arkaplan\nakirmizi= '\\033[41m'\nayesil= '\\033[42m'\nasari= '\\033[43m'\nalacivert= '\\033[44m'\namor= '\\033[45m'\namavi= '\\033[46m'\nabeyaz= '\\033[47m'\napsiyah= '\\033[100m'#a --> arkaplan-parlak\napkirmizi= '\\033[101m'\napyesil= '\\033[102m'\napsari= '\\033[103m'\naplacivert= '\\033[104m'\napmor= '\\033[105m'\napmavi= '\\033[106m'\napbeyaz= '\\033[107m'\nfaceCascade = cv2.CascadeClassifier('yuz.xml')#buraya yuz.xml doyasinin konumunu girin\ncap = cv2.VideoCapture(0)\ncap.set(3,640) # set Width\ncap.set(4,480) # set Height\nwhile True:\n ret, img = cap.read()\n img = cv2.flip(img, -1)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = faceCascade.detectMultiScale(\n gray,\n\n scaleFactor=1.2,\n minNeighbors=5, \n minSize=(20, 20)\n )\n\n for (x,y,w,h) in faces:\n #print(pyesil + str(x),pyesil + str(y),pmavi +str(w),pmavi +str(h))\n #print(w,h)\n if(w>250):\n print(pmavi+\"Kameraya Cok Yakinsin Uzaklas!!\",w)\n if(w>200 and w<250):\n print(pyesil+\"Cok Yakin\",w)\n if(w>150 and w<200):\n print(yesil+\"Yakin\",w)\n if(w>100 and w<150):\n print(psari+\"Orta\",w)\n if(w>50 and w<100):\n print(mor+\"Uzak\",w)\n if(w<50):\n print(pkirmizi+\"Cok Uzak\",w)\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,50,50),2)\n #roi_gray = gray[y:y+h, x:x+w]\n roi_color = img[y:y+h, x:x+w] \n cv2.imshow('video',img)\n k = cv2.waitKey(30) & 0xff\n if k == 27: # press 'ESC' to quit\n break\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"opencv_yüz_mesafe_tanıma.py","file_name":"opencv_yüz_mesafe_tanıma.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"679277","text":"# **************************************************************\n# Projekt : Pibeacon\n# Modul : rfcomm.server\n# --------------------------------------------------------------\n# Autor(en) : Timo Senn\n# Beginn-Datum : 30.04.2017\n# --------------------------------------------------------------\n# Beschreibung : RFCOMM-Server for pairing\n# --------------------------------------------------------------\n#\n# **************************************************************\n# Änderungs-Protokoll:\n# --------------------------------------------------------------\n# wann wer was\n# 10.05.2017 TS Adding Checkbox for Pairing\n# --------------------------------------------------------------\nimport bluetooth\nimport socket\nimport _thread\nfrom comm.intcomm import IntComm\nfrom comm.intmessage import IntMessage as IntMsg\n\nclass Server(IntComm):\n\n _commCallback = None\n\n def __init__(self, commCallback):\n self._commCallback = commCallback\n\n def comm(self, msg):\n pass\n \n def startServer(self):\n \n print (\"Starting server\")\n server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )\n\n port = 1\n server_sock.bind((\"\",port))\n server_sock.listen(1)\n port = server_sock.getsockname()[1]\n\n self._commCallback(IntMsg(IntMsg.SIGNAL_DHBWBEACON, {'DATA': 'Started new Server on Socket ' + str(port)}))\n\n\n self._commCallback(IntMsg(IntMsg.SIGNAL_DHBWBEACON, {'DATA': 'Waiting for connection on RFCOMM channel %d' % port}))\n\n client_sock,address = server_sock.accept()\n\n self._commCallback(IntMsg(IntMsg.SIGNAL_DHBWBEACON, {'DATA': 'Accepted connection from ' + address}))\n\n self._commCallback(IntMsg(IntMsg.SIGNAL_DHBWBEACON, {'disconnected' + str(client_info)}))\n client_sock.close()\n server_sock.close()\n\n","sub_path":"src/rfcomm/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"93074680","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nfrom scipy.stats import kstest, ks_2samp\n# from sklearn.preprocessing import StandardScaler\nfrom sklearn import preprocessing\n\ndef violin(data, str = 'g_active_power'):\n fig, ax = plt.subplots(figsize = (23,8))\n data['full_time'] = pd.to_datetime(data['full_time'])\n ax = sns.violinplot(x = data['full_time'].dt.hour, y = data[str], color = 'aqua',scale = 'width', data = data)\n ax.set_xlabel('hour')\n ax.set_ylabel(str)\n plt.show()\n\ndef test_seperate_year(str = 'g_active_power'):\n fig, ax = plt.subplots(figsize = (10,5))\n x = d_2007.index\n ax.plot(x, d_2007[str], 'bo--')\n ax.plot(x, d_2008[str], 'ro--')\n ax.plot(x, d_2009[str], 'go--')\n ax.plot(x, d_2010[str], 'yo--')\n ax.legend(['2007', '2008', '2009', '2010'])\n ax.set_xlabel('hour in a day')\n ax.set_ylabel(str)\n plt.title(str+' hourly distribution in a day (during year 2007-2010)')\n plt.show()\n \n \n \n# Ks_test for the normality of hourly data, return the p-value of test\n\ndef ks_test(data, hour = 0, str = 'g_active_power'):\n x = data.loc[data['full_time'].dt.hour == hour][str]\n xs = preprocessing.scale(x)\n rvs = stats.norm.rvs(size=x.size)\n test = ks_2samp(xs, rvs)\n return test.pvalue \n\n","sub_path":"util_hour.py","file_name":"util_hour.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"277462486","text":"import os\nimport glob\n\nfrom io import StringIO\n\nfrom django.apps import apps\nfrom django.core import management\nfrom django.db.migrations import writer\nfrom django.core.management import BaseCommand\n\n\nclass Command(BaseCommand):\n help = \"Locate files and create data migrations for them.\"\n\n def handle(self, *args, **options):\n fixture_file = options['file'] if options['file'] else 'initial_data'\n fixture_template = f\"{fixture_file}.*\"\n applied_number = 0\n\n for app in apps.get_app_configs():\n for fixture_path in glob.glob(os.path.join(app.path, 'fixtures', fixture_template)):\n if not glob.glob(os.path.join(app.path, 'migrations', '0001*')):\n self.stdout.write(self.style.MIGRATE_HEADING(f\"Migrations for '{app.label}':\\n\"))\n self.stdout.write(\n self.style.WARNING(f\"Ignoring '{os.path.basename(fixture_path)}' - not migrated.\\n\")\n )\n self.stdout.write(\n self.style.WARNING('There are no migrations at all\\n')\n )\n continue\n\n if self.migration_exists(app, fixture_path):\n self.stdout.write(self.style.MIGRATE_HEADING(f\"Migrations for '{app.label}':\\n\"))\n self.stdout.write(\n self.style.NOTICE(\n f\"Ignoring '{os.path.basename(fixture_path)}' - migration already exists.\\n\"\n )\n )\n continue\n\n self.create_migration(app, fixture_path)\n applied_number += 1\n\n self.stdout.write(\n self.style.SUCCESS(f'{applied_number} fixtures has been loaded')\n )\n\n def monkey_patch_migration_template(self, app, fixture_path):\n \"\"\"\n Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE\n\n Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we\n don't have to do any complex regex or reflection.\n\n It's hacky... but works atm.\n \"\"\"\n self._MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE\n module_split = app.module.__name__.split('.')\n\n if len(module_split) == 1:\n module_import = \"import %s\\n\" % module_split[0]\n else:\n module_import = \"from %s import %s\\n\" % (\n '.'.join(module_split[:-1]),\n module_split[-1:][0],\n )\n\n writer.MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE.replace(\n '%(imports)s',\n \"%(imports)s\" + \"\\nfrom django_migration_fixture import fixture\\n%s\" % module_import\n ).replace(\n '%(operations)s',\n \" migrations.RunPython(**fixture(%s, ['%s'])),\\n\" % (\n app.label,\n os.path.basename(fixture_path)\n ) + \"%(operations)s\\n\"\n )\n\n def restore_migration_template(self):\n \"\"\"\n Restore the migration template.\n \"\"\"\n writer.MIGRATION_TEMPLATE = self._MIGRATION_TEMPLATE\n\n def migration_exists(self, app, fixture_path):\n \"\"\"\n Return true if it looks like a migration already exists.\n \"\"\"\n base_name = os.path.basename(fixture_path)\n # Loop through all migrations\n for migration_path in glob.glob(os.path.join(app.path, 'migrations', '*.py')):\n if base_name in open(migration_path).read():\n return True\n return False\n\n def create_migration(self, app, fixture_path):\n \"\"\"\n Create a data migration for app that uses fixture_path.\n \"\"\"\n self.monkey_patch_migration_template(app, fixture_path)\n\n out = StringIO()\n management.call_command('makemigrations', app.label, empty=True, stdout=out)\n\n self.restore_migration_template()\n self.stdout.write(out.getvalue())\n\n def add_arguments(self, parser):\n parser.add_argument('-f', '--file', type=str)\n","sub_path":"django_migration_fixture/management/commands/create_initial_data_fixtures.py","file_name":"create_initial_data_fixtures.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"49620962","text":"# -*- coding: utf-8 -*-\n\n\n#Given 2 ints, a and b, return their sum. \n#However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20.\n\n'''\nsorta_sum(3, 4) → 7\nsorta_sum(9, 4) → 20\nsorta_sum(10, 11) → 21\n'''\n\ndef sorta_sum(a, b):\n add_ab = a + b\n if add_ab >= 10 and add_ab <= 19:\n return 20\n else:\n return add_ab","sub_path":"Logic1_sorta_sum.py","file_name":"Logic1_sorta_sum.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"597915270","text":"import time\nfrom datetime import timedelta\nimport os\n\n'''\nПростой скрипт для чтения файла, без дополнительных условий (if)\nДобавил счетчик времени - для анализа \"timedelta\"\n0-11 номер счета\n11-41 это ФИО\n42-47 это сумма\n'''\nstart_time = time.monotonic()\nos.chdir(r\"D:\\python_lab\\test_file_db\")\nif os.path.exists('text_01.txt') == True:\n print(\"Файл *.txt существует\")\nelse:\n print(\"Файл *.txt НЕ существует\")\n\n# s = {'ФИО': [номер счета, сумма на счете]}\ns = {}\n\nf = open('text_01.txt', 'r', encoding='utf-8')\nline = f.readline()\n\nwhile line:\n # print(line)\n # print(\"\\nНомер счета: \" + line[0:11])\n # print(\"\\tФИО владельца счета: \" + line[11:41])\n # print(\"\\tСумма на счете: \" + line[41:47])\n a = line[0:11]\n b = line[11:41]\n c = line[41:47]\n s[b.strip()] = [a, c] # тут убираем все лишние пробелы вокруг ФИО\n line = f.readline()\n f.close\nprint(s)\n\nfile_2 = open('text_02.txt', 'w', encoding='utf-8')\nwhile file_2:\n for fio, info in s.items():\n file_2.write(fio + ' ' + info[0] + ' ' + info[1] + '\\n')\n file_2.close\n break\nend_time = time.monotonic()\n\n# сохраняем в файл с кодировкой DOS\nfile_3 = open('text_02_02.txt', 'w', encoding='cp866')\nwhile file_3:\n for fio, info in s.items():\n file_3.write(fio + ' ' + info[0] + ' ' + info[1] + '\\n')\n file_3.close\n break\nend_time = time.monotonic()\nprint(\"\\nЗатраченное время на скрипт: \")\nprint(timedelta(seconds=end_time-start_time))\n","sub_path":"test_file_db/rw_txt.py","file_name":"rw_txt.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"373652644","text":"import copy\n\ndef maze_solver(maze):\n ''' return a list of moves showing the correct steps to solve the given maze \n @maze: list of list, representing the maze\n\n return: list of correct moves to solve the maze.\n '''\n for row in range(len(maze)):\n for col in range(len(maze[row])):\n if maze[row][col] == 's':\n p_s = (row,col)\n if maze[row][col] == 'e':\n p_e = (row,col)\n discovered = {p_s:None}\n #print('start',p_s)\n #print('end',p_e)\n recursive_dfs(maze,p_s,discovered)\n #print(discovered)\n return recursive_maze(maze,p_s,p_e,discovered)\n \n\ndef recursive_dfs(maze,p_s,discovered):\n direction = ['down','up','left','right']\n row,col = p_s\n around = [(row+1,col),(row-1,col),(row,col-1),(row,col+1)]#down,up,left,right\n for i in range(len(around)):\n if (maze[around[i][0]][around[i][1]] =='.' or maze[around[i][0]][around[i][1]]=='e') and (around[i] not in discovered):\n discovered[around[i]] = [p_s,direction[i]]\n recursive_dfs(maze,around[i],discovered)\n \n#return something like {(1, 15): [(1, 14), 'right']}\n \ndef recursive_maze(maze,p_s,p_e,discovered):\n path = []\n if p_e in discovered:\n path.append(p_e)\n walk = p_e\n while walk != p_s:\n parent = discovered[walk][0]\n# print(walk,discovered[walk])\n path.append(discovered[walk][1])\n walk = parent\n path.reverse()\n return path[:-1]\n\ndef main():\n file = open(\"maze.txt\", 'r') \n maze = []\n for line in file: # Read input maze, store into a 2-D list\n maze.append([])\n for character in line:\n maze[-1].append(character)\n \n print(maze_solver(maze))\n '''\n Result should be something like this, not unique solution though.\n ['right', 'down', 'down', 'right', 'right', 'up', 'up', 'right', 'right', 'down', \n 'down', 'down', 'right', 'up', 'right', 'up', 'up', 'right', 'right', 'right', 'down', \n 'down', 'down', 'down', 'right', 'up', 'right', 'up', 'up', 'up', 'right', 'right', 'right']\n '''\n\n\nmain()\n","sub_path":"Graphs/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"69082707","text":"\n##################################################\n## {Description}\n##################################################\n## {License_info}\n##################################################\n## Author: {Sahar Yousefi}\n## Copyright: Copyright {2020}, {LUMC}\n## Credits: [Sahar Yousefi]\n## License: {GPL}\n## Version: 1.0.0\n## Mmaintainer: {Sahar Yousefi}\n## Email: {s.yousefi.radi[at]lumc.nl}\n## Status: {Research}\n##################################################\nfrom datetime import datetime\nfrom functions.network_caller.hybrid_multi_task_translate_hr_residual_attention2_UnetSkipAttention_not1 import net_translate\nimport numpy as np\nimport tensorflow as tf\nimport os\n\nif __name__ == '__main__':\n '''\n this function calls the translation network\n \n '''\n no_averages=0\n config = [1, 3, 5, 3, 1]\n np.random.seed(1)\n tf.set_random_seed(1)\n fold=8\n server_path = '/exports/lkeb-hpc/syousefi/Code/'\n Logs = 'Log_asl_pet/rest/01_cross_validation/resi_skip_att_not1/residual_skip_not1_fold_'+str(fold)+'/'\n\n # use mixed precision\n mixed_precision = True\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n # check if gpu is available\n GPU = tf.test.is_gpu_available(\n cuda_only=False,\n min_cuda_compute_capability=None\n )\n\n # current date and time\n now = datetime.now()\n date_time = now.strftime(\"%m%d%Y_%H\")\n\n dc12 = net_translate(data_path_AMUC=\"/exports/lkeb-hpc/syousefi/Data/ASL2PET_high_res/AMUC_high_res/\",\n data_path_LUMC=\"/exports/lkeb-hpc/syousefi/Data/ASL2PET_high_res/LUMC_high_res/\",\n server_path=server_path, Logs=Logs,\n config=config)\n dc12.run_net(no_averages,fold=fold)","sub_path":"run_network/run_hybrid_multitask_net_hr_residual_attention2_UnetSkipAttention_not1.py","file_name":"run_hybrid_multitask_net_hr_residual_attention2_UnetSkipAttention_not1.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"199270936","text":"def n_gram(sequence=None, n=1):\n n_gram_list = []\n\n if sequence is None:\n return n_gram_list\n\n for idx, s in enumerate(sequence):\n n_gram_list.append(sequence[idx:idx+n])\n\n return n_gram_list\n\n\ndef main(text1, text2):\n X = set(n_gram(text1, 2))\n Y = set(n_gram(text2, 2))\n\n # 和集合\n print(X | Y)\n\n # 積集合\n print(X & Y)\n\n # 差集合\n print(X - Y)\n print(Y - X)\n\n\nif __name__ == '__main__':\n string1 = 'paraparaparadise'\n string2 = 'paragraph'\n main(string1, string2)\n","sub_path":"chapter_1/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"36187827","text":"import logging\n# https://stackoverflow.com/questions/56494070/how-to-use-pdfminer-six-with-python-3\n\nclass PdfReader:\n\n logger = logging.getLogger(\"pdfreader\")\n\n def __init__(self):\n self.text = None\n\n @classmethod\n def read_and_convert(cls, file):\n from pdfminer3.layout import LAParams, LTTextBox\n from pdfminer3.pdfpage import PDFPage\n from pdfminer3.pdfinterp import PDFResourceManager\n from pdfminer3.pdfinterp import PDFPageInterpreter\n from pdfminer3.converter import PDFPageAggregator\n from pdfminer3.converter import TextConverter\n from pdfminer3.converter import XMLConverter\n import io\n\n resource_manager = PDFResourceManager()\n fake_file_handle = io.StringIO()\n converter = TextConverter(resource_manager, fake_file_handle, laparams=LAParams())\n # converter = XMLConverter(resource_manager, fake_file_handle, laparams=LAParams()) # not tested\n page_interpreter = PDFPageInterpreter(resource_manager, converter)\n\n cls.logger.info(\"PDF FILE\", file)\n with open(file, 'rb') as fh:\n for i, page in enumerate(PDFPage.get_pages(fh,\n caching=True,\n check_extractable=True)):\n page_interpreter.process_page(page)\n print(f\"=================== page {i}=================\")\n\n text = fake_file_handle.getvalue()\n\n # close open handles\n converter.close()\n fake_file_handle.close()\n\n\n \"\"\"\n > pdf2txt.py [-P password] [-o output] [-t text|html|xml|tag]\n [-O output_dir] [-c encoding] [-s scale] [-R rotation]\n [-Y normal|loose|exact] [-p pagenos] [-m maxpages]\n [-S] [-C] [-n] [-A] [-V]\n [-M char_margin] [-L line_margin] [-W word_margin]\n [-F boxes_flow] [-d]\n input.pdf ...\n-P password : PDF password.\n-o output : Output file name.\n-t text|html|xml|tag : Output type. (default: automatically inferred from the output file name.)\n-O output_dir : Output directory for extracted images.\n-c encoding : Output encoding. (default: utf-8)\n-s scale : Output scale.\n-R rotation : Rotates the page in degree.\n-Y normal|loose|exact : Specifies the layout mode. (only for HTML output.)\n-p pagenos : Processes certain pages only.\n-m maxpages : Limits the number of maximum pages to process.\n-S : Strips control characters.\n-C : Disables resource caching.\n-n : Disables layout analysis.\n-A : Applies layout analysis for all texts including figures.\n-V : Automatically detects vertical writing.\n-M char_margin : Speficies the char margin.\n-W word_margin : Speficies the word margin.\n-L line_margin : Speficies the line margin.\n-F boxes_flow : Speficies the box flow ratio.\n-d : Turns on Debug output.\n\n \"\"\"\n print(f\"\\n......\\n{text[:100]}\\n...\\n{text[-100:]}\\n......\\n\")\n return text\n\ndef main():\n test_read()\n\n\ndef test_read():\n pdfReader = PdfReader()\n pdfReader.read_and_convert(\"/Users/pm286/projects/openDiagram/physchem/liion/PMC7040616/fulltext.pdf\");\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"physchem/python/pdfreader.py","file_name":"pdfreader.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"32906791","text":"# coding=utf-8\nfrom comet_ml import Experiment\nfrom comet_ml.utils import ConfusionMatrix\n\nimport numpy as np\nfrom matplotlib import cm\nfrom MachineLearn.Classes import DataSet, Data\n\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.model_selection import KFold\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.optimizers import *\nfrom keras.utils import to_categorical\nfrom rbflayer import RBFLayer, InitCentersRandom\nfrom sklearn.preprocessing import LabelBinarizer\n\nCOLOR = cm.rainbow(np.linspace(0, 1, 5))\nLEARNING_RATE = 0.1\nepochs = 50\nK_FOLD = 3\nGRID_NEURON = [5, 10, 15, 20]\nGRID_B = [.25, .5, .75, 1]\n_OPTIMIZER = SGD(lr=LEARNING_RATE, momentum=0.0, decay=0.0, nesterov=False)\n\noDataSet = DataSet()\nbase = np.loadtxt(\"Datasets/dermatology.data\", usecols=range(34), dtype=int,delimiter=\",\")\nclasses = np.loadtxt(\"Datasets/dermatology.data\", dtype=int, usecols=-1, delimiter=\",\")\n\n\nfor x, y in enumerate(base):\n oDataSet.add_sample_of_attribute(np.array(list(np.float32(y)) + [classes[x]]))\noDataSet.attributes = oDataSet.attributes.astype(float)\noDataSet.normalize_data_set()\n\nlb = LabelBinarizer()\nlb.fit(oDataSet.labels)\n\nfor j in range(16,20):\n experiment = Experiment(api_key=\"9F7edG4BHTWFJJetI2XctSUzM\",\n project_name=\"mest-rn-t6-dermatology\",\n workspace=\"lukkascost\",\n )\n experiment.set_name(\"REALIZACAO_{:02d}\".format(j + 1))\n\n slices = KFold(n_splits=K_FOLD, shuffle=True)\n oData = Data(len(oDataSet.labelsNames), 31, samples=50)\n oData.random_training_test_by_percent(np.unique(classes, return_counts=True)[1], 0.8)\n grid_result = np.zeros((len(GRID_NEURON), len(GRID_B), K_FOLD))\n for g1, g_param in enumerate(GRID_NEURON):\n for g2, g2_param in enumerate(GRID_B):\n k_slice = 0\n for train, test in slices.split(oData.Training_indexes):\n model = Sequential()\n rbflayer = RBFLayer(g_param,\n initializer=InitCentersRandom(oDataSet.attributes[oData.Training_indexes[train]]),\n betas=g2_param,\n input_shape=(base.shape[1],))\n model.add(rbflayer)\n model.add(Dense(len(lb.classes_), activation='sigmoid'))\n model.compile(loss='categorical_crossentropy',\n optimizer=_OPTIMIZER)\n model.fit(oDataSet.attributes[oData.Training_indexes[train]],\n lb.transform(oDataSet.labels[oData.Training_indexes[train]]),\n batch_size=1,\n epochs=epochs,\n verbose=0)\n\n y_pred = model.predict(oDataSet.attributes[oData.Training_indexes[test]]).argmax(axis=1)\n y_true = oDataSet.labels[oData.Training_indexes[test]]\n grid_result[g1,g2, k_slice] = accuracy_score(y_true, y_pred)\n # print(grid_result)\n k_slice += 1\n print(grid_result)\n best_p = GRID_NEURON[np.unravel_index(np.argmax(np.mean(grid_result, axis=2)), grid_result.shape[:2])[0]]\n best_b = GRID_B[np.unravel_index(np.argmax(np.mean(grid_result, axis=2)), grid_result.shape[:2])[1]]\n\n model = Sequential()\n rbflayer = RBFLayer(best_p,\n initializer=InitCentersRandom(oDataSet.attributes[oData.Training_indexes]),\n betas=best_b,\n input_shape=(base.shape[1],))\n\n model.add(rbflayer)\n model.add(Dense(len(lb.classes_), activation='sigmoid'))\n model.compile(loss='categorical_crossentropy',\n optimizer=_OPTIMIZER)\n model.fit(oDataSet.attributes[oData.Training_indexes],\n lb.transform(oDataSet.labels[oData.Training_indexes]),\n batch_size=1,\n epochs=epochs,\n verbose=1)\n\n y_pred = model.predict(oDataSet.attributes[oData.Testing_indexes]).argmax(axis=1)\n y_true = oDataSet.labels[oData.Testing_indexes]\n\n experiment.log_metric(\"test_accuracy\", accuracy_score(y_true, y_pred))\n experiment.log_metric(\"beta\", best_b)\n experiment.log_metric(\"neurons\", best_p)\n experiment.log_confusion_matrix(matrix=confusion_matrix(y_true, y_pred).tolist(), labels=oDataSet.labelsNames)\n # model.save('model.h5')\n # experiment.log_asset(\"model.h5\")\n model.save_weights('model.weights')\n experiment.log_asset(\"model.weights\")\n\n print(accuracy_score(y_true, y_pred))\n print(confusion_matrix(y_true, y_pred))\n oData.confusion_matrix = confusion_matrix(y_true, y_pred)\n oData.model = model\n oData.params = {\"k_fold\": K_FOLD, \"GRID_RESULT\": grid_result, \"GRID_VALUES_NEURON\": GRID_NEURON,\"GRID_VALUES_BETA\": GRID_B, \"LEARNING RATE\": LEARNING_RATE,\n \"EPOCHS\": epochs}\n experiment.log_other(\"params\", oData.params)\n y_pred = model.predict(oDataSet.attributes[oData.Training_indexes]).argmax(axis=1)\n y_true = oDataSet.labels[oData.Training_indexes]\n experiment.log_metric(\"train_accuracy\", accuracy_score(y_true, y_pred))\n experiment.end()\n oDataSet.append(oData)","sub_path":"T6/Dts_4_1.py","file_name":"Dts_4_1.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"70378310","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom sfcc.pages.login.login_page import LoginPage\nfrom sfcc.pages.checkout_page import CheckoutPage\nfrom sfcc.pages.customize_page import CustomizePage\nimport unittest\n\n\nclass MixOrderTests(unittest.TestCase):\n\n def tests_addtocart(self):\n \"\"\"Test Scenario: \n 1. Login\n 2. Add 3 Custom Text Glasseware products to Cart\n 3. Click on Cart Icon to navigate to Cart Page\n 4. Click on Checkout button\n 6. Place order to complete\n 7. Repeats Steps 2-6\n \"\"\"\n base_url = 'https://Storefront:Yeti2017@staging-na-yeti.demandware.net/s/Yeti_US/en_US/login'\n driver = webdriver.Chrome()\n driver.implicitly_wait(10)\n driver.get(base_url)\n\n cookie = {\n 'domain': 'staging-na-yeti.demandware.net',\n 'httpOnly': False,\n 'name': 'consent-accepted',\n 'path': '/',\n 'secure': False,\n 'value': 'true'}\n driver.add_cookie(cookie)\n driver.refresh()\n\n driver.maximize_window()\n\n lp = LoginPage(driver)\n checkout = CheckoutPage(driver)\n custom = CustomizePage(driver)\n \n lp.login('qa2005121119@yeti.com', 'T3ster#!')\n\n product_urls = [\n '/drinkware/rambler-18-oz-bottle/YRAM18.html',\n '/drinkware/rambler-36-oz-bottle/YRAM36.html',\n '/drinkware/rambler-24-oz-mug/YRAM24.html']\n x = 1\n while x <= 3:\n for product_url in product_urls:\n driver.get('https://staging-na-yeti.demandware.net/s/Yeti_US/en_US' + product_url)\n custom.pdpClickCustomButton()\n custom.customModal()\n custom.selectCustomMono()\n custom.clickApproval()\n custom.clickAddToCart()\n\n cart_url = 'https://staging-na-yeti.demandware.net/s/Yeti_US/en_US/cart'\n driver.get(cart_url)\n checkout.checkoutBtn()\n checkout.shippingBtn()\n checkout.clickVerifyAddress()\n checkout.accountPayment('111')\n order_number = driver.find_element(By.XPATH, '//p[@class=\"order-number\"]//a').text\n print(order_number)\n\n x += 1","sub_path":"sfcc/tests/checkout/mixed_custom_checkout_tests.py","file_name":"mixed_custom_checkout_tests.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"110965857","text":"def ortalama_hesapla(vize,final):\n if (type(vize) == int and type(final) == int):\n if 0 < vize < 100:\n if 0 < final < 100:\n sonuc = (vize * 40 + final * 60) / 100\n if 0 < sonuc <= 40:\n print(\"notunuz dc\")\n elif 40 < sonuc <= 60:\n print(\"Notunuz cb\")\n elif 60 < sonuc <= 80:\n print(\"Notunuz bb\")\n elif 80 < sonuc <= 100:\n print(\"Notunuz aa\")\n else:\n print(\"geçersiz final notu\")\n else:\n print(\"geçersiz vize notu\")\nogr1vize=int(input(\"Birinci öğrencinin vize notunu girin: \"))\nogr1final=int(input(\"Birinci öğrencinin final notunu girin.\"))\nortalama_hesapla(ogr1vize,ogr1final)","sub_path":"if-else.py","file_name":"if-else.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"361635162","text":"import logging\nimport requests\n\nclass MailGun(object):\n base_url = \"https://api.mailgun.net/v2\"\n\n def __init__(self, domain, api_key):\n self.domain = domain\n self.api_key = api_key\n\n def send_email(self, from_addr, to_addrs, subject, text=None, html=None):\n if not isinstance(to_addrs, list):\n to_addrs = [to_addrs]\n\n url = \"%s/%s/messages\" % (self.base_url, self.domain)\n resp = requests.post(url,\n auth=(\"api\", self.api_key),\n data={\n \"from\": from_addr,\n \"to\": to_addrs,\n \"subject\": subject,\n \"text\": text,\n \"html\": html,\n })\n if not resp.ok:\n logging.error(\"Error sending email: %s\", resp.text)\n\n return resp.ok\n","sub_path":"lib/mailgun.py","file_name":"mailgun.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"504536199","text":"import numpy\nimport pandas\n\nfrom acquisition import quote_db\nfrom config import config\n\n\ndef compute_rps_using_window(quote, market, n):\n stock_percent = quote.close.rolling(n).agg(lambda rows: round(100 * (rows[-1] / rows[0] - 1), 3))\n market_percent = market.close.rolling(n).agg(lambda rows: round(100 * (rows[-1] / rows[0] - 1), 3))\n\n key = 'rps{}'.format(n)\n quote.loc[:, key] = (stock_percent - market_percent).ewm(span=5, adjust=False).mean()\n # quote.loc[:, key] = stock_percent - market_percent\n\n return quote\n\n\ndef compute_rps_percent(quote, market, n):\n percent: pandas.Series = quote.percent - market.percent\n percent = percent.cumsum()\n return percent.ewm(span=n, adjust=False).mean()\n\n\ndef compute_rps(quote, market, n, market_index):\n percent: pandas.Series = quote.percent - market.percent\n percent[-1] = percent[-2] if numpy.isnan(percent[-1]) else percent[-1]\n # percent.iat[-1] = percent[-2] if numpy.isnan(percent[-1]) else percent[-1]\n\n if market_index != 'maq':\n market_index = ''\n quote_copy = quote.copy()\n quote_copy.loc[:, 'rps' + market_index] = percent.loc[:]\n\n quote_copy.loc[:, 'erps' + market_index] = percent.ewm(span=n, adjust=False).mean()\n\n return quote_copy\n\n\ndef relative_price_strength(quote, period='day', market_index='maq'):\n period_type = config.period_map[period]['period']\n if market_index != 'maq':\n code = str(quote.code[-1])\n if code[0] == '6':\n market_index = '0000001'\n elif code[0] == '0':\n market_index = '1399001'\n elif code[0] == '3':\n market_index = '1399006'\n market = quote_db.get_price_info_df_db(market_index, len(quote), end_date=quote.index[-1], period_type=period_type)\n # q = quote[~quote.index.isin(market.index)]\n\n # window\n # for n in [3, 10, 20]:\n # quote = compute_rps(quote, market, n)\n\n # percent\n # s1 = compute_rps(quote, market, 3)\n # s2 = compute_rps(quote, market, 10)\n # quote.loc[:, 'rps'] = s1 - s2\n\n quote = compute_rps(quote, market, 30, market_index)\n\n return quote\n","sub_path":"indicator/relative_price_strength.py","file_name":"relative_price_strength.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"516829224","text":"from PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport copy\n\n\ndef noise(img, noise_range = 32): \n img_out = np.zeros_like(img).astype(np.float)\n h, w = img_out.shape\n \n for i in range(h):\n for j in range(w): \n noise = random.randint(-noise_range, noise_range)\n pix = img[i][j] + noise\n if pix > 255: \n pix = 255\n elif pix < 0:\n pix = 0\n img_out[i][j] = pix\n\n img_out = img_out.astype(np.uint8)\n\n return img_out\n\n\ndef noise_spike(img, number = 1000, noise_range = 32):\n img_out = copy.deepcopy(img).astype(np.float)\n h, w = img.shape\n \n for _ in range(number): \n y = random.randint(0, h - 1)\n x = random.randint(0, w - 1)\n noise = random.randint(-noise_range, noise_range)\n pix = img_out[y][x] + noise\n if pix > 255: \n pix = 255\n elif pix < 0:\n pix = 0\n img_out[y][x] = pix\n \n img_out = img_out.astype(np.uint8)\n\n return img_out\n","sub_path":"0625/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"216438529","text":"# -*- coding: utf-8 -*-\r\n__author__ = 'ducta'\r\n\r\nfrom flask.ext.script import Manager\r\nfrom app import create_app\r\n\r\napp = create_app()\r\nmanager = Manager(app)\r\n\r\n\r\n@manager.command\r\ndef runserver():\r\n \"\"\"Runs the Flask development server.\"\"\"\r\n app.run(host='0.0.0.0', port=8888)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n manager.run(default_command='runserver')\r\n","sub_path":"ynap/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"318752023","text":"from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets\nfrom testCases import *\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sklearn.linear_model\n\nnp.random.seed(1)\n\n# data visual\nX, Y = load_planar_dataset()\n# print(\"X: \", X.shape)\n# print(\"Y: \", Y.shape)\n# plt.scatter(X[0, :], X[1, :], c=np.squeeze(Y), s=40, cmap=plt.cm.Spectral)\n# plt.show()\n# plt.ion()\n# plt.pause(0.01)\n# input(\"Press Enter to Continue\")\n# plt.close()\n\n# LR predict init\nclf = sklearn.linear_model.LogisticRegressionCV()\nclf.fit(X.T, Y.T)\n# LR predict visual\n# plot_decision_boundary(lambda x: clf.predict(x), X, np.squeeze(Y))\n# plt.title(\"Logistic Regression\")\n# plt.show()\n# plt.ion()\n# plt.pause(0.01)\n# input(\"Press Enter to Continue\")\n# plt.close()\n# LR predict accuracy\nLR_predictions = clf.predict(X.T)\nprint(\"逻辑回归的准确性: %d \" % float(\n (np.dot(Y, LR_predictions) + np.dot(1 - Y, 1 - LR_predictions)) / float(Y.size) * 100) + \"% \" + \"(正确标记的数据点所占的百分比)\")\n\n\ndef layer_size(X, Y):\n n_x = X.shape[0] # input layer\n n_h = 4 # hidden layer\n n_y = Y.shape[0] # output layer\n return n_x, n_h, n_y\n\n\ndef initialize_parameters(n_x, n_h, n_y):\n np.random.seed(2)\n W1 = np.random.randn(n_h, n_x) * 0.01\n b1 = np.zeros(shape=(n_h, 1))\n W2 = np.random.randn(n_y, n_h) * 0.01\n b2 = np.zeros(shape=(n_y, 1))\n\n parameters = {\n \"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2\n }\n\n return parameters\n\n\ndef foward_propagation(X, parameters):\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n\n assert (W1.shape[1] == X.shape[0])\n assert (W1.shape[0] == b1.shape[0])\n Z1 = np.dot(W1, X) + b1\n A1 = np.tanh(Z1)\n assert (A1.shape == (b1.shape[0], X.shape[1]))\n\n assert (W2.shape[1] == A1.shape[0])\n assert (W2.shape[0] == b2.shape[0])\n Z2 = np.dot(W2, A1) + b2\n A2 = sigmoid(Z2)\n assert (A2.shape == (b2.shape[0], X.shape[1]))\n\n caches = {\n \"Z1\": Z1,\n \"A1\": A1,\n \"Z2\": Z2,\n \"A2\": A2\n }\n return caches\n\n\ndef compute_cost(Y_hat, Y):\n m = Y.shape[1]\n Cost = np.sum(np.dot(Y, np.diag(np.log(Y_hat).flat)) + np.dot(1 - Y, np.diag(np.log(1 - Y_hat).flat))) / (-m)\n assert (isinstance(Cost, float))\n return Cost\n\n\ndef back_propagation(parameters, caches, X, Y):\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n\n Z1 = caches[\"Z1\"]\n A1 = caches[\"A1\"]\n Z2 = caches[\"Z2\"]\n A2 = caches[\"A2\"]\n\n n_x = W1.shape[1]\n n_h = W1.shape[0]\n n_y = W2.shape[0]\n m = A2.shape[1]\n\n dZ2 = A2 - Y\n dW2 = np.dot(dZ2, A1.T)/m\n db2 = np.sum(dZ2, axis=1, keepdims = True)/m\n dZ1 = np.multiply(np.dot(W2.T, dZ2), 1-np.power(A1, 2))\n dW1 = np.dot(dZ1, X.T)/m\n db1 = np.sum(dZ1, axis=1, keepdims=True)/m\n assert (dW2.shape == W2.shape)\n assert (db2.shape == b2.shape)\n assert (dW1.shape == W1.shape)\n assert (db1.shape == b1.shape)\n\n grads = {\n \"dW2\": dW2,\n \"db2\": db2,\n \"dW1\": dW1,\n \"db1\": db1\n }\n return grads\n\n\ndef update_parameters(parameters, grads, learning_rate = 1.2):\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n\n dW1 = grads[\"dW1\"]\n db1 = grads[\"db1\"]\n dW2 = grads[\"dW2\"]\n db2 = grads[\"db2\"]\n\n W1 = W1 - learning_rate * dW1\n b1 = b1 - learning_rate * db1\n W2 = W2 - learning_rate * dW2\n b2 = b2 - learning_rate * db2\n\n parameters = {\n \"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2\n }\n return parameters\n\n\ndef predict(parameters, X):\n c = foward_propagation(X, parameters)\n return np.round(c[\"A2\"])\n\n\n# one hidden layer neural network\nnum_iteration = 10000\nn_x, n_h, n_y = layer_size(X, Y)\nparameters = initialize_parameters(n_x, n_h, n_y)\nfor i in range(1, num_iteration):\n caches = foward_propagation(X, parameters)\n cost = compute_cost(caches[\"A2\"], Y)\n grads = back_propagation(parameters, caches, X, Y)\n parameters = update_parameters(parameters, grads, learning_rate=0.6)\n print(\"Iteration: \", str(i), \", cost: \", cost)\n\n\n# output result\nprediction = predict(parameters, X)\nplt.title(\"Decision Boundary for hidden layer size \" + str(4))\nplot_decision_boundary(lambda x: predict(parameters, x.T), X, np.squeeze(Y))\nplt.show()\nprint(\"One-Hidden Layer的准确性: %d \" % float(\n (np.dot(Y, prediction.T) + np.dot(1 - Y, 1 - prediction.T)) / float(Y.size) * 100) + \"% \" + \"(正确标记的数据点所占的百分比)\")\n","sub_path":"PA2/One-Hidden-Layer-Network.py","file_name":"One-Hidden-Layer-Network.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"381141948","text":"import json\nimport keras\nimport keras.preprocessing.text as kpt\nfrom keras.preprocessing.text import Tokenizer\nfrom pathlib import Path\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib import pyplot\n\n# extract data from a csv\n# notice the cool options to skip lines at the beginning\n# and to only take data from certain columns\npath_browscap = Path(os.getcwd()).parent / \"UA\" / \"browscap.csv\"\ndf = pd.read_csv(str(path_browscap), delimiter=\",\", dtype=\"str\")\nmask = ((df['PropertyName'].str.len() > 30) &\n ((df['Device_Type'].str.contains('Mobile Phone')) |\n (df['Device_Type'].str.contains('Desktop')) |\n (df['Device_Type'].str.contains('Tablet')) |\n (df['Device_Type'].str.contains('TV Device'))))\ndf = df.loc[mask]\ndf = df[df.Device_Type != '0']\ndf = df[df.Device_Type != '']\ndf = df[df.Device_Type.notna()]\ndocs = df['PropertyName']\n\n# create our training data from the tweets\nX = docs.tolist()\n#print(len(X))\n# replace general desktop and window desktop as Desktop, and general mobile phone as Mobile Phone\nX = [x.replace('Windows Desktop', 'Desktop') for x in X]\nX = [x.replace('general Desktop', 'Desktop') for x in X]\nX = [x.replace('general Mobile Phone', 'Mobile Phone') for x in X]\n\n# index all the device labels\nY = df['Device_Type'].tolist()\n\nY = [x.replace('Windows Desktop', 'Desktop') for x in Y]\nY = [x.replace('general Desktop', 'Desktop') for x in Y]\nY = [x.replace('general Mobile Phone', 'Mobile Phone') for x in Y]\n#print(set(Y))\n\n# only work with the most popular words found in our dataset\nmax_words = 3500 #4090\n# create a new Tokenizer\ntokenizer = Tokenizer(num_words=max_words)\n# feed our tweets to the Tokenizer\ntokenizer.fit_on_texts(X)\n# Tokenizers come with a convenient list of words and IDs\ndictionary = tokenizer.word_index\nwith open('dictionary.json', 'w') as dictionary_file:\n json.dump(dictionary, dictionary_file)\n\n\ndef convert_text_to_index_array(my_text):\n # one really important thing that `text_to_word_sequence` does\n # is make all texts the same length -- in this case, the length\n # of the longest text in the set.\n return [dictionary[word] for word in kpt.text_to_word_sequence(my_text)]\n\n\nallWordIndices = []\n# for each tweet, change each token to its ID in the Tokenizer's word_index\nfor text in X:\n wordIndices = convert_text_to_index_array(text)\n allWordIndices.append(wordIndices)\n\n# now we have a list of all tweets converted to index arrays.\n# cast as an array for future usage.\nallWordIndices = np.asarray(allWordIndices)\n\n# create one-hot matrices out of the indexed tweets\nX = tokenizer.sequences_to_matrix(allWordIndices, mode='binary')\n# treat the labels as categories\nlabel_encoder = LabelEncoder()\ninteger_encoded = label_encoder.fit(Y)\nprint(label_encoder.classes_)\nY = label_encoder.transform(Y)\nY = keras.utils.to_categorical(Y, 4)\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\n\nX_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.10, random_state=1234)\n\nmodel = Sequential()\nmodel.add(Dense(128, input_shape=(max_words,)))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(32))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(4))\nmodel.add(Activation('softmax'))\nmodel.summary()\n\ncallbacks_list = [\n keras.callbacks.ReduceLROnPlateau(monitor='val_loss', patience=2, factor=0.1),\n keras.callbacks.ModelCheckpoint(filepath='model.h5', monitor='val_loss', save_best_only=True),\n # keras.callbacks.TensorBoard(log_dir='tf_logs', histogram_freq=1)\n ]\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nhistory = model.fit(X_train, Y_train,\n batch_size=512,\n epochs=15,\n verbose=1,\n validation_data=(X_val, Y_val),\n callbacks=callbacks_list)\n\nmodel_json = model.to_json()\nwith open('model.json', 'w') as json_file:\n json_file.write(model_json)\n\npyplot.plot(history.history['loss'])\npyplot.plot(history.history['val_loss'])\npyplot.title('model train vs validation loss')\npyplot.ylabel('loss')\npyplot.xlabel('epoch')\npyplot.legend(['train', 'validation'], loc='upper right')\npyplot.show()\n","sub_path":"neuralProfiler/makeModel.py","file_name":"makeModel.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"12415966","text":"from flask import Flask, render_template, request, redirect, url_for\r\nfrom flask_mysqldb import MySQL\r\nfrom datetime import datetime\r\napp = Flask(__name__)\r\n\r\napp.config['MYSQL_HOST'] = 'localhost'\r\napp.config['MYSQL_USER'] = 'root'\r\napp.config['MYSQL_PASSWORD'] = 'new-password'\r\napp.config['MYSQL_DB'] = 'organ_donation_network_db'\r\napp.config['MYSQL_PORT'] = 3307\r\ndb = MySQL(app)\r\n\r\ndoctors = []\r\norgans = []\r\norganisations = []\r\nloc = []\r\norganisation_id = \"\"\r\norg_login = False\r\n\r\n@app.route('/')\r\ndef index(msg=\"\"):\r\n global organisations, loc\r\n\r\n load_loc()\r\n\r\n cur = db.connection.cursor()\r\n\r\n cur.execute(\"select organisation_id, organisation_name, city \\\r\n from organisation\")\r\n organisations = cur.fetchall()\r\n\r\n cur.close()\r\n\r\n return render_template('index.html', \r\n locations=loc, organisations=organisations, msg=msg)\r\n\r\n\r\n#########################ORGANISATION UTILITY FUNCTIONS#########################\r\n\r\n@app.route('/login/', methods=['GET', 'POST'])\r\ndef login(user , msg = \"\"):\r\n form = request.form\r\n global doctors, organs, organisation_id, org_login\r\n \r\n if(user == \"org\"):\r\n org_login = True\r\n cur = db.connection.cursor()\r\n hit = cur.execute(\"select * from organisation \\\r\n where organisation_id = %s and pass = %s\", \r\n (form['organisation_id'], form['Pass']))\r\n\r\n if(hit == 0):\r\n cur.close()\r\n return index(msg = \"Wrong Credentials\")\r\n\r\n row = list(cur.fetchone())\r\n\r\n organisation_id = form['organisation_id']\r\n\r\n cur.execute(\"select count(donor_id) \\\r\n from donated natural join donor \\\r\n where organisation_id = %s\", (organisation_id))\r\n donors = cur.fetchone()\r\n \r\n cur.execute(\"select doctor_id, doctor_name, organ_name \\\r\n from doctor natural join organ \\\r\n where organisation_id = %s\", (organisation_id))\r\n doctors = cur.fetchall()\r\n \r\n cur.execute(\"select * from organ natural join doctor \\\r\n where organisation_id = %s group by organ_id\", \r\n (organisation_id))\r\n organs = cur.fetchall()\r\n\r\n \r\n cur.execute(\"select contact_number \\\r\n from organisation_contact where \\\r\n organisation_id = %s\",(organisation_id))\r\n contact = cur.fetchall()\r\n\r\n cur.close()\r\n\r\n row.append((int)(donors[0]))\r\n row.append(len(doctors))\r\n row.append(contact)\r\n\r\n return render_template('home.html', organisation_data=row, msg = \"\")\r\n\r\n else:\r\n org_login = False\r\n cur = db.connection.cursor()\r\n hit = cur.execute(\"select * from patient \\\r\n where patient_id = %s and pass = %s \\\r\n and organisation_id = %s\", (form['patient_id'], \r\n form['Pass'], form['organisation_id']))\r\n \r\n if(hit == 0):\r\n cur.close()\r\n return index(msg = \"Wrong Credentials\")\r\n\r\n organisation_id = form['organisation_id']\r\n\r\n return patient_details(form['patient_id'])\r\n\r\n@app.route('/add_new_organisation', methods=['GET', 'POST'])\r\ndef add_new_organisation():\r\n global organisation_id\r\n form = request.form\r\n cur = db.connection.cursor()\r\n\r\n cur.execute(\"insert into organisation \\\r\n (pass, organisation_name, head_name, office_no, street_no, city, state) \\\r\n values (%s, %s, %s, %s, %s, %s, %s)\", \r\n [form['Pass'], form['organisation_name'], form['head_name'], \r\n form['office_no'], form['street_no'], \r\n form['location'][:form['location'].find(',')], \r\n form['location'][form['location'].find(',') + 1:]])\r\n db.connection.commit()\r\n \r\n cur.execute(\"select organisation_id \\\r\n from organisation order by \\\r\n organisation_id desc limit 1\")\r\n organisation_id = cur.fetchone()[0]\r\n \r\n contacts = form['contact'].split()\r\n\r\n for contact in contacts:\r\n cur.execute(\"insert into organisation_contact \\\r\n (organisation_id, contact_number) \\\r\n values (%s, %s)\", (organisation_id, contact))\r\n db.connection.commit()\r\n\r\n cur.close()\r\n\r\n return index(msg=\"Your ID is {}. Login using your password\".format(organisation_id))\r\n\r\n@app.route('/review_transplants', methods=['GET', 'POST'])\r\ndef review_transplants():\r\n global organisation_id\r\n\r\n cur = db.connection.cursor()\r\n\r\n cur.execute(\"select donor_id, donor_name, patient_id, \\\r\n patient_name, organ_name, transplantation_date \\\r\n from \\\r\n (select * from donated \\\r\n where patient_id is not null) transplants\\\r\n natural join donor \\\r\n natural join organ \\\r\n join patient using (patient_id) \\\r\n where patient.organisation_id = %s\", [organisation_id])\r\n transplants = cur.fetchall()\r\n \r\n cur.close()\r\n\r\n msg = \"\"\r\n if(len(transplants) == 0):\r\n msg = \"No transplants approved till date\"\r\n\r\n return render_template(\"review_transplantations.html\", \r\n transplants=transplants, msg=msg)\r\n\r\n#########################PATIENT UTILITY FUNCTIONS#########################\r\n\r\n@app.route('/view_patient', methods=['GET', 'POST'])\r\ndef view_patient(msg=\"\"):\r\n global doctors, loc, organisation_id\r\n return render_template ('view_patients.html', \r\n doctors=doctors, locations=loc, \r\n msg=msg, organisation_id=organisation_id)\r\n\r\n@app.route('/search_patient/', methods=['GET', 'POST'])\r\ndef search_patient(type):\r\n global organisation_id, doctors, loc\r\n \r\n form = request.form\r\n\r\n cur = db.connection.cursor()\r\n if(type == \"id\"):\r\n cur.execute(\"select distinct(patient_id), patient_name \\\r\n from attended_by natural join patient \\\r\n where organisation_id = %s and patient_id = %s\", \r\n (organisation_id, form['patient_id'])) \r\n\r\n elif(type == \"name\"):\r\n cur.execute(\"select distinct(patient_id), patient_name \\\r\n from attended_by natural join patient \\\r\n where organisation_id = %s and patient_name = %s\", \r\n (organisation_id, form['patient_name'])) \r\n\r\n elif(type == \"city\"):\r\n cur.execute(\"select distinct(patient_id), patient_name \\\r\n from attended_by natural join patient \\\r\n where organisation_id = %s and city = %s\", \r\n (organisation_id, form['city'])) \r\n \r\n elif(type == \"state\"):\r\n cur.execute(\"select distinct(patient_id), patient_name \\\r\n from attended_by natural join patient \\\r\n where organisation_id = %s and state = %s\", \r\n (organisation_id, form['state']))\r\n\r\n elif(type == \"all\"):\r\n cur.execute(\"select distinct(patient_id), patient_name \\\r\n from attended_by natural join patient \\\r\n where organisation_id = %s\", [organisation_id])\r\n \r\n patients = cur.fetchall()\r\n cur.close()\r\n\r\n msg = \"\"\r\n if(len(patients) == 0):\r\n msg = \"No matching records\"\r\n\r\n return render_template ('view_patients.html', \r\n patients=patients, doctors=doctors, msg = msg, \r\n locations=loc, organisation_id=organisation_id)\r\n\r\n@app.route('/add_new_patient/', methods=['GET', 'POST'])\r\ndef add_new_patient(signup = \"false\"):\r\n global organisation_id\r\n \r\n form = request.form \r\n\r\n cur = db.connection.cursor()\r\n \r\n cur.execute(\"insert into patient (patient_name, date_of_birth, \\\r\n insurance_no, house_no, street_no, city, state, pass, organisation_id) \\\r\n values (%s, %s, %s, %s, %s, %s, %s, %s, %s)\", \r\n [form['patient_name'], str_to_date(form['date_of_birth']), \r\n form['insurance_no'], form['house_no'], form['street_no'], \r\n form['location'][:form['location'].find(',')], \r\n form['location'][form['location'].find(',') + 1:],\r\n form['Pass'], form['organisation_id']])\r\n\r\n organisation_id = form['organisation_id']\r\n\r\n cur.execute(\"select patient_id from patient order by patient_id desc limit 1\")\r\n patient_id = cur.fetchone()[0]\r\n \r\n db.connection.commit()\r\n\r\n contacts = form['contact'].split()\r\n\r\n for contact in contacts:\r\n cur.execute(\"insert into patient_contact \\\r\n (patient_id, contact_number) \\\r\n values (%s, %s)\", (patient_id, contact))\r\n db.connection.commit()\r\n\r\n if(signup == \"false\"):\r\n cur.execute(\"insert into attended_by (patient_id, doctor_id, date_of_demand) \\\r\n values (%s, %s, %s)\", (patient_id, form['doctor_id'], \r\n datetime.strptime(form['date_of_demand'], \"%Y-%m-%d\").strftime('%Y-%m-%d')))\r\n db.connection.commit()\r\n\r\n else:\r\n return index(msg=\"Your ID is {}. Login using your password and registered organisation\".format(patient_id))\r\n cur.close()\r\n \r\n return patient_details(patient_id)\r\n\r\n@app.route('/patient_details/', methods=['GET', 'POST'])\r\ndef patient_details(patient_id, donorlist = [], msg = \"\", organ_id = 0):\r\n \r\n global organisation_id\r\n cur = db.connection.cursor()\r\n \r\n cur.execute(\"select * from patient where patient_id = %s\", [patient_id])\r\n details = cur.fetchone()\r\n\r\n cur.execute(\"select doctor_id, date_of_demand, doctor_name, organ_name, organ_id \\\r\n from attended_by natural join doctor natural join organ \\\r\n where patient_id = %s and organisation_id = %s\", \r\n (patient_id, organisation_id))\r\n doctorlist = cur.fetchall()\r\n\r\n cur.execute(\"select doctor_id, doctor_name, organ_name\\\r\n from doctor natural join organ \\\r\n where organisation_id = %s and doctor_id not in \\\r\n (select doctor_id from attended_by where patient_id = %s)\", \r\n (organisation_id, patient_id))\r\n doctors = cur.fetchall()\r\n\r\n cur.execute(\"select donor_id, donor_name, organ_name, \\\r\n transplantation_date from patient \\\r\n natural join donated \\\r\n join donor using (donor_id) \\\r\n natural join organ \\\r\n where patient_id = %s and \\\r\n donor.organisation_id = %s\",\r\n (patient_id, organisation_id))\r\n transplants = cur.fetchall()\r\n\r\n cur.execute(\"select contact_number \\\r\n from patient_contact where \\\r\n patient_id = %s\", [patient_id])\r\n contact = cur.fetchall()\r\n\r\n cur.close()\r\n\r\n details = list(details)\r\n details.append(contact)\r\n\r\n return render_template('patient_details.html', transplants=transplants,\r\n details=details, doctors=doctors, msg=msg, org_login=org_login,\r\n doctorlist=doctorlist, donorlist=donorlist, organ_id=organ_id)\r\n\r\n@app.route('/add_new_doctor/', methods=['GET', 'POST'])\r\ndef add_new_doctor(patient_id): \r\n form = request.form\r\n\r\n cur = db.connection.cursor()\r\n \r\n cur.execute(\"insert into attended_by (patient_id, doctor_id, date_of_demand) \\\r\n values (%s, %s, %s)\", (patient_id , form['doctor_id'], \r\n datetime.strptime(form['date_of_demand'], \"%Y-%m-%d\").strftime('%Y-%m-%d')))\r\n\r\n db.connection.commit()\r\n cur.close()\r\n\r\n return patient_details(patient_id)\r\n\r\n@app.route('/delete_patient/', methods=['GET', 'POST'])\r\ndef delete_patient(patient_id):\r\n\r\n global organisation_id\r\n cur = db.connection.cursor()\r\n\r\n cur.execute(\"delete from attended_by where patient_id = %s and \\\r\n doctor_id in (select doctor_id from doctor where organisation_id = %s)\", \r\n (patient_id, organisation_id))\r\n \r\n db.connection.commit()\r\n cur.close()\r\n\r\n cur = db.connection.cursor()\r\n cur.execute(\"delete from patient where patient_id = %s \\\r\n and not exists \\\r\n (select * from attended_by \\\r\n where patient_id = %s)\",\r\n (patient_id, patient_id))\r\n \r\n db.connection.commit()\r\n cur.close()\r\n\r\n if(org_login):\r\n return view_patient(\"Patient deleted\")\r\n else:\r\n return index(msg=\"You removed yourself from the Organisation/Hospital\")\r\n\r\n@app.route('/search_for_donor/', methods=['GET', 'POST'])\r\ndef search_for_donor(patient_id):\r\n form = request.form\r\n donorlist = []\r\n cur = db.connection.cursor()\r\n\r\n if(form['type'] == \"Search by Age\"):\r\n cur.execute(\"select date_of_birth from patient where patient_id = %s\",\r\n [patient_id])\r\n patient_dob = cur.fetchone()[0]\r\n\r\n cur.execute(\"select donor_id, donor_name, date_of_birth, \\\r\n city, state, organ_name, organ_id \\\r\n from donor natural join donated natural join organ \\\r\n where patient_id is null and \\\r\n organ_id = %s and \\\r\n (abs(datediff(date_of_birth, %s)) / 365) <= 5\", \r\n (form['organ_id'], patient_dob))\r\n \r\n elif(form['type'] == \"Search by City\"):\r\n cur.execute(\"select city from patient where patient_id = %s\",\r\n [patient_id])\r\n patient_city = cur.fetchone()[0]\r\n\r\n cur.execute(\"select donor_id, donor_name, date_of_birth, \\\r\n city, state, organ_name, organ_id \\\r\n from donor natural join donated natural join organ \\\r\n where patient_id is null and \\\r\n organ_id = %s and city = %s\", \r\n (form['organ_id'], patient_city))\r\n\r\n elif(form['type'] == \"Search by State\"):\r\n cur.execute(\"select state from patient where patient_id = %s\",\r\n [patient_id])\r\n patient_state = cur.fetchone()[0]\r\n\r\n cur.execute(\"select donor_id, donor_name, date_of_birth, \\\r\n city, state, organ_name, organ_id \\\r\n from donor natural join donated natural join organ \\\r\n where patient_id is null and \\\r\n organ_id = %s and state = %s\", \r\n (form['organ_id'], patient_state))\r\n\r\n elif(form['type'] == \"Search without Constraints\"):\r\n\r\n cur.execute(\"select donor_id, donor_name, date_of_birth, \\\r\n city, state, organ_name, organ_id \\\r\n from donor natural join donated natural join organ \\\r\n where patient_id is null and organ_id = %s\", \r\n (form['organ_id']))\r\n\r\n donorlist = cur.fetchall()\r\n cur.close()\r\n \r\n msg = \"\"\r\n\r\n if(len(donorlist) == 0):\r\n msg = \"No matching donors\"\r\n\r\n return patient_details(patient_id, donorlist, msg, form['organ_id'])\r\n\r\n@app.route('/approve_donation/', methods=['GET', 'POST'])\r\ndef approve_donation(patient_id):\r\n\r\n global organisation_id\r\n form = request.form\r\n\r\n cur = db.connection.cursor()\r\n\r\n cur.execute(\"update donated \\\r\n set patient_id=%s, \\\r\n transplantation_date=%s \\\r\n where donor_id=%s and organ_id=%s\",\r\n (patient_id, str_to_date(form['transplantation_date']), \r\n form['donor_id'], form['organ_id']))\r\n \r\n cur.execute(\"delete from attended_by where patient_id = %s and \\\r\n doctor_id in \\\r\n (select doctor_id from doctor \\\r\n where organisation_id = %s and \\\r\n organ_id = %s)\", \r\n (patient_id, organisation_id, form['organ_id']))\r\n \r\n db.connection.commit()\r\n cur.close()\r\n\r\n return patient_details(patient_id = patient_id, msg = \"Transplantation Approved\")\r\n\r\n#########################DONOR UTILITY FUNCTIONS#########################\r\n\r\n@app.route('/view_donor', methods=['GET', 'POST'])\r\ndef view_donor():\r\n global organisation_id, organs, loc\r\n return render_template ('view_donors.html', \r\n organs=organs, locations=loc, \r\n organisation_id=organisation_id)\r\n\r\n@app.route('/add_new_donor', methods=['GET', 'POST'])\r\ndef add_new_donor():\r\n global organisation_id\r\n form = request.form \r\n cur = db.connection.cursor()\r\n\r\n organisation_id = form['organisation_id']\r\n \r\n cur.execute(\"insert into donor (donor_name, date_of_birth, house_no,\\\r\n street_no, city, state, organisation_id) \\\r\n values (%s, %s, %s, %s, %s, %s, %s)\", \r\n [form['donor_name'], str_to_date(form['date_of_birth']), \r\n form['house_no'], form['street_no'], \r\n form['location'][:form['location'].find(',')],\r\n form['location'][form['location'].find(',') + 1:], organisation_id])\r\n db.connection.commit()\r\n \r\n cur.execute(\"select donor_id from donor order by donor_id desc limit 1\")\r\n donor_id = cur.fetchone()[0]\r\n\r\n contacts = form['contact'].split()\r\n\r\n for contact in contacts:\r\n cur.execute(\"insert into donor_contact \\\r\n (donor_id, contact_number) \\\r\n values (%s, %s)\", (donor_id, contact))\r\n db.connection.commit()\r\n \r\n cur.execute(\"insert into donated (donor_id, organ_id, date_of_donation, date_of_expiry) \\\r\n values (%s, %s, %s, %s)\", \r\n [donor_id, form['organ_id'], \r\n str_to_date(form['date_of_donation']), \r\n str_to_date(form['date_of_expiry'])])\r\n \r\n db.connection.commit()\r\n cur.close()\r\n \r\n return donor_details(donor_id)\r\n\r\n@app.route('/search_donor/', methods=['GET', 'POST'])\r\ndef search_donor(type):\r\n\r\n global organisation_id, doctors, loc, organs\r\n form = request.form\r\n cur = db.connection.cursor()\r\n\r\n if(type == \"id\"):\r\n cur.execute(\"select distinct(donor_id), donor_name \\\r\n from donor \\\r\n where organisation_id = %s and donor_id = %s\", \r\n (organisation_id, form['donor_id']))\r\n\r\n elif(type == \"name\"):\r\n cur.execute(\"select distinct(donor_id), donor_name \\\r\n from donor \\\r\n where organisation_id = %s and \\\r\n donor_name REGEXP \\\"[:alpha]*%s[:alpha]*\\\"\", \r\n (organisation_id, form['donor_name']))\r\n\r\n elif(type == \"city\"):\r\n cur.execute(\"select distinct(donor_id), donor_name \\\r\n from donor \\\r\n where organisation_id = %s and city = %s\", \r\n (organisation_id, form['city']))\r\n\r\n elif(type == \"state\"):\r\n cur.execute(\"select distinct(donor_id), donor_name \\\r\n from donor \\\r\n where organisation_id = %s and state = %s\", \r\n (organisation_id, form['state']))\r\n\r\n elif(type == \"all\"):\r\n cur.execute(\"select distinct(donor_id), donor_name \\\r\n from donor \\\r\n where organisation_id = %s\", [organisation_id])\r\n\r\n donors = cur.fetchall()\r\n cur.close()\r\n \r\n msg = \"\"\r\n\r\n if(len(donors) == 0):\r\n msg = \"No matching records\"\r\n\r\n return render_template ('view_donors.html', \r\n organs=organs, donors=donors, doctors=doctors, \r\n locations=loc, msg = msg, organisation_id=organisation_id)\r\n\r\n@app.route('/donor_details/', methods=['GET', 'POST'])\r\ndef donor_details(donor_id):\r\n global organs\r\n\r\n cur = db.connection.cursor()\r\n \r\n cur.execute(\"select * from donor where donor_id = %s\", [donor_id])\r\n details = cur.fetchone()\r\n\r\n cur.execute(\"select organ_name, date_of_donation \\\r\n from donor natural join donated \\\r\n natural join organ where donor_id = %s\", [donor_id])\r\n organlist = cur.fetchall()\r\n \r\n cur.execute(\"select contact_number \\\r\n from donor_contact where \\\r\n donor_id = %s\", [donor_id])\r\n contact = cur.fetchall()\r\n\r\n cur.close()\r\n\r\n details = list(details)\r\n details.append(contact)\r\n\r\n return render_template('donor_details.html', \r\n details=details, organs=organs, \r\n organlist=organlist)\r\n\r\n@app.route('/add_new_organ/', methods=['GET', 'POST'])\r\ndef add_new_organ(donor_id): \r\n form = request.form\r\n\r\n cur = db.connection.cursor()\r\n \r\n cur.execute(\"insert into donated \\\r\n (donor_id, organ_id, date_of_donation, \\\r\n date_of_expiry) values (%s, %s, %s, %s)\", \r\n (donor_id, form['organ_id'], \r\n str_to_date(form['date_of_donation']), \r\n str_to_date(form['date_of_expiry'])))\r\n \r\n db.connection.commit()\r\n cur.close()\r\n\r\n return donor_details(donor_id)\r\n\r\n#########################DOCTOR UTILITY FUNCTIONS#########################\r\n\r\n@app.route('/doctor_login', methods=['GET', 'POST'])\r\ndef doctor_login():\r\n form = request.form\r\n\r\n cur = db.connection.cursor()\r\n \r\n hit = cur.execute('select doctor_id, pass \\\r\n from doctor where \\\r\n doctor_id = %s and pass = %s', \r\n (form['doctor_id'], form['Pass']))\r\n cur.close()\r\n \r\n if(hit == 0):\r\n return index(msg=\"Wrong credentials\")\r\n\r\n cur = db.connection.cursor()\r\n\r\n cur.execute('select patient_id, patient_name, \\\r\n date_of_demand, date_of_birth, city, state\\\r\n from attended_by \\\r\n natural join patient \\\r\n where doctor_id = %s',\r\n (form['doctor_id']))\r\n patients = cur.fetchall()\r\n\r\n cur.execute('select doctor_name, highest_degree, \\\r\n date_of_birth, date_of_joining, organisation_name, city \\\r\n from doctor natural join organisation \\\r\n where doctor_id = %s', \r\n (form['doctor_id']))\r\n doctor = cur.fetchone()\r\n\r\n cur.execute('select contact_number \\\r\n from doctor_contact \\\r\n where doctor_id = %s', (form['doctor_id']))\r\n contact = cur.fetchall()\r\n\r\n cur.close()\r\n\r\n doctor = list(doctor)\r\n doctor.append(contact)\r\n \r\n msg = \"\"\r\n if(len(patients) == 0):\r\n msg = \"Currently there are no patients under you\"\r\n\r\n return render_template('doctor_patients.html', doctor=doctor, patients=patients, msg=msg)\r\n\r\n@app.route('/view_doctor', methods=['GET', 'POST'])\r\ndef view_doctor():\r\n\r\n global doctors, organs, organisation_id\r\n\r\n cur = db.connection.cursor()\r\n \r\n cur.execute(\"select doctor_id, doctor_name, organ_name \\\r\n from doctor natural join organ \\\r\n where organisation_id = %s\", (organisation_id))\r\n doctors = cur.fetchall()\r\n\r\n cur.execute(\"select * from organ natural join doctor \\\r\n where organisation_id = %s \\\r\n group by organ_id\", (organisation_id))\r\n organs = cur.fetchall()\r\n\r\n cur.execute(\"select organ_id, organ_name from organ\")\r\n all_organs = cur.fetchall()\r\n\r\n cur.close()\r\n\r\n doctors = list(doctors)\r\n\r\n return render_template ('view_doctors.html', \r\n doctor_data = doctors, organs = all_organs)\r\n\r\n@app.route('/add_doctor', methods=['GET', 'POST'])\r\ndef add_doctor():\r\n global organisation_id\r\n \r\n form = request.form \r\n cur = db.connection.cursor()\r\n \r\n cur.execute(\"insert into doctor (doctor_name, date_of_birth, date_of_joining, \\\r\n highest_degree, organ_id, organisation_id, pass) \\\r\n values (%s, %s, %s, %s, %s, %s, %s)\", \r\n (form['doctor_name'], str_to_date(form['date_of_birth']), \r\n str_to_date(form['date_of_joining']), form['highest_degree'], \r\n form['organ_id'], organisation_id, form['pass']))\r\n \r\n db.connection.commit()\r\n \r\n cur.execute(\"select doctor_id from doctor \\\r\n order by doctor_id desc limit 1\")\r\n doctor_id = cur.fetchone()[0]\r\n \r\n contacts = form['contact'].split()\r\n\r\n for contact in contacts:\r\n cur.execute(\"insert into doctor_contact \\\r\n (doctor_id, contact_number) \\\r\n values (%s, %s)\", (doctor_id, contact))\r\n db.connection.commit()\r\n\r\n cur.close()\r\n\r\n return view_doctor()\r\n\r\n#########################GENERAL UTILITY FUNCTIONS#########################\r\n\r\ndef load_loc():\r\n global loc\r\n\r\n cur = db.connection.cursor()\r\n\r\n cur.execute('select * from locations')\r\n \r\n for location in cur.fetchall():\r\n loc.append(location[0] + ', ' + location[1])\r\n\r\n cur.close()\r\n\r\ndef str_to_date(date):\r\n return datetime.strptime(date, \"%Y-%m-%d\").strftime('%Y-%m-%d')\r\n \r\nif __name__ == '__main__':\r\n app.run(debug = True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"624794318","text":"import numpy as np\nfrom atom import Atom\nfrom verlet import Verlet\nfrom model import LennartJonesModel\n\nclass Molecule(list):\n\n def get_symbols(self):\n \"\"\"Returns the chemichal symbol of the molecule\"\"\"\n s = []\n for atom in self:\n s.append(atom.sym)\n return s\n\n def get_positions(self):\n \"\"\"REturns positions of all the atoms in the molecule\"\"\"\n positions = np.zeros((len(self),3))\n i = 0\n for atom in self:\n positions[i,:] = atom.pos\n i+=1\n return positions\n\n def writetofile(self):\n with open('output.xyz', 'w') as file:\n file.write('{}\\n'.format(len(self)))\n file.write(\"This line has a comment\\n\")\n for atom in self:\n file.write(\"{:s} {:.2f} {:.2f} {:.2f}\\n\".format(atom.sym,atom.pos[0],atom.pos[1],atom.pos[2]))\n\n def set_positions(self):\n model = LennartJonesModel('H',1,2)\n algo = Verlet(model, self)\n v = algo.run(10)\n for atom in self:\n atom.pos = atom.pos + v\n\nif __name__ == '__main__':\n H1 = Atom('H', np.array([1, 2, 4]))\n H2 = Atom('H', np.array([1, 4, 4]))\n H3 = Atom('H', np.array([4, 5, 7]))\n O = Atom('O',[1,3,4])\n\n mol = Molecule([H1,H2,H3])\n symbols = mol.get_symbols()\n positions = mol.get_positions()\n mol.writetofile()\n mol.set_positions()\n\n\n","sub_path":"molecular-dynamics/molecule.py","file_name":"molecule.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"346219280","text":"# coding: utf-8\n# from __future__ import absolute_import\n\nimport sqlite3\nimport os\n\nimport observable\n\nclass Model(object):\n\n def __init__(self, args):\n self.args = args\n self.data = observable.Observable(0) # MVC\n \n self.db = 0\n self.cursor = 0\n \n self.db_connect()\n\n def __del__(self):\n self.db_disconnect()\n print('db access closed')\n\n def db_connect(self):\n if os.path.isfile(self.args['--bdd']):\n self.db = sqlite3.connect(self.args['--bdd'])\n self.cursor = self.db.cursor()\n self.db.commit()\n else:\n print('BDD not found at {}/{}'.format(os.getcwd(), self.args['--bdd']))\n \n def db_disconnect(self):\n if self.db:\n self.db.close()\n \n def pushToDb(self, entry):\n # entry = (1.2, 1, 1, 1, 'Test')\n self.cursor.execute(u'INSERT INTO table_main(temperature, \\\n glaire_exist, \\\n glaire_state, \\\n calins, \\\n commentaire) VALUES (?, ?, ?, ?, ?)', entry)\n self.db.commit()\n \n def pullFromDb(self, tablename):\n self.cursor.execute(\"\"\"SELECT * FROM %s \"\"\" % tablename)\n data = self.cursor.fetchall()\n self.data.set(data)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"268953265","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('repuesto', '0001_initial'),\n ('vehiculo', '0001_initial'),\n ('sucursal', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='sucursal',\n name='repuestos',\n field=models.ManyToManyField(to='repuesto.Repuesto'),\n ),\n migrations.AddField(\n model_name='sucursal',\n name='vehiculos',\n field=models.ManyToManyField(to='vehiculo.Vehiculo'),\n ),\n ]\n","sub_path":"concesionario/concesionario/apps/sucursal/migrations/0002_auto_20150930_1436.py","file_name":"0002_auto_20150930_1436.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"578680246","text":"from datetime import datetime\n\nfrom gino import Gino\n\ndb = Gino()\n\n\nclass User(db.Model):\n __tablename__ = 'users'\n\n id = db.Column(db.BigInteger(), primary_key=True)\n nickname = db.Column(db.Unicode(), default='noname')\n profile = db.Column(db.JSONB())\n name = db.StringProperty(default='noname')\n age = db.IntegerProperty(default=18)\n birthday = db.DateTimeProperty()\n\n def __repr__(self):\n return f'Nickname: {self.name}, Age: {self.age}, ' \\\n f'Birthday: {self.birthday}'\n\n\nasync def main():\n await db.create_pool('postgresql://localhost/gino')\n u = User()\n u.age += 10\n print('Pure in-memory object:', u)\n\n u = await User.create(name='fantix', birthday=datetime.utcnow())\n u.age += 1\n print('New user, default age taking effect:', u)\n\n u = await User.get(u.id)\n print('Reload from DB:', u)\n\n u.update(birthday=datetime.now())\n print('In memory update birthday:', u)\n\n await u.update(age=User.age - 2, name='daisy').apply()\n print('Applied update on age and name:', u)\n\n u = await User.get(u.id)\n print('Reload from DB:', u)\n\n u = await User.get(u.id)\n await u.update(age=User.age - 2, nickname='daisy').apply()\n print('Update both without cache:', u)\n\n print(await u.delete())\n\n\nif __name__ == '__main__':\n import asyncio\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n","sub_path":"examples/json_property.py","file_name":"json_property.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"617235759","text":"import logging\nfrom typing import Callable, Optional, Mapping, Iterable, Tuple\nfrom adam.curriculum.curriculum_utils import Phase1InstanceGroup\nfrom adam.curriculum.imprecise_descriptions_curriculum import (\n make_imprecise_size_curriculum,\n make_imprecise_temporal_descriptions,\n make_subtle_verb_distinctions_curriculum,\n)\nimport random\nfrom adam.learner.objects import PursuitObjectLearnerNew\nfrom adam.curriculum.phase2_curriculum import (\n build_functionally_defined_objects_curriculum,\n build_gaila_m13_curriculum,\n build_m13_shuffled_curriculum,\n)\nfrom adam.curriculum.preposition_curriculum import make_prepositions_curriculum\nfrom adam.curriculum.verbs_with_dynamic_prepositions_curriculum import (\n make_verb_with_dynamic_prepositions_curriculum,\n)\nfrom adam.experiment.experiment_utils import (\n build_each_object_by_itself_curriculum_train,\n build_each_object_by_itself_curriculum_test,\n build_debug_curriculum_train,\n build_debug_curriculum_test,\n build_generics_curriculum,\n build_m6_prepositions_curriculum,\n build_pursuit_curriculum,\n build_functionally_defined_objects_train_curriculum,\n)\nfrom adam.language.dependency import LinearizedDependencyTree\nfrom adam.language.language_generator import LanguageGenerator\nfrom adam.language.language_utils import phase2_language_generator\nfrom adam.language_specific.english import ENGLISH_DETERMINERS\nfrom adam.learner.attributes import SubsetAttributeLearner, SubsetAttributeLearnerNew\nfrom adam.learner.functional_learner import FunctionalLearner\nfrom adam.learner.integrated_learner import IntegratedTemplateLearner\nfrom adam.learner.language_mode import LanguageMode\nfrom adam.learner.relations import SubsetRelationLearnerNew\nfrom adam.learner.verbs import SubsetVerbLearner, SubsetVerbLearnerNew\nfrom adam.ontology.phase2_ontology import GAILA_PHASE_2_ONTOLOGY\nfrom adam.perception.high_level_semantics_situation_to_developmental_primitive_perception import (\n GAILA_PHASE_1_PERCEPTION_GENERATOR,\n)\nfrom adam.situation.high_level_semantics_situation import HighLevelSemanticsSituation\nfrom vistautils.parameters import Parameters\nfrom vistautils.parameters_only_entrypoint import parameters_only_entry_point\n\nfrom adam.curriculum.m6_curriculum import make_m6_curriculum\nfrom adam.curriculum.phase1_curriculum import (\n build_gaila_phase1_object_curriculum,\n build_gaila_phase1_attribute_curriculum,\n build_gaila_phase1_relation_curriculum,\n build_gaila_phase1_verb_curriculum,\n build_gaila_phase_1_curriculum,\n)\nfrom adam.experiment import Experiment, execute_experiment\nfrom adam.experiment.observer import LearningProgressHtmlLogger, CandidateAccuracyObserver\nfrom adam.learner import TopLevelLanguageLearner\nfrom adam.learner.object_recognizer import ObjectRecognizer\nfrom adam.learner.prepositions import SubsetPrepositionLearner\nfrom adam.learner.pursuit import HypothesisLogger\nfrom adam.learner.objects import (\n ObjectPursuitLearner,\n SubsetObjectLearner,\n SubsetObjectLearnerNew,\n ObjectRecognizerAsTemplateLearner,\n)\nfrom adam.ontology.phase1_ontology import (\n GAILA_PHASE_1_ONTOLOGY,\n ME_HACK,\n YOU_HACK,\n PHASE_1_CURRICULUM_OBJECTS,\n)\nfrom adam.random_utils import RandomChooser\n\nLANGUAGE_GEN = LanguageGenerator[ # pylint: disable=invalid-name\n HighLevelSemanticsSituation, LinearizedDependencyTree\n]\n\nCURRICULUM_BUILDER = Callable[ # pylint: disable=invalid-name\n [Optional[int], Optional[int], LANGUAGE_GEN], Iterable[Phase1InstanceGroup]\n]\n\n\ndef log_experiment_entry_point(params: Parameters) -> None:\n experiment_name = params.string(\"experiment\")\n debug_log_dir = params.optional_creatable_directory(\"debug_log_directory\")\n\n graph_logger: Optional[HypothesisLogger]\n if debug_log_dir:\n logging.info(\"Debug graphs will be written to %s\", debug_log_dir)\n graph_logger = HypothesisLogger(debug_log_dir, enable_graph_rendering=True)\n else:\n graph_logger = None\n\n logger = LearningProgressHtmlLogger.create_logger(params)\n\n language_mode = params.enum(\n \"language_mode\", LanguageMode, default=LanguageMode.ENGLISH\n )\n\n (training_instance_groups, test_instance_groups) = curriculum_from_params(\n params, language_mode\n )\n\n execute_experiment(\n Experiment(\n name=experiment_name,\n training_stages=training_instance_groups,\n learner_factory=learner_factory_from_params(\n params, graph_logger, language_mode\n ),\n pre_example_training_observers=[\n logger.pre_observer(),\n CandidateAccuracyObserver(\"pre-acc-observer\"),\n ],\n post_example_training_observers=[logger.post_observer()],\n test_instance_groups=test_instance_groups,\n test_observers=[logger.test_observer()],\n sequence_chooser=RandomChooser.for_seed(0),\n ),\n log_path=params.optional_creatable_directory(\"hypothesis_log_dir\"),\n log_hypotheses_every_n_examples=params.integer(\n \"log_hypothesis_every_n_steps\", default=250\n ),\n log_learner_state=params.boolean(\"log_learner_state\", default=True),\n learner_logging_path=params.optional_creatable_directory(\"experiment_group_dir\"),\n starting_point=params.integer(\"starting_point\", default=-1),\n point_to_log=params.integer(\"point_to_log\", default=0),\n load_learner_state=params.optional_existing_file(\"learner_state_path\"),\n )\n\n\ndef learner_factory_from_params(\n params: Parameters,\n graph_logger: Optional[HypothesisLogger],\n language_mode: LanguageMode = LanguageMode.ENGLISH,\n) -> Callable[[], TopLevelLanguageLearner]: # type: ignore\n learner_type = params.string(\n \"learner\",\n [\n \"pursuit\",\n \"object-subset\",\n \"preposition-subset\",\n \"attribute-subset\",\n \"verb-subset\",\n \"integrated-learner\",\n \"integrated-learner-recognizer\",\n \"pursuit-gaze\",\n ],\n )\n\n beam_size = params.positive_integer(\"beam_size\", default=10)\n\n if language_mode == LanguageMode.CHINESE and learner_type not in [\n \"integrated-learner\",\n \"integrated-learner-recognizer\",\n ]:\n raise RuntimeError(\"Only able to test Chinese with integrated learner.\")\n\n rng = random.Random()\n rng.seed(0)\n perception_generator = GAILA_PHASE_1_PERCEPTION_GENERATOR\n\n objects = [YOU_HACK, ME_HACK]\n objects.extend(PHASE_1_CURRICULUM_OBJECTS)\n\n # Eval hack! This is specific to the Phase 1 ontology\n object_recognizer = ObjectRecognizer.for_ontology_types(\n objects,\n determiners=ENGLISH_DETERMINERS,\n ontology=GAILA_PHASE_1_ONTOLOGY,\n language_mode=language_mode,\n perception_generator=perception_generator,\n )\n\n if learner_type == \"pursuit\":\n return lambda: ObjectPursuitLearner.from_parameters(\n params.namespace(\"pursuit\"), graph_logger=graph_logger\n )\n elif learner_type == \"pursuit-gaze\":\n return lambda: IntegratedTemplateLearner(\n object_learner=PursuitObjectLearnerNew(\n learning_factor=0.05,\n graph_match_confirmation_threshold=0.7,\n lexicon_entry_threshold=0.7,\n rng=rng,\n smoothing_parameter=0.002,\n ontology=GAILA_PHASE_2_ONTOLOGY,\n language_mode=language_mode,\n rank_gaze_higher=True,\n ),\n attribute_learner=SubsetAttributeLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n relation_learner=SubsetRelationLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n action_learner=SubsetVerbLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n )\n elif learner_type == \"object-subset\":\n return lambda: SubsetObjectLearner(\n ontology=GAILA_PHASE_1_ONTOLOGY, language_mode=LanguageMode.ENGLISH\n )\n elif learner_type == \"attribute-subset\":\n return lambda: SubsetAttributeLearner(\n ontology=GAILA_PHASE_1_ONTOLOGY,\n object_recognizer=object_recognizer,\n language_mode=LanguageMode.ENGLISH,\n )\n elif learner_type == \"preposition-subset\":\n return lambda: SubsetPrepositionLearner(\n # graph_logger=graph_logger,\n object_recognizer=object_recognizer,\n ontology=GAILA_PHASE_1_ONTOLOGY,\n language_mode=LanguageMode.ENGLISH,\n )\n elif learner_type == \"verb-subset\":\n return lambda: SubsetVerbLearner(\n ontology=GAILA_PHASE_1_ONTOLOGY,\n object_recognizer=object_recognizer,\n language_mode=LanguageMode.ENGLISH,\n )\n elif learner_type == \"integrated-learner\":\n return lambda: IntegratedTemplateLearner(\n object_learner=SubsetObjectLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n attribute_learner=SubsetAttributeLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n relation_learner=SubsetRelationLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n action_learner=SubsetVerbLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n functional_learner=FunctionalLearner(language_mode=language_mode),\n )\n elif learner_type == \"integrated-learner-recognizer\":\n return lambda: IntegratedTemplateLearner(\n object_learner=ObjectRecognizerAsTemplateLearner(\n object_recognizer=object_recognizer, language_mode=language_mode\n ),\n attribute_learner=SubsetAttributeLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n relation_learner=SubsetRelationLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n action_learner=SubsetVerbLearnerNew(\n ontology=GAILA_PHASE_2_ONTOLOGY,\n beam_size=beam_size,\n language_mode=language_mode,\n ),\n functional_learner=FunctionalLearner(language_mode=language_mode),\n )\n else:\n raise RuntimeError(\"can't happen\")\n\n\ndef curriculum_from_params(\n params: Parameters, language_mode: LanguageMode = LanguageMode.ENGLISH\n):\n str_to_train_test_curriculum: Mapping[\n str, Tuple[CURRICULUM_BUILDER, Optional[CURRICULUM_BUILDER]]\n ] = {\n \"m6-deniz\": (make_m6_curriculum, None),\n \"each-object-by-itself\": (\n build_each_object_by_itself_curriculum_train,\n build_each_object_by_itself_curriculum_test,\n ),\n \"pursuit\": (\n build_pursuit_curriculum,\n build_each_object_by_itself_curriculum_test,\n ),\n \"m6-preposition\": (build_m6_prepositions_curriculum, None),\n \"m9-objects\": (build_gaila_phase1_object_curriculum, None),\n \"m9-attributes\": (build_gaila_phase1_attribute_curriculum, None),\n \"m9-relations\": (build_gaila_phase1_relation_curriculum, None),\n \"m9-events\": (build_gaila_phase1_verb_curriculum, None),\n \"m9-debug\": (build_debug_curriculum_train, build_debug_curriculum_test),\n \"m9-complete\": (build_gaila_phase_1_curriculum, None),\n \"m13-imprecise-size\": (make_imprecise_size_curriculum, None),\n \"m13-imprecise-temporal\": (make_imprecise_temporal_descriptions, None),\n \"m13-subtle-verb-distinction\": (make_subtle_verb_distinctions_curriculum, None),\n \"m13-object-restrictions\": (build_functionally_defined_objects_curriculum, None),\n \"m13-functionally-defined-objects\": (\n build_functionally_defined_objects_train_curriculum,\n build_functionally_defined_objects_curriculum,\n ),\n \"m13-generics\": (build_generics_curriculum, None),\n \"m13-complete\": (build_gaila_m13_curriculum, None),\n \"m13-verbs-with-dynamic-prepositions\": (\n make_verb_with_dynamic_prepositions_curriculum,\n None,\n ),\n \"m13-shuffled\": (build_m13_shuffled_curriculum, build_gaila_m13_curriculum),\n \"m13-relations\": (make_prepositions_curriculum, None),\n }\n\n curriculum_name = params.string(\"curriculum\", str_to_train_test_curriculum.keys())\n language_generator = phase2_language_generator(language_mode)\n\n if params.has_namespace(\"pursuit-curriculum-params\"):\n pursuit_curriculum_params = params.namespace(\"pursuit-curriculum-params\")\n else:\n pursuit_curriculum_params = Parameters.empty()\n\n (training_instance_groups, test_instance_groups) = str_to_train_test_curriculum[\n curriculum_name\n ]\n\n num_samples = params.optional_positive_integer(\"num_samples\")\n num_noise_objects = params.optional_positive_integer(\"num_noise_objects\")\n\n return (\n training_instance_groups(num_samples, num_noise_objects, language_generator)\n if curriculum_name != \"pursuit\"\n else training_instance_groups(\n num_samples,\n num_noise_objects,\n language_generator,\n pursuit_curriculum_params=pursuit_curriculum_params,\n ),\n test_instance_groups(num_samples, num_noise_objects, language_generator)\n if test_instance_groups\n else [],\n )\n\n\nif __name__ == \"__main__\":\n parameters_only_entry_point(log_experiment_entry_point)\n","sub_path":"adam/experiment/log_experiment.py","file_name":"log_experiment.py","file_ext":"py","file_size_in_byte":14237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"512226672","text":"\"\"\"ontrendclothing URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom product.views import productviews\n\nurlpatterns = [\n\n path('', productviews.login),\n path('login', productviews.login),\n path('custLogin', productviews.custLogin),\n path('logout', productviews.logout),\n path('custLogout', productviews.custLogout),\n path('addproduct', productviews.addproduct),\n path('showproduct', productviews.showproduct),\n path('editproduct/', productviews.editproduct),\n path('updateproduct/', productviews.updateproduct),\n path('deleteproduct/', productviews.deleteproduct),\n path('addtype', productviews.addtype),\n path('addvendor', productviews.addvendor),\n path('adduser', productviews.adduser),\n path('showuser', productviews.showuser),\n path('edituser/', productviews.edituser),\n path('updateuser/', productviews.updateuser),\n path('deleteuser/', productviews.deleteuser),\n path('addcust', productviews.addcust),\n path('showcust', productviews.showcust),\n path('editcust/', productviews.editcust),\n path('updatecust/', productviews.updatecust),\n path('deletecust/', productviews.deletecust),\n path('home', productviews.home),\n path('custhome', productviews.custhome),\n path('onlinestore', productviews.onlinestore),\n path('allproducts', productviews.allproducts),\n path('custallproducts', productviews.custallproducts),\n path('productdetails/', productviews.productdetails),\n path('custproductdetails/', productviews.custproductdetails),\n path('addreview', productviews.addreview),\n path('search', productviews.search),\n path('searchproduct', productviews.searchproduct),\n path('custsearchproduct', productviews.custsearchproduct),\n path('getsearchedproduct', productviews.getsearchedproduct),\n path('getcustsearchedproduct', productviews.getcustsearchedproduct),\n path('customize', productviews.customize),\n \n]\n","sub_path":"ontrendclothing/ontrendclothing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"148283584","text":"from bs4 import BeautifulSoup\nimport re\nimport numpy as np\nimport os.path\n\ndef drop_sketches(df):\n \"\"\"Drop artists from dataframe that are vastly overrepresented and/or whose\n work largely includes many sketches/photographs\"\"\"\n artists=['George Romney','William Blake','Edward Lear','Thomas Rowlandson',\n 'Felice Beato','Joseph Mallord William Turner','John Robert Cozens',\n 'James Ward','George Stubbs','unknown artist (Britain)']\n for artist in artists:\n z= df[df['artist_name'] == artist]\n if artist=='Felice Beato' or artist=='unknown artist (Britain)':\n #Delete all of these works\n badbool = z['label_names_cleaned'].str.contains('lab')\n else:\n badbool = z['label_names_cleaned'].str.contains('sketch')\n badlist = z[badbool].index.tolist()\n df = df.drop(df.index[badlist])\n df = df.reset_index(drop=True)\n return df\n\ndef drop_duplicatepics(df):\n \"\"\"Example usage: df = cln.drop_duplicatepics(db)\n Drops all rows that have duplicate thumbnails (except 1st occurance)\"\"\"\n z = df.duplicated(subset='url_to_thumb')\n bad_rows = []\n for i, boolz in enumerate(z):\n if boolz:\n bad_rows.append(i)\n print(df['url_to_thumb'].iloc[[i]])\n print(bad_rows)\n df = df.drop(df.index[bad_rows])\n df = df.reset_index(drop=True)\n return df\n\ndef drop_label(df):\n \"\"\"Example usage: df = cln.verify_label(db)\n Drops all rows that don't have label info \"\"\"\n bad_rows=[]\n for i, row in df.iterrows():\n if row['label_names'] is None:\n print('dropping')\n bad_rows.append(i)\n print(bad_rows)\n df = df.drop(df.index[bad_rows])\n df = df.reset_index(drop=True)\n return df\n\ndef verify_year(years):\n \"\"\"Example usage: db['date'] = cln.verify_year(db['date'])\n Verifies that all 'date' entries are nan and counts them up \"\"\"\n cnt = 0\n for i, yr in years.iteritems():\n if yr is None:\n years.set_value(i, np.nan)\n print('none value')\n cnt+=1\n continue\n if isinstance(yr, str):\n years.set_value(i, np.nan)\n print('str value')\n cnt+=1\n continue\n if yr>2050 or yr<-1000:\n years.set_value(i, np.nan)\n print('bad year value')\n cnt+=1\n if np.isnan(yr):\n cnt+=1\n continue\n print(\"# of years without values: {:d}\".format(cnt))\n print('# of total year entries: {:d}'.format(years.size))\n return years\n\ndef convert_year(years, debug=False):\n \"\"\"Example usage: db['date'] = cln.convert_year(db['date']) \"\"\"\n for i, yr in years.iteritems():\n if debug:\n print(yr)\n print(type(yr))\n if yr is None:\n years.set_value(i, np.nan)\n continue\n if is_int(yr):\n continue\n if isinstance(yr, float):\n if np.isnan(yr):\n continue\n yr = q_html(yr)\n yr = q_all(yr)\n yr = dedashslash(yr)\n if is_int(yr):\n years.set_value(i, int(yr))\n else:\n years.set_value(i, np.nan)\n return years\n\n\ndef q_space(yr):\n if yr[0] == ' ':\n yr = yr[1:]\n if yr[-1] == ' ':\n yr = yr[:-1]\n return yr\n\ndef q_circa_about(yr):\n if yr[:6] == 'circa ' or yr[:6] == 'about ' or yr[:6] == 'Circa ':\n yr = yr[6:]\n return yr\n\ndef q_around(yr):\n if yr[:7] == 'around ' or yr[:7] == 'Around ':\n yr = yr[7:]\n return yr\n\ndef q_cdot(yr):\n if yr[:2] == 'c.':\n yr = yr[2:]\n return yr\n\ndef q_c(yr):\n if yr[0] == 'c' and is_int(yr[1]):\n yr = yr[1:]\n return yr\n\ndef q_cadot(yr):\n if yr[0:4] == 'ca. ' or yr[0:4] == 'Ca. ':\n yr = yr[4:]\n return yr\n\ndef q_parens(yr):\n if yr[0] == '(' and yr[-1] == ')':\n yr = yr[1:-1]\n return yr\n\ndef q_CdotEdot(yr):\n if yr[-4:] == 'C.E.':\n yr = yr[:-4]\n return yr\n\ndef q_last4(yr):\n if yr[-6:-4] == ', ' and is_int(yr[-4:]):\n yr = yr[-4:]\n return yr\n\ndef q_all(yr):\n yr = q_space(yr)\n yr = q_last4(yr)\n yr = q_parens(yr)\n yr = q_circa_about(yr)\n yr = q_cdot(yr)\n yr = q_c(yr)\n yr = q_cadot(yr)\n yr = q_CdotEdot(yr)\n return yr\n\ndef q_html(yr):\n \"\"\"Use beautiful soup on html tags. Many tags have this form\"\"\"\n if yr[:5] == ' int(yrlist[1]):\n # `1519-21` or 319-21\n yrlist[1] = yrlist[0][:-2] + yrlist[1]\n # Take average of range\n yr = (int(yrlist[0]) + int(yrlist[1])) / 2\n yr = int(round(yr))\n return yr\n","sub_path":"scripts/cln.py","file_name":"cln.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"185593944","text":"\"\"\"\nA popular masseuse receives a sequence of back-to-back appointment requests and is debating which ones to accept.\n She needs a break between appointments and therefore she cannot accept any adjacent requests.\n Given a sequence of back-to-back appoint­ ment requests, find the optimal (highest total booked minutes)\n set the masseuse can honor. Return the number of minutes.\n\nNote: This problem is slightly different from the original one in the book.\n\n \n\nExample 1:\n\nInput: [1,2,3,1]\nOutput: 4\nExplanation: Accept request 1 and 3, total minutes = 1 + 3 = 4\nExample 2:\n\nInput: [2,7,9,3,1]\nOutput: 12\nExplanation: Accept request 1, 3 and 5, total minutes = 2 + 9 + 1 = 12\nExample 3:\n\nInput: [2,1,4,5,3,1,1,3]\nOutput: 12\nExplanation: Accept request 1, 3, 5 and 8, total minutes = 2 + 4 + 3 + 3 = 12\n\n\n链接:https://leetcode-cn.com/problems/the-masseuse-lcci\n\n\"\"\"\n\n\nclass Solution:\n def massage(self, nums: list) -> int:\n n = len(nums)\n dp = nums\n if not nums:\n return 0\n if n == 1:\n return nums[0]\n if nums[1] >= nums[0]:\n dp[1] = nums[1]\n else:\n dp[1] = nums[0]\n for i in range(2, len(nums)):\n new = nums[i] + dp[i-2]\n if new > dp[i-1]:\n dp[i] = new\n else:\n dp[i] = dp[i-1]\n return dp[-1]\n\n\nclass Solution2:\n def caculate(self, l):\n dp = [i for i in l]\n for i in range(2, len(l)):\n dp[i] = max(dp[i-2] + l[i], dp[i-1])\n return dp[-1]\n\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.massage([2,1]))\n s2 = Solution2()\n print(s2.caculate([2,1,4,5,3,1,1,3]))\n","sub_path":"code_practice/dp/appointment_easy.py","file_name":"appointment_easy.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"126788293","text":"\"\"\"Tests for Handlers.\"\"\"\n\nimport json\nfrom unittest.mock import MagicMock\nfrom unittest.mock import patch\n\n\nimport application\nfrom oto import response\nfrom pytest_mock import mocker\n\n\nfrom test_product import handlers\nfrom test_product.logic import vendor_logic\n\n\n@patch('test_product.handlers.g')\ndef test_exception_handler(mock_g):\n \"\"\"Verify exception_Handler returns 500 status code and json payload.\"\"\"\n message = (\n 'The server encountered an internal error '\n 'and was unable to complete your request.')\n mock_error = MagicMock()\n server_response = handlers.exception_handler(mock_error)\n mock_g.log.exception.assert_called_with(mock_error)\n\n # assert status code is 500\n assert server_response.status_code == 500\n\n # assert json payload\n response_message = json.loads(server_response.data.decode())\n assert response_message['message'] == message\n assert response_message['code'] == response.error.ERROR_CODE_INTERNAL_ERROR\n\n\ndef test_get_vendor(test_vendor_id, mocker):\n \"\"\"Test get vendor data by vendor id.\"\"\"\n expected_response = {\n 'vendor_id': 26283,\n 'vendor_name': 'paras',\n 'vendor_company': 'BEINGJAINPARAS'}\n mocker.patch.object(\n vendor_logic, 'get_vendor_by_vendor_id',\n return_value=response.Response(message=expected_response))\n\n with application.app.test_request_context():\n handler_response = handlers.get_vendor(test_vendor_id)\n assert handler_response.status_code == 200\n vendor_logic.get_vendor_by_vendor_id.assert_called_with(test_vendor_id)\n\n\ndef test_get_vendor_not_found(test_vendor_id, mocker):\n \"\"\"Test get vendor data with not found error.\"\"\"\n mocker.patch.object(\n vendor_logic, 'get_vendor_by_vendor_id',\n return_value=response.create_not_found_response(\n '{} record id not available.'.format(test_vendor_id)))\n\n with application.app.test_request_context():\n handler_response = handlers.get_vendor(test_vendor_id)\n assert handler_response.status_code == 404\n vendor_logic.get_vendor_by_vendor_id.assert_called_with(test_vendor_id)\n\n\ndef test_create_vendor(mocker):\n \"\"\"Test create vendor data.\"\"\"\n data = {'vendor_id': '1', 'name': 'Paras', 'company': 'Dulhan Pvt Ltd'}\n mocker.patch.object(\n vendor_logic, 'create_new_vendor',\n return_value=response.Response(message='success'))\n\n with application.app.test_request_context(\n data=json.dumps(data),\n content_type='application/json'):\n handler_response = handlers.create_vendor()\n\n assert handler_response.status_code == 200\n vendor_logic.create_new_vendor.assert_called_once_with(data)\n\n\ndef test_update_vendor(test_vendor_id, mocker):\n \"\"\"Test update vendor data with vendor_id.\"\"\"\n data = {'name': 'Paras', 'company': 'Dulhan Pvt Ltd'}\n mocker.patch.object(\n vendor_logic, 'update_the_vendor',\n return_value=response.Response(message='success'))\n\n with application.app.test_request_context(\n data=json.dumps(data),\n content_type='application/json'):\n handler_response = handlers.update_vendor(test_vendor_id)\n\n assert handler_response.status_code == 200\n vendor_logic.update_the_vendor.assert_called_once_with(\n test_vendor_id, data)\n\n\ndef test_delete_vendor(test_vendor_id, mocker):\n \"\"\"Test delete vendor data.\"\"\"\n mocker.patch.object(\n vendor_logic, 'delete_the_vendor',\n return_value=response.Response(message='success'))\n\n with application.app.test_request_context():\n handler_response = handlers.delete_vendor(test_vendor_id)\n\n assert handler_response.status_code == 200\n vendor_logic.delete_the_vendor.assert_called_with(test_vendor_id)\n","sub_path":"tests/test_handlers.py","file_name":"test_handlers.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"328712204","text":"import heapq\n\ncases = int(input())\nfor c in range(cases):\n n = int(input())\n p = list(map(int, input().split()))\n q = []\n for i, x in enumerate(p):\n heapq.heappush(q, [-x, i])\n \n instructions = []\n while q:\n s = heapq.nsmallest(3, q)\n if (len(s) == 2 and s[0][0] == s[1][0]) or (len(s) == 3 and s[0][0] == s[1][0] and s[0][0] != s[2][0]):\n x1 = heapq.heappop(q)\n x2 = heapq.heappop(q)\n instructions.append((x1[1], x2[1]))\n x1[0] += 1\n x2[0] += 1\n if x1[0] != 0:\n heapq.heappush(q, x1)\n if x2[0] != 0:\n heapq.heappush(q, x2)\n else:\n x1 = heapq.heappop(q)\n instructions.append((x1[1],))\n x1[0] += 1\n if x1[0] != 0:\n heapq.heappush(q, x1)\n \n text = ' '.join(''.join(chr(ord('A') + e) for e in i) for i in instructions)\n print('Case #{}: {}'.format(c + 1, text))\n","sub_path":"solutions_5753053697277952_0/Python/zommerfelds/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"632464364","text":"import _thread\nimport time\n\ntask1_finished = False\ntask2_finished = False\n\n\ndef task1():\n global task1_finished\n print(\"task1\")\n for i in range(10):\n time.sleep(0.05)\n print(\"task1\")\n task1_finished = True\n\n\ndef task2(sleep_time, loop_count):\n global task2_finished\n print(\"task2:\", sleep_time, loop_count)\n for i in range(loop_count):\n time.sleep(sleep_time)\n print(\"task2\")\n task2_finished = True\n\n\n_thread.start_new_thread(task1, ())\n_thread.start_new_thread(task2, (0.05, 10))\n\nwhile not task1_finished or not task2_finished:\n time.sleep(0.1)\n\ntime.sleep(0.5) # wait for threads to exit\n","sub_path":"port/linux/test/python/_thread/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"354927569","text":"import random\nimport sys\nfrom collections import Counter\nimport numpy as np\nimport sympy as sp\nfrom sympy.physics.quantum.qubit import matrix_to_qubit\n\n\ndef normalize_state(state):\n return state/np.linalg.norm(state)\n\ndef n_kron(*args):\n result = np.array([[1.+0.j]])\n for op in args:\n result = np.kron(result, op)\n return result\n\ndef n_kron_list(args):\n result = np.array([[1.+0.j]])\n for op in args:\n result = np.kron(result, op)\n return result\n\n# |0>\nzero = np.array([[1.+0.j],\n [0.+0.j]], dtype=np.cfloat)\n# |1>\none = np.array([[0.+0.j],\n [1.+0.j]], dtype=np.cfloat)\n# |-> = 1/√2(|0>-|1>)\nminus = normalize_state(zero-one)\n# |+> = 1/√2(|0>+|1>)\nplus = normalize_state(zero+one)\n\n# Quantum logic gates\n#\n# - https://en.wikipedia.org/wiki/Quantum_logic_gate\n#\n#\npauli_x = np.array(\n [[0.+0.j, 1.+0.j],\n [1.+0.j, 0.+0.j]])\npauli_y = np.array(\n [[0.+0.j, -1j ],\n [1j , 0.+0.j]])\npauli_z = np.array(\n [[1.+0.j, 0.+0.j],\n [0.+0.j, -1.+0.j]])\nhadamard = np.array(\n [[1.+0.j, 1.+0.j],\n [1.+0.j, -1.+0.j]]\n )*1/np.sqrt(2.+0.j)\nID2 = np.eye(2, dtype=np.cfloat)\ntoffoli = np.array(\n [[1, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 1, 0]],\n dtype=np.cfloat)\nswap = np.array(\n [[1, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1]],\n dtype=np.cfloat)\n\ndef measure(amplitudes, repetitions=10):\n measurements = []\n for _ in range(repetitions):\n weights = [abs(amplitude)**2 for amplitude in amplitudes]\n outcome = random.choices(range(len(amplitudes)), weights)[0]\n new_state = np.zeros((len(amplitudes), 1))\n new_state[outcome][0] = 1\n measurements.append(new_state)\n sample = random.choice(measurements)\n qubit = list(matrix_to_qubit(np.array(sample)).free_symbols)[0]\n return qubit.qubit_values\n\ndef apply_pauli_x(psi, loc, n):\n op_list = [ID2]*n\n op_list[loc] = pauli_x\n op_matrix = n_kron_list(op_list)\n return np.dot(op_matrix, psi)\n\ndef apply_pauli_z(psi, loc, n):\n op_list = [ID2]*n\n op_list[loc] = pauli_z\n op_matrix = n_kron_list(op_list)\n return np.dot(op_matrix, psi)\n\ndef apply_hadamard(psi, loc, n):\n op_list = [ID2]*n\n op_list[loc] = hadamard\n op_matrix = n_kron_list(op_list)\n return np.dot(op_matrix, psi)\n\ndef apply_cnot(psi, control_loc, target_loc, n):\n P0 = np.dot(zero, zero.T)\n P1 = np.dot(one , one.T )\n op_list_0 = [ID2]*n\n op_list_0[control_loc] = P0\n op_list_1 = [ID2]*n\n op_list_1[control_loc] = P1\n op_list_1[ target_loc] = pauli_x\n op_matrix = n_kron_list(op_list_0)+n_kron_list(op_list_1)\n return np.dot(op_matrix, psi)\n\ndef apply_swap(psi, a_loc, b_loc, n):\n psi = apply_cnot(psi, a_loc, b_loc, n=n)\n psi = apply_cnot(psi, b_loc, a_loc, n=n)\n psi = apply_cnot(psi, a_loc, b_loc, n=n)\n return psi\n\ndef apply_cz(psi, control_loc, target_loc, n):\n P0 = np.dot(zero, zero.T)\n P1 = np.dot(one , one.T )\n op_list_0 = [ID2]*n\n op_list_0[control_loc] = P0\n op_list_1 = [ID2]*n\n op_list_1[control_loc] = P1\n op_list_1[ target_loc] = pauli_z\n op_matrix = n_kron_list(op_list_0)+n_kron_list(op_list_1)\n return np.dot(op_matrix, psi)\n\ndef apply_cz_rot(psi, control_loc, target_loc, rotation, n):\n P0 = np.dot(zero, zero.T)\n P1 = np.dot(one , one.T )\n op_list_0 = [ID2]*n\n op_list_0[control_loc] = P0\n op_list_1 = [ID2]*n\n op_list_1[control_loc] = P1\n op_list_1[ target_loc] = pauli_z**rotation\n op_matrix = n_kron_list(op_list_0)+n_kron_list(op_list_1)\n return np.dot(op_matrix, psi)\n\ndef apply_cz_and_swap(psi, a_loc, b_loc, rotation, n):\n psi = apply_cz_rot(psi, a_loc, b_loc, rotation, n=n)\n psi = apply_swap(psi, a_loc, b_loc, n=n)\n return psi\n\n\n# Quantum fourier transform\n#\n#\n# ─H───@^0.5───×───H────────────@^0.5─────×───H──────────@^0.5──×─H\n# │ │ │ │ │ │\n# ─────@───────×───@^0.25───×───@─────────×───@^0.25───×──@─────×──\n# │ │ │ │\n# ─────────────────┼────────┼───@^0.125───×───┼─���──────┼───────────\n# │ │ │ │ │ │\n# ─────────────────@────────×───@─────────×───@────────×───────────\n#\n#\n# Лавлагаа:\n# - https://qiskit.org/textbook/ch-algorithms/quantum-fourier-transform.html\n#\n# Сүүлийн төлөв:\n#\n# [0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j\n# 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j 0.25+0.j]\n#\n#\ndef fourier_transform():\n psi = n_kron_list([zero]*4)\n\n print(\"\\nQuantum fourier transform\\n\")\n\n psi = apply_hadamard(psi, 0, n=4)\n\n psi = apply_cz_and_swap(psi, 0, 1, 0.5, n=4)\n psi = apply_cz_and_swap(psi, 1, 2, 0.25, n=4)\n psi = apply_cz_and_swap(psi, 2, 3, 0.125, n=4)\n\n psi = apply_hadamard(psi, 0, n=4)\n\n psi = apply_cz_and_swap(psi, 0, 1, 0.5, n=4)\n psi = apply_cz_and_swap(psi, 1, 2, 0.25, n=4)\n\n psi = apply_hadamard(psi, 0, n=4)\n\n psi = apply_cz_and_swap(psi, 0, 1, 0.5, n=4)\n\n psi = apply_hadamard(psi, 0, n=4)\n\n\n measurements = []\n repetitions = 10000\n for idx in range(0, repetitions):\n psi_values = measure([a[0] for a in psi], repetitions=1)\n psi_str = \"\".join([str(bit) for bit in psi_values])\n measurements.append(psi_str)\n print(psi_str, \"=>\", int(psi_str, 2))\n pass\n\n print(\"\\n\", matrix_to_qubit(psi), \"\\n\")\n\n histogram = Counter(measurements)\n print(\"\\n\", list(histogram.keys()), \"\\n\")\n print(\"\\n\", histogram, \"\\n\")\n\n pass\n\n\nif __name__==\"__main__\":\n fourier_transform()\n","sub_path":"fourier_transform_quantum_np.py","file_name":"fourier_transform_quantum_np.py","file_ext":"py","file_size_in_byte":6628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"254223408","text":"import easygui\n\neasygui.msgbox('Selecione o arquivo de origem', 'Origem')\norigfile = easygui.fileopenbox()\narq = open(origfile, 'r')\n\narqdest = open(origfile + '.changed', 'w')\n\nsubstituiparam = 0\nachouparam = 0\n\nlog = 1 # 1=on 0=off\n\n\ndef findparam(x):\n global achouparam\n global substituiparam\n\n if (x.find(\"get:\") != -1):\n achouparam = 1\n if log: print(x)\n if (achouparam == 1 and x.find('tags:') > 0):\n substituiparam = 1\n if log: print(x)\n\n if (linha.find(\"post:\") != -1):\n achouparam = 2\n if log: print(x)\n if (achouparam == 2 and linha.find('tags:') > 0):\n substituiparam = 2\n if log: print(x)\n\n if (linha.find(\"delete:\") != -1):\n achouparam = 3\n if log: print(x)\n if (achouparam == 3 and linha.find('tags:') > 0):\n substituiparam = 3\n if log: print(x)\n\n if (linha.find(\"put:\") != -1):\n achouparam = 4\n if log: print(x)\n if (achouparam == 4 and linha.find('tags:') > 0):\n substituiparam = 4\n if log: print(x)\n\n\nfor linha in arq:\n\n if (substituiparam == 1):\n if log: print(\"Deletado: \" + linha)\n linha = ' - \"RETRIEVAL Operations\"\\n'\n if log: print(\"Alterado: \" + linha)\n substituiparam = 0\n achouparam = 0\n\n if (substituiparam == 2):\n if log: print(\"Deletado: \" + linha)\n linha = ' - \"CREATION Operations\"\\n'\n if log: print(\"Alterado: \" + linha)\n substituiparam = 0\n achouparam = 0\n\n if (substituiparam == 3):\n if log: print(\"Deletado: \" + linha)\n linha = ' - \"DELETION Operations\"\\n'\n if log: print(\"Alterado: \" + linha)\n substituiparam = 0\n achouparam = 0\n\n if (substituiparam == 4):\n if log: print(\"Deletado: \" + linha)\n linha = ' - \"MODIFICATION Operations\"\\n'\n if log: print(\"Alterado: \" + linha)\n substituiparam = 0\n achouparam = 0\n\n findparam(linha)\n arqdest.write(linha)\n\narq.close()\narqdest.close()\n","sub_path":"01 Clean YAML/1 - sub_param.py","file_name":"1 - sub_param.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"464802161","text":"import os\nimport pytest\nimport tempfile\nimport glob\n\n\nfrom masonry.core import Component\n\n\nCOMPONENT = Component('fixtures/components/AWS/EC2')\n\n\ndef test_component_load_file():\n \"\"\" Check that the component object can load a component yaml and\n store the correct attributes \"\"\"\n assert COMPONENT.component_directory == 'fixtures/components/AWS/EC2'\n assert COMPONENT.component_key == 'EC2'\n assert COMPONENT.system_key == 'AWS'\n\n\ndef test_component_justification_mapping():\n \"\"\" Check that the justifications this component satisfies have been\n correctly stored \"\"\"\n assert COMPONENT.justification_mapping == {\n 'NIST-800-53': {\n 'CM-2': [('AWS', 'EC2')]\n },\n 'PCI-DSS-MAY-2015': {\n 1.1: [('AWS', 'EC2')],\n 2.1: [('AWS', 'EC2')],\n '1.1.1': [('AWS', 'EC2')]\n }\n }\n\n\ndef test_get_justifications():\n \"\"\" Given a standard and control check that the get_justifications method\n returns the justifications for that control. \"\"\"\n justification = COMPONENT.get_justifications('PCI-DSS-MAY-2015', 1.1)\n assert len(justification['references']) == 2\n\n\ndef test_export_references():\n \"\"\" Check if the method correctly determins which references were saved\n locally and saves those to the appropriate location in the export directory\n \"\"\"\n TEMP_OUTPUT_DIR = tempfile.TemporaryDirectory()\n references = COMPONENT.meta.get('verifications')\n # Export files\n COMPONENT.export_references(references, TEMP_OUTPUT_DIR.name)\n # Check if files exists\n assert len(glob.glob(os.path.join(TEMP_OUTPUT_DIR.name, '*', '*', '*'))) == 1\n TEMP_OUTPUT_DIR.cleanup()\n\n\ndef test_export_component():\n \"\"\" Check if the method correctly returns the metadata needed for the\n certification \"\"\"\n TEMP_OUTPUT_DIR = tempfile.TemporaryDirectory()\n # Export files\n data = COMPONENT.export(TEMP_OUTPUT_DIR.name)\n assert data['EC2']['name'] == 'Amazon Elastic Compute Cloud'\n\n\nif __name__ == '__main__':\n pytest.main()\n","sub_path":"tests/test_masonry.py","file_name":"test_masonry.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"641214221","text":"import arcpy, os, sys, random\n\n#Grilla=r\"C:\\Users\\Fernando\\Downloads\\INFORMACION PARA FERNANDO\\INFORMACION PARA FERNANDO\\GRILLAS\\2K\\cuadr_bta.shp\"\n#Muetra=20\n#CarpetaSalida=r\"C:\\temp\"\n#LimiteProyecto=r\"C:\\Users\\Fernando\\Downloads\\INFORMACION PARA FERNANDO\\INFORMACION PARA FERNANDO\\GRILLAS\\temp\\Lim.shp\"\n#ExportarDGN=\"false\"\n\nGrilla=sys.argv[1]\nMuetra=int(sys.argv[2])\nCarpetaSalida=sys.argv[3]\nLimiteProyecto=sys.argv[4]\nboolExportarDGN=sys.argv[5]\n\narcpy.env.overwriteOutput=True\n\ndef FindIdentificador(Feat):\n Identificador=\"\"\n ListaInit= arcpy.ListFields(Feat)\n for field in ListaInit:\n if field.type==\"OID\":\n Identificador=field.name\n return Identificador\n\n\ndef SeleccionMuestra (capa,numeroMuestra, limiteProyecto):\n arcpy.env.workspace = Grilla\n sptref = arcpy.Describe(Grilla)\n stref = sptref.spatialreference\n arcpy.env.outputCoordinateSystem = stref\n #crear Query\n salida=None\n arcpy.env.workspace=CarpetaSalida\n if CarpetaSalida in (\".mdb\") or CarpetaSalida in (\".gdb\"):\n outfc = \"Grilla_aleatoria\"\n else:\n outfc = \"Grilla_aleatoria.shp\"\n\n\n if limiteProyecto!=\"\":\n salidainter=arcpy.MakeFeatureLayer_management(capa,\"salida\")\n salida = arcpy.SelectLayerByLocation_management(salidainter,\"WITHIN_CLEMENTINI\",limiteProyecto)\n else:\n salida=capa\n\n identificador = FindIdentificador(salida)\n fields = [identificador]\n Lista = []\n with arcpy.da.SearchCursor(salida, fields) as cursor:\n for row in cursor:\n Lista.append(row[0])\n random.shuffle(Lista)\n ListaAleatoria = Lista[:numeroMuestra]\n\n campo=arcpy.AddFieldDelimiters(capa,identificador)\n QueryAleatorio= campo+\"in \"+str(tuple(ListaAleatoria))\n arcpy.Select_analysis(salida,outfc ,QueryAleatorio)\n if boolExportarDGN == \"true\":\n CapaAleatoria = CarpetaSalida + os.sep + \"Grilla_aleatoria.dgn\"\n exportarDGN(outfc, CapaAleatoria)\n\ndef exportarDGN(CapaEntrada,capasalida):\n pathArcgis = os.environ[\"AGSDESKTOPJAVA\"]\n arcpy.ExportCAD_conversion(CapaEntrada,\"DGN_V8\",capasalida,\"\",\"\",pathArcgis+os.sep+\"ArcToolbox/Templates/template3d.dgn\")\n\ntry:\n SeleccionMuestra(Grilla,Muetra,LimiteProyecto)\nexcept Exception as e:\n arcpy.AddError(e.message)\n","sub_path":"IGAC2018/Grilla_Completa.py","file_name":"Grilla_Completa.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"173850917","text":"# -*- coding: utf-8 -*-\r\n# vim:fileencoding=utf-8\r\nfrom math import log\r\nfrom collections import OrderedDict\r\nclass file():\r\n\t\r\n\tdef __init__(self, alphabet,path):\r\n\t\t\r\n\t\tself.alphabet = alphabet\r\n\t\tself.path = path\r\n\t\tself.frequences = {}\r\n\t\tself.bigram_frequences = {}\t\r\n\t\tself.bigram_frequences_un = {}\t\r\n\t\tself.entropie = [0,0,0]\r\n\t\tself.result =\"result.txt\"\r\n\t\tself.length = 0\r\n\t\tself.Rest = [0,0,0]\r\n\r\n\r\n\tdef alphabet_check(self):\r\n\t\tif ' ' in self.alphabet:\r\n\t\t\treturn True\r\n\t\treturn False\r\n\r\n\tdef text_correction(self,boolean = True):\r\n\r\n\t\twith open(self.path, \"r\", encoding=\"utf-8\") as f,open(self.result, \"w\", encoding=\"utf-8\") as fout:\r\n\t\t\tlines = f.readlines()\r\n\t\t\tfor line in lines:\r\n\t\t\t\tif boolean:\r\n\t\t\t\t\tfor element in line.lower():\r\n\t\t\t\t\t\tif element not in self.alphabet :\r\n\t\t\t\t\t\t\tline = line.replace(element,' ')\r\n\t\t\t\t\tline = ' '.join(line.split())\r\n\t\t\t\t\tfout.write(line.lower()+' ')\r\n\t\t\t\telse:\r\n\t\t\t\t\tfor element in line.lower():\r\n\t\t\t\t\t\tif element not in self.alphabet:\r\n\t\t\t\t\t\t\tline = line.replace(element,'')\r\n\t\t\t\t\tfout.write(line.lower()+' ')\r\n\r\n\t\t\t\t\r\n\tdef frequency_analisys(self):\r\n\r\n\t\twith open(self.result, \"rt\", encoding=\"utf-8\") as file:\r\n\t\t\tf_read = file.read()\r\n\t\t\tself.length = len(f_read)\r\n\t\t\tfor element in f_read :\r\n\t\t\t\t\r\n\t\t\t\tif element in self.frequences :\r\n\t\t\t\t\tself.frequences[element] += 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.frequences[element] = 1\r\n\r\n\t\t\tfor i in range(1,len(f_read)):\r\n\t\t\t\tbigram = (f_read[i- 1]+ f_read[i])\r\n\r\n\t\t\t\tif bigram in self.bigram_frequences:\r\n\t\t\t\t\tself.bigram_frequences[bigram] += 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.bigram_frequences[bigram] = 1\r\n\t\t\ti = 0\r\n\t\t\twhile i + 1 < len(f_read):\r\n\t\t\t\tbigram = (f_read[i]+ f_read[i+1])\r\n\r\n\t\t\t\tif bigram in self.bigram_frequences_un:\r\n\t\t\t\t\tself.bigram_frequences_un[bigram] += 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.bigram_frequences_un[bigram] = 1\r\n\t\t\t\ti += 2\r\n\r\n\t\tfor i in self.alphabet:\r\n\t\t\tif i not in self.frequences:\r\n\t\t\t\tself.frequences[i] = 0\r\n\t\tfor i in self.alphabet:\r\n\t\t\tfor j in self.alphabet:\r\n\r\n\t\t\t\tif (i + j) not in self.bigram_frequences:\r\n\t\t\t\t\tself.bigram_frequences[i+j] = 0\r\n\r\n\t\tfor i in self.alphabet:\r\n\t\t\tfor j in self.alphabet:\r\n\r\n\t\t\t\tif (i + j) not in self.bigram_frequences_un:\r\n\t\t\t\t\tself.bigram_frequences_un[i+j] = 0\r\n\r\n\r\n\r\n\tdef entropie_calculating(self):\r\n\t\tself.text_correction(self.alphabet_check())\r\n\t\tself.frequency_analisys()\r\n\t\tfor value in self.frequences.values():\r\n\t\t\tif value :\r\n\t\t\t\tpropability = value / self.length\r\n\t\t\t\tself.entropie[0] -= propability * log(propability,2)\r\n\r\n\t\tfor value in self.bigram_frequences.values():\r\n\t\t\tif value:\r\n\t\t\t\tpropability = value / (self.length - 1)\r\n\t\t\t\tself.entropie[1] -= propability * log(propability,2)\r\n\t\tself.entropie[1] = self.entropie[1] / 2\r\n\r\n\t\tfor value in self.bigram_frequences_un.values():\r\n\t\t\tif value:\r\n\t\t\t\tpropability = value / (self.length / 2)\r\n\t\t\t\tself.entropie[2] -= propability * log(propability,2)\r\n\t\tself.entropie[2] = self.entropie[2] / 2\r\n\t\treturn self.entropie\r\n\r\n\t\t\t\r\n\tdef show(self):\r\n\t\tif 0 not in self.entropie:\r\n\t\t\tOd = OrderedDict(sorted(self.bigram_frequences.items()))\r\n\t\t\tself.frequences = sorted(self.frequences.items())\r\n\t\t\tOd_un= OrderedDict(sorted(self.bigram_frequences_un.items()))\r\n\t\t\tprint(Od)\r\n\t\t\tprint(self.frequences)\r\n\t\t\tprint(Od_un)\r\n\r\n\tdef R(self):\r\n\t\tfor i in range(len(self.entropie)):\r\n\t\t\tself.Rest[i] = 1- (self.entropie[i] / log(len(self.alphabet),2))\r\n\t\treturn self.Rest\r\n\r\n\t\t\r\n\r\n\r\n\r\ndef main():\r\n\tf = file(\"абвгдеёжзийклмнопрстуфхцчшщъыьэюя \",\"file.txt\")\r\n\tprint((f.entropie_calculating()))\r\n\t#.show()\r\n\tprint(f.R())\r\n\r\n\tf1 = file(\"абвгдеёжзийклмнопрстуфхцчшщъыьэюя\",\"file.txt\")\r\n\tprint((f1.entropie_calculating()))\r\n\r\n\tprint(f1.R())\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n\r\n\t\t\t\t \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"cp_1/KOROL_MICHAEL_FB-72_cp1/crypto_lab1.py","file_name":"crypto_lab1.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"650525508","text":"from django.db import models\nfrom django.utils import timezone\nfrom taggit.managers import TaggableManager\nfrom django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse\n\nfrom django.utils import timezone\n\nclass Site1Blogs(models.Model):\n\ttitle=models.CharField(max_length=100,verbose_name=\"Заголовок\")\n\tdescription=models.CharField(max_length=300,verbose_name=\"Краткое содержание\")\n\tcontent=models.TextField(verbose_name=\"Полное содержание\")\n\n\tlikes=models.IntegerField(default=0,verbose_name=\"Понравилось\")\n\timage=models.ImageField(upload_to=\"site1/list\",verbose_name=\"Изображение\")\n\tposted=models.DateField(default=timezone.now,verbose_name=\"Опубликовано\")\n\ttags=TaggableManager(blank=True,verbose_name=\"Теги\")\n\tuser=models.ForeignKey(User, default=timezone.now)\n\n\tviews=models.IntegerField(default=0,verbose_name=\"Просмотры\")\n\n\n\tdef request(request):\n\t\treturn {'request': request}\n\tdef save(self,*args,**kwargs):\n\t\ttry:\n\t\t\tthis_record=Site1Blogs.objects.get(pk=self.pk)\n\t\t\tif this_record.image != self.image:\n\t\t\t\tthis_record.image.delete(save=False)\n\t\texcept:\n\t\t\tpass\n\t\tsuper(Site1Blogs,self).save(*args,**kwargs)\n\tdef delete(self,*args,**kwargs):\n\t\tself.image.delete(save=False)\n\t\tsuper(Site1Blogs,self).delete(*args,**kwargs)\n\n\tclass Meta:\n\t\tordering=[\"-posted\"]\n\t\tverbose_name=\"статья блога\"\n\t\tverbose_name_plural=\"статьи блога\"\n\tdef __str__(self):\n\t\treturn \"Пользователь %s %s\" % (self.user, self.title)\n\nclass Site1Guestbook(models.Model):\n\tuser=models.CharField(max_length=20, verbose_name=\"Пользователь\")\n\tposted=models.DateTimeField(auto_now_add=True, db_index=True, verbose_name=\"Опубликовано\")\n\tcontent=models.TextField(verbose_name=\"Содержание\")\n\tclass Meta:\n\t\t\tordering=[\"-posted\"]\n\t\t\tverbose_name=\"Запись гостевой книги\"\n\t\t\tverbose_name_plural=\"Записи гостевой книги\"\n\n\tdef __str__(self):\n\t\treturn self.user\n\nclass Site1Feedback(models.Model):\n name = models.CharField(verbose_name='Имя', max_length=50)\n email = models.EmailField(verbose_name='Email')\n message = models.TextField(verbose_name='Сообщение', max_length=500)\n class Meta:\n\n verbose_name = 'Сообщение'\n verbose_name_plural = 'Сообщения'\n def __str__(self):\n return 'Имя: {}'.format(self.name)\n\nclass Site1Gallery(models.Model):\n\n\torder=models.PositiveSmallIntegerField(default=0,db_index=True,verbose_name=\"Порядковый номер\")\n\timage=models.ImageField(upload_to=\"site1/list\",verbose_name=\"Изображение\")\n\tdef save(self,*args,**kwargs):\n\t\ttry:\n\t\t\tthis_record=Site1Gallery.objects.get(pk=self.pk)\n\t\t\tif this_record.image != self.image:\n\t\t\t\tthis_record.image.delete(save=False)\n\t\texcept:\n\t\t\tpass\n\t\tsuper(Site1Gallery,self).save(*args,**kwargs)\n\tdef delete(self,*args,**kwargs):\n\t\tself.image.delete(save=False)\n\t\tsuper(Site1Gallery,self).delete(*args,**kwargs)\n\n\tclass Meta:\n\t\tordering=[\"order\"]\n\t\tverbose_name=\"Изображение\"\n\t\tverbose_name_plural=\"Изображения\"\n\nclass Site1New(models.Model):\n\ttitle=models.CharField(max_length=100,verbose_name=\"Заголовок\")\n\tdescription=models.CharField(max_length=300,verbose_name=\"Краткое содержание\")\n\tcontent=models.TextField(verbose_name=\"Полное содержание\")\n\tposted=models.DateTimeField(default=timezone.now, db_index=True, verbose_name=\"Опубликована\")\n\timage=models.ImageField(upload_to=\"site1/list\",verbose_name=\"Изображение\")\n\tlikes=models.IntegerField(default=0,verbose_name=\"Понравилось\")\n\tis_commentable=models.BooleanField(default=True,verbose_name=\"Разрешены комментарии\")\n\tuser=models.ForeignKey(User, default=timezone.now, verbose_name=\"Автор новости\")\n\tviews=models.IntegerField(default=0,verbose_name=\"Просмотры\")\n\n\tdef request(request):\n\t\treturn {'request': request}\n\tdef save(self,*args,**kwargs):\n\t\ttry:\n\t\t\tthis_record=Site1New.objects.get(pk=self.pk)\n\t\t\tif this_record.image != self.image:\n\t\t\t\tthis_record.image.delete(save=False)\n\t\texcept:\n\t\t\tpass\n\t\tsuper(Site1New,self).save(*args,**kwargs)\n\tdef delete(self,*args,**kwargs):\n\t\tself.image.delete(save=False)\n\t\tsuper(Site1New,self).delete(*args,**kwargs)\n\tclass Meta:\n\t\tordering=[\"-posted\"]\n\t\tverbose_name=\"новость\"\n\t\tverbose_name_plural=\"новости\"\n\tdef __str__(self):\n\t\treturn self.title\n\nclass Site1Service(models.Model):\n\tname=models.CharField(max_length=100,verbose_name=\"Заголовок\")\n\tdescription=models.CharField(max_length=300,verbose_name=\"Краткое содержание\")\n\tcontent=models.TextField(verbose_name=\"Полное содержание\")\n\n\timage=models.ImageField(upload_to=\"site1/list\",verbose_name=\"Изображение\")\n\tlikes=models.IntegerField(default=0,verbose_name=\"Понравилось\")\n\tviews=models.IntegerField(default=0,verbose_name=\"Просмотры\")\n\n\tdef save(self,*args,**kwargs):\n\t\ttry:\n\t\t\tthis_record=Site1Service.objects.get(pk=self.pk)\n\t\t\tif this_record.image != self.image:\n\t\t\t\tthis_record.image.delete(save=False)\n\t\texcept:\n\t\t\tpass\n\t\tsuper(Site1Service,self).save(*args,**kwargs)\n\tdef delete(self,*args,**kwargs):\n\t\tself.image.delete(save=False)\n\t\tsuper(Site1Service,self).delete(*args,**kwargs)\n\tclass Meta:\n\n\t\tverbose_name=\"услуга\"\n\t\tverbose_name_plural=\"услуги\"\n\tdef __str__(self):\n\t\treturn self.name\n\nclass Site1Calling(models.Model):\n name = models.CharField(verbose_name='Имя', max_length=50)\n phone = models.CharField(verbose_name='телефон', max_length=20)\n time = models.CharField(verbose_name='время', max_length=100)\n class Meta:\n\n verbose_name = 'звонок'\n verbose_name_plural = 'звонки'\n def __str__(self):\n return 'Имя: {}'.format(self.name)\n","sub_path":"site1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"315105758","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\n\nfrom lxml import etree\nimport time\nfrom msg import Msg\nimport chardet\nfrom django.core.files.base import ContentFile\nfrom django.core.files.storage import get_storage_class\nimport logging\n\nlogger = logging.getLogger('django')\n\nclass MsgProcesser(object):\n '''\n 消息处理模块\n '''\n \n def parseUserOrder(self,xmlStr):\n '''\n 解析用户消息\n '''\n xml=etree.fromstring(xmlStr)\n\n msg=Msg()\n \n msg.msgType=xml.find(\"MsgType\").text\n msg.fromUserName=xml.find(\"FromUserName\").text\n msg.toUserName=xml.find(\"ToUserName\").text\n msg.createTime=xml.find(\"CreateTime\").text\n\n if(msg.msgType=='text'):\n msg.content=xml.find(\"Content\").text\n\n if(msg.msgType=='voice'):\n msg.content=xml.find(\"Recognition\").text\n\n logger.info(msg.content)\n \n\n return msg\n\n def genMsg(self,msg):\n '''\n 生成用户消息\n '''\n self.__dict=dict()\n self.__dict['ToUserName']=msg.toUserName\n self.__dict['FromUserName']=msg.fromUserName\n self.__dict['CreateTime']=int(time.time())\n self.__dict['Content']=msg.content\n \n XmlForm=\"\"\"\n \n \n \n {CreateTime}\n \n \n \n \"\"\"\n\n return XmlForm.format(**self.__dict)\n\n \n \n\n","sub_path":"Django/WeChat/WeChat/msgProcesser.py","file_name":"msgProcesser.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"243134628","text":"import collections\nimport datetime\nimport io\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Union\n\nimport chess.pgn\nimport chess.svg\nfrom omegaconf import DictConfig, OmegaConf\nfrom rich import print\nfrom rich.console import Console\nfrom rich.progress import track\nfrom rich.table import Table\n\nfrom chessli import berserk_client\nfrom chessli.enums import Color\nfrom chessli.mistakes import Mistake, get_nag_name\nfrom chessli.openings import Opening\n\nconsole = Console()\n\n\ngames_client = berserk_client.games\n\n\ndef pgn_to_game(pgn: str) -> Optional[chess.pgn.Game]:\n return chess.pgn.read_game(io.StringIO(pgn))\n\n\n@dataclass\nclass GameManager:\n config: DictConfig\n\n def __post_init__(self):\n self._games = self.read_games()\n\n @property\n def path(self):\n path = self.config.paths.games.value\n path.mkdir(parents=True, exist_ok=True)\n return path\n\n @property\n def files(self) -> List[Path]:\n return list(self.path.glob(\"**/*.pgn\"))\n\n @property\n def games(self) -> List[Any]:\n return self._games\n\n def read_games(self):\n games = [\n Game(\n pgn=chess.pgn.read_game(io.StringIO(pgn.read_text())),\n json=OmegaConf.load(pgn.with_suffix(\".json\")),\n config=self.config,\n )\n for pgn in self.files\n ]\n return games\n\n @property\n def last_game(self) -> \"Game\":\n return self._games[-1]\n\n def fetch_games(self):\n new_games = []\n perftype_counter = collections.Counter()\n opening_counter = collections.Counter()\n console.log(f\"Fetching {self.config.user}'s games.\")\n games_by_user = [\n game\n for game in games_client.export_by_player(\n max=20,\n username=self.config.user,\n since=int(self.config.since),\n perf_type=self.config.perf_type,\n )\n ]\n\n if games_by_user:\n for game_json, game_pgn in track(\n [\n (\n game,\n games_client.export(\n game[\"id\"],\n literate=\"true\",\n as_pgn=True,\n opening=\"true\",\n tags=\"true\",\n moves=\"true\",\n evals=\"true\",\n ),\n )\n for game in games_by_user\n ],\n description=f\"Fetching additional game information...\",\n ):\n game = pgn_to_game(game_pgn)\n chessli_game = Game(pgn=game, json=game_json, config=self.config)\n chessli_game.store()\n new_games.append(chessli_game)\n\n perftype_counter.update([game_json[\"perf\"]])\n opening_counter.update([game.headers[\"Opening\"]])\n\n table = Table(\"Game Type\", \"Number of Plays\", title=f\"New Games :fire:\")\n for game, count in perftype_counter.items():\n table.add_row(game, str(count))\n # console.log(f\":fire: Fetched {count} '{game}' game(s)\")\n console.print(table)\n\n table = Table(\n \"Opening Name\", \"Number of Plays\", title=f\"New Openings :fire:\"\n )\n for opening, count in opening_counter.items():\n # console.log(f\":fire: {count} '{opening}'\")\n table.add_row(opening, str(count))\n console.print(table)\n\n self.config.fetch_time = str(datetime.datetime.now())\n new_fetch_config = OmegaConf.create(\n {\"since\": self.config.since, \"fetch_time\": self.config.fetch_time}\n )\n OmegaConf.save(\n config=new_fetch_config, f=self.config.paths.configs.fetching\n )\n else:\n console.log(\"You didn't play any game since, time to play! :fire: ♟️\")\n new_games = []\n return new_games\n\n\n@dataclass\nclass Game:\n config: DictConfig\n pgn: Optional[chess.pgn.Game]\n json: Optional[Union[Dict, DictConfig]]\n\n @property\n def name(self):\n return f\"{self.pgn.headers['White']}_vs_{self.pgn.headers['Black']}_{self.json['id']}\"\n\n @property\n def player(self) -> Color:\n return (\n Color.white\n if self.pgn.headers[\"White\"] == self.config.user\n else Color.black\n )\n\n def my_move(self, move_color: Color) -> bool:\n return True if self.player.value == move_color else False\n\n @property\n def path(self):\n path = self.config.paths.games.value / self.json[\"perf\"]\n path.mkdir(exist_ok=True, parents=True)\n return path\n\n def store(self, as_pgn: bool = True, as_json: bool = True):\n if as_pgn:\n (self.path / self.name).with_suffix(\".pgn\").write_text(str(self.pgn))\n if as_json:\n for key, value in self.json.items():\n if type(value) == datetime.datetime:\n self.json[key] = str(value)\n OmegaConf.save(\n config=OmegaConf.create(self.json),\n f=(self.path / self.name).with_suffix(\".json\"),\n )\n\n def mistakes(self) -> Optional[List[\"Mistake\"]]:\n _mistakes = []\n\n game = self.pgn\n\n while game is not None:\n whose_turn = not game.turn()\n move_color = \"White\" if whose_turn else \"Black\"\n if self.my_move(whose_turn):\n if game.nags:\n parent = game.parent\n parent_board = parent.board()\n if len(parent.variations) > 1:\n assert len(parent.variations) == 2\n variation_moves = str(parent.variations[1])\n nag = list(game.nags)[0]\n nag_name = get_nag_name(nag)\n\n _mistakes.append(\n Mistake(\n fen=parent_board.fen(),\n comment=game.comment,\n ply=parent.ply(),\n move_color=move_color,\n nag=nag,\n nag_name=nag_name,\n my_move=game.san(),\n best_move=parent.variations[1].san(),\n variation=variation_moves,\n game=self.pgn,\n )\n )\n game = game.next()\n\n return _mistakes\n\n @property\n def opening(self):\n game = self.pgn\n info = game.headers\n\n def get_moves(game) -> str:\n moves = []\n board = game.board()\n game = game.next()\n while info[\"Opening\"] not in game.comment:\n move = game.move\n moves.append(move)\n game = game.next()\n move = game.move\n moves.append(move)\n move_list = board.variation_san(moves)\n return move_list\n\n return Opening(\n name=info[\"Opening\"],\n eco=info[\"ECO\"],\n site=info[\"Site\"],\n moves=get_moves(game),\n config=self.config,\n )\n\n def apy_header(self):\n return \"model: Chessli Games\\ntags: chess::game_analysis\\ndeck: Chessli::games\\nmarkdown: False\\n\\n\"\n","sub_path":"chessli/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":7547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"641025578","text":"class Solution(object):\n # Original solution, very verbose\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n # Need to standardise input order\n # we want the longer number to always be on top\n # e.g. 12345\n # 2324\n if len(str(b)) > len(str(a)):\n a, b = b, a\n \n # Determine sign\n a_sign, b_sign = 1, 1\n if a < 0:\n a_sign = -1 \n a *= -1\n if b < 0:\n b_sign = -1\n b *= -1\n \n # Count the number of digits in the longer number\n digits = len(str(a))\n\n num = 0\n carry = 0\n # Need to isolate each number\n # e.g. x = 12345\n # For 0th signifiance digit (5)\n # floor(x / 10^0) % 10 = 5\n # For 1st signifiance digit (4)\n # floor(x / 10^1) % 10 = 1234 % 10 = 4\n for i in range(0, digits):\n a_digit = (a / 10 ** i) % 10\n b_digit = (b / 10 ** i) % 10\n result = a_digit * a_sign + b_digit * b_sign + carry\n\n # Need to consider concept of carry\n # if digits sum > 9, the set carry to 1\n # upon summation always add carry and always reset to zero\n\n carry = 0\n if result > 9:\n result = result % 10\n carry = 1\n num += result * (10 ** i)\n\n return num\n\n # What about negative integers?\n # Create test cases\n # One positive one negative\n # 999, 999\n\n","sub_path":"leetcode/371_sum_of_two_integers.py","file_name":"371_sum_of_two_integers.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"122943977","text":"'''\nLast week, my daughter's Y6 class was set the following problem: find two integers between 1 and 50, so that when the bigger number is divided by the smaller number,\nthe result is 4.625. The intension was that she would use trial and error. Being a computer scientist, I - of course - wrote a Python program. However, I generalised it to:\ndef intpair(target, top):\nwhere target is the result of the division that we are looking for, and top is the maximum integer to be tested. The function should return two integers. The call I used was:\nintpair(4.625, 50)\nIn this case I knew that there must be an answer, but in the general case there might not be, in which case the program needs to return -1, -1.\nintpair can be called by main(), which gets the values for target and top from the user and does some sanity checks before calling intpair.\n(For now, you can assume that the inputs are correct to type; if an int is expected an int will be entered by the user. Similarly float.)\nIf intpair returns -1, -1 you program needs to print an appropriate error message.\n'''\n\ndef intpair(minnum,maxnum,times):\n ## these two number are ints between[minnum,maxnum],so the max top should<=maxnum. Therefore,the max of base is maxnum//4.625\n baseMax=int(maxnum/times)\n if maxnum/minnum<=times:\n return None\n else:\n for i in range(minnum,baseMax+1,1):\n for j in range(int(i*times),i*int(times+1),1):\n if j/i==times:\n return i,j\n## return None\n\ndef main():\n a=int(input(\"Input minimun number(int)\"))\n b=int(input(\"Input maximun number(int)\"))\n c=float(input(\"How many times do you want?(float)\"))\n result=intpair(a,b,c)\n if result!=None:\n print(result)\n else:\n print(\"We found nothing\")\n\nmain()\n\n'''two tricks by using one loop:\n 1.check if dest-count*time<0.01\n 2.check if dest%1==0.0\n'''\n","sub_path":"week4_workshop.py","file_name":"week4_workshop.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"283304613","text":"from logging import DEBUG, debug\r\nfrom typing import Text\r\nfrom flask.templating import render_template\r\nimport requests\r\nimport re\r\nimport statistics\r\n\r\n\r\nfrom flask import Flask\r\n\r\napp = Flask(__name__)\r\n\r\n# GET THE API\r\ncovid = requests.get('https://api.covid19api.com/dayone/country/bangladesh/status/confirmed')\r\n#MAKE THE API INTO A DICTIONARY\r\ndata = covid.json()\r\n#INDEX THE LIST OF DICTIONARIES TO GET ONE WEEK OF SAID API\r\nweek_data = data[-7::1]\r\n\r\n#this takes in a list of dictionaries and goes through the dictionaires to index it to find the cases and then appends it to a list\r\ndef data_finder(data,slice=\"Cases\"):\r\n result = []\r\n for dict in data:\r\n result.append(dict[slice])\r\n return result\r\n\r\n#y axis of all cases\r\nall_y_axis = data_finder(data)\r\n#used a pattern of the date to find the x axis (or labels)\r\npattern = re.compile(r\"\\d\\d\\d\\d-\\d\\d-\\d\\d\")\r\nall_x_axis = re.findall(pattern, str(data))\r\n\r\n#y axis of one week of data(the actual cases)\r\nweek_y = all_y_axis[-7::1]\r\n#x axis of one week of data (the dates)\r\nweek_x = re.findall(pattern,str(week_data))\r\n\r\ndata_14 = all_y_axis[-14::1]\r\n\r\ndef sevenday(data):\r\n result = []\r\n for x in range(len(data)):\r\n result.append(statistics.mean(data[x:(7+x)]))\r\n return result\r\nall_average =sevenday(all_y_axis)\r\n\r\n\r\n \r\n\r\ndef indexer(data):\r\n result = []\r\n for x in range(1,8):\r\n seven = data[x:(7+x)]\r\n mean = statistics.mean(seven)\r\n result.append(mean)\r\n return result\r\n \r\nmean_data = indexer(data_14)\r\n\r\n\r\n@app.route(\"/\")\r\ndef hello_world():\r\n return render_template('all.html', x = all_x_axis, y = all_y_axis,all = all_average)\r\n\r\n@app.route(\"/week\")\r\ndef week():\r\n return render_template('week.html', x = week_x, y = week_y, mean_data = mean_data)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"633548273","text":"import time\nfrom flask import *\nimport sys\nimport psycopg2\nfrom datetime import *\nfrom datetime import timedelta\nfrom pymongo import *\ntoday= date.today().strftime(\"%d/%m/%Y\")\ndate= date.today()\ntomorrow= datetime.now()+timedelta(days=1)\n#DO NOT TOUCH THIS\napp = Flask(__name__)\napp.secret_key = 'some_secret'\n\n# flask stuff ----------\n@app.route(\"/\")\n\n@app.route(\"/\")\ndef hello(error=None):\n session.clear()\n mgdb_drop_db()\n mgdb_init_db()\n return render_template(\"choisir-mail.html\", rows=liste_mail(), hasError=error, session=session)\n\n@app.route('/after_choisir_email/', methods=['POST','GET'])\ndef after_choisir_email():\n email= request.form['email']\n passw= request.form['passw']\n if passw==checkpassw(pgsql_clientid_by_mail(email)[0][0])[0][0]:\n session['email'] = request.form['email']\n return actionmenu(session)\n else :\n return hello(error=\"Mauvais mot de passe\")\n\n@app.route('/after_choisir_nouveau_compte/')\ndef after_choisir_nouveau_compte(error=None):\n session.clear()\n\n return render_template(\"nouveau-compte.html\",hasError=error, session=session)\n\n@app.route('/after_nouveau_compte/', methods=['POST','GET']) #compte crée\ndef after_nouveau_compte():\n name = request.form['name']\n email = request.form['mail']\n passw = request.form['pass']\n for i in checkmail():\n if i[0] == email:\n #print(\"oulah\")\n return hello(error= \"Mail déjà existant dans la base de données\")\n else :\n pgsql_ajout_client(name,email,passw)\n session['email'] = request.form['mail']\n return actionmenu(session)\n\n@app.route('/back_to_menu/', methods=['POST','GET'])\ndef back_to_menu():\n return actionmenu(session)\n\n\n@app.route(\"/menu/\")\ndef actionmenu(session):\n session['name']=pgsql_client_by_mail(session['email'])[0][0]\n session['reserv']=pgsql_exist_reserv(pgsql_clientid_by_mail(session['email'])[0][0])[0][0]\n\n print (session['reserv'])\n if session['reserv']==False :\n return render_template(\"no-reserv.html\", session=session, jour=date.day, mois=date.month, annee=date.year)\n elif session['reserv']==True :\n date_fin = pgsql_reserv_active(pgsql_clientid_by_mail(session['email'])[0][0])[0][0]\n return render_template(\"choisir-action.html\", session=session, jour=date.day, mois=date.month, annee=date.year, date_fin=date_fin)\n else :\n return hello(error=None)\n\n# ------------------- Réservations\n@app.route('/consult_reserv/', methods=['POST','GET'])\ndef consult_reserv():\n rows= pgsql_liste_reserv(pgsql_clientid_by_mail(session['email'])[0][0])\n id=pgsql_reserv_active_id(pgsql_clientid_by_mail(session['email'])[0][0])\n if id :\n id=id[0][0]\n rows2= pgsql_list_paid(id)\n else:\n rows2=None\n return render_template(\"consult-reserv.html\", session=session, rows=rows, rows2=rows2)\n\n@app.route('/choisir_chambre/', methods=['POST','GET'])\ndef choisir_chambre():\n\n return render_template(\"choisir-chambre.html\", session=session, rows=liste_chambres(), date=today, tomorrow=tomorrow, desc=mgdb_display_chambres())\n\n@app.route('/confirmation_reserv/', methods=['POST','GET'])\ndef confirm_reserv():\n chambreID = request.form['chambreID']\n print(chambreID)\n date_debut = request.form['date_debut']\n print (date_debut)\n date_fin = request.form['date_fin']\n print(date_fin)\n pgsql_ajout_reserv(chambreID,date_debut,date_fin,pgsql_clientid_by_mail(session['email'])[0][0])\n return render_template(\"confirm-reserv.html\", session=session, chambreID=chambreID, date_debut=date_debut, date_fin=date_fin)\n# ------------------- Consommations\n@app.route('/choisir_conso/', methods=['POST','GET'])\ndef choisir_conso():\n return render_template(\"choisir-conso.html\", session=session, rows=liste_produits() )\n\n@app.route('/confirmation_conso/', methods=['POST','GET'])\ndef confirm_conso():\n consoNAME = pgsql_product_by_id(request.form['consoID'])\n consoNAME = consoNAME[0][0]\n consoQTE = request.form['consoQTE']\n pgsql_ajout_consommation(pgsql_clientid_by_mail(session ['email'])[0][0],request.form['consoID'],consoQTE)\n return render_template(\"confirm-conso.html\", session=session, consoQTE=consoQTE, consoNAME=consoNAME)\n# ------------------- Autres\n@app.route('/payer_reserv/', methods=['POST','GET'])\ndef payer_reserv():\n d,f,n,t=pgsql_facture(pgsql_clientid_by_mail(session['email'])[0][0])\n tch= int((f-d).days)*t\n tco=pgsql_somme_conso(pgsql_clientid_by_mail(session['email'])[0][0],d,f)\n sum=tch+tco\n paid=pgsql_get_paid(pgsql_reserv_active_id(pgsql_clientid_by_mail(session['email'])[0][0])[0][0])[0][0]\n if paid == None :\n paid=0\n remain = sum - paid\n return render_template(\"payer-reserv.html\", session=session, d=d,f=f,n=n,t=t,tch=tch,tco=tco,sum=sum,paid=paid,remain=remain)\n\n@app.route('/confirm_paiement/', methods=['POST','GET'])\ndef confirm_paiement():\n d,f,n,t=pgsql_facture(pgsql_clientid_by_mail(session['email'])[0][0])\n tch= int((f-d).days)*t\n tco=pgsql_somme_conso(pgsql_clientid_by_mail(session['email'])[0][0],d,f)\n sum=tch+tco\n paidOld=pgsql_get_paid(pgsql_reserv_active_id(pgsql_clientid_by_mail(session['email'])[0][0])[0][0])[0][0]\n paid=float(request.form['amount'])\n if paidOld==None :\n paidOld=0\n remain = sum - paidOld - paid\n print(pgsql_reserv_active_id(pgsql_clientid_by_mail(session['email'])[0][0])[0][0])\n pgsql_paiement(paid,pgsql_reserv_active_id(pgsql_clientid_by_mail(session['email'])[0][0])[0][0])\n return render_template(\"confirm-paiement.html\", session=session, paid=paid,remain=remain)\n\n\n\n\n# ---------- BDD SETUP -------------\n#interaction avec PostGres6\n\n\ndef pgsql_connect():\n try:\n db = psycopg2.connect(\"host=dbserver.emi.u-bordeaux.fr dbname=adanguin user=adanguin\")\n return db\n except Exception as e :\n flash('connexion error')\n return redirect(url_for('hello',error=str(e)))\n\n#------------------------------------ DB Commands -----\n\ndef checkmail():\n return pgsql_select('select mail from Hotel2019.Client;')\ndef checkpassw(idclient):\n return pgsql_select('select pass from Hotel2019.Client where idclient=\\'%s\\';'% (idclient))\n\ndef liste_mail():\n return pgsql_select('select mail from Hotel2019.Client;')\n\ndef liste_chambres():\n return pgsql_select('select * from Hotel2019.Chambre where numero NOT IN (select numero from Hotel2019.Reservation where date_fin>=current_date and date_debut<=current_date);')\n\ndef liste_chambres_occupees():\n return pgsql_select('select numero from Hotel2019.Reservation where date_fin>=current_date;')\n\n\ndef liste_produits():\n return pgsql_select('select * from Hotel2019.Bar;')\n\ndef pgsql_reserv_active(idclient):\n return pgsql_select('select date_fin from hotel2019.Reservation where idclient=\\'%s\\' and date_fin>=current_date ;'% (idclient))\n\ndef pgsql_reserv_active_id(idclient):\n return pgsql_select('select idreserv from hotel2019.Reservation where idclient=\\'%s\\' and date_debut<=current_date and date_fin>=current_date ;'% (idclient))\n\ndef pgsql_exist_reserv(idclient):\n return pgsql_select('select exists (select true from hotel2019.Reservation where idclient=\\'%s\\' and date_fin>=current_date );'% (idclient))\n\ndef pgsql_liste_reserv(idclient):\n return pgsql_select('select * from Hotel2019.Reservation where idclient=\\'%s\\';'% (idclient))\n\ndef pgsql_facture(idclient):\n temp = pgsql_select('select date_debut, date_fin, numero from hotel2019.Reservation where idclient=\\'%s\\' and date_fin>=current_date ;'% (idclient))\n d=temp[0][0]\n f=temp[0][1]\n n=temp[0][2]\n temp = pgsql_select('select tarif from hotel2019.chambre where numero=\\'%s\\';' %(n))\n t= temp[0][0]\n return d,f,n,t\ndef pgsql_tarifproduit(id):\n return pgsql_select('select tarif from hotel2019.bar where idproduit=\\'%s\\';' %(id))\n\ndef pgsql_somme_conso(idclient,d,f):\n sum=0\n temp = pgsql_select('select idproduit,qte from hotel2019.consommation where idclient=\\'%s\\' and dateconso<=\\'%s\\' and dateconso>=\\'%s\\';'%(idclient,f,d))\n for row in temp :\n t=pgsql_tarifproduit(row[0])[0][0]\n sum=sum+(t*row[1])\n return sum\n\ndef pgsql_get_paid(id):\n temp = pgsql_select('select sum(somme) from hotel2019.paiement where \"Numreservation\"=\\'%s\\';'%(int(id)))\n return temp\n\ndef pgsql_list_paid(id):\n temp = pgsql_select('select * from hotel2019.paiement where \"Numreservation\"=\\'%s\\';'%(int(id)))\n return temp\ndef pgsql_client_by_mail(mail):\n return pgsql_select('select nom from Hotel2019.Client where mail=\\'%s\\';' % (mail))\n\ndef pgsql_clientid_by_mail(mail):\n return pgsql_select('select idclient from Hotel2019.Client where mail=\\'%s\\';' % (mail))\n\ndef pgsql_product_by_id(ID):\n return pgsql_select('select nomproduit from Hotel2019.Bar where idproduit=\\'%s\\';' % (ID))\n\n# -- Commands that WRITE to the DB ---\n\ndef pgsql_ajout_client(newname,newmail,newpassword):\n return pgsql_insert('insert into Hotel2019.Client values(DEFAULT,\\'%s\\',\\'%s\\',\\'%s\\');' % (newname, newmail, newpassword))\n\ndef pgsql_ajout_consommation(idclient,idproduit,qte):\n return pgsql_insert('insert into Hotel2019.Consommation values(DEFAULT,\\'%s\\',\\'%s\\',\\'%s\\',current_date);' % (idclient,idproduit,qte))\n\ndef pgsql_ajout_reserv(chambreID,date_debut,date_fin,clientID):\n print(chambreID)\n return pgsql_insert('insert into Hotel2019.Reservation values(\\'%s\\',\\'%s\\',\\'%s\\',\\'%s\\',DEFAULT);' % (chambreID,date_debut,date_fin,clientID))\n\ndef pgsql_paiement(somme,id):\n return pgsql_insert('insert into Hotel2019.paiement values(\\'%s\\',current_date,\\'%s\\');' % ((float(somme),int(id))))\n# -------------------------------------- DB ACCESS & CONTROLS ------\ndef pgsql_select(command):\n db = pgsql_connect()\n\n cursor = db.cursor()\n try:\n cursor.execute(command)\n rows = cursor.fetchall()\n\n cursor.close()\n db.close()\n print('passed')\n return rows\n except Exception as e :\n print('failed')\n flash('sorry, this service is unavailable')\n return redirect(url_for('hello',error=str(e)))\n\ndef pgsql_insert(command):\n db = pgsql_connect()\n cursor = db.cursor()\n try:\n cursor.execute(command)\n nb = cursor.rowcount\n cursor.close()\n db.commit()\n print('passed')\n return nb\n except Exception as e:\n print(e)\n print('failed')\n flash ('Service Unavailable')\n return redirect(url_for('hello', error=str(e)))\n#--------------------------------------------------------------------------------------------\n#MongoDB\ndef get_mg_db():\n db=MongoClient(\"mongodb.emi.u-bordeaux.fr:27017\").adanguin\n return db\n\ndef mgdb_drop_db():\n mgdb = get_mg_db()\n mgdb.chambres.drop()\n mgdb.comments.drop()\n\ndef mgdb_init_db():\n mgdb = get_mg_db()\n with app.open_resource('static/hotel_chambres.json') as f:\n mgdb.chambres.insert(json.loads(f.read().decode('utf8')))\n print(\"db init\")\n\ndef mgdb_display_chambre(idchambre):\n mgdb = get_mg_db()\n if mgdb:\n return mgdb.chambres.find({\"chambre_id\":int(idchambre)})\n else:\n return None\ndef mgdb_display_chambres():\n mgdb = get_mg_db()\n if mgdb:\n return [chambre for chambre in mgdb.chambres.find()]\n else:\n return None\ndef mgdb_display_comments(idChambre):\n mdgb = det_mg_db()\n if mgdb:\n return mgdb.comments.find({\"chambre_id\":int(idChambre)})\n else:\n return None\n\ndef mgdb_insert_comment(idChambre, nom, prenom, jour, debut, fin, avis):\n mdgb = get_mg_db()\n result = mgdb.comments.insert(\n {\n \"chambre_id\": int(idChambre),\n \"client_nom\": nom, \n \"date\": jour,\n \"date_debut\": debut,\n \"date_fin\": fin,\n \"avis\": avis\n }\n )\n return result\n\n\n#DO NOT TOUCH THIS\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":11981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"205881670","text":"# Coded by D4n1l3k300\r\n# t.me/D4n13l3k00\r\nfrom .. import loader, utils\r\nimport re, random\r\n@loader.tds\r\nclass RandomizerMod(loader.Module):\r\n strings = {\"name\": \"Рандомайзер\"}\r\n prefix = \"[Рандомайзер]\\n\"\r\n @loader.owner\r\n async def rndintcmd(self, m):\r\n \".rndint - рандомное число из заданногоо диапозона\"\r\n args = utils.get_args_raw(m)\r\n check = re.compile(r\"^(\\d+)\\s+(\\d+)$\")\r\n if check.match(args):\r\n fr, to = check.match(args).groups()\r\n if int(fr) < int(to):\r\n rndint = random.randint(int(fr), int(to))\r\n await m.edit(self.prefix+f\"Режим: Рандомное число из диапозона\\nДиапозон: {fr}-{to}\\nВыпало число: {rndint}\")\r\n else: await m.edit(self.prefix+\"Вася, укажи диапозон чисел!\")\r\n else: await m.edit(self.prefix+\"Вася, укажи диапозон чисел!\")\r\n async def rndelmcmd(self, m):\r\n \".rndelm <элементы через запятую> - рандомный элемент из списка\"\r\n args = utils.get_args_raw(m)\r\n if not args: await m.edit(self.prefix+\"Вася, напиши список элементов через запятую!\"); return\r\n lst = [i.strip() for i in args.split(\",\") if i]\r\n await m.edit(self.prefix+f\"Режим: Рандомный элемент из списка\\nСписок: {', '.join(lst)}\\nВыпало: {random.choice(lst)}\")\r\n async def rndusercmd(self, m):\r\n \".rnduser - выбор рандомного юзера из чата\"\r\n if not m.chat: await m.edit(self.prefix+\"Это не чат\"); return\r\n users = await m.client.get_participants(m.chat)\r\n user = random.choice(users)\r\n await m.edit(self.prefix+f\"Режим: Рандомный юзер из чата\\nЮзер: {user.first_name} | {user.id}\")\r\n \r\n \r\n \r\n ","sub_path":"Randomizer.py","file_name":"Randomizer.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"282142239","text":"#divide two integers (Medium)\n#Leetcode https://leetcode.com/problems/divide-two-integers/\n#loops, update, track\n\n\n#use 2 loops, inner loops increase divisor everytime by 2 times and substract from dividend, to fast computation\n#if the inner divisorExp gets too big, pass the remainder of dividend to the outter loop \n#and start substracting divisor again\n\n#keep track of \"how many divisors have been substracted\"\n\n\n\n\nclass Solution(object):\n def divide(self, divident, divisor):\n \"\"\"\n :type dividend: int\n :type divisor: int\n :rtype: int\n \"\"\"\n \n #if divisor is 0, return inf\n if divisor == 0 :\n return sys.maxsize\n #use a flag to represent negative\n \n\n\n negative = False\n if (divident>0 and divisor<0) or (divident<0 and divisor>0):\n negative = True\n\n #change all input into positive\n divident = abs(divident)\n divisor = abs(divisor)\n\n result = 0\n\n\n #Outer loop\n while divident>=divisor: #deal with the remainder of the divident that can't be divided by divisorExp\n count = 1\n divisorExp = divisor\n #innter loop\n while divident>=divisorExp:\n divident -= divisorExp\n result+=count\n count += count #notice the divisorExp gets bigger by factor of 2 every time\n divisorExp += divisorExp\n\n if negative:\n if result < -2147483648:\n return -2147483648\n else:\n return -result\n else:\n if result>2147483647:\n return 2147483647\n else:\n return result\n\n\n\n \n\na = Solution()\nprint (a.divide(7,-2))\n\n\n\n","sub_path":"divide_int.py","file_name":"divide_int.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"434885154","text":"###############################################################################\n#\n# Copyright (C) 2015\n# ASTRON (Netherlands Institute for Radio Astronomy) \n# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n###############################################################################\n\nfrom common import *\nfrom mem_init_file import list_to_hex\nimport pi_ss_parallel\n\n# Purpose:\n# . Generate the HEX files for the ss_parallel instance.\n# Description:\n# . In 16b mode, no extra reordering takes place: dout=din.\n# . The ss_parallel instance requires 3 types of hex files (4 in total):\n# . Input reorder stage : ss_parallel_sb_16b_reorder_in.hex\n# . Main selection stage : ss_parallel_sb_16b_ss_wide_0.hex\n# : ss_parallel_sb_16b_ss_wide_1.hex\n# . Output reorder stage : ss_parallel_sb_16b_reorder_out.hex\n#\n# Remark:\n\nNOF_IN = 2\nNOF_INTERNALS = 2\nNOT_OUT = 2 \nFRAME_SIZE_IN = 864 # 12*72 or 9*96\nFRAME_SIZE_OUT = FRAME_SIZE_IN \n\nHEX_REORDER_IN_MEM_WIDTH = 8 # Actually 1 bit but HEX files require byte boundaries \nHEX_REORDER_IN_MEM_DEPTH = 1024 # 864 cycles * 1 bit to encode the 2 inputs on each word = 864 regs\nHEX_REORDER_IN_FILE_NAME = \"../hex/ss_parallel_sb_16b_reorder_in.hex\"\n\nHEX_SS_WIDE_MEM_WIDTH = 10\nHEX_SS_WIDE_MEM_DEPTH = 1024 # size = 864 words each (matches output block size) for each of its 2 internal instances\nHEX_SS_WIDE_FILE_PREFIX = \"../hex/ss_parallel_sb_16b_ss_wide_\"\n\nHEX_REORDER_OUT_MEM_WIDTH = 8 # Actually 4 bits but HEX files require byte boundaries\nHEX_REORDER_OUT_MEM_DEPTH = 1024 # 864 cycles * 4 bits to encode the 2 inputs on each word = 864 regs\nHEX_REORDER_OUT_FILE_NAME = \"../hex/ss_parallel_sb_16b_reorder_out.hex\"\n\n# This is not a TC but we must provide a TC to create the object\nimport test_case\ndummy_tc = test_case.Testcase('','')\n# We won't be using IO either.\nimport node_io\ndummy_io = node_io.NodeIO(dummy_tc.nodeImages, dummy_tc.base_ip)\n\nss = pi_ss_parallel.PiSsParallel(dummy_tc, dummy_io, NOF_IN, NOF_INTERNALS, NOT_OUT, FRAME_SIZE_IN, FRAME_SIZE_OUT)\n\n# ========================\n# Create the input matrix:\n# ========================\ndin = ss.create_Din()\n\n# =========================\n# Create the output matrix:\n# =========================\ndout = din\n\n# ======================\n# Generate the settings:\n# ======================\n[result, Rin, Dram, Dsel, Rout, Errout] = ss.create_settings(din, dout)\n\n# =====================================================\n# Create the selection buffer values from the settings:\n# =====================================================\nreorder_in_buf = ss.ssReorderIn.create_selection_buf(Rin)\nselect_buf = flatten(Dsel) \nreorder_out_buf = ss.ssReorderOut.create_selection_buf(Rout)\n\n# ================================\n# Generate hex file: input reorder\n# ================================\nlist_to_hex(reorder_in_buf, HEX_REORDER_IN_FILE_NAME, HEX_REORDER_IN_MEM_WIDTH, HEX_REORDER_IN_MEM_DEPTH)\n\n# ===========================\n# Generate hex files: ss_wide\n# ===========================\n# First replace the don't cares (-1) with zeroes for list_to_hex (requires integers)\nfor n,i in enumerate(select_buf):\n if i==-1:\n select_buf[n]=0\n\n\n# The created select_buf is a flat list meant to MM write to several instances \n# from a certain offset. However, we want to create a HEX file for each\n# individual instance, so split the list into 2 (sublist size of 864).\nfor i, sublist in zip(range(2), split_list(select_buf, 864)):\n list_to_hex(sublist, HEX_SS_WIDE_FILE_PREFIX+str(i)+\".hex\", HEX_SS_WIDE_MEM_WIDTH, HEX_SS_WIDE_MEM_DEPTH)\n\n# ==================================\n# Generate hex files: output reorder\n# ==================================\n# The output reorder list contains 864 words of 4 bits, so each word easily \n# fits within 32b words.\nlist_to_hex(reorder_out_buf, HEX_REORDER_OUT_FILE_NAME, HEX_REORDER_OUT_MEM_WIDTH, HEX_REORDER_OUT_MEM_DEPTH)\n","sub_path":"RadioHDL/trunk/applications/aartfaac/designs/aartfaac_bn_sdo/src/python/gen_hex_files_ss_parallel_sb_16b.py","file_name":"gen_hex_files_ss_parallel_sb_16b.py","file_ext":"py","file_size_in_byte":4541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"225618718","text":"from __future__ import division\nimport math\n\ndef merge_dicts (dol1, dol2):\n keys = set(dol1).union(dol2)\n no = []\n return dict((k, dol1.get(k, no) + dol2.get(k, no)) for k in keys)\n\ndef sign (num):\n return((1, -1)[num < 0])\n\ndef delta_angle (angle1, angle2):\n delta = angle1 - angle2\n while delta > math.pi:\n delta -= 2*math.pi\n while delta < -math.pi:\n delta += 2*math.pi\n\n return delta\n\nclass Robot (object):\n \"\"\"defines robot's specs\"\"\"\n def __init__(self, params):\n self.max_vel = params.get(\"max_vel\")\n self.slow_max_vel = params.get(\"slow_max_vel\")\n self.max_acc = params.get(\"max_acc\")\n self.max_angular_acc = params.get(\"max_angular_acc\")\n self.jerk = params.get(\"jerk\")\n self.width = params.get(\"width\")\n self.height = params.get(\"height\")\n self.cycle = params.get(\"cycle\")\n\nclass Point (object):\n \"\"\"point in the path defined by the user\"\"\"\n def __init__(self, x, y, angle, heading, s_mag, e_mag, p_vel, use_heading):\n self.x = x\n self.y = y\n self.angle = angle\n self.heading = heading\n self.start_mag = s_mag\n self.end_mag = e_mag\n self.p_vel = p_vel\n self.use_heading = True if use_heading == \"true\" else False\n self.magnitude_factor = 1.2\n\n self.dx = math.cos(angle)*self.start_mag\n self.dy = math.sin(angle)*self.end_mag\n self.ddx = 0\n self.ddy = 0\n\n def distance (self, point):\n return math.sqrt((self.x-point.x)**2 + (self.y-point.y)**2)\n\n def update_v (self, point, is_start):\n # self.magnitude = self.magnitude_factor*self.distance(point)*0.5\n if is_start:\n mag = self.start_mag\n else:\n mag = self.end_mag\n\n self.dx = math.cos(self.angle)*mag\n self.dy = math.sin(self.angle)*mag\n\n pass\n\nclass trajectory_point(object):\n \"\"\"single point in the path containes all\n the trajectory data of the point\"\"\"\n def __init__(self, x=0, y=0, angle=0, heading=0):\n self.time = 0\n self.y = y\n self.x = x\n self.angle = angle\n self.heading = heading\n self.wheading = 0\n self.vel = 0\n self.vx = 0\n self.vy = 0\n self.acc = 0\n self.dist = 0\n self.rule = 0\n self.slow_no_cam = False\n self.slow = False\n\n def update_distances (self, prev_point, angle):\n self.dist = ((self.x-prev_point.x)**2 + (self.y-prev_point.y)**2)**0.5\n self.angle = angle\n\n def update_point_backward (self, prev_point, max_vel, max_acc, jerk):\n dt = prev_point.time - self.time\n new_acc = (self.vel-prev_point.vel)/dt\n if (new_acc > max_acc):\n self.vel = sign(prev_point.dist)*((2*prev_point.acc*abs(prev_point.dist) + prev_point.vel**2))**0.5\n self.vel = min(max_vel, self.vel, key=abs)\n new_dt = prev_point.dist/self.vel\n self.acc = min(prev_point.acc + jerk*new_dt, max_acc, key=abs)\n\n\n def update_point_forward(self, prev_point, max_vel, max_acc, jerk):\n self.vel = sign(self.dist)*((2*prev_point.acc*abs(self.dist) + prev_point.vel**2))**0.5\n self.vel = min(max_vel, self.vel, key=abs)\n dt = self.dist/(self.vel + 10**(-8))\n\n max_acc_by_vel = max(max_acc-max_acc*(abs(self.vel)/max_vel), 0.1)\n self.acc = min(prev_point.acc + jerk*dt, max_acc_by_vel, key=abs)\n\n self.time = prev_point.time+dt\n\n def reset (self, max_acc):\n self.vel = 0\n self.acc = 0.1\n\n def update_point (self, prev_point):\n if ((prev_point.vel) == 0):\n dt = 0\n else:\n dt = self.dist/abs(prev_point.vel)\n\n self.time = prev_point.time + dt\n","sub_path":"Python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"98175735","text":"# Copyright (C) 2020 Jørgen S. Dokken\n#\n# This file is part of DOLFINX_MPC\n#\n# SPDX-License-Identifier: LGPL-3.0-or-later\n#\nimport dolfinx.geometry as geometry\nimport dolfinx.fem as fem\nimport dolfinx\nimport dolfinx.io\nimport dolfinx.log\nimport dolfinx_mpc\nimport dolfinx_mpc.utils\nimport numpy as np\nimport pygmsh\nimport ufl\nfrom petsc4py import PETSc\nfrom create_and_export_mesh import mesh_2D_rot, mesh_2D_dolfin\nfrom helpers import find_master_slave_relationship\n\ndolfinx.log.set_log_level(dolfinx.log.LogLevel.ERROR)\n\ncomp_col_pts = geometry.compute_collisions_point\nget_basis = dolfinx_mpc.cpp.mpc.get_basis_functions\n\n\ndef find_line_function(p0, p1):\n \"\"\"\n Find line y=ax+b for each of the lines in the mesh\n https://mathworld.wolfram.com/Two-PointForm.html\n \"\"\"\n # Line aligned with y axis\n if np.isclose(p1[0], p0[0]):\n return lambda x: np.isclose(x[0], p0[0])\n return lambda x: np.isclose(x[1],\n p0[1]+(p1[1]-p0[1])/(p1[0]-p0[0])*(x[0]-p0[0]))\n\n\ndef over_line(p0, p1):\n \"\"\"\n Check if a point is over or under y=ax+b for each of the lines in the mesh\n https://mathworld.wolfram.com/Two-PointForm.html\n \"\"\"\n return lambda x: x[1] > p0[1]+(p1[1]-p0[1])/(p1[0]-p0[0])*(x[0]-p0[0])\n\n\ndef demo_stacked_cubes(outfile, theta, gmsh=True, triangle=True):\n if gmsh:\n mesh_name = \"Grid\"\n if dolfinx.MPI.rank(dolfinx.MPI.comm_world) == 0:\n mesh_2D_rot(theta)\n filename = \"meshes/mesh_rot.xdmf\"\n ext = \"gmsh\" + \"{0:.2f}\".format(theta)\n else:\n mesh_name = \"mesh\"\n if triangle:\n if dolfinx.MPI.rank(dolfinx.MPI.comm_world) == 0:\n mesh_2D_dolfin(\"tri\")\n filename = \"meshes/mesh_tri.xdmf\"\n ext = \"tri\" + \"{0:.2f}\".format(theta)\n else:\n if dolfinx.MPI.rank(dolfinx.MPI.comm_world) == 0:\n mesh_2D_dolfin(\"quad\")\n filename = \"meshes/mesh_quad.xdmf\"\n ext = \"quad\" + \"{0:.2f}\".format(theta)\n\n with dolfinx.io.XDMFFile(dolfinx.MPI.comm_world,\n filename, \"r\") as xdmf:\n mesh = xdmf.read_mesh(mesh_name)\n mesh.name = \"mesh_\" + ext\n\n tdim = mesh.topology.dim\n fdim = tdim - 1\n\n # Helper until MeshTags can be read in from xdmf\n r_matrix = pygmsh.helpers.rotation_matrix([0, 0, 1], theta)\n\n # Find information about facets to be used in MeshTags\n bottom_points = np.dot(r_matrix, np.array([[0, 0, 0], [1, 0, 0],\n [1, 1, 0], [0, 1, 0]]).T)\n bottom = find_line_function(bottom_points[:, 0], bottom_points[:, 1])\n bottom_facets = dolfinx.mesh.locate_entities_geometrical(\n mesh, fdim, bottom, boundary_only=True)\n\n top_points = np.dot(r_matrix, np.array([[0, 1, 0], [1, 1, 0],\n [1, 2, 0], [0, 2, 0]]).T)\n top = find_line_function(top_points[:, 2], top_points[:, 3])\n top_facets = dolfinx.mesh.locate_entities_geometrical(\n mesh, fdim, top, boundary_only=True)\n\n left_side = find_line_function(top_points[:, 0], top_points[:, 3])\n left_facets = dolfinx.mesh.locate_entities_geometrical(\n mesh, fdim, left_side, boundary_only=True)\n\n right_side = find_line_function(top_points[:, 1], top_points[:, 2])\n right_facets = dolfinx.mesh.locate_entities_geometrical(\n mesh, fdim, right_side, boundary_only=True)\n\n interface = find_line_function(bottom_points[:, 2], bottom_points[:, 3])\n i_facets = dolfinx.mesh.locate_entities_geometrical(\n mesh, fdim, interface, boundary_only=True)\n\n top_cube = over_line(bottom_points[:, 2], bottom_points[:, 3])\n\n num_cells = mesh.topology.index_map(tdim).size_local\n cell_midpoints = dolfinx.cpp.mesh.midpoints(mesh, tdim,\n range(num_cells))\n top_cube_marker = 3\n indices = []\n values = []\n for cell_index in range(num_cells):\n if top_cube(cell_midpoints[cell_index]):\n indices.append(cell_index)\n values.append(top_cube_marker)\n ct = dolfinx.mesh.MeshTags(mesh, fdim, np.array(\n indices, dtype=np.intc), np.array(values, dtype=np.intc))\n\n # Create meshtags for facet data\n markers = {3: top_facets, 4: i_facets,\n 5: bottom_facets, 6: left_facets, 7: right_facets}\n indices = np.array([], dtype=np.intc)\n values = np.array([], dtype=np.intc)\n\n for key in markers.keys():\n indices = np.append(indices, markers[key])\n values = np.append(values, np.full(len(markers[key]), key,\n dtype=np.intc))\n mt = dolfinx.mesh.MeshTags(mesh, fdim,\n indices, values)\n\n V = dolfinx.VectorFunctionSpace(mesh, (\"Lagrange\", 1))\n V0 = V.sub(0).collapse()\n V1 = V.sub(1).collapse()\n\n g_vec = np.dot(r_matrix, [0, -1.25e2, 0])\n g = dolfinx.Constant(mesh, g_vec[:2])\n\n # Define boundary conditions (HAS TO BE NON-MASTER NODES)\n u_bc = dolfinx.function.Function(V)\n with u_bc.vector.localForm() as u_local:\n u_local.set(0.0)\n\n bottom_dofs = fem.locate_dofs_topological(V, fdim, bottom_facets)\n bc_bottom = fem.DirichletBC(u_bc, bottom_dofs)\n\n # def top_v(x):\n # values = np.empty((2, x.shape[1]))\n # values[0] = g_vec[0]\n # values[1] = g_vec[1]\n # return values\n # u_top = dolfinx.function.Function(V)\n # u_top.interpolate(top_v)\n # top_dofs = fem.locate_dofs_topological(V, fdim, top_facets)\n # bc_top = fem.DirichletBC(u_top, top_dofs)\n bcs = [bc_bottom] # , bc_top]\n\n # Elasticity parameters\n E = 1.0e3\n nu = 0\n mu = dolfinx.Constant(mesh, E / (2.0 * (1.0 + nu)))\n lmbda = dolfinx.Constant(mesh, E * nu / ((1.0 + nu) * (1.0 - 2.0 * nu)))\n\n # Stress computation\n def sigma(v):\n return (2.0 * mu * ufl.sym(ufl.grad(v)) +\n lmbda * ufl.tr(ufl.sym(ufl.grad(v))) * ufl.Identity(len(v)))\n\n # Define variational problem\n u = ufl.TrialFunction(V)\n v = ufl.TestFunction(V)\n a = ufl.inner(sigma(u), ufl.grad(v)) * ufl.dx\n ds = ufl.Measure(\"ds\", domain=mesh, subdomain_data=mt,\n subdomain_id=3)\n lhs = ufl.inner(dolfinx.Constant(mesh, (0, 0)), v)*ufl.dx\\\n + ufl.inner(g, v)*ds\n\n # Create standard master slave relationsship\n slaves, masters, coeffs, offsets = find_master_slave_relationship(\n V, (mt, 4), (ct, 3))\n\n # Set normal sliding of a single on each side of the cube to zero to\n # avoid translational invariant problem\n if np.isclose(theta, 0):\n def in_corner(x):\n return np.logical_or(np.isclose(x.T, [0, 2, 0]).all(axis=1),\n np.isclose(x.T, [1, 2, 0]).all(axis=1))\n V0 = V.sub(0).collapse()\n zero = dolfinx.Function(V0)\n with zero.vector.localForm() as zero_local:\n zero_local.set(0.0)\n dofs = fem.locate_dofs_geometrical((V.sub(0), V0), in_corner)\n bc_corner = dolfinx.DirichletBC(zero, dofs, V.sub(0))\n bcs.append(bc_corner)\n else:\n global_indices = V.dofmap.index_map.global_indices(False)\n x_coords = V.tabulate_dof_coordinates()\n V0 = V.sub(0).collapse()\n V1 = V.sub(1).collapse()\n m_side, s_side, c_side, o_side = [], [], [], []\n for key, corners in zip([6, 7], [[0, 3], [1, 2]]):\n local_side_facets = np.flatnonzero(mt.values == key)\n side_facets = mt.indices[local_side_facets]\n\n dofs_x = fem.locate_dofs_topological(\n (V.sub(0), V0), fdim, side_facets)[:, 0]\n dofs_y = fem.locate_dofs_topological(\n (V.sub(1), V1), fdim, side_facets)[:, 0]\n\n top_cube_side_x = np.flatnonzero(top_cube(x_coords[dofs_x].T))\n top_cube_side_y = np.flatnonzero(top_cube(x_coords[dofs_y].T))\n\n slip = False\n n_side = dolfinx_mpc.facet_normal_approximation(V, mt, key)\n n_side_vec = n_side.vector.getArray()\n for id_x in top_cube_side_x:\n x_dof = dofs_x[id_x]\n corner_1 = np.allclose(\n x_coords[x_dof], top_points[:, corners[0]])\n corner_2 = np.allclose(\n x_coords[x_dof], top_points[:, corners[1]])\n if corner_1 or corner_2:\n continue\n for id_y in top_cube_side_y:\n y_dof = dofs_y[id_y]\n same_coord = np.allclose(x_coords[x_dof], x_coords[y_dof])\n corner_1 = np.allclose(\n x_coords[y_dof], top_points[:, corners[0]])\n corner_2 = np.allclose(\n x_coords[y_dof], top_points[:, corners[1]])\n coeff = -n_side_vec[y_dof] / n_side_vec[x_dof]\n not_zero = not np.isclose(coeff, 0)\n not_corners = not corner_1 and not corner_2\n if not_corners and same_coord and not_zero:\n s_side.append(global_indices[x_dof])\n m_side.append(global_indices[y_dof])\n c_side.append(coeff)\n\n o_side.append(len(masters)+len(m_side))\n slip = True\n break\n if slip:\n break\n m_side = np.array(m_side, dtype=np.int64)\n s_side = np.array(s_side, dtype=np.int64)\n o_side = np.array(o_side, dtype=np.int64)\n\n masters = np.append(masters, m_side)\n slaves = np.append(slaves, s_side)\n coeffs = np.append(coeffs, c_side)\n offsets = np.append(offsets, o_side)\n\n mpc = dolfinx_mpc.cpp.mpc.MultiPointConstraint(V._cpp_object, slaves,\n masters, coeffs, offsets)\n\n # Setup MPC system\n A = dolfinx_mpc.assemble_matrix(a, mpc, bcs=bcs)\n b = dolfinx_mpc.assemble_vector(lhs, mpc)\n\n # Apply boundary conditions\n fem.apply_lifting(b, [a], [bcs])\n b.ghostUpdate(addv=PETSc.InsertMode.ADD_VALUES,\n mode=PETSc.ScatterMode.REVERSE)\n fem.set_bc(b, bcs)\n\n # Solve Linear problem\n solver = PETSc.KSP().create(dolfinx.MPI.comm_world)\n solver.setType(PETSc.KSP.Type.PREONLY)\n solver.getPC().setType(PETSc.PC.Type.LU)\n solver.setOperators(A)\n uh = b.copy()\n uh.set(0)\n solver.solve(b, uh)\n uh.ghostUpdate(addv=PETSc.InsertMode.INSERT,\n mode=PETSc.ScatterMode.FORWARD)\n\n # Back substitute to slave dofs\n dolfinx_mpc.backsubstitution(mpc, uh, V.dofmap)\n\n # Create functionspace and function for mpc vector\n Vmpc_cpp = dolfinx.cpp.function.FunctionSpace(mesh, V.element,\n mpc.mpc_dofmap())\n Vmpc = dolfinx.FunctionSpace(None, V.ufl_element(), Vmpc_cpp)\n\n # Write solution to file\n u_h = dolfinx.Function(Vmpc)\n u_h.vector.setArray(uh.array)\n u_h.name = \"u_mpc_\" + ext\n outfile.write_mesh(mesh)\n outfile.write_function(u_h, 0.0,\n \"Xdmf/Domain/\"\n + \"Grid[@Name='{0:s}'][1]\"\n .format(mesh.name))\n\n # Transfer data from the MPC problem to numpy arrays for comparison\n A_mpc_np = dolfinx_mpc.utils.PETScMatrix_to_global_numpy(A)\n mpc_vec_np = dolfinx_mpc.utils.PETScVector_to_global_numpy(b)\n\n # Solve the MPC problem using a global transformation matrix\n # and numpy solvers to get reference values\n\n # Generate reference matrices and unconstrained solution\n A_org = fem.assemble_matrix(a, bcs)\n\n A_org.assemble()\n L_org = fem.assemble_vector(lhs)\n fem.apply_lifting(L_org, [a], [bcs])\n L_org.ghostUpdate(addv=PETSc.InsertMode.ADD_VALUES,\n mode=PETSc.ScatterMode.REVERSE)\n fem.set_bc(L_org, bcs)\n\n # Create global transformation matrix\n K = dolfinx_mpc.utils.create_transformation_matrix(V.dim(), slaves,\n masters, coeffs,\n offsets)\n # Create reduced A\n A_global = dolfinx_mpc.utils.PETScMatrix_to_global_numpy(A_org)\n\n reduced_A = np.matmul(np.matmul(K.T, A_global), K)\n # Created reduced L\n vec = dolfinx_mpc.utils.PETScVector_to_global_numpy(L_org)\n reduced_L = np.dot(K.T, vec)\n # Solve linear system\n d = np.linalg.solve(reduced_A, reduced_L)\n # Back substitution to full solution vector\n uh_numpy = np.dot(K, d)\n # Compare LHS, RHS and solution with reference values\n dolfinx_mpc.utils.compare_matrices(reduced_A, A_mpc_np, slaves)\n dolfinx_mpc.utils.compare_vectors(reduced_L, mpc_vec_np, slaves)\n assert np.allclose(uh.array, uh_numpy[uh.owner_range[0]:\n uh.owner_range[1]])\n print(uh.norm())\n\n\nif __name__ == \"__main__\":\n outfile = dolfinx.io.XDMFFile(dolfinx.MPI.comm_world,\n \"results/rotated_cube.xdmf\", \"w\")\n demo_stacked_cubes(outfile, theta=0, gmsh=False, triangle=True)\n # FIXME: Does not work due to collision detection\n # demo_stacked_cubes(theta=0, gmsh=False, triangle=False)\n demo_stacked_cubes(outfile, theta=0, gmsh=True)\n demo_stacked_cubes(outfile, theta=np.pi/7, gmsh=True)\n outfile.close()\n","sub_path":"python/demos/cubes/rotated_cube.py","file_name":"rotated_cube.py","file_ext":"py","file_size_in_byte":13341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"167398019","text":"#爬91信息\nimport requests\nfrom bs4 import BeautifulSoup\nfor i in range(1,500):\n #print(i)\n url = 'http://g.p03.space/forumdisplay.php?fid=19&page='+str(i)\n #print(url)\n ret = requests.get(url=url)\n ret.encoding = ret.apparent_encoding\n #print(ret.text)\n soup = BeautifulSoup(ret.text,features='html.parser')\n r1 = soup.find(id='moderate')\n tb = r1.find('table')\n tbd_list = tb.find_all('tbody')\n #print(tbd_list)\n for tbd in tbd_list:\n th = tbd.find('th')\n a = th.find('a')\n if a:\n if '合肥' in a.text:\n a_url = a.attrs.get('href')\n a_txt = a.text\n #print('http://g.p03.space/' + a_url, a_txt)\n a_txt = 'http://g.p03.space/' + a_url +'信息'+a.text\n with open('信息.txt','a',encoding='utf-8') as f:\n f.write(a_txt)\n\n\n\n","sub_path":"spider/chouti.py","file_name":"chouti.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"19211025","text":"#!/usr/bin/env python\n\n# Import external modules\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.stats as stats\n# from theano.compile.ops import as_op\n# from theano import shared, scan, function\nimport pickle\nimport json\nfrom scipy.interpolate import interp1d\nfrom jet_div_spec import jet_div_spec\nimport theano\nimport theano.tensor as tt\nimport pymc3 as pm3\nimport matplotlib.pyplot as plt\nfrom tools.pyADASutils.standalone_continuo import adas_continuo_py\n\n\ndef np_find_nearest(array, value):\n idx = (np.abs(array - value)).argmin()\n return idx, array[idx]\n\n\ndef gaussian(center, x, peak, sigma):\n g = peak * np.exp(-1.*((x - center)**2) / (2*(sigma**2)) )\n return g\n\n\ndef expon(lamb, x):\n if all(x > 0):\n return lamb*np.exp(-lamb*(10*x))\n else:\n return\n\n\ndef linear(m, b, x):\n return m*x + b\n\n\ndef gen_stark_noisy_data(ne_prof_amp, ne_prof_std, x, wave, ax, noiseamp=0.02):\n \"\"\"D-delta Stark broadening function for pymc3 deterministic (no numpy!)\"\"\"\n # Stark broadening coefficients (Lomanowski et al 2015, NF)\n # lorentz_5_2_coeffs_D62 = {'C': 3.954E-16, 'a': 0.7149, 'b': 0.028}\n lorentz_5_2_D62_C_coeff = 3.954E-16\n lorentz_5_2_D62_a_coeff = 0.7149\n center = 0\n ne_prof = gaussian(center, x, np.abs(ne_prof_amp), np.abs(ne_prof_std))\n ax[0].plot(x, ne_prof, '-k')\n\n # Determine Stark FWHM\n # In the first instance, assume that D-delta is recombination dominated and that Te is constant,\n # so the emission along the LOS is weighted by ne*ne only.\n # Te_const = 1. # eV\n stark_fwhm = lorentz_5_2_D62_C_coeff * (ne_prof**lorentz_5_2_D62_a_coeff)\n\n # Sum up stark contributions\n # wv_pts = 100\n # wave = np.linspace(-0.1, 0.1, wv_pts)\n spectra_sum = np.zeros(len(wave))\n for i in range(len(x)):\n spectrum = (1. / (np.abs(wave)**(5. / 2.) + (stark_fwhm[i] / 2.)**(5. / 2.))) * ne_prof[i]*ne_prof[i]\n ax[1].semilogy(wave, spectrum, '-b')\n spectra_sum += spectrum\n\n noisy_spectrum = spectra_sum * (1. + noiseamp * (np.random.rand(len(wave)) - 0.5))\n\n ax[1].semilogy(wave, noisy_spectrum, '-k')\n plt.show()\n\n hwhm_idx, hwhm_val = np_find_nearest(spectra_sum, 0.5*np.max(spectra_sum))\n corr_fac = 1.04 # broaden wings\n # print(hwhm_idx)\n line_int_fwhm = np.abs(corr_fac*2.*wave[hwhm_idx])\n # print(line_int_fwhm)\n line_int_ne = (line_int_fwhm/lorentz_5_2_D62_C_coeff)**(1./lorentz_5_2_D62_a_coeff)\n # compare to line integrated spectra\n fit_spectrum = (1. / (np.abs(wave) ** (5. / 2.) + (line_int_fwhm / 2.) ** (5. / 2.)))\n ax[1].semilogy(wave, fit_spectrum , '--r')\n\n return spectra_sum\n\nclass JetDivSpecBayes:\n\n def __init__(self, obs_data=None):\n self.obs_data = obs_data\n self.x = np.linspace(-0.5, 0.5, 100)\n def do_inference(self):\n model = pm3.Model()\n with model:\n # Uniform priors\n ne_prof_amp = pm3.Uniform(\"ne_prof_amp\", 1.e19, 1.e21)\n ne_prof_std = pm3.Uniform(\"ne_prof_std\", 0.01, 0.5)\n te_prof_m = pm3.Uniform(\"te_prof_m\", -1.9, 0)\n\n # likelihood\n stark_spec = StarkForwardModel(self)(ne_prof_amp, ne_prof_std)\n fffb = ContinuoForwardModel(self)(ne_prof_amp, ne_prof_std, te_prof_m)\n\n L = pm3.Normal(\"obs_stark\", mu=stark_spec, sd=0.05 * stark_spec, observed=self.obs_data['stark_spec'])\n L2 = pm3.Normal(\"obs_fffb\", mu=fffb, sd=0.05*fffb, observed=self.obs_data['fffb'])\n\n step = pm3.Metropolis()\n trace = pm3.sample(5000, step=step)\n\n pm3.traceplot(trace)\n plt.show()\n ne_prof_std_samples = trace['ne_prof_std']\n ne_prof_amp_samples = trace['ne_prof_amp']\n te_prof_m_samples = trace['te_prof_m']\n\n plt.plot(ne_prof_amp_samples[2000:], ne_prof_std_samples[2000:], '.')\n plt.show()\n plt.plot(ne_prof_amp_samples[2000:], te_prof_m_samples[2000:], '.')\n plt.show()\n plt.plot(ne_prof_std_samples[2000:], te_prof_m_samples[2000:], '.')\n plt.show()\n\nclass StarkForwardModel(theano.gof.Op):\n itypes = [theano.tensor.dscalar,\n theano.tensor.dscalar]\n otypes = [theano.tensor.dvector]\n\n def __init__(self, cp):\n self.cp = cp # note cp is an instance of the 'JetDivSpecBayes' class\n\n def perform(self, node, inputs, outputs):\n ne_prof_amp_rand, ne_prof_std_rand = inputs[0], inputs[1]\n x = self.cp.x\n wave = self.cp.obs_data['wave_stark']\n\n # Stark broadening coefficients (Lomanowski et al 2015, NF)\n # lorentz_5_2_coeffs_D62 = {'C': 3.954E-16, 'a': 0.7149, 'b': 0.028}\n lorentz_5_2_D62_C_coeff = 3.954E-16\n lorentz_5_2_D62_a_coeff = 0.7149\n\n ne_prof = np.abs(ne_prof_amp_rand) * np.exp(-1. * (x ** 2) / (2 * (np.abs(ne_prof_std_rand) ** 2)))\n\n # Determine Stark FWHM\n # In the first instance, assume that D-delta is recombination dominated and that Te is constant,\n # so the emission along the LOS is weighted by ne*ne only.\n # Te_const = 1. # eV\n stark_fwhm = lorentz_5_2_D62_C_coeff * (ne_prof ** lorentz_5_2_D62_a_coeff)\n\n # Sum up stark contributions\n spectra_sum = np.zeros(len(wave))\n for i in range(len(x)):\n spectrum = (1. / (np.abs(wave) ** (5. / 2.) + (stark_fwhm[i] / 2.) ** (5. / 2.))) * ne_prof[i] * ne_prof[i]\n spectra_sum += spectrum\n\n # corr_fac = 1.04 # broaden wings\n # line_int_fwhm = np.abs(corr_fac * 2. * wave[(np.abs(spectra_sum - 0.5 * np.max(spectra_sum))).argmin()])\n # line_int_ne = (line_int_fwhm / lorentz_5_2_D62_C_coeff) ** (1. / lorentz_5_2_D62_a_coeff)\n\n outputs[0][0] = spectra_sum\n\n\nclass ContinuoForwardModel(theano.gof.Op):\n itypes = [theano.tensor.dscalar,\n theano.tensor.dscalar,\n theano.tensor.dscalar]\n otypes = [theano.tensor.dvector]\n\n def __init__(self, cp):\n self.cp = cp # note cp is an instance of the 'JetDivSpecBayes' class\n\n def perform(self, node, inputs, outputs):\n ne_prof_amp_rand, ne_prof_std_rand, te_prof_m_rand = inputs[0], inputs[1], inputs[2]\n x = self.cp.x\n wave = self.cp.obs_data['wave_fffb']\n\n Te_prof = te_prof_m_rand*x + 1\n ne_prof = np.abs(ne_prof_amp_rand) * np.exp(-1. * (x ** 2) / (2 * (np.abs(ne_prof_std_rand) ** 2)))\n\n contff, contin = adas_continuo_py(wave, Te_prof) # ph cm^3 s^-1 A^-1\n\n contin_sum = np.zeros(len(wave))\n dx = x[1] - x[0] # assume uniform grid\n for ix, vx in enumerate(x):\n contin_sum += ne_prof[ix] * ne_prof[ix] * dx * (1. / (4 * np.pi)) * contin[ix, :] * \\\n (1.0e-06) * 10.0 # ph s-1 m^-2 sr-1 nm-1\n\n # idx1, = np.where(np.logical_and(wave_nm > 340, wave_nm < 342))\n # idx2, = np.where(np.logical_and(wave_nm > 355, wave_nm < 357))\n # idx3, = np.where(np.logical_and(wave_nm > 392, wave_nm < 394))\n # idx4, = np.where(np.logical_and(wave_nm > 419, wave_nm < 421))\n # fffb_forward = np.array((contin_obs[idx1].mean(), contin_obs[idx2].mean(),\n # contin_obs[idx3].mean(), contin_obs[idx4].mean()))\n\n outputs[0][0] = contin_sum\n\ndef gen_continuo_noisy_data(Te_prof, ne_prof, x, wave_nm = np.linspace(340,440,100), noiseamp = 0.25):\n plt.plot(x, Te_prof)\n plt.show()\n plt.plot(x, ne_prof)\n plt.show()\n\n contff, contin = adas_continuo_py(wave_nm, Te_prof) # ph cm^3 s^-1 A^-1\n contff_sum = np.zeros(len(wave_nm))\n contin_sum = np.zeros(len(wave_nm))\n dx = x[1]-x[0] # assume uniform grid\n for ix, vx in enumerate(x):\n contff_sum += ne_prof[ix]*ne_prof[ix] * dx * (1. / (4 * np.pi)) * contff[ix, :] * (1.0e-06) * 10.0 # ph s-1 m^-2 sr-1 nm-1\n contin_sum += ne_prof[ix]*ne_prof[ix] * dx * (1. / (4 * np.pi)) * contin[ix, :] * (1.0e-06) * 10.0 # ph s-1 m^-2 sr-1 nm-1\n # plt.semilogy(wave_nm, contin_sum, 'k')\n #\n # plt.semilogy(wave_nm, contin_sum, 'r')\n # plt.show()\n\n contff_noisy = contff_sum*(1. + noiseamp*(np.random.rand(len(wave_nm))-0.5) )\n contin_noisy = contin_sum*(1. + noiseamp*(np.random.rand(len(wave_nm))-0.5) )\n # plt.semilogy(wave_nm, contin_noisy, '-', mfc='none')\n # plt.show()\n return contff_noisy, contin_noisy\n\nif __name__=='__main__':\n\n\n fig, ax = plt.subplots(ncols=2)\n\n x = np.linspace(-0.5, 0.5, 100)\n\n wave_fffb = np.linspace(340, 440, 100)\n wave_stark = np.linspace(-0.5, 0.5, 100)\n true_ne_prof_amp = 1.e20\n true_ne_prof_std = 0.2\n true_te_prof_m = -1.5\n true_stark_spec = gen_stark_noisy_data(true_ne_prof_amp, true_ne_prof_std, x, wave_stark, ax, noiseamp=0.1)\n\n contff_obs, contin_obs = gen_continuo_noisy_data(linear(true_te_prof_m, 1, x),\n gaussian(0, x, true_ne_prof_amp, true_ne_prof_std),\n x, wave_nm=wave_fffb, noiseamp=0.05)\n\n # idx1, = np.where(np.logical_and(wave_nm > 340, wave_nm < 342))\n # idx2, = np.where(np.logical_and(wave_nm > 355, wave_nm < 357))\n # idx3, = np.where(np.logical_and(wave_nm > 392, wave_nm < 394))\n # idx4, = np.where(np.logical_and(wave_nm > 419, wave_nm < 421))\n # fffb_obs = np.array((contin_obs[idx1].mean(), contin_obs[idx2].mean(), contin_obs[idx3].mean(), contin_obs[idx4].mean()))\n # fffb_obs_err = np.array((contin_obs[idx1].std(), contin_obs[idx2].std(), contin_obs[idx3].std(), contin_obs[idx4].std()))\n\n plt.semilogy(wave_fffb, contin_obs, '-k')\n # plt.errorbar([341, 356, 392, 420], fffb_obs, yerr = fffb_obs_err)\n plt.show()\n\n ###############################################\n # pymc3 implementation\n data = {\n 'wave_stark': wave_stark,\n 'stark_spec': true_stark_spec,\n 'wave_fffb': wave_fffb,\n 'fffb': contin_obs\n }\n\n obj = JetDivSpecBayes(obs_data=data)\n obj.do_inference()\n\n\n\n\n # GET SYNTHETIC DATA\n # pulse = 90423\n # work_dir = 'data/'\n # synth_spec_dict = {'synth_diag':None,\n # 'proc_synth_diag':work_dir + 'synth_data_e2deir_cstavrou_may1117_seq2.proc.json'\n # }\n # o = jet_div_spec(pulse, synth_spec_dict=synth_spec_dict)\n #\n # # Plot ne, Te along spectral chord\n #\n # fig, ax = plt.subplots(nrows=4, ncols=1, figsize=(5, 9), sharex=True)\n # left = 0.2 # the left side of the subplots of the figure\n # right = 0.95 # the right side of the subplots of the figure\n # bottom = 0.1 # the bottom of the subplots of the figure\n # top = 0.95 # the top of the subplots of the figure\n # wspace = 0.18 # the amount of width reserved for blank space between subplots\n # hspace = 0.1 # the amount of height reserved for white space between subplots\n # plt.subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace)\n #\n # spec = 'KT3A'\n # chord = '15'\n # dl = o.synth_spec.proc_diag[spec][chord]['los_1d']['l']\n # ne = o.synth_spec.proc_diag[spec][chord]['los_1d']['ne']\n # n0 = o.synth_spec.proc_diag[spec][chord]['los_1d']['n0']\n # te = o.synth_spec.proc_diag[spec][chord]['los_1d']['te']\n # d62exc = o.synth_spec.proc_diag[spec][chord]['los_1d']['H_emiss']['4101.2']['excit']\n # d62rec = o.synth_spec.proc_diag[spec][chord]['los_1d']['H_emiss']['4101.2']['recom']\n # d72exc = o.synth_spec.proc_diag[spec][chord]['los_1d']['H_emiss']['3969.5']['excit']\n # d72rec = o.synth_spec.proc_diag[spec][chord]['los_1d']['H_emiss']['3969.5']['recom']\n # d32exc = o.synth_spec.proc_diag[spec][chord]['los_1d']['H_emiss']['6561.9']['excit']\n # d32rec = o.synth_spec.proc_diag[spec][chord]['los_1d']['H_emiss']['6561.9']['recom']\n #\n # contff, contin = adas_continuo_py(400.0, te) # ph cm^3 s^-1 A^-1\n # contin = contin[:,0]*ne*ne * dl * (1. / (4 * np.pi)) * (1.0e-06) * 10.0 # ph s-1 m^-2 sr-1 nm-1\n #\n # ax[0].plot(dl,ne,'-k')\n # ax[0].plot(dl,n0,'--k')\n # ax[1].plot(dl,te,'-k')\n # ax[3].plot(dl,d72exc,'-r')\n # ax[3].plot(dl,d72rec,'-b')\n # ax[3].plot(dl,np.asarray(d72rec) + np.asarray(d72exc),'-k')\n # ax[2].plot(dl,contin,'-r')\n # # ax[3].plot(dl,d32rec,'-b')\n #\n # plt.show()","sub_path":"synth_fits_sandbox.py","file_name":"synth_fits_sandbox.py","file_ext":"py","file_size_in_byte":12248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"266124667","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport configparser\nimport requests\nimport random\nimport datetime\n\nCONFIG_NAME = \"setting.conf\"\nSECTION_NAME = \"conf\"\nURL_NAME = \"weixin_url\"\nNORMAL_DESC_NAME = \"normal_desc\"\nUP_DESC_NAME = \"up_desc\"\nUP_WEEKDAY_NAME = \"up_weekday\"\nTARGET_URL = \"target_url\"\nPIC_URL = \"pic_url\"\n\nconf = configparser.ConfigParser()\nconf.read(os.path.join(os.getcwd(), CONFIG_NAME), encoding='utf-8')\ndesc = conf.get(SECTION_NAME, NORMAL_DESC_NAME)\nif datetime.datetime.now().weekday() == conf.getint(SECTION_NAME, UP_WEEKDAY_NAME):\n desc = conf.get(SECTION_NAME, UP_DESC_NAME)\ntarget_url = conf.get(SECTION_NAME, TARGET_URL)\npic_url = conf.get(SECTION_NAME, PIC_URL)\n\nheaders = {\"Content-Type\": \"application/json\"}\ndata = {\n \"msgtype\": \"news\",\n \"news\": {\n \"articles\" : [\n {\n \"title\" : \"点餐提醒\",\n \"description\" : desc,\n \"url\" : target_url,\n \"picurl\" : pic_url\n }\n ]\n }\n}\n\nurl = conf.get(SECTION_NAME, URL_NAME)\n\ntry:\n r = requests.post(\n url=url,\n headers=headers,\n json=data)\nexcept Exception as err:\n print (\"Err: \", err)","sub_path":"weixinbot/meican/meican.py","file_name":"meican.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"573927091","text":"# ===== problem description =====\n# https://www.hackerrank.com/challenges/py-set-discard-remove-pop/problem\n\n# .remove(x)\n# This operation removes element from the set.\n# If element does not exist, it raises a KeyError.\n# The .remove(x) operation returns None.\n\n# Example\n\n# >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])\n# >>> s.remove(5)\n# >>> print s\n# set([1, 2, 3, 4, 6, 7, 8, 9])\n# >>> print s.remove(4)\n# None\n# >>> print s\n# set([1, 2, 3, 6, 7, 8, 9])\n# >>> s.remove(0)\n# KeyError: 0\n# .discard(x)\n# This operation also removes element from the set.\n# If element does not exist, it does not raise a KeyError.\n# The .discard(x) operation returns None.\n\n# Example\n\n# >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])\n# >>> s.discard(5)\n# >>> print s\n# set([1, 2, 3, 4, 6, 7, 8, 9])\n# >>> print s.discard(4)\n# None\n# >>> print s\n# set([1, 2, 3, 6, 7, 8, 9])\n# >>> s.discard(0)\n# >>> print s\n# set([1, 2, 3, 6, 7, 8, 9])\n# .pop()\n# This operation removes and return an arbitrary element from the set.\n# If there are no elements to remove, it raises a KeyError.\n\n# Example\n\n# >>> s = set([1])\n# >>> print s.pop()\n# 1\n# >>> print s\n# set([])\n# >>> print s.pop()\n# KeyError: pop from an empty set\n# Task\n# You have a non-empty set , and you have to execute commands given in lines.\n\n# The commands will be pop, remove and discard.\n\n# Input Format\n\n# The first line contains integer , the number of elements in the set .\n# The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9.\n# The third line contains integer , the number of commands.\n# The next lines contains either pop, remove and/or discard commands followed by their associated value.\n\n# Constraints\n\n\n\n# Output Format\n\n# Print the sum of the elements of set on a single line.\n\n# Sample Input\n\n# 9\n# 1 2 3 4 5 6 7 8 9\n# 10\n# pop\n# remove 9\n# discard 9\n# discard 8\n# remove 7\n# pop \n# discard 6\n# remove 5\n# pop \n# discard 5\n# Sample Output\n\n# 4\n# Explanation\n\n# After completing these operations on the set, we get set. Hence, the sum is .\n\n# Note: Convert the elements of set s to integers while you are assigning them. \n# To ensure the proper input of the set, we have added the first two lines of code to the editor.\n\n# ========== design ==========\n# get the number of elements \n# get input array of string; map magic convert to int array and set \n# get the number of commands\n# set method practice \n# error handling to avoid pop empty error is handled with try-exception \n\n# ========== implementation ========== \nn = int(input())\nst_i = set(map(int, input().split()))\nN = int(input())\n\ntry:\n for i in range(N):\n print(st_i) \n #get user input for command and optional index\n arr = input().split()\n command = arr[0]\n if command == 'remove':\n st_i.remove(int(arr[1]))\n elif command == 'discard':\n st_i.discard(int(arr[1]))\n elif command == 'pop':\n st_i.pop()\n \n\n sum = st_i.pop()\n while len(st_i) > 0:\n sum += st_i.pop() \n print(sum)\nexcept KeyError as e:\n print('0')\nfinally:\n pass\n","sub_path":"set-disard-remove-pop.py","file_name":"set-disard-remove-pop.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"589647107","text":"from random import *\nn = 0 # No. of Games Played\nusr_score = 0 # No. of times user won\ncpu_score = 0 # No. of times cpu won\ndraws = 0 # No. of draws\n\nl = [\"stone\", \"paper\", \"scissors\"]\n\nprint(\"Enter Your Choice : \")\nprint(\"Stone \\nPaper \\nScissors\")\n\nwhile n < 10: # you'll get 10 chances\n cpu_choice = choice(l)\n usr_choice = input(\">>>>> \").lower()\n\n if usr_choice == \"stone\":\n if cpu_choice == \"stone\":\n print(\"Draw\")\n draws += 1\n n += 1\n elif cpu_choice == \"paper\":\n print(\"You Lost\")\n cpu_score += 1\n n += 1\n else:\n print(\"You Won\")\n n += 1\n usr_score += 1\n elif usr_choice == \"paper\":\n if cpu_choice == \"paper\":\n print(\"Draw\")\n draws += 1\n n+=1\n elif cpu_choice == \"scissors\":\n print(\"You Lost\")\n cpu_score += 1\n n += 1\n else:\n print(\"You Won\")\n n += 1\n usr_score += 1\n elif usr_choice == \"scissors\":\n if cpu_choice == \"scissors\":\n print(\"Draw\")\n draws += 1\n n += 1\n elif cpu_choice == \"stone\":\n print(\"You Lost\")\n cpu_score += 1\n n += 1\n else:\n print(\"You Won\")\n n += 1\n usr_score += 1\n else:\n print(\"Invalid choice\")\n continue\n\nprint(\"No. of Draws :\", draws)\nprint(\"No. of times user won :\", usr_score)\nprint(\"No. of times cpu won :\", cpu_score)\nprint(\"User won\") if usr_score > cpu_score else print(\"Cpu Won\")\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"506252674","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import storage\nfrom firebase_admin import db\nimport time\nimport face_recognition\nimport numpy as np\nimport uuid\nimport datetime\nimport os\n\n\ncred = credentials.ApplicationDefault()\nfirebase_admin.initialize_app(cred, {\n 'projectId': \"iotfinal-a2cfe\",\n 'databaseURL': \"https://iotfinal-a2cfe.firebaseio.com\",\n 'storageBucket': \"iotfinal-a2cfe.appspot.com\"\n})\n\nprocessed_dic = db.reference('people').get()\nprocessed = []\nprocessed_data = []\nif processed_dic:\n for key, item in processed_dic.items():\n processed.append(np.array(item['encoding']))\n item['id'] = key\n processed_data.append(item)\nelse:\n processed_dic = {}\n\n\n\nwhile(1):\n unprocessed = db.reference('unprocessed').get()\n if not unprocessed:\n time.sleep(60)\n else:\n for key, item in unprocessed.items():\n print('PROCESSING FACE')\n db.reference('unprocessed').child(key).delete()\n db.reference('identified').child(key).set(item)\n encoding = np.array(item['encoding'])\n best_match = 2\n if processed:\n bm_index = 0\n for poc_indexm, poc_encoding in enumerate(processed):\n fc_val = face_recognition.face_distance([poc_encoding], encoding)\n if fc_val < best_match:\n bm_index = poc_indexm\n best_match = fc_val\n if best_match < .56:\n person = processed_data[bm_index]\n person['visits'][key] = item\n person['visits'][key].pop('encoding')\n person_db = db.reference('people').child(processed_data[bm_index]['id']).get()\n db.reference('people').child(processed_data[bm_index]['id']).child('visits').set(person['visits'])\n else:\n id = str(str(uuid.uuid4()))\n info = {}\n info['visits'] = {key: item}\n info['visits'][key].pop('encoding')\n info['name'] = 'unkown'\n info['encoding'] = encoding.tolist()\n db.reference('people').child(id).set(info)\n processed.append(encoding)\n info['encoding'] = encoding\n info['id'] = id\n processed_data.append(info)\n\n\n\n\n\n","sub_path":"Scripts/FaceServer_OLD.py","file_name":"FaceServer_OLD.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"583471210","text":"people_info = {\n 'jack': {'last_name': 'lore',\n 'age': 23,\n 'city': 'wuhan'},\n 'clark': {'last_name': 'cline',\n 'age': 29,\n 'city': 'xian'}\n}\nfor name, info in people_info.items():\n print(name.title() + \" \" + info['last_name'].title())\n print(\"\\t\" + str(info['age']))\n print(\"\\t\" + info['city'].title())\n","sub_path":"python_carsh_course/ch06/6_1.py","file_name":"6_1.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"51338145","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 13 14:49:20 2018\n\n@author: prasad\n@Roll No.: CMS1731\n\"\"\"\n\"\"\"Genetic Algorithm for Feature Selection using constrains\"\"\"\n\n\"Import Libraries\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn import datasets,preprocessing,svm\nfrom sklearn.metrics import confusion_matrix\n\n\"SVM Cross Validation Function\"\ndef CrossValidation(data,y):\n fold = 5\n shuf = np.random.choice(fold,len(data),replace=True)\n accuracy = []\n for i in np.arange(fold):\n \"divide data into test and train\"\n X_test = data.iloc[np.where(shuf == i)]\n X_train = data.iloc[np.where(shuf != i)]\n y_test = y[np.where(shuf == i)]\n y_train = y[np.where(shuf != i)]\n \"Create model for SVM\"\n model = svm.SVC(C = 1.0,kernel = \"rbf\")\n \"fit train data in model\"\n model.fit(X_train,y_train)\n \"predict test data using fitted model\"\n pred = model.predict(X_test)\n \"find accuracy for model\"\n Acc = model.score(X_test,y_test)\n \"Confusion matrix\"\n cm = confusion_matrix(y_test,pred)\n \"constrains: penalty for wrongly predicted examples\"\n wrongPred = (sum(sum(cm)) - sum(np.diag(cm))) / len(y_test)\n acc = Acc - wrongPred\n accuracy.append(acc)\n return(np.mean(accuracy))\n \n\"Removing population with all zeros i.e. no attributes selected\"\ndef CheckforNullPopulation(population):\n i = 0\n while(i < len(population)):\n if sum(population[i]) == 0:\n population.pop(i)\n i += 1\n return population\n\n\"Tournament Selection function\"\ndef TournamentSelection(fitness,population,newPopulationSize):\n fitterSolutions = []\n while True:\n p1 = fitness[np.random.randint(newPopulationSize)]\n p2 = fitness[np.random.randint(newPopulationSize)]\n \n if p1 >= p2:\n fitterSolutions.append(p1)\n \n if len(fitterSolutions) == len(fitness):\n break\n \n fitterSolutionsIndex = []\n for i in np.arange(len(fitterSolutions)):\n fitterSolutionsIndex.append(np.where(fitterSolutions[i] == fitness)[0][0])\n \n newSolution = []\n for i in np.arange(len(fitterSolutionsIndex)):\n newSolution.append(population[fitterSolutionsIndex[i]])\n return fitterSolutions , newSolution\n\n\"Crossover function\"\ndef Crossover(newSolution,bitSize,newPopulationSize):\n CrossOveredExamples = []\n while True: \n splitJunction = np.random.randint(bitSize-1)\n p1 = newSolution[np.random.randint(newPopulationSize)]\n p2 = newSolution[np.random.randint(newPopulationSize)]\n \n if splitJunction >= bitSize:\n CrossOveredExamples.append(np.append(p1[:splitJunction],p2[splitJunction:]))\n else: \n CrossOveredExamples.append(np.append(p1[splitJunction:],p2[:splitJunction]))\n \n CrossOveredExamples = CheckforNullPopulation(CrossOveredExamples)\n if len(CrossOveredExamples) == len(newSolution):\n break\n return CrossOveredExamples\n\n\"Mutation function\"\ndef Mutation(CrossOveredExamples,newPopulationSize,bitSize,mutationProbability,newSolution):\n mutatePopulation = []\n while True:\n mutationExample = CrossOveredExamples[np.random.randint(newPopulationSize)]\n flip = []\n for i in np.arange(bitSize):\n if np.random.uniform(0,(mutationProbability+0.01)) < mutationProbability:\n flip.append(abs(mutationExample[i] - 1))\n else:\n flip.append(mutationExample[i])\n mutatePopulation.append(np.array(flip))\n mutatePopulation = CheckforNullPopulation(mutatePopulation)\n if len(mutatePopulation) == len(newSolution):\n break \n return mutatePopulation\n\n\"Import datasets\"\ndata = pd.DataFrame(preprocessing.scale(datasets.load_iris().data))\ny = pd.factorize(datasets.load_iris().target)[0]\n\n\"Best subset and best accuracy finding function\"\ndef BestSubset(data,y,population):\n fitness = []\n for i in range(len(population)):\n SampleData = (data.drop((np.where(population[i]==0)[0]),axis=1))\n fitness.append(CrossValidation(SampleData,y))\n\n BestSubsetAccuracy = max(fitness)\n bestSubset = population[np.where(BestSubsetAccuracy == fitness)[0][0]]\n return bestSubset,BestSubsetAccuracy\n\n\"Main function\"\ndef GA():\n \"Define Parameters\"\n PopulationSize = 5\n bitSize = data.shape[1]\n population = []\n crossoverProbability = 0.7\n mutationProbability = 1 / PopulationSize\n \n \"Creating population\"\n for i in np.arange(PopulationSize):\n population.append(np.random.randint(low = 0,high = 2,size = bitSize))\n \n population = CheckforNullPopulation(population)\n newPopulationSize = len(population)\n #print(newPopulationSize)\n \n iter = 0\n \"Creating generations\"\n for k in range(10):\n iter += 1\n print(iter)\n \"Finding fitness ; here it is cv-accuracy using SVM\"\n fitness = []\n for i in range(len(population)):\n SampleData = (data.drop((np.where(population[i]==0)[0]),axis=1))\n fitness.append(CrossValidation(SampleData,y))\n \n \"Tournament Selection\" \n fitterSolutions , newSolution = TournamentSelection(fitness,population,newPopulationSize)\n \n \"Crossover\"\n CrossOveredExamples = Crossover(newSolution,bitSize,newPopulationSize)\n \n \"Mutation\"\n mutatePopulation = Mutation(CrossOveredExamples,newPopulationSize,bitSize,mutationProbability,newSolution)\n \n population = mutatePopulation\n \n \"Finding Best Subset\"\n bestSubset, BestSubsetAccuracy = BestSubset(data,y,population)\n return bestSubset, BestSubsetAccuracy\n\nbestSubset , BestSubsetAccuracy = GA()\nprint(\"Best subset is \",bestSubset ,\"and corrosponding accuracy is\" ,BestSubsetAccuracy)\n","sub_path":"GeneticAlgorithm/ConstrainGA/FeatureSelectionGA.py","file_name":"FeatureSelectionGA.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"72033278","text":"from runner import judge\nimport threading\nimport time\nclass Result:\n\tdef __init__(self):\n\t\tself.stat = []\n\t\tself.tot = 0\n\t\tself.lock = threading.Lock()\n\tdef add(self, x, score):\n\t\tself.lock.acquire()\n\t\tx[0] *= score\n\t\tself.tot += x[0]\n\t\tself.stat.append(x[1])\n\t\tself.lock.release()\n\tdef get(self):\n\t\treturn self.tot, self.stat\n\nclass JobQueue(threading.Thread):\n\tdef __init__(self):\n\t\tsuper(JobQueue, self).__init__()\n\t\tself.joblist = []\n\tdef add(self, job):\n\t\tself.joblist.append(job)\n\tdef run(self):\n\t\t#print('start run')\n\t\tfor job in self.joblist:\n\t\t\tjob.run()\n\nclass Job:\n\tdef __init__(self, code, ins, outs, res, score, _id):\n\t\tself.code = code\n\t\tself.ins = ins\n\t\tself.outs = outs\n\t\tself.res = res\n\t\tself.score = score\n\t\tself.id = _id\n\tdef run(self):\n\t\t#print('run job', self.id, 'code = ', self.code)\n\t\tx, info = judge(self.code, self.ins, self.outs)\n\t\tself.res.add([x, info], self.score)\n\t\t#print('job', self.id, 'finish')\n\t\t\n\ndef Task(ProgramDic, IOList, threads=1):\n\tcodeDic = {}\n\tfor auther, prog in ProgramDic.items():\n\t\tf = open(prog, 'r')\n\t\tcodeDic[auther] = f.read()\n\t\tf.close()\n\tsum, tt = 0, 0\n\tfor io in IOList:\n\t\ttry:\n\t\t\tsum += io[2]\n\t\texcept:\n\t\t\ttt += 1\n\tavr = (100-sum)/tt\n\tiolist = []\n\tfor io in IOList:\n\t\tfi = open(io[0], 'r')\n\t\tfo = open(io[1], 'r')\n\t\t#print(io[0], io[1])\n\t\tsi = fi.read().split()\n\t\tso = fo.read()\n\t\ttry:\n\t\t\tiolist.append((si, so, io[2]))\n\t\texcept:\n\t\t\tiolist.append((si, so, avr))\n\t\t#print(iolist[-1])\n\t\tfi.close()\n\t\tfo.close()\n\n\tjoblist = [JobQueue() for i in range(threads)]\n\tindex = 0\n\tresDic = {}\n\t_id = 0\n\tfor auther, code in codeDic.items():\n\t\tresDic[auther] = Result()\n\t\t#print('author:'+auther+'\\n', code, '\\n')\n\t\tfor io in iolist:\n\t\t\t#print(io[0], io[1])\n\t\t\tjoblist[index].add(Job(code, io[0], io[1], resDic[auther], io[2], _id))\n\t\t\t_id += 1\n\t\t\tindex = (index+1) % threads\n\tfor i in range(threads):\n\t\tjoblist[i].start()\n\tfor i in range(threads):\n\t\tjoblist[i].join()\n\tfor k, v in resDic.items():\n\t\tresDic[k] = v.get()\n\treturn resDic\n\nif __name__ == \"__main__\":\n\tproglist = {'std':'example/test/1volume/std.py', 'strange':'example/test/1volume/strange.py', 'wrong':'example/test/1volume/wrong.py'}\n\tiolist = [\n\t\t('example/test/1volume/0.in', 'example/test/1volume/0.ans'), \n\t\t('example/test/1volume/1.in', 'example/test/1volume/1.ans'), \n\t\t('example/test/1volume/2.in', 'example/test/1volume/2.ans'), \n\t\t('example/test/1volume/3.in', 'example/test/1volume/3.ans'), \n\t\t('example/test/1volume/4.in', 'example/test/1volume/4.ans'), \n\t]\n\t#iolist = iolist \n\tstart = time.time()\n\tresFullDic = Task(proglist, iolist)\n\tprint('time = ', time.time()-start)\n\tfor k, v in resFullDic.items():\n\t\tprint(k+' '*(10-len(k)), v[0])\n\t","sub_path":"easy_judge/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"20232472","text":"import numpy as np\nfrom sklearn.feature_selection import SelectFromModel, SelectKBest, mutual_info_classif\nfrom sklearn.linear_model import LogisticRegression\n\npath_to_selected_features = './res/MIFSLR_features.txt'\n\n\nclass MIFSLR(LogisticRegression):\n\n def __init__(self, penalty='l2', dual=False, tol=1e-4, C=1.0,\n fit_intercept=True, intercept_scaling=1, class_weight=None,\n random_state=None, solver='liblinear', max_iter=100,\n multi_class='ovr', verbose=0, warm_start=False, n_jobs=1, k=1000):\n\n super(MIFSLR, self).__init__(penalty, dual, tol, C, fit_intercept, intercept_scaling, class_weight, random_state,\n solver, max_iter, multi_class, verbose, warm_start, n_jobs)\n self.mifs = SelectKBest(mutual_info_classif, k=k)\n # self.dummy = DummyClassifier()\n\n def fit(self, X, y, sample_weight=None):\n self.mifs.fit(X, y)\n # with open(path_to_selected_features, 'a') as f:\n # f_list = []\n # for i in self.model.get_support(True):\n # f_list.append(str(i))\n # f.write(';'.join(f_list) + '\\n')\n X_new = self.mifs.transform(X)\n # if X_new.shape[1] == 0:\n # X_new = np.zeros(shape=(X_new.shape[0], 1))\n super(MIFSLR, self).fit(X_new, y, sample_weight)\n return self\n\n def predict_proba(self, X):\n X_new = self.mifs.transform(X)\n # if X_new.shape[1] == 0:\n # X_new = np.zeros(shape=(X_new.shape[0], 1))\n return super(MIFSLR, self).predict_proba(X_new)\n\n def decision_function(self, X):\n X_new = self.mifs.transform(X)\n # if X_new.shape[1] == 0:\n # X_new = np.zeros(shape=(X_new.shape[0], 1))\n return super(MIFSLR, self).decision_function(X_new)\n","sub_path":"ml_methods/mifslr.py","file_name":"mifslr.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"503817456","text":"from flask import Flask, render_template, request, Response\n\nfrom forms import IncomeInputForm, ExpenseInputForm\n\nfrom db import config, connect\n\napp = Flask(__name__)\nconn, cur = connect()\n\n\n@app.route(\"/\")\ndef default_form():\n return render_template(\n \"index.html\", expense_form=ExpenseInputForm(), income_form=IncomeInputForm()\n )\n\n\n@app.route(ExpenseInputForm.route, methods=[\"POST\"])\ndef handle_expense_submit():\n global cur\n\n values = dict(request.form.items())\n\n column_keys = [key for key in values.keys(\n ) if key in ExpenseInputForm.columns]\n column_values = [values[key] for key in column_keys]\n\n cur.execute(\n f\"INSERT INTO expenses ({', '.join(column_keys)}) \"\n f\"VALUES ({', '.join(column_values)})\"\n )\n\n return render_template(\"expense_submission.html\")\n\n\n@app.route(IncomeInputForm.route, methods=[\"POST\"])\ndef handle_income_submit():\n global cur\n\n values = dict(request.form.items())\n\n column_keys = [key for key in values.keys(\n ) if key in IncomeInputForm.columns]\n column_values = [values[key] for key in column_keys]\n\n cur.execute(\n f\"INSERT INTO expenses ({', '.join(column_keys)}) \"\n f\"VALUES ({', '.join(column_values)})\"\n )\n\n return render_template(\"income_submission.html\")\n\n\nif __name__ == \"__main__\":\n app.run(host=\"localhost\", port=\"9001\")\n conn.close()\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"220405026","text":"# -*- coding: utf-8 -*-\n\"\"\"\n.. module:: djstripe.settings.\n\n :synopsis: dj-stripe settings\n\n.. moduleauthor:: @kavdev, @pydanny, @lskillen, and @chrissmejia\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport sys\n\nfrom django.apps import apps as django_apps\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils import six\nfrom django.utils.module_loading import import_string\n\nPY3 = sys.version > \"3\"\n\n\ndef get_callback_function(setting_name, default=None):\n \"\"\"\n Resolve a callback function based on a setting name.\n\n If the setting value isn't set, default is returned. If the setting value\n is already a callable function, that value is used - If the setting value\n is a string, an attempt is made to import it. Anything else will result in\n a failed import causing ImportError to be raised.\n\n :param setting_name: The name of the setting to resolve a callback from.\n :type setting_name: string (``str``/``unicode``)\n :param default: The default to return if setting isn't populated.\n :type default: ``bool``\n :returns: The resolved callback function (if any).\n :type: ``callable``\n \"\"\"\n func = getattr(settings, setting_name, None)\n if not func:\n return default\n\n if callable(func):\n return func\n\n if isinstance(func, six.string_types):\n func = import_string(func)\n\n if not callable(func):\n raise ImproperlyConfigured(\"{name} must be callable.\".format(name=setting_name))\n\n return func\n\n\nsubscriber_request_callback = get_callback_function(\"DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK\",\n default=(lambda request: request.user))\n\naccount_holder_request_callback = get_callback_function(\"DJSTRIPE_ACCOUNT_HOLDER_MODEL_REQUEST_CALLBACK\",\n default=(lambda request: request.user))\n\nINVOICE_FROM_EMAIL = getattr(settings, \"DJSTRIPE_INVOICE_FROM_EMAIL\", \"billing@example.com\")\nPAYMENTS_PLANS = getattr(settings, \"DJSTRIPE_PLANS\", {})\nPLAN_HIERARCHY = getattr(settings, \"DJSTRIPE_PLAN_HIERARCHY\", {})\n\nPASSWORD_INPUT_RENDER_VALUE = getattr(settings, 'DJSTRIPE_PASSWORD_INPUT_RENDER_VALUE', False)\nPASSWORD_MIN_LENGTH = getattr(settings, 'DJSTRIPE_PASSWORD_MIN_LENGTH', 6)\n\nPRORATION_POLICY = getattr(settings, 'DJSTRIPE_PRORATION_POLICY', False)\nPRORATION_POLICY_FOR_UPGRADES = getattr(settings, 'DJSTRIPE_PRORATION_POLICY_FOR_UPGRADES', False)\nCANCELLATION_AT_PERIOD_END = not getattr(settings, 'DJSTRIPE_PRORATION_POLICY', False)\n\nSEND_INVOICE_RECEIPT_EMAILS = getattr(settings, \"DJSTRIPE_SEND_INVOICE_RECEIPT_EMAILS\", True)\nCURRENCIES = getattr(settings, \"DJSTRIPE_CURRENCIES\", (\n ('usd', 'U.S. Dollars',),\n ('gbp', 'Pounds (GBP)',),\n ('eur', 'Euros',))\n)\n\nDEFAULT_PLAN = getattr(settings, \"DJSTRIPE_DEFAULT_PLAN\", None)\n\n# Try to find the new settings variable first. If that fails, revert to the\n# old variable.\ntrial_period_for_subscriber_callback = (\n get_callback_function(\"DJSTRIPE_TRIAL_PERIOD_FOR_SUBSCRIBER_CALLBACK\") or\n get_callback_function(\"DJSTRIPE_TRIAL_PERIOD_FOR_USER_CALLBACK\"))\n\nDJSTRIPE_WEBHOOK_URL = getattr(settings, \"DJSTRIPE_WEBHOOK_URL\", r\"^webhook/$\")\n\n# Webhook event callbacks allow an application to take control of what happens\n# when an event from Stripe is received. One suggestion is to put the event\n# onto a task queue (such as celery) for asynchronous processing.\nWEBHOOK_EVENT_CALLBACK = get_callback_function(\"DJSTRIPE_WEBHOOK_EVENT_CALLBACK\")\n\n\ndef get_subscriber_model_string():\n \"\"\"Get the configured subscriber model as a module path string.\"\"\"\n return getattr(settings, \"DJSTRIPE_SUBSCRIBER_MODEL\", settings.AUTH_USER_MODEL)\n\n\ndef get_subscriber_model():\n \"\"\"\n Attempt to pull settings.DJSTRIPE_SUBSCRIBER_MODEL.\n\n Users have the option of specifying a custom subscriber model via the\n DJSTRIPE_SUBSCRIBER_MODEL setting.\n\n This methods falls back to AUTH_USER_MODEL if DJSTRIPE_SUBSCRIBER_MODEL is not set.\n\n Returns the subscriber model that is active in this project.\n \"\"\"\n model_name = get_subscriber_model_string()\n\n # Attempt a Django 1.7 app lookup\n try:\n subscriber_model = django_apps.get_model(model_name)\n except ValueError:\n raise ImproperlyConfigured(\"DJSTRIPE_SUBSCRIBER_MODEL must be of the form 'app_label.model_name'.\")\n except LookupError:\n raise ImproperlyConfigured(\"DJSTRIPE_SUBSCRIBER_MODEL refers to model '{model}' \"\n \"that has not been installed.\".format(model=model_name))\n\n if ((\"email\" not in [field_.name for field_ in subscriber_model._meta.get_fields()]) and\n not hasattr(subscriber_model, 'email')):\n raise ImproperlyConfigured(\"DJSTRIPE_SUBSCRIBER_MODEL must have an email attribute.\")\n\n if model_name != settings.AUTH_USER_MODEL:\n # Custom user model detected. Make sure the callback is configured.\n func = get_callback_function(\"DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK\")\n if not func:\n raise ImproperlyConfigured(\n \"DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK must be implemented \"\n \"if a DJSTRIPE_SUBSCRIBER_MODEL is defined.\")\n\n return subscriber_model\n\n\ndef get_account_holder_model_string():\n \"\"\"Get the configured subscriber model as a module path string.\"\"\"\n return getattr(settings, \"DJSTRIPE_ACCOUNT_HOLDER_MODEL\", settings.AUTH_USER_MODEL)\n\n\ndef get_account_holder_model():\n \"\"\"\n Attempt to pull settings.DJSTRIPE_ACCOUNT_HOLDER_MODEL.\n\n Users have the option of specifying a custom account holder model via the\n DJSTRIPE_ACCOUNT_HOLDER_MODEL setting.\n\n This methods falls back to AUTH_USER_MODEL if\n DJSTRIPE_ACCOUNT_HOLDER_MODEL is not set.\n\n Returns the account holder model that is active in this project.\n \"\"\"\n model_name = get_account_holder_model_string()\n\n # Attempt a Django 1.7 app lookup\n try:\n account_holder_model = django_apps.get_model(model_name)\n except ValueError:\n raise ImproperlyConfigured(\"DJSTRIPE_ACCOUNT_HOLDER_MODEL must be of the form 'app_label.model_name'.\")\n except LookupError:\n raise ImproperlyConfigured(\"DJSTRIPE_ACCOUNT_HOLDER_MODEL refers to model '{model}' \"\n \"that has not been installed.\".format(model=model_name))\n\n if ((\"email\" not in [field_.name for field_ in account_holder_model._meta.get_fields()]) and\n not hasattr(subscriber_model, 'email')):\n raise ImproperlyConfigured(\"DJSTRIPE_ACCOUNT_HOLDER_MODEL must have an email attribute.\")\n\n if model_name != settings.AUTH_USER_MODEL:\n # Custom user model detected. Make sure the callback is configured.\n func = get_callback_function(\"DJSTRIPE_ACCOUNT_HOLDER_MODEL_REQUEST_CALLBACK\")\n if not func:\n raise ImproperlyConfigured(\n \"DJSTRIPE_ACCOUNT_HOLDER_MODEL_REQUEST_CALLBACK must be implemented \"\n \"if a DJSTRIPE_ACCOUNT_HOLDER_MODEL is defined.\")\n\n return account_holder_model\n","sub_path":"djstripe/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"340490487","text":"# -*- coding: utf-8 -*-\n'''\nBuilds a Vega grammar specification from scratch\n'''\n\nimport vincent\n\nvis = vincent.Vega()\nvis.tabular_data((('A', 28), ('B', 55), ('C', 43), ('D', 91), ('E', 81), \n ('F', 53), ('G', 19), ('H', 87), ('I', 52)))\nvis.build_component(axes=[{\"type\":\"x\", \"scale\":\"x\"},{\"type\":\"y\", \"scale\":\"y\"}],\n scales=[{\"name\":\"x\", \"type\":\"ordinal\", \"range\":\"width\", \n \"domain\":{\"data\":\"table\", \"field\":\"data.x\"}},\n {\"name\":\"y\", \"range\":\"height\", \"nice\":True, \n \"domain\":{\"data\":\"table\", \"field\":\"data.y\"}}],\n marks=[{\"type\": \"rect\", \"from\": {\"data\": \"table\"},\n \"properties\": {\n \"enter\": {\n \"x\": {\"scale\": \"x\", \"field\": \"data.x\"},\n \"width\": {\"scale\": \"x\", \"band\": True,\n \"offset\": -1},\n \"y\": {\"scale\": \"y\", \"field\": \"data.y\"},\n \"y2\": {\"scale\": \"y\", \"value\": 0}\n },\n \"update\": {\"fill\": {\"value\": \"#2a3140\"}},\n \"hover\": {\"fill\": {\"value\": \"#a63737\"}}\n }}])\n\n#Generate both the Vega JSON and a data JSON. \npath = r'vega.json'\nvis.to_json(path, split_data=True, html=True)\n\n","sub_path":"examples/bar_fromscratch.py","file_name":"bar_fromscratch.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"186121960","text":"\n\nfrom xai.brain.wordbase.nouns._quirk import _QUIRK\n\n#calss header\nclass _QUIRKING(_QUIRK, ):\n\tdef __init__(self,): \n\t\t_QUIRK.__init__(self)\n\t\tself.name = \"QUIRKING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"quirk\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_quirking.py","file_name":"_quirking.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"109502427","text":"# Licensed to the StackStorm, Inc ('StackStorm') under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom collections import OrderedDict\n\nfrom mongoengine import ValidationError\nimport six\n\nfrom st2common import log as logging\nfrom st2common.constants.action import (ACTIONEXEC_STATUSES,\n ACTION_ID, ACTION_NAME, ACTION_PACK)\nfrom st2common.exceptions.db import StackStormDBObjectNotFoundError\nfrom st2common.models.system.common import ResourceReference\nfrom st2common.persistence.action import (RunnerType, Action, ActionExecution)\n\nLOG = logging.getLogger(__name__)\n\n\ndef get_runnertype_by_id(runnertype_id):\n \"\"\"\n Get RunnerType by id.\n\n On error, raise StackStormDBObjectNotFoundError\n \"\"\"\n try:\n runnertype = RunnerType.get_by_id(runnertype_id)\n except (ValueError, ValidationError) as e:\n LOG.warning('Database lookup for runnertype with id=\"%s\" resulted in '\n 'exception: %s', runnertype_id, e)\n raise StackStormDBObjectNotFoundError('Unable to find runnertype with '\n 'id=\"%s\"' % runnertype_id)\n\n return runnertype\n\n\ndef get_runnertype_by_name(runnertype_name):\n \"\"\"\n Get an runnertype by name.\n On error, raise ST2ObjectNotFoundError.\n \"\"\"\n try:\n runnertypes = RunnerType.query(name=runnertype_name)\n except (ValueError, ValidationError) as e:\n LOG.error('Database lookup for name=\"%s\" resulted in exception: %s',\n runnertype_name, e)\n raise StackStormDBObjectNotFoundError('Unable to find runnertype with name=\"%s\"'\n % runnertype_name)\n\n if not runnertypes:\n LOG.error('Database lookup for RunnerType with name=\"%s\" produced no results',\n runnertype_name)\n raise StackStormDBObjectNotFoundError('Unable to find RunnerType with name=\"%s\"'\n % runnertype_name)\n\n if len(runnertypes) > 1:\n LOG.warning('More than one RunnerType returned from DB lookup by name. '\n 'Result list is: %s', runnertypes)\n\n return runnertypes[0]\n\n\ndef get_action_by_id(action_id):\n \"\"\"\n Get Action by id.\n\n On error, raise StackStormDBObjectNotFoundError\n \"\"\"\n action = None\n\n try:\n action = Action.get_by_id(action_id)\n except (ValueError, ValidationError) as e:\n LOG.warning('Database lookup for action with id=\"%s\" resulted in '\n 'exception: %s', action_id, e)\n raise StackStormDBObjectNotFoundError('Unable to find action with '\n 'id=\"%s\"' % action_id)\n\n return action\n\n\ndef _get_action_by_pack_and_name(pack=None, name=None):\n \"\"\"\n Get Action by name and pack.\n\n Query doesn't raise an exception.\n \"\"\"\n return Action.query(name=name, pack=pack).first()\n\n\ndef get_actionexec_by_id(actionexec_id):\n \"\"\"\n Get ActionExecution by id.\n\n On error, raise ST2DBObjectNotFoundError.\n \"\"\"\n actionexec = None\n\n try:\n actionexec = ActionExecution.get_by_id(actionexec_id)\n except (ValidationError, ValueError) as e:\n LOG.error('Database lookup for actionexecution with id=\"%s\" resulted in '\n 'exception: %s', actionexec_id, e)\n raise StackStormDBObjectNotFoundError('Unable to find actionexecution with '\n 'id=\"%s\"' % actionexec_id)\n\n return actionexec\n\n\ndef get_action_by_dict(action_dict):\n \"\"\"\n Get Action object from DB based on action_dict values.\n\n action_dict is a dictionary that contains either an \"id\" field,\n a \"name\" field\", or both fields.\n\n Returns:\n - Action object found in DB. (None on lookup failure.)\n - modified action_dict with \"id\" key removed if lookup by\n id failed.\n \"\"\"\n action = None\n\n if ACTION_ID in action_dict:\n action_id = action_dict[ACTION_ID]\n try:\n action = get_action_by_id(action_id)\n if (ACTION_NAME not in action_dict or\n action_dict[ACTION_NAME] != getattr(action, ACTION_NAME)):\n action_dict[ACTION_NAME] = getattr(action, ACTION_NAME)\n except StackStormDBObjectNotFoundError:\n LOG.info('Action not found by id, falling back to lookup by name and '\n 'removing action id from Action Execution.')\n del action_dict[ACTION_ID]\n else:\n return (action, action_dict)\n\n if ACTION_NAME in action_dict:\n if ACTION_PACK not in action_dict:\n return (None, {})\n name = action_dict[ACTION_NAME]\n pack = action_dict[ACTION_PACK]\n\n action = _get_action_by_pack_and_name(pack=pack, name=name)\n\n if action:\n action_dict[ACTION_ID] = str(getattr(action, ACTION_ID))\n return (action, action_dict)\n\n # No action found by identifiers in action_dict.\n return (None, {})\n\n\ndef get_action_by_ref(action_ref):\n if (not isinstance(action_ref, str) and not isinstance(action_ref, unicode)\n and not isinstance(action_ref, ResourceReference)):\n raise Exception('Action reference has to be either str or ResourceReference.')\n\n if isinstance(action_ref, str) or isinstance(action_ref, unicode):\n action_ref = ResourceReference.from_string_reference(ref=action_ref)\n\n return _get_action_by_pack_and_name(name=action_ref.name, pack=action_ref.pack)\n\n\ndef update_actionexecution_status(new_status, end_timestamp=None, actionexec_id=None,\n actionexec_db=None):\n \"\"\"\n Update the status of the specified ActionExecution to the value provided in\n new_status.\n\n The ActionExecution may be specified using either actionexec_id, or as an\n actionexec_db instance.\n \"\"\"\n\n if (actionexec_id is None) and (actionexec_db is None):\n raise ValueError('Must specify an actionexec_id or an actionexec_db when '\n 'calling update_actionexecution_status')\n\n if actionexec_db is None:\n actionexec_db = get_actionexec_by_id(actionexec_id)\n\n if new_status not in ACTIONEXEC_STATUSES:\n raise ValueError('Attempting to set status for ActionExecution \"%s\" '\n 'to unknown status string. Unknown status is \"%s\"',\n actionexec_db, new_status)\n\n LOG.debug('Updating ActionExection: \"%s\" with status=\"%s\"',\n actionexec_db, new_status)\n actionexec_db.status = new_status\n\n if end_timestamp:\n actionexec_db.end_timestamp = end_timestamp\n\n actionexec_db = ActionExecution.add_or_update(actionexec_db)\n LOG.debug('Updated status for ActionExecution object: %s', actionexec_db)\n return actionexec_db\n\n\ndef get_args(action_parameters, action_db):\n \"\"\"\n :return: (positional_args, named_args)\n :rtype: (``str``, ``dict``)\n \"\"\"\n position_args_dict = _get_position_arg_dict(action_parameters, action_db)\n\n positional_args = []\n positional_args_keys = set()\n for pos, arg in six.iteritems(position_args_dict):\n positional_args.append(str(action_parameters.get(arg)))\n positional_args_keys.add(arg)\n positional_args = ' '.join(positional_args) # convert to string.\n\n named_args = {}\n for param in action_parameters:\n if param not in positional_args_keys:\n named_args[param] = action_parameters.get(param)\n\n return positional_args, named_args\n\n\ndef _get_position_arg_dict(action_parameters, action_db):\n action_db_params = action_db.parameters\n\n args_dict = {}\n for param in action_db_params:\n param_meta = action_db_params.get(param, None)\n if param_meta is not None:\n pos = param_meta.get('position')\n if pos is not None:\n args_dict[pos] = param\n args_dict = OrderedDict(sorted(args_dict.items()))\n return args_dict\n","sub_path":"st2common/st2common/util/action_db.py","file_name":"action_db.py","file_ext":"py","file_size_in_byte":8814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"404748360","text":"\"\"\"\nThis spider is a WebcruiterXML spider created on top of the CeviumXML Spider\nscrapy crawl webcruiter_xml -a extract=1 -a url=\"https://www.webcruiter.no/webservices/webcruiterculture.asmx/RSSFeed?company_id=45781&cultureid=SV&Collections=1,2,3,4,5,6,7,8&xmlversion=version2&link_source_id=0&orderby=applicationdeadline\"\n\nsample url:\n https://www.webcruiter.no/webservices/webcruiterculture.asmx/RSSFeed?company_id=45781&cultureid=SV&Collections=1,2,3,4,5,6,7,8&xmlversion=version2&link_source_id=0&orderby=applicationdeadline\n\"\"\"\n\nfrom brightcorp.spiders.ceviu_xml import CeviuXML\nfrom brightcorp.processors import ConvertDateString\n\n\nclass WebcruiterXML(CeviuXML):\n\n follow_job_url = False\n name = 'webcruiter_xml'\n tag = 'item'\n\n field_xpaths = {\n 'title': '//title/text()',\n 'url': '//link/text()',\n 'company': '//company_name/text()',\n 'zip_code': '//WorkplacePostno/text()',\n 'description': \"//*[name()='wc:AdvertTextFree']/node()\",\n 'jobtype': '//EmploymentTypes/EmploymentType/EmploymentTypeName/text()',\n 'jobcategory': '//SearchCriteria/Sectors/Sector/SectorName/text()',\n }\n\n location_xpaths = [\n '//WorkplaceStreetAddress/text()', '//WorkplacePostaddress/text()', '//WorkplaceCounties/text()'\n ]\n refnum_xpath = [\"//*[name()='wc:AdvertId']/text()\"]\n date_xpath = {\n 'xpath': '//date/text()',\n 'processors': [ConvertDateString('%Y-%m-%d')]\n }\n exp_date_xpath = {\n 'xpath': '//apply_within_date/text()',\n 'processors': [ConvertDateString('%Y-%m-%d')]\n }\n","sub_path":"brightcorp/brightcorp/spiders/webcruiter_xml.py","file_name":"webcruiter_xml.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"94757687","text":"from PIL import Image\nimport numpy\nimport scipy.fftpack\n\n\ndef phash(img):\n img = img.convert(\"L\").resize((96, 96), Image.ANTIALIAS) # Сжимаем изображение\n img_pixels = numpy.array(img.getdata(), dtype=numpy.float).reshape((96, 96)) # Получаем его пиксели в NP массив\n transformed = scipy.fftpack.dct(scipy.fftpack.dct(img_pixels, axis=0), axis=1) # Дискретное косинусное преобразование по\n # обоим осям\n lowfreq = transformed[:24, :24]\n median = numpy.median(lowfreq) # рассчитываем медианные значения\n return lowfreq > median # Строит хеш путём поэлементного сравнения\n","sub_path":"hash.py","file_name":"hash.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"526951359","text":"#no of guesses 9\r\n#print the no. of guesses left\r\n#and at the end we have to print the game over\r\n\r\nprint(\"Welcome to the Game Of Guessing\")\r\nprint(\"You have only 5 chances to win this game\")\r\nn=20\r\nc=5\r\nwhile(1):\r\n print(\"Enter the value of your choice\")\r\n num1 = int(input())\r\n if(num1 < n):\r\n if(c>1):\r\n print(\"enter the bigger number\")\r\n c=c-1\r\n print(c,end=\" Chances left\\n\")\r\n else:\r\n print(\"GAME OVER\")\r\n break\r\n\r\n #else:\r\n #print(\"Game Over\")\r\n # break\r\n\r\n elif(num1==n):\r\n print(\"Congrats you have a very good guessing ability\")\r\n break\r\n elif(num1 > n):\r\n if(c>1):\r\n print(\"enter the smaller number than this\")\r\n c=c-1\r\n print(c,end=\" Chances left\\n\")\r\n else:\r\n print(\"Game Over\")\r\n break\r\n\r\n\r\n\r\n","sub_path":"THE GAME OF GUESSING.py","file_name":"THE GAME OF GUESSING.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"244874784","text":"import sys\nimport os\nimport re\n\nfrom hg_help import HGcommand\nfrom hg_repo_helper import *\nfrom nose.tools import ok_\nfrom nose.tools import eq_\nfrom nose.tools import raises\nclass TestHGcommand:\n def setUp(self):\n self.command = HGcommand()\n prepareHGrepo()\n ok_(os.path.exists(HG_REPO),\"testrepo should present.\")\n\n def tearDown(self):\n cleanupRepo()\n self.command= None\n def __is_version_correct(self,source,version):\n return source==expected_output\n \n def test_should_reset_with_correct_version(self):\n output=self.command.reset(VER_1,HG_REPO)\n expected=\"\\d+\\sfiles\\supdated,\\s\\d+\\sfiles\\smerged,\\s\\d+\\sfiles\\sremoved,\\s\\d+\\sfiles\\sunresolved\"\n pattern=re.compile(expected)\n m=pattern.search(output)\n ok_(m!=None)\n\n def test_should_get_log_info(self):\n period_1 =' --date \"2010-03-03 12:39 to 2010-03-03 15:29\"'\n outputs = self.command.log(period_1,HG_REPO)\n ok_(outputs.find(VER_4)==0,\"should find \"+VER_4+\" at the beginning, but the result is :\"+outputs)\n \n \n def test_should_get_show_info(self):\n result = self.command.show(VER_1,HG_REPO)\n outputs=result.split(\"\\n\")\n expected=\"changeset: 14:ac9a7cf3330f\"\n eq_(expected,outputs[0],\"Should show \"+expected+\", result is : \"+outputs[0])\n\n def test_should_get_pull_info(self):\n expected = \"no changes found\"\n outputs=self.command.pull(HG_REPO)\n result=outputs.split(\"\\n\")\n eq_(expected,result[2],self.msg(expected,result[2]))\n def msg(self,expected,result):\n return \"Should be \"+expected+\", but the result is:\"+result\n","sub_path":"test/Test_hg_help.py","file_name":"Test_hg_help.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"152050236","text":"import numpy as np\nfrom sklearn import datasets\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn import svm\nimport itertools\n\niris = datasets.load_iris()\ndigits = datasets.load_digits()\n\n#print(iris.data.shape)\n#print(iris.target)\n#print(iris.target_names)\n\nnp.random.seed(0) # aby wyniki były powtarzalne\nindices = np.random.permutation(len(iris.data))\n#print(indices)\ntrain_X = iris.data[indices[:-10]]\ntrain_Y = iris.target[indices[:-10]]\ntest_X = iris.data[indices[-10:]]\ntest_Y = iris.target[indices[-10:]]\n#print(len(train_X), len(test_X))\n\n\nknn = KNeighborsClassifier()\nknn.fit(train_X, train_Y)\n\nprint('klasyfikacja:', knn.predict(test_X))\nprint('powinno byc :', test_Y)\n\n\n\"\"\" \nJak automatycznie policzyć liczbę pomyłek klasyfikatora? \nNapisz kod.\n\"\"\"\ndef zad01(jest, powinno_byc):\n return np.count_nonzero(jest!=powinno_byc)\n \nprint(zad01( knn.predict(test_X),test_Y))\n\n\"\"\"\nSprawdź przy jakim rozmiarze zbioru uczącego \n(ilu początkowych rekordów z danych \"digits\") \nzaczną pojawiać się błędy na pozostałych danych ze zbioru. \nNapisz kod który automatycznie to sprawdzi.\n\"\"\"\n\ndigits = datasets.load_digits()\n\n\ndef zad02():\n s = svm.SVC(gamma=0.001, C=100.) # tworzenie klasyfikatora\n for i in range(-1, -len(digits.data), -1): # petla ktora chodzi od -1 dalej w ujemne\n s.fit(digits.data[:i], digits.target[:i]) # najpierw bierzemy prawie cały zbiór a potem o jeden mniej (bez ostatniego itp)\n wyszlo = s.predict(digits.data[i:]) # sprawdzamy jak przewiduje wartoć tych przez nas niebadanych\n mialo_wyjsc = digits.target[i:]\n if(zad01(wyszlo, mialo_wyjsc) > 0):\n return abs(i)\n\nprint(zad02())\n\n\niris = datasets.load_iris()\n\n\"\"\"\nprint(iris.data.shape)\nprint(iris.target)\nprint(iris.target_names)\n\"\"\"\n\n# podział danych\nnp.random.seed(0) # aby wyniki były powtarzalne\nindices = np.random.permutation(len(iris.data))\nprint(indices)\ntrain_X = iris.data[indices[:-10]]\ntrain_Y = iris.target[indices[:-10]]\ntest_X = iris.data[indices[-10:]]\ntest_Y = iris.target[indices[-10:]]\nprint(len(train_X), len(test_X))\n\nknn.fit(train_X, train_Y)\n\n\"\"\"\nSpróbuj nauczyć klasyfikator kNN na części z dostępnych atrybutów zbioru iris.\nPodziel losowo (jak wyżej) dane iris na zbiór uczący i testujący\no tym samym rozmiarze. Następnie sprawdź dla której pary atrybutów uzyskasz\nnajlepszy wynik klasyfikacji zbioru testowego. Sprawdź czy wniosek jest taki\nsam dla różnych podziałów na zbiory uczące i testujące\n(sprawdź np.random.seed(s) dla s = 0..9).\nNapisz kod który automatycznie to sprawdzi.\n\"\"\"\n\ndef zad03():\n combinations = list(itertools.combinations(list(range(iris.data.shape[1])), 2))\n \n best = tuple()\n for i in range(10):\n np.random.seed(i) # aby wyniki były powtarzalne\n indices = np.random.permutation(len(iris.data))\n fraction = int(len(iris.data)/2)\n train_X = iris.data[indices[:-fraction]]\n train_Y = iris.target[indices[:-fraction]]\n test_X = iris.data[indices[-fraction:]]\n test_Y = iris.target[indices[-fraction:]]\n \n for combination in combinations:\n knn.fit(train_X[:,combination], train_Y)\n result = zad01(knn.predict(test_X[:,combination]), test_Y)\n if(combination == (0,1)):\n best = tuple((combination, result))\n else:\n if(result < best[1]):\n best = tuple((combination, result))\n print (f\"Najlepsze wyniki daja nastepujace numery atrybutow: {best[0]}. Ilosc pomylek w tym wypadku jest rowna {best[1]}.\")\n \n \n \nprint(zad03())\n\n\n\n\"\"\"\nZaimplementuj własny klasyfikator 1NN (kNN dla k=1) używający \nodległości euclidesowej. Sprawdź czy Twoja implementacja klasyfikatora daje \ntakie same wyniki jak sklearn.neighbors.NearestNeighbors\n\"\"\"\n\ndef nn(data, x):\n dists = []\n for i in range(data.shape[0]):\n dist = np.linalg.norm(data[i,:]-x)\n dists.append(dist)\n return(dists.index(min(dists)))\n\ndata = np.array([[0, 0, 2], [1, 0, 0], [0, 0, 1]])\nx = np.array([0, 0, 1.3])\nprint(nn(data, x))\n\n\ndef check(data, x):\n def referencyjna():\n neigh = NearestNeighbors(1, algorithm='brute', metric='euclidean')\n neigh.fit(data)\n return neigh.kneighbors([x], 1, return_distance=False)[0,0]\n assert nn(data, x) == referencyjna()\n\ndata = np.array([[0, 0, 2], [1, 0, 0], [0, 0, 1]])\nx = np.array([0, 0, 1.3])\ncheck(data, x)\n","sub_path":"Informatyka medyczna/lab01.py","file_name":"lab01.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"339574254","text":"# -*- coding: utf-8 -*-\nimport argparse\nimport os\nimport io\nimport logging\nimport time\nimport math\nimport pickle\n\n\ndef _get_model_file():\n cur_dir = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(cur_dir, \"model\", \"char_freq.pkl\")\n\n\ndef _read_name_char_freq():\n cur_dir = os.path.dirname(os.path.abspath(__file__))\n given_names_file = os.path.join(cur_dir, \"data\", \"all_given_names.txt\")\n with io.open(given_names_file, encoding=\"utf-8\") as _fp:\n names = _fp.read().splitlines()\n char_freq = {}\n for name in names:\n for char in name:\n char_freq[char] = 1 + char_freq.get(char, 0)\n for char in char_freq:\n char_freq[char] = 1.0 / (1 + math.exp(-char_freq[char]))\n return char_freq\n\n\nclass GivenNameModel(object):\n def __init__(self, fpath, from_scratch):\n if os.path.isfile(fpath) and not from_scratch:\n logging.warning(\"Load model: %s\", fpath)\n with io.open(fpath, \"rb\") as _fp:\n self.char_freq = pickle.load(_fp)\n else:\n self.char_freq = _read_name_char_freq()\n self.save(fpath)\n\n def save(self, fpath):\n logging.warning(\"Save model: %s\", fpath)\n _dir = os.path.dirname(fpath)\n if not os.path.isdir(_dir):\n os.makedirs(_dir)\n with io.open(fpath, \"wb\") as _fp:\n pickle.dump(self.char_freq, _fp, pickle.HIGHEST_PROTOCOL)\n\n def __get_name_weight(self, name):\n weight = 0\n for char in name:\n weight += self.char_freq.get(char, -0.73)\n return max(weight/len(name), 0)\n\n def predict_proba(self, names):\n weights = [self.__get_name_weight(name) for name in names]\n print(weights)\n return [math.tanh(_) for _ in weights]\n\n def predict(self, names):\n return [_ > 0.5 for _ in self.predict_proba(names)]\n\n\ndef main():\n \"\"\"Prog entry.\"\"\"\n start_time = time.time()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--from-scratch\", action=\"store_true\")\n parser.add_argument(\"--show-proba\", action=\"store_true\")\n parser.add_argument(\"--names-to-predict\", \"-n\", nargs=\"+\", default=[])\n args = parser.parse_args()\n\n model = GivenNameModel(_get_model_file(), args.from_scratch)\n\n if args.show_proba:\n result = model.predict_proba(args.names_to_predict)\n else:\n result = model.predict(args.names_to_predict)\n for index, name in enumerate(args.names_to_predict):\n print(u\"{}: {:f}\".format(name, result[index]))\n\n elapsed = time.time() - start_time\n logging.info(u\"Total time: %dm%s\", elapsed // 60, elapsed % 60)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n main()\n","sub_path":"guess_gender/decide_if_given_name.py","file_name":"decide_if_given_name.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"374380367","text":"import torch.nn as nn\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom hw_asr.base import BaseModel\r\n\r\n\r\nclass MaskedConv(nn.Module):\r\n def __init__(self, sequential: nn.Sequential) -> None:\r\n super(MaskedConv, self).__init__()\r\n self.sequential = sequential\r\n\r\n def forward(self, inputs, lengths):\r\n output = None\r\n for module in self.sequential:\r\n output = module(inputs)\r\n mask = torch.BoolTensor(output.size()).fill_(0).cuda()\r\n lengths = self.get_lengths(module, lengths)\r\n for i, length in enumerate(lengths):\r\n length = length.item()\r\n if (mask[i].size(2) - length) > 0:\r\n mask[i].narrow(dim=2, start=length, length=mask[i].size(2) - length).fill_(1)\r\n\r\n output = output.masked_fill(mask, 0)\r\n inputs = output\r\n\r\n return output, lengths\r\n\r\n def get_lengths(self, module, lengths):\r\n if isinstance(module, nn.Conv2d):\r\n res = (lengths + 2 * module.padding[1] - module.dilation[1] * (module.kernel_size[1] - 1) - 1) // \\\r\n module.stride[1] + 1\r\n return res\r\n return lengths\r\n\r\n\r\nclass RnnCell(nn.Module):\r\n def __init__(self, n_feats, hidden_size, dropout):\r\n super(RnnCell, self).__init__()\r\n self.rnn = nn.RNN(n_feats, hidden_size, num_layers=2, batch_first=True, bidirectional=True, dropout=dropout)\r\n self.bn = nn.BatchNorm1d(n_feats)\r\n\r\n def forward(self, inputs, inputs_length):\r\n total_length = inputs.size(0)\r\n inputs = F.relu(self.bn(inputs.transpose(1, 2)))\r\n output = inputs.transpose(1, 2)\r\n output = nn.utils.rnn.pack_padded_sequence(output, inputs_length.cpu(), enforce_sorted=False)\r\n output, _ = self.rnn(output)\r\n output, _ = nn.utils.rnn.pad_packed_sequence(output, total_length=total_length)\r\n\r\n return output\r\n\r\n\r\nclass DeepSpeech(BaseModel):\r\n def __init__(self, n_feats, n_class, hidden_size=512, num_layers=5, dropout=0.1, *args, **kwargs):\r\n super().__init__(n_feats, n_class, *args, **kwargs)\r\n self.conv = MaskedConv(nn.Sequential(\r\n nn.Conv2d(1, 32, kernel_size=(41, 11), stride=(2, 2), padding=(20, 5), bias=False),\r\n nn.BatchNorm2d(32),\r\n nn.Hardtanh(0, 20, inplace=True),\r\n nn.Conv2d(32, 32, kernel_size=(21, 11), stride=(2, 1), padding=(10, 5), bias=False),\r\n nn.BatchNorm2d(32),\r\n nn.Hardtanh(0, 20, inplace=True)\r\n ))\r\n self.layers = nn.ModuleList()\r\n n_feats = (n_feats - 1) // 2 + 1\r\n n_feats = ((n_feats - 1) // 2 + 1) * 32\r\n rnn_out = hidden_size * 2\r\n for i in range(num_layers):\r\n self.layers.append(RnnCell(\r\n n_feats=n_feats if i == 0 else rnn_out,\r\n hidden_size=hidden_size,\r\n dropout=dropout\r\n ))\r\n self.fc = nn.Sequential(\r\n nn.Linear(rnn_out, hidden_size),\r\n nn.ReLU(),\r\n nn.Linear(hidden_size, n_class, bias=False)\r\n )\r\n\r\n def forward(self, spectrogram, spectrogram_length, *args, **kwargs):\r\n inputs = spectrogram.unsqueeze(1).transpose(2, 3)\r\n outputs, output_lengths = self.conv(inputs, spectrogram_length)\r\n batch_size, channels, dimension, seq_lengths = outputs.size()\r\n outputs = outputs.permute(0, 3, 1, 2).view(batch_size, seq_lengths, channels * dimension)\r\n outputs = outputs.permute(1, 0, 2).contiguous()\r\n for layer in self.layers:\r\n outputs = layer(outputs, output_lengths)\r\n outputs = self.fc(outputs.transpose(0, 1)).log_softmax(dim=-1)\r\n return outputs\r\n\r\n def transform_input_lengths(self, input_lengths):\r\n return input_lengths // 2\r\n\r\n","sub_path":"hw_asr/model/deepspeech.py","file_name":"deepspeech.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"149415748","text":"#coding: utf-8\nimport json\nfrom django.shortcuts import render\nfrom main.forms import InviteRequestForm, FeedBackForm\nfrom main.tasks import send_invite_request, send_feedback\nfrom django.http import HttpResponse\n\ndef index(request):\n if request.method == 'POST':\n form = FeedBackForm(request.POST)\n if form.is_valid():\n results = {\n 'success': True,\n }\n send_feedback.delay(form)\n else:\n results = {\n 'success': False,\n 'errors': form.errors,\n }\n response = json.dumps(results)\n return HttpResponse(response, mimetype=\"application/json\")\n else:\n form = FeedBackForm()\n return render(request, 'index.html', locals())\n\ndef invite_request(request):\n is_send = False\n if request.method == 'POST':\n form = InviteRequestForm(request.POST)\n if form.is_valid():\n send_invite_request.delay(form)\n is_send = True\n else:\n form = InviteRequestForm()\n return render(request, 'invite_request.html', locals())","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"81827519","text":"import os\nimport distutils.util\nimport sklearn\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport clustersyn.datahandler as datahandler\nimport clustersyn.helper as helper\nimport clustersyn.group as group\n\n\nPATH_TO_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nCOLOURS = [\"r\", \"b\", \"g\", \"c\", \"m\", \"y\"]\n\nclass Composition:\n \n \"\"\"\n Class to orchestrate the computation and plotting of various visualisations on the \n dataframe as specified in the given dict.\n \"\"\"\n \n def __init__(self, df: datahandler.Dataframe, visualisation_parameters: dict, exp_name: str):\n \"\"\"\n :param df: instance of (loaded/configured) datahandler.Dataframe class\n :param visualisation_parameters: dict of params specifying what to visualise\n :param exp_name: string name of experiment for naming output files etc.\n \"\"\" \n self._df = df \n self.visualise(visualisation_parameters, exp_name)\n \n def df(self):\n return self._df\n \n def visualise(self, visualisation_parameters: dict, exp_name: str):\n \"\"\"\n Extract, set parameters and orchestrate visualisation of data\n \n :param visualisation_parameters: dict of params specifying what to visualise\n :param exp_name: string name of experiment for naming output files etc.\n \"\"\"\n perform_tsne = distutils.util.strtobool(visualisation_parameters[\"tsne\"])\n kde = distutils.util.strtobool(visualisation_parameters[\"kde\"])\n heatmap = distutils.util.strtobool(visualisation_parameters[\"heatmap\"])\n \n gt_ofile = \"data/GT_labels.pkl\"\n if os.path.isfile(gt_ofile):\n gt = helper.unpickle_object(gt_ofile)\n else:\n gt = self.df().ground_truth()\n helper.pickle_object(gt, gt_ofile)\n \n if perform_tsne | kde:\n \n n_components = int(visualisation_parameters[\"components\"])\n if n_components > 2:\n raise ValueError(\"Only currently visualising 2 components of tsne embedding.\")\n tsne = Tsne(self._df)\n \n tsne_embedding_ofile = \"data/tsne_embedding.pkl\"\n if os.path.isfile(tsne_embedding_ofile):\n embedding = helper.unpickle_object(tsne_embedding_ofile)\n else:\n embedding = tsne.apply(visualisation_parameters[\"distance\"], n_components)\n helper.pickle_object(embedding, tsne_embedding_ofile) \n \n if perform_tsne:\n \n label_classes = distutils.util.strtobool(visualisation_parameters[\"colour_classes\"])\n if label_classes:\n \n # colour points according ground truth\n name_to_int = {k: v for v, k in enumerate(set(gt))}\n gt_int = [name_to_int[class_name] for class_name in gt]\n int_to_name = dict([reversed(i) for i in name_to_int.items()])\n print(\"Class integer to name: \", int_to_name)\n tsne.plot(embedding, gt_int, int_to_name, \"_GT\")\n \n # colour points according to clustering\n clust_labels = helper.unpickle_object(\"data/{}_labels.pkl\".format(exp_name))\n name_to_int = {k: v for v, k in enumerate(set(clust_labels))}\n clust_labels_int = [name_to_int[class_name] for class_name in clust_labels]\n int_to_name = dict([reversed(i) for i in name_to_int.items()])\n tsne.plot(embedding, clust_labels_int, int_to_name, \"_{}\".format(exp_name))\n \n else:\n tsne.plot(embedding)\n \n if kde:\n tsne.plot_kde(embedding)\n \n if heatmap:\n \n # gather avaiable pickled labels and plot a heatmap of their pairwise adjusted rand scores\n labels, full_names = helper.load_pickles(\"data\", \"label\")\n names = [helper.return_label_title(name) for name in full_names]\n htmap = Heatmap(labels, names)\n htmap.plot()\n\nclass Tsne:\n \n \"\"\"\n Class for performing t-Distributed Stochastic Neighbor Embedding (t-SNE) analysis, \n the dimensionality reduction technique, on the data.\n \"\"\"\n \n def __init__(self, loaded_df: datahandler.Dataframe):\n \"\"\"\n :param loaded_df: instance of (loaded/configured) datahandler.Dataframe class\n \"\"\"\n self._df = loaded_df\n \n def df(self):\n return self._df\n \n def apply(self, metric: str, n_components: int) -> np.array:\n \"\"\"\n Apply t-sne dimensionality reduction on the loaded df\n\n :param metric: distance metric to use when computing pairwise distances in tsne embedding\n space\n :param n_components: number of components/dimensions to output/reduce to\n :return: embedding of the training data in low-dimensional space\n \"\"\"\n \n ts = sklearn.manifold.TSNE(n_components = n_components, metric = metric)\n return ts.fit_transform(self.df().matrix())\n\n def plot(self, embeddings: np.array, labels: list = None, int_to_name: dict = None, name: str = \"\"):\n \"\"\"\n Plot the tsne embeddings and colour according to class labels if given.\n\n :param embeddings: tsne embedding of data as np array\n :param labels: optional param to specify the class of each point (if wanting to colour the points)\n :param int_to_name: mapping from int label of classes to name (str) of classes\n :param name: name of experiment to output files as\n \"\"\"\n fig = plt.figure(figsize = (8,8))\n ax = fig.add_subplot(1,1,1) \n \n if labels == None:\n cvec = \"r\"\n \n else: \n clusters = len(set(labels)) \n label_color_dict = {}\n for i, cluster in enumerate(int_to_name.keys()):\n try:\n label_color_dict[cluster] = COLOURS[i]\n except:\n label_color_dict[cluster] = 'black' # many colours, default to black\n \n print(\"Colour of clusters: \", label_color_dict)\n cvec = [label_color_dict[label] for label in labels]\n print(\"Number of points in clusters: \", group.Cluster.get_proportion_in_clusters(cvec))\n\n patches = [mpatches.Patch(color=label_color_dict[i], label=int_to_name[i]) \n for i in label_color_dict.keys()]\n plt.legend(handles=patches, frameon=False, loc=\"best\", prop={'size': 18})\n \n tsne_df = pd.DataFrame(data = embeddings, columns = ['embedding 1', 'embedding 2'])\n ax.scatter(tsne_df['embedding 1'], tsne_df['embedding 2'], c = cvec, s = 0.1, marker = 'o')\n \n plt.tight_layout()\n fig.savefig(\"{}/data/tsne_embedding{}.png\".format(PATH_TO_DIR, name), dpi=1200)\n\n def plot_kde(self, embeddings: np.array):\n \"\"\"\n Plot the kernel density estimation of the tsne embedding to show the distribution of the points\n in the embedding. Points can be prone to overlapping with eachother in the tsne embedding.\n\n :param embeddings: np array of the tsne embedding\n \"\"\"\n kde = pd.DataFrame(data = embeddings, columns = ['embedding 1', 'embedding 2'])\n grid = sns.jointplot(x = kde['embedding 1'], y = kde['embedding 2'], data = kde, height = 6, kind = \"kde\", \n color = (0.19215686, 0.50980392, 0.74117647, 1.), cbar = True, cbar_kws = {'shrink' : 0.9})\n grid.plot_joint(plt.scatter, c=\"w\", s=0.1, marker=\"o\")\n \n grid.ax_joint.collections[0].set_alpha(0)\n plt.tight_layout()\n grid.set_axis_labels('', '')\n grid.savefig(\"{}/data/kde_embedding.png\".format(PATH_TO_DIR), dpi=1200)\n \n \nclass Heatmap:\n \n \"\"\"\n Class for plotting a heatmap to compare the similarity (using adjusted rand score)\n of labels that have been produced by different clustering algorithms.\n \"\"\"\n \n def __init__(self, labels: np.array, labels_names: list):\n \"\"\"\n :param labels: array of labels for different experiments to plot the heatmap of\n :param name: name of experiments related to each set of labellings in labels\n \"\"\"\n self._labellings = labels\n self._labels_names = labels_names\n \n def labellings(self) -> np.array:\n return self._labellings\n \n def labels_names(self) -> list:\n return self._labels_names\n \n def plot(self):\n \"\"\"\n Plots the adjusted rand score heatmap between pairs of labels produced from\n from different clustering algorithms.\n \"\"\"\n data_matrix, cols = Heatmap.compare_rand_scores(self.labellings(), self.labels_names())\n df = pd.DataFrame(data_matrix, index=cols, columns=cols)\n \n plt.figure(figsize=(10, 8))\n ax = sns.heatmap(df, linewidth=0.8, vmin=-1, vmax=1, cmap='hot', cbar_kws={'label': 'Adjusted rand score'})\n\n plt.xticks(fontsize=22, rotation=90)\n plt.yticks(fontsize=22, rotation=90) \n ax.tick_params(axis='both', which='major', pad=20)\n\n ax.figure.axes[-1].yaxis.label.set_size(25)\n ax.figure.axes[-1].tick_params(labelsize=20, rotation=90)\n ax.figure.axes[-1].yaxis.labelpad = 20 \n\n plt.tight_layout()\n plt.savefig(\"{}/data/heatmap.png\".format(PATH_TO_DIR), dpi=1200)\n \n @staticmethod\n def compare_rand_scores(labellings_array: np.array, labellings_names: list) -> (np.array, list): \n \"\"\"\n Iterate through each label and calculate its adjusted rand score with all other labels\n\n :param labellings_array: array of labellings from different experiments to compare\n :param labellings_names: list of strings corresponding to the names of the experiments\n from which the labels were computed\n :return: matrix of rand score values, and a list of the order of the names of experiments\n \"\"\"\n matrix, cols = [], []\n for exp1_labels, name in zip(labellings_array, labellings_names):\n scores_for_label = []\n for exp2_labels, compare_to_name in zip(labellings_array, labellings_names): \n try:\n score = sklearn.metrics.adjusted_rand_score(exp1_labels, exp2_labels)\n except:\n raise ValueError(\"Labels are not the same length. Cannot compute adjusted rand score.\")\n scores_for_label.append(score)\n \n cols.append(name)\n matrix.append(scores_for_label)\n\n return np.array(matrix), cols\n","sub_path":"clustersyn/visualise.py","file_name":"visualise.py","file_ext":"py","file_size_in_byte":10929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"421877730","text":"from os import name\nfrom query.models import EventCategory\nimport re\nfrom flask import Blueprint, request, make_response, jsonify, url_for, redirect\nfrom flask.views import MethodView\nfrom query.services import InquiryService\n# from query.models import Inquiry, Address\ninquiry_blueprint = Blueprint('inquiry_url', __name__, url_prefix='/inquiry')\nfrom auth.decorators import authanticate, privilege_required\nfrom exceptions.exception_error import ExceptionError\nfrom exceptions.dao_exceptions import DaoExceptionError\nclass InquiryApiView(MethodView):\n allow = {\n 'GET': \"view_all_inquiry\", \n 'POST': \"craete_inquiry\",\n 'DELETE': \"delete_inquiry\",\n 'PUT': 'edit_inquiry'\n }\n # decorators = [privilege_required(acl=allow), authanticate]\n \n\n def post(self):\n response_data = {\"success\": True, \"status_code\": 200}\n event_category = request.form.getlist('event_category_id') \n post_data = request.form.to_dict()\n post_data['event_category_id'] = list(map(int, event_category))\n create_inquiry_service = InquiryService()\n create_inquiry_service.create_inquiry(request_data=post_data)\n response_data['message'] = \"Inquiry Created success fullly\"\n \n return make_response(jsonify(response_data)), response_data['status_code']\n \n\n def get(self):\n inquiry_service = InquiryService()\n inquiry_data = inquiry_service.get_all_inquires()\n return make_response(jsonify(inquiry_data)), 200\n \n def put(self, inquiry_id, *args, **kwargs):\n response_data = {\"message\": {'msg': \"something wents wrong\"}, \"status\": \"fail\", \"status_code\": 501}\n try:\n user = request.environ['user']\n user_id = user['user_id']\n inquiry_service = InquiryService()\n event_category = request.form.getlist('event_category_id') \n put_data = request.form.to_dict()\n put_data['event_category_id'] = list(map(int, event_category))\n put_data['updated_by_id'] = user_id\n inquiry_data = inquiry_service.edit_inquiry(inquiry_id=inquiry_id, request_data=put_data)\n response_data['message'] = \"Inquiry Updated success fullly\"\n response_data['status_code'] = 200\n response_data['status'] = \"success\"\n except (ExceptionError, DaoExceptionError) as e:\n response_data['status_code'] = e.code\n response_data['message'] = e.get_traceback_details()\n return make_response(jsonify(response_data)), response_data['status_code']\n \n \nclass SendQueryPhotographer(MethodView):\n\n def post(self, *args, **kwargs):\n response_data = {\"status\": \"fail\", \"status_code\": 200}\n \n inquiry_service = InquiryService()\n post_data = request.form.to_dict()\n photographer_ids = request.form.getlist('photographer_id')\n inquiry_service.send_query(inquiry_id=post_data['inquiry_id'], photographer_ids=photographer_ids)\n response_data['message'] = \"Inquiry photographer send success\"\n\n return make_response(jsonify(response_data)), response_data['status_code']\n \n \n\ninquiry_api = InquiryApiView.as_view('inquiry_api')\nsend_query_api = SendQueryPhotographer.as_view('send_query_api')\n\ninquiry_blueprint.add_url_rule(\n '/',\n view_func=inquiry_api,\n methods=['POST']\n)\ninquiry_blueprint.add_url_rule(\n '/',\n view_func=inquiry_api,\n methods=['GET']\n)\n\ninquiry_blueprint.add_url_rule(\n '/',\n view_func=inquiry_api,\n \n methods=['PUT',],\n # options={\"name\", \"inquiry_add\"}\n\n)\ninquiry_blueprint.add_url_rule(\n '/send_query/',\n view_func=send_query_api,\n \n methods=['POST',],\n # options={\"name\", \"inquiry_add\"}\n\n)","sub_path":"query/views/inquiry.py","file_name":"inquiry.py","file_ext":"py","file_size_in_byte":3776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"486472012","text":"from rqalpha import run_file\nfrom datetime import datetime\nimport os\n\nfrom const.benchmark import BENCHMARK\nfrom const.my_po_params import MY_PO_PARAMS\nfrom src.my_calculator import check_root\n\n# s_date = \"2016-01-08\"\ns_date = \"2017-01-01\"\n# e_date = \"2018-01-01\"\n# e_date = \"2019-01-01\"\ne_date = \"2020-01-01\"\n\n# 考虑同时回测风险中性和风险暴露\n# for meth in [\"calc_weight\", \"calc_weight_with_exposure\"]:\nfor meth in [\"cvxpy_without_risk_control\"]:\n config_cw = {\n \"upper\": MY_PO_PARAMS.WEIGHT_UPPER,\n \"c\": MY_PO_PARAMS.TRANSACTION_COST,\n \"l\": MY_PO_PARAMS.L,\n \"lam\": MY_PO_PARAMS.LAM,\n \"exposure\": MY_PO_PARAMS.EXPOSURE,\n # \"calc_method\": MY_PO_PARAMS.CALC_METHOD\n \"calc_method\": meth\n }\n\n strategy_name = 'my_po'\n strategy_path = \"../src/%s.py\" % strategy_name\n\n # 保存优化问题的各个变量和解向量,每一行的格式为{'index_name':{'backtest_date': {key: value}}}\n opt_file = open(f\"../res/opt_weight/my_po-{config_cw['calc_method']}-{str(datetime.now().strftime('%Y%m%d'))}.txt\",\n 'w')\n\n for benchmark, ben_code in BENCHMARK.items():\n # if benchmark != 'ZZ500': continue\n\n print(\"=\" * 40 + \"\\n\" + f\"method:\\t{meth}\\nbenchmark:\\t{benchmark}\\n\" + \"=\" * 40)\n\n res_root = '../res/backtest/%s/%s' % (strategy_name + \"-\" + config_cw[\"calc_method\"], benchmark)\n check_root('/'.join(res_root.split('/')[:3]))\n check_root('/'.join(res_root.split('/')[:4]))\n check_root(res_root)\n\n config = {\n \"extra\": {\n \"context_vars\": {\n \"CONFIG_CW\": config_cw,\n \"bench_record\": benchmark,\n \"opt_file\": opt_file\n },\n # \"log_level\": \"error\",\n },\n \"base\":\n {\n \"start_date\": s_date,\n \"end_date\": e_date,\n \"benchmark\": ben_code,\n \"accounts\": {\n \"stock\": 50000000\n }\n },\n \"mod\":\n {\n \"sys_analyser\": {\n \"enabled\": True,\n \"plot\": False,\n \"plot_save_file\": res_root,\n \"report_save_path\": res_root,\n \"output_file\": os.path.join(res_root, \"result.pkl\")\n },\n \"sys_simulation\": {\n \"slippage\": 0.002\n }\n }\n }\n\n run_file(strategy_path, config)\n","sub_path":"run/run_my_po.py","file_name":"run_my_po.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"377356044","text":"\n\nfrom xai.brain.wordbase.nouns._shekel import _SHEKEL\n\n#calss header\nclass _SHEKELS(_SHEKEL, ):\n\tdef __init__(self,): \n\t\t_SHEKEL.__init__(self)\n\t\tself.name = \"SHEKELS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"shekel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_shekels.py","file_name":"_shekels.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"201091132","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom users.models import User\n\n\"\"\"\n请求方式: GET /users/usernames/(?P\\w{5,20})/count/\n\n请求参数:\n参数\t类型\t说明\nusername\tstr\t用户名\n\n返回数据:json\n返回值\t类型\t说明\nusername\tstr\t用户名\ncount\tint\t数量\n\"\"\"\n\nclass RegisterUsernameCountAPIView(APIView):\n\n def get(self, request, username):\n # 获取用户个数\n count = User.objects.filter(username=username).count()\n # 组织数据\n context = {\n 'count': count,\n 'username': username,\n }\n return Response(context)\n\n\n\"\"\"\n请求方式: GET /users/phones/(?P1[345789]\\d{9})/count/\n\n请求参数:\n参数\t类型\t说明\nmobile\tstr\t手机号\n\n返回数据:json\n\n返回值\t类型\t说明\nmobile\tstr\t手机号\ncount\tint\t数量\n\"\"\"\n\n\nclass RegisterPhoneCountAPIView(APIView):\n\n def get(self, request, mobile):\n # 获取用户个数\n count = User.objects.filter(mobile=mobile).count()\n # 组织数据\n context = {\n 'count': count,\n 'mobile': mobile,\n }\n return Response(context)\n","sub_path":"mall/apps/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"91909395","text":"\"\"\"\n提供各种计算工具\n\"\"\"\n\nimport numpy as np\n\n\ndef get_normalize(x):\n \"\"\"获得归一化后的向量以及mu和sigma参数\"\"\"\n\n m = x.shape[1]\n mu = np.sum(x, axis=1, keepdims=True) / m\n # 将向量中心化\n x_norm = x - mu\n # 计算方差归一常数\n sigma_square = np.sum(x_norm**2, axis=1, keepdims=True) / m\n sigma = np.sqrt(sigma_square + 0.001)\n x_norm = x_norm / sigma\n return mu, sigma, x_norm\n\n\ndef forward_prop(x, w, b):\n \"\"\"正向传播,输入x和特征向量,输出z和a\"\"\"\n\n # 获得最高层数\n L = len(w) - 1\n\n # 初始化向量\n z = [np.zeros(1)] * (L+1)\n a = [np.zeros(1)] * (L+1)\n a[0] = x\n\n # 前向传播:前面L-1层使用RELU,第L层使用Softmax\n for l in range(1, L+1):\n z[l] = np.dot(w[l], a[l-1]) + b[l]\n if l < L:\n a[l] = np.where(z[l]<0, 0, z[l])\n else:\n assist = np.sum(np.exp(z[l]), axis=0)\n a[l] = np.exp(z[l]) / assist\n\n return z, a\n\n\ndef back_prop(y, a, z, w):\n \"\"\"反向传播,输入y,预测值和特征向量,输出特征向量的增量\"\"\"\n\n # 获得当前batch的数据集数\n m = y.shape[1]\n # 获得最高层数\n L = len(w) - 1\n\n # 初始化向量\n dg = [np.zeros(1)] * (L+1)\n dz = [np.zeros(1)] * (L+1)\n dw = [np.zeros(1)] * (L+1)\n db = [np.zeros(1)] * (L+1)\n\n # 反向传播,第L层直接给出,前面使用递归\n for l in range(L, 0, -1):\n if l == L:\n dz[l] = a[l] - y\n else:\n dg[l] = np.where(z[l]<0, 0, 1)\n dz[l] = np.dot(w[l+1].T, dz[l+1]) * dg[l]\n dw[l] = np.dot(dz[l], a[l-1].T) / m\n db[l] = np.sum(dz[l], axis=1, keepdims=True) / m\n\n return dw, db\n\n\ndef get_accuracy(a_L, y):\n \"\"\"输入预测值和标签,计算正答率\"\"\"\n\n # 得到数据集数\n m = y.shape[1]\n\n # 对比两个最大值一维数组\n equal_ary = np.equal(np.argmax(a_L, 0), np.argmax(y, 0))\n # 得到平均值,会将输入数组自动转换为01\n accuracy = np.mean(equal_ary)\n return round(accuracy, 3)\n\n\ndef get_variance(b1, b2):\n \"\"\"根据训练集和测试集的偏差,计算方差\"\"\"\n\n variance_sqa = (b1 - b2) ** 2\n variance = np.sqrt(variance_sqa)\n return variance\n","sub_path":"np_play/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"560015433","text":"import hw2, hw4\nimport util\nimport mechanize\nimport sqlite3\nfrom queue import Queue, PriorityQueue\nfrom bs4 import BeautifulSoup\nfrom string import ascii_lowercase\nfrom urllib import parse, request\nfrom urllib.parse import urlparse\nfrom collections import defaultdict\nimport csv\nimport operator\nimport json\nfrom datetime import date, datetime\n\n\nmedical_terms = hw2.read_stopwords('medical_terms')\n\n\ndef renew_data():\n base = 'https://www.cdc.gov/diseasesconditions/az/'\n disease_pages_alpha = []\n disease_pages = []\n for a in ascii_lowercase:\n link = base + a + '.html'\n disease_pages_alpha.append(link)\n res = request.urlopen(link)\n html = res.read()\n soup = BeautifulSoup(html, 'html.parser')\n target = soup.find(\"div\", {\"class\": \"az-content\"})\n for link in target.findChildren(\"a\"):\n disease = [link.text, link.get('href')]\n disease_pages.append(disease)\n return disease_pages\n # store_csv('disease_pages.csv', disease_pages)\n\n\n# create vector according to the first three layer of descriptions\n# return the vector representation of a disease given its link\ndef create_vector(root):\n queue = Queue()\n queue.put((0, root))\n visited = []\n word_list = []\n depth = 0\n domain = urlparse(root).netloc\n while not queue.empty() and depth < 2:\n obj = queue.get()\n url = obj[1]\n depth = obj[0] + 1\n word_list = word_list + util.word_list(url)\n print(url)\n try:\n req = request.urlopen(url)\n html = req.read()\n\n visited.append(url)\n hw4.visitlog.debug(url)\n\n for link, title in hw4.parse_links(url, html):\n if (urlparse(link).netloc in domain) or (domain in urlparse(link).netloc):\n if hw4.not_self_reference(link, url) and (link not in visited):\n queue.put((depth, link))\n\n except Exception as e:\n print(e, url)\n word_list = [x for x in word_list if x != '']\n return compute_term_frequency(word_list)\n\n\ndef create_database():\n conn = sqlite3.connect('diseases.db')\n c = conn.cursor()\n try:\n c.execute('''DROP TABLE Diseases''')\n except:\n print('CANNOT DROP TABLE')\n c.execute('''CREATE TABLE Diseases(id INTEGER PRIMARY KEY, name TEXT, vec TEXT)''')\n today = date.today()\n disease_link = renew_data()\n id = 0\n for d in disease_link:\n id += 1\n name = d[0]\n link = d[1]\n vec = json.dumps(create_vector(link))\n try:\n c.execute('''INSERT INTO Diseases(id, name, vec)VALUES (?,?,?)''', (id, name, vec))\n except Exception as e:\n print(e)\n print(name)\n conn.rollback()\n conn.commit()\n conn.close()\n\n\ndef engine(query: str):\n words = util.process_string(query)\n vec = compute_term_frequency(words)\n conn = sqlite3.connect('diseases.db')\n c = conn.cursor()\n c.execute('''SELECT name, vec FROM Diseases''')\n target = defaultdict()\n for row in c:\n name = row[0]\n d_vec = json.loads(row[1])\n sim = hw2.cosine_sim(d_vec, vec)\n target[sim] = name\n idx = 0\n for i in sorted(target.keys(), reverse=True):\n if idx > 10:\n break\n idx += 1\n print(target[i])\n print(i)\n\n\n# return a vector representation of the input word list\ndef compute_term_frequency(words):\n vec = defaultdict()\n for w in words:\n if vec.get(w, None) is None:\n vec[w] = 0\n if w in medical_terms:\n vec[w] += 20\n else:\n vec[w] += 1\n return dict(vec)\n\n\ndef store_csv(name, data):\n with open(name, 'w') as resultFile:\n for row in data:\n resultFile.write(row[0] + ',' + row[1] + '\\n')\n resultFile.close()\n\n\ndef main():\n engine('Heart')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"492471176","text":"from sys import argv\nfrom pymongo import MongoClient\n\n__mongo_client__ = MongoClient()\n__2048_database__ = __mongo_client__.game_2048\n__2048_moves_collection__ = __2048_database__.moves\n__2048_scaled_moves_collection__ = __2048_database__.scaled_moves\n\ndef rotate(table, choice):\n\trot_table = [[0, 0, 0, 0] for _ in range(4)]\n\tfor i in range(4):\n\t\tfor j in range(4):\n\t\t\trot_table[j][-i-1] = table[i][j]\n\tif choice == 'U':\n\t\treturn [table, 'R', 2]\n\telif choice == 'R':\n\t\treturn [table, 'D', 3]\n\telif choice == 'D':\n\t\treturn [table, 'L', 4]\n\telif choice == 'L':\n\t\treturn [table, 'U', 1]\n\ndef main(rotate_table, scale):\n\tcollection_data = list(__2048_moves_collection__.find())\n\t__2048_scaled_moves_collection__.remove({ '_id': { '$ne': -1 } })\n\tprev_x = collection_data[0]\n\tfor xi in range(len(collection_data)):\n\t\tx = collection_data[xi]\n\t\tsame = True\n\t\tmax_val = 0\n\t\tfor i in range(4):\n\t\t\tfor j in range(4):\n\t\t\t\tif xi > 0 and x['table'][i][j] != prev_x['table'][i][j]:\n\t\t\t\t\tsame = False\n\t\t\t\tif x['table'][i][j] > max_val:\n\t\t\t\t\tmax_val = x['table'][i][j]\n\t\tif xi > 0 and same:\n\t\t\tprint(prev_x)\n\t\t\t__2048_moves_collection__.remove({ '_id': prev_x['_id'] });\n\t\telse:\n\t\t\ttable = [[int(c) for c in r] for r in x['table'][:]]\n\t\t\tchoice = str(x['choice'])\n\t\t\tn_choice = int(x['n_choice'])\n\t\t\tgame_id = str(x['game_id'])\n\t\t\tfor _ in range(4):\n\t\t\t\tscaled_object = { 'table': table, 'choice': choice, 'n_choice': n_choice, 'game_id': game_id, 'generated': True }\n\t\t\t\tfor i in range(4):\n\t\t\t\t\tfor j in range(4):\n\t\t\t\t\t\tif scale:\n\t\t\t\t\t\t\tscaled_object['table'][i][j] /= max_val\n\t\t\t\t\t\tscaled_object['cell_' + str(i) + '_' + str(j)] = scaled_object['table'][i][j]\n\t\t\t\t__2048_scaled_moves_collection__.insert_one(scaled_object)\n\t\t\t\tif not rotate_table:\n\t\t\t\t\tbreak\n\t\t\t\ttable, choice, n_choice = rotate(table, choice)\n\t\tprev_x = x\n\nif __name__ == \"__main__\":\n\tmain('-r' in argv, '-s' in argv)","sub_path":"clean_and_scale_data.py","file_name":"clean_and_scale_data.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"343390413","text":"import click\nimport itertools as it\nimport re\nimport time\nimport yaml\n\ndef read_file(filepath):\n \"\"\"\n Read file from *filepath*.\n\n Args:\n filepath (str): Path to file.\n\n Returns:\n File content.\n \"\"\"\n return \"\".join(\n open(\n filepath\n ).readlines()\n )\n\n\ndef load_yaml(filepath):\n \"\"\"\n Read and parse yaml from *filepath*.\n\n Args:\n filepath (str): Path to file.\n\n Returns:\n Dictionary of YAML file.\n \"\"\"\n return yaml.load(\n read_file(filepath)\n )\n\n\ndef parse_config(filepath):\n \"\"\"\n Load yaml and parse environment variables.\n\n Args:\n filepath (str): Path to file.\n\n Returns:\n Dictionary of YAML file with parsed environment variables.\n \"\"\"\n return replace_keys(\n load_yaml(filepath),\n v_func=env_var_or_object\n )\n\n\ndef env_var_or_object(object):\n \"\"\"\n In a dict, recursively replace *$variables*\n with their corresponding values.\n\n Args:\n object (object): Any object.\n\n Returns:\n Modified object.\n \"\"\"\n if isinstance(object, str):\n if re.match(\"\\$[A-Z]+\", object):\n return os.environ[object.replace(\"$\", \"\")]\n return object\n\n\ndef replace_keys(data, k_func=None, v_func=None):\n \"\"\"\n Recursively replace keys and or values\n of a data structure according to provided functions.\n \"\"\"\n k_func = (lambda x: x) if k_func is None else k_func\n v_func = (lambda x: x) if v_func is None else v_func\n if isinstance(data, dict):\n return {\n k_func(key): replace_keys(\n data[key],\n k_func,\n v_func\n ) for key in data\n }\n elif isinstance(data, list):\n return map(\n lambda x: replace_keys(\n x,\n k_func,\n v_func),\n data\n )\n return v_func(data)\n\n\ndef chunks(iterable, size=1000):\n x = iter(iterable)\n sizes = [size] if isinstance(size, int) else size\n while True:\n size = sizes.pop(0) if len(sizes) > 1 else sizes[0]\n chunk = tuple(it.islice(x, size))\n if not chunk:\n return\n yield chunk\n\ndef time_str():\n return time.strftime('%H:%M:%S')\n\ndef log(message):\n click.echo(\" \".join([\n \"\".join([\"[\", time_str(), \"]\"]),\n message\n ]))\n","sub_path":"dataflow/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"344940503","text":"\"\"\"\n这里声明各种模型中 GMeta 中的配置的键的常量\n\"\"\"\n\n\n\"\"\"在序列化时,指定排除的字段,数据格式为列表或者元组\"\"\"\nGMETA_SERIALIZER_EXCLUDE_FIELDS = 'exclude_fields'\n\n\"\"\"输出 schema 中的 title_field,数据类型:字符串\"\"\"\nGMETA_TITLE_FIELD = 'title_field'\n\n\"\"\"\n字段的重置配置,例如觉得字段默认的 verbose_name 不好看可以使用此配置,例子如下:\n\nfield_form_config = {\n 'comments': {\n 'verbose_name': '我是谁',\n 'required': False,\n }\n}\n\"\"\"\nGMETA_FIELD_CONFIG = 'field_form_config'\n\n\"\"\"\ndjango 中声明的字段的配置和输出配置键的映射\n\n此常量供业务内部调用\n\"\"\"\nGMETA_FIELD_CONFIG_MAP = {\n 'verbose_name': 'displayName'\n}\n\n\n\"\"\"\n创建数据时,添加用户时,指定的用户的字段\n\n数据类型:str\n\n- 在创建数据时,根据指定的字段,自动插入用户的数据\n\"\"\"\nGMETA_CLIENT_USER_FIELD = 'client_user_field'\n\n\"\"\"\n筛选数据时,是否根据当前登录用户进行筛选\n\n数据类型:bool\n\"\"\"\nGMETA_CLIENT_FILTER_BY_LOGIN_USER = 'client_filter_by_login_user'\n\n\"\"\"\n客户端接口不需要权限的设置\n\n数据类型:tuple,其中元素为客户单视图中的视图方法,例如 create, update 等等这些\n\n例如客户端首页的商品是不需要权限就可以浏览的,此时配置如下:\n\nclient_api_permission_skip = ('list', 'set', 'retrieve')\n\"\"\"\nGMETA_CLIENT_API_PERMISSION_SKIP = 'client_api_permission_skip'\n\n\n\"\"\"\n客户端接口认证的设置\n\n数据类型:tuple 其中元素为客户视图中的视图方法,例如 create, update 等等这些\n\n例如客户端有些模型的删除接口禁止访问,此时配置如下\n\nclient_api_no_authentication = ('destroy', )\n\"\"\"\nGMETA_CLIENT_API_NO_AUTHENTICATION = 'client_api_no_authentication'\n\n\"\"\"\n客户端接口允许调用的方法,默认使用白名单模式\n\n数据类型:tuple 其中元素为客户视图中的视图方法,例如 create, update 等等这些\n\n例如客户端有些模型只允许创建和更新接口,此时配置如下\n\nclient_api_authenticate_methods = ('create', 'update')\n\"\"\"\nGMETA_CLIENT_API_AUTHENTICATE_METHODS = 'client_api_authenticate_methods'\n\n\"\"\"计算属性,即@property函数,只允许读,不允许写,配置方式:\ncomputed_fields = (\n {'func_name', 'type', 'displayName', 'choices'},\n)\n\"\"\"\nGMETA_COMPUTED_FIELDS = 'computed_fields'\n\n\"\"\"\n使用Django的annotate来作计算字段\nannotated_fields = {\n 'distribution_num': {\n 'display_name': '分销收益次数',\n 'annotation': models.Count('walletbill'),\n 'type': FieldType.INTEGER,\n }\n}\n\"\"\"\nGMETA_ANNOTATED_FIELDS = 'annotated_fields'\n\nGMETA_OBJECT_VALIDATORS = 'validators'\n\n\"\"\"\nmanagers, 对应不同场景下,有不同的queryset,结构如下:\nmanagers = {\n 'client_api': xxxx,\n 'manager_api': yyyy,\n}\n\"\"\"\nGMETA_MANAGERS = 'managers'\n\n\"\"\"管理端导出文件指定的扩展字段 列表 List\n\nmanage_export_expand_fields = []\n\"\"\"\nGMETA_MANAGE_EXPORT_EXPAND_FIELDS = 'manage_export_expand_fields'\n\n\n\"\"\"管理端导出文件指定的字段 列表 List\n\nmanage_export_expand_fields = []\n\"\"\"\nGMETA_MANAGE_EXPORT_FIELDS = 'manage_export_fields'\n\n\n\"\"\"管理端迭代模型反向关系字段名称 字符串 str\n\nmanage_export_reverse_field = []\n\"\"\"\nGMETA_MANAGE_REVERSE_FIELD = 'manage_export_reverse_field'\n\n\n\"\"\"管理端模型反向关系字段和顶级字段的映射 字典 dict\n\nmanage_export_reverse_fields_map = []\n\"\"\"\nGMETA_MANAGE_REVERSE_FIELDS_MAP = 'manage_export_reverse_fields_map'\n\nGMETA_CREATOR_FIELD = 'creator_field'\nGMETA_UPDATER_FIELD = 'updater_field'\n","sub_path":"api_basebone/core/gmeta.py","file_name":"gmeta.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"336283346","text":"import os\nimport time\nfrom threading import Thread\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot\nfrom PyQt5.QtWidgets import QWidget, QGridLayout\nfrom source.UI.widgets.extensions import set_widget_background\nfrom source.UI.widgets.resizeable_image import ResizeableImage\nfrom source.UI.widgets.resizeable_text import ResizeableText\nfrom source.components.language.language import Language\nfrom source.components.weather.weather_controller import WeatherController\n\n\nclass WeatherWidget(QWidget):\n time_to_update = pyqtSignal()\n\n def __init__(self):\n super().__init__()\n lang = Language()\n weather = WeatherController('yandex').current_weather('Минск')\n self.header_label = ResizeableText(f'{lang[\"now\"]} {lang[\"in\"]} {weather.city}: {weather.condition}')\n self.cloud_widget = ResizeableImage(f'{os.path.dirname(__file__)}\\images\\weather\\{weather.image}')\n self.temperature_widget = ResizeableText(f'{weather.temperature}{lang[\"deg_m\"]}')\n self.wind_label = ResizeableText(lang['wind'])\n self.wind_widget = ResizeableText(f'{weather.wind} {lang[\"wind_m\"]}, {weather.wind_direction_abbr}')\n self.pressure_label = ResizeableText(lang['pressure'])\n self.pressure_widget = ResizeableText(f'{weather.pressure} {lang[\"pressure_m\"]}')\n self.humidity_label = ResizeableText(lang['humidity'])\n self.humidity_widget = ResizeableText(f'{weather.humidity}{lang[\"humidity_m\"]}')\n self.init_ui()\n self.init_threads()\n\n def init_ui(self):\n self.init_layout()\n self.setStyleSheet(\"ResizeableText {color: white}\")\n set_widget_background(self)\n\n def init_layout(self):\n layout = QGridLayout()\n layout.addWidget(QWidget(), 0, 0, 1, 8)\n layout.addWidget(self.header_label, 1, 1, 1, 6)\n layout.addWidget(self.cloud_widget, 2, 1, 2, 2)\n layout.addWidget(self.temperature_widget, 2, 3, 2, 2)\n layout.addWidget(self.wind_label, 4, 1, 1, 2)\n layout.addWidget(self.wind_widget, 5, 1, 1, 2)\n layout.addWidget(self.pressure_label, 4, 3, 1, 2)\n layout.addWidget(self.pressure_widget, 5, 3, 1, 2)\n layout.addWidget(self.humidity_label, 4, 5, 1, 2)\n layout.addWidget(self.humidity_widget, 5, 5, 1, 2)\n layout.addWidget(QWidget(), 6, 0, 1, 8)\n self.setLayout(layout)\n\n def init_threads(self):\n self.time_to_update.connect(self.update)\n Thread(target=self.clock, daemon=True).start()\n\n def clock(self):\n while True:\n time.sleep(900)\n self.time_to_update.emit()\n\n @pyqtSlot()\n def update(self):\n lang = Language()\n weather = WeatherController('yandex').current_weather('Минск')\n self.header_label.set_text(f'{lang[\"now\"]} {lang[\"in\"]} {weather.city}: {weather.condition}')\n self.cloud_widget.set_image(f'{os.path.dirname(__file__)}\\images\\weather\\{weather.image}')\n self.temperature_widget.set_text(f'{weather.temperature}{lang[\"deg_m\"]}')\n self.wind_label.set_text(lang['wind'])\n self.wind_widget.set_text(f'{weather.wind} {lang[\"wind_m\"]}, {weather.wind_direction_abbr}')\n self.pressure_label.set_text(lang['pressure'])\n self.pressure_widget.set_text(f'{weather.pressure} {lang[\"pressure_m\"]}')\n self.humidity_label.set_text(lang['humidity'])\n self.humidity_widget.set_text(f'{weather.humidity}{lang[\"humidity_m\"]}')\n","sub_path":"Mirror/source/UI/widgets/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"317854508","text":"from __future__ import print_function\nimport argparse\nimport os\nimport sys\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport sys\nsys.path.append('..')\nfrom models import Feat2_ResNet18\nfrom utils import Logger\nfrom loss import Proximity, Con_Proximity\n\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch CIFAR model Train')\nparser.add_argument('--batch-size', type=int, default=256, metavar='N',help='input batch size for training (default: 64)')\nparser.add_argument('--test-batch-size', type=int, default=512, metavar='N',help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=100, metavar='N',help='number of epochs to train (default: 10)')\nparser.add_argument('--lr_model', type=float, default=0.01, help=\"learning rate for CE Loss\")\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',help='SGD momentum (default: 0.5)')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,metavar='W', help='weight decay (default: 1e-4)')\nparser.add_argument('--lr_prox', type=float, default=0.5, help=\"learning rate for Proximity Loss\") # as per paper\nparser.add_argument('--weight-prox', type=float, default=1, help=\"weight for Proximity Loss\") # as per paper\nparser.add_argument('--lr_conprox', type=float, default=0.0001,help=\"learning rate for Con-Proximity Loss\") # as per paper\nparser.add_argument('--weight-conprox', type=float, default=0.0001,help=\"weight for Con-Proximity Loss\")\nparser.add_argument('--no-cuda', action='store_true', default=False,help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=49, metavar='N',help='how many batches to wait before logging training status')\nparser.add_argument('--save-dir', type=str, default='log')\nargs = parser.parse_args()\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\nsys.stdout = Logger(os.path.join(args.save_dir, 'resnet18_pcl' + '.txt'))\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10('../data', train=True, download=True,\n transform=transforms.Compose([\n transforms.Pad(4),\n transforms.RandomCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n ])),\n batch_size=args.batch_size, shuffle=True, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10('../data', train=False, transform=transforms.Compose([transforms.ToTensor(),])),\n batch_size=args.test_batch_size, shuffle=False, **kwargs)\n\nnum_classes = 10\nuse_gpu = args.cuda\nmodel = Feat2_ResNet18()\nif args.cuda:\n model.cuda()\nfilename = '../checkpoint/resnet18/resnet18_vallina.pth'\ncheckpoint = torch.load(filename)\nmodel.load_state_dict(checkpoint)\ncriterion_xent = nn.CrossEntropyLoss()\ncriterion_prox_512 = Proximity(num_classes=num_classes, feat_dim=512, use_gpu=use_gpu)\ncriterion_prox_256 = Proximity(num_classes=num_classes, feat_dim=256, use_gpu=use_gpu)\n\ncriterion_conprox_512 = Con_Proximity(num_classes=num_classes, feat_dim=512, use_gpu=use_gpu)\ncriterion_conprox_256 = Con_Proximity(num_classes=num_classes, feat_dim=256, use_gpu=use_gpu)\n\noptimizer_model = torch.optim.SGD(model.parameters(), lr=args.lr_model, weight_decay=args.weight_decay, momentum=args.momentum)\n\noptimizer_prox_512 = torch.optim.SGD(criterion_prox_512.parameters(), lr=args.lr_prox)\noptimizer_prox_256 = torch.optim.SGD(criterion_prox_256.parameters(), lr=args.lr_prox)\n\noptimizer_conprox_512 = torch.optim.SGD(criterion_conprox_512.parameters(), lr=args.lr_conprox)\noptimizer_conprox_256 = torch.optim.SGD(criterion_conprox_256.parameters(), lr=args.lr_conprox)\n\n\ndef train(epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n feats256, feats512, outputs = model(data)\n loss_xent = criterion_xent(outputs, target)\n\n loss_prox_512 = criterion_prox_512(feats512, target)\n loss_prox_256 = criterion_prox_256(feats256, target)\n\n loss_conprox_512 = criterion_conprox_512(feats512, target)\n loss_conprox_256 = criterion_conprox_256(feats256, target)\n\n loss_prox_512 *= args.weight_prox\n loss_prox_256 *= args.weight_prox\n\n loss_conprox_512 *= args.weight_conprox\n loss_conprox_256 *= args.weight_conprox\n\n loss = loss_xent + loss_prox_512 + loss_prox_256 - loss_conprox_512 - loss_conprox_256 # total loss\n optimizer_model.zero_grad()\n\n optimizer_prox_512.zero_grad()\n optimizer_prox_256.zero_grad()\n\n optimizer_conprox_512.zero_grad()\n optimizer_conprox_256.zero_grad()\n\n loss.backward()\n optimizer_model.step()\n\n for param in criterion_prox_512.parameters():\n param.grad.data *= (1. / args.weight_prox)\n optimizer_prox_512.step()\n\n for param in criterion_prox_256.parameters():\n param.grad.data *= (1. / args.weight_prox)\n optimizer_prox_256.step()\n\n for param in criterion_conprox_512.parameters():\n param.grad.data *= (1. / args.weight_conprox)\n optimizer_conprox_512.step()\n\n for param in criterion_conprox_256.parameters():\n param.grad.data *= (1. / args.weight_conprox)\n optimizer_conprox_256.step()\n\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.1f}%)]\\tLoss: {:.6f}\\tLoss_xce: {:.6f}\\tLoss_prox256: {:.6f}'\n '\\tLoss_prox512: {:.6f}\\tLoss_conprox256: {:.6f}\\tLoss_conprox512: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader),\n loss.item(),loss_xent.item(),loss_prox_256.item(),loss_prox_512.item(),\n loss_conprox_256.item(),loss_conprox_512.item()))\n\n torch.save(model.state_dict(), '../checkpoint/resnet18/resnet18_pcl.pth')\n\n\ndef inference():\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n _, _, output = model(data)\n test_loss += F.cross_entropy(output, target, reduction='sum').item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n test_loss /= len(test_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * float(correct) / len(test_loader.dataset)))\n\n\nfor epoch in range(1, args.epochs + 1):\n if epoch in [args.epochs * 0.5, args.epochs * 0.75, args.epochs * 0.9]:\n for param_group in optimizer_model.param_groups:\n param_group['lr'] *= 0.1\n for param_group in optimizer_prox_256.param_groups:\n param_group['lr'] *= 0.1\n for param_group in optimizer_conprox_256.param_groups:\n param_group['lr'] *= 0.1\n for param_group in optimizer_prox_512.param_groups:\n param_group['lr'] *= 0.1\n for param_group in optimizer_conprox_512.param_groups:\n param_group['lr'] *= 0.1\n print(\"Learning rate reduced.\")\n train(epoch)\n inference()","sub_path":"lab_resnet34/train_model/train_pcl.py","file_name":"train_pcl.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"414029969","text":"#! /usr/local/bin/env python\n# -*- coding: utf-8 -*-\nimport random\nimport numpy as np\nimport time\nimport copy\nfrom sklearn import linear_model\nfrom statistics import mean, stdev\nfrom math import log10\n\n# defined parameters\ntsg_non_site = 191624\ntsg_syn_site = 61470\ncont_non_site = 923307\ncont_syn_site = 319944\nmean_onset_age = 61.5\nage_sd = 13.5\n\n\n# define class of parameters\nclass parameter_object:\n def __init__(self,\n N,\n mutation_rate_coef,\n mutater_effect,\n mutater_mutation_rate,\n mutater_damage,\n tsg_non_damage,\n cont_non_damage,\n cont_non_fitness_only,\n fitness_coef,\n cancer_prob_coef,\n syn_damage=0):\n self.N = N\n self.mutation_rate = 1*(10**-8)*mutation_rate_coef\n self.mutater_effect = mutater_effect\n self.mutater_mutation_rate = mutater_mutation_rate\n tsgnon_d_list = np.random.exponential(tsg_non_damage, tsg_non_site)\n self.tsgnon_d = tsgnon_d_list.tolist()\n contnon_d_list = np.random.exponential(cont_non_damage, cont_non_site)\n self.contnon_d = contnon_d_list.tolist()\n syn_d_list = np.random.exponential(syn_damage, tsg_syn_site)\n self.syn_d = syn_d_list.tolist()\n self.cont_non_fitness_only = cont_non_fitness_only\n self.fitness_coef = fitness_coef\n self.cancer_prob_coef = cancer_prob_coef\n\n\ndef genotype_divide(mutations):\n homo = [x for x in set(mutations) if mutations.count(x) > 1]\n hetero = list(set(mutations) - set(homo))\n return(homo, hetero)\n\n\nclass Individual:\n def __init__(self, mutater, tsg_non, tsg_syn, cont_non, parameters):\n self._mutater = mutater\n self._tsg_non_hom, self._tsg_non_het = genotype_divide(tsg_non)\n self._tsg_syn_hom, self._tsg_syn_het = genotype_divide(tsg_syn)\n self._cont_non_hom, self._cont_non_het = genotype_divide(cont_non)\n damage = sum([parameters.tsgnon_d[mut] for mut in tsg_non])\n damage += sum([parameters.syn_d[mut] for mut in tsg_syn])\n if parameters.cont_non_fitness_only == \"T\":\n damage += sum([parameters.contnon_d[mut] for mut in cont_non])\n self._damage = damage\n fitness = 1 - damage * parameters.fitness_coef\n if parameters.cont_non_fitness_only == \"F\":\n cn_dam = sum([parameters.contnon_d[mut] for mut in cont_non])\n fitness -= cn_dam * parameters.fitness_coef\n self._fitness = 0 if fitness < 0 else fitness\n\n @property\n def mutater(self):\n return self._mutater\n\n @property\n def damage(self):\n return self._damage\n\n @property\n def fitness(self):\n return self._fitness\n\n # get [tsg_non_het, tsg_syn_het, cont_non_het, cont_syn_het]\n def mutations(self):\n mutations = copy.deepcopy([self._tsg_non_het, self._tsg_syn_het])\n mutations += copy.deepcopy([self._cont_non_het])\n return(mutations)\n\n # get [tsg_non_homo, tsg_syn_homo, cont_non_homo, cont_syn_homo]\n def homo_mutations(self):\n mutations = copy.deepcopy([self._tsg_non_hom, self._tsg_syn_hom])\n mutations += copy.deepcopy([self._cont_non_hom])\n return(mutations)\n\n def add_tsg_non(self, muts):\n old_het = set(copy.copy(self._tsg_non_het))\n old_hom = set(copy.copy(self._tsg_non_hom))\n self._tsg_non_het = list(old_het ^ set(muts))+list(old_hom & set(muts))\n self._tsg_non_hom = list(old_hom ^ set(muts))+list(old_het & set(muts))\n\n def add_tsg_syn(self, muts):\n old_het = set(copy.copy(self._tsg_syn_het))\n old_hom = set(copy.copy(self._tsg_syn_hom))\n self._tsg_syn_het = list(old_het ^ set(muts))+list(old_hom & set(muts))\n self._tsg_syn_hom = list(old_hom ^ set(muts))+list(old_het & set(muts))\n\n def add_cont_non(self, muts):\n old_het = set(copy.copy(self._cont_non_het))\n old_hom = set(copy.copy(self._cont_non_hom))\n self._cont_non_het = list(old_het ^ set(muts))\n self._cont_non_het += list(old_hom & set(muts))\n self._cont_non_hom = list(old_hom ^ set(muts))\n self._cont_non_hom += list(old_het & set(muts))\n\n def add_mutater(self, add_num):\n bef = copy.copy(self._mutater)\n if bef+add_num != 2:\n self._mutater = (bef+add_num) % 2\n elif bef == 1 and add_num == 1:\n self._mutater = np.random.randint(2)\n else:\n self.mutater = 2\n\n def variant_num_tsg_non(self, variant_list):\n num = len(set(self._tsg_non_het) & set(variant_list))\n num += len(set(self._tsg_non_hom) & set(variant_list)) * 2\n return(num)\n\n def variant_num_tsg_syn(self, variant_list):\n num = len(set(self._tsg_syn_het) & set(variant_list))\n num += len(set(self._tsg_syn_hom) & set(variant_list)) * 2\n return(num)\n\n def variant_num_cont_non(self, variant_list):\n num = len(set(self._cont_non_het) & set(variant_list))\n num += len(set(self._cont_non_hom) & set(variant_list)) * 2\n return(num)\n\n\n# make de nove mutations list (list of each ind de novo mutation num)\ndef new_mutation(mutater_num, site_num, params):\n mutation_rate = params.mutation_rate * site_num\n mut_ef = params.mutater_effect\n mut0 = np.random.poisson(mutation_rate, mutater_num.count(0)).tolist()\n mut1 = np.random.poisson(mutation_rate * mut_ef,\n mutater_num.count(1)).tolist()\n mut2 = np.random.poisson(mutation_rate * (mut_ef**2),\n mutater_num.count(2)).tolist()\n new_mus = []\n for i in range(params.N):\n if mutater_num[i] == 0:\n new_mus.append(mut0.pop())\n elif mutater_num[i] == 1:\n new_mus.append(mut1.pop())\n else:\n new_mus.append(mut2.pop())\n return new_mus\n\n\n# make offspring from two Individuals\ndef reproduct(ind1, ind2, params):\n mutater = np.random.binomial(ind1.mutater + ind2.mutater, 0.5)\n mutater = 2 if mutater > 2 else mutater\n muts = [ind1.mutations()[i] + ind2.mutations()[i] for i in range(3)]\n new_mut = [random.sample(l, np.random.binomial(len(l), 0.5)) for l in muts]\n new_mut = [new_mut[i] + ind1.homo_mutations()[i] for i in range(3)]\n return(Individual(mutater, *new_mut, params))\n\n\nclass Population:\n def __init__(self, params):\n self.individuals = [Individual(mutater=0, tsg_non=[], tsg_syn=[],\n cont_non=[], parameters=params)\n for i in range(params.N)]\n\n def get_fitness_list(self, params):\n fitness_list = [ind.fitness for ind in self.individuals]\n fit_sum = sum(fitness_list)\n fitness_list = [fit / fit_sum for fit in fitness_list]\n return fitness_list\n\n def get_cancer_prob(self, params):\n damage_list = [ind.damage for ind in self.individuals]\n prob_list = [1 + d * params.cancer_prob_coef for d in damage_list]\n prob_list = [0 if p < 0 else p for p in prob_list]\n prob_list = [prob / sum(prob_list) for prob in prob_list]\n return prob_list\n\n def get_mutater(self):\n mutater_list = [ind.mutater for ind in self.individuals]\n return(mutater_list)\n\n # add new mutations to each individuals\n def add_new_mutation(self, params):\n # individuals num of [mutater=0, mutater=1, mutater=2]\n mutater_num = self.get_mutater()\n new_mutater = np.random.binomial(1, params.mutater_mutation_rate,\n params.N).tolist()\n new_mut_tn = new_mutation(mutater_num, tsg_non_site, params)\n new_mut_ts = new_mutation(mutater_num, tsg_syn_site, params)\n new_mut_cn = new_mutation(mutater_num, cont_non_site, params)\n for n in range(params.N):\n if self.individuals[n].mutater < 2:\n self.individuals[n].add_mutater(new_mutater[n])\n if new_mut_tn[n] != 0:\n new_mus = np.random.randint(0, tsg_non_site,\n new_mut_tn[n]).tolist()\n self.individuals[n].add_tsg_non(new_mus)\n if new_mut_ts[n] != 0:\n new_mus = np.random.randint(0, tsg_syn_site,\n new_mut_ts[n]).tolist()\n self.individuals[n].add_tsg_syn(new_mus)\n if new_mut_cn[n] != 0:\n new_mus = np.random.randint(0, cont_non_site,\n new_mut_cn[n]).tolist()\n self.individuals[n].add_cont_non(new_mus)\n\n # make next generation population\n def next_generation_wf(self, params):\n fitness = self.get_fitness_list(params=params)\n rand_ind = np.random.choice(self.individuals, params.N*2, p=fitness)\n next_generation = [reproduct(rand_ind[n], rand_ind[n+1], params)\n for n in range(0, params.N*2, 2)]\n self.individuals = next_generation\n\n def variant_allelecount(self):\n v_AC = [[0 for i in range(tsg_non_site)]]\n v_AC += [[0 for i in range(tsg_syn_site)]]\n v_AC += [[0 for i in range(cont_non_site)]]\n for ind in self.individuals:\n het_muts = ind.mutations()\n hom_muts = ind.homo_mutations()\n for i in range(3):\n for het_mut in het_muts[i]:\n v_AC[i][het_mut] += 1\n for hom_mut in hom_muts[i]:\n v_AC[i][hom_mut] += 2\n return(v_AC)\n\n def print_rare_variant_num(self, params):\n v_AC = self.variant_allelecount()\n rare_nums = [0, 0, 0]\n for i in range(3):\n rare_nums[i] = sum([v_num for v_num in v_AC[i]\n if v_num < params.N*2*0.0005])\n return(rare_nums)\n\n def print_summary(self, params, sample_num=6000):\n sample_num = params.N if sample_num > params.N else sample_num\n v_AC = self.variant_allelecount()\n rare_variants = [[], [], []]\n rare_nums = []\n for i in range(3):\n rare_variants[i] = [v for v in range(len(v_AC[i]))\n if v_AC[i][v] < params.N*2*0.0005]\n rare_nums += [sum([v_AC[i][v] for v in rare_variants[i]])]\n cancer_prob = self.get_cancer_prob(params)\n sample = np.random.choice(self.individuals, sample_num,\n p=cancer_prob, replace=False).tolist()\n sample_age = [mean_onset_age-ind.damage for ind in sample]\n sample_age = [0 if age < 0 else age for age in sample_age]\n sample_tn_num = [ind.variant_num_tsg_non(rare_variants[0])\n for ind in sample]\n sample_ts_num = [ind.variant_num_tsg_syn(rare_variants[1])\n for ind in sample]\n sample_cn_num = [ind.variant_num_cont_non(rare_variants[2])\n for ind in sample]\n sample_age = np.array(sample_age).reshape(-1, 1)\n sample_tn_num = np.array(sample_tn_num).reshape(-1, 1)\n sample_ts_num = np.array(sample_ts_num).reshape(-1, 1)\n sample_cn_num = np.array(sample_cn_num).reshape(-1, 1)\n tsg_non_reg = linear_model.LinearRegression()\n tsg_non_reg.fit(sample_age, sample_tn_num)\n tsg_syn_reg = linear_model.LinearRegression()\n tsg_syn_reg.fit(sample_age, sample_ts_num)\n cont_non_reg = linear_model.LinearRegression()\n cont_non_reg.fit(sample_age, sample_cn_num)\n return(*rare_nums,\n float(tsg_non_reg.coef_), float(tsg_syn_reg.coef_),\n float(cont_non_reg.coef_))\n\n\ndef simulation(parameter_obj, times):\n t1 = time.time()\n population = Population(params=parameter_obj)\n focal = True\n tsgnon_v_num = []\n tsgsyn_v_num = []\n contnon_v_num = []\n generation = 0\n with open(f\"equiv{times}.tsv\", \"w\", 1) as out:\n while focal:\n generation += 1\n population.add_new_mutation(parameter_obj)\n population.next_generation_wf(parameter_obj)\n v_nums = population.print_rare_variant_num(parameter_obj)\n print(generation, *v_nums, sep=\"\\t\", file=out)\n if generation <= 100:\n tsgnon_v_num.append(v_nums[0])\n tsgsyn_v_num.append(v_nums[1])\n contnon_v_num.append(v_nums[2])\n else:\n del tsgnon_v_num[0]\n del tsgsyn_v_num[0]\n del contnon_v_num[0]\n tsgnon_v_num.append(v_nums[0])\n tsgsyn_v_num.append(v_nums[1])\n contnon_v_num.append(v_nums[2])\n tn = stdev(tsgnon_v_num)/mean(tsgnon_v_num)\n ts = stdev(tsgsyn_v_num)/mean(tsgsyn_v_num)\n cn = stdev(contnon_v_num)/mean(contnon_v_num)\n if (tn < 0.05 and ts < 0.05 and cn < 0.05) or generation > 500:\n focal = False\n # if generation % 10 == 0:\n # t2 = time.time()\n # elapsed_time = t2 - t1\n # muter = population.get_mutater()\n # muter_num = [muter.count(0), muter.count(1), muter.count(2)]\n # print(f\"now {generation} : {elapsed_time} sec:\")\n # print(v_nums, muter_num)\n result = population.print_summary(parameter_obj)\n t2 = time.time()\n elapsed_time = t2 - t1\n print(f\"all time spent {generation} : {elapsed_time} sec\")\n return(result)\n\n\ndef log_rand(min, max):\n log_min = log10(min) if min != 0 else log10(0.000001)\n log_max = log10(max)\n x = random.uniform(log_min, log_max)\n x = 10 ** x if x != 0.000001 else 0\n return(x)\n\n\ndef rand_params():\n rand = random.uniform\n p_list = [50000, # N\n rand(1, 10), # mutation_rate_coef\n rand(5, 50), # mutation_effect\n rand(0, 0.01), # mutater_mutation_rate\n rand(0, 5), # mutater_damage\n rand(0.1, 2), # tsg_non_damage\n rand(0.1, 1), # cont_non_damage\n random.choice([\"T\", \"F\"]), # cont_non_fitness_only\n log_rand(0.001, 0.5), # fitness_coef\n log_rand(0, 0.1)] # cancer_prob_coef\n return(p_list)\n\n\nwith open(\"pre_run.tsv\", \"w\", 1) as f:\n cols = [\"N\", \"mutation_rate_coef\", \"mutater_effect\", \"mutater_damage\",\n \"tsg_non_damage\", \"cont_non_damage\", \"cont_non_fitness_only\",\n \"fitness_coef\", \"cancer_prob_coef\",\n \"tsg_non_num\", \"tsg_syn_num\", \"cont_non_num\",\n \"tsg_non_reg\", \"tsg_syn_reg\", \"cont_non_reg\"]\n print(*cols, sep='\\t', file=f)\n for times in range(100):\n print(f\"simulate {times}\")\n rand_parameters = rand_params()\n out = simulation(parameter_object(*rand_parameters), times)\n print(*rand_parameters, *out, sep='\\t', file=f)\n","sub_path":"python/supplement/equiv_test.py","file_name":"equiv_test.py","file_ext":"py","file_size_in_byte":14988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"650534155","text":"import face_recognition\nimport os\nimport pickle\nimport postgresql\nimport sys\nimport dlib\nimport cv2\nimport re\nimport time\nimport base64\nimport json\nimport requests\nfrom io import BytesIO\n\n\ndef addPerson(PersonName , filepath):\n \n #Connect to DB\n db = postgresql.open('pq://bayan:toor@localhost:5432/test')\n \n known_image = face_recognition.load_image_file(filepath)\n encodings = face_recognition.face_encodings(known_image)\n print(known_image)\n if len(encodings) > 0:\n query = \"INSERT INTO vectors (file, vec_low) VALUES ('{}', CUBE(array[{}]) )\".format(\n PersonName,\n ','.join(str(s) for s in encodings[0][0:128]), \n )\n \n print(PersonName + ' has been added')\n db.execute(query) \n\n print(\"Added : \", PersonName)\n\ndef addPersonAPI(name , NewPath):\n email = \" \"\n with open(NewPath, \"rb\") as img_file:\n my_string = base64.b64encode(img_file.read())\n \n data = {'name':name,'email':email,'img64b':my_string}\n \n res = requests.post(url='http://192.168.10.9:5000/', data=data)\n \n if res.ok:\n print(\"response : \",res.text)\n\n resText = json.loads(res.text)\n\n if resText[\"found Person In DB\"]: \n print(\"person already exists!!!!!!!\")\n error = \"User Already Exists\"\n elif resText[\"number of faces found\"] > 1:\n print(\"More than one Face in Image!!!!!!!\")\n error = \"More than one Face in Image\"\n elif not(resText[\"Good Image\"]):\n print(\"Image is Bad!!!!!!!!!\")\n error = \"Image quality is too low\"\n else:\n print(\"Everything is Good\") \n error =\"Successful\"\n \n \n return error\n\n\n\n\n\n'''\n #print(face_encoding)\n entry = {'name': PersonName, 'embeddings': face_encoding}\n if not os.path.isfile(DATA_FILENAME):\n with open(DATA_FILENAME, 'wb') as outfile:\n pickle.dump(entry, outfile)\n\n else:\n with open(DATA_FILENAME, 'ab') as f:\n pickle.dump(entry, f, pickle.HIGHEST_PROTOCOL)\n #json.dump(entry, f)\n #f.write(os.linesep)\n'''\n \n","sub_path":"faceModule.py","file_name":"faceModule.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"613710732","text":"#!/usr/bin/python3\nimport re\n\n\nwith open('15.dat') as f:\n data = f.read()\nlines = data.split('\\n')\nlines.pop()\nregex = r\"(\\w+): \\w+ (-*\\d+), \\w+ (-*\\d+), \\w+ (-*\\d), \\w+ (-*\\d+), \\w+ (-*\\d+)\"\ningredient = list()\nfor line in lines:\n m = re.match(regex, line)\n ingredient.append((m.group(1), int(m.group(2)), int(m.group(3)),\n int(m.group(4)), int(m.group(5)), int(m.group(6))))\n# print(ingredient)\nbest = 0\nbest_ratio = list()\nfor i in range(100):\n for j in range(100):\n for k in range(100):\n for l in range(100):\n if (i + j + k + l) == 100:\n capacity = i * ingredient[0][1] + j * ingredient[1][1] +\\\n k * ingredient[2][1] + l * ingredient[3][1]\n durability = i * ingredient[0][2] + j * ingredient[1][2] +\\\n k * ingredient[2][2] + l * ingredient[3][2]\n flavor = i * ingredient[0][3] + j * ingredient[1][3] +\\\n k * ingredient[2][3] + l * ingredient[3][3]\n texture = i * ingredient[0][4] + j * ingredient[1][4] +\\\n k * ingredient[2][4] + l * ingredient[3][4]\n if capacity < 0:\n capacity = 0\n if durability < 0:\n durability = 0\n if flavor < 0:\n flavor = 0\n if texture < 0:\n texture = 0\n score = capacity * durability * flavor * texture\n if score > best:\n best = score\n best_ratio = [i, j, k, l]\nprint(best, best_ratio)\n","sub_path":"15a.py","file_name":"15a.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"549762075","text":"import sys\r\nvowels = 'aeiou'\r\ninp = sys.stdin.readline()\r\n\r\nskip = 0\r\nfor char in inp:\r\n if skip > 0:\r\n skip -= 1\r\n \r\n else:\r\n print(char, end=\"\")\r\n for vowel in vowels:\r\n if char == vowel:\r\n skip = 2\r\n","sub_path":"Open/Python 3/kemija08.py","file_name":"kemija08.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"621229310","text":"from aiogram import Bot, Dispatcher, executor, types\nfrom aiogram.utils.exceptions import CantParseEntities\nfrom dotenv import load_dotenv, find_dotenv\nfrom signal import signal, SIGINT\nfrom tqdm import tqdm\nfrom os import getenv\nimport sys\nimport fire\nimport uvloop\nimport redis\n\nload_dotenv(find_dotenv('.telegram'))\nuvloop.install()\n\nREDIS_HOST = getenv('REDIS_URL', 'localhost')\nchannel_id = getenv('MY_TELEGRAM_NUMBER')\n\nasync def push_update(content, bot):\n try:\n return await bot.send_message(\n channel_id, content, parse_mode='Markdown')\n except CantParseEntities:\n return await bot.send_message(channel_id, content)\n\n\nasync def listen(source):\n r_conn = redis.Redis(REDIS_HOST)\n p = r_conn.pubsub(ignore_subscribe_messages=True)\n p.subscribe(source)\n for message in tqdm(p.listen()):\n yield message['data']\n\n\nasync def subscribe_and_listen(bot, channel_name='processed'):\n async for message in listen(channel_name):\n await push_update(message, bot)\n\ndef main():\n fire.Fire(TelegramPublisher)\n\nclass TelegramPublisher:\n def publish(self, channel_name='processed'):\n signal(SIGINT, interrupt_handler)\n try:\n loop = uvloop.new_event_loop()\n bot = Bot(token=getenv('TELEGRAM_KEY'), loop=loop)\n task = loop.create_task(subscribe_and_listen(bot, channel_name))\n loop.run_until_complete(task)\n finally:\n task.cancel()\n loop.run_until_complete(bot.close())\n loop.close()\n\n\ndef interrupt_handler(signal, frame):\n print('\\nYou pressed Ctrl+C!')\n sys.exit(0)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"step6_orchestration/telegram_publisher/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"642524815","text":"import tensorflow as tf\nimport numpy as np\nfrom keras.datasets import mnist\n\n(x_train,y_train),(x_test,y_test) = mnist.load_data()\n\n\nprint(x_train.shape) #(60000,28,28)\nprint(y_train.shape) #(60000,)\nprint(x_test.shape) #(10000,28,28)\nprint(y_test.shape) #(10000,)\n\nx_train = x_train.reshape(60000,784).astype('float32')/255\nx_test = x_test.reshape(10000,784).astype('float32')/255\n\nsess = tf.Session()\naaa = tf.one_hot(y_train,depth=10).eval(session=sess)\nbbb = tf.one_hot(y_test,depth=10).eval(session=sess)\n\nprint(aaa.shape)\nprint(bbb.shape)\n\nx = tf.placeholder(tf.float32, shape=[None, 784])\ny = tf.placeholder(tf.float32, shape=[None, 10])\n\n\n# 첫번째 레이어\n# 3 = hidden layer(내가 정하고 싶은대로)\nw1 = tf.Variable(tf.random_normal([784,500]), name = 'weight1', dtype = tf.float32)\nb1 = tf.Variable(tf.random_normal([500]), name = 'bias1',dtype = tf.float32)\nlayer1 = tf.matmul(x,w1) + b1\n\nw2 = tf.Variable(tf.zeros([500,300]), name = 'weight2', dtype = tf.float32)\nb2 = tf.Variable(tf.zeros([300]), name = 'bias2',dtype = tf.float32)\nlayer2 = tf.matmul(layer1,w2) + b2\n\n\nw3 = tf.Variable(tf.zeros([300,200]), name = 'weight3', dtype = tf.float32)\nb3 = tf.Variable(tf.zeros([200]), name = 'bias3',dtype = tf.float32)\nlayer3 = tf.matmul(layer2,w3) + b3\n\n\nw4 = tf.Variable(tf.zeros([200,100]), name = 'weight4', dtype = tf.float32)\nb4 = tf.Variable(tf.zeros([100]), name = 'bias4',dtype = tf.float32)\nlayer4 = tf.matmul(layer3,w4) + b4\n\n\nw5 = tf.Variable(tf.zeros([100,80]), name = 'weight5', dtype = tf.float32)\nb5 = tf.Variable(tf.zeros([80]), name = 'bias5',dtype = tf.float32)\nlayer5 = tf.matmul(layer4,w5) + b5\n\nw6 = tf.Variable(tf.zeros([80,60]), name = 'weight6', dtype = tf.float32)\nb6 = tf.Variable(tf.zeros([60]), name = 'bias6',dtype = tf.float32)\nlayer6 = tf.matmul(layer5,w6) + b6\n\nw7 = tf.Variable(tf.zeros([60,50]), name = 'weight7', dtype = tf.float32)\nb7 = tf.Variable(tf.zeros([50]), name = 'bias7',dtype = tf.float32)\nlayer7 = tf.matmul(layer6,w7) + b7\n\n\nw8 = tf.Variable(tf.zeros([50,30]), name = 'weight8', dtype = tf.float32)\nb8 = tf.Variable(tf.zeros([30]), name = 'bias8',dtype = tf.float32)\nlayer8 = tf.matmul(layer7,w8) + b8\n\nw9 = tf.Variable(tf.random_normal([30,10]), name = 'weight9', dtype = tf.float32)\nb9 = tf.Variable(tf.random_normal([10]), name = 'bias9',dtype = tf.float32)\nhypothesis = tf.nn.softmax(tf.matmul(layer8,w9) + b9)\n\n\n# 마지막 최종 나가는 값 hypothesis\n\ncost = -tf.reduce_mean(y * tf.log(hypothesis) + (1-y)* tf.log(1-hypothesis))\n\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate= 1e-2).minimize(cost)\n\n'''\ntf.cast 0.5 보다 크면 true 0.5 보다 작거나 같으면 False\n\ntf.cast\n입력한 값의 결과를 지정한 자료형으로 변환해줌\n\ntf.equal\ntf.equal(x, y) : x, y를 비교하여 boolean 값을 반환\n'''\n# accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted,tf.argmax(y,1)), dtype=tf.float32))\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer()) # 초기화==선언\n for step in range(101): #(epoch부분)\n _, hy_val, cost_val = sess.run([optimizer,hypothesis, cost],feed_dict={x:x_train,y:aaa})\n print(step,cost_val)\n\n correct_prediction = tf.equal(tf.argmax(hypothesis,1),tf.argmax(y,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n print(\"Accuracy:\",sess.run(accuracy,feed_dict={x:x_test,y:bbb}))\n","sub_path":"tf/tf15_mnist.py","file_name":"tf15_mnist.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"2971076","text":"import discord,asyncio\nfrom discord.ext import commands\n\nclass management(commands.Cog):\n def __init__(self,bot):\n self.bot = bot\n # Re-define the bot object into the class.\n\n @commands.command()\n @commands.has_permissions(manage_channels=True)\n async def wipe(self,ctx):\n await ctx.send(\"Wiping channel in 15 seconds. Say `cancel` to abort.\")\n def check(msg):# callback that waits for the user to say \"cancel\"\n if msg.author == ctx.author and msg.content.lower() == \"cancel\":\n return True\n try:# initiates callback\n msg = await ctx.bot.wait_for('message', check=check, timeout=15.0)\n except asyncio.TimeoutError:# if \"cancel\" is not received, wipe channel\n await ctx.channel.clone()\n await ctx.channel.delete()\n else:# abort if \"cancel\" is received\n await ctx.send(\"Operation aborted.\",delete_after=15)\n\n @commands.command()\n @commands.has_permissions(manage_messages=True)\n async def purge(self,ctx,limit=\"0\"):\n try:\n await ctx.channel.purge(limit=int(limit))\n except:\n await ctx.send(\":warning: I couldn't purge any messages. Did you give me the correct permissions?\")\n return\n await ctx.send(\"Purged **\" + limit + \"** messages!\",delete_after=5)\n \n @commands.command()\n @commands.has_permissions(manage_messages=True)\n async def purgeuser(self,ctx,limit,target:discord.Member):\n def is_user(m):# Check to see if a message's author is the desired user to purge.\n return m.author == target\n # Purge messages that are only from the desired user.\n await ctx.channel.purge(limit=int(limit), check=is_user)\n await ctx.send(\"done\")\n\n\"\"\"@commands.command()\n@commands.has_permissions(manage_guild=True)\nasync def setting(self,ctx,*,params=None):\n try:\n split_params = params.split()\n setting_name = str(params[0]).lower()\n except:\n await ctx.send(\":warning: Invalid parameters!\")\n if setting_name == \"antipingttl\" and is_integer(params[1]) == True:\n settings.\"\"\"\n\n\n\n\n\ndef setup(bot):\n bot.add_cog(management(bot))","sub_path":"cogs/management.py","file_name":"management.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"38494512","text":"#!/usr/bin/env python3\n\nimport sys\nimport re\nf = open(sys.argv[1], \"r\")\n\ndef nums(s):\n return [int(x) for x in re.findall(r'(-?\\d+).?', s)]\n\ns = f.read().strip();\n\nfor i in range(len(s) - 4):\n window = set(s[i:i+4])\n \n if len(window) == 4:\n print(i + 4)\n break\n","sub_path":"2022/6/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"629414136","text":"def main():\n n, k = map(int, input().split())\n history = [0]\n moves = list(input().split())\n\n undo = False\n for move in moves:\n if move == 'undo':\n undo = True\n elif undo:\n undo = False\n x = int(move)\n for _ in range(x):\n history.pop()\n else:\n x = int(move)\n history.append((history[-1] + 3 * n + x) % n)\n\n print(history[-1])\n\nmain()\n","sub_path":"kattis/throwns.py","file_name":"throwns.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"307270540","text":"from Modules import ModernGL as GL\r\nfrom Modules import Window as WND\r\nimport struct\r\n\r\nWND.InitializeWindow()\r\nWND.BuildFullscreen()\r\nGL.InitializeModernGL()\r\n\r\nvert = GL.NewVertexShader('''\r\n\t#version 400\r\n\r\n\tin vec2 vert;\r\n\r\n\tin vec4 vert_color;\r\n\tout vec4 frag_color;\r\n\r\n\tuniform vec2 scale;\r\n\tuniform float rotation;\r\n\r\n\tvoid main() {\r\n\t\tfrag_color = vert_color;\r\n\t\tmat2 rot = mat2(cos(rotation), sin(rotation), -sin(rotation), cos(rotation));\r\n\t\tgl_Position = vec4((rot * vert) * scale, 0.0, 1.0);\r\n\t}\r\n''')\r\n\r\nif not vert:\r\n\tprint('NewVertexShader failed')\r\n\tprint(GL.CompilerLog())\r\n\r\nfrag = GL.NewFragmentShader('''\r\n\t#version 400\r\n\t\r\n\tin vec4 frag_color;\r\n\tout vec4 color;\r\n\r\n\tvoid main() {\r\n\t\tcolor = frag_color;\r\n\t}\r\n''')\r\n\r\nif not frag:\r\n\tprint('NewFragmentShader failed')\r\n\tprint(GL.CompilerLog())\r\n\r\nwidth, height = WND.GetSize()\r\n\r\nprog = GL.NewProgram([vert, frag])\r\n\r\nverts = [\r\n\t1.0, 0.0,\r\n\t-0.5, 0.86,\r\n\t-0.5, -0.86,\r\n\t\r\n\t-1.0, 0.0,\r\n\t0.5, -0.86,\r\n\t0.5, 0.86,\r\n]\r\n\r\ncolors = [\r\n\t1.0, 0.0, 0.0, 0.5,\r\n\t0.0, 1.0, 0.0, 0.5,\r\n\t0.0, 0.0, 1.0, 0.5,\r\n\t1.0, 0.0, 0.0, 0.5,\r\n\t0.0, 1.0, 0.0, 0.5,\r\n\t0.0, 0.0, 1.0, 0.5,\r\n]\r\n\r\nvao = GL.NewVertexArray()\r\nvbo = GL.NewVertexBuffer(struct.pack('12f', *verts))\r\ncolor = GL.NewVertexBuffer(struct.pack('24f', *colors))\r\n\r\nGL.Attribute4f(color, GL.AttribLocation(prog, 'vert_color'))\r\nGL.Attribute2f(vbo, GL.AttribLocation(prog, 'vert'))\r\nrotation = GL.UniformLocation(prog, 'rotation')\r\nscale = GL.UniformLocation(prog, 'scale')\r\n\r\nGL.Uniform2f(scale, height / width * 0.75, 0.75)\r\n\r\nwhile WND.Update():\r\n\tGL.Clear(240, 240, 240)\r\n\tif WND.GetKey(WND.BTN_ESCAPE) & WND.KEY_PRESSED:\r\n\t\tbreak\r\n\r\n\tGL.UseProgram(prog)\r\n\tGL.EnableOnly(GL.ENABLE_BLEND | GL.ENABLE_MULTISAMPLE)\r\n\tGL.Uniform1f(rotation, WND.GetTime())\r\n\tGL.UseVertexArray(vao)\r\n\tGL.RenderTriangles(6)\r\n\r\n\tGL.DebugFontColor(32, 32, 32)\r\n\tGL.DebugFontPrint(0, 0, 'FPS %f' % WND.GetFPS())\r\n","sub_path":"03_Blending.py","file_name":"03_Blending.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"287418455","text":"import sys\n\nimport basf2 as b2\nimport mdst\nimport modularAnalysis as ma\nimport reconstruction as re\n\nimport simulation as si\n\n\ndef simulation(input_file, output_file):\n my_path = b2.create_path()\n print(f\"Number of processes: {b2.get_nprocesses()}\")\n\n # load input ROOT file\n ma.inputMdst(environmentType=\"default\", filename=input_file, path=my_path)\n \"\"\"\n Loads the specified ROOT (DST/mDST/muDST) files with the RootInput module.\n\n The correct environment (e.g. magnetic field settings) are determined from the specified environment type.\n The currently available environments are:\n\n - 'MC5': for analysis of Belle II MC samples produced with releases prior to build-2016-05-01.\n This environment sets the constant magnetic field (B = 1.5 T)\n - 'MC6': for analysis of Belle II MC samples produced with build-2016-05-01 or newer but prior to release-00-08-00\n - 'MC7': for analysis of Belle II MC samples produced with build-2016-05-01 or newer but prior to release-00-08-00\n - 'MC8', for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00\n - 'MC9', for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00\n - 'MC10', for analysis of Belle II MC samples produced with release-00-08-00 or newer but prior to release-02-00-00\n - 'default': for analysis of Belle II MC samples produced with releases with release-02-00-00 or newer.\n This environment sets the default magnetic field (see geometry settings)\n - 'Belle': for analysis of converted (or during of conversion of) Belle MC/DATA samples\n - 'None': for analysis of generator level information or during simulation/my_reconstruction of\n previously generated events\n\n Note that there is no difference between MC6 and MC7. Both are given for sake of completion.\n The same is true for MC8, MC9 and MC10\n\n Parameters:\n environmentType (str): type of the environment to be loaded\n filename (str): the name of the file to be loaded\n path (basf2.Path): modules are added to this path\n skipNEvents (int): N events of the input files are skipped\n entrySequences (list(str)): The number sequences (e.g. 23:42,101) defining\n the entries which are processed for each inputFileName.\n parentLevel (int): Number of generations of parent files (files used as input when creating a file) to be read\n \"\"\"\n\n # In case of conflict with geometry, you may use this line instead:\n # analysis_main.add_module(\"RootInput\", inputFileName='B2A101-Y4SEventGeneration-evtgen.root')\n\n # simulation\n si.add_simulation(path=my_path)\n\n # my_reconstruction\n re.add_reconstruction(path=my_path)\n\n # dump in MDST format\n mdst.add_mdst_output(path=my_path, mc=True, filename=output_file)\n\n # Show progress of processing\n progress = b2.register_module(\"ProgressBar\")\n my_path.add_module(progress)\n\n # Process the events\n b2.process(my_path)\n print(b2.statistics)\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n print(f\"Simulating Belle II and saving resultant MDST, with arguments: {args}\")\n simulation(*args)\n print(\"Done!\")\n","sub_path":"b2jpsi_eta/src/simulation/belle2.py","file_name":"belle2.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"245839046","text":"import numpy as np\nimport time\nimport os\nimport platform\n\nclass BinaryPuzzle:\n\tdef __init__(self):\n\t\tself.board = []\n\t\tself.initilized = False\n\n\tdef readAidensFormat(self, string: str):\n\t\t# reads start config in the format \"1xx\\nx1x\\nx00\"\n\t\t# defines the full array flattened with x as undefined and \\n as seperators\n\t\trows = string.split(\"\\n\")\n\t\tself.board = []\n\t\tfor i in rows:\n\t\t\tself.board.append([])\n\t\t\tfor j in i:\n\t\t\t\tif j == \"0\":\n\t\t\t\t\tself.board[-1].append(0)\n\t\t\t\telif j == \"1\":\n\t\t\t\t\tself.board[-1].append(1)\n\t\t\t\telse:\n\t\t\t\t\tself.board[-1].append(-1)\n\n\t\tself.board = np.array(self.board, dtype=np.int8)\n\t\tself.initilized = True\n\n\tdef readFullArr(self, arr):\n\t\t# reads start confiig in the format [[1, -1, -1], [-1, 1, -1], [-1, 0, 0]\n\t\t# defines to the full 2d array with -1 as undefined\n\t\tself.board = np.array(arr, dtype=np.int8)\n\t\tself.initilized = True\n\n\tdef readPosArr(self, arr, size = 6):\n\t\t# reads the config in the format [ *[x, y, n] ]\n\t\t# defines the starting numbers as positions everything else is undefined\n\t\t# is size x size in size\n\t\tself.board = np.full((size, size), -1, dtype=np.int8)\n\t\tfor i in arr:\n\t\t\tself.board[i[1]][i[0]] = i[2]\n\n\t\tself.initilized = True\n\n\t@staticmethod\n\tdef checkBoard(board):\n\t\tmaxNum = len(board)//2 # maximum number of each letter per row and col\n\t\t# check count of each number per per row\n\t\tfor i in range(len(board)):\n\t\t\trow = board[i]\n\t\t\tcol = np.rot90(board)[i]\n\n\t\t\tfor line in [row, col]:\n\t\t\t\tif (line==0).sum() > maxNum or (line==1).sum() > maxNum:\n\t\t\t\t\treturn False\n\n\t\t# check threes in a rows\n\t\t# goes through every grid square except all the edge ones\n\t\tfor i in range(1, len(board)-1):\n\t\t\tfor j in range(len(board)):\n\t\t\t\t# gets gets the squares one left, this one and one right\n\t\t\t\thorz = [board[i-1][j], board[i][j], board[i+1][j]]\n\t\t\t\t# gets gets the squares one up, this one and one down\n\t\t\t\tvert = [board[j][i-1], board[j][i], board[j][i+1]]\n\n\t\t\t\t# for both horz and vert\n\t\t\t\tfor line in [horz, vert]:\n\t\t\t\t\t# check if they are either three zeros of three ones\n\t\t\t\t\tif line == [0]*3 or line == [1]*3:\n\t\t\t\t\t\treturn False\n\n\t\tif not np.any(board[:, 0] == -1): # only cares about uniqueness for full boards\n\n\t\t\t# # checks to see if all the rows and unique\n\t\t\t# np.unique returns the given array with duplicates removed\n\t\t\tif len(np.unique(board, axis=0)) != len(board):\n\t\t\t\treturn False\n\t\t\t# # checks to see if all the columns are unique\n\t\t\tif len(np.unique(board, axis=1)) != len(board):\n\t\t\t\treturn False\n\n\t\t# none of the checks failed\n\t\treturn True\n\n\t@staticmethod\n\tdef findEmpty(board):\n\t\t# finds the first square with a -1 from left to right top to bottom\n\t\tallPos = np.where(board==-1)\n\t\tif len(allPos[1]) == 0:\n\t\t\treturn False\n\t\treturn (allPos[0][0], allPos[1][0])\n\n\t@staticmethod\n\tdef printBoard(board, delay=0.):\n\t\tif delay != 0:\n\t\t\tif platform.system() == \"Linux\" or platform.system() == \"Darwin\":\n\t\t\t\tos.system(r\"clear && printf '\\e[3J'\")\n\t\t\telse:\n\t\t\t\tos.system(\"cls\")\n\t\tfor row in board:\n\t\t\tfor num in row:\n\t\t\t\tif num == -1:\n\t\t\t\t\tprint(\" \", end=\"\")\n\t\t\t\telse:\n\t\t\t\t\tprint(num, end=\"\")\n\t\t\tprint(\"\")\n\t\tprint(\"\\n\\n\")\n\t\ttime.sleep(delay)\n\n\tdef branch(self, board, callback):\n\t\tcallback(board)\n\n\t\t# checks if we filled every square, meaning we found a solution\n\t\tpos = self.findEmpty(board)\n\t\tif pos == False and self.checkBoard(board) == True:\n\t\t\treturn True, board\n\n\t\tfor test in [0, 1]:\n\t\t\t# sets the next undecided square to both 0 and 1\n\t\t\tboard[pos[0], pos[1]] = test\n\t\t\t# checks if its valid (so far)\n\t\t\tif self.checkBoard(board):\n\t\t\t\t# if it is continue recursively branching down\n\t\t\t\tout = self.branch(board, callback)\n\t\t\t\tif out[0] == True: # found a solution\n\t\t\t\t\treturn True, out[1]\n\n\t\t# if this branch isnt valid revert the changes and back out\n\t\tboard[pos[0], pos[1]] = -1\n\t\treturn False, []\n\n\tdef solve(self, display=False):\n\t\tif display:\n\t\t\tfunc = self.printBoard\n\t\telse:\n\t\t\tfunc = lambda *x:x\n\n\t\tif self.initilized:\n\t\t\treturn self.branch(self.board, func)[1]\n\t\telse:\n\t\t\traise Exception(\"Not initilized yet\")\t\t\t\n\nif __name__ == \"__main__\":\n\timport json\n\n\twith open(r\"examples.json\") as f:\n\t\texamples = json.loads(f.read())\n\n\tfor n, puz in enumerate(examples[\"puzzles\"]):\n\t\tprint(f\"Puzzle {n+1}\")\n\t\tpuzzle = BinaryPuzzle()\n\t\tpuzzle.readAidensFormat(puz)\n\t\tpuzzle.printBoard(puzzle.solve(display=False))\n","sub_path":"downloads/source/backtracking.py","file_name":"backtracking.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"286803758","text":"from flask import render_template, Blueprint, url_for, flash, redirect\nfrom flask_login import login_user, logout_user, current_user\n\nfrom project.auth.models import db, User\nfrom project.auth.forms import LoginForm, RegisterForm\n\nauth_blueprint = Blueprint(\n 'auth',\n __name__,\n template_folder='../templates',\n url_prefix='/auth'\n)\n\nhome_url = 'home.index'\n\n\n@auth_blueprint.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for(home_url))\n\n form = LoginForm()\n\n if form.validate_on_submit():\n user = User(username=form.username.data)\n login_user(user, remember=form.remember.data)\n\n flash(f\"Welcome {form.username.data}!\", category=\"success\")\n return redirect(url_for(home_url))\n\n return render_template('auth/login.html', form=form)\n\n\n@auth_blueprint.route('/logout', methods=['GET', 'POST'])\ndef logout():\n logout_user()\n flash(\"You have been logged out. Come back soon!\", category=\"success\")\n return redirect(url_for(home_url))\n\n\n@auth_blueprint.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegisterForm()\n\n if form.validate_on_submit():\n new_user = User(username=form.username.data)\n new_user.set_password(form.password.data)\n\n new_user.save()\n\n flash(\n f\"User {form.username.data} has been created, please login.\", category=\"success\")\n return redirect(url_for('.login'))\n\n return render_template('auth/register.html', form=form)\n","sub_path":"services/web/project/auth/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"282885872","text":"import socket\nimport select\nfrom macros import *\nimport time\nimport _pickle as pickle\n\nimport traceback\nfrom _thread import *\nimport numpy as np\nfrom pprint import pprint\n\n\nstatus = {'working': True, 'players': [], 'enemies': []}\n\n\ndef threaded_client(conn, status):\n\n while True:\n status_update = False \n ready_sockets, _, _ = select.select([conn], [], [], SERVER_TIMEOUT)\n if ready_sockets:\n try:\n response = pickle.loads(conn.recv(1024))\n if 'commands' in response:\n print('old status:')\n pprint(status)\n print('received:')\n pprint(response)\n for command in response['commands']:\n if 'movement' in command:\n command = command['movement']\n for player in status['players']:\n if player['id'] == command['id']:\n player['pos'] = command['pos']\n player['dir'] = command['dir']\n \n if 'animation' in command:\n command = command['animation']\n \n for player in status['players']:\n if player['id'] == command['id']:\n player['stats']['animating'] = command['stats']['animating']\n player['stats']['foreground_loc'] = command['stats']['foreground_loc']\n player['stats']['foreground_idx'] = command['stats']['foreground_idx']\n\n if 'speak' in command:\n command = command['speak']\n for player in status['players']:\n if player['id'] == command['id']:\n player['stats']['text'] = command['stats']['text']\n player['stats']['speaking'] = command['stats']['speaking']\n player['stats']['speaking_time'] = command['stats']['speaking_time']\n\n if player['stats']['speaking_time'] <= 0:\n player['stats']['speaking_time'] = DEFAULT_CHAT_TIME\n \n if player['stats']['speaking']:\n player['stats']['text'] = ''\n player['stats']['speaking'] = False\n \n \n if 'damage' in command:\n command = command['damage']\n pprint(response)\n \n if 'to-enemy' in command['type']:\n for enemy in status['enemies']:\n if enemy['id'] == command['hitted']['id']:\n enemy['stats']['hp'] = command['hitted']['stats']['hp']\n \n if command['hitted']['stats']['alive'] == False:\n status['enemies'].remove(enemy)\n \n if 'to-player' in command['type']:\n for player in status['players']:\n if player['id'] == command['hitted']['id']:\n player['stats']['hp'] = command['hitted']['stats']['hp']\n \n if command['hitted']['stats']['alive'] == False:\n status['players'].remove(player)\n\n print('new status:')\n pprint(status)\n \n status_update = True\n conn.send(pickle.dumps(status))\n \n except Exception as e:\n traceback.print_exc()\n break\n \n if not status_update:\n conn.send(pickle.dumps(status))\n\n\ndef start_server():\n n_players = 0\n clients = set()\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n print('Starting up server...')\n s.bind(('127.0.0.1', SERVER_PORT))\n s.listen(2)\n\n # Allow timeout to process KeyboardInterrupt\n s.settimeout(1.0)\n\n print('Done! Now listening...', flush=True)\n\n\n while True:\n try:\n client, address = s.accept()\n\n clients.add(client)\n conn_time = time.time()\n n_players += 1\n\n print(f'Connection has been established with: {address} at {conn_time}. Welcome :)')\n\n id = str(n_players)\n status['players'].append({'id': id, 'pos': (WIDTH/2, HEIGHT/2), 'dir': RIGHT, 'stats': INIT_STATS()})\n # status['enemies'].append({'id': id, 'pos': (np.random.randint(WIDTH), np.random.randint(HEIGHT)), 'stats': INIT_STATS()})\n\n client.send(pickle.dumps(id))\n\n try:\n start_new_thread(threaded_client, (client, status))\n except BaseException as e:\n print('Server Exception:', e)\n traceback.print_exc()\n\n except socket.timeout:\n continue\n except KeyboardInterrupt:\n s.close()\n exit()\n\n\n# Main Entry Point\nif __name__ == \"__main__\":\n start_server()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"449103734","text":"# MIT License\n\n# Copyright (c) 2022 Divine Darkey\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 deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# 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 all\n# 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 NON-INFRINGEMENT. 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 FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport os\nfrom collections import defaultdict\n\nimport click\n\nimport dupliCat\nfrom dupliCat import __version__\n\n\n@click.group()\ndef main() -> bool: # type: ignore\n pass\n\n\n@main.command(name=\"version\")\ndef version():\n \"\"\"outputs the version number of the script\"\"\"\n click.echo(click.style(f\"\\ndupliCat {__version__}\", fg=\"green\", bold=True))\n\n\n@main.command(name=\"search-duplicates\")\n@click.option(\"--no-recurse\", is_flag=True, help=\"Do not recurse into subdirectories\")\n@click.option(\"--path\", default=os.getcwd(), help=\"Path to the directory to be scanned\")\n@click.option(\"--delete\", is_flag=True, help=\"Delete duplicate files.\")\ndef search_duplicates(path: str, no_recurse: bool, delete: bool) -> None:\n click.echo(click.style(f\"Scanning {path!r}...\\n\", fg=\"green\", bold=True))\n\n duplicat = dupliCat.dupliCat(path=path, recurse=not no_recurse)\n try:\n duplicates = duplicat.search_duplicate()\n except dupliCat.NoDuplicatesFound:\n click.echo(click.style(\"No duplicates found.\", fg=\"green\", bold=True))\n return None\n except dupliCat.NoFilesFoundError:\n click.echo(click.style(f\"{path!r} directory is empty.\", bold=True))\n return None\n\n grouped_duplicates = defaultdict(list) # {SECURE_HASH: [DUPLIFILE, DUPLIFILE, ...]}\n for duplicate in duplicates:\n grouped_duplicates[duplicate.secure_hash].append(duplicate)\n\n length = len(grouped_duplicates)\n click.echo(\n click.style(\n f\"Found {length} {'duplicate' if length == 1 else 'duplicates'}\", bold=True\n )\n )\n\n # Print duplicated files\n for i, files in enumerate(grouped_duplicates.values(), start=1):\n q = click.style(\n f\"{i}. Size: {files[0].human_size}:\\t{', '.join([repr(f.path) for f in files])}\",\n fg=\"yellow\",\n bold=True,\n )\n click.echo(q)\n \n # print out total size of duplicates\n total_size = sum(f.size for f in duplicates)\n click.echo(click.style(f\"\\nTotal size: {duplicat.human_size(total_size)}\", fg=\"green\", bold=True))\n\n if delete and length > 0:\n # asking for confirmation on whether to delete files\n confirmation = click.confirm(\n click.style(\n \"\\nDo you want to delete duplicates? (This action is irreversible)\",\n bold=True,\n )\n )\n if not confirmation:\n return None\n\n # ask if we should keep a copy of a duplicate file or not\n keep_copy = click.confirm(\n click.style(\"Do you want to keep a copy of the original file?\", bold=True)\n )\n\n if keep_copy: # remove first file and keep the rest to be deleted\n files = [fs[1:] for fs in grouped_duplicates.values()]\n else:\n files = list(grouped_duplicates.values())\n\n # flattening the list\n files = [f for fs in files for f in fs]\n\n # deleting files\n counter = 0\n for f in files:\n try:\n f.delete()\n except Exception:\n continue\n else:\n counter += 1\n\n color = \"green\" if counter == len(files) else \"yellow\" if counter > 0 else \"red\"\n click.echo(\n click.style(\n f\"\\nDeleted {counter} {'file' if counter == 1 else 'files'} out of {len(files)}\",\n bold=True,\n fg=color,\n )\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/dupliCat/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"185908137","text":"# coding:iso-8859-9 Türkçe\r\n# p_31304.py: Omurgayı ortalama ve LaTeX'le eksen değerlerini tanımlama örneği.\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as mp\r\n\r\nX = np.linspace (-2 * np.pi, 2 * np.pi, 100, endpoint=True)\r\nF1 = X * np.sin (X)\r\n\r\neksenler = mp.gca()\r\neksenler.spines ['top'].set_color ('none')\r\neksenler.spines ['right'].set_color ('none')\r\n\r\n#eksenler.xaxis.set_ticks_position ('bottom') # Varsayılan...\r\neksenler.spines ['bottom'].set_position (('data', 0))\r\n#eksenler.yaxis.set_ticks_position ('left') # Varsayılan...\r\neksenler.spines ['left'].set_position (('data', 0))\r\n\r\nmp.xlabel (\"X = [$-2\\pi$, $+2\\pi$]\")\r\nmp.ylabel (\"F = X * Sin (X)\")\r\n\r\nmp.xticks ( # LaTeX r\"$-+\\pi$\" kuralları kullanılacak...\r\n [-6.28, -4.71, -3.14, -1.57, 1.57, 3.14, 4.71, 6.28],\r\n [\"$-2\\pi$\", \"$-3\\pi/2$\", \"$-\\pi$\", \"$-\\pi/2$\", \"$+\\pi/2$\", \"$+\\pi$\", \"$+3\\pi/2$\", r\"$+\\pi/2$\"])\r\nmp.yticks ([-5, -4, -3, -2, -1, 0, +1, 2])\r\n\r\nmp.plot (X, F1)\r\nmp.show()\r\n","sub_path":"Bernd Klein (520) ile Python/p_31304.py","file_name":"p_31304.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"413184266","text":"from tkinter import*\r\nfrom tkinter import ttk\r\nfrom tkinter import filedialog\r\nfrom subprocess import check_output\r\nimport winsound\r\n# To get the filename\r\nimport os\r\n\r\nroot = Tk()\r\nroot.title(\"Normalization Helper\")\r\nroot.geometry(\"380x400\")\r\n\r\nmainframe = ttk.Frame(root, padding=\"12 12 12 12\")\r\nmainframe.grid(column=0, row=0, sticky=(N, W, E, S))\r\nroot.columnconfigure(0, weight=1)\r\nroot.rowconfigure(0, weight=1)\r\n\r\n# Ask native filename and use it in command as input. location = yourfile.name\r\n# Wrap it with \"\" to get input with spaces\r\ndef getLocation():\r\n global inputFileLoc\r\n global scFileNo\r\n global inputFLSC\r\n global inputFLSCName\r\n inputFileLoc = filedialog.askopenfilename()\r\n # Badly named getting into only filename\r\n inputFLSC = os.path.basename(inputFileLoc)\r\n inputFLSCName = os.path.splitext(inputFLSC)[0]\r\n print(inputFileLoc)\r\n print(inputFLSC)\r\n #set scFileNo back to 0 so it will not go up endlessly\r\n scFileNo = 0\r\n \r\ndef getSaveTo():\r\n global saveFileLoc\r\n saveFileLoc = '\"' + filedialog.askdirectory() + '\"'\r\n print(saveFileLoc)\r\n\r\ndef getNormFileName():\r\n global timeGetter\r\n global normNameGet\r\n normNameGet = normFileN.get()\r\n timeGetter = timeBar.get()\r\n print(normNameGet)\r\n print(timeGetter)\r\n\r\nnormalize = '' # for use to test scrit\r\n# Screen Capture file number. To make multiple screenshots without overwriting.\r\nscFileNo = 0\r\n\r\n#Checkbox widget\r\ncheckB1 = IntVar()\r\ncheckB2 = IntVar()\r\ncheckB3 = IntVar()\r\ncheckB4 = IntVar()\r\ncheckB1.get()\r\ncheckB2.get()\r\ncheckB2.get()\r\n\r\ndef getCodecs():\r\n print(checkB1.get())\r\n print(checkB2.get())\r\n print(checkB3.get())\r\n global video\r\n video = ' -c:v ffv1 -level 3 -g 1 -slicecrc 1 -context 1 '\r\n global noVideo\r\n noVideo = ' -vn '\r\n global audio\r\n audio = '-c:a flac '\r\n global noAudio\r\n noAudio = ' -an '\r\n global report\r\n report = ' 2> '\r\n global noReport\r\n noReport = ''\r\n global codecVideo\r\n codecVideo = ''\r\n global codecAudio\r\n codecAudio = ''\r\n global saveLog\r\n saveLog = ''\r\n if checkB1.get() == 1:\r\n codecVideo = video\r\n else:\r\n codecVideo = noVideo\r\n if checkB2.get() == 1:\r\n codecAudio = audio\r\n else:\r\n codecAudio = noAudio\r\n if checkB3.get() == 1:\r\n saveLog = report + inputFileLoc + '_LOG.txt'\r\n else:\r\n saveLog = noReport\r\n\r\n# Start the with inputs from getLocation, getSaveTo and logToFile.\r\ndef convertStartVideo():\r\n saveFileName = normNameGet + '.mkv'# use as saveas for now. '' + \"_FFV1_FLAC\" NEEDS A FILETYPE\r\n ffToMkv = \"ffmpeg -i \"+ '\"' + inputFileLoc + '\"' + codecVideo + codecAudio + saveFileLoc + '/' + saveFileName + saveLog\r\n normalize = check_output(ffToMkv, shell=True, universal_newlines=True)\r\n print(normalize)\r\n print(\"DONE!\")\r\n winsound.PlaySound('SystemDefault', winsound.MB_OK)\r\n# FINISH THIS!!! Command for screen capture while loop for not overwriting the same imagefile over and over\r\ndef startScreenCap():\r\n global scFileNo\r\n scFileNo = scFileNo + 1\r\n # If name is entered use that if not use original filename\r\n if normNameGet != '':\r\n scFileName = normNameGet + \"_\" + str(scFileNo)\r\n else:\r\n scFileName = inputFLSCName + \"_\" + str(scFileNo)\r\n fileEnding = \".png\"\r\n startSC = \"ffmpeg -i \" + '\"' + inputFileLoc + '\"' + \" -ss \" + timeGetter + \" -frames 1 \" + saveFileLoc + \"/\" + scFileName + fileEnding\r\n takesnap = check_output(startSC, shell=True, universal_newlines=True)\r\n print(takesnap)\r\n print(\"DONE!\")\r\n winsound.PlaySound('SystemDefault', winsound.MB_OK)\r\n\r\n#Videoconversion buttons\r\nttk.Button(mainframe, text=\"1.Choose Input\", command=getLocation).grid(column=1, row=1)\r\nttk.Button(mainframe, text=\"3.Confirm Name\", command=getNormFileName).grid(column=2, row=2)\r\nttk.Button(mainframe, text=\"2.Choose Output\", command=getSaveTo).grid(column=3, row=1)\r\nttk.Button(mainframe, text=\"5.Convert\", command=convertStartVideo).grid(column=2, row=5,pady=10)\r\n\r\n# 3 Entries for HH:MM:SS\r\ntvalue = StringVar(mainframe, value=\"00:00:00\")\r\ntimeBar = ttk.Entry(mainframe, width=7, textvariable=tvalue)\r\ntimeBar.grid(column=2, row=9, padx=20,pady=10)\r\n#Video Screen capture buttons\r\n#Input, Outputloc, Output=inputname+Screen_Capture+%0.d.png have default time be 00:00:00 if else\r\nttk.Button(mainframe, text=\"3.Confirm Time\", command=getNormFileName).grid(column=2, row=10, pady=10)\r\nttk.Button(mainframe, text=\"5.Screen Capture\", command=startScreenCap).grid(column=2, row=11, pady=20)\r\n\r\n#Check button for audio or video conversion\r\nttk.Checkbutton(mainframe,text='4.Video Codec', variable=checkB1, onvalue=1, offvalue=0,command=getCodecs).grid(column=3, row=4, sticky=W)\r\nttk.Checkbutton(mainframe,text='4.Audio Codec', variable=checkB2, onvalue=1, offvalue=0,command=getCodecs).grid(column=3, row=5, sticky=W)\r\nttk.Checkbutton(mainframe,text='4.Enable Log', variable=checkB3, onvalue=1, offvalue=0,command=getCodecs).grid(column=3, row=6, sticky=W)\r\n\r\n#Text entry widget for setting normalized filename\r\nnormFileN = ttk.Entry(mainframe)\r\nnormFileN.grid(column=2, row=1, padx=20,pady=20)\r\n\r\ndef exitProgram():\r\n root.destroy()\r\n pass\r\n\r\nttk.Button(mainframe, text=\"Exit\", command=exitProgram).grid(column=2, row=15, sticky=S, pady=10)\r\n\r\n\r\nroot.mainloop()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"299378955","text":"#\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 neutron_lib.services import base as service_base\nfrom oslo_log import log as logging\nimport sqlalchemy\nfrom sqlalchemy.orm import exc\nfrom sqlalchemy.orm import session as se\n\nfrom neutron._i18n import _, _LW\nfrom neutron.db import _resource_extend as resource_extend\nfrom neutron.db import api as db_api\nfrom neutron.db import standard_attr\n\nLOG = logging.getLogger(__name__)\n\n\n@resource_extend.has_resource_extenders\nclass RevisionPlugin(service_base.ServicePluginBase):\n \"\"\"Plugin to populate revision numbers into standard attr resources.\"\"\"\n\n supported_extension_aliases = ['standard-attr-revisions']\n\n def __init__(self):\n super(RevisionPlugin, self).__init__()\n db_api.sqla_listen(se.Session, 'before_flush', self.bump_revisions)\n db_api.sqla_listen(se.Session, 'after_commit',\n self._clear_rev_bumped_flags)\n db_api.sqla_listen(se.Session, 'after_rollback',\n self._clear_rev_bumped_flags)\n\n def bump_revisions(self, session, context, instances):\n # bump revision number for any updated objects in the session\n for obj in session.dirty:\n if isinstance(obj, standard_attr.HasStandardAttributes):\n self._bump_obj_revision(session, obj)\n\n # see if any created/updated/deleted objects bump the revision\n # of another object\n objects_with_related_revisions = [\n o for o in session.deleted | session.dirty | session.new\n if getattr(o, 'revises_on_change', ())\n ]\n for obj in objects_with_related_revisions:\n self._bump_related_revisions(session, obj)\n\n def _bump_related_revisions(self, session, obj):\n for revises_col in getattr(obj, 'revises_on_change', ()):\n try:\n related_obj = self._find_related_obj(session, obj, revises_col)\n if not related_obj:\n LOG.warning(_LW(\"Could not find related %(col)s for \"\n \"resource %(obj)s to bump revision.\"),\n {'obj': obj, 'col': revises_col})\n continue\n # if related object revises others, bump those as well\n self._bump_related_revisions(session, related_obj)\n # no need to bump revisions on related objects being deleted\n if related_obj not in session.deleted:\n self._bump_obj_revision(session, related_obj)\n except exc.ObjectDeletedError:\n # object was in session but another writer deleted it\n pass\n\n def get_plugin_type(self):\n return \"revision_plugin\"\n\n def get_plugin_description(self):\n return \"Adds revision numbers to resources.\"\n\n @staticmethod\n @resource_extend.extends(\n list(standard_attr.get_standard_attr_resource_model_map()))\n def extend_resource_dict_revision(resource_res, resource_db):\n resource_res['revision_number'] = resource_db.revision_number\n\n def _find_related_obj(self, session, obj, relationship_col):\n \"\"\"Gets a related object off of a relationship.\n\n Raises a runtime error if the relationship isn't configured correctly\n for revision bumping.\n \"\"\"\n # first check to see if it's directly attached to the object already\n related_obj = getattr(obj, relationship_col)\n if related_obj:\n return related_obj\n for rel in sqlalchemy.inspect(obj).mapper.relationships:\n if rel.key != relationship_col:\n continue\n if not rel.load_on_pending:\n raise RuntimeError(_(\"revises_on_change relationships must \"\n \"have load_on_pending set to True to \"\n \"bump parent revisions on create: %s\"),\n relationship_col)\n\n def _clear_rev_bumped_flags(self, session):\n \"\"\"This clears all flags on commit/rollback to enable rev bumps.\"\"\"\n for inst in session:\n setattr(inst, '_rev_bumped', False)\n\n def _bump_obj_revision(self, session, obj):\n \"\"\"Increment object revision in compare and swap fashion.\n\n Before the increment, this checks and enforces any revision number\n constraints.\n \"\"\"\n if getattr(obj, '_rev_bumped', False):\n # we've already bumped the revision of this object in this txn\n return\n obj.bump_revision()\n setattr(obj, '_rev_bumped', True)\n","sub_path":"neutron/services/revisions/revision_plugin.py","file_name":"revision_plugin.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"200962820","text":"\"\"\"\nThis file provides simple functions to calculate the integrated stellar number counts\nas a function of limiting magnitude and galactic coordinates.\n\n:requires: NumPy\n:requires: matplotlib\n\n:version: 0.1\n\n:author: Sami-Matias Niemi\n:contact: s.niemi@ucl.ac.uk\n\"\"\"\nimport matplotlib\nmatplotlib.rc('text', usetex=True)\nmatplotlib.rcParams['font.size'] = 17\nmatplotlib.rc('xtick', labelsize=14)\nmatplotlib.rc('axes', linewidth=1.1)\nmatplotlib.rcParams['legend.fontsize'] = 11\nmatplotlib.rcParams['legend.handlelength'] = 3\nmatplotlib.rcParams['xtick.major.size'] = 5\nmatplotlib.rcParams['ytick.major.size'] = 5\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef bahcallSoneira(magnitude, longitude, latitude, constants):\n \"\"\"\n Implemented Equation B1 from Bahcall and Soneira 1980 (1980ApJS...44...73B).\n\n Note that the values return do not necessarily agree with the Table 6 of the paper values.\n Mostly the integrated number of stars agree within 15%, which is the error quoted\n in the paper.\n\n :param magnitude: limiting magnitude\n :type magnitude:float\n :param longitude: galactic longitude in degrees\n :type longitude: float\n :param latitude: galactic latitude in degrees\n :type latitude: float\n\n :return: Number of stars per square degree\n \"\"\"\n #rename variables for easy reference and convert coordinates to radians\n m = magnitude\n l = np.deg2rad(longitude)\n b = np.deg2rad(latitude)\n C1 = constants['C1']\n C2 = constants['C2']\n beta = constants['beta']\n alpha = constants['alpha']\n delta = constants['delta']\n lam = constants['lam']\n eta = constants['eta']\n kappa = constants['kappa']\n\n #magnitude dependent values\n if m <= 12:\n mu = 0.03\n gamma = 0.36\n elif 12 < m < 20:\n mu = 0.0075*(m - 12) + 0.03\n gamma = 0.04*(12 - m) + 0.36\n else:\n mu = 0.09\n gamma = 0.04\n\n #position dependency\n sigma = 1.45 - 0.2*np.cos(b) * np.cos(l)\n\n #precompute the delta mags\n dm = m - constants['mstar']\n dm2 = m - constants['mdagger']\n\n #split the equation to two parts\n D1 = (C1*10**(beta*dm)) / ((1. + 10**(alpha*dm))**delta) / ((np.sin(b)*(1 - mu/np.tan(b)*np.cos(l)))**(3 - 5*gamma))\n D2 = (C2*10**(eta*dm2)) / ((1. + 10**(kappa*dm2))**lam) / ((1 - np.cos(b)*np.cos(l))**sigma)\n\n #final counts\n D = D1 + D2\n\n return D\n\n\ndef integratedCountsVband():\n \"\"\"\n Returns constant values for the integrated number counts in the V-band.\n\n :return: constants to be used when calculating the integrated number counts.\n :rtype: dict\n \"\"\"\n return dict(C1=925., alpha=-0.132, beta=0.035, delta=3., mstar=15.75,\n C2=1050., kappa=-0.18, eta=0.087, lam=2.5, mdagger=17.5)\n\n\ndef _skyProjectionPlot(maglimit, b, l, z, blow, bhigh, llow, lhigh, bnum, lnum):\n \"\"\"\n Generate a sky projection plot.\n\n :param maglimit:\n :param b:\n :param l:\n :param z:\n :return:\n \"\"\"\n from kapteyn import maputils\n\n header = {'NAXIS': 2,\n 'NAXIS1': len(l),\n 'NAXIS2': len(b),\n 'CTYPE1': 'GLON',\n 'CRVAL1': llow,\n 'CRPIX1': 0,\n 'CUNIT1': 'deg',\n 'CDELT1': float(bhigh-blow)/bnum,\n 'CTYPE2': 'GLAT',\n 'CRVAL2': blow,\n 'CRPIX2': 0,\n 'CUNIT2': 'deg',\n 'CDELT2': float(lhigh-llow)/lnum}\n\n fig = plt.figure(figsize=(12, 11))\n frame1 = fig.add_axes([0.1,0.5,0.85, 0.44])\n frame2 = fig.add_axes([0.1,0.07,0.85, 0.4])\n\n #generate image\n f = maputils.FITSimage(externalheader=header, externaldata=np.log10(z))\n im1 = f.Annotatedimage(frame1)\n\n h = header.copy()\n h['CTYPE1'] = 'RA---CAR'\n h['CTYPE2'] = 'DEC--CAR'\n h['CRVAL1'] = 0\n h['CRVAL2'] = 0\n\n # Get an estimate of the new corners\n x = [0]*5\n y = [0]*5\n x[0], y[0] = f.proj.toworld((1, 1))\n x[1], y[1] = f.proj.toworld((len(l), 1))\n x[2], y[2] = f.proj.toworld((len(l), len(b)))\n x[3], y[3] = f.proj.toworld((1, len(b)))\n x[4], y[4] = f.proj.toworld((len(l)/2., len(b)))\n\n # Create a dummy object to calculate pixel coordinates\n # in the new system. Then we can find the area in pixels\n # that corresponds to the area in the sky.\n f2 = maputils.FITSimage(externalheader=h)\n px, py = f2.proj.topixel((x,y))\n pxlim = [int(min(px))-10, int(max(px))+10]\n pylim = [int(min(py))-10, int(max(py))+10]\n\n reproj = f.reproject_to(h, pxlim_dst=pxlim, pylim_dst=pylim)\n\n grat1 = im1.Graticule(skyout='Galactic', starty=blow, deltay=10, startx=llow, deltax=20)\n\n colorbar = im1.Colorbar(orientation='horizontal')\n colorbar.set_label(label='log10(Stars per sq deg)', fontsize=18)\n\n im1.Image()\n im1.plot()\n\n im2 = reproj.Annotatedimage(frame2)\n grat2 = im2.Graticule()\n\n im2.Image()\n im2.plot()\n\n title = r'Integrated Number Density of Stars $V \\leq %.1f$' % (maglimit)\n frame1.set_title(title, y=1.02)\n\n plt.savefig('stellarD%i.pdf' % maglimit)\n plt.close()\n\n\ndef skyNumbers(maglimit=20, blow=20., bhigh=90., llow=0., lhigh=360., bnum=71, lnum=361, plot=True):\n \"\"\"\n Calculate the integrated stellar number counts in a grid of galactic coordinates.\n Plot the results in two projections.\n\n :param maglimit: magnitude limit\n :type maglimit: int or float\n :param blow: lower limit for the galactic latitude\n :type blow: float\n :param bhigh: upper limit for the galactic latitude\n :type bhigh: float\n :param llow: lower limit for the galactic longitude\n :type llow: float\n :param lhigh: upper limit of the galacti longitude:\n :type lhigh: float\n :param bnum: number of galactic latitude grid points\n :type bnum: int\n :param lnum: number of galactic longitude grid points\n :type lnum: int\n :param plot: whether or not to generate sky coverage plots\n :type plot: bool\n\n :return: grid of galactic coordinates and the number of stars in the grid\n \"\"\"\n Nvconst = integratedCountsVband()\n\n b = np.linspace(blow, bhigh, num=bnum)\n l = np.linspace(llow, lhigh, num=lnum)\n\n counts = np.vectorize(bahcallSoneira)\n\n ll, bb = np.meshgrid(l, b)\n\n z = counts(maglimit, ll, bb, Nvconst)\n\n #plot\n if plot:\n _skyProjectionPlot(maglimit, b, l, z, blow, bhigh, llow, lhigh, bnum, lnum)\n\n return l, b, z\n\n\nif __name__ == '__main__':\n #constants for V-band\n Nvconst = integratedCountsVband()\n\n skyNumbers(maglimit=10)\n skyNumbers(maglimit=15)\n skyNumbers(maglimit=18)\n skyNumbers(maglimit=20)\n skyNumbers(maglimit=22)\n skyNumbers(maglimit=24)\n skyNumbers(maglimit=26)\n skyNumbers(maglimit=29)\n\n #testing\n #print bahcallSoneira(22, 90, 20, Nvconst)\n #print bahcallSoneira(22, 90, 30, Nvconst)\n #print bahcallSoneira(22, 90, 50, Nvconst)\n #print bahcallSoneira(22, 90, 90, Nvconst)","sub_path":"sources/stellarNumberCounts.py","file_name":"stellarNumberCounts.py","file_ext":"py","file_size_in_byte":6889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"222253209","text":"\nfrom odoo import api, models\nfrom dateutil.relativedelta import relativedelta\nimport datetime\nimport logging\nfrom datetime import timedelta,datetime\n\n_logger = logging.getLogger(__name__)\n\n\nclass ReportProductSale(models.AbstractModel):\n _name = \"report.total_transactions.total_transactions_report\"\n\n @api.model\n def _get_report_values(self, docids, data=None):\n date_from = data['form']['date_from']\n date_to = data['form']['date_to']\n journal_id = data['form']['journal_id']\n account_id = data['form']['account_id']\n doamin_cheq=[('move_id.state','=','posted')]\n yest_date=''\n\n user_log=self.env['res.users'].search([('id','=',self.env.uid)])\n if date_from:\n doamin_cheq.append((\"date\", \">=\", date_from))\n yest_date=datetime.strptime(date_from,'%Y-%m-%d')\n yest_date=yest_date=datetime.strftime(yest_date - timedelta(1), '%Y-%m-%d')\n if date_to:\n doamin_cheq.append((\"date\", \"<=\", date_to))\n \n if journal_id:\n doamin_cheq.append((\"journal_id\",\"=\",journal_id))\n if account_id:\n doamin_cheq.append((\"account_id\",\"=\",account_id))\n debit_list = []\n credit_list = []\n \n move_list = self.env['account.move.line'].search(doamin_cheq, order='date asc')\n user_log=self.env['res.users'].search([('id','=',self.env.uid)])\n type_jfr=''\n if user_log.lang=='en_US':\n type_jfr='cash'\n elif user_log.lang=='en_AA' or user_log.lang=='ar_SY':\n type_jfr='نقدي'\n\n last_amount=0\n if not yest_date:\n yest_date=datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d')\n _logger.info(\"yest_date\")\n _logger.info(yest_date)\n if journal_id:\n \n move_ls = self.env['account.move.line'].search([('move_id.state','=','posted'),(\"journal_id\",\"=\",journal_id)],order='date asc')\n else:\n move_ls = self.env['account.move.line'].search([('move_id.state','=','posted')],order='date asc')\n \n for lines in move_ls:\n if lines.journal_id.type=='cash':\n \n if lines.account_id.id==lines.journal_id.default_debit_account_id.id or lines.account_id==lines.journal_id.default_credit_account_id.id:\n \n if datetime.strptime(yest_date,'%Y-%m-%d').date()>=lines.date:\n last_amount+=lines.debit-lines.credit\n current_amount=0\n for line in move_list:\n if line.journal_id.type=='cash':\n ref=''\n\n if line.payment_id.communication:\n ref=line.payment_id.communication\n elif line.move_id.ref:\n ref=line.move_id.ref\n else:\n ref=line.name\n if line.account_id.id==line.journal_id.default_debit_account_id.id or line.account_id==line.journal_id.default_credit_account_id.id:\n \n if datetime.strptime(yest_date,'%Y-%m-%d').date()0:\n debit_list.append({\n 'date': line.date,\n 'rerference':ref,\n 'Amount':line.debit\n })\n if line.credit>0:\n credit_list.append({\n 'date': line.date,\n 'rerference':ref,\n 'Amount':line.credit\n })\n \n\n \n if len(debit_list)!=0 or len(credit_list) !=0:\n\n return {\n 'doc_ids': data['ids'],\n 'doc_model': data['model'],\n 'date_from': date_from,\n 'date_to': date_to,\n 'data_check':False,\n 'debit_list':debit_list,\n 'current_amount':current_amount,\n 'credit_list':credit_list,\n 'last_amount':last_amount,\n 'journal_id':self.env['account.journal'].search([('id','=',journal_id)]).name,\n \"name_report\":'كشــف وارد وصادر خزينه'\n }\n else:\n return {\n 'doc_ids': data['ids'],\n 'doc_model': data['model'],\n 'date_from': date_from,\n 'date_to': date_to,\n 'data_check':True,\n 'debit_list':debit_list,\n 'last_amount':last_amount,\n 'current_amount':current_amount,\n 'credit_list':credit_list,\n 'journal_id':self.env['account.journal'].search([('id','=',journal_id)]).name,\n \"name_report\":'كشــف وارد وصادر خزينه '\n }","sub_path":"total_transactions/report/total_transactions_report.py","file_name":"total_transactions_report.py","file_ext":"py","file_size_in_byte":4996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"139342314","text":"from flax_baseline.flows.base.base_flow import BaseFlow\nimport cv2\nfrom copy import deepcopy\n\ndata = [{\"name\": \"1_1_dasda\", \"x\": 225, \"y\": 78, \"width\": 340, \"height\": 74}, {\"name\": \"1_2_dasd\", \"x\": 225, \"y\": 167, \"width\": 342, \"height\": 87},\n {\"name\": \"10_1_ad\", \"x\": 565, \"y\": 308, \"width\": 398, \"height\": 70}, {\"name\": \"11_2\", \"x\": 264, \"y\": 400, \"width\": 736, \"height\": 70},\n {\"name\": \"3_1\", \"x\": 264, \"y\": 490, \"width\": 734, \"height\": 64}]\n\nregions = [\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 90,\n \"y\": 90,\n \"width\": 116,\n \"height\": 58\n },\n \"region_attributes\": {\n \"Item name\": \"Bank name (Doc ID)\",\n \"type\": \"Number\",\n \"true label\": \"2160\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 273,\n \"y\": 218,\n \"width\": 340,\n \"height\": 75\n },\n \"region_attributes\": {\n \"Item name\": \"Bank name\",\n \"type\": \"Kanji, box\",\n \"true label\": \"福岡銀行\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1228,\n \"y\": 217,\n \"width\": 687,\n \"height\": 85\n },\n \"region_attributes\": {\n \"Item name\": \"Branch name\",\n \"true label\": \"赤坂門\",\n \"type\": \"Kanji, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 286,\n \"y\": 357,\n \"width\": 188,\n \"height\": 61\n },\n \"region_attributes\": {\n \"Item name\": \"Type of account\",\n \"true label\": \"1\",\n \"type\": \"Check box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 612,\n \"y\": 349,\n \"width\": 400,\n \"height\": 74\n },\n \"region_attributes\": {\n \"Item name\": \"Account number\",\n \"true label\": \"1554999\",\n \"type\": \"Number, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1117,\n \"y\": 350,\n \"width\": 655,\n \"height\": 74\n },\n \"region_attributes\": {\n \"Item name\": \"Amount\",\n \"true label\": \"97790\",\n \"type\": \"Number, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 305,\n \"y\": 442,\n \"width\": 744,\n \"height\": 163\n },\n \"region_attributes\": {\n \"Item name\": \"Account holder name (kana)\",\n \"true label\": \"カントウコウゾウ\",\n \"type\": \"Katakana, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 308,\n \"y\": 761,\n \"width\": 739,\n \"height\": 156\n },\n \"region_attributes\": {\n \"Item name\": \"Customer name (kana)\",\n \"true label\": \"アゲインホールディング(カ\",\n \"type\": \"Katakana, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 295,\n \"y\": 938,\n \"width\": 705,\n \"height\": 120\n },\n \"region_attributes\": {\n \"Item name\": \"Customer name (kanji)\",\n \"true label\": \"アゲインホールディング株式会社\",\n \"type\": \"Kanji\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1164,\n \"y\": 438,\n \"width\": 609,\n \"height\": 76\n },\n \"region_attributes\": {\n \"Item name\": \"Confirmed Amount\",\n \"true label\": \"\",\n \"type\": \"Number, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1848,\n \"y\": 436,\n \"width\": 51,\n \"height\": 77\n },\n \"region_attributes\": {\n \"Item name\": \"Amount Type\",\n \"true label\": \"\",\n \"type\": \"Number, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1603,\n \"y\": 612,\n \"width\": 167,\n \"height\": 72\n },\n \"region_attributes\": {\n \"Item name\": \"Commission fee\",\n \"true label\": \"540\",\n \"type\": \"Number, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1846,\n \"y\": 612,\n \"width\": 58,\n \"height\": 74\n },\n \"region_attributes\": {\n \"Item name\": \"Commission Type\",\n \"true label\": \"\",\n \"type\": \"Number, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1537,\n \"y\": 709,\n \"width\": 359,\n \"height\": 73\n },\n \"region_attributes\": {\n \"Item name\": \"CMF\",\n \"true label\": \"\",\n \"type\": \"Number, box\"\n }\n },\n {\n \"shape_attributes\": {\n \"name\": \"rect\",\n \"x\": 1179,\n \"y\": 819,\n \"width\": 650,\n \"height\": 106\n },\n \"region_attributes\": {\n \"Item name\": \"Remarks Flag\",\n \"true label\": \"\",\n \"type\": \"Mix\"\n }\n }\n]\n\n\nclass CellcutImage(BaseFlow):\n\n def __init__(self):\n BaseFlow.__init__(self)\n\n def process(self, img):\n self.flax_debug.set_filename(img)\n img_org = cv2.imread(img)\n cellcuts = {}\n for region in regions:\n x = region['shape_attributes']['x']\n y = region['shape_attributes']['y']\n w = region['shape_attributes']['width']\n h = region['shape_attributes']['height']\n name = region['region_attributes']['Item name']\n img_crop = img_org[y - 5:y + h + 5, x - 5:x + w + 5]\n cellcuts[name] = img_crop\n self.flax_debug.save_cellcut_img(img_crop, name)\n\n return cellcuts\n\n def process_(self, img):\n self.flax_debug.set_filename(img)\n img_org = cv2.imread(img)\n cellcuts = {}\n for row in data:\n x = row['x']\n y = row['y']\n w = row['width']\n h = row['height']\n\n img_new = deepcopy(img_org)\n cellcut_img = img_new[y:y + h, x:x + w]\n cellcuts[row['name']] = cellcut_img\n # Save image cellcut to folder log\n self.flax_debug.save_cellcut_img(cellcut_img, row['name'])\n return cellcuts\n\n def run_test(self, img_dir):\n self.flax_file.set_dir_scan(img_dir)\n img_files = self.flax_file.scan_files()\n for img_name, img_path in img_files.items():\n cellcuts = self.process(img_path)\n print(img_name, cellcuts)\n","sub_path":"flax_baseline/flows/cellcut_image.py","file_name":"cellcut_image.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"184762270","text":"n = int(input(\"Enter the value\"))\n\nsums = [] \n\nfor i in range(1, n+1):\n print(i, sep=\" \", end=\" \")\n if i < n:\n print(\"+\", sep=\" \", end=\" \")\n sums.append(i) \n \n\nprint(\"=\", sum(sums))\n","sub_path":"serie1-n.py","file_name":"serie1-n.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"590852899","text":"from utils import inPageBound\nfrom utils import lowerSideOutOfBound\nfrom exception import OutofBoundError\n\nclass LayoutStrategy:\n def __init__(self, page_size):\n self.page_size = page_size\n self.current_position = (0, 0)\n self.max_depth = 0\n self.max_width = 0\n\n def updateCurrentPosition(self, component):\n pass\n\n def getCurrentPosition(self):\n return self.current_position\n\n def getMaxDepth(self):\n return self.max_depth\n\n def getMaxWidth(self):\n return self.max_width\n\nclass FlowLayout(LayoutStrategy):\n def __init__(self, page_size):\n LayoutStrategy.__init__(self, page_size)\n\n def updateCurrentPosition(self, component):\n '''update current position conforming to\n the size of component'''\n component.setRelativeOrigin(self.current_position)\n in_bound = inPageBound(self.page_size, component)\n comp_size = component.getSize()\n if in_bound:\n '''if there is a space available on the right end\n side and the lower side of the page for the\n component side'''\n comp_depth = self.current_position[1] + comp_size[1]\n comp_ext = self.current_position[0] + comp_size[0]\n if self.max_depth < comp_depth:\n self.max_depth = comp_depth\n if self.max_width < comp_ext:\n self.max_width = comp_ext\n self.current_position = ((self.current_position[0] +\n comp_size[0]),\n self.current_position[1])\n else:\n if lowerSideOutOfBound(self.page_size, component):\n '''if there is no space available for Component\n on lower side of the page'''\n raise OutofBoundError(\"\"\"component can't\n be drawn on page\"\"\")\n else:\n self.current_position = (0, self.max_depth)\n self.updateCurrentPosition(component)\n","sub_path":"app/pdfgen/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"401295665","text":"\"\"\"A Blender add-on containing workflow tools for Animation Production, created by DigitalDurian.\n\"\"\"\nfrom . import tk_anim, operators\nfrom .utils import (\n preferences,\n register_recursive,\n unregister_recursive,\n menus,\n ui,\n)\n\nbl_info = {\n \"name\": \"DigitalDurian Addon\",\n \"description\": \"A suite of tools geared towards animation production, created by DigitalDurian Animation\",\n \"author\": \"DigitalDurian Animation\",\n \"version\": (0, 1, 0),\n \"blender\": (2, 81, 0),\n \"location\": \"DDA menu\",\n \"warning\": \"This addon is still in development.\",\n \"wiki_url\": \"https://github.com/DigitalDurian/blender-tools\",\n \"tracker_url\": \"https://github.com/DigitalDurian/blender-tools/issues/new/choose\",\n \"support\": \"COMMUNITY\",\n \"category\": \"Pipeline\",\n}\n\n\nREGISTER_CLASSES = (preferences, ui, tk_anim, operators, menus)\n\n\ndef register():\n \"\"\"Register all of the DigitalDurian Addon classes.\"\"\"\n register_recursive(REGISTER_CLASSES)\n\n\ndef unregister():\n \"\"\"Unregister all of the DigitalDurian Addon classes.\"\"\"\n unregister_recursive(REGISTER_CLASSES)\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"82561259","text":"import re\nimport sys\nfrom itertools import islice\n\n\ndef take(n, iterable):\n return list(islice(iterable.items(), n))\n\n\nclass WordTracker:\n def __init__(self, word, line, file):\n self.count = 1\n self.word = word\n self.lines = {line}\n self.files = {file}\n\n def add(self, line, file):\n self.count += 1\n self.lines.add(line)\n self.files.add(file)\n\n\ncommon_words = ['-', '?', 'a', 'able', 'about', 'after', 'all', 'also', 'an', 'and', 'any', 'are', 'as', 'at', 'back',\n 'be', 'because', 'been', 'but', 'by', 'can', 'could', 'do', 'for', 'from', 'had', 'has', 'have', 'he',\n 'her', 'his', 'how', 'i', 'if', 'in', 'into', 'is', 'it', \"it's\", 'me', 'more', 'must', 'my', 'no',\n 'not', 'of', 'on', 'one', 'or', 'other', 'our', 'over', 'same', 'she', 'should', 'so', 'than', 'that',\n 'that\\'s', 'the', 'their', 'them', 'then', 'there', 'these', 'they', 'thing', 'this', 'those', 'time',\n 'to', 'up', 'us', 'use', 'was', 'we', 'we\\'re', 'we\\'ve', 'were', 'well', 'what', 'when', 'where',\n 'which', 'who', 'will', 'with', 'would', 'you', 'your']\n\nline_map = dict()\nword_map = dict()\nline_seq = 0\n\n\ndef read_file(filename):\n f = open(filename, \"r\")\n text = f.read()\n f.close()\n return text\n\n\ndef process_text(filename, content):\n lines = re.split('\\\\.(\\\\s+|\\n)', content)\n for line in lines:\n global line_seq\n line_seq += 1\n line = line.strip(\"\\n\")\n line_map[line_seq] = line\n words = line.split()\n for word in words:\n word = word.lower().strip()\n if word.endswith(','):\n word = word[:-1]\n if word not in common_words:\n if word in word_map:\n word_map[word].add(line_seq, filename)\n else:\n word_map[word] = WordTracker(word, line_seq, filename)\n\n\ndef show_data_for_word(word):\n if word not in word_map:\n print('\"{}\" is not in the read text'.format(word))\n else:\n print_word_data(word_map[word])\n\n\ndef print_word_data(word):\n word_lines = []\n for i in list(word.lines)[:10]:\n word_lines.append(line_map[i])\n print(\"{} ({}) in files: [{}] and lines:\\n\\n=> {}\".format(word.word, word.count, ', '.join(word.files),\n '\\n=> '.join(word_lines)))\n print('-' * 50)\n\n\nfor i in range(1, 7):\n filename = \"doc{}.txt\".format(i)\n text = read_file(\"{}\".format(filename))\n process_text(filename, text)\n\nordered = {k: v for k, v in sorted(word_map.items(), key=lambda item: item[1].count, reverse=True)}\n\nif len(sys.argv) > 1 and sys.argv[1].isnumeric():\n topN = int(sys.argv[1])\nelse:\n topN = 10\n\nprint('Showing results for top {} interesting words'.format(topN))\nprint(\"=\"*50)\nfiltered = take(topN, ordered)\nfor word in filtered:\n print_word_data(word[1])\n\nif len(sys.argv) > 2:\n for i in range(2, len(sys.argv)):\n show_data_for_word(sys.argv[i])\n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"121255579","text":"# Implict Type Conversion\n# Python convert automatically one data_type to another data_type\n\na=5\nb=2\nvalue=a/b\nprint(value)\nprint(type(value))\n\nx=10\nb=5.5\ntotal=x+b;\nprint(total)\nprint(type(total))\n\nj=\"Nitih\"\nk=\"Mahato\"\np=j+k;\nprint(p)\nprint(type(p))\n\n#q=20\n#u=\"10\"\n#r=q+u\n#print(r)\n#print(type(r))\n\n#m=20\n#n=\"Nitish\"\n#t=m+n\n#print(t)\n#print(type(t))\n","sub_path":"OPERATOR'S/Implict_type_Conversion.py","file_name":"Implict_type_Conversion.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"508962051","text":"import pygame\nfrom pygame.sprite import Sprite\n\n\nclass Ship(Sprite):\n def __init__(self, game_settings, screen):\n \"\"\"\n Initialize the ship and setup initial location\n \"\"\"\n super().__init__()\n self.screen = screen\n self.game_settings = game_settings\n\n # Load the ship image\n image = pygame.image.load('images/ship.png')\n self.image = pygame.transform.scale(image, (61, 64))\n\n # Setup the rectangular of the ship and screen\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n # Put every ship at the middle bottom of the screen\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n self.center = float(self.rect.centerx)\n\n # Moving signal\n self.moving_right = False\n self.moving_left = False\n\n def update(self):\n \"\"\"\n Adjust the location of ship by command\n \"\"\"\n # Update the location of the ship center\n if self.moving_right and self.rect.right < self.screen_rect.right:\n self.center += self.game_settings.ship_speed\n if self.moving_left and self.rect.left > 0:\n self.center -= self.game_settings.ship_speed\n\n # Update the ship location based on self.center\n self.rect.centerx = self.center\n\n def blit_me(self):\n \"\"\"\n Draw the ship at specific location\n \"\"\"\n self.screen.blit(self.image, self.rect)\n\n def center_ship(self):\n \"\"\"\n Center the ship\n \"\"\"\n self.center = self.screen_rect.centerx\n","sub_path":"ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"641124049","text":"#!/usr/bin/python\nimport sys\nimport itertools\n\n#from ExcelObjects import *\nfrom openpyxl import Workbook, load_workbook\nfrom openpyxl.styles import Protection\nfrom openpyxl.worksheet import SheetProtection\nfrom openpyxl.styles import fills, colors, Color, PatternFill\nfrom openpyxl.comments import Comment\n# for tabColor? from openpyxl.worksheet.properties import WorksheetProperties, PageSetupProperties\n\ndef defines():\n exceldef = {}\n exceldef['datasheet'] = 'Daten'\n exceldef['instructsheet'] = 'Anleitung'\n exceldef['firstrow'] = 5\n exceldef['cellcolor'] = Color(rgb = 'FFF9E38C') \n\n return exceldef \n\ndef setColor(cell, color):\n cell.fill = PatternFill(fill_type = 'solid', fgColor = color, bgColor = color)\n #print (cell.fill, cell.fill.fill_type)\n pass\n\ndef setDatatype(cell, coltype):\n cell.data_type = coltype['basetype']\n if coltype['num_fmt'] != None:\n cell.number_format = coltype['num_fmt']\n\n\ndef writeExcelFile (args, protect_headers = True, protect_ids = True, striped = True, datatypes = True, sortable = False):\n templateFilepath = args[0];\n targetFilepath = args[1];\n firstTubeNo = args[2];\n lastTubeNo = args[3];\n transactionId = args[4];\n try:\n lang = args[5]\n except IndexError:\n lang = \"de\"\n\n exceldef = defines()\n\n #set transactionId\n workbook = load_workbook(templateFilepath)\n workbook.properties.subject = transactionId\n\n #get references to sheets\n datasheet = workbook.get_sheet_by_name(exceldef['datasheet'])\n instructsheet = workbook.get_sheet_by_name(exceldef['instructsheet'])\n #helpsheet = workbook.get_sheet_by_name(exceldef['helpsheet'])\n\n #check datasheet size, raise error when endless rows or cols are formated\n #print (datasheet.max_column)\n if datasheet.max_column > 1023:\n raise ValueError ('excel datasheet has too much columns, check that only needed columns have been formated')\n #print (datasheet.max_row)\n if datasheet.max_row > 1023:\n raise ValueError ('excel datasheet has too much rows, check that only needed rows have been formated') \n\n #enable protection to switch the feature on\n if protect_headers == True or protect_ids == True:\n sheets = workbook.get_sheet_names()\n for sheetname in sheets:\n sheet = workbook.get_sheet_by_name(sheetname)\n sheet.protection.enable()\n\n\n #shortnames for rows to insert\n firstrow = exceldef['firstrow']\n lastrow = exceldef['firstrow'] + int(lastTubeNo) - int(firstTubeNo) \n\n #state of protection depends on last saved state and must be revisited for each cell\n for row in itertools.islice(datasheet.iter_rows(), 0, firstrow -1):\n for cell in row:\n if protect_headers == True and cell.comment == None: #cell protection deletes comments:\n cell.protection = Protection(locked = True, hidden = False)\n else:\n cell.protection = Protection(locked = False, hidden = False)\n\n #iterate through data cell and set properties\n #first read data type for column from example row\n coltype = {}\n for row in itertools.islice(datasheet.iter_rows(), firstrow -2, firstrow -1):\n for cell in row:\n #enabling arrows for column sorting in example row means to disable protection in tubenumber column and in the example fields \n if sortable == True:\n cell.protection = Protection(locked = False, hidden = False)\n \n coltype[cell.col_idx] = {}\n coltype[cell.col_idx]['basetype'] = cell.data_type\n\n if coltype[cell.col_idx]['basetype'] == 'n':\n coltype[cell.col_idx]['num_fmt'] = cell.number_format\n else:\n coltype[cell.col_idx]['num_fmt'] = None\n \n #print (cell.value, coltype[cell.col_idx]['basetype'], coltype[cell.col_idx]['num_fmt'])\n \n \n #release protection for cells to be filled by collectors, apply data constraints\n colcount = datasheet.max_column\n for col in range (1, colcount + 1, 1):\n for row in range (firstrow, lastrow + 1, 1):\n cell = datasheet.cell(column = col, row = row)\n cell.protection = Protection(locked = False, hidden = False)\n\n if datatypes == True:\n setDatatype(cell, coltype[col])\n\n if col == 1: #set color to each cell of tubenumber column\n setColor(cell, exceldef['cellcolor'])\n elif striped == True and int(row) % 2 == 0: # set colors for data cells, striped \n setColor(cell, exceldef['cellcolor'])\n \n #insert tubenumbers to column 1 in datasheet\n # do this after data_type was set \n rownum = firstrow\n for tube in range (int(firstTubeNo), int(lastTubeNo) + 1, 1):\n cell = datasheet.cell(column = 1, row = rownum)\n cell.value = tube\n rownum += 1\n #set protection, but it is only active when sheet protection is set above\n if protect_ids == True:\n cell.protection = Protection(locked = True, hidden = False)\n\n #reset style and content for rows not used by tubes\n rowcount = datasheet.max_row\n for row in itertools.islice(datasheet.iter_rows(), lastrow, rowcount):\n for cell in row:\n cell.value = None\n cell.fill = PatternFill(fill_type = None)\n cell.protection = Protection(locked = False, hidden = False)\n\n\n workbook.save(targetFilepath)\n return targetFilepath\n \n \n \n\n\nif __name__ == \"__main__\":\n\n\n if len(sys.argv) < 5: \n sys.exit ('''Write GBOL Collection Sheet.\n Usage: {0} templateFilepath targetFilepath firstTubeNo lastTubeNo transactionId lang\n templateFilepath: Path and filename of template collection sheet, e.g. documents/download/Sammeltabelle_GBOL_2014-10-14.xls\n targetFilepath: Path and filename of desired collection sheet, e.g. documents/download/700_2015-02-18_000000.xls\n firstTubeNo: Number of the first tube, e.g. 3500760\n lastTubeNo: Number of the last tube, e.g. 3500854\n transactionId: Transaction id as generated during material order, e.g. 700_2015-02-18_000000\n lang: Current language (not used)\n\n Example:\n {0} documents/download/Sammeltabelle_GBOL_2014-10-14.xls documents/download/700_2015-02-18_000000.xls 3500760 3500854 700_2015-02-18_000000\n '''.format(sys.argv[0]))\n\n else:\n args = sys.argv[1:]\n filepath = writeExcelFile(args)\n\n","sub_path":"WebPortal/gbol_portal/collection_sheet_write.py","file_name":"collection_sheet_write.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"613277281","text":"\"\"\"\nDAN The Automator\n\nhttps://www.youtube.com/watch?v=EtUT0D-tRHw\n\nKRad Shit\nLicense Goes Here\nFuck it\n\"\"\"\n\n__author__ = \"UVClay\"\n__version__ = \"git-master 5\"\nimport sys\nimport os\nimport configparser\nimport colorise\nimport re\nfrom time import strftime\nfrom subprocess import Popen\n\n_configfile = \"dan-test.conf\"\n_platform = sys.platform\n\n_danconfig = configparser.ConfigParser()\n_danconfig.read(_configfile)\n\ntry:\n _danconfig['main']['override']\nexcept KeyError:\n with open(_configfile, 'w') as confwrite:\n _danconfig['main']['override'] = '0'\n _danconfig.write(confwrite)\n confwrite.close()\n\nif _danconfig['main']['override'] != '1':\n if _platform == \"linux\" or _platform == \"linux2\":\n if os.environ.get(\"USERNAME\") != \"root\":\n colorise.cprint(\"You should be running this as root! DAN will automatically switch users.\", fg='red')\n quit()\n elif _platform == \"darwin\":\n if os.environ.get(\"USERNAME\") != \"root\":\n colorise.cprint(\"You should be running this as root! DAN will automatically switch users.\", fg='red')\n #quit()\n elif _platform == \"win32\":\n colorise.cprint(\n \"You should be running this as root! DAN will automatically switch users.\\n-little kid fucking dies-\",\n fg='red')\n # quit()\n else:\n colorise.cprint('Dunno what you\\'re running this on, dude. If it\\'s UNIX based, you should be fine.'\n '\\nDo you want to roll with it? (y/n)', fg='blue')\n if input() == 'y':\n colorise.cprint('Okay, cool. Just make sure you run this as root!')\n with open(_configfile, 'w') as confwrite:\n _danconfig['main']['override'] = '1'\n _danconfig.write(confwrite)\n confwrite.close()\n elif input() != 'y':\n colorise.cprint('Okay. I trust you fam. Sort out what you want to do then and come back maybe.')\n quit()\n else:\n colorise.cprint('You broke the logic and basically get fucked.')\n quit()\n\nif os.path.exists(_configfile):\n colorise.cprint(\"Configuration file found\", fg='green')\nelse:\n colorise.cprint(\"DAN config file not found! Please create one at \" + _configfile +\n \" before continuing.\\nSee https://www.github.com/UVClay/dan/wiki/GettingStarted for details.\",\n fg='red')\n quit()\n\ncolorise.cprint(\" ________ ________ ________ \", fg='blue')\ncolorise.cprint(\"|\\ ___ \\|\\ __ \\|\\ ___ \\ \", fg='blue')\ncolorise.cprint(\"\\ \\ \\_|\\ \\ \\ \\|\\ \\ \\ \\\\\\ \\ \\ \", fg='blue')\ncolorise.cprint(\" \\ \\ \\ \\\\\\ \\ \\ __ \\ \\ \\\\\\ \\ \\ \", fg='blue')\ncolorise.cprint(\" \\ \\ \\_\\\\\\ \\ \\ \\ \\ \\ \\ \\\\\\ \\ \\ \", fg='blue')\ncolorise.cprint(\" \\ \\_______\\ \\__\\ \\__\\ \\__\\\\\\ \\__\\ \", fg='blue')\ncolorise.cprint(\" \\|_______|\\|__|\\|__|\\|__| \\|__|\", fg='blue')\ncolorise.cprint(\" Version \" + __version__, fg='blue')\ncolorise.cprint(\" Running on \" + _platform, fg='blue')\n\ncleanextension = re.findall(r\"[\\w']+\", _danconfig['main']['extensions'])\nprint(\"\\n\\nDefined Extentions:\")\nprint(cleanextension)\nfor extension in cleanextension:\n if os.path.exists(_danconfig['main']['dandir'] + '/modules/extensions/' + extension + '.py'):\n colorise.cprint(extension, fg='green')\n else:\n colorise.cprint(extension + ' #Not Loaded (file not found)', fg='red')\n\ncleanbackup = re.findall(r\"[\\w']+\", _danconfig['main']['backups'])\nprint(\"\\n\\nDefined Backups:\")\nprint(cleanbackup)\nfor backup in cleanbackup:\n if os.path.exists(_danconfig['main']['dandir'] + '/modules/backups/' + backup + '.py'):\n colorise.cprint(backup, fg='green')\n else:\n colorise.cprint(backup + ' #Not Loaded (file not found)', fg='red')\n\ncleanoutput = re.findall(r\"[\\w']+\", _danconfig['main']['output'])\nprint(\"\\nDefined Outputs:\")\nprint(cleanoutput)\n\nfor output in cleanoutput:\n if os.path.exists(_danconfig['main']['dandir'] + '/modules/output/' + output + '.py'):\n colorise.cprint(output, fg='green')\n else:\n colorise.cprint(output + ' #Not Loaded (file not found)', fg='red')\n\n# Execution Phase\nfor extension in cleanextension:\n if os.path.exists(_danconfig['main']['dandir'] + '/modules/extensions/' + extension + '.py'):\n Popen(\"python3 \" + _danconfig['main']['dandir'] + \"/modules/extensions/\" + extension + \".py\")\n\nstrftime(\"%a, %d %b %Y %H:%M:%S\")","sub_path":"dan.py","file_name":"dan.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"604079837","text":"import torch\n\n\nclass DETRTracker:\n def __init__(self, name, network, device, data_processor):\n self.name = name\n network.to(device)\n network.eval()\n self.network = network\n self.device = device\n self.data_processor = data_processor\n\n def get_name(self):\n return self.name\n\n def initialize(self, image, bbox):\n z, z_mask = self.data_processor.do_init(image, bbox)\n z = z.unsqueeze(0)\n z_mask = z_mask.unsqueeze(0)\n z = z.to(self.device)\n z_mask = z_mask.to(self.device)\n with torch.no_grad():\n self.z_feat, self.z_feat_mask, self.z_feat_pos = self.network.inference_template(z, z_mask)\n\n def track(self, image):\n h, w = image.shape[0:2]\n x = self.data_processor.do_track(image)\n x = x.unsqueeze(0)\n x = x.to(self.device)\n with torch.no_grad():\n x_bbox_predicted = self.network.inference_instance(self.z_feat, self.z_feat_mask, self.z_feat_pos, x)\n x_bbox_predicted = x_bbox_predicted.cpu()\n x_bbox = self.data_processor.do_result(x_bbox_predicted[0], (w, h))\n return x_bbox\n","sub_path":"algorithms/tracker/detr_tracking_variants/encoder_shared_params_decoder_cross_attn_resnet50_decoder_no_z_mask_new_aug/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"16232104","text":"from time import sleep\n\nfrom districtobjects.Bungalow import Bungalow\nfrom districtobjects.FamilyHome import FamilyHome\nfrom districtobjects.Mansion import Mansion\n\n\nclass TightFit_A(object):\n name = \"TightFit_A\"\n expects = ['Waterbodies', \"Playgrounds\"]\n puts = [\"Residences\"]\n\n def getMinimumDistance(self, r):\n if isinstance(r, Mansion):\n return Mansion(0, 0).minimumClearance * self.m_clearance\n elif isinstance(r, Bungalow):\n return Bungalow(0, 0).minimumClearance * self.b_clearance\n elif isinstance(r, FamilyHome):\n return FamilyHome(0, 0).minimumClearance * self.f_clearance\n raise Exception\n\n def getPlan(self):\n return self.plan\n\n def place_residences(self, plan, frame=None, slow=False):\n\n i = 0\n r = self.next_to_place(i)\n r1 = r(0, 0)\n r1.original_min_clearance = r1.minimumClearance\n r1.minimumClearance = self.getMinimumDistance(r1)\n x = r1.minimumClearance\n\n while x < plan.width:\n\n y = r1.minimumClearance\n\n while y + r(0, 0).width + r(0, 0).minimumClearance < plan.height:\n r1 = r(x, y)\n r1.original_min_clearance = r1.minimumClearance\n r1.minimumClearance = self.getMinimumDistance(r1)\n\n # print plan.PLAYGROUND\n\n if plan.correctlyPlaced(r1):\n\n plan.addResidence(r1)\n if plan.NUMBER_OF_HOUSES == plan.getNumberOfHouses():\n return plan\n if frame is not None:\n frame.repaint(plan)\n if slow: sleep(0.1)\n y += r1.height + r1.minimumClearance\n i += 1\n r = self.next_to_place(i)\n else:\n y += 1\n x += r1.width + \\\n max(self.getMinimumDistance(r(0, 0)), r1.minimumClearance)\n return plan.deepCopy()\n\n def next_to_place(self, i):\n if i < self.fam_tresh:\n return FamilyHome\n elif i < self.bungalow_tresh:\n return Bungalow\n else:\n return Mansion\n\n def __init__(self, plan, i, j, k, frame=None, slow=False):\n\n assert isinstance(i, float)\n assert isinstance(j, float)\n assert isinstance(k, float)\n\n self.factors = [i, j, k]\n\n # print \"satight\",i,j,k\n self.f_clearance = i\n self.b_clearance = j\n self.m_clearance = k\n\n self.fam_tresh = plan.NUMBER_OF_HOUSES * plan.MINIMUM_FAMILYHOMES_PERCENTAGE\n self.bungalow_tresh = plan.NUMBER_OF_HOUSES * (\n plan.MINIMUM_FAMILYHOMES_PERCENTAGE + plan.MINIMUM_BUNGALOW_PERCENTAGE)\n\n self.plan = self.place_residences(plan, frame=frame, slow=slow).deepCopy()\n if frame is not None: frame.repaint(self.plan)\n # frame.repaint(self.plan)\n self.plan.params = [i, j, k]\n","sub_path":"code/residence_placers/TightFit_A.py","file_name":"TightFit_A.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"605404655","text":"import os.path\nimport re\n\nfrom setuptools import setup\n\n\ndef get_package_variable(name, rel_path='chinese_whispers/__init__.py'):\n path = os.path.join(os.path.abspath(os.path.dirname(__file__)), rel_path)\n\n pattern = re.compile(r'^{}.*?([\\'\"])(?P.+)\\1.*$'.format(re.escape(name)))\n\n with open(path, 'r', encoding='UTF-8') as f:\n for line in f:\n match = pattern.match(line)\n\n if match:\n return match.group('value')\n else:\n raise RuntimeError('Unable to find variable: ' + name)\n\n\n__version__ = get_package_variable('__version__')\n__license__ = get_package_variable('__license__')\n\nwith open('README.md', 'r', encoding='UTF-8') as f:\n long_description = f.read()\n\nwith open('requirements.txt', 'r', encoding='UTF-8') as f:\n install_requires = f.read()\n\nsetup(name='chinese-whispers',\n version=__version__,\n description='An implementation of the Chinese Whispers clustering algorithm.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/nlpub/chinese-whispers-python',\n author='NLPub',\n maintainer='Dmitry Ustalov',\n license=__license__,\n packages=['chinese_whispers'],\n entry_points={'console_scripts': ['chinese-whispers = chinese_whispers.__main__:main']},\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Topic :: Scientific/Engineering :: Information Analysis',\n 'Typing :: Typed'\n ],\n keywords=['graph clustering', 'unsupervised learning', 'chinese whispers', 'cluster analysis'],\n install_requires=install_requires,\n zip_safe=True)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"308673786","text":"from django.shortcuts import render, redirect\nfrom django.contrib import auth, messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.db.models import Q\nfrom session.models import User, account_activation_token\nfrom lib.decorators import anonymous_required\nfrom django.utils.encoding import force_text\nfrom django.utils.http import urlsafe_base64_decode\nfrom . import forms\nfrom lib.helpers import notify_form_errors\n\n@login_required\ndef logout(request):\n auth.logout(request)\n return redirect(\"index\")\n\n@anonymous_required\ndef index(request):\n register_form = forms.UserRegistrationForm()\n login_form = forms.UserLoginForm()\n return render(request, \"session/index.html\", {\"register_form\": register_form, \"login_form\": login_form})\n\n\n@anonymous_required\ndef login_handler(request):\n if request.method == \"POST\":\n form = forms.UserLoginForm(request.POST)\n\n if form.is_valid():\n # Form validation takes care of invalid credentials\n user = None\n user = User.objects.filter(Q(email=form.cleaned_data[\"identifier\"]) | Q(username=form.cleaned_data[\"identifier\"])).first()\n\n if not user.email_validated:\n user.send_activation_email(request)\n return redirect(\"session:activation-needed\")\n\n # Set the backend so Django knows how to authenticate\n user.backend = \"django.contrib.auth.backends.ModelBackend\"\n auth.login(request, user)\n\n if not user.finish_setup:\n return redirect(\"session:finish-setup\")\n\n return redirect(settings.POST_LOGIN_URL)\n else:\n notify_form_errors(request, form)\n\n return redirect(\"sess:index\")\n\n\n@anonymous_required\ndef register_handler(request):\n if request.method == \"POST\":\n form = forms.UserRegistrationForm(request.POST)\n\n if form.is_valid():\n user = User.objects.create_user(email=form.cleaned_data[\"email\"], password=form.cleaned_data[\"password\"],\n username=form.cleaned_data[\"username\"])\n user.send_activation_email(request)\n return redirect(\"sess:activation-needed\")\n else:\n notify_form_errors(request, form)\n\n return redirect(\"sess:index\")\n\n\n@anonymous_required\ndef email_validation_wait(request):\n return render(request, \"session/email_verify_wait.html\")\n\n\n@anonymous_required\ndef activate_email(request, uidb64, token):\n # Check the user\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n\n if not user or not account_activation_token.check_token(user, token):\n messages.error(request, \"Invalid validation link.\")\n return redirect(\"sess:activation-needed\")\n\n user.email_validated = True\n user.save(update_fields=[\"email_validated\"])\n messages.success(request, \"Successfully verified your email!\")\n\n # Log the user in\n user.backend = \"django.contrib.auth.backends.ModelBackend\"\n auth.login(request, user)\n\n if not user.finish_setup:\n return redirect(\"sess:finish-setup\")\n\n return redirect(settings.POST_LOGIN_URL)\n\n\n@login_required\ndef finish_user_setup(request):\n\n if request.user.finish_setup:\n return redirect(\"dash:index\")\n\n if request.method == \"POST\":\n form = forms.UserFinishSetupForm(request.POST, request.FILES, user=request.user)\n\n if form.is_valid():\n # Save what we know is good\n request.user.username = form.cleaned_data[\"username\"]\n request.user.first_name = form.cleaned_data[\"first_name\"]\n request.user.last_name = form.cleaned_data[\"last_name\"]\n\n if request.FILES.get(\"avatar\", None):\n request.user.avatar_url = request.FILES[\"avatar\"]\n\n request.user.finish_setup = True\n\n request.user.save()\n\n return redirect(\"dash:index\")\n\n else:\n form = forms.UserFinishSetupForm()\n\n return render(request, \"session/finish_setup.html\", {\"form\": form})\n","sub_path":"session/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"407596134","text":"from flask.ext.api import FlaskAPI\nfrom cmc_publish_failure_assistant import CMCPublishFailureAssistant\n\napp = FlaskAPI(__name__)\n\npublish_failure_assistant = CMCPublishFailureAssistant()\n\n\ndef get_str_id(objectID):\n return str(objectID)\n\n\ndef get_failsafe_key_value(dictionary, key, default=''):\n return dictionary.get(key, default)\n\n# Purpose: Make sure the dict object has string in place of ObjectID\n# and this purifying should be deep down in every level and return\n# only the keys specified in pluck_keys\ndef cleanup_dict(dict_obj, pluck_keys=None):\n for k, v in dict_obj.iteritems():\n if v and k in pluck_keys:\n if type(v).__name__ != 'dict' and type(v).__name__ == 'ObjectId':\n dict_obj[k] = get_str_id(v)\n else:\n dict_obj[k] = cleanup_dict(v)\n else:\n del dict_obj[k]\n return dict_obj\n\n\n# pluck_keys = which keys from actual response should be included\ndef make_failsafe_get_call(api_call_helper, method, param, pluck_keys=None):\n try:\n object = getattr(api_call_helper, method)(param)\n data = {}\n for key in pluck_keys if pluck_keys else object:\n value = get_failsafe_key_value(object, key, '')\n data[key] = get_str_id(value) if type(value).__name__ == 'ObjectId' else value\n return {\n 'status': 200,\n 'message': 'success',\n 'data': data\n }\n except Exception as e:\n return {\n 'status': 500,\n 'message': 'internal error',\n 'log': str(e)\n }\n\n\n@app.route('/distribution/')\ndef get_distribution(dist_id):\n pluck_keys = ['channel', 'campaign', 'originatingUser']\n return make_failsafe_get_call(publish_failure_assistant, 'get_distribution', str(dist_id), pluck_keys=pluck_keys)\n\n\n@app.route('/distribution//organization')\ndef get_org_for_distribution(dist_id):\n pluck_keys = ['access_key', ]\n return make_failsafe_get_call(publish_failure_assistant, 'get_organization_for_distribution', str(dist_id))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"cmc_publish_failure_tool/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"366954495","text":"import os,subprocess, random\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nfrom PIL import ImageEnhance\nfrom PIL import ImageFilter\nimport PIL.ImageOps\nimport PIL\n\nroot_path=os.getcwd()\nin_path=str(root_path+\"/in/\")\nout_path=str(root_path+\"/out/\")\ndb_path = os.path.abspath(root_path+\"/images_db/\")\n\nos.chdir(root_path)\n\nfor i,f in enumerate(os.listdir(db_path)):\n\tsource = os.path.join(db_path, f)\n\tdestination = os.path.join(in_path,(str(\"in.jpg\")))\n\tos.rename(source, destination)\n\tif i == 1:\n\t\tbreak\n\t\t\t\nos.chdir(in_path)\n\nimg=Image.open(\"in.jpg\")\nwidth, height = img.size\n\nuse_emboss = random.randint(0,3)\n\nuse_contour = random.randint(0,3)\n\nuse_unsharp = random.randint(0,1)\n\nuse_invert = random.randint(0,3)\n\nuse_contrast = random.randint(0,3)\n\nuse_color = random.randint(0,3)\n\nuse_posterize = random.randint(0,4)\n\nuse_shakal = random.randint(0,3)\n\nuse_noise = random.randint(0,2)\n\nuse_solarize = random.randint(0,3)\n\nif use_emboss == 1:\n img = img.filter(ImageFilter.EMBOSS)\n\nif use_contour == 1:\n\timg = img.filter(ImageFilter.CONTOUR)\n\timg = img.filter(ImageFilter.SMOOTH_MORE)\n\nif use_unsharp == 1:\n\trandradius=random.randint(10,50)\n\trandperc=random.randint(200,1000)\n\trandthreshold=random.randint(50,100)\n\timg = img.filter(ImageFilter.UnsharpMask(radius=randradius, percent=randperc, threshold=randthreshold))\n\t\nif use_contrast != 0:\n img_contrast_enhanced = PIL.ImageEnhance.Contrast(img)\n contrast_factor=random.randint(5,20)\n img = img_contrast_enhanced.enhance(contrast_factor)\n\nif use_color != 0:\n img_color_enhanced = PIL.ImageEnhance.Color(img)\n color_factor=random.randint(5,100)\n img = img_color_enhanced.enhance(color_factor)\n\n\nif use_invert != 0:\n img = PIL.ImageOps.invert(img)\n\n\nif use_posterize != 0:\n\timg = PIL.ImageOps.posterize(img,1)\n\n\nif use_solarize !=0:\n\tsolar_rand=random.randint(30,120)\n\timg=PIL.ImageOps.solarize(img,threshold=solar_rand)\n\nif (use_noise != 0 and use_emboss !=1 and use_contour != 1):\n\timg_pixels = img.load()\n\tnoise_factor = random.randint(10,20)\n\tdraw = ImageDraw.Draw(img)\n\tfor noise_x in range(width):\n\t\tfor noise_y in range(height):\n\t\t\tnoise_random = random.randint(-noise_factor,noise_factor )\n\t\t\tnoise_r = img_pixels[noise_x, noise_y][0] + noise_random\n\t\t\tnoise_g = img_pixels[noise_x, noise_y][1] + noise_random\n\t\t\tnoise_b = img_pixels[noise_x, noise_y][2] + noise_random\n\t\t\tif (noise_r < 0):\n\t\t\t\tnoise_r = 0\n\t\t\tif (noise_g < 0):\n\t\t\t\tnoise_g = 0\n\t\t\tif (noise_b < 0):\n\t\t\t\tnoise_g = 0\n\t\t\tif (noise_r > 255):\n\t\t\t\tnoise_r = 255\n\t\t\tif (noise_g > 255):\n\t\t\t\tnoise_g = 255\n\t\t\tif (noise_b > 255):\n\t\t\t\t noise_b = 255\n\t\t\tdraw.point((noise_x, noise_y), (noise_r, noise_g, noise_b))\n\nos.chdir(out_path)\n\nimg = PIL.ImageOps.equalize(img, mask=None)\n\nif use_shakal != 0:\n\timg.save(\"out.temp.jpg\",\"JPEG\", quality=2)\nelse:\n\timg.save(\"out.temp.jpg\", \"JPEG\", quality=100)\n\nimg1=Image.open(\"out.temp.jpg\")\n\nwidth1, height1 = img1.size\nwidth_half=int(width/2)\n\nif (width1 < 500 & height1<500):\n\tfont_size_ebat = 32\n\tfont_size_water = 12\n\ttextheight=height1-48\n\tmiddle=width_half-128\n\nelif (width1 <=1000 | height1 > 500):\n\tfont_size_ebat = 64\n\tfont_size_water = 18\n\ttextheight=height1-80\n\tmiddle=width_half-256\n\nelif width1 <= 2000:\n\tfont_size_ebat = 128\n\tfont_size_water = 48\n\ttextheight=height1-160\n\tmiddle=width_half-512\nelse:\n\tfont_size_ebat = 256\n\tfont_size_water = 96\n\ttextheight=height1-1152\n\tmiddle=width_half-1024\n\nrgb_img = img1.convert('RGB')\nr_w, g_w, b_w = rgb_img.getpixel((10,10))\n\nfont_ebat_color_rsum = 0\nfont_ebat_color_gsum = 0\nfont_ebat_color_bsum = 0\npixel_ebat_count=0\nimg1_pixels = img1.load()\n\nfor font_ebat_color_x in range(width1):\n\tfor font_ebat_color_y in range (textheight,height):\n\n\t\tfont_ebat_color_r = img1_pixels[font_ebat_color_x, font_ebat_color_y][0]\n\t\tfont_ebat_color_g = img1_pixels[font_ebat_color_x, font_ebat_color_y][1]\n\t\tfont_ebat_color_b = img1_pixels[font_ebat_color_x, font_ebat_color_y][2]\n\t\tpixel_ebat_count += 1\n\t\tfont_ebat_color_rsum += font_ebat_color_r\n\t\tfont_ebat_color_gsum += font_ebat_color_g\n\t\tfont_ebat_color_bsum += font_ebat_color_b\n\nfont_ebat_color_rmean = int(font_ebat_color_rsum/pixel_ebat_count)\nfont_ebat_color_gmean = int(font_ebat_color_gsum/pixel_ebat_count)\nfont_ebat_color_bmean = int(font_ebat_color_bsum/pixel_ebat_count)\n\nif(font_ebat_color_rmean < 90 and font_ebat_color_gmean < 90 and font_ebat_color_bmean < 90):\n font_color_ebat=(255,255,255)\nelif (font_ebat_color_rmean > 100 or font_ebat_color_gmean > 100 or font_ebat_color_bmean > 100):\n font_color_ebat=(0,0,0)\nelse:\n\tfont_color_ebat=(100,100,100)\n\nfont_water_color_rsum = 0\nfont_water_color_gsum = 0\nfont_water_color_bsum = 0\npixel_water_count=100\n\nfor font_water_color_x in range(width1):\n for font_water_color_y in range (0,100):\n font_water_color_r = img1_pixels[font_water_color_x, font_water_color_y][0]\n font_water_color_g = img1_pixels[font_water_color_x, font_water_color_y][1]\n font_water_color_b = img1_pixels[font_water_color_x, font_water_color_y][2]\n pixel_water_count += 1\n font_water_color_rsum += font_water_color_r\n font_water_color_gsum += font_water_color_g\n font_water_color_bsum += font_water_color_b\n\nfont_water_color_rmean = int(font_water_color_rsum/pixel_water_count)\nfont_water_color_gmean = int(font_water_color_gsum/pixel_water_count)\nfont_water_color_bmean = int(font_water_color_bsum/pixel_water_count)\n\nif(font_water_color_rmean < 90 and font_water_color_gmean < 90 and font_water_color_bmean < 90):\n font_color_water=(128,128,128)\nelif (font_water_color_rmean > 100 or font_water_color_gmean > 100 or font_water_color_bmean > 100): \n font_color_water=(64,64,64)\t\nelse:\n\tfont_color_water=(32,32,32)\nrandom_a_x=random.randint(0,width1-100)\nrandom_a_y=random.randint(0,textheight)\nrgb_a = img1.convert('RGB')\nr_a,g_a,b_a = rgb_a.getpixel((random_a_x,random_a_y))\n\nif ((r_a < 80 and g_a < 80 and b_a < 80)):\n\tfont_color_a = (255,255,255)\nelse:\n\tfont_color_a = (0,0,0)\n\nos.chdir(root_path)\n\nfont = \"font.ttf\"\nunicode_font_ebat = ImageFont.truetype(font, font_size_ebat)\nunicode_font_water = ImageFont.truetype(font, font_size_water)\nunicode_font_a = ImageFont.truetype(font, font_size_water)\n\nos.chdir(out_path)\n\ndraw = ImageDraw.Draw (img1)\n\nzhmih_roulette = random.randint(1,10)\nif zhmih_roulette == 1:\n\tdraw.text ((middle,textheight), \"iбатб жмыхнуло\", font=unicode_font_ebat,fill=font_color_ebat)\nelse:\n\tdraw.text ((middle,textheight), \"ебать жмыхнуло\", font=unicode_font_ebat,fill=font_color_ebat)\n\ndraw.text ((0,0), \"https://vk.com/ebat_zhmihnulo\", font=unicode_font_water,fill=font_color_water)\ndraw.text ((random_a_x,random_a_y),\"а\", font=unicode_font_a, fill=font_color_a)\nimg1.save(\"out.jpg\", \"JPEG\", quality=100)\n\nprint(\"EXTRA FRIED!Check\",out_path+\"out.jpg!\")\n","sub_path":"Shakal.py","file_name":"Shakal.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"456332054","text":"from keras.models import *\r\nfrom keras.layers import *\r\nfrom keras.optimizers import SGD\r\nfrom keras.applications.vgg16 import VGG16\r\nfrom keras import layers\r\nfrom keras.applications import *\r\nfrom keras.preprocessing.image import *\r\nfrom keras.callbacks import ModelCheckpoint\r\n\r\ndef create_model():\r\n vgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\r\n \r\n # Freeze the layers except the last 4 layers\r\n for layer in vgg_conv.layers[:-4]:\r\n layer.trainable = False\r\n \r\n for layer in vgg_conv.layers:\r\n print(layer, layer.trainable)\r\n \r\n # Create the model\r\n model = Sequential()\r\n \r\n # Add the vgg convolutional base model\r\n model.add(vgg_conv)\r\n \r\n # Add new layers\r\n #model.add(layers.Flatten())\r\n #model.add(layers.Dense(1024, activation='relu'))\r\n #model.add(layers.Dropout(0.5))\r\n #model.add(layers.Dense(10, activation='softmax'))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n model.add(layers.Convolution2D(512, (7, 7)))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n model.add(layers.Convolution2D(512,(1,1)))\r\n model.add(BatchNormalization())\r\n model.add(Activation('relu'))\r\n model.add(layers.Convolution2D(10,(1,1)))\r\n model.add(layers.Flatten())\r\n model.add(layers.Dense(10,activation='softmax'))\r\n \r\n return model\r\n \r\n\r\n\r\ndef model_train():\r\n model = create_model()\r\n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\r\n model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])\r\n checkpointer = ModelCheckpoint(filepath=\"weights.{epoch:04d}.dataAug.hdf5\", verbose=1, save_best_only=True, period=1)\r\n image_size = (224, 224)\r\n \r\n gen = ImageDataGenerator(rescale=1./255,rotation_range=30,shear_range=0.2,zoom_range=0.2)\r\n \r\n #gen = ImageDataGenerator(rescale=1./255, validation_split=0.2)\r\n train_generator = gen.flow_from_directory(\"mask_rcnn_full\", image_size, shuffle=True, batch_size=32, subset='training')\r\n validation_generator = gen.flow_from_directory(\"mask_rcnn_full\", image_size, shuffle=True, batch_size=32, subset='validation')\r\n nb_val = len(validation_generator.filenames)\r\n nb_trian = len(train_generator.filenames)\r\n print(\"nb_val:\",nb_val)\r\n print(\"nb_trian:\",nb_trian)\r\n \r\n model.fit_generator(train_generator, validation_data=validation_generator, nb_epoch=6, steps_per_epoch=nb_train//32*2, validation_steps=nb_val//32,callbacks=[checkpointer])\r\n\r\ndef load_model(weights_path):\r\n model = create_model()\r\n model.load_weights(weights_path)\r\n return model\r\n \r\n\r\nmodel_train()\r\n\r\n\r\n\r\n#VGG_epoch1 = load_model('weights.0001.hdf5')\r\n#VGG_epoch2 = load_model('weights.0002.hdf5')\r\n#VGG_epoch3 = load_model('weights.0003.hdf5')\r\n#VGG_epoch4 = load_model('weights.0004.hdf5')\r\n#VGG_epoch5 = load_model('weights.0005.hdf5')\r\n#VGG_epoch6 = load_model('weights.0006.hdf5')\r\n#\r\n#\r\n#\r\n#from keras.preprocessing.image import *\r\n#from keras.models import *\r\n#from keras.layers import *\r\n#from keras.applications import *\r\n#from keras.preprocessing.image import *\r\n#from keras.callbacks import ModelCheckpoint\r\n#\r\n#def predict_on_test(test_dir):\r\n# \r\n# models = [\"VGG_epoch1\",\"VGG_epoch2\",\"VGG_epoch3\",\"VGG_epoch4\",\"VGG_epoch5\",\"VGG_epoch6\"]\r\n# test_datagen = ImageDataGenerator(rescale=1./255)\r\n# height = 224\r\n# width = 224\r\n# batch_size = 32\r\n# f = h5py.File('VGGpreds.h5', 'w')\r\n#\r\n# for model in models:\r\n# test_generator = test_datagen.flow_from_directory(test_dir, target_size=(height, width),batch_size=1,class_mode='categorical', shuffle=False,)\r\n# filenames = test_generator.filenames\r\n# nb_samples = len(filenames)\r\n# preds = VGG_epoch1.predict_generator(test_generator, steps = nb_samples//batch_size)\r\n# f.create_dataset(model[-6:],data=preds)\r\n# \r\n# f.close()\r\n# ","sub_path":"VGG_modified_data_augmentation.py","file_name":"VGG_modified_data_augmentation.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"196909643","text":"\"\"\"\nUnittest the sorting algorithms\n\"\"\"\n\nimport unittest\nfrom Sorting.quickSort import *\nfrom Sorting.mergeSort import *\nfrom Sorting.heapSort import *\n\n\nclass UnittestSorting(unittest.TestCase):\n def setUp(self):\n self.testcases = []\n self.testcases.append([])\n self.testcases.append([1])\n self.testcases.append([1, 2, 3])\n self.testcases.append([3, 2, 1])\n self.testcases.append([1, 1, 2])\n self.testcases.append([2, 2, 1])\n self.testcases.append([2, 2, 2])\n self.testcases.append([1, 24, 98, 27, 18, 89, 77])\n\n def test_quickSort(self):\n for nums in self.testcases:\n print('Sorting', nums)\n if quick_sort(nums, 0, len(nums) - 1) != sorted(nums):\n print(quick_sort(nums, 0, len(nums) - 1))\n print('Wrong result for test case', nums)\n print('Expected', sorted(nums))\n\n def test_mergeSort(self):\n for nums in self.testcases:\n if merge_sort(nums, 0, len(nums), [0]*len(nums)) != sorted(nums):\n print(merge_sort(nums, 0, len(nums), [0]*len(nums)))\n print('Wrong result for test case', nums)\n print('Expected', sorted(nums))\n\n def test_heapSort(self):\n for nums in self.testcases:\n print('Sorting', nums, '...')\n if heap_sort(nums) != sorted(nums):\n print('Wrong result for test case', nums)\n print('Expected', sorted(nums))\n print('After heap sort', heap_sort(nums))\n","sub_path":"Sorting/unit_test_sortings.py","file_name":"unit_test_sortings.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"244574452","text":"# (c) Copyright IBM Corp. 2022. All Rights Reserved.\n\"\"\"ResilientHelper Module\"\"\"\nimport base64\nimport logging\n\nimport six\nfrom bs4 import BeautifulSoup\nfrom resilient import SimpleHTTPException\n\n# Handle unicode in 2.x and 3.x\ntry:\n unicode\nexcept NameError:\n unicode = str\n\nCONFIG_DATA_SECTION = \"fn_service_now\"\nSECOPS_TABLE_NAME = \"sn_si_incident\"\nSECOPS_PLAYBOOK_TASK_TABLE_NAME = \"sn_si_task\"\nSECOPS_PLAYBOOK_TASK_PREFIX = \"SIT\"\nCP4S_CASES_REST_PREFIX = \"cases-rest\"\n\nLOG = logging.getLogger(__name__)\n\n# Define an Incident that gets sent to ServiceNow\nclass Incident(object):\n \"\"\"Class that represents a Resilient Incident. See API notes for more\"\"\"\n def __init__(self, incident_id, incident_name, incident_description):\n self.type = \"res_incident\"\n self.incident_id = incident_id\n self.incident_name = incident_name\n self.incident_description = incident_description\n\n def as_dict(self):\n \"\"\"Returns this class object as a dictionary\"\"\"\n return self.__dict__\n\n\n# Define a Task that gets sent to ServiceNow\nclass Task(object):\n \"\"\"Class that represents a Resilient Task. See API notes for more\"\"\"\n def __init__(self, incident_id, task_id, task_name, task_instructions):\n self.type = \"res_task\"\n self.incident_id = incident_id\n self.task_id = task_id\n self.task_name = task_name\n self.task_instructions = task_instructions\n\n def as_dict(self):\n \"\"\"Returns this class as a Dictionary\"\"\"\n return self.__dict__\n\n\nclass ResilientHelper(object):\n \"\"\"A helper class for sn_utilities\"\"\"\n def __init__(self, app_configs):\n\n log = logging.getLogger(__name__)\n log.debug(\"Initializing ResilientHelper\")\n\n self.app_configs = app_configs\n\n self.SN_HOST = self.get_config_option(\"sn_host\", placeholder=\"https://instance.service-now.com\")\n self.SN_API_URI = self.get_config_option(\"sn_api_uri\")\n\n # https://service-now-host.com/api//\"))\n\n # Handle password surrounded by ' or \"\n pwd = str(self.get_config_option(\"sn_password\", placeholder=\"\"))\n if (pwd.startswith(\"'\") and pwd.endswith(\"'\")) or (pwd.startswith('\"') and pwd.endswith('\"')):\n self.SN_PASSWORD = pwd[1:-1]\n else:\n self.SN_PASSWORD = pwd\n\n self.SN_AUTH = (self.SN_USERNAME, self.SN_PASSWORD)\n\n self.CP4S_PREFIX = self.get_config_option(\"cp4s_cases_prefix\", placeholder=CP4S_CASES_REST_PREFIX, optional=True)\n\n # Default headers\n self.headers = {\"Content-Type\": \"application/json\", \"Accept\": \"application/json\"}\n\n log.debug(\"ResilientHelper initialized\")\n log.debug(\"App Configs: sn_host: %s sn_api_uri: %s sn_api_url: %s sn_table_name: %s sn_username: %s cp4s_cases_prefix: %s\",\n self.SN_HOST, self.SN_API_URI, self.SN_API_URL, self.SN_TABLE_NAME, self.SN_USERNAME, self.CP4S_PREFIX)\n\n @classmethod\n def _byteify(cls, data):\n \"\"\"Function to handle json.loads object_hook for supporting Python 2 and 3\"\"\"\n\n if six.PY2:\n if isinstance(data, unicode):\n return data.encode(\"utf-8\")\n\n elif isinstance(data, dict):\n return {cls._byteify(key): cls._byteify(value) for key, value in data.items()}\n\n return data\n\n elif six.PY3:\n data_as_utf8_str = data\n\n if isinstance(data, unicode):\n data_as_utf8_str = data.encode(\"utf-8\")\n\n # if Python 3.x data_as_utf8_str will be bytes, so we convert back to str\n if isinstance(data_as_utf8_str, bytes):\n data_as_utf8_str = data_as_utf8_str.decode((\"utf-8\"))\n\n elif isinstance(data, dict):\n data_as_utf8_str = {cls._byteify(key): cls._byteify(value) for key, value in data.items()}\n\n return data_as_utf8_str\n else:\n raise ValueError(\"We do not support this version of Python\")\n\n @staticmethod\n def _encodeBase64(str_to_encode):\n \"\"\"A helper function to encode a base64 string for Python 3 and 3 support\"\"\"\n if six.PY2:\n return base64.b64encode(str_to_encode)\n\n elif six.PY3:\n str_to_encode = base64.b64encode(str_to_encode)\n return str_to_encode.decode(\"utf-8\")\n\n else:\n raise ValueError(\"We do not support this version of Python\")\n\n @staticmethod\n def str_to_unicode(str_to_convert):\n if six.PY2:\n return unicode(str_to_convert)\n\n elif six.PY3:\n return str(str_to_convert)\n\n else:\n raise ValueError(\"We do not support this version of Python\")\n\n def get_config_option(self, option_name, optional=False, placeholder=None):\n \"\"\"Given option_name, checks if it is in appconfig. Raises ValueError if a mandatory option is missing\"\"\"\n option = self.app_configs.get(option_name, placeholder)\n err = \"'{0}' is mandatory and is not set in app.config file. You must set this value to run this function\".format(option_name)\n\n if not option and optional is False:\n raise ValueError(err)\n elif optional is False and placeholder is not None and option == placeholder:\n raise ValueError(err)\n else:\n return option\n\n @staticmethod\n def get_function_input(inputs, input_name, optional=False):\n \"\"\"Given input_name, checks if it defined. Raises ValueError if a mandatory input is None\"\"\"\n\n log = logging.getLogger(__name__)\n log.debug(\"Trying to get function input: %s from %s. optional = %s\", input_name, inputs, optional)\n\n the_input = inputs.get(input_name)\n\n if the_input is None and optional is False:\n err = \"'{0}' is a mandatory function input\".format(input_name)\n raise ValueError(err)\n else:\n log.debug(\"Got function input: %s\", input_name)\n return the_input\n\n @staticmethod\n def generate_res_id(incident_id, task_id=None, sn_res_id=None):\n \"\"\"If incident_id and task_id are valid, returns \"RES-1001-2002\"\n Else if task_id is None, returns \"RES-1001\". If sn_res_id if defined\n just return it. \"\"\"\n\n # If sn_res_id is defined, just return it. This helps us with closing from Data Table\n if sn_res_id is not None:\n return sn_res_id\n\n res_id = [\"RES\", str(incident_id)]\n if task_id is not None:\n res_id.append(str(task_id))\n return \"-\".join(res_id)\n\n @staticmethod\n def parse_res_id(res_id):\n \"\"\"Parse res_id (RES-1001-2002) and return a dict with incident_id and task_id\"\"\"\n incident_id, task_id = None, None\n ids = res_id.split(\"-\")\n\n incident_id = ids[1]\n if len(ids) == 3:\n task_id = ids[2]\n\n return {\"incident_id\": incident_id, \"task_id\": task_id}\n\n def generate_res_link(self, incident_id, host, org_id, task_id=None):\n \"\"\"Function that generates a https URL to the incident or task\"\"\"\n\n # for CP4S cases endpoint, remove the cases-rest prefix (CP4S_CASES_REST_PREFIX)\n if self.CP4S_PREFIX in host:\n base_host = host.replace(self.CP4S_PREFIX + \".\", \"\")\n link = \"https://{0}/app/respond/#cases/{1}\".format(base_host, incident_id)\n else:\n link = \"https://{0}/#incidents/{1}\".format(host, incident_id)\n\n if task_id is not None:\n link += \"?taskId={0}&tabName=details&orgId={1}\".format(task_id, org_id)\n\n return link\n\n def generate_sn_link(self, sn_query, sn_table_name=None):\n \"\"\"Function that generates a URL to the record in ServiceNow\"\"\"\n if not sn_table_name:\n sn_table_name = self.SN_TABLE_NAME\n\n # https://devxxxx.service-now.com/nav_to.do?uri=incident.do?sysparm_query=number=INC0000009\n uri = \"{0}/nav_to.do?uri={1}.do?sysparm_query={2}\".format(self.SN_HOST, sn_table_name, sn_query)\n return uri\n\n @staticmethod\n def convert_text_to_richtext(text, color=\"green\"):\n \"\"\"Converts text to richtext and adds a color\"\"\"\n\n colors = {\n \"green\": \"#00b33c\",\n \"orange\": \"#ff9900\",\n \"yellow\": \"#e6e600\",\n \"red\": \"#e60000\"\n }\n\n color = colors.get(color)\n\n return \"\"\"
    {1}
    \"\"\".format(color, text)\n\n @staticmethod\n def state_to_text(state):\n \"\"\"Converts O/A to Active and C to Closed\"\"\"\n if state == \"O\" or state == \"A\":\n return \"Active\"\n elif state == \"C\":\n return \"Closed\"\n else:\n raise ValueError(\"{0} is not a valid Resilient State. O=Open Task, A=Active Incident, C=Closed Incident/Task\".format(state))\n\n @staticmethod\n def get_incident(client, incident_id):\n \"\"\"Function that gets the incident from Resilient\"\"\"\n\n log = logging.getLogger(__name__)\n err_msg = None\n get_url = \"/incidents/{0}?text_content_output_format=always_text&handle_format=names\".format(incident_id)\n\n # Get the incident from resilient api\n try:\n log.debug(\"GET Incident from Resilient: ID %s URL: %s\", incident_id, get_url)\n incident = client.get(get_url)\n log.debug(\"Incident got successfully: %s\", incident)\n except Exception as err:\n err_msg = \"Error trying to get Incident {0}.\".format(incident_id)\n\n if err.message and \"not found\" in err.message.lower():\n err_msg = \"{0} Could not find Incident with ID {1}\".format(err_msg, incident_id)\n elif isinstance(err, SimpleHTTPException):\n err_msg = \"{0}\\nServer Error.\\nStatus Code: {1}\\nURL: {2}\\n{3}\".format(err_msg, err.response.status_code, err.response.url, err.message)\n else:\n err_msg = \"{0} {1}\".format(err_msg, err)\n\n raise ValueError(err_msg)\n\n return Incident(incident_id, incident[\"name\"], incident[\"description\"])\n\n @staticmethod\n def rename_incident(client, incident_id, new_incident_name):\n \"\"\"\n Static function to update the name of a incident.\n Primarily used for prepending sn_ref_id to the incident's name\n for easy filtering when viewing incident list\n \"\"\"\n\n def change_func(data):\n data[\"name\"] = new_incident_name\n\n url = \"/incidents/{0}?text_content_output_format=always_text&handle_format=names\".format(incident_id)\n\n # Use the get_put option to GET the data, apply the change, and PUT it back to the server\n try:\n LOG.debug(\"PUT Incident from Resilient: ID: %s URL: %s New Name: %s\", incident_id, url, new_incident_name)\n client.get_put(url, change_func)\n LOG.info(\"Incident was successfully renamed to '%s'\", new_incident_name)\n except Exception as err:\n raise ValueError(str(err))\n\n @staticmethod\n def get_task(client, task_id, incident_id):\n \"\"\"Function that gets the task from Resilient. Gets the task's instructions too\"\"\"\n\n log = logging.getLogger(__name__)\n err_msg = None\n\n # Get the task from resilient api\n try:\n get_url = \"/tasks/{0}?text_content_output_format=always_text&handle_format=names\".format(task_id)\n log.debug(\"GET Task from Resilient: ID %s URL: %s\", task_id, get_url)\n task = client.get(get_url)\n log.debug(\"Task got successfully: %s\", task)\n except Exception as err:\n err_msg = \"Error trying to get Task {0}.\".format(task_id)\n\n if err.message and \"not found\" in err.message.lower():\n err_msg = \"{0} Could not find Task with ID {1}\".format(err_msg, task_id)\n elif isinstance(err, SimpleHTTPException):\n err_msg = \"{0}\\nServer Error.\\nStatus Code: {1}\\nURL: {2}\\n{3}\".format(err_msg, err.response.status_code, err.response.url, err.message)\n else:\n err_msg = \"{0} {1}\".format(err_msg, err)\n\n raise ValueError(err_msg)\n\n\n # Get the task_instructions in plaintext\n try:\n get_url = \"/tasks/{0}/instructions_ex\".format(task_id)\n log.debug(\"GET task_instructions for: ID %s URL: %s\", task_id, get_url)\n task_instructions = client.get_content(get_url)\n soup = BeautifulSoup(unicode(task_instructions, \"utf-8\"), 'html.parser')\n soup = soup.get_text()\n # BeautifulSoup decoding of the HTML includes quotation marks and non-breaking spaces\n # so we need to remove those for the instructions text that will go to SNOW\n task_instructions = soup.replace(u'\\xa0', u' ').replace(u'\"',u'')\n log.debug(\"task_instructions got successfully\")\n except Exception as err:\n err_msg = \"Error trying to get task_instructions for Task {0}.\".format(task_id)\n\n if isinstance(err, SimpleHTTPException):\n err_msg = \"{0}\\nServer Error.\\nStatus Code: {1}\\nURL: {2}\\n{3}\".format(err_msg, err.response.status_code, err.response.url, err.message)\n else:\n err_msg = \"{0} {1}\".format(err_msg, err)\n\n raise ValueError(err_msg)\n\n\n return Task(incident_id, task_id, task[\"name\"], task_instructions)\n\n @staticmethod\n def rename_task(client, task_id, new_task_name):\n \"\"\"\n Static function to update the name of a task.\n Primarily used for prepending sn_ref_id to the task's name\n for easy filtering when viewing task list\n \"\"\"\n\n def change_func(data):\n data[\"name\"] = new_task_name\n\n url = \"/tasks/{0}?text_content_output_format=always_text&handle_format=names\".format(task_id)\n\n # Use the get_put option to GET the data, apply the change, and PUT it back to the server\n try:\n LOG.debug(\"PUT Task from Resilient: ID: %s URL: %s New Name: %s\", task_id, url, new_task_name)\n client.get_put(url, change_func)\n LOG.info(\"Task was successfully renamed to '%s'\", new_task_name)\n except Exception as err:\n raise ValueError(str(err))\n\n\n @classmethod\n def get_attachment(cls, res_client, attachment_id, incident_id=None, task_id=None):\n \"\"\"Function that gets incident/task attachment\"\"\"\n\n log = logging.getLogger(__name__)\n attachment = {\"id\": None, \"name\": None, \"content_type\": None, \"contents\": None}\n err_msg, get_url = None, None\n\n # Get attachment metadata url\n if task_id:\n get_url = \"/tasks/{0}/attachments/{1}\".format(task_id, attachment_id)\n elif incident_id:\n get_url = \"/incidents/{0}/attachments/{1}\".format(incident_id, attachment_id)\n else:\n raise ValueError(\"Failed to get_attachment. task_id or incident_id must be specified with attachment_id\")\n\n # Get attachment metadata\n try:\n log.debug(\"GET Attachment metadata: ID %s URL: %s\", attachment_id, get_url)\n meta_data = res_client.get(get_url)\n log.debug(\"Attachment metadata got successfully\")\n except Exception as err:\n err_msg = \"Error trying to get Attachment {0}.\".format(attachment_id)\n\n if err.message and \"not found\" in err.message.lower():\n err_msg = \"{0} Could not find Attachment with ID {1}. incident_id: {2} task_id: {3}\".format(err_msg, attachment_id, incident_id, task_id)\n elif isinstance(err, SimpleHTTPException):\n err_msg = \"{0}\\nServer Error.\\nStatus Code: {1}\\nURL: {2}\\n{3}\".format(err_msg, err.response.status_code, err.response.url, err.message)\n else:\n err_msg = \"{0} {1}\".format(err_msg, err)\n\n raise ValueError(err_msg)\n\n attachment[\"content_type\"] = meta_data[\"content_type\"]\n attachment[\"id\"] = attachment_id\n attachment[\"name\"] = meta_data[\"name\"]\n\n # Get attachment contencts url\n get_contents_url = \"{0}/contents\".format(get_url)\n\n # Get attachment contents\n try:\n log.debug(\"GET Attachment contents: ID %s URL: %s\", attachment_id, get_url)\n attachment[\"contents\"] = cls._encodeBase64(res_client.get_content(get_contents_url))\n log.debug(\"Attachment contents got successfully\")\n except Exception as err:\n err_msg = \"Error trying to get Attachment contents for ID: {0}.\".format(attachment_id)\n\n if err.message and \"not found\" in err.message.lower():\n err_msg = \"{0} Could not find Attachment with ID {1}. incident_id: {2} task_id: {3}\".format(err_msg, attachment_id, incident_id, task_id)\n elif isinstance(err, SimpleHTTPException):\n err_msg = \"{0}\\nServer Error.\\nStatus Code: {1}\\nURL: {2}\\n{3}\".format(err_msg, err.response.status_code, err.response.url, err.message)\n else:\n err_msg = \"{0} {1}\".format(err_msg, err)\n\n return attachment\n\n @classmethod\n def generate_sn_request_data(cls, res_client, res_datatable, incident_id, sn_table_name, res_link, task_id=None, init_note=None, sn_optional_fields=None):\n \"\"\"Function that generates the data that is sent in the request to the /create endpoint in ServiceNow\"\"\"\n\n log = logging.getLogger(__name__)\n err_msg, request_data = None, None\n\n log.debug(\"Generating request for ServiceNow. incident_id: %s task_id: %s sn_table_name: %s res_link: %s init_note: %s sn_optional_fields: %s res_datatable: %s\",\n incident_id, task_id, sn_table_name, res_link, init_note, sn_optional_fields, res_datatable)\n\n # Generate the res_id\n res_id = cls.generate_res_id(incident_id, task_id)\n\n log.debug(\"res_id: {0}\".format(res_id))\n\n # Check if already exists in data table\n sn_ref_id = res_datatable.get_sn_ref_id(res_id)\n\n if sn_ref_id:\n err_msg = \"Failed to create a ServiceNow Record. This {0} already exists in ServiceNow. {0} ID: {1}. sn_ref_id: {2}\"\n\n if task_id:\n err_msg = err_msg.format(\"Task\", task_id, sn_ref_id)\n\n else:\n err_msg = err_msg.format(\"Incident\", incident_id, sn_ref_id)\n\n return {\n \"success\": False,\n \"data\": err_msg\n }\n\n if task_id is not None:\n # Get the task\n task = cls.get_task(res_client, task_id, incident_id)\n\n # Add task to the request_data\n request_data = task.as_dict()\n\n else:\n incident = cls.get_incident(res_client, incident_id)\n\n # Add incident to the request_data\n request_data = incident.as_dict()\n\n # Add sn_table_name, resilient_id, link and init_note to the request_data\n request_data[\"sn_table_name\"] = sn_table_name\n request_data[\"id\"] = res_id\n request_data[\"link\"] = res_link\n request_data[\"sn_init_work_note\"] = init_note\n\n # Extend request_data if there is data in 'sn_optional_fields'\n if sn_optional_fields is not None and len(sn_optional_fields) > 0:\n fields = []\n for field in sn_optional_fields:\n fields.append({\"name\": field, \"value\": sn_optional_fields[field]})\n request_data[\"sn_optional_fields\"] = fields\n else:\n request_data[\"sn_optional_fields\"] = None\n\n log.debug(\"sn_request_data %s\", request_data)\n\n return {\n \"success\": True,\n \"data\": request_data\n }\n\n def get_table_name(self, sn_ref_id):\n\n if self.SN_TABLE_NAME == SECOPS_TABLE_NAME and sn_ref_id.startswith(SECOPS_PLAYBOOK_TASK_PREFIX):\n return SECOPS_PLAYBOOK_TASK_TABLE_NAME\n \n return self.SN_TABLE_NAME\n\n def sn_api_request(self, rc, method, endpoint, params=None, data=None, headers=None):\n \"\"\"Method to handle resquests to our custom APIs in ServiceNow\"\"\"\n log = logging.getLogger(__name__)\n\n res, return_value = None, None\n\n SUPPORTED_METHODS = [\"GET\", \"POST\", \"PATCH\"]\n\n if method not in SUPPORTED_METHODS:\n raise ValueError(\"{0} is not a supported ServiceNow API Request. Supported methods are: {1}\".format(method, SUPPORTED_METHODS))\n\n headers = self.headers if headers is None else headers\n url = \"{0}{1}\".format(self.SN_API_URL, endpoint)\n\n res = rc.execute(\n method=method,\n url=url,\n auth=self.SN_AUTH,\n headers=headers,\n params=params,\n data=data\n )\n\n log.info(\"SN REQUEST:\\nmethod: %s\\nurl: %s\\nbody: %s\", res.request.method, res.request.url, res.request.body)\n\n if method is \"GET\":\n log.info(\"SN RESPONSE: %s\", res)\n return_value = res\n\n elif method in (\"POST\", \"PATCH\"):\n log.info(\"SN RESPONSE: %s\", res.json())\n return_value = res.json()[\"result\"]\n\n return return_value\n","sub_path":"fn_service_now/fn_service_now/util/resilient_helper.py","file_name":"resilient_helper.py","file_ext":"py","file_size_in_byte":21285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"544905382","text":"from cs1lib import *\nfrom System_extra_credit import *\nfrom Body_extra_credit import *\nfrom speed_changer import *\nfrom time import clock\n\nWINDOW_SIZE = 800\n\nTIME_SCALE = 5000000\nPIXELS_PER_METER = 1.5 / 1e9 # distance scale for the simulation\n\n# Conversion rate from AUs\nMETERS_PER_AU = 1.49598e11\n# Conversion rate from EMs\nKG_PER_EM = 5.972e24\n\n# Radius of sun\nRADIUS_OF_SUN = 6.955e8\n\nFRAME_RATE = 60\nTIMESTEP = 1.0 / FRAME_RATE\n\ndef is_within_rect(pos_x, pos_y, rect_x, rect_y, rect_x_2, rect_y_2):\n return (pos_x >= rect_x and pos_x <= rect_x_2) and (pos_y >= rect_y and pos_y <= rect_y_2)\n\ndef main():\n \n # Make the background color black\n set_clear_color(0, 0, 0)\n enable_smoothing()\n \n # Initialize planets\n sun = Body(1.9891e30, 0, 0, 0, 0, 40, 1.0, 1.0, 0.0, \"Sun\", \"sun.png\")\n earth = Body(1 * KG_PER_EM, 1 * METERS_PER_AU + RADIUS_OF_SUN, 0, 0, 29790, 5, 0.0, 1.0, 0.0, \"Earth\", \"earth.png\")\n mercury = Body(0.06 * KG_PER_EM, 0.3871 * METERS_PER_AU + RADIUS_OF_SUN, 0, 0, 47890, 5.0 * 2493 / 6378, 0.5, 0.5, 0.5, \"Mercury\", \"mercury.png\")\n venus = Body(0.82 * KG_PER_EM, 0.7233 * METERS_PER_AU + RADIUS_OF_SUN, 0, 0, 35040, 5.0 / 6378 * 6052, 1.0, 1.0 / 200.0, 0.0, \"Venus\", \"venus.png\")\n mars = Body(0.11 * KG_PER_EM, 1.524 * METERS_PER_AU + RADIUS_OF_SUN, 0, 0, 24140, 5.0 / 6378 * 3397, 0.6, 0.6, 0.0, \"Mars\", \"mars.png\")\n \n # Create variable to remember time\n current_time = clock()\n \n # Create array of bodies\n bodies = [sun, earth, mercury, venus, mars]\n \n # Create system variable\n solar_system = System(bodies)\n \n # Speed changer object\n speed = speed_changer(WINDOW_SIZE - 200, WINDOW_SIZE - 20, WINDOW_SIZE - 20, TIME_SCALE * 10.0, TIME_SCALE / 100.0, TIME_SCALE)\n current_time_scale = TIME_SCALE\n \n while not (window_closed()):\n # Clear and redraw\n clear()\n solar_system.draw(WINDOW_SIZE/2, WINDOW_SIZE/2, PIXELS_PER_METER)\n \n # Update time scale\n current_time_scale = speed.get_speed()\n speed.draw()\n \n if mouse_down() and is_within_rect(mouse_x(), mouse_y(), WINDOW_SIZE - 200, WINDOW_SIZE - 25, WINDOW_SIZE - 20, WINDOW_SIZE - 15):\n speed.got_click(mouse_x())\n \n # Update the accelerations\n solar_system.update(TIMESTEP * current_time_scale)\n \n request_redraw()\n if clock() - current_time < TIMESTEP: # Make sure that the amount of time passed from the calculations is not larger than the TIMESTEP\n # Only sleep for the rest of the time that was used by calculations\n sleep(TIMESTEP - (clock() - current_time))\n \n # Update the time\n current_time = clock()\n \n\nstart_graphics(main, \"Solar System\", WINDOW_SIZE, WINDOW_SIZE)","sub_path":"Lab 2/extra_credit.py","file_name":"extra_credit.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"240202137","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 24 11:32:43 2021\n\n@author: russ\n\"\"\"\nimport pprint\nimport clip_utils\n\n\n\nimport sys\nsys.path.append( r\"D:\\Russ\\0000\\python00\\python3\\_examples\" )\nimport ex_helpers\n\n# ----------------------------------------\ndef ex_template():\n ex_name = \"ex_template\"\n print( f\"\"\"{ex_helpers.begin_example( ex_name )} template showing use of begin_example, end-example ===============\n \"\"\" )\n\n print( \"thats all folks\" )\n\n ex_helpers.end_example( ex_name )\n\n#ex_template()\n\n# ------------------------------------------\ndef test_allign_eq_signs( ):\n \"\"\"\n what it says, read\n\n\n \"\"\"\n\n a_test_string = \\\n\"\"\" s = 1 + 7\n ssss = 1 + 7\n aaaaa = \"a long walk in the woods\"\n bbb = \"a long walk in the woods\" # with comment\n another = 333 # with comment\n two equal = and =\n equal sign hidden # = sign after comment\n different = 22\n no equal sign here\n or here either\n\"\"\"\n print( a_test_string )\n ret = clip_utils.allign_eq_signs( a_test_string )\n\n print( \"================= allign returns =>\" )\n pprint.pprint( ret )\n\n a_string = clip_utils.list_to_string_lines( ret )\n print( a_string )\n\ntest_allign_eq_signs()\n\n\n\n# ------------------------------------------\ndef test_list_to_string_lines( ):\n ex_name = \"test_list_to_string_lines\"\n print( f\"\"\"{ex_helpers.begin_example( ex_name )} ===============\n \"\"\" )\n a_list = [ \"aaa\", \"vvv\", \"ccc\", \"d\", \"what the heck\", \"was blank\", ]\n a_string = clip_utils.list_to_string_lines( a_list )\n print( a_string )\n\n ex_helpers.end_example( ex_name )\n\n#test_list_to_string_lines()\n\n\n# ----------------------------------------\ndef test_clean_string_to_list( ):\n \"\"\"\n in_text,\n delete_tailing_spaces = True,\n delete_comments = False,\n delete_blank_lines = False,\n \"\"\"\n\n in_text = \"\"\"\n for ix, i_line in enumerate(lines1):\n\n # alternate odd even\n if odd:\n part_b = i_line # trail comment\n odd = False # trail comment # trail comment\n else:\n # if first line does not start with http or https\n # we will return False\n if ix == 1: # 2 in a way fix this?\n # add www, use in to find a beinning\n # https://snippets.readthedocs.org/en/latest/\n # 012345\n # !! need to check for both http and htts\n # !! find and use is_url function\n prefix = i_line[0:4]\n if prefix != \"http\":\n prefix = i_line[0:5]\n if prefix != \"https\":\n self.logger.info(\"prefix \" + prefix)\n return (False, \"not http or https\", \"\")\n\n\n\n\n \"\"\"\n\n clean_string, cnt_deleted = clean_string_to_list(in_text)\n #pprint.pprint( f\">>>>{clean_string_to_list(in_text)}<<<<\")\n\n pprint.pprint( clean_string )\n\n clean_string, cnt_deleted = clean_string_to_list(in_text, delete_comments = True, )\n pprint.pprint( clean_string )\n\n clean_string, cnt_deleted = clean_string_to_list(in_text,\n delete_comments = True,\n delete_blank_lines = True,)\n print( f\"cnt_deleted cnt_deleted\")\n pprint.pprint( clean_string )\n\n\n# ----------------------------------------\n#test_clean_string_to_list( )\n\n\n\n# # ------------------- fix !!\n# def test_trans_search_replace(): now name_to_literal\n# \"\"\"\n# new april 2021\n\n\n# \"\"\"\n\n# import parameters\n# parms = parameters.Parameters()\n# test_object = CmdProcessor( )\n\n# input_list = [\"abc\", \"what\", \"tab\", \"newline\", \"space\"]\n# for a_string in input_list:\n\n# ret = test_object.trans_search_replace( a_string )\n# print( f\"input >{a_string}< ->{ret}<\" )\n\n\n\n","sub_path":"test/test_string_utils.py","file_name":"test_string_utils.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"352552662","text":"# Copyright 2018 Google LLC\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# [START gae_python37_app]\r\nfrom flask import Flask\r\nimport imaplib\r\n\r\n# If `entrypoint` is not defined in app.yaml, App Engine will look for an app\r\n# called `app` in `main.py`.\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/')\r\ndef get_mail():\r\n mail = imaplib.IMAP4_SSL('imap.gmail.com')\r\n mail.login('sam.brazen2@gmail.com', 'vrajeala1')\r\n mail.list()\r\n # Out: list of \"folders\" aka labels in gmail.\r\n mail.select(\"inbox\") # connect to inbox.\r\n\r\n result, data = mail.search(None, '(FROM \"Pinterest\" SUBJECT \"Please confirm your email\")')\r\n\r\n ids = data[0] # data is a list.\r\n id_list = ids.split() # ids is a space separated string\r\n latest_email_id = id_list[-1] # get the latest\r\n\r\n result, data = mail.fetch(latest_email_id, \"(RFC822)\") # fetch the email body (RFC822) for the given ID\r\n\r\n raw_email = data[0][1].decode('utf-8') # here's the body, which is raw text of the whole email\r\n # including headers and alternate payloads\r\n return raw_email\r\n\r\n\r\nif __name__ == '__main__':\r\n # This is used when running locally only. When deploying to Google App\r\n # Engine, a webserver process such as Gunicorn will serve the app. This\r\n # can be configured by adding an `entrypoint` to app.yaml.\r\n app.run(host='127.0.0.1', port=8282, debug=True)\r\n# [END gae_python37_app]\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"91824625","text":"# https://mypy.readthedocs.io/en/stable/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime\r\nfrom __future__ import annotations\r\n\r\nimport datetime\r\nimport os\r\nimport tempfile\r\nimport hashlib\r\nimport base64\r\nimport io\r\nimport urllib.parse\r\nimport time\r\nimport json\r\nimport functools\r\nimport binascii\r\nimport stat as stat_module\r\nimport glob as local_glob\r\nimport re\r\nimport shutil\r\nimport collections\r\nimport itertools\r\nimport random\r\nimport math\r\nimport ssl\r\nimport socket\r\nimport threading\r\nimport platform\r\nimport concurrent.futures\r\nimport multiprocessing as mp\r\nfrom typing import (\r\n overload,\r\n Optional,\r\n Tuple,\r\n Callable,\r\n Sequence,\r\n Iterator,\r\n Mapping,\r\n Any,\r\n Dict,\r\n TextIO,\r\n BinaryIO,\r\n cast,\r\n NamedTuple,\r\n List,\r\n Union,\r\n TYPE_CHECKING,\r\n)\r\n\r\nif TYPE_CHECKING:\r\n # only supported in python 3.8+\r\n # this works because we postponed evaluation of type annotations with PEP 563,\r\n # and because we don't use Literal as a base class or for casting\r\n from typing import Literal\r\n\r\n\r\nimport urllib3\r\nimport xmltodict\r\nimport filelock\r\n\r\nfrom blobfile import google, azure\r\nfrom blobfile.common import (\r\n Request,\r\n FileBody,\r\n Error,\r\n RequestFailure,\r\n RestartableStreamingWriteFailure,\r\n ConcurrentWriteFailure,\r\n)\r\n\r\n# feature flags\r\nUSE_STREAMING_READ_REQUEST = True\r\n\r\nBLOBFILE_BACKENDS_ENV_VAR = \"BLOBFILE_BACKENDS\"\r\nBACKOFF_INITIAL = 0.1\r\nBACKOFF_MAX = 60.0\r\nBACKOFF_JITTER_FRACTION = 0.5\r\nEARLY_EXPIRATION_SECONDS = 5 * 60\r\nDEFAULT_CONNECTION_POOL_MAX_SIZE = 32\r\nDEFAULT_MAX_CONNECTION_POOL_COUNT = 10\r\nDEFAULT_AZURE_WRITE_CHUNK_SIZE = 8 * 2 ** 20\r\nDEFAULT_GOOGLE_WRITE_CHUNK_SIZE = 8 * 2 ** 20\r\nDEFAULT_RETRY_LOG_THRESHOLD = 0\r\nCONNECT_TIMEOUT = 10\r\nREAD_TIMEOUT = 30\r\nCHUNK_SIZE = 2 ** 20\r\n# it looks like azure signed urls cannot exceed the lifetime of the token used\r\n# to create them, so don't keep the key around too long\r\nAZURE_SAS_TOKEN_EXPIRATION_SECONDS = 60 * 60\r\n# these seem to be expired manually, but we don't currently detect that\r\nAZURE_SHARED_KEY_EXPIRATION_SECONDS = 24 * 60 * 60\r\n# max 100MB https://docs.microsoft.com/en-us/rest/api/storageservices/put-block#remarks\r\n# there is a preview version of the API that allows this to be 4000MiB\r\nAZURE_MAX_BLOCK_SIZE = 100_000_000\r\nAZURE_BLOCK_COUNT_LIMIT = 50_000\r\nPARALLEL_COPY_MINIMUM_PART_SIZE = 32 * 2 ** 20\r\n\r\nINVALID_HOSTNAME_STATUS = 600 # fake status for invalid hostname\r\n\r\n# https://cloud.google.com/storage/docs/naming\r\n# https://www.w3.org/TR/xml/#charsets\r\nINVALID_CHARS = (\r\n set().union(range(0x0, 0x9)).union(range(0xB, 0xE)).union(range(0xE, 0x20))\r\n)\r\n\r\nHOSTNAME_EXISTS = 0\r\nHOSTNAME_DOES_NOT_EXIST = 1\r\nHOSTNAME_STATUS_UNKNOWN = 2\r\n\r\nAZURE_RESPONSE_HEADER_TO_REQUEST_HEADER = {\r\n \"Cache-Control\": \"x-ms-blob-cache-control\",\r\n \"Content-Type\": \"x-ms-blob-content-type\",\r\n \"Content-MD5\": \"x-ms-blob-content-md5\",\r\n \"Content-Encoding\": \"x-ms-blob-content-encoding\",\r\n \"Content-Language\": \"x-ms-blob-content-language\",\r\n \"Content-Disposition\": \"x-ms-blob-content-disposition\",\r\n}\r\n\r\nESCAPED_COLON = \"___COLON___\"\r\n\r\n\r\nclass Stat(NamedTuple):\r\n size: int\r\n mtime: float\r\n ctime: float\r\n md5: Optional[str]\r\n version: Optional[str]\r\n\r\n\r\nclass DirEntry(NamedTuple):\r\n path: str\r\n name: str\r\n is_dir: bool\r\n is_file: bool\r\n stat: Optional[Stat]\r\n\r\n\r\n_http = None\r\n_http_pid = None\r\n_http_lock = threading.Lock()\r\n_connection_pool_max_size = DEFAULT_CONNECTION_POOL_MAX_SIZE\r\n_max_connection_pool_count = DEFAULT_MAX_CONNECTION_POOL_COUNT\r\n# https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs#about-block-blobs\r\n# the chunk size determines the maximum size of an individual blob\r\n_azure_write_chunk_size = DEFAULT_AZURE_WRITE_CHUNK_SIZE\r\n_google_write_chunk_size = DEFAULT_GOOGLE_WRITE_CHUNK_SIZE\r\n_retry_log_threshold = DEFAULT_RETRY_LOG_THRESHOLD\r\n_retry_limit = None\r\n\r\n\r\ndef _default_log_fn(msg: str) -> None:\r\n print(f\"blobfile: {msg}\")\r\n\r\n\r\n_log_callback = _default_log_fn\r\n\r\n\r\ndef _get_http_pool() -> urllib3.PoolManager:\r\n # ssl is not fork safe https://docs.python.org/2/library/ssl.html#multi-processing\r\n # urllib3 may not be fork safe https://github.com/urllib3/urllib3/issues/1179\r\n # both are supposedly threadsafe though, so we shouldn't need a thread-local pool\r\n global _http, _http_pid\r\n with _http_lock:\r\n if _http is None or _http_pid != os.getpid():\r\n # tensorflow imports requests which calls\r\n # import urllib3.contrib.pyopenssl\r\n # urllib3.contrib.pyopenssl.inject_into_urllib3()\r\n # which will monkey patch urllib3 to use pyopenssl and sometimes break things\r\n # with errors such as \"certificate verify failed\"\r\n # https://github.com/pyca/pyopenssl/issues/823\r\n # https://github.com/psf/requests/issues/5238\r\n # in order to fix this here are a couple of options:\r\n\r\n # method 1\r\n # from urllib3.util import ssl_\r\n\r\n # if ssl_.IS_PYOPENSSL:\r\n # import urllib3.contrib.pyopenssl\r\n\r\n # urllib3.contrib.pyopenssl.extract_from_urllib3()\r\n # http = urllib3.PoolManager()\r\n\r\n # method 2\r\n # build a context based on https://github.com/urllib3/urllib3/blob/edc3ddb3d1cbc5871df4a17a53ca53be7b37facc/src/urllib3/util/ssl_.py#L220\r\n # this exists because there's no obvious way to cause that function to use the ssl.SSLContext except for un-monkey-patching urllib3\r\n context = ssl.SSLContext(ssl.PROTOCOL_TLS)\r\n context.verify_mode = ssl.CERT_REQUIRED\r\n context.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_COMPRESSION\r\n context.load_default_certs()\r\n _http_pid = os.getpid()\r\n _http = urllib3.PoolManager(\r\n ssl_context=context,\r\n maxsize=_connection_pool_max_size,\r\n num_pools=_max_connection_pool_count,\r\n )\r\n # for debugging with mitmproxy\r\n # _http = urllib3.ProxyManager('http://localhost:8080/', ssl_context=context)\r\n\r\n return _http\r\n\r\n\r\n# rather than a global configure object, there should probably be a context\r\n# object that tracks all the settings\r\n#\r\n# class Context:\r\n# # class with all blobfile functions as methods\r\n# # and existing global variables as properties\r\n# def create_context(**config_options) -> Context:\r\n# # create a context\r\n# _global_context = create_context()\r\n# def configure(**config_options) -> None:\r\n# global _global_context\r\n# _global_context = create_context(**config_options)\r\n# def copy():\r\n# # proxy functions for all methods on Context\r\n# return _global_context.copy()\r\n\r\n\r\ndef configure(\r\n *,\r\n log_callback: Callable[[str], None] = _default_log_fn,\r\n connection_pool_max_size: int = DEFAULT_CONNECTION_POOL_MAX_SIZE,\r\n max_connection_pool_count: int = DEFAULT_MAX_CONNECTION_POOL_COUNT,\r\n azure_write_chunk_size: int = DEFAULT_AZURE_WRITE_CHUNK_SIZE,\r\n google_write_chunk_size: int = DEFAULT_GOOGLE_WRITE_CHUNK_SIZE,\r\n retry_log_threshold: int = DEFAULT_RETRY_LOG_THRESHOLD,\r\n retry_limit: Optional[int] = None,\r\n) -> None:\r\n \"\"\"\r\n log_callback: a log callback function `log(msg: string)` to use instead of printing to stdout\r\n connection_pool_max_size: the max size for each per-host connection pool\r\n max_connection_pool_count: the maximum count of per-host connection pools\r\n azure_write_chunk_size: the size of blocks to write to Azure Storage blobs, can be set to a maximum of 100MB\r\n retry_log_threshold: set a retry count threshold above which to log failures to the log callback function\r\n \"\"\"\r\n global _log_callback\r\n _log_callback = log_callback\r\n global _http, _http_pid, _connection_pool_max_size, _max_connection_pool_count, _azure_write_chunk_size, _retry_log_threshold, _retry_limit, _google_write_chunk_size\r\n with _http_lock:\r\n _http = None\r\n _http_pid = None\r\n _connection_pool_max_size = connection_pool_max_size\r\n _max_connection_pool_count = max_connection_pool_count\r\n _azure_write_chunk_size = azure_write_chunk_size\r\n _google_write_chunk_size = google_write_chunk_size\r\n _retry_log_threshold = retry_log_threshold\r\n _retry_limit = retry_limit\r\n\r\n\r\nclass TokenManager:\r\n \"\"\"\r\n Automatically refresh tokens when they expire\r\n \"\"\"\r\n\r\n def __init__(self, get_token_fn: Callable[[Any], Tuple[Any, float]]) -> None:\r\n self._get_token_fn = get_token_fn\r\n self._tokens = {}\r\n self._expirations = {}\r\n self._lock = threading.Lock()\r\n\r\n def get_token(self, key: Any) -> Any:\r\n with self._lock:\r\n now = time.time()\r\n expiration = self._expirations.get(key)\r\n if expiration is None or (now + EARLY_EXPIRATION_SECONDS) > expiration:\r\n self._tokens[key], self._expirations[key] = self._get_token_fn(key)\r\n assert self._expirations[key] is not None\r\n\r\n assert key in self._tokens\r\n return self._tokens[key]\r\n\r\n\r\ndef _is_gce_instance() -> bool:\r\n try:\r\n socket.getaddrinfo(\"metadata.google.internal\", 80)\r\n except socket.gaierror:\r\n return False\r\n return True\r\n\r\n\r\ndef _google_get_access_token(key: Any) -> Tuple[Any, float]:\r\n now = time.time()\r\n\r\n # https://github.com/googleapis/google-auth-library-java/blob/master/README.md#application-default-credentials\r\n _, err = google.load_credentials()\r\n if err is None:\r\n\r\n def build_req() -> Request:\r\n req = google.create_access_token_request(\r\n scopes=[\"https://www.googleapis.com/auth/devstorage.full_control\"]\r\n )\r\n req.success_codes = (200, 400)\r\n return req\r\n\r\n resp = _execute_request(build_req)\r\n result = json.loads(resp.data)\r\n if resp.status == 400:\r\n error = result[\"error\"]\r\n description = result.get(\"error_description\", \"\")\r\n msg = f\"Error with google credentials: [{error}] {description}\"\r\n if error == \"invalid_grant\":\r\n if description.startswith(\"Invalid JWT:\"):\r\n msg += \"\\nPlease verify that your system clock is correct.\"\r\n elif description == \"Bad Request\":\r\n msg += \"\\nYour credentials may be expired, please run the following commands: `gcloud auth application-default revoke` (this may fail but ignore the error) then `gcloud auth application-default login`\"\r\n raise Error(msg)\r\n assert resp.status == 200\r\n return result[\"access_token\"], now + float(result[\"expires_in\"])\r\n elif (\r\n os.environ.get(\"NO_GCE_CHECK\", \"false\").lower() != \"true\" and _is_gce_instance()\r\n ):\r\n # see if the metadata server has a token for us\r\n def build_req() -> Request:\r\n return Request(\r\n method=\"GET\",\r\n url=\"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token\",\r\n headers={\"Metadata-Flavor\": \"Google\"},\r\n )\r\n\r\n resp = _execute_request(build_req)\r\n result = json.loads(resp.data)\r\n return result[\"access_token\"], now + float(result[\"expires_in\"])\r\n else:\r\n raise Error(err)\r\n\r\n\r\ndef _azure_can_access_container(\r\n account: str, container: str, auth: Tuple[str, str]\r\n) -> bool:\r\n # https://myaccount.blob.core.windows.net/mycontainer?restype=container&comp=list\r\n def build_req() -> Request:\r\n req = Request(\r\n method=\"GET\",\r\n url=azure.build_url(account, \"/{container}\", container=container),\r\n params={\"restype\": \"container\", \"comp\": \"list\", \"maxresults\": \"1\"},\r\n success_codes=(200, 403, 404, INVALID_HOSTNAME_STATUS),\r\n )\r\n return azure.make_api_request(req, auth=auth)\r\n\r\n resp = _execute_request(build_req)\r\n # technically INVALID_HOSTNAME_STATUS means we can't access the account because it\r\n # doesn't exist, but to be consistent with how we treat this error elsewhere we\r\n # ignore it here\r\n if resp.status == INVALID_HOSTNAME_STATUS:\r\n return True\r\n # anonymous requests will for some reason get a 404 when they should get a 403\r\n # so treat a 404 from anon requests as a 403\r\n if resp.status == 404 and auth[0] == azure.ANONYMOUS:\r\n return False\r\n # if the container list succeeds or the container doesn't exist, return success\r\n return resp.status in (200, 404)\r\n\r\n\r\ndef _azure_get_storage_account_key(\r\n account: str, container: str, creds: Mapping[str, Any]\r\n) -> Optional[Tuple[Any, float]]:\r\n # get an access token for the management service\r\n def build_req() -> Request:\r\n return azure.create_access_token_request(\r\n creds=creds, scope=\"https://management.azure.com/\"\r\n )\r\n\r\n resp = _execute_request(build_req)\r\n result = json.loads(resp.data)\r\n auth = (azure.OAUTH_TOKEN, result[\"access_token\"])\r\n\r\n if \"subscription_ids\" in creds:\r\n subscription_ids = creds[\"subscription_ids\"]\r\n else:\r\n # get a list of subscriptions so we can query each one for storage accounts\r\n def build_req() -> Request:\r\n req = Request(\r\n method=\"GET\",\r\n url=\"https://management.azure.com/subscriptions\",\r\n params={\"api-version\": \"2020-01-01\"},\r\n )\r\n return azure.make_api_request(req, auth=auth)\r\n\r\n resp = _execute_request(build_req)\r\n result = json.loads(resp.data)\r\n subscription_ids = [item[\"subscriptionId\"] for item in result[\"value\"]]\r\n\r\n for subscription_id in subscription_ids:\r\n # get a list of storage accounts\r\n def build_req() -> Request:\r\n req = Request(\r\n method=\"GET\",\r\n url=f\"https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Storage/storageAccounts\",\r\n params={\"api-version\": \"2019-04-01\"},\r\n success_codes=(200, 401, 403),\r\n )\r\n return azure.make_api_request(req, auth=auth)\r\n\r\n resp = _execute_request(build_req)\r\n if resp.status in (401, 403):\r\n # we aren't allowed to query this for this subscription, skip it\r\n # it's unclear if this is still necessary since we query for subscriptions first\r\n continue\r\n\r\n out = json.loads(resp.data)\r\n # check if we found the storage account we are looking for\r\n for obj in out[\"value\"]:\r\n if obj[\"name\"] == account:\r\n storage_account_id = obj[\"id\"]\r\n break\r\n else:\r\n continue\r\n\r\n def build_req() -> Request:\r\n req = Request(\r\n method=\"POST\",\r\n url=f\"https://management.azure.com{storage_account_id}/listKeys\",\r\n params={\"api-version\": \"2019-04-01\"},\r\n )\r\n return azure.make_api_request(req, auth=auth)\r\n\r\n resp = _execute_request(build_req)\r\n result = json.loads(resp.data)\r\n for key in result[\"keys\"]:\r\n if key[\"permissions\"] == \"FULL\":\r\n storage_key_auth = (azure.SHARED_KEY, key[\"value\"])\r\n if _azure_can_access_container(account, container, storage_key_auth):\r\n return storage_key_auth\r\n else:\r\n raise Error(\r\n f\"Found storage account key, but it was unable to access storage account: '{account}' and container: '{container}'\"\r\n )\r\n raise Error(\r\n f\"Storage account was found, but storage account keys were missing: '{account}'\"\r\n )\r\n return None\r\n\r\n\r\ndef _azure_get_access_token(key: Any) -> Tuple[Any, float]:\r\n account, container = key\r\n now = time.time()\r\n creds = azure.load_credentials()\r\n if \"storageAccountKey\" in creds:\r\n if \"account\" in creds:\r\n if creds[\"account\"] != account:\r\n raise Error(\r\n f\"Found credentials for account '{creds['account']}' but needed credentials for account '{account}'\"\r\n )\r\n auth = (azure.SHARED_KEY, creds[\"storageAccountKey\"])\r\n if _azure_can_access_container(account, container, auth):\r\n return (auth, now + AZURE_SHARED_KEY_EXPIRATION_SECONDS)\r\n elif \"refreshToken\" in creds:\r\n # we have a refresh token, convert it into an access token for this account\r\n def build_req() -> Request:\r\n return azure.create_access_token_request(\r\n creds=creds,\r\n scope=f\"https://{account}.blob.core.windows.net/\",\r\n success_codes=(200, 400),\r\n )\r\n\r\n resp = _execute_request(build_req)\r\n result = json.loads(resp.data)\r\n if resp.status == 400:\r\n if (\r\n (\r\n result[\"error\"] == \"invalid_grant\"\r\n and \"AADSTS700082\" in result[\"error_description\"]\r\n )\r\n or (\r\n result[\"error\"] == \"interaction_required\"\r\n and \"AADSTS50078\" in result[\"error_description\"]\r\n )\r\n or (\r\n result[\"error\"] == \"interaction_required\"\r\n and \"AADSTS50076\" in result[\"error_description\"]\r\n )\r\n ):\r\n raise Error(\r\n \"Your refresh token is no longer valid, please run `az login` to get a new one\"\r\n )\r\n else:\r\n raise Error(\r\n f\"Encountered an error when requesting an access token: `{result['error']}: {result['error_description']}`. You can attempt to fix this by re-running `az login`.\"\r\n )\r\n\r\n auth = (azure.OAUTH_TOKEN, result[\"access_token\"])\r\n\r\n # for some azure accounts this access token does not work, check if it works\r\n if _azure_can_access_container(account, container, auth):\r\n return (auth, now + float(result[\"expires_in\"]))\r\n\r\n # fall back to getting the storage keys\r\n storage_account_key_auth = _azure_get_storage_account_key(\r\n account=account, container=container, creds=creds\r\n )\r\n if storage_account_key_auth is not None:\r\n return (storage_account_key_auth, now + AZURE_SHARED_KEY_EXPIRATION_SECONDS)\r\n elif \"appId\" in creds:\r\n # we have a service principal, get an oauth token\r\n def build_req() -> Request:\r\n return azure.create_access_token_request(\r\n creds=creds, scope=\"https://storage.azure.com/\"\r\n )\r\n\r\n resp = _execute_request(build_req)\r\n result = json.loads(resp.data)\r\n auth = (azure.OAUTH_TOKEN, result[\"access_token\"])\r\n if _azure_can_access_container(account, container, auth):\r\n return (auth, now + float(result[\"expires_in\"]))\r\n\r\n # fall back to getting the storage keys\r\n storage_account_key_auth = _azure_get_storage_account_key(\r\n account=account, container=container, creds=creds\r\n )\r\n if storage_account_key_auth is not None:\r\n return (storage_account_key_auth, now + AZURE_SHARED_KEY_EXPIRATION_SECONDS)\r\n\r\n # oddly, it seems that if you request a public container with a valid azure account, you cannot list the bucket\r\n # but if you list it with no account, that works fine\r\n anonymous_auth = (azure.ANONYMOUS, \"\")\r\n if _azure_can_access_container(account, container, anonymous_auth):\r\n return (anonymous_auth, float(\"inf\"))\r\n\r\n msg = f\"Could not find any credentials that grant access to storage account: '{account}' and container: '{container}'\"\r\n if len(creds) == 0:\r\n msg += \"\"\"\r\n\r\nNo Azure credentials were found. If the container is not marked as public, please do one of the following:\r\n\r\n* Log in with 'az login', blobfile will use your default credentials to lookup your storage account key\r\n* Set the environment variable 'AZURE_STORAGE_KEY' to your storage account key which you can find by following this guide: https://docs.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage\r\n* Create an account with 'az ad sp create-for-rbac --name ' and set the 'AZURE_APPLICATION_CREDENTIALS' environment variable to the path of the output from that command or individually set the 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', and 'AZURE_TENANT_ID' environment variables\"\"\"\r\n raise Error(msg)\r\n\r\n\r\ndef _azure_get_sas_token(key: Any) -> Tuple[Any, float]:\r\n auth = global_azure_access_token_manager.get_token(key=key)\r\n if auth[0] == azure.ANONYMOUS:\r\n # for public containers, use None as the token so that this will be cached\r\n # and we can tell when we don't have a real SAS token for a container\r\n return (None, time.time() + AZURE_SAS_TOKEN_EXPIRATION_SECONDS)\r\n\r\n account, _ = key\r\n\r\n def build_req() -> Request:\r\n req = azure.create_user_delegation_sas_request(account=account)\r\n auth = global_azure_access_token_manager.get_token(key=key)\r\n if auth[0] != azure.OAUTH_TOKEN:\r\n raise Error(\"Only oauth tokens can be used to get SAS tokens\")\r\n return azure.make_api_request(req, auth=auth)\r\n\r\n resp = _execute_request(build_req)\r\n out = xmltodict.parse(resp.data)\r\n t = time.time() + AZURE_SAS_TOKEN_EXPIRATION_SECONDS\r\n return out[\"UserDelegationKey\"], t\r\n\r\n\r\nglobal_google_access_token_manager = TokenManager(_google_get_access_token)\r\n\r\nglobal_azure_access_token_manager = TokenManager(_azure_get_access_token)\r\n\r\nglobal_azure_sas_token_manager = TokenManager(_azure_get_sas_token)\r\n\r\n\r\ndef _exponential_sleep_generator(\r\n initial: float = BACKOFF_INITIAL,\r\n maximum: float = BACKOFF_MAX,\r\n multiplier: float = 2,\r\n) -> Iterator[float]:\r\n base = initial\r\n while True:\r\n # https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/\r\n sleep = (\r\n base * (1 - BACKOFF_JITTER_FRACTION)\r\n + base * random.random() * BACKOFF_JITTER_FRACTION\r\n )\r\n yield sleep\r\n base *= multiplier\r\n if base > maximum:\r\n base = maximum\r\n\r\n\r\ndef _execute_azure_api_request(req: Request) -> urllib3.HTTPResponse:\r\n u = urllib.parse.urlparse(req.url)\r\n account = u.netloc.split(\".\")[0]\r\n path_parts = u.path.split(\"/\")\r\n if len(path_parts) < 2:\r\n raise Error(\"missing container from path\")\r\n container = u.path.split(\"/\")[1]\r\n\r\n def build_req() -> Request:\r\n return azure.make_api_request(\r\n req,\r\n auth=global_azure_access_token_manager.get_token(key=(account, container)),\r\n )\r\n\r\n return _execute_request(build_req)\r\n\r\n\r\ndef _execute_google_api_request(req: Request) -> urllib3.HTTPResponse:\r\n def build_req() -> Request:\r\n return google.make_api_request(\r\n req, access_token=global_google_access_token_manager.get_token(key=\"\")\r\n )\r\n\r\n return _execute_request(build_req)\r\n\r\n\r\ndef _execute_request(build_req: Callable[[], Request],) -> urllib3.HTTPResponse:\r\n for attempt, backoff in enumerate(_exponential_sleep_generator()):\r\n req = build_req()\r\n url = req.url\r\n if req.params is not None:\r\n if len(req.params) > 0:\r\n url += \"?\" + urllib.parse.urlencode(req.params)\r\n\r\n f = None\r\n if isinstance(req.data, FileBody):\r\n f = open(req.data.path, \"rb\")\r\n body = _WindowedFile(f, start=req.data.start, end=req.data.end)\r\n else:\r\n body = req.data\r\n\r\n err = None\r\n try:\r\n resp = _get_http_pool().request(\r\n method=req.method,\r\n url=url,\r\n headers=req.headers,\r\n body=body,\r\n timeout=urllib3.Timeout(connect=CONNECT_TIMEOUT, read=READ_TIMEOUT),\r\n preload_content=req.preload_content,\r\n retries=False,\r\n redirect=False,\r\n )\r\n if resp.status in req.success_codes:\r\n return resp\r\n else:\r\n message = f\"unexpected status {resp.status}\"\r\n if url.startswith(google.BASE_URL) and resp.status in (429, 503):\r\n message += \": if you are writing a blob this error may be due to multiple concurrent writers - make sure you are not writing to the same blob from multiple processes simultaneously\"\r\n err = RequestFailure.create_from_request_response(\r\n message=message, request=req, response=resp\r\n )\r\n if resp.status not in req.retry_codes:\r\n raise err\r\n except (\r\n urllib3.exceptions.ConnectTimeoutError,\r\n urllib3.exceptions.ReadTimeoutError,\r\n urllib3.exceptions.ProtocolError,\r\n # we should probably only catch SSLErrors matching `DECRYPTION_FAILED_OR_BAD_RECORD_MAC`\r\n # but it's not obvious what the error code will be from the logs\r\n # and because we are connecting to known servers, it's likely that non-transient\r\n # SSL errors will be rare, so for now catch all SSLErrors\r\n urllib3.exceptions.SSLError,\r\n # urllib3 wraps all errors in its own exception classes\r\n # but seems to miss ssl.SSLError\r\n # https://github.com/urllib3/urllib3/blob/9971e27e83a891ba7b832fa9e5d2f04bbcb1e65f/src/urllib3/response.py#L415\r\n # https://github.com/urllib3/urllib3/blame/9971e27e83a891ba7b832fa9e5d2f04bbcb1e65f/src/urllib3/response.py#L437\r\n # https://github.com/urllib3/urllib3/issues/1764\r\n ssl.SSLError,\r\n ) as e:\r\n if isinstance(e, urllib3.exceptions.NewConnectionError):\r\n # azure accounts have unique urls and it's hard to tell apart\r\n # an invalid hostname from a network error\r\n url = urllib.parse.urlparse(req.url)\r\n assert url.hostname is not None\r\n if (\r\n url.hostname.endswith(\".blob.core.windows.net\")\r\n and _check_hostname(url.hostname) == HOSTNAME_DOES_NOT_EXIST\r\n ):\r\n # in order to handle the azure failures in some sort-of-reasonable way\r\n # create a fake response that has a special status code we can\r\n # handle just like a 404\r\n fake_resp = urllib3.response.HTTPResponse(\r\n status=INVALID_HOSTNAME_STATUS,\r\n body=io.BytesIO(b\"\"), # avoid error when using \"with resp:\"\r\n )\r\n if fake_resp.status in req.success_codes:\r\n return fake_resp\r\n else:\r\n raise RequestFailure.create_from_request_response(\r\n \"host does not exist\", request=req, response=fake_resp\r\n )\r\n\r\n err = RequestFailure.create_from_request_response(\r\n message=f\"request failed with exception {e}\",\r\n request=req,\r\n response=urllib3.response.HTTPResponse(status=0, body=io.BytesIO(b\"\")),\r\n )\r\n finally:\r\n if f is not None:\r\n f.close()\r\n\r\n if _retry_limit is not None and attempt >= _retry_limit:\r\n raise err\r\n\r\n if attempt >= _retry_log_threshold:\r\n _log_callback(\r\n f\"error {err} when executing http request {req} attempt {attempt}, sleeping for {backoff:.1f} seconds before retrying\"\r\n )\r\n time.sleep(backoff)\r\n assert False, \"unreachable\"\r\n\r\n\r\ndef _check_hostname(hostname: str) -> int:\r\n try:\r\n socket.getaddrinfo(hostname, None, family=socket.AF_INET)\r\n except socket.gaierror as e:\r\n if e.errno == socket.EAI_NONAME:\r\n if platform.system() == \"Linux\":\r\n # on linux we appear to get EAI_NONAME if the host does not exist\r\n # and EAI_AGAIN if there is a temporary failure in resolution\r\n return HOSTNAME_DOES_NOT_EXIST\r\n else:\r\n # it's not clear on other platforms how to differentiate a temporary\r\n # name resolution failure from a permanent one, EAI_NONAME seems to be\r\n # returned for either case\r\n # if we cannot look up the hostname, but we\r\n # can look up google, then it's likely the hostname does not exist\r\n try:\r\n socket.getaddrinfo(\"www.google.com\", None, family=socket.AF_INET)\r\n except socket.gaierror:\r\n # if we can't resolve google, then the network is likely down and\r\n # we don't know if the hostname exists or not\r\n return HOSTNAME_STATUS_UNKNOWN\r\n # in this case, we could resolve google, but not the original hostname\r\n # likely the hostname does not exist (though this is definitely not a foolproof check)\r\n return HOSTNAME_DOES_NOT_EXIST\r\n else:\r\n # we got some sort of other socket error, so it's unclear if the host exists or not\r\n return HOSTNAME_STATUS_UNKNOWN\r\n # no errors encountered, the hostname exists\r\n return HOSTNAME_EXISTS\r\n\r\n\r\ndef _is_local_path(path: str) -> bool:\r\n return not _is_google_path(path) and not _is_azure_path(path)\r\n\r\n\r\ndef _is_google_path(path: str) -> bool:\r\n url = urllib.parse.urlparse(path)\r\n return url.scheme == \"gs\"\r\n\r\n\r\ndef _is_azure_path(path: str) -> bool:\r\n url = urllib.parse.urlparse(path)\r\n return (\r\n url.scheme == \"https\" and url.netloc.endswith(\".blob.core.windows.net\")\r\n ) or url.scheme == \"az\"\r\n\r\n\r\ndef _download_chunk(src: str, dst: str, start: int, size: int) -> None:\r\n # this is a little inefficient because each time we open a file we do\r\n # a query for file metadata, we could call the StreamingReadFile subclass\r\n # directly with the known size and avoid this\r\n #\r\n # in addition, we could provide a fake size (start + size) and change the call\r\n # to _request_chunk to always specify the end of the file\r\n # this should cause the connection to be put back into the pool by urllib3\r\n with BlobFile(src, \"rb\") as src_f:\r\n src_f.seek(start)\r\n # open output file such that we can write directly to the correct range\r\n with open(dst, \"rb+\") as dst_f:\r\n dst_f.seek(start)\r\n bytes_read = 0\r\n while True:\r\n n = min(CHUNK_SIZE, size - bytes_read)\r\n assert n >= 0\r\n block = src_f.read(n)\r\n if block == b\"\":\r\n if bytes_read != size:\r\n raise Error(\r\n f\"read wrong number of bytes from file `{src}`, expected {size} but read {bytes_read}\"\r\n )\r\n break\r\n dst_f.write(block)\r\n bytes_read += len(block)\r\n\r\n\r\ndef _parallel_download(\r\n executor: concurrent.futures.Executor, src: str, dst: str, return_md5: bool\r\n) -> Optional[str]:\r\n s = stat(src)\r\n\r\n # pre-allocate output file\r\n with open(dst, \"wb\") as f:\r\n f.seek(s.size - 1)\r\n f.write(b\"\\0\")\r\n\r\n max_workers = getattr(executor, \"_max_workers\", os.cpu_count() or 1)\r\n part_size = max(math.ceil(s.size / max_workers), PARALLEL_COPY_MINIMUM_PART_SIZE)\r\n start = 0\r\n futures = []\r\n while start < s.size:\r\n future = executor.submit(\r\n _download_chunk, src, dst, start, min(part_size, s.size - start)\r\n )\r\n futures.append(future)\r\n start += part_size\r\n for future in futures:\r\n future.result()\r\n\r\n if return_md5:\r\n with BlobFile(dst, \"rb\") as f:\r\n return binascii.hexlify(_block_md5(f)).decode(\"utf8\")\r\n\r\n\r\ndef _azure_upload_chunk(\r\n path: str, start: int, size: int, url: str, block_id: str\r\n) -> None:\r\n req = Request(\r\n url=url,\r\n method=\"PUT\",\r\n params=dict(comp=\"block\", blockid=block_id),\r\n # this needs to be specified since we use a file object for the data\r\n headers={\"Content-Length\": str(size)},\r\n data=FileBody(path, start=start, end=start + size),\r\n success_codes=(201,),\r\n )\r\n _execute_azure_api_request(req)\r\n\r\n\r\ndef _azure_finalize_blob(\r\n path: str, url: str, block_ids: List[str], md5_digest: bytes\r\n) -> None:\r\n body = {\"BlockList\": {\"Latest\": block_ids}}\r\n req = Request(\r\n url=url,\r\n method=\"PUT\",\r\n # azure does not calculate md5s for us, we have to do that manually\r\n # https://blogs.msdn.microsoft.com/windowsazurestorage/2011/02/17/windows-azure-blob-md5-overview/\r\n headers={\"x-ms-blob-content-md5\": base64.b64encode(md5_digest).decode(\"utf8\")},\r\n params=dict(comp=\"blocklist\"),\r\n data=body,\r\n success_codes=(201, 400),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status == 400:\r\n result = xmltodict.parse(resp.data)\r\n if result[\"Error\"][\"Code\"] == \"InvalidBlockList\":\r\n # the most likely way this could happen is if the file was deleted while\r\n # we were uploading, so assume that is what happened\r\n # this could be interpreted as a sort of RestartableStreamingWriteFailure but\r\n # that could result in two processes fighting while uploading the file\r\n raise ConcurrentWriteFailure.create_from_request_response(\r\n f\"Invalid block list, most likely a concurrent writer wrote to the same path: `{path}`\",\r\n request=req,\r\n response=resp,\r\n )\r\n else:\r\n raise RequestFailure.create_from_request_response(\r\n message=f\"unexpected status {resp.status}\", request=req, response=resp\r\n )\r\n\r\n\r\ndef _azure_block_index_to_block_id(index: int, upload_id: int) -> str:\r\n assert index < 2 ** 17\r\n id_plus_index = (upload_id << 17) + index\r\n assert id_plus_index < 2 ** 64\r\n return base64.b64encode(id_plus_index.to_bytes(8, byteorder=\"big\")).decode(\"utf8\")\r\n\r\n\r\ndef _azure_parallel_upload(\r\n executor: concurrent.futures.Executor, src: str, dst: str, return_md5: bool\r\n) -> Optional[str]:\r\n assert _is_local_path(src) and _is_azure_path(dst)\r\n\r\n with BlobFile(src, \"rb\") as f:\r\n md5_digest = _block_md5(f)\r\n\r\n account, container, blob = azure.split_path(dst)\r\n dst_url = azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n )\r\n\r\n upload_id = random.randint(0, 2 ** 47 - 1)\r\n s = stat(src)\r\n block_ids = []\r\n max_workers = getattr(executor, \"_max_workers\", os.cpu_count() or 1)\r\n part_size = min(\r\n max(math.ceil(s.size / max_workers), PARALLEL_COPY_MINIMUM_PART_SIZE),\r\n AZURE_MAX_BLOCK_SIZE,\r\n )\r\n i = 0\r\n start = 0\r\n futures = []\r\n while start < s.size:\r\n block_id = _azure_block_index_to_block_id(i, upload_id)\r\n future = executor.submit(\r\n _azure_upload_chunk,\r\n src,\r\n start,\r\n min(_azure_write_chunk_size, s.size - start),\r\n dst_url,\r\n block_id,\r\n )\r\n futures.append(future)\r\n block_ids.append(block_id)\r\n i += 1\r\n start += part_size\r\n for future in futures:\r\n future.result()\r\n\r\n _azure_finalize_blob(\r\n path=dst, url=dst_url, block_ids=block_ids, md5_digest=md5_digest\r\n )\r\n return binascii.hexlify(md5_digest).decode(\"utf8\") if return_md5 else None\r\n\r\n\r\nclass _WindowedFile:\r\n \"\"\"\r\n A file object that reads from a window into a file\r\n \"\"\"\r\n\r\n def __init__(self, f: Any, start: int, end: int) -> None:\r\n self._f = f\r\n self._start = start\r\n self._end = end\r\n self._pos = -1\r\n self.seek(0)\r\n\r\n def tell(self) -> int:\r\n return self._pos - self._start\r\n\r\n def seek(self, offset: int, whence: int = io.SEEK_SET) -> None:\r\n new_pos = self._start + offset\r\n assert whence == io.SEEK_SET and self._start <= new_pos < self._end\r\n self._f.seek(new_pos, whence)\r\n self._pos = new_pos\r\n\r\n def read(self, n: Optional[int] = None) -> Any:\r\n assert self._pos <= self._end\r\n if n is None:\r\n n = self._end - self._pos\r\n n = min(n, self._end - self._pos)\r\n buf = self._f.read(n)\r\n self._pos += len(buf)\r\n if n > 0 and len(buf) == 0:\r\n raise Error(\"failed to read expected amount of data from file\")\r\n assert self._pos <= self._end\r\n return buf\r\n\r\n\r\ndef _google_upload_part(path: str, start: int, size: int, dst: str) -> str:\r\n bucket, blob = google.split_path(dst)\r\n req = Request(\r\n url=google.build_url(\"/upload/storage/v1/b/{bucket}/o\", bucket=bucket),\r\n method=\"POST\",\r\n params=dict(uploadType=\"media\", name=blob),\r\n data=FileBody(path, start=start, end=start + size),\r\n success_codes=(200,),\r\n )\r\n resp = _execute_google_api_request(req)\r\n metadata = json.loads(resp.data)\r\n return metadata[\"generation\"]\r\n\r\n\r\ndef _google_delete_part(bucket: str, name: str) -> None:\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{object}\", bucket=bucket, object=name\r\n ),\r\n method=\"DELETE\",\r\n success_codes=(204, 404),\r\n )\r\n _execute_google_api_request(req)\r\n\r\n\r\ndef _google_parallel_upload(\r\n executor: concurrent.futures.Executor, src: str, dst: str, return_md5: bool\r\n) -> Optional[str]:\r\n assert _is_local_path(src) and _is_google_path(dst)\r\n\r\n with BlobFile(src, \"rb\") as f:\r\n md5_digest = _block_md5(f)\r\n\r\n s = stat(src)\r\n\r\n dstbucket, dstname = google.split_path(dst)\r\n source_objects = []\r\n object_names = []\r\n max_workers = getattr(executor, \"_max_workers\", os.cpu_count() or 1)\r\n part_size = max(math.ceil(s.size / max_workers), PARALLEL_COPY_MINIMUM_PART_SIZE)\r\n i = 0\r\n start = 0\r\n futures = []\r\n while start < s.size:\r\n suffix = f\".part.{i}\"\r\n future = executor.submit(\r\n _google_upload_part,\r\n src,\r\n start,\r\n min(part_size, s.size - start),\r\n dst + suffix,\r\n )\r\n futures.append(future)\r\n object_names.append(dstname + suffix)\r\n i += 1\r\n start += part_size\r\n for name, future in zip(object_names, futures):\r\n generation = future.result()\r\n source_objects.append(\r\n {\r\n \"name\": name,\r\n \"generation\": generation,\r\n \"objectPreconditions\": {\"ifGenerationMatch\": generation},\r\n }\r\n )\r\n\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{destinationBucket}/o/{destinationObject}/compose\",\r\n destinationBucket=dstbucket,\r\n destinationObject=dstname,\r\n ),\r\n method=\"POST\",\r\n data={\"sourceObjects\": source_objects},\r\n success_codes=(200,),\r\n )\r\n resp = _execute_google_api_request(req)\r\n metadata = json.loads(resp.data)\r\n hexdigest = binascii.hexlify(md5_digest).decode(\"utf8\")\r\n _google_maybe_update_md5(dst, metadata[\"generation\"], hexdigest)\r\n\r\n # delete parts in parallel\r\n delete_futures = []\r\n for name in object_names:\r\n future = executor.submit(_google_delete_part, dstbucket, name)\r\n delete_futures.append(future)\r\n for future in delete_futures:\r\n future.result()\r\n\r\n return hexdigest if return_md5 else None\r\n\r\n\r\ndef copy(\r\n src: str,\r\n dst: str,\r\n overwrite: bool = False,\r\n parallel: bool = False,\r\n parallel_executor: Optional[concurrent.futures.Executor] = None,\r\n return_md5: bool = False,\r\n) -> Optional[str]:\r\n \"\"\"\r\n Copy a file from one path to another\r\n\r\n If both paths are on the same blob storage, this will perform a remote copy operation without downloading\r\n the contents locally.\r\n\r\n If `overwrite` is `False` (the default), an exception will be raised if the destination\r\n path exists.\r\n\r\n If `parallel` is `True`, use multiple processes to dowload or upload the file. For this to work, one path must be on blob storage and the other path must be local. This can be faster on cloud machines but is not in general guaranteed to be faster than using serial copy. The default is `False`.\r\n\r\n If `parallel_executor` is set to a `concurrent.futures.Executor` and `parallel` is set to `True`, the provided executor will be used instead of creating a new one for each call to `copy()`.\r\n\r\n If `return_md5` is set to `True`, an md5 will be calculated during the copy and returned if available,\r\n or else None will be returned.\r\n \"\"\"\r\n # it would be best to check isdir() for remote paths, but that would\r\n # involve 2 extra network requests, so just do this test instead\r\n if _guess_isdir(src):\r\n raise IsADirectoryError(f\"Is a directory: '{src}'\")\r\n if _guess_isdir(dst):\r\n raise IsADirectoryError(f\"Is a directory: '{dst}'\")\r\n\r\n if not overwrite:\r\n if exists(dst):\r\n raise FileExistsError(\r\n f\"Destination '{dst}' already exists and overwrite is disabled\"\r\n )\r\n\r\n # special case cloud to cloud copy, don't download the file\r\n if _is_google_path(src) and _is_google_path(dst):\r\n srcbucket, srcname = google.split_path(src)\r\n dstbucket, dstname = google.split_path(dst)\r\n params = {}\r\n while True:\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}\",\r\n sourceBucket=srcbucket,\r\n sourceObject=srcname,\r\n destinationBucket=dstbucket,\r\n destinationObject=dstname,\r\n ),\r\n method=\"POST\",\r\n params=params,\r\n success_codes=(200, 404),\r\n )\r\n resp = _execute_google_api_request(req)\r\n if resp.status == 404:\r\n raise FileNotFoundError(f\"Source file not found: '{src}'\")\r\n result = json.loads(resp.data)\r\n if result[\"done\"]:\r\n if return_md5:\r\n return _google_get_md5(result[\"resource\"])\r\n else:\r\n return\r\n params[\"rewriteToken\"] = result[\"rewriteToken\"]\r\n\r\n if _is_azure_path(src) and _is_azure_path(dst):\r\n # https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob\r\n dst_account, dst_container, dst_blob = azure.split_path(dst)\r\n src_account, src_container, src_blob = azure.split_path(src)\r\n\r\n def build_req() -> Request:\r\n src_url = azure.build_url(\r\n src_account,\r\n \"/{container}/{blob}\",\r\n container=src_container,\r\n blob=src_blob,\r\n )\r\n if src_account != dst_account:\r\n # the signed url can expire, so technically we should get the sas_token and build the signed url\r\n # each time we build a new request\r\n sas_token = global_azure_sas_token_manager.get_token(\r\n key=(src_account, src_container)\r\n )\r\n # if we don't get a token, it's likely we have anonymous access to the container\r\n # if we do get a token, the container is likely private and we need to use\r\n # a signed url as the source\r\n if sas_token is not None:\r\n src_url, _ = azure.generate_signed_url(key=sas_token, url=src_url)\r\n req = Request(\r\n url=azure.build_url(\r\n dst_account,\r\n \"/{container}/{blob}\",\r\n container=dst_container,\r\n blob=dst_blob,\r\n ),\r\n method=\"PUT\",\r\n headers={\"x-ms-copy-source\": src_url},\r\n success_codes=(202, 404),\r\n )\r\n return azure.make_api_request(\r\n req,\r\n auth=global_azure_access_token_manager.get_token(\r\n key=(dst_account, dst_container)\r\n ),\r\n )\r\n\r\n resp = _execute_request(build_req)\r\n if resp.status == 404:\r\n raise FileNotFoundError(f\"Source file not found: '{src}'\")\r\n copy_id = resp.headers[\"x-ms-copy-id\"]\r\n copy_status = resp.headers[\"x-ms-copy-status\"]\r\n etag = resp.headers[\"etag\"]\r\n\r\n # wait for potentially async copy operation to finish\r\n # https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob\r\n # pending, success, aborted, failed\r\n backoff = _exponential_sleep_generator()\r\n while copy_status == \"pending\":\r\n time.sleep(next(backoff))\r\n req = Request(\r\n url=azure.build_url(\r\n dst_account,\r\n \"/{container}/{blob}\",\r\n container=dst_container,\r\n blob=dst_blob,\r\n ),\r\n method=\"GET\",\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.headers[\"x-ms-copy-id\"] != copy_id:\r\n raise Error(\"Copy id mismatch\")\r\n etag = resp.headers[\"etag\"]\r\n copy_status = resp.headers[\"x-ms-copy-status\"]\r\n if copy_status != \"success\":\r\n raise Error(f\"Invalid copy status: '{copy_status}'\")\r\n if return_md5:\r\n # if the file is the same one that we just copied, return the stored MD5\r\n isfile, metadata = _azure_isfile(dst)\r\n if isfile and metadata[\"etag\"] == etag:\r\n return _azure_get_md5(metadata)\r\n return\r\n\r\n if parallel:\r\n copy_fn = None\r\n if (_is_azure_path(src) or _is_google_path(src)) and _is_local_path(dst):\r\n copy_fn = _parallel_download\r\n\r\n if _is_local_path(src) and _is_azure_path(dst):\r\n copy_fn = _azure_parallel_upload\r\n\r\n if _is_local_path(src) and _is_google_path(dst):\r\n copy_fn = _google_parallel_upload\r\n\r\n if copy_fn is not None:\r\n if parallel_executor is None:\r\n with concurrent.futures.ProcessPoolExecutor() as executor:\r\n return copy_fn(executor, src, dst, return_md5=return_md5)\r\n else:\r\n return copy_fn(parallel_executor, src, dst, return_md5=return_md5)\r\n\r\n for attempt, backoff in enumerate(_exponential_sleep_generator()):\r\n try:\r\n with BlobFile(src, \"rb\", streaming=True) as src_f, BlobFile(\r\n dst, \"wb\", streaming=True\r\n ) as dst_f:\r\n m = hashlib.md5()\r\n while True:\r\n block = src_f.read(CHUNK_SIZE)\r\n if block == b\"\":\r\n break\r\n if return_md5:\r\n m.update(block)\r\n dst_f.write(block)\r\n if return_md5:\r\n return m.hexdigest()\r\n else:\r\n return\r\n except RestartableStreamingWriteFailure as err:\r\n # currently this is the only type of failure we retry, since we can re-read the source\r\n # stream from the beginning\r\n # if this failure occurs, the upload must be restarted from the beginning\r\n # https://cloud.google.com/storage/docs/resumable-uploads#practices\r\n # https://github.com/googleapis/gcs-resumable-upload/issues/15#issuecomment-249324122\r\n if _retry_limit is not None and attempt >= _retry_limit:\r\n raise\r\n\r\n if attempt >= _retry_log_threshold:\r\n _log_callback(\r\n f\"error {err} when executing a streaming write to {dst} attempt {attempt}, sleeping for {backoff:.1f} seconds before retrying\"\r\n )\r\n time.sleep(backoff)\r\n\r\n\r\ndef _calc_range(start: Optional[int] = None, end: Optional[int] = None) -> str:\r\n # https://cloud.google.com/storage/docs/xml-api/get-object-download\r\n # oddly range requests are not mentioned in the JSON API, only in the XML api\r\n if start is not None and end is not None:\r\n return f\"bytes={start}-{end-1}\"\r\n elif start is not None:\r\n return f\"bytes={start}-\"\r\n elif end is not None:\r\n if end > 0:\r\n return f\"bytes=0-{end-1}\"\r\n else:\r\n return f\"bytes=-{-int(end)}\"\r\n else:\r\n raise Error(\"Invalid range\")\r\n\r\n\r\ndef _create_google_page_iterator(\r\n url: str, method: str, params: Mapping[str, str]\r\n) -> Iterator[Dict[str, Any]]:\r\n p = dict(params).copy()\r\n\r\n while True:\r\n req = Request(url=url, method=method, params=p, success_codes=(200, 404))\r\n resp = _execute_google_api_request(req)\r\n if resp.status == 404:\r\n return\r\n result = json.loads(resp.data)\r\n yield result\r\n if \"nextPageToken\" not in result:\r\n break\r\n p[\"pageToken\"] = result[\"nextPageToken\"]\r\n\r\n\r\ndef _create_azure_page_iterator(\r\n url: str,\r\n method: str,\r\n data: Optional[Mapping[str, str]] = None,\r\n params: Optional[Mapping[str, str]] = None,\r\n) -> Iterator[Dict[str, Any]]:\r\n if params is None:\r\n p = {}\r\n else:\r\n p = dict(params).copy()\r\n if data is None:\r\n d = None\r\n else:\r\n d = dict(data).copy()\r\n while True:\r\n req = Request(\r\n url=url,\r\n method=method,\r\n params=p,\r\n data=d,\r\n success_codes=(200, 404, INVALID_HOSTNAME_STATUS),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status in (404, INVALID_HOSTNAME_STATUS):\r\n return\r\n result = xmltodict.parse(resp.data)[\"EnumerationResults\"]\r\n yield result\r\n if result[\"NextMarker\"] is None:\r\n break\r\n p[\"marker\"] = result[\"NextMarker\"]\r\n\r\n\r\ndef _google_get_entries(bucket: str, result: Mapping[str, Any]) -> Iterator[DirEntry]:\r\n if \"prefixes\" in result:\r\n for p in result[\"prefixes\"]:\r\n path = google.combine_path(bucket, p)\r\n yield _entry_from_dirpath(path)\r\n if \"items\" in result:\r\n for item in result[\"items\"]:\r\n path = google.combine_path(bucket, item[\"name\"])\r\n if item[\"name\"].endswith(\"/\"):\r\n yield _entry_from_dirpath(path)\r\n else:\r\n yield _entry_from_path_stat(path, _google_make_stat(item))\r\n\r\n\r\ndef _azure_get_entries(\r\n account: str, container: str, result: Mapping[str, Any]\r\n) -> Iterator[DirEntry]:\r\n blobs = result[\"Blobs\"]\r\n if blobs is None:\r\n return\r\n if \"BlobPrefix\" in blobs:\r\n if isinstance(blobs[\"BlobPrefix\"], dict):\r\n blobs[\"BlobPrefix\"] = [blobs[\"BlobPrefix\"]]\r\n for bp in blobs[\"BlobPrefix\"]:\r\n path = azure.combine_path(account, container, bp[\"Name\"])\r\n yield _entry_from_dirpath(path)\r\n if \"Blob\" in blobs:\r\n if isinstance(blobs[\"Blob\"], dict):\r\n blobs[\"Blob\"] = [blobs[\"Blob\"]]\r\n for b in blobs[\"Blob\"]:\r\n path = azure.combine_path(account, container, b[\"Name\"])\r\n if b[\"Name\"].endswith(\"/\"):\r\n yield _entry_from_dirpath(path)\r\n else:\r\n props = b[\"Properties\"]\r\n yield _entry_from_path_stat(path, _azure_make_stat(props))\r\n\r\n\r\ndef _google_isfile(path: str) -> Tuple[bool, Dict[str, Any]]:\r\n bucket, blob = google.split_path(path)\r\n if blob == \"\":\r\n return False, {}\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{object}\", bucket=bucket, object=blob\r\n ),\r\n method=\"GET\",\r\n success_codes=(200, 404),\r\n )\r\n resp = _execute_google_api_request(req)\r\n return resp.status == 200, json.loads(resp.data)\r\n\r\n\r\ndef _azure_isfile(path: str) -> Tuple[bool, Dict[str, Any]]:\r\n account, container, blob = azure.split_path(path)\r\n if blob == \"\":\r\n return False, {}\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"HEAD\",\r\n success_codes=(200, 404, INVALID_HOSTNAME_STATUS),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n return resp.status == 200, resp.headers\r\n\r\n\r\ndef exists(path: str) -> bool:\r\n \"\"\"\r\n Return true if that path exists (either as a file or a directory)\r\n \"\"\"\r\n if _is_local_path(path):\r\n return os.path.exists(path)\r\n elif _is_google_path(path):\r\n isfile, _ = _google_isfile(path)\r\n if isfile:\r\n return True\r\n return isdir(path)\r\n elif _is_azure_path(path):\r\n isfile, _ = _azure_isfile(path)\r\n if isfile:\r\n return True\r\n return isdir(path)\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef basename(path: str) -> str:\r\n \"\"\"\r\n Get the filename component of the path\r\n\r\n For GCS, this is the part after the bucket\r\n \"\"\"\r\n if _is_google_path(path):\r\n _, obj = google.split_path(path)\r\n return obj.split(\"/\")[-1]\r\n elif _is_azure_path(path):\r\n _, _, obj = azure.split_path(path)\r\n return obj.split(\"/\")[-1]\r\n else:\r\n return os.path.basename(path)\r\n\r\n\r\ndef _string_overlap(s1: str, s2: str) -> int:\r\n length = min(len(s1), len(s2))\r\n for i in range(length):\r\n if s1[i] != s2[i]:\r\n return i\r\n return length\r\n\r\n\r\ndef _split_path(path: str) -> List[str]:\r\n # a/b/c => a/, b/, c\r\n # a/b/ => a/, b/\r\n # /a/b/c => /, a/, b/, c\r\n parts = []\r\n part = \"\"\r\n for c in path:\r\n part += c\r\n if c == \"/\":\r\n parts.append(part)\r\n part = \"\"\r\n if part != \"\":\r\n parts.append(part)\r\n return parts\r\n\r\n\r\ndef _entry_from_dirpath(path: str) -> DirEntry:\r\n path = _strip_slash(path)\r\n return DirEntry(\r\n name=basename(path), path=path, is_dir=True, is_file=False, stat=None\r\n )\r\n\r\n\r\ndef _entry_from_path_stat(path: str, stat: Stat) -> DirEntry:\r\n assert not path.endswith(\"/\")\r\n return DirEntry(\r\n name=basename(path), path=path, is_dir=False, is_file=True, stat=stat\r\n )\r\n\r\n\r\ndef _expand_implicit_dirs(root: str, it: Iterator[DirEntry]) -> Iterator[DirEntry]:\r\n # blob storage does not always have definitions for each intermediate dir\r\n # if we have a listing like\r\n # gs://test/a/b\r\n # gs://test/a/b/c/d\r\n # then we emit an entry \"gs://test/a/b/c\" for the implicit dir \"c\"\r\n # requires that iterator return objects in sorted order\r\n previous_path = root\r\n for entry in it:\r\n # find the overlap between the previous_path and the current\r\n entry_slash_path = _get_slash_path(entry)\r\n offset = _string_overlap(previous_path, entry_slash_path)\r\n relpath = entry_slash_path[offset:]\r\n cur = entry_slash_path[:offset]\r\n if len(relpath) == 0:\r\n yield _entry_from_dirpath(cur)\r\n else:\r\n for part in _split_path(relpath):\r\n cur += part\r\n yield _entry_from_dirpath(cur)\r\n assert entry_slash_path >= previous_path\r\n previous_path = entry_slash_path\r\n\r\n\r\ndef _compile_pattern(s: str):\r\n tokens = [t for t in re.split(\"([*]+)\", s) if t != \"\"]\r\n regexp = \"\"\r\n for tok in tokens:\r\n if tok == \"*\":\r\n regexp += r\"[^/]*\"\r\n elif tok == \"**\":\r\n regexp += r\".*\"\r\n else:\r\n regexp += re.escape(tok)\r\n return re.compile(regexp + r\"/?$\")\r\n\r\n\r\ndef _glob_full(pattern: str) -> Iterator[DirEntry]:\r\n prefix, _, _ = pattern.partition(\"*\")\r\n\r\n re_pattern = _compile_pattern(pattern)\r\n\r\n for entry in _expand_implicit_dirs(root=prefix, it=_list_blobs(path=prefix)):\r\n entry_slash_path = _get_slash_path(entry)\r\n if bool(re_pattern.match(entry_slash_path)):\r\n if entry_slash_path == prefix and entry.is_dir:\r\n # we matched the parent directory\r\n continue\r\n yield entry\r\n\r\n\r\nclass _GlobTask(NamedTuple):\r\n cur: str\r\n rem: Sequence[str]\r\n\r\n\r\nclass _GlobEntry(NamedTuple):\r\n entry: DirEntry\r\n\r\n\r\nclass _GlobTaskComplete(NamedTuple):\r\n pass\r\n\r\n\r\ndef _process_glob_task(\r\n root: str, t: _GlobTask\r\n) -> Iterator[Union[_GlobTask, _GlobEntry]]:\r\n cur = t.cur + t.rem[0]\r\n rem = t.rem[1:]\r\n if \"**\" in cur:\r\n for entry in _glob_full(root + cur + \"\".join(rem)):\r\n yield _GlobEntry(entry)\r\n elif \"*\" in cur:\r\n re_pattern = _compile_pattern(root + cur)\r\n prefix, _, _ = cur.partition(\"*\")\r\n path = root + prefix\r\n for entry in _list_blobs(path=path, delimiter=\"/\"):\r\n entry_slash_path = _get_slash_path(entry)\r\n # in the case of dirname/* we should not return the path dirname/\r\n if entry_slash_path == path and entry.is_dir:\r\n # we matched the parent directory\r\n continue\r\n if bool(re_pattern.match(entry_slash_path)):\r\n if len(rem) == 0:\r\n yield _GlobEntry(entry)\r\n else:\r\n assert entry_slash_path.startswith(root)\r\n yield _GlobTask(entry_slash_path[len(root) :], rem)\r\n else:\r\n if len(rem) == 0:\r\n path = root + cur\r\n entry = _get_entry(path)\r\n if entry is not None:\r\n yield _GlobEntry(entry)\r\n else:\r\n yield _GlobTask(cur, rem)\r\n\r\n\r\ndef _glob_worker(\r\n root: str,\r\n tasks: mp.Queue[_GlobTask],\r\n results: mp.Queue[Union[_GlobEntry, _GlobTask, _GlobTaskComplete]],\r\n) -> None:\r\n while True:\r\n t = tasks.get()\r\n for r in _process_glob_task(root=root, t=t):\r\n results.put(r)\r\n results.put(_GlobTaskComplete())\r\n\r\n\r\ndef _local_glob(pattern: str) -> Iterator[str]:\r\n for filepath in local_glob.iglob(pattern, recursive=True):\r\n filepath = os.path.normpath(filepath)\r\n if filepath.endswith(os.sep):\r\n filepath = filepath[:-1]\r\n yield filepath\r\n\r\n\r\ndef glob(pattern: str, parallel: bool = False) -> Iterator[str]:\r\n \"\"\"\r\n Find files and directories matching a pattern. Supports * and **\r\n\r\n For local paths, this function uses glob.glob() which has special handling for * and **\r\n that is not quite the same as remote paths. See https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames#different-behavior-for-dot-files-in-local-file-system_1 for more information.\r\n\r\n Globs can have confusing performance, see https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames#efficiency-consideration:-using-wildcards-over-many-objects for more information.\r\n\r\n You can set `parallel=True` to use multiple processes to perform the glob. It's likely\r\n that the results will no longer be in order.\r\n \"\"\"\r\n if _is_local_path(pattern):\r\n # scanglob currently does an os.stat for each matched file\r\n # until scanglob can be implemented directly on scandir\r\n # this code is here to not\r\n if \"?\" in pattern or \"[\" in pattern or \"]\" in pattern:\r\n raise Error(\"Advanced glob queries are not supported\")\r\n yield from _local_glob(pattern)\r\n else:\r\n for entry in scanglob(pattern=pattern, parallel=parallel):\r\n yield entry.path\r\n\r\n\r\ndef scanglob(pattern: str, parallel: bool = False) -> Iterator[DirEntry]:\r\n \"\"\"\r\n Same as `glob`, but returns `DirEntry` objects instead of strings\r\n \"\"\"\r\n if \"?\" in pattern or \"[\" in pattern or \"]\" in pattern:\r\n raise Error(\"Advanced glob queries are not supported\")\r\n\r\n if _is_local_path(pattern):\r\n for filepath in _local_glob(pattern):\r\n # doing a stat call for each file isn't the most efficient\r\n # iglob uses os.scandir internally, but doesn't expose the information from that, so we'd\r\n # need to re-implement local glob\r\n # we could make the behavior with remote glob more consistent though if we did that\r\n s = os.stat(filepath)\r\n is_dir = stat_module.S_ISDIR(s.st_mode)\r\n yield DirEntry(\r\n path=filepath,\r\n name=basename(filepath),\r\n is_dir=is_dir,\r\n is_file=not is_dir,\r\n stat=None\r\n if is_dir\r\n else Stat(\r\n size=s.st_size,\r\n mtime=s.st_mtime,\r\n ctime=s.st_ctime,\r\n md5=None,\r\n version=None,\r\n ),\r\n )\r\n elif _is_google_path(pattern) or _is_azure_path(pattern):\r\n if \"*\" not in pattern:\r\n entry = _get_entry(pattern)\r\n if entry is not None:\r\n yield entry\r\n return\r\n\r\n if _is_google_path(pattern):\r\n bucket, blob_prefix = google.split_path(pattern)\r\n if \"*\" in bucket:\r\n raise Error(\"Wildcards cannot be used in bucket name\")\r\n root = google.combine_path(bucket, \"\")\r\n else:\r\n account, container, blob_prefix = azure.split_path(pattern)\r\n if \"*\" in account or \"*\" in container:\r\n raise Error(\"Wildcards cannot be used in account or container\")\r\n root = azure.combine_path(account, container, \"\")\r\n\r\n initial_task = _GlobTask(\"\", _split_path(blob_prefix))\r\n\r\n if parallel:\r\n tasks = mp.Queue()\r\n tasks.put(initial_task)\r\n tasks_enqueued = 1\r\n results = mp.Queue()\r\n\r\n tasks_done = 0\r\n with mp.Pool(initializer=_glob_worker, initargs=(root, tasks, results)):\r\n while tasks_done < tasks_enqueued:\r\n r = results.get()\r\n if isinstance(r, _GlobEntry):\r\n yield r.entry\r\n elif isinstance(r, _GlobTask):\r\n tasks.put(r)\r\n tasks_enqueued += 1\r\n elif isinstance(r, _GlobTaskComplete):\r\n tasks_done += 1\r\n else:\r\n raise Error(\"Invalid result\")\r\n else:\r\n dq: collections.deque[_GlobTask] = collections.deque()\r\n dq.append(initial_task)\r\n while len(dq) > 0:\r\n t = dq.popleft()\r\n for r in _process_glob_task(root=root, t=t):\r\n if isinstance(r, _GlobEntry):\r\n yield r.entry\r\n else:\r\n dq.append(r)\r\n else:\r\n raise Error(f\"Unrecognized path '{pattern}'\")\r\n\r\n\r\ndef _strip_slash(path: str) -> str:\r\n if path.endswith(\"/\"):\r\n return path[:-1]\r\n else:\r\n return path\r\n\r\n\r\ndef _strip_slashes(path: str) -> str:\r\n while path.endswith(\"/\"):\r\n path = path[:-1]\r\n return path\r\n\r\n\r\ndef isdir(path: str) -> bool:\r\n \"\"\"\r\n Return true if a path is an existing directory\r\n \"\"\"\r\n if _is_local_path(path):\r\n return os.path.isdir(path)\r\n elif _is_google_path(path):\r\n if not path.endswith(\"/\"):\r\n path += \"/\"\r\n bucket, blob = google.split_path(path)\r\n if blob == \"\":\r\n req = Request(\r\n url=google.build_url(\"/storage/v1/b/{bucket}\", bucket=bucket),\r\n method=\"GET\",\r\n success_codes=(200, 404),\r\n )\r\n resp = _execute_google_api_request(req)\r\n return resp.status == 200\r\n else:\r\n params = dict(prefix=blob, delimiter=\"/\", maxResults=\"1\")\r\n req = Request(\r\n url=google.build_url(\"/storage/v1/b/{bucket}/o\", bucket=bucket),\r\n method=\"GET\",\r\n params=params,\r\n success_codes=(200, 404),\r\n )\r\n resp = _execute_google_api_request(req)\r\n if resp.status == 404:\r\n return False\r\n result = json.loads(resp.data)\r\n return \"items\" in result or \"prefixes\" in result\r\n elif _is_azure_path(path):\r\n if not path.endswith(\"/\"):\r\n path += \"/\"\r\n account, container, blob = azure.split_path(path)\r\n if blob == \"\":\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}\", container=container, blob=blob\r\n ),\r\n method=\"GET\",\r\n params=dict(restype=\"container\"),\r\n success_codes=(200, 404, INVALID_HOSTNAME_STATUS),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n return resp.status == 200\r\n else:\r\n # even though we're only interested in having one result, we still need to make an\r\n # iterator. as it happens, azure is perfectly willing to return an empty first page.\r\n it = _create_azure_page_iterator(\r\n url=azure.build_url(account, \"/{container}\", container=container),\r\n method=\"GET\",\r\n params=dict(\r\n comp=\"list\",\r\n restype=\"container\",\r\n prefix=blob,\r\n delimiter=\"/\",\r\n maxresults=\"1\",\r\n ),\r\n )\r\n for result in it:\r\n if result[\"Blobs\"] is not None:\r\n return \"BlobPrefix\" in result[\"Blobs\"] or \"Blob\" in result[\"Blobs\"]\r\n return False\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef _guess_isdir(path: str) -> bool:\r\n \"\"\"\r\n Guess if a path is a directory without performing network requests\r\n \"\"\"\r\n if _is_local_path(path) and os.path.isdir(path):\r\n return True\r\n elif (_is_google_path(path) or _is_azure_path(path)) and path.endswith(\"/\"):\r\n return True\r\n return False\r\n\r\n\r\ndef _list_blobs(path: str, delimiter: Optional[str] = None) -> Iterator[DirEntry]:\r\n params = {}\r\n if delimiter is not None:\r\n params[\"delimiter\"] = delimiter\r\n\r\n if _is_google_path(path):\r\n bucket, prefix = google.split_path(path)\r\n it = _create_google_page_iterator(\r\n url=google.build_url(\"/storage/v1/b/{bucket}/o\", bucket=bucket),\r\n method=\"GET\",\r\n params=dict(prefix=prefix, **params),\r\n )\r\n get_entries = functools.partial(_google_get_entries, bucket)\r\n elif _is_azure_path(path):\r\n account, container, prefix = azure.split_path(path)\r\n it = _create_azure_page_iterator(\r\n url=azure.build_url(account, \"/{container}\", container=container),\r\n method=\"GET\",\r\n params=dict(comp=\"list\", restype=\"container\", prefix=prefix, **params),\r\n )\r\n get_entries = functools.partial(_azure_get_entries, account, container)\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n for result in it:\r\n for entry in get_entries(result):\r\n yield entry\r\n\r\n\r\ndef _get_slash_path(entry: DirEntry) -> str:\r\n return entry.path + \"/\" if entry.is_dir else entry.path\r\n\r\n\r\ndef _normalize_path(path: str) -> str:\r\n if _is_azure_path(path):\r\n return azure.normalize_path(path)\r\n return path\r\n\r\n\r\ndef _list_blobs_in_dir(prefix: str, exclude_prefix: bool) -> Iterator[DirEntry]:\r\n # the prefix check doesn't work without normalization\r\n normalized_prefix = _normalize_path(prefix)\r\n for entry in _list_blobs(path=normalized_prefix, delimiter=\"/\"):\r\n if exclude_prefix and _get_slash_path(entry) == normalized_prefix:\r\n continue\r\n yield entry\r\n\r\n\r\ndef listdir(path: str, shard_prefix_length: int = 0) -> Iterator[str]:\r\n \"\"\"\r\n Returns an iterator of the contents of the directory at `path`\r\n\r\n If your filenames are uniformly distributed (like hashes) then you can use `shard_prefix_length`\r\n to query them more quickly. `shard_prefix_length` will do multiple queries in parallel,\r\n querying each possible prefix independently.\r\n\r\n Using `shard_prefix_length` will only consider prefixes that are not unusual characters\r\n (mostly these are ascii values < 0x20) some of these could technically show up in a path.\r\n \"\"\"\r\n for entry in scandir(path, shard_prefix_length=shard_prefix_length):\r\n yield entry.name\r\n\r\n\r\ndef scandir(path: str, shard_prefix_length: int = 0) -> Iterator[DirEntry]:\r\n \"\"\"\r\n Same as `listdir`, but returns `DirEntry` objects instead of strings\r\n \"\"\"\r\n if (_is_google_path(path) or _is_azure_path(path)) and not path.endswith(\"/\"):\r\n path += \"/\"\r\n if not exists(path):\r\n raise FileNotFoundError(f\"The system cannot find the path specified: '{path}'\")\r\n if not isdir(path):\r\n raise NotADirectoryError(f\"The directory name is invalid: '{path}'\")\r\n if _is_local_path(path):\r\n for de in os.scandir(path):\r\n if de.is_dir():\r\n yield DirEntry(\r\n name=de.name,\r\n path=os.path.abspath(de.path),\r\n is_dir=True,\r\n is_file=False,\r\n stat=None,\r\n )\r\n else:\r\n s = de.stat()\r\n yield DirEntry(\r\n name=de.name,\r\n path=os.path.abspath(de.path),\r\n is_dir=False,\r\n is_file=True,\r\n stat=Stat(\r\n size=s.st_size,\r\n mtime=s.st_mtime,\r\n ctime=s.st_ctime,\r\n md5=None,\r\n version=None,\r\n ),\r\n )\r\n elif _is_google_path(path) or _is_azure_path(path):\r\n if shard_prefix_length == 0:\r\n yield from _list_blobs_in_dir(path, exclude_prefix=True)\r\n else:\r\n prefixes = mp.Queue()\r\n items = mp.Queue()\r\n tasks_enqueued = 0\r\n\r\n valid_chars = [\r\n i for i in range(256) if i not in INVALID_CHARS and i != ord(\"/\")\r\n ]\r\n for repeat in range(1, shard_prefix_length + 1):\r\n for chars in itertools.product(valid_chars, repeat=repeat):\r\n prefix = \"\"\r\n for c in chars:\r\n prefix += chr(c)\r\n # we need to check for exact matches for shorter prefix lengths\r\n # if we only searched for prefixes of length `shard_prefix_length`\r\n # we would skip shorter names, for instance \"a\" would be skipped if we\r\n # we had `shard_prefix_length=2`\r\n # instead we check for an exact match for everything shorter than\r\n # our `shard_prefix_length`\r\n exact = repeat != shard_prefix_length\r\n prefixes.put((path, prefix, exact))\r\n tasks_enqueued += 1\r\n\r\n tasks_done = 0\r\n with mp.Pool(\r\n initializer=_sharded_listdir_worker, initargs=(prefixes, items)\r\n ):\r\n while tasks_done < tasks_enqueued:\r\n entry = items.get()\r\n if entry is None:\r\n tasks_done += 1\r\n continue\r\n yield entry\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef _get_entry(path: str) -> Optional[DirEntry]:\r\n if _is_google_path(path):\r\n isfile, metadata = _google_isfile(path)\r\n if isfile:\r\n if path.endswith(\"/\"):\r\n return _entry_from_dirpath(path)\r\n else:\r\n return _entry_from_path_stat(path, _google_make_stat(metadata))\r\n elif _is_azure_path(path):\r\n isfile, metadata = _azure_isfile(path)\r\n if isfile:\r\n if path.endswith(\"/\"):\r\n return _entry_from_dirpath(path)\r\n else:\r\n return _entry_from_path_stat(path, _azure_make_stat(metadata))\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n if isdir(path):\r\n return _entry_from_dirpath(path)\r\n return None\r\n\r\n\r\ndef _sharded_listdir_worker(\r\n prefixes: mp.Queue[Tuple[str, str, bool]], items: mp.Queue[Optional[DirEntry]]\r\n) -> None:\r\n while True:\r\n base, prefix, exact = prefixes.get(True)\r\n if exact:\r\n path = base + prefix\r\n entry = _get_entry(path)\r\n if entry is not None:\r\n items.put(entry)\r\n else:\r\n it = _list_blobs_in_dir(base + prefix, exclude_prefix=False)\r\n for entry in it:\r\n items.put(entry)\r\n items.put(None) # indicate that we have finished this path\r\n\r\n\r\ndef makedirs(path: str) -> None:\r\n \"\"\"\r\n Make any directories necessary to ensure that path is a directory\r\n \"\"\"\r\n if _is_local_path(path):\r\n os.makedirs(path, exist_ok=True)\r\n elif _is_google_path(path):\r\n if not path.endswith(\"/\"):\r\n path += \"/\"\r\n bucket, blob = google.split_path(path)\r\n req = Request(\r\n url=google.build_url(\"/upload/storage/v1/b/{bucket}/o\", bucket=bucket),\r\n method=\"POST\",\r\n params=dict(uploadType=\"media\", name=blob),\r\n success_codes=(200, 400),\r\n )\r\n resp = _execute_google_api_request(req)\r\n if resp.status == 400:\r\n raise Error(f\"Unable to create directory, bucket does not exist: '{path}'\")\r\n elif _is_azure_path(path):\r\n if not path.endswith(\"/\"):\r\n path += \"/\"\r\n account, container, blob = azure.split_path(path)\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"PUT\",\r\n headers={\"x-ms-blob-type\": \"BlockBlob\"},\r\n success_codes=(201, 400),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status == 400:\r\n raise Error(\r\n f\"Unable to create directory, account/container does not exist: '{path}'\"\r\n )\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef remove(path: str) -> None:\r\n \"\"\"\r\n Remove a file at the given path\r\n \"\"\"\r\n if _is_local_path(path):\r\n os.remove(path)\r\n elif _is_google_path(path):\r\n if path.endswith(\"/\"):\r\n raise IsADirectoryError(f\"Is a directory: '{path}'\")\r\n bucket, blob = google.split_path(path)\r\n if blob == \"\":\r\n raise FileNotFoundError(\r\n f\"The system cannot find the path specified: '{path}'\"\r\n )\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{object}\", bucket=bucket, object=blob\r\n ),\r\n method=\"DELETE\",\r\n success_codes=(204, 404),\r\n )\r\n resp = _execute_google_api_request(req)\r\n if resp.status == 404:\r\n raise FileNotFoundError(\r\n f\"The system cannot find the path specified: '{path}'\"\r\n )\r\n elif _is_azure_path(path):\r\n if path.endswith(\"/\"):\r\n raise IsADirectoryError(f\"Is a directory: '{path}'\")\r\n account, container, blob = azure.split_path(path)\r\n if blob == \"\":\r\n raise FileNotFoundError(\r\n f\"The system cannot find the path specified: '{path}'\"\r\n )\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"DELETE\",\r\n success_codes=(202, 404, INVALID_HOSTNAME_STATUS),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status in (404, INVALID_HOSTNAME_STATUS):\r\n raise FileNotFoundError(\r\n f\"The system cannot find the path specified: '{path}'\"\r\n )\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef rmdir(path: str) -> None:\r\n \"\"\"\r\n Remove an empty directory at the given path\r\n \"\"\"\r\n if _is_local_path(path):\r\n os.rmdir(path)\r\n return\r\n\r\n # directories in blob storage are different from normal directories\r\n # a directory exists if there are any blobs that have that directory as a prefix\r\n # when the last blob with that prefix is deleted, the directory no longer exists\r\n # except in the case when there is a blob with a name ending in a slash\r\n # representing an empty directory\r\n\r\n # to make this more usable it is not an error to delete a directory that does\r\n # not exist, but is still an error to delete a non-empty one\r\n if not path.endswith(\"/\"):\r\n path += \"/\"\r\n\r\n if _is_google_path(path):\r\n _, blob = google.split_path(path)\r\n elif _is_azure_path(path):\r\n _, _, blob = azure.split_path(path)\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n if blob == \"\":\r\n raise Error(f\"Cannot delete bucket: '{path}'\")\r\n it = listdir(path)\r\n try:\r\n next(it)\r\n except FileNotFoundError:\r\n # this directory does not exist\r\n return\r\n except StopIteration:\r\n # this directory exists and is empty\r\n pass\r\n else:\r\n # this directory exists but is not empty\r\n raise OSError(f\"The directory is not empty: '{path}'\")\r\n\r\n if _is_google_path(path):\r\n bucket, blob = google.split_path(path)\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{object}\", bucket=bucket, object=blob\r\n ),\r\n method=\"DELETE\",\r\n success_codes=(204,),\r\n )\r\n _execute_google_api_request(req)\r\n elif _is_azure_path(path):\r\n account, container, blob = azure.split_path(path)\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"DELETE\",\r\n success_codes=(202,),\r\n )\r\n _execute_azure_api_request(req)\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef _google_parse_timestamp(text: str) -> float:\r\n return datetime.datetime.strptime(text, \"%Y-%m-%dT%H:%M:%S.%f%z\").timestamp()\r\n\r\n\r\ndef _google_make_stat(item: Mapping[str, Any]) -> Stat:\r\n if \"metadata\" in item and \"blobfile-mtime\" in item[\"metadata\"]:\r\n mtime = float(item[\"metadata\"][\"blobfile-mtime\"])\r\n else:\r\n mtime = _google_parse_timestamp(item[\"updated\"])\r\n return Stat(\r\n size=int(item[\"size\"]),\r\n mtime=mtime,\r\n ctime=_google_parse_timestamp(item[\"timeCreated\"]),\r\n md5=_google_get_md5(item),\r\n version=item[\"generation\"],\r\n )\r\n\r\n\r\ndef _azure_parse_timestamp(text: str) -> float:\r\n return datetime.datetime.strptime(\r\n text.replace(\"GMT\", \"Z\"), \"%a, %d %b %Y %H:%M:%S %z\"\r\n ).timestamp()\r\n\r\n\r\ndef _azure_make_stat(item: Mapping[str, str]) -> Stat:\r\n if \"Creation-Time\" in item:\r\n raw_ctime = item[\"Creation-Time\"]\r\n else:\r\n raw_ctime = item[\"x-ms-creation-time\"]\r\n if \"x-ms-meta-blobfilemtime\" in item:\r\n mtime = float(item[\"x-ms-meta-blobfilemtime\"])\r\n else:\r\n mtime = _azure_parse_timestamp(item[\"Last-Modified\"])\r\n return Stat(\r\n size=int(item[\"Content-Length\"]),\r\n mtime=mtime,\r\n ctime=_azure_parse_timestamp(raw_ctime),\r\n md5=_azure_get_md5(item),\r\n version=item[\"Etag\"],\r\n )\r\n\r\n\r\ndef stat(path: str) -> Stat:\r\n \"\"\"\r\n Stat a file or object representing a directory, returns a Stat object\r\n \"\"\"\r\n if _is_local_path(path):\r\n s = os.stat(path)\r\n return Stat(\r\n size=s.st_size, mtime=s.st_mtime, ctime=s.st_ctime, md5=None, version=None\r\n )\r\n elif _is_google_path(path):\r\n isfile, metadata = _google_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n return _google_make_stat(metadata)\r\n elif _is_azure_path(path):\r\n isfile, metadata = _azure_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n return _azure_make_stat(metadata)\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef set_mtime(path: str, mtime: float, version: Optional[str] = None) -> bool:\r\n \"\"\"\r\n Set the mtime for a path, returns True on success\r\n\r\n A version can be specified (as returned by `stat()`) to only update the mtime if the\r\n version matches\r\n \"\"\"\r\n if _is_local_path(path):\r\n assert version is None\r\n os.utime(path, times=(mtime, mtime))\r\n return True\r\n elif _is_google_path(path):\r\n bucket, blob = google.split_path(path)\r\n params = None\r\n if version is not None:\r\n params = dict(ifGenerationMatch=version)\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{object}\", bucket=bucket, object=blob\r\n ),\r\n method=\"PATCH\",\r\n params=params,\r\n data=dict(metadata={\"blobfile-mtime\": str(mtime)}),\r\n success_codes=(200, 404, 412),\r\n )\r\n resp = _execute_google_api_request(req)\r\n if resp.status == 404:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n return resp.status == 200\r\n elif _is_azure_path(path):\r\n account, container, blob = azure.split_path(path)\r\n headers = {}\r\n if version is not None:\r\n headers[\"If-Match\"] = version\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"HEAD\",\r\n params=dict(comp=\"metadata\"),\r\n headers=headers,\r\n success_codes=(200, 404, 412),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status == 404:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n if resp.status == 412:\r\n return False\r\n\r\n headers = {k: v for k, v in resp.headers.items() if k.startswith(\"x-ms-meta-\")}\r\n headers[\"x-ms-meta-blobfilemtime\"] = str(mtime)\r\n if version is not None:\r\n headers[\"If-Match\"] = version\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"PUT\",\r\n params=dict(comp=\"metadata\"),\r\n headers=headers,\r\n success_codes=(200, 404, 412),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status == 404:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n return resp.status == 200\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef rmtree(path: str) -> None:\r\n \"\"\"\r\n Delete a directory tree\r\n \"\"\"\r\n if not isdir(path):\r\n raise NotADirectoryError(f\"The directory name is invalid: '{path}'\")\r\n\r\n if _is_local_path(path):\r\n shutil.rmtree(path)\r\n elif _is_google_path(path):\r\n if not path.endswith(\"/\"):\r\n path += \"/\"\r\n bucket, blob = google.split_path(path)\r\n it = _create_google_page_iterator(\r\n url=google.build_url(\"/storage/v1/b/{bucket}/o\", bucket=bucket),\r\n method=\"GET\",\r\n params=dict(prefix=blob),\r\n )\r\n for result in it:\r\n for entry in _google_get_entries(bucket, result):\r\n entry_slash_path = _get_slash_path(entry)\r\n entry_bucket, entry_blob = google.split_path(entry_slash_path)\r\n assert entry_bucket == bucket and entry_blob.startswith(blob)\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{object}\",\r\n bucket=bucket,\r\n object=entry_blob,\r\n ),\r\n method=\"DELETE\",\r\n # 404 is allowed in case a failed request successfully deleted the file\r\n # before erroring out\r\n success_codes=(204, 404),\r\n )\r\n _execute_google_api_request(req)\r\n elif _is_azure_path(path):\r\n if not path.endswith(\"/\"):\r\n path += \"/\"\r\n account, container, blob = azure.split_path(path)\r\n it = _create_azure_page_iterator(\r\n url=azure.build_url(account, \"/{container}\", container=container),\r\n method=\"GET\",\r\n params=dict(comp=\"list\", restype=\"container\", prefix=blob),\r\n )\r\n for result in it:\r\n for entry in _azure_get_entries(account, container, result):\r\n entry_slash_path = _get_slash_path(entry)\r\n entry_account, entry_container, entry_blob = azure.split_path(\r\n entry_slash_path\r\n )\r\n assert (\r\n entry_account == account\r\n and entry_container == container\r\n and entry_blob.startswith(blob)\r\n )\r\n req = Request(\r\n url=azure.build_url(\r\n account,\r\n \"/{container}/{blob}\",\r\n container=container,\r\n blob=entry_blob,\r\n ),\r\n method=\"DELETE\",\r\n # 404 is allowed in case a failed request successfully deleted the file\r\n # before erroring out\r\n success_codes=(202, 404),\r\n )\r\n _execute_azure_api_request(req)\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef walk(\r\n top: str, topdown: bool = True, onerror: Optional[Callable] = None\r\n) -> Iterator[Tuple[str, Sequence[str], Sequence[str]]]:\r\n \"\"\"\r\n Walk a directory tree in a similar manner to os.walk\r\n \"\"\"\r\n if not isdir(top):\r\n return\r\n\r\n if _is_local_path(top):\r\n top = os.path.normpath(top)\r\n for root, dirnames, filenames in os.walk(\r\n top=top, topdown=topdown, onerror=onerror\r\n ):\r\n assert isinstance(root, str)\r\n if root.endswith(os.sep):\r\n root = root[:-1]\r\n yield (root, sorted(dirnames), sorted(filenames))\r\n elif _is_google_path(top) or _is_azure_path(top):\r\n top = _normalize_path(top)\r\n if not top.endswith(\"/\"):\r\n top += \"/\"\r\n if topdown:\r\n dq: collections.deque[str] = collections.deque()\r\n dq.append(top)\r\n while len(dq) > 0:\r\n cur = dq.popleft()\r\n assert cur.endswith(\"/\")\r\n if _is_google_path(top):\r\n bucket, blob = google.split_path(cur)\r\n it = _create_google_page_iterator(\r\n url=google.build_url(\"/storage/v1/b/{bucket}/o\", bucket=bucket),\r\n method=\"GET\",\r\n params=dict(delimiter=\"/\", prefix=blob),\r\n )\r\n get_entries = functools.partial(_google_get_entries, bucket)\r\n elif _is_azure_path(top):\r\n account, container, blob = azure.split_path(cur)\r\n it = _create_azure_page_iterator(\r\n url=azure.build_url(\r\n account, \"/{container}\", container=container\r\n ),\r\n method=\"GET\",\r\n params=dict(\r\n comp=\"list\", restype=\"container\", delimiter=\"/\", prefix=blob\r\n ),\r\n )\r\n get_entries = functools.partial(\r\n _azure_get_entries, account, container\r\n )\r\n else:\r\n raise Error(f\"Unrecognized path: '{top}'\")\r\n dirnames = []\r\n filenames = []\r\n for result in it:\r\n for entry in get_entries(result):\r\n entry_path = _get_slash_path(entry)\r\n if entry_path == cur:\r\n continue\r\n if entry.is_dir:\r\n dirnames.append(entry.name)\r\n else:\r\n filenames.append(entry.name)\r\n yield (_strip_slash(cur), dirnames, filenames)\r\n dq.extend(join(cur, dirname) + \"/\" for dirname in dirnames)\r\n else:\r\n if _is_google_path(top):\r\n bucket, blob = google.split_path(top)\r\n it = _create_google_page_iterator(\r\n url=google.build_url(\"/storage/v1/b/{bucket}/o\", bucket=bucket),\r\n method=\"GET\",\r\n params=dict(prefix=blob),\r\n )\r\n get_entries = functools.partial(_google_get_entries, bucket)\r\n elif _is_azure_path(top):\r\n account, container, blob = azure.split_path(top)\r\n it = _create_azure_page_iterator(\r\n url=azure.build_url(account, \"/{container}\", container=container),\r\n method=\"GET\",\r\n params=dict(comp=\"list\", restype=\"container\", prefix=blob),\r\n )\r\n get_entries = functools.partial(_azure_get_entries, account, container)\r\n else:\r\n raise Error(f\"Unrecognized path: '{top}'\")\r\n\r\n cur = []\r\n dirnames_stack = [[]]\r\n filenames_stack = [[]]\r\n for result in it:\r\n for entry in get_entries(result):\r\n entry_slash_path = _get_slash_path(entry)\r\n if entry_slash_path == top:\r\n continue\r\n relpath = entry_slash_path[len(top) :]\r\n parts = relpath.split(\"/\")\r\n dirpath = parts[:-1]\r\n if dirpath != cur:\r\n # pop directories from the current path until we match the prefix of this new path\r\n while cur != dirpath[: len(cur)]:\r\n yield (\r\n top + \"/\".join(cur),\r\n dirnames_stack.pop(),\r\n filenames_stack.pop(),\r\n )\r\n cur.pop()\r\n # push directories from the new path until the current path matches it\r\n while cur != dirpath:\r\n dirname = dirpath[len(cur)]\r\n cur.append(dirname)\r\n filenames_stack.append([])\r\n # add this to child dir to the list of dirs for the parent\r\n dirnames_stack[-1].append(dirname)\r\n dirnames_stack.append([])\r\n if entry.is_file:\r\n filenames_stack[-1].append(entry.name)\r\n while len(cur) > 0:\r\n yield (top + \"/\".join(cur), dirnames_stack.pop(), filenames_stack.pop())\r\n cur.pop()\r\n yield (_strip_slash(top), dirnames_stack.pop(), filenames_stack.pop())\r\n assert len(dirnames_stack) == 0 and len(filenames_stack) == 0\r\n else:\r\n raise Error(f\"Unrecognized path: '{top}'\")\r\n\r\n\r\ndef dirname(path: str) -> str:\r\n \"\"\"\r\n Get the directory name of the path\r\n\r\n On GCS, the root directory is gs:///\r\n On Azure Storage, the root directory is https://.blob.core.windows.net//\r\n \"\"\"\r\n if _is_google_path(path):\r\n bucket, obj = google.split_path(path)\r\n obj = _strip_slashes(obj)\r\n if \"/\" in obj:\r\n obj = \"/\".join(obj.split(\"/\")[:-1])\r\n return google.combine_path(bucket, obj)\r\n else:\r\n return google.combine_path(bucket, \"\")[:-1]\r\n elif _is_azure_path(path):\r\n account, container, obj = azure.split_path(path)\r\n obj = _strip_slashes(obj)\r\n if \"/\" in obj:\r\n obj = \"/\".join(obj.split(\"/\")[:-1])\r\n return azure.combine_path(account, container, obj)\r\n else:\r\n return azure.combine_path(account, container, \"\")[:-1]\r\n else:\r\n return os.path.dirname(path)\r\n\r\n\r\ndef join(a: str, *args: str) -> str:\r\n \"\"\"\r\n Join file paths, if a path is an absolute path, it will replace the entire path component of previous paths\r\n \"\"\"\r\n out = a\r\n for b in args:\r\n out = _join2(out, b)\r\n return out\r\n\r\n\r\ndef _safe_urljoin(a: str, b: str) -> str:\r\n # a \":\" symbol in a relative url path will be interpreted as a fully qualified path\r\n # escape the \":\" to avoid this\r\n # https://stackoverflow.com/questions/55202875/python-urllib-parse-urljoin-on-path-starting-with-numbers-and-colon\r\n if ESCAPED_COLON in b:\r\n raise Error(f\"url cannot contain string '{ESCAPED_COLON}'\")\r\n escaped_b = b.replace(\":\", ESCAPED_COLON)\r\n joined = urllib.parse.urljoin(a, escaped_b)\r\n return joined.replace(ESCAPED_COLON, \":\")\r\n\r\n\r\ndef _join2(a: str, b: str) -> str:\r\n if _is_local_path(a):\r\n return os.path.join(a, b)\r\n elif _is_google_path(a) or _is_azure_path(a):\r\n if not a.endswith(\"/\"):\r\n a += \"/\"\r\n\r\n if _is_google_path(a):\r\n bucket, obj = google.split_path(a)\r\n obj = _safe_urljoin(obj, b)\r\n if obj.startswith(\"/\"):\r\n obj = obj[1:]\r\n return google.combine_path(bucket, obj)\r\n elif _is_azure_path(a):\r\n account, container, obj = azure.split_path(a)\r\n obj = _safe_urljoin(obj, b)\r\n if obj.startswith(\"/\"):\r\n obj = obj[1:]\r\n return azure.combine_path(account, container, obj)\r\n else:\r\n raise Error(f\"Unrecognized path: '{a}'\")\r\n else:\r\n raise Error(f\"Unrecognized path: '{a}'\")\r\n\r\n\r\ndef get_url(path: str) -> Tuple[str, Optional[float]]:\r\n \"\"\"\r\n Get a URL for the given path that a browser could open\r\n \"\"\"\r\n if _is_google_path(path):\r\n bucket, blob = google.split_path(path)\r\n return google.generate_signed_url(\r\n bucket, blob, expiration=google.MAX_EXPIRATION\r\n )\r\n elif _is_azure_path(path):\r\n account, container, blob = azure.split_path(path)\r\n url = azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n )\r\n token = global_azure_sas_token_manager.get_token(key=(account, container))\r\n if token is None:\r\n # the container has public access\r\n return url, float(\"inf\")\r\n return azure.generate_signed_url(key=token, url=url)\r\n elif _is_local_path(path):\r\n return f\"file://{path}\", None\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n\r\ndef _block_md5(f: BinaryIO) -> bytes:\r\n m = hashlib.md5()\r\n while True:\r\n block = f.read(CHUNK_SIZE)\r\n if block == b\"\":\r\n break\r\n m.update(block)\r\n return m.digest()\r\n\r\n\r\ndef _azure_maybe_update_md5(path: str, etag: str, hexdigest: str) -> bool:\r\n account, container, blob = azure.split_path(path)\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"HEAD\",\r\n headers={\"If-Match\": etag},\r\n success_codes=(200, 404, 412),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status in (404, 412):\r\n return False\r\n\r\n # these will be cleared if not provided, there does not appear to be a PATCH method like for GCS\r\n # https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties#remarks\r\n headers: Dict[str, str] = {}\r\n for src, dst in AZURE_RESPONSE_HEADER_TO_REQUEST_HEADER.items():\r\n if src in resp.headers:\r\n headers[dst] = resp.headers[src]\r\n headers[\"x-ms-blob-content-md5\"] = base64.b64encode(\r\n binascii.unhexlify(hexdigest)\r\n ).decode(\"utf8\")\r\n\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"PUT\",\r\n params=dict(comp=\"properties\"),\r\n headers={\r\n **headers,\r\n # https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations\r\n \"If-Match\": etag,\r\n },\r\n success_codes=(200, 404, 412),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n return resp.status == 200\r\n\r\n\r\ndef _google_maybe_update_md5(path: str, generation: str, hexdigest: str) -> bool:\r\n bucket, blob = google.split_path(path)\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{object}\", bucket=bucket, object=blob\r\n ),\r\n method=\"PATCH\",\r\n params=dict(ifGenerationMatch=generation),\r\n # it looks like we can't set the underlying md5Hash, only the metadata fields\r\n data=dict(metadata={\"md5\": hexdigest}),\r\n success_codes=(200, 404, 412),\r\n )\r\n\r\n resp = _execute_google_api_request(req)\r\n return resp.status == 200\r\n\r\n\r\ndef _google_get_md5(metadata: Mapping[str, Any]) -> Optional[str]:\r\n if \"md5Hash\" in metadata:\r\n return base64.b64decode(metadata[\"md5Hash\"]).hex()\r\n\r\n if \"metadata\" in metadata and \"md5\" in metadata[\"metadata\"]:\r\n # fallback to our custom hash if this is a composite object that is lacking the md5Hash field\r\n return metadata[\"metadata\"][\"md5\"]\r\n\r\n return None\r\n\r\n\r\ndef _azure_get_md5(metadata: Mapping[str, Any]) -> Optional[str]:\r\n if \"Content-MD5\" in metadata:\r\n b64_encoded = metadata[\"Content-MD5\"]\r\n if b64_encoded is None:\r\n return None\r\n return base64.b64decode(b64_encoded).hex()\r\n else:\r\n return None\r\n\r\n\r\ndef md5(path: str) -> str:\r\n \"\"\"\r\n Get the MD5 hash for a file in hexdigest format.\r\n\r\n For GCS this will look up the MD5 in the blob's metadata, unless it's a composite object, in which case\r\n it must be calculated by downloading the file.\r\n For Azure this can look up the MD5 if it's available, otherwise it must calculate it.\r\n For local paths, this must always calculate the MD5.\r\n \"\"\"\r\n if _is_google_path(path):\r\n isfile, metadata = _google_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n\r\n h = _google_get_md5(metadata)\r\n if h is not None:\r\n return h\r\n\r\n # this is probably a composite object, calculate the md5 and store it on the file if the file has not changed\r\n with BlobFile(path, \"rb\") as f:\r\n result = _block_md5(f).hex()\r\n\r\n _google_maybe_update_md5(path, metadata[\"generation\"], result)\r\n return result\r\n elif _is_azure_path(path):\r\n isfile, metadata = _azure_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n # https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties\r\n h = _azure_get_md5(metadata)\r\n if h is None:\r\n # md5 is missing, calculate it and store it on file if the file has not changed\r\n with BlobFile(path, \"rb\") as f:\r\n h = _block_md5(f).hex()\r\n _azure_maybe_update_md5(path, metadata[\"Etag\"], h)\r\n return h\r\n else:\r\n with BlobFile(path, \"rb\") as f:\r\n return _block_md5(f).hex()\r\n\r\n\r\nclass _StreamingReadFile(io.RawIOBase):\r\n def __init__(self, path: str, size: int) -> None:\r\n super().__init__()\r\n self._size = size\r\n self._path = path\r\n # current reading byte offset in the file\r\n self._offset = 0\r\n self._f = None\r\n self.requests = 0\r\n self.failures = 0\r\n self.bytes_read = 0\r\n\r\n def _request_chunk(\r\n self, streaming: bool, start: int, end: Optional[int] = None\r\n ) -> urllib3.response.HTTPResponse:\r\n raise NotImplementedError\r\n\r\n def readall(self) -> bytes:\r\n # https://github.com/christopher-hesse/blobfile/issues/46\r\n # due to a limitation of the ssl module, we cannot read more than 2**31 bytes at a time\r\n # reading a huge file in a single request is probably a bad idea anyway since the request\r\n # cannot be retried without re-reading the entire requested amount\r\n # instead, read into a buffer and return the buffer\r\n pieces = []\r\n while True:\r\n bytes_remaining = self._size - self._offset\r\n assert bytes_remaining >= 0, \"read more bytes than expected\"\r\n # if a user doesn't like this value, it is easy to use .read(size) directly\r\n opt_piece = self.read(min(CHUNK_SIZE, bytes_remaining))\r\n assert opt_piece is not None, \"file is in non-blocking mode\"\r\n piece = opt_piece\r\n if len(piece) == 0:\r\n break\r\n pieces.append(piece)\r\n return b\"\".join(pieces)\r\n\r\n # https://bugs.python.org/issue27501\r\n def readinto(self, b: Any) -> Optional[int]:\r\n bytes_remaining = self._size - self._offset\r\n if bytes_remaining <= 0:\r\n return 0\r\n\r\n if len(b) > bytes_remaining:\r\n # if we get a file that was larger than we expected, don't read the extra data\r\n b = b[:bytes_remaining]\r\n\r\n n = 0 # for pyright\r\n if USE_STREAMING_READ_REQUEST:\r\n for attempt, backoff in enumerate(_exponential_sleep_generator()):\r\n if self._f is None:\r\n resp = self._request_chunk(streaming=True, start=self._offset)\r\n if resp.status == 416:\r\n # likely the file was truncated while we were reading it\r\n # return an empty string\r\n return 0\r\n self._f = resp\r\n self.requests += 1\r\n\r\n err = None\r\n try:\r\n opt_n = self._f.readinto(b)\r\n assert opt_n is not None, \"file is in non-blocking mode\"\r\n n = opt_n\r\n if n == 0:\r\n # assume that the connection has died\r\n # if the file was truncated, we'll try to open it again and end up\r\n # returning out of this loop\r\n err = Error(\r\n f\"failed to read from connection while reading file at {self._path}\"\r\n )\r\n else:\r\n # only break out if we successfully read at least one byte\r\n break\r\n except (\r\n urllib3.exceptions.ReadTimeoutError, # haven't seen this error here, but seems possible\r\n urllib3.exceptions.ProtocolError,\r\n urllib3.exceptions.SSLError,\r\n ssl.SSLError,\r\n ) as e:\r\n err = Error(f\"exception {e} while reading file at {self._path}\")\r\n # assume that the connection has died or is in an unusable state\r\n # we don't want to put a broken connection back in the pool\r\n # so don't call self._f.release_conn()\r\n self._f.close()\r\n self._f = None\r\n self.failures += 1\r\n\r\n if _retry_limit is not None and attempt >= _retry_limit:\r\n raise err\r\n\r\n if attempt >= _retry_log_threshold:\r\n _log_callback(\r\n f\"error {err} when executing readinto({len(b)}) at offset {self._offset} attempt {attempt}, sleeping for {backoff:.1f} seconds before retrying\"\r\n )\r\n time.sleep(backoff)\r\n else:\r\n resp = self._request_chunk(\r\n streaming=False, start=self._offset, end=self._offset + len(b)\r\n )\r\n if resp.status == 416:\r\n # likely the file was truncated while we were reading it\r\n # return an empty string\r\n return 0\r\n self.requests += 1\r\n n = len(resp.data)\r\n b[:n] = resp.data\r\n self.bytes_read += n\r\n self._offset += n\r\n return n\r\n\r\n def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:\r\n if whence == io.SEEK_SET:\r\n new_offset = offset\r\n elif whence == io.SEEK_CUR:\r\n new_offset = self._offset + offset\r\n elif whence == io.SEEK_END:\r\n new_offset = self._size + offset\r\n else:\r\n raise ValueError(\r\n f\"Invalid whence ({whence}, should be {io.SEEK_SET}, {io.SEEK_CUR}, or {io.SEEK_END})\"\r\n )\r\n if new_offset != self._offset:\r\n self._offset = new_offset\r\n if self._f is not None:\r\n self._f.close()\r\n self._f = None\r\n return self._offset\r\n\r\n def tell(self) -> int:\r\n return self._offset\r\n\r\n def close(self) -> None:\r\n if self.closed:\r\n return\r\n\r\n if hasattr(self, \"_f\") and self._f is not None:\r\n # normally we would return the connection to the pool at this point, but in rare\r\n # circumstances this can cause an invalid socket to be in the connection pool and\r\n # crash urllib3\r\n # https://github.com/urllib3/urllib3/issues/1878\r\n self._f.close()\r\n self._f = None\r\n\r\n super().close()\r\n\r\n def readable(self) -> bool:\r\n return True\r\n\r\n def seekable(self) -> bool:\r\n return True\r\n\r\n\r\nclass _GoogleStreamingReadFile(_StreamingReadFile):\r\n def __init__(self, path: str) -> None:\r\n isfile, metadata = _google_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file or bucket: '{path}'\")\r\n super().__init__(path, int(metadata[\"size\"]))\r\n\r\n def _request_chunk(\r\n self, streaming: bool, start: int, end: Optional[int] = None\r\n ) -> urllib3.response.HTTPResponse:\r\n bucket, name = google.split_path(self._path)\r\n req = Request(\r\n url=google.build_url(\r\n \"/storage/v1/b/{bucket}/o/{name}\", bucket=bucket, name=name\r\n ),\r\n method=\"GET\",\r\n params=dict(alt=\"media\"),\r\n headers={\"Range\": _calc_range(start=start, end=end)},\r\n success_codes=(206, 416),\r\n # if we are streaming the data, make\r\n # sure we don't preload it\r\n preload_content=not streaming,\r\n )\r\n return _execute_google_api_request(req)\r\n\r\n\r\nclass _AzureStreamingReadFile(_StreamingReadFile):\r\n def __init__(self, path: str) -> None:\r\n isfile, metadata = _azure_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file or directory: '{path}'\")\r\n super().__init__(path, int(metadata[\"Content-Length\"]))\r\n\r\n def _request_chunk(\r\n self, streaming: bool, start: int, end: Optional[int] = None\r\n ) -> urllib3.response.HTTPResponse:\r\n account, container, blob = azure.split_path(self._path)\r\n req = Request(\r\n url=azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n ),\r\n method=\"GET\",\r\n headers={\"Range\": _calc_range(start=start, end=end)},\r\n success_codes=(206, 416),\r\n # if we are streaming the data, make\r\n # sure we don't preload it\r\n preload_content=not streaming,\r\n )\r\n resp = _execute_azure_api_request(req)\r\n return resp\r\n\r\n\r\nclass _StreamingWriteFile(io.BufferedIOBase):\r\n def __init__(self, chunk_size: int) -> None:\r\n # current writing byte offset in the file\r\n self._offset = 0\r\n # contents waiting to be uploaded\r\n self._buf = b\"\"\r\n self._chunk_size = chunk_size\r\n\r\n def _upload_chunk(self, chunk: bytes, finalize: bool) -> None:\r\n raise NotImplementedError\r\n\r\n def _upload_buf(self, finalize: bool = False):\r\n if finalize:\r\n size = len(self._buf)\r\n else:\r\n size = (len(self._buf) // self._chunk_size) * self._chunk_size\r\n assert size > 0\r\n chunk = self._buf[:size]\r\n self._buf = self._buf[size:]\r\n\r\n self._upload_chunk(chunk, finalize)\r\n self._offset += len(chunk)\r\n\r\n def close(self) -> None:\r\n if self.closed:\r\n return\r\n\r\n # we will have a partial remaining buffer at this point\r\n self._upload_buf(finalize=True)\r\n super().close()\r\n\r\n def tell(self) -> int:\r\n return self._offset\r\n\r\n def writable(self) -> bool:\r\n return True\r\n\r\n def write(self, b: bytes) -> int:\r\n self._buf += b\r\n while len(self._buf) > self._chunk_size:\r\n self._upload_buf()\r\n return len(b)\r\n\r\n def readinto(self, b: Any) -> int:\r\n raise io.UnsupportedOperation(\"not readable\")\r\n\r\n def detach(self) -> io.RawIOBase:\r\n raise io.UnsupportedOperation(\"no underlying raw stream\")\r\n\r\n def read1(self, size: int = -1) -> bytes:\r\n raise io.UnsupportedOperation(\"not readable\")\r\n\r\n def readinto1(self, b: Any) -> int:\r\n raise io.UnsupportedOperation(\"not readable\")\r\n\r\n\r\nclass _GoogleStreamingWriteFile(_StreamingWriteFile):\r\n def __init__(self, path: str) -> None:\r\n bucket, name = google.split_path(path)\r\n req = Request(\r\n url=google.build_url(\r\n \"/upload/storage/v1/b/{bucket}/o?uploadType=resumable\", bucket=bucket\r\n ),\r\n method=\"POST\",\r\n data=dict(name=name),\r\n success_codes=(200, 400, 404),\r\n )\r\n resp = _execute_google_api_request(req)\r\n if resp.status in (400, 404):\r\n raise FileNotFoundError(f\"No such file or bucket: '{path}'\")\r\n self._upload_url = resp.headers[\"Location\"]\r\n # https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload\r\n assert _google_write_chunk_size % (256 * 1024) == 0\r\n super().__init__(chunk_size=_google_write_chunk_size)\r\n\r\n def _upload_chunk(self, chunk: bytes, finalize: bool) -> None:\r\n start = self._offset\r\n end = self._offset + len(chunk) - 1\r\n\r\n total_size = \"*\"\r\n if finalize:\r\n total_size = self._offset + len(chunk)\r\n assert len(self._buf) == 0\r\n\r\n headers = {\r\n \"Content-Type\": \"application/octet-stream\",\r\n \"Content-Range\": f\"bytes {start}-{end}/{total_size}\",\r\n }\r\n if len(chunk) == 0 and finalize:\r\n # this is not mentioned in the docs but appears to be allowed\r\n # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range\r\n headers[\"Content-Range\"] = f\"bytes */{total_size}\"\r\n\r\n req = Request(\r\n url=self._upload_url,\r\n data=chunk,\r\n headers=headers,\r\n method=\"PUT\",\r\n success_codes=(200, 201) if finalize else (308,),\r\n )\r\n\r\n try:\r\n _execute_google_api_request(req)\r\n except RequestFailure as e:\r\n # https://cloud.google.com/storage/docs/resumable-uploads#practices\r\n if e.response_status in (404, 410):\r\n raise RestartableStreamingWriteFailure(\r\n message=e.message,\r\n request_string=e.request_string,\r\n response_status=e.response_status,\r\n error=e.error,\r\n error_description=e.error_description,\r\n )\r\n else:\r\n raise\r\n\r\n\r\ndef _clear_uncommitted_blocks(url: str, metadata: Dict[str, str]) -> None:\r\n # to avoid leaking uncommitted blocks, we can do a Put Block List with\r\n # all the existing blocks for a file\r\n # this will change the last-modified timestamp and the etag\r\n req = Request(\r\n url=url, params=dict(comp=\"blocklist\"), method=\"GET\", success_codes=(200, 404)\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status != 200:\r\n return\r\n\r\n result = xmltodict.parse(resp.data)\r\n if result[\"BlockList\"][\"CommittedBlocks\"] is None:\r\n return\r\n\r\n blocks = result[\"BlockList\"][\"CommittedBlocks\"][\"Block\"]\r\n if isinstance(blocks, dict):\r\n blocks = [blocks]\r\n\r\n body = {\"BlockList\": {\"Latest\": [b[\"Name\"] for b in blocks]}}\r\n # make sure to preserve metadata for the file\r\n headers: Dict[str, str] = {\r\n k: v for k, v in metadata.items() if k.startswith(\"x-ms-meta-\")\r\n }\r\n for src, dst in AZURE_RESPONSE_HEADER_TO_REQUEST_HEADER.items():\r\n if src in metadata:\r\n headers[dst] = metadata[src]\r\n req = Request(\r\n url=url,\r\n method=\"PUT\",\r\n params=dict(comp=\"blocklist\"),\r\n headers={**headers, \"If-Match\": metadata[\"etag\"]},\r\n data=body,\r\n success_codes=(201, 404, 412),\r\n )\r\n _execute_azure_api_request(req)\r\n\r\n\r\nclass _AzureStreamingWriteFile(_StreamingWriteFile):\r\n def __init__(self, path: str) -> None:\r\n self._path = path\r\n account, container, blob = azure.split_path(path)\r\n self._url = azure.build_url(\r\n account, \"/{container}/{blob}\", container=container, blob=blob\r\n )\r\n # block blobs let you upload up to 100,000 \"uncommitted\" blocks with user-chosen block ids\r\n # using the \"Put Block\" call\r\n # you may then call \"Put Block List\" with up to 50,000 block ids of the blocks you\r\n # want to be in the blob (50,000 is the max blocks per blob)\r\n # all unused uncommitted blocks will be deleted\r\n # uncommitted blocks also expire after a week if they are not committed\r\n #\r\n # since we use block blobs, there are a few ways we could implement this streaming write file\r\n #\r\n # method 1:\r\n # upload the first chunk of the file as block id \"0\", the second as block id \"1\" etc\r\n # when we are done writing the file, we call \"Put Block List\" using range(num_blocks) as\r\n # the block ids\r\n #\r\n # this has the advantage that if our program crashes, the same block ids will be reused\r\n # for the next upload and so we'll never get more than 50,000 uncommitted blocks\r\n #\r\n # in general, azure does not seem to support concurrent writers except maybe\r\n # for writing small files (GCS does to a limited extent through resumable upload sessions)\r\n #\r\n # with method 1, if you have two writers:\r\n #\r\n # writer 0: write block id \"0\"\r\n # writer 1: write block id \"0\"\r\n # writer 1: crash\r\n # writer 0: write block id \"1\"\r\n # writer 0: put block list [\"0\", \"1\"]\r\n #\r\n # then you will end up with block \"0\" from writer 1 and block \"1\" from writer 0, which means\r\n # your file will be corrupted\r\n #\r\n # this appears to be the method used by the azure python SDK\r\n #\r\n # method 2:\r\n # generate a random session id\r\n # upload the first chunk of the file as block id \"-0\",\r\n # the second block as \"-1\" etc\r\n # when we are done writing the file, call \"Put Block List\" using\r\n # [f\"-{i}\" for i in range(num_blocks)] as the block list\r\n #\r\n # this has the advantage that we should not observe data corruption from concurrent writers\r\n # assuming that the session ids are unique, although whichever writer finishes first will\r\n # win, because calling \"Put Block List\" will delete all uncommitted blocks\r\n #\r\n # this has the disadvantage that we can end up hitting the uncommitted block limit\r\n # 1) with 100,000 concurrent writers, each one would write the first block, then all\r\n # would immediately hit the block limit and get 409 errors\r\n # 2) with a single writer that crashes every time it writes the second block, it would\r\n # retry 100,000 times, then be unable to continue due to all the uncommitted blocks\r\n # it was generating\r\n #\r\n # the workaround we use here is that whenever a file is opened for reading, we clear all\r\n # uncommitted blocks by calling \"Put Block List\" with the list of currently committed blocks\r\n #\r\n # this seems to be reasonably fast in practice, and means that failure #2 should not be an issue\r\n #\r\n # failure #1 could still happen with concurrent writers, but this should result only in a\r\n # confusing error message (409 error) instead of a ConcurrentWriteFailure, though we\r\n # could likely raise that error if we saw a 409 with the error RequestEntityTooLargeBlockCountExceedsLimit\r\n #\r\n # this does change the behavior slightly, now the writer that will end up succeeding on \"Put Block List\"\r\n # is likely to be the last writer to open the file for writing, the others will fail\r\n # because their uncommitted blocks have been cleared\r\n #\r\n # it would be nice to replace this with a less odd method, but it's not obvious how\r\n # to do this on azure storage\r\n #\r\n # if there were upload sessions like GCS, this wouldn't be an issue\r\n # if there was no uncommitted block limit, method 2 would work fine\r\n # if blobs could automatically expire without having to add a container lifecycle rule\r\n # then we could upload to a temp path, then copy to the final path (assuming copy is atomic)\r\n # without automatic expiry, we'd leak temp files\r\n # we can use the lease system, but then we have to deal with leases\r\n\r\n self._upload_id = random.randint(0, 2 ** 47 - 1)\r\n self._block_index = 0\r\n # check to see if there is an existing blob at this location with the wrong type\r\n req = Request(\r\n url=self._url,\r\n method=\"HEAD\",\r\n success_codes=(200, 400, 404, INVALID_HOSTNAME_STATUS),\r\n )\r\n resp = _execute_azure_api_request(req)\r\n if resp.status == 200:\r\n if resp.headers[\"x-ms-blob-type\"] == \"BlockBlob\":\r\n # because we delete all the uncommitted blocks, any concurrent writers will fail\r\n # but they would fail anyway since the first writer to finish would end up\r\n # deleting all uncommitted blocks\r\n # this means that the last writer to start is likely to win, the others should fail\r\n # with ConcurrentWriteFailure\r\n _clear_uncommitted_blocks(self._url, resp.headers)\r\n else:\r\n # if the existing blob type is not compatible with the block blob we are about to write\r\n # we have to delete the file before writing our block blob or else we will get a 409\r\n # error when putting the first block\r\n remove(path)\r\n elif resp.status in (400, INVALID_HOSTNAME_STATUS) or (\r\n resp.status == 404\r\n and resp.headers[\"x-ms-error-code\"] == \"ContainerNotFound\"\r\n ):\r\n raise FileNotFoundError(\r\n f\"No such file or container/account does not exist: '{path}'\"\r\n )\r\n self._md5 = hashlib.md5()\r\n super().__init__(chunk_size=_azure_write_chunk_size)\r\n\r\n def _upload_chunk(self, chunk: bytes, finalize: bool) -> None:\r\n start = 0\r\n while start < len(chunk):\r\n # premium block blob storage supports block blobs and append blobs\r\n # https://azure.microsoft.com/en-us/blog/azure-premium-block-blob-storage-is-now-generally-available/\r\n # we use block blobs because they are compatible with WASB:\r\n # https://docs.microsoft.com/en-us/azure/databricks/kb/data-sources/wasb-check-blob-types\r\n end = start + _azure_write_chunk_size\r\n data = chunk[start:end]\r\n self._md5.update(data)\r\n req = Request(\r\n url=self._url,\r\n method=\"PUT\",\r\n params=dict(\r\n comp=\"block\",\r\n blockid=_azure_block_index_to_block_id(\r\n self._block_index, self._upload_id\r\n ),\r\n ),\r\n data=data,\r\n success_codes=(201,),\r\n )\r\n _execute_azure_api_request(req)\r\n self._block_index += 1\r\n if self._block_index >= AZURE_BLOCK_COUNT_LIMIT:\r\n raise Error(\r\n f\"Exceeded block count limit of {AZURE_BLOCK_COUNT_LIMIT} for Azure Storage. Increase `azure_write_chunk_size` so that {AZURE_BLOCK_COUNT_LIMIT} * `azure_write_chunk_size` exceeds the size of the file you are writing.\"\r\n )\r\n\r\n start += _azure_write_chunk_size\r\n\r\n if finalize:\r\n block_ids = [\r\n _azure_block_index_to_block_id(i, self._upload_id)\r\n for i in range(self._block_index)\r\n ]\r\n _azure_finalize_blob(\r\n path=self._path,\r\n url=self._url,\r\n block_ids=block_ids,\r\n md5_digest=self._md5.digest(),\r\n )\r\n\r\n\r\n@overload\r\ndef BlobFile(\r\n path: str,\r\n mode: Literal[\"rb\", \"wb\", \"ab\"],\r\n streaming: Optional[bool] = ...,\r\n buffer_size: int = ...,\r\n cache_dir: Optional[str] = ...,\r\n) -> BinaryIO:\r\n ...\r\n\r\n\r\n@overload\r\ndef BlobFile(\r\n path: str,\r\n mode: Literal[\"r\", \"w\", \"a\"] = ...,\r\n streaming: Optional[bool] = ...,\r\n buffer_size: int = ...,\r\n cache_dir: Optional[str] = ...,\r\n) -> TextIO:\r\n ...\r\n\r\n\r\ndef BlobFile(\r\n path: str,\r\n mode: Literal[\"r\", \"rb\", \"w\", \"wb\", \"a\", \"ab\"] = \"r\",\r\n streaming: Optional[bool] = None,\r\n buffer_size: int = io.DEFAULT_BUFFER_SIZE,\r\n cache_dir: Optional[str] = None,\r\n):\r\n \"\"\"\r\n Open a local or remote file for reading or writing\r\n\r\n Args:\r\n path local or remote path\r\n mode: one of \"r\", \"rb\", \"w\", \"wb\", \"a\", \"ab\" indicating the mode to open the file in\r\n streaming: the default for `streaming` is `True` when `mode` is in `\"r\", \"rb\"` and `False` when `mode` is in `\"w\", \"wb\", \"a\", \"ab\"`.\r\n * `streaming=True`:\r\n * Reading is done without downloading the entire remote file.\r\n * Writing is done to the remote file directly, but only in chunks of a few MB in size. `flush()` will not cause an early write.\r\n * Appending is not implemented.\r\n * `streaming=False`:\r\n * Reading is done by downloading the remote file to a local file during the constructor.\r\n * Writing is done by uploading the file on `close()` or during destruction.\r\n * Appending is done by downloading the file during construction and uploading on `close()` or during destruction.\r\n buffer_size: number of bytes to buffer, this can potentially make reading more efficient.\r\n cache_dir: a directory in which to cache files for reading, only valid if `streaming=False` and `mode` is in `\"r\", \"rb\"`. You are reponsible for cleaning up the cache directory.\r\n\r\n Returns:\r\n A file-like object\r\n \"\"\"\r\n if _guess_isdir(path):\r\n raise IsADirectoryError(f\"Is a directory: '{path}'\")\r\n\r\n if BLOBFILE_BACKENDS_ENV_VAR in os.environ:\r\n backends = os.environ[BLOBFILE_BACKENDS_ENV_VAR].split(\",\")\r\n path_backend = None\r\n if _is_local_path(path):\r\n path_backend = \"local\"\r\n elif _is_google_path(path):\r\n path_backend = \"google\"\r\n elif _is_azure_path(path):\r\n path_backend = \"azure\"\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n if path_backend not in backends:\r\n raise Error(\r\n f\"The environment variable `{BLOBFILE_BACKENDS_ENV_VAR}` is set to `{os.environ[BLOBFILE_BACKENDS_ENV_VAR]}`, but the path uses backend `{path_backend}`, if you wish to use this path with blobfile, please change the value of `{BLOBFILE_BACKENDS_ENV_VAR}` to include `{path_backend}`\"\r\n )\r\n\r\n if streaming is None:\r\n streaming = mode in (\"r\", \"rb\")\r\n\r\n if _is_local_path(path) and \"w\" in mode:\r\n # local filesystems require that intermediate directories exist, but this is not required by the\r\n # remote filesystems\r\n # for consistency, automatically create local intermediate directories\r\n if dirname(path) != \"\":\r\n makedirs(dirname(path))\r\n\r\n if streaming:\r\n if mode not in (\"w\", \"wb\", \"r\", \"rb\"):\r\n raise Error(f\"Invalid mode for streaming file: '{mode}'\")\r\n if cache_dir is not None:\r\n raise Error(\"Cannot specify cache_dir for streaming files\")\r\n if _is_local_path(path):\r\n f = io.FileIO(path, mode=mode)\r\n if \"r\" in mode:\r\n f = io.BufferedReader(f, buffer_size=buffer_size)\r\n else:\r\n f = io.BufferedWriter(f, buffer_size=buffer_size)\r\n elif _is_google_path(path):\r\n if mode in (\"w\", \"wb\"):\r\n f = _GoogleStreamingWriteFile(path)\r\n elif mode in (\"r\", \"rb\"):\r\n f = _GoogleStreamingReadFile(path)\r\n f = io.BufferedReader(f, buffer_size=buffer_size)\r\n else:\r\n raise Error(f\"Unsupported mode: '{mode}'\")\r\n elif _is_azure_path(path):\r\n if mode in (\"w\", \"wb\"):\r\n f = _AzureStreamingWriteFile(path)\r\n elif mode in (\"r\", \"rb\"):\r\n f = _AzureStreamingReadFile(path)\r\n f = io.BufferedReader(f, buffer_size=buffer_size)\r\n else:\r\n raise Error(f\"Unsupported mode: '{mode}'\")\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n # this should be a protocol so we don't have to cast\r\n # but the standard library does not seem to have a file-like protocol\r\n binary_f = cast(BinaryIO, f)\r\n if \"b\" in mode:\r\n return binary_f\r\n else:\r\n text_f = io.TextIOWrapper(binary_f, encoding=\"utf8\")\r\n # TextIOWrapper bypasses buffering on purpose: https://bugs.python.org/issue13393\r\n # Example: https://gist.github.com/christopher-hesse/b4aab4f6f9bcba597d079f3363dfab2c\r\n #\r\n # This happens when TextIOWrapper calls f.read1(CHUNK_SIZE)\r\n # https://github.com/python/cpython/blob/3d17c045b4c3d09b72bbd95ed78af1ae6f0d98d2/Modules/_io/textio.c#L1854\r\n # and BufferedReader only reads the requested size, not the buffer_size\r\n # https://github.com/python/cpython/blob/8666356280084f0426c28a981341f72eaaacd006/Modules/_io/bufferedio.c#L945\r\n #\r\n # The workaround appears to be to set the _CHUNK_SIZE property or monkey patch binary_f.read1 to call binary_f.read\r\n if hasattr(text_f, \"_CHUNK_SIZE\"):\r\n setattr(text_f, \"_CHUNK_SIZE\", buffer_size)\r\n return cast(TextIO, text_f)\r\n else:\r\n remote_path = None\r\n tmp_dir = None\r\n if mode not in (\"w\", \"wb\", \"r\", \"rb\", \"a\", \"ab\"):\r\n raise Error(f\"Invalid mode: '{mode}'\")\r\n\r\n if cache_dir is not None and mode not in (\"r\", \"rb\"):\r\n raise Error(\"cache_dir only supported in read mode\")\r\n\r\n local_filename = basename(path)\r\n if local_filename == \"\":\r\n local_filename = \"local.tmp\"\r\n if _is_google_path(path) or _is_azure_path(path):\r\n remote_path = path\r\n if mode in (\"a\", \"ab\"):\r\n tmp_dir = tempfile.mkdtemp()\r\n local_path = join(tmp_dir, local_filename)\r\n if exists(remote_path):\r\n copy(remote_path, local_path)\r\n elif mode in (\"r\", \"rb\"):\r\n if cache_dir is None:\r\n tmp_dir = tempfile.mkdtemp()\r\n local_path = join(tmp_dir, local_filename)\r\n copy(remote_path, local_path)\r\n else:\r\n if not _is_local_path(cache_dir):\r\n raise Error(f\"cache_dir must be a local path: '{cache_dir}'\")\r\n makedirs(cache_dir)\r\n path_md5 = hashlib.md5(path.encode(\"utf8\")).hexdigest()\r\n lock_path = join(cache_dir, f\"{path_md5}.lock\")\r\n tmp_path = join(cache_dir, f\"{path_md5}.tmp\")\r\n with filelock.FileLock(lock_path):\r\n remote_version = \"\"\r\n # get some sort of consistent remote hash so we can check for a local file\r\n if _is_google_path(path):\r\n isfile, metadata = _google_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n remote_version = metadata[\"generation\"]\r\n remote_hash = _google_get_md5(metadata)\r\n elif _is_azure_path(path):\r\n # in the azure case the remote md5 may not exist\r\n # this duplicates some of md5() because we want more control\r\n isfile, metadata = _azure_isfile(path)\r\n if not isfile:\r\n raise FileNotFoundError(f\"No such file: '{path}'\")\r\n remote_version = metadata[\"Etag\"]\r\n remote_hash = _azure_get_md5(metadata)\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n perform_copy = False\r\n if remote_hash is None:\r\n # there is no remote md5, copy the file\r\n # and attempt to update the md5\r\n perform_copy = True\r\n else:\r\n expected_local_path = join(\r\n cache_dir, remote_hash, local_filename\r\n )\r\n perform_copy = not exists(expected_local_path)\r\n\r\n if perform_copy:\r\n local_hexdigest = copy(\r\n remote_path, tmp_path, overwrite=True, return_md5=True\r\n )\r\n assert local_hexdigest is not None, \"failed to return md5\"\r\n # the file we downloaded may not match the remote file because\r\n # the remote file changed while we were downloading it\r\n # in this case make sure we don't cache it under the wrong md5\r\n local_path = join(\r\n cache_dir, local_hexdigest, local_filename\r\n )\r\n os.makedirs(dirname(local_path), exist_ok=True)\r\n if os.path.exists(local_path):\r\n # the file is already here, nevermind\r\n os.remove(tmp_path)\r\n else:\r\n os.replace(tmp_path, local_path)\r\n\r\n if remote_hash is None:\r\n if _is_azure_path(path):\r\n _azure_maybe_update_md5(\r\n path, remote_version, local_hexdigest\r\n )\r\n elif _is_google_path(path):\r\n _google_maybe_update_md5(\r\n path, remote_version, local_hexdigest\r\n )\r\n else:\r\n assert remote_hash is not None\r\n local_path = join(cache_dir, remote_hash, local_filename)\r\n else:\r\n tmp_dir = tempfile.mkdtemp()\r\n local_path = join(tmp_dir, local_filename)\r\n elif _is_local_path(path):\r\n local_path = path\r\n else:\r\n raise Error(f\"Unrecognized path: '{path}'\")\r\n\r\n f = _ProxyFile(\r\n local_path=local_path, mode=mode, tmp_dir=tmp_dir, remote_path=remote_path\r\n )\r\n if \"r\" in mode:\r\n f = io.BufferedReader(f, buffer_size=buffer_size)\r\n else:\r\n f = io.BufferedWriter(f, buffer_size=buffer_size)\r\n binary_f = cast(BinaryIO, f)\r\n if \"b\" in mode:\r\n return binary_f\r\n else:\r\n text_f = io.TextIOWrapper(binary_f, encoding=\"utf8\")\r\n return cast(TextIO, text_f)\r\n\r\n\r\nclass _ProxyFile(io.FileIO):\r\n def __init__(\r\n self,\r\n local_path: str,\r\n mode: 'Literal[\"r\", \"rb\", \"w\", \"wb\", \"a\", \"ab\"]',\r\n tmp_dir: Optional[str],\r\n remote_path: Optional[str],\r\n ) -> None:\r\n super().__init__(local_path, mode=mode)\r\n self._mode = mode\r\n self._tmp_dir = tmp_dir\r\n self._local_path = local_path\r\n self._remote_path = remote_path\r\n self._closed = False\r\n\r\n def close(self) -> None:\r\n if not hasattr(self, \"_closed\") or self._closed:\r\n return\r\n\r\n super().close()\r\n try:\r\n if self._remote_path is not None and self._mode in (\"w\", \"wb\", \"a\", \"ab\"):\r\n copy(self._local_path, self._remote_path, overwrite=True)\r\n finally:\r\n # if the copy fails, still cleanup our local temp file so it is not leaked\r\n if self._tmp_dir is not None:\r\n os.remove(self._local_path)\r\n os.rmdir(self._tmp_dir)\r\n self._closed = True\r\n","sub_path":"blobfile/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":135262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"574134519","text":"import numpy as np\nimport random\nimport gym\nimport gym_sch\nimport tensorflow.compat.v1 as tf\ntf.enable_eager_execution()\n#tf.disable_v2_behavior()\nenv = gym.make(\"sch-v0\", stoch = False)\ntf.keras.backend.clear_session()\nenv.from_json(\"/home/pfrode/LearnWSL/spinningup/apprentissage/info_2020_scheduling/Mathis/PraindeMine.json\")\nfrom manon_agent_ppg import Agent_ppo_se\nimport matplotlib.pyplot as plt\ntf.keras.backend.clear_session()\n\ndef validate_ppo_se(agent, env):\n\tfor k in range(21):\n\t\tenv.reset(stoch = False)\n\t\tenv.products[\"PainDeMieEmballe\"][\"demand\"] = k\n\t\tenv.products[\"PainDeMieSansCrouteEmballe\"][\"demand\"] = 20-k\n\t\tcompt = 0\n\t\twhile not env.done :\n\t\t\tstate = np.array(env.observation_space)\n\t\t\taction = agent.choose_action(state, test = False, valid = True)[0]\n\t\t\tenv.step([action])\n\t\t\tcompt += 1\n\t\tprint(\"Demand : {:2d}:{:2d} Score : {}.\".format(k,20-k,env.score))\nagent = Agent_ppo_se(0.0005, len(env.action_space), len(env.observation_space), 0.97)\nmod = agent.model_loading(\"model_stoch\")\nagent.predict = mod\nvalidate_ppo_se(agent, env)\n","sub_path":"Pierre/PPG_sans_entropy_no_overfit/reload.py","file_name":"reload.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"619169680","text":"# -*- coding: utf-8 -*-\n\n\nfrom fuel.datasets import H5PYDataset\nfrom fuel.utils import find_in_data_path\nfrom fuel.schemes import SequentialScheme\nfrom fuel.streams import DataStream\n\n\nclass Cars196Dataset(H5PYDataset):\n\n _filename = 'cars196/cars196.hdf5'\n\n def __init__(self, which_sets, **kwargs):\n try:\n# path = find_in_data_path(self._filename)\n path = \"/home/wzzhen/Desktop/chainer/lib/datasets/data/cars196/cars196.hdf5\"\n except IOError as e:\n msg = str(e) + (\"\"\".\n You need to download the dataset and convert it to hdf5 before.\"\"\")\n raise IOError(msg)\n super(Cars196Dataset, self).__init__(\n file_or_path=path, which_sets=which_sets, **kwargs)\n\n\ndef load_as_ndarray(which_sets=['train', 'test']):\n datasets = []\n for split in which_sets:\n data = Cars196Dataset([split], load_in_memory=True).data_sources\n datasets.append(data)\n return datasets\n\n\nif __name__ == '__main__':\n dataset = Cars196Dataset(['train'])\n\n st = DataStream(\n dataset, iteration_scheme=SequentialScheme(dataset.num_examples, 1))\n it = st.get_epoch_iterator()\n it.next()\n","sub_path":"lib/datasets/cars196_dataset.py","file_name":"cars196_dataset.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"19383132","text":"class Product:\n def __init__(self,price,item_name,weight,brand,status='for sale'):\n self.price = price\n self.item_name = item_name\n self.weight = weight\n self.brand = brand\n self.status = status\n\n def sell(self):\n if self.status == 'for sale':\n self.status = 'sold'\n return self\n \n def add_tax(self,tax):\n self.price += self.price * tax\n return self\n \n def return_item(self,reason_for_return):\n if reason_for_return == 'defective':\n self.price = 0\n self.status = 'defective'\n if reason_for_return == 'like new':\n self.status = 'for sale'\n if reason_for_return == 'opened':\n self.status = 'used'\n self.price -= self.price * .2\n return self\n\n def display_info(self):\n print(f'Item: {self.item_name}\\nPrice: {self.price}\\nWeight: {self.weight}\\nBrand: {self.brand}\\nStatus: {self.status}')\n return self\n \nbike = Product(200,'bicycle','35lbs','huffy')\n\nbike.add_tax(.10).sell().display_info()\nbike.return_item('defective').display_info()\n\n","sub_path":"PythonFundAssignments/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"408200607","text":"coords = [[-1, 3],\n [4, 3],\n [2, 1],\n [-1, -2],\n [3, -3]]\n\nx = 1\ny = 0\n\ndef get_gcd(a, b):\n if (b == 0):\n return a\n return get_gcd(b, a % b)\n\n\ndef getReducedForm(dy, dx):\n g = get_gcd(abs(dy), abs(dx))\n\n # get sign of result\n sign = (dy < 0) ^ (dx < 0)\n\n if (sign):\n return (-abs(dy) // g, abs(dx) // g)\n else:\n return (abs(dy) // g, abs(dx) // g)\n\n\ndef findAll(points, N, xO, yO):\n st = dict()\n\n for element in range(N):\n # get x and y co-ordinate of current point\n curX = points[element][0]\n curY = points[element][1]\n\n temp = getReducedForm(curY - yO, curX - xO)\n\n # if this slope is not there in set,\n # increase ans by 1 and insert in set\n if (temp not in st):\n st[temp] = []\n\n return st\n\n\n\ndef minLinesToCoverPoints(points, N, xO, yO):\n st = dict()\n minLines = 0\n res = findAll(points, N, xO, yO)\n for i in range(N):\n curX = points[i][0]\n curY = points[i][1]\n temp = getReducedForm(curY - yO, curX - xO)\n if (temp in res):\n cell = [points[i][0], points[i][1]]\n res[temp].append(cell)\n if (temp not in st):\n st[temp] = 1\n minLines += 1\n return res\n\n\nif __name__ == '__main__':\n\n\n print(list(minLinesToCoverPoints(coords, len(coords), x, y).values()))\n result = list(minLinesToCoverPoints(coords, len(coords), x, y).values())\n for i in result:\n print(str(i) + \"\\n\")\n","sub_path":"LineCoverProblemSolution/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"65939176","text":"import numpy as np\nimport cv2\nimport xlsxwriter\n\n\nim = cv2.imread('lastImage.jpg')\nheight, width = im.shape[:2]\nratio = float(width)/float(height)\nneww =int(560*ratio) \nnewh = int(560)\nprint(neww)\nimage = cv2.resize(im,(neww, newh), interpolation = cv2.INTER_CUBIC)\n\ngray = cv2.cvtColor(image , cv2.COLOR_BGR2GRAY)\nblur = cv2.GaussianBlur(gray, (5,5) ,0)\nthresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)\nkernel = np.ones((3,3),np.uint8)\nerosion = cv2.erode(thresh,kernel,iterations = 1)\nthresh = cv2.dilate(erosion,kernel,iterations = 1)\ncv2.imshow('thresh',thresh)\ncontours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n\narray = np.zeros((1,100))\n\nfor cnt in contours:\n if cv2.contourArea(cnt)>100:\n [x,y,w,h] = cv2.boundingRect(cnt)\n\n if h>30:\n cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)\n roi = thresh[y:y+h,x:x+w]\n roismall = cv2.resize(roi,(10,10))\n x = roismall.reshape((1,100))\n array = np.append(array,x,axis = 0)\n\n cv2.imshow('trial',roismall)\n cv2.imshow('image',image)\n cv2.waitKey(0)\n#cv2.destroyAllWindows(0)\n#print(array[2].reshape((10,10)))\n\nworkbook = xlsxwriter.Workbook('arrays.xlsx')\nworksheet = workbook.add_worksheet()\n\n\nrow = 0\n\n#for col, data in enumerate(array[3]):\n# worksheet.write_column(row, col, data)\n\nworkbook.close()\n\n\n","sub_path":"HWR/seg.py","file_name":"seg.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"145461104","text":"answer = input(\"Summer has started. Would rather go the beach or to the movies?\")\r\n\r\nif answer == 'beach' or answer == 'go to the beach' or answer == \"Beach\" or answer == \"Go to the beach\" or answer == \"Go to the Beach\" or answer == \"BEACH\":\r\n print(\" \")\r\n answerb = input (\"What do you want to do? Eat or play volleyball?\")\r\n if answerb == \"eat\" or answerb == \"EAT\" or answerb == \"Eat\":\r\n print (\"LET'S GO EAT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\r\nelse:\r\n print('the movies sounds better')\r\n answerm =input (\"Are you gonna go alone or with a special friend?\")\r\n if answerm == (\"alone\" or \"go alone\"):\r\n print (\"You're such a loner but whatever.\")\r\n answerm2 = input(\"You walk into the movies and see your ex with his/her significant other. What do you do? Do you walk away or confront them?\")\r\n if answerm2 == \"walk away\" or answerm2 == \"walk\":\r\n answerm3 = input(\"are you sure?\")\r\n if answerm3 == \"yes\":\r\n print (\"you're a loser. anyways.......\")\r\n\r\n\r\n else:\r\n print (\"I'm in the mood for some drama\")\r\n answerm4 = input(\"Do you want to go up to them with an attitude or politely?\")\r\n if answerm4 == \"attitude\" or answerm4 == \"with attitude\":\r\n print (\"So I've seen you've downgraded\")\r\n answerm5 = input(\"What are you gonna tell your ex?\")\r\n print (\"You go girl!!!!!!\")\r\n else:\r\n print (\"No you can't be polite. You should've chose attitude\")\r\n answerm5 = input(\"What are you gonna tell your ex?\")\r\n print (\"You go girl!!!!!!\")\r\n\r\n else:\r\n print (\"Im in the mood for some drama\")\r\n answerm4 = input(\"Do you want to go up to them with an attitude or politely?\")\r\n","sub_path":"adventure.py","file_name":"adventure.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"501578270","text":"from django.urls import path\nfrom blog import views\nfrom .feeds import LatestPostsFeed\n\napp_name = 'blog'\n# пространство имен приложения\nurlpatterns = [\n path('', views.post_list, name='post_list'),\n path('tag//', views.post_list, name='post_list_by_tag'),\n # path('', views.PostListView.as_view(), name='post_list'),\n path('////',\n # извлечение значений из URL'a. возвращается в виде строки,\n # потому мы используем конвертер\n views.post_detail, name='post_detail'),\n path('/share/', views.post_share, name='post_share'),\n path('feed/', LatestPostsFeed(), name='post_feed'),\n path('search/', views.post_search, name='post_search')\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"602651843","text":"import sys\nimport socket\nimport time\nimport bcrypt\n\nimport Adafruit_DHT\n\n\n# Parse command line parameters.\n#sensor_args = { '11': Adafruit_DHT.DHT11,\n# '22': Adafruit_DHT.DHT22,\n# '2302': Adafruit_DHT.AM2302 }\n#if len(sys.argv) == 3 and sys.argv[1] in sensor_args:\n# sensor = sensor_args[sys.argv[1]]\n# pin = sys.argv[2]\n#else:\n# print('Usage: sudo ./Adafruit_DHT.py [11|22|2302] ')\n# print('Example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO pin #4')\n# sys.exit(1)\n\n# Try to grab a sensor reading. Use the read_retry method which will retry up\n# to 15 times to get a sensor reading (waiting 2 seconds between each retry).\n\n\n# Un-comment the line below to convert the temperature to Fahrenheit.\n# temperature = temperature * 9/5.0 + 32\n\n# Note that sometimes you won't get a reading and\n# the results will be null (because Linux can't\n# guarantee the timing of calls to read the sensor).\n# If this happens try again!\nsensor = Adafruit_DHT.DHT11\npin = '12'\ns = socket.socket()\nprint (\"Socket successfully created\")\n\nport = 420\n\ns.bind(('', port))\nprint (\"socket binded to %s\" %(port))\n\ns.listen(5)\nprint (\"socket is listening\")\nmessage = ('T{0:0.1f} H{1:0.1f}'.format(1, 2))\nhashedMessage = bcrypt.hashpw(message)\nprint(hashedMessage)\n\n\nwhile True:\n humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)\n \n c, addr = s.accept()\n print (\"got connection from\"), addr\n if humidity is not None and temperature is not None:\n message = ('T{0:0.1f} H{1:0.1f}'.format(temperature, humidity))\n hashedMessage = bcrypt.hashpw(message)\n c.send(message.encode('UTF-8'))\n strTemp = (\"{0:0.1f}\".format(temperature))\n strHumid = (\"{0:0.1f}\".format(humidity))\n c.sendall(strTemp.encode('UTF-8'))\n c.sendall(strHumid.encode('UTF-8'))\n \n else:\n print('Failed to get reading. Try again!')\n sys.exit(1)\n\n c.close()\n \n","sub_path":"src/PieReadTest/PieReadServer.py","file_name":"PieReadServer.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"647119533","text":"import sys\nsys.stdin = open('5105.txt', 'r')\n\ndef findstart(N, data):\n for i in range(N):\n for j in range(N):\n if data[i][j] == 2:\n x, y = i, j\n break\n maze(x, y)\n\ndef maze(x, y):\n global path_count\n queue = [[x, y]]\n visited = [[x, y]]\n dx = [1, -1, 0, 0]\n dy = [0, 0, 1, -1]\n while stack:\n x, y = queue[0]\n for n in range(4):\n nx = x + dx[n]\n ny = y + dy[n]\n if 0 <= nx < N and 0 <= ny < N and [nx, ny] not in visited and (data[nx][ny] == 1 or data[nx][ny] == 3):\n visited.append([nx, ny])\n stack.append([nx, ny])\n path[nx][ny] = path[x][y] + 1\n if data[nx][ny] == 3:\n path_count = path[nx][ny] - 1\n return\n else:\n queue.pop()\n\nfor tc in range(1, int(input())+1):\n N = int(input())\n data = [[int(d) for d in input()] for _ in range(N)]\n\n stack = []\n visited = []\n\n path = [[0]*N for _ in range(N)]\n path_count = 0\n\n findstart(N, data)\n print('#{} {}'.format(tc, path_count))\n\n","sub_path":"05_algo/algo/190828/51052.py","file_name":"51052.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"244763050","text":"import time\nfrom time import strftime\n\n\ndef _fields_exist(tree_element):\n for field in [Attendance.f_attendance_id, Attendance.f_course_name, Attendance.f_group_id,\n Attendance.f_student_name, Attendance.f_time, Attendance.f_tutor_id]:\n elem = tree_element.find(field)\n if elem is None:\n return \"Parse XML error: no {} field\".format(field)\n return True\n\n\ndef _map_xml(tree):\n time_epoch_text = tree.find(Attendance.f_time).text\n if not time_epoch_text.isnumeric():\n return \"Invalid time parse: {}\".format(time_epoch_text)\n\n attendance = Attendance()\n attendance.attendance_id = tree.find(Attendance.f_attendance_id).text\n attendance.student_name = tree.find(Attendance.f_student_name).text\n attendance.group_name = tree.find(Attendance.f_group_id).text\n attendance.tutor_name = tree.find(Attendance.f_tutor_id).text\n attendance.course_name = tree.find(Attendance.f_course_name).text\n attendance.time_str = strftime(\"%d.%m %H:%M\", time.localtime(int(time_epoch_text) / 1000))\n return attendance\n\n\ndef from_XML(tree_element):\n check_result = _fields_exist(tree_element)\n if check_result is not True:\n return check_result\n return _map_xml(tree_element)\n\n\nclass Attendance:\n def __init__(self):\n self.attendance_id = None\n self.student_name = None\n self.group_name = None\n self.tutor_name = None\n self.course_name = None\n self.time_str = None\n\n f_attendance_id = \"attendanceId\"\n f_student_name = \"studentId\"\n f_group_id = \"groupId\"\n f_tutor_id = \"tutorId\"\n f_time = \"timeEpoh\"\n f_course_name = \"courseId\"\n\n def to_string(self):\n return \"{0} {1} \\n {2} {3}\".format(self.student_name, self.group_name, self.course_name, self.time_str)\n","sub_path":"Python_software_engineering/Raspberry Pi/raspberry_pi/web_client/attendance.py","file_name":"attendance.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"30705481","text":"from django import forms\nfrom home.models import Post\n# from django.contrib.auth.forms import formss\n# from django.contrib.auth.models import User\n\nFRUIT_CHOICES= [\n ('orange', 'Oranges'),\n ('cantaloupe', 'Cantaloupes'),\n ('mango', 'Mangoes'),\n ('honeydew', 'Honeydews'),\n ]\n\nclass HomeForm(forms.ModelForm):\n post = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n\n\n }\n ))\n name = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class' :'base',\n 'max_length': '30',\n 'required': 'False',\n 'help_text': 'Optional.',\n\n }\n ))\n language = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class' :'base',\n 'max_length': '30',\n 'required': 'False',\n 'help_text': 'Optional.',\n\n }\n ))\n email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')\n # picture = forms.ImageField()\n sample_chapter = forms.FileField(label='Select a file',\n help_text='max. 42 megabytes')\n cover_image = forms.ImageField(label='Select a file',\n help_text='max. 42 megabytes')\n favorite_fruit = forms.CharField(label='What is your favorite fruit?', widget=forms.Select(choices=FRUIT_CHOICES))\n\n class Meta:\n model = Post\n fields = ('post', 'name','language', 'email', 'sample_chapter','cover_image','favorite_fruit',)","sub_path":"home/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"102890838","text":"\"\"\"Test cases for the mocks module.\"\"\"\n\nimport sys\nimport unittest\nfrom functools import wraps\nfrom mock import patch, call, NonCallableMock\nfrom ..mocks import MockOpen, FileLikeMock\n\nif sys.version_info >= (3, 0):\n OPEN = \"builtins.open\"\nelse:\n OPEN = \"__builtin__.open\"\n\n\n@patch(OPEN, new_callable=MockOpen)\nclass TestOpenSingleFiles(unittest.TestCase):\n \"\"\"Test the MockOpen and FileLikeMock classes for single file usage.\"\"\"\n def test_read(self, mock_open):\n \"\"\"Check effects of reading from an empty file.\"\"\"\n handle = open(\"/path/to/file\", \"r\")\n self.assertFalse(handle.closed)\n self.assertEqual(\"/path/to/file\", handle.name)\n self.assertEqual(\"r\", handle.mode)\n self.assertEqual(0, handle.tell())\n\n text = handle.read()\n self.assertEqual(0, handle.tell())\n self.assertEqual(\"\", text)\n\n handle.close()\n self.assertTrue(handle.closed)\n\n self.assertEqual(handle, mock_open.return_value)\n mock_open.assert_called_once_with(\"/path/to/file\", \"r\")\n handle.read.assert_called_once_with()\n handle.close.assert_called_once_with()\n\n def test_write(self, mock_open):\n \"\"\"Check effects of writing to a file.\"\"\"\n handle = open(\"/path/to/file\", \"w\")\n self.assertFalse(handle.closed)\n self.assertEqual(\"/path/to/file\", handle.name)\n self.assertEqual(\"w\", handle.mode)\n self.assertEqual(0, handle.tell())\n\n handle.write(\"some text\\n\")\n self.assertEqual(len(\"some text\\n\"), handle.tell())\n handle.write(\"More text!\")\n self.assertEqual(\n len(\"some text\\n\") + len(\"More text!\"),\n handle.tell())\n\n handle.close()\n self.assertTrue(handle.closed)\n\n self.assertEqual(handle, mock_open.return_value)\n mock_open.assert_called_once_with(\"/path/to/file\", \"w\")\n self.assertEqual(\n [call(\"some text\\n\"), call(\"More text!\"), ],\n handle.write.mock_calls)\n self.assertEqual(\"some text\\nMore text!\", handle.read_data)\n handle.close.assert_called_once_with()\n\n def test_read_as_context_manager(self, mock_open):\n \"\"\"Check effects of reading from an empty file using a context\n manager.\n \"\"\"\n with open(\"/path/to/file\", \"r\") as handle:\n self.assertFalse(handle.closed)\n self.assertEqual(\"/path/to/file\", handle.name)\n self.assertEqual(\"r\", handle.mode)\n self.assertEqual(0, handle.tell())\n\n text = handle.read()\n self.assertEqual(0, handle.tell())\n self.assertEqual(\"\", text)\n\n self.assertTrue(handle.closed)\n self.assertEqual(handle, mock_open.return_value)\n mock_open.assert_called_once_with(\"/path/to/file\", \"r\")\n handle.read.assert_called_once_with()\n handle.close.assert_called_once_with()\n\n def test_write_as_context_manager(self, mock_open):\n \"\"\"Check effects of writing to a file using a context manager.\"\"\"\n with open(\"/path/to/file\", \"w\") as handle:\n self.assertFalse(handle.closed)\n self.assertEqual(\"/path/to/file\", handle.name)\n self.assertEqual(\"w\", handle.mode)\n self.assertEqual(0, handle.tell())\n\n handle.write(\"some text\\n\")\n self.assertEqual(len(\"some text\\n\"), handle.tell())\n handle.write(\"More text!\")\n self.assertEqual(\n len(\"some text\\n\") + len(\"More text!\"),\n handle.tell())\n\n self.assertTrue(handle.closed)\n self.assertEqual(handle, mock_open.return_value)\n mock_open.assert_called_once_with(\"/path/to/file\", \"w\")\n self.assertEqual(\n [call(\"some text\\n\"), call(\"More text!\"), ],\n handle.write.mock_calls)\n self.assertEqual(\"some text\\nMore text!\", handle.read_data)\n handle.close.assert_called_once_with()\n\n def test_seek(self, _):\n \"\"\"Check calling seek().\"\"\"\n with open(\"/path/to/file\", \"w+\") as handle:\n handle.write(\"There's no place like home\")\n handle.seek(len(\"There's \"))\n self.assertEqual(\"no place like home\", handle.read())\n\n def test_set_contents(self, mock_open):\n \"\"\"Check setting file's contents before reading from it.\"\"\"\n contents = [\n \"This is the first line\",\n \"This is the second\",\n \"This is the third line\",\n ]\n\n # We even allow adding contents to the file incrementally.\n mock_open.return_value.read_data = \"\\n\".join(contents[:-1])\n mock_open.return_value.read_data += \"\\n\" + contents[-1]\n\n with open(\"/path/to/file\", \"r\") as handle:\n data = handle.read()\n\n # Make sure the only call logged was to read().\n handle.write.assert_not_called()\n handle.read.assert_called_once_with()\n self.assertEqual(\"\\n\".join(contents), data)\n\n def test_read_size(self, mock_open):\n \"\"\"Check reading a certain amount of bytes from the file.\"\"\"\n mock_open.return_value.read_data = \"0123456789\"\n with open(\"/path/to/file\", \"r\") as handle:\n self.assertEqual(\"0123\", handle.read(4))\n self.assertEqual(\"4567\", handle.read(4))\n self.assertEqual(\"89\", handle.read())\n\n def test_different_read_calls(self, mock_open):\n \"\"\"Check that read/readline/readlines all work in sync.\"\"\"\n contents = [\n \"Now that she's back in the atmosphere\",\n \"With drops of Jupiter in her hair, hey, hey, hey\",\n \"She acts like summer and walks like rain\",\n \"Reminds me that there's a time to change, hey, hey, hey\",\n \"Since the return from her stay on the moon\",\n \"She listens like spring and she talks like June, hey, hey, hey\",\n ]\n\n mock_open.return_value.read_data = \"\\n\".join(contents)\n with open(\"/path/to/file\", \"r\") as handle:\n first_line = handle.read(len(contents[0]) + 1)\n second_line = handle.readline()\n third_line = handle.read(len(contents[2]) + 1)\n rest = handle.readlines()\n\n self.assertEqual(contents[0] + \"\\n\", first_line)\n self.assertEqual(contents[1] + \"\\n\", second_line)\n self.assertEqual(contents[2] + \"\\n\", third_line)\n self.assertEqual(\"\\n\".join(contents[3:]), \"\".join(rest))\n\n def test_different_write_calls(self, _):\n \"\"\"Check multiple calls to write and writelines.\"\"\"\n contents = [\n \"They paved paradise\",\n \"And put up a parking lot\",\n \"With a pink hotel, a boutique\",\n \"And a swinging hot SPOT\",\n \"Don't it always seem to go\",\n \"That you don't know what you've got\",\n \"'Til it's gone\",\n \"They paved paradise\",\n \"And put up a parking lot\",\n ]\n\n with open(\"/path/to/file\", \"w\") as handle:\n handle.write(contents[0] + \"\\n\")\n handle.write(contents[1] + \"\\n\")\n handle.writelines(line + \"\\n\" for line in contents[2:4])\n handle.write(contents[4] + \"\\n\")\n handle.writelines(line + \"\\n\" for line in contents[5:])\n\n self.assertEqual(contents, handle.read_data.splitlines())\n\n def test_iteration(self, mock_open):\n \"\"\"Test iterating over the file handle.\"\"\"\n contents = [\n \"So bye, bye, Miss American Pie\\n\",\n \"Drove my Chevy to the levee but the levee was dry\\n\",\n \"And them good ole boys were drinking whiskey 'n rye\\n\",\n \"Singin' this'll be the day that I die\\n\",\n \"This'll be the day that I die\",\n ]\n\n mock_open.return_value.read_data = \"\".join(contents)\n with open(\"/path/to/file\", \"r\") as handle:\n for (i, line) in enumerate(handle):\n self.assertEqual(contents[i], line)\n\n def test_getitem_after_call(self, mock_open):\n \"\"\"Retrieving a handle after the call to open() should give us the same\n object.\n \"\"\"\n with open(\"/path/to/file\", \"r\") as handle:\n pass\n\n self.assertEqual(handle, mock_open[\"/path/to/file\"])\n\n def test_setting_custom_mock(self, mock_open):\n \"\"\"Check 'manually' setting a mock for a file.\"\"\"\n custom_mock = NonCallableMock()\n mock_open[\"/path/to/file\"] = custom_mock\n\n # Make sure other files aren't affected.\n self.assertIsInstance(open(\"/path/to/other_file\", \"r\"), FileLikeMock)\n\n # Check with a regular call.\n self.assertEqual(custom_mock, open(\"/path/to/file\", \"r\"))\n\n # Check as a context manager.\n custom_mock.read.side_effect = IOError()\n custom_mock.write.side_effect = IOError()\n with open(\"/path/to/file\") as handle:\n self.assertIs(custom_mock, handle)\n self.assertRaises(IOError, handle.read)\n self.assertRaises(IOError, handle.write, \"error\")\n\n\n@patch(OPEN, new_callable=MockOpen)\nclass TestMultipleCalls(unittest.TestCase):\n \"\"\"Test multiple calls to open().\"\"\"\n def test_read_then_write(self, _):\n \"\"\"Accessing the same file should handle the same object.\n\n Reading from a file after writing to it should give us the same\n contents.\n \"\"\"\n with open(\"/path/to/file\", \"w\") as first_handle:\n first_handle.write(\"Ground control to Major Tom\")\n\n with open(\"/path/to/file\", \"r\") as second_handle:\n contents = second_handle.read()\n\n self.assertEqual(first_handle, second_handle)\n self.assertEqual(\"Ground control to Major Tom\", contents)\n\n def test_access_different_files(self, mock_open):\n \"\"\"Check access to different files with multiple calls to open().\"\"\"\n first_handle = mock_open[\"/path/to/first_file\"]\n second_handle = mock_open[\"/path/to/second_file\"]\n\n # Paths should be set when created, if possible.\n # Note this isn't the case when not specifically instantiating a file\n # mock (eg., by using `return_value` instead).\n self.assertEqual(\"/path/to/first_file\", first_handle.name)\n self.assertEqual(\"/path/to/second_file\", second_handle.name)\n\n first_handle.read_data = \"This is the FIRST file\"\n second_handle.read_data = \"This is the SECOND file\"\n\n with open(\"/path/to/first_file\", \"r\") as handle:\n self.assertEqual(\"/path/to/first_file\", handle.name)\n self.assertEqual(\"This is the FIRST file\", handle.read())\n\n with open(\"/path/to/second_file\", \"r\") as handle:\n self.assertEqual(\"/path/to/second_file\", handle.name)\n self.assertEqual(\"This is the SECOND file\", handle.read())\n\n # return_value is set to the last handle returned.\n self.assertEqual(second_handle, mock_open.return_value)\n\n self.assertEqual(\"r\", first_handle.mode)\n self.assertEqual(\"r\", second_handle.mode)\n first_handle.read.assert_called_once_with()\n second_handle.read.assert_called_once_with()\n\n def test_return_value(self, mock_open):\n \"\"\"Check that `return_value` always returns the last file mock.\"\"\"\n with open(\"/path/to/first_file\", \"r\"):\n pass\n\n with open(\"/path/to/second_file\", \"r\") as handle:\n self.assertEqual(handle, mock_open.return_value)\n\n\n@patch(OPEN, new_callable=MockOpen)\nclass TestSideEffects(unittest.TestCase):\n \"\"\"Test setting the side_effect attribute in various situations.\"\"\"\n def test_error_on_open(self, mock_open):\n \"\"\"Simulate error openning file.\"\"\"\n mock_open.side_effect = IOError()\n\n self.assertRaises(IOError, open, \"/not/there\", \"r\")\n\n def test_error_on_read(self, mock_open):\n \"\"\"Simulate error when reading from file.\"\"\"\n mock_open.return_value.read.side_effect = IOError()\n\n with open(\"/path/to/file\", \"w\") as handle:\n with self.assertRaises(IOError):\n handle.read()\n\n def test_error_on_write(self, mock_open):\n \"\"\"Simulate error when writing to file.\"\"\"\n mock_open.return_value.write.side_effect = IOError()\n\n with open(\"/path/to/file\", \"r\") as handle:\n with self.assertRaises(IOError):\n handle.write(\"text\")\n\n def test_error_by_name(self, mock_open):\n \"\"\"Raise an exception for a specific path.\"\"\"\n mock_open[\"/path/to/error_file\"].side_effect = IOError()\n\n # Trying to open a different file should be OK.\n with open(\"/path/to/allowed_file\", \"r\"):\n pass\n\n # But openning the bad file should raise an exception.\n self.assertRaises(IOError, open, \"/path/to/error_file\", \"r\")\n\n # Reset open's side effect and check read/write side effects.\n mock_open[\"/path/to/error_file\"].side_effect = None\n mock_open[\"/path/to/error_file\"].read.side_effect = IOError()\n mock_open[\"/path/to/error_file\"].write.side_effect = IOError()\n with open(\"/path/to/error_file\", \"r\") as handle:\n self.assertRaises(IOError, handle.read)\n self.assertRaises(IOError, handle.write, \"Bad write\")\n\n def test_hijack_read(self, mock_open):\n \"\"\"Replace the normal read() with a fake one.\n\n Replacing the side_effect causes the file's inner state to remain\n unchanged after the call to read().\n \"\"\"\n mock_open.return_value.read.side_effect = lambda: \"Hijacked!\"\n\n with open(\"/path/to/file\", \"w\") as handle:\n contents = handle.read()\n\n self.assertEqual(\"Hijacked!\", contents)\n self.assertEqual(0, handle.tell())\n\n def test_hijack_write(self, mock_open):\n \"\"\"Replace the normal write() with a fake one.\n\n Replacing the side_effect causes the file's inner state to remain\n unchanged after the call to write().\n \"\"\"\n def fake_write(data):\n # pylint: disable=missing-docstring\n contents[0] = data\n\n # If we define contents as a 'simple' variable (just None, for example)\n # the assignment inside fake_write() will assign to a local variable\n # instead of the 'outer' contents variable.\n contents = [None, ]\n mock_open.return_value.write.side_effect = fake_write\n\n with open(\"/path/to/file\", \"r\") as handle:\n handle.write(\"text\")\n\n self.assertEqual(\"text\", contents[0])\n self.assertEqual(0, handle.tell())\n\n def test_wrap_read(self, mock_open):\n \"\"\"Wrap the normal read() function to add to regular operations.\n\n This is a method of allowing the mock to behave normally while adding\n our own code around operations.\n \"\"\"\n def wrap_read(original_read):\n # pylint: disable=missing-docstring\n original_side_effect = original_read.side_effect\n\n @wraps(original_side_effect)\n def wrapped_read(*args, **kws):\n # pylint: disable=missing-docstring\n sentinal[0] = True\n return original_side_effect(*args, **kws)\n\n original_read.side_effect = wrapped_read\n\n # Avoid uninitialized assignment (see test_hijack_write()).\n sentinal = [False, ]\n mock_open.return_value.read_data = \"Some text\"\n wrap_read(mock_open.return_value.read)\n\n with open(\"/path/to/file\", \"w\") as handle:\n contents = handle.read()\n\n self.assertEqual(\"Some text\", contents)\n self.assertTrue(sentinal[0])\n\n def test_wrap_write(self, mock_open):\n \"\"\"Wrap the normal write() function to add to regular operations.\n\n This is a method of allowing the mock to behave normally while adding\n our own code around operations.\n \"\"\"\n def wrap_write(original_write):\n # pylint: disable=missing-docstring\n original_side_effect = original_write.side_effect\n\n @wraps(original_side_effect)\n def wrapped_write(*args, **kws):\n # pylint: disable=missing-docstring\n sentinal[0] = True\n return original_side_effect(*args, **kws)\n\n original_write.side_effect = wrapped_write\n\n # Avoid uninitialized assignment (see test_hijack_write()).\n sentinal = [False, ]\n wrap_write(mock_open.return_value.write)\n\n with open(\"/path/to/file\", \"w\") as handle:\n handle.write(\"Some text\")\n\n self.assertEqual(\"Some text\", handle.read_data)\n self.assertTrue(sentinal[0])\n\n\nclass TestAPI(unittest.TestCase):\n \"\"\"Test conformance to mock library's API.\"\"\"\n def test_read_data(self):\n \"\"\"Check passing of `read_data` to the constructor.\"\"\"\n mock_open = MockOpen(read_data=\"Data from the file\")\n\n with patch(OPEN, mock_open):\n with open(\"/path/to/file\", \"r\") as handle:\n contents = handle.read()\n\n self.assertEqual(\"Data from the file\", contents)\n\n def test_reset_mock(self):\n \"\"\"Check that reset_mock() works.\"\"\"\n # Reset globally for all file mocks.\n mock_open = MockOpen(read_data=\"Global\")\n mock_open[\"/path/to/file\"].read_data = \"File-specific\"\n mock_open.reset_mock()\n\n with patch(OPEN, mock_open):\n with open(\"/path/to/file\", \"r\") as handle:\n self.assertEqual(\"\", handle.read())\n\n # Reset a for a specific file mock.\n mock_open = MockOpen(read_data=\"Global\")\n mock_open[\"/path/to/file\"].read_data = \"File-specific\"\n mock_open[\"/path/to/file\"].reset_mock()\n\n with patch(OPEN, mock_open):\n with open(\"/path/to/file\", \"r\") as handle:\n self.assertEqual(\"\", handle.read())\n\n with open(\"/path/to/other/file\", \"r\") as handle:\n self.assertEqual(\"Global\", handle.read())\n","sub_path":"mock_open/test/test_mocks.py","file_name":"test_mocks.py","file_ext":"py","file_size_in_byte":17845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"222956766","text":"#!/bin/env python\n\nimport asyncio\nimport configparser\nimport discord\nimport logging\nimport reddit\n\n__version__ = '0.3'\n\nif __name__ == \"__main__\":\n try:\n logging.basicConfig(format=\"%(asctime)s [%(levelname)-8s] [%(module)-8s] %(message)s\", level=logging.INFO)\n logging.info(\"Starting Alfred version {0}\".format(__version__))\n config = configparser.ConfigParser()\n config.read(\"alfred.ini\")\n\n token = config.get(\"main\", \"token\")\n\n loglevel = config.get(\"main\", \"log_level\", fallback=\"INFO\")\n logging.getLogger().setLevel(loglevel)\n\n logging.info(\"Starting discord client using token={0}\".format(token))\n\n client = discord.Client()\n reddit = reddit.Reddit(config)\n client.loop.create_task(reddit.check_feeds(client))\n client.run(token)\n\n except (KeyError, configparser.NoSectionError, configparser.NoOptionError) as err:\n logging.exception(\"Error reading configuration file.\\r\\n{0}\\r\\n\".format(err))\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"347805616","text":"import sys\r\nfrom util.data_parser import DataParser\r\n\r\nif __name__ == '__main__':\r\n profile = sys.argv[1]\r\n minRec = int(sys.argv[2])\r\n #profile = 'KNN'\r\n #minRec = '1'\r\n '''\r\n initial : \r\n '''\r\n try:\r\n DataParser().set_setting_config(profile,minRec)\r\n except:\r\n print(\"Error in python !\")\r\n \r\n finally:\r\n print('OK')\r\n sys.stdout.flush() ","sub_path":"engine/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"567273188","text":"#Implementation is very similar to MorvanZhou's, read more of his work here https://github.com/MorvanZhou/Reinforcement-learning-with-tensorflow/blob/master/contents/10_A3C/A3C_discrete_action.py#L147\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow import layers\r\nimport numpy as np\r\n\r\n\r\nGLOBAL_REWARDS = []\r\n\r\n\r\n\r\n#Architecture of the Actor-Critic Network\r\nclass Brain(object):\r\n def __init__(self, actions, states, name, Global_Net=None, isGlobal=False, COEF_REG=0.001, shared=False):\r\n\r\n self.n_actions = actions #Number of discrete actions in environment\r\n self.n_states = states\r\n self.shared = shared\r\n\r\n if isGlobal:\r\n with tf.variable_scope(name):\r\n self.s = tf.placeholder(tf.float32, [None, self.n_states], name='s')\r\n self.actor_output, self.critic_output, self.actor_params, self.critic_params = self.build_net(name)\r\n\r\n else:\r\n #Creating Local Nets\r\n\r\n with tf.variable_scope(name):\r\n self.s = tf.placeholder(tf.float32, [None, self.n_states], name='s')\r\n self.actor_output, self.critic_output, self.actor_params, self.critic_params = self.build_net(name)\r\n\r\n #Additional Resources to compute Loss function\r\n self.action_history = tf.placeholder(tf.int32, [None], name='action_history')\r\n self.target_value = tf.placeholder(tf.float32, [None, 1], name='target_value')\r\n\r\n self.advantage = self.target_value - self.critic_output #TD-Error\r\n\r\n #Optimizer and decay learning rate\r\n _global_step = tf.Variable(0, trainable=False)\r\n learning_rate = tf.train.exponential_decay(0.001, _global_step, 10000, 0.96, staircase=True)\r\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate)\r\n\r\n\r\n with tf.variable_scope('value_loss'):\r\n self.value_loss = tf.reduce_mean(tf.square(self.advantage))\r\n\r\n with tf.variable_scope('policy_loss'):\r\n\r\n # Compute PG Loss\r\n action_mask = tf.one_hot(self.action_history, self.n_actions, on_value=1.0, off_value=0.0)\r\n self.prob_under_policy = tf.reduce_sum(self.actor_output * action_mask, axis=1, keep_dims=True)\r\n self.neglogp = - tf.log(self.prob_under_policy + 1e-13)\r\n self.actor_loss = tf.stop_gradient(self.advantage) * self.neglogp\r\n\r\n #Compute Entropy\r\n self.entropy = - tf.reduce_sum(self.actor_output * - tf.log(self.actor_output + 1e-13), axis=1, keep_dims=True)\r\n \r\n #Total Policy Loss: Entropy * coefficient_regularization + pg_loss\r\n self.policy_loss = tf.reduce_mean(COEF_REG* self.entropy + self.actor_loss)\r\n\r\n with tf.variable_scope('gradients'):\r\n self.actor_grads = tf.gradients(self.policy_loss, self.actor_params)\r\n self.critic_grads = tf.gradients(self.value_loss, self.critic_params)\r\n\r\n \r\n #Pushing Operations: Apply local gradients to Global Net\r\n self.push_actor_params_op = self.optimizer.apply_gradients(zip(self.actor_grads, Global_Net.actor_params), global_step=_global_step)\r\n self.push_critic_params_op = self.optimizer.apply_gradients(zip(self.critic_grads, Global_Net.critic_params), global_step=_global_step)\r\n\r\n #Pulling Operations: Copy Global Net to Local Net\r\n self.pull_actor_params_op = [ local_param.assign(global_param) for local_param, global_param in zip(self.actor_params, Global_Net.actor_params)]\r\n self.pull_critic_params_op = [ local_param.assign(global_param) for local_param, global_param in zip(self.critic_params, Global_Net.critic_params)]\r\n\r\n\r\n def build_net(self, scope, shared=False):\r\n init = tf.random_uniform_initializer(0.,1.)\r\n\r\n if shared:\r\n #Shared layer \r\n with tf.variable_scope('shared'):\r\n\r\n hidden = layers.dense(self.s, 128, tf.nn.tanh, kernel_initializer=init, name='shared_layer')\r\n hidden = layers.dense(hidden, 64, tf.nn.relu6, kernel_initializer=init, name='shared_layer')\r\n\r\n with tf.variable_scope('Actor'):\r\n a_output = layers.dense(hidden, self.n_actions, tf.nn.softmax, kernel_initializer=init, name='a_out')\r\n\r\n with tf.variable_scope('Critic'):\r\n c_output = layers.dense(hidden, 1, kernel_initializer=init, name='c_out')\r\n\r\n actor_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope= scope + 'shared/Actor')\r\n critic_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope= scope + 'shared/Critic')\r\n\r\n else:\r\n # Separate Actor and Critic Network\r\n with tf.variable_scope('Actor'):\r\n a_hidden = layers.dense(self.s, 64, tf.nn.relu6, kernel_initializer=init, name='a_hidden')\r\n a_output = layers.dense(a_hidden, self.n_actions, tf.nn.softmax, kernel_initializer=init, name='a_out')\r\n\r\n with tf.variable_scope('Critic'):\r\n c_hidden = layers.dense(self.s, 128, tf.nn.tanh, kernel_initializer=init, name='c_hidden')\r\n c_output = layers.dense(c_hidden, 1, kernel_initializer=init, name='c_out')\r\n\r\n actor_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope= scope + '/Actor')\r\n critic_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope= scope + '/Critic')\r\n\r\n return a_output, c_output, actor_params, critic_params\r\n\r\n def push_to_global_network(self, sess, feed_s, feed_a, feed_v):\r\n #Apply local gradients to the global network\r\n\r\n feed_dict = {\r\n self.s : feed_s,\r\n self.action_history: feed_a,\r\n self.target_value: feed_v\r\n }\r\n\r\n sess.run([self.push_actor_params_op, self.push_critic_params_op], feed_dict=feed_dict)\r\n\r\n def pull_from_global_network(self, sess):\r\n sess.run([self.pull_actor_params_op, self.pull_critic_params_op])\r\n\r\n def choose_action(self, sess, s):\r\n\r\n policy = sess.run(self.actor_output, feed_dict={\r\n self.s: s[np.newaxis,:] \r\n })\r\n\r\n action = np.random.choice(range(self.n_actions), p=policy.ravel())\r\n\r\n return action\r\n\r\ndef discount_reward(r, v_tp1):\r\n #Resolve credit assignment problem, r is array of rewards, v_s is the value estimate from the next state\r\n GAMMA =0.9\r\n\r\n discounted_r = np.zeros_like(r)\r\n\r\n for t in reversed(range(0, len(r))):\r\n v_tp1 = r[t] + GAMMA * v_tp1\r\n discounted_r[t] = v_tp1\r\n\r\n return discounted_r\r\n\r\n\r\nclass Agent(object):\r\n def __init__(self, name, env_create, global_network, maximum_episodes=500, trading=True):\r\n self.env = env_create()\r\n\r\n num_states = self.env.observation_space.shape[0]\r\n num_actions = self.env.action_space.n\r\n\r\n self.name = name\r\n self.local_brain = Brain(actions=num_actions, states=num_states, name=self.name, Global_Net=global_network)\r\n\r\n self.trading = trading\r\n\r\n self.max_episodes = maximum_episodes\r\n\r\n \r\n\r\n def work(self, coord, sess, rew_threshold, update_freq=15, Oanda=False, train=True):\r\n\r\n steps = 1\r\n epi = 1\r\n\r\n \r\n \r\n while not coord.should_stop():\r\n global GLOBAL_REWARDS\r\n\r\n epi_reward = 0\r\n \r\n #Store the transition phase\r\n memory_s, memory_a, memory_r = [], [], []\r\n \r\n #Reset Environment and obtain initial state\r\n \r\n if self.trading:\r\n #For Trading env only\r\n self.env._reset(train=True, Oanda=self.env.Oanda)\r\n s = self.env.sim.states[0]\r\n \r\n else:\r\n #Other OpenAI environment\r\n s = self.env.reset()\r\n\r\n action_dict = {i:0 for i in range(self.local_brain.n_actions)}\r\n\r\n while True:\r\n \r\n a = self.local_brain.choose_action(sess, s)\r\n\r\n \r\n if self.trading:\r\n if self.env.portfolio.holding_trade:\r\n a = 2\r\n\r\n s_, r, done, _ = self.env._step(a)\r\n \r\n else:\r\n s_, r, done, _ = self.env.step(a)\r\n\r\n action_dict[a] += 1\r\n\r\n epi_reward += r\r\n\r\n #Store the transition\r\n memory_s.append(s)\r\n memory_a.append(a)\r\n memory_r.append(r)\r\n\r\n if done or (steps % update_freq == 0):\r\n \r\n #Estimate the Value Function from next state onwards\r\n if done:\r\n v_tp1 = 0 #Terminal State, set to zero\r\n else:\r\n v_tp1 = sess.run(self.local_brain.critic_output, feed_dict={self.local_brain.s: s_[np.newaxis,:]}) #Bootstrapped for non-terminal states\r\n\r\n \r\n #Apply discount factors to reward\r\n value_targets = discount_reward(memory_r, v_tp1)\r\n\r\n\r\n feed_s, feed_a, feed_v = np.vstack(memory_s), np.array(memory_a), np.vstack(value_targets)\r\n \r\n #Apply local gradients onto global network (Actor and Critic)\r\n self.local_brain.push_to_global_network(sess, feed_s, feed_a, feed_v)\r\n\r\n #Use the updated params from global network\r\n self.local_brain.pull_from_global_network(sess)\r\n\r\n memory_s, memory_a, memory_r = [], [], []\r\n \r\n #Important!\r\n s = s_\r\n steps += 1\r\n\r\n if done:\r\n \r\n if self.trading:\r\n #Use portfolio reward tracker for greater accuracy\r\n epi_reward = self.env.portfolio.total_reward\r\n\r\n print (\"%s, Episode:%s, Reward: %s\"%(self.name, epi, epi_reward))\r\n print (action_dict)\r\n \r\n GLOBAL_REWARDS.append(epi_reward)\r\n\r\n epi += 1\r\n\r\n #Stop the training once either reward or episode limit is reached\r\n reward_reached = np.mean(GLOBAL_REWARDS[-10:]) >= rew_threshold\r\n episode_reached = epi >= self.max_episodes\r\n\r\n if reward_reached or episode_reached:\r\n coord.request_stop()\r\n\r\n break\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":"tradingtensors/Agents/ActorCritic.py","file_name":"ActorCritic.py","file_ext":"py","file_size_in_byte":10822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"340342443","text":"import numpy as np\nimport os\nimport ast\n\n\"\"\"\n Mx = r\n\n M is a square n x n matrix.\n x,r is a n x 1 vector.\n\n This uses Thomas's algorithm and the 'numpy' library for matrix managements.\n Stage 1: Apply LU decomposition ( LUx = r,where Ux = p => Lp = r ) with down-ward sweep straight into Ux = p\n Stage 2: Solve Ux = p straight for x\n\n Input: create a file with name 'mat_input.txt' in the same folder as 'tridiag_matrix_solver.py' (os.getcwd())\n Example input (should only be 2 lines):\n M = [[2,3,0,0],[6,3,9,0],[0,2,5,2],[0,0,4,3]]\n r_trans = [[21,69,34,22]]\n Where \"_trans\" indicates transpose if you need to.\n Run the function example() in the main() function to see an example tri-diagonal matrix solving.\n\"\"\"\nPATH = os.getcwd() + \"\\\\mat_input.txt\"\nN = None\nM_mat = None\nx_vec = None\nr_vec = None\nU = None\np = None\n\ndef matrix_input():\n M = None\n r = None\n try:\n with open(PATH,'r') as f:\n for line in f:\n inp = line.split(\"=\")\n inp = [s.strip() for s in inp]\n if inp[0].startswith(\"M\"):\n if inp[0].endswith(\"trans\"):\n M = np.asarray(ast.literal_eval(inp[1])).T\n else:\n M = np.asarray(ast.literal_eval(inp[1]))\n else:\n if inp[0].endswith(\"trans\"):\n r = np.asarray(ast.literal_eval(inp[1])).T\n else:\n r = np.asarray(ast.literal_eval(inp[1]))\n except FileNotFoundError as err:\n print(\"mat_input.txt not found.\")\n print(\"mat_input.txt should have path: \" + PATH)\n\n precondition(M,r)\n\n\n\ndef precondition(M,r):\n global M_mat,x_vec,r_vec,N\n assert len(M.shape) == 2, \"M must be a 2-dimensional matrix\"\n assert M.shape[0] == M.shape[1] , \"M is not a square matrix\"\n assert M.shape[0] == r.shape[0],\"M,r are not in the same dimension\"\n N = M.shape[0]\n num = len(np.where(M != 0)[0])\n assert num == N + 2*(N-1),\"M is not a tri-diagonal matrix.\"\n M_mat = M\n r_vec = r\n x_vec = np.zeros((N,1))\n U_decomposition()\n\ndef U_decomposition():\n global U,p\n U = np.diag(np.diag(np.ones((N,N)))) # Contains ys\n p = np.zeros((N,1))\n for n in range(N):\n if n == 0:\n y_0 = M_mat[0,1] / M_mat[0,0]\n p_0 = r_vec[0,0] / M_mat[0,0]\n U[0,1] = y_0\n p[0,0] = p_0\n elif n == N - 1:\n p_n = (r_vec[n,0] - M_mat[n,n-1] * p[n-1,0]) / (M_mat[n,n] - M_mat[n,n-1] * U[n-1,n])\n p[n,0] = p_n\n else:\n y_n = M_mat[n,n+1] / (M_mat[n,n] - M_mat[n,n-1] * U[n-1,n])\n p_n = (r_vec[n,0] - M_mat[n,n-1] * p[n-1,0]) / (M_mat[n,n] - M_mat[n,n-1] * U[n-1,n])\n U[n,n+1] = y_n\n p[n,0] = p_n\n print(\"Decomposed U matrix: \\n\",U)\n print(\"Decomposed p vector: \\n\",p)\n solve_for_x_vec()\n\ndef solve_for_x_vec():\n global x_vec\n x_vec[N-1,0] = p[N-1,0]\n # _n means going backwards start at N-2 towards 0 instead of starting at 0\n for _n in range(N-2,-1,-1):\n x_n = p[_n] - U[_n,_n + 1] * x_vec[_n + 1,0]\n x_vec[_n,0] = x_n\n print(\"Result for x: \\n\" , x_vec)\n print(\"Re-checking result:\" ,\"\\n---Original r vector--- \\n\" , r_vec , \"\\n---Calculated r vector--- \\n\",np.dot(M_mat,x_vec))\n\ndef example():\n N = 5\n M = np.asarray([[2,3,0,0],[6,3,9,0],[0,2,5,2],[0,0,4,3]])\n r = np.asarray([[21,69,34,22]]).T\n precondition(M,r)\n\ndef main():\n matrix_input()\n\nmain()\n","sub_path":"tridiag_matrix_solver.py","file_name":"tridiag_matrix_solver.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"74578143","text":"import sys\nimport time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.utils import shuffle\n\nfrom svm import SVC\nfrom svm_by_pkg import SSVM\n\n\ndef load_data(dataset_name, n_features=2):\n if dataset_name == \"iris\":\n X, y = datasets.load_iris(return_X_y=True)\n elif dataset_name == \"wine\":\n X, y = datasets.load_wine(return_X_y=True)\n # 降成2维便于可视化\n X = PCA(n_features).fit_transform(X)\n mask = y < 2\n X = X[mask]\n y = y[mask]\n y[y == 0] = -1.0\n y = y.astype(float) # 都要是float类型的,整数类型会出现错误\n # X, y = shuffle(X, y)\n X = X.T\n return X, y\n\n\ndef plot_split_line(dataName, clf1, clf2, X, y, filename):\n plt.style.use(\"ggplot\")\n plt.figure(figsize=(5, 4))\n plt.scatter(X[0, :], X[1, :], c=y)\n\n # 画分割线\n def f(x, w, b): return (-w[0] / w[1]) * x - (b / w[1])\n\n if dataName == \"iris\":\n x = np.linspace(-3, 1.5)\n elif dataName == \"wine\":\n x = np.linspace(0, 100)\n\n w1, b1 = clf1.coef, clf1.intercept\n plt.plot(x, f(x, w1, b1), 'k--', label=\"SMO\")\n\n w2, b2 = clf2.coef, clf2.intercept\n plt.plot(x, f(x, w2, b2), 'r--', label=\"QP\")\n plt.legend()\n plt.savefig(filename, dpi=300)\n\n\ndef test(dataName):\n X, y = load_data(dataName, 2)\n start = time.time()\n clf1 = SVC(C=1.0, kernel=\"linear\", eps=1e-10, max_iter=2000)\n clf1.fit(X, y)\n print('time span:', time.time() - start)\n y_1 = clf1.predict(X)\n\n start = time.time()\n clf2 = SSVM()\n clf2.fit_dual_problem(X, y)\n print('time span:', time.time() - start)\n y_2 = clf2.predict(X)\n\n print(\"ACC: clf1 = %.4f \\t clf2 = %.4f\" %\n (accuracy_score(y_1, y), accuracy_score(y_2, y)))\n print(\"n_sv: clf1 = %d \\t clf2 = %d\" % (clf1.n_sv, clf2.n_sv))\n print(\"dual_coef:\")\n print(\"clf1 = \", clf1.dual_coef)\n print(\"clf2 = \", clf2.dual_coef)\n print(\"coef: clf1 = \", clf1.coef, \" \\t clf2 = \", clf2.coef)\n print(\"intercept: clf1 = \", clf1.intercept, \" \\t clf2 = \", clf2.intercept)\n\n plot_split_line(dataName, clf1, clf2, X, y,\n \"svm\\\\\" + dataName + \"_SVC.png\")\n\n\nif __name__ == \"__main__\":\n # sys.stdout = open(\"svm\\\\out.txt\", \"w\")\n test(\"iris\")\n # test(\"wine\")\n","sub_path":"svm/test_svc.py","file_name":"test_svc.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"217830810","text":"# coding=utf-8\n# Copyright 2023 Meta Platforms, Inc. and The HuggingFace Inc. team. 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\"\"\" PyTorch ConvNextV2 model.\"\"\"\n\n\nfrom typing import Optional, Tuple, Union\n\nimport torch\nimport torch.utils.checkpoint\nfrom torch import nn\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\n\nfrom ...activations import ACT2FN\nfrom ...modeling_outputs import (\n BackboneOutput,\n BaseModelOutputWithNoAttention,\n BaseModelOutputWithPoolingAndNoAttention,\n ImageClassifierOutputWithNoAttention,\n)\nfrom ...modeling_utils import PreTrainedModel\nfrom ...utils import (\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n logging,\n replace_return_docstrings,\n)\nfrom ...utils.backbone_utils import BackboneMixin\nfrom .configuration_convnextv2 import ConvNextV2Config\n\n\nlogger = logging.get_logger(__name__)\n\n# General docstring\n_CONFIG_FOR_DOC = \"ConvNextV2Config\"\n\n# Base docstring\n_CHECKPOINT_FOR_DOC = \"facebook/convnextv2-tiny-1k-224\"\n_EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7]\n\n# Image classification docstring\n_IMAGE_CLASS_CHECKPOINT = \"facebook/convnextv2-tiny-1k-224\"\n_IMAGE_CLASS_EXPECTED_OUTPUT = \"tabby, tabby cat\"\n\nCONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"facebook/convnextv2-tiny-1k-224\",\n # See all ConvNextV2 models at https://huggingface.co/models?filter=convnextv2\n]\n\n\n# Copied from transformers.models.beit.modeling_beit.drop_path\ndef drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:\n \"\"\"\n Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\n\n Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,\n however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...\n See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the\n layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the\n argument.\n \"\"\"\n if drop_prob == 0.0 or not training:\n return input\n keep_prob = 1 - drop_prob\n shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets\n random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)\n random_tensor.floor_() # binarize\n output = input.div(keep_prob) * random_tensor\n return output\n\n\n# Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNextV2\nclass ConvNextV2DropPath(nn.Module):\n \"\"\"Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).\"\"\"\n\n def __init__(self, drop_prob: Optional[float] = None) -> None:\n super().__init__()\n self.drop_prob = drop_prob\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n return drop_path(hidden_states, self.drop_prob, self.training)\n\n def extra_repr(self) -> str:\n return \"p={}\".format(self.drop_prob)\n\n\nclass ConvNextV2GRN(nn.Module):\n \"\"\"GRN (Global Response Normalization) layer\"\"\"\n\n def __init__(self, dim: int):\n super().__init__()\n self.weight = nn.Parameter(torch.zeros(1, 1, 1, dim))\n self.bias = nn.Parameter(torch.zeros(1, 1, 1, dim))\n\n def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:\n # Compute and normalize global spatial feature maps\n global_features = torch.norm(hidden_states, p=2, dim=(1, 2), keepdim=True)\n norm_features = global_features / (global_features.mean(dim=-1, keepdim=True) + 1e-6)\n hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states\n\n return hidden_states\n\n\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->ConvNextV2\nclass ConvNextV2LayerNorm(nn.Module):\n r\"\"\"LayerNorm that supports two data formats: channels_last (default) or channels_first.\n The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,\n width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).\n \"\"\"\n\n def __init__(self, normalized_shape, eps=1e-6, data_format=\"channels_last\"):\n super().__init__()\n self.weight = nn.Parameter(torch.ones(normalized_shape))\n self.bias = nn.Parameter(torch.zeros(normalized_shape))\n self.eps = eps\n self.data_format = data_format\n if self.data_format not in [\"channels_last\", \"channels_first\"]:\n raise NotImplementedError(f\"Unsupported data format: {self.data_format}\")\n self.normalized_shape = (normalized_shape,)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n if self.data_format == \"channels_last\":\n x = torch.nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)\n elif self.data_format == \"channels_first\":\n input_dtype = x.dtype\n x = x.float()\n u = x.mean(1, keepdim=True)\n s = (x - u).pow(2).mean(1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.eps)\n x = x.to(dtype=input_dtype)\n x = self.weight[:, None, None] * x + self.bias[:, None, None]\n return x\n\n\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextEmbeddings with ConvNext->ConvNextV2\nclass ConvNextV2Embeddings(nn.Module):\n \"\"\"This class is comparable to (and inspired by) the SwinEmbeddings class\n found in src/transformers/models/swin/modeling_swin.py.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.patch_embeddings = nn.Conv2d(\n config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size\n )\n self.layernorm = ConvNextV2LayerNorm(config.hidden_sizes[0], eps=1e-6, data_format=\"channels_first\")\n self.num_channels = config.num_channels\n\n def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:\n num_channels = pixel_values.shape[1]\n if num_channels != self.num_channels:\n raise ValueError(\n \"Make sure that the channel dimension of the pixel values match with the one set in the configuration.\"\n )\n embeddings = self.patch_embeddings(pixel_values)\n embeddings = self.layernorm(embeddings)\n return embeddings\n\n\nclass ConvNextV2Layer(nn.Module):\n \"\"\"This corresponds to the `Block` class in the original implementation.\n\n There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,\n H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back\n\n The authors used (2) as they find it slightly faster in PyTorch.\n\n Args:\n config ([`ConvNextV2Config`]): Model configuration class.\n dim (`int`): Number of input channels.\n drop_path (`float`): Stochastic depth rate. Default: 0.0.\n \"\"\"\n\n def __init__(self, config, dim, drop_path=0):\n super().__init__()\n # depthwise conv\n self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)\n self.layernorm = ConvNextV2LayerNorm(dim, eps=1e-6)\n # pointwise/1x1 convs, implemented with linear layers\n self.pwconv1 = nn.Linear(dim, 4 * dim)\n self.act = ACT2FN[config.hidden_act]\n self.grn = ConvNextV2GRN(4 * dim)\n self.pwconv2 = nn.Linear(4 * dim, dim)\n self.drop_path = ConvNextV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()\n\n def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:\n input = hidden_states\n x = self.dwconv(hidden_states)\n # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)\n x = x.permute(0, 2, 3, 1)\n x = self.layernorm(x)\n x = self.pwconv1(x)\n x = self.act(x)\n x = self.grn(x)\n x = self.pwconv2(x)\n # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)\n x = x.permute(0, 3, 1, 2)\n\n x = input + self.drop_path(x)\n return x\n\n\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextStage with ConvNeXT->ConvNeXTV2, ConvNext->ConvNextV2\nclass ConvNextV2Stage(nn.Module):\n \"\"\"ConvNeXTV2 stage, consisting of an optional downsampling layer + multiple residual blocks.\n\n Args:\n config ([`ConvNextV2Config`]): Model configuration class.\n in_channels (`int`): Number of input channels.\n out_channels (`int`): Number of output channels.\n depth (`int`): Number of residual blocks.\n drop_path_rates(`List[float]`): Stochastic depth rates for each layer.\n \"\"\"\n\n def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):\n super().__init__()\n\n if in_channels != out_channels or stride > 1:\n self.downsampling_layer = nn.Sequential(\n ConvNextV2LayerNorm(in_channels, eps=1e-6, data_format=\"channels_first\"),\n nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),\n )\n else:\n self.downsampling_layer = nn.Identity()\n drop_path_rates = drop_path_rates or [0.0] * depth\n self.layers = nn.Sequential(\n *[ConvNextV2Layer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]\n )\n\n def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:\n hidden_states = self.downsampling_layer(hidden_states)\n hidden_states = self.layers(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextEncoder with ConvNext->ConvNextV2\nclass ConvNextV2Encoder(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.stages = nn.ModuleList()\n drop_path_rates = [\n x.tolist() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths)).split(config.depths)\n ]\n prev_chs = config.hidden_sizes[0]\n for i in range(config.num_stages):\n out_chs = config.hidden_sizes[i]\n stage = ConvNextV2Stage(\n config,\n in_channels=prev_chs,\n out_channels=out_chs,\n stride=2 if i > 0 else 1,\n depth=config.depths[i],\n drop_path_rates=drop_path_rates[i],\n )\n self.stages.append(stage)\n prev_chs = out_chs\n\n def forward(\n self,\n hidden_states: torch.FloatTensor,\n output_hidden_states: Optional[bool] = False,\n return_dict: Optional[bool] = True,\n ) -> Union[Tuple, BaseModelOutputWithNoAttention]:\n all_hidden_states = () if output_hidden_states else None\n\n for i, layer_module in enumerate(self.stages):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n hidden_states = layer_module(hidden_states)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)\n\n return BaseModelOutputWithNoAttention(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n )\n\n\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextPreTrainedModel with ConvNext->ConvNextV2, convnext->convnextv2\nclass ConvNextV2PreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = ConvNextV2Config\n base_model_prefix = \"convnextv2\"\n main_input_name = \"pixel_values\"\n supports_gradient_checkpointing = True\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights\"\"\"\n if isinstance(module, (nn.Linear, nn.Conv2d)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, ConvNextV2Encoder):\n module.gradient_checkpointing = value\n\n\nCONVNEXTV2_START_DOCSTRING = r\"\"\"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`ConvNextV2Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\nCONVNEXTV2_INPUTS_DOCSTRING = r\"\"\"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`ConvNextImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare ConvNextV2 model outputting raw features without any specific head on top.\",\n CONVNEXTV2_START_DOCSTRING,\n)\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextModel with CONVNEXT->CONVNEXTV2, ConvNext->ConvNextV2\nclass ConvNextV2Model(ConvNextV2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.config = config\n\n self.embeddings = ConvNextV2Embeddings(config)\n self.encoder = ConvNextV2Encoder(config)\n\n # final layernorm layer\n self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=BaseModelOutputWithPoolingAndNoAttention,\n config_class=_CONFIG_FOR_DOC,\n modality=\"vision\",\n expected_output=_EXPECTED_OUTPUT_SHAPE,\n )\n def forward(\n self,\n pixel_values: torch.FloatTensor = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if pixel_values is None:\n raise ValueError(\"You have to specify pixel_values\")\n\n embedding_output = self.embeddings(pixel_values)\n\n encoder_outputs = self.encoder(\n embedding_output,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n last_hidden_state = encoder_outputs[0]\n\n # global average pooling, (N, C, H, W) -> (N, C)\n pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))\n\n if not return_dict:\n return (last_hidden_state, pooled_output) + encoder_outputs[1:]\n\n return BaseModelOutputWithPoolingAndNoAttention(\n last_hidden_state=last_hidden_state,\n pooler_output=pooled_output,\n hidden_states=encoder_outputs.hidden_states,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n \"\"\",\n CONVNEXTV2_START_DOCSTRING,\n)\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextForImageClassification with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,convnext->convnextv2\nclass ConvNextV2ForImageClassification(ConvNextV2PreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.num_labels = config.num_labels\n self.convnextv2 = ConvNextV2Model(config)\n\n # Classifier head\n self.classifier = (\n nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()\n )\n\n # Initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n checkpoint=_IMAGE_CLASS_CHECKPOINT,\n output_type=ImageClassifierOutputWithNoAttention,\n config_class=_CONFIG_FOR_DOC,\n expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,\n )\n def forward(\n self,\n pixel_values: torch.FloatTensor = None,\n labels: Optional[torch.LongTensor] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the image classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.convnextv2(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)\n\n pooled_output = outputs.pooler_output if return_dict else outputs[1]\n\n logits = self.classifier(pooled_output)\n\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n if not return_dict:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return ImageClassifierOutputWithNoAttention(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n ConvNeXT V2 backbone, to be used with frameworks like DETR and MaskFormer.\n \"\"\",\n CONVNEXTV2_START_DOCSTRING,\n)\n# Copied from transformers.models.convnext.modeling_convnext.ConvNextBackbone with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,facebook/convnext-tiny-224->facebook/convnextv2-tiny-1k-224\nclass ConvNextV2Backbone(ConvNextV2PreTrainedModel, BackboneMixin):\n def __init__(self, config):\n super().__init__(config)\n super()._init_backbone(config)\n\n self.embeddings = ConvNextV2Embeddings(config)\n self.encoder = ConvNextV2Encoder(config)\n self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes\n\n # Add layer norms to hidden states of out_features\n hidden_states_norms = {}\n for stage, num_channels in zip(self._out_features, self.channels):\n hidden_states_norms[stage] = ConvNextV2LayerNorm(num_channels, data_format=\"channels_first\")\n self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)\n\n # initialize weights and apply final processing\n self.post_init()\n\n @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n pixel_values: torch.Tensor,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> BackboneOutput:\n \"\"\"\n Returns:\n\n Examples:\n\n ```python\n >>> from transformers import AutoImageProcessor, AutoBackbone\n >>> import torch\n >>> from PIL import Image\n >>> import requests\n\n >>> url = \"http://images.cocodataset.org/val2017/000000039769.jpg\"\n >>> image = Image.open(requests.get(url, stream=True).raw)\n\n >>> processor = AutoImageProcessor.from_pretrained(\"facebook/convnextv2-tiny-1k-224\")\n >>> model = AutoBackbone.from_pretrained(\"facebook/convnextv2-tiny-1k-224\")\n\n >>> inputs = processor(image, return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n\n embedding_output = self.embeddings(pixel_values)\n\n outputs = self.encoder(\n embedding_output,\n output_hidden_states=True,\n return_dict=True,\n )\n\n hidden_states = outputs.hidden_states\n\n feature_maps = ()\n # we skip the stem\n for idx, (stage, hidden_state) in enumerate(zip(self.stage_names[1:], hidden_states[1:])):\n if stage in self.out_features:\n hidden_state = self.hidden_states_norms[stage](hidden_state)\n feature_maps += (hidden_state,)\n\n if not return_dict:\n output = (feature_maps,)\n if output_hidden_states:\n output += (outputs.hidden_states,)\n return output\n\n return BackboneOutput(\n feature_maps=feature_maps,\n hidden_states=outputs.hidden_states if output_hidden_states else None,\n attentions=None,\n )\n","sub_path":"src/transformers/models/convnextv2/modeling_convnextv2.py","file_name":"modeling_convnextv2.py","file_ext":"py","file_size_in_byte":23962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"212690489","text":"\"\"\"\r\nDeep Q network,\r\nUsing:\r\nTensorflow: 1.0\r\ngym: 0.7.3\r\n\"\"\"\r\n# _ 是忽略的意思,如果一个输出用_代替,就代表这个值不关键\r\n\r\nimport gym\r\nfrom RL_brain import DeepQNetwork\r\n\r\nenv = gym.make('CartPole-v0')\r\nenv = env.unwrapped\r\n\r\nprint(env.action_space) # discrete(2) 两个离散动作:向左or向右\r\nprint(env.observation_space)\r\nprint(env.observation_space.high)\r\nprint(env.observation_space.low)\r\n\r\nRL = DeepQNetwork(\r\n n_actions = env.action_space.n,\r\n n_features = env.observation_space.shape[0],\r\n learning_rate = 0.01, e_greedy = 0.9,\r\n replace_target_iter = 100 , memory_size = 2000,\r\n e_greedy_increment = 0.001,\r\n)\r\n\r\ntotal_steps = 0\r\n\r\nfor i_episode in range(100):\r\n observation = env.reset()\r\n ep_r = 0\r\n while True:\r\n env.render()\r\n\r\n action = RL.choose_action(observation)\r\n\r\n observation_ , reward , done , info = env.step(action)\r\n\r\n # 设置reward\r\n x , x_dot , theta , theta_dot = observation_ # 状态由四个特征定义\r\n r1 = (env.x_threshold - abs(x))/env.x_threshold - 0.8\r\n r2 = (env.theta_threshold_radians - abs(theta))/env.theta_threshold_radians - 0.5\r\n reward = r1 + r2\r\n\r\n RL.store_transition(observation , action , reward ,observation_)\r\n\r\n ep_r += reward\r\n if total_steps > 1000:\r\n RL.learn()\r\n\r\n if done:\r\n print(\r\n 'episode: ',i_episode,\r\n 'e_r: ',round(ep_r , 2), # round :四舍五入小数点后两位\r\n 'epsilon: ',round(RL.epsilon , 2),\r\n )\r\n break\r\n\r\n observation = observation_\r\n total_steps += 1\r\n\r\nRL.plot_cost()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"莫烦强化学习/OpenAI_gym/run_CarPole.py","file_name":"run_CarPole.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"}